dsh-zdiary-kit 0.7.6 → 0.8.3

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/dist/lib/lint.js CHANGED
@@ -24,13 +24,13 @@
24
24
  import fs from 'node:fs';
25
25
  import path from 'node:path';
26
26
  import { allNotes, graphEdges, localDate, MAX_SCAN, notesWithFlag, parseErrorWarnings } from './zk.js';
27
+ import { normalizeTitle, resolveWikiTarget, WIKI_LINK, wikiIndex } from './wikilink.js';
27
28
  import { parseFrontmatter } from './frontmatter.js';
29
+ import { AGENTS_TEMPLATE, AGENTS_TEMPLATE_FLAT, TEMPLATE_VERSION } from './agents-template.js';
28
30
  /** 每类最多回多少条(计划 §4 M3);总数另给 */
29
31
  export const MAX_ITEMS = 50;
30
- /** 标题归一化只压空白与大小写,不改字(中文不受影响,也不会把「A B」和「AB」当成同一个) */
31
- export function normalizeTitle(title) {
32
- return String(title ?? '').replace(/\s+/g, ' ').trim().toLowerCase();
33
- }
32
+ /** 标题归一化与链接解析在 `lib/wikilink.ts`(dream 也用同一套);这里保留导出,免得调用方跟着搬 */
33
+ export { normalizeTitle };
34
34
  /** 同一标题出现在多篇里(slug 命名下不同目录可以同名,检索时容易挑错) */
35
35
  export function duplicateTitles(notes, max = MAX_ITEMS) {
36
36
  const groups = new Map();
@@ -48,10 +48,101 @@ export function duplicateTitles(notes, max = MAX_ITEMS) {
48
48
  dup.sort((a, b) => b.paths.length - a.paths.length || a.title.localeCompare(b.title));
49
49
  return { total: dup.length, items: dup.slice(0, max) };
50
50
  }
51
+ /** 相似标题的判定:字符二元组 Jaccard 下限;短串被长串包含时另算(短串至少 6 字) */
52
+ const SIMILAR_RATIO = 0.6;
53
+ const SIMILAR_SHORT = 6;
54
+ /** 同目录最多两两比较多少篇:超过就截断并置 truncated,别让 1 万篇变成 O(n²) */
55
+ const SIMILAR_GROUP_MAX = 300;
56
+ /** 比较用的标题:NFKC → 小写 → 去标点 / 空白。中文不改字,只抹掉排版差异 */
57
+ function similarKey(title) {
58
+ return String(title ?? '').normalize('NFKC').toLowerCase().replace(/[\s\p{P}\p{S}]/gu, '');
59
+ }
60
+ function bigrams(key) {
61
+ const chars = [...key];
62
+ const out = new Set();
63
+ for (let i = 0; i < chars.length - 1; i++)
64
+ out.add(chars[i] + chars[i + 1]);
65
+ if (out.size === 0 && chars.length > 0)
66
+ out.add(chars[0]);
67
+ return out;
68
+ }
69
+ function jaccard(a, b) {
70
+ if (a.size === 0 || b.size === 0)
71
+ return 0;
72
+ let shared = 0;
73
+ for (const gram of a)
74
+ if (b.has(gram))
75
+ shared += 1;
76
+ return shared / (a.size + b.size - shared);
77
+ }
78
+ /**
79
+ * 疑似重复标题(P2-10):精确查重只能挡住手滑 —— 中文改两个字就绕过去了。
80
+ *
81
+ * 纯机械:NFKC + 去标点后按字符二元组算 Jaccard ≥ 0.6,或短串(≥ 6 字)被长串包含。
82
+ * 只在**同目录**内比较(不同目录的同名本来允许);全等标题留给 duplicateTitles,这里不重复报。
83
+ * 只报告:`zk_new` 不用它拦人,误报会挡住正常写作。
84
+ *
85
+ * 日记不进来(由调用方按 `isDaily` 过滤):标题就是日期,`2026-10-01` 与 `2026-10-02`
86
+ * 的二元组 Jaccard 是 0.86 —— 一年日记会吐出上千组「疑似重复」,真问题全被淹掉。
87
+ * 纯数字标题(日期 / 编号)同样跳过:那是「按天 / 按号」的记录,不是同一个结论写了两遍。
88
+ */
89
+ export function similarTitles(notes, scanTruncated, max = MAX_ITEMS) {
90
+ const groups = new Map();
91
+ for (const note of notes) {
92
+ const title = note.title || path.basename(note.path, path.extname(note.path));
93
+ const key = similarKey(title);
94
+ if (!key)
95
+ continue;
96
+ // 纯数字:日期 / 编号类标题,相似度只反映「数字挨着」,不反映重复结论
97
+ if (/^\d+$/.test(key))
98
+ continue;
99
+ const dir = path.posix.dirname(note.path);
100
+ const list = groups.get(dir) ?? [];
101
+ list.push({ title, path: note.path, key, exact: normalizeTitle(title), grams: bigrams(key), size: [...key].length });
102
+ groups.set(dir, list);
103
+ }
104
+ let truncated = scanTruncated;
105
+ const found = [];
106
+ for (const group of groups.values()) {
107
+ let list = group;
108
+ if (list.length > SIMILAR_GROUP_MAX) {
109
+ truncated = true;
110
+ list = list.slice(0, SIMILAR_GROUP_MAX);
111
+ }
112
+ for (let i = 0; i < list.length; i++) {
113
+ for (let j = i + 1; j < list.length; j++) {
114
+ const a = list[i];
115
+ const b = list[j];
116
+ // 归一化后完全一样:那是 duplicateTitles 的活(这里报会让同一件事出现两遍)
117
+ if (a.exact === b.exact)
118
+ continue;
119
+ // 短标题的二元组太少(RAG / RAG 2 会算出 0.67),噪声大于信号
120
+ if (a.size < 4 || b.size < 4)
121
+ continue;
122
+ let score = jaccard(a.grams, b.grams);
123
+ let hit = score >= SIMILAR_RATIO;
124
+ if (!hit) {
125
+ const [short, long, shortSize] = a.size <= b.size ? [a.key, b.key, a.size] : [b.key, a.key, b.size];
126
+ if (shortSize >= SIMILAR_SHORT && long.includes(short)) {
127
+ hit = true;
128
+ score = SIMILAR_RATIO;
129
+ }
130
+ }
131
+ if (!hit)
132
+ continue;
133
+ found.push({
134
+ titles: [a.title, b.title],
135
+ paths: [a.path, b.path],
136
+ score: Math.round(score * 100) / 100,
137
+ });
138
+ }
139
+ }
140
+ }
141
+ found.sort((a, b) => b.score - a.score || a.paths[0].localeCompare(b.paths[0]));
142
+ return { total: found.length, truncated, items: found.slice(0, max) };
143
+ }
51
144
  /** 注入的三份 meta 里只有 MEMORY / USER 会写来源链接;AGENTS 是规则,不查 */
52
145
  const MEMORY_LINK_FILES = ['MEMORY.md', 'USER.md'];
53
- /** `[[路径]]` / `[[路径|别名]]` / `[[路径#小节]]` 都认,取路径部分 */
54
- const WIKI_LINK = /\[\[([^\]|#]+)(?:#[^\]|]*)?(?:\|[^\]]*)?\]\]/g;
55
146
  /** 按列表条目切分(含缩进续行):只有条目才谈得上「没附来源」 */
56
147
  function listEntries(body) {
57
148
  const out = [];
@@ -76,26 +167,12 @@ function listEntries(body) {
76
167
  flush();
77
168
  return out;
78
169
  }
170
+ /** 记忆条目的观察日期(P1-3):只认 YYYY-MM-DD 这种能机械解析的形状 */
171
+ const DATE_IN_LINE = /\b\d{4}-\d{2}-\d{2}\b/;
79
172
  function collapse(text, max = 100) {
80
173
  const one = text.replace(/\s+/g, ' ').trim();
81
174
  return one.length > max ? one.slice(0, max) + '…' : one;
82
175
  }
83
- function insideNotebook(cfg, abs) {
84
- const root = path.resolve(cfg.notebook);
85
- const p = path.resolve(abs);
86
- return p === root || p.startsWith(root + path.sep);
87
- }
88
- function statusOf(abs) {
89
- try {
90
- return parseFrontmatter(fs.readFileSync(abs, 'utf8')).fields.status ?? '';
91
- }
92
- catch {
93
- return '';
94
- }
95
- }
96
- function relOf(cfg, abs) {
97
- return path.relative(cfg.notebook, abs).split(path.sep).join('/');
98
- }
99
176
  /**
100
177
  * 记忆层体检:MEMORY.md / USER.md 里的 `[[来源]]` 是否还指向活笔记。
101
178
  *
@@ -107,48 +184,15 @@ function relOf(cfg, abs) {
107
184
  * 归档标题不反查 —— 归档默认不进检索,这里再造一套索引就成了第二真相。「语义重复」也不查。
108
185
  */
109
186
  export function memoryLinkIssues(cfg, notes, max = MAX_ITEMS) {
110
- const titles = new Set();
111
- for (const n of notes) {
112
- titles.add(normalizeTitle(n.title));
113
- titles.add(normalizeTitle(path.basename(n.path, path.extname(n.path))));
114
- }
187
+ const index = wikiIndex(notes);
115
188
  const items = [];
116
189
  const seen = new Set();
117
190
  let files = 0;
118
191
  let links = 0;
119
192
  let unlinked = 0;
120
- /** null = 活着 / 没问题;否则给出失效原因与命中路径 */
121
- const resolve = (target) => {
122
- const rel = target.replace(/\\/g, '/').replace(/^\.\//, '').trim();
123
- if (!rel)
124
- return null;
125
- const candidates = /\.md$/i.test(rel) ? [rel] : [rel, `${rel}.md`];
126
- for (const candidate of candidates) {
127
- const abs = path.resolve(cfg.notebook, candidate);
128
- if (!insideNotebook(cfg, abs) || !fs.existsSync(abs) || !fs.statSync(abs).isFile())
129
- continue;
130
- const hit = relOf(cfg, abs);
131
- // 显式写 archive/ 路径 = 有意引用旧结论(supersede 就是这样重写入链的),不算漂移
132
- if (hit === cfg.archiveDir || hit.startsWith(`${cfg.archiveDir}/`))
133
- return null;
134
- return statusOf(abs) === 'superseded'
135
- ? { reason: 'superseded', path: hit }
136
- : null;
137
- }
138
- // 链接还停在废弃前的路径:文件已经搬进 archive/ —— 这正是要抓的漂移
139
- if (!rel.startsWith(`${cfg.archiveDir}/`)) {
140
- for (const candidate of candidates) {
141
- const abs = path.resolve(cfg.notebook, cfg.archiveDir, candidate);
142
- if (!insideNotebook(cfg, abs) || !fs.existsSync(abs) || !fs.statSync(abs).isFile())
143
- continue;
144
- return { reason: 'superseded', path: relOf(cfg, abs) };
145
- }
146
- }
147
- // 标题式链接只在活笔记里找(zk 的 wiki 链接两种写法都认)
148
- if (titles.has(normalizeTitle(rel)))
149
- return null;
150
- return { reason: 'missing', path: '' };
151
- };
193
+ let undated = 0;
194
+ let retired = 0;
195
+ let retiredBroken = 0;
152
196
  for (const name of MEMORY_LINK_FILES) {
153
197
  let body = '';
154
198
  try {
@@ -162,9 +206,14 @@ export function memoryLinkIssues(cfg, notes, max = MAX_ITEMS) {
162
206
  for (const match of line.matchAll(WIKI_LINK)) {
163
207
  links += 1;
164
208
  const target = String(match[1] ?? '').trim();
165
- const issue = resolve(target);
166
- if (!issue)
209
+ // `[[ ]]` 这种空目标不是链接,也不该算「失效」:解析器对它返回 missing
210
+ if (!target)
211
+ continue;
212
+ const resolved = resolveWikiTarget(cfg, target, index);
213
+ // 显式写 archive/ 路径的链接是有意引用旧结论(supersede 重写入链就是这个形状),不算漂移
214
+ if (resolved.status === 'live' || resolved.explicit)
167
215
  continue;
216
+ const issue = { reason: resolved.status === 'archived' ? 'superseded' : 'missing', path: resolved.path };
168
217
  const key = `${name}\u0000${target}`;
169
218
  if (seen.has(key))
170
219
  continue;
@@ -172,12 +221,27 @@ export function memoryLinkIssues(cfg, notes, max = MAX_ITEMS) {
172
221
  items.push({ source: name, entry: collapse(line), link: target, reason: issue.reason, path: issue.path });
173
222
  }
174
223
  }
175
- // 只对 MEMORY.md 数「没附来源」:USER.md 是偏好清单,大多数条目本来就没有来源
224
+ // 只对 MEMORY.md 数「没附来源 / 没日期 / 退役」:USER.md 是偏好清单,大多数条目本来就没有来源
176
225
  if (name === 'MEMORY.md') {
177
- unlinked += listEntries(body).filter((entry) => !entry.includes('[[')).length;
226
+ for (const entry of listEntries(body)) {
227
+ const first = entry.split('\n', 1)[0] ?? '';
228
+ if (!entry.includes('[['))
229
+ unlinked += 1;
230
+ // 退役行:磁盘保留、注入仍按原文(P1-3 A 案),只核对它指向的新结论是否还活着
231
+ if (/^\s*(?:[-*+]|\d+[.)])\s+\[superseded\b/i.test(first)) {
232
+ retired += 1;
233
+ const next = /→\s*\[\[([^\]|#]+)/.exec(entry);
234
+ const resolved = next ? resolveWikiTarget(cfg, String(next[1] ?? '').trim(), index) : null;
235
+ if (!resolved || resolved.status !== 'live')
236
+ retiredBroken += 1;
237
+ continue;
238
+ }
239
+ if (!DATE_IN_LINE.test(first))
240
+ undated += 1;
241
+ }
178
242
  }
179
243
  }
180
- return { files, links, total: items.length, unlinked, items: items.slice(0, max) };
244
+ return { files, links, total: items.length, unlinked, undated, retired, retiredBroken, items: items.slice(0, max) };
181
245
  }
182
246
  /**
183
247
  * 一行「记忆链接」摘要:`zk-kit lint` 与 `zk_lint` 共用,免得两处各写一遍文案、
@@ -199,7 +263,69 @@ export function formatMemoryLinks(bucket) {
199
263
  }
200
264
  if (bucket.unlinked > 0)
201
265
  parts.push(`${bucket.unlinked} 个条目没附来源链接`);
202
- return `${bucket.total === 0 ? '✓' : '✗'} 记忆链接:${parts.join('|')}`;
266
+ if (bucket.undated > 0)
267
+ parts.push(`${bucket.undated} 个条目没写日期(YYYY-MM-DD)`);
268
+ if (bucket.retired > 0) {
269
+ parts.push(bucket.retiredBroken > 0
270
+ ? `${bucket.retired} 条已退役,其中 ${bucket.retiredBroken} 条的新结论不是活笔记`
271
+ : `${bucket.retired} 条已退役`);
272
+ }
273
+ return `${bucket.total === 0 && bucket.retiredBroken === 0 ? '✓' : '✗'} 记忆链接:${parts.join('|')}`;
274
+ }
275
+ /**
276
+ * 三个后加的桶(缺字段 / 标签卫生 / 模板版本)的文案,同样只写一份:
277
+ * `zk-kit lint` 与 `zk_lint` 各写一遍就会改到一半。返回空数组 = 这一库三项都没问题,不占行。
278
+ */
279
+ export function formatLintExtras(r) {
280
+ const lines = [];
281
+ if (r.incomplete.total > 0) {
282
+ lines.push(`✗ frontmatter 缺字段:${r.incomplete.total} 篇 — ` +
283
+ r.incomplete.items.slice(0, 5).map((i) => `${i.path}(缺 ${i.missing.join('/')})`).join('、') +
284
+ (r.incomplete.total > 5 ? ' …' : '') +
285
+ '|缺失被索引落成空串,status / authority 的机械门对它们静默失效');
286
+ }
287
+ if (r.tags.reported) {
288
+ const cv = r.tags.caseVariants;
289
+ const sg = r.tags.singletons;
290
+ lines.push(cv.total === 0
291
+ ? `✓ 标签卫生:${r.tags.total} 个标签,没有大小写变体;单例 ${sg.total} 个` +
292
+ (sg.items.length ? `(${sg.items.slice(0, 5).join('、')})` : '')
293
+ : `✗ 标签卫生:${cv.total} 组大小写变体 — ` +
294
+ cv.items.slice(0, 3).map((g) => `${g.variants.join(' / ')}(${g.total})`).join(';') +
295
+ `;单例 ${sg.total} 个`);
296
+ }
297
+ if (r.template.stale) {
298
+ const t = r.template;
299
+ if (t.version > t.current) {
300
+ // 插件比库旧(用户降级过插件 / 手写了更高标记):给旧模板等于让 agent 把规则改回去
301
+ lines.push(`⚠️ AGENTS.md 的模板版本比插件新(v${t.version} > 当前 v${t.current})—— ` +
302
+ '插件是旧的那个,别改文件去配它;升级插件后再看。这里不给旧模板,免得把规则改回去。');
303
+ }
304
+ else {
305
+ lines.push(`⚠️ AGENTS.md 是${t.version === 0 ? '旧版 / 无版本标记' : `旧版模板 v${t.version}`}` +
306
+ `(当前 v${t.current})—— 只报告,不覆盖。` +
307
+ (t.currentText
308
+ ? `新版模板全文如下:按需合并,别整篇覆盖你改过的规则;合并后把首行标记更新为 v${t.current}。`
309
+ : ''));
310
+ if (t.currentText) {
311
+ lines.push('--- 新版模板开始 ---');
312
+ lines.push(t.currentText.trimEnd());
313
+ lines.push('--- 新版模板结束 ---');
314
+ }
315
+ }
316
+ }
317
+ if (r.similarTitles.total > 0) {
318
+ const sample = r.similarTitles.items.slice(0, 3)
319
+ .map((g) => `「${g.titles[0]}」/「${g.titles[1]}」(${g.score.toFixed(2)})`)
320
+ .join(';');
321
+ lines.push(`⚠️ 疑似重复标题:${r.similarTitles.total} 组 — ${sample}` +
322
+ (r.similarTitles.total > 3 ? ' …' : '') +
323
+ '|只报告,合并由人裁决');
324
+ }
325
+ if (r.indexHint) {
326
+ lines.push('· 笔记已到 150 篇(不含日记):根目录还没有 INDEX.md —— 需要总索引时再建(zk_stats 有实时目录 / 标签分布)');
327
+ }
328
+ return lines;
203
329
  }
204
330
  export function oneWayLinks(edges, notes, skipSource) {
205
331
  const linked = new Set(edges.map((e) => e.sourcePath + '\u0000' + e.targetPath));
@@ -227,6 +353,103 @@ export function oneWayLinks(edges, notes, skipSource) {
227
353
  .sort((a, b) => a.path.localeCompare(b.path)),
228
354
  }));
229
355
  }
356
+ /** 模板承诺的四个字段里,这三个是机械规则的前提(title 由文件名兜底,不查) */
357
+ const REQUIRED_FIELDS = ['type', 'status', 'authority'];
358
+ /**
359
+ * frontmatter 缺字段(P2-13):`toRecord` 把缺失的 status / type / authority 一律落成空串,
360
+ * 于是「没写 authority」=「authority 正常」—— dream 的 informal 门对它们静默失效。
361
+ * 索引里区分不出「没写」与「空值」,只能逐篇读 frontmatter;代价是 O(n) 次读盘,
362
+ * 护栏是只读 live 且非日记,扫描触到上限时置 truncated。
363
+ *
364
+ * 只在 layered 下检查:flat 的笔记本来就不写这三个字段(没有 group / 模板),
365
+ * 对它报这一桶等于把整个库标红,那就不是「可发现的状态」而是噪音。
366
+ */
367
+ export function incompleteFrontmatter(cfg, notes, skip, scanTruncated, max = 20) {
368
+ const byField = { type: 0, status: 0, authority: 0 };
369
+ const items = [];
370
+ let total = 0;
371
+ for (const note of notes) {
372
+ if (skip(note.path))
373
+ continue;
374
+ let fields;
375
+ try {
376
+ fields = parseFrontmatter(fs.readFileSync(path.resolve(cfg.notebook, note.path), 'utf8')).fields;
377
+ }
378
+ catch {
379
+ continue;
380
+ }
381
+ const missing = REQUIRED_FIELDS.filter((key) => !String(fields[key] ?? '').trim());
382
+ if (!missing.length)
383
+ continue;
384
+ total += 1;
385
+ for (const key of missing)
386
+ byField[key] += 1;
387
+ if (items.length < max)
388
+ items.push({ path: note.path, missing });
389
+ }
390
+ return { total, truncated: scanTruncated, byField, items };
391
+ }
392
+ /** 小库不查标签卫生:20 个标签里出现几个单例是正常的,报出来只是噪音 */
393
+ const TAG_MIN = 30;
394
+ /**
395
+ * 标签卫生(P2-14):标签是中文召回的补丁,补丁自己的卫生没人看。
396
+ * 大小写变体纯机械可判(`#Agent` / `#agent`),单例标签是「写了一次就再没出现」的那批。
397
+ * 只报告,不合并 —— 在别的库里它们可能就是两个概念,裁决留给人。
398
+ */
399
+ export function tagHygiene(notes, max = 20) {
400
+ const counts = new Map();
401
+ for (const note of notes)
402
+ for (const tag of note.tags)
403
+ counts.set(tag, (counts.get(tag) ?? 0) + 1);
404
+ const tags = [...counts.keys()];
405
+ if (tags.length < TAG_MIN) {
406
+ return { total: tags.length, reported: false, caseVariants: { total: 0, items: [] }, singletons: { total: 0, items: [] } };
407
+ }
408
+ const groups = new Map();
409
+ for (const tag of tags) {
410
+ const key = tag.toLowerCase();
411
+ const list = groups.get(key) ?? [];
412
+ list.push(tag);
413
+ groups.set(key, list);
414
+ }
415
+ const variants = [...groups.values()]
416
+ .filter((group) => group.length > 1)
417
+ .map((group) => {
418
+ group.sort((a, b) => (counts.get(b) ?? 0) - (counts.get(a) ?? 0) || a.localeCompare(b));
419
+ return { variants: group, total: group.reduce((sum, tag) => sum + (counts.get(tag) ?? 0), 0) };
420
+ })
421
+ .sort((a, b) => b.total - a.total || a.variants[0].localeCompare(b.variants[0]));
422
+ const singletons = tags.filter((tag) => counts.get(tag) === 1).sort((a, b) => a.localeCompare(b));
423
+ return {
424
+ total: tags.length,
425
+ reported: true,
426
+ caseVariants: { total: variants.length, items: variants.slice(0, max) },
427
+ singletons: { total: singletons.length, items: singletons.slice(0, 10) },
428
+ };
429
+ }
430
+ const TEMPLATE_MARK_RE = /<!--\s*zdiary-template:\s*v(\d+)\s*-->/;
431
+ /**
432
+ * 模板版本(P2-15):模板是行为契约,不是静态文档 —— 它每轮注入,写错一句就是每轮都在执行错规则。
433
+ * 但模板允许用户改,不能自动覆盖;版本标记把「过期」变成可发现状态,只报告。
434
+ */
435
+ export function templateStatus(cfg) {
436
+ let body = '';
437
+ try {
438
+ body = fs.readFileSync(path.join(cfg.notebook, 'AGENTS.md'), 'utf8');
439
+ }
440
+ catch {
441
+ return { present: false, version: 0, current: TEMPLATE_VERSION, stale: false };
442
+ }
443
+ const hit = TEMPLATE_MARK_RE.exec(body);
444
+ const version = hit ? Number(hit[1]) : 0;
445
+ const stale = version !== TEMPLATE_VERSION;
446
+ const base = { present: true, version, current: TEMPLATE_VERSION, stale };
447
+ // 不 stale 时不要留下 currentText: undefined —— 宿主按无损 JSON 校验,undefined 会让整次调用 invalid;
448
+ // 版本比插件新时也不给:那是插件该升级,不是用户该回退
449
+ return stale && version < TEMPLATE_VERSION
450
+ ? { ...base, currentText: cfg.structure === 'flat' ? AGENTS_TEMPLATE_FLAT : AGENTS_TEMPLATE }
451
+ : base;
452
+ }
230
453
  export async function lintNotebook(cfg, opts = {}, signal) {
231
454
  const staleDays = Math.min(3650, Math.max(1, Math.trunc(opts.staleDays ?? 90)));
232
455
  const now = opts.now ?? new Date();
@@ -347,6 +570,7 @@ export async function lintNotebook(cfg, opts = {}, signal) {
347
570
  items: oneWayItems.slice(0, MAX_ITEMS),
348
571
  };
349
572
  const parseErrors = parseErrorWarnings(cfg, warnings);
573
+ const scanTruncated = notes.length >= MAX_SCAN;
350
574
  const staleNotes = notes
351
575
  .map((n) => ({ note: n, at: Date.parse(n.modified) }))
352
576
  .filter((x) => Number.isFinite(x.at) && x.at < cutoff)
@@ -359,10 +583,13 @@ export async function lintNotebook(cfg, opts = {}, signal) {
359
583
  modified: localDate(x.note.modified),
360
584
  })),
361
585
  };
586
+ // 日记不参与下面两项:标题就是日期(相似度必然高),篇数又按天自动增长
587
+ // (一年日记足以把任何库顶到 150 篇,可库里其实只有几十篇知识)。
588
+ const nonDaily = notes.filter((n) => !isDaily(path.resolve(cfg.notebook, n.path)));
362
589
  return {
363
590
  notebook: cfg.notebook,
364
591
  notes: notes.length,
365
- truncated: notes.length >= MAX_SCAN,
592
+ truncated: scanTruncated,
366
593
  staleDays,
367
594
  parseErrors: { total: parseErrors.length, items: parseErrors.slice(0, MAX_ITEMS) },
368
595
  orphans: bucket(orphanAbs.filter((abs) => !isDaily(abs))),
@@ -371,6 +598,15 @@ export async function lintNotebook(cfg, opts = {}, signal) {
371
598
  tagless: bucket(taglessAbs.filter((abs) => !isDaily(abs))),
372
599
  oneWayLinks: oneWayBucket,
373
600
  duplicateTitles: duplicateTitles(notes),
601
+ // 日记按天写,标题就是日期:同类比较只会产出一堆误报(见 similarTitles 的注释)
602
+ similarTitles: similarTitles(nonDaily, scanTruncated),
374
603
  memoryLinks: memoryLinkIssues(cfg, notes),
604
+ incomplete: cfg.structure === 'layered'
605
+ ? incompleteFrontmatter(cfg, notes, (rel) => isDaily(path.resolve(cfg.notebook, rel)), scanTruncated)
606
+ : { total: 0, truncated: false, byField: { type: 0, status: 0, authority: 0 }, items: [] },
607
+ tags: tagHygiene(notes),
608
+ template: templateStatus(cfg),
609
+ // 150 篇(不含日记)是检索开始变糊的拐点:提示一下,不生成静态索引(会过期,还要决定谁更新)
610
+ indexHint: nonDaily.length >= 150 && !fs.existsSync(path.join(cfg.notebook, 'INDEX.md')),
375
611
  };
376
612
  }
@@ -5,7 +5,9 @@
5
5
  *
6
6
  * 硬约定(与 docs/plan-memory-layers.md §3 D6 一致):
7
7
  * · 预算按**总载荷**算,不是只卡 MEMORY.md;
8
- * · 截断顺序纯机械:先丢 MEMORY 的尾部 `##` 整段,再丢 USER 的尾部整段,
8
+ * · 切分按三级降级:`##` 小节 → 顶层列表项 → 空行段落。只有 `##` 一级时,
9
+ * `# 记忆` + 要点列表(最常见的写法)一个小节都切不出来,预算会整个失效 —— 见 P0-1;
10
+ * · 截断顺序纯机械:先丢 MEMORY 的尾部整条,再丢 USER 的尾部整段,
9
11
  * 最后各自只留首段;AGENTS.md 是硬规则,永不截断(单独超预算时只告警);
10
12
  * · 丢掉的段落留一份**目录**(段落标题,计入预算),agent 用 zk_read 取回正文 ——
11
13
  * 选哪段是 agent 按当前任务判断,插件只搬运目录,不猜相关性;
@@ -48,33 +50,116 @@ export function countWords(text) {
48
50
  }
49
51
  /** 目录最多列几段:再多就只给「还有 N 段」,免得目录自己把预算吃掉 */
50
52
  const TOC_MAX = 5;
53
+ /** 目录里单条标题最多多长(条目可能是一整句结论) */
54
+ const TOC_TITLE_MAX = 40;
55
+ /** 到预算的这个比例就回显用量:等到截断才说,已经是最坏的时刻 */
56
+ const MEMORY_NEAR_RATIO = 0.8;
57
+ /** 围栏代码块:里面的 `- ` 与空行都不是条目 / 段落边界 */
58
+ const FENCED = /^\s*(?:```|~~~)/;
59
+ /** 二级小节(原有切分口径) */
60
+ const SECTION = /^##\s+/;
61
+ /** 顶层列表项;缩进的子项算续行,不另起一条 */
62
+ const LIST_ITEM = /^(?:[-*+]|\d+[.)])\s+/;
63
+ function finishSplit(head, sections, mode) {
64
+ return {
65
+ head: head.join('\n').trim(),
66
+ sections: sections.map((s) => s.join('\n').trim()).filter(Boolean),
67
+ mode,
68
+ };
69
+ }
70
+ /**
71
+ * 三级降级切分(P0-1):`##` 小节 → 顶层列表项 → 空行段落。
72
+ * 只按 `##` 切时,「`# 记忆` + 要点列表」这种形状切不出任何小节,丢弃循环一次都不进,
73
+ * 预算于是完全不生效(真机 880 / 449 / 895 词都是这个形状)。降级只影响超预算的库:
74
+ * 预算内不调用这个函数的结果做任何改写。
75
+ *
76
+ * 三级都跳过围栏里的行 —— 代码块里的 `- ` 或空行不该被当成可丢弃的条目。
77
+ */
51
78
  function splitSections(body) {
79
+ const lines = String(body ?? '').split('\n');
80
+ let fenced = false;
81
+ // 1a) `##` 小节
52
82
  const head = [];
53
83
  const sections = [];
54
- for (const line of body.split('\n')) {
55
- if (/^##\s+/.test(line))
84
+ for (const line of lines) {
85
+ if (FENCED.test(line))
86
+ fenced = !fenced;
87
+ if (!fenced && SECTION.test(line))
56
88
  sections.push([line]);
57
89
  else if (sections.length > 0)
58
90
  sections[sections.length - 1].push(line);
59
91
  else
60
92
  head.push(line);
61
93
  }
62
- return {
63
- head: head.join('\n').trim(),
64
- sections: sections.map((s) => s.join('\n').trim()).filter(Boolean),
65
- };
94
+ if (sections.length > 0)
95
+ return finishSplit(head, sections, 'sections');
96
+ // 1b) 顶层列表项:`# 标题` + 若干 `- 结论` 是 MEMORY.md 最常见的形状。
97
+ // 至少两条才走这一级:只有一条时它更像散文里的一个符号,交给段落切分更不容易整篇卡死。
98
+ const itemHead = [];
99
+ const items = [];
100
+ let current = null;
101
+ fenced = false;
102
+ for (const line of lines) {
103
+ if (FENCED.test(line))
104
+ fenced = !fenced;
105
+ if (!fenced && LIST_ITEM.test(line)) {
106
+ if (current)
107
+ items.push(current);
108
+ current = [line];
109
+ }
110
+ else if (current) {
111
+ current.push(line);
112
+ }
113
+ else {
114
+ itemHead.push(line);
115
+ }
116
+ }
117
+ if (current)
118
+ items.push(current);
119
+ if (items.length >= 2)
120
+ return finishSplit(itemHead, items, 'items');
121
+ // 1c) 空行段落:整篇散文也能按段丢。首段作为 head(通常是标题 / 开场),永远保留。
122
+ const paragraphs = [];
123
+ let para = null;
124
+ fenced = false;
125
+ for (const line of lines) {
126
+ if (FENCED.test(line))
127
+ fenced = !fenced;
128
+ if (!fenced && !line.trim()) {
129
+ if (para)
130
+ paragraphs.push(para);
131
+ para = null;
132
+ continue;
133
+ }
134
+ if (!para)
135
+ para = [line];
136
+ else
137
+ para.push(line);
138
+ }
139
+ if (para)
140
+ paragraphs.push(para);
141
+ const [first, ...rest] = paragraphs;
142
+ return finishSplit(first ?? [], rest, 'paragraphs');
66
143
  }
67
144
  function joinSections(split) {
68
145
  return [split.head, ...split.sections].filter(Boolean).join('\n\n');
69
146
  }
70
- /** 只留首段(preamble + 第一个 `##` 段) */
147
+ /** 只留首段(preamble + 第一个切出来的段) */
71
148
  function firstSection(body) {
72
149
  const split = splitSections(body);
73
- return joinSections({ head: split.head, sections: split.sections.slice(0, 1) });
150
+ return joinSections({ head: split.head, sections: split.sections.slice(0, 1), mode: split.mode });
74
151
  }
75
- function sectionTitle(section) {
152
+ function sectionTitle(section, mode) {
76
153
  const first = section.split('\n', 1)[0] ?? '';
77
- return first.replace(/^##\s+/, '').trim() || '(无标题)';
154
+ const raw = mode === 'sections'
155
+ ? first.replace(/^##\s+/, '')
156
+ : mode === 'items'
157
+ ? first.replace(LIST_ITEM, '')
158
+ : first;
159
+ const one = raw.replace(/\s+/g, ' ').trim();
160
+ if (!one)
161
+ return '(无标题)';
162
+ return one.length > TOC_TITLE_MAX ? one.slice(0, TOC_TITLE_MAX) + '…' : one;
78
163
  }
79
164
  /**
80
165
  * 被截掉段落的目录:代替「按位置丢尾段」的不可见性。
@@ -216,7 +301,7 @@ function computePayload(cfg) {
216
301
  const over = () => total() + countWords(tocText([...dropped, ...mine], tocCap)) > budget;
217
302
  while (over() && split.sections.length > 1) {
218
303
  const section = split.sections.pop();
219
- mine.unshift({ name, title: sectionTitle(section) });
304
+ mine.unshift({ name, title: sectionTitle(section, split.mode) });
220
305
  const body = joinSections(split);
221
306
  original.set(name, body);
222
307
  words.set(name, countWords(body));
@@ -236,7 +321,7 @@ function computePayload(cfg) {
236
321
  const present = files.filter((f) => (original.get(f.name) ?? '').length > 0);
237
322
  const bodies = present.map((f) => `## ${f.name}\n\n${escapeFrame(original.get(f.name) ?? '')}`);
238
323
  const keptWords = total();
239
- const finalWords = keptWords + countWords(toc);
324
+ let finalWords = keptWords + countWords(toc);
240
325
  const originalWords = files.reduce((sum, f) => sum + (pristineWords.get(f.name) ?? 0), 0);
241
326
  // 报「正文被截掉多少」,不是净减少:目录也会占词,混在一起会让人以为没丢多少
242
327
  const truncatedWords = Math.max(0, originalWords - keptWords);
@@ -257,7 +342,30 @@ function computePayload(cfg) {
257
342
  notes.push(`AGENTS.md 占 ${agentsWords}/${budget} 词且不参与截断,留给 USER / MEMORY 的只有 ${Math.max(0, budget - agentsWords)} 词`);
258
343
  }
259
344
  if (finalWords > budget) {
260
- notes.push(`预算不足:内容 ${finalWords} 词,超出 ${budget} 词;AGENTS.md 为硬规则,不截断`);
345
+ // 超预算时点名「谁已经没法再丢」:只说「AGENTS 不截断」会把 MEMORY 的条目形状问题藏在后面
346
+ const stuck = [];
347
+ if (agentsWords > 0)
348
+ stuck.push(`AGENTS.md 为硬规则不截断(${agentsWords} 词)`);
349
+ for (const name of ['MEMORY.md', 'USER.md']) {
350
+ const left = words.get(name) ?? 0;
351
+ if (left <= 0)
352
+ continue;
353
+ const what = splitSections(original.get(name) ?? '').mode;
354
+ stuck.push(`${name} ${left} 词(已无更多可丢的${what === 'items' ? '条目' : what === 'paragraphs' ? '段落' : '小节'})`);
355
+ }
356
+ notes.push(`预算不足:内容 ${finalWords} 词,超出 ${budget} 词;${stuck.join('、')}`);
357
+ }
358
+ // 接近上限就回显用量:增长是连续的,等到第一次截断才说,正好是最坏的时刻。
359
+ // 这一行算进 finalWords(否则「280/300」是假的);放不下就整条不加 —— 宁可不说,
360
+ // 也不让提醒本身把预算吃满。与「已截断 / 预算不足」互斥。
361
+ if (notes.length === 0 && budget > 0 && finalWords >= budget * MEMORY_NEAR_RATIO) {
362
+ // 两遍:先量这一行本身占多少词,再把它算进 finalWords 后重报数字 ——
363
+ // 否则会说着「280/300」却实际注入 285 词(提示自己也要吃饭)
364
+ const cost = countWords(`记忆已用 ${finalWords}/${budget} 词(100%)`);
365
+ if (finalWords + cost <= budget) {
366
+ finalWords += cost;
367
+ notes.push(`记忆已用 ${finalWords}/${budget} 词(${Math.round((finalWords / budget) * 100)}%)`);
368
+ }
261
369
  }
262
370
  const notice = notes.length > 0 ? `\n\n(注入预算 ${budget} 词:${notes.join(';')})` : '';
263
371
  // 只有用了这套约定的库(根目录有 AGENTS.md)才提醒周节奏
@@ -275,6 +383,7 @@ function computePayload(cfg) {
275
383
  text,
276
384
  words: finalWords,
277
385
  budget,
386
+ ratio: budget > 0 ? Math.round((finalWords / budget) * 100) / 100 : 0,
278
387
  truncatedWords,
279
388
  tocWords: countWords(toc),
280
389
  files: files.map((f) => ({