sage-mem 2.12.1 → 2.15.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.en.md +9 -6
- package/README.md +10 -7
- package/lib/autodream/audit.js +170 -16
- package/lib/client.js +614 -66
- package/lib/index.js +13 -1
- package/lib/memory/checkpoint.js +3 -2
- package/lib/memory/frontmatter.js +59 -12
- package/lib/memory/scan.js +56 -0
- package/lib/memory/trim-plan.js +34 -14
- package/lib/shared/hash.js +117 -0
- package/lib/typert.host.js +37 -0
- package/package.json +1 -1
- package/skills/sage-mem/SKILL.md +1 -0
package/README.en.md
CHANGED
|
@@ -12,7 +12,7 @@
|
|
|
12
12
|
|
|
13
13
|
**Cross-session memory for DeepSeek Harness — plain markdown files, no database, no worker.**
|
|
14
14
|
|
|
15
|
-
**Current release: `2.
|
|
15
|
+
**Current release: `2.15.0`** — the npm badge above is the dynamic source of truth. **Contract baseline: `1.0.0`** — the first stable release, whose public commitments, the capability boundaries and the list of things it explicitly cannot do are frozen in the
|
|
16
16
|
[frozen contract](https://github.com/gezi-wen/sage-mem/blob/main/docs/1.0.0-contract.md).
|
|
17
17
|
|
|
18
18
|
If it is useful to you, a Star is the most direct feedback.
|
|
@@ -193,7 +193,7 @@ Since 1.9.0 the memory-management surface follows the harness language (**Settin
|
|
|
193
193
|
|
|
194
194
|

|
|
195
195
|
|
|
196
|
-
*Health — one screen answers "is anything wrong with this library": the **conflict queue on top** (a finite list that needs your decision: which of two contradictory statements is void) and the **audit below** (dangling index entries, missing index entries, broken links and the rest, reported in red by category). "Points to an archived memory" is only a hint — it does not count as a problem, and there is **no one-click fix**: which one to change is your call. The audit only reports and never modifies. Since 2.10.1 it has two size categories: **over-size memories** (40 KB or more counts as a problem; 16–40 KB is only a hint — 2.10.2 raised both lines from 8/16 KB) and an **over-long index** (report only, see [size governance](#size-governance-what-to-do-when-a-memory-grows-too-big)). When there is really something to deal with, the badge gets a **「复制修复提示词」(copy fix prompt)** button next to it (2.6.0): it turns what this screen needs into one prompt in your clipboard — **the audit problems and the pending conflicts are written as two separate sections** (fix these / only advise on those), so you can paste it to the agent and let it work. A receipt appears at the bottom afterwards — it closes itself in 10 seconds, closes as soon as you switch tabs, and you can dismiss it by hand.*
|
|
196
|
+
*Health — one screen answers "is anything wrong with this library": the **conflict queue on top** (a finite list that needs your decision: which of two contradictory statements is void) and the **audit below** (dangling index entries, missing index entries, broken links and the rest, reported in red by category). "Points to an archived memory" is only a hint — it does not count as a problem, and there is **no one-click fix**: which one to change is your call. The audit only reports and never modifies. Since 2.10.1 it has two size categories: **over-size memories** (40 KB or more counts as a problem; 16–40 KB is only a hint — 2.10.2 raised both lines from 8/16 KB) and an **over-long index** (report only, see [size governance](#size-governance-what-to-do-when-a-memory-grows-too-big)). Since 2.14.0 it adds two more **hints** (neither counts as a problem): **orphaned archive pieces** (the memory a slice came from is gone, or two archived files are byte-identical) and **index slimming proposals** (dangling entries and over-long lines pinned to a line number — whether to change them is your call); it also fills in two categories that used to count as problems without any place to render — **multiple index variants** and **over-size memories**. When there is really something to deal with, the badge gets a **「复制修复提示词」(copy fix prompt)** button next to it (2.6.0): it turns what this screen needs into one prompt in your clipboard — **the audit problems and the pending conflicts are written as two separate sections** (fix these / only advise on those), so you can paste it to the agent and let it work. A receipt appears at the bottom afterwards — it closes itself in 10 seconds, closes as soon as you switch tabs, and you can dismiss it by hand.*
|
|
197
197
|
|
|
198
198
|
*Lab (2.9.0, sits after Health) — only switches that change **which memories are picked**, all off by default. Today it holds one: **MMR de-duplication**. When one topic takes every injection slot, it subtracts each candidate's similarity to what is already picked before choosing. It only changes **which items are picked** (never the score, never a file, never a pinned baseline memory) and returns candidates as-is when they fit the slots. Why it is off by default: in the offline comparison it never fired (the IDF gate already keeps candidates under 10), and in a stress run with the gate disabled duplication fell only 4.5% while wrong picks rose 24% — it knows "different", not "irrelevant". Read the three notes on that page before turning it on; **if memories seem to go missing, switch it off and restart**.
|
|
199
199
|
|
|
@@ -445,7 +445,7 @@ It records item by item: **file / operation (create · rewrite · archive) / rea
|
|
|
445
445
|
|
|
446
446
|
1. **The safety boundary is in the tool set, not in the prompt** — during autodream the host gives the model only read-only tools, and only rewrite mode adds the rewriting tools; and **there is no "delete" capability at all** — archiving moves a file into `archive/`, recoverable by hand.
|
|
447
447
|
2. **A rollback point is created automatically before rewriting**, under `<parent of the memory directory>/.sage-mem/autodream/snapshots/<runId>/`, keeping the most recent N. The reason: the memory directory is **not under any version control** and deletion has no recycle bin, so "rollback-ability" has to be built by hand.
|
|
448
|
-
3. **An audit runs automatically at the end** — dangling index entries, missing index entries, `type` disagreeing with the file name prefix, CRLF, broken wikilinks, "space + #" swallowed as a YAML comment inside frontmatter, missing frontmatter, temporary files left behind by an interrupted archive, plus "unreadable" as a category of its own, and the result and the before/after comparison are written into the report. It **only reports, it does not change**. The index `MEMORY.md` is a list, not a memory, so it takes part in **neither** the "type vs prefix" check nor the "missing frontmatter" check (since 1.9.1).
|
|
448
|
+
3. **An audit runs automatically at the end** — dangling index entries, missing index entries, `type` disagreeing with the file name prefix, CRLF, broken wikilinks, "space + #" swallowed as a YAML comment inside frontmatter, missing frontmatter, temporary files left behind by an interrupted archive, plus "unreadable" as a category of its own, and the result and the before/after comparison are written into the report. Since 2.14.0 it also reports **orphaned archive pieces** (the memory a slice came from is gone, or two archived files are identical) and **index slimming proposals** (dangling entries and over-long lines pinned to a line number) — same rule: report only, never counted as problems. It **only reports, it does not change**. The index `MEMORY.md` is a list, not a memory, so it takes part in **neither** the "type vs prefix" check nor the "missing frontmatter" check (since 1.9.1).
|
|
449
449
|
|
|
450
450
|
### Rename Note
|
|
451
451
|
|
|
@@ -464,15 +464,18 @@ The two things are moved **differently**, spelled out:
|
|
|
464
464
|
|
|
465
465
|
⚠️ **The premise is that the shape matches.** The four-type division and the frontmatter are sage-mem's own conventions: if your memories in CC were already "one Markdown file per memory + frontmatter" (which is what ours were at the time), just copy them over; **if they were not** (if they were all piled into a single `CLAUDE.md`, say), you need to organize them first — and that job can perfectly well be handed to an agent: have it read the old material and lay it out as files under the four types.
|
|
466
466
|
|
|
467
|
-
## To-do Board (experimental · since 2.11.0;
|
|
467
|
+
## To-do Board (experimental · since 2.11.0; wrapped up in 2.15.0)
|
|
468
468
|
|
|
469
469
|
`project_session-state.md` in the memory directory has always been a to-do list you keep for yourself: injected into every session, but you still have to open the file to see what is left. 2.11.0 puts it in the **right sidebar**: Settings → Memory management → Lab → enable "To-do board", and the sidebar's Start page gains a card that opens a tab.
|
|
470
470
|
|
|
471
471
|
- **Ticking = moving**: a finished item is removed from its group and appended to the "Done, pending deletion" block (created at the end of the file on first use); un-ticking moves it back to the end of its original group. "Clear all" is what actually deletes rows.
|
|
472
|
-
- **Edit it**: add an item at the end of a group, edit one in place, undo / redo
|
|
472
|
+
- **Edit it**: add an item at the end of a group, edit one in place, undo / redo **3–5 steps** (5 by default).
|
|
473
|
+
- **See only what is open**: the default filter is "Open" (legacy `- [x]` lines appear under "All"; the pending-deletion block always shows, since it is a queue). Each group remembers whether it was expanded.
|
|
474
|
+
- **Wrap-up has a button**: **"Move to log"** on the pending-deletion block appends the rows to `session-log.md` and removes them from the list — log first, list second, verbatim text, already-logged rows skipped, **not undoable**.
|
|
475
|
+
- **See work owed elsewhere**: the 未完成 (open-work) section of `tasks/*/WORKING.md` is aggregated into a **read-only** block (never merged back).
|
|
473
476
|
- **The file is still the only truth**: the board does line-level surgery only; edit the file with any tool and the board follows within 4 seconds.
|
|
474
477
|
- **Hot**: flipping the switch takes effect immediately, no restart (unlike MMR).
|
|
475
|
-
- **Off by default**; no drag-and-drop ordering
|
|
478
|
+
- **Off by default**; no drag-and-drop ordering. Details in `docs/todo-board.md`.
|
|
476
479
|
|
|
477
480
|
## Initial memory: scaffold the library with an agent (2.12.0; moved to Lab in 2.12.1)
|
|
478
481
|
|
package/README.md
CHANGED
|
@@ -14,7 +14,7 @@
|
|
|
14
14
|
|
|
15
15
|
> File-based cross-session memory for DeepSeek Harness — every memory is a plain markdown file you can open, edit and delete. No database, no worker, no port.
|
|
16
16
|
|
|
17
|
-
**当前发布版本:`2.
|
|
17
|
+
**当前发布版本:`2.15.0`** —— 顶部 npm 徽章是动态权威。**契约基线:`1.0.0`** —— 第一个稳定版,公开承诺、能力边界与「明确做不到」的清单冻结在
|
|
18
18
|
[契约冻结](https://github.com/gezi-wen/sage-mem/blob/main/docs/1.0.0-contract.md)。
|
|
19
19
|
|
|
20
20
|
如果它对你有用,给个 Star 是最直接的反馈。
|
|
@@ -193,7 +193,7 @@ SAGE_MEM_DIR=/path/to/your/memory
|
|
|
193
193
|
|
|
194
194
|

|
|
195
195
|
|
|
196
|
-
*库健康 —— 一屏回答「这个库有没有事」:**冲突队列在上**(要你裁决的有限队列:两条说法互斥,选哪一方作废),**体检在下**(索引悬空、漏索引、双链断链等结构问题按类报红)。「指向已归档」只作提示、不计入问题;也**不提供一键修补** —— 改哪条由你决定。体检只报告、不修改。2.10.1 起体检多两类体积审计:**超线体积**(单条 ≥ 40 KB 计入问题、16–40 KB 只列提示;这两条线 2.10.2 从 8/16 KB 抬上来)与**索引过长**(只报不改,见[体积治理](#体积治理超线了怎么办)
|
|
196
|
+
*库健康 —— 一屏回答「这个库有没有事」:**冲突队列在上**(要你裁决的有限队列:两条说法互斥,选哪一方作废),**体检在下**(索引悬空、漏索引、双链断链等结构问题按类报红)。「指向已归档」只作提示、不计入问题;也**不提供一键修补** —— 改哪条由你决定。体检只报告、不修改。2.10.1 起体检多两类体积审计:**超线体积**(单条 ≥ 40 KB 计入问题、16–40 KB 只列提示;这两条线 2.10.2 从 8/16 KB 抬上来)与**索引过长**(只报不改,见[体积治理](#体积治理超线了怎么办))。2.14.0 起再加两类**提示**(都不计入问题):**孤儿归档件**(切片所属的那条记忆已经没了、或两份归档件内容完全相同)与**索引瘦身提案**(悬空条目与超长行直接指到行号,改不改由你);同时补上原先「算进了问题却没有渲染位置」的两类 —— **索引有多份变体**与**超线体积**。真有事要处理时,徽标后面会多一颗**「复制修复提示词」**(2.6.0):把这一屏要处理的事整理成一段提示词放进剪贴板 —— **体检问题与待裁决冲突分两段写**(前者照清单修、后者只给建议),粘给智能体就能照着办;复制成功后下方弹一条提示,10 秒自收、换页签即收、也能自己关掉。*
|
|
197
197
|
|
|
198
198
|
*实验性(2.9.0,排在库健康之后)—— 只给「会改变选出哪些记忆」的开关,默认全关。当前只有一项 **MMR 去重**:注入名额被同一件事的多份记忆占满时,先扣掉候选与已选中那些的相似度再挑。它**只改挑哪几条**(不改打分、不改文件、不碰锁定的 baseline 记忆),候选不够名额时原样返回。为什么默认关:离线对照里它一次都没触发(证据门已把候选压到 10 条以内),而关掉证据门的压力测试中重复度只降 4.5%、误注入却涨了 24% —— 它只知道「不像」,不知道「不相关」。打开前请读那一页的三条声明;**若觉得记忆变少了,关掉它、重启即可恢复**。*
|
|
199
199
|
|
|
@@ -445,7 +445,7 @@ sage-mem 给记忆目录的写入加了**版本守卫**:写入前记下当前
|
|
|
445
445
|
|
|
446
446
|
1. **安全边界在工具集上,不在提示词里** —— 自动做梦时宿主只把只读工具交给模型,改写模式才多给改写工具;而且**没有「删除」这个能力**,归档是把文件移进 `archive/`,可以人工捞回。
|
|
447
447
|
2. **改写前自动建回滚点**,落在 `<记忆目录的上一层>/.sage-mem/autodream/snapshots/<runId>/`,保留最近 N 份。理由是记忆目录**不在任何版本控制下**、删除没有回收站,「可回滚」得自己造。
|
|
448
|
-
3. **跑完自动审计** —— 索引悬空、漏索引、`type` 与文件名前缀不一致、CRLF、双链断链、frontmatter 里被 YAML 当注释吞掉的「空格 + #」、无 frontmatter
|
|
448
|
+
3. **跑完自动审计** —— 索引悬空、漏索引、`type` 与文件名前缀不一致、CRLF、双链断链、frontmatter 里被 YAML 当注释吞掉的「空格 + #」、无 frontmatter、归档中途残留的临时文件,外加「读不动」单列一类,结果与前后对比写进报告。2.14.0 起还会报**孤儿归档件**(切片所属的记忆没了 / 两份归档件内容相同)与**索引瘦身提案**(悬空条目与超长行指到行号)。它**只报不改**,后两类提示也不计入问题。索引 `MEMORY.md` 是清单而不是一条记忆,因此**不参与**「type 与前缀」和「无 frontmatter」这两项(1.9.1 起)。
|
|
449
449
|
|
|
450
450
|
### 改名说明
|
|
451
451
|
|
|
@@ -464,15 +464,18 @@ sage-mem 给记忆目录的写入加了**版本守卫**:写入前记下当前
|
|
|
464
464
|
|
|
465
465
|
⚠️ **前提是形状对得上。** 四类划分与 frontmatter 是 sage-mem 自己的约定:如果你在 CC 里的记忆本来就是「一条一个 Markdown + frontmatter」(我们当时是这种),拷过来即可;**如果不是**(比如都堆在一个 `CLAUDE.md` 里),需要先整理一遍 —— 这活儿正好可以交给一个 agent 做:让它读旧语料,按四类落成文件。
|
|
466
466
|
|
|
467
|
-
## 待办清单看板(实验性 · 2.11.0
|
|
467
|
+
## 待办清单看板(实验性 · 2.11.0 起;2.15.0 收尾)
|
|
468
468
|
|
|
469
|
-
记忆目录里的 `
|
|
469
|
+
记忆目录里的 `project_session_state.md` 一直是「给自己看的代办清单」——每场会话都会注入,人却要打开文件才知道还剩什么。2.11.0 把它搬进**右侧栏**:设置 → 记忆管理 → 实验性 → 打开「待办清单看板」,右侧栏「开始」页就会多一张卡片,点开是一个页签。
|
|
470
470
|
|
|
471
471
|
- **勾选 = 搬家**:完成项从原组删掉、搬进「已完成,待删除」块(文件里还没这一块就自动在末尾建),取消完成再搬回原组末尾;「清空全部」才真删。
|
|
472
|
-
- **改得动**:每组底部加一条、点卡片行内改一句;撤销 /
|
|
472
|
+
- **改得动**:每组底部加一条、点卡片行内改一句;撤销 / 重做 **3–5 步可配**(默认 5)。
|
|
473
|
+
- **一眼只看没做完的**:默认「未完成」档(老文件里遗留的 `- [x]` 行要点「全部」才出现,「已完成,待删除」块始终在——它是队列);每组的展开状态会记住。
|
|
474
|
+
- **收尾有按钮**:待删除块上的**「搬进流水」**把条目写进 `session-log.md` 再从清单删掉——先写流水再删行、正文照抄、已记过的跳过、**不可撤销**。
|
|
475
|
+
- **看得见别的文件里欠着的活**:`tasks/*/WORKING.md` 的「未完成」节汇总成一条**只读**区块(不合并写入)。
|
|
473
476
|
- **文件仍是唯一真相**:看板只做行级手术,其余字节原样;你用任何编辑器改它,看板 4 秒内跟上。
|
|
474
477
|
- **热的**:拨开关立刻生效,不用重启(与 MMR 不同)。
|
|
475
|
-
-
|
|
478
|
+
- **默认关闭**;不做拖拽排序。细节见 `docs/todo-board.md`。
|
|
476
479
|
|
|
477
480
|
## 初始记忆:让 agent 建个骨架(2.12.0,2.12.1 挪到「实验性」)
|
|
478
481
|
|
package/lib/autodream/audit.js
CHANGED
|
@@ -25,8 +25,9 @@
|
|
|
25
25
|
*/
|
|
26
26
|
|
|
27
27
|
import { readdir, readFile } from 'node:fs/promises'
|
|
28
|
+
import { createHash } from 'node:crypto'
|
|
28
29
|
import { join } from 'node:path'
|
|
29
|
-
import { hasFrontmatter, parseFrontmatter } from '../memory/frontmatter.js'
|
|
30
|
+
import { hasFrontmatter, frontmatterField, parseFrontmatter, stripFrontmatterBlock } from '../memory/frontmatter.js'
|
|
30
31
|
import { isIndexName, resolveIndexNames } from '../memory/index-file.js'
|
|
31
32
|
import { isNonEntry, isReserved } from '../memory/naming.js'
|
|
32
33
|
import { classifySize, indexFindings, sizeText } from '../memory/size-policy.js'
|
|
@@ -107,20 +108,40 @@ export function parseFrontmatterLite(content) {
|
|
|
107
108
|
}
|
|
108
109
|
}
|
|
109
110
|
|
|
111
|
+
/** 索引里一条相对链接的形态:`](file.md)` / `](file.md#L12)`。**唯一一份**。 */
|
|
112
|
+
const INDEX_LINK_RE = /\]\(([^)]+\.md)(?:#[^)]*)?\)/g
|
|
113
|
+
|
|
114
|
+
/**
|
|
115
|
+
* 抽出 MEMORY.md 里的相对链接目标**与所在行号**(2.14.0:索引瘦身提案要指到具体行)。
|
|
116
|
+
*
|
|
117
|
+
* 悬空判定用 `indexTargets`(去重目标),提案要行号 —— 两者共用这一份扫描,
|
|
118
|
+
* 免得「报表说悬空 3 条、提案里却定不出是哪一行」。
|
|
119
|
+
*
|
|
120
|
+
* @param {string} indexText
|
|
121
|
+
* @returns {{target: string, line: number}[]} 按出现顺序,未去重
|
|
122
|
+
*/
|
|
123
|
+
export function indexLinks(indexText) {
|
|
124
|
+
const out = []
|
|
125
|
+
if (typeof indexText !== 'string' || indexText === '') return out
|
|
126
|
+
const lines = indexText.split(/\r?\n/)
|
|
127
|
+
for (let i = 0; i < lines.length; i++) {
|
|
128
|
+
for (const m of lines[i].matchAll(INDEX_LINK_RE)) {
|
|
129
|
+
const raw = m[1].trim()
|
|
130
|
+
// 跳过外链与子目录路径:索引只指根目录下的记忆文件。
|
|
131
|
+
if (/^[a-z]+:\/\//i.test(raw) || raw.includes('/') || raw.includes('\\')) continue
|
|
132
|
+
out.push({ target: raw, line: i + 1 })
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
return out
|
|
136
|
+
}
|
|
137
|
+
|
|
110
138
|
/**
|
|
111
139
|
* 抽 MEMORY.md 里的相对链接目标(`](file.md)` / `](file.md#L12)`)。
|
|
112
140
|
* @param {string} indexText
|
|
113
141
|
* @returns {string[]} 去重后的文件名列表
|
|
114
142
|
*/
|
|
115
143
|
export function indexTargets(indexText) {
|
|
116
|
-
|
|
117
|
-
for (const m of indexText.matchAll(/\]\(([^)]+\.md)(?:#[^)]*)?\)/g)) {
|
|
118
|
-
const raw = m[1].trim()
|
|
119
|
-
// 跳过外链与子目录路径:索引只指根目录下的记忆文件。
|
|
120
|
-
if (/^[a-z]+:\/\//i.test(raw) || raw.includes('/') || raw.includes('\\')) continue
|
|
121
|
-
out.add(raw)
|
|
122
|
-
}
|
|
123
|
-
return [...out]
|
|
144
|
+
return [...new Set(indexLinks(indexText).map((l) => l.target))]
|
|
124
145
|
}
|
|
125
146
|
|
|
126
147
|
/**
|
|
@@ -133,7 +154,10 @@ export function indexTargets(indexText) {
|
|
|
133
154
|
*
|
|
134
155
|
* @param {string} dir
|
|
135
156
|
* @returns {Promise<{files: string[], all: string[], skipped: number, indexText: string,
|
|
136
|
-
* indexFile: string|null, indexVariants: string[], archiveKeys: Set<string>,
|
|
157
|
+
* indexFile: string|null, indexVariants: string[], archiveKeys: Set<string>,
|
|
158
|
+
* archiveKeyToFile: Map<string, string>,
|
|
159
|
+
* archiveEntries: {file: string, from: string, bytes: number, hash: string}[],
|
|
160
|
+
* archiveCount: number}>}
|
|
137
161
|
*/
|
|
138
162
|
async function readDirSnapshot(dir) {
|
|
139
163
|
let entries
|
|
@@ -175,19 +199,47 @@ async function readDirSnapshot(dir) {
|
|
|
175
199
|
// 归档区:文件名、去掉 .md 的名字、以及 frontmatter 里的 `name`。
|
|
176
200
|
// 内容读不动只少一个名字,绝不让整场审计失败 —— 归档区本来就不是被审对象。
|
|
177
201
|
const archiveKeys = new Set()
|
|
202
|
+
/** 名字键(小写)→ 归档文件名:孤儿检测要按「谁被引用」反查回具体那份。 */
|
|
203
|
+
const archiveKeyToFile = new Map()
|
|
204
|
+
/**
|
|
205
|
+
* 归档件元数据(2.14.0 孤儿检测)。
|
|
206
|
+
*
|
|
207
|
+
* 每份 `.md` 全文在这一轮**本来就要读一遍**(为了拿 frontmatter 里的 `name`),
|
|
208
|
+
* 所以顺手带上 bytes / sha1 / `archived_from` 不产生第二次 IO —— 这是为什么孤儿
|
|
209
|
+
* 检测挂在这里、而不是另起一次归档区遍历。
|
|
210
|
+
*/
|
|
211
|
+
const archiveEntries = []
|
|
178
212
|
let archiveCount = 0
|
|
213
|
+
const addArchiveKey = (key, file) => {
|
|
214
|
+
const k = String(key ?? '').trim()
|
|
215
|
+
if (!k) return
|
|
216
|
+
archiveKeys.add(k)
|
|
217
|
+
if (!archiveKeyToFile.has(k.toLowerCase())) archiveKeyToFile.set(k.toLowerCase(), file)
|
|
218
|
+
}
|
|
179
219
|
try {
|
|
180
220
|
const archived = await readdir(join(dir, ARCHIVE_DIR), { withFileTypes: true })
|
|
181
221
|
for (const e of archived) {
|
|
182
222
|
if (!e.isFile() || !e.name.toLowerCase().endsWith('.md')) continue
|
|
183
223
|
archiveCount++
|
|
184
|
-
|
|
185
|
-
|
|
224
|
+
addArchiveKey(e.name, e.name)
|
|
225
|
+
addArchiveKey(e.name.replace(/\.md$/i, ''), e.name)
|
|
186
226
|
try {
|
|
187
|
-
const
|
|
188
|
-
|
|
227
|
+
const text = await readFile(join(dir, ARCHIVE_DIR, e.name), 'utf8')
|
|
228
|
+
const meta = parseFrontmatterLite(text)
|
|
229
|
+
if (meta.name) addArchiveKey(meta.name.trim(), e.name)
|
|
230
|
+
/**
|
|
231
|
+
* ⚠️ 指纹取**正文**,不取全文:同一段内容归档两次时 `archived_at` / `name` /
|
|
232
|
+
* 归档名都不一样,全文比对永远不相等 —— 那条判据会变成永不触发的死代码。
|
|
233
|
+
*/
|
|
234
|
+
const body = stripFrontmatterBlock(text)
|
|
235
|
+
archiveEntries.push({
|
|
236
|
+
file: e.name,
|
|
237
|
+
from: frontmatterField(text, 'archived_from'),
|
|
238
|
+
bytes: Buffer.byteLength(body, 'utf8'),
|
|
239
|
+
hash: createHash('sha1').update(body, 'utf8').digest('hex'),
|
|
240
|
+
})
|
|
189
241
|
} catch {
|
|
190
|
-
/*
|
|
242
|
+
/* 读不动:名字池与孤儿检测都少一条而已 */
|
|
191
243
|
}
|
|
192
244
|
}
|
|
193
245
|
} catch (err) {
|
|
@@ -202,6 +254,8 @@ async function readDirSnapshot(dir) {
|
|
|
202
254
|
indexFile: index.name,
|
|
203
255
|
indexVariants: index.variants,
|
|
204
256
|
archiveKeys,
|
|
257
|
+
archiveKeyToFile,
|
|
258
|
+
archiveEntries,
|
|
205
259
|
archiveCount,
|
|
206
260
|
}
|
|
207
261
|
}
|
|
@@ -243,7 +297,7 @@ function stripCode(raw) {
|
|
|
243
297
|
* @returns {Promise<object>} 结构化审计结果(problems 是所有计分项之和)
|
|
244
298
|
*/
|
|
245
299
|
export async function auditMemoryDir(dir, opts = {}) {
|
|
246
|
-
const { files, all, skipped, indexText, indexFile, indexVariants, archiveKeys, archiveCount } =
|
|
300
|
+
const { files, all, skipped, indexText, indexFile, indexVariants, archiveKeys, archiveKeyToFile, archiveEntries, archiveCount } =
|
|
247
301
|
await readDirSnapshot(dir)
|
|
248
302
|
const nowMs = Number.isFinite(opts?.nowMs) ? opts.nowMs : Date.now()
|
|
249
303
|
// 索引本身不是一条记忆:大小写归一后排除(`memory.md` / `MEMORY.MD` 一样排除)。
|
|
@@ -405,6 +459,64 @@ export async function auditMemoryDir(dir, opts = {}) {
|
|
|
405
459
|
}
|
|
406
460
|
}
|
|
407
461
|
|
|
462
|
+
/**
|
|
463
|
+
* 孤儿归档件(2.14.0 记忆治理)。
|
|
464
|
+
*
|
|
465
|
+
* **只列两类** —— 判据是「假阳性会让这盏灯永远亮着」(`archivedLinks` 当年踩过同一个坑):
|
|
466
|
+
* · `no_source`:归档件头里写了 `archived_from`,而那个原件已经不在活动区,
|
|
467
|
+
* 且没有任何活动文件链接它 —— 切片失去了上下文(它属于的那条记忆没了)。
|
|
468
|
+
* · `duplicate`:两份归档件内容完全相同(sha1 + 字节数双判)。整理时留了两份的典型形态。
|
|
469
|
+
*
|
|
470
|
+
* **刻意不列**「归档件没有任何引用」:实测 127 份里 102 份无人引用(81%)—— 那正是归档的
|
|
471
|
+
* 正常状态(归档=静默失效可回退),逐条列出来等于挂一盏永远关不掉的红灯。
|
|
472
|
+
* 它只作为 `archiveReferenced` 这个数字存在(「126 份里有 24 份被引用」)。
|
|
473
|
+
*/
|
|
474
|
+
const referencedArchive = new Set()
|
|
475
|
+
for (const l of archivedLinks) {
|
|
476
|
+
const file = archiveKeyToFile.get(String(l.target ?? '').trim().toLowerCase())
|
|
477
|
+
if (file) referencedArchive.add(file)
|
|
478
|
+
}
|
|
479
|
+
/**
|
|
480
|
+
* 第二条引用通道:**指针行**。
|
|
481
|
+
*
|
|
482
|
+
* trim 切走一段之后,原文里留的是 `> 这段旧内容已归档到 archive/<归档件名>(…)` ——
|
|
483
|
+
* 它**不是** `[[wikilink]]`,所以只按 `archivedLinks` 统计会把绝大多数切片算成
|
|
484
|
+
* 「没人引用」(实测:真实库 126 份归档里 wikilink 只命中 1 份,而指针行命中 26 份)。
|
|
485
|
+
* 「切片还有没有上下文」问的就是这两条通道合起来还有没有人指着它。
|
|
486
|
+
*/
|
|
487
|
+
for (const text of contents.values()) {
|
|
488
|
+
for (const m of stripCode(text).matchAll(/archive\/([^\s))"'`]+?\.md)/g)) {
|
|
489
|
+
const file = archiveKeyToFile.get(m[1].toLowerCase())
|
|
490
|
+
if (file) referencedArchive.add(file)
|
|
491
|
+
}
|
|
492
|
+
}
|
|
493
|
+
const activeNames = new Set(entries.map((f) => f.toLowerCase()))
|
|
494
|
+
const orphans = []
|
|
495
|
+
for (const a of archiveEntries) {
|
|
496
|
+
const from = String(a.from ?? '').trim()
|
|
497
|
+
if (!from) continue
|
|
498
|
+
const fromKey = from.toLowerCase()
|
|
499
|
+
if (activeNames.has(fromKey) || activeNames.has(fromKey.replace(/\.md$/i, ''))) continue
|
|
500
|
+
// 被某条活动记忆链接着的切片不算孤儿:它还有上下文,只是内容变旧了。
|
|
501
|
+
if (referencedArchive.has(a.file)) continue
|
|
502
|
+
orphans.push({ file: a.file, kind: 'no_source', from })
|
|
503
|
+
}
|
|
504
|
+
/**
|
|
505
|
+
* 内容完全重复:同 sha1 且同字节数才算一对。同一份内容被归档了三次时,只把后来的
|
|
506
|
+
* 对着**最早**那份报,不做两两组合(否则一对重复报成三条,人反而看不清该留哪份)。
|
|
507
|
+
*/
|
|
508
|
+
const byHash = new Map()
|
|
509
|
+
for (const a of archiveEntries) {
|
|
510
|
+
const k = `${a.hash}:${a.bytes}`
|
|
511
|
+
if (!byHash.has(k)) byHash.set(k, [])
|
|
512
|
+
byHash.get(k).push(a)
|
|
513
|
+
}
|
|
514
|
+
for (const group of byHash.values()) {
|
|
515
|
+
if (group.length < 2) continue
|
|
516
|
+
for (const other of group.slice(1)) orphans.push({ file: other.file, kind: 'duplicate', with: group[0].file })
|
|
517
|
+
}
|
|
518
|
+
orphans.sort((a, b) => (a.kind === b.kind ? a.file.localeCompare(b.file) : a.kind < b.kind ? -1 : 1))
|
|
519
|
+
|
|
408
520
|
/**
|
|
409
521
|
* 归档 / 恢复崩溃留下的私有名残留(只报不删)。顶层与归档区都扫:
|
|
410
522
|
* 归档动作的源在顶层,而人工移动 / 历史版本可能让残留在归档区里也出现。
|
|
@@ -439,12 +551,33 @@ export async function auditMemoryDir(dir, opts = {}) {
|
|
|
439
551
|
}
|
|
440
552
|
}
|
|
441
553
|
const indexOversize = []
|
|
554
|
+
/**
|
|
555
|
+
* 索引瘦身**提案**(2.14.0 ③)—— 只出清单,**不写盘**。
|
|
556
|
+
*
|
|
557
|
+
* 为什么不给「一键删」:MEMORY.md 是注入入口,删错一行 = 之后想不起来;而插件里
|
|
558
|
+
* 没有任何自动备份机制(备份全靠人手落 `.bak`)。这版把「哪一行该动」指到行号,
|
|
559
|
+
* 交给「复制修复提示词」那条通路 —— 与 2.6.0 的纪律一致:面板只报告,动手的是人或 agent。
|
|
560
|
+
*/
|
|
561
|
+
const indexProposals = []
|
|
562
|
+
const headOf = (line) => {
|
|
563
|
+
const arr = [...String(line ?? '').trim()]
|
|
564
|
+
return arr.length > 48 ? `${arr.slice(0, 48).join('')}…` : arr.join('')
|
|
565
|
+
}
|
|
442
566
|
if (indexText) {
|
|
443
567
|
const findings = indexFindings(indexText)
|
|
444
568
|
// ok 不进清单:健康的索引不该在报告里占一行。
|
|
445
569
|
if (findings.level !== 'ok') {
|
|
446
570
|
indexOversize.push({ file: indexFile, bytes: findings.bytes, longLines: findings.longLines.length })
|
|
447
571
|
}
|
|
572
|
+
const danglingLower = new Set(dangling.map((d) => d.toLowerCase()))
|
|
573
|
+
for (const link of indexLinks(indexText)) {
|
|
574
|
+
if (!danglingLower.has(link.target.toLowerCase())) continue
|
|
575
|
+
indexProposals.push({ kind: 'dangling', line: link.line, target: link.target })
|
|
576
|
+
}
|
|
577
|
+
const lines = indexText.split(/\r?\n/)
|
|
578
|
+
for (const l of findings.longLines) {
|
|
579
|
+
indexProposals.push({ kind: 'long_line', line: l.line, chars: l.chars, head: headOf(lines[l.line - 1]) })
|
|
580
|
+
}
|
|
448
581
|
}
|
|
449
582
|
/** 强制线以上的条数 —— 这是体积这一项对 `problems` 的唯一贡献。 */
|
|
450
583
|
const oversizeForced = oversize.filter((o) => o.level === 'force').length
|
|
@@ -490,6 +623,12 @@ export async function auditMemoryDir(dir, opts = {}) {
|
|
|
490
623
|
oversize,
|
|
491
624
|
// 索引超长:**只报不改**(MEMORY.md 在保护名单里),因此永不进 problems。
|
|
492
625
|
indexOversize,
|
|
626
|
+
// 2.14.0 记忆治理:孤儿归档件(提示)与索引瘦身提案(只报不改)—— 两项都**不进 problems**,
|
|
627
|
+
// 理由同上:它们要处置的对象要么本来就不许改,要么是「归档的正常状态」。
|
|
628
|
+
orphans,
|
|
629
|
+
// 「档案馆 126 份,其中 24 份被活动记忆引用」—— 只做统计,不逐条列(见 orphans 上方那段)。
|
|
630
|
+
archiveReferenced: referencedArchive.size,
|
|
631
|
+
indexProposals,
|
|
493
632
|
problems,
|
|
494
633
|
}
|
|
495
634
|
}
|
|
@@ -529,6 +668,21 @@ export function formatAudit(report, limit = 12) {
|
|
|
529
668
|
section('索引过长(只报不改:MEMORY.md 在保护名单里)', report.indexOversize ?? [], (r) =>
|
|
530
669
|
`${r.file} ${sizeText(r.bytes)} · ${r.longLines} 行超过单行上限`,
|
|
531
670
|
)
|
|
671
|
+
/**
|
|
672
|
+
* 2.14.0 两节治理提示(都不计入 problems)。
|
|
673
|
+
*
|
|
674
|
+
* 标题里写清「怎么办」,理由同体积那节:只说「有孤儿」,模型只会如实转述。
|
|
675
|
+
* 「内容重复」的那一份**该删哪份要人来定**(可能是新版 vs 旧版),所以措辞里给的是
|
|
676
|
+
* 「确认后删一份」,不是「删掉旧的」。
|
|
677
|
+
*/
|
|
678
|
+
section('孤儿归档件(提示,不计入问题)', report.orphans ?? [], (r) =>
|
|
679
|
+
r.kind === 'duplicate'
|
|
680
|
+
? `${r.file} 与 ${r.with} 内容完全相同(确认后删一份)`
|
|
681
|
+
: `${r.file} ← archive 切片,原件 ${r.from} 已不在(恢复或删除,都行)`,
|
|
682
|
+
)
|
|
683
|
+
section('索引瘦身提案(只报不改,交给「复制修复提示词」)', report.indexProposals ?? [], (r) =>
|
|
684
|
+
r.kind === 'dangling' ? `第 ${r.line} 行指向不存在的 ${r.target}` : `第 ${r.line} 行 ${r.chars} 字:${r.head}`,
|
|
685
|
+
)
|
|
532
686
|
// 多个大小写变体各自都可能是「用户以为的那份索引」:两边都列出来,让他删掉多余的。
|
|
533
687
|
section('索引大小写冲突(同一目录存在多个变体,请只保留一个)', report.indexConflicts ?? [], (r) => r.file)
|
|
534
688
|
section('type 与前缀不一致', report.typeMismatch, (r) => `${r.file} type=${r.type} 前缀=${r.prefix}`)
|