@zhushanwen/pi-subagent-workflow 8.3.0 → 8.5.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 (103) hide show
  1. package/package.json +18 -4
  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__/chat-engine-routing.test.ts +597 -0
  6. package/src/execution/__tests__/execution-record.test.ts +127 -1
  7. package/src/execution/__tests__/pi-invocation.test.ts +62 -1
  8. package/src/execution/__tests__/relay-agent.test.ts +448 -0
  9. package/src/execution/__tests__/relay-env.test.ts +42 -0
  10. package/src/execution/__tests__/startup-config-declaration.test.ts +35 -0
  11. package/src/execution/__tests__/stream-sink-retirement.test.ts +261 -0
  12. package/src/execution/__tests__/subprocess-agent-runner-routing.test.ts +310 -0
  13. package/src/execution/__tests__/subprocess-agent-runner.test.ts +53 -5
  14. package/src/execution/agent-registry.ts +10 -0
  15. package/src/execution/config.ts +25 -2
  16. package/src/execution/engine/__tests__/common/data-dir.test.ts +53 -0
  17. package/src/execution/engine/__tests__/common/errors.test.ts +132 -0
  18. package/src/execution/engine/__tests__/common/event-journal.test.ts +177 -0
  19. package/src/execution/engine/__tests__/common/kill-chain.test.ts +192 -0
  20. package/src/execution/engine/__tests__/common/nesting-guard.test.ts +81 -0
  21. package/src/execution/engine/__tests__/common/persona-router.test.ts +123 -0
  22. package/src/execution/engine/__tests__/common/pool-manager.test.ts +154 -0
  23. package/src/execution/engine/__tests__/common/schema-emulation.test.ts +128 -0
  24. package/src/execution/engine/__tests__/conformance/__fixtures__/pi-golden-events.json +28 -0
  25. package/src/execution/engine/__tests__/conformance/agent-event-invariants.ts +141 -0
  26. package/src/execution/engine/__tests__/conformance/contract.abort.test.ts +109 -0
  27. package/src/execution/engine/__tests__/conformance/contract.agent-events.test.ts +101 -0
  28. package/src/execution/engine/__tests__/conformance/contract.probe.test.ts +77 -0
  29. package/src/execution/engine/__tests__/conformance/contract.read-degradation.test.ts +104 -0
  30. package/src/execution/engine/__tests__/conformance/contract.relay.test.ts +342 -0
  31. package/src/execution/engine/__tests__/conformance/engine-conformance.live.test.ts +201 -0
  32. package/src/execution/engine/__tests__/conformance/golden-replay.pi.test.ts +76 -0
  33. package/src/execution/engine/__tests__/conformance/golden-replay.zcode.test.ts +79 -0
  34. package/src/execution/engine/__tests__/engine-discovery.test.ts +87 -0
  35. package/src/execution/engine/__tests__/engines-declaration.test.ts +36 -0
  36. package/src/execution/engine/__tests__/model-prompt.test.ts +85 -0
  37. package/src/execution/engine/__tests__/paths.test.ts +39 -0
  38. package/src/execution/engine/__tests__/registry.test.ts +120 -0
  39. package/src/execution/engine/__tests__/routing.test.ts +231 -0
  40. package/src/execution/engine/common/data-dir.ts +62 -0
  41. package/src/execution/engine/common/errors.ts +183 -0
  42. package/src/execution/engine/common/event-journal.ts +254 -0
  43. package/src/execution/engine/common/journal-replay.ts +62 -0
  44. package/src/execution/engine/common/kill-chain.ts +221 -0
  45. package/src/execution/engine/common/nesting-guard.ts +50 -0
  46. package/src/execution/engine/common/persona-router.ts +108 -0
  47. package/src/execution/engine/common/pool-manager.ts +226 -0
  48. package/src/execution/engine/common/schema-emulation.ts +189 -0
  49. package/src/execution/engine/common/session-view-projection.ts +51 -0
  50. package/src/execution/engine/engine-discovery.ts +65 -0
  51. package/src/execution/engine/engines/pi/__tests__/pi-engine.test.ts +469 -0
  52. package/src/execution/engine/engines/pi/__tests__/reader.test.ts +155 -0
  53. package/src/execution/engine/engines/pi/__tests__/task-spec-mapper.test.ts +164 -0
  54. package/src/execution/engine/engines/pi/pi-engine.ts +415 -0
  55. package/src/execution/engine/engines/pi/reader.ts +48 -0
  56. package/src/execution/engine/engines/pi/registration.ts +35 -0
  57. package/src/execution/engine/engines/pi/task-spec-mapper.ts +100 -0
  58. package/src/execution/engine/engines/zcode/__tests__/__fixtures__/zcode-golden-spawn.json +39 -0
  59. package/src/execution/engine/engines/zcode/__tests__/launcher.test.ts +150 -0
  60. package/src/execution/engine/engines/zcode/__tests__/parser.test.ts +246 -0
  61. package/src/execution/engine/engines/zcode/__tests__/preparer.test.ts +228 -0
  62. package/src/execution/engine/engines/zcode/__tests__/reader.test.ts +210 -0
  63. package/src/execution/engine/engines/zcode/__tests__/registration.test.ts +64 -0
  64. package/src/execution/engine/engines/zcode/__tests__/zcode-engine.live.test.ts +127 -0
  65. package/src/execution/engine/engines/zcode/__tests__/zcode-engine.test.ts +567 -0
  66. package/src/execution/engine/engines/zcode/constants.ts +43 -0
  67. package/src/execution/engine/engines/zcode/golden-sample.ts +39 -0
  68. package/src/execution/engine/engines/zcode/launcher.ts +161 -0
  69. package/src/execution/engine/engines/zcode/parser.ts +436 -0
  70. package/src/execution/engine/engines/zcode/preparer.ts +363 -0
  71. package/src/execution/engine/engines/zcode/reader.ts +381 -0
  72. package/src/execution/engine/engines/zcode/registration.ts +37 -0
  73. package/src/execution/engine/engines/zcode/zcode-engine.ts +648 -0
  74. package/src/execution/engine/host-task-spec.ts +47 -0
  75. package/src/execution/engine/model-prompt.ts +59 -0
  76. package/src/execution/engine/paths.ts +42 -0
  77. package/src/execution/engine/port.ts +153 -0
  78. package/src/execution/engine/registry.ts +123 -0
  79. package/src/execution/engine/routing.ts +218 -0
  80. package/src/execution/engine/types.ts +304 -0
  81. package/src/execution/execute-options-mapper.ts +5 -1
  82. package/src/execution/execution-record.ts +6 -0
  83. package/src/execution/model-resolver.ts +6 -0
  84. package/src/execution/pi-invocation.ts +32 -2
  85. package/src/execution/record-entry.ts +14 -0
  86. package/src/execution/record-store.ts +34 -0
  87. package/src/execution/relay-env.ts +37 -0
  88. package/src/execution/session-runner.ts +24 -0
  89. package/src/execution/stream-sink.ts +26 -0
  90. package/src/execution/subagent-service.ts +249 -11
  91. package/src/execution/subprocess-agent-runner.ts +196 -14
  92. package/src/execution/types.ts +56 -0
  93. package/src/index.ts +46 -1
  94. package/src/interface/command-actions.ts +72 -8
  95. package/src/interface/subagent-actions.ts +8 -2
  96. package/src/interface/subagent-tool.ts +6 -0
  97. package/src/interface/subagents.ts +198 -30
  98. package/src/orchestration/__tests__/__fixtures__/worker-template.snapshot.txt +5 -2
  99. package/src/orchestration/__tests__/worker-script-template-snapshot.test.ts +3 -3
  100. package/src/orchestration/models/types.ts +7 -0
  101. package/src/orchestration/worker-script-builder.ts +5 -2
  102. package/src/shared/meta-parser.ts +5 -1
  103. package/src/shared/resource-meta.ts +5 -0
@@ -0,0 +1,192 @@
1
+ // kill-chain.test.ts —— 杀链两分支 + 超时终态合成 + abort 两级编排(fake timers)。
2
+ //
3
+ // 三视角:①构建者——SIGTERM 优雅 / 超时 SIGKILL 两分支的信号序列正确;②使用者——
4
+ // abortWithFallback 对 CLI-only 与 native-interrupt 引擎都收敛不悬挂;③观察者——
5
+ // 合成终态的 error 含 stdout 尾部与 exitCode=null(被信号杀死判据)。
6
+
7
+ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
8
+
9
+ import {
10
+ abortWithFallback,
11
+ killChain,
12
+ synthesizeTimeoutOutcome,
13
+ } from "../../common/kill-chain.ts";
14
+ import type { KillableChild } from "../../common/kill-chain.ts";
15
+
16
+ /** fake 子进程:记录 kill 信号序列,emitExit 模拟退出(置退出态 + 触发 exit listener)。 */
17
+ function makeFakeChild(): {
18
+ child: KillableChild;
19
+ signals: string[];
20
+ emitExit(code: number | null, signal: NodeJS.Signals | null): void;
21
+ } {
22
+ const listeners: Array<(code: number | null, signal: NodeJS.Signals | null) => void> = [];
23
+ const signals: string[] = [];
24
+ const child: KillableChild = {
25
+ exitCode: null,
26
+ signalCode: null,
27
+ kill(signal?: NodeJS.Signals | number): boolean {
28
+ signals.push(String(signal ?? "SIGTERM"));
29
+ return true;
30
+ },
31
+ once(event: "exit", listener: (code: number | null, signal: NodeJS.Signals | null) => void): KillableChild {
32
+ if (event === "exit") listeners.push(listener);
33
+ return child;
34
+ },
35
+ };
36
+ return {
37
+ child,
38
+ signals,
39
+ emitExit(code, signal) {
40
+ child.exitCode = code;
41
+ child.signalCode = signal;
42
+ for (const l of listeners.splice(0)) l(code, signal);
43
+ },
44
+ };
45
+ }
46
+
47
+ beforeEach(() => {
48
+ vi.useFakeTimers();
49
+ });
50
+
51
+ afterEach(() => {
52
+ vi.useRealTimers();
53
+ });
54
+
55
+ describe("killChain", () => {
56
+ it("SIGTERM 后进程优雅退出 → 'terminated',无 SIGKILL", async () => {
57
+ const { child, signals, emitExit } = makeFakeChild();
58
+ const p = killChain(child, { graceMs: 5_000 });
59
+ emitExit(0, null); // SIGTERM 被 trap 后正常退出
60
+ expect(await p).toBe("terminated");
61
+ expect(signals).toEqual(["SIGTERM"]);
62
+ });
63
+
64
+ it("SIGTERM 超时未退 → SIGKILL 兜底 → 'killed'(fake timers 推进两级窗口)", async () => {
65
+ const { child, signals } = makeFakeChild();
66
+ const p = killChain(child, { graceMs: 5_000 });
67
+ expect(signals).toEqual(["SIGTERM"]); // kill 同步发出
68
+ await vi.advanceTimersByTimeAsync(5_000); // grace 窗口走完,进程仍活
69
+ expect(signals).toEqual(["SIGTERM", "SIGKILL"]);
70
+ await vi.advanceTimersByTimeAsync(10_000); // SIGKILL 收尸窗口(进程不退也返回)
71
+ expect(await p).toBe("killed");
72
+ });
73
+
74
+ it("进程已退出(调用前)→ 不发任何信号,'terminated'", async () => {
75
+ const { child, signals, emitExit } = makeFakeChild();
76
+ emitExit(1, null);
77
+ expect(await killChain(child, { graceMs: 5_000 })).toBe("terminated");
78
+ expect(signals).toEqual([]);
79
+ });
80
+
81
+ it("grace 窗口内恰在超时前一毫秒退出 → 复核退出态,不误发 SIGKILL", async () => {
82
+ const { child, signals, emitExit } = makeFakeChild();
83
+ const p = killChain(child, { graceMs: 5_000 });
84
+ emitExit(null, "SIGTERM"); // 被 SIGTERM 杀死(signalCode 形态)
85
+ await vi.advanceTimersByTimeAsync(5_000);
86
+ expect(await p).toBe("terminated");
87
+ expect(signals).toEqual(["SIGTERM"]);
88
+ });
89
+ });
90
+
91
+ describe("synthesizeTimeoutOutcome", () => {
92
+ it("合成 engine_timeout 终态:error 含 slug + stdout 尾部 + engine: pi 重跑建议;exitCode=null", () => {
93
+ const outcome = synthesizeTimeoutOutcome(
94
+ { task: "review files", slug: "review-files" },
95
+ "last stdout lines...",
96
+ );
97
+ expect(outcome.error).toContain("engine_timeout");
98
+ expect(outcome.error).toContain("review-files");
99
+ expect(outcome.error).toContain("last stdout lines...");
100
+ expect(outcome.error).toMatch(/`engine: pi`/);
101
+ expect(outcome.exitCode).toBe(null);
102
+ expect(outcome.content).toBe("");
103
+ expect(outcome.engineId).toBe("pi");
104
+ });
105
+
106
+ it("stdout 尾部超 2000 字截断;engineId 可指定", () => {
107
+ const outcome = synthesizeTimeoutOutcome(
108
+ { task: "t", slug: "s" },
109
+ "y".repeat(3_000),
110
+ "zcode",
111
+ );
112
+ expect(outcome.engineId).toBe("zcode");
113
+ expect(outcome.error).toContain("...");
114
+ expect(outcome.error.length).toBeLessThan(3_000);
115
+ });
116
+ });
117
+
118
+ describe("abortWithFallback", () => {
119
+ it("CLI-only 引擎(无原生中断):abort → 直接杀链,SIGTERM 退 → 'terminated'", async () => {
120
+ const { child, signals, emitExit } = makeFakeChild();
121
+ const controller = new AbortController();
122
+ const p = abortWithFallback(child, controller.signal);
123
+ controller.abort();
124
+ emitExit(0, null); // SIGTERM 生效
125
+ expect(await p).toBe("terminated");
126
+ expect(signals).toEqual(["SIGTERM"]);
127
+ });
128
+
129
+ it("原生中断生效:abort → native interrupt → 进程退出,不走杀链(零 kill 信号)", async () => {
130
+ const { child, signals, emitExit } = makeFakeChild();
131
+ const controller = new AbortController();
132
+ const interrupt = vi.fn(async () => {
133
+ emitExit(0, null); // 引擎原生中断让进程优雅退出
134
+ });
135
+ const p = abortWithFallback(child, controller.signal, interrupt);
136
+ controller.abort();
137
+ expect(await p).toBe("terminated");
138
+ expect(interrupt).toHaveBeenCalledTimes(1);
139
+ expect(signals).toEqual([]); // 从未发信号——原生中断足量
140
+ });
141
+
142
+ it("原生中断无效(进程未停)→ 宽限窗口后落杀链 SIGKILL → 'killed'", async () => {
143
+ const { child, signals } = makeFakeChild();
144
+ const controller = new AbortController();
145
+ const interrupt = vi.fn(async () => undefined); // 中断送达但进程不退
146
+ const p = abortWithFallback(child, controller.signal, interrupt, {
147
+ nativeGraceMs: 3_000,
148
+ graceMs: 5_000,
149
+ });
150
+ controller.abort();
151
+ expect(interrupt).toHaveBeenCalledTimes(1);
152
+ await vi.advanceTimersByTimeAsync(3_000); // native 宽限窗口走完
153
+ expect(signals).toEqual(["SIGTERM"]);
154
+ await vi.advanceTimersByTimeAsync(5_000); // 杀链 grace 窗口走完
155
+ expect(signals).toEqual(["SIGTERM", "SIGKILL"]);
156
+ await vi.advanceTimersByTimeAsync(10_000);
157
+ expect(await p).toBe("killed");
158
+ });
159
+
160
+ it("原生中断 throw(协议错)→ 不阻断兜底,继续杀链", async () => {
161
+ const { child, signals, emitExit } = makeFakeChild();
162
+ const controller = new AbortController();
163
+ const interrupt = vi.fn(async () => {
164
+ throw new Error("rpc broken");
165
+ });
166
+ const p = abortWithFallback(child, controller.signal, interrupt, { nativeGraceMs: 100, graceMs: 5_000 });
167
+ controller.abort();
168
+ await vi.advanceTimersByTimeAsync(100);
169
+ emitExit(0, null); // 后续 SIGTERM 生效
170
+ expect(await p).toBe("terminated");
171
+ expect(signals).toEqual(["SIGTERM"]);
172
+ });
173
+
174
+ it("进程自然退出(signal 从未 abort)→ 'terminated',promise 不悬挂", async () => {
175
+ const { child, signals, emitExit } = makeFakeChild();
176
+ const controller = new AbortController();
177
+ const p = abortWithFallback(child, controller.signal);
178
+ emitExit(0, null);
179
+ expect(await p).toBe("terminated");
180
+ expect(signals).toEqual([]);
181
+ });
182
+
183
+ it("signal 已 abort 的场景(先 abort 后接线)→ 立即执行两级中断", async () => {
184
+ const { child, signals, emitExit } = makeFakeChild();
185
+ const controller = new AbortController();
186
+ controller.abort(); // 先 abort
187
+ const p = abortWithFallback(child, controller.signal);
188
+ emitExit(0, null);
189
+ expect(await p).toBe("terminated");
190
+ expect(signals).toEqual(["SIGTERM"]);
191
+ });
192
+ });
@@ -0,0 +1,81 @@
1
+ // nesting-guard.test.ts —— 嵌套标记注入与原生标记剥离(D8 双层防护)。
2
+ //
3
+ // 三视角:①构建者——三引擎原生标记(PI_SUBAGENT_* / CLAUDECODE / ZSW_NESTED)全部
4
+ // 剥离且其余 env 保留;②使用者——子代理进程内 assertNotNestedSpawn 同步拒绝且文案
5
+ // 可操作;③观察者——产出的 env 是新对象(不污染入参)。
6
+
7
+ import { describe, expect, it } from "vitest";
8
+
9
+ import {
10
+ assertNotNestedSpawn,
11
+ buildNestedSpawnEnv,
12
+ NESTED_SPAWN_ENV,
13
+ } from "../../common/nesting-guard.ts";
14
+ import { EngineError } from "../../common/errors.ts";
15
+
16
+ describe("buildNestedSpawnEnv", () => {
17
+ it("注入统一标记 XYZ_AGENT_SUBAGENT=1", () => {
18
+ const env = buildNestedSpawnEnv({ PATH: "/usr/bin" });
19
+ expect(env[NESTED_SPAWN_ENV]).toBe("1");
20
+ expect(env.PATH).toBe("/usr/bin");
21
+ });
22
+
23
+ it("剥离 pi 原生标记 PI_SUBAGENT_*(任意后缀)", () => {
24
+ const env = buildNestedSpawnEnv({
25
+ PI_SUBAGENT_ID: "bg-1",
26
+ PI_SUBAGENT_CWD: "/tmp/x",
27
+ PI_SUBAGENT_SESSION: "abc",
28
+ KEEP_ME: "yes",
29
+ });
30
+ expect("PI_SUBAGENT_ID" in env).toBe(false);
31
+ expect("PI_SUBAGENT_CWD" in env).toBe(false);
32
+ expect("PI_SUBAGENT_SESSION" in env).toBe(false);
33
+ expect(env.KEEP_ME).toBe("yes");
34
+ });
35
+
36
+ it("剥离 CC 与 zsub 的原生标记(CLAUDECODE / ZSW_NESTED)", () => {
37
+ const env = buildNestedSpawnEnv({
38
+ CLAUDECODE: "1",
39
+ ZSW_NESTED: "1",
40
+ CLAUDE_UNRELATED: "keep", // 非嵌套标记的 CLAUDE_ 前缀不受影响
41
+ });
42
+ expect("CLAUDECODE" in env).toBe(false);
43
+ expect("ZSW_NESTED" in env).toBe(false);
44
+ expect(env.CLAUDE_UNRELATED).toBe("keep");
45
+ });
46
+
47
+ it("返回新对象,不 mutate 入参(spawn env 组装链安全)", () => {
48
+ const base = { PATH: "/usr/bin", PI_SUBAGENT_ID: "x" };
49
+ const env = buildNestedSpawnEnv(base);
50
+ expect(base.PI_SUBAGENT_ID).toBe("x");
51
+ expect("XYZ_AGENT_SUBAGENT" in base).toBe(false);
52
+ expect(env).not.toBe(base);
53
+ });
54
+
55
+ it("空白 env 也能产出仅含标记的最小 env", () => {
56
+ const env = buildNestedSpawnEnv({});
57
+ expect(env).toEqual({ [NESTED_SPAWN_ENV]: "1" });
58
+ });
59
+ });
60
+
61
+ describe("assertNotNestedSpawn", () => {
62
+ it("检测到统一标记(本进程已是 subagent)→ 抛 nested_spawn_rejected", () => {
63
+ expect(() => assertNotNestedSpawn({ [NESTED_SPAWN_ENV]: "1" })).toThrowError(EngineError);
64
+ try {
65
+ assertNotNestedSpawn({ [NESTED_SPAWN_ENV]: "1" });
66
+ expect.unreachable("should throw");
67
+ } catch (err) {
68
+ const e = err as EngineError;
69
+ expect(e.code).toBe("nested_spawn_rejected");
70
+ // 文案说明防护规则(标记名)+ 指向 task 内自行完成
71
+ expect(e.message).toContain("XYZ_AGENT_SUBAGENT");
72
+ expect(e.recovery).toMatch(/inside the current task/);
73
+ }
74
+ });
75
+
76
+ it("无标记 / 值非 '1' → 不抛(顶层进程正常派发)", () => {
77
+ expect(() => assertNotNestedSpawn({})).not.toThrow();
78
+ expect(() => assertNotNestedSpawn({ [NESTED_SPAWN_ENV]: "0" })).not.toThrow();
79
+ expect(() => assertNotNestedSpawn({ [NESTED_SPAWN_ENV]: undefined })).not.toThrow();
80
+ });
81
+ });
@@ -0,0 +1,123 @@
1
+ // persona-router.test.ts —— persona 三策略路由 + argv 预算前置拦截。
2
+ //
3
+ // 三视角:①构建者——三通道产出物各归其位;②使用者——argv 超限时报
4
+ // prompt_too_large 且文案含三条恢复建议;③观察者——估算口径含多字节字符与分隔符。
5
+
6
+ import { describe, expect, it } from "vitest";
7
+
8
+ import {
9
+ applyPersona,
10
+ assertArgvBudget,
11
+ DEFAULT_ARGV_BUDGET_BYTES,
12
+ estimateArgvBytes,
13
+ } from "../../common/persona-router.ts";
14
+ import { EngineError } from "../../common/errors.ts";
15
+ import type { EngineCapabilities } from "../../types.ts";
16
+
17
+ const CAPS_FILE: EngineCapabilities = {
18
+ schemaEnforcement: "emulated", steer: "unsupported", conversation: "unsupported",
19
+ personaInjection: "file", eventGranularity: "coarse", sandbox: "none",
20
+ sessionRead: "partial", resume: "cold", interrupt: "kill-only", permissionMode: "native",
21
+ };
22
+ const CAPS_FLAG: EngineCapabilities = { ...CAPS_FILE, personaInjection: "flag" };
23
+ const CAPS_PROMPT: EngineCapabilities = { ...CAPS_FILE, personaInjection: "prompt" };
24
+
25
+ const persona = {
26
+ agentRef: "reviewer",
27
+ skillPath: "/skills/review.md",
28
+ appendSystemPrompt: ["You are a careful code reviewer.", "Be terse."],
29
+ };
30
+
31
+ describe("applyPersona 三策略路由", () => {
32
+ it("file 策略:人设全文进 fileCandidate(路径相对池目录),promptSegment 为空", () => {
33
+ const routing = applyPersona(persona, CAPS_FILE);
34
+ expect(routing.promptSegment).toBe("");
35
+ expect(routing.fileCandidate).toBeDefined();
36
+ expect(routing.fileCandidate?.suggestedPath).toBe("persona.md");
37
+ expect(routing.fileCandidate?.content).toContain("# Agent: reviewer");
38
+ expect(routing.fileCandidate?.content).toContain("/skills/review.md");
39
+ expect(routing.fileCandidate?.content).toContain("You are a careful code reviewer.");
40
+ });
41
+
42
+ it("flag 策略:promptSegment 为纯人设正文(launcher 组 flag 直传),无 fileCandidate", () => {
43
+ const routing = applyPersona(persona, CAPS_FLAG);
44
+ expect(routing.fileCandidate).toBeUndefined();
45
+ expect(routing.promptSegment).toContain("You are a careful code reviewer.");
46
+ expect(routing.promptSegment).toContain("Be terse.");
47
+ // 纯正文:不带 prompt 通道的结构头
48
+ expect(routing.promptSegment).not.toContain("## Persona");
49
+ });
50
+
51
+ it("prompt 策略:promptSegment 为带结构头的人设段(拼进最终 prompt)", () => {
52
+ const routing = applyPersona(persona, CAPS_PROMPT);
53
+ expect(routing.promptSegment.startsWith("## Persona")).toBe(true);
54
+ expect(routing.promptSegment).toContain("# Agent: reviewer");
55
+ expect(routing.promptSegment).toContain("You are a careful code reviewer.");
56
+ });
57
+
58
+ it("空 persona(全字段缺省):三通道都产出空载体(白占 argv/prompt 无意义)", () => {
59
+ expect(applyPersona({}, CAPS_FILE)).toEqual({ promptSegment: "" });
60
+ expect(applyPersona({}, CAPS_FLAG)).toEqual({ promptSegment: "" });
61
+ expect(applyPersona({}, CAPS_PROMPT)).toEqual({ promptSegment: "" });
62
+ });
63
+
64
+ it("仅 appendSystemPrompt:file 通道照常落文件(agentRef/skillPath 头部行缺省)", () => {
65
+ const routing = applyPersona({ appendSystemPrompt: ["only body"] }, CAPS_FILE);
66
+ expect(routing.fileCandidate?.content).toBe("only body");
67
+ });
68
+ });
69
+
70
+ describe("estimateArgvBytes", () => {
71
+ it("ASCII:字节数之和 + 每参数 1 个 NUL 分隔符", () => {
72
+ // "ab"(2) + "cde"(3) + 2 个 NUL = 7
73
+ expect(estimateArgvBytes(["ab", "cde"])).toBe(7);
74
+ expect(estimateArgvBytes([])).toBe(0);
75
+ });
76
+
77
+ it("多字节字符按 UTF-8 计(中文 3 字节/字)——字符数口径会低估", () => {
78
+ // "中"=3 字节 + 1 NUL = 4
79
+ expect(estimateArgvBytes(["中"])).toBe(4);
80
+ // "a中b" = 1+3+1 = 5 字节 + 1 = 6
81
+ expect(estimateArgvBytes(["a中b"])).toBe(6);
82
+ });
83
+ });
84
+
85
+ describe("assertArgvBudget", () => {
86
+ it(`默认上限 ${DEFAULT_ARGV_BUDGET_BYTES} 字节(128KB)且预算内通过`, () => {
87
+ expect(DEFAULT_ARGV_BUDGET_BYTES).toBe(128 * 1024);
88
+ expect(() => assertArgvBudget(["--prompt", "short"])).not.toThrow();
89
+ });
90
+
91
+ it("超限抛 prompt_too_large:detail 含实际/上限字节数", () => {
92
+ const bigArg = "x".repeat(1024);
93
+ const argv = [bigArg, bigArg]; // 2KB,limit 1KB
94
+ let caught: EngineError | undefined;
95
+ try {
96
+ assertArgvBudget(argv, 1024);
97
+ expect.unreachable("should throw");
98
+ } catch (err) {
99
+ caught = err as EngineError;
100
+ }
101
+ expect(caught).toBeInstanceOf(EngineError);
102
+ expect(caught?.code).toBe("prompt_too_large");
103
+ expect(caught?.message).toContain("2050"); // 1024*2 + 2 NUL
104
+ expect(caught?.message).toContain("1024");
105
+ });
106
+
107
+ it("错误恢复指引含三条建议:缩短 task / persona 移 file 通道 / 换 stdin 引擎", () => {
108
+ try {
109
+ assertArgvBudget(["y".repeat(3000)], 1024);
110
+ expect.unreachable("should throw");
111
+ } catch (err) {
112
+ const e = err as EngineError;
113
+ expect(e.recovery).toMatch(/shorten the task/i);
114
+ expect(e.recovery).toMatch(/file channel/);
115
+ expect(e.recovery).toMatch(/stdin/);
116
+ }
117
+ });
118
+
119
+ it("limit 可配(调用方收紧到引擎实测限额)", () => {
120
+ expect(() => assertArgvBudget(["a".repeat(100)], 50)).toThrowError(/prompt_too_large/);
121
+ expect(() => assertArgvBudget(["a".repeat(100)], 101)).not.toThrow();
122
+ });
123
+ });
@@ -0,0 +1,154 @@
1
+ // pool-manager.test.ts —— 池 acquire/release 引用计数 / 归零整池删除 / journal 保留
2
+ // / 清理失败标记 / spawnedFiles 单次清理(D5 + §3.3.9)。
3
+ //
4
+ // 三视角:①构建者——计数归零才删、删除边界三硬规则逐条;②使用者——release 幂等
5
+ // 安全(无引用 no-op);③观察者——清理失败有 .pool-cleanup-failed 标记(可观测)。
6
+
7
+ import { mkdirSync, mkdtempSync, existsSync, readdirSync, rmSync, writeFileSync } from "node:fs";
8
+ import { tmpdir } from "node:os";
9
+ import { join } from "node:path";
10
+
11
+ import { afterEach, beforeEach, describe, expect, it } from "vitest";
12
+
13
+ import {
14
+ acquirePool,
15
+ cleanupSpawnedFiles,
16
+ POOL_CLEANUP_FAILED_MARKER,
17
+ releasePoolRef,
18
+ resetPoolRegistryForTests,
19
+ } from "../../common/pool-manager.ts";
20
+ import { resolvePoolDir } from "../../paths.ts";
21
+
22
+ let tmpRoot: string;
23
+
24
+ beforeEach(() => {
25
+ tmpRoot = mkdtempSync(join(tmpdir(), "engine-pool-test-"));
26
+ resetPoolRegistryForTests();
27
+ });
28
+
29
+ afterEach(() => {
30
+ rmSync(tmpRoot, { recursive: true, force: true });
31
+ });
32
+
33
+ describe("acquirePool", () => {
34
+ it("mkdir -p 返回池目录(路径经 resolvePoolDir 派生),重复 acquire 幂等", async () => {
35
+ const dir1 = await acquirePool(tmpRoot, "zcode", "reviewer");
36
+ const dir2 = await acquirePool(tmpRoot, "zcode", "reviewer");
37
+ expect(dir1).toBe(resolvePoolDir(tmpRoot, "zcode", "reviewer"));
38
+ expect(dir1).toBe(dir2);
39
+ expect(existsSync(dir1)).toBe(true);
40
+ });
41
+
42
+ it("poolKey 经 sanitizeSeg 归一(脏字符不进文件系统路径)", async () => {
43
+ const dir = await acquirePool(tmpRoot, "zcode", "weird/key..name");
44
+ expect(dir).toBe(resolvePoolDir(tmpRoot, "zcode", "weird-key-name"));
45
+ });
46
+ });
47
+
48
+ describe("releasePoolRef 引用计数与整池删除", () => {
49
+ it("双引用:release 一次池仍在(原生状态未删),归零才整池删除", async () => {
50
+ const poolDir = resolvePoolDir(tmpRoot, "zcode", "reviewer");
51
+ await acquirePool(tmpRoot, "zcode", "reviewer");
52
+ await acquirePool(tmpRoot, "zcode", "reviewer");
53
+ mkdirSync(join(poolDir, "home"), { recursive: true });
54
+ writeFileSync(join(poolDir, "home", "config.json"), "{}");
55
+
56
+ await releasePoolRef(tmpRoot, "zcode", "reviewer");
57
+ expect(existsSync(join(poolDir, "home"))).toBe(true); // 计数 1,不删
58
+
59
+ await releasePoolRef(tmpRoot, "zcode", "reviewer"); // 归零
60
+ expect(existsSync(join(poolDir, "home"))).toBe(false); // 原生状态已删
61
+ });
62
+
63
+ it("journal-*.jsonl 不随池删(生命周期跟随 record),目录保留", async () => {
64
+ const poolDir = resolvePoolDir(tmpRoot, "zcode", "reviewer");
65
+ await acquirePool(tmpRoot, "zcode", "reviewer");
66
+ writeFileSync(join(poolDir, "journal-bg-1.jsonl"), "{}\n");
67
+ mkdirSync(join(poolDir, "home"), { recursive: true });
68
+
69
+ await releasePoolRef(tmpRoot, "zcode", "reviewer");
70
+ expect(existsSync(join(poolDir, "journal-bg-1.jsonl"))).toBe(true);
71
+ expect(existsSync(join(poolDir, "home"))).toBe(false);
72
+ // 只剩 journal:目录本体保留(journal 还在用)
73
+ expect(existsSync(poolDir)).toBe(true);
74
+ expect(readdirSync(poolDir)).toEqual(["journal-bg-1.jsonl"]);
75
+ });
76
+
77
+ it("无引用的 release(进程重启后 GC)→ 保守 no-op 不删池", async () => {
78
+ const poolDir = resolvePoolDir(tmpRoot, "zcode", "reviewer");
79
+ mkdirSync(join(poolDir, "home"), { recursive: true });
80
+ await releasePoolRef(tmpRoot, "zcode", "reviewer");
81
+ expect(existsSync(join(poolDir, "home"))).toBe(true);
82
+ });
83
+
84
+ it("池目录不存在时 release 归零 → 无原生状态可清,视为成功不抛", async () => {
85
+ await acquirePool(tmpRoot, "zcode", "ghost");
86
+ // 归零但目录已被外部删除
87
+ rmSync(resolvePoolDir(tmpRoot, "zcode", "ghost"), { recursive: true, force: true });
88
+ await expect(releasePoolRef(tmpRoot, "zcode", "ghost")).resolves.toBeUndefined();
89
+ });
90
+
91
+ it("删除失败置 .pool-cleanup-failed 标记文件(可观测不静默),不 throw", async () => {
92
+ const poolDir = resolvePoolDir(tmpRoot, "zcode", "reviewer");
93
+ await acquirePool(tmpRoot, "zcode", "reviewer");
94
+ mkdirSync(join(poolDir, "home"), { recursive: true });
95
+ writeFileSync(join(poolDir, "journal-bg-1.jsonl"), "{}\n");
96
+
97
+ // 注入失败 fs:rm 对 home 目录 reject(标记写入仍走真实 fs——失败要可观测)
98
+ const realFs = await import("node:fs/promises");
99
+ const injected = {
100
+ mkdir: (p: string, o: { recursive: boolean }) => realFs.mkdir(p, o),
101
+ readdir: (p: string) => realFs.readdir(p, { withFileTypes: true }),
102
+ rm: async (p: string, o: { recursive: boolean; force: boolean }) => {
103
+ if (p === join(poolDir, "home")) throw new Error("EACCES: permission denied");
104
+ return realFs.rm(p, o);
105
+ },
106
+ rmdir: (p: string) => realFs.rmdir(p),
107
+ writeFile: (p: string, d: string) => realFs.writeFile(p, d, "utf8"),
108
+ };
109
+
110
+ await expect(releasePoolRef(tmpRoot, "zcode", "reviewer", injected)).resolves.toBeUndefined();
111
+ const markerPath = join(poolDir, POOL_CLEANUP_FAILED_MARKER);
112
+ expect(existsSync(markerPath)).toBe(true);
113
+ // 标记内容是失败清单 JSON(含失败条目与原因)
114
+ const payload = JSON.parse(
115
+ (await import("node:fs")).readFileSync(markerPath, "utf8"),
116
+ ) as { failures: string[] };
117
+ expect(payload.failures.length).toBe(1);
118
+ expect(payload.failures[0]).toContain("home");
119
+ expect(payload.failures[0]).toContain("EACCES");
120
+ });
121
+ });
122
+
123
+ describe("cleanupSpawnedFiles(单次性产物)", () => {
124
+ it("keepForResume=true → 全部保留(resume 续接原 session,不重写产物)", async () => {
125
+ const f = join(tmpRoot, "prompt.txt");
126
+ writeFileSync(f, "x");
127
+ await cleanupSpawnedFiles([f], { keepForResume: true });
128
+ expect(existsSync(f)).toBe(true);
129
+ });
130
+
131
+ it("keepForResume=false → 删除;目录产物递归删", async () => {
132
+ const file = join(tmpRoot, "prompt.txt");
133
+ const dir = join(tmpRoot, "persona");
134
+ writeFileSync(file, "x");
135
+ mkdirSync(dir, { recursive: true });
136
+ writeFileSync(join(dir, "persona.md"), "y");
137
+ await cleanupSpawnedFiles([file, dir], { keepForResume: false });
138
+ expect(existsSync(file)).toBe(false);
139
+ expect(existsSync(dir)).toBe(false);
140
+ });
141
+
142
+ it("不存在的路径幂等(ENOENT 忽略);单条失败不 throw 其余继续", async () => {
143
+ const good = join(tmpRoot, "good.txt");
144
+ writeFileSync(good, "x");
145
+ // 真实 fs 下很难制造 rm 失败——用「父路径为文件」制造 ENOTDIR 失败:
146
+ // rm(recursive, force) 对 «file/child» 形态报 ENOTDIR(force 只豁免 ENOENT)
147
+ const blocked = join(tmpRoot, "plain-file", "child");
148
+ writeFileSync(join(tmpRoot, "plain-file"), "not a dir");
149
+ await expect(
150
+ cleanupSpawnedFiles([blocked, good], { keepForResume: false }),
151
+ ).resolves.toBeUndefined();
152
+ expect(existsSync(good)).toBe(false);
153
+ });
154
+ });
@@ -0,0 +1,128 @@
1
+ // schema-emulation.test.ts —— 三级容错提取逐级用例 + ajv 校验 + tail 载体。
2
+ //
3
+ // 三视角:①构建者——三级容错每级有独立触达用例(直接 parse / fence / 括号扫描);
4
+ // ②使用者——ok:false 时 error 简述 + tail 足以构造重试 prompt;③观察者——prompt
5
+ // 注入段含 schema 声明与输出约定(emulated 引擎拼进 prompt 后模型可遵循)。
6
+
7
+ import { describe, expect, it } from "vitest";
8
+
9
+ import {
10
+ buildSchemaEmulationSegment,
11
+ extractAndValidateStructuredOutput,
12
+ SCHEMA_EMULATION_TAIL_CHARS,
13
+ } from "../../common/schema-emulation.ts";
14
+
15
+ const objectSchema = {
16
+ type: "object",
17
+ properties: { verdict: { type: "string" }, issues: { type: "array", items: { type: "string" } } },
18
+ required: ["verdict"],
19
+ } as const;
20
+
21
+ describe("buildSchemaEmulationSegment", () => {
22
+ it("注入段含 schema JSON 声明 + 输出格式约定(用户可见 prompt 断言)", () => {
23
+ const segment = buildSchemaEmulationSegment(objectSchema);
24
+ expect(segment).toContain("## Structured Output Requirement");
25
+ expect(segment).toContain(JSON.stringify(objectSchema));
26
+ expect(segment).toMatch(/```json/);
27
+ expect(segment).toMatch(/ONLY the JSON value/);
28
+ expect(segment).toMatch(/JSON Schema \(draft-07\)/);
29
+ });
30
+ });
31
+
32
+ describe("extractAndValidateStructuredOutput 三级容错", () => {
33
+ it("第 1 级:输出整体即合法 JSON → 直接 parse 通过 + ajv 通过", () => {
34
+ const text = JSON.stringify({ verdict: "pass", issues: [] });
35
+ const result = extractAndValidateStructuredOutput(text, objectSchema);
36
+ expect(result).toEqual({ ok: true, parsed: { verdict: "pass", issues: [] } });
37
+ });
38
+
39
+ it("第 2 级:markdown code fence 包裹 → 剥 fence 后 parse 通过", () => {
40
+ const text = "Here is my answer:\n```json\n{\"verdict\": \"fail\", \"issues\": [\"a\", \"b\"]}\n```\n";
41
+ const result = extractAndValidateStructuredOutput(text, objectSchema);
42
+ expect(result).toEqual({ ok: true, parsed: { verdict: "fail", issues: ["a", "b"] } });
43
+ });
44
+
45
+ it("第 2 级:无语言标注的裸 fence 也能剥", () => {
46
+ const text = "```\n{\"verdict\": \"pass\"}\n```";
47
+ const result = extractAndValidateStructuredOutput(text, objectSchema);
48
+ expect(result).toEqual({ ok: true, parsed: { verdict: "pass" } });
49
+ });
50
+
51
+ it("第 3 级:前后杂文本包裹 → 首尾括号扫描提取", () => {
52
+ const text = "Sure! The review result is:\n\n{\"verdict\": \"fail\", \"issues\": [\"x\"]}\n\nHope this helps.";
53
+ const result = extractAndValidateStructuredOutput(text, objectSchema);
54
+ expect(result).toEqual({ ok: true, parsed: { verdict: "fail", issues: ["x"] } });
55
+ });
56
+
57
+ it("第 3 级:array 根也支持(首个 '[' 到末个 ']')", () => {
58
+ const arraySchema = { type: "array", items: { type: "string" } };
59
+ const result = extractAndValidateStructuredOutput("prefix [\"a\",\"b\"] suffix", arraySchema);
60
+ expect(result).toEqual({ ok: true, parsed: ["a", "b"] });
61
+ });
62
+
63
+ it("提取成功但 ajv 校验失败 → ok:false 含 ajv 错误明细与原始尾部", () => {
64
+ // verdict 缺失(required)+ issues 类型错
65
+ const text = '{"issues": "not-an-array"}';
66
+ const result = extractAndValidateStructuredOutput(text, objectSchema);
67
+ expect(result.ok).toBe(false);
68
+ if (!result.ok) {
69
+ expect(result.error).toContain("Schema validation failed");
70
+ expect(result.error).toContain("verdict");
71
+ expect(result.tail).toBe(text);
72
+ }
73
+ });
74
+
75
+ it("三级提取全失败(无任何 JSON)→ ok:false 且 error 指明三级路径", () => {
76
+ const result = extractAndValidateStructuredOutput("no json here at all", objectSchema);
77
+ expect(result.ok).toBe(false);
78
+ if (!result.ok) {
79
+ expect(result.error).toContain("3-stage");
80
+ expect(result.error).toContain("code-fence");
81
+ expect(result.error).toContain("bracket scan");
82
+ }
83
+ });
84
+
85
+ it("提取成功但 JSON 语法损坏(括号扫描后仍 parse 失败)→ ok:false", () => {
86
+ const result = extractAndValidateStructuredOutput("result: {verdict: pass}", objectSchema);
87
+ expect(result.ok).toBe(false);
88
+ });
89
+
90
+ it("ajv 编译失败(非法 schema)→ ok:false 指明 host 侧编译失败", () => {
91
+ // type: "foo" 是 ajv 编译期拒绝的非法类型值
92
+ const result = extractAndValidateStructuredOutput('{"a":1}', { type: "foo" });
93
+ expect(result.ok).toBe(false);
94
+ if (!result.ok) {
95
+ expect(result.error).toContain("compilation failed");
96
+ }
97
+ });
98
+ });
99
+
100
+ describe("tail 载体(错误展示)", () => {
101
+ it(`tail 截断到原始输出尾部 ${SCHEMA_EMULATION_TAIL_CHARS} 字`, () => {
102
+ const head = "H".repeat(300);
103
+ const tailPart = "T".repeat(400);
104
+ const text = `${head}${tailPart}`; // 700 字,尾部 500 = 末段(100H + 400T)
105
+ const result = extractAndValidateStructuredOutput(text, objectSchema);
106
+ expect(result.ok).toBe(false);
107
+ if (!result.ok) {
108
+ expect(result.tail.length).toBe(SCHEMA_EMULATION_TAIL_CHARS);
109
+ expect(result.tail).toBe("H".repeat(100) + "T".repeat(400));
110
+ }
111
+ });
112
+
113
+ it("短输出 tail 为原文(不截断)", () => {
114
+ const text = "short broken output";
115
+ const result = extractAndValidateStructuredOutput(text, objectSchema);
116
+ expect(result.ok).toBe(false);
117
+ if (!result.ok) {
118
+ expect(result.tail).toBe(text);
119
+ }
120
+ });
121
+ });
122
+
123
+ describe("D4 硬分流守护(静态断言)", () => {
124
+ it("本模块的 ajv 只在 emulated 路径——native 引擎(pi-env 链路)不 import 本模块(由全仓 grep 守护,见任务报告)", () => {
125
+ // 占位用例:硬分流是 import 约束,运行时无对应断言点;保留用例记录守护方式
126
+ expect(typeof extractAndValidateStructuredOutput).toBe("function");
127
+ });
128
+ });