sage-mem 2.12.1 → 2.14.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 +3 -3
- package/README.md +3 -3
- package/lib/autodream/audit.js +170 -16
- package/lib/client.js +144 -46
- package/lib/memory/frontmatter.js +59 -12
- package/lib/memory/trim-plan.js +34 -14
- package/lib/shared/hash.js +117 -0
- package/lib/typert.host.js +20 -0
- package/package.json +1 -1
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.14.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
|
|
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.14.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
|
|
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}`)
|
package/lib/client.js
CHANGED
|
@@ -65,6 +65,27 @@ window.__ModuleLoader__.load({
|
|
|
65
65
|
return "rgba(" + ((n >> 16) & 255) + "," + ((n >> 8) & 255) + "," + (n & 255) + "," + a.toFixed(3) + ")";
|
|
66
66
|
}
|
|
67
67
|
|
|
68
|
+
/**
|
|
69
|
+
* 错误详情尽量展开,避免 "[object Object]" 式黑洞。
|
|
70
|
+
*
|
|
71
|
+
* 2.14.0 从 `10-starmap-head.js` 搬到这里:它原本声明在 `StarmapRuntime` 那个
|
|
72
|
+
* IIFE **里面**,而 `60-autodream-panel.js` 的错误分支也在调它 —— 拼接顺序是
|
|
73
|
+
* 先 IIFE 后工厂主体,闭包方向是反的,于是 remote 一失败就抛
|
|
74
|
+
* `ReferenceError: detail is not defined`。危险之处在于**只有失败分支才炸**:
|
|
75
|
+
* 正常路径全绿、界面也不白屏,只是「错误提示变成另一条错误」。
|
|
76
|
+
* `client-scope-test` 第 7 组现在按作用域盯着这一类(不只看这一个名字)。
|
|
77
|
+
*/
|
|
78
|
+
function detail(e) {
|
|
79
|
+
if (!e) return "未知错误";
|
|
80
|
+
if (e instanceof Error) return (e.message || String(e)) + (e.stack ? " · " + e.stack.slice(0, 180) : "");
|
|
81
|
+
try {
|
|
82
|
+
const s = JSON.stringify(e);
|
|
83
|
+
return s && s !== "{}" ? s.slice(0, 200) : String(e);
|
|
84
|
+
} catch (_) {
|
|
85
|
+
return String(e);
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
|
|
68
89
|
// ── 陈旧宿主(2.1.22 / issue #10)────────────────────────────────
|
|
69
90
|
//
|
|
70
91
|
// `@deepseek-ai/dsh-typert-loader` 把每个包的 TYPERT manifest **按包名缓存、
|
|
@@ -239,17 +260,8 @@ const StarmapRuntime = (function (require, _react) {
|
|
|
239
260
|
let react = _react;
|
|
240
261
|
const h = react.createElement;
|
|
241
262
|
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
if (!e) return "未知错误";
|
|
245
|
-
if (e instanceof Error) return (e.message || String(e)) + (e.stack ? " · " + e.stack.slice(0, 180) : "");
|
|
246
|
-
try {
|
|
247
|
-
const s = JSON.stringify(e);
|
|
248
|
-
return s && s !== "{}" ? s.slice(0, 200) : String(e);
|
|
249
|
-
} catch (_) {
|
|
250
|
-
return String(e);
|
|
251
|
-
}
|
|
252
|
-
}
|
|
263
|
+
// detail() 2.14.0 已搬到 05-shared.js(工厂作用域):本 IIFE 与 IIFE 外的
|
|
264
|
+
// 60-autodream-panel.js 都要用它,放在 IIFE 里就只对内可见。
|
|
253
265
|
|
|
254
266
|
function preview(v) {
|
|
255
267
|
try {
|
|
@@ -3644,7 +3656,15 @@ h("span", { key: "sep", className: "smem-actions-sep", "aria-hidden": "true" }),
|
|
|
3644
3656
|
rows(list, render),
|
|
3645
3657
|
])
|
|
3646
3658
|
: null);
|
|
3647
|
-
const hints =
|
|
3659
|
+
const hints = AUDIT_HINTS.map(function (g) {
|
|
3660
|
+
const list = (Array.isArray(r[g.field]) ? r[g.field] : []).filter(function (x) { return x && typeof x === "object"; });
|
|
3661
|
+
if (!list.length) return null;
|
|
3662
|
+
return h("div", { className: "smem-audit-hint", key: "hint-" + g.field }, [
|
|
3663
|
+
h("div", { className: "smem-audit-h", key: "h" }, g.title + " · " + list.length + " 条"),
|
|
3664
|
+
g.note ? h("div", { className: "smem-ar-hint", key: "n" }, g.note) : null,
|
|
3665
|
+
rows(list, g.item),
|
|
3666
|
+
]);
|
|
3667
|
+
}).filter(Boolean);
|
|
3648
3668
|
// 分节表(字段 / 标题 / 条目格式)与「复制修复提示词」共用同一份,定义在
|
|
3649
3669
|
// `client/56-health-prompt.js` 的 `AUDIT_SECTIONS` —— 面板上看到的每一行,
|
|
3650
3670
|
// 就是提示词里读到的那一行。这里只负责把它渲染成「标题(说明)」。
|
|
@@ -3662,18 +3682,21 @@ h("span", { key: "sep", className: "smem-actions-sep", "aria-hidden": "true" }),
|
|
|
3662
3682
|
standalone ? null : toolClose(props),
|
|
3663
3683
|
]),
|
|
3664
3684
|
r.problems
|
|
3665
|
-
? h("div", { key: "secs" },
|
|
3666
|
-
|
|
3667
|
-
|
|
3685
|
+
? h("div", { key: "secs" }, (function () {
|
|
3686
|
+
const secs = AUDIT_SECTIONS.map(function (s) {
|
|
3687
|
+
return section(sectionTitle(s), r[s.field], s.item);
|
|
3688
|
+
}).filter(Boolean);
|
|
3689
|
+
if (secs.length) return secs;
|
|
3690
|
+
// 2.14.0:`problems` 有数、分类行却一条都渲染不出来 —— 旧版就是在这种状态下
|
|
3691
|
+
// 只亮一颗红徽标、下面留白(`indexConflicts` / `oversize` 都没进分类表)。
|
|
3692
|
+
// 分类表补齐之后这条只是兜底:宁可多一行解释,也不要「有问题但看不见」。
|
|
3693
|
+
return [h("div", { className: "smem-audit-row", key: "unmapped" },
|
|
3694
|
+
"问题 " + r.problems + " 条:本屏分类表还没有对应这一类,先看下面的提示。")];
|
|
3695
|
+
})())
|
|
3668
3696
|
: h("div", { className: "smem-empty smem-empty--ok", key: "ok" },
|
|
3669
3697
|
"没有发现问题 —— 索引、双链、frontmatter 与行尾都对得上。"),
|
|
3670
3698
|
hints.length
|
|
3671
|
-
? h("div", {
|
|
3672
|
-
h("div", { className: "smem-audit-h", key: "h" }, "指向已归档(提示,不计入问题)"),
|
|
3673
|
-
h("div", { className: "smem-ar-hint", key: "n" },
|
|
3674
|
-
"归档不是删除:这些链接的目标还在档案馆里躺着,恢复它链接就活了 —— 不用改。"),
|
|
3675
|
-
rows(hints, AUDIT_ARCHIVED_LINKS.item),
|
|
3676
|
-
])
|
|
3699
|
+
? h("div", { key: "hints" }, hints)
|
|
3677
3700
|
: null,
|
|
3678
3701
|
h("div", { className: "smem-ar-hint", key: "ro" }, "这里只报告、不修改 —— 要改哪条,用那条记忆自己的编辑入口。"),
|
|
3679
3702
|
]);
|
|
@@ -5535,6 +5558,13 @@ h("span", { key: "sep", className: "smem-actions-sep", "aria-hidden": "true" }),
|
|
|
5535
5558
|
fix: "文件在、索引里没有 —— 在索引里补一行 `- [标题](文件.md) — 一句话`",
|
|
5536
5559
|
item: function (x) { return String(x.file == null ? "" : x.file); },
|
|
5537
5560
|
},
|
|
5561
|
+
{
|
|
5562
|
+
// 2.14.0:这一类**已经算进 problems** 却一直没有渲染位置 —— 于是「问题 N」
|
|
5563
|
+
// 徽标亮着、清单里一行都没有(只有大小写敏感的卷上才会出现,但一旦出现就是哑的)。
|
|
5564
|
+
field: "indexConflicts", title: "索引有多份变体", sub: "同一目录里同时存在多个大小写变体",
|
|
5565
|
+
fix: "只保留一份索引(通常是 MEMORY.md),把多余的变体改名或删掉 —— 它们的内容可能不一样,先各自看一眼",
|
|
5566
|
+
item: function (x) { return String(x.file == null ? "" : x.file); },
|
|
5567
|
+
},
|
|
5538
5568
|
{
|
|
5539
5569
|
field: "typeMismatch", title: "type 与前缀对不上", sub: "",
|
|
5540
5570
|
fix: "本库以前缀为准,改 frontmatter 的 type(确实该换类型的再改文件名)",
|
|
@@ -5580,23 +5610,65 @@ h("span", { key: "sep", className: "smem-actions-sep", "aria-hidden": "true" }),
|
|
|
5580
5610
|
fix: "归档中途崩溃留下的私有名,内容可能还在 —— 先问我,再决定改回 .md 还是删除",
|
|
5581
5611
|
item: function (x) { return String(x.file == null ? "" : x.file); },
|
|
5582
5612
|
},
|
|
5613
|
+
{
|
|
5614
|
+
// 2.14.0:体积这一项原先也不在分节表里 —— force 档计数进了 problems,
|
|
5615
|
+
// 面板却没有位置显示是哪几条(与上面 indexConflicts 同一个缺口)。
|
|
5616
|
+
// warn / force 都列(面板要看见「该处置了」),但只有 force 进 problems。
|
|
5617
|
+
field: "oversize", title: "超线体积", sub: "≥40 KB 必须处置,16 KB 起只提醒",
|
|
5618
|
+
fix: "能拆一节就 archive_segment,拆不开就 write_memory 压缩(正文别为了省行删事实)",
|
|
5619
|
+
item: function (x) {
|
|
5620
|
+
const lv = String(x.level == null ? "" : x.level) === "force" ? "必须处置" : "提醒";
|
|
5621
|
+
return String(x.file == null ? "" : x.file) + " · " + fmtSize(typeof x.bytes === "number" ? x.bytes : 0) + " · " + lv;
|
|
5622
|
+
},
|
|
5623
|
+
},
|
|
5583
5624
|
];
|
|
5584
5625
|
|
|
5585
|
-
/**
|
|
5586
|
-
|
|
5587
|
-
|
|
5588
|
-
|
|
5589
|
-
|
|
5626
|
+
/**
|
|
5627
|
+
* 体检的**提示类**(不计入 problems)—— 面板与提示词共用同一份(2.6.0 的教训:
|
|
5628
|
+
* 两处各写一份标题,久了就会出现「面板说 8 条、复制出去只有 6 条」)。
|
|
5629
|
+
*
|
|
5630
|
+
* · `note` 给面板的一句「为什么不用管 / 该怎么处置」;
|
|
5631
|
+
* · `fix` 给提示词的行动口径(纪律必须写死:归档不是删除、索引只报不改)。
|
|
5632
|
+
*
|
|
5633
|
+
* 2.14.0 新增两类:孤儿归档件(治理发现的死件)、索引瘦身提案(只报不改)。
|
|
5634
|
+
*/
|
|
5635
|
+
const AUDIT_HINTS = [
|
|
5636
|
+
{
|
|
5637
|
+
field: "archivedLinks",
|
|
5638
|
+
title: "指向已归档(提示,不计入问题)",
|
|
5639
|
+
note: "归档不是删除:这些链接的目标还在档案馆里躺着,恢复它链接就活了 —— 不用改。",
|
|
5640
|
+
fix: "归档不是删除,目标还在档案馆里 —— 能改成指向现有活动记忆就改;改不了就保持原样,不要为此恢复归档,也不要删掉链接所在的记忆",
|
|
5641
|
+
item: function (x) {
|
|
5642
|
+
return String(x.file == null ? "" : x.file) + " → [[" + String(x.target == null ? "" : x.target) + "]]";
|
|
5643
|
+
},
|
|
5590
5644
|
},
|
|
5591
|
-
|
|
5592
|
-
|
|
5593
|
-
|
|
5594
|
-
|
|
5595
|
-
|
|
5596
|
-
|
|
5597
|
-
|
|
5598
|
-
|
|
5599
|
-
|
|
5645
|
+
{
|
|
5646
|
+
field: "orphans",
|
|
5647
|
+
title: "孤儿归档件(提示,不计入问题)",
|
|
5648
|
+
note: "「原件已不在」= 这段旧内容所属的那条记忆没了;「内容相同」= 整理时留了两份 —— 恢复还是删,你定。",
|
|
5649
|
+
fix: "这两类都**先别动手**:no_source 的先确认原件该不该恢复(可能是有意删掉的);duplicate 的两份都要读一遍,可能是「新版 + 旧版」而不是重复。拿不准就原样留着,归档件不影响检索",
|
|
5650
|
+
item: function (x) {
|
|
5651
|
+
const f = String(x.file == null ? "" : x.file);
|
|
5652
|
+
if (String(x.kind == null ? "" : x.kind) === "duplicate") {
|
|
5653
|
+
return f + " 与 " + String(x.with == null ? "?" : x.with) + " 内容完全相同";
|
|
5654
|
+
}
|
|
5655
|
+
return f + " ← 原件 " + String(x.from == null ? "?" : x.from) + " 已不在";
|
|
5656
|
+
},
|
|
5657
|
+
},
|
|
5658
|
+
{
|
|
5659
|
+
field: "indexProposals",
|
|
5660
|
+
title: "索引瘦身提案(只报不改)",
|
|
5661
|
+
note: "MEMORY.md 是每轮注入的入口,插件不自动改它 —— 要动就复制修复提示词,按行号改,改前先落一份 .bak。",
|
|
5662
|
+
// dangling 与上面「索引悬空」是**同一批条目**(这里只是补上行号),不重复算两件事;
|
|
5663
|
+
// 真正只有这里才有的是 long_line(超长行)。
|
|
5664
|
+
fix: "只改**下面点到行号**的地方:dangling 那几行与上面「索引悬空」是同一批,这里多给行号,别当成两件事;long_line 那行压成「一句描述 + 指针」。动 MEMORY.md 之前先把它备份成 MEMORY.md.bak-<时间戳>,改完把改动的行贴给我",
|
|
5665
|
+
item: function (x) {
|
|
5666
|
+
const line = "第 " + String(x.line == null ? "?" : x.line) + " 行";
|
|
5667
|
+
if (String(x.kind == null ? "" : x.kind) === "dangling") return line + " 指向不存在的 " + String(x.target == null ? "?" : x.target);
|
|
5668
|
+
return line + " " + String(x.chars == null ? "?" : x.chars) + " 字:" + String(x.head == null ? "" : x.head);
|
|
5669
|
+
},
|
|
5670
|
+
},
|
|
5671
|
+
];
|
|
5600
5672
|
|
|
5601
5673
|
/** 冲突类型 → 中文标签(提示词正文只出中文,所以不走界面那份 i18n 键)。 */
|
|
5602
5674
|
const CONFLICT_KIND_ZH = {
|
|
@@ -5647,14 +5719,26 @@ h("span", { key: "sep", className: "smem-actions-sep", "aria-hidden": "true" }),
|
|
|
5647
5719
|
const r = report && typeof report === "object" ? report : null;
|
|
5648
5720
|
if (!r) return null;
|
|
5649
5721
|
const problems = typeof r.problems === "number" && isFinite(r.problems) ? r.problems : 0;
|
|
5650
|
-
|
|
5722
|
+
/**
|
|
5723
|
+
* 提示类(孤儿归档件 / 索引瘦身提案)里有几条。
|
|
5724
|
+
*
|
|
5725
|
+
* 2.14.0 起这段的门槛从「problems > 0」放宽成「problems > 0 **或** 有提案」——
|
|
5726
|
+
* 否则治理发现的死件与索引超长永远走不到这颗按钮上(它们按设计不进 problems)。
|
|
5727
|
+
*/
|
|
5728
|
+
const hintCount = AUDIT_HINTS.reduce(function (n, g) {
|
|
5729
|
+
const list = Array.isArray(r[g.field]) ? r[g.field] : [];
|
|
5730
|
+
return n + list.filter(function (x) { return x && typeof x === "object"; }).length;
|
|
5731
|
+
}, 0);
|
|
5732
|
+
if (problems <= 0 && hintCount === 0) return null;
|
|
5651
5733
|
|
|
5652
5734
|
const lines = [];
|
|
5653
5735
|
// 不在这里写「记忆目录」—— 那是整段提示词的开头(`buildHealthFixPrompt` 统一写一次),
|
|
5654
5736
|
// 两段各写一遍会在合成后的文本里出现两次同样的路径。
|
|
5655
5737
|
lines.push(
|
|
5656
5738
|
"扫描 " + auditPromptNum(r.fileCount) + " 个记忆 · 索引 " + auditPromptNum(r.indexEntries) +
|
|
5657
|
-
" 条 · 档案馆 " + auditPromptNum(r.archivedCount) +
|
|
5739
|
+
" 条 · 档案馆 " + auditPromptNum(r.archivedCount) +
|
|
5740
|
+
(typeof r.archiveReferenced === "number" ? " 条(被活动记忆引用 " + auditPromptNum(r.archiveReferenced) + " 条)" : " 条") +
|
|
5741
|
+
" · 问题合计 " + problems,
|
|
5658
5742
|
);
|
|
5659
5743
|
lines.push("");
|
|
5660
5744
|
lines.push("修复口径:");
|
|
@@ -5664,12 +5748,15 @@ h("span", { key: "sep", className: "smem-actions-sep", "aria-hidden": "true" }),
|
|
|
5664
5748
|
lines.push("2. 只改清单里指出的那一点:正文与其它 frontmatter 字段不要顺手动,行尾保持 LF。");
|
|
5665
5749
|
lines.push("3. 不删记忆:要下线用归档,不要删文件;「归档残留」这一类先问我再动。");
|
|
5666
5750
|
lines.push("4. 拿不准的(读不出来、type 该怎么统一)先说不确定,不要猜着改。");
|
|
5751
|
+
if (problems <= 0) {
|
|
5752
|
+
lines.push("5. 本屏**没有硬问题**:下面全是提示与提案(只报不改)。没有我点头之前,一个文件都不要动。");
|
|
5753
|
+
}
|
|
5667
5754
|
|
|
5668
|
-
const listed = appendPromptGroups(lines, AUDIT_SECTIONS, r);
|
|
5669
|
-
const hinted = appendPromptGroups(lines,
|
|
5755
|
+
const listed = problems > 0 ? appendPromptGroups(lines, AUDIT_SECTIONS, r) : 0;
|
|
5756
|
+
const hinted = appendPromptGroups(lines, AUDIT_HINTS, r);
|
|
5670
5757
|
lines.push("");
|
|
5671
5758
|
lines.push("改完请自己再核对一遍(能跑 audit_memory 就跑),然后告诉我每条改了什么。");
|
|
5672
|
-
return { lines: lines, count: listed, hints: hinted };
|
|
5759
|
+
return { lines: lines, count: listed + hinted, hard: problems > 0, hints: hinted };
|
|
5673
5760
|
}
|
|
5674
5761
|
|
|
5675
5762
|
/**
|
|
@@ -5722,7 +5809,11 @@ h("span", { key: "sep", className: "smem-actions-sep", "aria-hidden": "true" }),
|
|
|
5722
5809
|
if (a && b) {
|
|
5723
5810
|
lines.push("这次两部分都有:A 是体检发现的结构问题(**要修**),B 是待裁决的矛盾(**只做判断,不要改盘上的文件**)。");
|
|
5724
5811
|
} else if (a) {
|
|
5725
|
-
|
|
5812
|
+
// 2.14.0:A 段现在也可能是「只有提示与提案」—— 措辞必须跟着分叉,
|
|
5813
|
+
// 不然智能体会把一段只报告的内容当成「按清单修」去改盘。
|
|
5814
|
+
lines.push(a.hard
|
|
5815
|
+
? "这次只有 A:体检发现的结构问题(**要修**);当前没有待裁决的矛盾。"
|
|
5816
|
+
: "这次只有 A 的提示类:体检**没有硬问题**,下面是治理提案(**只报不改**);当前没有待裁决的矛盾。");
|
|
5726
5817
|
} else {
|
|
5727
5818
|
lines.push("这次只有 B:待裁决的矛盾(**只做判断,不要改盘上的文件**);体检没有发现问题。");
|
|
5728
5819
|
}
|
|
@@ -5730,7 +5821,7 @@ h("span", { key: "sep", className: "smem-actions-sep", "aria-hidden": "true" }),
|
|
|
5730
5821
|
|
|
5731
5822
|
if (a) {
|
|
5732
5823
|
lines.push("");
|
|
5733
|
-
lines.push("════ A · 体检问题:按下面的清单修 ════");
|
|
5824
|
+
lines.push(a.hard ? "════ A · 体检问题:按下面的清单修 ════" : "════ A · 体检提示与提案:只报不改 ════");
|
|
5734
5825
|
Array.prototype.push.apply(lines, a.lines);
|
|
5735
5826
|
}
|
|
5736
5827
|
if (b) {
|
|
@@ -8463,8 +8554,10 @@ h("span", { key: "sep", className: "smem-actions-sep", "aria-hidden": "true" }),
|
|
|
8463
8554
|
function conflictErrText(err) {
|
|
8464
8555
|
const code = err && typeof err.code === "string" ? err.code : "";
|
|
8465
8556
|
const key = CONFLICT_CODE_KEY[code] || "conflict.code.unknown";
|
|
8466
|
-
|
|
8467
|
-
|
|
8557
|
+
// 2.14.0:局部量改叫 hostDetail —— 工厂作用域现在有一份共享的 detail()
|
|
8558
|
+
// (错误详情展开),同名会遮蔽它,也让 client-scope-test 的「只此一份」判据读不清。
|
|
8559
|
+
const hostDetail = err && typeof err.error === "string" ? err.error : "";
|
|
8560
|
+
return t(key) + (hostDetail ? t("conflict.code.detail", { detail: hostDetail }) : "");
|
|
8468
8561
|
}
|
|
8469
8562
|
|
|
8470
8563
|
/** 打开「冲突」这一屏。数据没取过才取(挂载时已经取过一次,通常直接有内容)。 */
|
|
@@ -8830,10 +8923,15 @@ h("span", { key: "sep", className: "smem-actions-sep", "aria-hidden": "true" }),
|
|
|
8830
8923
|
// 冲突徽标数的是**待裁决**(open)条数 —— 与冲突页签里的「N 条待裁决」同源。
|
|
8831
8924
|
// -1 = 还没取到队列(显示「未载」,不假装 0 条)。
|
|
8832
8925
|
const conflictOpen = conf && conf.counts && typeof conf.counts.open === "number" ? conf.counts.open : -1;
|
|
8833
|
-
// 「复制修复提示词」那颗按钮的分母:体检问题 +
|
|
8926
|
+
// 「复制修复提示词」那颗按钮的分母:体检问题 + 待裁决冲突 + **治理提案**。全都没有(=0)时按钮不渲染;
|
|
8834
8927
|
// 冲突队列还没载入(-1)不算进分母 —— 免得按钮先冒出来又消失。
|
|
8928
|
+
// 2.14.0:孤儿归档件与索引瘦身提案按设计不进 problems,只数 problems 会让它们
|
|
8929
|
+
// 永远走不到这颗按钮上(治理看得到、复制不出去)。
|
|
8930
|
+
const proposalCount = (audit && Array.isArray(audit.orphans) ? audit.orphans.length : 0)
|
|
8931
|
+
+ (audit && Array.isArray(audit.indexProposals) ? audit.indexProposals.length : 0);
|
|
8835
8932
|
const healthWork = (audit && typeof audit.problems === "number" && audit.problems > 0 ? audit.problems : 0)
|
|
8836
|
-
+ (conflictOpen > 0 ? conflictOpen : 0)
|
|
8933
|
+
+ (conflictOpen > 0 ? conflictOpen : 0)
|
|
8934
|
+
+ proposalCount;
|
|
8837
8935
|
|
|
8838
8936
|
// 2.12.0(2.12.1 改位置):初始记忆卡片 —— 挂在**实验性**那一屏最上面。
|
|
8839
8937
|
// 放这里的理由(2026-11-17 定):它不是日常动作,是「第一次上手」用的一段材料,
|
|
@@ -34,13 +34,66 @@ export function hasFrontmatter(content) {
|
|
|
34
34
|
return typeof content === 'string' && /^---\r?\n[\s\S]*?\r?\n---/.test(content)
|
|
35
35
|
}
|
|
36
36
|
|
|
37
|
+
/**
|
|
38
|
+
* frontmatter 块的匹配规则(**唯一一份**):`parseFrontmatter` 与 `frontmatterField` 共用。
|
|
39
|
+
*
|
|
40
|
+
* 换行必须容忍 CRLF:任何用 Windows 编辑器碰过一次的文件都会被换成 `\r\n`,而旧版写的是
|
|
41
|
+
* `/^---\n/` —— 匹配失败 → description/type 全空 → 「baseline 那条带 `\r?\n` 的正则照旧命中,
|
|
42
|
+
* 但这条记忆永远检索不到」,症状极具欺骗性。
|
|
43
|
+
*/
|
|
44
|
+
const FRONTMATTER_BLOCK_RE = /^---\r?\n([\s\S]*?)\r?\n---/
|
|
45
|
+
|
|
46
|
+
/**
|
|
47
|
+
* 从 frontmatter 正文里读一个顶层标量(`key: value`)。
|
|
48
|
+
*
|
|
49
|
+
* `[ \t]` / `[ \t\r]` 而不是 `\s`:`\s` 会连 CRLF 的 `\r` 一起吃进捕获组,值尾留一个 `\r`
|
|
50
|
+
* 会让下面的引号剥离(`["']$`)失配,值尾巴上挂一个残引号。
|
|
51
|
+
*/
|
|
52
|
+
function grabFromBody(body, key) {
|
|
53
|
+
const hit = body.match(new RegExp(`^${key}:[ \\t]*(.+?)[ \\t\\r]*$`, 'm'))
|
|
54
|
+
if (!hit) return ''
|
|
55
|
+
return hit[1].replace(/^["']|["']$/g, '').trim()
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/**
|
|
59
|
+
* 读 frontmatter 里**任意一个顶层标量**(2.14.0 为归档元数据开放:孤儿归档件检测要读
|
|
60
|
+
* `archived_from`)。
|
|
61
|
+
*
|
|
62
|
+
* 为什么不干脆给 `parseFrontmatter` 再加两个返回字段:那个返回形状被
|
|
63
|
+
* `test/shared-parity-test.mjs` 与客户端 codec 对拍着,加字段等于动一条跨层契约;
|
|
64
|
+
* 而审计只想要其中一个值。这里共用同一段匹配与剥离规则,**判据仍然只有一份**。
|
|
65
|
+
*
|
|
66
|
+
* @param {string} content 文件全文
|
|
67
|
+
* @param {string} key 顶层键名(只接受 `[A-Za-z0-9_.-]`,挡掉正则注入)
|
|
68
|
+
* @returns {string} 找不到 / 参数不合法一律空串
|
|
69
|
+
*/
|
|
70
|
+
export function frontmatterField(content, key) {
|
|
71
|
+
if (typeof content !== 'string' || typeof key !== 'string') return ''
|
|
72
|
+
if (!/^[A-Za-z0-9_.-]+$/.test(key)) return ''
|
|
73
|
+
const m = content.match(FRONTMATTER_BLOCK_RE)
|
|
74
|
+
return m ? grabFromBody(m[1], key) : ''
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/**
|
|
78
|
+
* 去掉开头的 frontmatter 块,只留正文(2.14.0:归档件「内容完全相同」按**正文**判)。
|
|
79
|
+
*
|
|
80
|
+
* 为什么必须剥:同一段内容被归档两次,两次的 `archived_at` / `name` / 归档名都不同,
|
|
81
|
+
* 全文比对永远不相等 —— 那样这条判据只会是一条永远不触发的死代码。
|
|
82
|
+
*
|
|
83
|
+
* 与 `parseFrontmatter` 用同一条块规则:两边对「frontmatter 到哪里结束」不许有第二种说法。
|
|
84
|
+
* **不 trim**:正文末尾少一个空格是内容差异,不是同一份文件。
|
|
85
|
+
*
|
|
86
|
+
* @param {string} content 文件全文
|
|
87
|
+
* @returns {string} 正文(没有 frontmatter 时原样返回)
|
|
88
|
+
*/
|
|
89
|
+
export function stripFrontmatterBlock(content) {
|
|
90
|
+
if (typeof content !== 'string') return ''
|
|
91
|
+
return content.replace(FRONTMATTER_BLOCK_RE, '').replace(/^\r?\n/, '')
|
|
92
|
+
}
|
|
93
|
+
|
|
37
94
|
/** 解析 frontmatter 的 name/description/type(兼容顶层与 metadata 嵌套两种 type)。 */
|
|
38
95
|
export function parseFrontmatter(content) {
|
|
39
|
-
|
|
40
|
-
// 而旧版这里写的是 /^---\n/ —— 匹配失败 → description/type 全空 →
|
|
41
|
-
// 「baseline 走 parseBaseline 那条带 \r?\n 的正则照旧命中,但这条记忆永远检索不到」,
|
|
42
|
-
// 症状极具欺骗性。下文定义的 parseBaseline 与 extractTitle 早已是 \r?\n。
|
|
43
|
-
const m = content.match(/^---\r?\n([\s\S]*?)\r?\n---/)
|
|
96
|
+
const m = content.match(FRONTMATTER_BLOCK_RE)
|
|
44
97
|
if (!m) {
|
|
45
98
|
return {
|
|
46
99
|
name: '', description: '', type: '', tags: [], aliases: [], updated: '', baselinePriority: 0,
|
|
@@ -50,13 +103,7 @@ export function parseFrontmatter(content) {
|
|
|
50
103
|
}
|
|
51
104
|
}
|
|
52
105
|
const body = m[1]
|
|
53
|
-
const grab = (key) =>
|
|
54
|
-
// [ \t] / [ \t\r] 而不是 \s:\s 会连 CRLF 的 \r 一起吃进捕获组,值尾留一个 \r
|
|
55
|
-
// 会让下面的引号剥离(["']$)失配,description 尾巴上挂一个残引号。
|
|
56
|
-
const hit = body.match(new RegExp(`^${key}:[ \\t]*(.+?)[ \\t\\r]*$`, 'm'))
|
|
57
|
-
if (!hit) return ''
|
|
58
|
-
return hit[1].replace(/^["']|["']$/g, '').trim()
|
|
59
|
-
}
|
|
106
|
+
const grab = (key) => grabFromBody(body, key)
|
|
60
107
|
let type = grab('type')
|
|
61
108
|
if (!type) {
|
|
62
109
|
const nested = body.match(/^metadata:\s*\r?\n(?:\s+[^\r\n]+\r?\n)*?\s+type:\s*(\S+)/m)
|
package/lib/memory/trim-plan.js
CHANGED
|
@@ -13,8 +13,15 @@
|
|
|
13
13
|
* 3. 被裁段 ≥ `TRIM_MIN_SEGMENT_BYTES`;剩余正文 ≥ `TRIM_MIN_REMAIN_BYTES`
|
|
14
14
|
* —— 太小没有收益,剪到只剩骨架就该走整文件归档那条路。code: `segment_too_small` / `remain_too_small`(契约指定)
|
|
15
15
|
* 4. 标题找不到 / 重名不猜。code: `heading_not_found` / `heading_ambiguous`(契约指定)
|
|
16
|
-
* 5. `archiveName` = `<原名去 .md>-<slug>-<YYYYMMDD>.md`,且必须过
|
|
17
|
-
* `
|
|
16
|
+
* 5. `archiveName` = `<原名去 .md>-<slug ≤16>-<YYYYMMDD>-<hash4>.md`,且必须过
|
|
17
|
+
* `shared/md-name.js` 的 `isPlainMdName`(归档名也是要落盘的名字,非法名会把归档件
|
|
18
|
+
* 写到意想不到的地方)。code: `invalid_name`
|
|
19
|
+
* 四段的顺序**是契约**:原名在最前(归档件被「恢复」搬回根目录后,体检按
|
|
20
|
+
* `f.split('_')[0]` 判类型前缀,`audit.js` 那一侧盯着),日期在 hash 前(人一眼看到
|
|
21
|
+
* 「哪天收的」),hash 是**被归档那段正文**的 4 位 FNV-1a(`shared/hash.js`)。
|
|
22
|
+
* 为什么要有 hash:撞名是硬拒绝(`trim-archive.js` 的 `writeFileExclusive` 不覆盖、
|
|
23
|
+
* 不改名),slug 一收短,同日同前缀就会假撞;加上内容指纹之后只有「正文真重复」
|
|
24
|
+
* 才撞 —— 那本来就该拒。
|
|
18
25
|
* 6. `remaining` = 前缀 + `pointer` + 后缀,其中「前缀 + segment + 后缀 === 原文」**逐字节成立**。
|
|
19
26
|
* 这条就是往返断言:把 pointer 换回 segment,必须一字不差地还原原文件。
|
|
20
27
|
* code: `invalid`(内部不变量被破坏时的兜底,正常情况下永不出现)
|
|
@@ -39,6 +46,7 @@
|
|
|
39
46
|
|
|
40
47
|
import { isPlainMdName } from '../shared/md-name.js'
|
|
41
48
|
import { stampDate } from '../shared/stamp.js'
|
|
49
|
+
import { fnv1aHex } from '../shared/hash.js'
|
|
42
50
|
import { parseFrontmatter } from './frontmatter.js'
|
|
43
51
|
|
|
44
52
|
/** 被裁段的最小体积。太小的段搬进 archive/ 只是把垃圾换个地方放。 */
|
|
@@ -50,8 +58,14 @@ export const TRIM_MIN_REMAIN_BYTES = 1024
|
|
|
50
58
|
/** 缘由最少几个字(去空白后数)。「整理」两个字说不清为什么要动用户的正文。 */
|
|
51
59
|
const MIN_REASON_CHARS = 4
|
|
52
60
|
|
|
53
|
-
/**
|
|
54
|
-
|
|
61
|
+
/**
|
|
62
|
+
* 归档名里 slug 的长度上限(契约 §2 第 5 条)。
|
|
63
|
+
*
|
|
64
|
+
* 40 → 16(2.14.0):归档名要能当**一条活记忆的名字**用(恢复就是原样搬回根目录),
|
|
65
|
+
* 而 40 个中文字符 = 120 字节,一个名字就能把面板一行撑满。截断丢掉的那点辨识度,
|
|
66
|
+
* 由尾部的 4 位内容 hash 补回来(它不是给人读的,是给「同名判定」用的)。
|
|
67
|
+
*/
|
|
68
|
+
const MAX_SLUG_CHARS = 16
|
|
55
69
|
|
|
56
70
|
/** `title` 只是给人看的标签,别把整段正文塞进去。 */
|
|
57
71
|
const MAX_TITLE_CHARS = 80
|
|
@@ -136,7 +150,7 @@ function trimBlankEdges(lines, start, end) {
|
|
|
136
150
|
return { start: s + 1, end: e + 1 }
|
|
137
151
|
}
|
|
138
152
|
|
|
139
|
-
/** 标题/正文 → slug:去掉空白与文件名保留字符,最长
|
|
153
|
+
/** 标题/正文 → slug:去掉空白与文件名保留字符,最长 16 个字符,空则 `section`。 */
|
|
140
154
|
function slugOf(text) {
|
|
141
155
|
const cleaned = cutChars(String(text ?? '').replace(SLUG_BAD_RE, ''), MAX_SLUG_CHARS)
|
|
142
156
|
return cleaned || 'section'
|
|
@@ -282,15 +296,7 @@ export function planTrim({ content, name, selector, reason, at } = {}) {
|
|
|
282
296
|
if (!picked.ok) return picked
|
|
283
297
|
const { start, end, title, sliceLabel } = picked
|
|
284
298
|
|
|
285
|
-
// ⑤
|
|
286
|
-
const when = Number.isFinite(at) ? at : Date.now()
|
|
287
|
-
const date = stampDate(when)
|
|
288
|
-
const archiveName = `${rawName.replace(/\.md$/i, '')}-${slugOf(title)}-${date.replace(/-/g, '')}.md`
|
|
289
|
-
if (!isPlainMdName(archiveName)) {
|
|
290
|
-
return { ok: false, code: 'invalid_name', error: `算出来的归档名不合法:${archiveName}` }
|
|
291
|
-
}
|
|
292
|
-
|
|
293
|
-
// ⑥ 切片。这三段拼回去必须与原文逐字节相同(不变量 6 的实现侧断言)。
|
|
299
|
+
// ⑤ 切片。这三段拼回去必须与原文逐字节相同(不变量 6 的实现侧断言)。
|
|
294
300
|
const offsets = lineOffsets(src, lines)
|
|
295
301
|
const startOff = offsets[start - 1]
|
|
296
302
|
const endOff = offsets[end - 1] + lines[end - 1].length
|
|
@@ -300,6 +306,20 @@ export function planTrim({ content, name, selector, reason, at } = {}) {
|
|
|
300
306
|
if (prefix + segment + suffix !== src) {
|
|
301
307
|
return { ok: false, code: 'invalid', error: '内部不变量被破坏(行偏移切不出原文),拒绝给出结果' }
|
|
302
308
|
}
|
|
309
|
+
|
|
310
|
+
// ⑥ 归档名:<原名去 .md>-<slug ≤16>-<YYYYMMDD>-<hash4>.md
|
|
311
|
+
//
|
|
312
|
+
// 顺序:切片先算,名字后算 —— hash 的输入必须是**被归档的那段正文**(`segment`,
|
|
313
|
+
// 也就是归档件的正文),不是整份原文、也不是标题。这样「同一天、同一前缀、标题
|
|
314
|
+
// 被截成同一串」的两段不同正文不会假撞;而真的把同一段裁两次会得到同名,
|
|
315
|
+
// 被 `trim-archive.js` 的排他写拒掉(`code:'exists'`)—— 那是正确的拒绝。
|
|
316
|
+
const when = Number.isFinite(at) ? at : Date.now()
|
|
317
|
+
const date = stampDate(when)
|
|
318
|
+
const archiveName = `${rawName.replace(/\.md$/i, '')}-${slugOf(title)}-${date.replace(/-/g, '')}-${fnv1aHex(segment)}.md`
|
|
319
|
+
if (!isPlainMdName(archiveName)) {
|
|
320
|
+
return { ok: false, code: 'invalid_name', error: `算出来的归档名不合法:${archiveName}` }
|
|
321
|
+
}
|
|
322
|
+
|
|
303
323
|
const pointer = trimPointerLine(archiveName, date, why)
|
|
304
324
|
const remaining = prefix + pointer + suffix
|
|
305
325
|
|
|
@@ -0,0 +1,117 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 内容短指纹(FNV-1a 32 位,零依赖)—— **只给文件名用**,不做安全哈希。
|
|
3
|
+
*
|
|
4
|
+
* ## 为什么不用 `node:crypto`
|
|
5
|
+
*
|
|
6
|
+
* 用它的是 `lib/memory/trim-plan.js`(裁段规划器),而那个模块被
|
|
7
|
+
* `test/structure-test.mjs` 第 5 组钉成「纯逻辑层」:**零 node 内建 import**。
|
|
8
|
+
* 那条守卫不是为了洁癖 —— `planTrim` 要在没有磁盘、没有夹具的情况下对着字符串
|
|
9
|
+
* 做几百条断言(`test/trim-plan-test.mjs`),一旦它 import 了 `node:*`,
|
|
10
|
+
* 纯度就从「结构上成立」退化成「这次没人写错」。
|
|
11
|
+
*
|
|
12
|
+
* 另一条路是把 hash 算在 IO 层(`trim-archive.js`)再传进 `planTrim` —— 那会改
|
|
13
|
+
* `planTrim` 的签名,等于让「归档名怎么算」横跨两层,`trim-plan-test.mjs` 再也
|
|
14
|
+
* 不能单独验证一个名字。所以:**函数留在这里,算在纯函数那一侧。**
|
|
15
|
+
*
|
|
16
|
+
* 本项目还有别的哈希(`lib/autodream/snapshot.js` / `memory/chunks.js` 用
|
|
17
|
+
* `node:crypto` 的 sha256、`lib/autodream/audit.js` 用 sha1)—— 那些是**内容校验**
|
|
18
|
+
* 与**去重判据**,要抗碰撞,该用 crypto。这里只要「同一天同前缀的两段不同正文
|
|
19
|
+
* 别撞在同一个名字上」,32 位足够,且必须零依赖。两种需求,两套实现。
|
|
20
|
+
*
|
|
21
|
+
* ## 为什么是 4 位十六进制
|
|
22
|
+
*
|
|
23
|
+
* 名字的骨架是 `<原名去 .md>-<slug ≤16>-<YYYYMMDD>-<hash4>.md`:
|
|
24
|
+
*
|
|
25
|
+
* - 撞名的后果不是「换个名字」,而是**硬拒绝**(`trim-archive.js` 的
|
|
26
|
+
* `writeFileExclusive` → `code:'exists'`,不覆盖也不改名)。slug 从 40 收短到 16
|
|
27
|
+
* 之后,「同一天、同一前缀、标题被截断成同一串」就会假撞 —— 一次治理跑不动。
|
|
28
|
+
* - 4 位 = 16 位 = 65536 个取值。同一前缀同一天真的有 10 段要归档时,
|
|
29
|
+
* 假撞概率 ≈ 10×9/2/65536 ≈ **0.07%**;而 body 真重复(同一段被裁两次)
|
|
30
|
+
* 得到同名、被 `exists` 拒,那本来就是**该拒**的。
|
|
31
|
+
* - 再短(3 位)假撞率 ×16;再长(6 位)名字又要多两个字符,且对「同日同前缀」
|
|
32
|
+
* 这个真实场景没有额外收益。
|
|
33
|
+
*
|
|
34
|
+
* 取的是**低位**(`padStart(8,'0')` 之后 `slice(-n)`),这一点容易写反,实测说话:
|
|
35
|
+
*
|
|
36
|
+
* FNV-1a 的一步是 `h = (h ^ b) * prime`。乘法把进位从**低位向高位**传播,
|
|
37
|
+
* 所以末字节的改动先落在低位、要再经过若干字节才扩散到高位。于是对「只差末尾
|
|
38
|
+
* 一点点」的文本,**低位才是强端**。
|
|
39
|
+
*
|
|
40
|
+
* 本机实测(`fnv1a32` 同一实现,200 条 `'很长的正文内容'×20` + 依次换末字):
|
|
41
|
+
* - 取高 4 位:**162 / 200 distinct** —— 38 次碰撞
|
|
42
|
+
* - 取低 4 位:**200 / 200 distinct** —— 0 次碰撞
|
|
43
|
+
*
|
|
44
|
+
* 这个场景不是刁难,它就是 `planTrim` 的真实输入:同一份记忆的不同切片,往往
|
|
45
|
+
* 只差标题和末尾几行。取高位 = 假撞 = `writeFileExclusive` 硬拒 = 一次治理直接
|
|
46
|
+
* 跑不动 —— 那正是加这个 hash 要堵的洞。`test/trim-plan-test.mjs` 第 11 组有一条
|
|
47
|
+
* 属性断言(200 条近似文本必须 200 个不同名字)盯着这件事,改回高位当场红。
|
|
48
|
+
*
|
|
49
|
+
* 输入按 **UTF-8 字节**喂(不是 UTF-16 code unit):同一份中文正文在任何平台上
|
|
50
|
+
* 都得同一个名字,而「文件里那段字节」正是我们对它的直觉。
|
|
51
|
+
*
|
|
52
|
+
* 零 import(`test/duplication-test.mjs` 第 2 组要求 `shared/*.js` 谁都能引、
|
|
53
|
+
* 不制造循环)—— 所以这里手写 UTF-8 拆字节,不借 `TextEncoder` 之外的任何东西,
|
|
54
|
+
* 干脆连全局都不借。
|
|
55
|
+
*/
|
|
56
|
+
|
|
57
|
+
/** FNV-1a 的初始值(32 位偏移基数)。 */
|
|
58
|
+
const FNV_OFFSET_BASIS = 2166136261
|
|
59
|
+
|
|
60
|
+
/** FNV-1a 的乘法质数(32 位)。 */
|
|
61
|
+
const FNV_PRIME = 16777619
|
|
62
|
+
|
|
63
|
+
/** 喂一个字节:异或后乘质数,`Math.imul` 保证按 32 位整数取模(`*` 会溢出成浮点)。 */
|
|
64
|
+
const stepByte = (h, b) => Math.imul(h ^ b, FNV_PRIME) >>> 0
|
|
65
|
+
|
|
66
|
+
/**
|
|
67
|
+
* 字符串 → 32 位无符号整数指纹(UTF-8 字节序,FNV-1a)。
|
|
68
|
+
*
|
|
69
|
+
* 代理对先合成真正的 code point 再拆字节;落单的代理(半个表情、截断的文件)
|
|
70
|
+
* 按 3 字节形态编码 —— 不抛错,也不去修它:哈希只要**确定性**,不做字符校验。
|
|
71
|
+
*/
|
|
72
|
+
export function fnv1a32(str) {
|
|
73
|
+
const s = String(str ?? '')
|
|
74
|
+
let h = FNV_OFFSET_BASIS >>> 0
|
|
75
|
+
for (let i = 0; i < s.length; i += 1) {
|
|
76
|
+
let cp = s.charCodeAt(i)
|
|
77
|
+
if (cp >= 0xd800 && cp <= 0xdbff && i + 1 < s.length) {
|
|
78
|
+
const lo = s.charCodeAt(i + 1)
|
|
79
|
+
if (lo >= 0xdc00 && lo <= 0xdfff) {
|
|
80
|
+
cp = 0x10000 + ((cp - 0xd800) << 10) + (lo - 0xdc00)
|
|
81
|
+
i += 1
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
if (cp < 0x80) {
|
|
85
|
+
h = stepByte(h, cp)
|
|
86
|
+
} else if (cp < 0x800) {
|
|
87
|
+
h = stepByte(h, 0xc0 | (cp >> 6))
|
|
88
|
+
h = stepByte(h, 0x80 | (cp & 0x3f))
|
|
89
|
+
} else if (cp < 0x10000) {
|
|
90
|
+
h = stepByte(h, 0xe0 | (cp >> 12))
|
|
91
|
+
h = stepByte(h, 0x80 | ((cp >> 6) & 0x3f))
|
|
92
|
+
h = stepByte(h, 0x80 | (cp & 0x3f))
|
|
93
|
+
} else {
|
|
94
|
+
h = stepByte(h, 0xf0 | (cp >> 18))
|
|
95
|
+
h = stepByte(h, 0x80 | ((cp >> 12) & 0x3f))
|
|
96
|
+
h = stepByte(h, 0x80 | ((cp >> 6) & 0x3f))
|
|
97
|
+
h = stepByte(h, 0x80 | (cp & 0x3f))
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
return h >>> 0
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/**
|
|
104
|
+
* 文件名里那一段:`n` 位小写十六进制(默认 4),取 32 位的**低位**。
|
|
105
|
+
*
|
|
106
|
+
* 为什么是低位:见文件头「取的是低位」那一段(乘法把影响从低位向高位传播,
|
|
107
|
+
* 近似文本的差异先落在低位)。`padStart(8,'0')` 不能省 —— 指纹恰好小到不足 8 位时
|
|
108
|
+
* (例如 `0x0000abcd`),`slice(-n)` 会拿到比 `n` 短的串,名字就长短不一了。
|
|
109
|
+
*
|
|
110
|
+
* @param {string} str — 要指纹化的正文
|
|
111
|
+
* @param {number} [n] — 位数(1-8,默认 4;越界按 4 处理,不抛错 —— 这是个命名助手,不该在治理路上炸)
|
|
112
|
+
* @returns {string} 例:`fnv1aHex('hello')` = `'2cab'`(完整指纹 `4f9f2cab` 的低 4 位)
|
|
113
|
+
*/
|
|
114
|
+
export function fnv1aHex(str, n = 4) {
|
|
115
|
+
const width = Number.isInteger(n) && n > 0 && n <= 8 ? n : 4
|
|
116
|
+
return fnv1a32(str).toString(16).padStart(8, '0').slice(-width)
|
|
117
|
+
}
|
package/lib/typert.host.js
CHANGED
|
@@ -170,6 +170,21 @@ const auditTypeMismatchSchema = z.object({
|
|
|
170
170
|
'effective': z.string().readonly(),
|
|
171
171
|
}).readonly()
|
|
172
172
|
const auditHazardSchema = z.object({ 'file': z.string().readonly(), 'line': z.string().readonly() }).readonly()
|
|
173
|
+
// 2.14.0 记忆治理:孤儿归档件(不进 problems)与索引瘦身提案(只报不改)。
|
|
174
|
+
// 同一条纪律:strict 会把没声明的字段剥掉 —— 不声明,面板就永远看不见这两类。
|
|
175
|
+
const auditOrphanSchema = z.object({
|
|
176
|
+
'file': z.string().readonly(),
|
|
177
|
+
'kind': z.string().readonly(),
|
|
178
|
+
'with': z.string().readonly().optional(),
|
|
179
|
+
'from': z.string().readonly().optional(),
|
|
180
|
+
}).readonly()
|
|
181
|
+
const auditIndexProposalSchema = z.object({
|
|
182
|
+
'kind': z.string().readonly(),
|
|
183
|
+
'line': z.number().readonly(),
|
|
184
|
+
'target': z.string().readonly().optional(),
|
|
185
|
+
'chars': z.number().readonly().optional(),
|
|
186
|
+
'head': z.string().readonly().optional(),
|
|
187
|
+
}).readonly()
|
|
173
188
|
const auditReportSchema = z.object({
|
|
174
189
|
'dir': z.string().readonly(),
|
|
175
190
|
'fileCount': z.number().readonly(),
|
|
@@ -209,6 +224,11 @@ const auditReportSchema = z.object({
|
|
|
209
224
|
'bytes': z.number().readonly(),
|
|
210
225
|
'longLines': z.number().readonly(),
|
|
211
226
|
}).readonly()).readonly().optional(),
|
|
227
|
+
// 2.14.0 记忆治理(三项都**不进 problems**):孤儿归档件、被引用的归档件计数、
|
|
228
|
+
// 索引瘦身提案。前两项给「档案馆里哪些是死件」,第三项把「该动哪一行」指到行号。
|
|
229
|
+
'orphans': z.array(auditOrphanSchema).readonly().optional(),
|
|
230
|
+
'archiveReferenced': z.number().readonly().optional(),
|
|
231
|
+
'indexProposals': z.array(auditIndexProposalSchema).readonly().optional(),
|
|
212
232
|
'problems': z.number().readonly(),
|
|
213
233
|
}).readonly()
|
|
214
234
|
|
package/package.json
CHANGED