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,418 @@
1
+ /**
2
+ * research.ts 测试
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
+
10
+ import {
11
+ slugify,
12
+ urlToId,
13
+ parseFrontmatter,
14
+ getTimestamp,
15
+ loadCatalog,
16
+ saveCatalog,
17
+ loadTopicState,
18
+ saveTopicState,
19
+ scanNewSources,
20
+ getTopicDir,
21
+ type Article,
22
+ } from "../research";
23
+
24
+ describe("slugify", () => {
25
+ it("should convert spaces to hyphens", () => {
26
+ expect(slugify("Momentum Crash Factor")).toBe("momentum-crash-factor");
27
+ });
28
+
29
+ it("should handle Chinese characters", () => {
30
+ expect(slugify("A股 波动率因子")).toBe("a股-波动率因子");
31
+ });
32
+
33
+ it("should trim and lowercase", () => {
34
+ expect(slugify(" Hello World ")).toBe("hello-world");
35
+ });
36
+
37
+ it("should strip special characters", () => {
38
+ expect(slugify("Factor #1 (test)")).toBe("factor-1-test");
39
+ });
40
+
41
+ it("should collapse multiple hyphens", () => {
42
+ expect(slugify("a b---c")).toBe("a-b-c");
43
+ });
44
+
45
+ it("should return empty string for empty input", () => {
46
+ expect(slugify("")).toBe("");
47
+ });
48
+ });
49
+
50
+ describe("urlToId", () => {
51
+ it("should return consistent 12-char hash", () => {
52
+ const id1 = urlToId("https://example.com/article1");
53
+ const id2 = urlToId("https://example.com/article1");
54
+ expect(id1).toBe(id2);
55
+ expect(id1.length).toBe(12);
56
+ });
57
+
58
+ it("should produce different IDs for different URLs", () => {
59
+ const id1 = urlToId("https://example.com/a");
60
+ const id2 = urlToId("https://example.com/b");
61
+ expect(id1).not.toBe(id2);
62
+ });
63
+
64
+ it("should handle empty string", () => {
65
+ const id = urlToId("");
66
+ expect(id.length).toBe(12);
67
+ });
68
+ });
69
+
70
+ describe("parseFrontmatter", () => {
71
+ it("should parse string fields", () => {
72
+ const content = `---
73
+ url: https://example.com
74
+ title: Test Article
75
+ source_type: academic
76
+ ---
77
+ Content here`;
78
+ const fm = parseFrontmatter(content);
79
+ expect(fm.url).toBe("https://example.com");
80
+ expect(fm.title).toBe("Test Article");
81
+ expect(fm.source_type).toBe("academic");
82
+ });
83
+
84
+ it("should parse numeric fields", () => {
85
+ const content = `---
86
+ score: 8
87
+ ---
88
+ Content`;
89
+ const fm = parseFrontmatter(content);
90
+ expect(fm.score).toBe(8);
91
+ });
92
+
93
+ it("should parse float fields", () => {
94
+ const content = `---
95
+ score: 7.5
96
+ ---
97
+ Content`;
98
+ const fm = parseFrontmatter(content);
99
+ expect(fm.score).toBe(7.5);
100
+ });
101
+
102
+ it("should parse boolean fields", () => {
103
+ const content = `---
104
+ reviewed: true
105
+ published: false
106
+ ---
107
+ Content`;
108
+ const fm = parseFrontmatter(content);
109
+ expect(fm.reviewed).toBe(true);
110
+ expect(fm.published).toBe(false);
111
+ });
112
+
113
+ it("should parse quoted values", () => {
114
+ const content = `---
115
+ title: "Hello: World"
116
+ ---
117
+ Content`;
118
+ const fm = parseFrontmatter(content);
119
+ expect(fm.title).toBe("Hello: World");
120
+ });
121
+
122
+ it("should return empty object when no frontmatter", () => {
123
+ const fm = parseFrontmatter("Just content without frontmatter");
124
+ expect(fm).toEqual({});
125
+ });
126
+
127
+ it("should handle empty frontmatter", () => {
128
+ const content = `---
129
+ ---
130
+ Content`;
131
+ const fm = parseFrontmatter(content);
132
+ expect(fm).toEqual({});
133
+ });
134
+
135
+ it("should handle ISO datetime in found_at", () => {
136
+ const content = `---
137
+ found_at: "2026-05-09T12:00:00"
138
+ ---
139
+ Content`;
140
+ const fm = parseFrontmatter(content);
141
+ expect(fm.found_at).toBe("2026-05-09T12:00:00");
142
+ });
143
+ });
144
+
145
+ describe("getTimestamp", () => {
146
+ it("should return format YYYY-MM-DDTHHmm", () => {
147
+ const ts = getTimestamp();
148
+ expect(ts).toMatch(/^\d{4}-\d{2}-\d{2}T\d{4}$/);
149
+ });
150
+ });
151
+
152
+ describe("loadCatalog / saveCatalog", () => {
153
+ let tmpDir: string;
154
+
155
+ beforeEach(() => {
156
+ tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "research-test-"));
157
+ });
158
+
159
+ afterEach(() => {
160
+ fs.rmSync(tmpDir, { recursive: true, force: true });
161
+ });
162
+
163
+ it("should return empty array when no catalog exists", () => {
164
+ const catalog = loadCatalog(tmpDir);
165
+ expect(catalog).toEqual([]);
166
+ });
167
+
168
+ it("should save and load catalog", () => {
169
+ const articles: Article[] = [
170
+ {
171
+ id: "abc123def456",
172
+ url: "https://example.com/1",
173
+ title: "Test Article 1",
174
+ source_type: "academic",
175
+ found_at: "2026-05-09T12:00:00",
176
+ score: 8,
177
+ dir: "sources/arxiv/",
178
+ file: "2026-05-09T1200_article.md",
179
+ },
180
+ ];
181
+
182
+ saveCatalog(tmpDir, articles);
183
+ const loaded = loadCatalog(tmpDir);
184
+ expect(loaded).toEqual(articles);
185
+ });
186
+
187
+ it("should overwrite existing catalog", () => {
188
+ saveCatalog(tmpDir, [
189
+ { id: "1", url: "a", title: "A", source_type: "blog", found_at: "", score: 5, dir: "", file: "" },
190
+ ]);
191
+ saveCatalog(tmpDir, [
192
+ { id: "2", url: "b", title: "B", source_type: "blog", found_at: "", score: 5, dir: "", file: "" },
193
+ ]);
194
+ const loaded = loadCatalog(tmpDir);
195
+ expect(loaded).toHaveLength(1);
196
+ expect(loaded[0].id).toBe("2");
197
+ });
198
+ });
199
+
200
+ describe("loadTopicState / saveTopicState", () => {
201
+ let tmpDir: string;
202
+
203
+ beforeEach(() => {
204
+ tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "research-test-"));
205
+ });
206
+
207
+ afterEach(() => {
208
+ fs.rmSync(tmpDir, { recursive: true, force: true });
209
+ });
210
+
211
+ it("should return default state when no file exists", () => {
212
+ const state = loadTopicState(tmpDir, "test-slug");
213
+ expect(state.slug).toBe("test-slug");
214
+ expect(state.articles).toEqual({});
215
+ expect(state.directions).toEqual([]);
216
+ expect(state.iteration).toBe(0);
217
+ expect(state.max_iterations).toBe(3);
218
+ });
219
+
220
+ it("should save and load state", () => {
221
+ const state = loadTopicState(tmpDir, "test-slug");
222
+ state.topic = "Test Topic";
223
+ state.articles["abc123"] = {
224
+ direction: "pending",
225
+ source_eval: "pending",
226
+ interpretation: "pending",
227
+ };
228
+ saveTopicState(tmpDir, "test-slug", state);
229
+
230
+ const loaded = loadTopicState(tmpDir, "test-slug");
231
+ expect(loaded.topic).toBe("Test Topic");
232
+ expect(loaded.articles["abc123"]).toEqual({
233
+ direction: "pending",
234
+ source_eval: "pending",
235
+ interpretation: "pending",
236
+ });
237
+ });
238
+
239
+ it("should not merge with catalog (independent management)", () => {
240
+ // 验证 saveTopicState 不触碰 catalog
241
+ const articles: Article[] = [{ id: "1", url: "a", title: "A", source_type: "blog", found_at: "", score: 5, dir: "", file: "" }];
242
+ saveCatalog(tmpDir, articles);
243
+
244
+ const state = loadTopicState(tmpDir, "slug");
245
+ state.articles["x"] = { direction: "pending", source_eval: "pending", interpretation: "pending" };
246
+ saveTopicState(tmpDir, "slug", state);
247
+
248
+ // catalog 应保持不变
249
+ const catalog = loadCatalog(tmpDir);
250
+ expect(catalog).toHaveLength(1);
251
+ expect(catalog[0].id).toBe("1");
252
+ });
253
+ });
254
+
255
+ describe("scanNewSources", () => {
256
+ let tmpDir: string;
257
+ let topicDir: string;
258
+
259
+ beforeEach(() => {
260
+ tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "research-test-"));
261
+ // scanNewSources 使用 getResearchDir(cwd) = cwd/docs/research
262
+ topicDir = path.join(tmpDir, "project");
263
+ fs.mkdirSync(path.join(topicDir, "docs", "research", "sources", "arxiv"), { recursive: true });
264
+ fs.mkdirSync(path.join(topicDir, "docs", "research", "sources", "ssrn"), { recursive: true });
265
+ });
266
+
267
+ afterEach(() => {
268
+ fs.rmSync(tmpDir, { recursive: true, force: true });
269
+ });
270
+
271
+ it("should return empty when no article files exist", () => {
272
+ const articles = scanNewSources(topicDir, []);
273
+ expect(articles).toEqual([]);
274
+ });
275
+
276
+ it("should scan and return new articles from source dirs", () => {
277
+ const articleContent = `---
278
+ url: https://arxiv.org/abs/1234
279
+ title: Test Paper
280
+ score: 8
281
+ source_type: academic
282
+ found_at: "2026-05-09T12:00:00"
283
+ ---
284
+ Paper content here`;
285
+
286
+ fs.writeFileSync(path.join(topicDir, "docs", "research", "sources", "arxiv", "2026-05-09T1200_article.md"), articleContent);
287
+
288
+ const articles = scanNewSources(topicDir, []);
289
+ expect(articles).toHaveLength(1);
290
+ expect(articles[0].title).toBe("Test Paper");
291
+ expect(articles[0].url).toBe("https://arxiv.org/abs/1234");
292
+ expect(articles[0].source_type).toBe("academic");
293
+ expect(articles[0].score).toBe(8);
294
+ expect(articles[0].dir).toBe("sources/arxiv/");
295
+ expect(articles[0].id.length).toBe(12);
296
+ });
297
+
298
+ it("should skip already cataloged articles", () => {
299
+ const url = "https://arxiv.org/abs/1234";
300
+ const existingId = urlToId(url);
301
+ const existingCatalog: Article[] = [
302
+ {
303
+ id: existingId,
304
+ url,
305
+ title: "Test Paper",
306
+ source_type: "academic",
307
+ found_at: "2026-05-09T12:00:00",
308
+ score: 8,
309
+ dir: "sources/arxiv/",
310
+ file: "2026-05-09T1200_article.md",
311
+ },
312
+ ];
313
+
314
+ const articleContent = `---
315
+ url: ${url}
316
+ title: Test Paper
317
+ score: 8
318
+ source_type: academic
319
+ ---
320
+ Content`;
321
+ fs.writeFileSync(path.join(topicDir, "docs", "research", "sources", "arxiv", "2026-05-09T1200_article.md"), articleContent);
322
+
323
+ const articles = scanNewSources(topicDir, existingCatalog.map((a) => a.id));
324
+ expect(articles).toHaveLength(0);
325
+ });
326
+
327
+ it("should handle articles from multiple source dirs", () => {
328
+ const article1 = `---
329
+ url: https://arxiv.org/a
330
+ title: Paper A
331
+ score: 7
332
+ source_type: academic
333
+ ---
334
+ A`;
335
+ const article2 = `---
336
+ url: https://ssrn.com/b
337
+ title: Paper B
338
+ score: 9
339
+ source_type: academic
340
+ ---
341
+ B`;
342
+
343
+ fs.writeFileSync(path.join(topicDir, "docs", "research", "sources", "arxiv", "2026-05-09T1200_article.md"), article1);
344
+ fs.writeFileSync(path.join(topicDir, "docs", "research", "sources", "ssrn", "2026-05-09T1201_article.md"), article2);
345
+
346
+ const articles = scanNewSources(topicDir, []);
347
+ expect(articles).toHaveLength(2);
348
+ expect(articles.map((a) => a.title).sort()).toEqual(["Paper A", "Paper B"]);
349
+ expect(articles.map((a) => a.dir).sort()).toEqual(["sources/arxiv/", "sources/ssrn/"]);
350
+ });
351
+
352
+ it("should skip files without proper frontmatter gracefully", () => {
353
+ // 写一个没有 frontmatter 的文件,应被跳过
354
+ fs.writeFileSync(path.join(topicDir, "docs", "research", "sources", "arxiv", "bad_article.md"), "No frontmatter here");
355
+ // 写一个正常文件
356
+ const goodArticle = `---
357
+ url: https://example.com/good
358
+ title: Good Article
359
+ score: 6
360
+ source_type: blog
361
+ ---
362
+ Content`;
363
+ fs.writeFileSync(path.join(topicDir, "docs", "research", "sources", "arxiv", "good_article.md"), goodArticle);
364
+
365
+ const articles = scanNewSources(topicDir, []);
366
+ expect(articles).toHaveLength(1);
367
+ expect(articles[0].title).toBe("Good Article");
368
+ });
369
+
370
+ it("should return empty when sources dir does not exist", () => {
371
+ const noSourcesDir = path.join(tmpDir, "empty");
372
+ const articles = scanNewSources(noSourcesDir, []);
373
+ expect(articles).toEqual([]);
374
+ });
375
+
376
+ it("should assign default values for missing frontmatter fields", () => {
377
+ const articleContent = `---
378
+ url: https://example.com/minimal
379
+ ---
380
+ Some content`;
381
+ fs.writeFileSync(path.join(topicDir, "docs", "research", "sources", "arxiv", "minimal_article.md"), articleContent);
382
+
383
+ const articles = scanNewSources(topicDir, []);
384
+ expect(articles).toHaveLength(1);
385
+ expect(articles[0].url).toBe("https://example.com/minimal");
386
+ expect(articles[0].title).toBe("minimal"); // falls back to filename (without _article.md suffix)
387
+ expect(articles[0].source_type).toBe("other"); // default
388
+ expect(articles[0].score).toBe(5); // default
389
+ expect(articles[0].id.length).toBe(12);
390
+ });
391
+
392
+ it("should produce consistent id for same url across scans", () => {
393
+ const articleContent = `---
394
+ url: https://example.com/consistent
395
+ title: Consistent
396
+ score: 7
397
+ source_type: blog
398
+ ---
399
+ Content`;
400
+ fs.writeFileSync(path.join(topicDir, "docs", "research", "sources", "arxiv", "2026-05-09T1200_article.md"), articleContent);
401
+
402
+ // 用空 catalog 扫描两次,验证 id 一致性
403
+ const articles1 = scanNewSources(topicDir, []);
404
+ expect(articles1[0].id).toBe(urlToId("https://example.com/consistent"));
405
+
406
+ // 模拟增量扫描:加入 catalog 后第二次应返回空
407
+ const articles2 = scanNewSources(topicDir, articles1.map((a) => a.id));
408
+ expect(articles2).toHaveLength(0);
409
+ });
410
+ });
411
+
412
+ describe("getTopicDir", () => {
413
+ // getTopicDir 是向后兼容别名,返回 getResearchDir(cwd) = cwd/docs/research
414
+ it("should return getResearchDir(cwd) (backward compat alias)", () => {
415
+ const dir = getTopicDir("/home/user/project", "test-slug");
416
+ expect(dir).toBe("/home/user/project/docs/research");
417
+ });
418
+ });
@@ -0,0 +1,127 @@
1
+ import { describe, it, expect } from "vitest";
2
+ import * as fs from "node:fs";
3
+ import * as path from "node:path";
4
+
5
+ // ============================================================
6
+ // Smoke Test: barrel export + package.json 检查
7
+ // ============================================================
8
+
9
+ describe("smoke: barrel export", () => {
10
+ it("所有公共 API 从 index.ts barrel export 成功", () => {
11
+ // 验证 barrel export 的 API 名称列表与 plan 一致
12
+ const exports = [
13
+ "runSubagent",
14
+ "loadAgentDef",
15
+ "createSubagentWidget",
16
+ "saveSubagentOutput",
17
+ "readSubagentOutput",
18
+ "createStateManager",
19
+ "createUIUpdater",
20
+ "registerWorkflowTool",
21
+ ];
22
+ const expectedTypeExports = [
23
+ "AgentDef",
24
+ "SubagentResult",
25
+ "SubagentEvent",
26
+ "ActionDef",
27
+ ];
28
+
29
+ // 验证函数名列表完整
30
+ expect(exports).toHaveLength(8);
31
+ expect(expectedTypeExports).toHaveLength(4);
32
+
33
+ // 全部函数名存在且无重复
34
+ const allNames = [...exports, ...expectedTypeExports];
35
+ const uniqueNames = new Set(allNames);
36
+ expect(uniqueNames.size).toBe(allNames.length);
37
+
38
+ // 验证 index.ts 中每个函数都有对应的子模块文件
39
+ const workflowDir = path.resolve(__dirname, "..");
40
+ const files = [
41
+ "subagent.ts",
42
+ "subagent-utils.ts",
43
+ "agent-loader.ts",
44
+ "widget.ts",
45
+ "output.ts",
46
+ "types.ts",
47
+ "state.ts",
48
+ "workflow.ts",
49
+ "index.ts",
50
+ ];
51
+ for (const file of files) {
52
+ const filePath = path.join(workflowDir, file);
53
+ expect(fs.existsSync(filePath)).toBe(true);
54
+ }
55
+ });
56
+
57
+ it("index.ts 包含所有 barrel export 语句", () => {
58
+ const indexPath = path.resolve(__dirname, "..", "index.ts");
59
+ const content = fs.readFileSync(indexPath, "utf-8");
60
+
61
+ // 验证导出语句
62
+ expect(content).toContain('export { runSubagent } from "./subagent"');
63
+ expect(content).toContain('export { loadAgentDef, type AgentDef } from "./agent-loader"');
64
+ expect(content).toContain('export { createSubagentWidget } from "./widget"');
65
+ expect(content).toContain('export { saveSubagentOutput, readSubagentOutput } from "./output"');
66
+ expect(content).toContain('export type { SubagentResult, SubagentEvent } from "./types"');
67
+ expect(content).toContain('export { createStateManager, createUIUpdater } from "./state"');
68
+ expect(content).toContain('export { registerWorkflowTool, type ActionDef } from "./workflow"');
69
+ });
70
+
71
+ it("package.json 字段完整", () => {
72
+ const pkgPath = path.resolve(__dirname, "..", "package.json");
73
+ const pkg = JSON.parse(fs.readFileSync(pkgPath, "utf-8"));
74
+
75
+ expect(pkg.name).toBe("workflow");
76
+ expect(pkg.version).toBe("1.0.0");
77
+ expect(pkg.type).toBe("commonjs");
78
+ expect(pkg.main).toBe("index.ts");
79
+
80
+ // dependencies 为空
81
+ expect(pkg.dependencies).toEqual({});
82
+
83
+ // peerDependencies 包含 pi-core 依赖
84
+ expect(pkg.peerDependencies?.["@earendil-works/pi-coding-agent"]).toBe("*");
85
+ expect(pkg.peerDependencies?.["@earendil-works/pi-tui"]).toBe("*");
86
+ expect(pkg.peerDependencies?.["typebox"]).toBe("*");
87
+
88
+ // devDependencies
89
+ expect(pkg.devDependencies?.["vitest"]).toBeDefined();
90
+ expect(pkg.devDependencies?.["@types/node"]).toBeDefined();
91
+ });
92
+
93
+ it("vitest.config.ts 存在且格式正确", () => {
94
+ const configPath = path.resolve(__dirname, "..", "vitest.config.ts");
95
+ const content = fs.readFileSync(configPath, "utf-8");
96
+
97
+ expect(content).toContain("defineConfig");
98
+ expect(content).toContain("tests/**/*.test.ts");
99
+ });
100
+
101
+ it("所有 .ts 文件行数不超过 200 行", () => {
102
+ const workflowDir = path.resolve(__dirname, "..");
103
+ const tsFiles = fs.readdirSync(workflowDir).filter(f => f.endsWith(".ts") && f !== "vitest.config.ts");
104
+
105
+ for (const file of tsFiles) {
106
+ const lines = fs.readFileSync(path.join(workflowDir, file), "utf-8").split("\n").length;
107
+ expect(
108
+ lines,
109
+ `${file} 行数 ${lines} 超过 200 行`,
110
+ ).toBeLessThanOrEqual(200);
111
+ }
112
+ });
113
+
114
+ it("types.ts 只导出 SubagentResult + SubagentEvent,不含 PV 专用类型", () => {
115
+ const typesPath = path.resolve(__dirname, "..", "types.ts");
116
+ const content = fs.readFileSync(typesPath, "utf-8");
117
+
118
+ // types.ts 不应包含 PV 专用类型
119
+ expect(content).not.toContain("PlanVerifyState");
120
+ expect(content).not.toContain("Phase");
121
+ expect(content).not.toContain("Issue");
122
+
123
+ // 应包含通用类型
124
+ expect(content).toContain("SubagentResult");
125
+ expect(content).toContain("SubagentEvent");
126
+ });
127
+ });