dsh-zdiary-kit 3.14.1 → 3.15.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -15,12 +15,12 @@ import { assertNotArchiveCreate, indexPolicy, ZkError, zk } from './zk.js';
15
15
  import { AGENTS_TEMPLATE, AGENTS_TEMPLATE_FLAT, WORKFLOW_TEMPLATE } from './agents-template.js';
16
16
  import { PERSONA_TEMPLATE } from './persona-template.js';
17
17
  import { effectivePaths, isPluginOwned, normGroupPath, parseGroupBlocks, sameGroupPath, samePaths } from './notebook-config.js';
18
- export { AGENTS_TEMPLATE, AGENTS_TEMPLATE_FLAT, WORKFLOW_TEMPLATE } from './agents-template.js';
18
+ export { AGENTS_TEMPLATE, AGENTS_TEMPLATE_FLAT, WORKFLOW_TEMPLATE, WORKFLOW_VERSION } from './agents-template.js';
19
19
  export const DAILY_TEMPLATE = `# {{format-date now "%Y-%m-%d"}}
20
20
 
21
21
  {{content}}
22
22
  `;
23
- /** layered 的日记模板:多三节,`{{content}}` 必须在,否则 stdin 的正文被丢(Z9) */
23
+ /** layered 的日记模板:多三节,`{{content}}` 必须在,否则 stdin 的正文被丢 */
24
24
  export const DAILY_TEMPLATE_LAYERED = `# {{format-date now "%Y-%m-%d"}}
25
25
 
26
26
  ## Events
@@ -368,7 +368,7 @@ export async function ensureNotebook(cfg, signal, opts = {}) {
368
368
  let initialized = false;
369
369
  if (!fs.existsSync(configFile)) {
370
370
  // init 会把目录里已有的笔记一起索引进空库 —— 10k / 1 链实测 202 s,
371
- // 原来的 120 s 会把进程杀在写事务里,留下半库。这里直接给建库预算(M5.0a)。
371
+ // 原来的 120 s 会把进程杀在写事务里,留下半库。这里直接给建库预算。
372
372
  await zk(cfg, ['init', cfg.notebook], { signal, timeoutMs: indexPolicy.buildTimeoutMs });
373
373
  initialized = true;
374
374
  }
@@ -380,10 +380,10 @@ export async function ensureNotebook(cfg, signal, opts = {}) {
380
380
  })
381
381
  : ensureTemplates(cfg, { 'daily.md': DAILY_TEMPLATE });
382
382
  // AGENTS.md 是工作约定(写之前查重 / MEMORY 条目格式与截断方向)。
383
- // layered 自动写;flat 只有显式 withAgents 才写 —— 0.1.0 的 vault 升级过来必须一个文件都不多(M0)。
384
- // 不写的话,默认安装既没有约定、也没有周节奏提醒(P1-6),所以要有一个 opt-in 入口。
383
+ // layered 自动写;flat 只有显式 withAgents 才写 —— 0.1.0 的 vault 升级过来必须一个文件都不多。
384
+ // 不写的话,默认安装既没有约定、也没有周节奏提醒,所以要有一个 opt-in 入口。
385
385
  const agentsWritten = layered || opts.withAgents === true ? writeAgentsTemplate(cfg) : false;
386
- // 人格层(角色)只走显式 opt-in:两种结构都不自动多一个文件(D10)。
386
+ // 人格层(角色)只走显式 opt-in:两种结构都不自动多一个文件。
387
387
  const personaWritten = opts.withPersona === true
388
388
  ? writePersonaTemplate(cfg)
389
389
  : { personaWritten: false };
@@ -5,7 +5,7 @@
5
5
  * 给 MEMORY 的晋升(topCited)、退役保护(retireCandidates)、同日淘汰、周审审计流
6
6
  * 提供「其实被用过」的证据;否则没被召回过的笔记永远拿不到这类信号。
7
7
  *
8
- * 硬边界(§7.4 / §9.4 / §15.12):
8
+ * 硬边界:
9
9
  * · 不记查询词、不记正文、不上报;`title` 只是命中笔记的标题,用来关联 MEMORY 的标题式 `[[来源]]`;
10
10
  * · 默认关(`cfg.recallSignal`),关掉时不读不写,输出与改动前逐字节一致;
11
11
  * · 原子写(tmp + rename)+ 失败静默,计数不能把工具调用弄失败;
@@ -101,3 +101,47 @@ export function similarCandidates(notes, title, dir, max = 3) {
101
101
  out.sort((a, b) => b.score - a.score || a.path.localeCompare(b.path));
102
102
  return out.slice(0, max);
103
103
  }
104
+ /** 标签的比较形态:NFKC → 小写 → 去首尾空白。不抹标点:`C++` 与 `C#` 是两件事 */
105
+ function tagKey(tag) {
106
+ return String(tag ?? '').normalize('NFKC').toLowerCase().trim();
107
+ }
108
+ /**
109
+ * 与 `tag` 近义的已有标签,最多 `max` 条:大小写变体优先,其次按使用篇数降序。
110
+ * `inventory` 由调用方给(写路径用建笔记前的全库快照,lint 用频次表),这里不读盘。
111
+ */
112
+ export function similarTags(tag, inventory, max = 3) {
113
+ const key = tagKey(tag);
114
+ if (!key)
115
+ return [];
116
+ const grams = bigrams(key);
117
+ const out = [];
118
+ for (const item of inventory) {
119
+ if (item.tag === tag)
120
+ continue;
121
+ const other = tagKey(item.tag);
122
+ if (!other)
123
+ continue;
124
+ let kind = null;
125
+ if (other === key)
126
+ kind = 'case';
127
+ else {
128
+ // 长度按码点算(不混用 UTF-16 length),与 similarKeyOf 同一口径
129
+ const keySize = [...key].length;
130
+ const otherSize = [...other].length;
131
+ const [short, long, shortSize] = keySize <= otherSize ? [key, other, keySize] : [other, key, otherSize];
132
+ if (shortSize >= 2 && long.includes(short))
133
+ kind = 'similar';
134
+ else if (keySize >= 2 && otherSize >= 2) {
135
+ const otherGrams = bigrams(other);
136
+ if (jaccard(grams, otherGrams) >= SIMILAR_RATIO)
137
+ kind = 'similar';
138
+ }
139
+ }
140
+ if (kind)
141
+ out.push({ tag: item.tag, count: item.count, kind });
142
+ }
143
+ out.sort((a, b) => (a.kind === b.kind ? 0 : a.kind === 'case' ? -1 : 1) ||
144
+ b.count - a.count ||
145
+ a.tag.localeCompare(b.tag));
146
+ return out.slice(0, max);
147
+ }
@@ -0,0 +1,99 @@
1
+ /**
2
+ * `zk-kit tidy`:收掉旧笔记正文里与 frontmatter `tags` 重复的标签段。
3
+ *
4
+ * 为什么要有这一步:写路径从 v3.x 起只写 frontmatter(`placeTags`),新笔记不再产生第二份;
5
+ * 但**已存在的笔记**没有修复入口 —— 只清一本库治不了别的库。lint 负责让债可见,
6
+ * 这里负责把它收掉,两边共用 `body-tags.ts` 的同一份判据。
7
+ *
8
+ * 三条边界,都是为了「不改结论、不丢标签」:
9
+ * · 只删**整段只有 hashtag** 的段落;句子里的 `#tag` 不是目标;
10
+ * · 只删 frontmatter 已覆盖的(子集判据)—— 正文有、frontmatter 没有的标签是漂移,
11
+ * 删了会丢标签、并集会复活旧词,交人裁;
12
+ * · 没有 `tags` 格(flat / 自定义模板)的笔记一个字不碰:正文标签是 zk 唯一的索引来源。
13
+ * 默认预演,`--fix` 才落盘;跳过 raw / archive / journal 与根目录 meta。
14
+ */
15
+ import fs from 'node:fs';
16
+ import path from 'node:path';
17
+ import { markIndexDirty, scanNotes } from './zk.js';
18
+ import { isMetaPath } from './meta.js';
19
+ import { parseFrontmatter } from './frontmatter.js';
20
+ import { stripTagParagraphs, tagCleanup } from './body-tags.js';
21
+ import { isUnderDir } from './zk.js';
22
+ /** 与巡检同一个读盘上限:命令不该把一个大文件拉进内存 */
23
+ const TIDY_MAX_BYTES = 1024 * 1024;
24
+ /**
25
+ * 扫全库并按判据收标签段。幂等:清过的笔记下一次不再出现。
26
+ *
27
+ * 扫的是 zk 索引里的活笔记(`scanNotes` 已排除 raw / archive / meta),再按 dailyDir 跳过日记:
28
+ * 日记模板没有 `tags` 格,正文 hashtag 在日记里是自由写法,不是要收的债。
29
+ */
30
+ export async function tidyTags(cfg, opts = {}, signal) {
31
+ const dryRun = opts.dryRun !== false;
32
+ const scan = await scanNotes(cfg, {}, signal);
33
+ const notes = scan.notes;
34
+ const items = [];
35
+ const drift = [];
36
+ let scanned = 0;
37
+ let skipped = 0;
38
+ let paragraphs = 0;
39
+ let changed = 0;
40
+ for (const note of notes) {
41
+ if (isMetaPath(note.path) || isUnderDir(note.path, cfg.dailyDir))
42
+ continue;
43
+ const abs = note.absPath ? path.resolve(note.absPath) : path.resolve(cfg.notebook, note.path);
44
+ let content = '';
45
+ try {
46
+ if (fs.statSync(abs).size > TIDY_MAX_BYTES) {
47
+ skipped += 1;
48
+ continue;
49
+ }
50
+ content = fs.readFileSync(abs, 'utf8');
51
+ }
52
+ catch {
53
+ skipped += 1;
54
+ continue;
55
+ }
56
+ scanned += 1;
57
+ const cleanup = tagCleanup(content);
58
+ if (!cleanup)
59
+ continue;
60
+ if (!cleanup.removable) {
61
+ // 漂移只报:删段会丢标签,并集会把旧词复活 —— 两个动作都需要人裁
62
+ drift.push({ path: note.path, title: note.title, tags: cleanup.drift });
63
+ continue;
64
+ }
65
+ items.push({
66
+ path: note.path,
67
+ title: note.title,
68
+ paragraphs: cleanup.paragraphs.length,
69
+ tags: cleanup.tags,
70
+ });
71
+ paragraphs += cleanup.paragraphs.length;
72
+ if (dryRun)
73
+ continue;
74
+ const next = stripTagParagraphs(content, cleanup.paragraphs);
75
+ // 兜底:删完标签段必须还在 frontmatter 里;形状一变就放弃这一篇,别写坏文件
76
+ if (next === content || !('tags' in parseFrontmatter(next).fields))
77
+ continue;
78
+ try {
79
+ fs.writeFileSync(abs, next, 'utf8');
80
+ markIndexDirty(cfg);
81
+ changed += 1;
82
+ }
83
+ catch {
84
+ // 单篇写失败不该让整次清理看起来失败:计划里已经列出它,下一轮还会进来
85
+ skipped += 1;
86
+ }
87
+ }
88
+ return {
89
+ dryRun,
90
+ scanned,
91
+ truncated: scan.completeness !== 'complete',
92
+ skipped,
93
+ notes: items.length,
94
+ paragraphs,
95
+ changed,
96
+ items,
97
+ drift,
98
+ };
99
+ }
@@ -1,5 +1,5 @@
1
1
  /**
2
- * 日记时间轴校验(v3.1 M0):只报告,不改文件(计划 §2 D1 / D2 / D5)。
2
+ * 日记时间轴校验:只报告,不改文件。
3
3
  *
4
4
  * 为什么单独一层:日记的 `## HH:MM` / `### HH:MM` 是人的工作面,空块、倒序、层级混用
5
5
  * 都不会让 zk 报错,也不会影响检索 —— 只会让时间轴慢慢读不出顺序。自动重排会改正文顺序,
package/dist/lib/usage.js CHANGED
@@ -1,7 +1,7 @@
1
1
  /**
2
2
  * 本地聚合计数(**不是** usage 日志):只数「哪个工具被调了几次」,不记查询词、不记路径、不上报。
3
3
  *
4
- * 为什么需要(plan §14.4):到 3.9.0 为止,入口 / 一跳的验收全是机械口径
4
+ * 为什么需要:到 3.9.0 为止,入口 / 一跳的验收全是机械口径
5
5
  * (子进程数、传输字节、schema、与 `graph` 对账),没有一条问「这条路有没有被真的用上」。
6
6
  * 于是「补入口 + 遍历」只能靠论证说它对。这里给出唯一可观测的代理:
7
7
  * `zk_stats` 里的 `usage`,发布后过一段时间看 `walk` / `entryPoints` / `counterEntries` 有没有涨。
@@ -18,7 +18,7 @@ export function normalizeTitle(title) {
18
18
  return String(title ?? '').replace(/\s+/g, ' ').trim().toLowerCase();
19
19
  }
20
20
  /**
21
- * 「同一篇」的身份键(§9.2):有稳定 id 就只看 id,老笔记 / 日记退回 path。
21
+ * 「同一篇」的身份键:有稳定 id 就只看 id,老笔记 / 日记退回 path。
22
22
  * 改名 / 移动 / 重建索引不会改 frontmatter 里的 id,所以这个键不随检索地址漂移。
23
23
  */
24
24
  export function noteKey(note) {
@@ -60,7 +60,7 @@ export function resolveWikiTarget(cfg, target, index) {
60
60
  const rel = String(target ?? '').replace(/\\/g, '/').replace(/^\.\//, '').trim();
61
61
  if (!rel)
62
62
  return { status: 'missing', path: '', explicit: false };
63
- // 稳定 ID 优先(§9.2):`[[<id>]]` 直接落到那篇笔记的当前路径,改名之后也不断链。
63
+ // 稳定 ID 优先:`[[<id>]]` 直接落到那篇笔记的当前路径,改名之后也不断链。
64
64
  // 老库没有 id,byId 为空,下面的路径 / 标题解析顺序逐字不变。
65
65
  const byId = index.byId.get(rel);
66
66
  if (byId)
package/dist/lib/zk.js CHANGED
@@ -14,9 +14,9 @@ import { BIN_DIR } from '../config/paths.js';
14
14
  import { ExecError, findOnPath, run } from './exec.js';
15
15
  import { readJson, writeJson } from './json-file.js';
16
16
  import { withFileLockSync } from './lock.js';
17
- import { parseFrontmatter, setFrontmatter } from './frontmatter.js';
17
+ import { parseFrontmatter, placeTags, setFrontmatter } from './frontmatter.js';
18
18
  import { isMetaPath, META_NAMES } from './meta.js';
19
- import { similarCandidates } from './similar.js';
19
+ import { similarCandidates, similarTags } from './similar.js';
20
20
  import { linkContextOf } from './edge-context.js';
21
21
  import { fenceMask } from './fence.js';
22
22
  import { emptyTemplateSlots } from './sections.js';
@@ -127,7 +127,7 @@ function baseArgs(cfg) {
127
127
  const WARNING_LINE = /^zk: warning: /;
128
128
  /**
129
129
  * 索引策略。测试会改 `waitMs` / `lockWaitMs` / `autoBuildMaxNotes` 把等待压到毫秒级;
130
- * 生产路径一律用默认值(不要从配置里读 —— 这几个数是按 §0.5.1 的实测定的)。
130
+ * 生产路径一律用默认值(不要从配置里读 —— 这几个数是实测定的)。
131
131
  */
132
132
  export const indexPolicy = {
133
133
  /** 建索引预算:10k / 3 链约 13 min(6.6 s + 26 ms × 链接数),留一倍余量 */
@@ -400,7 +400,7 @@ function releaseIndexLock(cfg, lock) {
400
400
  }
401
401
  /**
402
402
  * 启动一次索引:进程内 single-flight 靠 builds Map,跨进程靠调用方先抢到的锁。
403
- * 不传 lock 的只有两种:M5.0a 的冷建路径(db 本来就不完整,与 flush 互斥)、
403
+ * 不传 lock 的只有两种:冷建路径(db 本来就不完整,与 flush 互斥)、
404
404
  * 以及锁建不出来时的降级(退回 R6 之前的行为,不让显式重建失败)。
405
405
  * 成功时按「建库前拍下的 generation」清 dirty:建库期间的写入会留下差值,不会被误清。
406
406
  */
@@ -480,10 +480,10 @@ async function waitForIndexLockRelease(cfg, signal, budgetMs = indexPolicy.lockW
480
480
  /**
481
481
  * 读之前补一次增量索引(R6 的「写后可读」)。返回一条告警,或 null。
482
482
  *
483
- * 优先级(§9.3 第 4 步 / §10.3 第 2 条):db 不完整(missing / interrupted)时**一律不在这里建**,
483
+ * 优先级:db 不完整(missing / interrupted)时**一律不在这里建**,
484
484
  * 交给紧随其后的 `ensureIndexReady` —— 它决定「小库自己补完 / 大库后台建并报 index-building」。
485
485
  * 所以 stale 回退只可能落在「完整但过期的 db」上,绝不会退回读半库,
486
- * 也就不会把 M5.0a 修掉的「读 → 杀 → 半库 → 再读」循环放回来。
486
+ * 也就不会把冷建守卫修掉的「读 → 杀 → 半库 → 再读」循环放回来。
487
487
  *
488
488
  * 挂在 zk() 这个唯一读入口上,searchNotesDetailed / lint / dream 以及 findNote / stats / 反查
489
489
  * 都自动覆盖;不脏时只是一次 stat + 一次读状态文件。
@@ -791,8 +791,8 @@ function parseList(stdout) {
791
791
  }
792
792
  /** 搜索 / 列举笔记 */
793
793
  /**
794
- * 所有查询都排除的路径/文件名(计划 §7)。
795
- * 两个坑(Z4):
794
+ * 所有查询都排除的路径/文件名。
795
+ * 两个坑:
796
796
  * · 不传 glob(`-x 'archive/**'` 会静默失效);
797
797
  * · `-x` 是**相对 cwd** 解析的,不是相对 `--notebook-dir` —— 插件跑在任意 cwd 下,
798
798
  * 所以一律拼成绝对路径,否则换台机器/换个工作目录排除就静默失效。
@@ -844,7 +844,7 @@ function coverageOf(text, words) {
844
844
  return n;
845
845
  }
846
846
  /**
847
- * 全量遍历用的字段格式(plan §0.5.1):10k 实测 JSON 17.2 MB,
847
+ * 全量遍历用的字段格式:10k 实测 JSON 17.2 MB,
848
848
  * 这些字段只要约 2 MB,且省掉 body / rawContent / snippets。
849
849
  *
850
850
  * 分隔符用控制字符:标题 / 标签 / lead 里几乎不会出现;lead 放最后,
@@ -1193,7 +1193,7 @@ export async function allNotes(cfg, opts = {}, signal) {
1193
1193
  }
1194
1194
  /**
1195
1195
  * 用 zk 的过滤器挑笔记,只取**绝对路径**。
1196
- * 别用 `{{path}}`:它相对 cwd,换个工作目录就变成 `../../tmp/...`(Z4 同款坑)。
1196
+ * 别用 `{{path}}`:它相对 cwd,换个工作目录就变成 `../../tmp/...`(同款坑)。
1197
1197
  * 一类过滤器一次进程,不要按笔记逐条跑;取 MAX_SCAN + 1 条才能区分「正好 10 000」与「还有更多」。
1198
1198
  */
1199
1199
  export async function scanNotesWithFlag(cfg, flag, signal) {
@@ -1206,17 +1206,13 @@ export async function scanNotesWithFlag(cfg, flag, signal) {
1206
1206
  const paths = capped ? all.slice(0, MAX_SCAN) : all;
1207
1207
  return { paths, completeness: capped ? 'partial' : 'complete', scanned: paths.length };
1208
1208
  }
1209
- /** 旧入口:只要路径(调用方不需要三态时用) */
1210
- export async function notesWithFlag(cfg, flag, signal) {
1211
- return (await scanNotesWithFlag(cfg, flag, signal)).paths;
1212
- }
1213
1209
  /**
1214
1210
  * `zk graph` 的 `--limit` 上限。注意它限的是**笔记载入数**(`zk graph --help`:`Limit the number of notes found`),
1215
1211
  * 不是边数 —— 实测 1 个来源 + 6 个目标、`--limit 3` 只回 2 条边。边集不完整的后果是**误报**,见 `graphEdges`。
1216
1212
  */
1217
1213
  export const MAX_GRAPH_NOTES = 10_000;
1218
1214
  /**
1219
- * 全部双链边(一次 `zk graph`)。路径是**笔记本相对**的,按路径比对,不缓存 targetId(Z11 之后 id 会变)。
1215
+ * 全部双链边(一次 `zk graph`)。路径是**笔记本相对**的,按路径比对,不缓存 targetId(id 会变)。
1220
1216
  *
1221
1217
  * `truncated` 必须往上报:`--limit` 到顶时 zk 不报错,少掉的那条边如果正好是回链,
1222
1218
  * S→X 就会被算成单向 —— 这是整个巡检里唯一能产生**误报**的截断(笔记扫描到顶只会漏报)。
@@ -1264,7 +1260,7 @@ export async function graphEdges(cfg, signal, opts = {}) {
1264
1260
  /**
1265
1261
  * 全图预算的默认值(篇数):真正生效的是配置 `graphBudgetNotes`(默认取它)。
1266
1262
  *
1267
- * 实测(§0.5.1):1k / 0 链 0.45 s,10k / 1 链 26–31 s / 17 MB;成本随链接数线性涨
1263
+ * 实测:1k / 0 链 0.45 s,10k / 1 链 26–31 s / 17 MB;成本随链接数线性涨
1268
1264
  * (6.6 s + 26 ms × 链接数),真实库 2–5 链/篇时 10k 会超过 60 s 超时。
1269
1265
  * 超过这个数就不要再调 `graphEdges`:改按篇反查(`backlinksOf` / `outlinksOf`),
1270
1266
  * 读不到就显式报 partial,别拿「返回了结果」冒充完整。
@@ -1273,7 +1269,7 @@ export const GRAPH_BUDGET_NOTES = 2_000;
1273
1269
  /** 按篇反查的默认上限:够显示用;改写链接的调用方自己传更大的限制 */
1274
1270
  export const MAX_LINK_NOTES = 200;
1275
1271
  /**
1276
- * 按篇反查双链:一次 `zk list --link-to` / `--linked-by`,不建全图(plan §0.5.1 结论 3)。
1272
+ * 按篇反查双链:一次 `zk list --link-to` / `--linked-by`,不建全图。
1277
1273
  *
1278
1274
  * ⚠️ 只认**绝对路径**。zk 0.15.7 实测:给相对路径、标题或不存在的路径时,过滤条件会被
1279
1275
  * 当成没写,返回**全库** —— 宁可先挡掉,也不要把「全库」当入链。
@@ -1330,7 +1326,7 @@ function seedAt(cfg, rel, opts = {}) {
1330
1326
  if (abs !== root && !abs.startsWith(root + path.sep))
1331
1327
  return null;
1332
1328
  // 种子也是「进入网络的入口」:meta / raw 不是可导航的笔记,归档要先显式允许。
1333
- // 与邻居侧的 `excludedNames` 同口径 —— 不能只有邻居过滤、种子随便进(plan §14.5)。
1329
+ // 与邻居侧的 `excludedNames` 同口径 —— 不能只有邻居过滤、种子随便进。
1334
1330
  const norm = rel.replace(/\\/g, '/').replace(/^\.\//, '');
1335
1331
  if (isMetaPath(norm))
1336
1332
  return null;
@@ -1356,7 +1352,7 @@ function seedAt(cfg, rel, opts = {}) {
1356
1352
  * 种子解析:路径 / `[[路径]]` 只看磁盘(0 个子进程);标题 / `[[id]]` 走一次 `zk list -M exact`(1 个子进程)。
1357
1353
  *
1358
1354
  * 为什么不用「全库扫描 + resolveWikiTarget」:10k 上那是一整趟 `zk list`(约 2.6 s / 2 MB),
1359
- * 会把单种子 1 跳从 2 个进程抬到 3 个,与 R8 的成本口径(§11.3)不符。
1355
+ * 会把单种子 1 跳从 2 个进程抬到 3 个,与 R8 的成本口径不符。
1360
1356
  * `-M exact` 实测能命中 frontmatter 的 id 与标题,但它是「逐词精确」而不是「整串相等」
1361
1357
  * (`记忆预算` 会同时命中 `记忆预算的另一篇`),所以拿到候选后还要在 JS 里比对一次
1362
1358
  * id / 标题 / 文件名,对不上就当没找到 —— 不拿第一个命中冒充种子。
@@ -1395,11 +1391,11 @@ async function resolveWalkSeed(cfg, raw, opts = {}, signal) {
1395
1391
  * 标题 / id 种子再加一次 `-M exact` 解析(共 3 个)。`limit` 硬钳 `MAX_LINK_NOTES` = 200,
1396
1392
  * 不用 `MAX_SCAN` —— 后者配合 `--format json` 会吐 17 MB,等于把全图成本放回来。
1397
1393
  * 默认排除 archive / raw / meta(与 `excludedNames` 同口径):邻居与**种子**两侧都过滤,
1398
- * 不能只过滤一侧(plan §14.5)。
1394
+ * 不能只过滤一侧。
1399
1395
  *
1400
1396
  * 每条邻居多带 `section` / `linkLine`(那条边所在的小节与那一行):
1401
1397
  * 入链用邻居 JSON 里已经在传输的 `rawContent`,出链读一次种子文件 —— 两边都是 **0 个额外子进程**。
1402
- * 没有这两个字段,`lead` 对同一篇种子的所有出链是同一段文字,等于只给了 8 个标题(plan §14.1)。
1398
+ * 没有这两个字段,`lead` 对同一篇种子的所有出链是同一段文字,等于只给了 8 个标题。
1403
1399
  */
1404
1400
  export async function walkFrom(cfg, opts, signal) {
1405
1401
  const direction = opts.direction ?? 'both';
@@ -1487,7 +1483,7 @@ export function sanitizeListArgs(argv) {
1487
1483
  * `zk list` 的透传入口(人终端用)。排除项与 format 在这里注入,不交给调用方。
1488
1484
  *
1489
1485
  * 0 命中且给了 `-m` 时退回正则(`-M re`):FTS5 不切中文,不兜底的话
1490
- * `query -m 中文短语` 会静默返回空(Z12,和 searchNotes 同一个坑)。
1486
+ * `query -m 中文短语` 会静默返回空(和 searchNotes 同一个坑)。
1491
1487
  * 用户自己写了 `-M` 就尊重用户的选择,不覆盖。
1492
1488
  */
1493
1489
  export async function queryNotes(cfg, argv, signal) {
@@ -1535,7 +1531,7 @@ function assertWritablePath(cfg, abs) {
1535
1531
  }
1536
1532
  }
1537
1533
  /**
1538
- * archive/ 只放 `supersede` 搬进去的旧结论(计划 §2 D6):新建写进去不会报错,
1534
+ * archive/ 只放 `supersede` 搬进去的旧结论:新建写进去不会报错,
1539
1535
  * 但 archive 在 excludedNames 里 —— 笔记会从检索、统计、反链里全部消失。
1540
1536
  * 只有 supersede 能往 archive 里搬:`zk_rename` 改名进 archive 是另一条既有守卫
1541
1537
  * (见 renameNote),这里只拦「新建」。
@@ -1647,7 +1643,7 @@ function normalizeNoteName(raw) {
1647
1643
  return name;
1648
1644
  }
1649
1645
  /**
1650
- * 稳定 ID(§9.2):10 位十六进制短随机串(40 bit,10⁴ 篇库的碰撞概率可忽略)。
1646
+ * 稳定 ID:10 位十六进制短随机串(40 bit,10⁴ 篇库的碰撞概率可忽略)。
1651
1647
  * 纯小写 hex,不会与路径 / `.md` 后缀 / 中文标题撞形,`[[id]]` 才认得出来。
1652
1648
  */
1653
1649
  export function newNoteId() {
@@ -1656,7 +1652,7 @@ export function newNoteId() {
1656
1652
  /**
1657
1653
  * 用 zk new 建一篇(正文走 stdin → 模板里的 {{content}})。
1658
1654
  *
1659
- * 撞名(Z8):`zk new` 遇到同名文件时 exit 0、**内容不写**、只回显路径 —— 不查就会静默丢内容。
1655
+ * 撞名:`zk new` 遇到同名文件时 exit 0、**内容不写**、只回显路径 —— 不查就会静默丢内容。
1660
1656
  * 所以在建之前拍一张目录快照,建完发现文件名本来就有,直接报错(先写入的内容一个字没动,可以放心重试)。
1661
1657
  */
1662
1658
  export async function createNote(cfg, input, signal, scan = (c, s) => allNotes(c, { includeArchived: true }, s)) {
@@ -1723,6 +1719,10 @@ export async function createNote(cfg, input, signal, scan = (c, s) => allNotes(c
1723
1719
  if (clash) {
1724
1720
  throw new ZkError(`同名笔记已存在:${dir === '.' ? '' : dir + '/'}${clash}`, '换一个 name,或直接用 read / edit 改那一篇');
1725
1721
  }
1722
+ // 标签先进正文(模板的 `{{content}}` 位置是对的),建完再决定要不要搬进 frontmatter:
1723
+ // 只有这样才能同时照顾「模板有 tags 格」(layered)与「只有正文 hashtag 可索引」(flat)。
1724
+ const inputTags = [...new Set((input.tags ?? []).map((t) => String(t).trim().replace(/^#+/, '')).filter(Boolean))];
1725
+ const injected = inputTags.length ? withTagsDetailed(input.content ?? '', inputTags) : { content: input.content ?? '', appended: null };
1726
1726
  const args = ['new', dirAbs, '-t', title, '-i', '-p'];
1727
1727
  if (input.group)
1728
1728
  args.push('-g', input.group);
@@ -1731,7 +1731,7 @@ export async function createNote(cfg, input, signal, scan = (c, s) => allNotes(c
1731
1731
  args.push('--extra', `type=${input.type}`);
1732
1732
  if (input.authority)
1733
1733
  args.push('--extra', `authority=${input.authority}`);
1734
- const stdout = await zk(cfg, args, { signal, input: input.content ?? '' });
1734
+ const stdout = await zk(cfg, args, { signal, input: injected.content });
1735
1735
  const last = stdout.trim().split('\n').filter(Boolean).pop() ?? '';
1736
1736
  if (!last)
1737
1737
  throw new ZkError('zk new 没有返回笔记路径');
@@ -1793,13 +1793,17 @@ export async function createNote(cfg, input, signal, scan = (c, s) => allNotes(c
1793
1793
  summaryWarning = `summary 没写进去:${err instanceof Error ? err.message : String(err)}(文件已建好,可以直接编辑那一节)`;
1794
1794
  }
1795
1795
  }
1796
- // 稳定 ID(§9.2):只给 zk_new 新建的笔记写 id,老笔记 / 日记不回填。
1796
+ // 稳定 ID:只给 zk_new 新建的笔记写 id,老笔记 / 日记不回填。
1797
1797
  // 建完才写:zk new -i 索引的是模板产物,改了文件就得标脏,让下一次读补索引(R6)。
1798
- // 收尾失败一律吞掉(同 markIndexDirty):笔记已经建好,不能让一次 id 写入看起来像整次创建失败。
1798
+ // 标签落点也在这一趟里定:模板有 `tags` 格就并进那一格(并撤掉刚追加的正文行),否则留在正文。
1799
+ // 收尾失败一律吞掉(同 markIndexDirty):笔记已经建好,不能让一次收尾写入看起来像整次创建失败。
1799
1800
  try {
1800
1801
  const text = fs.readFileSync(finalAbs, 'utf8');
1801
- if (!parseFrontmatter(text).fields.id) {
1802
- fs.writeFileSync(finalAbs, setFrontmatter(text, { id: newNoteId() }), 'utf8');
1802
+ let next = placeTags(text, inputTags, injected.appended);
1803
+ if (!parseFrontmatter(next).fields.id)
1804
+ next = setFrontmatter(next, { id: newNoteId() });
1805
+ if (next !== text) {
1806
+ fs.writeFileSync(finalAbs, next, 'utf8');
1803
1807
  markIndexDirty(cfg);
1804
1808
  }
1805
1809
  }
@@ -1811,12 +1815,26 @@ export async function createNote(cfg, input, signal, scan = (c, s) => allNotes(c
1811
1815
  emptyTemplateSections = emptyTemplateSlots(fs.readFileSync(finalAbs, 'utf8')).map((slot) => slot.heading);
1812
1816
  }
1813
1817
  catch { /* 收尾失败:文件已落盘,不回滚 */ }
1818
+ // 近义标签:只用建之前那份快照(建完再扫一遍等于多起一个进程),归档里的旧词汇不算
1819
+ let tagHints = [];
1820
+ if (inputTags.length && snapshot) {
1821
+ const counts = new Map();
1822
+ for (const note of snapshot) {
1823
+ if (inArchive(cfg, note.path))
1824
+ continue;
1825
+ for (const tag of note.tags)
1826
+ counts.set(tag, (counts.get(tag) ?? 0) + 1);
1827
+ }
1828
+ const inventory = [...counts].map(([tag, count]) => ({ tag, count }));
1829
+ tagHints = inputTags.flatMap((input) => similarTags(input, inventory, 2).map((hit) => ({ ...hit, input })));
1830
+ }
1814
1831
  return {
1815
1832
  path: relPathOf(cfg, finalAbs),
1816
1833
  absPath: finalAbs,
1817
1834
  title,
1818
1835
  archived,
1819
1836
  similar,
1837
+ tagHints,
1820
1838
  summaryApplied,
1821
1839
  summaryWarning,
1822
1840
  emptyTemplateSections,
@@ -2049,7 +2067,7 @@ export function appendDaily(cfg, p, entry, now = new Date()) {
2049
2067
  return appendToNote(cfg, p, entry, { heading: `${hh}:${mm}`, section: 'Events' });
2050
2068
  }
2051
2069
  const NOTE_EXT = /\.(md|markdown|org|txt)$/i;
2052
- /** 相对笔记本、去掉扩展名的路径 —— 也就是 zk 双链里写的那一段(Z11) */
2070
+ /** 相对笔记本、去掉扩展名的路径 —— 也就是 zk 双链里写的那一段 */
2053
2071
  export function linkStemOf(cfg, abs) {
2054
2072
  return relPathOf(cfg, abs).replace(NOTE_EXT, '');
2055
2073
  }
@@ -2119,7 +2137,7 @@ export async function notebookStats(cfg, signal) {
2119
2137
  };
2120
2138
  }
2121
2139
  /**
2122
- * 目录 / 标签分布(P2-11):静态 INDEX.md 会过期,实时分布不需要第二份真相。
2140
+ * 目录 / 标签分布:静态 INDEX.md 会过期,实时分布不需要第二份真相。
2123
2141
  * 数据来自已经载入的 live,不新增 zk 进程。
2124
2142
  */
2125
2143
  function distributionOf(live) {
@@ -2200,11 +2218,11 @@ async function inboundSources(cfg, rel, signal, opts = {}) {
2200
2218
  /**
2201
2219
  * 废弃一篇笔记:标 status → 重写入链 → 搬进 archive/(保留原相对路径)。
2202
2220
  *
2203
- * 为什么必须重写入链(Z11):双链是路径式的,文件一 move 全部入链即断。
2221
+ * 为什么必须重写入链:双链是路径式的,文件一 move 全部入链即断。
2204
2222
  * 顺序:先改入链(指向将来的归档路径)→ 再改自己的 frontmatter → 最后 rename;
2205
2223
  * 正常路径下可重放:第二次调用看到 status 已是 superseded 就直接返回。
2206
2224
  * 例外:frontmatter 已写、rename 失败时,重试会直接返回,需要人工把文件搬进 archive/。
2207
- * 索引不用手动重建(Z11:zk 下次运行时自己追平),但调用方不要在同一次里依赖旧 targetId。
2225
+ * 索引不用手动重建(zk 下次运行时自己追平),但调用方不要在同一次里依赖旧 targetId。
2208
2226
  */
2209
2227
  export async function supersedeNote(cfg, opts, signal) {
2210
2228
  const dryRun = opts.dryRun !== false;
@@ -2583,21 +2601,30 @@ function hasHashtag(body, tag) {
2583
2601
  const escaped = tag.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
2584
2602
  return new RegExp(`(^|[^\\p{L}\\p{N}_-])#${escaped}(?![\\p{L}\\p{N}_-])`, 'u').test(body);
2585
2603
  }
2586
- export function withTags(content, tags) {
2604
+ /**
2605
+ * 正文标签:返回追加后的正文与**实际追加的那一行**。
2606
+ *
2607
+ * 为什么要返回那一行:建完笔记后如果模板有 frontmatter `tags` 格,标签要搬进那一格,
2608
+ * 刚追加的正文行必须精确撤掉(只撤我们自己写的那行,用户正文里的标签行一个字不动)。
2609
+ */
2610
+ export function withTagsDetailed(content, tags) {
2587
2611
  const body = String(content ?? '').replace(/\s+$/, '');
2588
2612
  if (!tags.length)
2589
- return body;
2613
+ return { content: body, appended: null };
2590
2614
  // 正文里已经写过的标签跳过:以前正文写了 #tag、入参又给 tags,末尾会多出一行一模一样的
2591
2615
  const missing = tags.filter((tag) => !hasHashtag(body, tag));
2592
2616
  if (!missing.length)
2593
- return body;
2617
+ return { content: body, appended: null };
2594
2618
  const line = missing.map((t) => `#${t}`).join(' ');
2595
- return body ? `${body}\n\n${line}` : line;
2619
+ return { content: body ? `${body}\n\n${line}` : line, appended: line };
2620
+ }
2621
+ export function withTags(content, tags) {
2622
+ return withTagsDetailed(content, tags).content;
2596
2623
  }
2597
2624
  /**
2598
- * 中文笔记没打标签的提示(P2-9):写路径是唯一便宜的修复点。
2625
+ * 中文笔记没打标签的提示:写路径是唯一便宜的修复点。
2599
2626
  *
2600
- * 为什么是「没标签」而不是「搜不到」:P2-7 之后中文查询已经会并上子串匹配,正文照样找得回来;
2627
+ * 为什么是「没标签」而不是「搜不到」:中文查询已经会并上子串匹配,正文照样找得回来;
2601
2628
  * 真正的代价在下一道门 —— `zk_dream` 的机械门按「无标签」把笔记拒出晋升候选,
2602
2629
  * `zk_stats` 的 byTag 分布里也没有它。标签仍是唯一能确定性筛选的维度。
2603
2630
  *