pi-ate-workflow 0.2.3 → 0.2.5

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.
package/subagent.ts CHANGED
@@ -1,132 +1,140 @@
1
- /**
2
- * workflow: 子代理执行器公开 API
3
- *
4
- * spawn 实现在 subagent-spawn-once.ts 和 subagent-spawn-visible.ts。
5
- * 超时在 timeout-config.ts 单点解析(fallback < timeoutMs < agentTimeouts < 显式传参)。
6
- * 桥接在 intercom-bridge.ts 默认注入(PI_SUBAGENT_* 5 变量)。
7
- */
8
-
9
- import * as fs from "node:fs";
10
- import * as path from "node:path";
11
- import type { SubagentResult, SubagentEvent } from "./types";
12
- import {
13
- createVisibleTaskDir,
14
- findAndInjectParentSession,
15
- writeTempPrompt,
16
- } from "./subagent-utils";
17
- import { loadAgentDef } from "@pi-atelier/shared-utils";
18
- import { spawnOnce } from "./subagent-spawn-once";
19
- import { spawnVisible } from "./subagent-spawn-visible";
20
- import { resolveSubagentTimeout } from "./timeout-config";
21
- import {
22
- buildIntercomBridge,
23
- resolveOrchestratorName,
24
- } from "./intercom-bridge";
25
-
26
- /** 模块级 session 文件解析器,由各扩展在 session_start 时注册 */
27
- let _sessionFileResolver: (() => string | undefined) | undefined;
28
-
29
- /** 各扩展在 session_start hook 中调用,注册当前会话文件路径的获取方式 */
30
- export function setSessionFileResolver(resolver: (() => string | undefined) | undefined) {
31
- _sessionFileResolver = resolver;
32
- }
33
-
34
- /** 格式约束,拼入 task 让子代理自检,执行后验证 */
35
- export interface OutputConstraint {
36
- /** 约束描述(自然语言,拼入 task) */
37
- rule: string;
38
- /** 验证函数:返回 null 表示通过,否则返回错误描述 */
39
- validate: (output: string) => string | null;
40
- }
41
-
42
- /** 构建格式约束追加提示词 */
43
- function buildConstraintAppendix(constraints: OutputConstraint[]): string {
44
- const rules = constraints.map((c, i) => `${i + 1}. ${c.rule}`).join("\n");
45
- return `\n\n---\n\n## 输出格式约束(严格遵守)\n\n你的输出会被自动化系统解析,必须严格遵守以下格式规则:\n\n${rules}\n\n**在输出审查结果之前,先检查你的输出是否符合上述所有规则。如果不符合,修正后再输出。**`;
46
- }
47
-
48
- /** 验证输出是否满足所有约束,返回不通过的列表 */
49
- export function validateOutputConstraints(output: string, constraints: OutputConstraint[]): string[] {
50
- const violations: string[] = [];
51
- for (const c of constraints) {
52
- const err = c.validate(output);
53
- if (err) violations.push(err);
54
- }
55
- return violations;
56
- }
57
-
58
- /**
59
- * 运行子代理(唯一 spawn 路径)。
60
- *
61
- * 超时:timeoutMs 参数为显式传参(最高优先级);未传时由配置链解析
62
- * (代码 fallback 30min < subagent.timeoutMs < subagent.agentTimeouts[agentName])。
63
- * 桥接:默认注入 PI_SUBAGENT_* 桥接环境变量(extraEnv 传入的变量优先保留)。
64
- *
65
- * @param agentName 对应 ~/.pi/agent/agents/{name}.md
66
- * @param visible true=在 tmux/WezTerm 窗格中可见运行(默认),false=后台运行
67
- */
68
- export async function runSubagent(
69
- agentName: string,
70
- task: string,
71
- cwd: string,
72
- signal?: AbortSignal,
73
- modelOverride?: string,
74
- timeoutMs?: number,
75
- onEvent?: (event: SubagentEvent) => void,
76
- outputConstraints?: OutputConstraint[],
77
- visible: boolean = true,
78
- extraEnv?: Record<string, string>,
79
- ): Promise<SubagentResult> {
80
- const agentDef = loadAgentDef(agentName, cwd);
81
- if (!agentDef) {
82
- throw new Error(`子代理定义 "${agentName}" 未找到。请确保 ${agentName}.md 在 ~/.pi/agent/agents/、~/.agents/agents/ 或项目级 .pi/agents/ 中存在。`);
83
- }
84
-
85
- // 超时单点解析:显式传参 > agentTimeouts > timeoutMs > fallback
86
- const effectiveTimeout = resolveSubagentTimeout(agentName, cwd, timeoutMs);
87
-
88
- // 自动解析当前会话文件路径,用于建立 parentSession 关联
89
- const parentSessionPath = _sessionFileResolver?.();
90
-
91
- // 桥接环境变量:默认注入,调用方 extraEnv 优先
92
- const orchestratorName = await resolveOrchestratorName();
93
- const bridgeEnv = buildIntercomBridge(orchestratorName, agentName);
94
- const env = { ...bridgeEnv, ...extraEnv };
95
-
96
- const useVisible = visible && !!(process.env.TMUX || process.env.WEZTERM_PANE);
97
-
98
- const tmpPromptPath = await writeTempPrompt(agentDef.systemPrompt);
99
-
100
- try {
101
- const constraintAppendix = outputConstraints?.length ? buildConstraintAppendix(outputConstraints) : "";
102
- const fullTask = task + constraintAppendix;
103
-
104
- const MAX_RETRIES = 2;
105
- let lastResult: SubagentResult | undefined;
106
-
107
- for (let attempt = 0; attempt <= MAX_RETRIES; attempt++) {
108
- const taskForAttempt = attempt === 0 ? fullTask
109
- : `${fullTask}\n\n---\n\n⚠️ 你上一轮的输出不符合格式约束:\n${validateOutputConstraints(lastResult!.output, outputConstraints!).join("\n")}\n\n请修正格式后重新输出完整的审查结果。不要重复工具调用,直接输出修正后的文本。`;
110
-
111
- const result = useVisible
112
- ? await spawnVisible(taskForAttempt, cwd, tmpPromptPath, agentDef, signal, modelOverride, effectiveTimeout, onEvent, parentSessionPath, env)
113
- : await spawnOnce(taskForAttempt, cwd, tmpPromptPath, agentDef, signal, modelOverride, effectiveTimeout, onEvent, parentSessionPath, env);
114
- lastResult = result;
115
-
116
- // 后台模式:子进程退出后通过 sessionId 查找 session 文件并注入 parentSession
117
- if (!useVisible && parentSessionPath && result.subSessionId) {
118
- findAndInjectParentSession(result.subSessionId, parentSessionPath, cwd);
119
- }
120
-
121
- if (!outputConstraints?.length) break;
122
- if (result.exitCode !== 0 && result.output.length <= 100) break;
123
-
124
- const violations = validateOutputConstraints(result.output, outputConstraints);
125
- if (violations.length === 0) break;
126
- }
127
-
128
- return lastResult!;
129
- } finally {
130
- try { const dir = path.dirname(tmpPromptPath); fs.unlinkSync(tmpPromptPath); fs.rmdirSync(dir); } catch { /* ignore */ }
131
- }
132
- }
1
+ /**
2
+ * workflow: 子代理执行器公开 API
3
+ *
4
+ * spawn 实现在 subagent-spawn-once.ts 和 subagent-spawn-visible.ts。
5
+ * 超时在 timeout-config.ts 单点解析(fallback < timeoutMs < agentTimeouts < 显式传参)。
6
+ * 桥接在 intercom-bridge.ts 默认注入(PI_SUBAGENT_* 5 变量)。
7
+ */
8
+
9
+ import * as fs from "node:fs";
10
+ import * as path from "node:path";
11
+ import type { SubagentResult, SubagentEvent } from "./types";
12
+ import {
13
+ createVisibleTaskDir,
14
+ findAndInjectParentSession,
15
+ writeTempPrompt,
16
+ } from "./subagent-utils";
17
+ import { loadAgentDef } from "@pi-atelier/shared-utils";
18
+ import { spawnOnce } from "./subagent-spawn-once";
19
+ import { spawnVisible } from "./subagent-spawn-visible";
20
+ import { resolveSubagentTimeout } from "./timeout-config";
21
+ import {
22
+ buildIntercomBridge,
23
+ resolveOrchestratorName,
24
+ } from "./intercom-bridge";
25
+ import { isSystemicSubagentFailure, buildSystemicFailureResult } from "./utils";
26
+
27
+ /** 模块级 session 文件解析器,由各扩展在 session_start 时注册 */
28
+ let _sessionFileResolver: (() => string | undefined) | undefined;
29
+
30
+ /** 各扩展在 session_start hook 中调用,注册当前会话文件路径的获取方式 */
31
+ export function setSessionFileResolver(resolver: (() => string | undefined) | undefined) {
32
+ _sessionFileResolver = resolver;
33
+ }
34
+
35
+ /** 格式约束,拼入 task 让子代理自检,执行后验证 */
36
+ export interface OutputConstraint {
37
+ /** 约束描述(自然语言,拼入 task) */
38
+ rule: string;
39
+ /** 验证函数:返回 null 表示通过,否则返回错误描述 */
40
+ validate: (output: string) => string | null;
41
+ }
42
+
43
+ /** 构建格式约束追加提示词 */
44
+ function buildConstraintAppendix(constraints: OutputConstraint[]): string {
45
+ const rules = constraints.map((c, i) => `${i + 1}. ${c.rule}`).join("\n");
46
+ return `\n\n---\n\n## 输出格式约束(严格遵守)\n\n你的输出会被自动化系统解析,必须严格遵守以下格式规则:\n\n${rules}\n\n**在输出审查结果之前,先检查你的输出是否符合上述所有规则。如果不符合,修正后再输出。**`;
47
+ }
48
+
49
+ /** 验证输出是否满足所有约束,返回不通过的列表 */
50
+ export function validateOutputConstraints(output: string, constraints: OutputConstraint[]): string[] {
51
+ const violations: string[] = [];
52
+ for (const c of constraints) {
53
+ const err = c.validate(output);
54
+ if (err) violations.push(err);
55
+ }
56
+ return violations;
57
+ }
58
+
59
+ /**
60
+ * 运行子代理(唯一 spawn 路径)。
61
+ *
62
+ * 超时:timeoutMs 参数为显式传参(最高优先级);未传时由配置链解析
63
+ * (代码 fallback 30min < subagent.timeoutMs < subagent.agentTimeouts[agentName])。
64
+ * 桥接:默认注入 PI_SUBAGENT_* 桥接环境变量(extraEnv 传入的变量优先保留)。
65
+ *
66
+ * @param agentName 对应 ~/.pi/agent/agents/{name}.md
67
+ * @param visible true=在 tmux/WezTerm 窗格中可见运行(默认),false=后台运行
68
+ */
69
+ export async function runSubagent(
70
+ agentName: string,
71
+ task: string,
72
+ cwd: string,
73
+ signal?: AbortSignal,
74
+ modelOverride?: string,
75
+ timeoutMs?: number,
76
+ onEvent?: (event: SubagentEvent) => void,
77
+ outputConstraints?: OutputConstraint[],
78
+ visible: boolean = true,
79
+ extraEnv?: Record<string, string>,
80
+ ): Promise<SubagentResult> {
81
+ const agentDef = loadAgentDef(agentName, cwd);
82
+ if (!agentDef) {
83
+ throw new Error(`子代理定义 "${agentName}" 未找到。请确保 ${agentName}.md 在 ~/.pi/agent/agents/、~/.agents/agents/ 或项目级 .pi/agents/ 中存在。`);
84
+ }
85
+
86
+ // 超时单点解析:显式传参 > agentTimeouts > timeoutMs > fallback
87
+ const effectiveTimeout = resolveSubagentTimeout(agentName, cwd, timeoutMs);
88
+
89
+ // 自动解析当前会话文件路径,用于建立 parentSession 关联
90
+ const parentSessionPath = _sessionFileResolver?.();
91
+
92
+ // 桥接环境变量:默认注入,调用方 extraEnv 优先
93
+ const orchestratorName = await resolveOrchestratorName();
94
+ const bridgeEnv = buildIntercomBridge(orchestratorName, agentName);
95
+ const env = { ...bridgeEnv, ...extraEnv };
96
+
97
+ const useVisible = visible && !!(process.env.TMUX || process.env.WEZTERM_PANE);
98
+
99
+ const tmpPromptPath = await writeTempPrompt(agentDef.systemPrompt);
100
+
101
+ try {
102
+ const constraintAppendix = outputConstraints?.length ? buildConstraintAppendix(outputConstraints) : "";
103
+ const fullTask = task + constraintAppendix;
104
+
105
+ const MAX_RETRIES = 2;
106
+ let lastResult: SubagentResult | undefined;
107
+
108
+ for (let attempt = 0; attempt <= MAX_RETRIES; attempt++) {
109
+ const taskForAttempt = attempt === 0 ? fullTask
110
+ : `${fullTask}\n\n---\n\n⚠️ 你上一轮的输出不符合格式约束:\n${validateOutputConstraints(lastResult!.output, outputConstraints!).join("\n")}\n\n请修正格式后重新输出完整的审查结果。不要重复工具调用,直接输出修正后的文本。`;
111
+
112
+ const result = useVisible
113
+ ? await spawnVisible(taskForAttempt, cwd, tmpPromptPath, agentDef, signal, modelOverride, effectiveTimeout, onEvent, parentSessionPath, env)
114
+ : await spawnOnce(taskForAttempt, cwd, tmpPromptPath, agentDef, signal, modelOverride, effectiveTimeout, onEvent, parentSessionPath, env);
115
+ lastResult = result;
116
+
117
+ // 后台模式:子进程退出后通过 sessionId 查找 session 文件并注入 parentSession
118
+ if (!useVisible && parentSessionPath && result.subSessionId) {
119
+ findAndInjectParentSession(result.subSessionId, parentSessionPath, cwd);
120
+ }
121
+
122
+ // 系统性失败(error 字段 / timedOut / 空占位输出兼 stderr 非空,含 visible jsonl 终结形态信号):
123
+ // spawn 层阵亡,重试无效——组装失败档(error 必填 + stderr 尾部透出)直接返回,不消耗重试次数
124
+ if (isSystemicSubagentFailure(result)) {
125
+ lastResult = buildSystemicFailureResult(result);
126
+ break;
127
+ }
128
+
129
+ if (!outputConstraints?.length) break;
130
+ if (result.exitCode !== 0 && result.output.length <= 100) break;
131
+
132
+ const violations = validateOutputConstraints(result.output, outputConstraints);
133
+ if (violations.length === 0) break;
134
+ }
135
+
136
+ return lastResult!;
137
+ } finally {
138
+ try { const dir = path.dirname(tmpPromptPath); fs.unlinkSync(tmpPromptPath); fs.rmdirSync(dir); } catch { /* ignore */ }
139
+ }
140
+ }
@@ -1,19 +1,47 @@
1
1
  /**
2
2
  * 测试 createVisibleTaskDir — 可见模式临时目录与 launch.sh 生成
3
3
  *
4
- * extraEnv → export 行注入、单引号转义、Unix 路径转换、AUTO_EXIT 注入
4
+ * extraEnv → export 行注入、单引号转义、Unix 路径转换、AUTO_EXIT 注入、
5
+ * proc.pid 自报行、创建时触发超龄清扫(mock proc-guard 隔离真实 Temp)
5
6
  */
6
- import { describe, it, expect } from "vitest";
7
+ import { describe, it, expect, vi, beforeEach } from "vitest";
7
8
  import * as fs from "node:fs";
8
9
  import * as os from "node:os";
9
10
  import * as path from "node:path";
10
11
  import { createVisibleTaskDir } from "../subagent-utils";
12
+ import { sweepStaleVisibleTaskDirs } from "../proc-guard";
13
+
14
+ vi.mock("../proc-guard", () => ({
15
+ sweepStaleVisibleTaskDirs: vi.fn(),
16
+ }));
17
+ const sweepMock = vi.mocked(sweepStaleVisibleTaskDirs);
11
18
 
12
19
  function cleanupDir(dir: string) {
13
20
  try { fs.rmSync(dir, { recursive: true, force: true }); } catch { /* ignore */ }
14
21
  }
15
22
 
16
23
  describe("createVisibleTaskDir — launch.sh 生成", () => {
24
+ beforeEach(() => { sweepMock.mockClear(); });
25
+
26
+ it("launch.sh 首行自报 proc.pid(shell pid + winpid,含路径转义)", () => {
27
+ const dir = createVisibleTaskDir("task", "C:\\Users\\test\\project", "/tmp/prompt.md", { tools: ["read"] });
28
+ try {
29
+ const script = fs.readFileSync(dir.launchScript, "utf-8");
30
+ // 自报行:落盘到任务目录的 proc.pid,Unix 路径(避免反斜杠转义歧义)
31
+ const unixTaskDir = dir.taskDir.replace(/\\/g, "/");
32
+ expect(script).toContain(`> '${unixTaskDir}/proc.pid'`);
33
+ expect(script).toContain("cat /proc/$$/winpid");
34
+ expect(script).toContain('echo "$$ ');
35
+ } finally { cleanupDir(dir.taskDir); }
36
+ });
37
+
38
+ it("创建时顺带触发超龄残留清扫(兑底主进程退出导致的残留)", () => {
39
+ const dir = createVisibleTaskDir("task", "/cwd", "/tmp/prompt.md", { tools: ["read"] });
40
+ try {
41
+ expect(sweepMock).toHaveBeenCalledTimes(1);
42
+ } finally { cleanupDir(dir.taskDir); }
43
+ });
44
+
17
45
  it("extraEnv 写入 export 行", () => {
18
46
  const extraEnv = {
19
47
  PI_SUBAGENT_ORCHESTRATOR_TARGET: "my-session",
@@ -0,0 +1,192 @@
1
+ /**
2
+ * 测试 proc-guard.ts — 进程身份探测 / 死透等待 / 树杀
3
+ *
4
+ * 执行器注入 mock,不触碰真实进程;清扫测试见 sweep-stale.test.ts。
5
+ */
6
+ import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
7
+ import * as fs from "node:fs";
8
+ import * as os from "node:os";
9
+ import * as path from "node:path";
10
+ import {
11
+ readProcPid,
12
+ resolvePlatformPid,
13
+ isPidAlive,
14
+ killTree,
15
+ waitForPidExit,
16
+ type ProcGuardExecutor,
17
+ } from "../proc-guard";
18
+
19
+ // ─── readProcPid / resolvePlatformPid ───────────────────
20
+
21
+ describe("readProcPid", () => {
22
+ it("解析合法自报文件(shellPid winpid)", () => {
23
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), "pg-test-"));
24
+ try {
25
+ fs.writeFileSync(path.join(dir, "proc.pid"), "1234 5678\n");
26
+ expect(readProcPid(dir)).toEqual({ shellPid: 1234, winpid: 5678 });
27
+ } finally { fs.rmSync(dir, { recursive: true, force: true }); }
28
+ });
29
+
30
+ it("winpid 为 0 也解析(Unix 平台仍可用 shell pid)", () => {
31
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), "pg-test-"));
32
+ try {
33
+ fs.writeFileSync(path.join(dir, "proc.pid"), "1234 0");
34
+ expect(readProcPid(dir)).toEqual({ shellPid: 1234, winpid: 0 });
35
+ } finally { fs.rmSync(dir, { recursive: true, force: true }); }
36
+ });
37
+
38
+ it("文件缺失返回 null", () => {
39
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), "pg-test-"));
40
+ try {
41
+ expect(readProcPid(dir)).toBeNull();
42
+ } finally { fs.rmSync(dir, { recursive: true, force: true }); }
43
+ });
44
+
45
+ it("格式异常(非数字/单段/shellPid<=0)返回 null", () => {
46
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), "pg-test-"));
47
+ try {
48
+ fs.writeFileSync(path.join(dir, "proc.pid"), "not a pid");
49
+ expect(readProcPid(dir)).toBeNull();
50
+ fs.writeFileSync(path.join(dir, "proc.pid"), "999");
51
+ expect(readProcPid(dir)).toBeNull();
52
+ fs.writeFileSync(path.join(dir, "proc.pid"), "0 0");
53
+ expect(readProcPid(dir)).toBeNull();
54
+ } finally { fs.rmSync(dir, { recursive: true, force: true }); }
55
+ });
56
+ });
57
+
58
+ describe("resolvePlatformPid — 平台适用 pid", () => {
59
+ it("info 为 null 返回 null", () => {
60
+ expect(resolvePlatformPid(null)).toBeNull();
61
+ });
62
+ it("win32 下判 winpid;winpid=0 无可用 pid", () => {
63
+ vi.stubGlobal("process", { ...process, platform: "win32" });
64
+ try {
65
+ expect(resolvePlatformPid({ shellPid: 1, winpid: 2 })).toBe(2);
66
+ expect(resolvePlatformPid({ shellPid: 1, winpid: 0 })).toBeNull();
67
+ } finally { vi.unstubAllGlobals(); }
68
+ });
69
+ it("非 win32 下判 shell pid;winpid=0 不构成降级信号", () => {
70
+ vi.stubGlobal("process", { ...process, platform: "linux" });
71
+ try {
72
+ expect(resolvePlatformPid({ shellPid: 5, winpid: 0 })).toBe(5);
73
+ expect(resolvePlatformPid({ shellPid: 5, winpid: 99 })).toBe(5);
74
+ } finally { vi.unstubAllGlobals(); }
75
+ });
76
+ });
77
+
78
+ // ─── isPidAlive / killTree / waitForPidExit(执行器注入) ────
79
+
80
+ const makeExecutor = (stdout: string | null): ProcGuardExecutor => ({
81
+ run: vi.fn(() => stdout),
82
+ });
83
+
84
+ describe("isPidAlive(win32 分支)", () => {
85
+ beforeEach(() => { vi.stubGlobal("process", { ...process, platform: "win32" }); });
86
+ afterEach(() => { vi.unstubAllGlobals(); });
87
+
88
+ it("stdout 含 pid 判活", () => {
89
+ const ex = makeExecutor("bash.exe 1234 Console 1 2,048 K");
90
+ expect(isPidAlive(1234, ex)).toBe(true);
91
+ });
92
+ it("stdout 不含 pid(INFO: No tasks)判死", () => {
93
+ const ex = makeExecutor("INFO: No tasks are running which match the specified criteria.");
94
+ expect(isPidAlive(1234, ex)).toBe(false);
95
+ });
96
+ // W4 修复防护:列解析防内存列数字子串误判(旧 includes 会匹配 "22,222" 里的 "222")
97
+ it("pid 仅出现在内存列(非第二列)不误判存活", () => {
98
+ const ex = makeExecutor("bar.exe 990 Console 1 22,222 K");
99
+ expect(isPidAlive(222, ex)).toBe(false);
100
+ });
101
+ it("探测命令失败(null)fail-safe 判活", () => {
102
+ const ex = makeExecutor(null);
103
+ expect(isPidAlive(1234, ex)).toBe(true);
104
+ });
105
+ it("pid<=0 判死", () => {
106
+ expect(isPidAlive(0, makeExecutor("anything 0"))).toBe(false);
107
+ });
108
+ });
109
+
110
+ describe("isPidAlive(Unix 分支)", () => {
111
+ beforeEach(() => { vi.stubGlobal("process", { ...process, platform: "linux" }); });
112
+ afterEach(() => { vi.unstubAllGlobals(); });
113
+
114
+ it("非 EPERM 异常判死(进程不存在)", () => {
115
+ const killSpy = vi.spyOn(process, "kill").mockImplementation(() => {
116
+ const err = new Error("no such process") as NodeJS.ErrnoException;
117
+ err.code = "ESRCH";
118
+ throw err;
119
+ });
120
+ try {
121
+ expect(isPidAlive(4242, makeExecutor(null))).toBe(false);
122
+ } finally { killSpy.mockRestore(); }
123
+ });
124
+ it("EPERM 判活(进程存在但无权限探测)", () => {
125
+ const killSpy = vi.spyOn(process, "kill").mockImplementation(() => {
126
+ const err = new Error("not permitted") as NodeJS.ErrnoException;
127
+ err.code = "EPERM";
128
+ throw err;
129
+ });
130
+ try {
131
+ expect(isPidAlive(4242, makeExecutor(null))).toBe(true);
132
+ } finally { killSpy.mockRestore(); }
133
+ });
134
+ it("无异常判活", () => {
135
+ const killSpy = vi.spyOn(process, "kill").mockImplementation(() => true);
136
+ try {
137
+ expect(isPidAlive(4242, makeExecutor(null))).toBe(true);
138
+ } finally { killSpy.mockRestore(); }
139
+ });
140
+ it("pid<=0 判死", () => {
141
+ expect(isPidAlive(-1, makeExecutor(null))).toBe(false);
142
+ });
143
+ });
144
+
145
+ describe("killTree", () => {
146
+ it("win32 用 taskkill /T /F /PID 树杀", () => {
147
+ vi.stubGlobal("process", { ...process, platform: "win32" });
148
+ try {
149
+ const ex = makeExecutor("");
150
+ killTree(777, ex);
151
+ expect(ex.run).toHaveBeenCalledWith("taskkill", ["/T", "/F", "/PID", "777"]);
152
+ } finally { vi.unstubAllGlobals(); }
153
+ });
154
+ it("Unix 用 kill -9 直接目标", () => {
155
+ vi.stubGlobal("process", { ...process, platform: "linux" });
156
+ try {
157
+ const ex = makeExecutor("");
158
+ killTree(777, ex);
159
+ expect(ex.run).toHaveBeenCalledWith("kill", ["-9", "777"]);
160
+ } finally { vi.unstubAllGlobals(); }
161
+ });
162
+ it("pid<=0 不执行", () => {
163
+ const ex = makeExecutor("");
164
+ killTree(0, ex);
165
+ expect(ex.run).not.toHaveBeenCalled();
166
+ });
167
+ });
168
+
169
+ describe("waitForPidExit", () => {
170
+ it("已死透立即返回 true(一次探测即出)", async () => {
171
+ vi.stubGlobal("process", { ...process, platform: "win32" });
172
+ try {
173
+ const ex = makeExecutor("INFO: No tasks are running");
174
+ const dead = await waitForPidExit(1234, { executor: ex, sleep: async () => {} });
175
+ expect(dead).toBe(true);
176
+ expect(ex.run).toHaveBeenCalledTimes(1);
177
+ } finally { vi.unstubAllGlobals(); }
178
+ });
179
+ it("持续存活超时返回 false", async () => {
180
+ vi.stubGlobal("process", { ...process, platform: "win32" });
181
+ try {
182
+ const ex = makeExecutor("bash.exe 1234 Console");
183
+ const dead = await waitForPidExit(1234, {
184
+ timeoutMs: 10,
185
+ intervalMs: 5,
186
+ sleep: async () => {},
187
+ executor: ex,
188
+ });
189
+ expect(dead).toBe(false);
190
+ } finally { vi.unstubAllGlobals(); }
191
+ });
192
+ });
@@ -66,8 +66,13 @@ describe("spawnOnce — extraEnv 透传", () => {
66
66
  await resultPromise;
67
67
 
68
68
  const spawnOpts = spawnCalls[0][2];
69
+ // 语义修正(2026-11-24):spawn env = process.env ∪ extraEnv,同名键以 extraEnv 为准。
70
+ // 旧断言 objectContaining(process.env) 在键重叠时自相矛盾(子代理环境跑测试必红)。
71
+ const nonOverlapEnv = Object.fromEntries(
72
+ Object.entries(process.env).filter(([k]) => !(k in extraEnv)),
73
+ );
69
74
  expect(spawnOpts.env).toEqual(expect.objectContaining(extraEnv));
70
- expect(spawnOpts.env).toEqual(expect.objectContaining(process.env));
75
+ expect(spawnOpts.env).toEqual(expect.objectContaining(nonOverlapEnv));
71
76
  });
72
77
 
73
78
  it("extraEnv 的值覆盖 process.env 中同名 key", async () => {