workflowParticipantModel.test.ts 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992
  1. import { describe, expect, it } from "vitest";
  2. import type { WorkflowRunState } from "@zcode/shared/zcode-protocol-v4";
  3. import {
  4. collapseStatuses,
  5. handoffsAround,
  6. handoffsWithin,
  7. instanceCardId,
  8. liveParticipantView,
  9. participantAlsoIn,
  10. participantById,
  11. participantCounts,
  12. participantRepeats,
  13. participantStatus,
  14. } from "../src/components/workflow-graph/participant-model.js";
  15. import {
  16. phasesOf,
  17. runHasPhaseVocabulary,
  18. } from "../src/components/workflow-graph/instance-phases.js";
  19. import type {
  20. StepRunStatus,
  21. WorkflowCausalityGraphData,
  22. WorkflowParticipantData,
  23. WorkflowStepData,
  24. } from "../src/components/workflow-graph/types.js";
  25. /**
  26. * 参与者层的纯选择器(docs/dynamic-workflow/presentation.md)。载荷的 `participants`
  27. * 已是交接序、`handoffs` 已归约;这里只做分桶、计数、状态折叠,外加实时视图(`many` 卡
  28. * 按实例拆分、成员卡按 ordinal 收窄;追记 2026-09-04:单卡绑定唯一实例、多实例时同样拆分)。
  29. * 隐式阶段的合成在 workflowPhaseModel 套件。
  30. */
  31. function step(
  32. overrides: Partial<WorkflowStepData> & { id: string; lane: string; phase: string },
  33. ): WorkflowStepData {
  34. return { kind: "ask", label: overrides.id, ...overrides };
  35. }
  36. // fixer 在 attempt 与 gate 两个阶段都出场;工作区只在 attempt;裁判只在 gate。
  37. // attempt 内 fixer → workspace → fixer 一个环(回边 `back`)。
  38. const GRAPH: WorkflowCausalityGraphData = {
  39. exits: ["phase#2"],
  40. handoffs: [
  41. { from: "phase#1:actor#1", to: "phase#1:workspace", types: ["Patch"] },
  42. { back: true, from: "phase#1:workspace", to: "phase#1:actor#1" },
  43. { from: "phase#2:actor#1", to: "phase#2:actor#2", types: ["Report", "Bench"] },
  44. ],
  45. lanes: [
  46. { id: "actor#1", line: 3, name: "fixer" },
  47. { id: "actor#2", line: 4, name: "referee" },
  48. { id: "workspace" },
  49. ],
  50. participants: [
  51. { id: "phase#1:actor#1", lane: "actor#1", phase: "phase#1", steps: ["ask#1", "ask#2"] },
  52. {
  53. id: "phase#1:workspace",
  54. lane: "workspace",
  55. phase: "phase#1",
  56. steps: ["world-read#1", "world-read#2", "world-read#3"],
  57. },
  58. { id: "phase#2:actor#1", lane: "actor#1", phase: "phase#2", steps: ["ask#3"] },
  59. { id: "phase#2:actor#2", lane: "actor#2", phase: "phase#2", steps: ["ask#4"] },
  60. ],
  61. phaseEdges: [{ from: "phase#1", to: "phase#2" }],
  62. phases: [
  63. { id: "phase#1", line: 2, name: "attempt" },
  64. { id: "phase#2", line: 9, name: "gate" },
  65. ],
  66. sink: ["ask#4"],
  67. steps: [
  68. step({ id: "ask#1", lane: "actor#1", phase: "phase#1" }),
  69. step({ id: "ask#2", lane: "actor#1", phase: "phase#1", repeat: "serial" }),
  70. step({ id: "world-read#1", kind: "world-read", lane: "workspace", phase: "phase#1" }),
  71. step({ id: "world-read#2", kind: "world-read", lane: "workspace", phase: "phase#1" }),
  72. step({ id: "world-read#3", kind: "world-read", lane: "workspace", phase: "phase#1" }),
  73. step({ id: "ask#3", lane: "actor#1", phase: "phase#2" }),
  74. step({ id: "ask#4", lane: "actor#2", phase: "phase#2" }),
  75. ],
  76. };
  77. const by = (id: string): WorkflowParticipantData => participantById(GRAPH, id)!;
  78. describe("participantCounts", () => {
  79. it("counts asks for a subagent card and reads for the workspace card — never both", () => {
  80. expect(participantCounts(GRAPH, by("phase#1:actor#1"))).toEqual({ asks: 2, reads: 0 });
  81. expect(participantCounts(GRAPH, by("phase#1:workspace"))).toEqual({ asks: 0, reads: 3 });
  82. expect(participantCounts(GRAPH, by("phase#2:actor#2"))).toEqual({ asks: 1, reads: 0 });
  83. });
  84. it("counts an unknown step id as an ask rather than dropping it", () => {
  85. // 载荷不会出这种事;真出了,卡上的数字与 steps 长度对得上比对不上好。
  86. const orphan: WorkflowParticipantData = {
  87. id: "phase#2:actor#9",
  88. lane: "actor#9",
  89. phase: "phase#2",
  90. steps: ["ask#404"],
  91. };
  92. expect(participantCounts(GRAPH, orphan)).toEqual({ asks: 1, reads: 0 });
  93. });
  94. });
  95. describe("participantRepeats", () => {
  96. it("flags the card when any of its steps carries `repeat` — the self-loop's only trace", () => {
  97. expect(participantRepeats(GRAPH, by("phase#1:actor#1"))).toBe(true);
  98. expect(participantRepeats(GRAPH, by("phase#1:workspace"))).toBe(false);
  99. expect(participantRepeats(GRAPH, by("phase#2:actor#1"))).toBe(false);
  100. });
  101. });
  102. describe("handoffsAround / handoffsWithin", () => {
  103. it("splits a card's hand-offs into incoming and outgoing, verbatim edges", () => {
  104. const around = handoffsAround(GRAPH, "phase#1:actor#1");
  105. expect(around.outgoing).toEqual([
  106. { from: "phase#1:actor#1", to: "phase#1:workspace", types: ["Patch"] },
  107. ]);
  108. expect(around.incoming).toEqual([
  109. { back: true, from: "phase#1:workspace", to: "phase#1:actor#1" },
  110. ]);
  111. // 只收交接、不看阶段边:gate 里的 fixer 没有人交给它。
  112. expect(handoffsAround(GRAPH, "phase#2:actor#1")).toEqual({
  113. incoming: [],
  114. outgoing: [{ from: "phase#2:actor#1", to: "phase#2:actor#2", types: ["Report", "Bench"] }],
  115. });
  116. expect(handoffsAround(GRAPH, "nobody")).toEqual({ incoming: [], outgoing: [] });
  117. });
  118. it("keeps only the edges with both ends inside the given set", () => {
  119. const attempt = new Set(["phase#1:actor#1", "phase#1:workspace"]);
  120. expect(handoffsWithin(GRAPH, attempt)).toHaveLength(2);
  121. // 一端在集合外 → 不算:交接严格阶段内,这条边不会出现在任何一个模块里。
  122. const mixed = new Set(["phase#1:actor#1", "phase#2:actor#2"]);
  123. expect(handoffsWithin(GRAPH, mixed)).toEqual([]);
  124. expect(handoffsWithin(GRAPH, new Set())).toEqual([]);
  125. });
  126. });
  127. describe("participantAlsoIn", () => {
  128. it("lists the OTHER phases the same lane appears in, in phase-table order", () => {
  129. expect(participantAlsoIn(GRAPH, by("phase#1:actor#1")).map((phase) => phase.id)).toEqual([
  130. "phase#2",
  131. ]);
  132. expect(participantAlsoIn(GRAPH, by("phase#2:actor#1")).map((phase) => phase.id)).toEqual([
  133. "phase#1",
  134. ]);
  135. expect(participantAlsoIn(GRAPH, by("phase#1:workspace"))).toEqual([]);
  136. expect(participantAlsoIn(GRAPH, by("phase#2:actor#2"))).toEqual([]);
  137. });
  138. it("dedupes when a lane has several cards in one other phase (member cards)", () => {
  139. const graph: WorkflowCausalityGraphData = {
  140. ...GRAPH,
  141. participants: [
  142. ...GRAPH.participants,
  143. {
  144. id: "phase#2:actor#2[0]",
  145. lane: "actor#2",
  146. member: { index: 0, of: 2 },
  147. phase: "phase#2",
  148. steps: ["ask#4"],
  149. },
  150. {
  151. id: "phase#2:actor#2[1]",
  152. lane: "actor#2",
  153. member: { index: 1, of: 2 },
  154. phase: "phase#2",
  155. steps: ["ask#4"],
  156. },
  157. { id: "phase#1:actor#2", lane: "actor#2", phase: "phase#1", steps: ["ask#1"] },
  158. ],
  159. };
  160. expect(
  161. participantAlsoIn(graph, participantById(graph, "phase#1:actor#2")!).map((p) => p.id),
  162. ).toEqual(["phase#2"]);
  163. });
  164. });
  165. describe("collapseStatuses", () => {
  166. const collapse = (...values: StepRunStatus[]) => {
  167. const statuses: Record<string, StepRunStatus> = {};
  168. values.forEach((value, index) => {
  169. statuses[`s${index}`] = value;
  170. });
  171. return collapseStatuses(Object.keys(statuses), statuses);
  172. };
  173. it("reports running first — the reader's first question is whether it still moves", () => {
  174. expect(collapse("failed", "running")).toBe("running");
  175. expect(collapse("done", "running", "pending")).toBe("running");
  176. });
  177. it("reports failed once everything settled and something failed", () => {
  178. expect(collapse("done", "failed")).toBe("failed");
  179. });
  180. it("reports done only when every member settled cleanly", () => {
  181. expect(collapse("done", "done")).toBe("done");
  182. });
  183. it("reads a set with both settled and queued members as running: started, not finished", () => {
  184. // 追记「缺席不是状态」:旧规则把做到一半读成「还没开始」,与把缺席读成 pending 是同一个混淆。
  185. expect(collapse("done", "pending")).toBe("running");
  186. expect(collapse("pending", "failed")).toBe("running");
  187. });
  188. it("is pending only when every member is queued", () => {
  189. expect(collapse("pending")).toBe("pending");
  190. expect(collapse("pending", "pending")).toBe("pending");
  191. });
  192. it("is undefined in the static view and when none of the ids were observed", () => {
  193. expect(collapseStatuses(["a", "b"], undefined)).toBeUndefined();
  194. expect(collapseStatuses(["a", "b"], {})).toBeUndefined();
  195. expect(collapseStatuses([], { a: "running" })).toBeUndefined();
  196. // 只看自己名下的 id:别人的 running 不点亮这张卡。
  197. expect(collapseStatuses(["a"], { a: "done", b: "running" })).toBe("done");
  198. // 没有条目的 id 不参与:控制流没走的分支站点不把已结算的兄弟拖成 pending。
  199. expect(collapseStatuses(["a", "b"], { a: "done" })).toBe("done");
  200. expect(collapseStatuses(["a", "b"], { b: "failed" })).toBe("failed");
  201. });
  202. });
  203. describe("participantStatus", () => {
  204. it("prefers the live view's per-instance override, else folds the card's steps", () => {
  205. const statuses: Record<string, StepRunStatus> = { "ask#1": "done", "ask#2": "running" };
  206. expect(participantStatus(by("phase#1:actor#1"), statuses)).toBe("running");
  207. expect(
  208. participantStatus(by("phase#1:actor#1"), statuses, { "phase#1:actor#1": "failed" }),
  209. ).toBe("failed");
  210. // 覆盖表里没有这张卡 → 退回 step 折叠。
  211. expect(participantStatus(by("phase#1:actor#1"), statuses, { other: "failed" })).toBe("running");
  212. // 没有任何观察 → 静态。
  213. expect(participantStatus(by("phase#2:actor#2"), statuses)).toBeUndefined();
  214. expect(participantStatus(by("phase#2:actor#2"), undefined)).toBeUndefined();
  215. });
  216. });
  217. describe("instanceCardId", () => {
  218. it("suffixes the participant id with `@ordinal`", () => {
  219. expect(instanceCardId("phase#2:actor#3", 4)).toBe("phase#2:actor#3@4");
  220. });
  221. });
  222. describe("liveParticipantView", () => {
  223. // gate 里多一张 `many` 卡(judge,lane actor#3)与两张 referee 成员卡;judge 收 fixer 的交接。
  224. const LIVE_GRAPH: WorkflowCausalityGraphData = {
  225. ...GRAPH,
  226. handoffs: [
  227. ...GRAPH.handoffs,
  228. { from: "phase#2:actor#1", to: "phase#2:actor#3", types: ["Draft"] },
  229. { from: "phase#2:actor#3", to: "phase#2:actor#2[0]" },
  230. ],
  231. lanes: [...GRAPH.lanes, { id: "actor#3", line: 5 }],
  232. participants: [
  233. ...GRAPH.participants.slice(0, 3),
  234. {
  235. id: "phase#2:actor#2[0]",
  236. lane: "actor#2",
  237. member: { index: 0, of: 2 },
  238. phase: "phase#2",
  239. steps: ["ask#4"],
  240. },
  241. {
  242. id: "phase#2:actor#2[1]",
  243. lane: "actor#2",
  244. member: { index: 1, of: 2 },
  245. phase: "phase#2",
  246. steps: ["ask#4"],
  247. },
  248. {
  249. id: "phase#2:actor#3",
  250. lane: "actor#3",
  251. many: true,
  252. phase: "phase#2",
  253. steps: ["ask#5~actor#3"],
  254. },
  255. ],
  256. steps: [
  257. ...GRAPH.steps,
  258. // may-set 展开的拷贝:节点报的是站点 id `ask#5`,关联键走 `source`。
  259. step({
  260. id: "ask#5~actor#3",
  261. lane: "actor#3",
  262. lanes: ["actor#3", "actor#1"],
  263. phase: "phase#2",
  264. source: "ask#5",
  265. }),
  266. ],
  267. };
  268. function runWith(
  269. actors: WorkflowRunState["actors"],
  270. nodes: WorkflowRunState["nodes"],
  271. ): WorkflowRunState {
  272. return {
  273. actors,
  274. usage: { spentTokens: 0, nodesUsed: nodes.length },
  275. lastEventSequence: nodes.length,
  276. nodes,
  277. runId: "dwfrun-1",
  278. status: "running",
  279. };
  280. }
  281. it("is the identity without a run — same graph reference, nothing overridden", () => {
  282. const view = liveParticipantView(LIVE_GRAPH, undefined);
  283. expect(view.graph).toBe(LIVE_GRAPH);
  284. expect(view.instances).toEqual({});
  285. expect(view.participantStatuses).toEqual({});
  286. });
  287. it("splits a `many` card into one `${id}@${ordinal}` card per actor instance, copying its hand-offs", () => {
  288. const run = runWith(
  289. // 乱序给出:实例卡按 ordinal 排。
  290. [
  291. { ordinal: 2, siteId: "actor#3", status: "running" },
  292. { name: "judge-1", ordinal: 1, siteId: "actor#3", status: "waiting" },
  293. ],
  294. [
  295. {
  296. actorOrdinal: 1,
  297. actorSiteId: "actor#3",
  298. ordinal: 1,
  299. phase: "settled",
  300. outcome: "ok",
  301. siteId: "ask#5",
  302. },
  303. {
  304. actorOrdinal: 2,
  305. actorSiteId: "actor#3",
  306. ordinal: 2,
  307. phase: "executing",
  308. siteId: "ask#5",
  309. },
  310. // 别的车道上的同站点实例与这张卡无关。
  311. {
  312. actorOrdinal: 1,
  313. actorSiteId: "actor#1",
  314. ordinal: 3,
  315. phase: "settled",
  316. outcome: "failed",
  317. siteId: "ask#5",
  318. },
  319. ],
  320. );
  321. const view = liveParticipantView(LIVE_GRAPH, run);
  322. expect(view.graph).not.toBe(LIVE_GRAPH);
  323. expect(view.graph.participants.map((participant) => participant.id)).toEqual([
  324. "phase#1:actor#1",
  325. "phase#1:workspace",
  326. "phase#2:actor#1",
  327. "phase#2:actor#2[0]",
  328. "phase#2:actor#2[1]",
  329. "phase#2:actor#3@1",
  330. "phase#2:actor#3@2",
  331. ]);
  332. const split = view.graph.participants.filter((participant) => participant.id.includes("@"));
  333. // 实例卡不再是 `many`:它就是一个具体实例。
  334. expect(split.every((participant) => participant.many === undefined)).toBe(true);
  335. expect(split[0]).toMatchObject({ lane: "actor#3", phase: "phase#2", steps: ["ask#5~actor#3"] });
  336. expect(view.participantStatuses["phase#2:actor#3@1"]).toBe("done");
  337. expect(view.participantStatuses["phase#2:actor#3@2"]).toBe("running");
  338. expect(view.instances).toEqual({
  339. "phase#2:actor#3@1": { name: "judge-1", ordinal: 1, participant: "phase#2:actor#3" },
  340. "phase#2:actor#3@2": { ordinal: 2, participant: "phase#2:actor#3" },
  341. });
  342. // 进出这张卡的交接各复制到每张实例卡;其他边原样。
  343. expect(view.graph.handoffs).toEqual([
  344. ...GRAPH.handoffs,
  345. { from: "phase#2:actor#1", to: "phase#2:actor#3@1", types: ["Draft"] },
  346. { from: "phase#2:actor#1", to: "phase#2:actor#3@2", types: ["Draft"] },
  347. { from: "phase#2:actor#3@1", to: "phase#2:actor#2[0]" },
  348. { from: "phase#2:actor#3@2", to: "phase#2:actor#2[0]" },
  349. ]);
  350. // 图的其他部分不动。
  351. expect(view.graph.steps).toBe(LIVE_GRAPH.steps);
  352. expect(view.graph.phases).toBe(LIVE_GRAPH.phases);
  353. });
  354. it("keeps the `many` card whole while no instance has appeared yet", () => {
  355. const run = runWith(
  356. [{ ordinal: 1, siteId: "actor#1", status: "running" }],
  357. [
  358. {
  359. actorOrdinal: 1,
  360. actorSiteId: "actor#1",
  361. ordinal: 1,
  362. phase: "executing",
  363. siteId: "ask#1",
  364. },
  365. ],
  366. );
  367. const view = liveParticipantView(LIVE_GRAPH, run);
  368. // 没有拆分 → 图引用不变(memo 友好);`many` 卡的状态留给 step 折叠,也不绑定任何实例。
  369. expect(view.graph).toBe(LIVE_GRAPH);
  370. expect("phase#2:actor#3" in view.instances).toBe(false);
  371. expect("phase#2:actor#3" in view.participantStatuses).toBe(false);
  372. });
  373. it("narrows a member card to the index-th actor of its lane by ordinal; a missing actor reads pending", () => {
  374. const run = runWith(
  375. // ordinal 7 先到、3 后到:第 0 个成员是 ordinal 3,第 1 个是 7。
  376. [
  377. { name: "referee-b", ordinal: 7, siteId: "actor#2", status: "waiting" },
  378. { ordinal: 3, siteId: "actor#2", status: "running" },
  379. ],
  380. [
  381. {
  382. actorOrdinal: 3,
  383. actorSiteId: "actor#2",
  384. ordinal: 1,
  385. phase: "settled",
  386. outcome: "failed",
  387. siteId: "ask#4",
  388. },
  389. {
  390. actorOrdinal: 3,
  391. actorSiteId: "actor#2",
  392. ordinal: 2,
  393. phase: "executing",
  394. siteId: "ask#4",
  395. },
  396. {
  397. actorOrdinal: 7,
  398. actorSiteId: "actor#2",
  399. ordinal: 4,
  400. phase: "settled",
  401. outcome: "ok",
  402. siteId: "ask#4",
  403. },
  404. ],
  405. );
  406. const view = liveParticipantView(LIVE_GRAPH, run);
  407. // 成员 0 = ordinal 3:failed + running → running(running 优先);成员 1 = ordinal 7:done。
  408. expect(view.participantStatuses["phase#2:actor#2[0]"]).toBe("running");
  409. expect(view.participantStatuses["phase#2:actor#2[1]"]).toBe("done");
  410. // 成员卡不拆分:图引用不变,且非成员卡没有覆盖值。
  411. expect(view.graph).toBe(LIVE_GRAPH);
  412. expect("phase#2:actor#1" in view.participantStatuses).toBe(false);
  413. // 成员卡绑定各自的实例(追记 2026-09-04):名字从实例来、id 不变,`bound` 标记它不是拆分卡。
  414. expect(view.instances).toEqual({
  415. "phase#2:actor#2[0]": { bound: true, ordinal: 3, participant: "phase#2:actor#2[0]" },
  416. "phase#2:actor#2[1]": {
  417. bound: true,
  418. name: "referee-b",
  419. ordinal: 7,
  420. participant: "phase#2:actor#2[1]",
  421. },
  422. });
  423. // 只有一个实例:第 1 个成员的 actor 还没出现 → pending,而不是缺席。
  424. const oneActor = liveParticipantView(
  425. LIVE_GRAPH,
  426. runWith(
  427. [{ ordinal: 3, siteId: "actor#2", status: "waiting" }],
  428. [
  429. {
  430. actorOrdinal: 3,
  431. actorSiteId: "actor#2",
  432. ordinal: 1,
  433. phase: "settled",
  434. outcome: "ok",
  435. siteId: "ask#4",
  436. },
  437. ],
  438. ),
  439. );
  440. expect(oneActor.participantStatuses["phase#2:actor#2[0]"]).toBe("done");
  441. expect(oneActor.participantStatuses["phase#2:actor#2[1]"]).toBe("pending");
  442. expect("phase#2:actor#2[1]" in oneActor.instances).toBe(false);
  443. // 实例数多于 `of`:多出的实例不出卡——静态基数是作者写下的字面量,这是成员卡与单卡的差别。
  444. const surplus = liveParticipantView(
  445. LIVE_GRAPH,
  446. runWith(
  447. [3, 7, 9].map((ordinal) => ({ ordinal, siteId: "actor#2", status: "waiting" as const })),
  448. [],
  449. ),
  450. );
  451. expect(surplus.graph).toBe(LIVE_GRAPH);
  452. expect(Object.keys(surplus.instances)).toEqual(["phase#2:actor#2[0]", "phase#2:actor#2[1]"]);
  453. // 实例在场但一个节点都没有 → 聚合空集 = pending。
  454. const idle = liveParticipantView(
  455. LIVE_GRAPH,
  456. runWith([{ ordinal: 3, siteId: "actor#2", status: "waiting" }], []),
  457. );
  458. expect(idle.participantStatuses["phase#2:actor#2[0]"]).toBe("pending");
  459. });
  460. it("binds a single card to its one actor: runtime name carried, id and graph untouched", () => {
  461. const run = runWith(
  462. [{ name: "修复员", ordinal: 4, siteId: "actor#1", status: "running" }],
  463. [
  464. {
  465. actorOrdinal: 4,
  466. actorSiteId: "actor#1",
  467. ordinal: 1,
  468. phase: "executing",
  469. siteId: "ask#1",
  470. },
  471. ],
  472. );
  473. const view = liveParticipantView(LIVE_GRAPH, run);
  474. // 不拆分 → 图引用不变。
  475. expect(view.graph).toBe(LIVE_GRAPH);
  476. // fixer 在两个阶段各有一张单卡:同一个实例绑到每一张上(同一个子代理的两次出场)。
  477. expect(view.instances["phase#1:actor#1"]).toEqual({
  478. bound: true,
  479. name: "修复员",
  480. ordinal: 4,
  481. participant: "phase#1:actor#1",
  482. });
  483. expect(view.instances["phase#2:actor#1"]).toEqual({
  484. bound: true,
  485. name: "修复员",
  486. ordinal: 4,
  487. participant: "phase#2:actor#1",
  488. });
  489. // 绑定不改状态口径:单卡仍由 step 折叠,没有覆盖值。
  490. expect("phase#1:actor#1" in view.participantStatuses).toBe(false);
  491. expect("phase#2:actor#1" in view.participantStatuses).toBe(false);
  492. });
  493. it("splits a single card like `many` once two actors have appeared on its lane", () => {
  494. const run = runWith(
  495. // 乱序给出:实例卡按 ordinal 排。
  496. [
  497. { name: "fixer-b", ordinal: 6, siteId: "actor#1", status: "waiting" },
  498. { name: "fixer-a", ordinal: 2, siteId: "actor#1", status: "running" },
  499. ],
  500. [
  501. {
  502. actorOrdinal: 2,
  503. actorSiteId: "actor#1",
  504. ordinal: 1,
  505. phase: "executing",
  506. siteId: "ask#1",
  507. },
  508. {
  509. actorOrdinal: 6,
  510. actorSiteId: "actor#1",
  511. ordinal: 2,
  512. phase: "settled",
  513. outcome: "ok",
  514. siteId: "ask#1",
  515. },
  516. {
  517. actorOrdinal: 6,
  518. actorSiteId: "actor#1",
  519. ordinal: 3,
  520. phase: "settled",
  521. outcome: "failed",
  522. siteId: "ask#3",
  523. },
  524. ],
  525. );
  526. const view = liveParticipantView(LIVE_GRAPH, run);
  527. expect(view.graph).not.toBe(LIVE_GRAPH);
  528. expect(view.graph.participants.map((participant) => participant.id)).toEqual([
  529. "phase#1:actor#1@2",
  530. "phase#1:actor#1@6",
  531. "phase#1:workspace",
  532. "phase#2:actor#1@2",
  533. "phase#2:actor#1@6",
  534. "phase#2:actor#2[0]",
  535. "phase#2:actor#2[1]",
  536. "phase#2:actor#3",
  537. ]);
  538. // 拆分卡不带 `bound`:它就是那个实例,标签念 `#ordinal`。
  539. expect(view.instances["phase#1:actor#1@2"]).toEqual({
  540. name: "fixer-a",
  541. ordinal: 2,
  542. participant: "phase#1:actor#1",
  543. });
  544. expect(view.instances["phase#2:actor#1@6"]).toEqual({
  545. name: "fixer-b",
  546. ordinal: 6,
  547. participant: "phase#2:actor#1",
  548. });
  549. // 状态按实例收窄(与 `many` 拆分同一条规则)。
  550. expect(view.participantStatuses).toMatchObject({
  551. "phase#1:actor#1@2": "running",
  552. "phase#1:actor#1@6": "done",
  553. "phase#2:actor#1@2": "pending",
  554. "phase#2:actor#1@6": "failed",
  555. });
  556. // 进出原卡的交接各复制到每张实例卡(attempt 里的环两端、gate 里 fixer 发出的两条);其他边原样。
  557. expect(view.graph.handoffs).toEqual([
  558. { from: "phase#1:actor#1@2", to: "phase#1:workspace", types: ["Patch"] },
  559. { from: "phase#1:actor#1@6", to: "phase#1:workspace", types: ["Patch"] },
  560. { back: true, from: "phase#1:workspace", to: "phase#1:actor#1@2" },
  561. { back: true, from: "phase#1:workspace", to: "phase#1:actor#1@6" },
  562. { from: "phase#2:actor#1@2", to: "phase#2:actor#2", types: ["Report", "Bench"] },
  563. { from: "phase#2:actor#1@6", to: "phase#2:actor#2", types: ["Report", "Bench"] },
  564. { from: "phase#2:actor#1@2", to: "phase#2:actor#3", types: ["Draft"] },
  565. { from: "phase#2:actor#1@6", to: "phase#2:actor#3", types: ["Draft"] },
  566. { from: "phase#2:actor#3", to: "phase#2:actor#2[0]" },
  567. ]);
  568. });
  569. // ——— 追记 2026-09-09「运行时实例带阶段坐标」:绑定从「按车道」变成「按 (站点, 阶段)」———
  570. /**
  571. * 本 bug 的形状:一个 `runBatch(p)` 从 5 个阶段各调一次,每次并行派 20 个子代理。静态是对的
  572. * ——一条车道 `actor#1`、一个 ask 站点 `ask#1` 被 5 个阶段认领,于是 5 份拷贝、5 张 `many` 卡。
  573. */
  574. const FAN_OUT_PHASES = ["调研", "起草", "校对", "复核", "收尾"];
  575. const FAN_OUT: WorkflowCausalityGraphData = {
  576. exits: ["phase#5"],
  577. handoffs: [],
  578. lanes: [{ id: "actor#1", name: "worker" }],
  579. participants: FAN_OUT_PHASES.map((_, i) => ({
  580. id: `phase#${i + 1}:actor#1`,
  581. lane: "actor#1",
  582. many: true,
  583. phase: `phase#${i + 1}`,
  584. steps: [`ask#1~phase#${i + 1}`],
  585. })),
  586. phaseEdges: FAN_OUT_PHASES.slice(1).map((_, i) => ({
  587. from: `phase#${i + 1}`,
  588. to: `phase#${i + 2}`,
  589. })),
  590. phases: FAN_OUT_PHASES.map((name, i) => ({ id: `phase#${i + 1}`, name })),
  591. steps: FAN_OUT_PHASES.map((_, i) =>
  592. step({
  593. id: `ask#1~phase#${i + 1}`,
  594. lane: "actor#1",
  595. phase: `phase#${i + 1}`,
  596. source: "ask#1",
  597. }),
  598. ),
  599. };
  600. /** 100 个实例、100 个节点,全在同一条车道与同一个站点上,只有出生阶段不同。 */
  601. function fanOutRun(stamped: boolean): WorkflowRunState {
  602. const stamp = (name: string) => (stamped ? { phaseName: name } : {});
  603. return runWith(
  604. FAN_OUT_PHASES.flatMap((name, i) =>
  605. Array.from({ length: 20 }, (_, k) => ({
  606. ordinal: i * 20 + k + 1,
  607. siteId: "actor#1",
  608. status: "waiting" as const,
  609. ...stamp(name),
  610. })),
  611. ),
  612. FAN_OUT_PHASES.flatMap((name, i) =>
  613. Array.from({ length: 20 }, (_, k) => ({
  614. actorOrdinal: i * 20 + k + 1,
  615. actorSiteId: "actor#1",
  616. ordinal: i * 20 + k + 1,
  617. outcome: "ok" as const,
  618. phase: "settled" as const,
  619. siteId: "ask#1",
  620. ...stamp(name),
  621. })),
  622. ),
  623. );
  624. }
  625. it("splits a re-entered site by the instance's birth phase: each card lists its own 20, not all 100", () => {
  626. const view = liveParticipantView(FAN_OUT, fanOutRun(true));
  627. expect(view.graph.participants).toHaveLength(100);
  628. FAN_OUT_PHASES.forEach((_, i) => {
  629. const cards = view.graph.participants.filter(
  630. (participant) => participant.phase === `phase#${i + 1}`,
  631. );
  632. expect(cards.map((participant) => participant.id)).toEqual(
  633. Array.from({ length: 20 }, (_, k) => `phase#${i + 1}:actor#1@${i * 20 + k + 1}`),
  634. );
  635. });
  636. // 状态同样按实例收窄:每张卡只折自己那一个节点。
  637. expect(view.participantStatuses["phase#3:actor#1@41"]).toBe("done");
  638. expect(view.instances["phase#3:actor#1@41"]).toEqual({
  639. ordinal: 41,
  640. participant: "phase#3:actor#1",
  641. });
  642. });
  643. it("keeps the lane-wide binding when no instance carries a stamp — the legacy contract", () => {
  644. // 旧 CLI / 旧 run / 无标记脚本:这正是 bug 的画面(每站 100 张卡),保持不变。
  645. const view = liveParticipantView(FAN_OUT, fanOutRun(false));
  646. expect(view.graph.participants).toHaveLength(500);
  647. });
  648. it("keeps a reused actor on both cards: it has a node stamped in each phase", () => {
  649. const run = runWith(
  650. [{ name: "修复员", ordinal: 4, phaseName: "attempt", siteId: "actor#1", status: "running" }],
  651. [
  652. {
  653. actorOrdinal: 4,
  654. actorSiteId: "actor#1",
  655. ordinal: 1,
  656. outcome: "ok",
  657. phase: "settled",
  658. phaseName: "attempt",
  659. siteId: "ask#1",
  660. },
  661. {
  662. actorOrdinal: 4,
  663. actorSiteId: "actor#1",
  664. ordinal: 2,
  665. phase: "executing",
  666. phaseName: "gate",
  667. siteId: "ask#3",
  668. },
  669. ],
  670. );
  671. const view = liveParticipantView(LIVE_GRAPH, run);
  672. // 「一个实例跨两阶段」与「两批实例各自出生于不同阶段」的区别正在戳上:这里仍是两张卡都列它。
  673. expect(view.graph).toBe(LIVE_GRAPH);
  674. expect(view.instances["phase#1:actor#1"]).toEqual({
  675. bound: true,
  676. name: "修复员",
  677. ordinal: 4,
  678. participant: "phase#1:actor#1",
  679. });
  680. expect(view.instances["phase#2:actor#1"]).toEqual({
  681. bound: true,
  682. name: "修复员",
  683. ordinal: 4,
  684. participant: "phase#2:actor#1",
  685. });
  686. });
  687. it("splits by phase rather than by lane: gate lists only the instance that worked there", () => {
  688. // 与「splits a single card like `many`」同一形状,只是带了戳:两个实例都出生在 attempt,
  689. // 只有 @6 走到了 gate。无戳时两张卡都拆成 @2 / @6(那条既有用例),有戳时 gate 只剩 @6。
  690. const run = runWith(
  691. [
  692. { name: "fixer-b", ordinal: 6, phaseName: "attempt", siteId: "actor#1", status: "waiting" },
  693. { name: "fixer-a", ordinal: 2, phaseName: "attempt", siteId: "actor#1", status: "running" },
  694. ],
  695. [
  696. {
  697. actorOrdinal: 2,
  698. actorSiteId: "actor#1",
  699. ordinal: 1,
  700. phase: "executing",
  701. phaseName: "attempt",
  702. siteId: "ask#1",
  703. },
  704. {
  705. actorOrdinal: 6,
  706. actorSiteId: "actor#1",
  707. ordinal: 2,
  708. outcome: "ok",
  709. phase: "settled",
  710. phaseName: "attempt",
  711. siteId: "ask#1",
  712. },
  713. {
  714. actorOrdinal: 6,
  715. actorSiteId: "actor#1",
  716. ordinal: 3,
  717. outcome: "failed",
  718. phase: "settled",
  719. phaseName: "gate",
  720. siteId: "ask#3",
  721. },
  722. ],
  723. );
  724. const view = liveParticipantView(LIVE_GRAPH, run);
  725. expect(view.graph.participants.map((participant) => participant.id)).toEqual([
  726. "phase#1:actor#1@2",
  727. "phase#1:actor#1@6",
  728. "phase#1:workspace",
  729. "phase#2:actor#1",
  730. "phase#2:actor#2[0]",
  731. "phase#2:actor#2[1]",
  732. "phase#2:actor#3",
  733. ]);
  734. expect(view.instances["phase#2:actor#1"]).toEqual({
  735. bound: true,
  736. name: "fixer-b",
  737. ordinal: 6,
  738. participant: "phase#2:actor#1",
  739. });
  740. expect(view.participantStatuses["phase#1:actor#1@2"]).toBe("running");
  741. expect(view.participantStatuses["phase#1:actor#1@6"]).toBe("done");
  742. });
  743. it("lands an instance born before the first marker on the unnamed card only", () => {
  744. // 标记之前发出的 step 分析器放在无名的 `unphased` 里;无戳的实例是同一个事实的另一面。
  745. const graph: WorkflowCausalityGraphData = {
  746. handoffs: [],
  747. lanes: [{ id: "actor#1", name: "fixer" }],
  748. participants: [
  749. { id: "unphased:actor#1", lane: "actor#1", phase: "unphased", steps: ["ask#0"] },
  750. { id: "phase#1:actor#1", lane: "actor#1", phase: "phase#1", steps: ["ask#1"] },
  751. ],
  752. phases: [{ id: "unphased" }, { id: "phase#1", name: "attempt" }],
  753. steps: [
  754. step({ id: "ask#0", lane: "actor#1", phase: "unphased" }),
  755. step({ id: "ask#1", lane: "actor#1", phase: "phase#1" }),
  756. ],
  757. };
  758. const run = runWith(
  759. [
  760. { ordinal: 1, siteId: "actor#1", status: "waiting" },
  761. { ordinal: 2, phaseName: "attempt", siteId: "actor#1", status: "running" },
  762. ],
  763. [
  764. {
  765. actorOrdinal: 1,
  766. actorSiteId: "actor#1",
  767. ordinal: 1,
  768. outcome: "ok",
  769. phase: "settled",
  770. siteId: "ask#0",
  771. },
  772. {
  773. actorOrdinal: 2,
  774. actorSiteId: "actor#1",
  775. ordinal: 2,
  776. phase: "executing",
  777. phaseName: "attempt",
  778. siteId: "ask#1",
  779. },
  780. ],
  781. );
  782. const view = liveParticipantView(graph, run);
  783. expect(view.graph).toBe(graph);
  784. expect(view.instances["unphased:actor#1"]?.ordinal).toBe(1);
  785. expect(view.instances["phase#1:actor#1"]?.ordinal).toBe(2);
  786. });
  787. it("shows an instance whose stamp matches no card everywhere on its lane, never nowhere", () => {
  788. const run = runWith(
  789. [{ ordinal: 4, phaseName: "留白", siteId: "actor#1", status: "running" }],
  790. [
  791. {
  792. actorOrdinal: 4,
  793. actorSiteId: "actor#1",
  794. ordinal: 1,
  795. phase: "executing",
  796. phaseName: "留白",
  797. siteId: "ask#1",
  798. },
  799. {
  800. actorOrdinal: 4,
  801. actorSiteId: "actor#1",
  802. ordinal: 2,
  803. outcome: "ok",
  804. phase: "settled",
  805. phaseName: "留白",
  806. siteId: "ask#3",
  807. },
  808. ],
  809. );
  810. const view = liveParticipantView(LIVE_GRAPH, run);
  811. expect(view.instances["phase#1:actor#1"]?.ordinal).toBe(4);
  812. expect(view.instances["phase#2:actor#1"]?.ordinal).toBe(4);
  813. });
  814. it("still binds on a graph with no phase table at all — nothing to divide by", () => {
  815. // 无标记脚本的原图(UI 合成隐式阶段之前):归属集无处可落,绑定必须照旧按车道走。
  816. const graph: WorkflowCausalityGraphData = {
  817. handoffs: [],
  818. lanes: [{ id: "actor#1", name: "fixer" }],
  819. participants: [
  820. { id: "unphased:actor#1", lane: "actor#1", phase: "unphased", steps: ["ask#1"] },
  821. ],
  822. steps: [step({ id: "ask#1", lane: "actor#1", phase: "unphased" })],
  823. };
  824. const view = liveParticipantView(
  825. graph,
  826. runWith([{ ordinal: 1, phaseName: "attempt", siteId: "actor#1", status: "running" }], []),
  827. );
  828. expect(view.instances["unphased:actor#1"]?.ordinal).toBe(1);
  829. });
  830. it("binds through the prefix rule when the display phase name was truncated at 128", () => {
  831. const long = "x".repeat(128);
  832. const graph: WorkflowCausalityGraphData = {
  833. ...LIVE_GRAPH,
  834. phases: [
  835. { id: "phase#1", name: long },
  836. { id: "phase#2", name: "gate" },
  837. ],
  838. };
  839. const run = runWith(
  840. [{ ordinal: 4, phaseName: `${long}yyy`, siteId: "actor#1", status: "running" }],
  841. [
  842. {
  843. actorOrdinal: 4,
  844. actorSiteId: "actor#1",
  845. ordinal: 1,
  846. phase: "executing",
  847. phaseName: `${long}yyy`,
  848. siteId: "ask#1",
  849. },
  850. ],
  851. );
  852. const view = liveParticipantView(graph, run);
  853. expect(view.instances["phase#1:actor#1"]?.ordinal).toBe(4);
  854. // gate 上它既没有节点、戳也不匹配:这张卡不绑定任何实例。
  855. expect("phase#2:actor#1" in view.instances).toBe(false);
  856. });
  857. });
  858. /**
  859. * 一个戳(实例的出生阶段)落在哪些 display 阶段上(追记 2026-09-09「节点的归属阶段集」)。
  860. * 卡片绑定与站的观察共用这一条规则。
  861. */
  862. describe("phasesOf", () => {
  863. const graph: WorkflowCausalityGraphData = {
  864. handoffs: [],
  865. lanes: [],
  866. participants: [],
  867. phases: [
  868. { id: "unphased" },
  869. { id: "phase#1", name: "attempt" },
  870. { id: "phase#2", name: "gate" },
  871. ],
  872. steps: [],
  873. };
  874. it("sends a stamped instance to the display phases whose name it matches", () => {
  875. expect([...phasesOf("gate", graph, true)]).toEqual(["phase#2"]);
  876. });
  877. it("sends an unstamped instance to the unnamed phase once the run has vocabulary", () => {
  878. expect([...phasesOf(undefined, graph, true)]).toEqual(["unphased"]);
  879. });
  880. it("sends an unstamped instance everywhere while the run has no vocabulary — today's behaviour", () => {
  881. expect([...phasesOf(undefined, graph, false)]).toEqual(["unphased", "phase#1", "phase#2"]);
  882. });
  883. it("falls back to every phase when a branch comes out empty: never hide a running subagent", () => {
  884. expect([...phasesOf("留白", graph, true)]).toEqual(["unphased", "phase#1", "phase#2"]);
  885. // 有词汇但图里没有无名阶段(每个 step 都在首个标记之后):无戳的实例宁可到处显示。
  886. const named: WorkflowCausalityGraphData = { ...graph, phases: graph.phases!.slice(1) };
  887. expect([...phasesOf(undefined, named, true)]).toEqual(["phase#1", "phase#2"]);
  888. // 没有阶段词汇表的图(UI 合成隐式阶段之前):空集,没有可归的地方。
  889. expect([...phasesOf("gate", { ...graph, phases: undefined }, true)]).toEqual([]);
  890. });
  891. it("uses the same prefix rule as the timeline when the display name was truncated", () => {
  892. const long = "x".repeat(128);
  893. const truncated: WorkflowCausalityGraphData = {
  894. ...graph,
  895. phases: [{ id: "phase#1", name: long }],
  896. };
  897. expect([...phasesOf(`${long}yyy`, truncated, true)]).toEqual(["phase#1"]);
  898. });
  899. });
  900. describe("runHasPhaseVocabulary", () => {
  901. const run = (overrides: Partial<WorkflowRunState>): WorkflowRunState => ({
  902. actors: [],
  903. lastEventSequence: 0,
  904. nodes: [],
  905. runId: "dwfrun-1",
  906. status: "running",
  907. usage: { nodesUsed: 0, spentTokens: 0 },
  908. ...overrides,
  909. });
  910. it("is true as soon as any actor or node carries a stamp", () => {
  911. expect(runHasPhaseVocabulary(undefined)).toBe(false);
  912. expect(runHasPhaseVocabulary(run({}))).toBe(false);
  913. expect(
  914. runHasPhaseVocabulary(
  915. run({ actors: [{ ordinal: 1, siteId: "actor#1", status: "waiting" }] }),
  916. ),
  917. ).toBe(false);
  918. expect(
  919. runHasPhaseVocabulary(
  920. run({
  921. actors: [{ ordinal: 1, phaseName: "attempt", siteId: "actor#1", status: "waiting" }],
  922. }),
  923. ),
  924. ).toBe(true);
  925. expect(
  926. runHasPhaseVocabulary(
  927. run({
  928. nodes: [{ ordinal: 1, phase: "queued", phaseName: "attempt", siteId: "ask#1" }],
  929. }),
  930. ),
  931. ).toBe(true);
  932. });
  933. });