@zhushanwen/pi-subagent-workflow 8.5.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 (92) hide show
  1. package/package.json +7 -6
  2. package/src/execution/__tests__/bg-notify-render.test.ts +73 -0
  3. package/src/execution/__tests__/chat-engine-routing.test.ts +6 -2
  4. package/src/execution/__tests__/delivery-methods.test.ts +38 -1
  5. package/src/execution/__tests__/execute-options-mapper.test.ts +11 -0
  6. package/src/execution/__tests__/execution-record.test.ts +110 -0
  7. package/src/execution/__tests__/explicit-agent-ref-guard.test.ts +171 -0
  8. package/src/execution/__tests__/format-schema-instruction.test.ts +63 -32
  9. package/src/execution/__tests__/helpers/spawn-mock.ts +4 -0
  10. package/src/execution/__tests__/index-session-start.test.ts +86 -7
  11. package/src/execution/__tests__/lifecycle-manager.test.ts +46 -0
  12. package/src/execution/__tests__/list-fields.test.ts +45 -14
  13. package/src/execution/__tests__/model-resolver.test.ts +57 -5
  14. package/src/execution/__tests__/notifier-flush.test.ts +64 -26
  15. package/src/execution/__tests__/notify-ledger.test.ts +826 -0
  16. package/src/execution/__tests__/output-collector.test.ts +299 -2
  17. package/src/execution/__tests__/rpc-mode.test.ts +1 -1
  18. package/src/execution/__tests__/run-spawn-edges.test.ts +44 -1
  19. package/src/execution/__tests__/run-spawn-stdout-callback-throw.test.ts +199 -0
  20. package/src/execution/__tests__/session-runner-schema-env.test.ts +39 -0
  21. package/src/execution/__tests__/spawn-args.test.ts +37 -26
  22. package/src/execution/__tests__/start-sync-model-guard.test.ts +150 -0
  23. package/src/execution/__tests__/subprocess-agent-runner.test.ts +94 -1
  24. package/src/execution/__tests__/timeout-integration.test.ts +220 -2
  25. package/src/execution/__tests__/tool-action.test.ts +92 -1
  26. package/src/execution/agent-registry.ts +6 -0
  27. package/src/execution/argv-mirror.ts +5 -1
  28. package/src/execution/concurrency-pool.ts +1 -1
  29. package/src/execution/engine/engines/zcode/__tests__/zcode-engine.test.ts +13 -0
  30. package/src/execution/engine/engines/zcode/zcode-engine.ts +11 -1
  31. package/src/execution/engine/types.ts +6 -1
  32. package/src/execution/execute-options-mapper.ts +8 -7
  33. package/src/execution/execution-record.ts +60 -1
  34. package/src/execution/lifecycle-manager.ts +23 -1
  35. package/src/execution/model-config-service.ts +16 -1
  36. package/src/execution/model-resolver.ts +31 -59
  37. package/src/execution/notifier.ts +105 -35
  38. package/src/execution/notify-ledger.ts +580 -0
  39. package/src/execution/output-collector.ts +143 -3
  40. package/src/execution/session-runner.ts +304 -71
  41. package/src/execution/subagent-service.ts +24 -2
  42. package/src/execution/subprocess-agent-runner.ts +14 -0
  43. package/src/execution/types.ts +68 -5
  44. package/src/execution/ui-request-queue.ts +14 -4
  45. package/src/index.ts +54 -1
  46. package/src/interface/__tests__/subagent-tool-path-guard.test.ts +157 -0
  47. package/src/interface/__tests__/subagent-tool-prompt.test.ts +12 -0
  48. package/src/interface/bg-notify-render.ts +33 -12
  49. package/src/interface/helpers.ts +2 -2
  50. package/src/interface/subagent-actions.ts +26 -9
  51. package/src/interface/subagent-tool-schema.ts +156 -0
  52. package/src/interface/subagent-tool.ts +56 -125
  53. package/src/interface/subagents.ts +2 -2
  54. package/src/orchestration/__tests__/__fixtures__/worker-template.snapshot.txt +16 -3
  55. package/src/orchestration/__tests__/agent-call-catch-fallback.test.ts +0 -6
  56. package/src/orchestration/__tests__/agent-call-stream.test.ts +0 -5
  57. package/src/orchestration/__tests__/error-recovery-handlers.test.ts +89 -4
  58. package/src/orchestration/__tests__/execute-agent-call.test.ts +137 -0
  59. package/src/orchestration/__tests__/jsonl-run-store-corrupt-entry.test.ts +150 -0
  60. package/src/orchestration/__tests__/jsonl-run-store-retention.test.ts +202 -0
  61. package/src/orchestration/__tests__/launcher-nested-workflow.test.ts +326 -3
  62. package/src/orchestration/__tests__/lifecycle.test.ts +41 -7
  63. package/src/orchestration/__tests__/non-cloneable-return-e2e.test.ts +95 -0
  64. package/src/orchestration/__tests__/review-fix-loop-e2e.test.ts +57 -3
  65. package/src/orchestration/__tests__/skill-discovery.test.ts +44 -0
  66. package/src/orchestration/__tests__/worker-exit-without-result.test.ts +368 -0
  67. package/src/orchestration/__tests__/worker-script-builder-runtime.test.ts +43 -0
  68. package/src/orchestration/__tests__/worker-script-template-snapshot.test.ts +21 -2
  69. package/src/orchestration/agent-opts-resolver.ts +104 -23
  70. package/src/orchestration/error-recovery.ts +189 -33
  71. package/src/orchestration/execute-agent-call.ts +39 -0
  72. package/src/orchestration/jsonl-run-store.ts +121 -7
  73. package/src/orchestration/launcher.ts +60 -15
  74. package/src/orchestration/lifecycle.ts +10 -7
  75. package/src/orchestration/models/__tests__/budget.test.ts +1 -61
  76. package/src/orchestration/models/budget.ts +5 -35
  77. package/src/orchestration/models/run-runtime.ts +24 -9
  78. package/src/orchestration/models/types.ts +9 -0
  79. package/src/orchestration/script-lint.ts +1 -1
  80. package/src/orchestration/skill-discovery.ts +31 -8
  81. package/src/orchestration/worker-script-builder.ts +16 -3
  82. package/src/shared/__tests__/model-ref.test.ts +306 -0
  83. package/src/shared/__tests__/schema-jsonify.test.ts +1 -1
  84. package/src/shared/__tests__/timer-delay.test.ts +61 -0
  85. package/src/shared/model-ref.ts +286 -0
  86. package/src/shared/schema-env.ts +44 -0
  87. package/src/shared/schema-jsonify.ts +6 -4
  88. package/src/shared/timer-delay.ts +54 -0
  89. package/workflows/review-fix-loop-utils.cjs +9 -7
  90. package/workflows/review-fix-loop.js +20 -12
  91. package/src/orchestration/__tests__/concurrency-gate.test.ts +0 -125
  92. package/src/orchestration/concurrency-gate.ts +0 -69
@@ -5,8 +5,9 @@
5
5
  // (usage 收口进 getTotalUsage,text 收口进 getFullText,均在 execution-record.test 测)。
6
6
  import { describe, expect, it } from "vitest";
7
7
 
8
- import { extractParsedOutput } from "../output-collector.ts";
9
- import type { ToolCall } from "../types.ts";
8
+ import { isStaleContextErrorMsg, DETERMINISTIC_SCHEMA_FAILURE_PREFIX, isDeterministicSchemaFailureMsg, STALE_CONTEXT_PATTERNS } from "../../orchestration/execute-agent-call.ts";
9
+ import { collectResult, describeMissingParsedOutput, extractParsedOutput, neutralizeStalePatterns } from "../output-collector.ts";
10
+ import type { ExecutionRecord, ToolCall } from "../types.ts";
10
11
 
11
12
  // ============================================================
12
13
  // extractParsedOutput
@@ -58,4 +59,300 @@ describe("extractParsedOutput", () => {
58
59
  ];
59
60
  expect(extractParsedOutput(calls)).toEqual({ ok: true });
60
61
  });
62
+
63
+ // [F-1 失败吞没修复] 失败调用(pi 失败路径 details 默认 {})的 details 不是
64
+ // schema 校验产出——journal 实锤 tool_end isError=true details={} 曾被当
65
+ // parsedOutput,gate 终止/模型自弃的 run 以 parsedOutput={} 静默 completed。
66
+ it("skips failed structured-output call with details:{} (isError=true) — no parsedOutput", () => {
67
+ const calls: ToolCall[] = [
68
+ { toolName: "bash", result: { content: [] } },
69
+ { toolName: "structured-output", isError: true, result: { details: {}, content: [{ type: "text", text: "Schema validation failed: /target is required" }] } },
70
+ ];
71
+ expect(extractParsedOutput(calls)).toBeUndefined();
72
+ });
73
+
74
+ it("skips failed call with details, still picks later valid call (reverse order)", () => {
75
+ const calls: ToolCall[] = [
76
+ { toolName: "structured-output", isError: true, result: { details: {} } },
77
+ { toolName: "structured-output", result: { details: { fixed: true } } },
78
+ ];
79
+ expect(extractParsedOutput(calls)).toEqual({ fixed: true });
80
+ });
81
+
82
+ it("isError on non-structured-output calls does not affect extraction", () => {
83
+ const calls: ToolCall[] = [
84
+ { toolName: "bash", isError: true, result: { details: "ignored" } },
85
+ { toolName: "structured-output", result: { details: { answer: 1 } } },
86
+ ];
87
+ expect(extractParsedOutput(calls)).toEqual({ answer: 1 });
88
+ });
89
+ });
90
+
91
+ // ============================================================
92
+ // describeMissingParsedOutput(F-1 三态归因)
93
+ // ============================================================
94
+
95
+ describe("describeMissingParsedOutput", () => {
96
+ it("returns undefined when a valid parsedOutput exists", () => {
97
+ const calls: ToolCall[] = [
98
+ { toolName: "structured-output", isError: true, result: { details: {} } },
99
+ { toolName: "structured-output", result: { details: { ok: 1 } } },
100
+ ];
101
+ expect(describeMissingParsedOutput(calls)).toBeUndefined();
102
+ });
103
+
104
+ it("state 1: validation failure — isError calls present, error carries last summary", () => {
105
+ const calls: ToolCall[] = [
106
+ { toolName: "structured-output", isError: true, result: { details: {}, content: [{ type: "text", text: "Schema validation failed: /target is required" }] } },
107
+ ];
108
+ const msg = describeMissingParsedOutput(calls);
109
+ expect(msg).toContain("failed");
110
+ expect(msg).toContain("1 structured-output call(s) failed");
111
+ expect(msg).toContain("Schema validation failed: /target is required");
112
+ });
113
+
114
+ it("state 2: structured-output never called — error hints to check extension install (C1 blind spot)", () => {
115
+ const calls: ToolCall[] = [
116
+ { toolName: "bash", result: { content: [] } },
117
+ { toolName: "read", result: { content: [] } },
118
+ ];
119
+ const msg = describeMissingParsedOutput(calls);
120
+ expect(msg).toContain("structured-output tool was never called");
121
+ expect(msg).toContain("structured-output extension is installed");
122
+ });
123
+
124
+ it("state 3: SO called successfully but no details", () => {
125
+ const calls: ToolCall[] = [
126
+ { toolName: "structured-output", result: { content: [] } },
127
+ ];
128
+ const msg = describeMissingParsedOutput(calls);
129
+ expect(msg).toContain("none of the successful calls carried result details");
130
+ });
131
+
132
+ it("empty toolCalls → state 2 (never called)", () => {
133
+ expect(describeMissingParsedOutput([])).toContain("never called");
134
+ });
135
+
136
+ it("summary truncates long error text (300 chars cap)", () => {
137
+ const longText = "x".repeat(500);
138
+ const calls: ToolCall[] = [
139
+ { toolName: "structured-output", isError: true, result: { details: {}, content: [{ type: "text", text: longText }] } },
140
+ ];
141
+ const msg = describeMissingParsedOutput(calls);
142
+ expect(msg).toContain("...");
143
+ expect(msg!.length).toBeLessThan(longText.length);
144
+ });
145
+
146
+ // 文案约束:不得命中 execute-agent-call 的 STALE_CONTEXT_PATTERNS("aborted" 等),
147
+ // 否则会被误诊为 stale-context 跳过重试。
148
+ it("messages avoid STALE_CONTEXT_PATTERNS substrings (no false stale-context triage)", () => {
149
+ const samples = [
150
+ describeMissingParsedOutput([])!,
151
+ describeMissingParsedOutput([{ toolName: "structured-output", isError: true, result: { details: {} } }])!,
152
+ describeMissingParsedOutput([{ toolName: "structured-output", result: { content: [] } }])!,
153
+ ];
154
+ for (const msg of samples) {
155
+ const lower = msg.toLowerCase();
156
+ expect(lower).not.toContain("aborted");
157
+ expect(lower).not.toContain("ctx is stale");
158
+ expect(lower).not.toContain("context canceled");
159
+ }
160
+ });
161
+
162
+ // ── [F-R1] 态2(isError 分支)错误摘要拼接段中和 ──
163
+ //
164
+ // 动态错误文本(模型/provider 原始错误)可能携带 "aborted"/"ctx is stale" 等
165
+ // STALE_CONTEXT_PATTERNS 词;不中和则归因 error 经 collectResult → result.error
166
+ // 流到 execute-agent-call 的 isStaleContextErrorMsg 分诊,被误诊为 stale-context
167
+ // 跳过重试。固定前缀静态无命中(上一用例锁定),中和只针对动态段。
168
+ describe("F-R1: 态2 错误摘要 STALE_CONTEXT_PATTERNS 中和", () => {
169
+ function failedSoCallsWith(text: string): ToolCall[] {
170
+ return [
171
+ { toolName: "structured-output", isError: true, result: { details: {}, content: [{ type: "text", text }] } },
172
+ ];
173
+ }
174
+
175
+ it("失败 content 含 'aborted'/'ctx is stale' → 摘要被 [redacted],归因 error 不触发 isStaleContextErrorMsg", () => {
176
+ const msg = describeMissingParsedOutput(
177
+ failedSoCallsWith("Request aborted: context canceled — ctx is stale after session replacement"),
178
+ )!;
179
+ expect(msg).toContain("[redacted]");
180
+ const lower = msg.toLowerCase();
181
+ expect(lower).not.toContain("aborted");
182
+ expect(lower).not.toContain("ctx is stale");
183
+ expect(lower).not.toContain("context canceled");
184
+ // 消费点语义锁定:归因 error 进入 stale-context 分诊必须为 false(可重试)
185
+ expect(isStaleContextErrorMsg(msg)).toBe(false);
186
+ });
187
+
188
+ it("大小写变体('ABORTED')同样被中和(分诊是大小写不敏感子串匹配)", () => {
189
+ const msg = describeMissingParsedOutput(failedSoCallsWith("ABORTED by provider"))!;
190
+ expect(msg).toContain("[redacted]");
191
+ expect(isStaleContextErrorMsg(msg)).toBe(false);
192
+ });
193
+
194
+ it("无动态内容时整条归因也不命中(防御回归锁定)", () => {
195
+ const msg = describeMissingParsedOutput([
196
+ { toolName: "structured-output", isError: true, result: { details: {} } },
197
+ ])!;
198
+ expect(isStaleContextErrorMsg(msg)).toBe(false);
199
+ });
200
+
201
+ it("neutralizeStalePatterns:多 pattern 同时命中 + 无命中原样透传", () => {
202
+ expect(neutralizeStalePatterns("aborted CTX IS STALE / context canceled")).toBe(
203
+ "[redacted] [redacted] / [redacted]",
204
+ );
205
+ expect(neutralizeStalePatterns("provider socket hang up")).toBe("provider socket hang up");
206
+ });
207
+ });
208
+
209
+ // ── [F-R4] 态2 文案按最后错误内容分类,不再硬编码 "(schema validation)" ──
210
+ describe("F-R4: 态2 失败原因分类", () => {
211
+ it("最后错误含 'validation failed'(大小写不敏感)→ (schema validation)", () => {
212
+ const calls: ToolCall[] = [
213
+ { toolName: "structured-output", isError: true, result: { details: {}, content: [{ type: "text", text: "Schema validation failed: /target is required" }] } },
214
+ ];
215
+ const msg = describeMissingParsedOutput(calls)!;
216
+ expect(msg).toContain("(schema validation)");
217
+ expect(msg).not.toContain("(execution failure)");
218
+ });
219
+
220
+ it("最后错误为非校验失败(如 provider 错误)→ (execution failure)", () => {
221
+ const calls: ToolCall[] = [
222
+ { toolName: "structured-output", isError: true, result: { details: {}, content: [{ type: "text", text: "provider socket hang up" }] } },
223
+ ];
224
+ const msg = describeMissingParsedOutput(calls)!;
225
+ expect(msg).toContain("(execution failure)");
226
+ expect(msg).not.toContain("(schema validation)");
227
+ });
228
+ });
229
+ });
230
+
231
+ // ============================================================
232
+ // MF-1: 三态可重试性矩阵(确定性失败标记)
233
+ // ============================================================
234
+
235
+ describe("MF-1: 三态可重试性矩阵(确定性失败标记)", () => {
236
+ // 矩阵(SSOT 注释在 execute-agent-call DETERMINISTIC_SCHEMA_FAILURE_PREFIX 与
237
+ // describeMissingParsedOutput JSDoc,本 describe 是执行面锁定):
238
+ // 态① 从未调用 SO → 带标记 → 不可重试(环境确定性,C1 安装盲区)
239
+ // 态② SO isError(gate 终止/不可满足 schema)→ 带标记 → 不可重试(同 schema 重试必同结果)
240
+ // 态③ 调用过但无 details → 无标记 → 可重试(可能瞬态,保留既有重试语义)
241
+
242
+ it("态① 从未调用 SO → error 以确定性标记开头(不可重试)", () => {
243
+ const msg = describeMissingParsedOutput([])!;
244
+ expect(msg.startsWith(DETERMINISTIC_SCHEMA_FAILURE_PREFIX)).toBe(true);
245
+ expect(isDeterministicSchemaFailureMsg(msg)).toBe(true);
246
+ });
247
+
248
+ it("态② isError/schema validation 子类 → error 以确定性标记开头(不可重试)", () => {
249
+ const msg = describeMissingParsedOutput([
250
+ { toolName: "structured-output", isError: true, result: { details: {}, content: [{ type: "text", text: "Schema validation failed: /target is required" }] } },
251
+ ])!;
252
+ expect(msg.startsWith(DETERMINISTIC_SCHEMA_FAILURE_PREFIX)).toBe(true);
253
+ expect(isDeterministicSchemaFailureMsg(msg)).toBe(true);
254
+ });
255
+
256
+ it("态② execution failure 子类(provider 瞬态)同样带标记(isError 态整体不重试)", () => {
257
+ const msg = describeMissingParsedOutput([
258
+ { toolName: "structured-output", isError: true, result: { details: {}, content: [{ type: "text", text: "provider socket hang up" }] } },
259
+ ])!;
260
+ expect(isDeterministicSchemaFailureMsg(msg)).toBe(true);
261
+ });
262
+
263
+ it("态③ 调用过但无 details → 不带标记(可重试语义保留)", () => {
264
+ const msg = describeMissingParsedOutput([
265
+ { toolName: "structured-output", result: { content: [] } },
266
+ ])!;
267
+ expect(isDeterministicSchemaFailureMsg(msg)).toBe(false);
268
+ });
269
+
270
+ it("有有效 parsedOutput → 无归因无标记(不适用矩阵)", () => {
271
+ expect(
272
+ describeMissingParsedOutput([{ toolName: "structured-output", result: { details: { ok: 1 } } }]),
273
+ ).toBeUndefined();
274
+ });
275
+
276
+ // 验收④:标记词不命中 STALE_CONTEXT_PATTERNS——若命中,isStaleContextErrorMsg
277
+ // 分诊(判定在前)会抢先归因 stale-context,虽然同样不重试,但归因语义被污染
278
+ // (TUI/日志把 schema 失败误报为 stale)。
279
+ it("标记词与全部 STALE_CONTEXT_PATTERNS 零交集,isStaleContextErrorMsg 不抢先", () => {
280
+ const lower = DETERMINISTIC_SCHEMA_FAILURE_PREFIX.toLowerCase();
281
+ for (const pattern of STALE_CONTEXT_PATTERNS) {
282
+ expect(lower.includes(pattern)).toBe(false);
283
+ }
284
+ expect(isStaleContextErrorMsg(DETERMINISTIC_SCHEMA_FAILURE_PREFIX)).toBe(false);
285
+ });
286
+ });
287
+
288
+ // ============================================================
289
+ // collectResult — F-1 集成行为(schemaExpected → 失败标注)
290
+ // ============================================================
291
+
292
+ describe("collectResult — F-1 schemaExpected 失败标注", () => {
293
+ /** 最小 ExecutionRecord stub(collectResult 只读 turns/toolCalls 派生面)。 */
294
+ function makeRecordWithCalls(calls: ToolCall[]): ExecutionRecord {
295
+ return {
296
+ id: "rec-1",
297
+ turns: [{ toolCalls: calls, text: "done", turnCount: 1, closed: true }],
298
+ turnCount: 1,
299
+ } as unknown as ExecutionRecord;
300
+ }
301
+
302
+ const baseArgs = {
303
+ startTime: Date.now(),
304
+ sessionId: "s-1",
305
+ sessionFile: undefined,
306
+ };
307
+
308
+ it("schemaExpected + failed SO call (details:{}) + success=true → success=false + error attributed", () => {
309
+ const record = makeRecordWithCalls([
310
+ { toolName: "structured-output", isError: true, result: { details: {}, content: [{ type: "text", text: "validation boom" }] } },
311
+ ]);
312
+ const result = collectResult(record, { ...baseArgs, success: true, error: undefined, schemaExpected: true });
313
+ expect(result.success).toBe(false);
314
+ expect(result.error).toContain("validation boom");
315
+ expect(result.parsedOutput).toBeUndefined();
316
+ });
317
+
318
+ it("schemaExpected + never called SO + success=true → error hints extension check", () => {
319
+ const record = makeRecordWithCalls([{ toolName: "bash", result: { content: [] } }]);
320
+ const result = collectResult(record, { ...baseArgs, success: true, error: undefined, schemaExpected: true });
321
+ expect(result.success).toBe(false);
322
+ expect(result.error).toContain("structured-output extension is installed");
323
+ });
324
+
325
+ it("schemaExpected + valid details → success preserved (S3 e2e semantics no regression)", () => {
326
+ const record = makeRecordWithCalls([
327
+ { toolName: "structured-output", result: { details: { answer: 42 } } },
328
+ ]);
329
+ const result = collectResult(record, { ...baseArgs, success: true, error: undefined, schemaExpected: true });
330
+ expect(result.success).toBe(true);
331
+ expect(result.error).toBeUndefined();
332
+ expect(result.parsedOutput).toEqual({ answer: 42 });
333
+ });
334
+
335
+ it("no schemaExpected (plain mode) + no SO call → success unchanged", () => {
336
+ const record = makeRecordWithCalls([{ toolName: "bash", result: { content: [] } }]);
337
+ const result = collectResult(record, { ...baseArgs, success: true, error: undefined });
338
+ expect(result.success).toBe(true);
339
+ expect(result.parsedOutput).toBeUndefined();
340
+ });
341
+
342
+ it("success=false path: existing error not overwritten by F-1 attribution", () => {
343
+ const record = makeRecordWithCalls([]);
344
+ const result = collectResult(record, { ...baseArgs, success: false, error: "provider boom", schemaExpected: true });
345
+ expect(result.success).toBe(false);
346
+ expect(result.error).toBe("provider boom");
347
+ });
348
+
349
+ it("[MF-1] F-1 标注的 error 携带确定性标记(流到 executeAgentCall 即不可重试)", () => {
350
+ const record = makeRecordWithCalls([
351
+ { toolName: "structured-output", isError: true, result: { details: {}, content: [{ type: "text", text: "Schema validation failed: /target is required" }] } },
352
+ ]);
353
+ const result = collectResult(record, { ...baseArgs, success: true, error: undefined, schemaExpected: true });
354
+ expect(result.success).toBe(false);
355
+ expect(result.error).toBeDefined();
356
+ expect(isDeterministicSchemaFailureMsg(result.error)).toBe(true);
357
+ });
61
358
  });
@@ -11,7 +11,7 @@ import { parseSpawnLine } from "../spawn-event-adapter.ts";
11
11
 
12
12
  describe("buildSpawnArgs - RPC mode", () => {
13
13
  const baseParams = {
14
- model: "gpt-4",
14
+ modelRef: { provider: "openai", id: "gpt-4" },
15
15
  thinkingLevel: undefined,
16
16
  agentTools: undefined,
17
17
  appendSystemPromptPath: undefined,
@@ -69,7 +69,7 @@ vi.mock("../temp-prompt.ts", () => ({
69
69
  cleanupTempPrompt: vi.fn(async () => {}),
70
70
  }));
71
71
 
72
- import { killAllSpawnedChildren, runSpawn, spawnedChildren, WAKEUP_GRACE_MS, computeWatchdogMs } from "../session-runner.ts";
72
+ import { killAllSpawnedChildren, runSpawn, spawnedChildren, WAKEUP_GRACE_MS, computeWatchdogMs, SPAWN_WATCHDOG_ENV } from "../session-runner.ts";
73
73
  import { readActivePendingFromSessionFile } from "../session-pending.ts";
74
74
  import {
75
75
  emitStdoutLine,
@@ -98,10 +98,16 @@ describe("runSpawn", () => {
98
98
  vi.clearAllMocks();
99
99
  // existsSync 默认 false(sessionFile 不存在兜底路径)
100
100
  mockExistsSync.mockReturnValue(false);
101
+ // [F-4 假红源修复] env 隔离:makeOpts 默认 maxTurns=undefined →
102
+ // resolveSpawnWatchdogMs 走 env 兑底分支,宿主 export SPAWN_WATCHDOG 即假红。
103
+ // 空串 = 未设(raw falsy 判定);MF-4b 用例内的手动 save/delete/restore 与本
104
+ // stub 兼容(finally 恢复到 stub 值,语义不变)。
105
+ vi.stubEnv(SPAWN_WATCHDOG_ENV, "");
101
106
  });
102
107
 
103
108
  afterEach(() => {
104
109
  vi.restoreAllMocks();
110
+ vi.unstubAllEnvs();
105
111
  });
106
112
 
107
113
  // ── 1. orphan 进程兜底(C1)──
@@ -492,6 +498,43 @@ describe("runSpawn", () => {
492
498
  }
493
499
  });
494
500
 
501
+ // [MF-4b] 预算语义对齐:maxTurns 未传且无兑底 env → count>0 分支不 re-arm watchdog,
502
+ // 不限时等待后代。若误回旧 50min 估算默认,51min 处会 kill,本用例失败。
503
+ it("MF-4b: agent_end(count>0)+ maxTurns 未传 → 不 re-arm watchdog(不限时等待)", async () => {
504
+ // hermetic:确保兑底 env 未设(若外层 shell 误设会让「不限时」断言失效)
505
+ const prevWatchdogEnv = process.env[SPAWN_WATCHDOG_ENV];
506
+ delete process.env[SPAWN_WATCHDOG_ENV];
507
+ mockPending.mockReturnValue({ count: 2 });
508
+ const record = makeRecord();
509
+ const promise = runSpawn(record, "Task: slow-desc-no-turns", makeOpts(), makeCtx());
510
+
511
+ await waitForSpawn();
512
+ const child = lastSpawnedChild();
513
+
514
+ vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout", "Date"] });
515
+ try {
516
+ emitStdoutLine(child, sessionHeader());
517
+ emitStdoutLine(child, { type: "agent_end", messages: [], willRetry: false });
518
+ await new Promise((r) => setImmediate(r));
519
+ // keep alive:不 kill
520
+ expect(child.killed).toBe(false);
521
+
522
+ // 超过旧 50min 估算默认仍不 kill = watchdog 未 re-arm
523
+ await vi.advanceTimersByTimeAsync(51 * 60 * 1000);
524
+ expect(child.killed).toBe(false);
525
+
526
+ child.stdout.end();
527
+ child.stderr.end();
528
+ child.emit("close", 143);
529
+
530
+ const result = await promise;
531
+ expect(result.success).toBe(true);
532
+ } finally {
533
+ if (prevWatchdogEnv !== undefined) process.env[SPAWN_WATCHDOG_ENV] = prevWatchdogEnv;
534
+ vi.useRealTimers();
535
+ }
536
+ });
537
+
495
538
  // [S-9] pending.error 分支(sessionFile 不可读 → 保守 keep-alive + re-arm dynamic watchdog)
496
539
  // 集成行为 guard:session-pending 单测覆盖 error 返回值,但 session-runner 的 no-kill +
497
540
  // re-arm 到 computeWatchdogMs(maxTurns) 行为无集成 guard。若 re-arm 误删/误用固定超时,
@@ -0,0 +1,199 @@
1
+ // src/execution/__tests__/run-spawn-stdout-callback-throw.test.ts
2
+ //
3
+ // [F-R2] stdout data 同步回调链内 fail-fast throw 不逃逸(不升级为 uncaughtException 崩宿主)。
4
+ //
5
+ // 背景:session-runner 的两处 timer 安全校验调用位于 child.stdout.on("data") 同步回调链内:
6
+ // ① agent_end keep-alive 分支的 resolveSpawnWatchdogMs(→ assertSafeTimerDelay fail-fast)
7
+ // ② chatMode agent_settled 分支的 armIdleTimer(→ assertSafeTimerDelay fail-fast)
8
+ // 旧实现任一处 throw 都会逃出事件回调 = Node uncaughtException 崩宿主进程。
9
+ // 修复:调用点包 try/catch 降级(不挂 timer),错误经 bestEffort("error") 可见。
10
+ //
11
+ // mock 结构与 run-spawn-chatmode-settled.test.ts 一致(FakeChild + lifecycle-manager 真实模块)。
12
+ // logger 整体 mock(loggerMock spy)断言错误可见——「fail-fast 语义保留(错误可见、行为明确)
13
+ // 但不升级为进程崩溃」。
14
+ import { spawn } from "node:child_process";
15
+ import * as fs from "node:fs";
16
+
17
+ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
18
+
19
+ // logger mock:bestEffort / session-runner 共享同一 loggerMock(断言错误可见性)。
20
+ // vi.hoisted:vi.mock 工厂被提升到顶层 const 之前执行,loggerMock 必须经 vi.hoisted 创建。
21
+ const { loggerMock } = vi.hoisted(() => ({
22
+ loggerMock: { debug: vi.fn(), info: vi.fn(), warn: vi.fn(), error: vi.fn() },
23
+ }));
24
+ vi.mock("@zhushanwen/pi-extension-logger", () => ({ getLogger: () => loggerMock }));
25
+
26
+ vi.mock("node:child_process", async () => {
27
+ const { FakeChild } = await import("./helpers/spawn-mock.ts");
28
+ return {
29
+ spawn: vi.fn(() => new FakeChild()),
30
+ // buildEnvBlock 的 git branch 调用(execFile 异步):默认 err-first 兜底 → catch → branch=""
31
+ execFile: vi.fn(
32
+ (
33
+ _cmd: string,
34
+ _args: readonly string[],
35
+ _opts: unknown,
36
+ cb: (err: Error | null, stdout?: string, stderr?: string) => void,
37
+ ) => cb(new Error("execFile not configured in this test")),
38
+ ),
39
+ };
40
+ });
41
+
42
+ vi.mock("node:fs", async () => {
43
+ const actual = await import("node:fs");
44
+ return {
45
+ default: {
46
+ ...actual,
47
+ mkdirSync: vi.fn(),
48
+ existsSync: vi.fn(() => false),
49
+ appendFileSync: vi.fn(),
50
+ writeFileSync: vi.fn(),
51
+ readdirSync: vi.fn(() => []),
52
+ },
53
+ mkdirSync: vi.fn(),
54
+ existsSync: vi.fn(() => false),
55
+ appendFileSync: vi.fn(),
56
+ writeFileSync: vi.fn(),
57
+ readdirSync: vi.fn(() => []),
58
+ promises: actual.promises,
59
+ };
60
+ });
61
+
62
+ vi.mock("../alive-store.ts", () => ({
63
+ writeAliveMarker: vi.fn(),
64
+ }));
65
+
66
+ // 场景 ① 依赖 keep-alive 分支命中:count=1(有活跃后代 → 不 kill → 重挂 watchdog)
67
+ vi.mock("../session-pending.ts", () => ({
68
+ readActivePendingFromSessionFile: vi.fn(() => ({ count: 1 })),
69
+ }));
70
+
71
+ vi.mock("../temp-prompt.ts", () => ({
72
+ writePromptToTempFile: vi.fn(async (agent: string) => {
73
+ const safeName = agent.replace(/[^\w.-]+/g, "_");
74
+ return { dir: `/tmp/fake-${safeName}`, filePath: `/tmp/fake-${safeName}/prompt-${safeName}.md` };
75
+ }),
76
+ cleanupTempPrompt: vi.fn(async () => {}),
77
+ }));
78
+
79
+ import { runSpawn, SPAWN_WATCHDOG_ENV } from "../session-runner.ts";
80
+ import type { SessionRunnerContext } from "../session-runner.ts";
81
+ import { hasIdleTimer, _resetLifecycleState } from "../lifecycle-manager.ts";
82
+ import { createRecord } from "../execution-record.ts";
83
+ import type { ExecutionRecord } from "../types.ts";
84
+ import {
85
+ emitStdoutLine,
86
+ type FakeChild,
87
+ lastSpawnedChild as lastSpawnedChildOf,
88
+ makeCtx,
89
+ makeOpts,
90
+ makeRecord,
91
+ sessionHeader,
92
+ waitForSpawn as waitForSpawnOf,
93
+ } from "./helpers/spawn-mock.ts";
94
+
95
+ const mockSpawn = vi.mocked(spawn);
96
+
97
+ const lastSpawnedChild = (): FakeChild => lastSpawnedChildOf(mockSpawn);
98
+ const waitForSpawn = (timeoutMs = 1000): Promise<void> => waitForSpawnOf(mockSpawn, timeoutMs);
99
+
100
+ /** 构造 chatMode record(idleTimeoutMs 设为超出 setTimeout 安全域的值 → assertSafeTimerDelay throw)。 */
101
+ function makeChatModeRecord(id = "sa-f2-idle"): ExecutionRecord {
102
+ return createRecord(id, {
103
+ agent: "general-purpose",
104
+ model: "test-model",
105
+ mode: "sync",
106
+ task: "chat task",
107
+ slug: "chat",
108
+ startedAt: 1_000_000,
109
+ rootSessionId: "root-session",
110
+ parentRecordId: undefined,
111
+ depth: 0,
112
+ chatMode: true,
113
+ // > 2^31-1:Node setTimeout 溢出域,assertSafeTimerDelay fail-fast
114
+ idleTimeoutMs: Number.MAX_SAFE_INTEGER,
115
+ });
116
+ }
117
+
118
+ describe("[F-R2] stdout 回调链内 fail-fast throw 不逃逸", () => {
119
+ beforeEach(() => {
120
+ vi.clearAllMocks();
121
+ _resetLifecycleState();
122
+ });
123
+
124
+ afterEach(() => {
125
+ vi.restoreAllMocks();
126
+ _resetLifecycleState();
127
+ });
128
+
129
+ it("① agent_end keep-alive 分支 resolveSpawnWatchdogMs throw → 降级不 re-arm,run 正常收尾,error 可见", async () => {
130
+ const record = makeRecord();
131
+ const promise = runSpawn(record, "Task: keepalive", makeOpts(), makeCtx());
132
+
133
+ await waitForSpawn();
134
+ const child = lastSpawnedChild();
135
+
136
+ emitStdoutLine(child, sessionHeader("sess-fr2a"));
137
+ // 初始 watchdog 解析在 spawn 后同步块内已完成(env 未设 → 不挂)。
138
+ // 此刻设非法 env:agent_end keep-alive 分支再读 env → assertSafeTimerDelay throw。
139
+ process.env[SPAWN_WATCHDOG_ENV] = String(Number.MAX_SAFE_INTEGER);
140
+ try {
141
+ emitStdoutLine(child, { type: "agent_end", willRetry: false });
142
+ // 给 stream flush 留一个 tick(对齐 chatmode 测试模式):throw 若逃逸回调,
143
+ // vitest 会以 unhandled error 判本测试失败——能走到断言即「未崩宿主」。
144
+ await new Promise((r) => setTimeout(r, 20));
145
+
146
+ // 降级语义:不 re-arm(无 timer 可直接观察的是——子进程未被 kill、run 未被中断)
147
+ expect(child.killed).toBe(false);
148
+
149
+ // 错误可见(fail-fast 语义保留):bestEffort("error") 经 logger.error 落日志
150
+ expect(loggerMock.error).toHaveBeenCalledWith(
151
+ expect.stringContaining("resolveSpawnWatchdogMs"),
152
+ expect.objectContaining({ detail: expect.stringContaining("exceeds the Node setTimeout limit") }),
153
+ );
154
+
155
+ // 收尾:run 正常完成(未被回调异常打断)
156
+ child.stdout.end();
157
+ child.stderr.end();
158
+ child.emit("close", 0);
159
+ const result = await promise;
160
+ expect(result.success).toBe(true);
161
+ } finally {
162
+ delete process.env[SPAWN_WATCHDOG_ENV];
163
+ }
164
+ });
165
+
166
+ it("② chatMode agent_settled armIdleTimer throw → 降级不挂 idle timer,onRoundSettled 照常、提前 resolve", async () => {
167
+ const record = makeChatModeRecord("sa-f2-idle");
168
+ const onRoundSettled = vi.fn();
169
+ const ctx: Partial<SessionRunnerContext> = { onRoundSettled };
170
+ const promise = runSpawn(record, "Task: idle", makeOpts(), makeCtx(ctx as SessionRunnerContext));
171
+
172
+ await waitForSpawn();
173
+ const child = lastSpawnedChild();
174
+
175
+ emitStdoutLine(child, sessionHeader("sess-fr2b"));
176
+ emitStdoutLine(child, { type: "agent_settled" });
177
+ await new Promise((r) => setTimeout(r, 20));
178
+
179
+ // 降级语义:idle timer 未挂(throw 发生在 arm 入口校验,先于 setTimeout)
180
+ expect(hasIdleTimer(record.id)).toBe(false);
181
+ expect(child.killed).toBe(false);
182
+
183
+ // catch 后续语句照常执行:本轮完成通知不因 GC timer 故障丢失
184
+ expect(onRoundSettled).toHaveBeenCalledTimes(1);
185
+
186
+ // 错误可见
187
+ expect(loggerMock.error).toHaveBeenCalledWith(
188
+ expect.stringContaining("armIdleTimer"),
189
+ expect.objectContaining({ detail: expect.stringContaining("exceeds the Node setTimeout limit") }),
190
+ );
191
+
192
+ // 收尾:chatMode 首轮 agent_settled 已 resolveRun(0),close 后 runSpawn 正常返回
193
+ child.stdout.end();
194
+ child.stderr.end();
195
+ child.emit("close", 0);
196
+ const result = await promise;
197
+ expect(result.success).toBe(true);
198
+ });
199
+ });
@@ -94,8 +94,10 @@ import {
94
94
  applySchemaEnvToChildEnv,
95
95
  type RunOptions,
96
96
  runSpawn,
97
+ SCHEMA_ENV_MAX_BYTES,
97
98
  type SessionRunnerContext,
98
99
  } from "../session-runner.ts";
100
+ import { schemaEnvByteLength } from "../../shared/schema-env.ts";
99
101
 
100
102
  const mockSpawn = vi.mocked(spawn);
101
103
  const mockExistsSync = vi.mocked(fs.existsSync);
@@ -225,6 +227,43 @@ describe("applySchemaEnvToChildEnv (T3.9/T3.11/T3.16)", () => {
225
227
  expect(childEnv.HOME).toBe("/home/user");
226
228
  expect(childEnv.PI_WORKFLOW_SCHEMA).toBe('{"x":1}');
227
229
  });
230
+
231
+ // [SO-DATA-4] 边界内通过:255KB(< 256KiB 上限)正常注入,行为不变
232
+ it("[SO-DATA-4] 255KB schema 正常注入(上限内不误拒)", () => {
233
+ const childEnv: Record<string, string | undefined> = {};
234
+ // ASCII 串 byteLength === length,构造 255KB 纯 JSON body(外层再包一层合法 JSON)
235
+ const padding = "x".repeat(255 * 1024);
236
+ const schemaJson = JSON.stringify({ type: "object", properties: { pad: { const: padding } } });
237
+ expect(schemaEnvByteLength(schemaJson)).toBeLessThanOrEqual(SCHEMA_ENV_MAX_BYTES);
238
+ applySchemaEnvToChildEnv(childEnv, schemaJson);
239
+ expect(childEnv.PI_WORKFLOW_SCHEMA).toBe(schemaJson);
240
+ });
241
+
242
+ // [SO-DATA-4] 超限 fail-fast:257KB 拒绝,错误消息含实际大小 + 精简/拆分指引 + E2BIG 归因
243
+ it("[SO-DATA-4] 257KB schema fail-fast 拒绝(错误含实际大小与恢复指引)", () => {
244
+ const childEnv: Record<string, string | undefined> = {};
245
+ const padding = "x".repeat(257 * 1024);
246
+ const schemaJson = JSON.stringify({ type: "object", properties: { pad: { const: padding } } });
247
+ expect(schemaEnvByteLength(schemaJson)).toBeGreaterThan(SCHEMA_ENV_MAX_BYTES);
248
+ expect(() => applySchemaEnvToChildEnv(childEnv, schemaJson)).toThrow(
249
+ expect.objectContaining({
250
+ message: expect.stringContaining("bytes exceeds"),
251
+ }),
252
+ );
253
+ // 错误消息含实际大小、上限、精简/拆分指引与 E2BIG 归因(可操作性验收)
254
+ try {
255
+ applySchemaEnvToChildEnv(childEnv, schemaJson);
256
+ throw new Error("expected applySchemaEnvToChildEnv to throw");
257
+ } catch (err) {
258
+ const msg = err instanceof Error ? err.message : String(err);
259
+ expect(msg).toContain(String(schemaEnvByteLength(schemaJson))); // 实际大小
260
+ expect(msg).toContain(String(SCHEMA_ENV_MAX_BYTES)); // 上限值
261
+ expect(msg).toContain("simplify the schema"); // 精简指引
262
+ expect(msg).toContain("E2BIG"); // ARG_MAX/E2BIG 约束说明
263
+ }
264
+ // fail-fast:不写入半截值
265
+ expect(childEnv.PI_WORKFLOW_SCHEMA).toBeUndefined();
266
+ });
228
267
  });
229
268
 
230
269
  // ── runSpawn 集成测试:schemaEnv 经 RunOptions → childEnv ──