pi-ate-workflow 0.2.5 → 0.2.6
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/index.ts +1 -1
- package/package.json +1 -1
- package/subagent-jsonl-signal.ts +37 -4
- package/subagent-spawn-once.ts +31 -5
- package/subagent-utils.ts +28 -11
- package/tests/spawn-once-extra-env.test.ts +11 -5
- package/tests/subagent-find-session-file.test.ts +214 -0
- package/tests/subagent-spawn-once-jsonl-crosscheck.test.ts +243 -0
- package/tests/subagent-spawn-once.test.ts +16 -6
package/index.ts
CHANGED
|
@@ -33,7 +33,7 @@ export type { SubagentResult, SubagentEvent } from "./types";
|
|
|
33
33
|
export { createStateManager, createUIUpdater } from "./state";
|
|
34
34
|
export { registerWorkflowTool, type ActionDef } from "./workflow";
|
|
35
35
|
export { findSessionFile, getSubagentStatusSummary, isSubagentSuccess, isSystemicSubagentFailure, buildSystemicFailureResult, isEmptyPlaceholderOutput, EMPTY_OUTPUT_PLACEHOLDERS } from "./utils";
|
|
36
|
-
export { checkSessionJsonlTermination } from "./subagent-jsonl-signal";
|
|
36
|
+
export { checkSessionJsonlTermination, crossCheckOnceSessionJsonl } from "./subagent-jsonl-signal";
|
|
37
37
|
export { discoverAgents, getAgentDescription } from "./agents";
|
|
38
38
|
export { AGENT_DIR, AGENTS_DIR } from "./paths";
|
|
39
39
|
|
package/package.json
CHANGED
package/subagent-jsonl-signal.ts
CHANGED
|
@@ -1,9 +1,10 @@
|
|
|
1
1
|
/**
|
|
2
|
-
*
|
|
2
|
+
* 子代理系统性失败信号:子会话 session.jsonl 终结形态判定(visible / once 两种 spawn 模式共用)
|
|
3
3
|
*
|
|
4
|
-
* visible spawn 的子进程输出直进终端窗格、stderr 无数据源(pipe
|
|
5
|
-
*
|
|
6
|
-
*
|
|
4
|
+
* visible spawn 的子进程输出直进终端窗格、stderr 无数据源(pipe 拿不到数据);
|
|
5
|
+
* once spawn 的子进程加载崩溃经 bash 包装时可出现 exitCode=0 且 stderr 空。
|
|
6
|
+
* 两种模式下 close 分支的 exitCode/stderr 判定都会失效,失败信号改看 jsonl:
|
|
7
|
+
* 文件缺失或无 message 事件(未进入对话阶段)= spawn 层阵亡,判系统性失败档。
|
|
7
8
|
*
|
|
8
9
|
* 注:pi 的 session.jsonl 没有 result/agent_end 类终结事件——正常会话末行
|
|
9
10
|
* 即 message 事件(2026-11 实测多个已终结会话),故「正常终结形态」的实态
|
|
@@ -11,6 +12,7 @@
|
|
|
11
12
|
*/
|
|
12
13
|
|
|
13
14
|
import * as fs from "node:fs";
|
|
15
|
+
import { findSessionFileById } from "./subagent-utils";
|
|
14
16
|
|
|
15
17
|
/** 判定结果:ok=false 时 reason 说明异常形态(拼入系统性失败档报错) */
|
|
16
18
|
export interface JsonlTerminationSignal {
|
|
@@ -41,3 +43,34 @@ export function checkSessionJsonlTermination(sessionFile: string): JsonlTerminat
|
|
|
41
43
|
return { ok: false, reason: `session.jsonl 读取失败: ${err instanceof Error ? err.message : String(err)}` };
|
|
42
44
|
}
|
|
43
45
|
}
|
|
46
|
+
|
|
47
|
+
/** once 模式交叉校验 error 措辞前缀(runSubagent 据 error 字段归系统性失败档;测试锁字面量) */
|
|
48
|
+
const ONCE_CROSS_CHECK_SOURCE = "once 模式信号源=jsonl 交叉校验";
|
|
49
|
+
|
|
50
|
+
/**
|
|
51
|
+
* once 模式失败信号源:空占位形态下的 jsonl 交叉校验(与 visible 模式信号源对齐)。
|
|
52
|
+
* 由 subagent-spawn-once.ts 的 close 分支在等待尾刷容忍窗后调用:
|
|
53
|
+
* - 无 session 事件 → 子会话未建立,直接判异常(不查文件)
|
|
54
|
+
* - 有 session 事件 → findSessionFileById 定位子会话文件;缺失或终结形态异常 → 判异常
|
|
55
|
+
* - 判定正常 → 返回 undefined(不注入 error,维持现行为)
|
|
56
|
+
*
|
|
57
|
+
* @returns 异常形态返回 error 文案(含 sessionId 与判定原因);正常返回 undefined
|
|
58
|
+
*/
|
|
59
|
+
export function crossCheckOnceSessionJsonl(
|
|
60
|
+
capturedSessionId: string | undefined,
|
|
61
|
+
cwd: string,
|
|
62
|
+
exitCode: number | null,
|
|
63
|
+
stderr: string,
|
|
64
|
+
): string | undefined {
|
|
65
|
+
const exitInfo = `exitCode=${exitCode ?? 1},stderr ${stderr.trim() ? "非空" : "空"}——疑似进程加载崩溃经 bash 包装假退出`;
|
|
66
|
+
if (!capturedSessionId) {
|
|
67
|
+
return `${ONCE_CROSS_CHECK_SOURCE}:stdout 无 session 事件,子会话未建立(${exitInfo},bash 包装退出码不可信)`;
|
|
68
|
+
}
|
|
69
|
+
const sessionFile = findSessionFileById(capturedSessionId, cwd);
|
|
70
|
+
if (!sessionFile) {
|
|
71
|
+
return `${ONCE_CROSS_CHECK_SOURCE}:子会话 ${capturedSessionId} 的 session.jsonl 缺失(session 目录中未找到该会话文件)(${exitInfo})`;
|
|
72
|
+
}
|
|
73
|
+
const signal = checkSessionJsonlTermination(sessionFile);
|
|
74
|
+
if (signal.ok) return undefined;
|
|
75
|
+
return `${ONCE_CROSS_CHECK_SOURCE}:子会话 ${capturedSessionId} 的 ${signal.reason}(${exitInfo})`;
|
|
76
|
+
}
|
package/subagent-spawn-once.ts
CHANGED
|
@@ -9,6 +9,14 @@ import { spawn } from "node:child_process";
|
|
|
9
9
|
import { SubagentSession } from "./subagent-session";
|
|
10
10
|
import type { SubagentEvent, SubagentResult } from "./types";
|
|
11
11
|
import { getPiCommand } from "./subagent-utils";
|
|
12
|
+
import { crossCheckOnceSessionJsonl } from "./subagent-jsonl-signal";
|
|
13
|
+
|
|
14
|
+
/**
|
|
15
|
+
* 空占位形态下 jsonl 交叉校验前的等待——孤儿进程 jsonl 尾刷容忍窗
|
|
16
|
+
* (与 visible 模式 finish 尾刷同款常数;spec: subagent-spawn-runtime)。
|
|
17
|
+
* 导出仅供测试推进 fake timers 时引用,不进 barrel。
|
|
18
|
+
*/
|
|
19
|
+
export const JSONL_CROSS_CHECK_DELAY_MS = 500;
|
|
12
20
|
|
|
13
21
|
export function spawnOnce(
|
|
14
22
|
task: string,
|
|
@@ -126,11 +134,29 @@ export function spawnOnce(
|
|
|
126
134
|
if (!line.trim()) continue;
|
|
127
135
|
try { session.parseStreamEvent(JSON.parse(line)); } catch { /* skip */ }
|
|
128
136
|
}
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
137
|
+
const exitCode = code ?? 1;
|
|
138
|
+
const output = session.formatOutput("(no output)");
|
|
139
|
+
|
|
140
|
+
// 正常路径(有 assistant 文本)零变化:立即返回,不等待、不交叉校验。
|
|
141
|
+
// 触发条件取「未收集到任何文本」而非 isEmptyPlaceholderOutput 的包含匹配,
|
|
142
|
+
// 避免正文里恰好含占位字面量的真实输出被误判。
|
|
143
|
+
if (session.formatOutput("").trim() !== "") {
|
|
144
|
+
session.resolveOnce({ exitCode, output, stderr });
|
|
145
|
+
return;
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
// 空占位形态 → once 模式信号源=jsonl 交叉校验(spec: subagent-spawn-runtime)。
|
|
149
|
+
// 先等 JSONL_CROSS_CHECK_DELAY_MS(bash 异常退出时 pi 孤儿进程尚在跑、jsonl 未刷盘的窗口),
|
|
150
|
+
// 再按 capturedSessionId 定位子会话文件判定;注入 error 后由 runSubagent 归系统性失败档(不重试)。
|
|
151
|
+
setTimeout(() => {
|
|
152
|
+
if (session.isDone) return; // 等待窗内已被 abort / 超时先行 resolve
|
|
153
|
+
session.resolveOnce({
|
|
154
|
+
exitCode,
|
|
155
|
+
output,
|
|
156
|
+
stderr,
|
|
157
|
+
error: crossCheckOnceSessionJsonl(session.capturedSessionId, cwd, code, stderr),
|
|
158
|
+
});
|
|
159
|
+
}, JSONL_CROSS_CHECK_DELAY_MS);
|
|
134
160
|
});
|
|
135
161
|
|
|
136
162
|
proc.on("error", (err) => {
|
package/subagent-utils.ts
CHANGED
|
@@ -36,19 +36,27 @@ export function injectParentSession(sessionFilePath: string, parentPath: string)
|
|
|
36
36
|
}
|
|
37
37
|
|
|
38
38
|
/**
|
|
39
|
-
* 通过 sessionId 查找子代理 session
|
|
40
|
-
*
|
|
39
|
+
* 通过 sessionId 查找子代理 session 文件路径(只读定位,无副作用)。
|
|
40
|
+
* 路径推导:PI_CODING_AGENT_SESSION_DIR ∨ ~/.pi/agent/sessions + cwd slug 子目录
|
|
41
|
+
* + 首行 header.id 匹配(按修改时间降序,只查最近 20 个 .jsonl)。
|
|
42
|
+
*
|
|
43
|
+
* 从 findAndInjectParentSession 抽出(opsx-subarch-cmds-late 7.1),
|
|
44
|
+
* 供 spawnOnce close 分支的 jsonl 交叉校验复用;路径推导逻辑零变化。
|
|
45
|
+
*
|
|
46
|
+
* @returns 命中返回 session 文件路径;未命中(sessionId 空 / 目录缺失 / 无匹配)返回 undefined
|
|
41
47
|
*/
|
|
42
|
-
export function
|
|
43
|
-
if (!sessionId
|
|
48
|
+
export function findSessionFileById(sessionId: string | undefined, cwd: string): string | undefined {
|
|
49
|
+
if (!sessionId) return undefined;
|
|
44
50
|
const baseDir = process.env.PI_CODING_AGENT_SESSION_DIR
|
|
45
51
|
|| path.join(os.homedir(), ".pi/agent/sessions");
|
|
46
52
|
if (!fs.existsSync(baseDir)) return;
|
|
47
53
|
|
|
48
|
-
// 从 cwd 推导 session
|
|
49
|
-
|
|
54
|
+
// 从 cwd 推导 session 子目录——与 pi SDK session-manager 的 slug 公式逐字一致
|
|
55
|
+
// (去掉单个前导分隔符;其余 / 与 \ 与盘符冒号全部换成 -)。只替换 / 时 Windows 盘符
|
|
56
|
+
// 冒号残留 → 永远定位不到 pi 实际写入的目录(findAndInjectParentSession 曾因此在 Windows 静默空转)。
|
|
57
|
+
const cwdSlug = "--" + cwd.replace(/^[/\\]/, "").replace(/[/\\:]/g, "-") + "--";
|
|
50
58
|
const sessionDir = path.join(baseDir, cwdSlug);
|
|
51
|
-
if (!fs.existsSync(sessionDir)) return;
|
|
59
|
+
if (!fs.existsSync(sessionDir)) return undefined;
|
|
52
60
|
|
|
53
61
|
try {
|
|
54
62
|
// 按修改时间降序,优先检查最近的文件
|
|
@@ -67,13 +75,22 @@ export function findAndInjectParentSession(sessionId: string | undefined, parent
|
|
|
67
75
|
fs.closeSync(fd);
|
|
68
76
|
const firstLine = buf.toString("utf-8").split("\n")[0];
|
|
69
77
|
const header = JSON.parse(firstLine);
|
|
70
|
-
if (header.id === sessionId)
|
|
71
|
-
injectParentSession(filePath, parentPath);
|
|
72
|
-
return;
|
|
73
|
-
}
|
|
78
|
+
if (header.id === sessionId) return filePath;
|
|
74
79
|
} catch { /* skip */ }
|
|
75
80
|
}
|
|
76
81
|
} catch { /* skip */ }
|
|
82
|
+
return undefined;
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/**
|
|
86
|
+
* 通过 sessionId 查找子代理 session 文件并注入 parentSession。
|
|
87
|
+
* 用于 spawnOnce 模式(session 文件路径未知,需要按 ID 搜索)。
|
|
88
|
+
* 定位委托 findSessionFileById(抽取后本调用方行为零变化)。
|
|
89
|
+
*/
|
|
90
|
+
export function findAndInjectParentSession(sessionId: string | undefined, parentPath: string, cwd: string): void {
|
|
91
|
+
if (!sessionId || !parentPath) return;
|
|
92
|
+
const filePath = findSessionFileById(sessionId, cwd);
|
|
93
|
+
if (filePath) injectParentSession(filePath, parentPath);
|
|
77
94
|
}
|
|
78
95
|
|
|
79
96
|
/**
|
|
@@ -23,7 +23,13 @@ vi.mock("node:child_process", async (importOriginal) => {
|
|
|
23
23
|
};
|
|
24
24
|
});
|
|
25
25
|
|
|
26
|
-
import { spawnOnce } from "../subagent-spawn-once";
|
|
26
|
+
import { spawnOnce, JSONL_CROSS_CHECK_DELAY_MS } from "../subagent-spawn-once";
|
|
27
|
+
|
|
28
|
+
/** 空占位 close 路径先等 JSONL_CROSS_CHECK_DELAY_MS 再 jsonl 交叉校验——fake timers 需推进过等待窗 */
|
|
29
|
+
async function emitCloseAndSettle(code: number): Promise<void> {
|
|
30
|
+
mockProc.emit("close", code);
|
|
31
|
+
await vi.advanceTimersByTimeAsync(JSONL_CROSS_CHECK_DELAY_MS);
|
|
32
|
+
}
|
|
27
33
|
|
|
28
34
|
function createMockProcess() {
|
|
29
35
|
const proc = new EventEmitter() as any;
|
|
@@ -47,7 +53,7 @@ describe("spawnOnce — extraEnv 透传", () => {
|
|
|
47
53
|
|
|
48
54
|
it("不传 extraEnv 时 spawn env 为 process.env", async () => {
|
|
49
55
|
const resultPromise = spawnOnce("task", "/cwd", "/tmp/prompt.md", { tools: ["read"] });
|
|
50
|
-
|
|
56
|
+
await emitCloseAndSettle(0);
|
|
51
57
|
await resultPromise;
|
|
52
58
|
|
|
53
59
|
const spawnOpts = spawnCalls[0][2];
|
|
@@ -62,7 +68,7 @@ describe("spawnOnce — extraEnv 透传", () => {
|
|
|
62
68
|
PI_SUBAGENT_CHILD_INDEX: "1",
|
|
63
69
|
};
|
|
64
70
|
const resultPromise = spawnOnce("task", "/cwd", "/tmp/prompt.md", { tools: ["read"] }, undefined, undefined, undefined, undefined, undefined, extraEnv);
|
|
65
|
-
|
|
71
|
+
await emitCloseAndSettle(0);
|
|
66
72
|
await resultPromise;
|
|
67
73
|
|
|
68
74
|
const spawnOpts = spawnCalls[0][2];
|
|
@@ -78,7 +84,7 @@ describe("spawnOnce — extraEnv 透传", () => {
|
|
|
78
84
|
it("extraEnv 的值覆盖 process.env 中同名 key", async () => {
|
|
79
85
|
const extraEnv = { PATH: "/custom/path" };
|
|
80
86
|
const resultPromise = spawnOnce("task", "/cwd", "/tmp/prompt.md", { tools: ["read"] }, undefined, undefined, undefined, undefined, undefined, extraEnv);
|
|
81
|
-
|
|
87
|
+
await emitCloseAndSettle(0);
|
|
82
88
|
await resultPromise;
|
|
83
89
|
|
|
84
90
|
const spawnOpts = spawnCalls[0][2];
|
|
@@ -87,7 +93,7 @@ describe("spawnOnce — extraEnv 透传", () => {
|
|
|
87
93
|
|
|
88
94
|
it("extraEnv 为空对象时仍包含 process.env", async () => {
|
|
89
95
|
const resultPromise = spawnOnce("task", "/cwd", "/tmp/prompt.md", { tools: ["read"] }, undefined, undefined, undefined, undefined, undefined, {});
|
|
90
|
-
|
|
96
|
+
await emitCloseAndSettle(0);
|
|
91
97
|
await resultPromise;
|
|
92
98
|
|
|
93
99
|
const spawnOpts = spawnCalls[0][2];
|
|
@@ -0,0 +1,214 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 测试 findSessionFileById 抽取(opsx-subarch-cmds-late 7.1,spec: subagent-spawn-runtime「定位函数可复用」)
|
|
3
|
+
*
|
|
4
|
+
* 覆盖:
|
|
5
|
+
* 1. 路径推导行为锁死(从 findAndInjectParentSession 抽出,零变化):
|
|
6
|
+
* PI_CODING_AGENT_SESSION_DIR 覆盖 + cwd slug 子目录 + 首行 header.id 匹配 + 最近 20 个文件窗口 + 容错
|
|
7
|
+
* 2. 既有调用方 findAndInjectParentSession 经新函数定位后行为等价:
|
|
8
|
+
* 命中注入到同一文件 / 已有 parentSession 不覆盖 / 未命中不触碰 / 参数为空直接返回
|
|
9
|
+
*
|
|
10
|
+
* 用真实临时目录(只读定位与首行注入都走真实 fs)。cwd 用 Unix 风格假路径,slug 目录按被测函数
|
|
11
|
+
* 自身的推导公式布局——这部分锁的是「抽取前后行为一致」。
|
|
12
|
+
*
|
|
13
|
+
* Windows 布局一致性(Q1-A 根因修,opsx-subarch-cmds-late):slug 公式与 pi SDK
|
|
14
|
+
* session-manager 逐字同式(/ 与 \ 与盘符冒号全部换 -)。目录名用 **实际观测值**硬编码
|
|
15
|
+
* (ls ~/.pi/agent/sessions/ 实证),不依赖被测函数推导——锁的是「与 pi 真实目录布局一致」。
|
|
16
|
+
* 修复前 Windows 下永远不命中:once 模式 jsonl 交叉校验会把「子代理合法跑完但零文本输出」
|
|
17
|
+
* 误报为 jsonl 缺失。
|
|
18
|
+
*/
|
|
19
|
+
import { describe, it, expect, beforeEach, afterEach } from "vitest";
|
|
20
|
+
import * as fs from "node:fs";
|
|
21
|
+
import * as os from "node:os";
|
|
22
|
+
import * as path from "node:path";
|
|
23
|
+
import { findSessionFileById, findAndInjectParentSession } from "../subagent-utils";
|
|
24
|
+
|
|
25
|
+
const CWD = "/proj/x";
|
|
26
|
+
const PARENT = "/sessions/parent.jsonl";
|
|
27
|
+
const FILE_PREFIX = "2026-11-25T00-00-00";
|
|
28
|
+
|
|
29
|
+
let sessionRoot = "";
|
|
30
|
+
let prevEnv: string | undefined;
|
|
31
|
+
|
|
32
|
+
/** Windows 实际布局:cwd 与 pi 写出的 slug 目录名(观测值,不推导) */
|
|
33
|
+
const WIN_CWD = "C:\\Users\\Administrator\\.pi\\agent\\git\\github.com\\catlain";
|
|
34
|
+
const WIN_CWD_FORWARD = "C:/Users/Administrator/.pi/agent/git/github.com/catlain";
|
|
35
|
+
const WIN_SLUG = "--C--Users-Administrator-.pi-agent-git-github.com-catlain--";
|
|
36
|
+
|
|
37
|
+
function makeSessionDirAt(slug: string): string {
|
|
38
|
+
const dir = path.join(sessionRoot, slug);
|
|
39
|
+
fs.mkdirSync(dir, { recursive: true });
|
|
40
|
+
return dir;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
function makeSessionDir(cwd: string = CWD): string {
|
|
44
|
+
// Unix 组仅用 CWD 一个值;期望目录名硬编码(观测自 pi SDK slug 公式),不复制被测公式
|
|
45
|
+
// ——复制公式会让测试随实现一起漂移,锁不住回归。
|
|
46
|
+
const expected: Record<string, string> = { [CWD]: "--proj-x--", "/proj/other": "--proj-other--" };
|
|
47
|
+
const dir = path.join(sessionRoot, expected[cwd] ?? `__unexpected_cwd__:${cwd}`);
|
|
48
|
+
fs.mkdirSync(dir, { recursive: true });
|
|
49
|
+
return dir;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/** 写一个两行 session 文件(header + message),返回路径 */
|
|
53
|
+
function writeSessionFile(dir: string, id: string, extra: Record<string, unknown> = {}): string {
|
|
54
|
+
const filePath = path.join(dir, `${FILE_PREFIX}_${id}.jsonl`);
|
|
55
|
+
const header = JSON.stringify({ type: "session", version: 3, id, cwd: CWD, ...extra });
|
|
56
|
+
const body = JSON.stringify({ type: "message", message: { role: "user", content: [] } });
|
|
57
|
+
fs.writeFileSync(filePath, `${header}\n${body}\n`, "utf-8");
|
|
58
|
+
return filePath;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
function readHeader(filePath: string): Record<string, unknown> {
|
|
62
|
+
return JSON.parse(fs.readFileSync(filePath, "utf-8").split("\n")[0]);
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
beforeEach(() => {
|
|
66
|
+
sessionRoot = fs.mkdtempSync(path.join(os.tmpdir(), "pi-wf-sess-"));
|
|
67
|
+
prevEnv = process.env.PI_CODING_AGENT_SESSION_DIR;
|
|
68
|
+
process.env.PI_CODING_AGENT_SESSION_DIR = sessionRoot;
|
|
69
|
+
});
|
|
70
|
+
|
|
71
|
+
afterEach(() => {
|
|
72
|
+
if (prevEnv === undefined) delete process.env.PI_CODING_AGENT_SESSION_DIR;
|
|
73
|
+
else process.env.PI_CODING_AGENT_SESSION_DIR = prevEnv;
|
|
74
|
+
fs.rmSync(sessionRoot, { recursive: true, force: true });
|
|
75
|
+
});
|
|
76
|
+
|
|
77
|
+
describe("findSessionFileById:路径推导行为锁死(抽取零变化)", () => {
|
|
78
|
+
it("命中:slug 目录内首行 header.id 匹配 → 返回该文件路径(非匹配文件跳过)", () => {
|
|
79
|
+
const dir = makeSessionDir();
|
|
80
|
+
writeSessionFile(dir, "sess-other");
|
|
81
|
+
const target = writeSessionFile(dir, "sess-hit");
|
|
82
|
+
expect(findSessionFileById("sess-hit", CWD)).toBe(target);
|
|
83
|
+
});
|
|
84
|
+
|
|
85
|
+
it("命中:只看首行 header.id(id 出现在后续行不算)", () => {
|
|
86
|
+
const dir = makeSessionDir();
|
|
87
|
+
const filePath = path.join(dir, "a.jsonl");
|
|
88
|
+
const header = JSON.stringify({ type: "session", version: 3, id: "sess-a" });
|
|
89
|
+
const later = JSON.stringify({ type: "session_info", id: "sess-b" });
|
|
90
|
+
fs.writeFileSync(filePath, `${header}\n${later}\n`, "utf-8");
|
|
91
|
+
expect(findSessionFileById("sess-b", CWD)).toBeUndefined();
|
|
92
|
+
expect(findSessionFileById("sess-a", CWD)).toBe(filePath);
|
|
93
|
+
});
|
|
94
|
+
|
|
95
|
+
it("命中:只查最近 20 个文件——目标 mtime 最旧排第 21 → 未命中;窗口内文件照常命中", () => {
|
|
96
|
+
const dir = makeSessionDir();
|
|
97
|
+
const oldest = writeSessionFile(dir, "sess-oldest");
|
|
98
|
+
for (let i = 0; i < 20; i++) writeSessionFile(dir, `sess-${i}`);
|
|
99
|
+
const old = new Date(Date.now() - 60_000);
|
|
100
|
+
fs.utimesSync(oldest, old, old);
|
|
101
|
+
expect(findSessionFileById("sess-oldest", CWD)).toBeUndefined();
|
|
102
|
+
expect(findSessionFileById("sess-19", CWD)).toBe(path.join(dir, `${FILE_PREFIX}_sess-19.jsonl`));
|
|
103
|
+
});
|
|
104
|
+
|
|
105
|
+
it("容错:候选文件首行非 JSON / 首行超 500 字节截断 → 跳过不抛,继续找后续文件", () => {
|
|
106
|
+
const dir = makeSessionDir();
|
|
107
|
+
fs.writeFileSync(path.join(dir, "0_broken.jsonl"), "not json at all\n", "utf-8");
|
|
108
|
+
fs.writeFileSync(path.join(dir, "1_huge.jsonl"), `{"type":"session","id":"${"x".repeat(600)}"}\n`, "utf-8");
|
|
109
|
+
const target = writeSessionFile(dir, "sess-after-broken");
|
|
110
|
+
expect(findSessionFileById("sess-after-broken", CWD)).toBe(target);
|
|
111
|
+
});
|
|
112
|
+
|
|
113
|
+
it("未命中:slug 目录内无匹配 id → undefined", () => {
|
|
114
|
+
const dir = makeSessionDir();
|
|
115
|
+
writeSessionFile(dir, "sess-other");
|
|
116
|
+
expect(findSessionFileById("sess-missing", CWD)).toBeUndefined();
|
|
117
|
+
});
|
|
118
|
+
|
|
119
|
+
it("未命中:cwd 对应 slug 目录不存在 → undefined(另一 cwd 的目录不串查)", () => {
|
|
120
|
+
writeSessionFile(makeSessionDir("/proj/other"), "sess-hit");
|
|
121
|
+
expect(findSessionFileById("sess-hit", CWD)).toBeUndefined();
|
|
122
|
+
});
|
|
123
|
+
|
|
124
|
+
it("未命中:sessionId 为 undefined / 空串 → undefined(base 目录缺失也不抛)", () => {
|
|
125
|
+
fs.rmSync(sessionRoot, { recursive: true, force: true });
|
|
126
|
+
expect(findSessionFileById(undefined, CWD)).toBeUndefined();
|
|
127
|
+
expect(findSessionFileById("", CWD)).toBeUndefined();
|
|
128
|
+
});
|
|
129
|
+
|
|
130
|
+
it("未命中:base 目录(PI_CODING_AGENT_SESSION_DIR)不存在 → undefined 不抛", () => {
|
|
131
|
+
fs.rmSync(sessionRoot, { recursive: true, force: true });
|
|
132
|
+
expect(findSessionFileById("sess-hit", CWD)).toBeUndefined();
|
|
133
|
+
});
|
|
134
|
+
});
|
|
135
|
+
|
|
136
|
+
describe("Windows 目录布局一致性(Q1-A:slug 与 pi SDK 同式)", () => {
|
|
137
|
+
it("盘符冒号与反斜杠全部换 - → 命中 pi 实际写入的目录", () => {
|
|
138
|
+
const dir = makeSessionDirAt(WIN_SLUG);
|
|
139
|
+
const target = writeSessionFile(dir, "sess-win");
|
|
140
|
+
expect(findSessionFileById("sess-win", WIN_CWD)).toBe(target);
|
|
141
|
+
});
|
|
142
|
+
|
|
143
|
+
it("cwd 用正斜杠写法 → 同一目录(两种分隔符推导结果一致)", () => {
|
|
144
|
+
const dir = makeSessionDirAt(WIN_SLUG);
|
|
145
|
+
const target = writeSessionFile(dir, "sess-win");
|
|
146
|
+
expect(findSessionFileById("sess-win", WIN_CWD_FORWARD)).toBe(target);
|
|
147
|
+
});
|
|
148
|
+
|
|
149
|
+
it("修复前形态锁死:旧公式(仅换 /,保留盘符冒号)算出的目录不是查找目标", () => {
|
|
150
|
+
// 旧目录名含 ':'——Windows 禁止目录名含冒号(mkdir 必 ENOENT),物理上不可能存在;
|
|
151
|
+
// 因此不断言"旧目录里的文件不被找到",改断言"对修复前的 cwd 变换结果不命中":
|
|
152
|
+
// 旧公式对 WIN_CWD 的输出形如 --C:-Users-…(冒号保留),新公式必不落到该名字。
|
|
153
|
+
expect(findSessionFileById("sess-win", WIN_CWD)).toBeUndefined();
|
|
154
|
+
// 对照:正确目录建好后同一调用命中——证明 undefined 来自目录名不匹配,而非调用本身失效
|
|
155
|
+
const dir = makeSessionDirAt(WIN_SLUG);
|
|
156
|
+
const target = writeSessionFile(dir, "sess-win");
|
|
157
|
+
expect(findSessionFileById("sess-win", WIN_CWD)).toBe(target);
|
|
158
|
+
});
|
|
159
|
+
|
|
160
|
+
it("Unix 路径行为不变:仅去单个前导 /,后续 / 换 -", () => {
|
|
161
|
+
const dir = makeSessionDirAt("--proj-x--");
|
|
162
|
+
const target = writeSessionFile(dir, "sess-u");
|
|
163
|
+
expect(findSessionFileById("sess-u", "/proj/x")).toBe(target);
|
|
164
|
+
// 前导 // 只去一个(与 SDK 一致,不吞第二个分隔符)
|
|
165
|
+
expect(findSessionFileById("sess-u", "//proj/x")).toBeUndefined();
|
|
166
|
+
});
|
|
167
|
+
|
|
168
|
+
it("调用方连带生效:Windows cwd 下 parentSession 注入到正确文件", () => {
|
|
169
|
+
const dir = makeSessionDirAt(WIN_SLUG);
|
|
170
|
+
const target = writeSessionFile(dir, "sess-win");
|
|
171
|
+
findAndInjectParentSession("sess-win", PARENT, WIN_CWD);
|
|
172
|
+
expect(readHeader(target).parentSession).toBe(PARENT);
|
|
173
|
+
});
|
|
174
|
+
});
|
|
175
|
+
|
|
176
|
+
describe("findAndInjectParentSession 经 findSessionFileById 定位(调用方行为零变化)", () => {
|
|
177
|
+
it("命中:parentSession 注入到 findSessionFileById 返回的同一文件,其他文件不动", () => {
|
|
178
|
+
const dir = makeSessionDir();
|
|
179
|
+
const other = writeSessionFile(dir, "sess-other");
|
|
180
|
+
const target = writeSessionFile(dir, "sess-hit");
|
|
181
|
+
findAndInjectParentSession("sess-hit", PARENT, CWD);
|
|
182
|
+
expect(findSessionFileById("sess-hit", CWD)).toBe(target);
|
|
183
|
+
expect(readHeader(target).parentSession).toBe(PARENT);
|
|
184
|
+
expect(readHeader(other).parentSession).toBeUndefined();
|
|
185
|
+
// 只改首行:后续行原样保留
|
|
186
|
+
const lines = fs.readFileSync(target, "utf-8").split("\n");
|
|
187
|
+
expect(lines[1]).toContain('"type":"message"');
|
|
188
|
+
});
|
|
189
|
+
|
|
190
|
+
it("命中但 header 已有 parentSession → 不覆盖(injectParentSession 既有语义)", () => {
|
|
191
|
+
const dir = makeSessionDir();
|
|
192
|
+
const target = writeSessionFile(dir, "sess-hit", { parentSession: "/sessions/first.jsonl" });
|
|
193
|
+
findAndInjectParentSession("sess-hit", PARENT, CWD);
|
|
194
|
+
expect(readHeader(target).parentSession).toBe("/sessions/first.jsonl");
|
|
195
|
+
});
|
|
196
|
+
|
|
197
|
+
it("未命中:不触碰任何文件", () => {
|
|
198
|
+
const dir = makeSessionDir();
|
|
199
|
+
const other = writeSessionFile(dir, "sess-other");
|
|
200
|
+
const before = fs.readFileSync(other, "utf-8");
|
|
201
|
+
findAndInjectParentSession("sess-missing", PARENT, CWD);
|
|
202
|
+
expect(fs.readFileSync(other, "utf-8")).toBe(before);
|
|
203
|
+
expect(readHeader(other).parentSession).toBeUndefined();
|
|
204
|
+
});
|
|
205
|
+
|
|
206
|
+
it("sessionId 或 parentPath 为空 → 直接返回,不定位", () => {
|
|
207
|
+
const dir = makeSessionDir();
|
|
208
|
+
const target = writeSessionFile(dir, "sess-hit");
|
|
209
|
+
findAndInjectParentSession(undefined, PARENT, CWD);
|
|
210
|
+
findAndInjectParentSession("", PARENT, CWD);
|
|
211
|
+
findAndInjectParentSession("sess-hit", "", CWD);
|
|
212
|
+
expect(readHeader(target).parentSession).toBeUndefined();
|
|
213
|
+
});
|
|
214
|
+
});
|
|
@@ -0,0 +1,243 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 测试 spawnOnce close 分支的 jsonl 交叉校验
|
|
3
|
+
*(opsx-subarch-cmds-late 7.3,spec: subagent-spawn-runtime「once 模式系统性失败 jsonl 交叉校验」)
|
|
4
|
+
*
|
|
5
|
+
* 法2 缺口:once 后台模式下子进程加载崩溃(如依赖丢失)经 bash 包装后 exitCode 报 0 且 stderr 为空,
|
|
6
|
+
* F1 的 exitCode/stderr 判定失效,仍呈现 (no output) 假成功。修复把 visible 模式的 jsonl 信号源
|
|
7
|
+
* 接入 once:空占位形态下先等 JSONL_CROSS_CHECK_DELAY_MS(孤儿进程 jsonl 尾刷容忍窗),
|
|
8
|
+
* 再按 stdout 捕获的 sessionId 定位子会话文件、判定终结形态,异常则注入 error 归系统性失败档。
|
|
9
|
+
*
|
|
10
|
+
* 隔离:spawn 与 findSessionFileById 走 mock(定位函数自身的路径推导见 subagent-find-session-file.test.ts),
|
|
11
|
+
* checkSessionJsonlTermination 走真实实现读临时文件——close 分支的判定逻辑与真实信号函数一起被覆盖。
|
|
12
|
+
*/
|
|
13
|
+
import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
|
|
14
|
+
import * as fs from "node:fs";
|
|
15
|
+
import * as os from "node:os";
|
|
16
|
+
import * as path from "node:path";
|
|
17
|
+
import { EventEmitter } from "node:events";
|
|
18
|
+
|
|
19
|
+
const { findSessionFileByIdMock } = vi.hoisted(() => ({
|
|
20
|
+
findSessionFileByIdMock: vi.fn<(sessionId: string | undefined, cwd: string) => string | undefined>(),
|
|
21
|
+
}));
|
|
22
|
+
|
|
23
|
+
vi.mock("../subagent-utils", () => ({
|
|
24
|
+
getPiCommand: vi.fn(() => ({ command: "node", args: ["/usr/local/bin/pi"] })),
|
|
25
|
+
findSessionFileById: findSessionFileByIdMock,
|
|
26
|
+
}));
|
|
27
|
+
|
|
28
|
+
let mockProc: any;
|
|
29
|
+
vi.mock("node:child_process", async (importOriginal) => {
|
|
30
|
+
const actual = await importOriginal() as any;
|
|
31
|
+
return {
|
|
32
|
+
...actual,
|
|
33
|
+
spawn: vi.fn(() => mockProc),
|
|
34
|
+
};
|
|
35
|
+
});
|
|
36
|
+
|
|
37
|
+
import { spawnOnce, JSONL_CROSS_CHECK_DELAY_MS } from "../subagent-spawn-once";
|
|
38
|
+
import { isSystemicSubagentFailure, isSubagentSuccess } from "../utils";
|
|
39
|
+
|
|
40
|
+
const CWD = "/cwd";
|
|
41
|
+
const SOURCE = "once 模式信号源=jsonl 交叉校验";
|
|
42
|
+
|
|
43
|
+
function createMockProcess() {
|
|
44
|
+
const proc = new EventEmitter() as any;
|
|
45
|
+
proc.stdout = new EventEmitter();
|
|
46
|
+
proc.stderr = new EventEmitter();
|
|
47
|
+
proc.kill = vi.fn();
|
|
48
|
+
proc.killed = false;
|
|
49
|
+
return proc;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
function startOnce(signal?: AbortSignal) {
|
|
53
|
+
return spawnOnce("task", CWD, "/tmp/prompt.md", { tools: ["read"] }, signal);
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
function emitSessionEvent(id: string) {
|
|
57
|
+
mockProc.stdout.emit("data", Buffer.from(`{"type":"session","version":3,"id":"${id}"}\n`));
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/** close + 推进过容忍窗(fake timers 下 Promise 才会落定) */
|
|
61
|
+
async function emitCloseAndSettle(code: number) {
|
|
62
|
+
mockProc.emit("close", code);
|
|
63
|
+
await vi.advanceTimersByTimeAsync(JSONL_CROSS_CHECK_DELAY_MS);
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
let tmpDir = "";
|
|
67
|
+
|
|
68
|
+
/** 写一个真实 session.jsonl:header + 可选 message 事件,返回路径 */
|
|
69
|
+
function writeSessionFile(id: string, withMessage: boolean): string {
|
|
70
|
+
const filePath = path.join(tmpDir, `2026-11-25T00-00-00_${id}.jsonl`);
|
|
71
|
+
const header = JSON.stringify({ type: "session", version: 3, id, cwd: CWD });
|
|
72
|
+
const lines = [header];
|
|
73
|
+
if (withMessage) {
|
|
74
|
+
lines.push(JSON.stringify({ type: "message", message: { role: "assistant", content: [{ type: "text", text: "done" }] } }));
|
|
75
|
+
}
|
|
76
|
+
fs.writeFileSync(filePath, lines.join("\n") + "\n", "utf-8");
|
|
77
|
+
return filePath;
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
beforeEach(() => {
|
|
81
|
+
vi.useFakeTimers();
|
|
82
|
+
mockProc = createMockProcess();
|
|
83
|
+
// 显式重设返回值:vi.clearAllMocks 不清 mockReturnValue,避免用例间污染
|
|
84
|
+
findSessionFileByIdMock.mockReset();
|
|
85
|
+
findSessionFileByIdMock.mockReturnValue(undefined);
|
|
86
|
+
tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "pi-wf-once-"));
|
|
87
|
+
});
|
|
88
|
+
|
|
89
|
+
afterEach(() => {
|
|
90
|
+
vi.useRealTimers();
|
|
91
|
+
fs.rmSync(tmpDir, { recursive: true, force: true });
|
|
92
|
+
});
|
|
93
|
+
|
|
94
|
+
describe("spawnOnce close 分支:空占位形态的 jsonl 交叉校验", () => {
|
|
95
|
+
it("① stdout 空 + 无 session 事件 + exitCode 0 → 注入 error(含「jsonl 交叉校验」「stdout 无 session 事件」),归系统性失败档", async () => {
|
|
96
|
+
const resultPromise = startOnce();
|
|
97
|
+
|
|
98
|
+
await emitCloseAndSettle(0);
|
|
99
|
+
const result = await resultPromise;
|
|
100
|
+
|
|
101
|
+
expect(result.exitCode).toBe(0); // exitCode 保持子进程原值
|
|
102
|
+
expect(result.output).toBe("(no output)"); // 输出占位不变
|
|
103
|
+
expect(result.error).toContain(SOURCE);
|
|
104
|
+
expect(result.error).toContain("stdout 无 session 事件");
|
|
105
|
+
expect(result.error).toContain("exitCode=0");
|
|
106
|
+
expect(result.error).toContain("stderr 空");
|
|
107
|
+
expect(findSessionFileByIdMock).not.toHaveBeenCalled(); // 无 sessionId 不查文件
|
|
108
|
+
expect(isSystemicSubagentFailure(result)).toBe(true);
|
|
109
|
+
expect(isSubagentSuccess(result)).toBe(false);
|
|
110
|
+
});
|
|
111
|
+
|
|
112
|
+
it("①' stderr 非空时 error 如实标注「非空」(不写死「空」)", async () => {
|
|
113
|
+
const resultPromise = startOnce();
|
|
114
|
+
mockProc.stderr.emit("data", Buffer.from("some warning"));
|
|
115
|
+
|
|
116
|
+
await emitCloseAndSettle(0);
|
|
117
|
+
const result = await resultPromise;
|
|
118
|
+
|
|
119
|
+
expect(result.stderr).toBe("some warning");
|
|
120
|
+
expect(result.error).toContain(SOURCE);
|
|
121
|
+
expect(result.error).toContain("stderr 非空");
|
|
122
|
+
});
|
|
123
|
+
|
|
124
|
+
it("② jsonl 存在且含 message 事件 → 不注入 error(不误伤),维持现行为", async () => {
|
|
125
|
+
findSessionFileByIdMock.mockReturnValue(writeSessionFile("sess-ok", true));
|
|
126
|
+
const resultPromise = startOnce();
|
|
127
|
+
emitSessionEvent("sess-ok");
|
|
128
|
+
|
|
129
|
+
await emitCloseAndSettle(0);
|
|
130
|
+
const result = await resultPromise;
|
|
131
|
+
|
|
132
|
+
expect(findSessionFileByIdMock).toHaveBeenCalledWith("sess-ok", CWD);
|
|
133
|
+
expect(result.error).toBeUndefined();
|
|
134
|
+
expect(result.exitCode).toBe(0);
|
|
135
|
+
expect(result.output).toBe("(no output)");
|
|
136
|
+
expect(result.subSessionId).toBe("sess-ok");
|
|
137
|
+
expect(isSystemicSubagentFailure(result)).toBe(false);
|
|
138
|
+
expect(isSubagentSuccess(result)).toBe(true);
|
|
139
|
+
});
|
|
140
|
+
|
|
141
|
+
it("③ jsonl 存在但无 message 事件 → 注入 error(含 sessionId 与判定原因),归系统性失败档", async () => {
|
|
142
|
+
findSessionFileByIdMock.mockReturnValue(writeSessionFile("sess-nomsg", false));
|
|
143
|
+
const resultPromise = startOnce();
|
|
144
|
+
emitSessionEvent("sess-nomsg");
|
|
145
|
+
|
|
146
|
+
await emitCloseAndSettle(0);
|
|
147
|
+
const result = await resultPromise;
|
|
148
|
+
|
|
149
|
+
expect(result.error).toContain(SOURCE);
|
|
150
|
+
expect(result.error).toContain("sess-nomsg");
|
|
151
|
+
expect(result.error).toContain("无 message 事件");
|
|
152
|
+
expect(isSystemicSubagentFailure(result)).toBe(true);
|
|
153
|
+
expect(isSubagentSuccess(result)).toBe(false);
|
|
154
|
+
});
|
|
155
|
+
|
|
156
|
+
it("③' 有 session 事件但 session 文件缺失(定位未命中)→ 注入 error(含 sessionId 与「缺失」)", async () => {
|
|
157
|
+
findSessionFileByIdMock.mockReturnValue(undefined);
|
|
158
|
+
const resultPromise = startOnce();
|
|
159
|
+
emitSessionEvent("sess-lost");
|
|
160
|
+
|
|
161
|
+
await emitCloseAndSettle(0);
|
|
162
|
+
const result = await resultPromise;
|
|
163
|
+
|
|
164
|
+
expect(findSessionFileByIdMock).toHaveBeenCalledWith("sess-lost", CWD);
|
|
165
|
+
expect(result.error).toContain(SOURCE);
|
|
166
|
+
expect(result.error).toContain("sess-lost");
|
|
167
|
+
expect(result.error).toContain("缺失");
|
|
168
|
+
expect(isSystemicSubagentFailure(result)).toBe(true);
|
|
169
|
+
});
|
|
170
|
+
|
|
171
|
+
it("正常路径(有 assistant 文本)零变化:close 后立即 resolve,不等待、不交叉校验", async () => {
|
|
172
|
+
const resultPromise = startOnce();
|
|
173
|
+
emitSessionEvent("sess-text");
|
|
174
|
+
mockProc.stdout.emit(
|
|
175
|
+
"data",
|
|
176
|
+
Buffer.from('{"type":"message_end","message":{"role":"assistant","content":[{"type":"text","text":"hello"}]}}\n'),
|
|
177
|
+
);
|
|
178
|
+
mockProc.emit("close", 0);
|
|
179
|
+
|
|
180
|
+
// 不推进计时器,Promise 也应直接落定(未被容忍窗挂住)
|
|
181
|
+
const result = await resultPromise;
|
|
182
|
+
|
|
183
|
+
expect(result.output).toContain("hello");
|
|
184
|
+
expect(result.error).toBeUndefined();
|
|
185
|
+
expect(findSessionFileByIdMock).not.toHaveBeenCalled();
|
|
186
|
+
});
|
|
187
|
+
|
|
188
|
+
it("正文恰好含占位字面量的真实输出不触发交叉校验(触发条件=未收集到任何文本)", async () => {
|
|
189
|
+
const resultPromise = startOnce();
|
|
190
|
+
emitSessionEvent("sess-literal");
|
|
191
|
+
mockProc.stdout.emit(
|
|
192
|
+
"data",
|
|
193
|
+
Buffer.from('{"type":"message_end","message":{"role":"assistant","content":[{"type":"text","text":"result: (no output)"}]}}\n'),
|
|
194
|
+
);
|
|
195
|
+
mockProc.emit("close", 0);
|
|
196
|
+
|
|
197
|
+
const result = await resultPromise;
|
|
198
|
+
|
|
199
|
+
expect(result.output).toBe("result: (no output)");
|
|
200
|
+
expect(result.error).toBeUndefined();
|
|
201
|
+
expect(findSessionFileByIdMock).not.toHaveBeenCalled();
|
|
202
|
+
});
|
|
203
|
+
|
|
204
|
+
it("容忍窗:close 后窗口内不 resolve,推进到 JSONL_CROSS_CHECK_DELAY_MS(500)后才落定", async () => {
|
|
205
|
+
expect(JSONL_CROSS_CHECK_DELAY_MS).toBe(500);
|
|
206
|
+
const resultPromise = startOnce();
|
|
207
|
+
let settled = false;
|
|
208
|
+
void resultPromise.then(() => { settled = true; });
|
|
209
|
+
|
|
210
|
+
mockProc.emit("close", 0);
|
|
211
|
+
await vi.advanceTimersByTimeAsync(JSONL_CROSS_CHECK_DELAY_MS - 1);
|
|
212
|
+
expect(settled).toBe(false);
|
|
213
|
+
expect(findSessionFileByIdMock).not.toHaveBeenCalled();
|
|
214
|
+
|
|
215
|
+
await vi.advanceTimersByTimeAsync(1);
|
|
216
|
+
await resultPromise;
|
|
217
|
+
expect(settled).toBe(true);
|
|
218
|
+
await expect(resultPromise).resolves.toMatchObject({ error: expect.stringContaining(SOURCE) });
|
|
219
|
+
});
|
|
220
|
+
|
|
221
|
+
it("等待窗内被 abort 先行 resolve → 结果取 abort,交叉校验不覆盖", async () => {
|
|
222
|
+
const controller = new AbortController();
|
|
223
|
+
const resultPromise = startOnce(controller.signal);
|
|
224
|
+
emitSessionEvent("sess-abort");
|
|
225
|
+
mockProc.emit("close", 0);
|
|
226
|
+
|
|
227
|
+
controller.abort();
|
|
228
|
+
await vi.advanceTimersByTimeAsync(JSONL_CROSS_CHECK_DELAY_MS);
|
|
229
|
+
const result = await resultPromise;
|
|
230
|
+
|
|
231
|
+
expect(result.stderr).toContain("aborted");
|
|
232
|
+
expect(result.error).toBeUndefined();
|
|
233
|
+
expect(findSessionFileByIdMock).not.toHaveBeenCalled();
|
|
234
|
+
});
|
|
235
|
+
});
|
|
236
|
+
|
|
237
|
+
describe("barrel 导出防回归", () => {
|
|
238
|
+
it("crossCheckOnceSessionJsonl 经 index.ts 显式列名导出", async () => {
|
|
239
|
+
const barrel = await import("../index");
|
|
240
|
+
expect(typeof barrel.crossCheckOnceSessionJsonl).toBe("function");
|
|
241
|
+
expect(typeof barrel.checkSessionJsonlTermination).toBe("function");
|
|
242
|
+
});
|
|
243
|
+
});
|
|
@@ -26,7 +26,16 @@ vi.mock("node:child_process", async (importOriginal) => {
|
|
|
26
26
|
};
|
|
27
27
|
});
|
|
28
28
|
|
|
29
|
-
import { spawnOnce } from "../subagent-spawn-once";
|
|
29
|
+
import { spawnOnce, JSONL_CROSS_CHECK_DELAY_MS } from "../subagent-spawn-once";
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* 空占位形态的 close 路径会先等 JSONL_CROSS_CHECK_DELAY_MS(孤儿进程 jsonl 尾刷容忍窗)
|
|
33
|
+
* 再做 jsonl 交叉校验后 resolve——fake timers 下必须推进过等待窗 Promise 才会落定。
|
|
34
|
+
*/
|
|
35
|
+
async function emitCloseAndSettle(code: number): Promise<void> {
|
|
36
|
+
mockProc.emit("close", code);
|
|
37
|
+
await vi.advanceTimersByTimeAsync(JSONL_CROSS_CHECK_DELAY_MS);
|
|
38
|
+
}
|
|
30
39
|
|
|
31
40
|
function createMockProcess() {
|
|
32
41
|
const proc = new EventEmitter() as any;
|
|
@@ -69,7 +78,7 @@ describe("spawnOnce", () => {
|
|
|
69
78
|
const resultPromise = spawnOnce("task", "/cwd", "/tmp/prompt.md", { tools: ["read"] }, undefined, undefined, undefined, onEvent);
|
|
70
79
|
|
|
71
80
|
mockProc.stdout.emit("data", Buffer.from('{"type":"tool_execution_start","toolName":"read"}\n'));
|
|
72
|
-
|
|
81
|
+
await emitCloseAndSettle(0);
|
|
73
82
|
|
|
74
83
|
await resultPromise;
|
|
75
84
|
expect(onEvent).toHaveBeenCalledWith(expect.objectContaining({ type: "tool", toolName: "read" }));
|
|
@@ -80,7 +89,7 @@ describe("spawnOnce", () => {
|
|
|
80
89
|
const resultPromise = spawnOnce("task", "/cwd", "/tmp/prompt.md", { tools: ["read"] }, undefined, undefined, undefined, onEvent);
|
|
81
90
|
|
|
82
91
|
mockProc.stdout.emit("data", Buffer.from('{"type":"message_update","assistantMessageEvent":{"type":"text_delta","delta":"thinking..."}}\n'));
|
|
83
|
-
|
|
92
|
+
await emitCloseAndSettle(0);
|
|
84
93
|
|
|
85
94
|
await resultPromise;
|
|
86
95
|
expect(onEvent).toHaveBeenCalledWith(expect.objectContaining({ type: "thinking" }));
|
|
@@ -124,7 +133,8 @@ describe("spawnOnce", () => {
|
|
|
124
133
|
it("没有输出时返回 (no output)", async () => {
|
|
125
134
|
const resultPromise = spawnOnce("task", "/cwd", "/tmp/prompt.md", { tools: ["read"] });
|
|
126
135
|
|
|
127
|
-
|
|
136
|
+
// 注:此形态现会额外注入 error(jsonl 交叉校验),断言见 subagent-spawn-once-jsonl-crosscheck.test.ts
|
|
137
|
+
await emitCloseAndSettle(0);
|
|
128
138
|
|
|
129
139
|
const result = await resultPromise;
|
|
130
140
|
expect(result.output).toBe("(no output)");
|
|
@@ -133,7 +143,7 @@ describe("spawnOnce", () => {
|
|
|
133
143
|
it("model override 传递给 pi 命令", async () => {
|
|
134
144
|
const resultPromise = spawnOnce("task", "/cwd", "/tmp/prompt.md", { tools: ["read"] }, undefined, "gpt-4");
|
|
135
145
|
|
|
136
|
-
|
|
146
|
+
await emitCloseAndSettle(0);
|
|
137
147
|
await resultPromise;
|
|
138
148
|
|
|
139
149
|
const args = spawnCalls[0][1];
|
|
@@ -144,7 +154,7 @@ describe("spawnOnce", () => {
|
|
|
144
154
|
it("agentDef.model 作为默认 model", async () => {
|
|
145
155
|
const resultPromise = spawnOnce("task", "/cwd", "/tmp/prompt.md", { tools: ["read"], model: "claude-3" });
|
|
146
156
|
|
|
147
|
-
|
|
157
|
+
await emitCloseAndSettle(0);
|
|
148
158
|
await resultPromise;
|
|
149
159
|
|
|
150
160
|
const args = spawnCalls[0][1];
|