get-workflow-run-tool.test.ts 66 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768
  1. import { describe, expect, it } from "vitest";
  2. import {
  3. GET_WORKFLOW_RUN_TOOL_NAME,
  4. GetWorkflowRunOutputSchema,
  5. type DynamicWorkflowRunDetail,
  6. type DynamicWorkflowRunPort,
  7. type GetWorkflowRunOutput,
  8. } from "@zcode/contracts";
  9. import { PermissionService } from "../src/permission/service.js";
  10. import { resolveRuntimePermissionCapability } from "../src/tool/executor/permission-capability.js";
  11. import { getWorkflowRunToolEntry } from "../src/tool/handlers/get-workflow-run.js";
  12. import { buildWorkflowRunSummary } from "../src/tool/handlers/get-workflow-run-summary.js";
  13. import { registerBuiltInTools } from "../src/tool/handlers/index.js";
  14. import { createToolRegistry } from "../src/tool/registry.js";
  15. import { expectV2CommonContract } from "./tool-contract-assertions.js";
  16. import type { ToolExecutionContext, ToolHandlerFailure } from "../src/tool/types.js";
  17. /** 快照时刻:run 的 updatedAt 之后 40 秒,createdAt 之后 5m 40s。所有年龄都对它算。 */
  18. const NOW = Date.UTC(2026, 7, 21, 9, 5, 40);
  19. const RUNNING_DETAIL: DynamicWorkflowRunDetail = {
  20. runId: "dwfrun-running",
  21. label: "nightly triage",
  22. labelSource: "name",
  23. status: "running",
  24. ownedByThisSession: true,
  25. createdAt: Date.UTC(2026, 7, 21, 9, 0, 0),
  26. updatedAt: Date.UTC(2026, 7, 21, 9, 5, 0),
  27. usage: {
  28. spentTokens: 1_204,
  29. nodesObserved: 3,
  30. nodesRunning: 1,
  31. nodesCompleted: 2,
  32. nodesFailed: 0,
  33. },
  34. actors: [
  35. { siteId: "agent#1", ordinal: 1, name: "judge" },
  36. { siteId: "agent#2", ordinal: 1 },
  37. ],
  38. logTail: [
  39. { sequence: 11, message: "collected the failing specs", at: Date.UTC(2026, 7, 21, 9, 0, 50) },
  40. { sequence: 14, message: "asked the judge", at: Date.UTC(2026, 7, 21, 9, 4, 40) },
  41. ],
  42. subagents: [
  43. {
  44. siteId: "agent#1",
  45. ordinal: 1,
  46. name: "judge",
  47. state: "executing",
  48. phaseName: "judge",
  49. currentAsk: {
  50. siteId: "ask#4",
  51. ordinal: 1,
  52. actorSeq: 2,
  53. instructionsHead: "Judge specs 1-7 for flakiness; report real failures with evidence",
  54. startedAt: Date.UTC(2026, 7, 21, 9, 4, 28),
  55. turn: 4,
  56. toolCalls: 7,
  57. lastTool: {
  58. name: "Read",
  59. target: "packages/net/retry.spec.ts",
  60. at: Date.UTC(2026, 7, 21, 9, 5, 32),
  61. },
  62. },
  63. stepsSettled: 1,
  64. stepsFailed: 0,
  65. tokens: 5_100,
  66. lastProgressAt: Date.UTC(2026, 7, 21, 9, 5, 32),
  67. },
  68. {
  69. siteId: "agent#2",
  70. ordinal: 1,
  71. // 活着的 run 上端口从不发 `done`(那是终态词):歇着的子代理是 `idle`。
  72. state: "idle",
  73. phaseName: "collect",
  74. stepsSettled: 1,
  75. stepsFailed: 0,
  76. tokens: 2_130,
  77. },
  78. ],
  79. health: {
  80. lastProgressAt: Date.UTC(2026, 7, 21, 9, 5, 0),
  81. consecutiveFailures: 0,
  82. cachedSteps: 0,
  83. pendingQuestionsKnown: true,
  84. },
  85. };
  86. /**
  87. * 模型面的输入是**工具输出**,不是端口详情:`summary` 与 `generatedAt` 由 handler 铸出,
  88. * 格式器只是它们的纯函数。钉住一个固定的 `generatedAt`,整段文本(含每一个「多久以前」)
  89. * 因此可以逐字断言。
  90. */
  91. const RUNNING_OUTPUT: GetWorkflowRunOutput = {
  92. ...(RUNNING_DETAIL as unknown as Omit<GetWorkflowRunOutput, "summary" | "generatedAt">),
  93. generatedAt: NOW,
  94. summary:
  95. "Running for 5m 40s. 2 of 3 dispatched steps settled, 1 running (1 executing). Last progress 40s ago.",
  96. };
  97. /** 只实现 `getRunDetail` 的桩端口;其余成员被触达即说明接线跑偏。 */
  98. function stubDetailPort(
  99. details: Readonly<Record<string, DynamicWorkflowRunDetail>>,
  100. ): DynamicWorkflowRunPort {
  101. const unreachable = (name: string) => () => {
  102. throw new Error(`stubDetailPort.${name} 不应被 GetWorkflowRun handler 触及`);
  103. };
  104. return {
  105. submit: unreachable("submit"),
  106. getTask: unreachable("getTask"),
  107. waitForTask: unreachable("waitForTask"),
  108. cancel: unreachable("cancel"),
  109. listEvents: unreachable("listEvents"),
  110. listRuns: unreachable("listRuns"),
  111. async getRunDetail(runId: string) {
  112. return details[runId];
  113. },
  114. } as unknown as DynamicWorkflowRunPort;
  115. }
  116. function contextWith(port?: DynamicWorkflowRunPort): ToolExecutionContext {
  117. return {
  118. abortSignal: new AbortController().signal,
  119. sessionId: "sess_get_run" as never,
  120. toolCallId: "toolu_get_run",
  121. traceId: "trace_get_run" as never,
  122. workingDirectory: "/workspace/project",
  123. workspaceRoot: "/workspace/project",
  124. ...(port === undefined ? {} : { dynamicWorkflowRunPort: port }),
  125. } as ToolExecutionContext;
  126. }
  127. async function call(
  128. runId: string,
  129. port?: DynamicWorkflowRunPort,
  130. ): Promise<Record<string, unknown>> {
  131. return (await getWorkflowRunToolEntry.handler({ run_id: runId }, contextWith(port))) as Record<
  132. string,
  133. unknown
  134. >;
  135. }
  136. function asFailure(output: unknown): ToolHandlerFailure {
  137. const failure = output as ToolHandlerFailure;
  138. expect(failure.result).toBe(false);
  139. return failure;
  140. }
  141. /**
  142. * 输出 = 端口详情逐字段搬过来,外加 handler 自己铸的两件事:那一句摘要,和这次快照的时刻。
  143. * 时钟是真的 `Date.now()`,所以这里只钉形状不钉值——值的确定性由格式器与摘要的单测钉。
  144. */
  145. function expectMirrorsDetail(
  146. output: Record<string, unknown>,
  147. detail: DynamicWorkflowRunDetail,
  148. ): void {
  149. expect(GetWorkflowRunOutputSchema.parse(output)).toEqual({
  150. ...detail,
  151. summary: expect.any(String),
  152. generatedAt: expect.any(Number),
  153. });
  154. }
  155. describe("GetWorkflowRun handler — capability and identity", () => {
  156. it("returns the same business failure for an absent port and an absent method", async () => {
  157. const portWithoutMethod = {
  158. async submit() {
  159. throw new Error("unreachable");
  160. },
  161. } as unknown as DynamicWorkflowRunPort;
  162. const withoutPort = asFailure(await call("dwfrun-x"));
  163. const withoutMethod = asFailure(await call("dwfrun-x", portWithoutMethod));
  164. expect(withoutPort.message).toContain("workflow_introspection_unavailable");
  165. expect(withoutMethod).toEqual(withoutPort);
  166. });
  167. // 未知 runId 是一个**结构化失败**而不是一个空对象:后者会让模型以为这个 run 存在但没内容。
  168. it("fails with run_not_found for an unknown run id", async () => {
  169. const failure = asFailure(await call("dwfrun-nope", stubDetailPort({})));
  170. expect(failure.message).toContain("run_not_found");
  171. expect(failure.message).toContain("dwfrun-nope");
  172. // 能力缺席与 run 未知必须可分辨。
  173. expect(failure.errorCode).not.toBe(asFailure(await call("dwfrun-nope")).errorCode);
  174. });
  175. });
  176. describe("GetWorkflowRun handler — running snapshot", () => {
  177. it("gives progress, actors and the log tail, with neither result nor error", async () => {
  178. const output = await call(
  179. "dwfrun-running",
  180. stubDetailPort({ "dwfrun-running": RUNNING_DETAIL }),
  181. );
  182. expectMirrorsDetail(output, RUNNING_DETAIL);
  183. expect("result" in output).toBe(false);
  184. expect("error" in output).toBe(false);
  185. });
  186. // 每 run 的并发上界(docs/dynamic-workflow/concurrency.md「Two bounds on a run」)。端口只在不等于
  187. // 默认并发时给这个字段,所以「无则缺席」在读面上是构造成立的,不是这里再判一次。
  188. it("carries the run's own concurrency bound when it has one", async () => {
  189. const detail: DynamicWorkflowRunDetail = { ...RUNNING_DETAIL, maxConcurrency: 3 };
  190. const output = await call("dwfrun-running", stubDetailPort({ "dwfrun-running": detail }));
  191. expectMirrorsDetail(output, detail);
  192. });
  193. it("omits the bound entirely for a run at the machine default", async () => {
  194. const output = await call(
  195. "dwfrun-running",
  196. stubDetailPort({ "dwfrun-running": RUNNING_DETAIL }),
  197. );
  198. expect("maxConcurrency" in output).toBe(false);
  199. });
  200. // 每 run 的子代理模型(docs/dynamic-workflow/launch.md)。与并发上界同规「无则缺席」:
  201. // 继承会话模型的 run 没有可说的。
  202. it("carries the run's own subagent model when it chose one", async () => {
  203. const detail: DynamicWorkflowRunDetail = {
  204. ...RUNNING_DETAIL,
  205. subagentModel: "bigmodel/GLM-4.6$high",
  206. };
  207. const output = await call("dwfrun-running", stubDetailPort({ "dwfrun-running": detail }));
  208. expectMirrorsDetail(output, detail);
  209. });
  210. it("omits the model entirely for a run on the session model", async () => {
  211. const output = await call(
  212. "dwfrun-running",
  213. stubDetailPort({ "dwfrun-running": RUNNING_DETAIL }),
  214. );
  215. expect("subagentModel" in output).toBe(false);
  216. });
  217. // 本 run 的脚本文件(docs/dynamic-workflow/launch.md「Script files」)。端口给绝对路径(run
  218. // 身份的一部分),模型面给工作区相对写法——模型接下来要 Edit 这个文件,而那是它在别处
  219. // 读写文件时用的那一种路径。
  220. it("rewrites the run's script file as a workspace-relative path", async () => {
  221. const detail: DynamicWorkflowRunDetail = {
  222. ...RUNNING_DETAIL,
  223. scriptPath: "/workspace/project/.zcode/workflow-drafts/audit.dwf.ts",
  224. };
  225. const output = await call("dwfrun-running", stubDetailPort({ "dwfrun-running": detail }));
  226. expect(output.scriptPath).toBe(".zcode/workflow-drafts/audit.dwf.ts");
  227. });
  228. it("keeps a script file outside the working directory absolute", async () => {
  229. const detail: DynamicWorkflowRunDetail = {
  230. ...RUNNING_DETAIL,
  231. scriptPath: "/elsewhere/shared/audit.dwf.ts",
  232. };
  233. const output = await call("dwfrun-running", stubDetailPort({ "dwfrun-running": detail }));
  234. expect(output.scriptPath).toBe("/elsewhere/shared/audit.dwf.ts");
  235. expectMirrorsDetail(output, detail);
  236. });
  237. it("omits the script file entirely for a run that recorded none", async () => {
  238. const output = await call(
  239. "dwfrun-running",
  240. stubDetailPort({ "dwfrun-running": RUNNING_DETAIL }),
  241. );
  242. expect("scriptPath" in output).toBe(false);
  243. });
  244. it("carries the possiblyInterrupted annotation", async () => {
  245. const detail: DynamicWorkflowRunDetail = {
  246. ...RUNNING_DETAIL,
  247. ownedByThisSession: false,
  248. possiblyInterrupted: true,
  249. };
  250. const output = await call("dwfrun-running", stubDetailPort({ "dwfrun-running": detail }));
  251. expectMirrorsDetail(output, detail);
  252. });
  253. });
  254. describe("GetWorkflowRun handler — the situation cross-section", () => {
  255. it("carries the phase table, the roster and health across the boundary unchanged", async () => {
  256. const detail: DynamicWorkflowRunDetail = {
  257. ...RUNNING_DETAIL,
  258. phases: [
  259. {
  260. name: "collect",
  261. state: "done",
  262. rounds: 1,
  263. nodesSettled: 2,
  264. nodesRunning: 0,
  265. enteredAt: 1,
  266. exitedAt: 2,
  267. },
  268. {
  269. name: "judge",
  270. state: "current",
  271. rounds: 1,
  272. nodesSettled: 1,
  273. nodesRunning: 1,
  274. enteredAt: 2,
  275. },
  276. ],
  277. };
  278. const output = await call("dwfrun-running", stubDetailPort({ "dwfrun-running": detail }));
  279. expectMirrorsDetail(output, detail);
  280. });
  281. // 一个 actor 都没有的 run 是空数组,不是缺席:「有几个子代理」永远有答案,而 0 就是那个答案。
  282. it("keeps an empty roster as an empty array and an absent phase table absent", async () => {
  283. const detail: DynamicWorkflowRunDetail = { ...RUNNING_DETAIL, subagents: [] };
  284. const output = await call("dwfrun-running", stubDetailPort({ "dwfrun-running": detail }));
  285. expect(output.subagents).toEqual([]);
  286. expect("phases" in output).toBe(false);
  287. });
  288. it("clamps the roster at 64 rows and says it clamped", async () => {
  289. const one = RUNNING_DETAIL.subagents[1]!;
  290. const many = Array.from({ length: 70 }, (_, index) => ({ ...one, ordinal: index + 1 }));
  291. const output = await call(
  292. "dwfrun-many",
  293. stubDetailPort({ "dwfrun-many": { ...RUNNING_DETAIL, subagents: many } }),
  294. );
  295. expect(output.subagents).toHaveLength(64);
  296. expect(output.subagentsTruncated).toBe(true);
  297. expect(GetWorkflowRunOutputSchema.safeParse(output).success).toBe(true);
  298. const exact = await call(
  299. "dwfrun-exact",
  300. stubDetailPort({ "dwfrun-exact": { ...RUNNING_DETAIL, subagents: many.slice(0, 64) } }),
  301. );
  302. expect("subagentsTruncated" in exact).toBe(false);
  303. });
  304. // 终态 run 没有残留行是常态;`leftover_running=0` 读起来像一件发生过的事。
  305. it("drops a zero leftover count instead of reporting it", async () => {
  306. const detail: DynamicWorkflowRunDetail = {
  307. ...RUNNING_DETAIL,
  308. status: "stopped",
  309. stopReason: "interrupted",
  310. health: { ...RUNNING_DETAIL.health, leftoverRunning: 0 },
  311. };
  312. const output = await call("dwfrun-left", stubDetailPort({ "dwfrun-left": detail }));
  313. expect((output.health as Record<string, unknown>).leftoverRunning).toBeUndefined();
  314. expect(GetWorkflowRunOutputSchema.safeParse(output).success).toBe(true);
  315. });
  316. // turn / toolCalls 缺席读作「不知道」:老 journal 没有 node-progress,handler 不得补 0。
  317. it("never fabricates progress readings a journal does not have", async () => {
  318. const detail: DynamicWorkflowRunDetail = {
  319. ...RUNNING_DETAIL,
  320. subagents: [
  321. {
  322. siteId: "agent#1",
  323. ordinal: 1,
  324. state: "executing",
  325. currentAsk: { siteId: "ask#1", ordinal: 0 },
  326. stepsSettled: 0,
  327. stepsFailed: 0,
  328. tokens: 0,
  329. },
  330. ],
  331. };
  332. const output = await call("dwfrun-old", stubDetailPort({ "dwfrun-old": detail }));
  333. const ask = (output.subagents as Record<string, unknown>[])[0]!.currentAsk as Record<
  334. string,
  335. unknown
  336. >;
  337. for (const key of [
  338. "turn",
  339. "toolCalls",
  340. "lastTool",
  341. "startedAt",
  342. "actorSeq",
  343. "instructionsHead",
  344. ]) {
  345. expect(key in ask).toBe(false);
  346. }
  347. });
  348. // 一次调用一把尺:摘要与模型面的每一个年龄都对这一个读数算。
  349. it("stamps the snapshot with one clock and assembles the summary from it", async () => {
  350. const before = Date.now();
  351. const output = await call(
  352. "dwfrun-running",
  353. stubDetailPort({ "dwfrun-running": RUNNING_DETAIL }),
  354. );
  355. expect(output.generatedAt as number).toBeGreaterThanOrEqual(before);
  356. expect(output.generatedAt as number).toBeLessThanOrEqual(Date.now());
  357. expect(String(output.summary)).toContain("dispatched steps settled");
  358. expect(String(output.summary).length).toBeLessThanOrEqual(400);
  359. });
  360. });
  361. describe("GetWorkflowRun handler — terminal artifact", () => {
  362. function completedWith(result: unknown): DynamicWorkflowRunDetail {
  363. return { ...RUNNING_DETAIL, status: "completed", result };
  364. }
  365. it("passes a string artifact through verbatim", async () => {
  366. const output = await call(
  367. "dwfrun-done",
  368. stubDetailPort({ "dwfrun-done": completedWith("all specs green") }),
  369. );
  370. expect(output.result).toBe("all specs green");
  371. });
  372. // 序列化走 core 的唯一实现(serializeWorkflowArtifact),与完成通知和 TaskOutput 同一段文本。
  373. it("pretty-prints a structured artifact exactly like the completion notification", async () => {
  374. const output = await call(
  375. "dwfrun-done",
  376. stubDetailPort({ "dwfrun-done": completedWith({ verdict: "ship", failures: [] }) }),
  377. );
  378. expect(output.result).toBe('{\n "verdict": "ship",\n "failures": []\n}');
  379. expect(GetWorkflowRunOutputSchema.safeParse(output).success).toBe(true);
  380. });
  381. it("keeps null as a legal artifact and omits the field for undefined", async () => {
  382. const nullResult = await call(
  383. "dwfrun-null",
  384. stubDetailPort({ "dwfrun-null": completedWith(null) }),
  385. );
  386. const voidResult = await call(
  387. "dwfrun-void",
  388. stubDetailPort({ "dwfrun-void": { ...RUNNING_DETAIL, status: "completed" } }),
  389. );
  390. expect(nullResult.result).toBe("null");
  391. expect("result" in voidResult).toBe(false);
  392. });
  393. });
  394. // ⚠ 术语:上一个 describe 的 "artifact" 是脚本的**顶层返回值**(进 `result`);这一个是
  395. // 脚本经 `artifact.*` **发布给用户看的产出**(进 `artifacts`)。两者在同一份输出里并列。
  396. // 见 docs/dynamic-workflow/authoring.md「Artifacts: what the user keeps」。
  397. describe("GetWorkflowRun handler — published artifacts", () => {
  398. const AUDIT = {
  399. id: "audit",
  400. kind: "file" as const,
  401. title: "审计报告",
  402. contentType: "application/pdf",
  403. sourcePath: "out/audit.pdf",
  404. version: 2,
  405. itemCount: 0,
  406. versions: [
  407. { version: 1, publishedAt: 1, bytes: 10, uri: "zcode-artifact://one" },
  408. { version: 2, publishedAt: 2, bytes: 4_096, uri: "zcode-artifact://two" },
  409. ],
  410. };
  411. const PERF = {
  412. id: "perf",
  413. kind: "chart" as const,
  414. version: 1,
  415. itemCount: 12,
  416. spec: { x: { field: "round" }, y: { field: "ms" } },
  417. versions: [{ version: 1, publishedAt: 3 }],
  418. };
  419. it("hoists the latest version's bytes and drops uri / spec / versions from the model face", async () => {
  420. const output = await call(
  421. "dwfrun-art",
  422. stubDetailPort({
  423. "dwfrun-art": { ...RUNNING_DETAIL, status: "completed", artifacts: [AUDIT, PERF] },
  424. }),
  425. );
  426. expect(output.artifacts).toEqual([
  427. {
  428. id: "audit",
  429. kind: "file",
  430. title: "审计报告",
  431. version: 2,
  432. contentType: "application/pdf",
  433. // 最新版的字节数,不是第一版的。
  434. bytes: 4_096,
  435. sourcePath: "out/audit.pdf",
  436. itemCount: 0,
  437. },
  438. { id: "perf", kind: "chart", version: 1, itemCount: 12 },
  439. ]);
  440. expect(GetWorkflowRunOutputSchema.safeParse(output).success).toBe(true);
  441. });
  442. // 任意状态都附:一个还在跑的 run 也可能已经交付了第一张图。
  443. it("carries artifacts on a running run too, and omits the field when there are none", async () => {
  444. const running = await call(
  445. "dwfrun-art-running",
  446. stubDetailPort({ "dwfrun-art-running": { ...RUNNING_DETAIL, artifacts: [PERF] } }),
  447. );
  448. expect(running.status).toBe("running");
  449. expect(running.artifacts).toHaveLength(1);
  450. // 零件 / 端口不发这个键 ⇒ 整字段缺席(空数组读起来像「跑过但没产出」)。
  451. const none = await call("dwfrun-running", stubDetailPort({ "dwfrun-running": RUNNING_DETAIL }));
  452. expect("artifacts" in none).toBe(false);
  453. const empty = await call(
  454. "dwfrun-art-empty",
  455. stubDetailPort({ "dwfrun-art-empty": { ...RUNNING_DETAIL, artifacts: [] } }),
  456. );
  457. expect("artifacts" in empty).toBe(false);
  458. });
  459. it("bounds the section at 32 (= ARTIFACT_CAPS.maxArtifactsPerRun)", async () => {
  460. const many = Array.from({ length: 40 }, (_, index) => ({
  461. id: `a${index + 1}`,
  462. kind: "markdown" as const,
  463. version: 1,
  464. itemCount: 0,
  465. versions: [{ version: 1, publishedAt: 1, bytes: 8 }],
  466. }));
  467. const output = await call(
  468. "dwfrun-art-many",
  469. stubDetailPort({ "dwfrun-art-many": { ...RUNNING_OUTPUT, artifacts: many } }),
  470. );
  471. expect(output.artifacts).toHaveLength(32);
  472. });
  473. it("renders one line per artifact after <result> / <error>, in the notification's format", () => {
  474. const content = String(
  475. getWorkflowRunToolEntry.formatModelContent?.({
  476. ...RUNNING_OUTPUT,
  477. status: "completed",
  478. result: "shipped",
  479. artifacts: [
  480. {
  481. id: "audit",
  482. kind: "file",
  483. title: "审计报告",
  484. version: 2,
  485. contentType: "application/pdf",
  486. bytes: 4_096,
  487. sourcePath: "out/audit.pdf",
  488. itemCount: 0,
  489. },
  490. { id: "perf", kind: "chart", version: 1, itemCount: 12 },
  491. ],
  492. }),
  493. );
  494. expect(content).toContain('<artifacts count="2">');
  495. // 与完成通知逐字共用一个格式器:两处的读者是同一个模型。
  496. expect(content).toContain("- audit (file, v2, application/pdf, 4096 bytes): 审计报告");
  497. expect(content).toContain("- perf (chart, v1, 12 items)");
  498. // 排在 result 之后:run 的收场先读,交付物清单是索引。
  499. expect(content.indexOf("<artifacts")).toBeGreaterThan(content.indexOf("<result>"));
  500. });
  501. it("keeps the primary flag on the model face and marks its line right after the kind", async () => {
  502. const REPORT = {
  503. id: "report",
  504. kind: "markdown" as const,
  505. title: "审计报告",
  506. description: "结论与修复建议",
  507. version: 1,
  508. itemCount: 0,
  509. primary: true as const,
  510. versions: [{ version: 1, publishedAt: 4, bytes: 2_048, primary: true as const }],
  511. };
  512. const output = await call(
  513. "dwfrun-art-primary",
  514. stubDetailPort({
  515. "dwfrun-art-primary": {
  516. ...RUNNING_OUTPUT,
  517. status: "completed",
  518. // The port already orders the deliverable first; the handler keeps that order.
  519. artifacts: [REPORT, PERF],
  520. },
  521. }),
  522. );
  523. expect(output.artifacts).toEqual([
  524. {
  525. id: "report",
  526. kind: "markdown",
  527. title: "审计报告",
  528. version: 1,
  529. bytes: 2_048,
  530. itemCount: 0,
  531. primary: true,
  532. },
  533. { id: "perf", kind: "chart", version: 1, itemCount: 12 },
  534. ]);
  535. expect(GetWorkflowRunOutputSchema.safeParse(output).success).toBe(true);
  536. const content = String(
  537. getWorkflowRunToolEntry.formatModelContent?.({
  538. ...RUNNING_OUTPUT,
  539. status: "completed",
  540. artifacts: output.artifacts!,
  541. }),
  542. );
  543. expect(content).toContain("- report (markdown, primary, v1, 2048 bytes): 审计报告");
  544. expect(content).toContain("- perf (chart, v1, 12 items)");
  545. });
  546. it("omits the block when there are no artifacts", () => {
  547. expect(String(getWorkflowRunToolEntry.formatModelContent?.(RUNNING_OUTPUT))).not.toContain(
  548. "<artifacts",
  549. );
  550. });
  551. // 描述文案里的那一句:产物已经在用户面前,按标题引用而不是复述内容。
  552. it("tells the model in the tool description not to paste artifact contents", () => {
  553. expect(getWorkflowRunToolEntry.metadata.description).toContain(
  554. "ALREADY shown to them as cards",
  555. );
  556. expect(getWorkflowRunToolEntry.metadata.description).toContain(
  557. "The one marked `primary` is the deliverable",
  558. );
  559. });
  560. });
  561. describe("GetWorkflowRun handler — terminal failure", () => {
  562. it("passes the Interrupted code and the stop reason through so the model can tell a dead process from a bad script", async () => {
  563. const detail: DynamicWorkflowRunDetail = {
  564. ...RUNNING_DETAIL,
  565. status: "stopped",
  566. stopReason: "interrupted",
  567. error: {
  568. code: "Interrupted",
  569. message: "dynamic workflow run dwfrun-dead was interrupted",
  570. },
  571. };
  572. const output = await call("dwfrun-dead", stubDetailPort({ "dwfrun-dead": detail }));
  573. expectMirrorsDetail(output, detail);
  574. });
  575. it("carries an errored run's failure", async () => {
  576. const detail: DynamicWorkflowRunDetail = {
  577. ...RUNNING_DETAIL,
  578. status: "errored",
  579. error: { code: "DriverError", message: "the script threw" },
  580. };
  581. const output = await call("dwfrun-errored", stubDetailPort({ "dwfrun-errored": detail }));
  582. expect(output.status).toBe("errored");
  583. expect("stopReason" in output).toBe(false);
  584. expect(output.error).toEqual(detail.error);
  585. });
  586. // provider 停下(apps/zcode-cli/packages/dynamic-workflow/docs/execution-engine.md):结构化明细原样过界,模型面据它选文案。
  587. it("carries a provider stop's structured details", async () => {
  588. const detail: DynamicWorkflowRunDetail = {
  589. ...RUNNING_DETAIL,
  590. status: "stopped",
  591. stopReason: "provider",
  592. error: {
  593. code: "ProviderStop",
  594. message: "Subagent turn failed: [1006] token expired",
  595. providerStop: {
  596. kind: "auth",
  597. reason: "auth_failed",
  598. providerId: "account:bigmodel-coding-plan",
  599. providerLabel: "BigModel",
  600. modelId: "GLM-5.3",
  601. providerCode: "1006",
  602. subagent: "verify@2",
  603. phase: "Verify",
  604. rawMessage: "[1006] token expired",
  605. },
  606. },
  607. };
  608. const output = await call("dwfrun-stop", stubDetailPort({ "dwfrun-stop": detail }));
  609. expectMirrorsDetail(output, detail);
  610. });
  611. });
  612. describe("GetWorkflowRun model content", () => {
  613. it("renders the common cross-section, usage, actors and log tail as blocks", () => {
  614. const content = String(getWorkflowRunToolEntry.formatModelContent?.(RUNNING_OUTPUT));
  615. expect(content).toContain("<run_id>dwfrun-running</run_id>");
  616. expect(content).toContain('<label source="name">nightly triage</label>');
  617. expect(content).toContain("<status>running</status>");
  618. expect(content).toContain("<owned_by_this_session>true</owned_by_this_session>");
  619. // 时刻写两遍:可核对的 ISO,加上读者真正要的那个量(相对 generatedAt 的年龄)。
  620. expect(content).toContain("<updated_at>2026-08-21T09:05:00.000Z (40s ago)</updated_at>");
  621. expect(content).toContain("<created_at>2026-08-21T09:00:00.000Z (5m 40s ago)</created_at>");
  622. expect(content).toContain("<usage>spent_tokens=1204");
  623. expect(content).not.toContain("budget");
  624. expect(content).toContain("nodes_observed=3");
  625. expect(content).toContain("nodes_running=1");
  626. // 花名册取代了原先那张「只有身份」的 actors 表:名字在前,地址与相位随后。
  627. expect(content).toContain("judge agent#1@1 executing");
  628. expect(content).toContain("agent#2@1");
  629. expect(content).toContain("[11] 4m 50s ago collected the failing specs");
  630. expect(content).not.toContain("possibly_interrupted");
  631. expect(content).not.toContain("<result>");
  632. expect(content).not.toContain("<error");
  633. });
  634. // 一次省略 `max_concurrency` 的 AmendWorkflow 沿用的就是这个数,所以它必须在模型面上
  635. // 可见——否则模型无从知道一次修订会继承什么。
  636. it("gives the run's concurrency bound its own tag, and only when there is one", () => {
  637. const limited = String(
  638. getWorkflowRunToolEntry.formatModelContent?.({ ...RUNNING_OUTPUT, maxConcurrency: 3 }),
  639. );
  640. expect(limited).toContain("<max_concurrency>3</max_concurrency>");
  641. expect(String(getWorkflowRunToolEntry.formatModelContent?.(RUNNING_OUTPUT))).not.toContain(
  642. "max_concurrency",
  643. );
  644. });
  645. // 同理:一次省略 `subagent_model` 的 AmendWorkflow 沿用的就是这个字符串。
  646. it("gives the run's subagent model its own tag, and only when there is one", () => {
  647. const chosen = String(
  648. getWorkflowRunToolEntry.formatModelContent?.({
  649. ...RUNNING_OUTPUT,
  650. subagentModel: "bigmodel/GLM-4.6$high",
  651. }),
  652. );
  653. expect(chosen).toContain("<subagent_model>bigmodel/GLM-4.6$high</subagent_model>");
  654. expect(String(getWorkflowRunToolEntry.formatModelContent?.(RUNNING_OUTPUT))).not.toContain(
  655. "subagent_model",
  656. );
  657. });
  658. // 脚本点名的模型(docs/dynamic-workflow/launch.md「GetWorkflowRun」):修订里同名的模型沿用这些绑定。
  659. it("lists the script's model bindings one per line, next to the subagent model, only when there are any", () => {
  660. const bound = String(
  661. getWorkflowRunToolEntry.formatModelContent?.({
  662. ...RUNNING_OUTPUT,
  663. subagentModel: "bigmodel/GLM-4.6$high",
  664. modelBindings: {
  665. "GLM-5.3-Flash": "zhipu/GLM-5.3-Flash",
  666. "GLM-5.3$high": "zhipu/GLM-5.3$high",
  667. },
  668. }),
  669. );
  670. expect(bound).toContain(
  671. '<script_models>\n"GLM-5.3-Flash" = zhipu/GLM-5.3-Flash\n"GLM-5.3$high" = zhipu/GLM-5.3$high\n</script_models>',
  672. );
  673. expect(bound.indexOf("<subagent_model>")).toBeLessThan(bound.indexOf("<script_models>"));
  674. expect(String(getWorkflowRunToolEntry.formatModelContent?.(RUNNING_OUTPUT))).not.toContain(
  675. "script_models",
  676. );
  677. });
  678. // 脚本文件那一句进 `<amendable>`(docs/dynamic-workflow/launch.md「Script files」):这一块
  679. // 说的就是「怎么修订」,少了文件就等于让模型去内联重贴一份两万 token 的脚本。
  680. it("names the script file inside <amendable>, in both the short and the full form", () => {
  681. const sentence =
  682. ' Its script is at .zcode/workflow-drafts/audit.dwf.ts: edit that file in place and pass `path: ".zcode/workflow-drafts/audit.dwf.ts"` to AmendWorkflow instead of a script.';
  683. // 健康在跑:整块只有一句话,脚本文件那一句仍然跟在后面。
  684. const running = String(
  685. getWorkflowRunToolEntry.formatModelContent?.({
  686. ...RUNNING_OUTPUT,
  687. scriptPath: ".zcode/workflow-drafts/audit.dwf.ts",
  688. }),
  689. );
  690. expect(running).toContain(`cache.${sentence}</amendable>`);
  691. // 终态(errored 是这一块最高价值的那一支):完整论证之后接同一句。
  692. const errored = String(
  693. getWorkflowRunToolEntry.formatModelContent?.({
  694. ...RUNNING_OUTPUT,
  695. status: "errored" as const,
  696. scriptPath: ".zcode/workflow-drafts/audit.dwf.ts",
  697. }),
  698. );
  699. expect(errored).toContain("Do NOT rewrite from scratch.");
  700. expect(errored).toContain(`${sentence}</amendable>`);
  701. });
  702. it("says nothing about a script file when the run recorded none", () => {
  703. for (const output of [RUNNING_OUTPUT, { ...RUNNING_OUTPUT, status: "errored" as const }]) {
  704. const content = String(getWorkflowRunToolEntry.formatModelContent?.(output));
  705. expect(content).toContain("<amendable>");
  706. expect(content).not.toContain("Its script is at");
  707. }
  708. });
  709. it("says so in words when a running run has produced no log yet", () => {
  710. const content = String(
  711. getWorkflowRunToolEntry.formatModelContent?.({
  712. ...RUNNING_OUTPUT,
  713. actors: [],
  714. logTail: [],
  715. }),
  716. );
  717. expect(content).toMatch(/no log/i);
  718. });
  719. it("puts the artifact in its own block and the failure code in an attribute", () => {
  720. const completed = String(
  721. getWorkflowRunToolEntry.formatModelContent?.({
  722. ...RUNNING_OUTPUT,
  723. status: "completed",
  724. result: '{\n "verdict": "ship"\n}',
  725. }),
  726. );
  727. const interrupted = String(
  728. getWorkflowRunToolEntry.formatModelContent?.({
  729. ...RUNNING_OUTPUT,
  730. status: "stopped",
  731. stopReason: "interrupted",
  732. error: { code: "Interrupted", message: "the owning process exited" },
  733. }),
  734. );
  735. expect(completed).toContain('<result>\n{\n "verdict": "ship"\n}\n</result>');
  736. expect(interrupted).toContain("<stop_reason>interrupted</stop_reason>");
  737. expect(interrupted).toContain('<error code="Interrupted">the owning process exited</error>');
  738. });
  739. // provider 停下的 `<error>` 块与终态通知共用同一函数:原因 → 动作 → 事实行 → 原文行。
  740. it("renders a provider stop as the curated cause/fix block", () => {
  741. const content = String(
  742. getWorkflowRunToolEntry.formatModelContent?.({
  743. ...RUNNING_OUTPUT,
  744. status: "stopped",
  745. stopReason: "provider",
  746. error: {
  747. code: "ProviderStop",
  748. message: "Subagent turn failed: [1006] token expired",
  749. providerStop: {
  750. kind: "auth",
  751. reason: "auth_failed",
  752. providerId: "account:bigmodel-coding-plan",
  753. providerLabel: "BigModel",
  754. modelId: "GLM-5.3",
  755. providerCode: "1006",
  756. subagent: "verify@2",
  757. phase: "Verify",
  758. rawMessage: "[1006] token expired",
  759. },
  760. },
  761. }),
  762. );
  763. expect(content).toContain("<stop_reason>provider</stop_reason>");
  764. expect(content).toContain('<error code="ProviderStop">');
  765. expect(content).toContain("Sign-in to BigModel (account:bigmodel-coding-plan) expired");
  766. expect(content).toContain(`ResumeWorkflowRun with run_id="${RUNNING_OUTPUT.runId}"`);
  767. expect(content).toContain(
  768. "provider=account:bigmodel-coding-plan model=GLM-5.3 subagent=verify@2 phase=Verify code=1006",
  769. );
  770. expect(content).toContain("raw: [1006] token expired");
  771. // 可恢复提示要先让模型去解决原因,而不是盲目续跑。
  772. expect(content).toContain("<resumable>");
  773. expect(content).toMatch(/resolve the cause/i);
  774. });
  775. it("reports an invalid result instead of throwing", () => {
  776. expect(String(getWorkflowRunToolEntry.formatModelContent?.({ runId: 42 }))).toContain(
  777. "invalid result",
  778. );
  779. });
  780. // <resumable> 提示块的判定谓词与 port.resume 的门同语义:`stopped`,不论 reason
  781. // (apps/zcode-cli/packages/dynamic-workflow/docs/execution-engine.md)。钉正反例,防它被放宽到 errored(ScriptError 的
  782. // run replay 会逐字复现失败,绝不能引导模型去恢复它)。
  783. it("adds the <resumable> hint exactly for stopped runs, with the reason-specific caveat", () => {
  784. const user = String(
  785. getWorkflowRunToolEntry.formatModelContent?.({
  786. ...RUNNING_OUTPUT,
  787. status: "stopped",
  788. stopReason: "user",
  789. }),
  790. );
  791. const interrupted = String(
  792. getWorkflowRunToolEntry.formatModelContent?.({
  793. ...RUNNING_OUTPUT,
  794. status: "stopped",
  795. stopReason: "interrupted",
  796. error: { code: "Interrupted", message: "the owning process exited" },
  797. }),
  798. );
  799. expect(user).toContain("<resumable>");
  800. expect(user).toContain("ResumeWorkflowRun");
  801. expect(interrupted).toContain("<resumable>");
  802. expect(interrupted).toContain("ResumeWorkflowRun");
  803. // user 的提示块要说明它是有人故意停的、只在用户要求时恢复;interrupted 不带这句
  804. // (cancel-resume 追记 2026-09-09)。
  805. expect(user).toMatch(/stopped on purpose/i);
  806. expect(user).toMatch(/only when the user asks/i);
  807. expect(interrupted).not.toMatch(/stopped on purpose/i);
  808. // 「原样续跑等用户开口」与「为修而停的现在就修」是两件事:model 停的提示块两句都要有,
  809. // user 停的只有前一句(amend-resume 追记 2026-09-14)。
  810. const model = String(
  811. getWorkflowRunToolEntry.formatModelContent?.({
  812. ...RUNNING_OUTPUT,
  813. status: "stopped",
  814. stopReason: "model",
  815. }),
  816. );
  817. expect(model).toMatch(/only if that is what the user wants/i);
  818. expect(model).toMatch(/amend it now/i);
  819. expect(user).not.toMatch(/amend it now/i);
  820. expect(getWorkflowRunToolEntry.metadata.description ?? "").toMatch(/only when the user asks/i);
  821. });
  822. it("keeps the <resumable> hint off every non-resumable state", () => {
  823. const nonResumable = [
  824. // completed:已经跑完,没有可恢复的东西。
  825. { ...RUNNING_OUTPUT, status: "completed" as const, result: "done" },
  826. // running / pending:在飞或未起飞,恢复是无意义动作。
  827. RUNNING_OUTPUT,
  828. { ...RUNNING_OUTPUT, status: "pending" as const },
  829. // errored:脚本真失败,replay 会逐字复现失败——谓词绝不能放宽到它。
  830. {
  831. ...RUNNING_OUTPUT,
  832. status: "errored" as const,
  833. error: { code: "DriverError", message: "the script itself failed" },
  834. },
  835. ];
  836. for (const detail of nonResumable) {
  837. expect(String(getWorkflowRunToolEntry.formatModelContent?.(detail))).not.toContain(
  838. "<resumable>",
  839. );
  840. }
  841. });
  842. // 修订续跑(apps/zcode-cli/packages/dynamic-workflow/docs/execution-engine.md「Terminal states」):amend 的可用集是**任意
  843. // 终态**,与 plain resume 集刻意不同。两块提示各说各的,谁也不许污染谁。
  844. it("adds the <amendable> hint for every terminal run, including completed and ScriptError", () => {
  845. const terminal = [
  846. { ...RUNNING_OUTPUT, status: "completed" as const, result: "done" },
  847. { ...RUNNING_OUTPUT, status: "stopped" as const, stopReason: "user" as const },
  848. {
  849. ...RUNNING_OUTPUT,
  850. status: "errored" as const,
  851. error: { code: "DriverError", message: "the script itself failed" },
  852. },
  853. {
  854. ...RUNNING_OUTPUT,
  855. status: "stopped" as const,
  856. stopReason: "interrupted" as const,
  857. error: { code: "Interrupted", message: "the owning process exited" },
  858. },
  859. ];
  860. for (const detail of terminal) {
  861. const content = String(getWorkflowRunToolEntry.formatModelContent?.(detail));
  862. expect(content).toContain("<amendable>");
  863. expect(content).toContain("AmendWorkflow");
  864. expect(content).toContain("run_id");
  865. // run ID 进提示:模型可以直接照抄,不必回头翻 <run_id>。
  866. expect(content).toContain(RUNNING_OUTPUT.runId);
  867. // 只改设定时省略 script(docs/dynamic-workflow/launch.md「Keeping the predecessor's script」):
  868. // 不说出来,模型会为了改一个数把整份脚本再抄一遍。
  869. expect(content).toContain(
  870. "To change only its settings (max_concurrency, subagent_model, name), omit both `script` and `path`: the new run keeps this run's script.",
  871. );
  872. }
  873. });
  874. // docs/dynamic-workflow/launch.md「The `AmendWorkflow` tool」:在飞的 run 也可修订(amend 会先停下它),
  875. // 所以提示块对 running / pending 也在场,尾句说的是「现在就改、不要先 TaskStop」。
  876. // 但**健康地在跑**的那一种收缩成一句:那时没有任何决定要模型现在做,整段论证只是在挤占
  877. // 它读花名册的注意力;还没起飞的(pending)和已经停滞的仍给完整论证。
  878. it("keeps the <amendable> hint on runs that have not finished, with the amend-now tail", () => {
  879. const stalled = {
  880. ...RUNNING_OUTPUT,
  881. health: { ...RUNNING_OUTPUT.health, stalledSince: Date.UTC(2026, 7, 21, 9, 3, 0) },
  882. };
  883. for (const detail of [{ ...RUNNING_OUTPUT, status: "pending" as const }, stalled]) {
  884. const content = String(getWorkflowRunToolEntry.formatModelContent?.(detail));
  885. expect(content).toContain("<amendable>");
  886. expect(content).toContain("It is still running");
  887. expect(content).toContain("Do not TaskStop it first");
  888. }
  889. });
  890. it("collapses <amendable> to one sentence while the run is running and healthy", () => {
  891. const content = String(getWorkflowRunToolEntry.formatModelContent?.(RUNNING_OUTPUT));
  892. expect(content).toContain(
  893. '<amendable>AmendWorkflow with run_id "dwfrun-running" supersedes this run with a revised script and imports its finished work as cache.</amendable>',
  894. );
  895. // 一句话形态不带「省略 script」那句:健康地在跑的 run 没有要模型现在做的决定。
  896. expect(content).not.toContain("omit both `script` and `path`");
  897. expect(content).not.toContain("Do not TaskStop it first");
  898. });
  899. it("replaces <resumable> and <amendable> with <superseded> on a superseded run", () => {
  900. const content = String(
  901. getWorkflowRunToolEntry.formatModelContent?.({
  902. ...RUNNING_OUTPUT,
  903. status: "stopped" as const,
  904. stopReason: "superseded" as const,
  905. supersededBy: "dwfrun-next",
  906. }),
  907. );
  908. expect(content).toContain("<superseded_by>dwfrun-next</superseded_by>");
  909. expect(content).toContain("<superseded>");
  910. expect(content).toContain("run dwfrun-next");
  911. expect(content).not.toContain("<resumable>");
  912. expect(content).not.toContain("<amendable>");
  913. });
  914. // 脚本真失败是修订的最高价值场景,而模型的默认反射是从头重写。尾句必须把它说破。
  915. it("tells a script-failed run to fix the script instead of rewriting from scratch", () => {
  916. const scriptError = String(
  917. getWorkflowRunToolEntry.formatModelContent?.({
  918. ...RUNNING_OUTPUT,
  919. status: "errored" as const,
  920. error: { code: "DriverError", message: "the script itself failed" },
  921. }),
  922. );
  923. expect(scriptError).toMatch(/rewrite/i);
  924. expect(scriptError).toMatch(/fix the script/i);
  925. });
  926. // 两块提示同时在场(stopped 既可 plain resume 又可修订)时,差别必须写在提示里:
  927. // 同 run 同脚本 vs 新 run 新脚本。否则模型只会看到两条都能点的路由。
  928. it("distinguishes plain resume from amend when a run qualifies for both", () => {
  929. const cancelled = String(
  930. getWorkflowRunToolEntry.formatModelContent?.({
  931. ...RUNNING_OUTPUT,
  932. status: "stopped" as const,
  933. stopReason: "user" as const,
  934. }),
  935. );
  936. expect(cancelled).toContain("<resumable>");
  937. expect(cancelled).toContain("<amendable>");
  938. // plain resume 侧的语义未被削弱:同 run ID、逐字节相同脚本。
  939. expect(cancelled).toContain("same run ID");
  940. expect(cancelled).toMatch(/byte-for-byte/i);
  941. // amend 侧:新 run、修订脚本。
  942. expect(cancelled).toMatch(/revised script/i);
  943. });
  944. });
  945. // ————————————————————————————————————————————————
  946. // 停驻中的升级问题(apps/zcode-cli/packages/dynamic-workflow/docs/execution-engine.md)。
  947. //
  948. // 这是模型侧**唯一**的发现面:升级通知有两条已知的丢弃路径(stale branch generation /
  949. // shutdown),而 `ResolveWorkflowQuestion` 只认 qid。spec 把「查询兜底」写成了那两条路径的
  950. // 安全网,`unknown_question` 的服务端文案与升级通知也都明确指向这里——所以这几条断言钉住的
  951. // 不是一个展示细节,而是那两处承诺是否兑现。
  952. // ————————————————————————————————————————————————
  953. const PARKED_QUESTIONS = [
  954. {
  955. qid: "dwfq-parked01-1",
  956. actor: "agent#1@1",
  957. actorName: "judge",
  958. question: "评分上限是 95,通过线是 96,这个门不可能过。",
  959. context: "已经试了 6 轮,最高 95。",
  960. askedAt: Date.UTC(2026, 7, 21, 9, 5, 0),
  961. },
  962. {
  963. qid: "dwfq-parked01-2",
  964. actor: "agent#2@1",
  965. question: "两条指令互相矛盾,先满足哪一条?",
  966. askedAt: Date.UTC(2026, 7, 21, 9, 4, 30),
  967. },
  968. ];
  969. const PARKED_DETAIL: DynamicWorkflowRunDetail = {
  970. ...RUNNING_DETAIL,
  971. runId: "dwfrun-parked",
  972. pendingQuestions: PARKED_QUESTIONS,
  973. };
  974. const PARKED_OUTPUT: GetWorkflowRunOutput = {
  975. ...RUNNING_OUTPUT,
  976. runId: "dwfrun-parked",
  977. pendingQuestions: PARKED_QUESTIONS,
  978. };
  979. describe("GetWorkflowRun handler — pending escalations", () => {
  980. it("surfaces parked questions with their IDs, and keeps the field absent when there are none", async () => {
  981. const output = await call("dwfrun-parked", stubDetailPort({ "dwfrun-parked": PARKED_DETAIL }));
  982. const parsed = GetWorkflowRunOutputSchema.parse(output);
  983. expect(parsed.pendingQuestions).toHaveLength(2);
  984. expect(parsed.pendingQuestions?.[0]).toEqual({
  985. qid: "dwfq-parked01-1",
  986. actor: "agent#1@1",
  987. actorName: "judge",
  988. question: "评分上限是 95,通过线是 96,这个门不可能过。",
  989. context: "已经试了 6 轮,最高 95。",
  990. askedAt: Date.UTC(2026, 7, 21, 9, 5, 0),
  991. });
  992. // 匿名 actor 不合成兜底名;可选字段缺席就是缺席。
  993. expect(parsed.pendingQuestions?.[1] && "actorName" in parsed.pendingQuestions[1]).toBe(false);
  994. expect(parsed.pendingQuestions?.[1] && "context" in parsed.pendingQuestions[1]).toBe(false);
  995. // 零条 → 整字段缺席(空数组读起来像「问过、已答完」,缺席才是「没人在等」)。
  996. const idle = await call("dwfrun-running", stubDetailPort({ "dwfrun-running": RUNNING_DETAIL }));
  997. expect("pendingQuestions" in idle).toBe(false);
  998. const empty = await call(
  999. "dwfrun-empty",
  1000. stubDetailPort({
  1001. "dwfrun-empty": { ...RUNNING_DETAIL, runId: "dwfrun-empty", pendingQuestions: [] },
  1002. }),
  1003. );
  1004. expect("pendingQuestions" in empty).toBe(false);
  1005. });
  1006. it("renders the pending block with the qid and the ResolveWorkflowQuestion instruction", () => {
  1007. const content = String(getWorkflowRunToolEntry.formatModelContent?.(PARKED_OUTPUT));
  1008. expect(content).toContain("<pending_questions>");
  1009. expect(content).toContain("dwfq-parked01-1");
  1010. expect(content).toContain("dwfq-parked01-2");
  1011. expect(content).toContain("judge");
  1012. // 匿名 actor 落到结构化 ref。
  1013. expect(content).toContain("agent#2@1");
  1014. expect(content).toContain("ResolveWorkflowQuestion");
  1015. // 排在 log 尾巴之前:一个停驻的 actor 是此刻要做的事,不该埋在二十行叙事后面。
  1016. expect(content.indexOf("<pending_questions>")).toBeLessThan(content.indexOf("<log_tail>"));
  1017. });
  1018. it("omits the pending block entirely for a run with nothing parked", () => {
  1019. expect(String(getWorkflowRunToolEntry.formatModelContent?.(RUNNING_OUTPUT))).not.toContain(
  1020. "pending_questions",
  1021. );
  1022. });
  1023. });
  1024. // ————————————————————————————————————————————————
  1025. // 情势截面(docs/dynamic-workflow/launch.md「`GetWorkflowRun`」)。
  1026. //
  1027. // 三个场景钉的是同一件事:这份输出能不能回答「run 在哪、谁在干什么、它还在动吗」。
  1028. // 块序是契约,每一行的事实也是——所以这里既断言顺序,也断言那几行的字。
  1029. // `summary` 用真正的拼装器铸出(不是手写一句),于是这三段文本就是端到端的真实渲染。
  1030. // ————————————————————————————————————————————————
  1031. /** 块在文本里的出现位置,用来断言块序。 */
  1032. function blockOrder(content: string, tags: readonly string[]): number[] {
  1033. return tags.map((tag) => content.indexOf(tag));
  1034. }
  1035. function renderWithSummary(base: Omit<GetWorkflowRunOutput, "summary">): string {
  1036. const output: GetWorkflowRunOutput = { ...base, summary: buildWorkflowRunSummary(base) };
  1037. return String(getWorkflowRunToolEntry.formatModelContent?.(output));
  1038. }
  1039. const SITREP_BASE: Omit<GetWorkflowRunOutput, "summary"> = {
  1040. runId: "dwfrun-7f3a",
  1041. label: "nightly triage",
  1042. labelSource: "name",
  1043. status: "running",
  1044. ownedByThisSession: true,
  1045. createdAt: Date.UTC(2026, 7, 21, 9, 0, 0),
  1046. updatedAt: Date.UTC(2026, 7, 21, 9, 5, 0),
  1047. generatedAt: NOW,
  1048. maxConcurrency: 3,
  1049. subagentModel: "bigmodel/GLM-4.6$high",
  1050. // 计数与花名册互相对齐:活相位的子代理各占一条还在跑的 ask 行(executing / waiting /
  1051. // parked 各一),所以 nodesRunning = 3;nodesObserved 是三态之和 = 5 + 3。
  1052. usage: {
  1053. spentTokens: 18_420,
  1054. nodesObserved: 8,
  1055. nodesRunning: 3,
  1056. nodesCompleted: 5,
  1057. nodesFailed: 0,
  1058. },
  1059. actors: [
  1060. { siteId: "agent#1", ordinal: 1, name: "collector" },
  1061. { siteId: "agent#2", ordinal: 1, name: "judge" },
  1062. { siteId: "agent#2", ordinal: 2, name: "judge" },
  1063. { siteId: "agent#3", ordinal: 1 },
  1064. ],
  1065. logTail: [
  1066. { sequence: 11, message: "collected 14 failing specs", at: Date.UTC(2026, 7, 21, 9, 0, 50) },
  1067. { sequence: 14, message: "dispatching judges in pairs", at: Date.UTC(2026, 7, 21, 9, 1, 50) },
  1068. {
  1069. sequence: 19,
  1070. message: "judge#1 finished: 6 flaky, 1 real",
  1071. at: Date.UTC(2026, 7, 21, 9, 4, 10),
  1072. },
  1073. ],
  1074. phases: [
  1075. {
  1076. name: "collect",
  1077. state: "done",
  1078. rounds: 1,
  1079. nodesSettled: 2,
  1080. nodesRunning: 0,
  1081. enteredAt: Date.UTC(2026, 7, 21, 9, 0, 0),
  1082. exitedAt: Date.UTC(2026, 7, 21, 9, 1, 20),
  1083. },
  1084. {
  1085. name: "judge",
  1086. state: "current",
  1087. rounds: 1,
  1088. nodesSettled: 3,
  1089. nodesRunning: 3,
  1090. enteredAt: Date.UTC(2026, 7, 21, 9, 1, 20),
  1091. },
  1092. { name: "verify", state: "ahead", rounds: 0, nodesSettled: 0, nodesRunning: 0 },
  1093. { name: "report", state: "ahead", rounds: 0, nodesSettled: 0, nodesRunning: 0 },
  1094. ],
  1095. subagents: [
  1096. {
  1097. siteId: "agent#1",
  1098. ordinal: 1,
  1099. name: "collector",
  1100. // 活着的 run 上端口从不发 `done`(那是终态词):干完自己那份活的子代理是 `idle`。
  1101. state: "idle",
  1102. phaseName: "collect",
  1103. stepsSettled: 2,
  1104. stepsFailed: 0,
  1105. tokens: 6_210,
  1106. },
  1107. {
  1108. siteId: "agent#2",
  1109. ordinal: 1,
  1110. name: "judge",
  1111. state: "parked",
  1112. phaseName: "judge",
  1113. currentAsk: {
  1114. siteId: "ask#4",
  1115. ordinal: 0,
  1116. actorSeq: 1,
  1117. instructionsHead: "Judge specs 8-14 for flakiness; report real failures with evidence",
  1118. startedAt: Date.UTC(2026, 7, 21, 9, 2, 0),
  1119. },
  1120. parkedOn: "q-01",
  1121. stepsSettled: 1,
  1122. stepsFailed: 0,
  1123. tokens: 4_980,
  1124. },
  1125. {
  1126. siteId: "agent#2",
  1127. ordinal: 2,
  1128. name: "judge",
  1129. state: "executing",
  1130. phaseName: "judge",
  1131. currentAsk: {
  1132. siteId: "ask#4",
  1133. ordinal: 1,
  1134. actorSeq: 2,
  1135. instructionsHead: "Judge specs 1-7 for flakiness; report real failures with evidence",
  1136. startedAt: Date.UTC(2026, 7, 21, 9, 4, 28),
  1137. turn: 4,
  1138. toolCalls: 7,
  1139. lastTool: {
  1140. name: "Read",
  1141. target: "packages/net/retry.spec.ts",
  1142. at: Date.UTC(2026, 7, 21, 9, 5, 32),
  1143. },
  1144. },
  1145. stepsSettled: 1,
  1146. stepsFailed: 0,
  1147. tokens: 5_100,
  1148. lastProgressAt: Date.UTC(2026, 7, 21, 9, 5, 32),
  1149. },
  1150. {
  1151. siteId: "agent#3",
  1152. ordinal: 1,
  1153. state: "waiting",
  1154. phaseName: "judge",
  1155. wait: {
  1156. cause: "backoff",
  1157. reason: "429",
  1158. retryAfterMs: 20_000,
  1159. since: Date.UTC(2026, 7, 21, 9, 5, 20),
  1160. },
  1161. stepsSettled: 1,
  1162. stepsFailed: 0,
  1163. tokens: 2_130,
  1164. },
  1165. ],
  1166. health: {
  1167. lastProgressAt: Date.UTC(2026, 7, 21, 9, 5, 0),
  1168. concurrency: {
  1169. effective: 2,
  1170. cap: 3,
  1171. reason: "rate_limited",
  1172. since: Date.UTC(2026, 7, 21, 9, 4, 35),
  1173. },
  1174. consecutiveFailures: 0,
  1175. cachedSteps: 0,
  1176. pendingQuestionsKnown: true,
  1177. },
  1178. pendingQuestions: [
  1179. {
  1180. qid: "q-01",
  1181. actor: "agent#2@1",
  1182. actorName: "judge",
  1183. question: "Two specs disagree on the retry budget; which one is authoritative?",
  1184. context: "packages/net/retry.spec.ts vs docs/net/retry.md",
  1185. askedAt: Date.UTC(2026, 7, 21, 9, 5, 0),
  1186. },
  1187. ],
  1188. artifacts: [
  1189. { id: "triage-board", kind: "board", title: "Triage board", version: 3, itemCount: 7 },
  1190. ],
  1191. };
  1192. describe("GetWorkflowRun model content — a running situation report", () => {
  1193. const content = renderWithSummary(SITREP_BASE);
  1194. it("keeps the contract block order, summary first and routing last", () => {
  1195. const order = blockOrder(content, [
  1196. "<summary>",
  1197. "<run_id>",
  1198. "<status>",
  1199. "<max_concurrency>",
  1200. "<subagent_model>",
  1201. "<created_at>",
  1202. "<pending_questions>",
  1203. "<health>",
  1204. "<phases>",
  1205. "<subagents>",
  1206. "<log_tail>",
  1207. "<usage>",
  1208. "<artifacts",
  1209. "<amendable>",
  1210. ]);
  1211. expect(order).toEqual([...order].sort((left, right) => left - right));
  1212. expect(order.every((index) => index >= 0)).toBe(true);
  1213. });
  1214. it("assembles the summary from status, phase position, step counts, questions and progress", () => {
  1215. expect(content).toContain(
  1216. "<summary>Running for 5m 40s, in phase 2 of 4 (judge). 5 of 8 dispatched steps settled, 3 running (1 executing, 1 waiting, 1 parked). 1 question awaiting your answer. Last progress 40s ago.</summary>",
  1217. );
  1218. });
  1219. it("reports health on one line with the throttle and its age", () => {
  1220. expect(content).toContain(
  1221. "<health>last_progress=40s ago concurrency=2/3 (rate_limited since 1m 05s ago) stalled=no consecutive_failures=0 cached_steps=0</health>",
  1222. );
  1223. });
  1224. // `ahead` 的行只有名字和状态:它还没发生过,所以没有轮次、没有计数、没有时长。
  1225. it("draws the phase table with rounds, counts and the current phase's time so far", () => {
  1226. expect(content).toContain("1. collect done 1 round 2 steps settled 1m 20s");
  1227. expect(content).toContain("2. judge current 1 round 3 settled, 3 running 4m 20s so far");
  1228. expect(content).toContain("3. verify ahead");
  1229. expect(content).toContain("4. report ahead");
  1230. });
  1231. // 一行读作「谁 · 在哪 · 什么相位 · 哪个阶段 · 在做什么 · 花了多少」。
  1232. it("draws one roster line per subagent, with the ask, the last tool and the wait cause", () => {
  1233. expect(content).toContain(
  1234. "judge agent#2@2 executing phase judge ask#4@1 (step 3), 1m 12s on this step, turn 4, 7 tool calls, last Read packages/net/retry.spec.ts 8s ago 5,100 tokens",
  1235. );
  1236. expect(content).toContain(
  1237. "judge agent#2@1 parked phase judge on question q-01 for 40s 4,980 tokens",
  1238. );
  1239. expect(content).toContain(
  1240. "agent#3@1 waiting phase judge backoff after 429 for 20s, retry in 20s 2,130 tokens",
  1241. );
  1242. expect(content).toContain(
  1243. "collector agent#1@1 idle phase collect 2 steps 6,210 tokens",
  1244. );
  1245. // 任务摘要缩进一行挂在它所属的那一行下面。
  1246. expect(content).toContain(
  1247. " task: Judge specs 1-7 for flakiness; report real failures with evidence",
  1248. );
  1249. });
  1250. it("prefixes each log line with its age", () => {
  1251. expect(content).toContain("[19] 1m 30s ago judge#1 finished: 6 flaky, 1 real");
  1252. });
  1253. it("dates the parked question by age instead of an ISO instant", () => {
  1254. expect(content).toContain("[q-01] judge asked 40s ago");
  1255. expect(content).toContain("ResolveWorkflowQuestion");
  1256. });
  1257. });
  1258. describe("GetWorkflowRun model content — a completed run", () => {
  1259. const completed: Omit<GetWorkflowRunOutput, "summary"> = {
  1260. ...SITREP_BASE,
  1261. status: "completed",
  1262. updatedAt: Date.UTC(2026, 7, 21, 9, 4, 20),
  1263. usage: {
  1264. ...SITREP_BASE.usage,
  1265. spentTokens: 41_200,
  1266. nodesRunning: 0,
  1267. nodesCompleted: 12,
  1268. nodesObserved: 12,
  1269. },
  1270. phases: [
  1271. {
  1272. name: "collect",
  1273. state: "done",
  1274. rounds: 1,
  1275. nodesSettled: 2,
  1276. nodesRunning: 0,
  1277. enteredAt: Date.UTC(2026, 7, 21, 9, 0, 0),
  1278. exitedAt: Date.UTC(2026, 7, 21, 9, 1, 20),
  1279. },
  1280. {
  1281. name: "judge",
  1282. state: "done",
  1283. rounds: 1,
  1284. nodesSettled: 6,
  1285. nodesRunning: 0,
  1286. enteredAt: Date.UTC(2026, 7, 21, 9, 1, 20),
  1287. exitedAt: Date.UTC(2026, 7, 21, 9, 3, 0),
  1288. },
  1289. {
  1290. name: "verify",
  1291. state: "done",
  1292. rounds: 2,
  1293. nodesSettled: 3,
  1294. nodesRunning: 0,
  1295. enteredAt: Date.UTC(2026, 7, 21, 9, 3, 0),
  1296. exitedAt: Date.UTC(2026, 7, 21, 9, 4, 0),
  1297. },
  1298. {
  1299. name: "report",
  1300. state: "done",
  1301. rounds: 1,
  1302. nodesSettled: 1,
  1303. nodesRunning: 0,
  1304. enteredAt: Date.UTC(2026, 7, 21, 9, 4, 0),
  1305. exitedAt: Date.UTC(2026, 7, 21, 9, 4, 20),
  1306. },
  1307. ],
  1308. // 终态 run 上干完的子代理才是 `done`。
  1309. subagents: [{ ...SITREP_BASE.subagents[0]!, state: "done" }],
  1310. health: {
  1311. lastProgressAt: Date.UTC(2026, 7, 21, 9, 4, 20),
  1312. consecutiveFailures: 0,
  1313. cachedSteps: 2,
  1314. pendingQuestionsKnown: true,
  1315. },
  1316. pendingQuestions: undefined,
  1317. result: "12 specs triaged",
  1318. artifacts: [
  1319. {
  1320. id: "report",
  1321. kind: "markdown",
  1322. title: "Nightly triage report",
  1323. version: 1,
  1324. itemCount: 0,
  1325. primary: true,
  1326. },
  1327. ],
  1328. };
  1329. const content = renderWithSummary(completed);
  1330. it("counts phases instead of pointing at one, and names the deliverable", () => {
  1331. expect(content).toContain(
  1332. "<summary>Completed in 4m 20s, across 4 phases. 12 steps settled, 41,200 tokens. Deliverable: Nightly triage report (markdown, primary).</summary>",
  1333. );
  1334. });
  1335. // 终态 run 不报 stalled(它当然不动了),也不报 leftover(没有残留行)。
  1336. it("drops the stalled reading from a terminal run's health", () => {
  1337. expect(content).toContain(
  1338. "<health>last_progress=1m 20s ago consecutive_failures=0 cached_steps=2</health>",
  1339. );
  1340. expect(content).not.toContain("stalled=");
  1341. expect(content).not.toContain("leftover");
  1342. });
  1343. it("gives every phase its duration and no 'so far'", () => {
  1344. expect(content).toContain("2. judge done 1 round 6 steps settled 1m 40s");
  1345. expect(content).toContain("3. verify done 2 rounds 3 steps settled 1m 00s");
  1346. expect(content).not.toContain("so far");
  1347. });
  1348. });
  1349. describe("GetWorkflowRun model content — an interrupted run seen from another session", () => {
  1350. const interrupted: Omit<GetWorkflowRunOutput, "summary"> = {
  1351. ...SITREP_BASE,
  1352. status: "stopped",
  1353. stopReason: "interrupted",
  1354. ownedByThisSession: false,
  1355. updatedAt: Date.UTC(2026, 7, 21, 9, 5, 0),
  1356. error: { code: "Interrupted", message: "the owning process exited" },
  1357. // 终态 run 里「还在跑」的行就是残留行:nodesRunning = leftoverRunning = 两个 unfinished
  1358. // 子代理各自那一条。observed 仍是三态之和 = 5 + 2。
  1359. usage: { ...SITREP_BASE.usage, nodesObserved: 7, nodesRunning: 2 },
  1360. phases: [
  1361. {
  1362. name: "collect",
  1363. state: "done",
  1364. rounds: 1,
  1365. nodesSettled: 2,
  1366. nodesRunning: 0,
  1367. enteredAt: Date.UTC(2026, 7, 21, 9, 0, 0),
  1368. exitedAt: Date.UTC(2026, 7, 21, 9, 1, 20),
  1369. },
  1370. {
  1371. name: "judge",
  1372. state: "unfinished",
  1373. rounds: 1,
  1374. nodesSettled: 3,
  1375. nodesRunning: 2,
  1376. enteredAt: Date.UTC(2026, 7, 21, 9, 1, 20),
  1377. },
  1378. { name: "verify", state: "ahead", rounds: 0, nodesSettled: 0, nodesRunning: 0 },
  1379. { name: "report", state: "ahead", rounds: 0, nodesSettled: 0, nodesRunning: 0 },
  1380. ],
  1381. subagents: [
  1382. { ...SITREP_BASE.subagents[0]!, state: "done" },
  1383. {
  1384. siteId: "agent#2",
  1385. ordinal: 1,
  1386. name: "judge",
  1387. state: "unfinished",
  1388. phaseName: "judge",
  1389. currentAsk: {
  1390. siteId: "ask#4",
  1391. ordinal: 0,
  1392. actorSeq: 1,
  1393. startedAt: Date.UTC(2026, 7, 21, 9, 2, 0),
  1394. },
  1395. stepsSettled: 1,
  1396. stepsFailed: 0,
  1397. tokens: 4_980,
  1398. },
  1399. {
  1400. siteId: "agent#2",
  1401. ordinal: 2,
  1402. name: "judge",
  1403. state: "unfinished",
  1404. phaseName: "judge",
  1405. currentAsk: {
  1406. siteId: "ask#4",
  1407. ordinal: 1,
  1408. actorSeq: 2,
  1409. startedAt: Date.UTC(2026, 7, 21, 9, 4, 28),
  1410. },
  1411. stepsSettled: 1,
  1412. stepsFailed: 0,
  1413. tokens: 5_100,
  1414. },
  1415. ],
  1416. health: {
  1417. lastProgressAt: Date.UTC(2026, 7, 21, 9, 5, 0),
  1418. consecutiveFailures: 0,
  1419. cachedSteps: 0,
  1420. leftoverRunning: 2,
  1421. // 停驻表只活在提问那个进程的内存里:这次读根本不知道有没有人在等。
  1422. pendingQuestionsKnown: false,
  1423. },
  1424. pendingQuestions: undefined,
  1425. artifacts: undefined,
  1426. };
  1427. const content = renderWithSummary(interrupted);
  1428. it("says the leftovers will be re-dispatched and that the run is another session's", () => {
  1429. expect(content).toContain(
  1430. "<summary>Stopped (interrupted) 40s ago after 5m 00s, in phase 2 of 4 (judge). 5 of 7 dispatched steps settled; 2 were still running when the owning process exited and will be re-dispatched on resume. Pending questions are unknown from this session. Owned by another session.</summary>",
  1431. );
  1432. });
  1433. // 沉默会被读成「没有人在等」,而那是最危险的误读——这是仅有的两处「把不知道说出口」之一。
  1434. it("replaces the pending block with the explicit unknown sentence", () => {
  1435. expect(content).toContain(
  1436. "<pending_questions>Unknown: pending questions are tracked only by the process",
  1437. );
  1438. expect(content).toContain(
  1439. "Resuming the run will re-ask any question its subagent still needs answered.",
  1440. );
  1441. expect(content).not.toContain("[q-01]");
  1442. });
  1443. // 另一处:终态 run 里标着 running 的行是残留,不是活的工作。
  1444. it("adds the leftover note under health and marks the phase unfinished", () => {
  1445. expect(content).toContain(
  1446. 'The 2 "running" steps below are leftovers of the exited process, not live work.',
  1447. );
  1448. expect(content).toContain("2. judge unfinished 1 round 3 settled, 2 unfinished");
  1449. expect(content).toContain(
  1450. "judge agent#2@1 unfinished phase judge ask#4@0 (step 2) was in flight at the stop",
  1451. );
  1452. });
  1453. it("still routes to ResumeWorkflowRun and AmendWorkflow with the full argument", () => {
  1454. expect(content).toContain("<resumable>");
  1455. expect(content).toContain("<amendable>");
  1456. expect(content).toContain("Use it when the script or a setting needs to change");
  1457. });
  1458. });
  1459. describe("GetWorkflowRun declaration", () => {
  1460. it("declares a read-only, no-side-effect capability consistently on both faces", () => {
  1461. expect(getWorkflowRunToolEntry.metadata).toMatchObject({
  1462. name: GET_WORKFLOW_RUN_TOOL_NAME,
  1463. readOnly: true,
  1464. destructive: false,
  1465. concurrentSafe: true,
  1466. needsApproval: false,
  1467. sideEffectScope: "none",
  1468. riskLevel: "low",
  1469. timeoutMs: 10_000,
  1470. });
  1471. expect(getWorkflowRunToolEntry.permission).toMatchObject({
  1472. permission: "getWorkflowRun",
  1473. needsApproval: false,
  1474. sideEffectScope: "none",
  1475. riskLevel: "low",
  1476. denyPriority: "beforeAsk",
  1477. });
  1478. expect(getWorkflowRunToolEntry.permission.alwaysAsk).toBeUndefined();
  1479. });
  1480. // 产物就是可能大到需要 artifact 的那类载荷(照 TaskOutput)。
  1481. it("budgets the result as a persistable artifact", () => {
  1482. expect(getWorkflowRunToolEntry.resultBudget).toMatchObject({
  1483. maxInlineBytes: 400_000,
  1484. maxModelBytes: 400_000,
  1485. strategy: "artifact",
  1486. artifact: { enabled: true, retention: "session" },
  1487. });
  1488. expect(getWorkflowRunToolEntry.maxModelChars).toBe(100_000);
  1489. expect(getWorkflowRunToolEntry.resultArtifactContentType).toBe("text/plain");
  1490. });
  1491. // tool-contracts.test.ts 的 v2 全量循环在第一处不一致就中止;新工具在这里各自再钉一遍。
  1492. it("declares the v2 common contract", () => {
  1493. expectV2CommonContract(getWorkflowRunToolEntry);
  1494. });
  1495. it("steers the model to TaskOutput for blocking waits and away from polling", () => {
  1496. const description = getWorkflowRunToolEntry.metadata.description ?? "";
  1497. expect(description).toMatch(/do not poll/i);
  1498. expect(description).toMatch(/notification/i);
  1499. expect(description).toContain("TaskOutput");
  1500. expect(description).toMatch(/wait/i);
  1501. expect(description).toContain("ListWorkflowRuns");
  1502. });
  1503. // 路由引导(2026-08-29):可恢复终态要指路 ResumeWorkflowRun。钉关键词,不钉逐字。
  1504. it("cross-references ResumeWorkflowRun for the resumable terminal states", () => {
  1505. const description = getWorkflowRunToolEntry.metadata.description ?? "";
  1506. expect(description).toContain("ResumeWorkflowRun");
  1507. expect(description).toMatch(/cancel/i);
  1508. expect(description).toContain("interrupted");
  1509. });
  1510. // 修订续跑(2026-08-31):描述里也要有第二条路由,且必须与上一条区分开。
  1511. it("cross-references AmendWorkflow for any run and names the superseded state", () => {
  1512. const description = getWorkflowRunToolEntry.metadata.description ?? "";
  1513. expect(description).toContain("AmendWorkflow");
  1514. expect(description).not.toContain("resume_from");
  1515. expect(description).toMatch(/revised/i);
  1516. expect(description).toContain("superseded");
  1517. });
  1518. });
  1519. describe("GetWorkflowRun registration", () => {
  1520. it("is always on, with no gate option", () => {
  1521. const registry = createToolRegistry();
  1522. registerBuiltInTools(registry);
  1523. expect(registry.has(GET_WORKFLOW_RUN_TOOL_NAME)).toBe(true);
  1524. expect(registry.toContracts().map((tool) => tool.name)).toContain(GET_WORKFLOW_RUN_TOOL_NAME);
  1525. });
  1526. for (const mode of ["plan", "build", "yolo"] as const) {
  1527. it(`is auto-allowed in ${mode} mode`, () => {
  1528. const capability = resolveRuntimePermissionCapability(
  1529. getWorkflowRunToolEntry,
  1530. { run_id: "dwfrun-x" },
  1531. {
  1532. workingDirectory: "/workspace/project",
  1533. workspaceRoot: "/workspace/project",
  1534. } as never,
  1535. );
  1536. expect(
  1537. new PermissionService().checkPermission(
  1538. {
  1539. input: { run_id: "dwfrun-x" },
  1540. mode,
  1541. riskLevel: "low",
  1542. toolName: GET_WORKFLOW_RUN_TOOL_NAME,
  1543. },
  1544. capability,
  1545. ),
  1546. ).toMatchObject({ allowed: true, decision: "allow" });
  1547. });
  1548. }
  1549. });
  1550. // 留白(docs/dynamic-workflow/launch.md「The `FillWorkflowHole` tool」):`holes` 与 pendingQuestions 同规——
  1551. // 零条缺席、逐字段镜像;模型面的 `<holes>` 块列出等着的与补过的,并点名 FillWorkflowHole 与 hole_id。
  1552. describe("GetWorkflowRun handler — holes", () => {
  1553. const holes = [
  1554. {
  1555. siteId: "hole#1",
  1556. ordinal: 1,
  1557. name: "决定分组",
  1558. type: "Verdict",
  1559. state: "waiting" as const,
  1560. since: NOW - 40_000,
  1561. },
  1562. {
  1563. siteId: "hole#2",
  1564. ordinal: 1,
  1565. name: "收尾",
  1566. type: "string",
  1567. state: "filled" as const,
  1568. filledAt: NOW - 10_000,
  1569. filledBy: "sess_get_run",
  1570. },
  1571. ];
  1572. it("mirrors the holes list and leaves it absent when empty", async () => {
  1573. const detail: DynamicWorkflowRunDetail = { ...RUNNING_DETAIL, holes };
  1574. const output = await call("dwfrun-running", stubDetailPort({ "dwfrun-running": detail }));
  1575. expectMirrorsDetail(output, detail);
  1576. // 摘要也点一句:等着的留白是此刻等着模型做的事(补过的不算)。
  1577. expect(output.summary).toContain("1 hole awaiting your code.");
  1578. const empty = await call(
  1579. "dwfrun-running",
  1580. stubDetailPort({ "dwfrun-running": { ...RUNNING_DETAIL, holes: [] } }),
  1581. );
  1582. expect("holes" in empty).toBe(false);
  1583. expect(empty.summary).not.toContain("hole");
  1584. });
  1585. it("renders a <holes> block naming FillWorkflowHole and the hole ids, after pending questions", () => {
  1586. const text = getWorkflowRunToolEntry.formatModelContent!({
  1587. ...RUNNING_OUTPUT,
  1588. pendingQuestions: [
  1589. { qid: "dwfq-1", actor: "agent#1@1", question: "q?", askedAt: NOW - 5_000 },
  1590. ],
  1591. holes,
  1592. }) as string;
  1593. expect(text).toContain("<holes>");
  1594. expect(text).toContain('[hole#1] "决定分组": Verdict — waiting 40s');
  1595. expect(text).toContain('[hole#2] "收尾": string — filled 10s ago');
  1596. expect(text).toContain(
  1597. 'FillWorkflowHole with run_id="dwfrun-running" and the hole id in brackets as hole_id',
  1598. );
  1599. expect(text.indexOf("<pending_questions>")).toBeLessThan(text.indexOf("<holes>"));
  1600. expect(text.indexOf("<holes>")).toBeLessThan(text.indexOf("<health"));
  1601. expect(getWorkflowRunToolEntry.formatModelContent!(RUNNING_OUTPUT) as string).not.toContain(
  1602. "<holes>",
  1603. );
  1604. });
  1605. });
  1606. // 递归留白:嵌套站点 id 在 `<holes>` 块的方括号里逐字出现(转义不碰 `/` 与 `#`)。
  1607. describe("GetWorkflowRun — nested hole ids", () => {
  1608. it("prints the nested site id verbatim", () => {
  1609. const text = getWorkflowRunToolEntry.formatModelContent!({
  1610. ...RUNNING_OUTPUT,
  1611. holes: [
  1612. {
  1613. siteId: "hole#1/hole#1/hole#2",
  1614. ordinal: 1,
  1615. name: "内层",
  1616. type: "Inner",
  1617. state: "waiting" as const,
  1618. since: NOW - 1_000,
  1619. },
  1620. ],
  1621. }) as string;
  1622. expect(text).toContain('[hole#1/hole#1/hole#2] "内层": Inner — waiting 1s');
  1623. });
  1624. });