@andares/pi-toolkits 0.10.0 → 0.11.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/README.md CHANGED
@@ -56,6 +56,7 @@ After installing, verify in any pi session:
56
56
  - [🔎 review — third-party code review](#review)
57
57
  - [🗜️ compact — dedicated compaction model](#compact)
58
58
  - [🚀 autostart — session startup automation](#autostart)
59
+ - [🧠 init — agent memory framework](#init)
59
60
  - [Development](#development)
60
61
  - [Contributing](#contributing)
61
62
  - [License](#license)
@@ -75,6 +76,7 @@ After installing, verify in any pi session:
75
76
  | 🔎 **review** third-party code review | `/third-review` | summon the configured review model to check + fix the task just finished, focusing on "is this round's requirement implemented / is anything missing / is anything wrong" |
76
77
  | 🗜️ **compact** dedicated compaction model | `/compact-model` | give `/compact` and auto-compact a cheap fast model to summarize with, leaving the main model free to focus on the conversation; zero overhead when unconfigured, falls back to pi's default on any failure |
77
78
  | 🚀 **autostart** session startup automation | `.pi/autostart.toml` | declare slash commands to run automatically at session start, per project (first use case: mounting multi-repo directories with `/add-dir`); never runs in untrusted directories, unregistered commands are skipped instead of being sent to the model |
79
+ | 🧠 **init** agent memory framework | `/ask-init` | install or adopt a fixed memory layout (`AGENTS.md` + `specs/` + `.agents/memory` + `.agents/implementations`), migrate an existing one with a snapshot and a coverage table, and audit it later for drift, budgets and duplicated facts |
78
80
 
79
81
  ---
80
82
 
@@ -367,6 +369,87 @@ An **identical command line** declared by both sources runs once: a duplicate is
367
369
 
368
370
  ---
369
371
 
372
+ ## 🧠 init — agent memory framework
373
+
374
+ <a name="init"></a>
375
+
376
+ `/ask-init` installs one opinionated memory shape into a project, or adopts the
377
+ documentation that is already there. The point is not the directory names — it is
378
+ the split between three things that decay when mixed:
379
+
380
+ | Family | Location | Answers | Lifetime |
381
+ | --- | --- | --- | --- |
382
+ | **plan** | `specs/` (`PLAN.md` + `<unit>.md`) | what to do, how it will be accepted | written before work, status updated at close |
383
+ | **memory** | `.agents/memory/` | what is known, decided, and why | long-lived; append and compact only |
384
+ | **evidence** | `.agents/implementations/` | what changed, when, with what proof | one record per change, never rewritten |
385
+
386
+ Only agent-facing material moves under the hidden `.agents/` directory, so the
387
+ repository root stays readable: `AGENTS.md`, `specs/`, `design/`, `docs/`,
388
+ `legal/` remain visible and reviewable.
389
+
390
+ **Commands**:
391
+
392
+ | Command | What it does |
393
+ | --- | --- |
394
+ | `/ask-init` | detect → show the plan → (confirm) → move/scaffold/snapshot → dispatch the prose work to the model |
395
+ | `/ask-init plan [--deep]` | print the plan and write nothing (`--dry-run` is the same) |
396
+ | `/ask-init check` | audit the installed framework (read-only; writes only a runtime report under `.agents/framework/reports/`) |
397
+ | `/ask-init roots` | sync the directories added with `pi-add-dir` into the framework state |
398
+ | `/ask-init --yes` | skip the confirmation panel |
399
+ | `/ask-init --lang zh\|en` | language for generated prose (default: detected from the project's own docs) |
400
+
401
+ **What the mechanical half guarantees**:
402
+
403
+ 1. **Snapshot first** — every path the run may write (including every file whose
404
+ path references are rewritten) is copied to `.agents/framework/snapshots/<stamp>/`
405
+ with a sha256 manifest and the `git status` of that moment.
406
+ 2. **Writes stay inside the repository** — added roots are never written from
407
+ extension code; a scope card there is an ordinary tool call and therefore goes
408
+ through the permission gate.
409
+ 3. **Nothing is clobbered** — a create skips an existing path; a move refuses a
410
+ non-empty destination and turns the conflict into a manual task.
411
+ 4. **Counts reconcile** — the reference rewrite uses the same bare-reference
412
+ predicate as the survey, so "N occurrences in M files" from the plan is what
413
+ the run reports (and the rewrite report lists every file).
414
+ 5. **No silent loss** — a coverage table (`.agents/framework/reports/coverage-*.md`)
415
+ gets one row per migrated source section: found, declared with a destination, or
416
+ open with a reason. The audit fails while any row is open.
417
+
418
+ The prose half is a bounded work order with acceptance criteria per task: fill the
419
+ entry, merge the legacy plan, triage `todos/` into specs, deduplicate sections,
420
+ record budget debt, fill the coverage table. The model closes its own loop with the
421
+ `framework_audit` tool (activated for the run only).
422
+
423
+ **Migration of an existing project** moves `memory/`, `implementations/`,
424
+ `prompts/` under `.agents/` (one `git mv` each), moves `memory/PLAN.md` to
425
+ `specs/PLAN.md` byte-identically, and rewrites path references — with the counts
426
+ reported before and after. `todos/` is retired: requirement wording goes into the
427
+ unit spec verbatim. The default pass is conservative: install, fix mechanical
428
+ drift (tombstones, duplicated sections, appendix order), and record an over-budget
429
+ `AGENTS.md` as debt instead of rewriting prose; `--deep` opts into structural edits.
430
+
431
+ **Audit codes** (stable, so reports compare across runs): `E-PATH-01` bare legacy
432
+ paths, `E-STATE-01` memory gitignored, `W-STATE-01` memory not yet committed, `E-INDEX-01` index ↔ file
433
+ mismatch, `E-LINK-01` broken internal links, `W-BUDGET-01` `AGENTS.md` over budget,
434
+ `W-DUP-01` the same section in two files, `W-ORDER-01` sections appended after the
435
+ appendix, `W-COV-01` open coverage rows, `W-TODO-01` retired `todos/` still present,
436
+ `W-ROOT-02` zero-byte root files, `W-SCAFFOLD-01` unfilled `TODO(ask-init)` markers,
437
+ `I-INSTALL-01` framework not installed yet.
438
+
439
+ **Multi-repository workspaces**: memory lives in the main repository only.
440
+ `pi-add-dir` injects each added root's `AGENTS.md` verbatim into every request, so a
441
+ root entry must stay a **scope card** (≤30 lines: what lives there, its commands,
442
+ which main-repo memory file describes it) — never a second copy of the rules.
443
+
444
+ The framework contract shipped into a project is English (it is read by models and
445
+ published); text written *into* a project follows that project's language.
446
+
447
+ > **After the run**, `/reload` so the new `AGENTS.md` enters the prompt. The
448
+ > framework version lives in `.agents/framework/state.toml`; a project whose state
449
+ > version is newer than the installed tool is never migrated.
450
+
451
+ ---
452
+
370
453
  ## 🛠️ Development
371
454
 
372
455
  <a name="development"></a>
package/README.zh-CN.md CHANGED
@@ -56,6 +56,7 @@ pi -e ./src/index.ts
56
56
  - [🔎 review — 第三方代码评审](#review)
57
57
  - [🗜️ compact — 独立压缩模型](#compact)
58
58
  - [🚀 autostart — 会话启动自动化](#autostart)
59
+ - [🧠 init — agent 记忆框架](#init)
59
60
  - [开发](#development)
60
61
  - [贡献](#contributing)
61
62
  - [许可](#license)
@@ -75,6 +76,7 @@ pi -e ./src/index.ts
75
76
  | 🔎 **review** 第三方代码评审 | `/third-review` | 召唤配置的评审模型,对刚完成的任务做查+修,重点检查「本轮需求实现 / 是否有遗漏 / 是否有错误」 |
76
77
  | 🗜️ **compact** 独立压缩模型 | `/compact-model` | 给 `/compact` 与 auto-compact 配一个便宜快模型做总结,主模型专注对话;未配置零开销、任何异常回落 pi 默认 |
77
78
  | 🚀 **autostart** 会话启动自动化 | `.pi/autostart.toml` | 项目内声明启动时自动执行的斜杠命令(首批用例:`/add-dir` 多仓库挂载);未信任不执行、未注册命令跳过不发给模型 |
79
+ | 🧠 **init** agent 记忆框架 | `/ask-init` | 安装或接管一套固定的记忆结构(`AGENTS.md` + `specs/` + `.agents/memory` + `.agents/implementations`),带快照与覆盖表迁移旧文档,之后可随时审计漂移、预算与重复事实 |
78
80
 
79
81
  ---
80
82
 
@@ -367,6 +369,71 @@ run = [
367
369
 
368
370
  ---
369
371
 
372
+ ## 🧠 init — agent 记忆框架
373
+
374
+ <a name="init"></a>
375
+
376
+ `/ask-init` 给项目安装一套有明确立场的记忆结构,或者接管项目里已经存在的文档。
377
+ 重点不是目录名,而是把三样混在一起必然腐烂的东西分开:
378
+
379
+ | 家庭 | 位置 | 回答什么 | 生命周期 |
380
+ | --- | --- | --- | --- |
381
+ | **计划** | `specs/`(`PLAN.md` + `<unit>.md`) | 要做什么、怎么验收 | 开工前写,结项时更新状态 |
382
+ | **记忆** | `.agents/memory/` | 已知什么、定过什么、为什么 | 长期;只追加、只压缩 |
383
+ | **证据** | `.agents/implementations/` | 改了什么、什么时候、证据在哪 | 一次写定,不再改写 |
384
+
385
+ 只有「纯给 agent 看」的东西进隐藏目录 `.agents/`,所以仓库根仍然清爽:
386
+ `AGENTS.md`、`specs/`、`design/`、`docs/`、`legal/` 都留在外面可读可审。
387
+
388
+ **命令**:
389
+
390
+ | 命令 | 作用 |
391
+ | --- | --- |
392
+ | `/ask-init` | 检测 → 出计划 → 确认 → 移动/脚手架/快照 → 把正文工作派发给模型 |
393
+ | `/ask-init plan [--deep]` | 只打印计划,不写任何盘(`--dry-run` 同义) |
394
+ | `/ask-init check` | 审计已装的框架(只读;只在 `.agents/framework/reports/` 留下运行期报告) |
395
+ | `/ask-init roots` | 把 `pi-add-dir` 添加的目录同步进框架状态 |
396
+ | `/ask-init --yes` | 跳过确认面板 |
397
+ | `/ask-init --lang zh\|en` | 生成正文的语言(默认按项目自身文档判定) |
398
+
399
+ **机械那一半保证什么**:
400
+
401
+ 1. **先快照再动** —— 本次可能写的每一条路径(包括所有会被改写的引用文件)都复制到
402
+ `.agents/framework/snapshots/<stamp>/`,并带 sha256 清单与当时的 `git status`。
403
+ 2. **只写仓内** —— 扩展代码绝不写 added root;在那里建 scope card 是普通工具调用,
404
+ 因此会经过权限闸门。
405
+ 3. **不覆盖** —— 创建时已存在的文件跳过;移动时目标非空则拒绝,并转成人工任务。
406
+ 4. **计数对账** —— 引用改写与检测用同一个「裸路径」判定,计划里的「N 处 / M 个文件」
407
+ 就是运行时报告的数字(并附逐文件清单)。
408
+ 5. **不静默丢内容** —— 迁移的每个源章节在覆盖表里都有一行:命中、声明去向、或标记
409
+ OPEN 并写理由;只要还有 OPEN,审计就不算通过。
410
+
411
+ 正文那一半是一份带验收标准的工作单:填空入口、合并旧计划、把 `todos/` 收敛进 specs、
412
+ 去重章节、登记预算债务、填覆盖表。模型用只在本轮激活的 `framework_audit` 工具自检收口。
413
+
414
+ **迁移既有项目**会把 `memory/`、`implementations/`、`prompts/` 移到 `.agents/` 下
415
+ (逐个 `git mv`),把 `memory/PLAN.md` 原样搬到 `specs/PLAN.md`,再改写路径引用,
416
+ 前后计数都会报出来。`todos/` 退役:需求原文原样进对应单元的 spec。默认是**保守 pass**:
417
+ 装框架、修机械漂移(墓碑、重复章节、附录顺序),超预算的 `AGENTS.md` 只登记成债务;
418
+ `--deep` 才允许结构性改写。
419
+
420
+ **审计码**(稳定,可跨次对比):`E-PATH-01` 裸旧路径、`E-STATE-01` 记忆被 gitignore、`W-STATE-01` 记忆尚未提交、`E-INDEX-01` 索引与实际文件不一致、`E-LINK-01` 内部链接失效、
421
+ `W-BUDGET-01` `AGENTS.md` 超预算、`W-DUP-01` 同一章节出现在两个文件、
422
+ `W-ORDER-01` 附录之后又追加章节、`W-COV-01` 覆盖表仍有 OPEN、
423
+ `W-TODO-01` 仍存在退役的 `todos/`、`W-ROOT-02` 根下零字节文件、
424
+ `W-SCAFFOLD-01` 未填的 `TODO(ask-init)` 标记、`I-INSTALL-01` 尚未安装框架。
425
+
426
+ **多仓库工作区**:记忆只住主仓。`pi-add-dir` 会把每个 added root 的 `AGENTS.md`
427
+ 全文注入每次请求,所以根里的入口只能是 **scope card**(≤30 行:这里放什么、它的命令、
428
+ 去主仓哪个记忆文件读),绝不能是规则的第二份副本。
429
+
430
+ 装进项目的框架契约用英文(给模型读、也随 npm 发布);写进项目的正文跟随项目语言。
431
+
432
+ > **跑完记得 `/reload`**,让新的 `AGENTS.md` 进入提示词。框架版本记在
433
+ > `.agents/framework/state.toml`;若项目的状态版本比当前工具新,则拒绝迁移。
434
+
435
+ ---
436
+
370
437
  ## 🛠️ 开发
371
438
 
372
439
  <a name="development"></a>
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@andares/pi-toolkits",
3
- "version": "0.10.0",
4
- "description": "Integrated toolkit extension for pi — ask mode (read-only Q&A), session-scoped permission checks, model favorites, prompt stash, third-party code review, session autostart, and a dedicated compaction model",
3
+ "version": "0.11.0",
4
+ "description": "Integrated toolkit extension for pi — ask mode (read-only Q&A), session-scoped permission checks, model favorites, prompt stash, third-party code review, session autostart, a dedicated compaction model, and an agent memory framework (/ask-init)",
5
5
  "type": "module",
6
6
  "license": "MIT",
7
7
  "repository": {
@@ -30,7 +30,11 @@
30
30
  "autostart",
31
31
  "permission",
32
32
  "approval",
33
- "boundary"
33
+ "boundary",
34
+ "agent-memory",
35
+ "memory-framework",
36
+ "scaffold",
37
+ "init"
34
38
  ],
35
39
  "peerDependencies": {
36
40
  "@earendil-works/pi-coding-agent": ">=0.99.0",
@@ -0,0 +1,162 @@
1
+ /**
2
+ * init feature — pure document analysis shared by the planner and the auditor.
3
+ *
4
+ * These helpers answer questions about *documents*, not about the filesystem:
5
+ * duplicated sections, tombstones, appendix ordering, oversized sections and
6
+ * path references. Keeping them here means the plan's warnings and the audit's
7
+ * findings cannot drift apart.
8
+ */
9
+ import type { DocInfo, Heading } from "./types.js";
10
+
11
+ /** Normalise a heading for comparison: drop numbering, markup, emoji, case. */
12
+ export function normalizeHeading(text: string): string {
13
+ return text
14
+ .replace(/^[§#\s]*\d+(?:[.\-–]\d+)*[.、:)]?\s*/, "")
15
+ .replace(/[`*_~[\]]/g, "")
16
+ .replace(/[\p{Emoji_Presentation}\p{Extended_Pictographic}]/gu, "")
17
+ .replace(/[\s\u3000]+/g, "")
18
+ .replace(/[::,,。.、()()]/g, "")
19
+ .toLowerCase();
20
+ }
21
+
22
+ /** H2 headings (level 2 only) of a document. */
23
+ export function topSections(doc: DocInfo): Heading[] {
24
+ return doc.headings.filter((heading) => heading.level === 2);
25
+ }
26
+
27
+ export interface DuplicateGroup {
28
+ readonly normalized: string;
29
+ readonly occurrences: Array<{ path: string; heading: string; line: number }>;
30
+ }
31
+
32
+ /** Same H2 heading appearing in two or more documents. */
33
+ export function duplicateHeadings(docs: readonly DocInfo[]): DuplicateGroup[] {
34
+ const groups = new Map<string, DuplicateGroup["occurrences"]>();
35
+ for (const doc of docs) {
36
+ for (const heading of topSections(doc)) {
37
+ const key = normalizeHeading(heading.text);
38
+ if (key.length < 2) continue;
39
+ const list = groups.get(key) ?? [];
40
+ list.push({ path: doc.rel, heading: heading.text, line: heading.line });
41
+ groups.set(key, list);
42
+ }
43
+ }
44
+ const out: DuplicateGroup[] = [];
45
+ for (const [normalized, occurrences] of groups) {
46
+ if (occurrences.length < 2) continue;
47
+ // Same file twice is a different problem (repeated section), still useful.
48
+ out.push({ normalized, occurrences });
49
+ }
50
+ return out.sort((a, b) => b.occurrences.length - a.occurrences.length);
51
+ }
52
+
53
+ /** Section bodies as `[heading, body]`, body ending at the next same-or-higher heading. */
54
+ export function sectionBodies(doc: DocInfo): Array<{ heading: Heading; body: string }> {
55
+ const lines = doc.text.split("\n");
56
+ const out: Array<{ heading: Heading; body: string }> = [];
57
+ for (const heading of doc.headings) {
58
+ if (heading.level !== 2) continue;
59
+ const start = heading.line; // 0-based index of the line *after* the heading
60
+ let end = lines.length;
61
+ for (const other of doc.headings) {
62
+ if (other.line <= heading.line) continue;
63
+ if (other.level <= 2) {
64
+ end = other.line - 1;
65
+ break;
66
+ }
67
+ }
68
+ out.push({ heading, body: lines.slice(start, end).join("\n").trim() });
69
+ }
70
+ return out;
71
+ }
72
+
73
+ const POINTER_PHRASES =
74
+ /(已迁|迁至|移至|见\s*`|参见\s*`|moved to|see\s+`|已并入|merged into)/i;
75
+
76
+ /**
77
+ * A "tombstone": a section whose whole body is a one-line pointer to wherever
78
+ * the content went. After the move is registered in the index such sections are
79
+ * pure noise, so the plan asks for their removal.
80
+ */
81
+ export function tombstones(doc: DocInfo): Heading[] {
82
+ const out: Heading[] = [];
83
+ for (const { heading, body } of sectionBodies(doc)) {
84
+ if (body.length === 0 || body.length > 220) continue;
85
+ if (!POINTER_PHRASES.test(body)) continue;
86
+ const meaningful = body
87
+ .split("\n")
88
+ .map((line) => line.trim())
89
+ .filter((line) => line.length > 0 && !line.startsWith("|"));
90
+ if (meaningful.length <= 3) out.push(heading);
91
+ }
92
+ return out;
93
+ }
94
+
95
+ /**
96
+ * Headings that sit after the historical appendix started. Appendices are the
97
+ * last thing in a document by convention; dated sections appended later mean
98
+ * the file grew without a compacting pass.
99
+ */
100
+ export function sectionsAfterAppendix(doc: DocInfo): Heading[] {
101
+ const sections = topSections(doc);
102
+ const firstAppendix = sections.findIndex((heading) =>
103
+ /^(附录|appendix)/i.test(heading.text.trim()),
104
+ );
105
+ if (firstAppendix < 0) return [];
106
+ return sections
107
+ .slice(firstAppendix + 1)
108
+ .filter((heading) => !/^(附录|appendix)/i.test(heading.text.trim()));
109
+ }
110
+
111
+ /** The N largest H2 sections, with their character counts (split candidates). */
112
+ export function largestSections(
113
+ doc: DocInfo,
114
+ limit = 3,
115
+ ): Array<{ heading: Heading; chars: number }> {
116
+ return sectionBodies(doc)
117
+ .map(({ heading, body }) => ({ heading, chars: body.length }))
118
+ .sort((a, b) => b.chars - a.chars)
119
+ .slice(0, limit);
120
+ }
121
+
122
+ /**
123
+ * Paths mentioned in a document that the framework can verify: memory files,
124
+ * specs, implementation records. Returned without the surrounding backticks so
125
+ * callers can `existsSync` them directly.
126
+ */
127
+ export function extractFrameworkPaths(text: string): string[] {
128
+ const out = new Set<string>();
129
+ const re =
130
+ /(?:\.agents\/memory\/(?:[\w.\-]+\.md)|specs\/[\w./-]+\.md|\.agents\/implementations\/[\w.\-]+\.md)/g;
131
+ for (const match of text.matchAll(re)) out.add(match[0]);
132
+ return [...out];
133
+ }
134
+
135
+ /** First paragraph of a section, used as the coverage anchor. */
136
+ export function sectionAnchor(doc: DocInfo, heading: Heading): string {
137
+ const lines = doc.text.split("\n");
138
+ let index = heading.line; // first line after the heading
139
+ let collected = "";
140
+ let started = false;
141
+ for (; index < lines.length; index += 1) {
142
+ const line = lines[index].trim();
143
+ if (/^#{1,6}\s/.test(line)) break;
144
+ if (line.length === 0) {
145
+ if (started) break;
146
+ continue;
147
+ }
148
+ if (/^([-*+]\s|\d+[.)]\s|\||>)/.test(line)) continue;
149
+ collected = collected.length === 0 ? line : `${collected} ${line}`;
150
+ started = true;
151
+ if (collected.length >= 80) break;
152
+ }
153
+ return collected.slice(0, 80);
154
+ }
155
+
156
+ /** Normalise prose for anchor matching (drop markdown emphasis and spacing). */
157
+ export function normalizeProse(text: string): string {
158
+ return text
159
+ .replace(/[`*_~[\]]/g, "")
160
+ .replace(/[\s\u3000]+/g, "")
161
+ .toLowerCase();
162
+ }
@@ -0,0 +1,264 @@
1
+ import { describe, expect, it } from "vitest";
2
+ import { createHash } from "node:crypto";
3
+ import { existsSync, readFileSync, writeFileSync } from "node:fs";
4
+ import { join } from "node:path";
5
+ import { applyPlan, rewriteText, stateToToml } from "./apply.js";
6
+ import { parseState } from "./detect.js";
7
+ import { detect } from "./detect.js";
8
+ import { buildPlan } from "./plan.js";
9
+ import { installedProject, project, remove } from "./test-helpers.js";
10
+ import type { Plan } from "./types.js";
11
+
12
+ const ORIGINAL_PLAN = "# 计划\n\n## 路线\n\n- M1 未完成\n";
13
+ const LEGACY: Record<string, string> = {
14
+ "AGENTS.md": [
15
+ "# demo — 项目指南",
16
+ "",
17
+ "细节记忆放在 `memory/`。",
18
+ "",
19
+ "## 8. 问题清单",
20
+ "",
21
+ "已迁至 `memory/PLAN.md` §5。",
22
+ "",
23
+ ].join("\n"),
24
+ "memory/PLAN.md": ORIGINAL_PLAN,
25
+ "memory/FINISHED.md": "# 已完成\n\n## 摘要\n\n- M0:见 `implementations/2026-01-01_a.md`\n",
26
+ "memory/ARCHITECTURE.md": "# 架构\n\n## 分层\n\n- 见 `memory/DESIGN.md`\n",
27
+ "memory/DESIGN.md": "# 视觉\n",
28
+ "implementations/2026-01-01_a.md": "# a\n\n见 `memory/ARCHITECTURE.md`。\n",
29
+ "specs/a.md": "# a\n\n证据:`implementations/2026-01-01_a.md`。\n",
30
+ "todos/2026-01-02-x.md": "# 原始需求\n\n做点事。\n",
31
+ "src/a.ts": "// 见 `memory/DESIGN.md`\n",
32
+ };
33
+
34
+ function planFor(root: string): Plan {
35
+ return buildPlan(detect(root), {
36
+ toolVersion: "test",
37
+ now: new Date("2026-10-26T10:00:00+08:00"),
38
+ });
39
+ }
40
+
41
+ describe("rewriteText", () => {
42
+ const pairs = [
43
+ { from: "memory/PLAN.md", to: "specs/PLAN.md" },
44
+ { from: "memory/", to: ".agents/memory/" },
45
+ ];
46
+
47
+ it("applies the longest prefix first", () => {
48
+ const result = rewriteText("see `memory/PLAN.md` and `memory/X.md`", pairs);
49
+ expect(result.text).toBe("see `specs/PLAN.md` and `.agents/memory/X.md`");
50
+ expect(result.hits).toBe(2);
51
+ });
52
+
53
+ it("leaves already-migrated paths and path tails alone", () => {
54
+ const result = rewriteText("`.agents/memory/X.md` ~/.pi/agent/memory/y", pairs);
55
+ expect(result.text).toBe("`.agents/memory/X.md` ~/.pi/agent/memory/y");
56
+ expect(result.hits).toBe(0);
57
+ });
58
+ });
59
+
60
+ describe("applyPlan", () => {
61
+ it("moves the legacy layout, rewrites references and keeps the originals", () => {
62
+ const root = project(LEGACY);
63
+ try {
64
+ const plan = planFor(root);
65
+ const expectedHits = plan.facts.refs.hits;
66
+ const applied = applyPlan(plan, { now: new Date("2026-10-26T10:00:00+08:00") });
67
+
68
+ expect(existsSync(join(root, "memory"))).toBe(false);
69
+ expect(existsSync(join(root, "implementations"))).toBe(false);
70
+ expect(existsSync(join(root, ".agents/memory/FINISHED.md"))).toBe(true);
71
+ expect(existsSync(join(root, ".agents/implementations/2026-01-01_a.md"))).toBe(true);
72
+
73
+ // The plan file moves byte-identically; the model shapes it afterwards.
74
+ expect(readFileSync(join(root, "specs/PLAN.md"), "utf8")).toBe(ORIGINAL_PLAN);
75
+
76
+ // References are rewritten in prose and code alike.
77
+ expect(readFileSync(join(root, "src/a.ts"), "utf8")).toContain(".agents/memory/DESIGN.md");
78
+ expect(readFileSync(join(root, "specs/a.md"), "utf8")).toContain(
79
+ ".agents/implementations/2026-01-01_a.md",
80
+ );
81
+ const agents = readFileSync(join(root, "AGENTS.md"), "utf8");
82
+ expect(agents).toContain(".agents/memory/");
83
+ expect(agents).toContain("specs/PLAN.md");
84
+
85
+ // Snapshot keeps the pre-move bytes (and therefore the old paths).
86
+ expect(applied.snapshot?.dir).toMatch(/^\.agents\/framework\/snapshots\//);
87
+ const snapshotFile = join(root, applied.snapshot?.dir ?? "", "files/src/a.ts");
88
+ expect(readFileSync(snapshotFile, "utf8")).toContain("memory/DESIGN.md");
89
+ expect(existsSync(join(root, applied.snapshot?.dir ?? "", "manifest.json"))).toBe(true);
90
+
91
+ // Counts reconcile with the survey.
92
+ expect(applied.rewrites?.hits).toBe(expectedHits);
93
+
94
+ // State, work order and coverage worklist exist and are readable.
95
+ expect(applied.statePath).toBe(".agents/framework/state.toml");
96
+ const state = parseState(readFileSync(join(root, ".agents/framework/state.toml"), "utf8"));
97
+ expect(state.version).toBe(1);
98
+ expect(state.migrations.length).toBeGreaterThan(0);
99
+ expect(state.lang).toBe("zh");
100
+ expect(applied.planPath).toMatch(/^\.agents\/framework\/plans\/plan-.*\.json$/);
101
+ const order = JSON.parse(readFileSync(join(root, applied.planPath ?? ""), "utf8")) as {
102
+ tasks: Array<{ id: string }>;
103
+ };
104
+ expect(order.tasks.map((task) => task.id)).toContain("triage-todos");
105
+ expect(applied.created).toContain(".agents/memory/README.md");
106
+
107
+ expect(plan.artifacts.coverage).toMatch(/^\.agents\/framework\/reports\/coverage-.*\.md$/);
108
+ const coverage = readFileSync(join(root, plan.artifacts.coverage ?? ""), "utf8");
109
+ expect(coverage).toContain("OPEN");
110
+ expect(coverage).toContain("AGENTS.md");
111
+ } finally {
112
+ remove(root);
113
+ }
114
+ });
115
+
116
+ it("is safe to run twice", () => {
117
+ const root = project(LEGACY);
118
+ try {
119
+ const plan = planFor(root);
120
+ applyPlan(plan, { now: new Date("2026-10-26T10:00:00+08:00") });
121
+ const second = applyPlan(plan, { now: new Date("2026-10-26T10:05:00+08:00") });
122
+ expect(second.moved).toHaveLength(0);
123
+ expect(second.rewrites?.hits).toBe(0);
124
+ expect(second.skipped.length).toBeGreaterThan(0);
125
+ expect(existsSync(join(root, ".agents/memory/FINISHED.md"))).toBe(true);
126
+ expect(existsSync(join(root, "memory"))).toBe(false);
127
+ } finally {
128
+ remove(root);
129
+ }
130
+ });
131
+
132
+ it("writes nothing on a dry run", () => {
133
+ const root = project(LEGACY);
134
+ try {
135
+ const plan = planFor(root);
136
+ applyPlan(plan, {
137
+ dryRun: true,
138
+ now: new Date("2026-10-26T10:00:00+08:00"),
139
+ });
140
+ expect(existsSync(join(root, "memory"))).toBe(true);
141
+ expect(existsSync(join(root, ".agents"))).toBe(false);
142
+ } finally {
143
+ remove(root);
144
+ }
145
+ });
146
+
147
+ it("does not merge two copies of a directory on its own", () => {
148
+ const root = installedProject({
149
+ "memory/FINISHED.md": "# old finished\n",
150
+ });
151
+ try {
152
+ const plan = planFor(root);
153
+ expect(plan.mode).toBe("reconcile");
154
+ applyPlan(plan, { now: new Date("2026-10-26T10:00:00+08:00") });
155
+ expect(existsSync(join(root, "memory/FINISHED.md"))).toBe(true);
156
+ expect(readFileSync(join(root, ".agents/memory/FINISHED.md"), "utf8")).toContain("Summary");
157
+ } finally {
158
+ remove(root);
159
+ }
160
+ });
161
+
162
+ it("round-trips state through TOML", () => {
163
+ const root = installedProject();
164
+ try {
165
+ const plan = planFor(root);
166
+ const state = {
167
+ version: 1,
168
+ tool: "9.9.9",
169
+ created: "2026-01-01T00:00:00+08:00",
170
+ updated: "2026-01-02T00:00:00+08:00",
171
+ profile: "core" as const,
172
+ modules: ["design"],
173
+ lang: "zh" as const,
174
+ roots: [
175
+ {
176
+ label: "api",
177
+ path: "../api",
178
+ absolute: "/tmp/api",
179
+ role: "backend",
180
+ agentsMd: "scope-card" as const,
181
+ source: "add-dir" as const,
182
+ exists: true,
183
+ lastSeen: "2026-01-02T00:00:00+08:00",
184
+ },
185
+ ],
186
+ managed: [],
187
+ migrations: [{ at: "2026-01-02T00:00:00+08:00", to: "1", notes: "adopt" }],
188
+ };
189
+ const parsed = parseState(stateToToml(state));
190
+ expect(parsed.roots[0]).toMatchObject({ label: "api", agentsMd: "scope-card" });
191
+ expect(parsed.migrations[0].notes).toBe("adopt");
192
+ expect(parsed.budgets).toBeUndefined();
193
+ void plan;
194
+ } finally {
195
+ remove(root);
196
+ }
197
+ });
198
+ });
199
+
200
+
201
+ describe("review regressions", () => {
202
+ it("preserves relative prefixes while rewriting", () => {
203
+ const result = rewriteText("see `../memory/A.md` and `./implementations/B.md`", [
204
+ { from: "memory/", to: ".agents/memory/" },
205
+ { from: "implementations/", to: ".agents/implementations/" },
206
+ ]);
207
+ expect(result.text).toBe(
208
+ "see `../.agents/memory/A.md` and `./.agents/implementations/B.md`",
209
+ );
210
+ expect(result.hits).toBe(2);
211
+ });
212
+
213
+ it("records managed hashes after the reference rewrite", () => {
214
+ const root = project(LEGACY);
215
+ try {
216
+ applyPlan(planFor(root), { now: new Date("2026-10-26T10:00:00+08:00") });
217
+ const state = parseState(readFileSync(join(root, ".agents/framework/state.toml"), "utf8"));
218
+ for (const entry of state.managed) {
219
+ const digest = createHash("sha256")
220
+ .update(readFileSync(join(root, entry.path)))
221
+ .digest("hex");
222
+ expect(entry.sha256, entry.path).toBe(digest);
223
+ }
224
+ } finally {
225
+ remove(root);
226
+ }
227
+ });
228
+
229
+ it("moves a root-level PLAN.md into the plan home", () => {
230
+ const root = project({
231
+ "AGENTS.md": "# demo\n\nSee `PLAN.md`.\n",
232
+ "PLAN.md": "# Plan\n\n## Route\n\n- open item\n",
233
+ });
234
+ try {
235
+ const plan = planFor(root);
236
+ const move = plan.actions.find((action) => action.kind === "move-file");
237
+ expect(move && move.kind === "move-file" ? move.from : "").toBe("PLAN.md");
238
+ expect(plan.tasks.some((task) => task.id === "edit-plan")).toBe(true);
239
+ const applied = applyPlan(plan, { now: new Date("2026-10-26T10:00:00+08:00") });
240
+ expect(existsSync(join(root, "PLAN.md"))).toBe(false);
241
+ expect(readFileSync(join(root, "specs/PLAN.md"), "utf8")).toContain("open item");
242
+ // The moved source must be recoverable, not just the destination.
243
+ expect(
244
+ existsSync(join(root, applied.snapshot?.dir ?? "", "files/PLAN.md")),
245
+ ).toBe(true);
246
+ } finally {
247
+ remove(root);
248
+ }
249
+ });
250
+ });
251
+
252
+
253
+ it("does not corrupt non-UTF-8 files during reference rewriting", () => {
254
+ const root = project(LEGACY);
255
+ try {
256
+ const latin = Buffer.from("// see `memory/DESIGN.md` — caf\xe9\n", "latin1");
257
+ writeFileSync(join(root, "src/latin1.ts"), latin);
258
+ applyPlan(planFor(root), { now: new Date("2026-10-26T10:00:00+08:00") });
259
+ expect(readFileSync(join(root, "src/latin1.ts"))).toEqual(latin);
260
+ expect(readFileSync(join(root, "src/a.ts"), "utf8")).toContain(".agents/memory/DESIGN.md");
261
+ } finally {
262
+ remove(root);
263
+ }
264
+ });