dsh-zdiary-kit 3.2.0 → 3.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,4 +1,4 @@
1
- # dsh-zdiary-kit 3.2.0
1
+ # dsh-zdiary-kit 3.3.0
2
2
 
3
3
  > 给 [DSH](https://github.com/deepseek-ai/deepseek-harness) 装一个**内置 [zk](https://github.com/zk-org/zk) 的知识库 / 日记本**:
4
4
  > 插件提供一键安装 zk(官方 release;设置页按钮或 `zk-kit install`)、自动建笔记本(zk init + 日记模板 + 日记 group),
@@ -12,7 +12,7 @@
12
12
  |---|---|
13
13
  | `zk_search` | 全文 / 标签 / 日期 / 断链 / 孤立笔记检索,返回标题、相对路径、绝对路径、标签、摘要;中文查询自动并用子串匹配(`matchStrategy` 说明用了 `fts` / `regex` / `mixed`,补上全文索引漏掉的笔记) |
14
14
  | `zk_query` | 结构化检索:按 type / status / 标签 / 目录 / 日期过滤,默认只看 active 且不含归档;`include_archived` 连归档一起查(此时未显式给 status 则不再默认过滤 active) |
15
- | `zk_new` | 新建原子笔记(zk 生成文件名、套模板、写索引),可带摘要、标签与双链;`summary` 填进模板的 `## Summary`(正文里已写了这一节就不动,返回 `summaryApplied: false`);`name` 可直接指定短文件名(不给则按标题生成,中文标题得到拼音长名);layered 下不给 `dir` 就按 `type` 落位(source → notes/sources),两者都没有、或给的 `dir` 不在任何 group 里都直接报错;`tags` 只补正文里没有的;flat 下按标题查重,重复直接报错;归档里有同名旧结论只警告并带出废弃原因;type / authority 只有 layered 模板会写进 frontmatter;`raw/`、`inbox/`、`archive/` 与根目录 meta 文件一律拒写(写进去会被排除出索引 / 被当成人写的工作面;归档只放 `zk_supersede` 搬进去的旧结论);中文笔记没有任何标签时在 `tagWarning` 里提示(只提示,不阻断) |
15
+ | `zk_new` | 新建原子笔记(zk 生成文件名、套模板、写索引),可带摘要、标签与双链;`summary` 填进模板的 `## Summary`(正文里已写了这一节就不动,返回 `summaryApplied: false`);`name` 可直接指定短文件名(不给则按标题生成,中文标题得到拼音长名);layered 下不给 `dir` 就按 `type` 落位(source → notes/sources),两者都没有、或给的 `dir` 不在任何 group 里都直接报错;`tags` 只补正文里没有的;flat 下按标题查重,重复直接报错;归档里有同名旧结论只警告并带出废弃原因;type / authority 只有 layered 模板会写进 frontmatter;`raw/`、`inbox/`、`archive/` 与根目录 meta 文件一律拒写(写进去会被排除出索引 / 被当成人写的工作面;归档只放 `zk_supersede` 搬进去的旧结论);同目录里有「改一两个字」的相似标题时在 `similar` 里提示(带分数,只提示、不阻断);中文笔记没有任何标签时在 `tagWarning` 里提示(只提示,不阻断) |
16
16
  | `zk_append` | 往已有笔记末尾续写(自动补空行,可先起二级标题);根目录 meta 文件拒写 |
17
17
  | `zk_daily` | 打开/创建某天的日记,并追加一条带时间的记录(layered 模板写进 `## Events` 的 `### HH:MM`,flat 追加到文件末尾的 `## HH:MM`) |
18
18
  | `zk_link` | 在两篇笔记间加 `[[…]]` 双链(已存在不重复加;目标不存在会给出候选;链接追加到文末,已有 Links/链接 小节则不重复起标题);meta 文件不作为来源或目标 |
@@ -19,6 +19,7 @@ import { absPathOf, allNotes, graphEdges, hasNotebook, isUnderDir, localDate, re
19
19
  import { isMetaPath } from '../../lib/meta.js';
20
20
  import { buildMemoryPayload, formatFileShares } from '../../lib/memory.js';
21
21
  import { RETIRED_ENTRY_RE } from '../../lib/memory-format.js';
22
+ import { TEMPLATE_VERSION } from '../../lib/agents-template.js';
22
23
  import { parseFrontmatter } from '../../lib/frontmatter.js';
23
24
  import { stripPersonaMarker } from '../../lib/persona-template.js';
24
25
  import { esc, layout, renderMarkdown } from './html.js';
@@ -286,6 +287,21 @@ async function handleMemory(res, cfg) {
286
287
  const usage = `记忆 ${payload.words}/${payload.budget} 词(${shares || '三份都空'})` +
287
288
  (payload.truncatedWords > 0 ? ` · 已截断 ${payload.truncatedWords} 词` : '') +
288
289
  (payload.retiredWords > 0 ? ` · 退役省略 ${payload.retiredWords} 词` : '');
290
+ // 格式债(P1):用量下面单列一行 —— 周审入口要能一眼看到日期 / 来源 / 模板版本三处缺口。
291
+ // 数字取载荷里的 formatDebt / templateVersion(与注入同一份,不重读文件、不跑 lint);
292
+ // 不补日期、不猜来源;全干净就不写这一行。
293
+ const debt = payload.formatDebt;
294
+ const templateVersion = payload.templateVersion;
295
+ // 没有 AGENTS.md 时 templateVersion 也是 0:靠 files[].present 区分「没模板」与「旧模板」
296
+ const agentsPresent = payload.files.some((f) => f.name === 'AGENTS.md' && f.present);
297
+ const formatParts = [];
298
+ if (debt.undated > 0 || debt.unlinked > 0) {
299
+ formatParts.push(`${debt.undated}/${debt.total} 条没日期`, `${debt.unlinked} 条没来源`);
300
+ }
301
+ if (agentsPresent && templateVersion !== TEMPLATE_VERSION) {
302
+ formatParts.push(`AGENTS 模板 ${templateVersion === 0 ? '无版本标记' : `v${templateVersion}`}(当前 v${TEMPLATE_VERSION})`);
303
+ }
304
+ const formatLine = formatParts.length > 0 ? `格式:${formatParts.join(' · ')}` : '';
289
305
  // 人格段:超上限只告警
290
306
  const c = payload.persona;
291
307
  const personaSummary = c.present
@@ -317,6 +333,7 @@ async function handleMemory(res, cfg) {
317
333
  `<p class="crumb"><a href="${VIEW}">首页</a> / 记忆</p>`,
318
334
  '<h1>记忆</h1>',
319
335
  `<p class="meta">${esc(usage)}</p>`,
336
+ formatLine ? `<p class="meta">${esc(formatLine)}</p>` : '',
320
337
  '<p class="meta">根目录 meta 由人和 agent 直接编辑,不进检索;这里只读,不提供编辑。</p>',
321
338
  `<h2>人格</h2>`,
322
339
  `<p class="meta">${esc(personaSummary)}</p>`,
@@ -526,6 +526,7 @@ export function buildTools(workspaceOf = () => processWorkspace()) {
526
526
  '归档里有同名旧结论不会拦,但会放进 archived(带 supersede-reason):先读它,别把同一个错误结论重新提出来。' +
527
527
  'type / authority 只有 layered 模板会写进 frontmatter。tags 会写成 #hashtag;links 里的目标会被追加成 wiki 双链。' +
528
528
  '中文笔记如果没有任何标签(入参 / 默认值 / 正文 hashtag 都没有),会在 tagWarning 里提示 —— 只提示,不阻断。' +
529
+ '同目录里有「改一两个字」的相似标题时会放进 similar(带分数):只提示,不阻断,也不自动建链接。' +
529
530
  '根目录 meta 文件(AGENTS / USER / MEMORY 等)与 raw/ 、inbox/ 不能写:前者会被当成人写的工作面,后两者会被排除出索引。',
530
531
  parameters: {
531
532
  type: 'object',
@@ -563,6 +564,14 @@ export function buildTools(workspaceOf = () => processWorkspace()) {
563
564
  reason: { type: 'string' },
564
565
  }, ['path', 'title', 'reason']),
565
566
  },
567
+ similar: {
568
+ type: 'array',
569
+ items: objSchema({
570
+ title: { type: 'string' },
571
+ path: { type: 'string' },
572
+ score: { type: 'number' },
573
+ }, ['title', 'path', 'score']),
574
+ },
566
575
  warnings: { type: 'array', items: { type: 'string' } },
567
576
  }, ['notebook', 'path', 'absPath', 'title', 'tags', 'links', 'summaryApplied', 'archived', 'warnings']),
568
577
  },
@@ -606,6 +615,7 @@ export function buildTools(workspaceOf = () => processWorkspace()) {
606
615
  return {
607
616
  notebook: cfg.notebook, path: created.path, absPath: created.absPath, title: created.title, tags, links,
608
617
  summaryApplied: created.summaryApplied, archived, warnings,
618
+ ...(created.similar.length ? { similar: created.similar } : {}),
609
619
  ...(created.summaryWarning ? { summaryWarning: created.summaryWarning } : {}),
610
620
  ...(tagWarning ? { tagWarning } : {}),
611
621
  };
@@ -621,6 +631,10 @@ export function buildTools(workspaceOf = () => processWorkspace()) {
621
631
  lines.push('⚠️ ' + v.summaryWarning);
622
632
  if (v.tagWarning)
623
633
  lines.push('⚠️ ' + v.tagWarning);
634
+ if (v.similar?.length) {
635
+ lines.push('⚠️ 疑似已有:' + v.similar.map((s) => `${s.title}(${s.path},${s.score.toFixed(2)})`).join('、') +
636
+ ' —— 先 read 确认是不是同一条;要合并就 zk_supersede,不要直接再写一遍');
637
+ }
624
638
  if (v.archived.length) {
625
639
  lines.push('⚠️ 归档里有同名旧结论:' + v.archived.map((h) => h.path + (h.reason ? `(废弃原因:${h.reason})` : '(没有记录废弃原因)')).join(';') +
626
640
  ' —— 先读它,确认不是同一个结论再复用标题');
@@ -924,6 +938,13 @@ export function buildTools(workspaceOf = () => processWorkspace()) {
924
938
  tocWords: { type: 'number' },
925
939
  totalWords: { type: 'number' },
926
940
  overheadWords: { type: 'number' },
941
+ // 格式债 / 模板版本:只读元数据,比 memoryUsage 的投影早一步就能拿到
942
+ formatDebt: objSchema({
943
+ total: { type: 'number' },
944
+ undated: { type: 'number' },
945
+ unlinked: { type: 'number' },
946
+ }, ['total', 'undated', 'unlinked']),
947
+ templateVersion: { type: 'number' },
927
948
  persona: objSchema({
928
949
  present: { type: 'boolean' },
929
950
  contentWords: { type: 'number' },
@@ -963,7 +984,7 @@ export function buildTools(workspaceOf = () => processWorkspace()) {
963
984
  retiredWords: { type: 'number' },
964
985
  }, ['name', 'present', 'words', 'originalWords', 'retiredWords']),
965
986
  },
966
- }, ['text', 'words', 'budget', 'ratio', 'truncatedWords', 'retiredWords', 'tocWords', 'totalWords', 'overheadWords', 'persona', 'notebook', 'defaultNotebook', 'pinned', 'notebooks', 'files']),
987
+ }, ['text', 'words', 'budget', 'ratio', 'truncatedWords', 'retiredWords', 'tocWords', 'totalWords', 'overheadWords', 'formatDebt', 'templateVersion', 'persona', 'notebook', 'defaultNotebook', 'pinned', 'notebooks', 'files']),
967
988
  },
968
989
  async run(_args, env) {
969
990
  // 不 ensureNotebook:读记忆不该依赖 zk,笔记本不存在时就是空载荷
@@ -21,6 +21,16 @@
21
21
  export const TEMPLATE_VERSION = 8;
22
22
  /** 首行版本标记(实测 4 词);不许带日期 —— 带日期的写法实测 6 词,白花 2 词 */
23
23
  export const TEMPLATE_MARK = `<!-- zdiary-template: v${TEMPLATE_VERSION} -->`;
24
+ /** 版本标记的正则(本文件内用;外部只通过 `templateVersionOf` 取数,免得又一个口径) */
25
+ const TEMPLATE_MARK_RE = /<!--\s*zdiary-template:\s*v(\d+)\s*-->/;
26
+ /**
27
+ * AGENTS.md 里的模板版本;没有标记返回 0。
28
+ * 只读标记、不校验正文哨兵 —— 哨兵是 lint 的事,记忆页只要一眼可读的版本号。
29
+ */
30
+ export function templateVersionOf(body) {
31
+ const hit = TEMPLATE_MARK_RE.exec(String(body ?? ''));
32
+ return hit ? Number(hit[1]) : 0;
33
+ }
24
34
  /**
25
35
  * 当前版本的正文哨兵:只查「标记已经是当前版本」的文件,用来发现
26
36
  * 「只把首行数字改成 vN、正文还是旧版」。
package/dist/lib/lint.js CHANGED
@@ -26,11 +26,12 @@ import path from 'node:path';
26
26
  import { allNotes, graphEdges, localDate, MAX_SCAN, notesWithFlag, parseErrorWarnings } from './zk.js';
27
27
  import { normalizeTitle, resolveWikiTarget, WIKI_LINK, wikiIndex } from './wikilink.js';
28
28
  import { parseFrontmatter } from './frontmatter.js';
29
- import { daysSinceDate, entryDate, isRetiredEntry, splitMemoryEntries } from './memory-format.js';
30
- import { AGENTS_TEMPLATE, AGENTS_TEMPLATE_FLAT, TEMPLATE_SENTINELS, TEMPLATE_VERSION } from './agents-template.js';
29
+ import { daysSinceDate, entryDate, isRetiredEntry, memoryFormatDebt, splitMemoryEntries } from './memory-format.js';
30
+ import { AGENTS_TEMPLATE, AGENTS_TEMPLATE_FLAT, TEMPLATE_SENTINELS, TEMPLATE_VERSION, templateVersionOf } from './agents-template.js';
31
31
  import { PERSONA_TEMPLATE_SENTINELS, PERSONA_TEMPLATE_VERSION } from './persona-template.js';
32
32
  import { timelineCounts, timelineIssues } from './timeline.js';
33
33
  import { isDayString } from './dates.js';
34
+ import { similarKeyOf, similarScore } from './similar.js';
34
35
  /** 每类最多回多少条(计划 §4 M3);总数另给 */
35
36
  export const MAX_ITEMS = 50;
36
37
  /** 时间轴只扫最近多少天(计划 §2 D4):一年日记会报几百条旧问题,把今天的问题挤出 50 条上限 */
@@ -56,33 +57,8 @@ export function duplicateTitles(notes, max = MAX_ITEMS) {
56
57
  dup.sort((a, b) => b.paths.length - a.paths.length || a.title.localeCompare(b.title));
57
58
  return { total: dup.length, items: dup.slice(0, max) };
58
59
  }
59
- /** 相似标题的判定:字符二元组 Jaccard 下限;短串被长串包含时另算(短串至少 6 字) */
60
- const SIMILAR_RATIO = 0.6;
61
- const SIMILAR_SHORT = 6;
62
60
  /** 同目录最多两两比较多少篇:超过就截断并置 truncated,别让 1 万篇变成 O(n²) */
63
61
  const SIMILAR_GROUP_MAX = 300;
64
- /** 比较用的标题:NFKC → 小写 → 去标点 / 空白。中文不改字,只抹掉排版差异 */
65
- function similarKey(title) {
66
- return String(title ?? '').normalize('NFKC').toLowerCase().replace(/[\s\p{P}\p{S}]/gu, '');
67
- }
68
- function bigrams(key) {
69
- const chars = [...key];
70
- const out = new Set();
71
- for (let i = 0; i < chars.length - 1; i++)
72
- out.add(chars[i] + chars[i + 1]);
73
- if (out.size === 0 && chars.length > 0)
74
- out.add(chars[0]);
75
- return out;
76
- }
77
- function jaccard(a, b) {
78
- if (a.size === 0 || b.size === 0)
79
- return 0;
80
- let shared = 0;
81
- for (const gram of a)
82
- if (b.has(gram))
83
- shared += 1;
84
- return shared / (a.size + b.size - shared);
85
- }
86
62
  /**
87
63
  * 疑似重复标题(P2-10):精确查重只能挡住手滑 —— 中文改两个字就绕过去了。
88
64
  *
@@ -98,15 +74,13 @@ export function similarTitles(notes, scanTruncated, max = MAX_ITEMS) {
98
74
  const groups = new Map();
99
75
  for (const note of notes) {
100
76
  const title = note.title || path.basename(note.path, path.extname(note.path));
101
- const key = similarKey(title);
102
- if (!key)
103
- continue;
104
- // 纯数字:日期 / 编号类标题,相似度只反映「数字挨着」,不反映重复结论
105
- if (/^\d+$/.test(key))
77
+ // 空标题、纯数字(日期 / 编号)都在这里被挡掉,口径与 zk_new 的写路径提示同一份
78
+ const target = similarKeyOf(title);
79
+ if (!target)
106
80
  continue;
107
81
  const dir = path.posix.dirname(note.path);
108
82
  const list = groups.get(dir) ?? [];
109
- list.push({ title, path: note.path, key, exact: normalizeTitle(title), grams: bigrams(key), size: [...key].length });
83
+ list.push({ title, path: note.path, exact: normalizeTitle(title), ...target });
110
84
  groups.set(dir, list);
111
85
  }
112
86
  let truncated = scanTruncated;
@@ -124,24 +98,14 @@ export function similarTitles(notes, scanTruncated, max = MAX_ITEMS) {
124
98
  // 归一化后完全一样:那是 duplicateTitles 的活(这里报会让同一件事出现两遍)
125
99
  if (a.exact === b.exact)
126
100
  continue;
127
- // 短标题的二元组太少(RAG / RAG 2 会算出 0.67),噪声大于信号
128
- if (a.size < 4 || b.size < 4)
129
- continue;
130
- let score = jaccard(a.grams, b.grams);
131
- let hit = score >= SIMILAR_RATIO;
132
- if (!hit) {
133
- const [short, long, shortSize] = a.size <= b.size ? [a.key, b.key, a.size] : [b.key, a.key, b.size];
134
- if (shortSize >= SIMILAR_SHORT && long.includes(short)) {
135
- hit = true;
136
- score = SIMILAR_RATIO;
137
- }
138
- }
139
- if (!hit)
101
+ // 相似判定只有 similar.ts 一份:短标题(< 4 码点)也由它挡掉
102
+ const score = similarScore(a, b);
103
+ if (score === null)
140
104
  continue;
141
105
  found.push({
142
106
  titles: [a.title, b.title],
143
107
  paths: [a.path, b.path],
144
- score: Math.round(score * 100) / 100,
108
+ score,
145
109
  });
146
110
  }
147
111
  }
@@ -211,10 +175,13 @@ export function memoryLinkIssues(cfg, notes, opts = {}) {
211
175
  }
212
176
  // 只对 MEMORY.md 数「没附来源 / 没日期 / 退役 / 陈旧」:USER.md 是偏好清单,大多数条目本来就没有来源
213
177
  if (name === 'MEMORY.md') {
178
+ // 日期 / 来源缺口取唯一口径 memoryFormatDebt(退役条目不算、`[[ ]]` 不算来源),
179
+ // 注入提示与记忆页用的也是它 —— 同一个「N 条没来源」不许在三处给出三个数。
180
+ const debt = memoryFormatDebt(body);
181
+ undated = debt.undated;
182
+ unlinked = debt.unlinked;
214
183
  for (const entry of splitMemoryEntries(body)) {
215
184
  const first = entry.split('\n', 1)[0] ?? '';
216
- if (!entry.includes('[['))
217
- unlinked += 1;
218
185
  // 退役行:磁盘保留、注入从 0.9 起省略(D3),只核对它指向的新结论是否还活着
219
186
  if (isRetiredEntry(entry)) {
220
187
  retired += 1;
@@ -226,10 +193,8 @@ export function memoryLinkIssues(cfg, notes, opts = {}) {
226
193
  }
227
194
  // 日期要真校验:`2026-99-99` 既不算「有日期」,也不该在陈旧里报一次
228
195
  const date = entryDate(entry);
229
- if (!date) {
230
- undated += 1;
196
+ if (!date)
231
197
  continue;
232
- }
233
198
  const age = daysSinceDate(date, now);
234
199
  if (age !== null && age > staleDays) {
235
200
  staleTotal += 1;
@@ -501,7 +466,6 @@ export function tagHygiene(notes, max = 20) {
501
466
  singletons: { total: singletons.length, items: singletons.slice(0, 10) },
502
467
  };
503
468
  }
504
- const TEMPLATE_MARK_RE = /<!--\s*zdiary-template:\s*v(\d+)\s*-->/;
505
469
  const PERSONA_MARK_RE = /<!--\s*zdiary-persona:\s*v(\d+)\s*-->/;
506
470
  const PLACEHOLDER_RE = /\{\{\s*[^}]+\s*\}\}/g;
507
471
  /**
@@ -594,8 +558,7 @@ export function templateStatus(cfg) {
594
558
  catch {
595
559
  return { present: false, version: 0, current: TEMPLATE_VERSION, stale: false };
596
560
  }
597
- const hit = TEMPLATE_MARK_RE.exec(body);
598
- const version = hit ? Number(hit[1]) : 0;
561
+ const version = templateVersionOf(body);
599
562
  const mismatchDetail = version === TEMPLATE_VERSION
600
563
  ? sentinelIssue(body, TEMPLATE_SENTINELS[TEMPLATE_VERSION])
601
564
  : null;
@@ -60,6 +60,29 @@ export function entryDate(entry) {
60
60
  return null;
61
61
  return validDate(m[1], m[2], m[3]) ? `${m[1]}-${m[2]}-${m[3]}` : null;
62
62
  }
63
+ /**
64
+ * 条目里的双链来源;只看写没写,链接是否真存在是 lint 的事。
65
+ * 目标是「非空白」:`[[ ]]` 不算来源(lint 的 `WIKI_LINK` 也把空目标当没链接),
66
+ * `[[目标|别名]]` / `[[目标#小节]]` 算。
67
+ */
68
+ const LINK = /\[\[[^\]\n]*\S[^\]\n]*\]\]/;
69
+ /**
70
+ * 数一遍格式债:只机械计数,不猜日期、不补来源 —— 两者仍由人和 agent 写。
71
+ * 注入与记忆页只负责把缺口摆出来,否则「按日期淘汰」对没日期的老库永远空转。
72
+ * 退役条目不算:它们按约定退役,不该因为格式被继续提醒。
73
+ */
74
+ export function memoryFormatDebt(body) {
75
+ const entries = splitMemoryEntries(body).filter((entry) => !isRetiredEntry(entry));
76
+ let undated = 0;
77
+ let unlinked = 0;
78
+ for (const entry of entries) {
79
+ if (!entryDate(entry))
80
+ undated += 1;
81
+ if (!LINK.test(entry))
82
+ unlinked += 1;
83
+ }
84
+ return { total: entries.length, undated, unlinked };
85
+ }
63
86
  /**
64
87
  * 去掉退役条目(整条,不留半行),返回正文与删掉的条数。
65
88
  * 磁盘上的文件不动 —— 省略只发生在注入路径上;记忆页 / git 仍看得到它们。
@@ -25,7 +25,8 @@ import fs from 'node:fs';
25
25
  import path from 'node:path';
26
26
  import { DREAM_INTERVAL_DAYS, daysSinceDream, lastDreamDate } from './dream.js';
27
27
  import { fileStamp } from './file-stamp.js';
28
- import { entryDate, splitMemoryEntries, stripRetiredEntries } from './memory-format.js';
28
+ import { entryDate, memoryFormatDebt, stripRetiredEntries } from './memory-format.js';
29
+ import { templateVersionOf } from './agents-template.js';
29
30
  import { PERSONA_META_FILES, MEMORY_META_FILES } from './meta.js';
30
31
  /** vault 根目录下、按优先级排列的三份 meta 文件(定义在 lib/meta.ts,这里只挂个本地名) */
31
32
  export const META_FILES = MEMORY_META_FILES;
@@ -73,6 +74,46 @@ function finishSplit(head, sections, mode) {
73
74
  mode,
74
75
  };
75
76
  }
77
+ /** 顶层列表项切分:缩进续行归上一条,围栏里的 `- ` 不算(与 1b / 单节降级共用) */
78
+ function splitItems(lines) {
79
+ const head = [];
80
+ const items = [];
81
+ let current = null;
82
+ let fenced = false;
83
+ for (const line of lines) {
84
+ if (FENCED.test(line))
85
+ fenced = !fenced;
86
+ if (!fenced && LIST_ITEM.test(line)) {
87
+ if (current)
88
+ items.push(current);
89
+ current = [line];
90
+ }
91
+ else if (current) {
92
+ current.push(line);
93
+ }
94
+ else {
95
+ head.push(line);
96
+ }
97
+ }
98
+ if (current)
99
+ items.push(current);
100
+ return { head, items };
101
+ }
102
+ /**
103
+ * 单节再切一层(P0-2):小节标题并进 head(永不丢),正文按顶层列表项切;
104
+ * 不足两条就保持原样 —— 只有一条时没有可丢的粒度,交给「预算不足」照旧点名。
105
+ * 初次切分与「丢到只剩一节」都走这一个函数,保证两条路径同形。
106
+ */
107
+ function degradeSingleSection(split) {
108
+ if (split.mode !== 'sections' || split.sections.length !== 1)
109
+ return null;
110
+ const [title, ...rest] = split.sections[0].split('\n');
111
+ const inner = splitItems(rest);
112
+ if (inner.items.length < 2)
113
+ return null;
114
+ const head = [split.head, title, inner.head.join('\n').trim()].filter(Boolean).join('\n\n');
115
+ return finishSplit([head], inner.items, 'items');
116
+ }
76
117
  /**
77
118
  * 三级降级切分(P0-1):`##` 小节 → 顶层列表项 → 空行段落。
78
119
  * 只按 `##` 切时,「`# 记忆` + 要点列表」这种形状切不出任何小节,丢弃循环一次都不进,
@@ -97,33 +138,17 @@ function splitSections(body) {
97
138
  else
98
139
  head.push(line);
99
140
  }
100
- if (sections.length > 0)
101
- return finishSplit(head, sections, 'sections');
141
+ if (sections.length > 0) {
142
+ const split = finishSplit(head, sections, 'sections');
143
+ // 只有一节时再降一层(P0-2):`## 结论` + 一串 `- 结论` 是最常见的形状,
144
+ // 不降级的话丢弃循环一次都不进,整篇绕过预算。
145
+ return split.sections.length === 1 ? degradeSingleSection(split) ?? split : split;
146
+ }
102
147
  // 1b) 顶层列表项:`# 标题` + 若干 `- 结论` 是 MEMORY.md 最常见的形状。
103
148
  // 至少两条才走这一级:只有一条时它更像散文里的一个符号,交给段落切分更不容易整篇卡死。
104
- const itemHead = [];
105
- const items = [];
106
- let current = null;
107
- fenced = false;
108
- for (const line of lines) {
109
- if (FENCED.test(line))
110
- fenced = !fenced;
111
- if (!fenced && LIST_ITEM.test(line)) {
112
- if (current)
113
- items.push(current);
114
- current = [line];
115
- }
116
- else if (current) {
117
- current.push(line);
118
- }
119
- else {
120
- itemHead.push(line);
121
- }
122
- }
123
- if (current)
124
- items.push(current);
125
- if (items.length >= 2)
126
- return finishSplit(itemHead, items, 'items');
149
+ const flat = splitItems(lines);
150
+ if (flat.items.length >= 2)
151
+ return finishSplit(flat.head, flat.items, 'items');
127
152
  // 1c) 空行段落:整篇散文也能按段丢。首段作为 head(通常是标题 / 开场),永远保留。
128
153
  const paragraphs = [];
129
154
  let para = null;
@@ -150,7 +175,9 @@ function splitSections(body) {
150
175
  function joinSections(split) {
151
176
  return [split.head, ...split.sections].filter(Boolean).join('\n\n');
152
177
  }
153
- /** 只留首段(preamble + 第一个切出来的段) */
178
+ /** 只留首段(preamble + 第一个切出来的段)。
179
+ * 单节形状下 splitSections 已经降级成条目,「首段」就是标题 + 第一条 ——
180
+ * 否则这个兜底对单节文件仍等于整篇,等于没裁。 */
154
181
  function firstSection(body) {
155
182
  const split = splitSections(body);
156
183
  return joinSections({ head: split.head, sections: split.sections.slice(0, 1), mode: split.mode });
@@ -339,8 +366,23 @@ function computePayload(cfg) {
339
366
  // 截断会改写这份计数;contentWords 保留原值,给 truncatedWords 与 files 用
340
367
  const words = new Map(contentWords);
341
368
  const total = () => [...words.values()].reduce((a, b) => a + b, 0);
342
- // 截断前的 MEMORY 正文:报告「有多少条没日期」要在丢之前数
369
+ // 截断前的 MEMORY 正文(退役条目已剔除):格式债要在丢之前数
343
370
  const memorySource = original.get('MEMORY.md') ?? '';
371
+ // 格式债(P1):日期 / 来源缺口的条数。只报告、不补 —— 但得摆到注入里,
372
+ // 否则「按日期淘汰」对没日期的老库永远空转,而 lint 一周才跑一次。
373
+ const debt = memoryFormatDebt(memorySource);
374
+ // 模板版本与记忆页共用这一份(只读首行 marker,不跑 lint):0 = 没有标记或没有 AGENTS.md
375
+ const agentsBody = original.get('AGENTS.md') ?? '';
376
+ const templateVersion = agentsBody.trim() ? templateVersionOf(agentsBody) : 0;
377
+ /** 格式债的一句;没有缺口返回空串。skipUndated 用于避开「只能按位置丢」已经报过的同一个数 */
378
+ const debtNote = (skipUndated) => {
379
+ const parts = [];
380
+ if (!skipUndated && debt.undated > 0)
381
+ parts.push(`${debt.undated} 条没日期`);
382
+ if (debt.unlinked > 0)
383
+ parts.push(`${debt.unlinked} 条没来源`);
384
+ return parts.length > 0 ? `MEMORY ${parts.join(' · ')}` : '';
385
+ };
344
386
  // ── 机械截断:MEMORY 最旧条目 → USER 尾段 → 各留首段 ──────────────
345
387
  // 丢掉的段落留一份目录(段落标题),让 agent 能按当前任务用 read 取回。
346
388
  // 目录自己也要占预算,所以每丢一段都把它算进去;目录有上限,循环一定收敛。
@@ -350,10 +392,23 @@ function computePayload(cfg) {
350
392
  for (const name of ['MEMORY.md', 'USER.md']) {
351
393
  if (total() + countWords(tocText(dropped, tocCap)) <= budget)
352
394
  break;
353
- const split = splitSections(original.get(name) ?? '');
395
+ // 丢弃前的原文:目录要用「在原文件里排第几」排序,而丢弃顺序会随最旧日期乱跳;
396
+ // 更要命的是「多节 → 降成条目」会把两套坐标系(小节序号 / 条目序号)混进同一个 order,
397
+ // 目录顺序于是乱掉。直接用它在原文里的字符偏移,小节和条目共用一套坐标。
398
+ const pristine = original.get(name) ?? '';
399
+ let split = splitSections(pristine);
354
400
  const mine = [];
355
401
  const over = () => total() + countWords(tocText([...dropped, ...mine], tocCap)) > budget;
356
- while (over() && split.sections.length > 1) {
402
+ // 每轮重判形态:多节先丢整节;只剩一节且还能降级时冻结标题、按条目继续丢。
403
+ // 否则「多节丢到只剩一节」也会停在那里,剩下那一节自己超预算时同样丢不动。
404
+ while (over()) {
405
+ if (split.sections.length <= 1) {
406
+ const deeper = degradeSingleSection(split);
407
+ if (!deeper)
408
+ break;
409
+ split = deeper;
410
+ continue;
411
+ }
357
412
  // MEMORY 按「最旧日期」丢;解析不出日期(或这是 USER)就退回尾部,行为与 0.8.3 一致
358
413
  let index = split.sections.length - 1;
359
414
  if (name === 'MEMORY.md') {
@@ -364,7 +419,9 @@ function computePayload(cfg) {
364
419
  index = oldest;
365
420
  }
366
421
  const section = split.sections.splice(index, 1)[0];
367
- mine.push({ name, title: sectionTitle(section, split.mode), order: index });
422
+ // 相同文本(两条一模一样的条目)会拿到同一个偏移:并列时保持丢弃顺序,足够好
423
+ const at = pristine.indexOf(section);
424
+ mine.push({ name, title: sectionTitle(section, split.mode), order: at < 0 ? Number.MAX_SAFE_INTEGER : at });
368
425
  const body = joinSections(split);
369
426
  original.set(name, body);
370
427
  words.set(name, countWords(body));
@@ -398,15 +455,20 @@ function computePayload(cfg) {
398
455
  let memoryInner = '';
399
456
  if (bodies.length > 0) {
400
457
  const notes = [];
401
- if (truncatedWords > 0)
402
- notes.push(`已截断 ${truncatedWords} 词`);
458
+ // 截断时也带上格式债(P1):先量词数,放不下就整条不加 —— 提示自己也要吃饭。
459
+ // 已经要说「只能按位置丢」时跳过没日期那半句,避免同一个数报两遍。
460
+ if (truncatedWords > 0) {
461
+ const suffix = debtNote(fellBack && debt.undated > 0);
462
+ const append = suffix && finalWords + countWords(` · ${suffix}`) <= budget ? ` · ${suffix}` : '';
463
+ notes.push(`已截断 ${truncatedWords} 词${append}`);
464
+ }
403
465
  if (omittedNote)
404
466
  notes.push(omittedNote);
405
467
  // 一条日期都没有只能按位置丢:说出来,别让人以为是按日期挑的(D2.5)
468
+ // 数字取内存里那份格式债,不在这里另数一遍(退役条目算不算会两边不一致)
406
469
  if (fellBack && truncatedWords > 0) {
407
- const undated = splitMemoryEntries(memorySource).filter((entry) => !entryDate(entry)).length;
408
- if (undated > 0)
409
- notes.push(`MEMORY 有 ${undated} 条没日期,只能按位置丢`);
470
+ if (debt.undated > 0)
471
+ notes.push(`MEMORY 有 ${debt.undated} 条没日期,只能按位置丢`);
410
472
  }
411
473
  // 目录放不下时至少留一句指路;否则被丢掉的段落对模型完全不可见
412
474
  if (!toc && dropped.length > 0) {
@@ -442,7 +504,17 @@ function computePayload(cfg) {
442
504
  const cost = countWords(`记忆已用 ${finalWords}/${budget} 词(100%)`);
443
505
  if (finalWords + cost <= budget) {
444
506
  finalWords += cost;
445
- notes.push(`记忆已用 ${finalWords}/${budget} 词(${Math.round((finalWords / budget) * 100)}%)`);
507
+ // 格式债跟在用量后面(P1):整条量过再说,放不下就一句都不加,
508
+ // 不能出现「MEMORY 9 条没日期」却丢了「3 条没来源」这种半句。
509
+ const suffix = debtNote(false);
510
+ const debtCost = suffix ? countWords(` · ${suffix}`) : 0;
511
+ if (suffix && finalWords + debtCost <= budget) {
512
+ finalWords += debtCost;
513
+ notes.push(`记忆已用 ${finalWords}/${budget} 词(${Math.round((finalWords / budget) * 100)}%) · ${suffix}`);
514
+ }
515
+ else {
516
+ notes.push(`记忆已用 ${finalWords}/${budget} 词(${Math.round((finalWords / budget) * 100)}%)`);
517
+ }
446
518
  }
447
519
  }
448
520
  const notice = notes.length > 0 ? `\n\n(注入预算 ${budget} 词:${notes.join(';')})` : '';
@@ -484,6 +556,8 @@ function computePayload(cfg) {
484
556
  truncatedWords,
485
557
  retiredWords,
486
558
  tocWords: countWords(toc),
559
+ formatDebt: debt,
560
+ templateVersion,
487
561
  files: files.map((f) => ({
488
562
  name: f.name,
489
563
  present: f.body.length > 0,
@@ -0,0 +1,103 @@
1
+ /**
2
+ * 标题相似度(唯一一份):周审 lint 与 zk_new 的写路径提示共用。
3
+ *
4
+ * 为什么单独一个文件:lint.ts 已经 import zk.ts,zk.ts 反向 import lint.ts 会成环;
5
+ * 相似判定抽到无依赖的小模块,两边都往下 import。
6
+ *
7
+ * 纯机械:NFKC → 小写 → 去标点 / 空白,按字符二元组算 Jaccard ≥ 0.6;
8
+ * 短串(≥ 6 字)被长串包含也算命中。不做语义判断、不调模型、不建索引。
9
+ */
10
+ import path from 'node:path';
11
+ import { normalizeTitle } from './wikilink.js';
12
+ /** 字符二元组 Jaccard 下限 */
13
+ const SIMILAR_RATIO = 0.6;
14
+ /** 短串被长串包含时,短串至少要这么长(码点数) */
15
+ const SIMILAR_SHORT = 6;
16
+ /** 标题短于这个码点数不参与比较:二元组太少(RAG / RAG 2 会算出 0.67),噪声大于信号 */
17
+ const SIMILAR_MIN = 4;
18
+ /** 比较用的标题:NFKC → 小写 → 去标点 / 空白。中文不改字,只抹掉排版差异 */
19
+ function similarKey(title) {
20
+ return String(title ?? '').normalize('NFKC').toLowerCase().replace(/[\s\p{P}\p{S}]/gu, '');
21
+ }
22
+ /** 字符二元组;单字标题退化成单字本身(否则集合为空,永远算不出相似) */
23
+ function bigrams(key) {
24
+ const chars = [...key];
25
+ const out = new Set();
26
+ for (let i = 0; i < chars.length - 1; i++)
27
+ out.add(chars[i] + chars[i + 1]);
28
+ if (out.size === 0 && chars.length > 0)
29
+ out.add(chars[0]);
30
+ return out;
31
+ }
32
+ /** Jaccard 相似度(0–1) */
33
+ function jaccard(a, b) {
34
+ if (a.size === 0 || b.size === 0)
35
+ return 0;
36
+ let shared = 0;
37
+ for (const gram of a)
38
+ if (b.has(gram))
39
+ shared += 1;
40
+ return shared / (a.size + b.size - shared);
41
+ }
42
+ /**
43
+ * 可比较的标题;空标题与纯数字(日期 / 编号)返回 null。
44
+ * 纯数字标题的相似度只反映「数字挨着」,不反映重复结论 —— 一年日记会吐出上千组误报。
45
+ */
46
+ export function similarKeyOf(title) {
47
+ const key = similarKey(title);
48
+ if (!key || /^\d+$/.test(key))
49
+ return null;
50
+ // size 按码点算([...key].length),不混用 .length:后者数 UTF-16 单元,
51
+ // 标题带 emoji / 扩展区汉字时会比码点多一倍,「谁是短串」会判错。
52
+ return { key, grams: bigrams(key), size: [...key].length };
53
+ }
54
+ /**
55
+ * 两个标题的相似度(两位小数);不相似返回 null。
56
+ * 「短串被长串包含」命中时按下限 0.6 记 —— 否则 0.5 的分数会让「已经报了」看起来自相矛盾。
57
+ */
58
+ export function similarScore(a, b) {
59
+ if (a.size < SIMILAR_MIN || b.size < SIMILAR_MIN)
60
+ return null;
61
+ const score = jaccard(a.grams, b.grams);
62
+ if (score >= SIMILAR_RATIO)
63
+ return Math.round(score * 100) / 100;
64
+ const [short, long, shortSize] = a.size <= b.size ? [a.key, b.key, a.size] : [b.key, a.key, b.size];
65
+ if (shortSize >= SIMILAR_SHORT && long.includes(short))
66
+ return SIMILAR_RATIO;
67
+ return null;
68
+ }
69
+ /**
70
+ * 写路径查重(P2):同一目录里与 title 相似的已有标题,最多 max 条,分数降序。
71
+ *
72
+ * 只提示、不阻断:误报会挡住正常写作,是否合并仍是人的判断。
73
+ * 归一化后全等的交给 duplicateTitles / createNote 的硬查重,这里不重复报。
74
+ * 归档由调用方先滤掉 —— 这里不认识 Config,也不该自己判断哪些路径算归档。
75
+ */
76
+ export function similarCandidates(notes, title, dir, max = 3) {
77
+ const target = similarKeyOf(title);
78
+ if (!target)
79
+ return [];
80
+ const exact = normalizeTitle(title);
81
+ const dirKey = dir.replace(/\/+$/, '');
82
+ const out = [];
83
+ for (const note of notes) {
84
+ if (!note.path || path.posix.dirname(note.path) !== dirKey)
85
+ continue;
86
+ // 无标题的笔记用文件名 —— 与 `similarTitles` 的 `title || basename` 同口径,
87
+ // 否则写路径与周审的候选集不一样(分数一致也没用)。
88
+ const otherTitle = note.title || path.basename(note.path, path.extname(note.path));
89
+ if (!otherTitle)
90
+ continue;
91
+ if (normalizeTitle(otherTitle) === exact)
92
+ continue;
93
+ const other = similarKeyOf(otherTitle);
94
+ if (!other)
95
+ continue;
96
+ const score = similarScore(target, other);
97
+ if (score === null)
98
+ continue;
99
+ out.push({ title: otherTitle, path: note.path, score });
100
+ }
101
+ out.sort((a, b) => b.score - a.score || a.path.localeCompare(b.path));
102
+ return out.slice(0, max);
103
+ }
package/dist/lib/zk.js CHANGED
@@ -13,6 +13,8 @@ import { BIN_DIR } from '../config/paths.js';
13
13
  import { ExecError, findOnPath, run } from './exec.js';
14
14
  import { parseFrontmatter, setFrontmatter } from './frontmatter.js';
15
15
  import { isMetaPath, META_NAMES } from './meta.js';
16
+ import { similarCandidates } from './similar.js';
17
+ import { normalizeTitle } from './wikilink.js';
16
18
  export class ZkError extends Error {
17
19
  hint;
18
20
  /**
@@ -42,10 +44,6 @@ export function localDate(iso) {
42
44
  const dd = String(d.getDate()).padStart(2, '0');
43
45
  return `${d.getFullYear()}-${mm}-${dd}`;
44
46
  }
45
- /** 标题查重用的归一化:压空白 + 小写(与 lint 的重名口径一致) */
46
- function normalizeTitle(title) {
47
- return String(title ?? '').replace(/\s+/g, ' ').trim().toLowerCase();
48
- }
49
47
  /** 废弃原因最多这么长:frontmatter 是给人看的审计线,不是自由文本容器 */
50
48
  const MAX_SUPERSEDE_REASON = 200;
51
49
  /** 一句话、单行;换行会弄坏 frontmatter,超长机械截断(不判断内容) */
@@ -671,8 +669,9 @@ export async function createNote(cfg, input, signal, scan = (c, s) => allNotes(c
671
669
  // 以前是各跑一次 `zk list`:同一个库扫两遍,还多起一个进程。
672
670
  const dupCheck = cfg.structure !== 'layered';
673
671
  let archived = [];
672
+ let similar = [];
673
+ let snapshot = null;
674
674
  if (hasNotebook(cfg)) {
675
- let snapshot = null;
676
675
  try {
677
676
  snapshot = await scan(cfg, signal);
678
677
  }
@@ -740,6 +739,11 @@ export async function createNote(cfg, input, signal, scan = (c, s) => allNotes(c
740
739
  throw new ZkError(`zk 说建好了但文件不存在:${abs}`);
741
740
  // 扩展名被用户改成 .markdown 等时,预判可能漏掉;这里再兜一次(只删本次新建的文件)
742
741
  const createdRel = relPathOf(cfg, abs);
742
+ // 相似标题(P2):按**实际落下的目录**比同目录标题(layered 不给 dir 时由 type / group 决定)。
743
+ // 只提示、不阻断 —— 精确同名在上面已经报错;口径与 zk_lint 的 similarTitles 同一份实现。
744
+ if (snapshot) {
745
+ similar = similarCandidates(snapshot.filter((n) => !inArchive(cfg, n.path)), title, path.posix.dirname(createdRel));
746
+ }
743
747
  if (isMetaPath(createdRel)) {
744
748
  if (!before.has(path.basename(abs))) {
745
749
  try {
@@ -786,7 +790,7 @@ export async function createNote(cfg, input, signal, scan = (c, s) => allNotes(c
786
790
  summaryWarning = `summary 没写进去:${err instanceof Error ? err.message : String(err)}(文件已建好,可以直接编辑那一节)`;
787
791
  }
788
792
  }
789
- return { path: relPathOf(cfg, finalAbs), absPath: finalAbs, title, archived, summaryApplied, summaryWarning };
793
+ return { path: relPathOf(cfg, finalAbs), absPath: finalAbs, title, archived, similar, summaryApplied, summaryWarning };
790
794
  }
791
795
  /** 笔记本相对路径是否在归档目录下(supersede 会把文件搬进去,路径保持不变) */
792
796
  function inArchive(cfg, rel) {
@@ -10,7 +10,8 @@
10
10
  另读 `DREAMS.md` 的「上次做梦」一行(不进正文、不计预算);
11
11
  `memoryUsage(cfg)` 是同一份载荷的投影(内容词 / 总词 / 预算 / 余量),给 dream 与后续页面用
12
12
  - `lib/memory-format.ts`:条目的唯一切分口径 —— `splitMemoryEntries` / `isRetiredEntry` / `entryDate` /
13
- `stripRetiredEntries` / `daysSinceDate`;memory、dream、lint 共用,禁止各写一套
13
+ `stripRetiredEntries` / `daysSinceDate` / `memoryFormatDebt`(日期与来源缺口的机械计数);
14
+ memory、dream、lint 共用,禁止各写一套
14
15
  - `lib/dream.ts`:`lastDreamDate` / `daysSinceDream`(只认整齐的一行,按本地日历天算);`dreamNotebook` 用它算默认窗口
15
16
  - `lib/wikilink.ts`:`[[链接]]` 的解析口径(路径 → `.md` → `archive/` → 活笔记标题),lint 与 dream 共用一份
16
17
  - `lib/persona-template.ts`:`PERSONA_TEMPLATE` 与独立版本标记(`<!-- zdiary-persona: vN -->`,
@@ -59,7 +60,9 @@
59
60
  **记忆层与事实层的一致性。** `MEMORY.md` 每条结论后附 `[[来源路径]]`(写进 AGENTS 模板);
60
61
  `zk_lint` 的 `memoryLinks` 只做机械核对:原路径 → 加 `.md` → `archive/` 下同名 → 活笔记标题 / 文件名,
61
62
  旧路径在 `archive/` 下找到同名(或活文件带 `status: superseded`)报 `superseded`,都找不到报 `missing`;
62
- 显式写 `archive/` 的链接是有意引用,不算漂移;另数 MEMORY.md 里有多少列表条目没附链接(USER 不计)。
63
+ 显式写 `archive/` 的链接是有意引用,不算漂移;另数 MEMORY.md 里有多少活条目没附链接(USER 不计;
64
+ `[[ ]]` 这种空目标不算来源)。`unlinked` / `undated` 与注入提示、记忆页共用 `memoryFormatDebt()`,
65
+ 同一份 MEMORY 不会在三处给出三个数。
63
66
  P1-3 再加三项,都只报告:`undated`(条目首行没有 `YYYY-MM-DD`,退役行不计)、`retired`(`- [superseded …]` 条目数)、
64
67
  `retiredBroken`(退役行的 `→ [[新结论]]` 解析不到活笔记)。0.9 起注入会省略退役条目(notice 说明省略了几条),
65
68
  但文件不删、不改 —— 「注入 = 文件原文」收窄为「注入 = 原文去掉退役条目」(D3)。
@@ -107,12 +110,32 @@ v8 把 `zk_read` 改成原生 `read` 后仍为 180 词(flat 80)。
107
110
  宁可不说,也不让提醒本身把预算吃满。与「已截断」「预算不足」互斥,三者只会出现一个。
108
111
  `zk_context` 另返回 `ratio`(两位小数,> 1 表示超预算),给模型和测试一个机器可读的用量。
109
112
 
113
+ **格式债摆到眼前,不代劳(P1)。** 「按日期丢最旧」要求条目带 `YYYY-MM-DD`,可参考库里 9 条结论
114
+ **全部没有日期** —— 淘汰只能退回按位置丢,而这件事原先只有人主动跑 `zk_lint` 才看得见。
115
+ `lib/memory-format.ts` 的 `memoryFormatDebt()` 机械数一遍(活条目总数 / 没日期 / 没 `[[来源]]`,退役条目不算;
116
+ `[[ ]]` 这种空目标不算来源),**这是唯一口径**:注入提示、记忆页、`zk_lint` 的 `memoryLinks.unlinked` / `undated`
117
+ 都取它,同一份 MEMORY 不会在三处给出三个数。
118
+ 注入在「记忆已用」或「已截断」那一行后面追加 `MEMORY 9 条没日期 · 3 条没来源`;
119
+ 格式债**整条量过词数**,放不下就一句都不加(不许只剩半句),已经要说「只能按位置丢」时跳过没日期那半句,避免同一个数报两遍。
120
+ 记忆页在用量下面单列一行 `格式:9/9 条没日期 · 0 条没来源 · AGENTS 模板 v5(当前 v8)`,
121
+ 两个数直接取载荷里的 `formatDebt` / `templateVersion`(与注入同一份计算,不重读文件、不跑 lint;
122
+ 模板版本只读首行标记);没有 AGENTS.md 时 `templateVersion` 也是 0,靠 `files[].present` 区分「没模板」与「旧模板」,
123
+ 不报模板这一项;三处都干净就不写这一行。两个字段也出现在 `zk_context` 的输出里(只读、不计词数)。
124
+ **只报告,不补日期、不猜来源** —— 那仍是人和 agent 的语义判断,插件只负责让缺口在每轮注入与周审入口里都可见。
125
+
110
126
  **三级切分(P0-1)。** 只按 `##` 小节切时,「`# 记忆` + 要点列表」这种最常见的形状一个小节都切不出来,
111
127
  丢弃循环一次都不进,预算于是完全不生效(真机实测 880 / 449 / 895 词,`truncatedWords` 都是 0)。
112
128
  现在按顺序降级:`##` 小节 → 顶层列表项(至少两条,缩进续行归上一条)→ 空行段落(首段作为 head);
113
129
  三级都跳过 ```` ``` ```` 围栏里的行 —— 代码块里的 `- ` 或空行不该被当成可丢弃的条目。
114
130
  `head` 永远保留;MEMORY 的丢弃对象按**日期**选(见下),USER 与无日期条目仍从尾部往前丢。
115
131
 
132
+ **单节再降一层(P0-2)。** 只按 `##` 切还有个更隐蔽的形状:整篇只有一个 `## 结论`、结论全是列表 —
133
+ 切出来正好一节,循环「只剩一节就不丢」,整篇照样绕过预算(参考库 12 条 444 词、15 条 525/500、
134
+ 18 条 610/500 都是这个形状)。现在单节会把小节标题并进 `head`(永不丢),正文再按顶层列表项切一层,
135
+ **≥ 2 条才降级**(只有一条时没有可丢的粒度,仍交给「预算不足」点名)。截断循环每轮重判形态:
136
+ 多节先丢整节;只剩一节且可降级就冻结标题、按条目继续丢 —— 否则多节文件丢到只剩一节也会停住。
137
+ `firstSection()` 的兜底随之变成「标题 + 第一条」,不然它对单节文件仍等于整篇,等于没裁。
138
+
116
139
  **截断留目录,不静默消失。** 丢掉的段会合成一份紧凑目录(`MEMORY.md:§标题、§标题`),
117
140
  标题取首行(去掉 `##` 或列表符号)、压到 40 字,最多 5 个;目录自己也算预算(载荷里的 `tocWords`,
118
141
  `min(40, 20%)`:默认 500 词预算时封顶 40 词),
@@ -56,8 +56,12 @@
56
56
  一行 `时间轴:12 处(空块 5 · 倒序 2 · 格式 1 · 位置 4)` + 可折叠的逐行明细;正文仍按原 markdown 渲染,
57
57
  空块保持空 `<h3>`,不排序、不隐藏。普通笔记与没有问题的日记页逐字不变;不受 `zk_lint` 的 90 天窗口限制。
58
58
  - 记忆页(`?p=memory`):分**人格 / 用户 / 工作约定 / 记忆 / 周审**五段 + 载荷预览,
59
- 顶部一行 `记忆 N/预算 词(AGENTS … · MEMORY …(退役 N))`,复用 `buildMemoryPayload` /
60
- `formatFileShares`;文件按常量直接读盘(**不走 `loadNote`** —— 它自己就拒绝 meta),
59
+ 顶部一行 `记忆 N/预算 词(AGENTS … · MEMORY …(退役 N))`,下面可能还有一行格式债
60
+ `格式:9/9 条没日期 · 0 条没来源 · AGENTS 模板 v5(当前 v8)`(只读标记、不跑 lint;三处都干净时不出现);
61
+ 用量行复用 `buildMemoryPayload` / `formatFileShares`,格式行直接取载荷里的 `formatDebt` /
62
+ `templateVersion`(与注入同一份计算,不重读文件、不跑 lint)—— 与 `zk_lint.memoryLinks` 的
63
+ `undated` / `unlinked` 也是同一个 `memoryFormatDebt`,三处不会各报一个数;
64
+ 文件按常量直接读盘(**不走 `loadNote`** —— 它自己就拒绝 meta),
61
65
  缺失的显示「还没写」而不是 404;正文与笔记页同一套转义 + 双链白名单,
62
66
  `[[…]]` 只在该笔记存在时变成链接,其余保持不可点的 `<span class="wikilink">`。
63
67
  人格文件的版本标记与 frontmatter 不显示成正文,改成一行字段(name / role / updated / audit);
@@ -118,6 +118,11 @@ YAML 独有的转义(`\N`、`\_`)不是合法 JSON,退回「去掉引号
118
118
  允许复用标题,但先读旧结论。「是不是同一个错误」仍然由 agent 判断,插件只负责把材料摆出来。
119
119
  代价是每次 `zk_new` 多一次全库 `zk list --include-archived`(扫描上限 1 万篇,按比例放大)——
120
120
  用一次读换一条「不会静默复用的错误结论」;zk 跑不起来时 layered 照建(归档提醒降级),flat 直接报错(标题查重是写入前的硬门槛,fail-closed)。
121
+ `similar`(v3.3):同一次全库扫描顺带算「同目录、改一两个字」的相似标题 —— 归一化后按字符二元组算 Jaccard ≥ 0.6,
122
+ 或短串(≥ 6 字)被长串包含;最多 3 条、分数降序,放进输出的 `similar` 并渲染
123
+ `⚠️ 疑似已有:标题(path,0.72)`。阈值与 `zk_lint` 的 `similarTitles` 是同一份实现(`lib/similar.ts`),
124
+ 两边分数逐条一致;**只提示、不阻断、不自动 `zk_link`、不改标题** —— 误报会挡住正常写作,合并与否仍由 agent 判断。
125
+ 精确同名仍走上面的硬查重(`similar` 里不会重复报),不同目录不比,归档不参与。
121
126
  **读取交给宿主。** 不提供 `zk_read`:DSH 原生 `read` 已经处理行号、分页、沙箱与 read-before-write。
122
127
  `zk_search` / `zk_query` 的每条笔记、`zk_new` / `zk_daily` 的返回都带 `absPath`(相对笔记本的 `path` 仍在,
123
128
  双链与 `zk_*` 参数用得上),模型直接把 `absPath` 传给 `read`;根目录 meta 文件(`MEMORY.md` / `USER.md`)
@@ -130,6 +135,8 @@ YAML 独有的转义(`\N`、`\_`)不是合法 JSON,退回「去掉引号
130
135
  「补空行 / 二级标题 / 写入指定小节」的语义,守卫(meta / `raw/` / `inbox/`)也仍然在。
131
136
  `zk_context` 的 `files[].originalWords`(截断前词数)、`files[].retiredWords`(退役条目占的词数,只算在 `MEMORY.md` 上)、
132
137
  `tocWords`(目录占的词数)与 `ratio`(用量 = `words / budget`,两位小数,> 1 表示超预算)只用于解释预算,不改变注入内容。
138
+ `formatDebt`(`total / undated / unlinked`,与记忆页、`zk_lint.memoryLinks` 同一个 `memoryFormatDebt`)
139
+ 与 `templateVersion`(AGENTS.md 首行标记;0 = 没标记或没文件,用 `files[].present` 区分)是同一批只读元数据。
133
140
  `originalWords` 含退役条目;展示层的「原 X」会先减掉 `retiredWords`,所以退役不会再被当成截断报出来。
134
141
  人格单独一组:`persona.present / contentWords / words / noticeWords / budget / overBudget / overWords / files[]`(`contentWords` 含 `## PERSONA.md` 标题),
135
142
  外加 `totalWords`(`countWords(payload.text)`)与 `overheadWords`(框 / 做梦提醒 / notice / 人格告警等开销)。
@@ -180,8 +187,9 @@ flat(没有 `## Events`)要求 `## HH:MM`,顺序检查跨全文。时间
180
187
  (supersede 重写入链就是这个形状),不算漂移。归档标题不反查(归档默认不进检索,反查就成了第二套索引),
181
188
  「语义重复」不查。为什么必须有:`zk_supersede` 只重写 `zk graph` 里的入链,meta 文件被 `excludedNames`
182
189
  排除在图外 —— 链接不会跟着搬,`--broken-links` 也统计不到;记忆说 X、库里 X 已废弃,这是两层脱节的入口。
183
- `unlinked` 只数 **MEMORY.md** 的列表条目里没有 `[[链接]]` 的(USER.md 是偏好清单,本来大多没有来源,
184
- 不计;散文段落也不算,避免把自由文本变成告警噪音)。
190
+ `unlinked` 只数 **MEMORY.md** 的活条目里没有有效 `[[链接]]` 的(USER.md 是偏好清单,本来大多没有来源,
191
+ 不计;散文段落也不算,避免把自由文本变成告警噪音;退役行不计,`[[ ]]` 空目标不算来源)。
192
+ 它与 `undated` 取自 `memoryFormatDebt()`,和注入提示、记忆页是同一个数。
185
193
  同一份条目解析还数 `undated`(首行没有真校验过的 `YYYY-MM-DD`,退役行不计)、`retired`(`- [superseded …]` 条目数)
186
194
  与 `retiredBroken`(退役行的 `→ [[新结论]]` 解析不到活笔记),以及 `stale`(有日期且超过 `stale_days`,默认 90 天未复核)——
187
195
  都只报告;注入从 0.9 起省略退役条目(notice 说明省略数),文件本身不动。条目切分与日期解析统一走 `lib/memory-format`。
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-zdiary-kit",
3
- "version": "3.2.0",
3
+ "version": "3.3.0",
4
4
  "description": "内置 zk 的 DSH 知识库 / 日记插件:装好即用 —— 自动装 zk、建笔记本,给 agent 一组 zk_* 工具(搜索、读写、日记、双链),设置页里管路径、索引与自检。",
5
5
  "icon": "./icon.svg",
6
6
  "repository": {