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).toHaveLength(7);
  120. expect(result.snapshot?.activities.map((activity) => activity.sessionId)).toEqual([
  121. "sess-clarify",
  122. "sess-task_analysis",
  123. "sess-arch_decompose",
  124. "sess-env_setup",
  125. "sess-meta_prompt",
  126. "sess-exec",
  127. "sess-final_critic",
  128. ]);
  129. expect(store.artifacts.has("wf_expert_test/artifacts/01-clarify.md")).toBe(true);
  130. expect(store.artifacts.has("wf_expert_test/artifacts/06-exec.md")).toBe(true);
  131. expect(store.artifacts.has("wf_expert_test/report.md")).toBe(true);
  132. expect(store.events.map((event) => event.type)).toContain("run_completed");
  133. expect(store.events.map((event) => event.type)).toContain("node_started");
  134. expect(store.events.map((event) => event.type)).toContain("executor_completed");
  135. expect(store.events.map((event) => event.type)).toContain("critic_passed");
  136. expect(store.graphRecords.some((record) => record.recordType === "meta")).toBe(true);
  137. expect(
  138. store.graphRecords.some(
  139. (record) =>
  140. record.recordType === "meta" &&
  141. record.definitionId === "expert" &&
  142. record.definitionVersion === "2",
  143. ),
  144. ).toBe(true);
  145. expect(
  146. store.graphRecords.some(
  147. (record) =>
  148. record.recordType === "op" && record.phase === "exec" && record.status === "completed",
  149. ),
  150. ).toBe(true);
  151. });
  152. it("runs from a generic workflow definition instead of hardcoded expert phases", async () => {
  153. const store = new MemoryWorkflowStore();
  154. const phases: string[] = [];
  155. const definition: WorkflowDefinition = {
  156. definitionId: "audit",
  157. definitionVersion: "1",
  158. description: "Small custom workflow used to verify definition-driven dispatch.",
  159. kind: "audit",
  160. phaseOrder: ["inspect", "fix", "verify", "complete"],
  161. phases: [
  162. {
  163. behavior: "agent",
  164. description: "Inspect the target.",
  165. phase: "inspect",
  166. title: "Inspect",
  167. },
  168. {
  169. artifactPath: "artifacts/fix.md",
  170. behavior: "scheduled_graph",
  171. description: "Apply the fix through the graph scheduler.",
  172. phase: "fix",
  173. title: "Fix",
  174. },
  175. {
  176. behavior: "critic",
  177. description: "Verify the fixed graph.",
  178. phase: "verify",
  179. title: "Verify",
  180. },
  181. {
  182. behavior: "complete",
  183. description: "Write the report.",
  184. phase: "complete",
  185. title: "Complete",
  186. },
  187. ],
  188. strategy: DEFAULT_EXPERT_WORKFLOW_STRATEGY,
  189. title: "Audit Workflow",
  190. };
  191. const runtime = new ExpertWorkflowRuntime({
  192. agentRunner: {
  193. run: async (input) => {
  194. phases.push(input.phase);
  195. return {
  196. response:
  197. input.phase === "verify"
  198. ? JSON.stringify({ reasoning: "custom workflow passed", verdict: "pass" })
  199. : `# ${input.phase}\n\nok`,
  200. sessionId: `sess-${input.phase}`,
  201. };
  202. },
  203. },
  204. createRunId: () => "wf_audit_test",
  205. definition,
  206. store,
  207. });
  208. const result = await runtime.start({
  209. cwd: "/repo",
  210. task: "audit configuration",
  211. });
  212. expect(result.status).toBe("completed");
  213. expect(result.snapshot?.kind).toBe("audit");
  214. expect(result.snapshot?.definitionId).toBe("audit");
  215. expect(result.snapshot?.definitionVersion).toBe("1");
  216. expect(result.snapshot?.phaseOrder).toEqual(["inspect", "fix", "verify", "complete"]);
  217. expect(phases).toEqual(["inspect", "fix", "verify"]);
  218. expect(store.events.every((event) => event.kind === "audit")).toBe(true);
  219. expect(store.artifacts.has("wf_audit_test/artifacts/fix.md")).toBe(true);
  220. });
  221. it("seeds scheduled exec nodes from a legacy architecture graph artifact", async () => {
  222. const store = new MemoryWorkflowStore();
  223. const phases: string[] = [];
  224. const execNodeIds: string[] = [];
  225. let now = 0;
  226. const runtime = new ExpertWorkflowRuntime({
  227. agentRunner: {
  228. run: async (input) => {
  229. phases.push(input.phase);
  230. if (input.phase === "arch_decompose") {
  231. return {
  232. response: [
  233. "```json",
  234. JSON.stringify({
  235. collections: [
  236. {
  237. explorable: false,
  238. goal: "Ship the API change",
  239. metric: "Unit tests pass",
  240. name: "implementation",
  241. nodeNames: ["implement_api", "validate_api"],
  242. },
  243. ],
  244. edges: [
  245. {
  246. interaction: "must_complete_before",
  247. source: "implement_api",
  248. target: "validate_api",
  249. type: "edge",
  250. },
  251. ],
  252. nodes: [
  253. {
  254. description: "Implement the API behavior.",
  255. name: "implement_api",
  256. prompt: "Update only the API boundary and keep validation scoped.",
  257. references: [],
  258. type: "node",
  259. },
  260. {
  261. description: "Validate the API behavior.",
  262. name: "validate_api",
  263. references: ["implement_api"],
  264. type: "node",
  265. },
  266. ],
  267. }),
  268. "```",
  269. ].join("\n"),
  270. sessionId: "sess-arch",
  271. };
  272. }
  273. if (input.phase === "exec") {
  274. const match = input.prompt.match(/Node id: ([^\n]+)/);
  275. execNodeIds.push(match?.[1] ?? "missing");
  276. if (match?.[1] === "implement_api") {
  277. expect(input.prompt).toContain(
  278. "Update only the API boundary and keep validation scoped.",
  279. );
  280. }
  281. }
  282. if (input.phase === "final_critic") {
  283. return {
  284. response: JSON.stringify({
  285. reasoning: "seeded graph passed",
  286. verdict: "pass",
  287. }),
  288. sessionId: "sess-final",
  289. };
  290. }
  291. return {
  292. response: `# ${input.phase}\n\nok`,
  293. sessionId: `sess-${input.phase}`,
  294. };
  295. },
  296. },
  297. createRunId: () => "wf_seeded_exec",
  298. now: () => new Date(1_700_000_000_000 + now++),
  299. store,
  300. });
  301. const result = await runtime.start({
  302. cwd: "/repo",
  303. task: "ship seeded exec graph",
  304. });
  305. expect(result.status).toBe("completed");
  306. expect(execNodeIds).toEqual(["implement_api", "validate_api"]);
  307. expect(phases.filter((phase) => phase === "exec")).toHaveLength(2);
  308. expect(result.snapshot?.graph.nodes.find((node) => node.id === "phase:exec")).toMatchObject({
  309. status: "completed",
  310. });
  311. expect(result.snapshot?.graph.nodes.find((node) => node.id === "implement_api")).toMatchObject({
  312. kind: "task",
  313. phase: "exec",
  314. status: "completed",
  315. });
  316. expect(result.snapshot?.graph.collections?.[0]).toMatchObject({
  317. collectionId: "implementation",
  318. nodeIds: ["implement_api", "validate_api"],
  319. phase: "exec",
  320. });
  321. expect(
  322. result.snapshot?.activities
  323. .filter((activity) => activity.phase === "exec")
  324. .map((activity) => activity.nodeId),
  325. ).toEqual(["implement_api", "validate_api"]);
  326. expect(
  327. store.graphRecords.some(
  328. (record) => record.recordType === "op" && record.type === "graph_seeded",
  329. ),
  330. ).toBe(true);
  331. expect(store.events.map((event) => event.type)).toContain("graph_expanded");
  332. });
  333. it("feeds meta prompt node instructions into scheduled exec nodes", async () => {
  334. const store = new MemoryWorkflowStore();
  335. const execPrompts: string[] = [];
  336. let now = 0;
  337. const runtime = new ExpertWorkflowRuntime({
  338. agentRunner: {
  339. run: async (input) => {
  340. if (input.phase === "arch_decompose") {
  341. return {
  342. response: JSON.stringify({
  343. nodes: [
  344. {
  345. description: "Implement the public API.",
  346. id: "implement_api",
  347. title: "Implement API",
  348. },
  349. ],
  350. }),
  351. sessionId: "sess-arch",
  352. };
  353. }
  354. if (input.phase === "meta_prompt") {
  355. return {
  356. response: JSON.stringify({
  357. nodePrompts: {
  358. implement_api: {
  359. description: "Implement only the public API boundary.",
  360. instructions: "Preserve existing validation behavior and add focused tests.",
  361. title: "Implement public API boundary",
  362. },
  363. },
  364. reasoning: "node instructions refined",
  365. }),
  366. sessionId: "sess-meta",
  367. };
  368. }
  369. if (input.phase === "exec") {
  370. execPrompts.push(input.prompt);
  371. }
  372. if (input.phase === "final_critic") {
  373. return {
  374. response: JSON.stringify({
  375. reasoning: "meta prompt fed scheduler",
  376. verdict: "pass",
  377. }),
  378. sessionId: "sess-final",
  379. };
  380. }
  381. return {
  382. response: `# ${input.phase}\n\nok`,
  383. sessionId: `sess-${input.phase}`,
  384. };
  385. },
  386. },
  387. createRunId: () => "wf_meta_prompt_nodes",
  388. now: () => new Date(1_700_000_000_000 + now++),
  389. store,
  390. });
  391. const result = await runtime.start({
  392. cwd: "/repo",
  393. task: "ship meta prompt node instructions",
  394. });
  395. expect(result.status).toBe("completed");
  396. expect(execPrompts).toHaveLength(1);
  397. expect(execPrompts[0]).toContain("Node: Implement public API boundary");
  398. expect(execPrompts[0]).toContain("Implement only the public API boundary.");
  399. expect(execPrompts[0]).toContain("Preserve existing validation behavior and add focused tests.");
  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. });