zcodeProtocolV4WorkflowRunsHoles.test.ts 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479
  1. // 留白(typed holes)在 shared 协议层的三份契约(docs/dynamic-workflow/presentation.md「Holes on the timeline」、
  2. // docs/dynamic-workflow/transcript-and-notifications.md「The hole row's live state」):
  3. // 1. display 载荷的 `holes` / `fill` 字段与通知载荷的 `hole` 种类过 strict schema;
  4. // 2. reducer 把 `hole-reached` / `hole-filled` 归约成 run 的 `holes[]`、并同步 `phaseNames` 与对齐的 `phaseHoles`;
  5. // 3. sessions-index 的侧栏摘要把留白站标成 open / waiting,并交出「等待补全」的那个名字。
  6. import { describe, expect, it } from "vitest";
  7. import {
  8. WORKFLOW_RUNS_LIMITS,
  9. deriveSessionWorkflowPhases,
  10. reduceWorkflowRunsState,
  11. toolCallCreateWorkflowDisplaySchema,
  12. workflowNotificationMetaSchema,
  13. workflowRunsStateSchema,
  14. type WorkflowRunProgressEnvelope,
  15. type WorkflowRunState,
  16. type WorkflowRunsState,
  17. } from "../src/zcode-protocol-v4/index.js";
  18. import { deriveSessionWorkflowActivity } from "../src/zcode-protocol-v4/index.js";
  19. import { getZCodeToolFamilyForName, normalizeZCodeToolName } from "../src/tool-identity.js";
  20. const RUN_ID = "dwfrun-holes";
  21. function progressLog(runId = RUN_ID) {
  22. let sequence = -1;
  23. return function progress(
  24. eventType: string,
  25. payload: Record<string, unknown> = {},
  26. ): WorkflowRunProgressEnvelope {
  27. sequence += 1;
  28. return { runId, toolCallId: "tc-1", sequence, eventType, payload };
  29. };
  30. }
  31. function step(
  32. state: WorkflowRunsState | undefined,
  33. envelope: WorkflowRunProgressEnvelope,
  34. ): WorkflowRunsState {
  35. const next = reduceWorkflowRunsState(state, envelope);
  36. if (next === null) throw new Error(`事件本应产生变化却返回 null:${envelope.eventType}`);
  37. return next;
  38. }
  39. function reduceAll(
  40. envelopes: readonly WorkflowRunProgressEnvelope[],
  41. ): WorkflowRunsState | undefined {
  42. let state: WorkflowRunsState | undefined;
  43. for (const envelope of envelopes) state = reduceWorkflowRunsState(state, envelope) ?? state;
  44. return state;
  45. }
  46. const REACHED = {
  47. instance: { siteId: "hole#1", ordinal: 1 },
  48. name: "决定分组",
  49. prompt: "侦察结果如下",
  50. phaseName: "决定分组",
  51. type: "Plan",
  52. reachedAt: 1_700_000_000_000,
  53. };
  54. describe("display 载荷:holes 与 fill", () => {
  55. const graph = {
  56. steps: [{ id: "ask#1", kind: "ask", label: "scout", lane: "actor#1", phase: "phase#1" }],
  57. lanes: [{ id: "actor#1", name: "scout" }],
  58. participants: [{ id: "p1", phase: "phase#1", lane: "actor#1", steps: ["ask#1"] }],
  59. handoffs: [],
  60. phases: [
  61. { id: "phase#1", name: "探索" },
  62. { id: "hole#1", name: "决定分组" },
  63. { id: "phase#2", name: "冒烟测试", fill: "hole#1" },
  64. ],
  65. holes: [{ siteId: "hole#2", name: "评判", type: "Verdict", tail: true }],
  66. };
  67. it("phases[].fill、steps[].fill 与 holes[] 过 strict schema;旧载荷不带它们照常通过", () => {
  68. const display = {
  69. kind: "create_workflow",
  70. ok: true,
  71. errorCount: 0,
  72. diagnostics: [],
  73. causalityGraph: graph,
  74. };
  75. const parsed = toolCallCreateWorkflowDisplaySchema.safeParse(display);
  76. expect(parsed.success).toBe(true);
  77. expect(parsed.success && parsed.data.causalityGraph?.holes?.[0]?.tail).toBe(true);
  78. expect(parsed.success && parsed.data.causalityGraph?.phases?.[2]?.fill).toBe("hole#1");
  79. const withFillStep = {
  80. ...display,
  81. causalityGraph: { ...graph, steps: [{ ...graph.steps[0], fill: "hole#1" }] },
  82. };
  83. expect(toolCallCreateWorkflowDisplaySchema.safeParse(withFillStep).success).toBe(true);
  84. const { holes: _holes, ...legacyGraph } = graph;
  85. void _holes;
  86. expect(
  87. toolCallCreateWorkflowDisplaySchema.safeParse({ ...display, causalityGraph: legacyGraph })
  88. .success,
  89. ).toBe(true);
  90. });
  91. it("开着的留白自己的站点是 kind `hole`、车道 `main` 的 step(与 contracts 的 CREATE_WORKFLOW_STEP_KINDS 同步)", () => {
  92. const holeStep = { id: "hole#2", kind: "hole", label: "评判", lane: "main", phase: "hole#2" };
  93. const parsed = toolCallCreateWorkflowDisplaySchema.safeParse({
  94. kind: "create_workflow",
  95. ok: true,
  96. errorCount: 0,
  97. diagnostics: [],
  98. causalityGraph: { ...graph, steps: [...graph.steps, holeStep] },
  99. });
  100. expect(parsed.success).toBe(true);
  101. expect(parsed.success && parsed.data.causalityGraph?.steps[1]?.kind).toBe("hole");
  102. expect(
  103. toolCallCreateWorkflowDisplaySchema.safeParse({
  104. kind: "create_workflow",
  105. ok: true,
  106. errorCount: 0,
  107. diagnostics: [],
  108. causalityGraph: { ...graph, steps: [{ ...holeStep, kind: "gap" }] },
  109. }).success,
  110. ).toBe(false);
  111. });
  112. it("display.fill:补全行的站点 id 与名字过 strict;未知键与空名被拒;缺席照常通过", () => {
  113. const display = {
  114. kind: "create_workflow",
  115. ok: true,
  116. errorCount: 0,
  117. diagnostics: [],
  118. causalityGraph: graph,
  119. };
  120. const fill = {
  121. siteId: "hole#1",
  122. name: "决定分组",
  123. draftPath: ".zcode/workflow-drafts/a.dwf.ts",
  124. line: 12,
  125. };
  126. expect(toolCallCreateWorkflowDisplaySchema.safeParse({ ...display, fill }).success).toBe(true);
  127. expect(
  128. toolCallCreateWorkflowDisplaySchema.safeParse({
  129. ...display,
  130. fill: { siteId: "hole#1", name: "" },
  131. }).success,
  132. ).toBe(false);
  133. expect(
  134. toolCallCreateWorkflowDisplaySchema.safeParse({ ...display, fill: { ...fill, type: "Plan" } })
  135. .success,
  136. ).toBe(false);
  137. });
  138. it("holes 上界 32;hole 条目里的未知键被 strict 拒绝", () => {
  139. const many = Array.from({ length: 33 }, (_, i) => ({
  140. siteId: `hole#${i + 1}`,
  141. name: `h${i + 1}`,
  142. type: "T",
  143. }));
  144. expect(
  145. toolCallCreateWorkflowDisplaySchema.safeParse({
  146. kind: "create_workflow",
  147. ok: true,
  148. errorCount: 0,
  149. diagnostics: [],
  150. causalityGraph: { ...graph, holes: many },
  151. }).success,
  152. ).toBe(false);
  153. expect(
  154. toolCallCreateWorkflowDisplaySchema.safeParse({
  155. kind: "create_workflow",
  156. ok: true,
  157. errorCount: 0,
  158. diagnostics: [],
  159. causalityGraph: { ...graph, holes: [{ siteId: "hole#9", name: "x", type: "T", extra: 1 }] },
  160. }).success,
  161. ).toBe(false);
  162. });
  163. });
  164. describe("通知载荷:kind = hole", () => {
  165. it("最小与完整两形都通过;prompt 超 4000 被拒", () => {
  166. expect(
  167. workflowNotificationMetaSchema.safeParse({
  168. kind: "hole",
  169. siteId: "hole#1",
  170. ordinal: 1,
  171. name: "决定分组",
  172. type: "Plan",
  173. }).success,
  174. ).toBe(true);
  175. expect(
  176. workflowNotificationMetaSchema.safeParse({
  177. kind: "hole",
  178. siteId: "hole#1",
  179. ordinal: 1,
  180. name: "决定分组",
  181. type: "Plan",
  182. prompt: "p",
  183. draftPath: "/w/.zcode/workflow-drafts/flaky.dwf.ts",
  184. line: 12,
  185. before: "探索",
  186. after: "执行",
  187. reachedAt: 1,
  188. }).success,
  189. ).toBe(true);
  190. expect(
  191. workflowNotificationMetaSchema.safeParse({
  192. kind: "hole",
  193. siteId: "hole#1",
  194. ordinal: 1,
  195. name: "n",
  196. type: "T",
  197. prompt: "x".repeat(4001),
  198. }).success,
  199. ).toBe(false);
  200. });
  201. });
  202. describe("tool identity:FillWorkflowHole 属于 workflow family", () => {
  203. it("按名归一并落到 workflow family(确认窗按 family 选运行确认块)", () => {
  204. expect(normalizeZCodeToolName("fillworkflowhole")).toBe("FillWorkflowHole");
  205. expect(getZCodeToolFamilyForName("FillWorkflowHole")).toBe("workflow");
  206. });
  207. });
  208. describe("workflowRuns reducer · hole-reached / hole-filled", () => {
  209. it("hole-reached 建一条 waiting 记录:站点 id 去重,type / prompt / since 随载荷而来", () => {
  210. const progress = progressLog();
  211. const state = reduceAll([
  212. progress("run-started", { runId: RUN_ID, caps: {} }),
  213. progress("hole-reached", REACHED),
  214. ]);
  215. expect(state?.runs[0]?.holes).toEqual([
  216. {
  217. siteId: "hole#1",
  218. ordinal: 1,
  219. name: "决定分组",
  220. type: "Plan",
  221. prompt: "侦察结果如下",
  222. state: "waiting",
  223. since: REACHED.reachedAt,
  224. },
  225. ]);
  226. expect(workflowRunsStateSchema.safeParse(state).success).toBe(true);
  227. });
  228. it("prompt 截到 500 字(499 字加 …);再次到达不带 prompt / type 时沿用记过的", () => {
  229. const progress = progressLog();
  230. const long = "长".repeat(WORKFLOW_RUNS_LIMITS.maxHolePromptLength + 40);
  231. const base = reduceAll([
  232. progress("run-started", { runId: RUN_ID, caps: {} }),
  233. progress("hole-reached", { ...REACHED, prompt: long }),
  234. ]);
  235. const prompt = base?.runs[0]?.holes?.[0]?.prompt;
  236. expect(prompt).toHaveLength(WORKFLOW_RUNS_LIMITS.maxHolePromptLength);
  237. expect(prompt?.endsWith("…")).toBe(true);
  238. expect(workflowRunsStateSchema.safeParse(base).success).toBe(true);
  239. const again = step(
  240. base,
  241. progress("hole-reached", { instance: { siteId: "hole#1", ordinal: 2 }, name: "决定分组" }),
  242. );
  243. expect(again.runs[0]?.holes?.[0]).toMatchObject({ ordinal: 2, type: "Plan", prompt });
  244. });
  245. it("同一站点再次到达(循环里的第二个 ordinal)只更新序号,不加第二条;重放幂等", () => {
  246. const progress = progressLog();
  247. const base = reduceAll([
  248. progress("run-started", { runId: RUN_ID, caps: {} }),
  249. progress("hole-reached", REACHED),
  250. ]);
  251. const second = progress("hole-reached", {
  252. ...REACHED,
  253. instance: { siteId: "hole#1", ordinal: 2 },
  254. });
  255. const again = step(base, second);
  256. expect(again.runs[0]?.holes).toHaveLength(1);
  257. expect(again.runs[0]?.holes?.[0]?.ordinal).toBe(2);
  258. // 同一条事件(同 sequence)重放:逐字节无变化 → null。
  259. expect(reduceWorkflowRunsState(again, second)).toBeNull();
  260. });
  261. it("type 与 reachedAt 缺席(旧 CLI / 简载荷)时键缺席,记录仍在", () => {
  262. const progress = progressLog();
  263. const state = reduceAll([
  264. progress("run-started", { runId: RUN_ID, caps: {} }),
  265. progress("hole-reached", { instance: { siteId: "hole#1", ordinal: 1 }, name: "n" }),
  266. ]);
  267. expect(state?.runs[0]?.holes).toEqual([
  268. { siteId: "hole#1", ordinal: 1, name: "n", state: "waiting" },
  269. ]);
  270. });
  271. it("name 缺席即整条无从展示:只抬水位", () => {
  272. const progress = progressLog();
  273. const base = step(undefined, progress("run-started", { runId: RUN_ID, caps: {} }));
  274. const next = step(
  275. base,
  276. progress("hole-reached", { instance: { siteId: "hole#1", ordinal: 1 } }),
  277. );
  278. expect(next.runs[0]).not.toHaveProperty("holes");
  279. });
  280. it("holes 上界 32:超出的站点被拒并置 truncated", () => {
  281. const progress = progressLog();
  282. let state: WorkflowRunsState | undefined = step(
  283. undefined,
  284. progress("run-started", { runId: RUN_ID, caps: {} }),
  285. );
  286. for (let i = 1; i <= WORKFLOW_RUNS_LIMITS.maxHoles + 1; i += 1) {
  287. state =
  288. reduceWorkflowRunsState(
  289. state,
  290. progress("hole-reached", {
  291. instance: { siteId: `hole#${i}`, ordinal: 1 },
  292. name: `h${i}`,
  293. }),
  294. ) ?? state;
  295. }
  296. expect(state?.runs[0]?.holes).toHaveLength(WORKFLOW_RUNS_LIMITS.maxHoles);
  297. expect(state?.runs[0]?.truncated).toBe(true);
  298. });
  299. it("hole-filled 把记录翻成 filled(提示语丢掉),并换上补全后的 phaseNames 与对齐的 phaseHoles", () => {
  300. const progress = progressLog();
  301. const state = reduceAll([
  302. progress("run-started", { runId: RUN_ID, caps: {} }),
  303. progress("run-launched", {
  304. inputId: "in-1",
  305. phaseNames: ["探索", "决定分组", "执行", "评判"],
  306. holes: [1, 3],
  307. phaseAlongside: [[], [], [3], []],
  308. }),
  309. progress("hole-reached", REACHED),
  310. progress("hole-filled", {
  311. siteId: "hole#1",
  312. filledAt: 1_700_000_001_000,
  313. filledBy: "main",
  314. phaseNames: ["探索", "决定分组", "冒烟测试", "分组", "执行", "评判"],
  315. holes: [5],
  316. }),
  317. ]);
  318. const run = state?.runs[0];
  319. expect(run?.holes).toEqual([
  320. {
  321. siteId: "hole#1",
  322. ordinal: 1,
  323. name: "决定分组",
  324. type: "Plan",
  325. state: "filled",
  326. since: REACHED.reachedAt,
  327. filledAt: 1_700_000_001_000,
  328. filledBy: "main",
  329. },
  330. ]);
  331. expect(run?.phaseNames).toEqual(["探索", "决定分组", "冒烟测试", "分组", "执行", "评判"]);
  332. expect(run?.phaseHoles).toEqual([5]);
  333. // 「同时在跑」表按插入位置右移:原来 执行(2) ∥ 评判(3) → 执行(4) ∥ 评判(5)。
  334. expect(run?.phaseAlongside).toEqual([[], [], [], [], [5], []]);
  335. expect(workflowRunsStateSchema.safeParse(state).success).toBe(true);
  336. });
  337. it("run-launched 的 holes 下标:越界、非整数、重复一律丢;phaseNames 缺席时不建 phaseHoles", () => {
  338. const progress = progressLog();
  339. const state = reduceAll([
  340. progress("run-started", { runId: RUN_ID, caps: {} }),
  341. progress("run-launched", {
  342. inputId: "in-1",
  343. phaseNames: ["a", "b"],
  344. holes: [1, 1, 7, -1, 0.5],
  345. }),
  346. ]);
  347. expect(state?.runs[0]?.phaseHoles).toEqual([1]);
  348. const bare = reduceAll([
  349. progress("run-started", { runId: RUN_ID, caps: {} }),
  350. progress("run-launched", { inputId: "in-2", holes: [0] }),
  351. ]);
  352. expect(bare?.runs[0]).not.toHaveProperty("phaseHoles");
  353. });
  354. it("hole-filled 不认识的站点:不造 holes 记录,但阶段表照换;siteId 缺席只抬水位", () => {
  355. const progress = progressLog();
  356. const base = reduceAll([
  357. progress("run-started", { runId: RUN_ID, caps: {} }),
  358. progress("run-launched", { inputId: "in-1", phaseNames: ["a", "h"], holes: [1] }),
  359. ]);
  360. const filled = step(
  361. base,
  362. progress("hole-filled", { siteId: "hole#9", filledAt: 1, phaseNames: ["a", "h", "x"] }),
  363. );
  364. expect(filled.runs[0]).not.toHaveProperty("holes");
  365. expect(filled.runs[0]?.phaseNames).toEqual(["a", "h", "x"]);
  366. expect(filled.runs[0]).not.toHaveProperty("phaseHoles");
  367. // siteId 缺席:只抬水位——除了 lastEventSequence 之外什么都不变。
  368. const bare = step(filled, progress("hole-filled", { filledAt: 2 }));
  369. expect(bare.runs[0]).toEqual({
  370. ...filled.runs[0],
  371. lastEventSequence: bare.runs[0]?.lastEventSequence,
  372. });
  373. });
  374. it("新的一世(run-started)剥掉 waiting 记录、保留 filled;终态同样清掉 waiting", () => {
  375. const progress = progressLog();
  376. const state = reduceAll([
  377. progress("run-started", { runId: RUN_ID, caps: {} }),
  378. progress("hole-reached", REACHED),
  379. progress("hole-filled", { siteId: "hole#1", filledAt: 5, phaseNames: ["决定分组"] }),
  380. progress("hole-reached", {
  381. instance: { siteId: "hole#2", ordinal: 1 },
  382. name: "评判",
  383. type: "Verdict",
  384. }),
  385. ]);
  386. expect(state?.runs[0]?.holes?.map((hole) => hole.state)).toEqual(["filled", "waiting"]);
  387. const settled = step(state, progress("run-settled", { status: "stopped", stopReason: "user" }));
  388. expect(settled.runs[0]?.holes?.map((hole) => hole.siteId)).toEqual(["hole#1"]);
  389. const resumed = step(settled, progress("run-started", { runId: RUN_ID, caps: {} }));
  390. expect(resumed.runs[0]?.holes?.map((hole) => hole.siteId)).toEqual(["hole#1"]);
  391. const reReached = step(
  392. resumed,
  393. progress("hole-reached", { instance: { siteId: "hole#2", ordinal: 1 }, name: "评判" }),
  394. );
  395. expect(reReached.runs[0]?.holes?.map((hole) => hole.state)).toEqual(["filled", "waiting"]);
  396. });
  397. });
  398. describe("sessions-index 侧栏摘要 · 留白站", () => {
  399. function run(overrides: Partial<WorkflowRunState> & { runId: string }): WorkflowRunState {
  400. return {
  401. status: "running",
  402. usage: { spentTokens: 0, nodesUsed: 0 },
  403. actors: [],
  404. nodes: [],
  405. lastEventSequence: 0,
  406. ...overrides,
  407. };
  408. }
  409. it("phaseHoles 标出的站带 hole: open;run.holes 里 waiting 的那一站带 hole: waiting", () => {
  410. const phases = deriveSessionWorkflowPhases(
  411. run({
  412. runId: "r1",
  413. phaseNames: ["探索", "决定分组", "执行", "评判"],
  414. phaseHoles: [1, 3],
  415. phases: [{ name: "探索", rounds: 1 }],
  416. currentPhase: "探索",
  417. holes: [{ siteId: "hole#1", ordinal: 1, name: "决定分组", state: "waiting" }],
  418. }),
  419. );
  420. expect(phases.map((phase) => phase.hole)).toEqual([undefined, "waiting", undefined, "open"]);
  421. expect(phases[1]?.status).toBe("pending");
  422. });
  423. it("补全后的留白不再是留白:phaseHoles 不再指向它,摘要行也没有 hole 键", () => {
  424. const phases = deriveSessionWorkflowPhases(
  425. run({
  426. runId: "r1",
  427. phaseNames: ["探索", "决定分组", "冒烟测试", "执行"],
  428. phaseHoles: [],
  429. holes: [{ siteId: "hole#1", ordinal: 1, name: "决定分组", state: "filled", filledAt: 1 }],
  430. }),
  431. );
  432. expect(phases.every((phase) => phase.hole === undefined)).toBe(true);
  433. });
  434. it("运行摘要交出 waitingHole:正在等补全的留白名(侧栏写「{name} · 等待补全」)", () => {
  435. const activity = deriveSessionWorkflowActivity({
  436. workflowRuns: {
  437. revision: 1,
  438. runs: [
  439. run({
  440. runId: "r1",
  441. phaseNames: ["探索", "决定分组"],
  442. phaseHoles: [1],
  443. holes: [{ siteId: "hole#1", ordinal: 1, name: "决定分组", state: "waiting" }],
  444. }),
  445. run({ runId: "r2", phaseNames: ["a"] }),
  446. ],
  447. },
  448. backgroundWorks: [],
  449. });
  450. expect(activity?.runs[0]?.waitingHole).toBe("决定分组");
  451. expect(activity?.runs[1]).not.toHaveProperty("waitingHole");
  452. });
  453. });