expert-workflow.test.ts 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736
  1. import { describe, expect, it } from "vitest";
  2. import type {
  3. ExpertWorkflowRunSnapshot,
  4. WorkflowDefinition,
  5. WorkflowEvent,
  6. WorkflowGraphRecord,
  7. WorkflowRunListItem,
  8. WorkflowStorePort,
  9. } from "@zcode/contracts";
  10. import { ExpertWorkflowRuntime, DEFAULT_EXPERT_WORKFLOW_STRATEGY } from "../src/workflow/expert.js";
  11. class MemoryWorkflowStore implements WorkflowStorePort {
  12. artifacts = new Map<string, string>();
  13. events: WorkflowEvent[] = [];
  14. graphRecords: WorkflowGraphRecord[] = [];
  15. snapshots = new Map<string, ExpertWorkflowRunSnapshot>();
  16. async appendEvent(event: WorkflowEvent): Promise<void> {
  17. this.events.push(event);
  18. }
  19. async appendGraphRecord(_runId: string, record: WorkflowGraphRecord): Promise<void> {
  20. this.graphRecords.push(record);
  21. }
  22. async listRuns(): Promise<WorkflowRunListItem[]> {
  23. return [...this.snapshots.values()]
  24. .map((snapshot) => ({
  25. completedAt: snapshot.completedAt,
  26. createdAt: snapshot.createdAt,
  27. cwd: snapshot.cwd,
  28. kind: snapshot.kind,
  29. runId: snapshot.runId,
  30. status: snapshot.status,
  31. task: snapshot.task,
  32. updatedAt: snapshot.updatedAt,
  33. }))
  34. .sort((a, b) => b.updatedAt.localeCompare(a.updatedAt));
  35. }
  36. async readEvents(runId: string): Promise<WorkflowEvent[]> {
  37. return this.events.filter((event) => event.runId === runId);
  38. }
  39. async readLatestRun(): Promise<ExpertWorkflowRunSnapshot | null> {
  40. const [latest] = await this.listRuns();
  41. return latest ? (this.snapshots.get(latest.runId) ?? null) : null;
  42. }
  43. async readRun(runId: string): Promise<ExpertWorkflowRunSnapshot | null> {
  44. return this.snapshots.get(runId) ?? null;
  45. }
  46. async writeArtifact(
  47. runId: string,
  48. relativePath: string,
  49. content: string,
  50. ): Promise<{ path: string; relativePath: string }> {
  51. const key = `${runId}/${relativePath}`;
  52. this.artifacts.set(key, content);
  53. return {
  54. path: key,
  55. relativePath,
  56. };
  57. }
  58. async writeReport(
  59. runId: string,
  60. content: string,
  61. ): Promise<{ path: string; relativePath: string }> {
  62. return this.writeArtifact(runId, "report.md", content);
  63. }
  64. async writeSnapshot(snapshot: ExpertWorkflowRunSnapshot): Promise<void> {
  65. this.snapshots.set(snapshot.runId, snapshot);
  66. }
  67. }
  68. describe("ExpertWorkflowRuntime", () => {
  69. it("runs the GSAP-inspired phase schedule and writes artifacts", async () => {
  70. const store = new MemoryWorkflowStore();
  71. const phases: string[] = [];
  72. let now = 0;
  73. const runtime = new ExpertWorkflowRuntime({
  74. agentRunner: {
  75. run: async (input) => {
  76. phases.push(input.phase);
  77. if (input.phase === "final_critic") {
  78. return {
  79. response: JSON.stringify({
  80. reasoning: "looks good",
  81. verdict: "pass",
  82. }),
  83. sessionId: `sess-${input.phase}`,
  84. traceId: `trace-${input.phase}`,
  85. turnId: `turn-${input.phase}`,
  86. };
  87. }
  88. return {
  89. response: `# ${input.phase}\n\nok`,
  90. sessionId: `sess-${input.phase}`,
  91. traceId: `trace-${input.phase}`,
  92. turnId: `turn-${input.phase}`,
  93. };
  94. },
  95. },
  96. createRunId: () => "wf_expert_test",
  97. now: () => new Date(1_700_000_000_000 + now++),
  98. store,
  99. });
  100. const result = await runtime.start({
  101. cwd: "/repo",
  102. task: "implement login",
  103. });
  104. expect(result.status).toBe("completed");
  105. expect(result.runId).toBe("wf_expert_test");
  106. expect(phases).toEqual([
  107. "clarify",
  108. "task_analysis",
  109. "arch_decompose",
  110. "env_setup",
  111. "meta_prompt",
  112. "exec",
  113. "final_critic",
  114. ]);
  115. expect(result.snapshot?.definitionId).toBe("expert");
  116. expect(result.snapshot?.definitionVersion).toBe("2");
  117. expect(result.snapshot?.strategy).toEqual(DEFAULT_EXPERT_WORKFLOW_STRATEGY);
  118. expect(result.snapshot?.phases.every((phase) => phase.status === "completed")).toBe(true);
  119. expect(result.snapshot?.activities.map((activity) => activity.sessionId)).toEqual([
  120. "sess-clarify",
  121. "sess-task_analysis",
  122. "sess-arch_decompose",
  123. "sess-env_setup",
  124. "sess-meta_prompt",
  125. "sess-exec",
  126. "sess-final_critic",
  127. ]);
  128. expect(store.artifacts.has("wf_expert_test/artifacts/01-clarify.md")).toBe(true);
  129. expect(store.artifacts.has("wf_expert_test/artifacts/06-exec.md")).toBe(true);
  130. expect(store.artifacts.has("wf_expert_test/report.md")).toBe(true);
  131. expect(store.events.map((event) => event.type)).toContain("run_completed");
  132. expect(store.events.map((event) => event.type)).toContain("node_started");
  133. expect(store.events.map((event) => event.type)).toContain("executor_completed");
  134. expect(store.events.map((event) => event.type)).toContain("critic_passed");
  135. expect(
  136. store.graphRecords.some(
  137. (record) =>
  138. record.recordType === "meta" &&
  139. record.definitionId === "expert" &&
  140. record.definitionVersion === "2",
  141. ),
  142. ).toBe(true);
  143. expect(
  144. store.graphRecords.some(
  145. (record) =>
  146. record.recordType === "op" && record.phase === "exec" && record.status === "completed",
  147. ),
  148. ).toBe(true);
  149. });
  150. it("runs from a generic workflow definition instead of hardcoded expert phases", async () => {
  151. const store = new MemoryWorkflowStore();
  152. const phases: string[] = [];
  153. const definition: WorkflowDefinition = {
  154. definitionId: "audit",
  155. definitionVersion: "1",
  156. description: "Small custom workflow used to verify definition-driven dispatch.",
  157. kind: "audit",
  158. phaseOrder: ["inspect", "fix", "verify", "complete"],
  159. phases: [
  160. {
  161. behavior: "agent",
  162. description: "Inspect the target.",
  163. phase: "inspect",
  164. title: "Inspect",
  165. },
  166. {
  167. artifactPath: "artifacts/fix.md",
  168. behavior: "scheduled_graph",
  169. description: "Apply the fix through the graph scheduler.",
  170. phase: "fix",
  171. title: "Fix",
  172. },
  173. {
  174. behavior: "critic",
  175. description: "Verify the fixed graph.",
  176. phase: "verify",
  177. title: "Verify",
  178. },
  179. {
  180. behavior: "complete",
  181. description: "Write the report.",
  182. phase: "complete",
  183. title: "Complete",
  184. },
  185. ],
  186. strategy: DEFAULT_EXPERT_WORKFLOW_STRATEGY,
  187. title: "Audit Workflow",
  188. };
  189. const runtime = new ExpertWorkflowRuntime({
  190. agentRunner: {
  191. run: async (input) => {
  192. phases.push(input.phase);
  193. return {
  194. response:
  195. input.phase === "verify"
  196. ? JSON.stringify({ reasoning: "custom workflow passed", verdict: "pass" })
  197. : `# ${input.phase}\n\nok`,
  198. sessionId: `sess-${input.phase}`,
  199. };
  200. },
  201. },
  202. createRunId: () => "wf_audit_test",
  203. definition,
  204. store,
  205. });
  206. const result = await runtime.start({
  207. cwd: "/repo",
  208. task: "audit configuration",
  209. });
  210. expect(result.status).toBe("completed");
  211. expect(result.snapshot?.kind).toBe("audit");
  212. expect(result.snapshot?.definitionId).toBe("audit");
  213. expect(result.snapshot?.definitionVersion).toBe("1");
  214. expect(result.snapshot?.phaseOrder).toEqual(["inspect", "fix", "verify", "complete"]);
  215. expect(phases).toEqual(["inspect", "fix", "verify"]);
  216. expect(store.events.every((event) => event.kind === "audit")).toBe(true);
  217. expect(store.artifacts.has("wf_audit_test/artifacts/fix.md")).toBe(true);
  218. });
  219. it("seeds scheduled exec nodes from a legacy architecture graph artifact", async () => {
  220. const store = new MemoryWorkflowStore();
  221. const phases: string[] = [];
  222. const execNodeIds: string[] = [];
  223. let now = 0;
  224. const runtime = new ExpertWorkflowRuntime({
  225. agentRunner: {
  226. run: async (input) => {
  227. phases.push(input.phase);
  228. if (input.phase === "arch_decompose") {
  229. return {
  230. response: [
  231. "```json",
  232. JSON.stringify({
  233. collections: [
  234. {
  235. explorable: false,
  236. goal: "Ship the API change",
  237. metric: "Unit tests pass",
  238. name: "implementation",
  239. nodeNames: ["implement_api", "validate_api"],
  240. },
  241. ],
  242. edges: [
  243. {
  244. interaction: "must_complete_before",
  245. source: "implement_api",
  246. target: "validate_api",
  247. type: "edge",
  248. },
  249. ],
  250. nodes: [
  251. {
  252. description: "Implement the API behavior.",
  253. name: "implement_api",
  254. prompt: "Update only the API boundary and keep validation scoped.",
  255. references: [],
  256. type: "node",
  257. },
  258. {
  259. description: "Validate the API behavior.",
  260. name: "validate_api",
  261. references: ["implement_api"],
  262. type: "node",
  263. },
  264. ],
  265. }),
  266. "```",
  267. ].join("\n"),
  268. sessionId: "sess-arch",
  269. };
  270. }
  271. if (input.phase === "exec") {
  272. const match = input.prompt.match(/Node id: ([^\n]+)/);
  273. execNodeIds.push(match?.[1] ?? "missing");
  274. if (match?.[1] === "implement_api") {
  275. expect(input.prompt).toContain(
  276. "Update only the API boundary and keep validation scoped.",
  277. );
  278. }
  279. }
  280. if (input.phase === "final_critic") {
  281. return {
  282. response: JSON.stringify({
  283. reasoning: "seeded graph passed",
  284. verdict: "pass",
  285. }),
  286. sessionId: "sess-final",
  287. };
  288. }
  289. return {
  290. response: `# ${input.phase}\n\nok`,
  291. sessionId: `sess-${input.phase}`,
  292. };
  293. },
  294. },
  295. createRunId: () => "wf_seeded_exec",
  296. now: () => new Date(1_700_000_000_000 + now++),
  297. store,
  298. });
  299. const result = await runtime.start({
  300. cwd: "/repo",
  301. task: "ship seeded exec graph",
  302. });
  303. expect(result.status).toBe("completed");
  304. expect(execNodeIds).toEqual(["implement_api", "validate_api"]);
  305. expect(phases.filter((phase) => phase === "exec")).toHaveLength(2);
  306. expect(result.snapshot?.graph.nodes.find((node) => node.id === "phase:exec")).toMatchObject({
  307. status: "completed",
  308. });
  309. expect(result.snapshot?.graph.nodes.find((node) => node.id === "implement_api")).toMatchObject({
  310. kind: "task",
  311. phase: "exec",
  312. status: "completed",
  313. });
  314. expect(result.snapshot?.graph.collections?.[0]).toMatchObject({
  315. collectionId: "implementation",
  316. nodeIds: ["implement_api", "validate_api"],
  317. phase: "exec",
  318. });
  319. expect(
  320. result.snapshot?.activities
  321. .filter((activity) => activity.phase === "exec")
  322. .map((activity) => activity.nodeId),
  323. ).toEqual(["implement_api", "validate_api"]);
  324. expect(
  325. store.graphRecords.some(
  326. (record) => record.recordType === "op" && record.type === "graph_seeded",
  327. ),
  328. ).toBe(true);
  329. expect(store.events.map((event) => event.type)).toContain("graph_expanded");
  330. });
  331. it("feeds meta prompt node instructions into scheduled exec nodes", async () => {
  332. const store = new MemoryWorkflowStore();
  333. const execPrompts: string[] = [];
  334. let now = 0;
  335. const runtime = new ExpertWorkflowRuntime({
  336. agentRunner: {
  337. run: async (input) => {
  338. if (input.phase === "arch_decompose") {
  339. return {
  340. response: JSON.stringify({
  341. nodes: [
  342. {
  343. description: "Implement the public API.",
  344. id: "implement_api",
  345. title: "Implement API",
  346. },
  347. ],
  348. }),
  349. sessionId: "sess-arch",
  350. };
  351. }
  352. if (input.phase === "meta_prompt") {
  353. return {
  354. response: JSON.stringify({
  355. nodePrompts: {
  356. implement_api: {
  357. description: "Implement only the public API boundary.",
  358. instructions: "Preserve existing validation behavior and add focused tests.",
  359. title: "Implement public API boundary",
  360. },
  361. },
  362. reasoning: "node instructions refined",
  363. }),
  364. sessionId: "sess-meta",
  365. };
  366. }
  367. if (input.phase === "exec") {
  368. execPrompts.push(input.prompt);
  369. }
  370. if (input.phase === "final_critic") {
  371. return {
  372. response: JSON.stringify({
  373. reasoning: "meta prompt fed scheduler",
  374. verdict: "pass",
  375. }),
  376. sessionId: "sess-final",
  377. };
  378. }
  379. return {
  380. response: `# ${input.phase}\n\nok`,
  381. sessionId: `sess-${input.phase}`,
  382. };
  383. },
  384. },
  385. createRunId: () => "wf_meta_prompt_nodes",
  386. now: () => new Date(1_700_000_000_000 + now++),
  387. store,
  388. });
  389. const result = await runtime.start({
  390. cwd: "/repo",
  391. task: "ship meta prompt node instructions",
  392. });
  393. expect(result.status).toBe("completed");
  394. expect(execPrompts).toHaveLength(1);
  395. expect(execPrompts[0]).toContain("Node: Implement public API boundary");
  396. expect(execPrompts[0]).toContain("Implement only the public API boundary.");
  397. expect(execPrompts[0]).toContain(
  398. "Preserve existing validation behavior and add focused tests.",
  399. );
  400. expect(result.snapshot?.graph.nodes.find((node) => node.id === "implement_api")).toMatchObject({
  401. description: "Implement only the public API boundary.",
  402. prompt: "Preserve existing validation behavior and add focused tests.",
  403. title: "Implement public API boundary",
  404. });
  405. expect(
  406. store.graphRecords.some(
  407. (record) => record.recordType === "op" && record.type === "node_prompts_updated",
  408. ),
  409. ).toBe(true);
  410. expect(
  411. store.events.some((event) => {
  412. const nodeIds = event.payload?.nodeIds;
  413. return (
  414. event.type === "graph_updated" &&
  415. Array.isArray(nodeIds) &&
  416. nodeIds.includes("implement_api")
  417. );
  418. }),
  419. ).toBe(true);
  420. });
  421. it("reopens critic-proposed nodes and reruns the generic scheduler", async () => {
  422. const store = new MemoryWorkflowStore();
  423. const phases: string[] = [];
  424. let criticCalls = 0;
  425. let now = 0;
  426. const runtime = new ExpertWorkflowRuntime({
  427. agentRunner: {
  428. run: async (input) => {
  429. phases.push(input.phase);
  430. if (input.phase === "final_critic") {
  431. criticCalls++;
  432. return {
  433. response:
  434. criticCalls === 1
  435. ? JSON.stringify({
  436. reasoning: "exec output missed validation",
  437. reopen_proposals: [
  438. {
  439. node_name: "phase:exec",
  440. reason: "rerun validation node",
  441. severity: "major",
  442. },
  443. ],
  444. verdict: "fail",
  445. })
  446. : JSON.stringify({
  447. reasoning: "fixed",
  448. verdict: "pass",
  449. }),
  450. sessionId: `sess-${input.phase}-${criticCalls}`,
  451. };
  452. }
  453. return {
  454. response: `# ${input.phase}\n\nok ${phases.length}`,
  455. sessionId: `sess-${input.phase}-${phases.length}`,
  456. };
  457. },
  458. },
  459. createRunId: () => "wf_reopen",
  460. now: () => new Date(1_700_000_000_000 + now++),
  461. store,
  462. });
  463. const result = await runtime.start({
  464. cwd: "/repo",
  465. task: "ship critic reopen",
  466. });
  467. expect(result.status).toBe("completed");
  468. expect(phases.filter((phase) => phase === "exec")).toHaveLength(2);
  469. expect(phases.filter((phase) => phase === "final_critic")).toHaveLength(2);
  470. expect(result.snapshot?.graph.nodes.find((node) => node.id === "phase:exec")).toMatchObject({
  471. reopenAttempts: 1,
  472. status: "completed",
  473. });
  474. expect(store.events.map((event) => event.type)).toEqual(
  475. expect.arrayContaining(["critic_failed", "node_reopened", "critic_passed"]),
  476. );
  477. expect(
  478. store.graphRecords.some(
  479. (record) =>
  480. record.recordType === "op" &&
  481. record.type === "reopen_node" &&
  482. record.nodeId === "phase:exec",
  483. ),
  484. ).toBe(true);
  485. });
  486. it("stops critic iteration when a fail verdict has no reopen proposal", async () => {
  487. const store = new MemoryWorkflowStore();
  488. const phases: string[] = [];
  489. let now = 0;
  490. const runtime = new ExpertWorkflowRuntime({
  491. agentRunner: {
  492. run: async (input) => {
  493. phases.push(input.phase);
  494. if (input.phase === "final_critic") {
  495. return {
  496. response: JSON.stringify({
  497. acceptanceGaps: ["manual review still needed"],
  498. reasoning: "cannot map issue to a node",
  499. reopenProposals: [],
  500. verdict: "fail",
  501. }),
  502. sessionId: "sess-final-critic",
  503. };
  504. }
  505. return {
  506. response: `# ${input.phase}\n\nok`,
  507. sessionId: `sess-${input.phase}`,
  508. };
  509. },
  510. },
  511. createRunId: () => "wf_empty_fail",
  512. now: () => new Date(1_700_000_000_000 + now++),
  513. store,
  514. });
  515. const result = await runtime.start({
  516. cwd: "/repo",
  517. task: "ship empty critic fail",
  518. });
  519. expect(result.status).toBe("completed");
  520. expect(phases.filter((phase) => phase === "exec")).toHaveLength(1);
  521. expect(phases.filter((phase) => phase === "final_critic")).toHaveLength(1);
  522. expect(store.events.map((event) => event.type)).toContain("critic_failed");
  523. expect(store.events.map((event) => event.type)).not.toContain("node_reopened");
  524. });
  525. it("pauses failed child sessions and retries with a new linked session", async () => {
  526. const store = new MemoryWorkflowStore();
  527. let calls = 0;
  528. const definition: WorkflowDefinition = {
  529. definitionId: "repairable",
  530. definitionVersion: "1",
  531. kind: "repairable",
  532. phaseOrder: ["work", "complete"],
  533. phases: [
  534. {
  535. behavior: "agent",
  536. description: "Do repairable work.",
  537. phase: "work",
  538. title: "Work",
  539. },
  540. {
  541. behavior: "complete",
  542. description: "Complete the workflow.",
  543. phase: "complete",
  544. title: "Complete",
  545. },
  546. ],
  547. strategy: DEFAULT_EXPERT_WORKFLOW_STRATEGY,
  548. title: "Repairable Workflow",
  549. };
  550. const runtime = new ExpertWorkflowRuntime({
  551. agentRunner: {
  552. run: async (input) => {
  553. calls++;
  554. await input.onChildSessionStarted?.({
  555. model: `test/model-${calls}`,
  556. sessionId: `sess-${calls}`,
  557. traceId: `trace-${calls}`,
  558. turnId: `turn-${calls}`,
  559. });
  560. if (calls === 1) {
  561. throw new Error("network down");
  562. }
  563. return {
  564. model: `test/model-${calls}`,
  565. response: "# work\n\nok",
  566. sessionId: `sess-${calls}`,
  567. traceId: `trace-${calls}`,
  568. turnId: `turn-${calls}`,
  569. };
  570. },
  571. },
  572. createRunId: () => "wf_repairable",
  573. definition,
  574. now: () => new Date(`2026-05-05T00:00:0${Math.min(calls, 9)}.000Z`),
  575. store,
  576. });
  577. const paused = await runtime.start({
  578. cwd: "/repo",
  579. task: "recover after network failure",
  580. });
  581. expect(paused.status).toBe("paused");
  582. expect(paused.snapshot?.failure).toMatchObject({
  583. activityId: expect.any(String),
  584. message: "network down",
  585. phase: "work",
  586. });
  587. expect(paused.snapshot?.recoveryActions.map((action) => action.action)).toEqual([
  588. "retry",
  589. "retry_with_current_model",
  590. "cancel",
  591. ]);
  592. expect(paused.snapshot?.sessionLinks).toEqual([
  593. expect.objectContaining({
  594. activityId: expect.any(String),
  595. attempt: 1,
  596. model: "test/model-1",
  597. phase: "work",
  598. sessionId: "sess-1",
  599. status: "failed",
  600. }),
  601. ]);
  602. const completed = await runtime.retry({
  603. cwd: "/repo",
  604. runId: "wf_repairable",
  605. });
  606. expect(completed.status).toBe("completed");
  607. expect(completed.snapshot?.failure).toBeUndefined();
  608. expect(completed.snapshot?.sessionLinks).toEqual([
  609. expect.objectContaining({
  610. attempt: 1,
  611. model: "test/model-1",
  612. sessionId: "sess-1",
  613. status: "failed",
  614. }),
  615. expect.objectContaining({
  616. attempt: 2,
  617. model: "test/model-2",
  618. sessionId: "sess-2",
  619. status: "completed",
  620. }),
  621. ]);
  622. expect(store.events.map((event) => event.type)).toEqual(
  623. expect.arrayContaining([
  624. "workflow_paused",
  625. "workflow_retry_started",
  626. "workflow_session_linked",
  627. ]),
  628. );
  629. });
  630. it("marks the latest run cancelled", async () => {
  631. const store = new MemoryWorkflowStore();
  632. const runtime = new ExpertWorkflowRuntime({
  633. agentRunner: {
  634. run: async () => ({
  635. response: "unused",
  636. sessionId: "sess-unused",
  637. }),
  638. },
  639. createRunId: () => "wf_cancel",
  640. now: () => new Date("2026-05-05T00:00:00Z"),
  641. store,
  642. });
  643. await store.writeSnapshot({
  644. activities: [
  645. {
  646. activityId: "act-exec",
  647. inputArtifactPaths: [],
  648. kind: "agent_session",
  649. nodeId: "phase:clarify",
  650. outputArtifactPaths: [],
  651. phase: "clarify",
  652. startedAt: "2026-05-05T00:00:00.000Z",
  653. status: "active",
  654. },
  655. ],
  656. artifacts: [],
  657. createdAt: "2026-05-05T00:00:00.000Z",
  658. cwd: "/repo",
  659. graph: {
  660. edges: [],
  661. nodes: [
  662. {
  663. dependsOn: [],
  664. id: "phase:clarify",
  665. kind: "phase",
  666. phase: "clarify",
  667. status: "active",
  668. title: "Clarify",
  669. },
  670. ],
  671. },
  672. kind: "expert",
  673. phaseOrder: ["clarify"],
  674. phases: [
  675. {
  676. activityId: "act-exec",
  677. phase: "clarify",
  678. status: "active",
  679. },
  680. ],
  681. runId: "wf_cancel",
  682. schemaVersion: 1,
  683. status: "running",
  684. strategy: DEFAULT_EXPERT_WORKFLOW_STRATEGY,
  685. task: "work",
  686. updatedAt: "2026-05-05T00:00:00.000Z",
  687. });
  688. const result = await runtime.cancel({
  689. cwd: "/repo",
  690. });
  691. expect(result.status).toBe("cancelled");
  692. const cancelled = await store.readRun("wf_cancel");
  693. expect(cancelled?.status).toBe("cancelled");
  694. expect(cancelled?.graph.nodes[0]?.status).toBe("cancelled");
  695. expect(cancelled?.phases[0]?.status).toBe("cancelled");
  696. expect(cancelled?.activities[0]?.status).toBe("cancelled");
  697. expect(store.graphRecords.some((record) => record.recordType === "op")).toBe(true);
  698. });
  699. });