get-workflow-run.test.ts 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460
  1. import { describe, expect, it } from "vitest";
  2. import {
  3. GET_WORKFLOW_RUN_TOOL_NAME,
  4. GetWorkflowRunInputJsonSchema,
  5. GetWorkflowRunInputSchema,
  6. GetWorkflowRunOutputJsonSchema,
  7. GetWorkflowRunOutputSchema,
  8. } from "../src/tools/get-workflow-run.js";
  9. const RUNNING = {
  10. runId: "dwfrun-1",
  11. label: "// triage the failing tests",
  12. labelSource: "script" as const,
  13. status: "running" as const,
  14. ownedByThisSession: true,
  15. createdAt: 1_755_000_000_000,
  16. updatedAt: 1_755_000_001_000,
  17. summary: "Running for 1m 00s. 2 of 3 dispatched steps settled, 1 running (1 executing).",
  18. generatedAt: 1_755_000_001_500,
  19. usage: {
  20. spentTokens: 1_204,
  21. nodesObserved: 3,
  22. nodesRunning: 1,
  23. nodesCompleted: 2,
  24. nodesFailed: 0,
  25. },
  26. actors: [{ siteId: "agent#1", ordinal: 1, name: "judge" }],
  27. logTail: [{ sequence: 12, message: "collected the failing specs" }],
  28. subagents: [
  29. {
  30. siteId: "agent#1",
  31. ordinal: 1,
  32. name: "judge",
  33. state: "executing" as const,
  34. stepsSettled: 2,
  35. stepsFailed: 0,
  36. tokens: 1_204,
  37. },
  38. ],
  39. health: { consecutiveFailures: 0, cachedSteps: 0, pendingQuestionsKnown: true },
  40. };
  41. describe("GetWorkflowRun input schema", () => {
  42. it("names the tool exactly as it registers", () => {
  43. expect(GET_WORKFLOW_RUN_TOOL_NAME).toBe("GetWorkflowRun");
  44. });
  45. // snake_case 随 TaskOutput 的 task_id:两个工具在模型眼里是同一族的 run/task 键。
  46. it("requires a non-empty snake_case run_id", () => {
  47. expect(GetWorkflowRunInputSchema.parse({ run_id: "dwfrun-1" })).toEqual({
  48. run_id: "dwfrun-1",
  49. });
  50. expect(GetWorkflowRunInputSchema.safeParse({ run_id: "" }).success).toBe(false);
  51. expect(GetWorkflowRunInputSchema.safeParse({}).success).toBe(false);
  52. expect(GetWorkflowRunInputSchema.safeParse({ runId: "dwfrun-1" }).success).toBe(false);
  53. });
  54. it("stays strict about unknown keys", () => {
  55. expect(
  56. GetWorkflowRunInputSchema.safeParse({ run_id: "dwfrun-1", logTailLimit: 100 }).success,
  57. ).toBe(false);
  58. });
  59. it("requires run_id in the model-facing JSON schema", () => {
  60. const schema = GetWorkflowRunInputJsonSchema as {
  61. properties?: Record<string, unknown>;
  62. required?: string[];
  63. };
  64. expect(Object.keys(schema.properties ?? {})).toEqual(["run_id"]);
  65. expect(schema.required).toEqual(["run_id"]);
  66. });
  67. });
  68. describe("GetWorkflowRun output schema", () => {
  69. it("roundtrips a running run with neither result nor error", () => {
  70. const parsed = GetWorkflowRunOutputSchema.parse(RUNNING);
  71. expect(parsed).toEqual(RUNNING);
  72. expect("result" in parsed).toBe(false);
  73. expect("error" in parsed).toBe(false);
  74. });
  75. // 子代理模型(docs/dynamic-workflow/launch.md):设过才在场,继承会话模型的 run 整字段缺席——
  76. // AmendWorkflow 省略 `subagent_model` 时沿用的就是这个值,所以「缺席」必须与「空串」可分辨。
  77. it("round-trips a subagent model and keeps it absent when the run inherits the session model", () => {
  78. const withModel = GetWorkflowRunOutputSchema.parse({
  79. ...RUNNING,
  80. subagentModel: "zhipu/glm-5.3$high",
  81. });
  82. expect(withModel.subagentModel).toBe("zhipu/glm-5.3$high");
  83. expect("subagentModel" in GetWorkflowRunOutputSchema.parse(RUNNING)).toBe(false);
  84. });
  85. // 脚本文件(docs/dynamic-workflow/launch.md「Script files」):记过才在场。在场时它就是下一次
  86. // AmendWorkflow 该传的 `path`,所以「缺席」必须与「空串」一样可分辨。
  87. it("round-trips the run's script file and keeps it absent when the run recorded none", () => {
  88. const withPath = GetWorkflowRunOutputSchema.parse({
  89. ...RUNNING,
  90. scriptPath: ".zcode/workflow-drafts/audit.dwf.ts",
  91. });
  92. expect(withPath.scriptPath).toBe(".zcode/workflow-drafts/audit.dwf.ts");
  93. expect("scriptPath" in GetWorkflowRunOutputSchema.parse(RUNNING)).toBe(false);
  94. });
  95. it("accepts a completed run whose result is the serialized artifact", () => {
  96. const output = {
  97. ...RUNNING,
  98. status: "completed" as const,
  99. result: '{\n "verdict": "ship"\n}',
  100. };
  101. expect(GetWorkflowRunOutputSchema.parse(output)).toEqual(output);
  102. });
  103. it("accepts an errored run and keeps the failure code verbatim", () => {
  104. // DriverError(脚本真失败)与 ReportCapExceeded 等契约码必须能被模型分辨,所以 code 是
  105. // 自由字符串而不是一个我们自己收窄的枚举。
  106. for (const code of ["DriverError", "ReportCapExceeded"]) {
  107. const output = {
  108. ...RUNNING,
  109. status: "errored" as const,
  110. error: { code, message: `run ended: ${code}` },
  111. };
  112. expect(GetWorkflowRunOutputSchema.parse(output).error).toEqual({
  113. code,
  114. message: `run ended: ${code}`,
  115. });
  116. }
  117. });
  118. // stopped(apps/zcode-cli/packages/dynamic-workflow/docs/execution-engine.md):reason 四值;provider 停下带结构化明细。
  119. it("accepts a stopped run with its reason and a provider stop's details", () => {
  120. const interrupted = {
  121. ...RUNNING,
  122. status: "stopped" as const,
  123. stopReason: "interrupted" as const,
  124. error: { code: "Interrupted", message: "the owning process exited" },
  125. };
  126. expect(GetWorkflowRunOutputSchema.parse(interrupted)).toEqual(interrupted);
  127. const providerStop = {
  128. ...RUNNING,
  129. status: "stopped" as const,
  130. stopReason: "provider" as const,
  131. error: {
  132. code: "ProviderStop",
  133. message: "Subagent turn failed: [1006] token expired",
  134. providerStop: {
  135. kind: "auth" as const,
  136. reason: "auth_failed",
  137. providerId: "account:bigmodel-coding-plan",
  138. modelId: "GLM-5.3",
  139. providerCode: "1006",
  140. subagent: "verify@2",
  141. rawMessage: "[1006] token expired",
  142. },
  143. },
  144. };
  145. expect(GetWorkflowRunOutputSchema.parse(providerStop)).toEqual(providerStop);
  146. expect(
  147. GetWorkflowRunOutputSchema.safeParse({ ...RUNNING, status: "stopped", stopReason: "crash" })
  148. .success,
  149. ).toBe(false);
  150. expect(
  151. GetWorkflowRunOutputSchema.safeParse({
  152. ...providerStop,
  153. error: {
  154. ...providerStop.error,
  155. providerStop: { ...providerStop.error.providerStop, kind: "bogus" },
  156. },
  157. }).success,
  158. ).toBe(false);
  159. });
  160. it("carries the actor name only when present", () => {
  161. const parsed = GetWorkflowRunOutputSchema.parse({
  162. ...RUNNING,
  163. actors: [{ siteId: "agent#1", ordinal: 1 }],
  164. });
  165. expect("name" in parsed.actors[0]!).toBe(false);
  166. });
  167. // docs/dynamic-workflow/authoring.md:用量是观察面,没有任何上限字段。
  168. it("has no cap fields on usage: budgetTotal / maxNodes are unknown keys", () => {
  169. for (const extra of [{ budgetTotal: 200_000 }, { maxNodes: 100 }]) {
  170. expect(
  171. GetWorkflowRunOutputSchema.safeParse({ ...RUNNING, usage: { ...RUNNING.usage, ...extra } })
  172. .success,
  173. ).toBe(false);
  174. }
  175. });
  176. it("accepts empty actor and log collections", () => {
  177. const parsed = GetWorkflowRunOutputSchema.parse({ ...RUNNING, actors: [], logTail: [] });
  178. expect(parsed.actors).toEqual([]);
  179. expect(parsed.logTail).toEqual([]);
  180. });
  181. it("requires the whole node-count block: a partial usage is a shape error", () => {
  182. expect(
  183. GetWorkflowRunOutputSchema.safeParse({
  184. ...RUNNING,
  185. usage: { spentTokens: 1, nodesObserved: 3 },
  186. }).success,
  187. ).toBe(false);
  188. });
  189. it("stays strict about unknown keys at every level", () => {
  190. expect(GetWorkflowRunOutputSchema.safeParse({ ...RUNNING, elapsedMs: 12 }).success).toBe(false);
  191. expect(
  192. GetWorkflowRunOutputSchema.safeParse({
  193. ...RUNNING,
  194. usage: { ...RUNNING.usage, budgetRemaining: 1 },
  195. }).success,
  196. ).toBe(false);
  197. expect(
  198. GetWorkflowRunOutputSchema.safeParse({
  199. ...RUNNING,
  200. actors: [{ siteId: "agent#1", ordinal: 1, persona: "you are…" }],
  201. }).success,
  202. ).toBe(false);
  203. expect(
  204. GetWorkflowRunOutputSchema.safeParse({
  205. ...RUNNING,
  206. logTail: [{ sequence: 1, message: "hi", timestamp: 0 }],
  207. }).success,
  208. ).toBe(false);
  209. });
  210. // ————————————————————————————————————————————————
  211. // 情势截面(阶段 / 花名册 / 健康)。docs/dynamic-workflow/launch.md「`GetWorkflowRun`」。
  212. // ————————————————————————————————————————————————
  213. // `at` 是事件的落库时刻;老 journal 上缺席,那样的行读不出年龄——两者必须可分辨。
  214. it("takes an optional journal time on a log entry and keeps it absent otherwise", () => {
  215. const timed = GetWorkflowRunOutputSchema.parse({
  216. ...RUNNING,
  217. logTail: [{ sequence: 12, message: "collected the failing specs", at: 1_755_000_000_500 }],
  218. });
  219. expect(timed.logTail[0]?.at).toBe(1_755_000_000_500);
  220. expect("at" in GetWorkflowRunOutputSchema.parse(RUNNING).logTail[0]!).toBe(false);
  221. });
  222. it("round-trips a phase table and rejects a state outside the closed set", () => {
  223. const withPhases = {
  224. ...RUNNING,
  225. phases: [
  226. { name: "collect", state: "done" as const, rounds: 1, nodesSettled: 2, nodesRunning: 0, enteredAt: 1, exitedAt: 2 },
  227. { name: "judge", state: "current" as const, rounds: 1, nodesSettled: 3, nodesRunning: 2, enteredAt: 2 },
  228. { name: "verify", state: "ahead" as const, rounds: 0, nodesSettled: 0, nodesRunning: 0 },
  229. ],
  230. };
  231. expect(GetWorkflowRunOutputSchema.parse(withPhases)).toEqual(withPhases);
  232. // 声明了阶段但一个都没进过的 run 整字段缺席,而不是空数组。
  233. expect("phases" in GetWorkflowRunOutputSchema.parse(RUNNING)).toBe(false);
  234. expect(
  235. GetWorkflowRunOutputSchema.safeParse({
  236. ...RUNNING,
  237. phases: [{ name: "judge", state: "skipped", rounds: 1, nodesSettled: 0, nodesRunning: 0 }],
  238. }).success,
  239. ).toBe(false);
  240. });
  241. // turn / toolCalls 缺席读作「不知道」,`0` 读作「一个工具都没调过」:老 journal 没有
  242. // node-progress,两者必须能在同一个 schema 下分别表达。
  243. it("round-trips a full subagent row and keeps every progress reading optional", () => {
  244. const full = {
  245. ...RUNNING,
  246. subagents: [
  247. {
  248. siteId: "agent#2",
  249. ordinal: 1,
  250. name: "judge",
  251. state: "executing" as const,
  252. phaseName: "judge",
  253. currentAsk: {
  254. siteId: "ask#4",
  255. ordinal: 1,
  256. actorSeq: 2,
  257. instructionsHead: "Judge specs 1-7 for flakiness",
  258. startedAt: 1_755_000_000_100,
  259. turn: 4,
  260. toolCalls: 7,
  261. lastTool: { name: "Read", target: "packages/net/retry.spec.ts", at: 1_755_000_001_000 },
  262. },
  263. wait: { cause: "backoff" as const, reason: "429", retryAfterMs: 20_000, since: 1_755_000_000_900 },
  264. parkedOn: "dwfq-1",
  265. stepsSettled: 2,
  266. stepsFailed: 1,
  267. tokens: 5_100,
  268. lastProgressAt: 1_755_000_001_000,
  269. },
  270. ],
  271. };
  272. expect(GetWorkflowRunOutputSchema.parse(full)).toEqual(full);
  273. const bare = GetWorkflowRunOutputSchema.parse(RUNNING).subagents[0]!;
  274. for (const key of ["currentAsk", "wait", "parkedOn", "phaseName", "lastProgressAt"]) {
  275. expect(key in bare).toBe(false);
  276. }
  277. // 花名册恒在场,一个 actor 都没有的 run 是空数组(与 phases 的「无则缺席」刻意不同)。
  278. expect(GetWorkflowRunOutputSchema.parse({ ...RUNNING, subagents: [] }).subagents).toEqual([]);
  279. expect(GetWorkflowRunOutputSchema.safeParse({ ...RUNNING, subagents: undefined }).success).toBe(false);
  280. });
  281. it("closes the subagent state and wait-cause enums", () => {
  282. for (const patch of [{ state: "thinking" }, { wait: { cause: "quota" } }]) {
  283. expect(
  284. GetWorkflowRunOutputSchema.safeParse({
  285. ...RUNNING,
  286. subagents: [{ ...RUNNING.subagents[0]!, ...patch }],
  287. }).success,
  288. ).toBe(false);
  289. }
  290. });
  291. it("bounds the roster at 64 rows and the phase table at 32", () => {
  292. const subagent = RUNNING.subagents[0]!;
  293. expect(
  294. GetWorkflowRunOutputSchema.safeParse({
  295. ...RUNNING,
  296. subagents: Array.from({ length: 65 }, () => subagent),
  297. }).success,
  298. ).toBe(false);
  299. const phase = { name: "p", state: "done" as const, rounds: 1, nodesSettled: 0, nodesRunning: 0 };
  300. expect(
  301. GetWorkflowRunOutputSchema.safeParse({ ...RUNNING, phases: Array.from({ length: 33 }, () => phase) }).success,
  302. ).toBe(false);
  303. });
  304. // leftoverRunning 为 0 时缺席(终态 run 没有残留是常态);pendingQuestionsKnown 必填——
  305. // 「没有人在等」与「查不到」是两个不同的事实,缺省会把后者读成前者。
  306. it("round-trips health, requires pendingQuestionsKnown and keeps concurrency optional", () => {
  307. const health = {
  308. lastProgressAt: 1_755_000_001_000,
  309. stalledSince: 1_755_000_000_800,
  310. concurrency: { effective: 2, cap: 3, reason: "rate_limited", since: 1_755_000_000_700 },
  311. consecutiveFailures: 1,
  312. cachedSteps: 4,
  313. leftoverRunning: 2,
  314. pendingQuestionsKnown: false,
  315. };
  316. expect(GetWorkflowRunOutputSchema.parse({ ...RUNNING, health }).health).toEqual(health);
  317. expect(
  318. GetWorkflowRunOutputSchema.safeParse({
  319. ...RUNNING,
  320. health: { consecutiveFailures: 0, cachedSteps: 0 },
  321. }).success,
  322. ).toBe(false);
  323. expect(
  324. GetWorkflowRunOutputSchema.safeParse({
  325. ...RUNNING,
  326. health: { ...RUNNING.health, leftoverRunning: 0 },
  327. }).success,
  328. ).toBe(false);
  329. });
  330. it("marks a clamped roster with a literal-true flag only", () => {
  331. expect(GetWorkflowRunOutputSchema.parse({ ...RUNNING, subagentsTruncated: true }).subagentsTruncated).toBe(true);
  332. expect(
  333. GetWorkflowRunOutputSchema.safeParse({ ...RUNNING, subagentsTruncated: false }).success,
  334. ).toBe(false);
  335. });
  336. // 摘要是 handler 拼出来的一句话,不是模型写的散文:上界拦住「又一份报告」。
  337. it("bounds the summary at 400 characters", () => {
  338. expect(GetWorkflowRunOutputSchema.safeParse({ ...RUNNING, summary: "x".repeat(400) }).success).toBe(true);
  339. expect(GetWorkflowRunOutputSchema.safeParse({ ...RUNNING, summary: "x".repeat(401) }).success).toBe(false);
  340. });
  341. it("carries the primary flag on a published artifact as a literal true only", () => {
  342. const artifact = { id: "report", kind: "markdown" as const, version: 1, itemCount: 0 };
  343. const withPrimary = { ...RUNNING, artifacts: [{ ...artifact, primary: true as const }] };
  344. expect(GetWorkflowRunOutputSchema.parse(withPrimary)).toEqual(withPrimary);
  345. expect(GetWorkflowRunOutputSchema.parse({ ...RUNNING, artifacts: [artifact] })).toEqual({
  346. ...RUNNING,
  347. artifacts: [artifact],
  348. });
  349. // strict + literal: a non-deliverable is the absence of the key, never `false`.
  350. expect(
  351. GetWorkflowRunOutputSchema.safeParse({ ...RUNNING, artifacts: [{ ...artifact, primary: false }] })
  352. .success,
  353. ).toBe(false);
  354. });
  355. // result 是**已序列化的文本**:序列化在 core 只有一处实现(serializeWorkflowArtifact),
  356. // 通知与本工具共用它。放行原值等于允许「同一个产物在两处长得不一样」。
  357. it("takes result as text only, never as a raw structure", () => {
  358. expect(
  359. GetWorkflowRunOutputSchema.safeParse({
  360. ...RUNNING,
  361. status: "completed",
  362. result: { verdict: "ship" },
  363. }).success,
  364. ).toBe(false);
  365. });
  366. it("projects the common cross-section into the model-facing JSON schema", () => {
  367. const schema = GetWorkflowRunOutputJsonSchema as {
  368. properties?: Record<string, unknown>;
  369. required?: string[];
  370. };
  371. expect(Object.keys(schema.properties ?? {})).toEqual([
  372. "runId",
  373. "label",
  374. "labelSource",
  375. "status",
  376. "stopReason",
  377. "resumedFrom",
  378. "supersededBy",
  379. "ownedByThisSession",
  380. "possiblyInterrupted",
  381. "createdAt",
  382. "updatedAt",
  383. // 情势的一句话,以及它和模型面所有「多久以前」共用的那一把尺。
  384. "summary",
  385. "generatedAt",
  386. "usage",
  387. // run 自有的并发上界(docs/dynamic-workflow/concurrency.md「Two bounds on a run」):只在低于本机天花板时出现。
  388. "maxConcurrency",
  389. // run 自有的子代理模型(docs/dynamic-workflow/launch.md):只在设过时出现,继承会话模型的 run 缺席。
  390. "subagentModel",
  391. // 脚本点名的模型绑定表(docs/dynamic-workflow/launch.md「Models the script names」):只在脚本点过名时出现。
  392. "modelBindings",
  393. // run 的脚本文件(docs/dynamic-workflow/launch.md「Script files」):只在记过时出现,
  394. // 已经写成模型面该看到的样子(工作区相对或绝对)。
  395. "scriptPath",
  396. "actors",
  397. "logTail",
  398. // 情势截面:阶段表「无则缺席」,花名册恒在场,健康恒在场。
  399. "phases",
  400. "subagents",
  401. "subagentsTruncated",
  402. "health",
  403. "result",
  404. "error",
  405. // 停驻中的升级问题(apps/zcode-cli/packages/dynamic-workflow/docs/execution-engine.md):可选、零条时整字段缺席。
  406. // 它是模型侧唯一的发现面——升级通知丢弃后,主代理只能从这里重新拿到 qid。
  407. "pendingQuestions",
  408. // 留白(docs/dynamic-workflow/launch.md「The `FillWorkflowHole` tool」):等着的与补过的,零条时整字段缺席。
  409. // 与 pendingQuestions 同一种角色——留白通知丢失后模型侧唯一的发现面。
  410. "holes",
  411. // 用户面产物(docs/dynamic-workflow/authoring.md):任意状态都附、零件时整字段缺席。
  412. // 模型据此知道哪些交付物已经以卡片呈现给用户,按标题引用而不复述内容。
  413. "artifacts",
  414. ]);
  415. const required = schema.required ?? [];
  416. expect(required).toContain("usage");
  417. expect(required).toContain("logTail");
  418. expect(required).toContain("summary");
  419. expect(required).toContain("generatedAt");
  420. expect(required).toContain("subagents");
  421. expect(required).toContain("health");
  422. expect(required).not.toContain("phases");
  423. expect(required).not.toContain("subagentsTruncated");
  424. expect(required).not.toContain("result");
  425. expect(required).not.toContain("error");
  426. expect(required).not.toContain("possiblyInterrupted");
  427. expect(required).not.toContain("pendingQuestions");
  428. expect(required).not.toContain("scriptPath");
  429. });
  430. });