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

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