@zhushanwen/pi-subagent-workflow 7.1.0 → 7.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +1 -1
- package/src/execution/__tests__/execute-nesting.test.ts +1 -1
- package/src/execution/__tests__/helpers/spawn-mock.ts +2 -0
- package/src/execution/__tests__/manifest-parentid.test.ts +117 -0
- package/src/execution/__tests__/record-store.test.ts +42 -2
- package/src/execution/__tests__/recursive-visibility-baseline.test.ts +340 -0
- package/src/execution/__tests__/recursive-visibility-env.test.ts +275 -0
- package/src/execution/__tests__/session-runner-schema-env.test.ts +5 -2
- package/src/execution/__tests__/timeout-integration.test.ts +2 -0
- package/src/execution/__tests__/tool-action.test.ts +26 -0
- package/src/execution/finalize-record.ts +1 -0
- package/src/execution/manifest-store.ts +6 -1
- package/src/execution/path-encoding.ts +12 -4
- package/src/execution/session-runner.ts +26 -1
- package/src/execution/subagent-service.ts +93 -10
- package/src/interface/subagent-actions.ts +15 -1
- package/src/interface/subagents.ts +1 -1
- package/src/orchestration/__tests__/jsonl-run-store-session-file.test.ts +52 -0
- package/src/orchestration/jsonl-run-store.ts +20 -1
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@zhushanwen/pi-subagent-workflow",
|
|
3
|
-
"version": "7.
|
|
3
|
+
"version": "7.3.0",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"main": "index.ts",
|
|
6
6
|
"description": "Unified subagent execution and multi-agent workflow orchestration for Pi — spawned-process agent runtime with sync/background modes, stateful workflow management with persistence, state machine, and execution tracing.",
|
|
@@ -91,7 +91,7 @@ vi.mock("node:fs", async () => {
|
|
|
91
91
|
// (finalizeRecord 收尾删 .alive)。其余导出(readAliveMarker/isProcessAlive)保留真实实现
|
|
92
92
|
// (worktree-manager/record-store 用,本组用例不涉及但保留以避免间接报错)。
|
|
93
93
|
vi.mock("../alive-store.ts", async (importOriginal) => {
|
|
94
|
-
const actual = await importOriginal<typeof import("../
|
|
94
|
+
const actual = await importOriginal<typeof import("../alive-store.ts")>();
|
|
95
95
|
return {
|
|
96
96
|
...actual,
|
|
97
97
|
writeAliveMarker: vi.fn(),
|
|
@@ -204,6 +204,8 @@ export function makeCtx(overrides: Partial<SessionRunnerContext> = {}): SessionR
|
|
|
204
204
|
skillDirs: [],
|
|
205
205
|
mainCwd: "/tmp/test",
|
|
206
206
|
mainSessionFile: undefined,
|
|
207
|
+
sessionRootId: "root-session-test",
|
|
208
|
+
rootCwd: "/tmp/test",
|
|
207
209
|
...overrides,
|
|
208
210
|
};
|
|
209
211
|
}
|
|
@@ -0,0 +1,117 @@
|
|
|
1
|
+
// ManifestStore — parentRecordId 落盘测试(M3a)。
|
|
2
|
+
//
|
|
3
|
+
// 验证 M3a 三条契约:
|
|
4
|
+
// 1. 新 record 落盘含 parentRecordId(depth>=1 subagent 读回直接父 record id)
|
|
5
|
+
// 2. 旧 manifest JSON(无 parentRecordId 字段)readManifest 仍有效(向后兼容)
|
|
6
|
+
// 3. isValidManifest 校验不改(5 必填不变,parentRecordId optional)
|
|
7
|
+
//
|
|
8
|
+
// isValidManifest 私有未 export——通过 readManifest 等价验证:readManifest 内部
|
|
9
|
+
// `isValidManifest(parsed) ? parsed : null`,非 null ⟺ 校验通过。不 export 私有函数
|
|
10
|
+
// 避免扩大公共 API 表面(M3a C1 约束:不改 isValidManifest,仅 2 行代码改动)。
|
|
11
|
+
|
|
12
|
+
import * as fs from "node:fs";
|
|
13
|
+
import * as os from "node:os";
|
|
14
|
+
import * as path from "node:path";
|
|
15
|
+
import { afterEach, beforeEach, describe, expect, it } from "vitest";
|
|
16
|
+
|
|
17
|
+
import { ManifestStore, type ManifestRecord } from "../manifest-store.ts";
|
|
18
|
+
|
|
19
|
+
/** 构造最小合法 ManifestRecord(5 必填),optional 字段按 overrides 传入。 */
|
|
20
|
+
function makeBaseManifest(overrides: Partial<ManifestRecord> = {}): ManifestRecord {
|
|
21
|
+
return {
|
|
22
|
+
id: "rec-test",
|
|
23
|
+
rootSessionId: "session-main",
|
|
24
|
+
agentName: "worker",
|
|
25
|
+
status: "completed",
|
|
26
|
+
createdAt: 1000,
|
|
27
|
+
...overrides,
|
|
28
|
+
};
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
describe("ManifestStore — parentRecordId 落盘 (M3a)", () => {
|
|
32
|
+
let tmpDir: string;
|
|
33
|
+
let store: ManifestStore;
|
|
34
|
+
|
|
35
|
+
beforeEach(() => {
|
|
36
|
+
tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "manifest-parentid-"));
|
|
37
|
+
store = new ManifestStore(tmpDir);
|
|
38
|
+
});
|
|
39
|
+
|
|
40
|
+
afterEach(() => {
|
|
41
|
+
fs.rmSync(tmpDir, { recursive: true, force: true });
|
|
42
|
+
});
|
|
43
|
+
|
|
44
|
+
// ── TC-m3a-new-record-parentid ──
|
|
45
|
+
it("新 record 落盘含 parentRecordId(depth>=1 读回直接父 record id)", async () => {
|
|
46
|
+
const record = makeBaseManifest({
|
|
47
|
+
id: "rec-child",
|
|
48
|
+
parentRecordId: "sa-parent-1",
|
|
49
|
+
});
|
|
50
|
+
await store.writeManifest(record);
|
|
51
|
+
|
|
52
|
+
const readBack = await store.readManifest("rec-child");
|
|
53
|
+
expect(readBack).not.toBeNull();
|
|
54
|
+
expect(readBack?.parentRecordId).toBe("sa-parent-1");
|
|
55
|
+
});
|
|
56
|
+
|
|
57
|
+
it("顶层 record(parentRecordId 缺失)落盘读回仍 undefined", async () => {
|
|
58
|
+
// 顶层 subagent parentRecordId=undefined(父是 main,main 无 record)
|
|
59
|
+
const record = makeBaseManifest({ id: "rec-top" });
|
|
60
|
+
await store.writeManifest(record);
|
|
61
|
+
|
|
62
|
+
const readBack = await store.readManifest("rec-top");
|
|
63
|
+
expect(readBack).not.toBeNull();
|
|
64
|
+
expect(readBack?.parentRecordId).toBeUndefined();
|
|
65
|
+
});
|
|
66
|
+
|
|
67
|
+
// ── TC-m3a-old-manifest-compat ──
|
|
68
|
+
it("旧 manifest JSON(无 parentRecordId)readManifest 返有效(isValidManifest 通过)", async () => {
|
|
69
|
+
// 手写旧版本格式 manifest(无 parentRecordId 字段),模拟旧 subagent-workflow 写的磁盘文件
|
|
70
|
+
const oldManifest = {
|
|
71
|
+
id: "rec-old",
|
|
72
|
+
rootSessionId: "session-main",
|
|
73
|
+
agentName: "worker",
|
|
74
|
+
status: "completed",
|
|
75
|
+
createdAt: 2000,
|
|
76
|
+
// 无 parentRecordId —— 旧版本写的
|
|
77
|
+
};
|
|
78
|
+
fs.writeFileSync(
|
|
79
|
+
path.join(tmpDir, "rec-old.json"),
|
|
80
|
+
JSON.stringify(oldManifest),
|
|
81
|
+
"utf-8",
|
|
82
|
+
);
|
|
83
|
+
|
|
84
|
+
const readBack = await store.readManifest("rec-old");
|
|
85
|
+
// readManifest 内 isValidManifest(parsed) ? parsed : null —— 非 null 即 5 必填校验通过
|
|
86
|
+
expect(readBack).not.toBeNull();
|
|
87
|
+
expect(readBack?.id).toBe("rec-old");
|
|
88
|
+
expect(readBack?.parentRecordId).toBeUndefined();
|
|
89
|
+
});
|
|
90
|
+
|
|
91
|
+
// ── TC-m3a-isvalidmanifest-unchanged ──
|
|
92
|
+
it("isValidManifest 不改:含/不含 parentRecordId 均通过(5 必填不变)", async () => {
|
|
93
|
+
// isValidManifest 私有,通过 readManifest 等价验证(非 null ⟺ 校验通过)。
|
|
94
|
+
// 含 parentRecordId —— 新格式
|
|
95
|
+
const withParent = makeBaseManifest({
|
|
96
|
+
id: "rec-with-parent",
|
|
97
|
+
parentRecordId: "sa-x",
|
|
98
|
+
});
|
|
99
|
+
await store.writeManifest(withParent);
|
|
100
|
+
expect(await store.readManifest("rec-with-parent")).not.toBeNull();
|
|
101
|
+
|
|
102
|
+
// 不含 parentRecordId —— 仅 5 必填(旧格式 / 顶层 record)
|
|
103
|
+
const minimal = {
|
|
104
|
+
id: "rec-minimal",
|
|
105
|
+
rootSessionId: "session-main",
|
|
106
|
+
agentName: "worker",
|
|
107
|
+
status: "completed",
|
|
108
|
+
createdAt: 3000,
|
|
109
|
+
};
|
|
110
|
+
fs.writeFileSync(
|
|
111
|
+
path.join(tmpDir, "rec-minimal.json"),
|
|
112
|
+
JSON.stringify(minimal),
|
|
113
|
+
"utf-8",
|
|
114
|
+
);
|
|
115
|
+
expect(await store.readManifest("rec-minimal")).not.toBeNull();
|
|
116
|
+
});
|
|
117
|
+
});
|
|
@@ -20,7 +20,9 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
|
|
20
20
|
import { writeAliveMarker } from "../alive-store.ts";
|
|
21
21
|
import { createRecord } from "../execution-record.ts";
|
|
22
22
|
import { writeFinalized } from "../finalized-marker.ts";
|
|
23
|
-
import type { ManifestRecord
|
|
23
|
+
import type { ManifestRecord } from "../manifest-store.ts";
|
|
24
|
+
import { ManifestStore } from "../manifest-store.ts";
|
|
25
|
+
import { getSubagentRecordsDir, getSubagentSessionDir } from "../path-encoding.ts";
|
|
24
26
|
import type { StatusFilter } from "../record-store.ts";
|
|
25
27
|
import { RecordStore } from "../record-store.ts";
|
|
26
28
|
import { writeCancelledTombstone } from "../tombstone-store.ts";
|
|
@@ -45,7 +47,7 @@ function makeRecord(over: Partial<ExecutionRecord> = {}): ExecutionRecord {
|
|
|
45
47
|
*/
|
|
46
48
|
function writeSessionJsonl(
|
|
47
49
|
filePath: string,
|
|
48
|
-
identity: { id: string; agent: string; mode: "sync" | "background"; task: string; startedAt: number; rootSessionId?: string; lastTs?: number },
|
|
50
|
+
identity: { id: string; agent: string; mode: "sync" | "background"; task: string; startedAt: number; rootSessionId?: string; parentRecordId?: string; depth?: number; lastTs?: number },
|
|
49
51
|
assistantText = "result text",
|
|
50
52
|
): void {
|
|
51
53
|
const lastTs = identity.lastTs ?? identity.startedAt + 1000;
|
|
@@ -60,6 +62,8 @@ function writeSessionJsonl(
|
|
|
60
62
|
startedAt: identity.startedAt,
|
|
61
63
|
};
|
|
62
64
|
if (identity.rootSessionId !== undefined) identityData.rootSessionId = identity.rootSessionId;
|
|
65
|
+
if (identity.parentRecordId !== undefined) identityData.parentRecordId = identity.parentRecordId;
|
|
66
|
+
if (identity.depth !== undefined) identityData.depth = identity.depth;
|
|
63
67
|
const identityEntry = JSON.stringify({
|
|
64
68
|
type: "custom",
|
|
65
69
|
id: "id-1",
|
|
@@ -189,6 +193,42 @@ describe("RecordStore", () => {
|
|
|
189
193
|
const found = store.collectRecords(100).find((r) => r.id === "dup-1");
|
|
190
194
|
expect(found?.status).toBe("running"); // 内存 running 覆盖磁盘 crashed
|
|
191
195
|
});
|
|
196
|
+
|
|
197
|
+
it("[MF-3/S-20] 跨进程组合:子进程(worktree)写入 enc(ROOT) 的深层 record 被 ROOT store 重建,同 rootSessionId 全树可见、他树被排除", () => {
|
|
198
|
+
// MF-3 修复后:worktree 子进程把其子 record 的 session 文件写到统一 enc(ROOT cwd) 段,
|
|
199
|
+
// ROOT 进程的 store 扫同一目录重建(旧实现子进程写到 enc(checkout) 段,此处为空)。
|
|
200
|
+
const rootCwd = "/Users/x/root-proj";
|
|
201
|
+
const sessionsDir = getSubagentSessionDir(tmpDir, rootCwd);
|
|
202
|
+
const recordsDir = getSubagentRecordsDir(tmpDir, rootCwd);
|
|
203
|
+
|
|
204
|
+
// 父 record A(ROOT 自己 spawn,parentRecordId 缺省=顶层)+ 孙 record C(B 子进程写入,
|
|
205
|
+
// 同 rootSessionId、parentRecordId=A、depth=2)+ 他树 record X(rootSessionId 不同)
|
|
206
|
+
fs.mkdirSync(sessionsDir, { recursive: true });
|
|
207
|
+
writeSessionJsonl(path.join(sessionsDir, "2026-01-01-uuid-a.jsonl"), {
|
|
208
|
+
id: "sa-A", agent: "worker", mode: "background", task: "level1", startedAt: 1000, rootSessionId: "root-main",
|
|
209
|
+
});
|
|
210
|
+
writeSessionJsonl(path.join(sessionsDir, "2026-01-01-uuid-c.jsonl"), {
|
|
211
|
+
id: "sa-C", agent: "worker", mode: "background", task: "level3", startedAt: 3000,
|
|
212
|
+
rootSessionId: "root-main", parentRecordId: "sa-A", depth: 2,
|
|
213
|
+
});
|
|
214
|
+
writeSessionJsonl(path.join(sessionsDir, "2026-01-01-uuid-x.jsonl"), {
|
|
215
|
+
id: "sa-X", agent: "worker", mode: "background", task: "other root", startedAt: 4000, rootSessionId: "root-other",
|
|
216
|
+
});
|
|
217
|
+
|
|
218
|
+
// ROOT 进程的 store:sessionsDir/recordsDir 与子进程写盘目录同段(getSubagentSessionDir 同源)
|
|
219
|
+
const store = new RecordStore(sessionsDir, new ManifestStore(recordsDir), undefined);
|
|
220
|
+
const recs = store.collectRecords(10, "all", "root-main");
|
|
221
|
+
const ids = recs.map((r) => r.id);
|
|
222
|
+
|
|
223
|
+
// 全树可见:A(顶层)与 C(深度 2,跨进程写入)都在列表,身份字段正确
|
|
224
|
+
expect(ids).toContain("sa-A");
|
|
225
|
+
expect(ids).toContain("sa-C");
|
|
226
|
+
const c = recs.find((r) => r.id === "sa-C");
|
|
227
|
+
expect(c?.parentRecordId).toBe("sa-A");
|
|
228
|
+
expect(c?.depth).toBe(2);
|
|
229
|
+
// 他树 record 被 rootSessionFilter 排除(隔离不破坏)
|
|
230
|
+
expect(ids).not.toContain("sa-X");
|
|
231
|
+
});
|
|
192
232
|
});
|
|
193
233
|
|
|
194
234
|
// ============================================================
|
|
@@ -0,0 +1,340 @@
|
|
|
1
|
+
// src/execution/__tests__/recursive-visibility-baseline.test.ts
|
|
2
|
+
//
|
|
3
|
+
// 递归 subagent 跨进程身份:进程级基线兜底验证(ALS 断裂修复)。
|
|
4
|
+
//
|
|
5
|
+
// 背景(2026-08-11 实测):pi RPC mode 的 stdin JSONL 是事件回调式读取
|
|
6
|
+
// (attachJsonlLineReader → stream.on("data")),每个 RPC 命令是独立异步链。
|
|
7
|
+
// initSession 里 execCtxAls.enterWith 的 store 不会贯穿到后续 tool 调用事件——
|
|
8
|
+
// 递归第二层 subagent 的 parentRecordId/depth 丢失(rootSessionId 是实例字段所以正确)。
|
|
9
|
+
//
|
|
10
|
+
// 修复:execCtxBaseline / forkDepthBaseline 实例字段(initSession 从 env 读取,
|
|
11
|
+
// 与 sessionRootId 同机制),createRecordForMode / 嵌套护栏读 ALS store 失败时兜底。
|
|
12
|
+
// 本文件验证:
|
|
13
|
+
// 1. 有 env(子进程身份)→ execute 创建的 record parentRecordId/depth 来自基线
|
|
14
|
+
// 2. 无 env(根进程)→ parentRecordId undefined / depth 0(顶层)
|
|
15
|
+
// 3. execCtxAls.run 的 store 优先于基线(并发链语义不回归)
|
|
16
|
+
// 4. forkDepth 基线:env PI_SUBAGENT_FORK_DEPTH → fork spawn env 递增
|
|
17
|
+
//
|
|
18
|
+
// mock 策略与 execute-nesting.test.ts 一致(spawn → FakeChild,fs 同步方法 mock,
|
|
19
|
+
// temp-prompt / alive-store / finalized-marker / manifest-store mock)。
|
|
20
|
+
|
|
21
|
+
import type { PassThrough } from "node:stream";
|
|
22
|
+
|
|
23
|
+
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
|
24
|
+
|
|
25
|
+
// ── mock modules(同 execute-nesting.test.ts)──
|
|
26
|
+
|
|
27
|
+
vi.mock("node:child_process", async () => {
|
|
28
|
+
const { EventEmitter } = await import("node:events");
|
|
29
|
+
const { PassThrough } = await import("node:stream");
|
|
30
|
+
|
|
31
|
+
class FakeChild extends EventEmitter {
|
|
32
|
+
pid = 12345;
|
|
33
|
+
stdout = new PassThrough();
|
|
34
|
+
stderr = new PassThrough();
|
|
35
|
+
killed = false;
|
|
36
|
+
killSignal: string | undefined;
|
|
37
|
+
kill(sig?: string): boolean {
|
|
38
|
+
this.killed = true;
|
|
39
|
+
this.killSignal = sig;
|
|
40
|
+
return true;
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
return {
|
|
45
|
+
spawn: vi.fn(() => new FakeChild()),
|
|
46
|
+
execFileSync: vi.fn(() => ""),
|
|
47
|
+
};
|
|
48
|
+
});
|
|
49
|
+
|
|
50
|
+
vi.mock("node:fs", async () => {
|
|
51
|
+
const actual = await import("node:fs");
|
|
52
|
+
return {
|
|
53
|
+
default: {
|
|
54
|
+
...actual,
|
|
55
|
+
mkdirSync: vi.fn(),
|
|
56
|
+
existsSync: vi.fn(() => false),
|
|
57
|
+
appendFileSync: vi.fn(),
|
|
58
|
+
writeFileSync: vi.fn(),
|
|
59
|
+
readdirSync: vi.fn(() => []),
|
|
60
|
+
},
|
|
61
|
+
mkdirSync: vi.fn(),
|
|
62
|
+
existsSync: vi.fn(() => false),
|
|
63
|
+
appendFileSync: vi.fn(),
|
|
64
|
+
writeFileSync: vi.fn(),
|
|
65
|
+
readdirSync: vi.fn(() => []),
|
|
66
|
+
promises: actual.promises,
|
|
67
|
+
};
|
|
68
|
+
});
|
|
69
|
+
|
|
70
|
+
vi.mock("../alive-store.ts", async (importOriginal) => {
|
|
71
|
+
const actual = await importOriginal<typeof import("../alive-store.ts")>();
|
|
72
|
+
return {
|
|
73
|
+
...actual,
|
|
74
|
+
writeAliveMarker: vi.fn(),
|
|
75
|
+
removeAliveMarker: vi.fn(),
|
|
76
|
+
};
|
|
77
|
+
});
|
|
78
|
+
|
|
79
|
+
vi.mock("../finalized-marker.ts", () => ({
|
|
80
|
+
writeFinalized: vi.fn(),
|
|
81
|
+
readFinalized: vi.fn(() => false),
|
|
82
|
+
}));
|
|
83
|
+
|
|
84
|
+
vi.mock("../manifest-store.ts", () => {
|
|
85
|
+
class FakeManifestStore {
|
|
86
|
+
writeManifest = vi.fn(async () => {});
|
|
87
|
+
readManifest = vi.fn(async () => null);
|
|
88
|
+
listAllSync = vi.fn(() => []);
|
|
89
|
+
recoverTmpFiles = vi.fn(async () => []);
|
|
90
|
+
}
|
|
91
|
+
// vi.fn 包裹:构造参数(recordsDir)可从 mock.calls 断言([MF-3] 目录统一验证)。
|
|
92
|
+
// 注意用普通 function(箭头函数不能被 new 调用)。
|
|
93
|
+
return { ManifestStore: vi.fn(function (_recordsDir: string) { return new FakeManifestStore(); }) };
|
|
94
|
+
});
|
|
95
|
+
|
|
96
|
+
vi.mock("../temp-prompt.ts", () => ({
|
|
97
|
+
writePromptToTempFile: vi.fn(async (agent: string) => {
|
|
98
|
+
const safeName = agent.replace(/[^\w.-]+/g, "_");
|
|
99
|
+
return { dir: `/tmp/fake-${safeName}`, filePath: `/tmp/fake-${safeName}/prompt-${safeName}.md` };
|
|
100
|
+
}),
|
|
101
|
+
cleanupTempPrompt: vi.fn(async () => {}),
|
|
102
|
+
}));
|
|
103
|
+
|
|
104
|
+
import { spawn } from "node:child_process";
|
|
105
|
+
|
|
106
|
+
import { ModelConfigService } from "../model-config-service.ts";
|
|
107
|
+
import type { ModelInfo, ModelRegistryLike } from "../model-resolver.ts";
|
|
108
|
+
import { ManifestStore } from "../manifest-store.ts";
|
|
109
|
+
import { getSubagentRecordsDir, getSubagentSessionDir } from "../path-encoding.ts";
|
|
110
|
+
import type { RecordStore } from "../record-store.ts";
|
|
111
|
+
import { SubagentService } from "../subagent-service.ts";
|
|
112
|
+
|
|
113
|
+
const mockSpawn = vi.mocked(spawn);
|
|
114
|
+
|
|
115
|
+
// ── 身份 env 名(与 subagent-service.ts 常量一致,避免魔法字符串)──
|
|
116
|
+
const ENV_ROOT_SESSION_ID = "PI_SUBAGENT_ROOT_SESSION_ID";
|
|
117
|
+
const ENV_SELF_RECORD_ID = "PI_SUBAGENT_SELF_RECORD_ID";
|
|
118
|
+
const ENV_DEPTH = "PI_SUBAGENT_DEPTH";
|
|
119
|
+
const ENV_ROOT_CWD = "PI_SUBAGENT_ROOT_CWD";
|
|
120
|
+
const ENV_FORK_DEPTH = "PI_SUBAGENT_FORK_DEPTH";
|
|
121
|
+
|
|
122
|
+
interface FakeChild {
|
|
123
|
+
pid: number;
|
|
124
|
+
stdout: PassThrough;
|
|
125
|
+
stderr: PassThrough;
|
|
126
|
+
killed: boolean;
|
|
127
|
+
killSignal: string | undefined;
|
|
128
|
+
kill(sig?: string): boolean;
|
|
129
|
+
emit(event: string, ...args: unknown[]): boolean;
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
function lastSpawnedChild(): FakeChild {
|
|
133
|
+
const result = mockSpawn.mock.results.at(-1);
|
|
134
|
+
if (!result) throw new Error("spawn was not called yet");
|
|
135
|
+
return result.value as FakeChild;
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
function getLastSpawnEnv(): Record<string, string | undefined> {
|
|
139
|
+
return (mockSpawn.mock.calls.at(-1)?.[2]?.env as Record<string, string | undefined>) ?? {};
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
async function waitForSpawn(timeoutMs = 1000): Promise<void> {
|
|
143
|
+
const start = Date.now();
|
|
144
|
+
while (mockSpawn.mock.results.length === 0) {
|
|
145
|
+
if (Date.now() - start > timeoutMs) {
|
|
146
|
+
throw new Error(`spawn was not called within ${timeoutMs}ms`);
|
|
147
|
+
}
|
|
148
|
+
await new Promise((r) => setTimeout(r, 2));
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
function sessionHeader(id = "baseline-session"): Record<string, unknown> {
|
|
153
|
+
return { type: "session", id, timestamp: "2026-08-11T00-00-00-000Z", cwd: "/tmp/test" };
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
function emitStdoutLine(child: FakeChild, obj: Record<string, unknown>): void {
|
|
157
|
+
child.stdout.write(`${JSON.stringify(obj)}\n`);
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
/** 驱动 FakeChild 完成:header + 可选事件 + close(0)(runSpawn 自然 resolve)。 */
|
|
161
|
+
async function driveChildToCompletion(child: FakeChild, events: Record<string, unknown>[] = []): Promise<void> {
|
|
162
|
+
emitStdoutLine(child, sessionHeader());
|
|
163
|
+
for (const e of events) emitStdoutLine(child, e);
|
|
164
|
+
child.stdout.end();
|
|
165
|
+
child.stderr.end();
|
|
166
|
+
child.emit("close", 0);
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
// ── 辅助:service 构造 ──
|
|
170
|
+
|
|
171
|
+
function makeEmptyRegistry(): ModelRegistryLike {
|
|
172
|
+
return { getAvailable: () => [], find: () => undefined, hasConfiguredAuth: () => true };
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
function makePi() {
|
|
176
|
+
return { sendMessage: vi.fn(), appendEntry: vi.fn(), events: { emit: vi.fn() } };
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
function setup(env: Record<string, string>): { service: SubagentService; store: RecordStore } {
|
|
180
|
+
const agentDir = "/tmp/baseline-it";
|
|
181
|
+
const modelService = new ModelConfigService({ agentDir });
|
|
182
|
+
modelService.initModel({
|
|
183
|
+
modelRegistry: makeEmptyRegistry(),
|
|
184
|
+
sessionId: "baseline-it",
|
|
185
|
+
ctxModel: { id: "m", name: "M", provider: "p", reasoning: false },
|
|
186
|
+
});
|
|
187
|
+
const service = new SubagentService({
|
|
188
|
+
cwd: agentDir,
|
|
189
|
+
modelService,
|
|
190
|
+
getMainSessionFile: () => "/mock/main-session.jsonl",
|
|
191
|
+
});
|
|
192
|
+
service.initSession({ pi: makePi(), sessionId: "baseline-it" });
|
|
193
|
+
const store = Reflect.get(service, "store") as RecordStore;
|
|
194
|
+
return { service, store };
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
const ctxModel: ModelInfo = { id: "m", name: "M", provider: "p", reasoning: false };
|
|
198
|
+
|
|
199
|
+
/** execCtxAls.run 的 duck-type(绕过 import AsyncLocalStorage)。 */
|
|
200
|
+
interface ExecCtxAls {
|
|
201
|
+
run: <T>(store: { recordId: string | undefined; depth: number }, cb: () => T) => T;
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
// ── 用例 ──
|
|
205
|
+
|
|
206
|
+
describe("进程级基线兜底(ALS 断裂修复,pi 事件回调模型)", () => {
|
|
207
|
+
beforeEach(() => {
|
|
208
|
+
vi.clearAllMocks();
|
|
209
|
+
// 清理身份 env,防用例间泄漏
|
|
210
|
+
for (const k of [ENV_ROOT_SESSION_ID, ENV_SELF_RECORD_ID, ENV_DEPTH, ENV_FORK_DEPTH, ENV_ROOT_CWD]) {
|
|
211
|
+
delete process.env[k];
|
|
212
|
+
}
|
|
213
|
+
});
|
|
214
|
+
|
|
215
|
+
afterEach(() => {
|
|
216
|
+
for (const k of [ENV_ROOT_SESSION_ID, ENV_SELF_RECORD_ID, ENV_DEPTH, ENV_FORK_DEPTH, ENV_ROOT_CWD]) {
|
|
217
|
+
delete process.env[k];
|
|
218
|
+
}
|
|
219
|
+
vi.restoreAllMocks();
|
|
220
|
+
});
|
|
221
|
+
|
|
222
|
+
it("[核心回归] 有 env(子进程身份):execute 创建 record 的 parentRecordId/depth 来自基线,不依赖 ALS store", async () => {
|
|
223
|
+
// 模拟第一层 subagent 进程:env 注入「自己的身份」(父 record id + depth=1)
|
|
224
|
+
process.env[ENV_ROOT_SESSION_ID] = "root-main";
|
|
225
|
+
process.env[ENV_SELF_RECORD_ID] = "sa-parent-record";
|
|
226
|
+
process.env[ENV_DEPTH] = "1";
|
|
227
|
+
|
|
228
|
+
const { service, store } = setup({});
|
|
229
|
+
|
|
230
|
+
// 不在 execCtxAls.run 内调用(模拟 ALS 断裂:事件回调上下文读不到 store)
|
|
231
|
+
const handle = await service.execute({ task: "child of parent", ctxModel });
|
|
232
|
+
|
|
233
|
+
const rec = store.collectRecords(10, "all", "root-main").find((r) => r.id === handle.subagentId);
|
|
234
|
+
expect(rec).toBeDefined();
|
|
235
|
+
expect(rec!.parentRecordId).toBe("sa-parent-record");
|
|
236
|
+
expect(rec!.depth).toBe(2); // 基线 depth 1 + 1
|
|
237
|
+
expect(rec!.rootSessionId).toBe("root-main");
|
|
238
|
+
|
|
239
|
+
// [MF-1 回归] 读侧 collectRecords 过滤必须与写侧盖章同源(sessionRootId)。
|
|
240
|
+
// 旧实现传 this.sessionId(子进程自己的 session id ≠ ROOT)→ 子进程内列表恒空。
|
|
241
|
+
// 子进程的本进程 sessionId 是 "baseline-it"(initSession 注入),而 record 归属
|
|
242
|
+
// root-main(env 贯穿的真 ROOT)——能查到即证明过滤用的是 sessionRootId。
|
|
243
|
+
const viaService = service.collectRecords(10);
|
|
244
|
+
expect(viaService.map((r) => r.id)).toContain(handle.subagentId);
|
|
245
|
+
expect(viaService[0]!.rootSessionId).toBe("root-main");
|
|
246
|
+
});
|
|
247
|
+
|
|
248
|
+
it("[顶层] 无 env(根进程):parentRecordId undefined / depth 0", async () => {
|
|
249
|
+
const { service, store } = setup({});
|
|
250
|
+
|
|
251
|
+
const handle = await service.execute({ task: "top level", ctxModel });
|
|
252
|
+
|
|
253
|
+
const rec = store.collectRecords(10, "all", "baseline-it").find((r) => r.id === handle.subagentId);
|
|
254
|
+
expect(rec).toBeDefined();
|
|
255
|
+
expect(rec!.parentRecordId).toBeUndefined();
|
|
256
|
+
expect(rec!.depth).toBe(0);
|
|
257
|
+
});
|
|
258
|
+
|
|
259
|
+
it("[优先级] execCtxAls.run 的 store 优先于基线(并发链语义不回归)", async () => {
|
|
260
|
+
process.env[ENV_ROOT_SESSION_ID] = "root-main";
|
|
261
|
+
process.env[ENV_SELF_RECORD_ID] = "sa-baseline";
|
|
262
|
+
process.env[ENV_DEPTH] = "0";
|
|
263
|
+
|
|
264
|
+
const { service, store } = setup({});
|
|
265
|
+
const execCtxAls = Reflect.get(service, "execCtxAls") as ExecCtxAls;
|
|
266
|
+
|
|
267
|
+
const handle = await execCtxAls.run({ recordId: "sa-inline-parent", depth: 3 }, () =>
|
|
268
|
+
service.execute({ task: "inline nested", ctxModel }),
|
|
269
|
+
);
|
|
270
|
+
|
|
271
|
+
const rec = store.collectRecords(10, "all", "root-main").find((r) => r.id === handle.subagentId);
|
|
272
|
+
expect(rec).toBeDefined();
|
|
273
|
+
expect(rec!.parentRecordId).toBe("sa-inline-parent"); // run store 优先,非基线 sa-baseline
|
|
274
|
+
expect(rec!.depth).toBe(4);
|
|
275
|
+
});
|
|
276
|
+
|
|
277
|
+
it("[forkDepth 基线] env PI_SUBAGENT_FORK_DEPTH=1 + fork:spawn env 递增为 2(读点兜底基线生效)", async () => {
|
|
278
|
+
process.env[ENV_ROOT_SESSION_ID] = "root-main";
|
|
279
|
+
process.env[ENV_SELF_RECORD_ID] = "sa-fork-parent";
|
|
280
|
+
process.env[ENV_DEPTH] = "0";
|
|
281
|
+
process.env[ENV_FORK_DEPTH] = "1";
|
|
282
|
+
|
|
283
|
+
const { service } = setup({});
|
|
284
|
+
|
|
285
|
+
const execPromise = service.execute({ task: "fork child", ctxModel, fork: true });
|
|
286
|
+
await waitForSpawn();
|
|
287
|
+
const childEnv = getLastSpawnEnv();
|
|
288
|
+
|
|
289
|
+
// 742 行 parentDepth = forkDepthAls.getStore() ?? forkDepthBaseline —— ALS 断裂时基线=1,+1 → 2
|
|
290
|
+
expect(childEnv.PI_SUBAGENT_FORK_DEPTH).toBe("2");
|
|
291
|
+
|
|
292
|
+
const child = lastSpawnedChild();
|
|
293
|
+
child.emit("close", 0);
|
|
294
|
+
await execPromise;
|
|
295
|
+
});
|
|
296
|
+
|
|
297
|
+
it("[嵌套护栏] 基线 depth 参与 execute 入口嵌套护栏(depth>MAX 拒绝)", async () => {
|
|
298
|
+
process.env[ENV_ROOT_SESSION_ID] = "root-main";
|
|
299
|
+
process.env[ENV_SELF_RECORD_ID] = "sa-deep-parent";
|
|
300
|
+
process.env[ENV_DEPTH] = "5";
|
|
301
|
+
|
|
302
|
+
const { service } = setup({});
|
|
303
|
+
|
|
304
|
+
// MAX_FORK_DEPTH 至少 > 5 才不会被误拒;这里验证基线参与计数的方式是
|
|
305
|
+
// 用直接深度断言——execute 不抛错说明 nestingDepth=6 未超限,护栏不误伤。
|
|
306
|
+
// (MAX_FORK_DEPTH 具体值由 session-context-resolver 定义,这里不硬编码。)
|
|
307
|
+
await expect(service.execute({ task: "deep but allowed", ctxModel })).resolves.toBeDefined();
|
|
308
|
+
});
|
|
309
|
+
|
|
310
|
+
it("[MF-3 回归] 有 ENV_ROOT_CWD(worktree 子进程):sessions 与 records 两套目录统一编码在 ROOT cwd 段", () => {
|
|
311
|
+
// 模拟 B(worktree 子进程,自身 cwd=checkout 路径)经 env 拿到真 ROOT cwd。
|
|
312
|
+
// 旧实现按 init.cwd 编码 → enc(checkout) 段,ROOT 磁盘重建扫不到(MF-3)。
|
|
313
|
+
const rootCwd = "/root/project";
|
|
314
|
+
process.env[ENV_ROOT_CWD] = rootCwd;
|
|
315
|
+
|
|
316
|
+
const agentDir = "/tmp/baseline-it";
|
|
317
|
+
const checkoutPath = "/var/folders/worktree/pi-subagents/--root-project--/branch";
|
|
318
|
+
const modelService = new ModelConfigService({ agentDir });
|
|
319
|
+
modelService.initModel({
|
|
320
|
+
modelRegistry: makeEmptyRegistry(),
|
|
321
|
+
sessionId: "baseline-it",
|
|
322
|
+
ctxModel: { id: "m", name: "M", provider: "p", reasoning: false },
|
|
323
|
+
});
|
|
324
|
+
// service cwd = checkout 路径(worktree 子进程的 spawn cwd)
|
|
325
|
+
const service = new SubagentService({
|
|
326
|
+
cwd: checkoutPath,
|
|
327
|
+
modelService,
|
|
328
|
+
getMainSessionFile: () => "/mock/main-session.jsonl",
|
|
329
|
+
});
|
|
330
|
+
|
|
331
|
+
const store = Reflect.get(service, "store") as RecordStore;
|
|
332
|
+
const sessionsDir = Reflect.get(store, "sessionsDir") as string;
|
|
333
|
+
// ManifestStore 在本文件被 mock:recordsDir 从构造调用参数取(vi.fn 包裹)
|
|
334
|
+
const recordsDir = vi.mocked(ManifestStore).mock.calls.at(-1)?.[0] as string | undefined;
|
|
335
|
+
|
|
336
|
+
// 两套目录都编码在 enc(ROOT cwd) 段(不是 enc(checkout))
|
|
337
|
+
expect(sessionsDir).toBe(getSubagentSessionDir(agentDir, rootCwd));
|
|
338
|
+
expect(recordsDir).toBe(getSubagentRecordsDir(agentDir, rootCwd));
|
|
339
|
+
});
|
|
340
|
+
});
|