dsh-zdiary-kit 0.7.6 → 0.9.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.
@@ -5,8 +5,11 @@
5
5
  *
6
6
  * 硬约定(与 docs/plan-memory-layers.md §3 D6 一致):
7
7
  * · 预算按**总载荷**算,不是只卡 MEMORY.md;
8
- * · 截断顺序纯机械:先丢 MEMORY 的尾部 `##` 整段,再丢 USER 的尾部整段,
9
- * 最后各自只留首段;AGENTS.md 是硬规则,永不截断(单独超预算时只告警);
8
+ * · 切分按三级降级:`##` 小节 → 顶层列表项 → 空行段落。只有 `##` 一级时,
9
+ * `# 记忆` + 要点列表(最常见的写法)一个小节都切不出来,预算会整个失效 —— 见 P0-1;
10
+ * · 截断顺序纯机械:先丢 MEMORY 里**日期最旧**的一条(都没有日期才退回尾部整条),
11
+ * 再丢 USER 的尾部整段,最后各自只留首段;AGENTS.md 是硬规则,永不截断(单独超预算时只告警);
12
+ * · 退役条目(`- [superseded …]`)磁盘保留、注入省略 —— 它们按约定退役,不该继续占预算;
10
13
  * · 丢掉的段落留一份**目录**(段落标题,计入预算),agent 用 zk_read 取回正文 ——
11
14
  * 选哪段是 agent 按当前任务判断,插件只搬运目录,不猜相关性;
12
15
  * · 中文按「1 词 / 2 字」计 —— 空白切分在中文上严重低估,预算会变成装饰。
@@ -20,6 +23,7 @@ import fs from 'node:fs';
20
23
  import path from 'node:path';
21
24
  import { DREAM_INTERVAL_DAYS, daysSinceDream, lastDreamDate } from './dream.js';
22
25
  import { fileStamp } from './file-stamp.js';
26
+ import { entryDate, splitMemoryEntries, stripRetiredEntries } from './memory-format.js';
23
27
  import { MEMORY_META_FILES } from './meta.js';
24
28
  /** vault 根目录下、按优先级排列的三份 meta 文件(定义在 lib/meta.ts,这里只挂个本地名) */
25
29
  export const META_FILES = MEMORY_META_FILES;
@@ -48,33 +52,135 @@ export function countWords(text) {
48
52
  }
49
53
  /** 目录最多列几段:再多就只给「还有 N 段」,免得目录自己把预算吃掉 */
50
54
  const TOC_MAX = 5;
55
+ /** 目录里单条标题最多多长(条目可能是一整句结论) */
56
+ const TOC_TITLE_MAX = 40;
57
+ /** 到预算的这个比例就回显用量:等到截断才说,已经是最坏的时刻 */
58
+ const MEMORY_NEAR_RATIO = 0.8;
59
+ /** 围栏代码块:里面的 `- ` 与空行都不是条目 / 段落边界 */
60
+ const FENCED = /^\s*(?:```|~~~)/;
61
+ /** 二级小节(原有切分口径) */
62
+ const SECTION = /^##\s+/;
63
+ /** 顶层列表项;缩进的子项算续行,不另起一条 */
64
+ const LIST_ITEM = /^(?:[-*+]|\d+[.)])\s+/;
65
+ function finishSplit(head, sections, mode) {
66
+ return {
67
+ head: head.join('\n').trim(),
68
+ sections: sections.map((s) => s.join('\n').trim()).filter(Boolean),
69
+ mode,
70
+ };
71
+ }
72
+ /**
73
+ * 三级降级切分(P0-1):`##` 小节 → 顶层列表项 → 空行段落。
74
+ * 只按 `##` 切时,「`# 记忆` + 要点列表」这种形状切不出任何小节,丢弃循环一次都不进,
75
+ * 预算于是完全不生效(真机 880 / 449 / 895 词都是这个形状)。降级只影响超预算的库:
76
+ * 预算内不调用这个函数的结果做任何改写。
77
+ *
78
+ * 三级都跳过围栏里的行 —— 代码块里的 `- ` 或空行不该被当成可丢弃的条目。
79
+ */
51
80
  function splitSections(body) {
81
+ const lines = String(body ?? '').split('\n');
82
+ let fenced = false;
83
+ // 1a) `##` 小节
52
84
  const head = [];
53
85
  const sections = [];
54
- for (const line of body.split('\n')) {
55
- if (/^##\s+/.test(line))
86
+ for (const line of lines) {
87
+ if (FENCED.test(line))
88
+ fenced = !fenced;
89
+ if (!fenced && SECTION.test(line))
56
90
  sections.push([line]);
57
91
  else if (sections.length > 0)
58
92
  sections[sections.length - 1].push(line);
59
93
  else
60
94
  head.push(line);
61
95
  }
62
- return {
63
- head: head.join('\n').trim(),
64
- sections: sections.map((s) => s.join('\n').trim()).filter(Boolean),
65
- };
96
+ if (sections.length > 0)
97
+ return finishSplit(head, sections, 'sections');
98
+ // 1b) 顶层列表项:`# 标题` + 若干 `- 结论` 是 MEMORY.md 最常见的形状。
99
+ // 至少两条才走这一级:只有一条时它更像散文里的一个符号,交给段落切分更不容易整篇卡死。
100
+ const itemHead = [];
101
+ const items = [];
102
+ let current = null;
103
+ fenced = false;
104
+ for (const line of lines) {
105
+ if (FENCED.test(line))
106
+ fenced = !fenced;
107
+ if (!fenced && LIST_ITEM.test(line)) {
108
+ if (current)
109
+ items.push(current);
110
+ current = [line];
111
+ }
112
+ else if (current) {
113
+ current.push(line);
114
+ }
115
+ else {
116
+ itemHead.push(line);
117
+ }
118
+ }
119
+ if (current)
120
+ items.push(current);
121
+ if (items.length >= 2)
122
+ return finishSplit(itemHead, items, 'items');
123
+ // 1c) 空行段落:整篇散文也能按段丢。首段作为 head(通常是标题 / 开场),永远保留。
124
+ const paragraphs = [];
125
+ let para = null;
126
+ fenced = false;
127
+ for (const line of lines) {
128
+ if (FENCED.test(line))
129
+ fenced = !fenced;
130
+ if (!fenced && !line.trim()) {
131
+ if (para)
132
+ paragraphs.push(para);
133
+ para = null;
134
+ continue;
135
+ }
136
+ if (!para)
137
+ para = [line];
138
+ else
139
+ para.push(line);
140
+ }
141
+ if (para)
142
+ paragraphs.push(para);
143
+ const [first, ...rest] = paragraphs;
144
+ return finishSplit(first ?? [], rest, 'paragraphs');
66
145
  }
67
146
  function joinSections(split) {
68
147
  return [split.head, ...split.sections].filter(Boolean).join('\n\n');
69
148
  }
70
- /** 只留首段(preamble + 第一个 `##` 段) */
149
+ /** 只留首段(preamble + 第一个切出来的段) */
71
150
  function firstSection(body) {
72
151
  const split = splitSections(body);
73
- return joinSections({ head: split.head, sections: split.sections.slice(0, 1) });
152
+ return joinSections({ head: split.head, sections: split.sections.slice(0, 1), mode: split.mode });
153
+ }
154
+ /**
155
+ * 下一个该丢的条目:能解析出日期时选**最旧**的一条(同日期按位置靠后的先丢);
156
+ * 一条日期都解析不出来返回 null —— 调用方退回尾部丢,老库行为不变(D2.6)。
157
+ *
158
+ * 为什么按日期而不是位置:条目约定是「新结论写顶部」,但没人能保证每次都守;
159
+ * 按位置丢会把最新结论先删掉,而那正好是最该留的。
160
+ */
161
+ function oldestIndex(split) {
162
+ let best = null;
163
+ for (const [index, section] of split.sections.entries()) {
164
+ const date = entryDate(section);
165
+ if (!date)
166
+ continue;
167
+ if (!best || date < best.date || (date === best.date && index > best.index)) {
168
+ best = { index, date };
169
+ }
170
+ }
171
+ return best?.index ?? null;
74
172
  }
75
- function sectionTitle(section) {
173
+ function sectionTitle(section, mode) {
76
174
  const first = section.split('\n', 1)[0] ?? '';
77
- return first.replace(/^##\s+/, '').trim() || '(无标题)';
175
+ const raw = mode === 'sections'
176
+ ? first.replace(/^##\s+/, '')
177
+ : mode === 'items'
178
+ ? first.replace(LIST_ITEM, '')
179
+ : first;
180
+ const one = raw.replace(/\s+/g, ' ').trim();
181
+ if (!one)
182
+ return '(无标题)';
183
+ return one.length > TOC_TITLE_MAX ? one.slice(0, TOC_TITLE_MAX) + '…' : one;
78
184
  }
79
185
  /**
80
186
  * 被截掉段落的目录:代替「按位置丢尾段」的不可见性。
@@ -198,16 +304,26 @@ export function buildMemoryPayload(cfg) {
198
304
  function computePayload(cfg) {
199
305
  const budget = cfg.memoryBudgetWords;
200
306
  const files = readMeta(cfg);
307
+ // 磁盘原文:files[].originalWords 与记忆页的对齐点,退役条目也算在里面
308
+ const diskWords = new Map(files.map((f) => [f.name, countWords(f.body)]));
201
309
  const original = new Map(files.map((f) => [f.name, f.body]));
202
- const pristineWords = new Map(files.map((f) => [f.name, countWords(f.body)]));
203
- // 截断会改写这份计数;pristineWords 保留原值,给「原多少词」和 truncatedWords 用
204
- const words = new Map(pristineWords);
310
+ // 退役条目:磁盘保留、注入省略(D3)。先去掉,后面的截断只面对活条目。
311
+ const omitted = stripRetiredEntries(original.get('MEMORY.md') ?? '');
312
+ if (omitted.count > 0)
313
+ original.set('MEMORY.md', omitted.body);
314
+ // 去掉退役行之后的内容词数:用来算「截断了多少」,不把省略算成截断
315
+ const contentWords = new Map(files.map((f) => [f.name, countWords(original.get(f.name) ?? '')]));
316
+ // 截断会改写这份计数;contentWords 保留原值,给 truncatedWords 与 files 用
317
+ const words = new Map(contentWords);
205
318
  const total = () => [...words.values()].reduce((a, b) => a + b, 0);
206
- // ── 机械截断:MEMORY 尾段 → USER 尾段 → 各留首段 ──────────────────
319
+ // 截断前的 MEMORY 正文:报告「有多少条没日期」要在丢之前数
320
+ const memorySource = original.get('MEMORY.md') ?? '';
321
+ // ── 机械截断:MEMORY 最旧条目 → USER 尾段 → 各留首段 ──────────────
207
322
  // 丢掉的段落留一份目录(段落标题),让 agent 能按当前任务用 zk_read 取回。
208
323
  // 目录自己也要占预算,所以每丢一段都把它算进去;目录有上限,循环一定收敛。
209
324
  const dropped = [];
210
325
  const tocCap = tocCapOf(budget);
326
+ let fellBack = false;
211
327
  for (const name of ['MEMORY.md', 'USER.md']) {
212
328
  if (total() + countWords(tocText(dropped, tocCap)) <= budget)
213
329
  break;
@@ -215,12 +331,23 @@ function computePayload(cfg) {
215
331
  const mine = [];
216
332
  const over = () => total() + countWords(tocText([...dropped, ...mine], tocCap)) > budget;
217
333
  while (over() && split.sections.length > 1) {
218
- const section = split.sections.pop();
219
- mine.unshift({ name, title: sectionTitle(section) });
334
+ // MEMORY 按「最旧日期」丢;解析不出日期(或这是 USER)就退回尾部,行为与 0.8.3 一致
335
+ let index = split.sections.length - 1;
336
+ if (name === 'MEMORY.md') {
337
+ const oldest = oldestIndex(split);
338
+ if (oldest === null)
339
+ fellBack = true;
340
+ else
341
+ index = oldest;
342
+ }
343
+ const section = split.sections.splice(index, 1)[0];
344
+ mine.push({ name, title: sectionTitle(section, split.mode), order: index });
220
345
  const body = joinSections(split);
221
346
  original.set(name, body);
222
347
  words.set(name, countWords(body));
223
348
  }
349
+ // 按原文件位置重建目录,而不是按丢弃顺序 —— 目录要能对上文件
350
+ mine.sort((a, b) => (a.order ?? 0) - (b.order ?? 0));
224
351
  dropped.push(...mine);
225
352
  }
226
353
  if (total() + countWords(tocText(dropped, tocCap)) > budget) {
@@ -236,15 +363,26 @@ function computePayload(cfg) {
236
363
  const present = files.filter((f) => (original.get(f.name) ?? '').length > 0);
237
364
  const bodies = present.map((f) => `## ${f.name}\n\n${escapeFrame(original.get(f.name) ?? '')}`);
238
365
  const keptWords = total();
239
- const finalWords = keptWords + countWords(toc);
240
- const originalWords = files.reduce((sum, f) => sum + (pristineWords.get(f.name) ?? 0), 0);
366
+ // 退役条目不算截断:它按约定退役,不是被预算挤掉的
367
+ const omittedNote = omitted.count > 0 ? `已省略 ${omitted.count} 条退役条目(见 MEMORY.md)` : '';
368
+ // 这条提示本身也要吃饭(D3.2):不把它算进 words,报出来的用量就会少一截
369
+ let finalWords = keptWords + countWords(toc) + countWords(omittedNote);
370
+ const contentSum = files.reduce((sum, f) => sum + (contentWords.get(f.name) ?? 0), 0);
241
371
  // 报「正文被截掉多少」,不是净减少:目录也会占词,混在一起会让人以为没丢多少
242
- const truncatedWords = Math.max(0, originalWords - keptWords);
372
+ const truncatedWords = Math.max(0, contentSum - keptWords);
243
373
  let text = '';
244
374
  if (bodies.length > 0) {
245
375
  const notes = [];
246
376
  if (truncatedWords > 0)
247
377
  notes.push(`已截断 ${truncatedWords} 词`);
378
+ if (omittedNote)
379
+ notes.push(omittedNote);
380
+ // 一条日期都没有只能按位置丢:说出来,别让人以为是按日期挑的(D2.5)
381
+ if (fellBack && truncatedWords > 0) {
382
+ const undated = splitMemoryEntries(memorySource).filter((entry) => !entryDate(entry)).length;
383
+ if (undated > 0)
384
+ notes.push(`MEMORY 有 ${undated} 条没日期,只能按位置丢`);
385
+ }
248
386
  // 目录放不下时至少留一句指路;否则被丢掉的段落对模型完全不可见
249
387
  if (!toc && dropped.length > 0) {
250
388
  const names = [...new Set(dropped.map((d) => d.name))];
@@ -257,7 +395,30 @@ function computePayload(cfg) {
257
395
  notes.push(`AGENTS.md 占 ${agentsWords}/${budget} 词且不参与截断,留给 USER / MEMORY 的只有 ${Math.max(0, budget - agentsWords)} 词`);
258
396
  }
259
397
  if (finalWords > budget) {
260
- notes.push(`预算不足:内容 ${finalWords} 词,超出 ${budget} 词;AGENTS.md 为硬规则,不截断`);
398
+ // 超预算时点名「谁已经没法再丢」:只说「AGENTS 不截断」会把 MEMORY 的条目形状问题藏在后面
399
+ const stuck = [];
400
+ if (agentsWords > 0)
401
+ stuck.push(`AGENTS.md 为硬规则不截断(${agentsWords} 词)`);
402
+ for (const name of ['MEMORY.md', 'USER.md']) {
403
+ const left = words.get(name) ?? 0;
404
+ if (left <= 0)
405
+ continue;
406
+ const what = splitSections(original.get(name) ?? '').mode;
407
+ stuck.push(`${name} ${left} 词(已无更多可丢的${what === 'items' ? '条目' : what === 'paragraphs' ? '段落' : '小节'})`);
408
+ }
409
+ notes.push(`预算不足:内容 ${finalWords} 词,超出 ${budget} 词;${stuck.join('、')}`);
410
+ }
411
+ // 接近上限就回显用量:增长是连续的,等到第一次截断才说,正好是最坏的时刻。
412
+ // 这一行算进 finalWords(否则「280/300」是假的);放不下就整条不加 —— 宁可不说,
413
+ // 也不让提醒本身把预算吃满。与「已截断 / 预算不足」互斥。
414
+ if (notes.length === 0 && budget > 0 && finalWords >= budget * MEMORY_NEAR_RATIO) {
415
+ // 两遍:先量这一行本身占多少词,再把它算进 finalWords 后重报数字 ——
416
+ // 否则会说着「280/300」却实际注入 285 词(提示自己也要吃饭)
417
+ const cost = countWords(`记忆已用 ${finalWords}/${budget} 词(100%)`);
418
+ if (finalWords + cost <= budget) {
419
+ finalWords += cost;
420
+ notes.push(`记忆已用 ${finalWords}/${budget} 词(${Math.round((finalWords / budget) * 100)}%)`);
421
+ }
261
422
  }
262
423
  const notice = notes.length > 0 ? `\n\n(注入预算 ${budget} 词:${notes.join(';')})` : '';
263
424
  // 只有用了这套约定的库(根目录有 AGENTS.md)才提醒周节奏
@@ -275,14 +436,30 @@ function computePayload(cfg) {
275
436
  text,
276
437
  words: finalWords,
277
438
  budget,
439
+ ratio: budget > 0 ? Math.round((finalWords / budget) * 100) / 100 : 0,
278
440
  truncatedWords,
279
441
  tocWords: countWords(toc),
280
442
  files: files.map((f) => ({
281
443
  name: f.name,
282
444
  present: f.body.length > 0,
283
445
  words: words.get(f.name) ?? 0,
284
- // files[].body 始终是原文件内容(截断只改 original 副本)
285
- originalWords: pristineWords.get(f.name) ?? 0,
446
+ // files[].body 始终是原文件内容(截断只改 original 副本);退役条目也算在原文里
447
+ originalWords: diskWords.get(f.name) ?? 0,
286
448
  })),
287
449
  };
288
450
  }
451
+ /**
452
+ * 记忆用量(D4)。只是 `buildMemoryPayload` 的投影 —— 不重读、不重算,
453
+ * 否则就是第三个计数口径,doctor / 设置页 / dream 三处迟早对不上。
454
+ */
455
+ export function memoryUsage(cfg) {
456
+ const payload = buildMemoryPayload(cfg);
457
+ const totalWords = countWords(payload.text);
458
+ return {
459
+ words: payload.words,
460
+ totalWords,
461
+ budget: payload.budget,
462
+ headroom: payload.budget - totalWords,
463
+ files: payload.files,
464
+ };
465
+ }
@@ -0,0 +1,188 @@
1
+ /**
2
+ * `.zk/config.toml` 的 group 只读解析。
3
+ *
4
+ * 为什么自己解析而不是引入 TOML 依赖:
5
+ * · 我们只关心 `[group."name"]` 的 `paths` / `template` 与它前面的注释;
6
+ * · 写回只做「替换 plugin-owned group 的 paths 行 / 组头改名」,用正则逐行改比
7
+ * 整份 TOML 序列化安全 —— 不会把用户的注释、顺序、自定义键重排掉。
8
+ *
9
+ * 约定:**解析不了就返回 null,绝不猜**。调用方把 null 当作「缺失 / 需要修」,
10
+ * 而不是按半份结果去改文件。
11
+ */
12
+ /** `[group."name"]` / `[group.'name']` / `[group.bare]` 的组头(允许行尾注释) */
13
+ const GROUP_HEADER = /^\s*\[group\.(?:"([^"]+)"|'([^']+)'|([A-Za-z0-9_-]+))(?:\.(note|extra))?\]\s*(?:#.*)?$/;
14
+ function arrayOf(raw) {
15
+ const text = raw.trim();
16
+ if (!text.startsWith('[') || !text.endsWith(']'))
17
+ return null;
18
+ const inner = text.slice(1, -1).trim();
19
+ if (!inner)
20
+ return [];
21
+ const items = [];
22
+ let i = 0;
23
+ while (i < inner.length) {
24
+ while (i < inner.length && /[\s,]/.test(inner[i]))
25
+ i++;
26
+ if (i >= inner.length)
27
+ break;
28
+ const quote = inner[i];
29
+ if (quote !== '"' && quote !== "'")
30
+ return null;
31
+ i++;
32
+ const start = i;
33
+ while (i < inner.length && inner[i] !== quote) {
34
+ // 双引号字符串里的转义只支持 \";单引号是 TOML 字面量,没有转义
35
+ if (quote === '"' && inner[i] === '\\')
36
+ i++;
37
+ i++;
38
+ }
39
+ if (i >= inner.length)
40
+ return null;
41
+ items.push(inner.slice(start, i));
42
+ i++;
43
+ while (i < inner.length && inner[i] !== ',') {
44
+ if (!/\s/.test(inner[i]))
45
+ return null;
46
+ i++;
47
+ }
48
+ }
49
+ return items;
50
+ }
51
+ /** 值 → 单行原始值(去掉行尾注释;引号里的 # 不算注释) */
52
+ function valueOf(line) {
53
+ let quote = '';
54
+ for (let i = 0; i < line.length; i++) {
55
+ const ch = line[i];
56
+ if (quote) {
57
+ if (quote === '"' && ch === '\\') {
58
+ i++;
59
+ continue;
60
+ }
61
+ if (ch === quote)
62
+ quote = '';
63
+ continue;
64
+ }
65
+ if (ch === '"' || ch === "'") {
66
+ quote = ch;
67
+ continue;
68
+ }
69
+ if (ch === '#')
70
+ return line.slice(0, i).trim();
71
+ }
72
+ return line.trim();
73
+ }
74
+ /** 解析整份 config.toml,返回 名字 → GroupBlock(同名重复时保留 duplicate 标记) */
75
+ export function parseGroupBlocks(text) {
76
+ const blocks = new Map();
77
+ const comments = [];
78
+ let current = null;
79
+ let section = null;
80
+ for (const line of text.split(/\r?\n/)) {
81
+ const header = GROUP_HEADER.exec(line);
82
+ if (header) {
83
+ const name = header[1] ?? header[2] ?? header[3] ?? '';
84
+ const sub = header[4];
85
+ if (!sub) {
86
+ const existing = blocks.get(name);
87
+ current = existing
88
+ ? { ...existing, duplicate: true, paths: null, pathsState: 'invalid', template: null }
89
+ : { name, paths: null, pathsState: 'absent', template: null, comment: comments.length ? comments.join('\n') : null, header: line, duplicate: false };
90
+ blocks.set(name, current);
91
+ section = 'base';
92
+ }
93
+ else {
94
+ // 子表必须跟在同名 base 后面;找不到就当没看见(TOML 本身也不合法)
95
+ current = blocks.get(name) ?? null;
96
+ section = current ? sub : null;
97
+ }
98
+ comments.length = 0;
99
+ continue;
100
+ }
101
+ if (/^\s*\[/.test(line)) { // 其它 section:结束当前 group,但保留注释缓冲给下一段
102
+ current = null;
103
+ section = null;
104
+ comments.length = 0;
105
+ continue;
106
+ }
107
+ const trimmed = line.trim();
108
+ if (trimmed.startsWith('#')) {
109
+ comments.push(trimmed);
110
+ continue;
111
+ }
112
+ if (!trimmed) {
113
+ comments.length = 0;
114
+ continue;
115
+ }
116
+ if (!current || !section) {
117
+ comments.length = 0;
118
+ continue;
119
+ }
120
+ // 重复 group:TOML 本身不合法,后续键一律不采信(保持 paths/template = null)
121
+ if (current.duplicate) {
122
+ comments.length = 0;
123
+ continue;
124
+ }
125
+ const eq = trimmed.indexOf('=');
126
+ if (eq <= 0) {
127
+ comments.length = 0;
128
+ continue;
129
+ }
130
+ const key = trimmed.slice(0, eq).trim();
131
+ const value = valueOf(trimmed.slice(eq + 1));
132
+ if (section === 'base' && key === 'paths') {
133
+ current.paths = arrayOf(value);
134
+ current.pathsState = current.paths ? 'set' : 'invalid';
135
+ }
136
+ else if (section === 'note' && key === 'template') {
137
+ current.template = unquote(value);
138
+ }
139
+ comments.length = 0;
140
+ }
141
+ return blocks;
142
+ }
143
+ function unquote(value) {
144
+ if (value.length >= 2 && ((value[0] === '"' && value.endsWith('"')) || (value[0] === "'" && value.endsWith("'")))) {
145
+ return value.slice(1, -1);
146
+ }
147
+ return null;
148
+ }
149
+ /** 组头是否是 dsh-zdiary-kit 自己写的(有它才允许 `--fix` 改) */
150
+ export function isPluginOwned(block) {
151
+ return !!block.comment && block.comment.includes('dsh-zdiary-kit');
152
+ }
153
+ /**
154
+ * zk 实际用于归组的路径。没写 `paths` 等价于 `[名字]`(zk 生成的 config 注释原话:
155
+ * "Omitting `paths` is equivalent to providing a single path equal to the name of the group"),
156
+ * 所以缺键不是「没有路径」,而是按同名目录占着 —— 冲突判断必须算上它。
157
+ * 解析失败 / 重复组返回 null(没有可信路径,不猜)。
158
+ */
159
+ export function effectivePaths(block) {
160
+ if (block.duplicate)
161
+ return null;
162
+ if (block.pathsState === 'set')
163
+ return block.paths;
164
+ return block.pathsState === 'absent' ? [block.name] : null;
165
+ }
166
+ /** 路径归一化:`./notes/` 与 `notes` 是同一个目录 */
167
+ export function normGroupPath(rel) {
168
+ const clean = rel.replace(/\\/g, '/').replace(/^\.\/+/, '').replace(/\/+/g, '/').replace(/\/+$/, '');
169
+ return clean === '.' ? '' : clean;
170
+ }
171
+ /**
172
+ * 两条路径是不是同一个目录(`./notes/` 与 `notes` 算同一个)。
173
+ *
174
+ * 只认「完全一样」:父子目录是**合法**的 —— zk 0.15 按最具体的路径归组,
175
+ * `notes` 与 `notes/concepts` 共存时,子目录里的笔记走后者(真机验证过)。
176
+ * 只有两条路径一模一样时,zk 命中哪个 group 就只剩实现细节了(实测:先定义的那个赢)。
177
+ */
178
+ export function sameGroupPath(a, b) {
179
+ return normGroupPath(a) === normGroupPath(b);
180
+ }
181
+ /** 两组 paths 是否一致(顺序无关;null 一律不一致) */
182
+ export function samePaths(actual, expected) {
183
+ if (!actual || actual.length !== expected.length)
184
+ return false;
185
+ const a = actual.map(normGroupPath).sort();
186
+ const b = expected.map(normGroupPath).sort();
187
+ return a.every((p, i) => p === b[i]);
188
+ }