@zhushanwen/pi-subagent-workflow 8.4.0 → 8.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (171) hide show
  1. package/package.json +22 -7
  2. package/relay/relay.mjs +390 -0
  3. package/skills/subagent-ext-config/SKILL.md +80 -0
  4. package/src/execution/__tests__/agent-registry.test.ts +110 -0
  5. package/src/execution/__tests__/bg-notify-render.test.ts +73 -0
  6. package/src/execution/__tests__/chat-engine-routing.test.ts +601 -0
  7. package/src/execution/__tests__/delivery-methods.test.ts +38 -1
  8. package/src/execution/__tests__/execute-options-mapper.test.ts +11 -0
  9. package/src/execution/__tests__/execution-record.test.ts +237 -1
  10. package/src/execution/__tests__/explicit-agent-ref-guard.test.ts +171 -0
  11. package/src/execution/__tests__/format-schema-instruction.test.ts +63 -32
  12. package/src/execution/__tests__/helpers/spawn-mock.ts +4 -0
  13. package/src/execution/__tests__/index-session-start.test.ts +86 -7
  14. package/src/execution/__tests__/lifecycle-manager.test.ts +46 -0
  15. package/src/execution/__tests__/list-fields.test.ts +45 -14
  16. package/src/execution/__tests__/model-resolver.test.ts +57 -5
  17. package/src/execution/__tests__/notifier-flush.test.ts +64 -26
  18. package/src/execution/__tests__/notify-ledger.test.ts +826 -0
  19. package/src/execution/__tests__/output-collector.test.ts +299 -2
  20. package/src/execution/__tests__/pi-invocation.test.ts +62 -1
  21. package/src/execution/__tests__/relay-agent.test.ts +448 -0
  22. package/src/execution/__tests__/relay-env.test.ts +42 -0
  23. package/src/execution/__tests__/rpc-mode.test.ts +1 -1
  24. package/src/execution/__tests__/run-spawn-edges.test.ts +44 -1
  25. package/src/execution/__tests__/run-spawn-stdout-callback-throw.test.ts +199 -0
  26. package/src/execution/__tests__/session-runner-schema-env.test.ts +39 -0
  27. package/src/execution/__tests__/spawn-args.test.ts +37 -26
  28. package/src/execution/__tests__/start-sync-model-guard.test.ts +150 -0
  29. package/src/execution/__tests__/startup-config-declaration.test.ts +35 -0
  30. package/src/execution/__tests__/stream-sink-retirement.test.ts +261 -0
  31. package/src/execution/__tests__/subprocess-agent-runner-routing.test.ts +310 -0
  32. package/src/execution/__tests__/subprocess-agent-runner.test.ts +147 -6
  33. package/src/execution/__tests__/timeout-integration.test.ts +220 -2
  34. package/src/execution/__tests__/tool-action.test.ts +92 -1
  35. package/src/execution/agent-registry.ts +16 -0
  36. package/src/execution/argv-mirror.ts +5 -1
  37. package/src/execution/concurrency-pool.ts +1 -1
  38. package/src/execution/config.ts +25 -2
  39. package/src/execution/engine/__tests__/common/data-dir.test.ts +53 -0
  40. package/src/execution/engine/__tests__/common/errors.test.ts +132 -0
  41. package/src/execution/engine/__tests__/common/event-journal.test.ts +177 -0
  42. package/src/execution/engine/__tests__/common/kill-chain.test.ts +192 -0
  43. package/src/execution/engine/__tests__/common/nesting-guard.test.ts +81 -0
  44. package/src/execution/engine/__tests__/common/persona-router.test.ts +123 -0
  45. package/src/execution/engine/__tests__/common/pool-manager.test.ts +154 -0
  46. package/src/execution/engine/__tests__/common/schema-emulation.test.ts +128 -0
  47. package/src/execution/engine/__tests__/conformance/__fixtures__/pi-golden-events.json +28 -0
  48. package/src/execution/engine/__tests__/conformance/agent-event-invariants.ts +141 -0
  49. package/src/execution/engine/__tests__/conformance/contract.abort.test.ts +109 -0
  50. package/src/execution/engine/__tests__/conformance/contract.agent-events.test.ts +101 -0
  51. package/src/execution/engine/__tests__/conformance/contract.probe.test.ts +77 -0
  52. package/src/execution/engine/__tests__/conformance/contract.read-degradation.test.ts +104 -0
  53. package/src/execution/engine/__tests__/conformance/contract.relay.test.ts +342 -0
  54. package/src/execution/engine/__tests__/conformance/engine-conformance.live.test.ts +201 -0
  55. package/src/execution/engine/__tests__/conformance/golden-replay.pi.test.ts +76 -0
  56. package/src/execution/engine/__tests__/conformance/golden-replay.zcode.test.ts +79 -0
  57. package/src/execution/engine/__tests__/engine-discovery.test.ts +87 -0
  58. package/src/execution/engine/__tests__/engines-declaration.test.ts +36 -0
  59. package/src/execution/engine/__tests__/model-prompt.test.ts +85 -0
  60. package/src/execution/engine/__tests__/paths.test.ts +39 -0
  61. package/src/execution/engine/__tests__/registry.test.ts +120 -0
  62. package/src/execution/engine/__tests__/routing.test.ts +231 -0
  63. package/src/execution/engine/common/data-dir.ts +62 -0
  64. package/src/execution/engine/common/errors.ts +183 -0
  65. package/src/execution/engine/common/event-journal.ts +254 -0
  66. package/src/execution/engine/common/journal-replay.ts +62 -0
  67. package/src/execution/engine/common/kill-chain.ts +221 -0
  68. package/src/execution/engine/common/nesting-guard.ts +50 -0
  69. package/src/execution/engine/common/persona-router.ts +108 -0
  70. package/src/execution/engine/common/pool-manager.ts +226 -0
  71. package/src/execution/engine/common/schema-emulation.ts +189 -0
  72. package/src/execution/engine/common/session-view-projection.ts +51 -0
  73. package/src/execution/engine/engine-discovery.ts +65 -0
  74. package/src/execution/engine/engines/pi/__tests__/pi-engine.test.ts +469 -0
  75. package/src/execution/engine/engines/pi/__tests__/reader.test.ts +155 -0
  76. package/src/execution/engine/engines/pi/__tests__/task-spec-mapper.test.ts +164 -0
  77. package/src/execution/engine/engines/pi/pi-engine.ts +415 -0
  78. package/src/execution/engine/engines/pi/reader.ts +48 -0
  79. package/src/execution/engine/engines/pi/registration.ts +35 -0
  80. package/src/execution/engine/engines/pi/task-spec-mapper.ts +100 -0
  81. package/src/execution/engine/engines/zcode/__tests__/__fixtures__/zcode-golden-spawn.json +39 -0
  82. package/src/execution/engine/engines/zcode/__tests__/launcher.test.ts +150 -0
  83. package/src/execution/engine/engines/zcode/__tests__/parser.test.ts +246 -0
  84. package/src/execution/engine/engines/zcode/__tests__/preparer.test.ts +228 -0
  85. package/src/execution/engine/engines/zcode/__tests__/reader.test.ts +210 -0
  86. package/src/execution/engine/engines/zcode/__tests__/registration.test.ts +64 -0
  87. package/src/execution/engine/engines/zcode/__tests__/zcode-engine.live.test.ts +127 -0
  88. package/src/execution/engine/engines/zcode/__tests__/zcode-engine.test.ts +580 -0
  89. package/src/execution/engine/engines/zcode/constants.ts +43 -0
  90. package/src/execution/engine/engines/zcode/golden-sample.ts +39 -0
  91. package/src/execution/engine/engines/zcode/launcher.ts +161 -0
  92. package/src/execution/engine/engines/zcode/parser.ts +436 -0
  93. package/src/execution/engine/engines/zcode/preparer.ts +363 -0
  94. package/src/execution/engine/engines/zcode/reader.ts +381 -0
  95. package/src/execution/engine/engines/zcode/registration.ts +37 -0
  96. package/src/execution/engine/engines/zcode/zcode-engine.ts +658 -0
  97. package/src/execution/engine/host-task-spec.ts +47 -0
  98. package/src/execution/engine/model-prompt.ts +59 -0
  99. package/src/execution/engine/paths.ts +42 -0
  100. package/src/execution/engine/port.ts +153 -0
  101. package/src/execution/engine/registry.ts +123 -0
  102. package/src/execution/engine/routing.ts +218 -0
  103. package/src/execution/engine/types.ts +309 -0
  104. package/src/execution/execute-options-mapper.ts +13 -8
  105. package/src/execution/execution-record.ts +66 -1
  106. package/src/execution/lifecycle-manager.ts +23 -1
  107. package/src/execution/model-config-service.ts +16 -1
  108. package/src/execution/model-resolver.ts +37 -59
  109. package/src/execution/notifier.ts +105 -35
  110. package/src/execution/notify-ledger.ts +580 -0
  111. package/src/execution/output-collector.ts +143 -3
  112. package/src/execution/pi-invocation.ts +32 -2
  113. package/src/execution/record-entry.ts +14 -0
  114. package/src/execution/record-store.ts +34 -0
  115. package/src/execution/relay-env.ts +37 -0
  116. package/src/execution/session-runner.ts +328 -71
  117. package/src/execution/stream-sink.ts +26 -0
  118. package/src/execution/subagent-service.ts +273 -13
  119. package/src/execution/subprocess-agent-runner.ts +210 -14
  120. package/src/execution/types.ts +124 -5
  121. package/src/execution/ui-request-queue.ts +14 -4
  122. package/src/index.ts +99 -1
  123. package/src/interface/__tests__/subagent-tool-path-guard.test.ts +157 -0
  124. package/src/interface/__tests__/subagent-tool-prompt.test.ts +12 -0
  125. package/src/interface/bg-notify-render.ts +33 -12
  126. package/src/interface/helpers.ts +2 -2
  127. package/src/interface/subagent-actions.ts +29 -9
  128. package/src/interface/subagent-tool-schema.ts +156 -0
  129. package/src/interface/subagent-tool.ts +56 -119
  130. package/src/interface/subagents.ts +2 -2
  131. package/src/orchestration/__tests__/__fixtures__/worker-template.snapshot.txt +19 -3
  132. package/src/orchestration/__tests__/agent-call-catch-fallback.test.ts +0 -6
  133. package/src/orchestration/__tests__/agent-call-stream.test.ts +0 -5
  134. package/src/orchestration/__tests__/error-recovery-handlers.test.ts +89 -4
  135. package/src/orchestration/__tests__/execute-agent-call.test.ts +137 -0
  136. package/src/orchestration/__tests__/jsonl-run-store-corrupt-entry.test.ts +150 -0
  137. package/src/orchestration/__tests__/jsonl-run-store-retention.test.ts +202 -0
  138. package/src/orchestration/__tests__/launcher-nested-workflow.test.ts +326 -3
  139. package/src/orchestration/__tests__/lifecycle.test.ts +41 -7
  140. package/src/orchestration/__tests__/non-cloneable-return-e2e.test.ts +95 -0
  141. package/src/orchestration/__tests__/review-fix-loop-e2e.test.ts +57 -3
  142. package/src/orchestration/__tests__/skill-discovery.test.ts +44 -0
  143. package/src/orchestration/__tests__/worker-exit-without-result.test.ts +368 -0
  144. package/src/orchestration/__tests__/worker-script-builder-runtime.test.ts +43 -0
  145. package/src/orchestration/__tests__/worker-script-template-snapshot.test.ts +22 -3
  146. package/src/orchestration/agent-opts-resolver.ts +104 -23
  147. package/src/orchestration/error-recovery.ts +189 -33
  148. package/src/orchestration/execute-agent-call.ts +39 -0
  149. package/src/orchestration/jsonl-run-store.ts +121 -7
  150. package/src/orchestration/launcher.ts +60 -15
  151. package/src/orchestration/lifecycle.ts +10 -7
  152. package/src/orchestration/models/__tests__/budget.test.ts +1 -61
  153. package/src/orchestration/models/budget.ts +5 -35
  154. package/src/orchestration/models/run-runtime.ts +24 -9
  155. package/src/orchestration/models/types.ts +16 -0
  156. package/src/orchestration/script-lint.ts +1 -1
  157. package/src/orchestration/skill-discovery.ts +31 -8
  158. package/src/orchestration/worker-script-builder.ts +19 -3
  159. package/src/shared/__tests__/model-ref.test.ts +306 -0
  160. package/src/shared/__tests__/schema-jsonify.test.ts +1 -1
  161. package/src/shared/__tests__/timer-delay.test.ts +61 -0
  162. package/src/shared/meta-parser.ts +5 -1
  163. package/src/shared/model-ref.ts +286 -0
  164. package/src/shared/resource-meta.ts +5 -0
  165. package/src/shared/schema-env.ts +44 -0
  166. package/src/shared/schema-jsonify.ts +6 -4
  167. package/src/shared/timer-delay.ts +54 -0
  168. package/workflows/review-fix-loop-utils.cjs +9 -7
  169. package/workflows/review-fix-loop.js +20 -12
  170. package/src/orchestration/__tests__/concurrency-gate.test.ts +0 -125
  171. package/src/orchestration/concurrency-gate.ts +0 -69
@@ -7,7 +7,7 @@
7
7
  * 通过 vi.mock("../lifecycle.ts") 控制 runWorkflow:返回固定 runId + 把预构造的
8
8
  * child run 注入 deps.runs,使 pollRunToResult 首轮即命中 done 返回(无需真实 worker)。
9
9
  */
10
- import { beforeEach, describe, expect, it, vi } from "vitest";
10
+ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
11
11
 
12
12
  import { Budget } from "../models/budget.ts";
13
13
  import type { RunSpec } from "../models/run-spec.ts";
@@ -26,9 +26,9 @@ vi.mock("../lifecycle.ts", () => ({
26
26
 
27
27
  // import 在 vi.mock 之后(hoisting 保证拿到 mock 版本)。runWorkflow 从被 mock 的
28
28
  // lifecycle 模块导入,与 launcher.ts 内部引用的是同一 mock 实例。
29
- import { runWorkflow } from "../lifecycle.ts";
29
+ import { runWorkflow, abortRun } from "../lifecycle.ts";
30
30
  import { ArgsValidationError } from "../args-validator.ts";
31
- import { executeNestedWorkflow } from "../launcher.ts";
31
+ import { RUN_WATCHDOG_ENV, executeNestedWorkflow, runAndWait } from "../launcher.ts";
32
32
 
33
33
  const MOCK_RUN_ID = "wf-test-child";
34
34
 
@@ -69,12 +69,15 @@ function makeParentRun(opts: {
69
69
  parentWorkflowChain?: readonly string[];
70
70
  budget?: Budget;
71
71
  aborted?: boolean;
72
+ /** 预算语义对齐:父 run 级时间预算(deadline 传导测试用) */
73
+ budgetTimeMs?: number;
72
74
  } = {}): WorkflowRun {
73
75
  const controller = new AbortController();
74
76
  if (opts.aborted) controller.abort();
75
77
  const spec = {
76
78
  scriptName: opts.scriptName ?? "parent-wf",
77
79
  parentWorkflowChain: opts.parentWorkflowChain,
80
+ budgetTimeMs: opts.budgetTimeMs,
78
81
  };
79
82
  return {
80
83
  spec,
@@ -109,6 +112,24 @@ function makeDoneChildRun(opts: {
109
112
  } as unknown as WorkflowRun;
110
113
  }
111
114
 
115
+ /**
116
+ * 构造 mock child WorkflowRun(running 态,pollRunToResult 持续轮询)。
117
+ * state 可变——deadline 测试中手动翻转为 done 模拟子 run 完成。
118
+ */
119
+ function makeRunningChildRun(): WorkflowRun {
120
+ return {
121
+ runId: MOCK_RUN_ID,
122
+ spec: { scriptName: "child-wf" },
123
+ state: {
124
+ status: "running",
125
+ reason: undefined,
126
+ scriptResult: undefined,
127
+ error: undefined,
128
+ budget: { usedTokens: 0, usedCost: 0 },
129
+ },
130
+ } as unknown as WorkflowRun;
131
+ }
132
+
112
133
  /** 构造 LauncherDeps mock:registry + runs(Map)+ 占位 port。 */
113
134
  function makeDeps(opts: {
114
135
  script?: WorkflowScript;
@@ -141,6 +162,17 @@ function setupRunWorkflow(childRun: WorkflowRun): void {
141
162
 
142
163
  beforeEach(() => {
143
164
  vi.clearAllMocks();
165
+ // [F-4 假红源修复] env 隔离对称化:本文件的「不限时」用例(deadline 传导 /
166
+ // runAndWait timeoutMs 语义)依赖「XYZ_SUBAGENT_RUN_WATCHDOG_MS 未设」基线,
167
+ // 宿主 shell export 即假红(U7 describe 内部 stubEnv 不覆盖同文件其他用例)。
168
+ // 空串 = 未设(getEnvRunWatchdogMs 的 raw falsy 判定);SPAWN_WATCHDOG 同款
169
+ // 防御(launcher 不读,防未来接线后回归)。
170
+ vi.stubEnv(RUN_WATCHDOG_ENV, "");
171
+ vi.stubEnv("XYZ_SUBAGENT_SPAWN_WATCHDOG_MS", "");
172
+ });
173
+
174
+ afterEach(() => {
175
+ vi.unstubAllEnvs();
144
176
  });
145
177
 
146
178
  // ── tests ────────────────────────────────────────────────────
@@ -274,4 +306,295 @@ describe("executeNestedWorkflow", () => {
274
306
  expect(result.content).toBe("");
275
307
  expect(result.error).toBe("agent exploded");
276
308
  });
309
+
310
+ // ── deadline 传导(预算语义对齐 2026-08)──
311
+ // 语义:父 spec.budgetTimeMs 显式设定 → 原样作为子 run 轮询 deadline(不 min(DEFAULT)
312
+ // 封顶);父未设 → 无 deadline。旧实现 min(父, 10min) 把父 time:2h 截断到 10min。
313
+ describe("deadline 传导(预算语义对齐)", () => {
314
+ it("父 budgetTimeMs=2h → 子 deadline 传导 2h(不 min(10min) 封顶)", async () => {
315
+ vi.useFakeTimers();
316
+ try {
317
+ const parent = makeParentRun({ budgetTimeMs: 7_200_000 });
318
+ const childRun = makeRunningChildRun();
319
+ const deps = makeDeps({ script: makeScript(), childRun });
320
+ setupRunWorkflow(childRun);
321
+
322
+ const promise = executeNestedWorkflow("child-wf", {}, parent, deps);
323
+
324
+ // 越过旧 10min 默认:不应 abort(若回归 min 封顶,这里会触发 time_limited abort)
325
+ await vi.advanceTimersByTimeAsync(600_000 + 500);
326
+ expect(vi.mocked(abortRun)).not.toHaveBeenCalled();
327
+
328
+ // 2h deadline 到期:abortRun 收到完整 7200000ms 超时 + time_limited
329
+ await vi.advanceTimersByTimeAsync(7_200_000 + 1_000 - 600_500);
330
+ const result = await promise;
331
+ expect(vi.mocked(abortRun)).toHaveBeenCalledTimes(1);
332
+ expect(vi.mocked(abortRun)).toHaveBeenCalledWith(
333
+ MOCK_RUN_ID,
334
+ deps,
335
+ "Workflow timed out after 7200000ms",
336
+ "time_limited",
337
+ );
338
+ void result;
339
+ } finally {
340
+ vi.useRealTimers();
341
+ }
342
+ });
343
+
344
+ it("父未传 budgetTimeMs → 无 deadline(远超旧 10min 默认不 abort,子完成正常返回)", async () => {
345
+ vi.useFakeTimers();
346
+ try {
347
+ const parent = makeParentRun();
348
+ const childRun = makeRunningChildRun();
349
+ const deps = makeDeps({ script: makeScript(), childRun });
350
+ setupRunWorkflow(childRun);
351
+
352
+ const promise = executeNestedWorkflow("child-wf", {}, parent, deps);
353
+
354
+ // 旧实现 DEFAULT_RUNANDWAIT_TIMEOUT_MS=10min 会在此 abort;不限时则不 abort
355
+ await vi.advanceTimersByTimeAsync(10 * 60 * 1000 + 500);
356
+ expect(vi.mocked(abortRun)).not.toHaveBeenCalled();
357
+
358
+ // 子 run 完成 → 正常返回 completed(deadline 仍是 undefined)
359
+ childRun.state.status = "done";
360
+ childRun.state.reason = "completed";
361
+ childRun.state.scriptResult = "ok";
362
+ await vi.advanceTimersByTimeAsync(500);
363
+ const result = await promise;
364
+ // 成功分支返回 { content, parsedOutput? }(无 reason 字段)——string scriptResult 走 content
365
+ expect(result.content).toBe("ok");
366
+ expect(result.error).toBeUndefined();
367
+ expect(vi.mocked(abortRun)).not.toHaveBeenCalled();
368
+ } finally {
369
+ vi.useRealTimers();
370
+ }
371
+ });
372
+
373
+ // [U2] 预算语义统一:budgetTimeMs <=0(含 0/负)与 undefined 同义 = 不限——
374
+ // 旧实现 0 传导给子 run 后 deadline=now 立即超时("timed out after 0ms"),与
375
+ // lifecycle 的 0=不限(>0 才挂 scheduleTimeBudget)语义分裂。
376
+ it("父 budgetTimeMs=0 → 不限(旧实现立即超时;子 run 晚完成正常返回,U2)", async () => {
377
+ vi.useFakeTimers();
378
+ try {
379
+ const parent = makeParentRun({ budgetTimeMs: 0 });
380
+ const childRun = makeRunningChildRun();
381
+ const deps = makeDeps({ script: makeScript(), childRun });
382
+ setupRunWorkflow(childRun);
383
+
384
+ const promise = executeNestedWorkflow("child-wf", {}, parent, deps);
385
+
386
+ // 旧实现 0 落成 deadline=now:首轮轮询即 abort time_limited。不限时则不 abort
387
+ await vi.advanceTimersByTimeAsync(5_000);
388
+ expect(vi.mocked(abortRun)).not.toHaveBeenCalled();
389
+
390
+ childRun.state.status = "done";
391
+ childRun.state.reason = "completed";
392
+ childRun.state.scriptResult = "ok";
393
+ await vi.advanceTimersByTimeAsync(500);
394
+ const result = await promise;
395
+ expect(result.content).toBe("ok");
396
+ expect(result.error).toBeUndefined();
397
+ expect(vi.mocked(abortRun)).not.toHaveBeenCalled();
398
+ } finally {
399
+ vi.useRealTimers();
400
+ }
401
+ });
402
+
403
+ it("父 budgetTimeMs=-5000 → 不限且错误串无 \"-5000ms\"(U2 负数同义不限)", async () => {
404
+ vi.useFakeTimers();
405
+ try {
406
+ const parent = makeParentRun({ budgetTimeMs: -5_000 });
407
+ const childRun = makeRunningChildRun();
408
+ const deps = makeDeps({ script: makeScript(), childRun });
409
+ setupRunWorkflow(childRun);
410
+
411
+ const promise = executeNestedWorkflow("child-wf", {}, parent, deps);
412
+
413
+ await vi.advanceTimersByTimeAsync(5_000);
414
+ expect(vi.mocked(abortRun)).not.toHaveBeenCalled();
415
+
416
+ childRun.state.status = "done";
417
+ childRun.state.reason = "completed";
418
+ childRun.state.scriptResult = "ok";
419
+ await vi.advanceTimersByTimeAsync(500);
420
+ const result = await promise;
421
+ expect(result.content).toBe("ok");
422
+ expect(result.error).toBeUndefined();
423
+ // 防御:任何路径都不产生 "timed out after -5000ms" 类错误串
424
+ const abortCalls = vi.mocked(abortRun).mock.calls.map((c) => String(c[2]));
425
+ expect(abortCalls.join(";")).not.toContain("-5000ms");
426
+ } finally {
427
+ vi.useRealTimers();
428
+ }
429
+ });
430
+ });
431
+
432
+ // ── runAndWait timeoutMs 语义(预算语义对齐 2026-08)──
433
+ describe("runAndWait timeoutMs 语义(预算语义对齐)", () => {
434
+ it("未传 timeoutMs → 不限(远超旧 10min 默认不 abort,完成后正常返回)", async () => {
435
+ vi.useFakeTimers();
436
+ try {
437
+ const childRun = makeRunningChildRun();
438
+ const deps = makeDeps({ script: makeScript(), childRun });
439
+ setupRunWorkflow(childRun);
440
+
441
+ // 只传 3 参:不传 signal / timeoutMs
442
+ const promise = runAndWait("child-wf", {}, deps);
443
+
444
+ await vi.advanceTimersByTimeAsync(10 * 60 * 1000 + 500);
445
+ expect(vi.mocked(abortRun)).not.toHaveBeenCalled();
446
+
447
+ childRun.state.status = "done";
448
+ childRun.state.reason = "completed";
449
+ childRun.state.scriptResult = "ok";
450
+ await vi.advanceTimersByTimeAsync(500);
451
+ const result = await promise;
452
+ expect(result.status).toBe("done");
453
+ expect(result.reason).toBe("completed");
454
+ expect(vi.mocked(abortRun)).not.toHaveBeenCalled();
455
+ } finally {
456
+ vi.useRealTimers();
457
+ }
458
+ });
459
+
460
+ it("显式 timeoutMs=1000 → 到期 abort time_limited(限时能力保留)", async () => {
461
+ vi.useFakeTimers();
462
+ try {
463
+ const childRun = makeRunningChildRun();
464
+ const deps = makeDeps({ script: makeScript(), childRun });
465
+ setupRunWorkflow(childRun);
466
+
467
+ const promise = runAndWait("child-wf", {}, deps, undefined, 1_000);
468
+
469
+ await vi.advanceTimersByTimeAsync(1_000 + 500);
470
+ const result = await promise;
471
+ expect(vi.mocked(abortRun)).toHaveBeenCalledTimes(1);
472
+ expect(vi.mocked(abortRun)).toHaveBeenCalledWith(
473
+ MOCK_RUN_ID,
474
+ deps,
475
+ "Workflow timed out after 1000ms",
476
+ "time_limited",
477
+ );
478
+ void result;
479
+ } finally {
480
+ vi.useRealTimers();
481
+ }
482
+ });
483
+
484
+ // [U2] 0/负 timeoutMs 与 undefined 同义 = 不限(旧实现 0 → 立即超时、
485
+ // 负数 → "timed out after -5000ms" 类错误串)。
486
+ it("timeoutMs=0 → 不限(旧实现立即超时;不产生 \"timed out after 0ms\",U2)", async () => {
487
+ vi.useFakeTimers();
488
+ try {
489
+ const childRun = makeRunningChildRun();
490
+ const deps = makeDeps({ script: makeScript(), childRun });
491
+ setupRunWorkflow(childRun);
492
+
493
+ const promise = runAndWait("child-wf", {}, deps, undefined, 0);
494
+
495
+ await vi.advanceTimersByTimeAsync(5_000);
496
+ expect(vi.mocked(abortRun)).not.toHaveBeenCalled();
497
+
498
+ childRun.state.status = "done";
499
+ childRun.state.reason = "completed";
500
+ childRun.state.scriptResult = "ok";
501
+ await vi.advanceTimersByTimeAsync(500);
502
+ const result = await promise;
503
+ expect(result.reason).toBe("completed");
504
+ expect(vi.mocked(abortRun)).not.toHaveBeenCalled();
505
+ } finally {
506
+ vi.useRealTimers();
507
+ }
508
+ });
509
+
510
+ // [U7] XYZ_SUBAGENT_RUN_WATCHDOG_MS:显式不限时 run 的绝对时限兑底(与
511
+ // spawn watchdog env 同款:未设 = 无兑底,设置 = opt-in 挂载)。
512
+ describe("XYZ_SUBAGENT_RUN_WATCHDOG_MS 兑底(U7)", () => {
513
+ it("env 设置 + 未传 timeoutMs → env 时限到期 abort time_limited,错误串含 env 值", async () => {
514
+ vi.useFakeTimers();
515
+ try {
516
+ vi.stubEnv(RUN_WATCHDOG_ENV, "1000");
517
+ const childRun = makeRunningChildRun();
518
+ const deps = makeDeps({ script: makeScript(), childRun });
519
+ setupRunWorkflow(childRun);
520
+
521
+ const promise = runAndWait("child-wf", {}, deps);
522
+
523
+ await vi.advanceTimersByTimeAsync(1_000 + 500);
524
+ const result = await promise;
525
+ expect(vi.mocked(abortRun)).toHaveBeenCalledWith(
526
+ MOCK_RUN_ID,
527
+ deps,
528
+ "Workflow timed out after 1000ms",
529
+ "time_limited",
530
+ );
531
+ // mock abortRun 不翻转 run 状态(对齐同组 timeoutMs=1000 用例):result.reason
532
+ // 是 toResult 对 running run 的防御 fallback,不在此断言
533
+ void result;
534
+ } finally {
535
+ vi.useRealTimers();
536
+ vi.unstubAllEnvs();
537
+ }
538
+ });
539
+
540
+ it("env 设置 + 显式 timeoutMs → 显式值优先(env 不截断显式限时)", async () => {
541
+ vi.useFakeTimers();
542
+ try {
543
+ vi.stubEnv(RUN_WATCHDOG_ENV, "1000");
544
+ const childRun = makeRunningChildRun();
545
+ const deps = makeDeps({ script: makeScript(), childRun });
546
+ setupRunWorkflow(childRun);
547
+
548
+ const promise = runAndWait("child-wf", {}, deps, undefined, 60_000);
549
+
550
+ // env 1000ms 到期:不 abort(显式 60s 优先)
551
+ await vi.advanceTimersByTimeAsync(1_000 + 500);
552
+ expect(vi.mocked(abortRun)).not.toHaveBeenCalled();
553
+
554
+ // 显式 60s 到期:才 abort,错误串为显式值
555
+ await vi.advanceTimersByTimeAsync(60_000);
556
+ const result = await promise;
557
+ expect(vi.mocked(abortRun)).toHaveBeenCalledWith(
558
+ MOCK_RUN_ID,
559
+ deps,
560
+ "Workflow timed out after 60000ms",
561
+ "time_limited",
562
+ );
563
+ void result;
564
+ } finally {
565
+ vi.useRealTimers();
566
+ vi.unstubAllEnvs();
567
+ }
568
+ });
569
+
570
+ it("env 非法值(abc / -1)→ 视为未设(无兑底,不限)", async () => {
571
+ vi.useFakeTimers();
572
+ try {
573
+ const childRun = makeRunningChildRun();
574
+ const deps = makeDeps({ script: makeScript(), childRun });
575
+ setupRunWorkflow(childRun);
576
+
577
+ vi.stubEnv(RUN_WATCHDOG_ENV, "abc");
578
+ const promiseAbc = runAndWait("child-wf", {}, deps);
579
+ await vi.advanceTimersByTimeAsync(10 * 60 * 1000 + 500);
580
+ expect(vi.mocked(abortRun)).not.toHaveBeenCalled();
581
+ // 收尾完成,防用例间 promise 悬挂
582
+ childRun.state.status = "done";
583
+ childRun.state.reason = "completed";
584
+ childRun.state.scriptResult = "ok";
585
+ await vi.advanceTimersByTimeAsync(500);
586
+ await promiseAbc;
587
+
588
+ vi.mocked(abortRun).mockClear();
589
+ vi.stubEnv(RUN_WATCHDOG_ENV, "-1");
590
+ // childRun 已是 done 态:pollRunToResult 首轮即命中终态返回,无 deadline 可言
591
+ await runAndWait("child-wf", {}, deps);
592
+ expect(vi.mocked(abortRun)).not.toHaveBeenCalled();
593
+ } finally {
594
+ vi.useRealTimers();
595
+ vi.unstubAllEnvs();
596
+ }
597
+ });
598
+ });
599
+ });
277
600
  });
@@ -90,7 +90,6 @@ function makeRunningRealRun(
90
90
  const worker = { terminate, postMessage: vi.fn() } as unknown as Parameters<typeof RunRuntime.prototype.constructor>[0];
91
91
  const runtime = new RunRuntime(
92
92
  worker as never,
93
- { withSlot: vi.fn() } as never,
94
93
  controller,
95
94
  undefined,
96
95
  );
@@ -174,6 +173,16 @@ describe("scheduleTimeBudget", () => {
174
173
  expect(() => timer.unref()).not.toThrow();
175
174
  timer.unref();
176
175
  });
176
+
177
+ // [U1] setTimeout 2^31-1 溢出 fail-fast:溢出 budgetTimeMs 被 Node 置 1ms 立即触发
178
+ //(「不限时预算」变「立即超时」),arm 入口拦截且错误含上限值与恢复指引。
179
+ it("budgetTimeMs 溢出(>2^31-1)→ fail-fast throw(不挂 timer、不静默 clamp)", () => {
180
+ const deps = makeDeps();
181
+ expect(() => scheduleTimeBudget("wf-overflow", deps, 3_000_000_000)).toThrowError(/2147483647/);
182
+ expect(() => scheduleTimeBudget("wf-overflow", deps, Number.MAX_SAFE_INTEGER)).toThrowError(
183
+ /Recovery/,
184
+ );
185
+ });
177
186
  });
178
187
 
179
188
  // ── runWorkflow ──────────────────────────────────────────────
@@ -242,17 +251,42 @@ describe("runWorkflow", () => {
242
251
  expect(deps.eventBus.emit).not.toHaveBeenCalled();
243
252
  });
244
253
 
245
- it("带 budgetTimeMs 时调度时间预算计时器", async () => {
254
+ it("带 budgetTimeMs 时调度时间预算计时器(真实消费:挂载 + 到期 time_limited)", async () => {
246
255
  const deps = makeDeps();
247
- const scheduleTimeBudgetSpy = vi.fn(() => undefined);
248
- (deps as LifecycleDeps & { scheduleTimeBudget?: unknown }).scheduleTimeBudget = scheduleTimeBudgetSpy;
249
256
  const spec = makeSpec({ budgetTimeMs: 3000 });
250
257
 
251
258
  const runId = await runWorkflow(spec, deps);
259
+ const run = deps.runs.get(runId)!;
252
260
 
253
- // scheduleTimeBudget lifecycle 内被调(runWorkflow 内联调,非走 deps.scheduleTimeBudget)
254
- // 注意:runWorkflow 内直接调本文件的 scheduleTimeBudget,不读 deps.scheduleTimeBudget
255
- expect(runId).toMatch(/^wf-/);
261
+ // 生产行为面①:budgetTimeMs>0 RunRuntime.timeBudgetTimer 被真实挂载
262
+ //(scheduleTimeBudget 产出的 Node timer,非死代码 spy)
263
+ expect(run.runtime?.timeBudgetTimer).toBeDefined();
264
+
265
+ // 生产行为面②:到期后 abortRun(time_limited) 真实触发——run 转 done,
266
+ // reason/error/通知全部落位(文件级 beforeEach 已 fake timers)
267
+ await vi.advanceTimersByTimeAsync(3000);
268
+ await flushMicrotasks();
269
+
270
+ expect(run.state.status).toBe("done");
271
+ expect(run.state.reason).toBe("time_limited");
272
+ expect(run.state.error).toContain("Time budget exceeded");
273
+ expect(deps.eventBus.emit).toHaveBeenCalledWith("pending:unregister", {
274
+ id: runId,
275
+ reason: "time_limited",
276
+ });
277
+ });
278
+
279
+ it("未传 budgetTimeMs → 不挂时间预算计时器(对照:runtime.timeBudgetTimer undefined)", async () => {
280
+ const deps = makeDeps();
281
+ const runId = await runWorkflow(makeSpec(), deps);
282
+ const run = deps.runs.get(runId)!;
283
+
284
+ expect(run.runtime?.timeBudgetTimer).toBeUndefined();
285
+
286
+ // 无预算 → 不存在到期 abort:推进 10min 后 run 仍 running
287
+ await vi.advanceTimersByTimeAsync(10 * 60 * 1000);
288
+ await flushMicrotasks();
289
+ expect(run.state.status).toBe("running");
256
290
  });
257
291
 
258
292
  it("signal 已 abort → fail fast(抛错,不创建 run)", async () => {
@@ -0,0 +1,95 @@
1
+ /**
2
+ * [F1] 端到端回归:execute() 返回不可克隆值 → run 收敛到 done,failed(非永久 running 悬挂)。
3
+ *
4
+ * 完整链路(真实 Worker 线程 + 真实 WorkerHostImpl,无 mock worker):
5
+ * 脚本 return { fn: () => 1 } → postMessage DataCloneError → worker 侧 _safePost 记录 +
6
+ * F1 fallback 回发可克隆 error 消息 → 主线程 handleScriptError(既有 script-error 重试
7
+ * 矩阵:3 次 rebuild + 指数退避 1s/2s/4s)→ 第 4 次 error 超限 → run done,failed。
8
+ *
9
+ * 修复前:return 消息被静默吞掉 → worker exit(0) → handleWorkerExit(0) no-op → run 永久
10
+ * running、runAndWait 无限挂起(本测试会超时红)。
11
+ *
12
+ * 主线程 belt(exit(0) 无终态消息 → 立即 failed)由 worker-exit-without-result.test.ts
13
+ * handler 级单测覆盖;两条防线共同保证「run 必达终态」不变式。
14
+ *
15
+ * 真实退避耗时 ~7s(1+2+4s)+ 4 次 worker 启动——per-test timeout 放宽到 30s。
16
+ */
17
+ import { describe, expect, it, vi } from "vitest";
18
+
19
+ import { runWorkflow } from "../lifecycle.ts";
20
+ import type { LifecycleDeps, RunStore } from "../models/ports.ts";
21
+ import type { RunSpec } from "../models/run-spec.ts";
22
+ import type { WorkflowRun } from "../models/workflow-run.ts";
23
+ import { WorkerHostImpl } from "../worker-host.ts";
24
+
25
+ /** 轮询直到 run 到达 done 终态或超时(挂起 → 超时红,即「非悬挂」断言本身)。 */
26
+ async function waitForTerminal(
27
+ runs: Map<string, WorkflowRun>,
28
+ runId: string,
29
+ timeoutMs: number,
30
+ ): Promise<WorkflowRun> {
31
+ const deadline = Date.now() + timeoutMs;
32
+ for (;;) {
33
+ const run = runs.get(runId);
34
+ if (run && run.state.status === "done") return run;
35
+ if (Date.now() > deadline) {
36
+ throw new Error(
37
+ `run ${runId} did not reach a terminal state within ${timeoutMs}ms ` +
38
+ `(status=${run?.state.status ?? "unknown"}) — hang regression`,
39
+ );
40
+ }
41
+ await new Promise((r) => setTimeout(r, 50));
42
+ }
43
+ }
44
+
45
+ describe("[F1] 不可克隆 return → run failed(非悬挂)— e2e", () => {
46
+ it(
47
+ "return { fn: () => 1 } → 经 script-error 重试矩阵收敛到 done,failed,归因含 structured-clone failed",
48
+ async () => {
49
+ const runs = new Map<string, WorkflowRun>();
50
+ const store: RunStore = {
51
+ save: vi.fn(async () => {}),
52
+ loadAll: async () => [],
53
+ stateFilePath: (id: string) => `/tmp/f1-e2e/${id}.jsonl`,
54
+ };
55
+ const deps = {
56
+ store,
57
+ workerHost: new WorkerHostImpl(),
58
+ runner: { run: vi.fn(async () => ({})) },
59
+ runs,
60
+ eventBus: { emit: vi.fn() },
61
+ onRunDone: vi.fn(),
62
+ log: vi.fn(),
63
+ } as unknown as LifecycleDeps & { onRunDone: ReturnType<typeof vi.fn> };
64
+
65
+ const spec: RunSpec = {
66
+ scriptSource: "return { ok: true, fn: () => 1 };",
67
+ args: {},
68
+ scriptName: "f1-non-cloneable",
69
+ scriptPath: "f1-non-cloneable.js",
70
+ slug: "f1-non-cloneable",
71
+ };
72
+
73
+ const runId = await runWorkflow(spec, deps);
74
+ expect(runs.get(runId)?.state.status).toBe("running");
75
+
76
+ // 挂起 → 此处超时 throw(修复前行为);收敛 → done
77
+ const run = await waitForTerminal(runs, runId, 30_000);
78
+
79
+ expect(run.state.reason).toBe("failed");
80
+ // worker 侧 fallback 消息经 handleScriptError 超限路径写入归因
81
+ expect(run.state.error).toContain("structured-clone failed");
82
+ // 终态副作用齐全(对比 SW-DATA-3/F1 前的幽灵悬挂:无 unregister / 无 onRunDone)
83
+ expect(deps.eventBus.emit).toHaveBeenCalledWith(
84
+ "pending:unregister",
85
+ expect.objectContaining({ id: runId, reason: "failed" }),
86
+ );
87
+ expect(deps.onRunDone).toHaveBeenCalledTimes(1);
88
+ // 终态已落盘(F1 不变式的持久化半边:非但收敛,且状态被记录可恢复)
89
+ expect(store.save).toHaveBeenCalled();
90
+ // workerLogs(DataCloneError 详情)随 error 消息落入 errorLogs,诊断不丢
91
+ expect(run.state.errorLogs.length).toBeGreaterThan(0);
92
+ },
93
+ 35_000,
94
+ );
95
+ });
@@ -418,11 +418,12 @@ describe("review-fix-loop E2E(真实 worker + 场景化 mock runner)", () =>
418
418
  // m6:aggregator prompt 裁决段(5.4 ADJUDICATION)——裁决证据/降级保真/采信抽查
419
419
  const aggPrompt = prompts[kinds.indexOf("aggregate")];
420
420
  expect(aggPrompt).toContain("ADJUDICATION");
421
- // m6:fix prompt 分流文案(trivial 直接修 / involved 标记 deferred)+ 自检要求
421
+ // m6:fix prompt 全等级修复文案(must-fix + minor 都修 / minor defer 需真实阻塞理由)+ 自检要求
422
422
  const fixPrompt = prompts[kinds.indexOf("fix")];
423
423
  expect(fixPrompt).toContain("Fix scope");
424
- expect(fixPrompt).toContain("fix trivial ones");
425
- expect(fixPrompt).toContain("mark involved ones as deferred");
424
+ expect(fixPrompt).toContain("across severity levels");
425
+ expect(fixPrompt).toContain("Minor (suggestion) issues are in fix scope too");
426
+ expect(fixPrompt).toContain("concrete blocker");
426
427
  expect(fixPrompt).toContain("self_check in each fixes[] entry MUST include");
427
428
  expect(fixPrompt).toContain("grep command + hit count + sync action");
428
429
  expect(reviewCalls.length).toBe(2);
@@ -430,6 +431,59 @@ describe("review-fix-loop E2E(真实 worker + 场景化 mock runner)", () =>
430
431
  RUN_TIMEOUT_MS,
431
432
  );
432
433
 
434
+ it(
435
+ "E2E-1b:suggestions-only 轮进 fix(全等级修复语义)→ R2 全清才 clean 终止",
436
+ async () => {
437
+ const runner = makeScenarioRunner({
438
+ review: [
439
+ // R1:suggestions-only(must_fix=0 + suggestion=2)——旧语义会在 all-clean break 提前终止(漏修);
440
+ // 新语义必须走 aggregate → fix 修复建议级问题
441
+ () => ({ report_file: "/tmp/r1b-sugg.md", must_fix: 0, suggestion: 2, reconciliation: [] }),
442
+ // R2:全 0 → all-clean(must-fix 与 suggestion 双零)终止
443
+ () => ({ report_file: "/tmp/r2b-sugg.md", must_fix: 0, suggestion: 0, reconciliation: [] }),
444
+ ],
445
+ aggregate: () => ({
446
+ report_file: "/tmp/agg-sugg.md", must_fix: 0, suggestion: 2,
447
+ must_fix_ids: [], fixes_caution: [],
448
+ }),
449
+ fix: () => ({
450
+ fixed_count: 2,
451
+ fixes: [
452
+ { issue_id: "S-1", description: "fix suggestion 1", self_check: "grep: 1 hit; synced", affected_files: ["src/a.ts"] },
453
+ { issue_id: "S-2", description: "fix suggestion 2", self_check: "grep: 1 hit; synced", affected_files: ["src/b.ts"] },
454
+ ],
455
+ deferred: [],
456
+ }),
457
+ });
458
+ const deps = makeDeps(runner);
459
+
460
+ const result = await runAndWait(
461
+ wf("review-fix-loop"),
462
+ { targetType: "file", target: "README.md", agents: agentMd("reviewer"), _runId: RUN_ID() },
463
+ deps,
464
+ undefined,
465
+ RUN_TIMEOUT_MS,
466
+ );
467
+
468
+ expect(result.reason).toBe("completed");
469
+ expect(result.error).toBeUndefined();
470
+ const outcome = assertScriptOutcome(result.scriptResult);
471
+ expect(outcome.terminated).toBe("clean");
472
+ expect(outcome.totalFixed).toBe(2);
473
+
474
+ // 关键差异:suggestions-only 轮也派 fixer(旧语义 R1 即 all-clean break,0 次 fix)
475
+ const { kinds, reviewCalls, prompts } = runner.stats();
476
+ expect(reviewCalls.length).toBe(2);
477
+ expect(kinds.filter((k) => k === "fix").length).toBe(1);
478
+ expect(kinds.filter((k) => k === "aggregate").length).toBe(1);
479
+ // fix prompt 携带全等级修复指令
480
+ const fixPrompt = prompts[kinds.indexOf("fix")];
481
+ expect(fixPrompt).toContain("across severity levels");
482
+ expect(fixPrompt).toContain("Minor (suggestion) issues are in fix scope too");
483
+ },
484
+ RUN_TIMEOUT_MS,
485
+ );
486
+
433
487
  it(
434
488
  "E2E-2:skipCleanAgents 语义(clean agent 下轮跳过)+ fixAgent 参数接受(§7.2 2/3)",
435
489
  async () => {
@@ -155,3 +155,47 @@ describe("resolveSkillPath — 结果缓存(IF8/DM3)", () => {
155
155
  expect(existsSyncCalls.count).toBeGreaterThan(callsAfterFirst); // 重扫发生
156
156
  });
157
157
  });
158
+
159
+ describe("resolveSkillPath — `..` 穿越守卫(三通道对称修复:skill 名是名字不是路径)", () => {
160
+ it("project 源:含 .. 逃逸 skills 根的名字 → not found(即使逃逸目标真实存在)", () => {
161
+ vi.spyOn(process, "cwd").mockReturnValue(projRoot);
162
+ // 逃逸目标真实存在:projRoot/.agents/skills/../../escape-target = projRoot/escape-target。
163
+ // 旧实现 path.resolve 吸收 .. 后 existsSync 命中 → 返回树外目录;守卫后必须 undefined。
164
+ mkdirp(join(projRoot, "escape-target"));
165
+
166
+ expect(resolveSkillPath("../../escape-target")).toBeUndefined();
167
+ });
168
+
169
+ it("user 源:含 .. 逃逸的名字 → not found(同样不受 existsSync 命中误导)", () => {
170
+ vi.spyOn(process, "cwd").mockReturnValue(projRoot);
171
+ // user skills 根 = homeRoot/.pi/agent/skills;../../escape-target → homeRoot/escape-target。
172
+ mkdirp(join(homeRoot, "escape-target"));
173
+
174
+ expect(resolveSkillPath("../../escape-target")).toBeUndefined();
175
+ });
176
+
177
+ it("npm 源:含 .. 逃逸包内 skills 根的名字 → not found", () => {
178
+ vi.spyOn(process, "cwd").mockReturnValue(projRoot);
179
+ // npm skills 根 = homeRoot/.pi/agent/npm/node_modules/pkg/skills;"../steal" 逃逸到 node_modules/<pkg>/steal。
180
+ mkdirp(join(homeRoot, ".pi/agent/npm/node_modules/pkg-a/steal"));
181
+
182
+ expect(resolveSkillPath("../steal")).toBeUndefined();
183
+ });
184
+
185
+ it("根内归一化不被误拒:sub/../real 解析后仍在 skills 根内,正常命中", () => {
186
+ vi.spyOn(process, "cwd").mockReturnValue(projRoot);
187
+ const real = join(projRoot, ".agents/skills", "real");
188
+ mkdirp(real);
189
+
190
+ // 守卫只拒逃逸,不拒归一化:root/sub/../real = root/real(根内)→ 命中。
191
+ expect(resolveSkillPath("sub/../real")).toBe(real);
192
+ });
193
+
194
+ it("绝对路径形式的 skill 名 → not found(名字不具备绝对寻址能力)", () => {
195
+ vi.spyOn(process, "cwd").mockReturnValue(projRoot);
196
+ mkdirp(join(projRoot, "outside-abs"));
197
+
198
+ // resolve(root, "/outside-abs") = /outside-abs —— 树外,拒。
199
+ expect(resolveSkillPath(join(projRoot, "outside-abs"))).toBeUndefined();
200
+ });
201
+ });