create-workflow.test.ts 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854
  1. import { describe, expect, it } from "vitest";
  2. import {
  3. CREATE_WORKFLOW_GRAPH_MAX_HANDOFF_TYPES,
  4. CREATE_WORKFLOW_GRAPH_MAX_HANDOFFS,
  5. CREATE_WORKFLOW_GRAPH_MAX_PARTICIPANTS,
  6. CREATE_WORKFLOW_GRAPH_MAX_PHASE_EDGES,
  7. CREATE_WORKFLOW_GRAPH_MAX_PHASES,
  8. CREATE_WORKFLOW_GRAPH_MAX_STEPS,
  9. CreateWorkflowCausalityGraphSchema,
  10. CreateWorkflowHandoffSchema,
  11. CreateWorkflowParticipantSchema,
  12. CreateWorkflowInputJsonSchema,
  13. CreateWorkflowInputSchema,
  14. CreateWorkflowOutputJsonSchema,
  15. CreateWorkflowOutputSchema,
  16. createWorkflowPhaseAlongside,
  17. createWorkflowPhaseNames,
  18. type CreateWorkflowOutput,
  19. } from "../src/tools/create-workflow.js";
  20. import type { BackgroundResultOriginMeta } from "../src/events/session.events.js";
  21. import type {
  22. DynamicWorkflowRunPort,
  23. DynamicWorkflowRunSubmitRequest,
  24. DynamicWorkflowRunEvent,
  25. } from "../src/interfaces/dynamic-workflow-run.port.js";
  26. import type { WorkflowTaskSnapshot } from "../src/interfaces/workflow.port.js";
  27. import { createTraceId } from "../src/interfaces/shared.js";
  28. const DIAGNOSTICS_ONLY: CreateWorkflowOutput = {
  29. diagnostics: [{ code: 2322, column: 7, line: 1, message: "Type error" }],
  30. ok: false,
  31. response: "The script does not typecheck.",
  32. };
  33. describe("CreateWorkflowOutputSchema — backgrounded run", () => {
  34. it("keeps accepting the diagnostics-only result unchanged", () => {
  35. // 坏脚本路径完全不变:handler 直接回诊断,不启动、不建 run,因此两个新字段缺席。
  36. const parsed = CreateWorkflowOutputSchema.parse(DIAGNOSTICS_ONLY);
  37. expect(parsed).toEqual(DIAGNOSTICS_ONLY);
  38. expect("status" in parsed).toBe(false);
  39. expect("backgroundTaskId" in parsed).toBe(false);
  40. });
  41. it("accepts status + backgroundTaskId when a run was started", () => {
  42. const output = {
  43. diagnostics: [],
  44. ok: true,
  45. response: "Workflow started.",
  46. status: "backgrounded" as const,
  47. backgroundTaskId: "dwf_run_01H",
  48. };
  49. expect(CreateWorkflowOutputSchema.parse(output)).toEqual(output);
  50. });
  51. it("admits only the backgrounded literal as a status", () => {
  52. // status 是"这次调用启动了一个后台 run"的唯一信号,不是通用状态字段:
  53. // running/completed 等值必须被拒,否则 executor 侧的分派要靠猜。
  54. for (const status of ["running", "completed", "failed", ""]) {
  55. expect(CreateWorkflowOutputSchema.safeParse({ ...DIAGNOSTICS_ONLY, status }).success).toBe(
  56. false,
  57. );
  58. }
  59. });
  60. it("requires backgroundTaskId to be a non-empty string", () => {
  61. for (const backgroundTaskId of ["", 42, null]) {
  62. expect(
  63. CreateWorkflowOutputSchema.safeParse({ ...DIAGNOSTICS_ONLY, backgroundTaskId }).success,
  64. ).toBe(false);
  65. }
  66. });
  67. it("stays strict about unknown keys", () => {
  68. // .strict() 的意义就是形状变更必须是一次显式的 schema 提交,而不是经 raw 夹带。
  69. expect(
  70. CreateWorkflowOutputSchema.safeParse({ ...DIAGNOSTICS_ONLY, runId: "smuggled" }).success,
  71. ).toBe(false);
  72. });
  73. it("carries both new fields into the model-facing JSON schema", () => {
  74. const properties = (CreateWorkflowOutputJsonSchema as { properties?: Record<string, unknown> })
  75. .properties;
  76. expect(Object.keys(properties ?? {})).toEqual(
  77. expect.arrayContaining(["diagnostics", "ok", "response", "status", "backgroundTaskId"]),
  78. );
  79. // 两个字段都是可选的:required 只保留今天的三个。
  80. const required = (CreateWorkflowOutputJsonSchema as { required?: string[] }).required ?? [];
  81. expect(required).not.toContain("status");
  82. expect(required).not.toContain("backgroundTaskId");
  83. });
  84. });
  85. // docs/dynamic-workflow/launch.md「The `CreateWorkflow` tool」:修订是 AmendWorkflow 的工作,CreateWorkflow
  86. // 没有前驱字段——`.strict()` 让旧写法 `resume_from` 成为可见的 schema 错误,而不是被静默忽略后变成
  87. // 一次全价重跑。
  88. describe("CreateWorkflowInputSchema — no predecessor field", () => {
  89. const SCRIPT = 'return await agent("a").ask<string>("go");';
  90. it("rejects resume_from in every spelling", () => {
  91. for (const key of ["resume_from", "resumeFrom", "run_id"]) {
  92. expect(CreateWorkflowInputSchema.safeParse({ script: SCRIPT, [key]: "dwfrun-prev" }).success).toBe(
  93. false,
  94. );
  95. }
  96. });
  97. it("does not project a predecessor field into the model-facing JSON schema", () => {
  98. const properties = (CreateWorkflowInputJsonSchema as { properties?: Record<string, unknown> })
  99. .properties;
  100. expect(Object.keys(properties ?? {})).toEqual(
  101. expect.arrayContaining(["name", "script", "saved", "max_concurrency", "subagent_model"]),
  102. );
  103. expect(properties).not.toHaveProperty("resume_from");
  104. });
  105. // 子代理选型(docs/dynamic-workflow/launch.md):模型面收一个宽松的字符串,规范化留给
  106. // resolveInput。空白串是错——它会让「设了但没说清」与「没设」在确认窗上长得一样。
  107. it("takes subagent_model as an optional trimmed non-empty string", () => {
  108. expect(CreateWorkflowInputSchema.parse({ script: SCRIPT })).toEqual({ script: SCRIPT });
  109. expect(
  110. CreateWorkflowInputSchema.parse({ script: SCRIPT, subagent_model: " glm-5.3-flash " }),
  111. ).toEqual({ script: SCRIPT, subagent_model: "glm-5.3-flash" });
  112. expect(
  113. CreateWorkflowInputSchema.safeParse({ script: SCRIPT, subagent_model: " " }).success,
  114. ).toBe(false);
  115. expect(
  116. CreateWorkflowInputSchema.safeParse({ script: SCRIPT, subagent_model: null }).success,
  117. ).toBe(false);
  118. });
  119. });
  120. // docs/dynamic-workflow/launch.md「Script files」:第三条来源 `path` 与只跟它走的顶层 `args`,
  121. // 外加两处回填事实。XOR 与「args 只跟 path」都住在 validateInput——归一化之后 `script` 与
  122. // `path` / `saved` 同时在场是合法执行态,schema 必须容得下它。
  123. describe("CreateWorkflowInputSchema — the file sources", () => {
  124. const SCRIPT = 'return await agent("a").ask<string>("go");';
  125. it("lists `path` and `args` for the model and hides the resolved facts", () => {
  126. const properties = (CreateWorkflowInputJsonSchema as { properties?: Record<string, unknown> })
  127. .properties;
  128. expect(Object.keys(properties ?? {}).sort()).toEqual([
  129. "args",
  130. "max_concurrency",
  131. "name",
  132. "path",
  133. "saved",
  134. "script",
  135. "subagent_model",
  136. ]);
  137. // 回填项与 `AmendWorkflow.predecessor` 同一姿态:运行时认它们,模型面不列它们。
  138. expect(properties).not.toHaveProperty("script_line_offset");
  139. const saved = (properties?.saved as { properties?: Record<string, unknown> } | undefined)
  140. ?.properties;
  141. expect(saved).not.toHaveProperty("draft");
  142. });
  143. it("accepts the normalized shape a `path` call resolves to", () => {
  144. const resolved = {
  145. script: SCRIPT,
  146. path: "/repo/.zcode/workflow-drafts/x.dwf.ts",
  147. args: { depth: 3 },
  148. script_line_offset: 5,
  149. };
  150. expect(CreateWorkflowInputSchema.parse(resolved)).toEqual(resolved);
  151. expect(CreateWorkflowInputSchema.safeParse({ path: "" }).success).toBe(false);
  152. expect(CreateWorkflowInputSchema.safeParse({ path: "a", script_line_offset: -1 }).success).toBe(
  153. false,
  154. );
  155. });
  156. it("accepts the normalized shape a `saved` call resolves to, draft included", () => {
  157. const resolved = {
  158. name: "nightly",
  159. script: SCRIPT,
  160. saved: {
  161. name: "nightly",
  162. args: { depth: 3 },
  163. path: "/repo/.zcode/workflows/nightly.dwf.ts",
  164. scope: "project" as const,
  165. draft: "/repo/.zcode/workflow-drafts/nightly.dwf.ts",
  166. },
  167. script_line_offset: 3,
  168. };
  169. expect(CreateWorkflowInputSchema.parse(resolved)).toEqual(resolved);
  170. });
  171. });
  172. describe("BackgroundResultOriginMeta", () => {
  173. it("admits workflow as a background source", () => {
  174. // 完成通知复用整条后台管线,所以 workflow run 的终态要能标注来源。
  175. const meta: BackgroundResultOriginMeta = {
  176. backgroundSource: "workflow",
  177. workId: "dwf_run_01H",
  178. title: "Review the codebase",
  179. };
  180. expect(meta.backgroundSource).toBe("workflow");
  181. });
  182. });
  183. describe("DynamicWorkflowRunPort", () => {
  184. it("is implementable over JSON-able shapes alone", () => {
  185. // 端口只承载 JSON 形状:引擎的词汇表(RunEvent / StoredEvent / RunStatus)留在领域包里,
  186. // contracts 绝不 import dynamic-workflow。这个 fake 就是那条规则的可执行证明。
  187. const events: DynamicWorkflowRunEvent[] = [
  188. { sequence: 0, type: "run-started", payload: { runId: "run_1" } },
  189. { sequence: 1, type: "node-settled", payload: { instance: { siteId: "ask#1", ordinal: 1 } } },
  190. ];
  191. const snapshot: WorkflowTaskSnapshot = {
  192. runId: "run_1",
  193. startedAt: new Date(0),
  194. status: "running",
  195. taskId: "run_1",
  196. };
  197. let cancelled = false;
  198. const port: DynamicWorkflowRunPort = {
  199. submit: (request: DynamicWorkflowRunSubmitRequest) =>
  200. Promise.resolve({ ok: true, runId: `run_${request.scriptText.length}` }),
  201. getTask: () => Promise.resolve(snapshot),
  202. waitForTask: () =>
  203. Promise.resolve({ ...snapshot, status: "completed", output: { artifact: 1 } }),
  204. cancel: () => {
  205. cancelled = true;
  206. return Promise.resolve(true);
  207. },
  208. listEvents: (_runId, opts) =>
  209. Promise.resolve({
  210. events: events.filter(
  211. (e) => opts.afterSequence === undefined || e.sequence > opts.afterSequence,
  212. ),
  213. hasMore: false,
  214. }),
  215. };
  216. return Promise.all([
  217. port.submit({
  218. scriptText: "return 1;",
  219. cwd: "/tmp",
  220. parentSessionId: "sess_p",
  221. trace: { traceId: createTraceId() },
  222. }),
  223. port.listEvents("run_1", { afterSequence: 0, limit: 10 }),
  224. port.cancel("run_1"),
  225. ]).then(([submitted, page]) => {
  226. expect(submitted.ok === true && submitted.runId).toBe("run_9");
  227. expect(page.events.map((e) => e.sequence)).toEqual([1]);
  228. expect(cancelled).toBe(true);
  229. });
  230. });
  231. });
  232. describe("CreateWorkflowCausalityGraphSchema — withdrawn refined display names", () => {
  233. // docs/dynamic-workflow/presentation.md:模型精炼整条撤回,
  234. // `refinedLabel` / `refinedName` 从四层 schema 删除。带它们的旧持久化载荷在进入严格
  235. // 解析前由 tool-result-metadata 剥离;schema 本身对它们一无所知,.strict() 直接拒绝。
  236. const graph = {
  237. steps: [
  238. {
  239. id: "ask#1",
  240. kind: "ask" as const,
  241. label: "ask",
  242. labelPattern: { head: "研究员" },
  243. lane: "actor#1",
  244. },
  245. ],
  246. lanes: [{ id: "actor#1", name: "planner" }],
  247. participants: [
  248. { id: "unphased:actor#1", phase: "unphased", lane: "actor#1", steps: ["ask#1"] },
  249. ],
  250. handoffs: [],
  251. };
  252. it("keeps accepting plain graphs byte-for-byte", () => {
  253. expect(CreateWorkflowCausalityGraphSchema.parse(graph)).toEqual(graph);
  254. });
  255. it("rejects refinedLabel on steps and refinedName on lanes", () => {
  256. expect(
  257. CreateWorkflowCausalityGraphSchema.safeParse({
  258. ...graph,
  259. steps: [{ ...graph.steps[0], refinedLabel: "调研市场行情" }],
  260. }).success,
  261. ).toBe(false);
  262. expect(
  263. CreateWorkflowCausalityGraphSchema.safeParse({
  264. ...graph,
  265. lanes: [{ ...graph.lanes[0], refinedName: "规划者" }],
  266. }).success,
  267. ).toBe(false);
  268. });
  269. });
  270. describe("CreateWorkflowCausalityGraphSchema — phase vocabulary", () => {
  271. // docs/dynamic-workflow/presentation.md:phases / phaseEdges / exits / Step.phase 是
  272. // **全有或全无**的一套词汇表,全部 additive 可选——零标记脚本的载荷照常通过 .strict()。
  273. const unphasedGraph = {
  274. steps: [
  275. {
  276. id: "world-read#1",
  277. kind: "world-read" as const,
  278. label: "glob *.ts",
  279. lane: "workspace",
  280. phase: "unphased",
  281. },
  282. {
  283. id: "ask#1",
  284. kind: "ask" as const,
  285. label: "planner",
  286. lane: "actor#1",
  287. phase: "phase#1",
  288. },
  289. ],
  290. lanes: [{ id: "workspace" }, { id: "actor#1", name: "planner" }],
  291. // 第二层:每阶段一张参与者卡,交接边在卡之间(docs/dynamic-workflow/presentation.md)。
  292. participants: [
  293. { id: "unphased:workspace", phase: "unphased", lane: "workspace", steps: ["world-read#1"] },
  294. { id: "phase#1:actor#1", phase: "phase#1", lane: "actor#1", steps: ["ask#1"] },
  295. ],
  296. handoffs: [{ from: "unphased:workspace", to: "phase#1:actor#1" }],
  297. // `unphased` 排在最前且**无 name**(UI 本地化);作者的阶段带 name 与首个标记的位置。
  298. phases: [{ id: "unphased" }, { id: "phase#1", name: "preflight", line: 3, column: 1 }],
  299. phaseEdges: [{ from: "unphased", to: "phase#1" }],
  300. // 控制流可在其后正常完成的阶段(阶段视图的「阶段 → 返回物」箭头)。
  301. exits: ["phase#1"],
  302. };
  303. it("round-trips the four fields together", () => {
  304. expect(CreateWorkflowCausalityGraphSchema.parse(unphasedGraph)).toEqual(unphasedGraph);
  305. });
  306. it("keeps accepting a payload with no phase field at all", () => {
  307. // 零标记脚本 = 词汇表整体缺席的载荷,逐字节通过。
  308. const legacy = {
  309. steps: [{ ...unphasedGraph.steps[1]!, phase: undefined }],
  310. lanes: unphasedGraph.lanes,
  311. // 无阶段词汇时参与者的 phase 恒为 `unphased`(此时 `phases` 缺席)。
  312. participants: [
  313. { id: "unphased:actor#1", phase: "unphased", lane: "actor#1", steps: ["ask#1"] },
  314. ],
  315. handoffs: [],
  316. };
  317. delete (legacy.steps[0] as { phase?: string }).phase;
  318. const parsed = CreateWorkflowCausalityGraphSchema.parse(legacy);
  319. expect(parsed).toEqual(legacy);
  320. expect("phases" in parsed).toBe(false);
  321. expect("phaseEdges" in parsed).toBe(false);
  322. expect("exits" in parsed).toBe(false);
  323. expect("phase" in parsed.steps[0]!).toBe(false);
  324. });
  325. it("represents an empty-but-present vocabulary", () => {
  326. // 有标记却零 step 的脚本会产出在场但空的三个数组。UI 的视图切换是「在场**且非空**」,
  327. // 所以空词汇表必须是**可表示**的——数组只有 .max() 上界,绝不能加 .min(1),否则
  328. // handler 那条诚实的直通路径会在契约边界上被打回。`exits` 在组内也可以是空数组
  329. // (脚本没有正常完成路径,例如无条件 throw)。
  330. const empty = {
  331. steps: [],
  332. lanes: [],
  333. participants: [],
  334. handoffs: [],
  335. phases: [],
  336. phaseEdges: [],
  337. exits: [],
  338. };
  339. const parsed = CreateWorkflowCausalityGraphSchema.parse(empty);
  340. expect(parsed).toEqual(empty);
  341. expect(parsed.phases).toEqual([]);
  342. expect(parsed.phaseEdges).toEqual([]);
  343. expect(parsed.exits).toEqual([]);
  344. });
  345. it("round-trips exits and bounds them at 32 phase ids", () => {
  346. // exits 与阶段表同一上界:它是阶段 id 的子集,最多与阶段表一样长。
  347. const exits = Array.from(
  348. { length: CREATE_WORKFLOW_GRAPH_MAX_PHASES },
  349. (_, i) => `phase#${i + 1}`,
  350. );
  351. const parsed = CreateWorkflowCausalityGraphSchema.parse({ ...unphasedGraph, exits });
  352. expect(parsed.exits).toEqual(exits);
  353. expect(
  354. CreateWorkflowCausalityGraphSchema.safeParse({
  355. ...unphasedGraph,
  356. exits: [...exits, "phase#33"],
  357. }).success,
  358. ).toBe(false);
  359. // 元素走同一组 id 上界。
  360. for (const bad of [[""], ["p".repeat(65)], [42]]) {
  361. expect(
  362. CreateWorkflowCausalityGraphSchema.safeParse({ ...unphasedGraph, exits: bad }).success,
  363. ).toBe(false);
  364. }
  365. });
  366. it("rejects the withdrawn refinedName on phases", () => {
  367. expect(
  368. CreateWorkflowCausalityGraphSchema.safeParse({
  369. ...unphasedGraph,
  370. phases: [
  371. unphasedGraph.phases[0]!,
  372. { ...unphasedGraph.phases[1]!, refinedName: "起飞前检查" },
  373. ],
  374. }).success,
  375. ).toBe(false);
  376. });
  377. it("rejects every field of the pre-single-arrow shape", () => {
  378. // docs/dynamic-workflow/presentation.md「The display contract」:硬断,不留可选过渡。
  379. // 分析器的边种类 / certainty / exact 见证位、step 的 region / certainty、车道的 families
  380. // 与顶层 regions 表都不再是载荷的一部分——.strict() 把每一个都挡回去,防止生产侧悄悄
  381. // 加回来(旧载荷在 UI 侧走 safeParse 失败的既有兜底:整个 display 视为不在场)。
  382. // docs/dynamic-workflow/presentation.md 再砍一刀:step 级 `edges` 与 `Lane.nesting`
  383. // 没有读者了,同样硬断。
  384. const [step0, step1] = unphasedGraph.steps;
  385. const [lane0, lane1] = unphasedGraph.lanes;
  386. const edge = { from: "world-read#1", to: "ask#1" };
  387. const handoff = unphasedGraph.handoffs[0]!;
  388. const phaseEdge = { from: "unphased", to: "phase#1" };
  389. const rejected: unknown[] = [
  390. // step 级边整个字段都不在了——空数组也是多出来的键。
  391. { ...unphasedGraph, edges: [] },
  392. { ...unphasedGraph, edges: [edge] },
  393. { ...unphasedGraph, edges: [{ ...edge, kind: "data" }] },
  394. // 交接边上的旧字段。
  395. { ...unphasedGraph, handoffs: [{ ...handoff, kind: "data" }] },
  396. { ...unphasedGraph, handoffs: [{ ...handoff, kind: "carry" }] },
  397. { ...unphasedGraph, handoffs: [{ ...handoff, certainty: "always" }] },
  398. { ...unphasedGraph, handoffs: [{ ...handoff, exact: true }] },
  399. { ...unphasedGraph, handoffs: [{ ...handoff, count: 2 }] },
  400. // 阶段边上的旧字段。
  401. { ...unphasedGraph, phaseEdges: [{ ...phaseEdge, kind: "seq" }] },
  402. { ...unphasedGraph, phaseEdges: [{ ...phaseEdge, certainty: "maybe" }] },
  403. { ...unphasedGraph, phaseEdges: [{ ...phaseEdge, exact: true }] },
  404. // step 上的旧字段。
  405. { ...unphasedGraph, steps: [{ ...step0, region: "seq#1" }, step1] },
  406. { ...unphasedGraph, steps: [{ ...step0, certainty: "always" }, step1] },
  407. // 车道上的旧字段:families(单一箭头之前)与 nesting(交接栈之前)。
  408. { ...unphasedGraph, lanes: [lane0, { ...lane1, families: ["loop#1"] }] },
  409. { ...unphasedGraph, lanes: [lane0, { ...lane1, nesting: 1 }] },
  410. { ...unphasedGraph, lanes: [lane0, { ...lane1, nesting: 0 }] },
  411. // 顶层 regions 表——空表也一样是多出来的键。
  412. { ...unphasedGraph, regions: [] },
  413. { ...unphasedGraph, regions: [{ id: "seq#1", kind: "seq" }] },
  414. ];
  415. for (const graph of rejected) {
  416. expect(CreateWorkflowCausalityGraphSchema.safeParse(graph).success).toBe(false);
  417. }
  418. });
  419. it("accepts only the literal true for `back` on either edge layer", () => {
  420. // `back` 是回边标记,不是布尔状态:false / "yes" 都不是「没标回边」的另一种拼法。
  421. // 缺席就是前向边;两层边同一形状,所以两层都要钉。
  422. const edge = { from: "phase#1:actor#1", to: "unphased:workspace" };
  423. const phaseEdge = { from: "phase#1", to: "unphased" };
  424. expect(
  425. CreateWorkflowCausalityGraphSchema.parse({
  426. ...unphasedGraph,
  427. handoffs: [{ ...edge, back: true }],
  428. }).handoffs,
  429. ).toEqual([{ ...edge, back: true }]);
  430. expect(
  431. CreateWorkflowCausalityGraphSchema.parse({
  432. ...unphasedGraph,
  433. phaseEdges: [{ ...phaseEdge, back: true }],
  434. }).phaseEdges,
  435. ).toEqual([{ ...phaseEdge, back: true }]);
  436. for (const back of [false, "yes", 1, null]) {
  437. expect(
  438. CreateWorkflowCausalityGraphSchema.safeParse({
  439. ...unphasedGraph,
  440. handoffs: [{ ...edge, back }],
  441. }).success,
  442. ).toBe(false);
  443. expect(
  444. CreateWorkflowCausalityGraphSchema.safeParse({
  445. ...unphasedGraph,
  446. phaseEdges: [{ ...phaseEdge, back }],
  447. }).success,
  448. ).toBe(false);
  449. }
  450. });
  451. it("bounds the vocabulary at 32 phases and 128 phase edges", () => {
  452. const phase = { id: "phase#1", name: "p" };
  453. const edge = { from: "phase#1", to: "phase#2", back: true as const };
  454. expect(
  455. CreateWorkflowCausalityGraphSchema.safeParse({
  456. ...unphasedGraph,
  457. phases: Array.from({ length: CREATE_WORKFLOW_GRAPH_MAX_PHASES }, (_, i) => ({
  458. ...phase,
  459. id: `phase#${i + 1}`,
  460. })),
  461. }).success,
  462. ).toBe(true);
  463. expect(
  464. CreateWorkflowCausalityGraphSchema.safeParse({
  465. ...unphasedGraph,
  466. phases: Array.from({ length: CREATE_WORKFLOW_GRAPH_MAX_PHASES + 1 }, (_, i) => ({
  467. ...phase,
  468. id: `phase#${i + 1}`,
  469. })),
  470. }).success,
  471. ).toBe(false);
  472. expect(
  473. CreateWorkflowCausalityGraphSchema.safeParse({
  474. ...unphasedGraph,
  475. phaseEdges: Array.from({ length: CREATE_WORKFLOW_GRAPH_MAX_PHASE_EDGES + 1 }, () => edge),
  476. }).success,
  477. ).toBe(false);
  478. });
  479. it("round-trips phase streams and keeps them to {from, to}, at most 128", () => {
  480. // docs/dynamic-workflow/presentation.md「Streams」:channel 串起来的两个 future 阶段是一条
  481. // 阶段流——不是 runs after,所以没有 `back`,也不带分析器的边种类。
  482. const streams = [
  483. { from: "phase#1", to: "phase#2" },
  484. { from: "phase#2", to: "phase#3" },
  485. ];
  486. const parsed = CreateWorkflowCausalityGraphSchema.parse({
  487. ...unphasedGraph,
  488. phaseStreams: streams,
  489. });
  490. expect(parsed.phaseStreams).toEqual(streams);
  491. for (const phaseStreams of [
  492. [{ from: "phase#1", to: "phase#2", back: true }],
  493. [{ from: "phase#1", to: "phase#2", kind: "data" }],
  494. [{ from: "", to: "phase#2" }],
  495. [{ from: "phase#1", to: "p".repeat(65) }],
  496. Array.from({ length: CREATE_WORKFLOW_GRAPH_MAX_PHASE_EDGES + 1 }, () => streams[0]),
  497. ]) {
  498. expect(
  499. CreateWorkflowCausalityGraphSchema.safeParse({ ...unphasedGraph, phaseStreams }).success,
  500. ).toBe(false);
  501. }
  502. });
  503. it("bounds phase ids and names like every other graph string", () => {
  504. for (const phases of [
  505. [{ id: "" }],
  506. [{ id: "p".repeat(65) }],
  507. [{ id: "phase#1", name: "" }],
  508. [{ id: "phase#1", name: "长".repeat(129) }],
  509. [{ id: "phase#1", line: 0 }],
  510. [{ id: "phase#1", label: "smuggled" }],
  511. ]) {
  512. expect(
  513. CreateWorkflowCausalityGraphSchema.safeParse({ ...unphasedGraph, phases }).success,
  514. ).toBe(false);
  515. }
  516. expect(
  517. CreateWorkflowCausalityGraphSchema.safeParse({
  518. ...unphasedGraph,
  519. steps: [{ ...unphasedGraph.steps[0]!, phase: "p".repeat(65) }],
  520. }).success,
  521. ).toBe(false);
  522. });
  523. });
  524. describe("CreateWorkflowCausalityGraphSchema — participants and handoffs", () => {
  525. // docs/dynamic-workflow/presentation.md「The display contract」:第二层是子代理导向——每阶段一张参与者
  526. // 卡(`${phase}:${lane}`,家族成员再带 `[index]`)+ 卡之间的交接边。两个字段**必填**:
  527. // 零参与者的图是空数组,不是缺席——step 级 `edges` 就是这样悄悄退出的,新字段不给缺席
  528. // 一条可通过的路。
  529. const step = (id: string, lane: string, phase: string) => ({
  530. id,
  531. kind: "ask" as const,
  532. label: lane,
  533. lane,
  534. phase,
  535. });
  536. const graph = {
  537. steps: [step("ask#1", "actor#1", "phase#1"), step("ask#2", "actor#2", "phase#1")],
  538. lanes: [
  539. { id: "actor#1", name: "planner" },
  540. { id: "actor#2", name: "worker" },
  541. ],
  542. participants: [
  543. { id: "phase#1:actor#1", phase: "phase#1", lane: "actor#1", steps: ["ask#1"] },
  544. { id: "phase#1:actor#2", phase: "phase#1", lane: "actor#2", steps: ["ask#2"] },
  545. ],
  546. handoffs: [{ from: "phase#1:actor#1", to: "phase#1:actor#2" }],
  547. phases: [{ id: "phase#1", name: "plan" }],
  548. phaseEdges: [],
  549. exits: ["phase#1"],
  550. };
  551. const [p0, p1] = graph.participants;
  552. const [h0] = graph.handoffs;
  553. it("exposes the bounds as constants the handler truncates against", () => {
  554. expect(CREATE_WORKFLOW_GRAPH_MAX_PARTICIPANTS).toBe(64);
  555. expect(CREATE_WORKFLOW_GRAPH_MAX_HANDOFFS).toBe(256);
  556. expect(CREATE_WORKFLOW_GRAPH_MAX_HANDOFF_TYPES).toBe(8);
  557. });
  558. it("round-trips participants and handoffs and requires both fields", () => {
  559. expect(CreateWorkflowCausalityGraphSchema.parse(graph)).toEqual(graph);
  560. const noParticipants: Record<string, unknown> = { ...graph };
  561. delete noParticipants.participants;
  562. const noHandoffs: Record<string, unknown> = { ...graph };
  563. delete noHandoffs.handoffs;
  564. expect(CreateWorkflowCausalityGraphSchema.safeParse(noParticipants).success).toBe(false);
  565. expect(CreateWorkflowCausalityGraphSchema.safeParse(noHandoffs).success).toBe(false);
  566. // 空图:两个数组在场且为空。
  567. expect(
  568. CreateWorkflowCausalityGraphSchema.parse({
  569. steps: [],
  570. lanes: [],
  571. participants: [],
  572. handoffs: [],
  573. }),
  574. ).toEqual({ steps: [], lanes: [], participants: [], handoffs: [] });
  575. });
  576. it("requires at least one step per participant and bounds the list at 64", () => {
  577. // 一张没有 step 的卡不代表任何子代理——运行状态无从聚合,检视器无 ask 可列。
  578. expect(CreateWorkflowParticipantSchema.safeParse({ ...p0, steps: [] }).success).toBe(false);
  579. expect(
  580. CreateWorkflowCausalityGraphSchema.safeParse({
  581. ...graph,
  582. participants: [{ ...p0, steps: [] }, p1],
  583. }).success,
  584. ).toBe(false);
  585. const manySteps = Array.from({ length: CREATE_WORKFLOW_GRAPH_MAX_STEPS }, (_, i) => `ask#${i}`);
  586. expect(CreateWorkflowParticipantSchema.safeParse({ ...p0, steps: manySteps }).success).toBe(
  587. true,
  588. );
  589. expect(
  590. CreateWorkflowParticipantSchema.safeParse({ ...p0, steps: [...manySteps, "ask#64"] }).success,
  591. ).toBe(false);
  592. // step id 走同一组 id 上界。
  593. for (const bad of [[""], ["s".repeat(65)], [42]]) {
  594. expect(CreateWorkflowParticipantSchema.safeParse({ ...p0, steps: bad }).success).toBe(false);
  595. }
  596. });
  597. it("requires id, phase and lane on every participant and rejects extra keys", () => {
  598. for (const key of ["id", "phase", "lane", "steps"]) {
  599. const partial: Record<string, unknown> = { ...p0 };
  600. delete partial[key];
  601. expect(CreateWorkflowParticipantSchema.safeParse(partial).success).toBe(false);
  602. }
  603. // 卡的展示名从车道表查,不进参与者;step 级 edges 的残留键也一样。
  604. for (const extra of [{ name: "planner" }, { edges: [] }, { nesting: 1 }, { region: "seq#1" }]) {
  605. expect(CreateWorkflowParticipantSchema.safeParse({ ...p0, ...extra }).success).toBe(false);
  606. }
  607. // 无阶段词汇的脚本:phase 恒为 `unphased`,与 `phases` 缺席同时成立。
  608. expect(
  609. CreateWorkflowCausalityGraphSchema.safeParse({
  610. steps: [step("ask#1", "actor#1", "unphased")],
  611. lanes: [graph.lanes[0]],
  612. participants: [
  613. { id: "unphased:actor#1", phase: "unphased", lane: "actor#1", steps: ["ask#1"] },
  614. ],
  615. handoffs: [],
  616. }).success,
  617. ).toBe(true);
  618. });
  619. it("shapes fan-out members as `member: {index ≥ 0, of ≥ 1}` and `many: true`", () => {
  620. // 字面量基数的家族每成员一张卡(id 带 `[index]`);基数未知时一张 `many` 卡代表全部。
  621. const member = { ...p1, id: "phase#1:actor#2[0]", member: { index: 0, of: 3 } };
  622. expect(CreateWorkflowParticipantSchema.parse(member)).toEqual(member);
  623. const many = { ...p1, many: true as const };
  624. expect(CreateWorkflowParticipantSchema.parse(many)).toEqual(many);
  625. for (const bad of [
  626. { index: -1, of: 3 },
  627. { index: 0.5, of: 3 },
  628. { index: 0, of: 0 },
  629. { index: 0, of: -1 },
  630. { index: 0 },
  631. { of: 3 },
  632. { index: "0", of: 3 },
  633. { index: 0, of: 3, label: "smuggled" },
  634. ]) {
  635. expect(CreateWorkflowParticipantSchema.safeParse({ ...p1, member: bad }).success).toBe(false);
  636. }
  637. // `many` 是标记,不是布尔状态:false 不是「不是 many」的另一种拼法。
  638. for (const many of [false, "yes", 1, null]) {
  639. expect(CreateWorkflowParticipantSchema.safeParse({ ...p1, many }).success).toBe(false);
  640. }
  641. });
  642. it("bounds the participant list at 64 and the handoff list at 256", () => {
  643. const participants = (n: number) =>
  644. Array.from({ length: n }, (_, i) => ({
  645. ...p0,
  646. id: `phase#1:actor#1[${i}]`,
  647. member: { index: i, of: n },
  648. }));
  649. expect(
  650. CreateWorkflowCausalityGraphSchema.safeParse({
  651. ...graph,
  652. participants: participants(CREATE_WORKFLOW_GRAPH_MAX_PARTICIPANTS),
  653. }).success,
  654. ).toBe(true);
  655. expect(
  656. CreateWorkflowCausalityGraphSchema.safeParse({
  657. ...graph,
  658. participants: participants(CREATE_WORKFLOW_GRAPH_MAX_PARTICIPANTS + 1),
  659. }).success,
  660. ).toBe(false);
  661. const handoffs = (n: number) => Array.from({ length: n }, () => h0);
  662. expect(
  663. CreateWorkflowCausalityGraphSchema.safeParse({
  664. ...graph,
  665. handoffs: handoffs(CREATE_WORKFLOW_GRAPH_MAX_HANDOFFS),
  666. }).success,
  667. ).toBe(true);
  668. expect(
  669. CreateWorkflowCausalityGraphSchema.safeParse({
  670. ...graph,
  671. handoffs: handoffs(CREATE_WORKFLOW_GRAPH_MAX_HANDOFFS + 1),
  672. }).success,
  673. ).toBe(false);
  674. });
  675. it("carries 1..8 artifact type names on a handoff, each within the name bound", () => {
  676. // `types` 只进检视器,不上箭头;在场就至少一个,最多 8 个,每个走名字上界。
  677. const withTypes = { ...h0, types: ["Plan", "Report"] };
  678. expect(CreateWorkflowHandoffSchema.parse(withTypes)).toEqual(withTypes);
  679. expect(CreateWorkflowHandoffSchema.parse({ ...h0, back: true })).toEqual({ ...h0, back: true });
  680. const max = Array.from({ length: CREATE_WORKFLOW_GRAPH_MAX_HANDOFF_TYPES }, (_, i) => `T${i}`);
  681. expect(CreateWorkflowHandoffSchema.safeParse({ ...h0, types: max }).success).toBe(true);
  682. for (const bad of [[], [...max, "T8"], [""], ["长".repeat(129)], [42], "Plan"]) {
  683. expect(CreateWorkflowHandoffSchema.safeParse({ ...h0, types: bad }).success).toBe(false);
  684. expect(
  685. CreateWorkflowCausalityGraphSchema.safeParse({
  686. ...graph,
  687. handoffs: [{ ...h0, types: bad }],
  688. }).success,
  689. ).toBe(false);
  690. }
  691. // 阶段边没有 types——它是控制流商,不携带产物。
  692. expect(
  693. CreateWorkflowCausalityGraphSchema.safeParse({
  694. ...graph,
  695. phaseEdges: [{ from: "phase#1", to: "phase#1", types: ["Plan"] }],
  696. }).success,
  697. ).toBe(false);
  698. });
  699. });
  700. describe("createWorkflowPhaseNames — the declared phase table for run-launched", () => {
  701. it("returns the named phases in declared order and skips the synthetic unnamed one", () => {
  702. expect(
  703. createWorkflowPhaseNames({
  704. steps: [],
  705. lanes: [],
  706. participants: [],
  707. handoffs: [],
  708. phases: [
  709. { id: "p1", name: "Research" },
  710. { id: "unphased" },
  711. { id: "p2", name: "Write" },
  712. ],
  713. }),
  714. ).toEqual(["Research", "Write"]);
  715. });
  716. it("returns undefined when the graph is absent or declares no phase vocabulary", () => {
  717. expect(createWorkflowPhaseNames(undefined)).toBeUndefined();
  718. expect(
  719. createWorkflowPhaseNames({ steps: [], lanes: [], participants: [], handoffs: [] }),
  720. ).toBeUndefined();
  721. expect(
  722. createWorkflowPhaseNames({
  723. steps: [],
  724. lanes: [],
  725. participants: [],
  726. handoffs: [],
  727. phases: [{ id: "unphased" }],
  728. }),
  729. ).toBeUndefined();
  730. });
  731. it("keeps at most CREATE_WORKFLOW_GRAPH_MAX_PHASES names", () => {
  732. const phases = Array.from({ length: CREATE_WORKFLOW_GRAPH_MAX_PHASES + 3 }, (_, index) => ({
  733. id: `p${index}`,
  734. name: `Phase ${index}`,
  735. }));
  736. expect(
  737. createWorkflowPhaseNames({ steps: [], lanes: [], participants: [], handoffs: [], phases }),
  738. ).toHaveLength(CREATE_WORKFLOW_GRAPH_MAX_PHASES);
  739. });
  740. });
  741. describe("createWorkflowPhaseAlongside — the phases a phase was entered beside", () => {
  742. const empty = { steps: [], lanes: [], participants: [], handoffs: [] };
  743. it("indexes into the named-phase table, dropping references to unnamed phases", () => {
  744. // 下标空间是**有名阶段**的:合成的 `unphased` 排在表首却不占位,所以 Research 是 0、
  745. // Write 是 1,而指向 `unphased` 的引用无处可落,只能丢掉。
  746. const graph = {
  747. ...empty,
  748. phases: [
  749. { id: "unphased", alongside: ["p1"] },
  750. { id: "p1", name: "Research", alongside: ["unphased", "p2"] },
  751. { id: "p2", name: "Write", alongside: ["p1"] },
  752. ],
  753. };
  754. expect(createWorkflowPhaseNames(graph)).toEqual(["Research", "Write"]);
  755. expect(createWorkflowPhaseAlongside(graph)).toEqual([[1], [0]]);
  756. });
  757. it("drops references to unlisted phases and to itself, and dedupes", () => {
  758. expect(
  759. createWorkflowPhaseAlongside({
  760. ...empty,
  761. phases: [
  762. { id: "p1", name: "Research", alongside: ["p1", "p9", "p2", "p2"] },
  763. { id: "p2", name: "Write" },
  764. ],
  765. }),
  766. ).toEqual([[1], []]);
  767. });
  768. it("returns undefined when no phase was entered beside another", () => {
  769. // 缺席就是「这条轨道是一条直线」,所以一串空数组也要塌成 undefined——包括每个引用都被
  770. // 丢光的情形。
  771. expect(createWorkflowPhaseAlongside(undefined)).toBeUndefined();
  772. expect(createWorkflowPhaseAlongside(empty)).toBeUndefined();
  773. expect(
  774. createWorkflowPhaseAlongside({ ...empty, phases: [{ id: "unphased", alongside: ["p1"] }] }),
  775. ).toBeUndefined();
  776. expect(
  777. createWorkflowPhaseAlongside({
  778. ...empty,
  779. phases: [
  780. { id: "p1", name: "Research" },
  781. { id: "p2", name: "Write" },
  782. ],
  783. }),
  784. ).toBeUndefined();
  785. expect(
  786. createWorkflowPhaseAlongside({
  787. ...empty,
  788. phases: [{ id: "p1", name: "Research", alongside: ["unphased"] }, { id: "unphased" }],
  789. }),
  790. ).toBeUndefined();
  791. });
  792. it("stops at CREATE_WORKFLOW_GRAPH_MAX_PHASES, with it the references past the cut", () => {
  793. const phases = Array.from({ length: CREATE_WORKFLOW_GRAPH_MAX_PHASES + 3 }, (_, index) => ({
  794. id: `p${index}`,
  795. name: `Phase ${index}`,
  796. alongside: [`p${index + 1}`],
  797. }));
  798. const alongside = createWorkflowPhaseAlongside({ ...empty, phases });
  799. expect(alongside).toHaveLength(CREATE_WORKFLOW_GRAPH_MAX_PHASES);
  800. expect(createWorkflowPhaseNames({ ...empty, phases })).toHaveLength(alongside!.length);
  801. expect(alongside![0]).toEqual([1]);
  802. // 最后一站指向的是被截掉的那个阶段:越界下标会把侧栏连到不存在的站上,所以它一起走。
  803. expect(alongside![CREATE_WORKFLOW_GRAPH_MAX_PHASES - 1]).toEqual([]);
  804. });
  805. });