dynamic-workflow-run-roster.test.ts 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800
  1. // 情势截面(docs/dynamic-workflow/launch.md「`GetWorkflowRun`」)的规则层:阶段表、子代理花名册、
  2. // 健康三组字段从「journal 事件 + 节点行 + actor 行 + 归约状态」派生出来的那一套判定。
  3. //
  4. // 这里刻意不碰 SQLite、不起引擎:规则密度高(状态词的判定顺序、缺席的读法、时间的唯一来源),
  5. // 而真取数面在测试里贵得离谱。事件与行都手搓,归约状态则走生产那条铸造链(toProgressPayload →
  6. // reduceWorkflowRunsState)——它是 run 面板与冷回放共用的那一个,不另起一份。接线是否通了由
  7. // dynamic-workflow-run-service.test.ts 的真库用例证明。
  8. import { describe, expect, it } from "vitest";
  9. import type {
  10. ActorRecord,
  11. NodeRecord,
  12. NodeRecordStatus,
  13. RunEvent,
  14. StoredEvent,
  15. } from "@zcode/dynamic-workflow";
  16. import {
  17. reduceWorkflowRunsState,
  18. type WorkflowRunsState,
  19. type WorkflowRunState,
  20. } from "@zcode/shared/zcode-protocol-v4";
  21. import { toProgressPayload } from "../src/app/dynamic-workflow-run-launch.js";
  22. import { buildWorkflowRunRoster } from "../src/app/dynamic-workflow-run-roster.js";
  23. const RUN_ID = "dwfrun-roster";
  24. /** 事件时刻的基准(2023-11-14T22:13:20Z),断言里一律写成 `T0 + 偏移`。 */
  25. const T0 = 1_700_000_000_000;
  26. /** 本次读的时刻:落在所有事件之后,于是上钳不生效,断言读的就是事件自己的时刻。 */
  27. const NOW = T0 + 600_000;
  28. type Entry = readonly [offset: number | undefined, event: RunEvent];
  29. /** 手搓事件轨:sequence 按顺序分配,`undefined` 偏移即「这条事件没有时间戳」(老 journal)。 */
  30. function evented(entries: readonly Entry[]): StoredEvent[] {
  31. return entries.map(([offset, event], index) => ({
  32. sequence: index + 1,
  33. event,
  34. ...(offset === undefined ? {} : { timeCreated: T0 + offset }),
  35. }));
  36. }
  37. /**
  38. * 与生产同一条铸造链:事件 → 进度载荷 → run 面板同款归约状态。
  39. *
  40. * `ceiling` 是铸载荷那一刻的默认并发(线上键 `concurrencyCeiling`,只落在 `run-started` 上)。给了它,
  41. * 归约状态才认得出「这个 run 自己定过一条不同于默认的界」——并发健康面的两个数正是从那条界算的。
  42. */
  43. function reduceOf(events: readonly StoredEvent[], ceiling?: number): WorkflowRunState | undefined {
  44. let state: WorkflowRunsState | undefined;
  45. for (const stored of events) {
  46. const payload = toProgressPayload({
  47. event: stored.event,
  48. runId: RUN_ID,
  49. sequence: stored.sequence,
  50. ...(ceiling === undefined ? {} : { concurrencyCeiling: ceiling }),
  51. });
  52. state = reduceWorkflowRunsState(state, payload) ?? state;
  53. }
  54. return state?.runs.find((run) => run.runId === RUN_ID);
  55. }
  56. function actorRow(siteId: string, name: string): ActorRecord {
  57. return { runId: RUN_ID, siteId, ordinal: 1, name };
  58. }
  59. function askRow(input: {
  60. siteId: string;
  61. ordinal?: number;
  62. actorSiteId: string;
  63. actorSeq: number;
  64. status: NodeRecordStatus;
  65. tokens?: number;
  66. }): NodeRecord {
  67. const ordinal = input.ordinal ?? 1;
  68. return {
  69. runId: RUN_ID,
  70. siteId: input.siteId,
  71. ordinal,
  72. kind: "ask",
  73. actorSiteId: input.actorSiteId,
  74. actorOrdinal: 1,
  75. actorSeq: input.actorSeq,
  76. inputHash: `hash-${input.siteId}-${ordinal}`,
  77. status: input.status,
  78. ...(input.tokens === undefined
  79. ? {}
  80. : { stats: { tokens: input.tokens, toolCalls: 3, turns: 2 } }),
  81. };
  82. }
  83. // ── (a) 在飞的 run:四个子代理各在一种处境上 ──────────────────────────────────────
  84. describe("情势截面 — 在飞的 run", () => {
  85. const events = evented([
  86. [0, { type: "run-started", runId: RUN_ID, caps: { maxConcurrency: 4 } }],
  87. [0, { type: "run-launched", inputId: "in-1", phaseNames: ["collect", "verify"] }],
  88. [1_000, { type: "phase-entered", name: "collect", ordinal: 1 }],
  89. // ① scout:模型请求真的在跑,两条进度事件说明它还在动。
  90. [
  91. 1_100,
  92. {
  93. type: "actor-created",
  94. actor: { siteId: "agent#1", ordinal: 1 },
  95. name: "scout",
  96. phaseName: "collect",
  97. },
  98. ],
  99. [
  100. 1_200,
  101. {
  102. type: "node-queued",
  103. instance: { siteId: "ask#1", ordinal: 1 },
  104. kind: "ask",
  105. actor: { siteId: "agent#1", ordinal: 1 },
  106. actorSeq: 1,
  107. phaseName: "collect",
  108. instructionsHead: "Read the release notes and list every regression you can name.",
  109. },
  110. ],
  111. [1_300, { type: "node-dispatched", instance: { siteId: "ask#1", ordinal: 1 } }],
  112. [1_400, { type: "node-executing", instance: { siteId: "ask#1", ordinal: 1 } }],
  113. [
  114. 2_000,
  115. {
  116. type: "node-progress",
  117. instance: { siteId: "ask#1", ordinal: 1 },
  118. turn: 1,
  119. toolCalls: 2,
  120. lastTool: { name: "Read", target: "docs/release.md" },
  121. },
  122. ],
  123. [2_010, { type: "usage-updated", spentTokens: 400 }],
  124. [
  125. 2_100,
  126. {
  127. type: "node-progress",
  128. instance: { siteId: "ask#1", ordinal: 1 },
  129. turn: 2,
  130. toolCalls: 5,
  131. lastTool: { name: "Bash", target: "rg -n regression" },
  132. },
  133. ],
  134. [2_110, { type: "usage-updated", spentTokens: 900 }],
  135. // ② runner:在退避阶梯上,连发两条 node-waiting。
  136. [
  137. 3_000,
  138. {
  139. type: "actor-created",
  140. actor: { siteId: "agent#2", ordinal: 1 },
  141. name: "runner",
  142. phaseName: "collect",
  143. },
  144. ],
  145. [
  146. 3_100,
  147. {
  148. type: "node-queued",
  149. instance: { siteId: "ask#2", ordinal: 1 },
  150. kind: "ask",
  151. actor: { siteId: "agent#2", ordinal: 1 },
  152. actorSeq: 1,
  153. phaseName: "collect",
  154. instructionsHead: "Re-run the failing suite and report the first red test.",
  155. },
  156. ],
  157. [3_200, { type: "node-dispatched", instance: { siteId: "ask#2", ordinal: 1 } }],
  158. [3_300, { type: "node-executing", instance: { siteId: "ask#2", ordinal: 1 } }],
  159. [
  160. 4_000,
  161. {
  162. type: "node-waiting",
  163. instance: { siteId: "ask#2", ordinal: 1 },
  164. cause: "backoff",
  165. reason: "provider returned 429",
  166. attempt: 1,
  167. retryAfterMs: 30_000,
  168. },
  169. ],
  170. [
  171. 5_000,
  172. {
  173. type: "node-waiting",
  174. instance: { siteId: "ask#2", ordinal: 1 },
  175. cause: "backoff",
  176. reason: "provider returned 429",
  177. attempt: 2,
  178. retryAfterMs: 60_000,
  179. },
  180. ],
  181. // ③ asker:把问题升级给了主代理,停在那儿等答案。
  182. [
  183. 6_000,
  184. {
  185. type: "actor-created",
  186. actor: { siteId: "agent#3", ordinal: 1 },
  187. name: "asker",
  188. phaseName: "collect",
  189. },
  190. ],
  191. [
  192. 6_100,
  193. {
  194. type: "node-queued",
  195. instance: { siteId: "ask#3", ordinal: 1 },
  196. kind: "ask",
  197. actor: { siteId: "agent#3", ordinal: 1 },
  198. actorSeq: 1,
  199. phaseName: "collect",
  200. instructionsHead: "Decide which fixture to keep.",
  201. },
  202. ],
  203. [6_200, { type: "node-dispatched", instance: { siteId: "ask#3", ordinal: 1 } }],
  204. [6_300, { type: "node-executing", instance: { siteId: "ask#3", ordinal: 1 } }],
  205. [
  206. 6_400,
  207. {
  208. type: "escalation-raised",
  209. qid: "dwfq-roster-1",
  210. actor: { siteId: "agent#3", ordinal: 1 },
  211. actorName: "asker",
  212. question: "Which fixture should survive?",
  213. askedAt: T0 + 6_400,
  214. },
  215. ],
  216. // ④ idler:两次 ask 都结算完了,后一次是 replay 命中(没有 queued,settled 就是出生事件)。
  217. [
  218. 7_000,
  219. {
  220. type: "actor-created",
  221. actor: { siteId: "agent#4", ordinal: 1 },
  222. name: "idler",
  223. phaseName: "collect",
  224. },
  225. ],
  226. [
  227. 7_100,
  228. {
  229. type: "node-queued",
  230. instance: { siteId: "ask#4", ordinal: 1 },
  231. kind: "ask",
  232. actor: { siteId: "agent#4", ordinal: 1 },
  233. actorSeq: 1,
  234. phaseName: "collect",
  235. instructionsHead: "Summarise the findings.",
  236. },
  237. ],
  238. [7_200, { type: "node-dispatched", instance: { siteId: "ask#4", ordinal: 1 } }],
  239. [7_300, { type: "node-settled", instance: { siteId: "ask#4", ordinal: 1 }, outcome: "ok" }],
  240. [
  241. 7_400,
  242. {
  243. type: "node-settled",
  244. instance: { siteId: "ask#4", ordinal: 2 },
  245. outcome: "ok",
  246. cached: true,
  247. phaseName: "collect",
  248. },
  249. ],
  250. // ⑤ run 级观察:闸门被限流压低,随后一段时间没有任何进度。
  251. [
  252. 10_000,
  253. {
  254. type: "concurrency-changed",
  255. key: "zhipu/glm-4",
  256. previous: 4,
  257. next: 2,
  258. reason: "rate_limited",
  259. cooldownMs: 5_000,
  260. },
  261. ],
  262. [11_000, { type: "run-stalled", sinceMs: 120_000, reason: "no turn resolved", cap: 2 }],
  263. ]);
  264. const nodes: NodeRecord[] = [
  265. askRow({ siteId: "ask#1", actorSiteId: "agent#1", actorSeq: 1, status: "running" }),
  266. askRow({ siteId: "ask#2", actorSiteId: "agent#2", actorSeq: 1, status: "running" }),
  267. askRow({ siteId: "ask#3", actorSiteId: "agent#3", actorSeq: 1, status: "running" }),
  268. askRow({
  269. siteId: "ask#4",
  270. actorSiteId: "agent#4",
  271. actorSeq: 1,
  272. status: "completed",
  273. tokens: 120,
  274. }),
  275. askRow({
  276. siteId: "ask#4",
  277. ordinal: 2,
  278. actorSiteId: "agent#4",
  279. actorSeq: 2,
  280. status: "completed",
  281. tokens: 80,
  282. }),
  283. ];
  284. const roster = buildWorkflowRunRoster({
  285. run: reduceOf(events),
  286. events,
  287. nodes,
  288. actors: [
  289. actorRow("agent#1", "scout"),
  290. actorRow("agent#2", "runner"),
  291. actorRow("agent#3", "asker"),
  292. actorRow("agent#4", "idler"),
  293. ],
  294. status: "running",
  295. pendingQuestions: [
  296. {
  297. qid: "dwfq-roster-1",
  298. actor: "agent#3@1",
  299. actorName: "asker",
  300. question: "Which fixture should survive?",
  301. askedAt: T0 + 6_400,
  302. },
  303. ],
  304. now: NOW,
  305. });
  306. const subagentOf = (siteId: string) =>
  307. roster.subagents.find((subagent) => subagent.siteId === siteId);
  308. it("正在跑的子代理带任务摘要、轮次读数与最近一次工具(时刻取那条 node-progress)", () => {
  309. expect(subagentOf("agent#1")).toMatchObject({
  310. name: "scout",
  311. state: "executing",
  312. phaseName: "collect",
  313. currentAsk: {
  314. siteId: "ask#1",
  315. ordinal: 1,
  316. actorSeq: 1,
  317. instructionsHead: "Read the release notes and list every regression you can name.",
  318. // 开始时刻是 node-dispatched,不是 node-queued:排队不是开跑。
  319. startedAt: T0 + 1_300,
  320. turn: 2,
  321. toolCalls: 5,
  322. lastTool: { name: "Bash", target: "rg -n regression", at: T0 + 2_100 },
  323. },
  324. stepsSettled: 0,
  325. tokens: 0,
  326. // run 级的 usage-updated 不带实例,所以它不算在**这个**子代理头上。
  327. lastProgressAt: T0 + 2_100,
  328. });
  329. });
  330. it("退避中的子代理报 waiting,since 是**进入**这次等待的时刻而不是最后一条观察", () => {
  331. expect(subagentOf("agent#2")).toMatchObject({
  332. state: "waiting",
  333. wait: {
  334. cause: "backoff",
  335. reason: "provider returned 429",
  336. // 阶梯上第二条带来的是新的重试间隔,但「卡了多久」要从第一条算。
  337. retryAfterMs: 60_000,
  338. since: T0 + 4_000,
  339. },
  340. });
  341. // 等待不是进度:最后一条进度仍是它开跑的那一刻。
  342. expect(subagentOf("agent#2")?.lastProgressAt).toBe(T0 + 3_300);
  343. // 没有 node-progress 的 ask 上三个读数一律缺席,不给 0。
  344. const currentAsk = subagentOf("agent#2")?.currentAsk;
  345. expect(currentAsk).toBeDefined();
  346. expect("turn" in currentAsk!).toBe(false);
  347. expect("toolCalls" in currentAsk!).toBe(false);
  348. expect("lastTool" in currentAsk!).toBe(false);
  349. });
  350. it("停驻等答案的子代理报 parked 而不是 executing(它确实有 ask 在跑,但那不是它此刻的处境)", () => {
  351. expect(subagentOf("agent#3")).toMatchObject({
  352. state: "parked",
  353. parkedOn: "dwfq-roster-1",
  354. currentAsk: { siteId: "ask#3", ordinal: 1 },
  355. });
  356. });
  357. it("活着的 run 里全部结算完的子代理是 idle(done 是终态才有的词),token 只累计已结算的 ask", () => {
  358. const idler = subagentOf("agent#4");
  359. expect(idler).toMatchObject({
  360. state: "idle",
  361. stepsSettled: 2,
  362. stepsFailed: 0,
  363. tokens: 200,
  364. lastProgressAt: T0 + 7_400,
  365. });
  366. expect("currentAsk" in idler!).toBe(false);
  367. });
  368. it("阶段表:走到的那个是 current,声明了没走到的是 ahead 且 rounds 为 0", () => {
  369. expect(roster.phases).toEqual([
  370. {
  371. name: "collect",
  372. state: "current",
  373. rounds: 1,
  374. nodesSettled: 2,
  375. nodesRunning: 3,
  376. enteredAt: T0 + 1_000,
  377. },
  378. { name: "verify", state: "ahead", rounds: 0, nodesSettled: 0, nodesRunning: 0 },
  379. ]);
  380. });
  381. it("健康:停滞时刻是最后一条 run-stalled(其后没有进度),并发报的是「自己那条界里放行了几个」", () => {
  382. expect(roster.health).toEqual({
  383. // 最后一条进度是 idler 的缓存结算;concurrency-changed 与 run-stalled 都不算进度。
  384. lastProgressAt: T0 + 7_400,
  385. stalledSince: T0 + 11_000,
  386. concurrency: { effective: 2, cap: 4, reason: "rate_limited", since: T0 + 10_000 },
  387. consecutiveFailures: 0,
  388. cachedSteps: 1,
  389. pendingQuestionsKnown: true,
  390. });
  391. });
  392. });
  393. // ── 进度的定义:脚本自己在动也算,等槽位不算 ────────────────────────────────────
  394. describe("情势截面 — 什么算进度", () => {
  395. function healthOf(events: readonly StoredEvent[]) {
  396. return buildWorkflowRunRoster({
  397. run: reduceOf(events),
  398. events,
  399. nodes: [],
  400. actors: [],
  401. status: "running",
  402. pendingQuestions: [],
  403. now: NOW,
  404. }).health;
  405. }
  406. it("停滞之后的一行 log 就把停滞清掉,并把最后进度推到那一刻:那是脚本在往前走", () => {
  407. // 两次 ask 之间跑一串 world read 的脚本一条 ask 事件都不发,把 log 排除掉,
  408. // 那段时间会被整个误报成停滞。
  409. const narrated = evented([
  410. [0, { type: "run-started", runId: RUN_ID, caps: { maxConcurrency: 4 } }],
  411. [1_000, { type: "run-stalled", sinceMs: 120_000, reason: "no turn resolved" }],
  412. [2_000, { type: "log", message: "scanning the workspace" }],
  413. ]);
  414. const health = healthOf(narrated);
  415. expect("stalledSince" in health).toBe(false);
  416. expect(health.lastProgressAt).toBe(T0 + 2_000);
  417. });
  418. it("一次 phase-entered 同样算进度:刚进阶段、正在派发的 run 不该读成停滞", () => {
  419. const advanced = evented([
  420. [0, { type: "run-started", runId: RUN_ID, caps: { maxConcurrency: 4 } }],
  421. [1_000, { type: "run-stalled", sinceMs: 120_000, reason: "no turn resolved" }],
  422. [3_000, { type: "phase-entered", name: "verify", ordinal: 1 }],
  423. ]);
  424. const health = healthOf(advanced);
  425. expect("stalledSince" in health).toBe(false);
  426. expect(health.lastProgressAt).toBe(T0 + 3_000);
  427. });
  428. it("停滞之后只剩等待观察时,停滞仍然在场:那段等待正是停滞本身", () => {
  429. const stuck = evented([
  430. [0, { type: "run-started", runId: RUN_ID, caps: { maxConcurrency: 4 } }],
  431. [
  432. 1_000,
  433. {
  434. type: "node-queued",
  435. instance: { siteId: "ask#1", ordinal: 1 },
  436. kind: "ask",
  437. actor: { siteId: "agent#1", ordinal: 1 },
  438. actorSeq: 1,
  439. },
  440. ],
  441. [2_000, { type: "run-stalled", sinceMs: 120_000, reason: "no slot" }],
  442. [3_000, { type: "node-waiting", instance: { siteId: "ask#1", ordinal: 1 }, cause: "slot" }],
  443. [
  444. 4_000,
  445. {
  446. type: "concurrency-changed",
  447. key: "zhipu/glm-4",
  448. previous: 4,
  449. next: 1,
  450. reason: "rate_limited",
  451. },
  452. ],
  453. ]);
  454. const health = healthOf(stuck);
  455. expect(health.stalledSince).toBe(T0 + 2_000);
  456. // 最后一条真正的进度还是那次排队。
  457. expect(health.lastProgressAt).toBe(T0 + 1_000);
  458. });
  459. });
  460. // ── 并发健康面:两个数说的是「它自己那条界里放行了几个」 ──────────────────────────
  461. describe("情势截面 — 并发", () => {
  462. /** 本 run 定了 3,机器天花板 6;治理器把共享闸门压到 2。 */
  463. const throttled = evented([
  464. [0, { type: "run-started", runId: RUN_ID, caps: { maxConcurrency: 3 } }],
  465. [
  466. 1_000,
  467. {
  468. type: "concurrency-changed",
  469. key: "zhipu/glm-4",
  470. previous: 6,
  471. next: 2,
  472. reason: "rate_limited",
  473. },
  474. ],
  475. ]);
  476. function healthOf(events: readonly StoredEvent[], ceiling: number) {
  477. return buildWorkflowRunRoster({
  478. run: reduceOf(events, ceiling),
  479. events,
  480. nodes: [],
  481. actors: [],
  482. status: "running",
  483. pendingQuestions: [],
  484. now: NOW,
  485. }).health;
  486. }
  487. it("cap 是**本 run 自己的**上界而不是机器天花板(否则 3 核的 run 永远显示成被限流)", () => {
  488. expect(healthOf(throttled, 6).concurrency).toEqual({
  489. effective: 2,
  490. cap: 3,
  491. reason: "rate_limited",
  492. since: T0 + 1_000,
  493. });
  494. });
  495. it("跑满自己那条界的 run:整个 concurrency 字段缺席(在场即「正被限着」)", () => {
  496. // 只有本 run 的上界低于天花板,共享闸门没动过 ⇒ effective === cap ⇒ 无话可说。
  497. const unthrottled = evented([
  498. [0, { type: "run-started", runId: RUN_ID, caps: { maxConcurrency: 3 } }],
  499. ]);
  500. expect("concurrency" in healthOf(unthrottled, 6)).toBe(false);
  501. });
  502. });
  503. // ── (b) 已完成的 run:完整阶段表 + 终态的三个状态词 ──────────────────────────────
  504. describe("情势截面 — 已完成的 run", () => {
  505. const events = evented([
  506. [0, { type: "run-started", runId: RUN_ID, caps: { maxConcurrency: 4 } }],
  507. [
  508. 0,
  509. {
  510. type: "run-launched",
  511. inputId: "in-2",
  512. phaseNames: ["plan", "build", "verify", "publish"],
  513. },
  514. ],
  515. [1_000, { type: "phase-entered", name: "plan", ordinal: 1 }],
  516. [1_100, { type: "actor-created", actor: { siteId: "agent#1", ordinal: 1 }, name: "planner" }],
  517. [
  518. 1_200,
  519. {
  520. type: "node-queued",
  521. instance: { siteId: "ask#1", ordinal: 1 },
  522. kind: "ask",
  523. actor: { siteId: "agent#1", ordinal: 1 },
  524. actorSeq: 1,
  525. phaseName: "plan",
  526. instructionsHead: "Draft the plan.",
  527. },
  528. ],
  529. [1_300, { type: "node-dispatched", instance: { siteId: "ask#1", ordinal: 1 } }],
  530. [1_400, { type: "node-settled", instance: { siteId: "ask#1", ordinal: 1 }, outcome: "ok" }],
  531. [2_000, { type: "phase-entered", name: "build", ordinal: 1 }],
  532. [2_100, { type: "actor-created", actor: { siteId: "agent#2", ordinal: 1 }, name: "builder" }],
  533. [
  534. 2_200,
  535. {
  536. type: "node-queued",
  537. instance: { siteId: "ask#2", ordinal: 1 },
  538. kind: "ask",
  539. actor: { siteId: "agent#2", ordinal: 1 },
  540. actorSeq: 1,
  541. phaseName: "build",
  542. instructionsHead: "Build it.",
  543. },
  544. ],
  545. [2_300, { type: "node-dispatched", instance: { siteId: "ask#2", ordinal: 1 } }],
  546. [2_400, { type: "node-settled", instance: { siteId: "ask#2", ordinal: 1 }, outcome: "failed" }],
  547. [
  548. 2_500,
  549. {
  550. type: "node-queued",
  551. instance: { siteId: "ask#2", ordinal: 2 },
  552. kind: "ask",
  553. actor: { siteId: "agent#2", ordinal: 1 },
  554. actorSeq: 2,
  555. phaseName: "build",
  556. instructionsHead: "Build it again.",
  557. },
  558. ],
  559. [2_600, { type: "node-dispatched", instance: { siteId: "ask#2", ordinal: 2 } }],
  560. [2_700, { type: "node-settled", instance: { siteId: "ask#2", ordinal: 2 }, outcome: "failed" }],
  561. // 回边:控制流又回了一趟 plan,然后才去 verify。
  562. [3_000, { type: "phase-entered", name: "plan", ordinal: 2 }],
  563. [4_000, { type: "phase-entered", name: "verify", ordinal: 1 }],
  564. [5_000, { type: "run-settled", status: "completed" }],
  565. ]);
  566. const roster = buildWorkflowRunRoster({
  567. run: reduceOf(events),
  568. events,
  569. nodes: [
  570. askRow({
  571. siteId: "ask#1",
  572. actorSiteId: "agent#1",
  573. actorSeq: 1,
  574. status: "completed",
  575. tokens: 50,
  576. }),
  577. askRow({
  578. siteId: "ask#2",
  579. actorSiteId: "agent#2",
  580. actorSeq: 1,
  581. status: "failed",
  582. tokens: 10,
  583. }),
  584. askRow({
  585. siteId: "ask#2",
  586. ordinal: 2,
  587. actorSiteId: "agent#2",
  588. actorSeq: 2,
  589. status: "failed",
  590. tokens: 20,
  591. }),
  592. ],
  593. actors: [actorRow("agent#1", "planner"), actorRow("agent#2", "builder")],
  594. status: "completed",
  595. pendingQuestions: [],
  596. now: NOW,
  597. });
  598. it("阶段表按声明序,回边的阶段取**最近一次**进入,离开时刻是下一个异名阶段进入的那一刻", () => {
  599. expect(roster.phases).toEqual([
  600. {
  601. name: "plan",
  602. state: "done",
  603. // 进过两次;取的是第二次的时刻,而不是第一次。
  604. rounds: 2,
  605. nodesSettled: 1,
  606. nodesRunning: 0,
  607. enteredAt: T0 + 3_000,
  608. exitedAt: T0 + 4_000,
  609. },
  610. {
  611. name: "build",
  612. state: "done",
  613. rounds: 1,
  614. nodesSettled: 2,
  615. nodesRunning: 0,
  616. enteredAt: T0 + 2_000,
  617. exitedAt: T0 + 3_000,
  618. },
  619. // 最后进入的阶段没有离开时刻;run 已终态,所以它也不是 current。
  620. {
  621. name: "verify",
  622. state: "done",
  623. rounds: 1,
  624. nodesSettled: 0,
  625. nodesRunning: 0,
  626. enteredAt: T0 + 4_000,
  627. },
  628. { name: "publish", state: "ahead", rounds: 0, nodesSettled: 0, nodesRunning: 0 },
  629. ]);
  630. });
  631. it("终态 run 的状态词只剩 done / failed,末尾连败被数成 2", () => {
  632. expect(roster.subagents).toMatchObject([
  633. { name: "planner", state: "done", stepsSettled: 1, stepsFailed: 0, tokens: 50 },
  634. { name: "builder", state: "failed", stepsSettled: 2, stepsFailed: 2, tokens: 30 },
  635. ]);
  636. expect(roster.health).toMatchObject({ consecutiveFailures: 2, cachedSteps: 0 });
  637. // 没有遗留行,整个字段缺席(0 是噪音)。
  638. expect("leftoverRunning" in roster.health).toBe(false);
  639. });
  640. });
  641. // ── (c) 被打断、且不在本会话手里的 run ─────────────────────────────────────────
  642. describe("情势截面 — 被打断且查不到停驻表的 run", () => {
  643. const events = evented([
  644. [0, { type: "run-started", runId: RUN_ID, caps: { maxConcurrency: 4 } }],
  645. [0, { type: "run-launched", inputId: "in-3", phaseNames: ["work"] }],
  646. [1_000, { type: "phase-entered", name: "work", ordinal: 1 }],
  647. [1_100, { type: "actor-created", actor: { siteId: "agent#1", ordinal: 1 }, name: "worker" }],
  648. [
  649. 1_200,
  650. {
  651. type: "node-queued",
  652. instance: { siteId: "ask#1", ordinal: 1 },
  653. kind: "ask",
  654. actor: { siteId: "agent#1", ordinal: 1 },
  655. actorSeq: 1,
  656. phaseName: "work",
  657. instructionsHead: "Do the long thing.",
  658. },
  659. ],
  660. [1_300, { type: "node-dispatched", instance: { siteId: "ask#1", ordinal: 1 } }],
  661. [1_400, { type: "node-executing", instance: { siteId: "ask#1", ordinal: 1 } }],
  662. ]);
  663. const roster = buildWorkflowRunRoster({
  664. run: reduceOf(events),
  665. events,
  666. nodes: [askRow({ siteId: "ask#1", actorSiteId: "agent#1", actorSeq: 1, status: "running" })],
  667. actors: [actorRow("agent#1", "worker")],
  668. status: "stopped",
  669. // 停驻表查不到:run 归另一个进程,这次读分不出「没人在等」与「不知道」。
  670. now: NOW,
  671. });
  672. it("行还标着 running 的子代理在终态 run 上是 unfinished,并被数进 leftoverRunning", () => {
  673. expect(roster.subagents[0]).toMatchObject({ name: "worker", state: "unfinished" });
  674. expect(roster.health.leftoverRunning).toBe(1);
  675. });
  676. it("查不到停驻表时 pendingQuestionsKnown 为假,且没有任何子代理被报成 parked", () => {
  677. expect(roster.health.pendingQuestionsKnown).toBe(false);
  678. expect(roster.subagents.every((subagent) => !("parkedOn" in subagent))).toBe(true);
  679. });
  680. it("终态 run 上仍有在飞 ask 的阶段是 unfinished,不是 done", () => {
  681. expect(roster.phases).toEqual([
  682. {
  683. name: "work",
  684. state: "unfinished",
  685. rounds: 1,
  686. nodesSettled: 0,
  687. nodesRunning: 1,
  688. enteredAt: T0 + 1_000,
  689. },
  690. ]);
  691. });
  692. });
  693. // ── (d) 老 journal:没有 node-progress、没有 instructionsHead、没有时间戳 ──────────
  694. describe("情势截面 — 老 journal", () => {
  695. const events = evented([
  696. [undefined, { type: "run-started", runId: RUN_ID, caps: { maxConcurrency: 4 } }],
  697. [undefined, { type: "phase-entered", name: "work", ordinal: 1 }],
  698. [
  699. undefined,
  700. { type: "actor-created", actor: { siteId: "agent#1", ordinal: 1 }, name: "veteran" },
  701. ],
  702. [
  703. undefined,
  704. {
  705. type: "node-queued",
  706. instance: { siteId: "ask#1", ordinal: 1 },
  707. kind: "ask",
  708. actor: { siteId: "agent#1", ordinal: 1 },
  709. actorSeq: 1,
  710. phaseName: "work",
  711. },
  712. ],
  713. [undefined, { type: "node-dispatched", instance: { siteId: "ask#1", ordinal: 1 } }],
  714. [undefined, { type: "node-executing", instance: { siteId: "ask#1", ordinal: 1 } }],
  715. ]);
  716. const roster = buildWorkflowRunRoster({
  717. run: reduceOf(events),
  718. events,
  719. nodes: [askRow({ siteId: "ask#1", actorSiteId: "agent#1", actorSeq: 1, status: "running" })],
  720. actors: [actorRow("agent#1", "veteran")],
  721. status: "running",
  722. pendingQuestions: [],
  723. now: NOW,
  724. });
  725. it("所有时刻整个缺席,绝不用读的那一刻兜底,也绝不出现 NaN", () => {
  726. const subagent = roster.subagents[0]!;
  727. expect(subagent.state).toBe("executing");
  728. expect("lastProgressAt" in subagent).toBe(false);
  729. expect("startedAt" in subagent.currentAsk!).toBe(false);
  730. expect("lastProgressAt" in roster.health).toBe(false);
  731. expect("enteredAt" in roster.phases![0]!).toBe(false);
  732. // 一趟 JSON 往返兜住整棵树:任何 NaN 都会在这里变成 null 而被断言抓住。
  733. expect(JSON.stringify(roster)).not.toContain("null");
  734. expect(JSON.stringify(roster)).not.toContain("NaN");
  735. });
  736. it("没有 node-queued 任务摘要、没有 node-progress 读数时,那几个键一个都不编", () => {
  737. const currentAsk = roster.subagents[0]!.currentAsk!;
  738. expect(currentAsk).toEqual({ siteId: "ask#1", ordinal: 1, actorSeq: 1 });
  739. });
  740. it("run 一条事件都没有时:阶段表整个缺席、花名册为空、健康全零", () => {
  741. const empty = buildWorkflowRunRoster({
  742. run: undefined,
  743. events: [],
  744. nodes: [],
  745. actors: [],
  746. status: "pending",
  747. pendingQuestions: [],
  748. now: NOW,
  749. });
  750. expect(empty).toEqual({
  751. subagents: [],
  752. health: { consecutiveFailures: 0, cachedSteps: 0, pendingQuestionsKnown: true },
  753. });
  754. });
  755. });