pi-ate-workflow 0.2.2 → 0.2.4

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-ate-workflow",
3
- "version": "0.2.2",
3
+ "version": "0.2.4",
4
4
  "type": "commonjs",
5
5
  "main": "index.ts",
6
6
  "description": "Workflow orchestration extension for pi-coding-agent — subagent spawning, research workflow, output capture",
package/proc-guard.ts ADDED
@@ -0,0 +1,168 @@
1
+ /**
2
+ * proc-guard: 可见子代理进程身份探测与树杀
3
+ *
4
+ * 清理安全性基建:launch.sh 启动最前自报 proc.pid("shellPid winpid"),
5
+ * 清理侧据此判定 pane 内进程树死透——目录删除动作永不早于死透确认。
6
+ *
7
+ * 平台适用 pid 语义:Windows 用 winpid(MSYS2 bash 的 $$ 是 MSYS pid,
8
+ * taskkill 无法消费),Unix 用 shell pid($$ 本身即平台原生 pid,
9
+ * winpid=0 只是"无 Windows 原生 pid"标记,不构成 Unix 的降级信号)。
10
+ */
11
+ import * as fs from "node:fs";
12
+ import * as path from "node:path";
13
+ import * as os from "node:os";
14
+ import { execFileSync } from "node:child_process";
15
+
16
+ /** 执行器抽象(依赖注入,测试可 mock;探测失败返回 null) */
17
+ export interface ProcGuardExecutor {
18
+ run(cmd: string, args: string[]): string | null;
19
+ }
20
+
21
+ const defaultExecutor: ProcGuardExecutor = {
22
+ run(cmd, args) {
23
+ try {
24
+ return execFileSync(cmd, args, {
25
+ encoding: "utf-8",
26
+ stdio: ["ignore", "pipe", "ignore"],
27
+ });
28
+ } catch {
29
+ return null;
30
+ }
31
+ },
32
+ };
33
+
34
+ /** proc.pid 自报信息(launch.sh 首行写入) */
35
+ export interface ProcPidInfo {
36
+ shellPid: number;
37
+ winpid: number;
38
+ }
39
+
40
+ /** 读取任务目录的 proc.pid;缺失/格式异常返回 null(走降级链) */
41
+ export function readProcPid(taskDir: string): ProcPidInfo | null {
42
+ try {
43
+ const raw = fs.readFileSync(path.join(taskDir, "proc.pid"), "utf-8").trim();
44
+ const m = raw.match(/^(\d+)\s+(\d+)$/);
45
+ if (!m) return null;
46
+ const shellPid = Number(m[1]);
47
+ const winpid = Number(m[2]);
48
+ if (shellPid <= 0) return null;
49
+ return { shellPid, winpid };
50
+ } catch {
51
+ return null;
52
+ }
53
+ }
54
+
55
+ /** 平台适用 pid:Windows 判 winpid,Unix 判 shell pid;无可用 pid 返回 null */
56
+ export function resolvePlatformPid(info: ProcPidInfo | null): number | null {
57
+ if (!info) return null;
58
+ if (process.platform === "win32") {
59
+ return info.winpid > 0 ? info.winpid : null;
60
+ }
61
+ return info.shellPid > 0 ? info.shellPid : null;
62
+ }
63
+
64
+ /**
65
+ * 判定 pid 是否存活。
66
+ * 探测命令失败(返回 null)时按存活处理——fail-safe,宁可多等/树杀,不误判死。
67
+ */
68
+ export function isPidAlive(pid: number, executor: ProcGuardExecutor = defaultExecutor): boolean {
69
+ if (pid <= 0) return false;
70
+ if (process.platform === "win32") {
71
+ const out = executor.run("tasklist", ["/FI", `PID eq ${pid}`, "/NH"]);
72
+ if (out === null) return true;
73
+ // tasklist 过滤无匹配时输出 "INFO: No tasks are running..." 且退出码 0,
74
+ // 必须按 stdout 是否包含 pid 判定,不能依赖退出码
75
+ return out.includes(String(pid));
76
+ }
77
+ try {
78
+ process.kill(pid, 0);
79
+ return true;
80
+ } catch (e: unknown) {
81
+ return (e as NodeJS.ErrnoException).code === "EPERM";
82
+ }
83
+ }
84
+
85
+ /** 整树强杀(Windows taskkill /T /F 带走全部子孙;Unix kill -9 直接目标) */
86
+ export function killTree(pid: number, executor: ProcGuardExecutor = defaultExecutor): void {
87
+ if (pid <= 0) return;
88
+ if (process.platform === "win32") {
89
+ executor.run("taskkill", ["/T", "/F", "/PID", String(pid)]);
90
+ } else {
91
+ executor.run("kill", ["-9", String(pid)]);
92
+ }
93
+ }
94
+
95
+ export interface WaitForPidExitOptions {
96
+ timeoutMs?: number;
97
+ intervalMs?: number;
98
+ sleep?: (ms: number) => Promise<void>;
99
+ executor?: ProcGuardExecutor;
100
+ }
101
+
102
+ /**
103
+ * 等待 pid 死透:intervalMs 间隔轮询,timeoutMs 上限。
104
+ * 返回是否确认死透;超时未死透返回 false(由调用方决定树杀兜底)。
105
+ */
106
+ export async function waitForPidExit(
107
+ pid: number,
108
+ options: WaitForPidExitOptions = {},
109
+ ): Promise<boolean> {
110
+ const {
111
+ timeoutMs = 10_000,
112
+ intervalMs = 500,
113
+ sleep = (ms: number) => new Promise<void>((resolve) => setTimeout(resolve, ms)),
114
+ executor = defaultExecutor,
115
+ } = options;
116
+ const deadline = Date.now() + timeoutMs;
117
+ while (Date.now() < deadline) {
118
+ if (!isPidAlive(pid, executor)) return true;
119
+ await sleep(intervalMs);
120
+ }
121
+ return !isPidAlive(pid, executor);
122
+ }
123
+
124
+ /** 超龄清扫默认阈值:24 小时 */
125
+ export const STALE_VISIBLE_TASK_DIR_MS = 24 * 60 * 60 * 1000;
126
+
127
+ /**
128
+ * 扫描 Temp 下超龄的 pi-visible-* 残留目录并删除。
129
+ * 兜底主进程意外退出导致延迟清理回调丢失的残留(定时器随进程消亡)。
130
+ *
131
+ * 超龄锚点:目录内全部条目(含文件)的最大 mtime,不取目录自身 mtime——
132
+ * Windows 文件系统下写文件内容不刷新父目录 mtime,取目录自身会把运行中的
133
+ * 长任务目录(stalled 轮询 5 分钟必然刷新 session.jsonl 的 mtime)误判为超龄。
134
+ * 逐目录容错:单个目录删除失败不中断扫描。
135
+ */
136
+ export function sweepStaleVisibleTaskDirs(
137
+ tmpRoot: string = os.tmpdir(),
138
+ maxAgeMs: number = STALE_VISIBLE_TASK_DIR_MS,
139
+ ): void {
140
+ try {
141
+ const entries = fs.readdirSync(tmpRoot);
142
+ for (const name of entries) {
143
+ if (!name.startsWith("pi-visible-")) continue;
144
+ const dir = path.join(tmpRoot, name);
145
+ try {
146
+ if (!isStaleVisibleTaskDir(dir, maxAgeMs)) continue;
147
+ fs.rmSync(dir, { recursive: true, force: true });
148
+ } catch { /* 单目录失败容错 */ }
149
+ }
150
+ } catch { /* 扫描根不可读则跳过 */ }
151
+ }
152
+
153
+ /** 目录内全部条目的最大 mtime 是否超过 maxAgeMs */
154
+ function isStaleVisibleTaskDir(dir: string, maxAgeMs: number): boolean {
155
+ try {
156
+ const stat = fs.statSync(dir);
157
+ if (!stat.isDirectory()) return false;
158
+ let newest = stat.mtimeMs;
159
+ for (const entry of fs.readdirSync(dir)) {
160
+ try {
161
+ newest = Math.max(newest, fs.statSync(path.join(dir, entry)).mtimeMs);
162
+ } catch { /* 条目消失则跳过 */ }
163
+ }
164
+ return Date.now() - newest > maxAgeMs;
165
+ } catch {
166
+ return false;
167
+ }
168
+ }
package/subagent-model.ts CHANGED
@@ -54,11 +54,9 @@ function persistModelToSettings(model: string): void {
54
54
  SUBAGENT_MODEL_DEFAULTS,
55
55
  );
56
56
  } catch (e) {
57
- // 写入失败不阻塞主流程,但必须留痕(静默吞错曾致持久化失败不可观测,fix-subagent-model-select-persist D3)
58
- console.error(
59
- "[subagent-model] persist 失败:",
60
- e instanceof Error ? e.message : e,
61
- );
57
+ // 写入失败不阻塞主流程,但必须留痕(静默吞错曾致持久化失败不可观测,fix-subagent-model-select-persist D3)。
58
+ // 直接传 e 保留 stack 与 Error.cause 链(harden-subagent-model-observability D1)
59
+ console.error("[subagent-model] persist 失败:", e);
62
60
  }
63
61
  }
64
62
 
@@ -18,6 +18,7 @@ import { SubagentSession } from "./subagent-session";
18
18
  import { createVisibleTaskDir, injectParentSession } from "./subagent-utils";
19
19
  import { detectTerminal, getBackend } from "./term-backend";
20
20
  import type { TermBackend } from "./term-backend";
21
+ import { createSafeCleanup } from "./visible-cleanup";
21
22
 
22
23
  export function spawnVisible(
23
24
  task: string,
@@ -72,10 +73,8 @@ export function spawnVisible(
72
73
  let lastLine = 0;
73
74
  let lastActivityTime = Date.now();
74
75
 
75
- const cleanup = () => {
76
- backend.killPane(paneId);
77
- try { fs.rmSync(taskDir, { recursive: true }); } catch { /* ignore */ }
78
- };
76
+ // 有序安全清理:目录删除永不早于 pane 内进程树死透确认(实现见 visible-cleanup.ts)
77
+ const safeCleanup = createSafeCleanup({ taskDir, paneId, backend });
79
78
 
80
79
  // ─── 轮询 session.jsonl ─────────────────
81
80
 
@@ -108,7 +107,7 @@ export function spawnVisible(
108
107
  });
109
108
  clearInterval(pollInterval);
110
109
  clearTimeout(wallTimer);
111
- cleanup();
110
+ void safeCleanup(true);
112
111
  }
113
112
  }, 2000);
114
113
 
@@ -123,7 +122,7 @@ export function spawnVisible(
123
122
  timedOut: true,
124
123
  });
125
124
  clearInterval(pollInterval);
126
- cleanup();
125
+ void safeCleanup(true);
127
126
  }, TIMEOUT_MS);
128
127
 
129
128
  // ─── 正常结束:收集剩余输出 ────────────
@@ -150,10 +149,9 @@ export function spawnVisible(
150
149
  clearInterval(pollInterval);
151
150
  clearTimeout(wallTimer);
152
151
 
153
- // 延迟清理临时目录(让用户看到最终输出;pane 由自动退出机制自行结束)
154
- setTimeout(() => {
155
- try { fs.rmSync(taskDir, { recursive: true }); } catch { /* ignore */ }
156
- }, 5000);
152
+ // 有序清理临时目录(等 pane 内进程死透后删除;pane 由自动退出机制自行结束,
153
+ // 死透等待期间用户仍可看到最终输出)
154
+ void safeCleanup(false);
157
155
  }
158
156
 
159
157
  // ─── AbortSignal ──────────────────────
@@ -168,7 +166,7 @@ export function spawnVisible(
168
166
  });
169
167
  clearInterval(pollInterval);
170
168
  clearTimeout(wallTimer);
171
- cleanup();
169
+ void safeCleanup(true);
172
170
  }
173
171
  };
174
172
  if (signal.aborted) onAbort();
package/subagent-utils.ts CHANGED
@@ -5,6 +5,7 @@
5
5
  import * as fs from "node:fs";
6
6
  import * as path from "node:path";
7
7
  import * as os from "node:os";
8
+ import { sweepStaleVisibleTaskDirs } from "./proc-guard";
8
9
 
9
10
  /**
10
11
  * 将 Windows 反斜杠路径转为 Unix 正斜杠路径。
@@ -124,6 +125,8 @@ export function createVisibleTaskDir(
124
125
  extraEnv?: Record<string, string>,
125
126
  ): VisibleTaskDir {
126
127
  const taskDir = fs.mkdtempSync(path.join(os.tmpdir(), "pi-visible-"));
128
+ // 顺带清扫超龄残留(主进程意外退出导致清理回调丢失的目录)
129
+ sweepStaleVisibleTaskDirs();
127
130
  const taskFile = path.join(taskDir, "task.txt");
128
131
  fs.writeFileSync(taskFile, task, { encoding: "utf-8" });
129
132
 
@@ -147,9 +150,14 @@ export function createVisibleTaskDir(
147
150
  const uSessionFile = toUnixPath(sessionFile);
148
151
  const uSystemPromptPath = toUnixPath(systemPromptPath);
149
152
  const uTaskFile = toUnixPath(taskFile);
153
+ const uProcPidFile = toUnixPath(path.join(taskDir, "proc.pid"));
150
154
 
151
155
  const script = [
152
156
  "#!/bin/bash",
157
+ // 进程身份自报:清理侧据此判定 pane 内进程死透(safe-cleanup-visible-subagent)
158
+ // $$ 为 shell pid;MSYS2/Git Bash 下经 /proc/$$/winpid 取 Windows 原生 pid,
159
+ // 非 MSYS2 环境回退 0(Unix 平台清理侧用 shell pid,winpid=0 不构成降级信号)
160
+ `echo "$$ $(cat /proc/$$/winpid 2>/dev/null || echo 0)" > '${uProcPidFile}' || true`,
153
161
  'export FNM_PATH="$HOME/.local/share/fnm"',
154
162
  'if [ -d "$FNM_PATH" ]; then export PATH="$FNM_PATH:$PATH" && eval "$(fnm env --shell bash)"; fi',
155
163
  `cd "${uCwd}"`,
@@ -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,187 @@
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
+ it("探测命令失败(null)fail-safe 判活", () => {
97
+ const ex = makeExecutor(null);
98
+ expect(isPidAlive(1234, ex)).toBe(true);
99
+ });
100
+ it("pid<=0 判死", () => {
101
+ expect(isPidAlive(0, makeExecutor("anything 0"))).toBe(false);
102
+ });
103
+ });
104
+
105
+ describe("isPidAlive(Unix 分支)", () => {
106
+ beforeEach(() => { vi.stubGlobal("process", { ...process, platform: "linux" }); });
107
+ afterEach(() => { vi.unstubAllGlobals(); });
108
+
109
+ it("非 EPERM 异常判死(进程不存在)", () => {
110
+ const killSpy = vi.spyOn(process, "kill").mockImplementation(() => {
111
+ const err = new Error("no such process") as NodeJS.ErrnoException;
112
+ err.code = "ESRCH";
113
+ throw err;
114
+ });
115
+ try {
116
+ expect(isPidAlive(4242, makeExecutor(null))).toBe(false);
117
+ } finally { killSpy.mockRestore(); }
118
+ });
119
+ it("EPERM 判活(进程存在但无权限探测)", () => {
120
+ const killSpy = vi.spyOn(process, "kill").mockImplementation(() => {
121
+ const err = new Error("not permitted") as NodeJS.ErrnoException;
122
+ err.code = "EPERM";
123
+ throw err;
124
+ });
125
+ try {
126
+ expect(isPidAlive(4242, makeExecutor(null))).toBe(true);
127
+ } finally { killSpy.mockRestore(); }
128
+ });
129
+ it("无异常判活", () => {
130
+ const killSpy = vi.spyOn(process, "kill").mockImplementation(() => true);
131
+ try {
132
+ expect(isPidAlive(4242, makeExecutor(null))).toBe(true);
133
+ } finally { killSpy.mockRestore(); }
134
+ });
135
+ it("pid<=0 判死", () => {
136
+ expect(isPidAlive(-1, makeExecutor(null))).toBe(false);
137
+ });
138
+ });
139
+
140
+ describe("killTree", () => {
141
+ it("win32 用 taskkill /T /F /PID 树杀", () => {
142
+ vi.stubGlobal("process", { ...process, platform: "win32" });
143
+ try {
144
+ const ex = makeExecutor("");
145
+ killTree(777, ex);
146
+ expect(ex.run).toHaveBeenCalledWith("taskkill", ["/T", "/F", "/PID", "777"]);
147
+ } finally { vi.unstubAllGlobals(); }
148
+ });
149
+ it("Unix 用 kill -9 直接目标", () => {
150
+ vi.stubGlobal("process", { ...process, platform: "linux" });
151
+ try {
152
+ const ex = makeExecutor("");
153
+ killTree(777, ex);
154
+ expect(ex.run).toHaveBeenCalledWith("kill", ["-9", "777"]);
155
+ } finally { vi.unstubAllGlobals(); }
156
+ });
157
+ it("pid<=0 不执行", () => {
158
+ const ex = makeExecutor("");
159
+ killTree(0, ex);
160
+ expect(ex.run).not.toHaveBeenCalled();
161
+ });
162
+ });
163
+
164
+ describe("waitForPidExit", () => {
165
+ it("已死透立即返回 true(一次探测即出)", async () => {
166
+ vi.stubGlobal("process", { ...process, platform: "win32" });
167
+ try {
168
+ const ex = makeExecutor("INFO: No tasks are running");
169
+ const dead = await waitForPidExit(1234, { executor: ex, sleep: async () => {} });
170
+ expect(dead).toBe(true);
171
+ expect(ex.run).toHaveBeenCalledTimes(1);
172
+ } finally { vi.unstubAllGlobals(); }
173
+ });
174
+ it("持续存活超时返回 false", async () => {
175
+ vi.stubGlobal("process", { ...process, platform: "win32" });
176
+ try {
177
+ const ex = makeExecutor("bash.exe 1234 Console");
178
+ const dead = await waitForPidExit(1234, {
179
+ timeoutMs: 10,
180
+ intervalMs: 5,
181
+ sleep: async () => {},
182
+ executor: ex,
183
+ });
184
+ expect(dead).toBe(false);
185
+ } finally { vi.unstubAllGlobals(); }
186
+ });
187
+ });
@@ -4,7 +4,7 @@
4
4
  * 读:getEffectiveConfig 三层合并;写:patchSettingsSectionWithBackup
5
5
  * 禁止裸 readFileSync/writeFileSync 整文件读写。
6
6
  */
7
- import { describe, it, expect, vi, beforeEach } from "vitest";
7
+ import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
8
8
 
9
9
  const { patchMock } = vi.hoisted(() => ({
10
10
  patchMock: vi.fn(),
@@ -154,3 +154,48 @@ describe("barrel 导出防回归", () => {
154
154
  expect(typeof wfBarrel.restoreSubagentModel).toBe("function");
155
155
  });
156
156
  });
157
+
158
+ describe("persist 失败留痕护栏(harden-subagent-model-observability D2/D4)", () => {
159
+ beforeEach(() => {
160
+ // resetAllMocks 清除 implementation(含上 describe 残留的 throw),避免埋雷式跨界污染
161
+ vi.resetAllMocks();
162
+ vi.spyOn(console, "error").mockImplementation(() => {});
163
+ setSubagentModelRestored(false);
164
+ });
165
+ afterEach(() => {
166
+ // 统一恢复 spy:断言失败时也不泄漏全局 mock(mockRestore 不在断言成功路径上)
167
+ vi.restoreAllMocks();
168
+ });
169
+
170
+ it("留痕传原始错误对象(stack/cause 不剥离)", () => {
171
+ const boom = new Error("lock contention", { cause: new Error("ENOENT") });
172
+ patchMock.mockImplementation(() => {
173
+ throw boom;
174
+ });
175
+ setSubagentModel("zai-coding-cn/glm-5.4");
176
+ expect(console.error).toHaveBeenCalledTimes(1);
177
+ // 第二参数必须是原 Error 对象(含 stack/cause),不是 e.message 字符串
178
+ expect(console.error).toHaveBeenCalledWith(
179
+ "[subagent-model] persist 失败:",
180
+ boom,
181
+ );
182
+ });
183
+
184
+ it("留痕回退被拦截:静默吞时本用例变红(护栏)", () => {
185
+ patchMock.mockImplementation(() => {
186
+ throw new Error("boom");
187
+ });
188
+ setSubagentModel("zai-coding-cn/glm-5.4");
189
+ // 若 catch 改回静默吞,这里的 toHaveBeenCalledTimes(1) 失败 → 回归可见
190
+ expect(console.error).toHaveBeenCalledTimes(1);
191
+ });
192
+
193
+ it("越界防御:labels 短于 items 时按索引取值(D4)", () => {
194
+ expect(
195
+ resolveSelectedByLabel(["a"], [{ v: 1 }, { v: 2 }], "a"),
196
+ ).toEqual({ v: 1 });
197
+ expect(
198
+ resolveSelectedByLabel(["a", "b", "c"], [{ v: 1 }], "c"),
199
+ ).toBeUndefined();
200
+ });
201
+ });
@@ -20,6 +20,17 @@ vi.mock("../subagent-spawn-once", () => ({
20
20
  spawnOnce: vi.fn(() => Promise.resolve({ exitCode: 0, output: "fallback", stderr: "" })),
21
21
  }));
22
22
 
23
+ const { safeCleanupMock, createSafeCleanupMock } = vi.hoisted(() => ({
24
+ safeCleanupMock: vi.fn(() => Promise.resolve()),
25
+ createSafeCleanupMock: vi.fn((_opts: unknown) => null as any),
26
+ }));
27
+ vi.mock("../visible-cleanup", () => ({
28
+ createSafeCleanup: (opts: any) => {
29
+ createSafeCleanupMock(opts);
30
+ return safeCleanupMock;
31
+ },
32
+ }));
33
+
23
34
  const { backendMock, termDetect } = vi.hoisted(() => {
24
35
  const backend = {
25
36
  splitPane: vi.fn(() => "%42"),
@@ -58,6 +69,7 @@ vi.mock("node:fs", async (importOriginal) => {
58
69
  import { spawnVisible } from "../subagent-spawn-visible";
59
70
  import { spawnOnce } from "../subagent-spawn-once";
60
71
  import { createVisibleTaskDir } from "../subagent-utils";
72
+ import { createSafeCleanup } from "../visible-cleanup";
61
73
 
62
74
  describe("spawnVisible", () => {
63
75
  beforeEach(() => {
@@ -66,6 +78,8 @@ describe("spawnVisible", () => {
66
78
  backendMock.splitPane.mockReturnValue("%42");
67
79
  backendMock.isPaneAlive.mockReturnValue(true);
68
80
  backendMock.killPane.mockClear();
81
+ safeCleanupMock.mockClear();
82
+ createSafeCleanupMock.mockClear();
69
83
  fsMock.existsSync.mockReturnValue(false);
70
84
  fsMock.readFileSync.mockReturnValue("");
71
85
  });
@@ -103,6 +117,8 @@ describe("spawnVisible", () => {
103
117
 
104
118
  const result = await resultPromise;
105
119
  expect(result.output).toContain("hello");
120
+ // 正常结束路径:finish 后走 safeCleanup(kill=false)(等死透后删目录,不主动杀)
121
+ expect(safeCleanupMock).toHaveBeenCalledWith(false);
106
122
  });
107
123
 
108
124
  it("超时时返回 timedOut 并清理 pane", async () => {
@@ -116,7 +132,12 @@ describe("spawnVisible", () => {
116
132
 
117
133
  const result = await resultPromise;
118
134
  expect(result.timedOut).toBe(true);
119
- expect(backendMock.killPane).toHaveBeenCalledWith("%42");
135
+ // 有序清理:超时路径交由 safeCleanup(kill=true)(内部先 killPane 再等死透后删目录)
136
+ expect(safeCleanupMock).toHaveBeenCalledWith(true);
137
+ expect(createSafeCleanupMock).toHaveBeenCalledWith(expect.objectContaining({
138
+ taskDir: "/tmp/pi-visible-test",
139
+ paneId: "%42",
140
+ }));
120
141
  });
121
142
 
122
143
  it("signal abort 时终止并清理", async () => {
@@ -131,7 +152,7 @@ describe("spawnVisible", () => {
131
152
  const result = await resultPromise;
132
153
  expect(result.stderr).toContain("aborted");
133
154
  expect(result.exitCode).toBe(1);
134
- expect(backendMock.killPane).toHaveBeenCalled();
155
+ expect(safeCleanupMock).toHaveBeenCalledWith(true);
135
156
  });
136
157
 
137
158
  it("extraEnv 透传到 createVisibleTaskDir", async () => {
@@ -0,0 +1,101 @@
1
+ /**
2
+ * 测试 sweepStaleVisibleTaskDirs — 超龄残留兜底清扫
3
+ *
4
+ * 隔离 tmpRoot(mkdtemp 独立目录),不触碰真实 Temp 的 pi-visible-* 残留。
5
+ */
6
+ import { describe, it, expect, vi } 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 { sweepStaleVisibleTaskDirs, STALE_VISIBLE_TASK_DIR_MS } from "../proc-guard";
11
+
12
+ // ESM namespace 不可 spyOn:改用 vi.mock 部分替换 rmSync(其余保留真实)
13
+ const holder = vi.hoisted(() => ({ origRm: null as any }));
14
+ vi.mock("node:fs", async (importOriginal) => {
15
+ const actual = await importOriginal() as any;
16
+ holder.origRm = actual.rmSync;
17
+ return { ...actual, rmSync: vi.fn((t: any, o: any) => holder.origRm(t, o)) };
18
+ });
19
+ const rmMock = vi.mocked(fs.rmSync);
20
+
21
+ const mkRoot = () => fs.mkdtempSync(path.join(os.tmpdir(), "pg-sweep-"));
22
+
23
+ /** 把目标及其内部全部条目的 atime/mtime 回拨指定毫秒(锄点=条目最大 mtime,目录需回拨内部条目;文件只回拨自身) */
24
+ const backdateTree = (target: string, ms: number) => {
25
+ const past = new Date(Date.now() - ms);
26
+ fs.utimesSync(target, past, past);
27
+ if (!fs.lstatSync(target).isDirectory()) return;
28
+ for (const entry of fs.readdirSync(target)) {
29
+ fs.utimesSync(path.join(target, entry), past, past);
30
+ }
31
+ };
32
+
33
+ describe("sweepStaleVisibleTaskDirs", () => {
34
+ it("超龄目录被删除,新鲜目录保留", () => {
35
+ const root = mkRoot();
36
+ try {
37
+ const stale = path.join(root, "pi-visible-old");
38
+ const fresh = path.join(root, "pi-visible-fresh");
39
+ fs.mkdirSync(stale); fs.mkdirSync(fresh);
40
+ fs.writeFileSync(path.join(stale, "task.txt"), "x");
41
+ fs.writeFileSync(path.join(fresh, "task.txt"), "y");
42
+ backdateTree(stale, STALE_VISIBLE_TASK_DIR_MS + 3600_000);
43
+
44
+ sweepStaleVisibleTaskDirs(root);
45
+ expect(fs.existsSync(stale)).toBe(false);
46
+ expect(fs.existsSync(fresh)).toBe(true);
47
+ } finally { fs.rmSync(root, { recursive: true, force: true }); }
48
+ });
49
+
50
+ it("锚点取目录内条目最大 mtime:文件新鲜则目录不删(目录 mtime 已超龄)", () => {
51
+ const root = mkRoot();
52
+ try {
53
+ const dir = path.join(root, "pi-visible-longrun");
54
+ fs.mkdirSync(dir);
55
+ fs.writeFileSync(path.join(dir, "task.txt"), "x");
56
+ backdateTree(dir, STALE_VISIBLE_TASK_DIR_MS + 3600_000); // 目录自身超龄
57
+ // 但 session.jsonl 五分钟前刚刷新(长任务运行中)
58
+ fs.writeFileSync(path.join(dir, "session.jsonl"), "line\n");
59
+ backdateTree(path.join(dir, "session.jsonl"), 5 * 60_000);
60
+
61
+ sweepStaleVisibleTaskDirs(root);
62
+ expect(fs.existsSync(dir)).toBe(true); // 锚点=最新文件 mtime,未超龄
63
+ } finally { fs.rmSync(root, { recursive: true, force: true }); }
64
+ });
65
+
66
+ it("非 pi-visible-* 前缀目录不触碰", () => {
67
+ const root = mkRoot();
68
+ try {
69
+ const other = path.join(root, "pi-pv-other");
70
+ fs.mkdirSync(other);
71
+ backdateTree(other, STALE_VISIBLE_TASK_DIR_MS * 2);
72
+ sweepStaleVisibleTaskDirs(root);
73
+ expect(fs.existsSync(other)).toBe(true);
74
+ } finally { fs.rmSync(root, { recursive: true, force: true }); }
75
+ });
76
+
77
+ it("单个目录删除失败不中断扫描(容错)", () => {
78
+ const root = mkRoot();
79
+ try {
80
+ const poisoned = path.join(root, "pi-visible-poison");
81
+ const stale = path.join(root, "pi-visible-ok");
82
+ fs.mkdirSync(poisoned); fs.mkdirSync(stale);
83
+ backdateTree(poisoned, STALE_VISIBLE_TASK_DIR_MS * 2);
84
+ backdateTree(stale, STALE_VISIBLE_TASK_DIR_MS * 2);
85
+ rmMock.mockImplementation(((target: any, opts: any) => {
86
+ if (String(target) === poisoned) throw new Error("EPERM");
87
+ return holder.origRm(target, opts);
88
+ }) as any);
89
+ try {
90
+ sweepStaleVisibleTaskDirs(root);
91
+ expect(fs.existsSync(stale)).toBe(false); // 后续目录继续处理
92
+ } finally {
93
+ rmMock.mockImplementation(((t: any, o: any) => holder.origRm(t, o)) as any);
94
+ }
95
+ } finally { fs.rmSync(root, { recursive: true, force: true }); }
96
+ });
97
+
98
+ it("扫描根不可读不抛错(顶层容错)", () => {
99
+ expect(() => sweepStaleVisibleTaskDirs(path.join(os.tmpdir(), "definitely-missing-root"))).not.toThrow();
100
+ });
101
+ });
@@ -0,0 +1,152 @@
1
+ /**
2
+ * 测试 visible-cleanup.ts — 有序安全清理的调用顺序契约
3
+ *
4
+ * 核心断言:目录删除(rmSync)永不早于 pane 内进程死透确认 / 树杀兜底;
5
+ * 降级分支 kill 场景保留 killPane。proc-guard 全 mock,不触碰真实进程与文件。
6
+ */
7
+ import { describe, it, expect, vi, beforeEach } from "vitest";
8
+
9
+ vi.mock("node:fs", () => ({
10
+ rmSync: vi.fn(),
11
+ existsSync: vi.fn(() => false),
12
+ readFileSync: vi.fn(() => { throw new Error("no fs in cleanup test"); }),
13
+ }));
14
+
15
+ vi.mock("../proc-guard", () => ({
16
+ readProcPid: vi.fn(() => ({ shellPid: 111, winpid: 222 })),
17
+ resolvePlatformPid: vi.fn(() => 222),
18
+ waitForPidExit: vi.fn(() => Promise.resolve(true)),
19
+ killTree: vi.fn(),
20
+ }));
21
+
22
+ import * as fs from "node:fs";
23
+ import { waitForPidExit, killTree, resolvePlatformPid } from "../proc-guard";
24
+ import { createSafeCleanup } from "../visible-cleanup";
25
+ import type { TermBackend } from "../term-backend";
26
+
27
+ const fsMock = vi.mocked(fs);
28
+ const mockedWait = vi.mocked(waitForPidExit);
29
+ const mockedKillTree = vi.mocked(killTree);
30
+ const mockedResolve = vi.mocked(resolvePlatformPid);
31
+
32
+ const makeBackend = (calls: string[]) => ({
33
+ splitPane: vi.fn(() => "%1"),
34
+ killPane: vi.fn((id: string) => { calls.push(`killPane:${id}`); }),
35
+ isPaneAlive: vi.fn(() => true),
36
+ }) as unknown as TermBackend;
37
+
38
+ const makeCalls = () => [] as string[];
39
+
40
+ describe("createSafeCleanup — 顺序契约", () => {
41
+ beforeEach(() => {
42
+ vi.clearAllMocks();
43
+ // clearAllMocks 不清 mockReturnValue,逐项恢复默认(防降级用例的 null 污染后续)
44
+ mockedWait.mockReturnValue(Promise.resolve(true));
45
+ mockedResolve.mockReturnValue(222);
46
+ });
47
+
48
+ it("kill=true 且死透:killPane → 死透确认 → 删除,不树杀", async () => {
49
+ const calls = makeCalls();
50
+ const backend = makeBackend(calls);
51
+ mockedWait.mockImplementation(async () => {
52
+ calls.push("confirmed-dead");
53
+ return true;
54
+ });
55
+ fsMock.rmSync.mockImplementation(() => calls.push("rmSync"));
56
+
57
+ const safeCleanup = createSafeCleanup({ taskDir: "/tmp/pi-visible-x", paneId: "%42", backend });
58
+ await safeCleanup(true);
59
+
60
+ expect(calls).toEqual(["killPane:%42", "confirmed-dead", "rmSync"]);
61
+ expect(mockedKillTree).not.toHaveBeenCalled();
62
+ });
63
+
64
+ it("kill=true 且 10s 未死透:killPane → 等待超时 → 树杀兜底 → 删除", async () => {
65
+ const calls = makeCalls();
66
+ const backend = makeBackend(calls);
67
+ mockedWait.mockResolvedValue(false);
68
+ mockedKillTree.mockImplementation(() => calls.push("killTree"));
69
+ fsMock.rmSync.mockImplementation(() => calls.push("rmSync"));
70
+
71
+ const safeCleanup = createSafeCleanup({ taskDir: "/tmp/pi-visible-x", paneId: "%42", backend });
72
+ await safeCleanup(true);
73
+
74
+ expect(calls).toEqual(["killPane:%42", "killTree", "rmSync"]);
75
+ });
76
+
77
+ it("kill=false(正常结束)死透:不主动杀 pane,只等死透后删除", async () => {
78
+ const calls = makeCalls();
79
+ const backend = makeBackend(calls);
80
+ fsMock.rmSync.mockImplementation(() => calls.push("rmSync"));
81
+
82
+ const safeCleanup = createSafeCleanup({ taskDir: "/tmp/pi-visible-x", paneId: "%42", backend });
83
+ await safeCleanup(false);
84
+
85
+ expect(calls).toEqual(["rmSync"]);
86
+ expect((backend as any).killPane).not.toHaveBeenCalled();
87
+ expect(mockedWait).toHaveBeenCalledWith(222);
88
+ });
89
+
90
+ it("kill=false 且等待超时未死透:同样树杀兜底后删除(防误判路径写已删文件)", async () => {
91
+ const calls = makeCalls();
92
+ const backend = makeBackend(calls);
93
+ mockedWait.mockResolvedValue(false);
94
+ mockedKillTree.mockImplementation(() => calls.push("killTree"));
95
+ fsMock.rmSync.mockImplementation(() => calls.push("rmSync"));
96
+
97
+ const safeCleanup = createSafeCleanup({ taskDir: "/tmp/pi-visible-x", paneId: "%42", backend });
98
+ await safeCleanup(false);
99
+
100
+ expect(calls).toEqual(["killTree", "rmSync"]);
101
+ });
102
+
103
+ it("身份缺失降级(kill=true):仍先 killPane,再延迟删除,不等待死透", async () => {
104
+ const calls = makeCalls();
105
+ const backend = makeBackend(calls);
106
+ mockedResolve.mockReturnValue(null);
107
+ fsMock.rmSync.mockImplementation(() => calls.push("rmSync"));
108
+
109
+ const safeCleanup = createSafeCleanup({ taskDir: "/tmp/pi-visible-x", paneId: "%42", backend });
110
+ vi.useFakeTimers();
111
+ const pending = safeCleanup(true);
112
+ // killPane 立即执行(同步分支),删除在 10s 延迟后
113
+ expect(calls).toEqual(["killPane:%42"]);
114
+ await vi.advanceTimersByTimeAsync(10_000);
115
+ await pending;
116
+ expect(calls).toEqual(["killPane:%42", "rmSync"]);
117
+ expect(mockedWait).not.toHaveBeenCalled();
118
+ vi.useRealTimers();
119
+ });
120
+
121
+ it("身份缺失降级(kill=false):不杀 pane,延迟删除(不劣于现状且更保守)", async () => {
122
+ const calls = makeCalls();
123
+ const backend = makeBackend(calls);
124
+ mockedResolve.mockReturnValue(null);
125
+ fsMock.rmSync.mockImplementation(() => calls.push("rmSync"));
126
+
127
+ const safeCleanup = createSafeCleanup({ taskDir: "/tmp/pi-visible-x", paneId: "%42", backend });
128
+ vi.useFakeTimers();
129
+ const pending = safeCleanup(false);
130
+ expect(calls).toEqual([]);
131
+ await vi.advanceTimersByTimeAsync(10_000);
132
+ await pending;
133
+ expect(calls).toEqual(["rmSync"]);
134
+ vi.useRealTimers();
135
+ });
136
+
137
+ it("后端无关性:清理仅消费 TermBackend 的 killPane 接口,不触 splitPane/isPaneAlive", async () => {
138
+ const calls = makeCalls();
139
+ const backend = makeBackend(calls);
140
+ const safeCleanup = createSafeCleanup({ taskDir: "/tmp/pi-visible-x", paneId: "%42", backend });
141
+ await safeCleanup(true);
142
+ expect((backend as any).splitPane).not.toHaveBeenCalled();
143
+ expect((backend as any).isPaneAlive).not.toHaveBeenCalled();
144
+ });
145
+
146
+ it("rmSync 抛错不影响后续清理调用(容错不抛出)", async () => {
147
+ const backend = makeBackend([]);
148
+ fsMock.rmSync.mockImplementation(() => { throw new Error("EPERM"); });
149
+ const safeCleanup = createSafeCleanup({ taskDir: "/tmp/pi-visible-x", paneId: "%42", backend });
150
+ await expect(safeCleanup(true)).resolves.toBeUndefined();
151
+ });
152
+ });
@@ -0,0 +1,58 @@
1
+ /**
2
+ * visible-cleanup: 可见子代理任务目录的有序安全清理
3
+ *
4
+ * 目录删除永不早于 pane 内进程树死透确认(safe-cleanup-visible-subagent)。
5
+ * 工厂形态便于独立单测清理时序,不依赖整个 spawnVisible。
6
+ */
7
+ import * as fs from "node:fs";
8
+ import type { TermBackend } from "./term-backend";
9
+ import { readProcPid, resolvePlatformPid, waitForPidExit, killTree } from "./proc-guard";
10
+
11
+ /** 降级延迟:身份文件缺失时的保守删除延迟(秒级,不劣于无确认机制的现状) */
12
+ const FALLBACK_DELETE_DELAY_MS = 10_000;
13
+
14
+ export interface SafeCleanupOptions {
15
+ taskDir: string;
16
+ paneId: string;
17
+ backend: TermBackend;
18
+ }
19
+
20
+ /**
21
+ * 生成有序安全清理函数。
22
+ *
23
+ * kill=true(超时/stalled/abort):killPane 关 PTY → 等待 proc.pid 对应进程
24
+ * 死透(上限 10s)→ 未死透则 taskkill /T /F 整树强杀 → 删除目录。
25
+ * kill=false(正常结束/pane 消失):不主动杀,只等死透(上限 10s,超时同样
26
+ * 树杀兜底——防 isPaneAlive 高负载误判导致的存活 pi 写已删文件)→ 删除目录。
27
+ * 身份文件缺失(无法解析出平台适用 pid)→ 降级:kill 场景仍先 killPane,
28
+ * 再延迟 10s 删除(行为不劣于现状,且不抛错中断清理)。
29
+ *
30
+ * 调用方应先 resolveOnce 再触发清理(异步后台执行,延迟不影响结果返回)。
31
+ */
32
+ export function createSafeCleanup(options: SafeCleanupOptions): (kill: boolean) => Promise<void> {
33
+ const { taskDir, paneId, backend } = options;
34
+
35
+ const rmTaskDir = () => {
36
+ try { fs.rmSync(taskDir, { recursive: true, force: true }); } catch { /* ignore */ }
37
+ };
38
+
39
+ return async (kill: boolean): Promise<void> => {
40
+ const pid = resolvePlatformPid(readProcPid(taskDir));
41
+ if (pid === null) {
42
+ if (kill) {
43
+ try { backend.killPane(paneId); } catch { /* ignore */ }
44
+ }
45
+ await new Promise((resolve) => setTimeout(resolve, FALLBACK_DELETE_DELAY_MS));
46
+ rmTaskDir();
47
+ return;
48
+ }
49
+ if (kill) {
50
+ try { backend.killPane(paneId); } catch { /* ignore */ }
51
+ }
52
+ const dead = await waitForPidExit(pid);
53
+ if (!dead) {
54
+ try { killTree(pid); } catch { /* ignore */ }
55
+ }
56
+ rmTaskDir();
57
+ };
58
+ }