create-workflow.test.ts 30 KB

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