workflow-scheduler-state.test.ts 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431
  1. import { describe, expect, it } from "vitest";
  2. import {
  3. ExpertWorkflowRunSnapshotSchema,
  4. WorkflowAgentCallInputSchema,
  5. WorkflowDefinitionSchema,
  6. WorkflowRunSnapshotSchema,
  7. WorkflowSchedulerStateSchema,
  8. WorkflowScriptMetaSchema,
  9. WorkflowStrategySchema,
  10. deriveWorkflowRunSchedulerState,
  11. deriveWorkflowSchedulerState,
  12. deriveWorkflowSessionLinks,
  13. } from "../src/workflow/index.js";
  14. import {
  15. WorkflowInputJsonSchema,
  16. WorkflowInputSchema,
  17. WorkflowOutputSchema,
  18. } from "../src/tools/workflow.js";
  19. describe("deriveWorkflowSchedulerState", () => {
  20. it("validates script workflow meta and agent call options", () => {
  21. const meta = WorkflowScriptMetaSchema.parse({
  22. description: "Review changed files",
  23. name: "review-changes",
  24. phases: [
  25. { title: "Review", detail: "Find candidate issues" },
  26. { title: "Verify", model: "lite" },
  27. ],
  28. whenToUse: "Use for code review.",
  29. });
  30. expect(meta.phases.map((phase) => phase.title)).toEqual(["Review", "Verify"]);
  31. expect(() =>
  32. WorkflowScriptMetaSchema.parse({
  33. description: "bad duplicate phases",
  34. name: "bad",
  35. phases: [{ title: "Review" }, { title: "Review" }],
  36. }),
  37. ).toThrow("Duplicate workflow phase title");
  38. const call = WorkflowAgentCallInputSchema.parse({
  39. opts: {
  40. agentType: "Reviewer",
  41. instructions: "Return raw findings.",
  42. isolation: "worktree",
  43. label: "review:diff",
  44. maxTurns: 8,
  45. model: "main",
  46. phase: "Review",
  47. schema: { type: "object" },
  48. skills: ["react"],
  49. systemPrompt: "Trusted workflows may set this through policy.",
  50. timeoutMs: 60_000,
  51. tools: ["Read"],
  52. },
  53. prompt: "Review current diff.",
  54. });
  55. expect(call.opts?.label).toBe("review:diff");
  56. });
  57. it("validates the model-facing Workflow tool schema", () => {
  58. expect(WorkflowInputSchema.parse({ script: "export const meta = {}" }).script).toContain(
  59. "meta",
  60. );
  61. expect(WorkflowInputSchema.parse({ name: "review", args: { target: "src" } }).name).toBe(
  62. "review",
  63. );
  64. expect(
  65. WorkflowInputSchema.parse({ scriptPath: ".zcode/workflows/review.workflow.js" }),
  66. ).toMatchObject({
  67. scriptPath: ".zcode/workflows/review.workflow.js",
  68. });
  69. expect(WorkflowInputSchema.parse({ resumeFromRunId: "wf_abc123" }).resumeFromRunId).toBe(
  70. "wf_abc123",
  71. );
  72. expect(() => WorkflowInputSchema.parse({})).toThrow("Workflow requires");
  73. expect(() => WorkflowInputSchema.parse({ resumeFromRunId: "workflow_old" })).toThrow();
  74. expect(
  75. (WorkflowInputJsonSchema.properties as Record<string, unknown>).scriptPath,
  76. ).toBeDefined();
  77. expect(
  78. WorkflowOutputSchema.parse({
  79. backgroundTaskId: "wf_abc123",
  80. response: "started",
  81. runId: "wf_abc123",
  82. status: "backgrounded",
  83. traceId: "trace",
  84. }).status,
  85. ).toBe("backgrounded");
  86. });
  87. it("validates workflow definitions with phase order and behavior metadata", () => {
  88. const definition = WorkflowDefinitionSchema.parse({
  89. definitionId: "audit",
  90. definitionVersion: "1",
  91. kind: "audit",
  92. phaseOrder: ["inspect", "fix", "complete"],
  93. phases: [
  94. {
  95. description: "Inspect the workspace.",
  96. phase: "inspect",
  97. title: "Inspect",
  98. },
  99. {
  100. behavior: "scheduled_graph",
  101. description: "Run graph nodes.",
  102. phase: "fix",
  103. title: "Fix",
  104. },
  105. {
  106. behavior: "complete",
  107. description: "Write the report.",
  108. phase: "complete",
  109. title: "Complete",
  110. },
  111. ],
  112. strategy: createStrategy(),
  113. title: "Audit Workflow",
  114. });
  115. expect(definition.phases.map((phase) => phase.behavior)).toEqual([
  116. "agent",
  117. "scheduled_graph",
  118. "complete",
  119. ]);
  120. expect(definition.definitionId).toBe("audit");
  121. expect(definition.definitionVersion).toBe("1");
  122. expect(() =>
  123. WorkflowDefinitionSchema.parse({
  124. ...definition,
  125. phaseOrder: ["inspect", "missing", "complete"],
  126. }),
  127. ).toThrow("unknown phase");
  128. });
  129. it("derives ready and blocked workflow graph nodes from dependencies", () => {
  130. const state = deriveWorkflowSchedulerState({
  131. edges: [{ from: "plan", to: "exec" }],
  132. nodes: [
  133. { dependsOn: [], id: "plan", kind: "phase", status: "completed", title: "Plan" },
  134. { dependsOn: ["plan"], id: "exec", kind: "phase", status: "pending", title: "Exec" },
  135. {
  136. dependsOn: ["missing"],
  137. id: "critic",
  138. kind: "phase",
  139. status: "pending",
  140. title: "Critic",
  141. },
  142. ],
  143. });
  144. expect(state.readyNodeIds).toEqual(["exec"]);
  145. expect(state.blockedNodes).toEqual([{ blockedBy: ["missing"], nodeId: "critic" }]);
  146. expect(state.counts).toMatchObject({
  147. blocked: 1,
  148. completed: 1,
  149. pending: 2,
  150. ready: 1,
  151. total: 3,
  152. });
  153. expect(WorkflowSchedulerStateSchema.parse(state).readyNodeIds).toEqual(["exec"]);
  154. });
  155. it("derives collection frontier and ready state", () => {
  156. const state = deriveWorkflowSchedulerState({
  157. collections: [
  158. {
  159. collectionId: "research",
  160. explorable: true,
  161. frontierTarget: 2,
  162. nodeIds: ["scan", "verify"],
  163. plannerRuns: 1,
  164. },
  165. ],
  166. edges: [{ from: "scan", to: "verify" }],
  167. nodes: [
  168. {
  169. collectionId: "research",
  170. dependsOn: [],
  171. id: "scan",
  172. kind: "task",
  173. status: "completed",
  174. title: "Scan",
  175. },
  176. {
  177. collectionId: "research",
  178. dependsOn: ["scan"],
  179. id: "verify",
  180. kind: "task",
  181. status: "pending",
  182. title: "Verify",
  183. },
  184. ],
  185. });
  186. expect(state.readyNodeIds).toEqual(["verify"]);
  187. expect(state.collectionStates).toEqual([
  188. expect.objectContaining({
  189. frontier: 1,
  190. frontierTarget: 2,
  191. plannerRuns: 1,
  192. readyNodeIds: ["verify"],
  193. }),
  194. ]);
  195. expect(state.nodes.find((entry) => entry.node.id === "verify")?.collectionIds).toEqual([
  196. "research",
  197. ]);
  198. });
  199. it("keeps workflow run contracts generic while preserving the expert alias", () => {
  200. const strategy = createStrategy();
  201. const snapshot = {
  202. activities: [],
  203. artifacts: [],
  204. createdAt: "2026-05-06T00:00:00.000Z",
  205. cwd: "/repo",
  206. graph: {
  207. edges: [],
  208. nodes: [{ dependsOn: [], id: "scan", kind: "task", status: "pending", title: "Scan" }],
  209. },
  210. kind: "audit",
  211. phaseOrder: ["scan"],
  212. phases: [{ phase: "scan", status: "pending" }],
  213. runId: "wf_audit_test",
  214. schemaVersion: 1,
  215. status: "running",
  216. strategy,
  217. task: "audit workflow contract",
  218. updatedAt: "2026-05-06T00:00:01.000Z",
  219. };
  220. expect(WorkflowRunSnapshotSchema.parse(snapshot).kind).toBe("audit");
  221. expect(ExpertWorkflowRunSnapshotSchema.parse(snapshot).kind).toBe("audit");
  222. });
  223. it("derives active child sessions from workflow run activities", () => {
  224. const snapshot = WorkflowRunSnapshotSchema.parse({
  225. activities: [
  226. {
  227. activityId: "act-running",
  228. inputArtifactPaths: [],
  229. kind: "agent_session",
  230. nodeId: "task:scan",
  231. outputArtifactPaths: [],
  232. phase: "exec",
  233. sessionId: "sess-child",
  234. startedAt: "2026-05-06T00:00:00.000Z",
  235. status: "active",
  236. traceId: "trace-child",
  237. },
  238. ],
  239. artifacts: [],
  240. createdAt: "2026-05-06T00:00:00.000Z",
  241. cwd: "/repo",
  242. graph: {
  243. edges: [],
  244. nodes: [
  245. {
  246. dependsOn: [],
  247. id: "task:scan",
  248. kind: "task",
  249. status: "active",
  250. title: "Scan",
  251. },
  252. ],
  253. },
  254. kind: "audit",
  255. phaseOrder: ["exec"],
  256. phases: [{ phase: "exec", status: "active" }],
  257. runId: "wf_scheduler_detail",
  258. schemaVersion: 1,
  259. status: "running",
  260. strategy: createStrategy(),
  261. task: "audit workflow state",
  262. updatedAt: "2026-05-06T00:00:01.000Z",
  263. });
  264. const state = deriveWorkflowRunSchedulerState(snapshot);
  265. expect(state.activeChildSessionIds).toEqual(["sess-child"]);
  266. expect(state.activeActivities).toEqual([
  267. {
  268. activityId: "act-running",
  269. nodeId: "task:scan",
  270. phase: "exec",
  271. sessionId: "sess-child",
  272. traceId: "trace-child",
  273. },
  274. ]);
  275. expect(WorkflowSchedulerStateSchema.parse(state).activeChildSessionIds).toEqual(["sess-child"]);
  276. });
  277. it("derives workflow session links from activity attempts", () => {
  278. const snapshot = WorkflowRunSnapshotSchema.parse({
  279. activities: [
  280. {
  281. activityId: "act-1",
  282. completedAt: "2026-05-06T00:00:02.000Z",
  283. inputArtifactPaths: [],
  284. kind: "agent_session",
  285. model: "zai/glm-main",
  286. nodeId: "task:scan",
  287. outputArtifactPaths: [],
  288. phase: "exec",
  289. sessionId: "sess-1",
  290. startedAt: "2026-05-06T00:00:00.000Z",
  291. status: "failed",
  292. },
  293. {
  294. activityId: "act-2",
  295. completedAt: "2026-05-06T00:00:04.000Z",
  296. inputArtifactPaths: [],
  297. kind: "agent_session",
  298. model: "deepseek/deepseek-v4-pro",
  299. nodeId: "task:scan",
  300. outputArtifactPaths: [],
  301. phase: "exec",
  302. sessionId: "sess-2",
  303. startedAt: "2026-05-06T00:00:03.000Z",
  304. status: "completed",
  305. },
  306. ],
  307. artifacts: [],
  308. createdAt: "2026-05-06T00:00:00.000Z",
  309. cwd: "/repo",
  310. graph: {
  311. edges: [],
  312. nodes: [
  313. {
  314. dependsOn: [],
  315. id: "task:scan",
  316. kind: "task",
  317. status: "completed",
  318. title: "Scan",
  319. },
  320. ],
  321. },
  322. kind: "audit",
  323. phaseOrder: ["exec"],
  324. phases: [{ phase: "exec", status: "completed" }],
  325. runId: "wf_links",
  326. schemaVersion: 1,
  327. status: "paused",
  328. strategy: createStrategy(),
  329. task: "audit workflow links",
  330. updatedAt: "2026-05-06T00:00:04.000Z",
  331. });
  332. expect(snapshot.sessionLinks).toEqual([]);
  333. expect(deriveWorkflowSessionLinks(snapshot)).toEqual([
  334. expect.objectContaining({
  335. activityId: "act-1",
  336. attempt: 1,
  337. model: "zai/glm-main",
  338. sessionId: "sess-1",
  339. status: "failed",
  340. }),
  341. expect.objectContaining({
  342. activityId: "act-2",
  343. attempt: 2,
  344. model: "deepseek/deepseek-v4-pro",
  345. sessionId: "sess-2",
  346. status: "completed",
  347. }),
  348. ]);
  349. });
  350. it("derives collection frontier state for ACP workflow debugging", () => {
  351. const state = deriveWorkflowSchedulerState({
  352. collections: [
  353. {
  354. collectionId: "research",
  355. explorable: true,
  356. frontierTarget: 2,
  357. nodeIds: ["scan", "inspect"],
  358. plannerRuns: 1,
  359. },
  360. ],
  361. edges: [{ from: "scan", to: "inspect" }],
  362. nodes: [
  363. {
  364. collectionId: "research",
  365. dependsOn: [],
  366. id: "scan",
  367. kind: "task",
  368. status: "completed",
  369. title: "Scan",
  370. },
  371. {
  372. collectionId: "research",
  373. dependsOn: ["scan"],
  374. id: "inspect",
  375. kind: "task",
  376. status: "pending",
  377. title: "Inspect",
  378. },
  379. ],
  380. });
  381. expect(state.collectionStates).toEqual([
  382. expect.objectContaining({
  383. activeNodeIds: [],
  384. completedNodeIds: ["scan"],
  385. frontier: 1,
  386. frontierTarget: 2,
  387. pendingNodeIds: ["inspect"],
  388. plannerRuns: 1,
  389. readyNodeIds: ["inspect"],
  390. status: "active",
  391. }),
  392. ]);
  393. expect(state.nodes.find((node) => node.node.id === "inspect")?.collectionIds).toEqual([
  394. "research",
  395. ]);
  396. expect(WorkflowSchedulerStateSchema.parse(state).collectionStates).toHaveLength(1);
  397. });
  398. });
  399. function createStrategy() {
  400. return WorkflowStrategySchema.parse({
  401. clarify: { confidenceThreshold: 0.8, maxRounds: 3, minRounds: 1 },
  402. executor: {
  403. drainingChangeHours: 1,
  404. frontierTarget: 3,
  405. maxConcurrentLoops: 2,
  406. maxConsecutiveErrors: 3,
  407. maxPlannerRuns: 10,
  408. },
  409. finalCritic: { maxIterations: 3 },
  410. reactLoop: { maxRounds: 30 },
  411. });
  412. }