pi-ate-workflow 0.1.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.
Files changed (46) hide show
  1. package/README.en.md +102 -0
  2. package/README.md +104 -0
  3. package/agent-loader.ts +88 -0
  4. package/index.ts +18 -0
  5. package/output.ts +89 -0
  6. package/package.json +50 -0
  7. package/research-analysis.ts +64 -0
  8. package/research-catalog.ts +33 -0
  9. package/research-scan.ts +65 -0
  10. package/research-state.ts +46 -0
  11. package/research-types.ts +53 -0
  12. package/research-utils.ts +107 -0
  13. package/research.ts +52 -0
  14. package/state.ts +121 -0
  15. package/subagent-spawn-once.ts +164 -0
  16. package/subagent-spawn-visible.ts +194 -0
  17. package/subagent-utils.ts +38 -0
  18. package/subagent.ts +93 -0
  19. package/tests/agent-loader.test.ts +183 -0
  20. package/tests/agent-schema-extra.test.ts +107 -0
  21. package/tests/agent-schema.test.ts +116 -0
  22. package/tests/output.test.ts +107 -0
  23. package/tests/research-analysis.test.ts +155 -0
  24. package/tests/research-extra.test.ts +175 -0
  25. package/tests/research.test.ts +418 -0
  26. package/tests/smoke.subagent.test.ts +127 -0
  27. package/tests/state-manager.test.ts +245 -0
  28. package/tests/state.test.ts +298 -0
  29. package/tests/subagent-api.test.ts +158 -0
  30. package/tests/subagent-spawn-once.test.ts +154 -0
  31. package/tests/subagent-spawn-visible.test.ts +139 -0
  32. package/tests/subagent-utils.test.ts +124 -0
  33. package/tests/test-helpers.ts +40 -0
  34. package/tests/ui-updater.test.ts +129 -0
  35. package/tests/utils-find-session.test.ts +114 -0
  36. package/tests/utils-status-summary.test.ts +158 -0
  37. package/tests/utils.test.ts +48 -0
  38. package/tests/widget.test.ts +114 -0
  39. package/tests/workflow-execution.test.ts +165 -0
  40. package/tests/workflow-registration.test.ts +155 -0
  41. package/tests/workflow.test.ts +207 -0
  42. package/types.ts +24 -0
  43. package/utils.ts +74 -0
  44. package/vitest.config.ts +21 -0
  45. package/widget.ts +104 -0
  46. package/workflow.ts +113 -0
@@ -0,0 +1,38 @@
1
+ /**
2
+ * workflow: 子代理工具函数
3
+ *
4
+ * 从 PV 的 subagent.ts 提取的通用函数。
5
+ */
6
+
7
+ import { spawn } from "node:child_process";
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 的 command + args。
14
+ * 优先用当前进程的可执行文件路径,回退到 PATH 中的 "pi"。
15
+ */
16
+ export function getPiCommand(): { command: string; args: string[] } {
17
+ const currentScript = process.argv[1];
18
+ const isBunVirtualScript = currentScript?.startsWith("/$bunfs/root/");
19
+ if (currentScript && !isBunVirtualScript && fs.existsSync(currentScript)) {
20
+ return { command: process.execPath, args: [currentScript] };
21
+ }
22
+ const execName = path.basename(process.execPath).toLowerCase();
23
+ if (/^(node|bun)(\.exe)?$/.test(execName)) {
24
+ return { command: "pi", args: [] };
25
+ }
26
+ return { command: process.execPath, args: [] };
27
+ }
28
+
29
+ /**
30
+ * 将 system prompt 写入临时文件,返回文件路径。
31
+ * 调用方负责删除临时文件和目录。
32
+ */
33
+ export async function writeTempPrompt(content: string): Promise<string> {
34
+ const tmpDir = await fs.promises.mkdtemp(path.join(os.tmpdir(), "pi-pv-"));
35
+ const filePath = path.join(tmpDir, "system-prompt.md");
36
+ await fs.promises.writeFile(filePath, content, { encoding: "utf-8", mode: 0o600 });
37
+ return filePath;
38
+ }
package/subagent.ts ADDED
@@ -0,0 +1,93 @@
1
+ /**
2
+ * workflow: 子代理执行器公开 API
3
+ *
4
+ * spawn 实现在 subagent-spawn-once.ts 和 subagent-spawn-visible.ts。
5
+ */
6
+
7
+ import * as fs from "node:fs";
8
+ import * as path from "node:path";
9
+ import type { SubagentResult, SubagentEvent } from "./types";
10
+ import { writeTempPrompt } from "./subagent-utils";
11
+ import { loadAgentDef } from "./agent-loader";
12
+ import { spawnOnce } from "./subagent-spawn-once";
13
+ import { spawnVisible } from "./subagent-spawn-visible";
14
+
15
+ /** 格式约束,拼入 task 让子代理自检,执行后验证 */
16
+ export interface OutputConstraint {
17
+ /** 约束描述(自然语言,拼入 task) */
18
+ rule: string;
19
+ /** 验证函数:返回 null 表示通过,否则返回错误描述 */
20
+ validate: (output: string) => string | null;
21
+ }
22
+
23
+ /** 构建格式约束追加提示词 */
24
+ function buildConstraintAppendix(constraints: OutputConstraint[]): string {
25
+ const rules = constraints.map((c, i) => `${i + 1}. ${c.rule}`).join("\n");
26
+ return `\n\n---\n\n## 输出格式约束(严格遵守)\n\n你的输出会被自动化系统解析,必须严格遵守以下格式规则:\n\n${rules}\n\n**在输出审查结果之前,先检查你的输出是否符合上述所有规则。如果不符合,修正后再输出。**`;
27
+ }
28
+
29
+ /** 验证输出是否满足所有约束,返回不通过的列表 */
30
+ export function validateOutputConstraints(output: string, constraints: OutputConstraint[]): string[] {
31
+ const violations: string[] = [];
32
+ for (const c of constraints) {
33
+ const err = c.validate(output);
34
+ if (err) violations.push(err);
35
+ }
36
+ return violations;
37
+ }
38
+
39
+ /**
40
+ * 运行子代理。支持输出格式约束:约束拼入 task,执行后验证,
41
+ * 不通过则追加修正提示重跑(最多 2 次)。
42
+ *
43
+ * @param agentName 对应 ~/.pi/agent/agents/{name}.md
44
+ * @param visible true=在 tmux 窗格中可见运行(默认),false=后台运行
45
+ */
46
+ export async function runSubagent(
47
+ agentName: string,
48
+ task: string,
49
+ cwd: string,
50
+ signal?: AbortSignal,
51
+ modelOverride?: string,
52
+ timeoutMs?: number,
53
+ onEvent?: (event: SubagentEvent) => void,
54
+ outputConstraints?: OutputConstraint[],
55
+ visible: boolean = true,
56
+ ): Promise<SubagentResult> {
57
+ const agentDef = loadAgentDef(agentName);
58
+ if (!agentDef) {
59
+ throw new Error(`子代理定义 "${agentName}" 未找到。请确保 ~/.pi/agent/agents/${agentName}.md 文件存在。`);
60
+ }
61
+
62
+ const useVisible = visible && !!process.env.TMUX;
63
+
64
+ const tmpPromptPath = await writeTempPrompt(agentDef.systemPrompt);
65
+
66
+ try {
67
+ const constraintAppendix = outputConstraints?.length ? buildConstraintAppendix(outputConstraints) : "";
68
+ const fullTask = task + constraintAppendix;
69
+
70
+ const MAX_RETRIES = 2;
71
+ let lastResult: SubagentResult | undefined;
72
+
73
+ for (let attempt = 0; attempt <= MAX_RETRIES; attempt++) {
74
+ const taskForAttempt = attempt === 0 ? fullTask
75
+ : `${fullTask}\n\n---\n\n⚠️ 你上一轮的输出不符合格式约束:\n${validateOutputConstraints(lastResult!.output, outputConstraints!).join("\n")}\n\n请修正格式后重新输出完整的审查结果。不要重复工具调用,直接输出修正后的文本。`;
76
+
77
+ const result = useVisible
78
+ ? await spawnVisible(taskForAttempt, cwd, tmpPromptPath, agentDef, signal, modelOverride, timeoutMs, onEvent)
79
+ : await spawnOnce(taskForAttempt, cwd, tmpPromptPath, agentDef, signal, modelOverride, timeoutMs, onEvent);
80
+ lastResult = result;
81
+
82
+ if (!outputConstraints?.length) break;
83
+ if (result.exitCode !== 0 && result.output.length <= 100) break;
84
+
85
+ const violations = validateOutputConstraints(result.output, outputConstraints);
86
+ if (violations.length === 0) break;
87
+ }
88
+
89
+ return lastResult!;
90
+ } finally {
91
+ try { const dir = path.dirname(tmpPromptPath); fs.unlinkSync(tmpPromptPath); fs.rmdirSync(dir); } catch { /* ignore */ }
92
+ }
93
+ }
@@ -0,0 +1,183 @@
1
+ /**
2
+ * Tests: agent-loader.ts — loadAgentDef + parseAgentFile + 缓存行为
3
+ *
4
+ * 测试场景(12 用例):
5
+ * 1) 加载存在带 frontmatter 的 agent 文件 → 返回完整 AgentDef
6
+ * 2) 加载存在无 frontmatter 的 agent 文件 → body 作为 systemPrompt
7
+ * 3) 加载不存在的 agent → 返回 null
8
+ * 4) 搜索两个路径(.pi/agent/agents 和 .agents/agents)
9
+ * 5) 缓存命中(mtime 未变)→ 不重新读文件
10
+ * 6) 缓存过期(mtime 改变)→ 重新读文件
11
+ * 7) frontmatter 解析:name/tools/model/thinking 字段
12
+ * 8) tools 逗号分隔
13
+ * 9) 引号移除
14
+ * 10) 无 tools 字段 → 默认 tools
15
+ * 11) 空 body 情况
16
+ */
17
+
18
+ import { describe, it, expect, vi, beforeEach } from "vitest";
19
+ import * as path from "node:path";
20
+
21
+ const MOCK_HOME = "/home/testuser";
22
+
23
+ // Track readFileSync call count
24
+ let readFileCallCount = 0;
25
+
26
+ vi.mock("node:os", () => ({ homedir: () => MOCK_HOME }));
27
+
28
+ const mockFiles = new Map<string, { content: string; mtimeMs: number }>();
29
+
30
+ vi.mock("node:fs", () => ({
31
+ existsSync: (p: string) => mockFiles.has(p),
32
+ statSync: (p: string) => {
33
+ const entry = mockFiles.get(p);
34
+ if (!entry) throw new Error(`ENOENT: ${p}`);
35
+ return { mtimeMs: entry.mtimeMs };
36
+ },
37
+ readFileSync: (p: string, _encoding?: any) => {
38
+ readFileCallCount++;
39
+ const entry = mockFiles.get(p);
40
+ if (!entry) throw new Error(`ENOENT: ${p}`);
41
+ return entry.content;
42
+ },
43
+ promises: {},
44
+ }));
45
+
46
+ function addMockFile(fullRelPath: string, content: string, mtimeMs: number = 1000) {
47
+ mockFiles.set(path.join(MOCK_HOME, fullRelPath), { content, mtimeMs });
48
+ }
49
+
50
+ import { loadAgentDef } from "../agent-loader";
51
+
52
+ describe("loadAgentDef", () => {
53
+ beforeEach(() => {
54
+ mockFiles.clear();
55
+ readFileCallCount = 0;
56
+ });
57
+
58
+ it("加载存在带 frontmatter 的 agent → 返回完整 AgentDef", () => {
59
+ addMockFile(".pi/agent/agents/reviewer.md",
60
+ "---\nname: reviewer\ntools: read,grep,find\nmodel: gpt-4\nthinking: auto\n---\n你是一个 code reviewer。",
61
+ );
62
+ const def = loadAgentDef("reviewer");
63
+ expect(def).not.toBeNull();
64
+ expect(def!.name).toBe("reviewer");
65
+ expect(def!.tools).toEqual(["read", "grep", "find"]);
66
+ expect(def!.model).toBe("gpt-4");
67
+ expect(def!.thinking).toBe("auto");
68
+ expect(def!.systemPrompt).toBe("你是一个 code reviewer。");
69
+ });
70
+
71
+ it("加载存在无 frontmatter 的 agent → body 作为 systemPrompt,默认 tools", () => {
72
+ addMockFile(".pi/agent/agents/simple.md", "你是一个简单的 agent,不做任何工具调用。");
73
+ const def = loadAgentDef("simple");
74
+ expect(def).not.toBeNull();
75
+ expect(def!.name).toBe("simple");
76
+ expect(def!.tools).toEqual(["read", "grep", "find", "ls"]);
77
+ expect(def!.systemPrompt).toBe("你是一个简单的 agent,不做任何工具调用。");
78
+ expect(def!.model).toBeUndefined();
79
+ });
80
+
81
+ it("加载不存在 agent → 返回 null", () => {
82
+ const def = loadAgentDef("nonexistent");
83
+ expect(def).toBeNull();
84
+ });
85
+
86
+ it("优先搜索 .pi/agent/agents,再搜索 .agents/agents", () => {
87
+ addMockFile(".agents/agents/fallback.md", "Fallback agent");
88
+ const def = loadAgentDef("fallback");
89
+ expect(def).not.toBeNull();
90
+ expect(def!.systemPrompt).toBe("Fallback agent");
91
+ });
92
+
93
+ it("第一路径存在时,不使用第二路径", () => {
94
+ addMockFile(".pi/agent/agents/dup.md", "Primary version");
95
+ addMockFile(".agents/agents/dup.md", "Secondary version");
96
+ const def = loadAgentDef("dup");
97
+ expect(def).not.toBeNull();
98
+ expect(def!.systemPrompt).toBe("Primary version");
99
+ });
100
+
101
+ it("缓存命中(mtime 未变)→ 只读一次文件", () => {
102
+ addMockFile(".pi/agent/agents/cached.md",
103
+ "---\nname: cached\ntools: read\n---\nContent",
104
+ 1000,
105
+ );
106
+ // First call — load and cache
107
+ const def1 = loadAgentDef("cached");
108
+ expect(def1).not.toBeNull();
109
+ const callsAfterFirst = readFileCallCount;
110
+
111
+ // Second call — should use cache
112
+ const def2 = loadAgentDef("cached");
113
+ expect(def2).not.toBeNull();
114
+ expect(readFileCallCount).toBe(callsAfterFirst);
115
+ });
116
+
117
+ it("缓存过期(mtime 改变)→ 重新读文件", () => {
118
+ addMockFile(".pi/agent/agents/outdated.md",
119
+ "---\nname: outdated\ntools: read\n---\nOld",
120
+ 1000,
121
+ );
122
+ // First call — populate cache
123
+ loadAgentDef("outdated");
124
+ const callsAfterFirst = readFileCallCount;
125
+
126
+ // Update file mtime and content
127
+ addMockFile(".pi/agent/agents/outdated.md",
128
+ "---\nname: outdated\ntools: read,grep\n---\nNew",
129
+ 2000,
130
+ );
131
+
132
+ const def = loadAgentDef("outdated");
133
+ expect(def).not.toBeNull();
134
+ expect(def!.tools).toEqual(["read", "grep"]);
135
+ expect(def!.systemPrompt).toBe("New");
136
+ expect(readFileCallCount).toBe(callsAfterFirst + 1);
137
+ });
138
+
139
+ it("frontmatter 解析:引号去除", () => {
140
+ addMockFile(".pi/agent/agents/quoted.md",
141
+ `---\nname: "quoted-agent"\ntools: "read,grep"\nmodel: 'gpt-4'\n---\nPrompt body`,
142
+ );
143
+ const def = loadAgentDef("quoted");
144
+ expect(def).not.toBeNull();
145
+ expect(def!.name).toBe("quoted-agent");
146
+ expect(def!.tools).toEqual(["read", "grep"]);
147
+ expect(def!.model).toBe("gpt-4");
148
+ });
149
+
150
+ it("无 tools 字段 → 默认 tools", () => {
151
+ addMockFile(".pi/agent/agents/notools.md", "---\nname: notools\n---\nJust a prompt");
152
+ const def = loadAgentDef("notools");
153
+ expect(def).not.toBeNull();
154
+ expect(def!.tools).toEqual(["read", "grep", "find", "ls"]);
155
+ });
156
+
157
+ it("tools 逗号分隔含空格 → 正确 trim", () => {
158
+ addMockFile(".pi/agent/agents/trimmed.md",
159
+ "---\nname: trimmed\ntools: read , grep , find\n---\nContent",
160
+ );
161
+ const def = loadAgentDef("trimmed");
162
+ expect(def).not.toBeNull();
163
+ expect(def!.tools).toEqual(["read", "grep", "find"]);
164
+ });
165
+
166
+ it("不带 frontmatter 且 body 为空 → body 用 content.trim()", () => {
167
+ addMockFile(".pi/agent/agents/emptybody.md", " \n \n");
168
+ const def = loadAgentDef("emptybody");
169
+ expect(def).not.toBeNull();
170
+ expect(def!.systemPrompt).toBe("");
171
+ });
172
+
173
+ it("frontmatter 有额外未知字段 → 忽略,不报错", () => {
174
+ addMockFile(".pi/agent/agents/extra.md",
175
+ "---\nname: extra\ntools: read\nunknown_field: hello\n---\nContent",
176
+ );
177
+ const def = loadAgentDef("extra");
178
+ expect(def).not.toBeNull();
179
+ expect(def!.name).toBe("extra");
180
+ expect(def!.tools).toEqual(["read"]);
181
+ expect(def!.systemPrompt).toBe("Content");
182
+ });
183
+ });
@@ -0,0 +1,107 @@
1
+ /**
2
+ * Phase 2 额外测试:Agent 定义文件格式兼容性
3
+ *
4
+ * 验证 agent .md 文件的 frontmatter 与 parseFrontmatter 兼容,
5
+ * 以及缺失字段时的边界行为。
6
+ */
7
+
8
+ import { describe, it, expect } from "vitest";
9
+ import * as fs from "node:fs";
10
+ import * as path from "node:path";
11
+ import * as os from "node:os";
12
+
13
+ import { parseFrontmatter } from "../research";
14
+
15
+ const AGENTS_DIR = path.join(os.homedir(), ".pi", "agent", "agents");
16
+
17
+ describe("Agent frontmatter 格式兼容性", () => {
18
+ const agentFiles = [
19
+ "_searcher.md",
20
+ "_directions.md",
21
+ "_source-eval.md",
22
+ "_interpretation.md",
23
+ ];
24
+
25
+ for (const agentFile of agentFiles) {
26
+ const filePath = path.join(AGENTS_DIR, agentFile);
27
+
28
+ it(`${agentFile} 的 tools frontmatter 与 parseFrontmatter 兼容`, () => {
29
+ // Skip if file doesn't exist
30
+ if (!fs.existsSync(filePath)) return;
31
+
32
+ const content = fs.readFileSync(filePath, "utf-8");
33
+ const fm = parseFrontmatter(content);
34
+
35
+ // tools 字段应包含至少一个工具名
36
+ expect(fm.tools).toBeDefined();
37
+ const toolsStr = String(fm.tools);
38
+ expect(toolsStr.length).toBeGreaterThan(0);
39
+ expect(toolsStr).toContain("read");
40
+ });
41
+
42
+ it(`${agentFile} 的 searcher 输出格式与 parseFrontmatter 兼容`, () => {
43
+ if (!fs.existsSync(filePath)) return;
44
+
45
+ const content = fs.readFileSync(filePath, "utf-8");
46
+
47
+ // 验证 frontmatter 可以被 parseFrontmatter 正确解析
48
+ const fm = parseFrontmatter(content);
49
+
50
+ // 所有 agent 应有 tools 字段且不为空
51
+ expect(fm.tools).toBeTruthy();
52
+ });
53
+ }
54
+
55
+ it("searcher 输出格式中的 article.md frontmatter 可被 parseFrontmatter 正确解析", () => {
56
+ // 模拟 searcher 输出格式描述中的 article.md 示例
57
+ const articleContent = `---
58
+ url: https://arxiv.org/abs/2301.12345
59
+ title: Deep Learning for Factor Investing
60
+ score: 8
61
+ source_type: academic
62
+ found_at: "2026-05-09T12:00:00"
63
+ ---
64
+ 论文主要内容...`;
65
+
66
+ const fm = parseFrontmatter(articleContent);
67
+ expect(fm.url).toBe("https://arxiv.org/abs/2301.12345");
68
+ expect(fm.title).toBe("Deep Learning for Factor Investing");
69
+ expect(fm.score).toBe(8);
70
+ expect(fm.source_type).toBe("academic");
71
+ expect(fm.found_at).toBe("2026-05-09T12:00:00");
72
+ });
73
+
74
+ it("fixture 缺 score 的 article.md → 解析不崩溃", () => {
75
+ // 模拟缺失 score 字段的 article.md
76
+ const articleContent = `---
77
+ url: https://arxiv.org/abs/2301.67890
78
+ title: A Study Without Score
79
+ source_type: academic
80
+ found_at: "2026-05-09T12:00:00"
81
+ ---
82
+ A paper without a numeric score`;
83
+
84
+ // 解析不应崩溃
85
+ const fm = parseFrontmatter(articleContent);
86
+ expect(fm.url).toBe("https://arxiv.org/abs/2301.67890");
87
+ expect(fm.title).toBe("A Study Without Score");
88
+ // score 应为 undefined(而非 NaN 或崩溃)
89
+ expect(fm.score).toBeUndefined();
90
+ });
91
+
92
+ it("fixture 缺多个字段的 article.md → 解析不崩溃", () => {
93
+ // 模拟只含 URL 的极简 article.md
94
+ const articleContent = `---
95
+ url: https://example.com/bare-minimum
96
+ ---
97
+ Just a URL`;
98
+
99
+ const fm = parseFrontmatter(articleContent);
100
+ expect(fm.url).toBe("https://example.com/bare-minimum");
101
+ // 缺失字段应为 undefined
102
+ expect(fm.title).toBeUndefined();
103
+ expect(fm.score).toBeUndefined();
104
+ expect(fm.source_type).toBeUndefined();
105
+ expect(fm.found_at).toBeUndefined();
106
+ });
107
+ });
@@ -0,0 +1,116 @@
1
+ /**
2
+ * Agent 定义文件验证测试
3
+ *
4
+ * 验证 ~/.pi/agent/agents/ 下 _searcher, _directions, _source-eval, _interpretation
5
+ * 四个 agent .md 文件格式符合要求。
6
+ */
7
+
8
+ import { describe, it, expect } from "vitest";
9
+ import * as fs from "node:fs";
10
+ import * as path from "node:path";
11
+ import * as os from "node:os";
12
+
13
+ const AGENTS_DIR = path.join(os.homedir(), ".pi", "agent", "agents");
14
+
15
+ const REQUIRED_AGENTS = [
16
+ "_searcher.md",
17
+ "_directions.md",
18
+ "_source-eval.md",
19
+ "_interpretation.md",
20
+ ];
21
+
22
+ interface ParsedAgent {
23
+ name: string;
24
+ tools: string[];
25
+ systemPrompt: string;
26
+ hasInput: boolean;
27
+ hasOutput: boolean;
28
+ hasRules: boolean;
29
+ }
30
+
31
+ function parseAgentFile(filePath: string): ParsedAgent | null {
32
+ if (!fs.existsSync(filePath)) return null;
33
+
34
+ const content = fs.readFileSync(filePath, "utf-8");
35
+ const fmMatch = content.match(/^---\s*\n([\s\S]*?)\n---\s*\n/);
36
+
37
+ let tools: string[] = [];
38
+ let name = path.basename(filePath, ".md");
39
+
40
+ if (fmMatch) {
41
+ const fm = fmMatch[1];
42
+ for (const line of fm.split("\n")) {
43
+ const idx = line.indexOf(":");
44
+ if (idx > 0) {
45
+ const key = line.slice(0, idx).trim();
46
+ let val = line.slice(idx + 1).trim();
47
+ if ((val.startsWith('"') && val.endsWith('"')) ||
48
+ (val.startsWith("'") && val.endsWith("'"))) {
49
+ val = val.slice(1, -1);
50
+ }
51
+ if (key === "tools") {
52
+ tools = val.split(",").map((t) => t.trim()).filter(Boolean);
53
+ }
54
+ if (key === "name") {
55
+ name = val;
56
+ }
57
+ }
58
+ }
59
+ }
60
+
61
+ const body = fmMatch ? content.slice(fmMatch[0].length) : content;
62
+ const hasInput = body.includes("## 输入");
63
+ const hasOutput = body.includes("## 输出");
64
+ const hasRules = body.includes("## 规则");
65
+
66
+ return { name, tools, systemPrompt: body, hasInput, hasOutput, hasRules };
67
+ }
68
+
69
+ describe("Agent 定义文件格式", () => {
70
+ for (const agentFile of REQUIRED_AGENTS) {
71
+ const filePath = path.join(AGENTS_DIR, agentFile);
72
+
73
+ it(`${agentFile} 文件存在`, () => {
74
+ const exists = fs.existsSync(filePath);
75
+ if (!exists) {
76
+ // 列出 agents 目录内容辅助调试
77
+ const files = fs.existsSync(AGENTS_DIR) ? fs.readdirSync(AGENTS_DIR) : [];
78
+ console.log(`agents 目录内容: ${files.join(", ")}`);
79
+ }
80
+ expect(exists, `${filePath} 不存在`).toBe(true);
81
+ });
82
+
83
+ if (!fs.existsSync(filePath)) continue;
84
+ it(`${agentFile} 包含 tools frontmatter`, () => {
85
+ const agent = parseAgentFile(filePath);
86
+ expect(agent!.tools.length).toBeGreaterThan(0);
87
+ });
88
+
89
+ it(`${agentFile} 包含 "输入" 章节`, () => {
90
+ const agent = parseAgentFile(filePath);
91
+ expect(agent!.hasInput).toBe(true);
92
+ });
93
+
94
+ it(`${agentFile} 包含 "输出" 章节`, () => {
95
+ const agent = parseAgentFile(filePath);
96
+ expect(agent!.hasOutput).toBe(true);
97
+ });
98
+
99
+ it(`${agentFile} 包含 "规则" 章节`, () => {
100
+ const agent = parseAgentFile(filePath);
101
+ expect(agent!.hasRules).toBe(true);
102
+ });
103
+
104
+ it(`${agentFile} 的 frontmatter 与 parseFrontmatter 兼容`, async () => {
105
+ const content = fs.readFileSync(filePath, "utf-8");
106
+ const fmMatch = content.match(/^---\s*\n([\s\S]*?)\n---\s*\n/);
107
+ expect(fmMatch).not.toBeNull();
108
+
109
+ // 验证 tools 字段可解析
110
+ const fmLines = fmMatch![1].split("\n");
111
+ const toolsLine = fmLines.find((l) => l.trim().startsWith("tools:"));
112
+ expect(toolsLine).toBeDefined();
113
+ expect(toolsLine!).toContain("read");
114
+ });
115
+ }
116
+ });
@@ -0,0 +1,107 @@
1
+ /**
2
+ * output.ts 测试 — saveSubagentOutput / readSubagentOutput
3
+ */
4
+
5
+ import { describe, it, expect, beforeEach, afterEach } from "vitest";
6
+ import * as fs from "node:fs";
7
+ import * as path from "node:path";
8
+ import * as os from "node:os";
9
+ import { saveSubagentOutput, readSubagentOutput } from "../output";
10
+
11
+ describe("saveSubagentOutput", () => {
12
+ let tmpDir: string;
13
+
14
+ beforeEach(() => {
15
+ tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "pi-output-test-"));
16
+ });
17
+
18
+ afterEach(() => {
19
+ fs.rmSync(tmpDir, { recursive: true, force: true });
20
+ });
21
+
22
+ it("should_create_file_in_plans_dir", () => {
23
+ const result = saveSubagentOutput(tmpDir, "review", "hello world");
24
+ const plansDir = path.join(tmpDir, ".pi", "plans");
25
+
26
+ expect(fs.existsSync(result.filePath)).toBe(true);
27
+ expect(result.filePath).toContain("review-");
28
+ expect(result.filePath).toMatch(/\.md$/);
29
+ expect(fs.readdirSync(plansDir).length).toBe(1);
30
+ });
31
+
32
+ it("should_write_full_output_to_file", () => {
33
+ const output = "line1\nline2\nline3";
34
+ const result = saveSubagentOutput(tmpDir, "test", output);
35
+
36
+ expect(fs.readFileSync(result.filePath, "utf-8")).toBe(output);
37
+ });
38
+
39
+ it("should_return_correct_line_count", () => {
40
+ const result = saveSubagentOutput(tmpDir, "test", "a\nb\nc\nd");
41
+ expect(result.lineCount).toBe(4);
42
+ });
43
+
44
+ it("should_return_correct_byte_size", () => {
45
+ const output = "hello"; // 5 bytes
46
+ const result = saveSubagentOutput(tmpDir, "test", output);
47
+ expect(result.size).toBe(5);
48
+ });
49
+
50
+ it("should_include_size_in_summary_as_bytes", () => {
51
+ const result = saveSubagentOutput(tmpDir, "test", "hello");
52
+ expect(result.summary).toContain("5B");
53
+ });
54
+
55
+ it("should_include_size_in_summary_as_kb", () => {
56
+ const big = "x".repeat(2048);
57
+ const result = saveSubagentOutput(tmpDir, "test", big);
58
+ expect(result.summary).toContain("2KB");
59
+ });
60
+
61
+ it("should_include_size_in_summary_as_mb", () => {
62
+ const big = "x".repeat(2 * 1024 * 1024);
63
+ const result = saveSubagentOutput(tmpDir, "test", big);
64
+ expect(result.summary).toContain("2.0MB");
65
+ });
66
+
67
+ it("should_include_passed_count_in_summary", () => {
68
+ const result = saveSubagentOutput(tmpDir, "test", "ok", { passed: 10 });
69
+ expect(result.summary).toContain("✅ 10 passed");
70
+ });
71
+
72
+ it("should_include_failed_and_critical_in_summary", () => {
73
+ const result = saveSubagentOutput(tmpDir, "test", "ok", { failed: 2, criticals: 1 });
74
+ expect(result.summary).toContain("❌ 2 failed");
75
+ expect(result.summary).toContain("🔴 1 critical");
76
+ });
77
+
78
+ it("should_include_warnings_in_summary", () => {
79
+ const result = saveSubagentOutput(tmpDir, "test", "ok", { warnings: 5 });
80
+ expect(result.summary).toContain("🟡 5 warnings");
81
+ });
82
+
83
+ it("should_include_zero_passed_in_summary", () => {
84
+ const result = saveSubagentOutput(tmpDir, "test", "ok", { passed: 0 });
85
+ expect(result.summary).toContain("✅ 0 passed");
86
+ });
87
+
88
+ it("should_create_plans_dir_if_missing", () => {
89
+ expect(fs.existsSync(path.join(tmpDir, ".pi", "plans"))).toBe(false);
90
+ saveSubagentOutput(tmpDir, "test", "content");
91
+ expect(fs.existsSync(path.join(tmpDir, ".pi", "plans"))).toBe(true);
92
+ });
93
+ });
94
+
95
+ describe("readSubagentOutput", () => {
96
+ it("should_read_existing_file", () => {
97
+ const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "pi-read-test-"));
98
+ const filePath = path.join(tmpDir, "output.md");
99
+ fs.writeFileSync(filePath, "test content", "utf-8");
100
+ expect(readSubagentOutput(filePath)).toBe("test content");
101
+ fs.rmSync(tmpDir, { recursive: true, force: true });
102
+ });
103
+
104
+ it("should_return_null_for_missing_file", () => {
105
+ expect(readSubagentOutput("/nonexistent/path/file.md")).toBeNull();
106
+ });
107
+ });