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.
@@ -6,14 +6,15 @@
6
6
  *
7
7
  * 两种结构(Config.structure):
8
8
  * · flat(默认,0.1.0 行为逐字节一致):notes/ + 日记 + 一个 daily group;
9
- * · layered:raw / inbox / notes/{sources,concepts,entities,patterns} / archive + 三套模板(daily / source / entry)+ 五个 group。
9
+ * · layered:raw / notes/{sources,concepts,entities,patterns} / archive + 三套模板(daily / source / entry)+ 五个 group。
10
10
  * 切到 layered **只建目录与模板,不搬已有笔记**。
11
11
  */
12
12
  import fs from 'node:fs';
13
13
  import path from 'node:path';
14
14
  import { ZkError, zk } from './zk.js';
15
- import { AGENTS_TEMPLATE, WORKFLOW_TEMPLATE } from './agents-template.js';
16
- export { AGENTS_TEMPLATE, WORKFLOW_TEMPLATE } from './agents-template.js';
15
+ import { AGENTS_TEMPLATE, AGENTS_TEMPLATE_FLAT, WORKFLOW_TEMPLATE } from './agents-template.js';
16
+ import { effectivePaths, isPluginOwned, normGroupPath, parseGroupBlocks, sameGroupPath, samePaths } from './notebook-config.js';
17
+ export { AGENTS_TEMPLATE, AGENTS_TEMPLATE_FLAT, WORKFLOW_TEMPLATE } from './agents-template.js';
17
18
  export const DAILY_TEMPLATE = `# {{format-date now "%Y-%m-%d"}}
18
19
 
19
20
  {{content}}
@@ -123,7 +124,7 @@ export function newNoteDir(cfg, input = {}) {
123
124
  const given = input.dir ? normDir(input.dir) : '';
124
125
  if (cfg.structure !== 'layered')
125
126
  return given || normDir(cfg.notesDir);
126
- const groups = layeredGroups(cfg).flatMap((group) => group.paths.map(normDir));
127
+ const groups = expectedGroups(cfg).flatMap((group) => group.paths.map(normDir));
127
128
  const hint = `可选目录:${groups.join(' / ')}(group 下的子目录也行);` +
128
129
  `落在 ${cfg.notesDir}/ 根不会套模板,没有 frontmatter,文件名是随机 id`;
129
130
  const dir = given || (input.type ? noteKindDir(cfg.notesDir, input.type) : null);
@@ -153,32 +154,154 @@ function layeredGroups(cfg) {
153
154
  named('pattern', 'entry.md', 'expert'),
154
155
  ];
155
156
  }
157
+ /** 当前结构期望的 group(flat 一个,layered 五个);顺序与目录一致 */
158
+ export function expectedGroups(cfg) {
159
+ return cfg.structure === 'layered' ? layeredGroups(cfg) : [dailyGroup(cfg)];
160
+ }
156
161
  /** 当前结构需要的目录(相对笔记本;flat 只有笔记与日记两个) */
157
162
  export function structureDirs(cfg) {
158
163
  const rels = [cfg.notesDir, cfg.dailyDir];
159
164
  if (cfg.structure === 'layered') {
160
- rels.push('raw', 'inbox', ...Object.values(PLURAL_DIR).map((dir) => `${cfg.notesDir}/${dir}`), cfg.archiveDir);
165
+ rels.push('raw', ...Object.values(PLURAL_DIR).map((dir) => `${cfg.notesDir}/${dir}`), cfg.archiveDir);
161
166
  }
162
167
  return [...new Set(rels)];
163
168
  }
169
+ /** 同一批 group 两两查「同一条路径」:每对只报一次 */
170
+ function overlapsOf(entries) {
171
+ const out = [];
172
+ for (let i = 0; i < entries.length; i++) {
173
+ const a = entries[i];
174
+ if (!a)
175
+ continue;
176
+ for (let j = i + 1; j < entries.length; j++) {
177
+ const b = entries[j];
178
+ if (!b)
179
+ continue;
180
+ const shared = (a.paths ?? []).find((x) => (b.paths ?? []).some((y) => sameGroupPath(x, y)));
181
+ if (shared !== undefined)
182
+ out.push({ a: a.name, b: b.name, path: normGroupPath(shared) });
183
+ }
184
+ }
185
+ return out;
186
+ }
187
+ function groupStatuses(groups, blocks) {
188
+ return groups.map((group) => {
189
+ const block = blocks?.get(group.name) ?? null;
190
+ // 缺 paths 的 group 按同名目录占着(zk 语义):冲突判断必须算上,否则会追加同路径组
191
+ const actualPaths = block ? effectivePaths(block) : null;
192
+ const actualTemplate = block?.template ?? null;
193
+ const conflict = block ? undefined : [...(blocks?.values() ?? [])].find((candidate) => effectivePaths(candidate)?.some((actual) => group.paths.some((expected) => sameGroupPath(actual, expected))))?.name;
194
+ return {
195
+ name: group.name,
196
+ expectedPaths: group.paths,
197
+ actualPaths,
198
+ pathsOk: !!block && !block.duplicate && samePaths(actualPaths, group.paths),
199
+ present: !!block,
200
+ expectedTemplate: group.template,
201
+ actualTemplate,
202
+ templateOk: !!block && !block.duplicate && actualTemplate === group.template,
203
+ duplicate: !!block?.duplicate,
204
+ owned: !!block && isPluginOwned(block),
205
+ ...(conflict ? { conflict } : {}),
206
+ };
207
+ });
208
+ }
209
+ /**
210
+ * 重叠说明(给人看的一行);level = config 是配置本身冲突、file 是 config.toml 里已经撞了。
211
+ * 同一对只报一次:两边都说一遍只会让设置页的告警更长。
212
+ * 父子目录不算冲突(zk 按最具体的路径归组),所以措辞只说「同一条路径」。
213
+ */
214
+ export function groupOverlapNotes(st) {
215
+ const out = [];
216
+ const seen = new Set();
217
+ const key = (o) => [o.a, o.b].sort().join('|');
218
+ for (const o of st.expectedOverlaps) {
219
+ seen.add(key(o));
220
+ out.push({
221
+ level: 'config',
222
+ text: `group "${o.a}" 与 "${o.b}" 都用 ${o.path} —— 改 dailyDir / notesDir,或换结构(groups --fix 不会写)`,
223
+ });
224
+ }
225
+ for (const o of st.actualOverlaps) {
226
+ if (seen.has(key(o)))
227
+ continue;
228
+ out.push({
229
+ level: 'file',
230
+ text: `group "${o.a}" 与 "${o.b}" 的 paths 都是 ${o.path} —— 手动检查 .zk/config.toml`,
231
+ });
232
+ }
233
+ return out;
234
+ }
235
+ function groupWarningsOf(groups, st) {
236
+ const out = [];
237
+ for (const group of groups) {
238
+ if (!group.present) {
239
+ out.push(group.conflict
240
+ ? `缺 group "${group.name}":路径 ${group.expectedPaths.join('、')} 已被 group "${group.conflict}" 占用 —— 跑 zk-kit groups --fix`
241
+ : `缺 group "${group.name}"(期望 ${group.expectedPaths.join('、')})—— 跑 zk-kit groups --fix`);
242
+ }
243
+ else if (group.duplicate) {
244
+ out.push(`group "${group.name}" 重复出现,解析不了 —— 手动检查 .zk/config.toml`);
245
+ }
246
+ else if (!group.pathsOk) {
247
+ out.push(`group "${group.name}" ${pathsDiff(group.expectedPaths, group.actualPaths)}`);
248
+ }
249
+ }
250
+ for (const note of groupOverlapNotes(st))
251
+ out.push(note.text);
252
+ return out;
253
+ }
254
+ /** 期望 / 实际 paths 的差异尾巴;actual 为 null = 解析不了(多行数组 / 未加引号的项),--fix 也不猜 */
255
+ function pathsDiff(expected, actual) {
256
+ return `期望 ${expected.join('、')},实际 ${actual?.join('、') ?? '解析不了'}` +
257
+ (actual === null ? '(可能是多行数组)—— 手动编辑 .zk/config.toml' : ' —— 跑 zk-kit groups --fix');
258
+ }
164
259
  /** 结构一致性检查:只报告,不建目录、不改配置(设置页据此显示告警) */
165
260
  export function structureStatus(cfg) {
166
261
  const dirs = structureDirs(cfg);
167
262
  const missing = dirs.filter((rel) => !fs.existsSync(path.join(cfg.notebook, rel)));
168
263
  const agentsPath = path.join(cfg.notebook, 'AGENTS.md');
169
264
  const required = cfg.structure === 'layered';
265
+ // 只看「会改变新建笔记落点」的目录:分层笔记目录与 raw/inbox。
266
+ // archive 对两种结构都合法,不参与漂移判断。
267
+ const drift = cfg.structure === 'flat'
268
+ ? ['raw', 'inbox', ...Object.values(PLURAL_DIR).map((dir) => `${cfg.notesDir}/${dir}`)]
269
+ : [];
270
+ const extra = [...new Set(drift)]
271
+ .map(normDir)
272
+ .filter((rel) => !dirs.map(normDir).includes(rel))
273
+ .filter((rel) => fs.existsSync(path.join(cfg.notebook, rel)))
274
+ .sort();
275
+ let blocks = null;
276
+ try {
277
+ blocks = parseGroupBlocks(fs.readFileSync(path.join(cfg.notebook, '.zk', 'config.toml'), 'utf8'));
278
+ }
279
+ catch {
280
+ blocks = null;
281
+ }
282
+ const expected = expectedGroups(cfg);
283
+ const groups = groupStatuses(expected, blocks);
284
+ const expectedOverlaps = overlapsOf(expected);
285
+ // 重复出现的组解析不出 paths,不参与「文件里已经撞了」的判断;缺 paths 的按同名目录算(zk 语义)
286
+ const actualOverlaps = blocks
287
+ ? overlapsOf([...blocks.values()].filter((block) => !block.duplicate)
288
+ .map((block) => ({ name: block.name, paths: effectivePaths(block) })))
289
+ : [];
170
290
  return {
171
291
  mode: cfg.structure,
172
292
  dirs,
173
293
  missing,
294
+ extra,
174
295
  ready: missing.length === 0,
175
- agents: { path: agentsPath, required, present: required ? fs.existsSync(agentsPath) : true },
296
+ agents: { path: agentsPath, required, present: fs.existsSync(agentsPath) },
297
+ groups,
298
+ expectedOverlaps,
299
+ actualOverlaps,
300
+ groupsOk: !!blocks && groups.every((group) => group.present && group.pathsOk) &&
301
+ expectedOverlaps.length === 0 && actualOverlaps.length === 0,
302
+ groupWarnings: blocks ? groupWarningsOf(groups, { expectedOverlaps, actualOverlaps }) : [],
176
303
  };
177
304
  }
178
- function hasGroup(configToml, group) {
179
- const escaped = group.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
180
- return new RegExp(`^\\[group\\."?${escaped}"?\\]`, 'm').test(configToml);
181
- }
182
305
  /** 建目录,返回真正新建的那些(相对笔记本) */
183
306
  function ensureDirs(cfg, rels) {
184
307
  const created = [];
@@ -203,8 +326,20 @@ function ensureTemplates(cfg, files) {
203
326
  }
204
327
  return written;
205
328
  }
329
+ /**
330
+ * 写根目录 AGENTS.md(缺了才写,已存在一律不覆盖 —— 模板允许用户改)。
331
+ * layered 用完整版;flat 用精简版(不出现 raw / inbox / archive / WORKFLOW 这些 flat 没有的路径)。
332
+ * 返回 true = 本次真的写了。
333
+ */
334
+ export function writeAgentsTemplate(cfg) {
335
+ const file = path.join(cfg.notebook, 'AGENTS.md');
336
+ if (fs.existsSync(file))
337
+ return false;
338
+ fs.writeFileSync(file, cfg.structure === 'layered' ? AGENTS_TEMPLATE : AGENTS_TEMPLATE_FLAT, 'utf8');
339
+ return true;
340
+ }
206
341
  /** 建好(或补好)笔记本;返回每一步各自做了没有,设置页直接展示 */
207
- export async function ensureNotebook(cfg, signal) {
342
+ export async function ensureNotebook(cfg, signal, opts = {}) {
208
343
  const layered = cfg.structure === 'layered';
209
344
  fs.mkdirSync(cfg.notebook, { recursive: true });
210
345
  const dirsCreated = ensureDirs(cfg, structureDirs(cfg));
@@ -221,14 +356,10 @@ export async function ensureNotebook(cfg, signal) {
221
356
  'entry.md': ENTRY_TEMPLATE,
222
357
  })
223
358
  : ensureTemplates(cfg, { 'daily.md': DAILY_TEMPLATE });
224
- // AGENTS.md 是 layered 的工作契约(检索词归宿 / 中文打 tags / 不会被宿主自动加载)。
225
- // flat 不写:0.1.0 的 vault 升级过来必须一个文件都不多(M0 的回归承诺)。
226
- const agentsFile = path.join(cfg.notebook, 'AGENTS.md');
227
- let agentsWritten = false;
228
- if (layered && !fs.existsSync(agentsFile)) {
229
- fs.writeFileSync(agentsFile, AGENTS_TEMPLATE, 'utf8');
230
- agentsWritten = true;
231
- }
359
+ // AGENTS.md 是工作契约(检索词归宿 / 中文打 tags / 不会被宿主自动加载)。
360
+ // layered 自动写;flat 只有显式 withAgents 才写 —— 0.1.0 的 vault 升级过来必须一个文件都不多(M0)。
361
+ // 不写的话,默认安装既没有约定、也没有周节奏提醒(P1-6),所以要有一个 opt-in 入口。
362
+ const agentsWritten = layered || opts.withAgents === true ? writeAgentsTemplate(cfg) : false;
232
363
  // WORKFLOW.md 是「动已有笔记」时才读的细则:不注入(省预算),但不进检索(是 meta)
233
364
  const workflowFile = path.join(cfg.notebook, 'WORKFLOW.md');
234
365
  let workflowWritten = false;
@@ -236,16 +367,44 @@ export async function ensureNotebook(cfg, signal) {
236
367
  fs.writeFileSync(workflowFile, WORKFLOW_TEMPLATE, 'utf8');
237
368
  workflowWritten = true;
238
369
  }
239
- const groups = layered ? layeredGroups(cfg) : [dailyGroup(cfg)];
370
+ const groups = expectedGroups(cfg);
240
371
  let configText = fs.readFileSync(configFile, 'utf8');
372
+ const blocks = parseGroupBlocks(configText);
241
373
  const groupsAdded = [];
374
+ const groupWarnings = [];
242
375
  for (const group of groups) {
243
- if (hasGroup(configText, group.name))
376
+ const block = blocks.get(group.name);
377
+ if (block) {
378
+ // 已有 group 一律不重写(用户可能改过 template / extra),只报告与配置的差异
379
+ if (block.duplicate) {
380
+ groupWarnings.push(`group "${group.name}" 重复出现,解析不了 —— 手动检查 .zk/config.toml`);
381
+ }
382
+ else if (!samePaths(effectivePaths(block), group.paths)) {
383
+ groupWarnings.push(`group "${group.name}" ${pathsDiff(group.paths, effectivePaths(block))}`);
384
+ }
244
385
  continue;
386
+ }
387
+ // 新 group 的路径已经被别的 group 占着(典型:只改 dailyGroup 不改 dailyDir;缺 paths 的按同名目录也算):
388
+ // 再追加就是两个 group 用同一条路径,zk 命中哪个模板就只剩实现细节了 —— 只报告,不写
389
+ const owner = [...blocks.values()].find((candidate) => effectivePaths(candidate)?.some((actual) => group.paths.some((expected) => sameGroupPath(actual, expected))));
390
+ if (owner) {
391
+ groupWarnings.push(`group "${group.name}" 没追加:路径 ${group.paths.join('、')} 已被 group "${owner.name}" 占用` +
392
+ '(跑 zk-kit groups --fix)');
393
+ continue;
394
+ }
245
395
  const prefix = configText.endsWith('\n') ? '' : '\n';
246
396
  configText += prefix + groupSection(group);
247
397
  fs.writeFileSync(configFile, configText, 'utf8');
248
398
  groupsAdded.push(group.name);
399
+ blocks.set(group.name, {
400
+ name: group.name,
401
+ paths: group.paths.map(normGroupPath),
402
+ pathsState: 'set',
403
+ template: group.template,
404
+ comment: `# ${group.comment}`,
405
+ header: `[group."${group.name}"]`,
406
+ duplicate: false,
407
+ });
249
408
  }
250
409
  return {
251
410
  notebook: cfg.notebook,
@@ -255,7 +414,184 @@ export async function ensureNotebook(cfg, signal) {
255
414
  dirsCreated,
256
415
  templatesWritten,
257
416
  groupsAdded,
417
+ groupWarnings,
258
418
  agentsWritten,
259
419
  workflowWritten,
260
420
  };
261
421
  }
422
+ const escapeRe = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
423
+ /** 只改组头名字(连同 .note / .extra 子表;裸键 / 引号写法都认),其它行一字不动 */
424
+ function renameGroup(text, from, to) {
425
+ const esc = escapeRe(from);
426
+ const re = new RegExp(`(\\[group\\.)(?:"${esc}"|'${esc}'|${esc}(?=[.\\]]))`, 'g');
427
+ return text.replace(re, `$1"${to}"`);
428
+ }
429
+ /** 只替换 base group 的 paths 行;多行数组 / 找不到都不猜(返回 null) */
430
+ function replacePaths(text, name, paths) {
431
+ const lines = text.split('\n');
432
+ const headerRe = /^\s*\[group\.(?:"([^"]+)"|'([^']+)'|([A-Za-z0-9_-]+))(?:\.(note|extra))?\]\s*(?:#.*)?$/;
433
+ let start = -1;
434
+ for (let i = 0; i < lines.length; i++) {
435
+ const m = headerRe.exec(lines[i]);
436
+ if (!m || m[4])
437
+ continue;
438
+ if ((m[1] ?? m[2] ?? m[3]) === name) {
439
+ start = i;
440
+ break;
441
+ }
442
+ }
443
+ if (start < 0)
444
+ return null;
445
+ let end = lines.length;
446
+ for (let i = start + 1; i < lines.length; i++) {
447
+ if (/^\s*\[/.test(lines[i])) {
448
+ end = i;
449
+ break;
450
+ }
451
+ }
452
+ const value = `[${paths.map((p) => JSON.stringify(p)).join(', ')}]`;
453
+ for (let i = start + 1; i < end; i++) {
454
+ const m = /^(\s*paths\s*=\s*)(\[[^\]]*\])(\s*(?:#.*)?)$/.exec(lines[i]);
455
+ if (m) {
456
+ lines[i] = m[1] + value + m[3];
457
+ return lines.join('\n');
458
+ }
459
+ if (/^\s*paths\s*=/.test(lines[i]))
460
+ return null; // 多行数组:不在本轮猜着改
461
+ }
462
+ lines.splice(start + 1, 0, `paths = ${value}`);
463
+ return lines.join('\n');
464
+ }
465
+ /**
466
+ * 显式修复 group 配置(`zk-kit groups --fix`):
467
+ * · 只改 dsh-zdiary-kit 自己写的 group(组头前有 `dsh-zdiary-kit` 注释);
468
+ * · 只改 `paths` 行,或把同路径的旧组头改名(dailyGroup 变更);
469
+ * · 写下去会让两个 group 用同一条路径时一律不写(父子目录不算):
470
+ * 期望路径自己就冲突时整轮不改,期望路径被别的 group 占着时只跳过那一个;
471
+ * · 用户自定义的 template / extra / 注释 / 顺序一律不动;
472
+ * · 写前备份 `.zk/config.toml.bak`,写临时文件后 rename。
473
+ */
474
+ export function fixGroupConfig(cfg) {
475
+ const file = path.join(cfg.notebook, '.zk', 'config.toml');
476
+ if (!fs.existsSync(file)) {
477
+ throw new ZkError('还没有 .zk/config.toml —— 先跑 zk-kit init');
478
+ }
479
+ const original = fs.readFileSync(file, 'utf8');
480
+ let text = original;
481
+ const updates = [];
482
+ const warnings = [];
483
+ const groups = expectedGroups(cfg);
484
+ const expectedNames = new Set(groups.map((group) => group.name));
485
+ // 期望路径自己就撞了(典型:dailyDir 与某个 group 的路径一样):一个都不写。
486
+ // 写下去就是两个 group 用同一条路径,zk 命中哪个模板就只剩实现细节了 —— 这比「没改」更难查。
487
+ const expectedOverlaps = overlapsOf(groups);
488
+ if (expectedOverlaps.length > 0) {
489
+ for (const note of groupOverlapNotes({ expectedOverlaps, actualOverlaps: [] }))
490
+ warnings.push(note.text);
491
+ const involved = new Set(expectedOverlaps.flatMap((overlap) => [overlap.a, overlap.b]));
492
+ for (const group of groups) {
493
+ if (!involved.has(group.name))
494
+ continue;
495
+ updates.push({
496
+ name: group.name,
497
+ action: 'skip',
498
+ expectedPaths: group.paths,
499
+ reason: '配置里有两个 group 要用同一条路径,先改 dailyDir / notesDir 或换结构',
500
+ });
501
+ }
502
+ return { notebook: cfg.notebook, changed: false, backup: null, updates, warnings };
503
+ }
504
+ // 1. 缺失的 group:先认领同路径的旧 plugin group(改组头名),再看路径是否被占
505
+ for (const group of groups) {
506
+ const blocks = parseGroupBlocks(text);
507
+ if (blocks.has(group.name))
508
+ continue;
509
+ const stale = [...blocks.values()].filter((block) => isPluginOwned(block) && !expectedNames.has(block.name));
510
+ const same = stale.find((block) => samePaths(effectivePaths(block), group.paths));
511
+ if (same) {
512
+ text = renameGroup(text, same.name, group.name);
513
+ updates.push({
514
+ name: group.name,
515
+ action: 'rename',
516
+ from: same.name,
517
+ expectedPaths: group.paths,
518
+ actualPaths: effectivePaths(same),
519
+ });
520
+ continue;
521
+ }
522
+ // dailyGroup 改名 + dailyDir 同时改:认不出旧组,也不冒险追加第二个日记组
523
+ const staleDaily = group.template === 'daily.md' ? stale.find((block) => block.template === 'daily.md') : undefined;
524
+ if (staleDaily) {
525
+ const reason = `旧日记 group "${staleDaily.name}" 的路径是 ${effectivePaths(staleDaily)?.join('、') ?? '解析不了'},` +
526
+ `与期望 ${group.paths.join('、')} 不一致 —— 先手动确认改名与路径`;
527
+ warnings.push(reason);
528
+ updates.push({ name: group.name, action: 'skip', expectedPaths: group.paths, reason });
529
+ continue;
530
+ }
531
+ const owner = [...blocks.values()].find((block) => effectivePaths(block)?.some((actual) => group.paths.some((expected) => sameGroupPath(actual, expected))));
532
+ if (owner) {
533
+ const reason = `路径 ${group.paths.join('、')} 已被 group "${owner.name}" 占用 —— 先手动处理这个 group`;
534
+ warnings.push(`group "${group.name}" 没追加:${reason}`);
535
+ updates.push({ name: group.name, action: 'skip', expectedPaths: group.paths, reason });
536
+ continue;
537
+ }
538
+ const prefix = text.endsWith('\n') ? '' : '\n';
539
+ text += prefix + groupSection(group);
540
+ updates.push({ name: group.name, action: 'append', expectedPaths: group.paths });
541
+ }
542
+ // 2. 已存在的 group:只改 plugin-owned 的 paths 行
543
+ for (const group of groups) {
544
+ const current = parseGroupBlocks(text);
545
+ const block = current.get(group.name);
546
+ if (!block)
547
+ continue;
548
+ if (block.duplicate) {
549
+ const reason = `group "${group.name}" 重复出现,解析不了 —— 手动检查 .zk/config.toml`;
550
+ warnings.push(reason);
551
+ updates.push({ name: group.name, action: 'skip', expectedPaths: group.paths, reason });
552
+ continue;
553
+ }
554
+ const actual = effectivePaths(block);
555
+ if (samePaths(actual, group.paths))
556
+ continue;
557
+ if (!isPluginOwned(block)) {
558
+ const reason = `不是插件建的 group,paths 未改(期望 ${group.paths.join('、')},实际 ${actual?.join('、') ?? '解析不了'})`;
559
+ warnings.push(`group "${group.name}":${reason}`);
560
+ updates.push({ name: group.name, action: 'skip', expectedPaths: group.paths, actualPaths: actual, reason });
561
+ continue;
562
+ }
563
+ // 期望路径被别的 group 占着:不替换 —— 之前只拦了「追加」,替换同样会造出两个 group 用同一条路径。
564
+ // 期望内部的 group 会自己走到期望路径,不算占用;用户建的 / 上一版留下的 group 才拦。
565
+ const rival = [...current.values()].find((candidate) => candidate.name !== group.name &&
566
+ !(expectedNames.has(candidate.name) && isPluginOwned(candidate)) &&
567
+ effectivePaths(candidate)?.some((p) => group.paths.some((expected) => sameGroupPath(p, expected))));
568
+ if (rival) {
569
+ const reason = `路径 ${group.paths.join('、')} 已被 group "${rival.name}" 占用(${effectivePaths(rival)?.join('、') ?? '解析不了'}),paths 未改 —— 先手动处理这个 group`;
570
+ warnings.push(`group "${group.name}":${reason}`);
571
+ updates.push({ name: group.name, action: 'skip', expectedPaths: group.paths, actualPaths: actual, reason });
572
+ continue;
573
+ }
574
+ const next = replacePaths(text, group.name, group.paths);
575
+ if (next === null) {
576
+ const reason = 'paths 行解析不了(可能是多行数组),未改 —— 手动编辑 .zk/config.toml';
577
+ warnings.push(`group "${group.name}":${reason}`);
578
+ updates.push({ name: group.name, action: 'skip', expectedPaths: group.paths, actualPaths: actual, reason });
579
+ continue;
580
+ }
581
+ text = next;
582
+ updates.push({
583
+ name: group.name,
584
+ action: 'paths',
585
+ expectedPaths: group.paths,
586
+ actualPaths: actual,
587
+ });
588
+ }
589
+ if (text === original)
590
+ return { notebook: cfg.notebook, changed: false, backup: null, updates, warnings };
591
+ const backup = `${file}.bak`;
592
+ fs.copyFileSync(file, backup);
593
+ const tmp = `${file}.tmp-${process.pid}`;
594
+ fs.writeFileSync(tmp, text, 'utf8');
595
+ fs.renameSync(tmp, file);
596
+ return { notebook: cfg.notebook, changed: true, backup, updates, warnings };
597
+ }
@@ -0,0 +1,77 @@
1
+ /**
2
+ * `[[链接]]` 的解析口径(lint 与 dream 共用)。
3
+ *
4
+ * 为什么要抽出来:`zk_lint` 查「MEMORY 里的来源链接还指向活笔记吗」,`zk_dream` 查
5
+ * 「这条候选是不是已经晋升进 MEMORY 了」—— 两处都要回答同一个问题(这个 `[[目标]]` 现在对应哪篇笔记),
6
+ * 各写一份的话,解析顺序迟早分叉,于是同一份 MEMORY 在两个工具里给出不同答案。
7
+ *
8
+ * 顺序固定(与 lint 原来的口径一致):原路径 → 加 `.md` → `archive/` 下同名 → 活笔记标题 / 文件名。
9
+ * 归档标题**不**反查:归档默认不进检索,再造一套索引就成了第二真相。
10
+ */
11
+ import fs from 'node:fs';
12
+ import path from 'node:path';
13
+ import { parseFrontmatter } from './frontmatter.js';
14
+ /** `[[路径]]` / `[[路径|别名]]` / `[[路径#小节]]` 都认,取路径部分 */
15
+ export const WIKI_LINK = /\[\[([^\]|#]+)(?:#[^\]|]*)?(?:\|[^\]]*)?\]\]/g;
16
+ /** 标题归一化:压空白 + 小写,不改字(中文不受影响,也不会把「A B」和「AB」当成同一个) */
17
+ export function normalizeTitle(title) {
18
+ return String(title ?? '').replace(/\s+/g, ' ').trim().toLowerCase();
19
+ }
20
+ export function wikiIndex(notes) {
21
+ const byTitle = new Map();
22
+ for (const note of notes) {
23
+ for (const key of [normalizeTitle(note.title), normalizeTitle(path.basename(note.path, path.extname(note.path)))]) {
24
+ if (key && !byTitle.has(key))
25
+ byTitle.set(key, note.path);
26
+ }
27
+ }
28
+ return { byTitle };
29
+ }
30
+ function insideNotebook(cfg, abs) {
31
+ const root = path.resolve(cfg.notebook);
32
+ const p = path.resolve(abs);
33
+ return p === root || p.startsWith(root + path.sep);
34
+ }
35
+ function statusOf(abs) {
36
+ try {
37
+ return parseFrontmatter(fs.readFileSync(abs, 'utf8')).fields.status ?? '';
38
+ }
39
+ catch {
40
+ return '';
41
+ }
42
+ }
43
+ function relOf(cfg, abs) {
44
+ return path.relative(cfg.notebook, abs).split(path.sep).join('/');
45
+ }
46
+ /** 把一个 `[[目标]]` 落到具体文件上:活笔记 / 已归档 / 不存在 */
47
+ export function resolveWikiTarget(cfg, target, index) {
48
+ const rel = String(target ?? '').replace(/\\/g, '/').replace(/^\.\//, '').trim();
49
+ if (!rel)
50
+ return { status: 'missing', path: '', explicit: false };
51
+ const candidates = /\.md$/i.test(rel) ? [rel] : [rel, `${rel}.md`];
52
+ for (const candidate of candidates) {
53
+ const abs = path.resolve(cfg.notebook, candidate);
54
+ if (!insideNotebook(cfg, abs) || !fs.existsSync(abs) || !fs.statSync(abs).isFile())
55
+ continue;
56
+ const hit = relOf(cfg, abs);
57
+ // 显式写 archive/ 路径 = 有意引用旧结论(supersede 就是这样重写入链的),不算漂移
58
+ if (hit === cfg.archiveDir || hit.startsWith(`${cfg.archiveDir}/`)) {
59
+ return { status: 'archived', path: hit, explicit: true };
60
+ }
61
+ return { status: statusOf(abs) === 'superseded' ? 'archived' : 'live', path: hit, explicit: false };
62
+ }
63
+ // 链接还停在废弃前的路径:文件已经搬进 archive/ —— 这正是要抓的漂移
64
+ if (!rel.startsWith(`${cfg.archiveDir}/`)) {
65
+ for (const candidate of candidates) {
66
+ const abs = path.resolve(cfg.notebook, cfg.archiveDir, candidate);
67
+ if (!insideNotebook(cfg, abs) || !fs.existsSync(abs) || !fs.statSync(abs).isFile())
68
+ continue;
69
+ return { status: 'archived', path: relOf(cfg, abs), explicit: false };
70
+ }
71
+ }
72
+ // 标题式链接只在活笔记里找
73
+ const byTitle = index.byTitle.get(normalizeTitle(rel));
74
+ if (byTitle)
75
+ return { status: 'live', path: byTitle, explicit: false };
76
+ return { status: 'missing', path: '', explicit: false };
77
+ }