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.
@@ -0,0 +1,116 @@
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
+ // 存活的目录跳过(死透检查)——修复反例:C2 sweep 违反自身不变量
67
+ it("proc.pid 指向活进程的超龄目录跳过不删", () => {
68
+ const root = mkRoot();
69
+ try {
70
+ const alive = path.join(root, "pi-visible-alive");
71
+ fs.mkdirSync(alive);
72
+ fs.writeFileSync(path.join(alive, "task.txt"), "x");
73
+ backdateTree(alive, STALE_VISIBLE_TASK_DIR_MS * 2);
74
+ // 假装该目录属于当前 vitest 进程(两平台语义位同填,必然存活)
75
+ fs.writeFileSync(path.join(alive, "proc.pid"), `${process.pid} ${process.pid}\n`);
76
+ sweepStaleVisibleTaskDirs(root);
77
+ expect(fs.existsSync(alive)).toBe(true);
78
+ } finally { fs.rmSync(root, { recursive: true, force: true }); }
79
+ });
80
+
81
+ it("非 pi-visible-* 前缀目录不触碰", () => {
82
+ const root = mkRoot();
83
+ try {
84
+ const other = path.join(root, "pi-pv-other");
85
+ fs.mkdirSync(other);
86
+ backdateTree(other, STALE_VISIBLE_TASK_DIR_MS * 2);
87
+ sweepStaleVisibleTaskDirs(root);
88
+ expect(fs.existsSync(other)).toBe(true);
89
+ } finally { fs.rmSync(root, { recursive: true, force: true }); }
90
+ });
91
+
92
+ it("单个目录删除失败不中断扫描(容错)", () => {
93
+ const root = mkRoot();
94
+ try {
95
+ const poisoned = path.join(root, "pi-visible-poison");
96
+ const stale = path.join(root, "pi-visible-ok");
97
+ fs.mkdirSync(poisoned); fs.mkdirSync(stale);
98
+ backdateTree(poisoned, STALE_VISIBLE_TASK_DIR_MS * 2);
99
+ backdateTree(stale, STALE_VISIBLE_TASK_DIR_MS * 2);
100
+ rmMock.mockImplementation(((target: any, opts: any) => {
101
+ if (String(target) === poisoned) throw new Error("EPERM");
102
+ return holder.origRm(target, opts);
103
+ }) as any);
104
+ try {
105
+ sweepStaleVisibleTaskDirs(root);
106
+ expect(fs.existsSync(stale)).toBe(false); // 后续目录继续处理
107
+ } finally {
108
+ rmMock.mockImplementation(((t: any, o: any) => holder.origRm(t, o)) as any);
109
+ }
110
+ } finally { fs.rmSync(root, { recursive: true, force: true }); }
111
+ });
112
+
113
+ it("扫描根不可读不抛错(顶层容错)", () => {
114
+ expect(() => sweepStaleVisibleTaskDirs(path.join(os.tmpdir(), "definitely-missing-root"))).not.toThrow();
115
+ });
116
+ });
@@ -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
+ });
package/utils.ts CHANGED
@@ -1,74 +1,133 @@
1
- /**
2
- * workflow: 子代理通用工具函数
3
- *
4
- * findSessionFile / getSubagentStatusSummary / isSubagentSuccess
5
- * 所有使用 runSubagent 的扩展共享。
6
- */
7
-
8
- import * as fs from "node:fs";
9
- import * as path from "node:path";
10
- import * as os from "node:os";
11
-
12
- /**
13
- * 从 ~/.pi/agent/sessions/ 中找到指定会话 ID 对应的文件路径
14
- */
15
- export function findSessionFile(sessionId: string): string | undefined {
16
- const sessionDir = path.join(os.homedir(), ".pi", "agent", "sessions");
17
- if (!fs.existsSync(sessionDir)) return undefined;
18
-
19
- for (const projectDir of fs.readdirSync(sessionDir)) {
20
- const projectPath = path.join(sessionDir, projectDir);
21
- if (!fs.statSync(projectPath).isDirectory()) continue;
22
- for (const file of fs.readdirSync(projectPath)) {
23
- if (file.includes(sessionId)) {
24
- return path.join(projectPath, file);
25
- }
26
- }
27
- }
28
- return undefined;
29
- }
30
-
31
- /**
32
- * 读取子代理会话的最新状态摘要
33
- */
34
- export function getSubagentStatusSummary(sessionId: string): string | undefined {
35
- const filePath = findSessionFile(sessionId);
36
- if (!filePath) return undefined;
37
- try {
38
- const content = fs.readFileSync(filePath, "utf-8");
39
- const lines = content.split("\n").filter(Boolean);
40
-
41
- let msgCount = 0;
42
- let lastToolName = "";
43
- let lastTs = "";
44
- for (const line of lines) {
45
- try {
46
- const e = JSON.parse(line);
47
- if (e.type === "message" && e.message?.role === "assistant") {
48
- msgCount++;
49
- lastTs = e.timestamp || lastTs;
50
- for (const c of e.message.content || []) {
51
- if (c.type === "toolCall") lastToolName = c.name;
52
- }
53
- }
54
- } catch { /* skip */ }
55
- }
56
-
57
- const age = lastTs ? `(${lastTs.slice(11, 19)})` : "";
58
- const toolInfo = lastToolName ? `,最近动作: ${lastToolName}` : "";
59
- return `${msgCount}条消息${toolInfo} ${age} [${(content.length / 1024).toFixed(0)}KB]`;
60
- } catch {
61
- return undefined;
62
- }
63
- }
64
-
65
- /**
66
- * 判断子代理是否成功执行
67
- *
68
- * 成功条件:exitCode=0 且无 error 且未超时,
69
- * 或者输出足够长(>100字符)且不是空输出且未超时。
70
- */
71
- export function isSubagentSuccess(result: { exitCode: number; output: string; error?: string; timedOut?: boolean }): boolean {
72
- if (result.exitCode === 0 && !result.error && !result.timedOut) return true;
73
- return result.output.length > 100 && result.output !== "(no output)" && !result.timedOut;
74
- }
1
+ /**
2
+ * workflow: 子代理通用工具函数
3
+ *
4
+ * findSessionFile / getSubagentStatusSummary / isSubagentSuccess
5
+ * 所有使用 runSubagent 的扩展共享。
6
+ */
7
+
8
+ import * as fs from "node:fs";
9
+ import * as path from "node:path";
10
+ import * as os from "node:os";
11
+ import type { SubagentResult } from "./types";
12
+
13
+ /**
14
+ * 从 ~/.pi/agent/sessions/ 中找到指定会话 ID 对应的文件路径
15
+ */
16
+ export function findSessionFile(sessionId: string): string | undefined {
17
+ const sessionDir = path.join(os.homedir(), ".pi", "agent", "sessions");
18
+ if (!fs.existsSync(sessionDir)) return undefined;
19
+
20
+ for (const projectDir of fs.readdirSync(sessionDir)) {
21
+ const projectPath = path.join(sessionDir, projectDir);
22
+ if (!fs.statSync(projectPath).isDirectory()) continue;
23
+ for (const file of fs.readdirSync(projectPath)) {
24
+ if (file.includes(sessionId)) {
25
+ return path.join(projectPath, file);
26
+ }
27
+ }
28
+ }
29
+ return undefined;
30
+ }
31
+
32
+ /**
33
+ * 读取子代理会话的最新状态摘要
34
+ */
35
+ export function getSubagentStatusSummary(sessionId: string): string | undefined {
36
+ const filePath = findSessionFile(sessionId);
37
+ if (!filePath) return undefined;
38
+ try {
39
+ const content = fs.readFileSync(filePath, "utf-8");
40
+ const lines = content.split("\n").filter(Boolean);
41
+
42
+ let msgCount = 0;
43
+ let lastToolName = "";
44
+ let lastTs = "";
45
+ for (const line of lines) {
46
+ try {
47
+ const e = JSON.parse(line);
48
+ if (e.type === "message" && e.message?.role === "assistant") {
49
+ msgCount++;
50
+ lastTs = e.timestamp || lastTs;
51
+ for (const c of e.message.content || []) {
52
+ if (c.type === "toolCall") lastToolName = c.name;
53
+ }
54
+ }
55
+ } catch { /* skip */ }
56
+ }
57
+
58
+ const age = lastTs ? `(${lastTs.slice(11, 19)})` : "";
59
+ const toolInfo = lastToolName ? `,最近动作: ${lastToolName}` : "";
60
+ return `${msgCount}条消息${toolInfo} ${age} [${(content.length / 1024).toFixed(0)}KB]`;
61
+ } catch {
62
+ return undefined;
63
+ }
64
+ }
65
+
66
+ /**
67
+ * 判断子代理是否成功执行
68
+ *
69
+ * 成功条件:exitCode=0 且无 error 且未超时,
70
+ * 或者输出足够长(>100字符)且不是空输出且未超时。
71
+ * 系统性失败形态(error 字段 / timedOut / 空占位输出兼 stderr 非空)一律判失败
72
+ * (exit 0 不再单独短路——opsx-subarch-meta-baseline F1 修复,spec: subagent-spawn-runtime)。
73
+ */
74
+ export function isSubagentSuccess(result: { exitCode: number; output: string; error?: string; timedOut?: boolean; stderr?: string }): boolean {
75
+ if (isSystemicSubagentFailure(result)) return false;
76
+ if (result.exitCode === 0 && !result.error && !result.timedOut) return true;
77
+ return result.output.length > 100 && result.output !== "(no output)" && !result.timedOut;
78
+ }
79
+
80
+ // ─── 系统性失败分类(F1 修复,spec: subagent-spawn-runtime)─────────────
81
+
82
+ /**
83
+ * 空占位输出形态文本(spawn 各分支兜底输出的字面量)。
84
+ * 字面量由测试锁死(subagent-failure-classification.test.ts)——
85
+ * 改动任一字面量须同步 spawn 分支与测试,防文本漂移静默破坏分类。
86
+ */
87
+ export const EMPTY_OUTPUT_PLACEHOLDERS: readonly string[] = [
88
+ "(no output)",
89
+ "(stalled, no output for 5 min)",
90
+ "(timed out)",
91
+ ];
92
+
93
+ /** stderr 尾部透出长度上限(防超长) */
94
+ export const STDERR_TAIL_LIMIT = 2000;
95
+
96
+ /** 判定输出是否为空占位形态:空串/纯空白,或包含任一已知占位字面量(前缀或包含匹配) */
97
+ export function isEmptyPlaceholderOutput(output: string): boolean {
98
+ if (output.trim() === "") return true;
99
+ return EMPTY_OUTPUT_PLACEHOLDERS.some((p) => output.includes(p));
100
+ }
101
+
102
+ /**
103
+ * 判定结果是否为系统性失败(spawn 层阵亡,重试无效)。
104
+ * 信号优先级:①error 字段存在;②timedOut 布尔为 true;③空占位输出兼 stderr 非空。
105
+ * 有实质输出时 stderr 不参与判定(噪声不误伤)。
106
+ */
107
+ export function isSystemicSubagentFailure(
108
+ result: { output: string; error?: string; timedOut?: boolean; stderr?: string },
109
+ ): boolean {
110
+ if (result.error) return true;
111
+ if (result.timedOut) return true;
112
+ return isEmptyPlaceholderOutput(result.output) && !!(result.stderr && result.stderr.trim());
113
+ }
114
+
115
+ /**
116
+ * 组装系统性失败档结果:跳过重试后返回的呈现形态。
117
+ * - output = 报错说明 + stderr 尾部(截尾防超长)
118
+ * - error 字段必填(失败档闭合标记,isSubagentSuccess 由此判 false)
119
+ * - exitCode 保持子进程原值(不因判失败而篡改)
120
+ */
121
+ export function buildSystemicFailureResult(result: SubagentResult): SubagentResult {
122
+ const reason = result.error
123
+ ? result.error
124
+ : result.timedOut
125
+ ? "timed out"
126
+ : "empty placeholder output with non-empty stderr";
127
+ const stderrTail = result.stderr.trim() ? result.stderr.slice(-STDERR_TAIL_LIMIT) : "";
128
+ const lines = [`[子代理系统性失败] ${reason}——已跳过自动重试(系统性失败重试无效)。`];
129
+ if (stderrTail) {
130
+ lines.push("", "—— stderr 尾部 ——", stderrTail);
131
+ }
132
+ return { ...result, output: lines.join("\n"), error: result.error || `systemic failure: ${reason}` };
133
+ }
@@ -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
+ }