@zhushanwen/pi-subagent-workflow 7.4.0 → 8.1.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 (166) hide show
  1. package/README.md +15 -0
  2. package/package.json +7 -4
  3. package/scripts/rfl.mjs +308 -0
  4. package/skills/workflow-script-format/SKILL.md +1 -1
  5. package/src/execution/__tests__/__fixtures__/truncline.snapshot.json +1 -0
  6. package/src/execution/__tests__/ask-user-transit-e2e.test.ts +10 -4
  7. package/src/execution/__tests__/before-agent-start-injection.test.ts +132 -0
  8. package/src/execution/__tests__/bg-notify-render.test.ts +15 -15
  9. package/src/execution/__tests__/chatmode-first-round-closure-service.test.ts +365 -0
  10. package/src/execution/__tests__/chatmode-first-round-closure-spawn.test.ts +190 -0
  11. package/src/execution/__tests__/chatmode-round-notify-real-chain.test.ts +215 -0
  12. package/src/execution/__tests__/conversation-wiring.test.ts +198 -0
  13. package/src/execution/__tests__/crash-recovery.test.ts +8 -2
  14. package/src/execution/__tests__/delivery-methods.test.ts +385 -0
  15. package/src/execution/__tests__/epipe-fallback.test.ts +241 -0
  16. package/src/execution/__tests__/execute-and-await-worktree.test.ts +49 -2
  17. package/src/execution/__tests__/execute-nesting.test.ts +20 -72
  18. package/src/execution/__tests__/execution-record.test.ts +199 -0
  19. package/src/execution/__tests__/finalize-record.test.ts +197 -15
  20. package/src/execution/__tests__/format.test.ts +131 -7
  21. package/src/execution/__tests__/gc-timer.test.ts +184 -0
  22. package/src/execution/__tests__/get-record-for-action-restart.test.ts +254 -0
  23. package/src/execution/__tests__/helpers/spawn-mock.ts +37 -10
  24. package/src/execution/__tests__/index-session-start-identity.test.ts +371 -0
  25. package/src/execution/__tests__/index-session-start.test.ts +257 -5
  26. package/src/execution/__tests__/lifecycle-manager-lock.test.ts +211 -0
  27. package/src/execution/__tests__/lifecycle-manager.test.ts +337 -0
  28. package/src/execution/__tests__/lifecycle-predicates.test.ts +116 -0
  29. package/src/execution/__tests__/list-component.test.ts +59 -5
  30. package/src/execution/__tests__/list-fields.test.ts +109 -0
  31. package/src/execution/__tests__/model-resolver.test.ts +38 -1
  32. package/src/execution/__tests__/nested-visibility-env-propagation.test.ts +287 -0
  33. package/src/execution/__tests__/nested-visibility.test.ts +325 -0
  34. package/src/execution/__tests__/notifier-flush.test.ts +209 -7
  35. package/src/execution/__tests__/one-shot-upgrade.test.ts +205 -0
  36. package/src/execution/__tests__/parent-child-matrix.test.ts +336 -0
  37. package/src/execution/__tests__/record-store.test.ts +442 -54
  38. package/src/execution/__tests__/recursive-visibility-baseline.test.ts +11 -12
  39. package/src/execution/__tests__/recursive-visibility-env.test.ts +18 -20
  40. package/src/execution/__tests__/resource-policy.test.ts +109 -0
  41. package/src/execution/__tests__/run-and-finalize-chatmode.test.ts +267 -0
  42. package/src/execution/__tests__/run-spawn-chatmode-settled.test.ts +253 -0
  43. package/src/execution/__tests__/run-spawn-edges.test.ts +18 -25
  44. package/src/execution/__tests__/run-spawn-integration.test.ts +29 -25
  45. package/src/execution/__tests__/run-spawn-resume.test.ts +322 -0
  46. package/src/execution/__tests__/run-spawn-rpc-mode.test.ts +14 -11
  47. package/src/execution/__tests__/session-pending.test.ts +61 -2
  48. package/src/execution/__tests__/session-reconstructor.test.ts +4 -4
  49. package/src/execution/__tests__/session-runner-epipe.test.ts +178 -0
  50. package/src/execution/__tests__/session-runner-schema-env.test.ts +15 -21
  51. package/src/execution/__tests__/session-start-reaper.test.ts +10 -8
  52. package/src/execution/__tests__/spawn-args.test.ts +127 -49
  53. package/src/execution/__tests__/spawn-worktree-guidance.test.ts +1 -0
  54. package/src/execution/__tests__/spawned-children.test.ts +92 -0
  55. package/src/execution/__tests__/status-refactor.test.ts +345 -0
  56. package/src/execution/__tests__/stdin-writer.test.ts +97 -0
  57. package/src/execution/__tests__/subagent-service-message-close.test.ts +629 -0
  58. package/src/execution/__tests__/subagent-service-parent-guard.test.ts +180 -0
  59. package/src/execution/__tests__/subagent-service.test.ts +49 -11
  60. package/src/execution/__tests__/timeout-integration.test.ts +27 -13
  61. package/src/execution/__tests__/tool-action.test.ts +12 -10
  62. package/src/execution/__tests__/truncline-snapshot.test.ts +81 -0
  63. package/src/execution/__tests__/turn-limiter-semantics.test.ts +194 -0
  64. package/src/execution/__tests__/worktree-manager.test.ts +300 -90
  65. package/src/execution/__tests__/worktree-pid-registration.integration.test.ts +17 -13
  66. package/src/execution/__tests__/worktree-reconcile.integration.test.ts +181 -0
  67. package/src/execution/__tests__/worktree-registry.test.ts +72 -34
  68. package/src/execution/agent-result-mapper.ts +4 -1
  69. package/src/execution/argv-mirror.ts +21 -2
  70. package/src/execution/channel-registry-access.ts +3 -1
  71. package/src/execution/execution-record.ts +126 -9
  72. package/src/execution/finalize-record.ts +99 -13
  73. package/src/execution/idle-gc.ts +47 -0
  74. package/src/execution/lifecycle-manager.ts +491 -0
  75. package/src/execution/lifecycle-predicates.ts +65 -0
  76. package/src/execution/manifest-store.ts +61 -16
  77. package/src/execution/model-resolver.ts +26 -5
  78. package/src/execution/notifier.ts +69 -12
  79. package/src/execution/pi-invocation.ts +21 -1
  80. package/src/execution/record-entry.ts +118 -0
  81. package/src/execution/record-store.ts +844 -108
  82. package/src/execution/session-pending.ts +121 -49
  83. package/src/execution/session-reconstructor.ts +224 -7
  84. package/src/execution/session-runner.ts +713 -316
  85. package/src/execution/sessions-index.ts +304 -0
  86. package/src/execution/stdin-writer.ts +93 -7
  87. package/src/execution/stream-sink.ts +20 -3
  88. package/src/execution/subagent-service.ts +917 -138
  89. package/src/execution/temp-prompt.ts +8 -3
  90. package/src/execution/turn-limiter.ts +14 -0
  91. package/src/execution/types.ts +218 -19
  92. package/src/execution/worktree-manager.ts +449 -59
  93. package/src/execution/worktree-registry.ts +97 -29
  94. package/src/index.ts +318 -20
  95. package/src/injectors/subagent-list-injector.ts +26 -8
  96. package/src/injectors/workflow-list-injector.ts +25 -8
  97. package/src/interface/__tests__/subagent-tool-prompt.test.ts +17 -4
  98. package/src/interface/__tests__/tool-render.test.ts +10 -8
  99. package/src/interface/__tests__/tool-workflow-script-generate.test.ts +103 -26
  100. package/src/interface/__tests__/tool-workflow-throw-paths.test.ts +179 -0
  101. package/src/interface/bg-notify-render.ts +32 -8
  102. package/src/interface/command-actions.ts +26 -7
  103. package/src/interface/commands.ts +21 -22
  104. package/src/interface/format.ts +53 -20
  105. package/src/interface/gui-mappers.ts +6 -8
  106. package/src/interface/helpers.ts +170 -10
  107. package/src/interface/list-component.ts +53 -14
  108. package/src/interface/subagent-actions.ts +235 -17
  109. package/src/interface/subagent-tool.ts +81 -16
  110. package/src/interface/subagents.ts +2 -1
  111. package/src/interface/tool-render.ts +21 -27
  112. package/src/interface/tool-workflow-script.ts +29 -33
  113. package/src/interface/tool-workflow.ts +67 -100
  114. package/src/interface/views/WorkflowsView.ts +89 -32
  115. package/src/interface/views/__tests__/WorkflowsView-signature.test.ts +264 -0
  116. package/src/interface/views/detail-content.ts +1 -1
  117. package/src/interface/views/format.ts +3 -3
  118. package/src/orchestration/__tests__/__fixtures__/worker-template.snapshot.txt +333 -0
  119. package/src/orchestration/__tests__/args-validator.test.ts +1 -1
  120. package/src/orchestration/__tests__/config-loader.test.ts +38 -0
  121. package/src/orchestration/__tests__/error-recovery-handlers.test.ts +394 -4
  122. package/src/orchestration/__tests__/error-recovery-workflow-call.test.ts +4 -4
  123. package/src/orchestration/__tests__/execute-agent-call.test.ts +144 -1
  124. package/src/orchestration/__tests__/jsonl-run-store-loadall-sources.test.ts +171 -0
  125. package/src/orchestration/__tests__/jsonl-run-store-session-file.test.ts +820 -19
  126. package/src/orchestration/__tests__/launcher-nested-workflow.test.ts +0 -2
  127. package/src/orchestration/__tests__/lifecycle-runid-injection.test.ts +96 -0
  128. package/src/orchestration/__tests__/lifecycle.test.ts +332 -149
  129. package/src/orchestration/__tests__/review-fix-loop-e2e.test.ts +1108 -19
  130. package/src/orchestration/__tests__/skill-discovery.test.ts +130 -61
  131. package/src/orchestration/__tests__/test-mocks.ts +197 -0
  132. package/src/orchestration/__tests__/worker-returnmeta-passthrough.test.ts +164 -0
  133. package/src/orchestration/__tests__/worker-script-template-snapshot.test.ts +110 -0
  134. package/src/orchestration/__tests__/workflow-nesting-e2e.test.ts +0 -2
  135. package/src/orchestration/__tests__/workflow-script-lint-memo.test.ts +110 -0
  136. package/src/orchestration/__tests__/workflows-e2e.test.ts +38 -40
  137. package/src/orchestration/agent-opts-resolver.ts +4 -1
  138. package/src/orchestration/args-validator.ts +2 -2
  139. package/src/orchestration/config-loader.ts +30 -1
  140. package/src/orchestration/error-recovery.ts +137 -30
  141. package/src/orchestration/execute-agent-call.ts +44 -10
  142. package/src/orchestration/jsonl-run-store.ts +397 -71
  143. package/src/orchestration/launcher.ts +7 -1
  144. package/src/orchestration/lifecycle.ts +145 -133
  145. package/src/orchestration/models/__tests__/trace.test.ts +408 -0
  146. package/src/orchestration/models/budget.ts +1 -1
  147. package/src/orchestration/models/run-runtime.ts +15 -17
  148. package/src/orchestration/models/run-spec.ts +2 -2
  149. package/src/orchestration/models/run-state.ts +3 -3
  150. package/src/orchestration/models/trace.ts +95 -15
  151. package/src/orchestration/models/types.ts +8 -9
  152. package/src/orchestration/models/workflow-run.ts +50 -71
  153. package/src/orchestration/models/workflow-script.ts +32 -1
  154. package/src/orchestration/skill-discovery.ts +30 -0
  155. package/src/orchestration/worker-handle.ts +1 -1
  156. package/src/orchestration/worker-host.ts +1 -1
  157. package/src/orchestration/worker-script-builder.ts +38 -11
  158. package/src/shared/__tests__/agent-ref.test.ts +34 -0
  159. package/src/shared/__tests__/resource-discovery-manifest-cache.test.ts +280 -0
  160. package/src/shared/__tests__/resource-discovery.test.ts +79 -0
  161. package/src/shared/__tests__/schema-jsonify.test.ts +81 -0
  162. package/src/shared/agent-ref.ts +22 -1
  163. package/src/shared/resource-discovery.ts +162 -59
  164. package/src/shared/schema-jsonify.ts +56 -0
  165. package/workflows/review-fix-loop-utils.cjs +542 -32
  166. package/workflows/review-fix-loop.js +462 -109
@@ -0,0 +1,322 @@
1
+ // src/__tests__/run-spawn-resume.test.ts
2
+ //
3
+ // runSpawn 的 resume 路径测试(M1 基建:重开已结束 session 继续对话)。
4
+ //
5
+ // 覆盖 M1 拆分 1:runSpawn 第 5 参数 resume(SpawnResumeOpts)→ buildSpawnArgs 追加
6
+ // --session <file> + model/thinkingLevel 覆盖 + record.sessionFile 提前锁定(handshake 不覆盖)。
7
+ //
8
+ // mock 模式与 run-spawn-rpc-mode.test.ts 一致(vi.mock 必须各文件独立声明,工厂内用
9
+ // `await import` 取回 FakeChild)。
10
+
11
+ import { spawn } from "node:child_process";
12
+ import * as fs from "node:fs";
13
+
14
+ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
15
+
16
+ vi.mock("node:child_process", async () => {
17
+ const { FakeChild } = await import("./helpers/spawn-mock.ts");
18
+ return {
19
+ spawn: vi.fn(() => new FakeChild()),
20
+ // buildEnvBlock 的 git branch 调用(execFile 异步):默认 err-first 兜底 → catch → branch=""
21
+ execFile: vi.fn(
22
+ (
23
+ _cmd: string,
24
+ _args: readonly string[],
25
+ _opts: unknown,
26
+ cb: (err: Error | null, stdout?: string, stderr?: string) => void,
27
+ ) => cb(new Error("execFile not configured in this test")),
28
+ ),
29
+ };
30
+ });
31
+
32
+ vi.mock("node:fs", async () => {
33
+ const actual = await import("node:fs");
34
+ return {
35
+ default: {
36
+ ...actual,
37
+ mkdirSync: vi.fn(),
38
+ existsSync: vi.fn(() => false),
39
+ appendFileSync: vi.fn(),
40
+ writeFileSync: vi.fn(),
41
+ readdirSync: vi.fn(() => []),
42
+ },
43
+ mkdirSync: vi.fn(),
44
+ existsSync: vi.fn(() => false),
45
+ appendFileSync: vi.fn(),
46
+ writeFileSync: vi.fn(),
47
+ readdirSync: vi.fn(() => []),
48
+ promises: actual.promises,
49
+ };
50
+ });
51
+
52
+ vi.mock("../alive-store.ts", () => ({
53
+ writeAliveMarker: vi.fn(),
54
+ }));
55
+
56
+ vi.mock("../temp-prompt.ts", () => ({
57
+ writePromptToTempFile: vi.fn(async (agent: string) => {
58
+ const safeName = agent.replace(/[^\w.-]+/g, "_");
59
+ return { dir: `/tmp/fake-${safeName}`, filePath: `/tmp/fake-${safeName}/prompt-${safeName}.md` };
60
+ }),
61
+ cleanupTempPrompt: vi.fn(async () => {}),
62
+ }));
63
+
64
+ import { getChildByRecord, runSpawn, spawnedChildren } from "../session-runner.ts";
65
+ import {
66
+ emitStdoutLine,
67
+ type FakeChild,
68
+ lastSpawnedChild as lastSpawnedChildOf,
69
+ makeCtx,
70
+ makeOpts,
71
+ makeRecord,
72
+ waitForSpawn as waitForSpawnOf,
73
+ } from "./helpers/spawn-mock.ts";
74
+
75
+ const mockSpawn = vi.mocked(spawn);
76
+ const mockExistsSync = vi.mocked(fs.existsSync);
77
+
78
+ const lastSpawnedChild = (): FakeChild => lastSpawnedChildOf(mockSpawn);
79
+ const waitForSpawn = (timeoutMs = 1000): Promise<void> => waitForSpawnOf(mockSpawn, timeoutMs);
80
+
81
+ /**
82
+ * 取最近一次 spawn 调用收到的 args 数组。
83
+ *
84
+ * getPiInvocation 在测试环境(existsSync 全 mock 默认 false + node 通用运行时)走分支 3,
85
+ * invocation.args === buildSpawnArgs 的完整输出,故此处直接读 spawn 的第二参数。
86
+ */
87
+ const lastSpawnArgs = (): string[] => {
88
+ const call = mockSpawn.mock.calls.at(-1);
89
+ if (!call) throw new Error("spawn was not called yet");
90
+ return call[1] as string[];
91
+ };
92
+
93
+ describe("runSpawn resume(M1 基建)", () => {
94
+ beforeEach(() => {
95
+ vi.clearAllMocks();
96
+ mockExistsSync.mockReturnValue(false);
97
+ });
98
+
99
+ afterEach(() => {
100
+ vi.restoreAllMocks();
101
+ });
102
+
103
+ it("resume 全参数:--session + model(:thinkingLevel) 进 args,且覆盖 opts.resolved", async () => {
104
+ const record = makeRecord();
105
+ const resumeSessionFile = "/sessions/sub/resume-target.jsonl";
106
+ const promise = runSpawn(record, "继续上轮对话", makeOpts(), makeCtx(), {
107
+ sessionFile: resumeSessionFile,
108
+ model: "anthropic/claude-sonnet",
109
+ thinkingLevel: "high",
110
+ });
111
+
112
+ await waitForSpawn();
113
+ const child = lastSpawnedChild();
114
+
115
+ // resume.sessionFile 文件存在(resume 前提)→ 让 existsSync 对它返回 true,
116
+ // 避免进程退出后兜底查找报错 + identity 补写路径走通。
117
+ mockExistsSync.mockImplementation((p: unknown) => String(p) === resumeSessionFile);
118
+ // 消费 stdin(含 get_state 握手命令 + prompt 命令),避免背压
119
+ child.stdin.on("data", () => {});
120
+
121
+ emitStdoutLine(child, { type: "turn_end" });
122
+ child.stdout.end();
123
+ child.emit("close", 0);
124
+
125
+ await promise;
126
+
127
+ const args = lastSpawnArgs();
128
+ // --session <resumeSessionFile> 紧跟 --session-dir
129
+ const sessionIdx = args.indexOf("--session");
130
+ expect(sessionIdx).toBeGreaterThan(-1);
131
+ expect(args[sessionIdx + 1]).toBe(resumeSessionFile);
132
+ const sessionDirIdx = args.indexOf("--session-dir");
133
+ expect(sessionIdx).toBe(sessionDirIdx + 2);
134
+ // --model 用 resume.model(覆盖 opts.resolved 的 test/test-model),thinkingLevel 作后缀
135
+ const modelIdx = args.indexOf("--model");
136
+ expect(modelIdx).toBeGreaterThan(-1);
137
+ expect(args[modelIdx + 1]).toBe("anthropic/claude-sonnet:high");
138
+ // 不应出现 opts.resolved 的 model(证明 resume.model 覆盖生效)
139
+ expect(args).not.toContain("test/test-model");
140
+
141
+ // record.sessionFile 提前锁定为 resume 值
142
+ expect(record.sessionFile).toBe(resumeSessionFile);
143
+ });
144
+
145
+ it("resume 不传 model/thinkingLevel → --model 回退 opts.resolved", async () => {
146
+ const record = makeRecord();
147
+ const resumeSessionFile = "/sessions/sub/no-model.jsonl";
148
+ const promise = runSpawn(record, "继续", makeOpts(), makeCtx(), {
149
+ sessionFile: resumeSessionFile,
150
+ });
151
+
152
+ await waitForSpawn();
153
+ const child = lastSpawnedChild();
154
+
155
+ mockExistsSync.mockImplementation((p: unknown) => String(p) === resumeSessionFile);
156
+ child.stdin.on("data", () => {});
157
+
158
+ emitStdoutLine(child, { type: "turn_end" });
159
+ child.stdout.end();
160
+ child.emit("close", 0);
161
+
162
+ await promise;
163
+
164
+ const args = lastSpawnArgs();
165
+ // --session 仍追加
166
+ const sessionIdx = args.indexOf("--session");
167
+ expect(sessionIdx).toBeGreaterThan(-1);
168
+ expect(args[sessionIdx + 1]).toBe(resumeSessionFile);
169
+ // --model 回退 opts.resolved(test/test-model)
170
+ const modelIdx = args.indexOf("--model");
171
+ expect(modelIdx).toBeGreaterThan(-1);
172
+ expect(args[modelIdx + 1]).toBe("test/test-model");
173
+ });
174
+
175
+ it("resume 时 handshake 仍调但 sessionFile 不被 response 覆盖(提前锁定)", async () => {
176
+ const record = makeRecord();
177
+ const resumeSessionFile = "/sessions/sub/locked.jsonl";
178
+ const promise = runSpawn(record, "继续", makeOpts(), makeCtx(), {
179
+ sessionFile: resumeSessionFile,
180
+ model: "openai/gpt-4o",
181
+ });
182
+
183
+ await waitForSpawn();
184
+ const child = lastSpawnedChild();
185
+
186
+ mockExistsSync.mockImplementation((p: unknown) => String(p) === resumeSessionFile);
187
+
188
+ // 捕获握手发出的 get_state 命令(证明 handshake 仍调),并 emit 一个 sessionFile 不同的
189
+ // response(模拟 handshake 返回新文件路径)→ 验证 record.sessionFile 不被覆盖。
190
+ let getStateSeen = false;
191
+ const conflictingSessionFile = "/sessions/sub/SHOULD-NOT-OVERWRITE.jsonl";
192
+ child.stdin.on("data", (data: Buffer | string) => {
193
+ const text = typeof data === "string" ? data : data.toString();
194
+ for (const line of text.split("\n")) {
195
+ if (!line.trim()) continue;
196
+ try {
197
+ const cmd = JSON.parse(line) as { type?: string; id?: string };
198
+ if (cmd.type === "get_state" && cmd.id) {
199
+ getStateSeen = true;
200
+ emitStdoutLine(child, {
201
+ type: "response",
202
+ command: "get_state",
203
+ success: true,
204
+ id: cmd.id,
205
+ data: { sessionFile: conflictingSessionFile, sessionId: "rpc-sess" },
206
+ });
207
+ }
208
+ } catch {
209
+ // 非 JSON 行(prompt 命令等)忽略
210
+ }
211
+ }
212
+ });
213
+
214
+ // 等 stdin listener 触发 + response 经 stdout pump 处理 → finishHandshake 执行
215
+ await new Promise((r) => setTimeout(r, 20));
216
+
217
+ emitStdoutLine(child, { type: "turn_end" });
218
+ child.stdout.end();
219
+ child.emit("close", 0);
220
+
221
+ await promise;
222
+
223
+ // handshake 确实被调(get_state 命令已发出)
224
+ expect(getStateSeen).toBe(true);
225
+ // 但 record.sessionFile 仍是 resume 锁定值,未被 response 覆盖
226
+ expect(record.sessionFile).toBe(resumeSessionFile);
227
+ expect(record.sessionFile).not.toBe(conflictingSessionFile);
228
+ });
229
+ });
230
+
231
+ // ============================================================
232
+ // [M4] spawnedChildren 记账竞态:旧 child close/error 晚于 resume spawn
233
+ // ============================================================
234
+
235
+ describe("[M4] spawnedChildren 记账竞态守卫(旧 child close 晚于 resume spawn)", () => {
236
+ beforeEach(() => {
237
+ vi.clearAllMocks();
238
+ mockExistsSync.mockReturnValue(false);
239
+ spawnedChildren.clear();
240
+ });
241
+
242
+ afterEach(() => {
243
+ spawnedChildren.clear();
244
+ vi.restoreAllMocks();
245
+ });
246
+
247
+ /**
248
+ * 竞态时序(PR #173 review 组 D):idle timer 对旧 child 发 SIGTERM(killed=true 但
249
+ * close 事件异步未到)→ deliverMessage 判 child.killed 走冷路径 resumeRound → 新 child
250
+ * spawn 并 set 覆盖注册 → 旧 child 的 close 事件此刻到达。守卫前:close handler 无条件
251
+ * delete(record.id) 误删新注册 → 新活进程脱离记账(killAllSpawnedChildren 漏杀 +
252
+ * 二次 resume 双写 session 文件)。守卫后:按句相等跳过删除。
253
+ */
254
+ it("旧 child close 晚于 resume spawn 到达:不误删新 child 注册(按值守卫)", async () => {
255
+ const record = makeRecord("m4-race-1");
256
+ // 首轮 runSpawn(注册 child1)
257
+ const p1 = runSpawn(record, "first round", makeOpts(), makeCtx());
258
+ await waitForSpawn();
259
+ const child1 = lastSpawnedChild();
260
+ child1.stdin.on("data", () => {});
261
+ expect(getChildByRecord(record.id)).toBe(child1);
262
+
263
+ // 模拟 idle timer SIGTERM:killed=true 但 close 事件**未派发**(异步窗口)
264
+ child1.kill("SIGTERM");
265
+
266
+ // 冷路径 resume:同 record 第二次 runSpawn,spawn child2 覆盖注册
267
+ const resumeFile = "/sessions/sub/m4-race.jsonl";
268
+ const p2 = runSpawn(record, "resume round", makeOpts(), makeCtx(), {
269
+ sessionFile: resumeFile,
270
+ });
271
+ await waitForSpawn();
272
+ const child2 = lastSpawnedChild();
273
+ child2.stdin.on("data", () => {});
274
+ expect(getChildByRecord(record.id)).toBe(child2);
275
+
276
+ // 旧 child1 的 close 事件此刻到达——守卫必须跳过删除
277
+ emitStdoutLine(child1, { type: "turn_end" });
278
+ child1.stdout.end();
279
+ child1.emit("close", 0);
280
+ await p1;
281
+
282
+ // 关键断言:新 child2 的注册未被旧 child 的迟到 close 误删
283
+ expect(getChildByRecord(record.id)).toBe(child2);
284
+
285
+ // child2 正常退出:close 后注册清理(守卫对当前句柄仍生效)
286
+ mockExistsSync.mockImplementation((p: unknown) => String(p) === resumeFile);
287
+ emitStdoutLine(child2, { type: "turn_end" });
288
+ child2.stdout.end();
289
+ child2.emit("close", 0);
290
+ await p2;
291
+ expect(getChildByRecord(record.id)).toBeUndefined();
292
+ });
293
+
294
+ it("旧 child spawn error 晚于 resume spawn 到达:同样不误删新 child 注册", async () => {
295
+ const record = makeRecord("m4-race-2");
296
+ const p1 = runSpawn(record, "first round", makeOpts(), makeCtx());
297
+ await waitForSpawn();
298
+ const child1 = lastSpawnedChild();
299
+ child1.stdin.on("data", () => {});
300
+
301
+ const p2 = runSpawn(record, "resume round", makeOpts(), makeCtx(), {
302
+ sessionFile: "/sessions/sub/m4-race-2.jsonl",
303
+ });
304
+ await waitForSpawn();
305
+ const child2 = lastSpawnedChild();
306
+ child2.stdin.on("data", () => {});
307
+ expect(getChildByRecord(record.id)).toBe(child2);
308
+
309
+ // 旧 child1 的 error 事件迟到(spawn 失败回调晚到)
310
+ child1.emit("error", new Error("spawn ENOENT (late)"));
311
+ await p1;
312
+
313
+ expect(getChildByRecord(record.id)).toBe(child2);
314
+
315
+ mockExistsSync.mockImplementation((p: unknown) => String(p) === "/sessions/sub/m4-race-2.jsonl");
316
+ emitStdoutLine(child2, { type: "turn_end" });
317
+ child2.stdout.end();
318
+ child2.emit("close", 0);
319
+ await p2;
320
+ expect(getChildByRecord(record.id)).toBeUndefined();
321
+ });
322
+ });
@@ -8,7 +8,7 @@
8
8
  // mock 工厂 + FakeChild + 工具函数共享自 helpers/spawn-mock.ts(详见该文件头注释)。
9
9
  // vi.mock 必须各文件独立声明(文件作用域),工厂内用 `await import` 取回 FakeChild。
10
10
 
11
- import { execFileSync, spawn } from "node:child_process";
11
+ import { spawn } from "node:child_process";
12
12
  import * as fs from "node:fs";
13
13
 
14
14
  import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
@@ -17,7 +17,15 @@ vi.mock("node:child_process", async () => {
17
17
  const { FakeChild } = await import("./helpers/spawn-mock.ts");
18
18
  return {
19
19
  spawn: vi.fn(() => new FakeChild()),
20
- execFileSync: vi.fn(() => ""),
20
+ // buildEnvBlock git branch 调用(execFile 异步):默认 err-first 兜底 → catch → branch=""
21
+ execFile: vi.fn(
22
+ (
23
+ _cmd: string,
24
+ _args: readonly string[],
25
+ _opts: unknown,
26
+ cb: (err: Error | null, stdout?: string, stderr?: string) => void,
27
+ ) => cb(new Error("execFile not configured in this test")),
28
+ ),
21
29
  };
22
30
  });
23
31
 
@@ -66,7 +74,6 @@ import {
66
74
  } from "./helpers/spawn-mock.ts";
67
75
 
68
76
  const mockSpawn = vi.mocked(spawn);
69
- const mockExec = vi.mocked(execFileSync);
70
77
  const mockExistsSync = vi.mocked(fs.existsSync);
71
78
  const mockAppendFileSync = vi.mocked(fs.appendFileSync);
72
79
 
@@ -82,7 +89,6 @@ const mockSessionFileExists = (p: string): void => mockSessionFileExistsOf(mockE
82
89
  describe("runSpawn", () => {
83
90
  beforeEach(() => {
84
91
  vi.clearAllMocks();
85
- mockExec.mockReturnValue("");
86
92
  mockExistsSync.mockReturnValue(false);
87
93
  });
88
94
 
@@ -131,7 +137,7 @@ describe("runSpawn", () => {
131
137
  });
132
138
  }
133
139
 
134
- it("无 header + get_state response 回填 sessionFile identity 写入成功", async () => {
140
+ it("无 header + get_state response 回填 sessionFile(identity 不再由 session-runner fs 写)", async () => {
135
141
  const record = makeRecord();
136
142
  const promise = runSpawn(record, "Task: rpc-no-header", makeOpts(), makeCtx());
137
143
 
@@ -158,12 +164,9 @@ describe("runSpawn", () => {
158
164
  expect(result.success).toBe(true);
159
165
  expect(record.sessionFile).toBe(expectedSessionFile);
160
166
  expect(result.sessionFile).toBe(expectedSessionFile);
161
- // identity 经握手回填的 sessionFile 写入(不再依赖 sessionHeader 条件)
162
- expect(mockAppendFileSync).toHaveBeenCalledWith(
163
- expectedSessionFile,
164
- expect.stringContaining('"customType":"subagent-identity"'),
165
- "utf-8",
166
- );
167
+ // [M4 / V2 决策 5] identity 不再由 session-runner fs 补写(迁移到子进程 session_start,
168
+ // 见 index-session-start-identity.test.ts)。此处仅守护 session-runner 不 fs 写 identity。
169
+ expect(mockAppendFileSync).not.toHaveBeenCalled();
167
170
  });
168
171
 
169
172
  it("无 header + get_state 无响应 → close 主动 settle 不阻塞,identity 不写入", async () => {
@@ -7,9 +7,9 @@ import * as fs from "node:fs";
7
7
  import * as os from "node:os";
8
8
  import * as path from "node:path";
9
9
 
10
- import { afterEach, describe, expect, it } from "vitest";
10
+ import { afterEach, beforeEach, describe, expect, it } from "vitest";
11
11
 
12
- import { readActivePendingFromSessionFile } from "../session-pending.ts";
12
+ import { readActivePendingFromSessionFile, clearPendingCursors } from "../session-pending.ts";
13
13
 
14
14
  function makeTmpSessionFile(lines: string[]): string {
15
15
  const dir = fs.mkdtempSync(path.join(os.tmpdir(), "session-pending-test-"));
@@ -136,3 +136,62 @@ describe("readActivePendingFromSessionFile", () => {
136
136
  expect(readActivePendingFromSessionFile(file)).toEqual({ count: 1, recentUnregister: false });
137
137
  });
138
138
  });
139
+
140
+ // [perf] 增量游标行为:同文件重复判定(层主被多个后代唤醒 N 次 → N 次 agent_end)
141
+ // 只读上次 offset 之后的新增行,累计差集语义与全量读一致。
142
+ describe("readActivePendingFromSessionFile — 增量游标 [perf]", () => {
143
+ let dir: string;
144
+ let file: string;
145
+
146
+ beforeEach(() => {
147
+ dir = fs.mkdtempSync(path.join(os.tmpdir(), "session-pending-incr-"));
148
+ file = path.join(dir, "session.jsonl");
149
+ clearPendingCursors();
150
+ });
151
+
152
+ afterEach(() => {
153
+ fs.rmSync(dir, { recursive: true, force: true });
154
+ });
155
+
156
+ it("首次全量 + append 后增量:unregister 只抵消对应 id(与全量读一致)", () => {
157
+ fs.writeFileSync(file, mkRegister("d1") + "\n" + mkRegister("d2") + "\n");
158
+ expect(readActivePendingFromSessionFile(file).count).toBe(2);
159
+
160
+ fs.appendFileSync(file, mkUnregister("d1", "completed") + "\n");
161
+ const r = readActivePendingFromSessionFile(file);
162
+ expect(r.error).toBeUndefined();
163
+ expect(r.count).toBe(1);
164
+ });
165
+
166
+ it("EOF 半行(append 竞态)不入账,补全换行后入账", () => {
167
+ fs.writeFileSync(file, mkRegister("d1") + "\n");
168
+ expect(readActivePendingFromSessionFile(file).count).toBe(1);
169
+
170
+ // 半行:无尾换行 → offset 不推进该行
171
+ const full = mkUnregister("d1", "completed", new Date().toISOString());
172
+ fs.appendFileSync(file, full.slice(0, full.length - 4));
173
+ expect(readActivePendingFromSessionFile(file).count).toBe(1);
174
+
175
+ // 补全(剩余字符 + 换行)→ 消费
176
+ fs.appendFileSync(file, full.slice(-4) + "\n");
177
+ const r = readActivePendingFromSessionFile(file);
178
+ expect(r.count).toBe(0);
179
+ expect(r.recentUnregister).toBe(true);
180
+ });
181
+
182
+ it("文件 truncate/重建(size 回退)→ 重置游标从头全读", () => {
183
+ fs.writeFileSync(file, mkRegister("d1") + "\n" + mkRegister("d2") + "\n");
184
+ expect(readActivePendingFromSessionFile(file).count).toBe(2);
185
+
186
+ fs.writeFileSync(file, mkRegister("d3") + "\n");
187
+ expect(readActivePendingFromSessionFile(file).count).toBe(1);
188
+ });
189
+
190
+ it("clearPendingCursors 后重新全量(累计 entries 不残留旧账)", () => {
191
+ fs.writeFileSync(file, mkRegister("d1") + "\n");
192
+ expect(readActivePendingFromSessionFile(file).count).toBe(1);
193
+ clearPendingCursors();
194
+ fs.appendFileSync(file, mkRegister("d2") + "\n");
195
+ expect(readActivePendingFromSessionFile(file).count).toBe(2);
196
+ });
197
+ });
@@ -102,7 +102,7 @@ describe("reconstructFromFile", () => {
102
102
  expect(rec!.agent).toBe("worker");
103
103
  expect(rec!.mode).toBe("background");
104
104
  expect(rec!.task).toBe("do it");
105
- expect(rec!.status).toBe("done");
105
+ expect(rec!.status).toBe("closed");
106
106
  expect(rec!.turns).toHaveLength(1);
107
107
  expect(rec!.turns[0].text).toBe("hello world");
108
108
  expect(rec!.turnCount).toBe(1);
@@ -284,7 +284,7 @@ describe("reconstructFromFile", () => {
284
284
  const rec = reconstructFromFile(filePath);
285
285
  expect(rec!.lastError).toBe("API timeout");
286
286
  expect(rec!.error).toBe("API timeout");
287
- expect(rec!.status).toBe("failed"); // error stopReason → failed
287
+ expect(rec!.status).toBe("closed"); // error stopReason → failed
288
288
  });
289
289
 
290
290
  it("stopReason=aborted 无 errorMessage → lastError = 'aborted'", () => {
@@ -295,7 +295,7 @@ describe("reconstructFromFile", () => {
295
295
  ]);
296
296
  const rec = reconstructFromFile(filePath);
297
297
  expect(rec!.lastError).toBe("aborted");
298
- expect(rec!.status).toBe("failed");
298
+ expect(rec!.status).toBe("closed");
299
299
  });
300
300
 
301
301
  it("前序 error 但最后 stop → lastError 清除(镜像 turn_end 语义),status=done", () => {
@@ -309,7 +309,7 @@ describe("reconstructFromFile", () => {
309
309
  ]);
310
310
  const rec = reconstructFromFile(filePath);
311
311
  expect(rec!.lastError).toBeUndefined(); // 后续 stop 清除了 error
312
- expect(rec!.status).toBe("done");
312
+ expect(rec!.status).toBe("closed");
313
313
  expect(rec!.result).toBe("oops\n\nrecovered");
314
314
  });
315
315
  });
@@ -0,0 +1,178 @@
1
+ // src/execution/__tests__/session-runner-epipe.test.ts
2
+ //
3
+ // [v4 A-1] session-runner 异步 stdin 'error' listener 测试。
4
+ //
5
+ // 背景:writeStdinLine 的 try/catch 只覆盖同步 write 抛错;子进程退出后内核回写 EPIPE
6
+ // 以异步 stream 'error' event 到达,若无 listener 会让 Node 抛 unhandled 'error' 崩主进程(P1)。
7
+ // runSpawn 在 spawn 后、首次 stdin 写入前注册 child.stdin.on('error') handler,合并
8
+ // 同步/异步 EPIPE 计数(共用 stdin-writer 的 recordEpipeFailure)。
9
+ //
10
+ // 验收:① listener 存在 ② error 触发后 spawnedChildren 不含该 recordId
11
+ // ③ recordEpipeFailure 计数累加(同步/异步合并)
12
+
13
+ import { spawn } from "node:child_process";
14
+
15
+ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
16
+
17
+ vi.mock("node:child_process", async () => {
18
+ const { FakeChild } = await import("./helpers/spawn-mock.ts");
19
+ return {
20
+ spawn: vi.fn(() => new FakeChild()),
21
+ // buildEnvBlock 的 git branch 调用(execFile 异步):默认 err-first 兜底 → catch → branch=""
22
+ execFile: vi.fn(
23
+ (
24
+ _cmd: string,
25
+ _args: readonly string[],
26
+ _opts: unknown,
27
+ cb: (err: Error | null, stdout?: string, stderr?: string) => void,
28
+ ) => cb(new Error("execFile not configured in this test")),
29
+ ),
30
+ };
31
+ });
32
+
33
+ vi.mock("node:fs", async () => {
34
+ const actual = await import("node:fs");
35
+ return {
36
+ default: {
37
+ ...actual,
38
+ mkdirSync: vi.fn(),
39
+ existsSync: vi.fn(() => false),
40
+ appendFileSync: vi.fn(),
41
+ writeFileSync: vi.fn(),
42
+ readdirSync: vi.fn(() => []),
43
+ },
44
+ mkdirSync: vi.fn(),
45
+ existsSync: vi.fn(() => false),
46
+ appendFileSync: vi.fn(),
47
+ writeFileSync: vi.fn(),
48
+ readdirSync: vi.fn(() => []),
49
+ promises: actual.promises,
50
+ };
51
+ });
52
+
53
+ vi.mock("../alive-store.ts", () => ({ writeAliveMarker: vi.fn() }));
54
+
55
+ vi.mock("../session-pending.ts", () => ({
56
+ readActivePendingFromSessionFile: vi.fn(() => ({ count: 0 })),
57
+ }));
58
+
59
+ vi.mock("../temp-prompt.ts", () => ({
60
+ writePromptToTempFile: vi.fn(async (agent: string) => {
61
+ const safeName = agent.replace(/[^\w.-]+/g, "_");
62
+ return { dir: `/tmp/fake-${safeName}`, filePath: `/tmp/fake-${safeName}/prompt-${safeName}.md` };
63
+ }),
64
+ cleanupTempPrompt: vi.fn(async () => {}),
65
+ }));
66
+
67
+ import {
68
+ EPIPE_FAILURE_THRESHOLD,
69
+ recordEpipeFailure,
70
+ resetAllEpipeFailures,
71
+ } from "../stdin-writer.ts";
72
+ import { runSpawn, spawnedChildren } from "../session-runner.ts";
73
+ import { _resetLifecycleState } from "../lifecycle-manager.ts";
74
+ import {
75
+ FakeChild,
76
+ lastSpawnedChild as lastSpawnedChildOf,
77
+ makeCtx,
78
+ makeOpts,
79
+ makeRecord,
80
+ waitForSpawn as waitForSpawnOf,
81
+ } from "./helpers/spawn-mock.ts";
82
+
83
+ const mockSpawn = vi.mocked(spawn);
84
+ const lastSpawnedChild = (): FakeChild => lastSpawnedChildOf(mockSpawn);
85
+ const waitForSpawn = (timeoutMs = 1000): Promise<void> => waitForSpawnOf(mockSpawn, timeoutMs);
86
+
87
+ /** 构造 EPIPE errno 错误(模拟子进程退出后内核回写 EPIPE)。 */
88
+ function epipeError(message = "write after end"): NodeJS.ErrnoException {
89
+ const err = new Error(message) as NodeJS.ErrnoException;
90
+ err.code = "EPIPE";
91
+ return err;
92
+ }
93
+
94
+ /** 手动 emit close 让 runSpawn 的 exitCode promise resolve(非 chatMode 默认 close resolve)。 */
95
+ function settleRunSpawn(child: FakeChild): void {
96
+ child.stdout.end();
97
+ child.stderr.end();
98
+ child.emit("close", 0);
99
+ }
100
+
101
+ describe("[v4 A-1] session-runner 异步 stdin 'error' listener", () => {
102
+ beforeEach(() => {
103
+ vi.clearAllMocks();
104
+ _resetLifecycleState();
105
+ resetAllEpipeFailures();
106
+ spawnedChildren.clear();
107
+ });
108
+
109
+ afterEach(() => {
110
+ _resetLifecycleState();
111
+ resetAllEpipeFailures();
112
+ spawnedChildren.clear();
113
+ });
114
+
115
+ it("① spawn 后注册 child.stdin 'error' listener", async () => {
116
+ const record = makeRecord("sa-listener");
117
+ const promise = runSpawn(record, "Task: listener-exists", makeOpts(), makeCtx());
118
+
119
+ await waitForSpawn();
120
+ const child = lastSpawnedChild();
121
+
122
+ // listener 已注册——无 listener 时异步 EPIPE 会崩主进程(这是 A-1 修复的 P1)
123
+ expect(child.stdin.listenerCount("error")).toBeGreaterThan(0);
124
+
125
+ settleRunSpawn(child);
126
+ await promise;
127
+ });
128
+
129
+ it("②③ async stdin 'error' → 移出 spawnedChildren + recordEpipeFailure 计数递增", async () => {
130
+ const record = makeRecord("sa-async-epipe");
131
+ const promise = runSpawn(record, "Task: async-epipe", makeOpts(), makeCtx());
132
+
133
+ await waitForSpawn();
134
+ const child = lastSpawnedChild();
135
+
136
+ // runSpawn 已把 child 注册进 spawnedChildren
137
+ expect(spawnedChildren.has(record.id)).toBe(true);
138
+
139
+ // 发一次异步 stdin 'error'(count 0→1,未达阈值,handler 只 warn 不 throw)
140
+ child.stdin.emit("error", epipeError());
141
+
142
+ // ② spawnedChildren 已移除该 recordId(标记 dead)
143
+ expect(spawnedChildren.has(record.id)).toBe(false);
144
+
145
+ // ③ 计数累加:handler 调 recordEpipeFailure 设为 1;此处再调一次应返回 2
146
+ // (若 handler 未运行,counter 仍为 0,本次调用只会返回 1)
147
+ expect(recordEpipeFailure(record.id)).toBe(2);
148
+
149
+ settleRunSpawn(child);
150
+ await promise;
151
+ });
152
+
153
+ it("③ 同步预置计数 + 异步 stdin 'error' 合并计数(handler 不 throw,防 listener 内 throw 崩进程)", async () => {
154
+ const record = makeRecord("sa-threshold");
155
+ const promise = runSpawn(record, "Task: threshold", makeOpts(), makeCtx());
156
+
157
+ await waitForSpawn();
158
+ const child = lastSpawnedChild();
159
+
160
+ // 预置 count=1(模拟 deliverMessage 同步路径已计 1 次失败——证明共用同一计数器)
161
+ expect(recordEpipeFailure(record.id)).toBe(1);
162
+
163
+ // [v4 A-1 裁决] async handler 内不 throw(stream 'error' listener 内 throw 会经 emit
164
+ // 传播为 uncaughtException 崩主进程,违背 A-1 防崩)——达阈值 throw 留同步路径。
165
+ // emit 不抛错:
166
+ expect(() => child.stdin.emit("error", epipeError())).not.toThrow();
167
+
168
+ // handler 调 recordEpipeFailure → count=2(达阈值但 async 不 throw);此处再调返回 3
169
+ expect(recordEpipeFailure(record.id)).toBe(3);
170
+ expect(EPIPE_FAILURE_THRESHOLD).toBe(2);
171
+
172
+ // handler 已移出 spawnedChildren(标记 dead,下次 deliverMessage 检测走冷路径)
173
+ expect(spawnedChildren.has(record.id)).toBe(false);
174
+
175
+ settleRunSpawn(child);
176
+ await promise;
177
+ });
178
+ });