dsh-zdiary-kit 3.7.0 → 3.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.
@@ -1,5 +1,5 @@
1
1
  /**
2
- * zk 工具(feature 的公共入口):14 个内置工具 + `[alias]` 别名工具,全部经 lib/zk.ts。
2
+ * zk 工具(feature 的公共入口):15 个内置工具 + `[alias]` 别名工具,全部经 lib/zk.ts。
3
3
  *
4
4
  * 设计要点:
5
5
  * · 除 zk_context(只读 meta 文件,不依赖 zk)外,每个工具进来先 ensureNotebook —— 第一次调用就自动建好笔记本,用户不用先点设置页;
@@ -15,10 +15,13 @@ import { configFor, pinSession, sessionNotebook, sessionState } from '../../conf
15
15
  import { defaultNotebook, expandHome, processWorkspace, resolveInWorkspace } from '../../config/paths.js';
16
16
  import { S, validateArgs } from '../../lib/tool.js';
17
17
  import { ensureNotebook, newNoteDir } from '../../lib/notebook.js';
18
- import { searchNotes, searchNotesDetailed, createNote, appendToNote, ensureDailyNote, appendDaily, linkNotes, withTags, taglessCjkWarning, notebookStats, supersedeNote, renameNote, hasNotebook, isUnderDir, localDate as dateOnly, runAlias, hasCjk, ZkError, } from '../../lib/zk.js';
18
+ import { searchNotes, searchNotesDetailed, createNote, appendToNote, ensureDailyNote, appendDaily, linkNotes, withTags, taglessCjkWarning, notebookStats, supersedeNote, renameNote, hasNotebook, isUnderDir, localDate as dateOnly, runAlias, hasCjk, walkFrom, ZkError, } from '../../lib/zk.js';
19
19
  import { configuredAliases, readAliases } from '../../lib/alias.js';
20
20
  import { buildMemoryPayload, memoryCapacity, META_FILES } from '../../lib/memory.js';
21
21
  import { assembleRecall } from '../../lib/recall.js';
22
+ import { entryPointLines, entryPointsOf } from '../../lib/entry-points.js';
23
+ import { archivedCounterparts, describeCounterEntries } from '../../lib/archive-probe.js';
24
+ import { bumpUsage, readUsage } from '../../lib/usage.js';
22
25
  import { META_NAMES } from '../../lib/meta.js';
23
26
  import { formatLintExtras, formatMemoryLinks, lintNotebook } from '../../lib/lint.js';
24
27
  import { dreamNotebook, STALE_DAYS } from '../../lib/dream.js';
@@ -39,6 +42,26 @@ const objSchema = (properties, required) => ({
39
42
  });
40
43
  /** lint 输出的三个共用形状(每类最多 50 条 + 总数) */
41
44
  const LINT_ENTRY = objSchema({ title: { type: 'string' }, path: { type: 'string' } }, ['title', 'path']);
45
+ /** R9:MEMORY.md 的活条目 → 入口(`via: query` 的来源可以不在本次结果里) */
46
+ const ENTRY_POINT = objSchema({
47
+ entry: { type: 'string' },
48
+ title: { type: 'string' },
49
+ path: { type: 'string' },
50
+ absPath: { type: 'string' },
51
+ via: { type: 'string', enum: ['query', 'result'] },
52
+ /** false = 标题 / id 写法且不在本批结果里:只有入口名,落地交给 zk_walk */
53
+ resolved: { type: 'boolean' },
54
+ }, ['entry', 'title', 'via', 'resolved']);
55
+ /** 死胡同探针:归档里同名的废弃结论(不是第二份结果列表) */
56
+ const COUNTER_ENTRY = objSchema({
57
+ matched: { type: 'string' },
58
+ title: { type: 'string' },
59
+ path: { type: 'string' },
60
+ absPath: { type: 'string' },
61
+ reason: { type: 'string' },
62
+ supersededBy: { type: 'string' },
63
+ score: { type: 'number' },
64
+ }, ['matched', 'title', 'path', 'absPath', 'reason', 'supersededBy', 'score']);
42
65
  const LINT_BUCKET = objSchema({ total: { type: 'number' }, items: { type: 'array', items: LINT_ENTRY } }, ['total', 'items']);
43
66
  const LINT_ONE_WAY_ITEM = objSchema({
44
67
  title: { type: 'string' },
@@ -274,6 +297,11 @@ function tagSuffix(record) {
274
297
  function detailOf(n) {
275
298
  return n.snippet && n.snippet !== n.lead ? n.snippet : (n.lead ?? '');
276
299
  }
300
+ /** 死胡同提醒(措辞与 `zk-kit search` 共用一份);没有就一个字都不加 */
301
+ function counterBlockOf(entries, truncated, zeroHit) {
302
+ const body = describeCounterEntries({ entries: entries ?? [], truncated: truncated === true }, { zeroHit });
303
+ return body ? '\n\n' + body : '';
304
+ }
277
305
  function noteLine(n, index) {
278
306
  const head = `${index + 1}. ${n.title || n.path}`;
279
307
  const meta = [n.absPath || n.path, dateOnly(n.created)].filter(Boolean).join(' · ');
@@ -378,7 +406,9 @@ export function buildTools(workspaceOf = () => processWorkspace()) {
378
406
  description: '在 zk 知识库里搜索笔记(全文 / 标签 / 日期 / 断链 / 孤立笔记),返回标题、相对路径、绝对路径、标签、创建日、摘要与命中片段。' +
379
407
  '找到后用原生 read 读全文:notes[].absPath 可以直接传给 read。写笔记前先用它查重。' +
380
408
  '中文会自动并用子串,多词按覆盖度合并(FTS 不切中文):matchStrategy 说明这次用了 fts / regex / mixed,mixed 表示补到了全文索引漏掉的笔记。' +
381
- '有 query 时默认按 FTS 相关性排序,显式给 sort 才改顺序。',
409
+ '有 query 时默认按 FTS 相关性排序,显式给 sort 才改顺序。' +
410
+ '结果还带 entryPoints(MEMORY 的活条目:via=query 表示这条结论跟查询有关,来源可以不在本次结果里)' +
411
+ '与 counterEntries(归档里同名旧结论 + 废弃原因,先看它别把废掉的结论重新提出来)。',
382
412
  parameters: {
383
413
  type: 'object',
384
414
  properties: {
@@ -417,13 +447,21 @@ export function buildTools(workspaceOf = () => processWorkspace()) {
417
447
  snippet: { type: 'string' },
418
448
  }, ['title', 'path', 'absPath', 'tags', 'created', 'lead']),
419
449
  },
450
+ /** R9:只在有命中且 MEMORY 里有对应活条目时出现 */
451
+ entryPoints: { type: 'array', items: ENTRY_POINT },
452
+ /** 入口超过上限时出现(true),不静默少列 */
453
+ entryPointsTruncated: { type: 'boolean' },
454
+ /** 死胡同探针:归档里同名的废弃结论(零子进程;只提示,不改结果集) */
455
+ counterEntries: { type: 'array', items: COUNTER_ENTRY },
456
+ counterEntriesTruncated: { type: 'boolean' },
420
457
  }, ['notebook', 'count', 'matchStrategy', 'completeness', 'hasMore', 'scanned', 'notes']),
421
458
  },
422
459
  async run(args, env) {
423
460
  const cfg = configFor(env.workspace, env.sessionId);
424
461
  await ensureNotebook(cfg);
462
+ const query = args.query ? String(args.query) : undefined;
425
463
  const result = await searchNotesDetailed(cfg, {
426
- query: args.query ? String(args.query) : undefined,
464
+ query,
427
465
  tags: Array.isArray(args.tags) ? args.tags.map(String) : undefined,
428
466
  since: args.since ? String(args.since) : undefined,
429
467
  until: args.until ? String(args.until) : undefined,
@@ -433,6 +471,14 @@ export function buildTools(workspaceOf = () => processWorkspace()) {
433
471
  // R1:有 query 且没显式给 sort → relevance(不传 --sort,保住 FTS 相关性顺序)
434
472
  sort: args.sort ? String(args.sort) : (args.query ? 'relevance' : 'created-desc'),
435
473
  });
474
+ // R9:查询命中的 MEMORY 条目 → 入口(来源可以不在本批结果里);先只读,不新增 zk 进程
475
+ const { points: entryPoints, truncated: entryPointsTruncated } = entryPointsOf(cfg, result.notes, { query });
476
+ const counters = archivedCounterparts(cfg, result.notes, { query });
477
+ bumpUsage(cfg, [
478
+ 'search',
479
+ ...(entryPoints.length ? ['entryPoints'] : []),
480
+ ...(counters.entries.length ? ['counterEntries'] : []),
481
+ ]);
436
482
  return {
437
483
  notebook: cfg.notebook,
438
484
  count: result.notes.length,
@@ -446,14 +492,19 @@ export function buildTools(workspaceOf = () => processWorkspace()) {
446
492
  created: dateOnly(n.created), lead: n.lead, words: n.words,
447
493
  ...(n.snippet ? { snippet: n.snippet } : {}),
448
494
  })),
495
+ ...(entryPoints.length ? { entryPoints } : {}),
496
+ ...(entryPointsTruncated ? { entryPointsTruncated } : {}),
497
+ ...(counters.entries.length ? { counterEntries: counters.entries } : {}),
498
+ ...(counters.truncated ? { counterEntriesTruncated: true } : {}),
449
499
  };
450
500
  },
451
501
  render(args, value) {
452
502
  const v = value;
503
+ const counters = counterBlockOf(v.counterEntries, v.counterEntriesTruncated, v.count === 0);
453
504
  if (!v.count) {
454
505
  return text(`没有匹配的笔记(笔记本 ${v.notebook})` +
455
506
  zeroHitHint(args, '或按 tags 查') +
456
- (v.completeness === 'unknown' ? ';但这次检索结果无法完整解析,不能当作「库里没有」' : ''));
507
+ (v.completeness === 'unknown' ? ';但这次检索结果无法完整解析,不能当作「库里没有」' : '') + entryPointLines(v.entryPoints, { truncated: v.entryPointsTruncated }) + counters);
457
508
  }
458
509
  const how = v.matchStrategy === 'mixed'
459
510
  ? '(中文:全文 + 子串合并,已补上全文索引漏掉的)'
@@ -461,7 +512,8 @@ export function buildTools(workspaceOf = () => processWorkspace()) {
461
512
  const tail = v.completeness === 'unknown'
462
513
  ? '\n⚠️ 无法确认结果是否完整(解析失败 / 补充检索失败),先别把它当成全部命中'
463
514
  : v.hasMore ? `\n⚠️ 还有更多匹配没返回(已检查 ${v.scanned} 条候选);要更全就提高 limit 或加过滤条件` : '';
464
- return text(`${v.count} 条(笔记本 ${v.notebook})${how}\n` + v.notes.map(noteLine).join('\n') + tail);
515
+ return text(`${v.count} 条(笔记本 ${v.notebook})${how}\n` + v.notes.map(noteLine).join('\n') +
516
+ entryPointLines(v.entryPoints, { truncated: v.entryPointsTruncated }) + tail + counters);
465
517
  },
466
518
  }),
467
519
  t({
@@ -469,7 +521,7 @@ export function buildTools(workspaceOf = () => processWorkspace()) {
469
521
  description: '结构化检索记忆:按 type(daily/source/concept/entity/pattern)、status(active/superseded)、标签、目录、日期、断链、孤立过滤。' +
470
522
  '默认只看 active 且不含归档;传 include_archived: true 会连归档一起查,此时未显式给 status 就不再默认过滤 active。' +
471
523
  '中文会自动并用子串,多词按覆盖度合并;有 query 时默认按 FTS 相关性排序。' +
472
- '这是查「记忆里有什么」的主入口。',
524
+ '这是查「记忆里有什么」的主入口。entryPoints / counterEntries 与 zk_search 同口径。',
473
525
  parameters: {
474
526
  type: 'object',
475
527
  properties: {
@@ -514,14 +566,22 @@ export function buildTools(workspaceOf = () => processWorkspace()) {
514
566
  archived: { type: 'boolean' },
515
567
  }, ['title', 'path', 'absPath', 'type', 'status', 'authority', 'tags', 'created', 'lead', 'archived']),
516
568
  },
569
+ /** R9:只在有命中且 MEMORY 里有对应活条目时出现 */
570
+ entryPoints: { type: 'array', items: ENTRY_POINT },
571
+ /** 入口超过上限时出现(true),不静默少列 */
572
+ entryPointsTruncated: { type: 'boolean' },
573
+ /** 死胡同探针:归档里同名的废弃结论(include_archived 时不重复报) */
574
+ counterEntries: { type: 'array', items: COUNTER_ENTRY },
575
+ counterEntriesTruncated: { type: 'boolean' },
517
576
  }, ['notebook', 'count', 'completeness', 'hasMore', 'scanned', 'notes']),
518
577
  },
519
578
  async run(args, env) {
520
579
  const cfg = configFor(env.workspace, env.sessionId);
521
580
  await ensureNotebook(cfg, env.signal);
522
581
  const includeArchived = args.include_archived === true;
582
+ const query = args.query ? String(args.query) : undefined;
523
583
  const result = await searchNotesDetailed(cfg, {
524
- query: args.query ? String(args.query) : undefined,
584
+ query,
525
585
  tags: Array.isArray(args.tags) ? args.tags.map(String) : undefined,
526
586
  paths: Array.isArray(args.dirs) ? args.dirs.map(String) : undefined,
527
587
  type: args.type ? [String(args.type)] : undefined,
@@ -537,6 +597,16 @@ export function buildTools(workspaceOf = () => processWorkspace()) {
537
597
  sort: args.sort ? String(args.sort) : (args.query ? 'relevance' : 'created-desc'),
538
598
  }, env.signal);
539
599
  const notes = result.notes;
600
+ // R9:与 zk_search 共用同一份计算(查询命中的来源可以不在本批结果里;零子进程)
601
+ const { points: entryPoints, truncated: entryPointsTruncated } = entryPointsOf(cfg, notes, { query });
602
+ const counters = includeArchived
603
+ ? { entries: [], scanned: 0, truncated: false }
604
+ : archivedCounterparts(cfg, notes, { query });
605
+ bumpUsage(cfg, [
606
+ 'query',
607
+ ...(entryPoints.length ? ['entryPoints'] : []),
608
+ ...(counters.entries.length ? ['counterEntries'] : []),
609
+ ]);
540
610
  return {
541
611
  notebook: cfg.notebook,
542
612
  count: notes.length,
@@ -559,14 +629,19 @@ export function buildTools(workspaceOf = () => processWorkspace()) {
559
629
  ...(n.snippet ? { snippet: n.snippet } : {}),
560
630
  archived: n.path.startsWith(cfg.archiveDir + '/'),
561
631
  })),
632
+ ...(entryPoints.length ? { entryPoints } : {}),
633
+ ...(entryPointsTruncated ? { entryPointsTruncated } : {}),
634
+ ...(counters.entries.length ? { counterEntries: counters.entries } : {}),
635
+ ...(counters.truncated ? { counterEntriesTruncated: true } : {}),
562
636
  };
563
637
  },
564
638
  render(args, value) {
565
639
  const v = value;
640
+ const counters = counterBlockOf(v.counterEntries, v.counterEntriesTruncated, v.count === 0);
566
641
  if (!v.count) {
567
642
  return text(`没有匹配的笔记(笔记本 ${v.notebook})` +
568
643
  zeroHitHint(args, '或给 tags 参数按标签查') +
569
- (v.completeness === 'unknown' ? ';但这次检索结果无法完整解析,不能当作「记忆里没有」' : ''));
644
+ (v.completeness === 'unknown' ? ';但这次检索结果无法完整解析,不能当作「记忆里没有」' : '') + entryPointLines(v.entryPoints, { truncated: v.entryPointsTruncated }) + counters);
570
645
  }
571
646
  const tail = v.completeness === 'unknown'
572
647
  ? '\n⚠️ 无法确认结果是否完整(解析失败 / 补充检索失败),先别把它当成全部命中'
@@ -576,7 +651,8 @@ export function buildTools(workspaceOf = () => processWorkspace()) {
576
651
  const detail = detailOf({ lead: String(n.lead ?? ''), snippet: String(n.snippet ?? '') });
577
652
  return `${i + 1}. ${String(n.title)} [${badges.join(' · ')}]\n ${String(n.absPath || n.path)} · ${String(n.created)}${detail ? '\n ' + detail : ''}`;
578
653
  });
579
- return text(`${v.count} 条(笔记本 ${v.notebook})\n` + lines.join('\n') + tail);
654
+ return text(`${v.count} 条(笔记本 ${v.notebook})\n` + lines.join('\n') +
655
+ entryPointLines(v.entryPoints, { truncated: v.entryPointsTruncated }) + tail + counters);
580
656
  },
581
657
  }),
582
658
  t({
@@ -621,7 +697,17 @@ export function buildTools(workspaceOf = () => processWorkspace()) {
621
697
  reason: { type: 'string', enum: ['included', 'duplicate', 'empty', 'over-budget'] },
622
698
  }, ['title', 'path', 'absPath', 'included', 'reason']),
623
699
  },
624
- }, ['notebook', 'text', 'used', 'budget', 'completeness', 'hasMore', 'notes']),
700
+ /** R9:与 zk_search / zk_query 共用同一份计算(没有就是空数组,不另算) */
701
+ entryPoints: { type: 'array', items: ENTRY_POINT },
702
+ /** 入口超过上限(true),不静默少列 */
703
+ entryPointsTruncated: { type: 'boolean' },
704
+ /** true = via=query 的入口已写进 text(占同一份预算);false 时正文里没有它们 */
705
+ entryPointsInText: { type: 'boolean' },
706
+ /** 死胡同探针:归档里同名的废弃结论 */
707
+ counterEntries: { type: 'array', items: COUNTER_ENTRY },
708
+ counterEntriesTruncated: { type: 'boolean' },
709
+ }, ['notebook', 'text', 'used', 'budget', 'completeness', 'hasMore', 'notes',
710
+ 'entryPoints', 'entryPointsTruncated', 'counterEntries', 'counterEntriesTruncated']),
625
711
  },
626
712
  async run(args, env) {
627
713
  const cfg = configFor(env.workspace, env.sessionId);
@@ -648,24 +734,128 @@ export function buildTools(workspaceOf = () => processWorkspace()) {
648
734
  const v = value;
649
735
  const kept = v.notes.filter((n) => n.included).length;
650
736
  const dropped = v.notes.length - kept;
737
+ const counters = counterBlockOf(v.counterEntries, v.counterEntriesTruncated, v.notes.length === 0);
651
738
  if (!v.notes.length) {
652
739
  return text(`没有匹配的笔记(笔记本 ${v.notebook})` +
653
740
  zeroHitHint(args, '或按 tags 查') +
654
- (v.completeness === 'unknown' ? ';但这次检索结果无法完整解析,不能当作「库里没有」' : ''));
741
+ (v.completeness === 'unknown' ? ';但这次检索结果无法完整解析,不能当作「库里没有」' : '') + entryPointLines(v.entryPoints, { truncated: v.entryPointsTruncated }) + counters);
655
742
  }
656
743
  const lines = [`召回装配:${v.used}/${v.budget} 词 · 收录 ${kept}/${v.notes.length} 篇(笔记本 ${v.notebook})`];
657
744
  if (v.text)
658
745
  lines.push('', v.text);
659
746
  if (dropped)
660
747
  lines.push(`(${dropped} 篇没放进去:整条丢弃,没有切半句;原因见 notes[].reason)`);
748
+ // `via: 'query'` 的入口已经写进 text(排在装配正文之前);只有预算放不下时才会在这里补回。
749
+ // 状态取自 assembleRecall 的 `entryPointsInText`,不从 text 里嗅字符串 —— 笔记正文也可能含那串字。
750
+ const points = entryPointLines(v.entryPoints, {
751
+ truncated: v.entryPointsTruncated,
752
+ skipQuery: v.entryPointsInText,
753
+ });
754
+ if (points)
755
+ lines.push(points.trimStart());
661
756
  const tail = v.completeness === 'unknown'
662
757
  ? '⚠️ 无法确认结果是否完整(解析失败 / 补充检索失败),先别把它当成全部命中'
663
758
  : v.hasMore ? '⚠️ 还有更多匹配没返回;要提高 limit 或缩小过滤范围' : '';
664
759
  if (tail)
665
760
  lines.push(tail);
761
+ if (counters)
762
+ lines.push(counters.trimStart());
666
763
  return text(lines.join('\n'));
667
764
  },
668
765
  }),
766
+ t({
767
+ name: 'zk_walk',
768
+ description: '从一篇笔记出发走一跳邻居(只读):direction=both 同时看反链与出链,in=谁链到它,out=它链到谁。' +
769
+ '种子写相对笔记本的路径、绝对路径,或精确标题 / 稳定 id([[标题]] / [[id]] 也认);不精确命中就返回空,不会退回全库。' +
770
+ '按篇反查、不建全图,成本与库规模基本无关;limit 硬顶 200,触顶 completeness=partial(邻居没列全,不代表没有)。' +
771
+ '每条邻居带 section / linkLine:那条边所在的小节与那一行 —— 没有它,同一篇种子的出链只有一串标题。' +
772
+ '只回标题 / 路径 / absPath / 摘要 / 那一行,全文仍用原生 read 读 absPath;不改标题、不自动 link、不写任何文件。',
773
+ parameters: {
774
+ type: 'object',
775
+ properties: {
776
+ path: S.str('种子笔记:相对笔记本的路径、绝对路径,或精确标题 / 稳定 id(也认 [[标题]] / [[id]])'),
777
+ direction: S.enum('走哪个方向:both 反链 + 出链,in 只看谁链到它,out 只看它链到谁(默认 both)', ['both', 'in', 'out']),
778
+ limit: S.num('每个方向最多几条(1-200,默认 10)'),
779
+ include_archived: S.bool('连 archive/ 里的废弃笔记一起看(默认 false)'),
780
+ },
781
+ required: ['path'],
782
+ additionalProperties: false,
783
+ },
784
+ output: {
785
+ schema: objSchema({
786
+ notebook: { type: 'string' },
787
+ /** 种子解析失败时整个键不出现(null 过不了 object 校验,不拿空对象冒充) */
788
+ seed: objSchema({ title: { type: 'string' }, path: { type: 'string' }, absPath: { type: 'string' } }, ['title', 'path', 'absPath']),
789
+ direction: { type: 'string', enum: ['both', 'in', 'out'] },
790
+ count: { type: 'number' },
791
+ truncated: { type: 'boolean' },
792
+ /** 只有 complete / partial:按篇反查没有产生 unknown 的路径 */
793
+ completeness: { type: 'string', enum: ['complete', 'partial'] },
794
+ notes: {
795
+ type: 'array',
796
+ items: objSchema({
797
+ title: { type: 'string' },
798
+ path: { type: 'string' },
799
+ absPath: { type: 'string' },
800
+ relation: { type: 'string', enum: ['in', 'out'] },
801
+ lead: { type: 'string' },
802
+ /** 这条边所在的 `##` / `###` 小节;找不到时键不出现(plan §14.1) */
803
+ section: { type: 'string' },
804
+ /** 这条边的那一行(压空白、截 160 码点):没有它,同一篇种子的出链长得一模一样 */
805
+ linkLine: { type: 'string' },
806
+ }, ['title', 'path', 'absPath', 'relation', 'lead']),
807
+ },
808
+ }, ['notebook', 'direction', 'count', 'truncated', 'completeness', 'notes']),
809
+ },
810
+ async run(args, env) {
811
+ const cfg = configFor(env.workspace, env.sessionId);
812
+ await ensureNotebook(cfg, env.signal);
813
+ const seed = args.path === undefined || args.path === null ? '' : String(args.path);
814
+ if (!seed.trim())
815
+ throw new ZkError('种子不能为空', '给 path:相对笔记本的路径,或精确标题 / id');
816
+ const direction = (args.direction === undefined ? 'both' : String(args.direction));
817
+ const r = await walkFrom(cfg, {
818
+ seed,
819
+ direction,
820
+ limit: args.limit === undefined ? 10 : Number(args.limit),
821
+ includeArchived: args.include_archived === true,
822
+ }, env.signal);
823
+ bumpUsage(cfg, ['walk']);
824
+ return {
825
+ notebook: cfg.notebook,
826
+ ...(r.seed ? { seed: r.seed } : {}),
827
+ direction,
828
+ count: r.notes.length,
829
+ truncated: r.truncated,
830
+ completeness: r.completeness,
831
+ notes: r.notes,
832
+ };
833
+ },
834
+ render(args, value) {
835
+ const v = value;
836
+ if (!v.seed) {
837
+ return text(`没找到种子笔记:${String(args.path ?? '')}\n` +
838
+ '要写相对 / 绝对路径,或精确标题 / 稳定 id;不精确匹配时不猜(不会退回全库)');
839
+ }
840
+ const label = v.seed.title && v.seed.title !== v.seed.path ? `${v.seed.title} · ${v.seed.path}` : v.seed.path;
841
+ if (!v.count) {
842
+ return text(`「${label}」没有 ${v.direction === 'both' ? '入链或出链' : v.direction === 'in' ? '入链' : '出链'}邻居(笔记本 ${v.notebook})`);
843
+ }
844
+ const lines = v.notes.map((n, i) => {
845
+ const arrow = n.relation === 'in' ? '← 链向本篇' : '→ 本篇链到';
846
+ const detail = detailOf({ lead: n.lead });
847
+ // 先给「为什么这条边存在」,再给摘要:同一篇种子的出链摘要往往逐字相同
848
+ const why = n.linkLine || n.section
849
+ ? `\n ${n.section ? `〔${n.section}〕` : '〔无小节〕'} ${n.linkLine ?? ''}`.trimEnd()
850
+ : '';
851
+ return `${i + 1}. ${arrow} ${n.title || n.path}${why}\n ${n.absPath || n.path}${detail ? '\n ' + detail : ''}`;
852
+ });
853
+ const tail = v.truncated
854
+ ? '\n⚠️ 邻居没列全(触到 limit);这不代表只有这些,要提高 limit 再走一次'
855
+ : '';
856
+ return text(`${v.count} 篇 1 跳邻居(种子 ${label} · 笔记本 ${v.notebook})\n` + lines.join('\n') + tail);
857
+ },
858
+ }),
669
859
  t({
670
860
  name: 'zk_new',
671
861
  description: '新建一篇笔记(zk 负责生成文件名、套用模板、写入索引)。适合记下一个概念、决定、来源或想法;' +
@@ -1227,6 +1417,7 @@ export function buildTools(workspaceOf = () => processWorkspace()) {
1227
1417
  'incomplete 是 frontmatter 缺 type / status / authority 的笔记:缺失被索引落成空串,机械门会静默失效。' +
1228
1418
  'tags 查标签卫生(大小写变体 / 单例,标签总数 ≥ 30 才报);template 说根目录 AGENTS.md 是不是当前版本。' +
1229
1419
  'similarTitles 是「改一两个字」的疑似重复(同目录、二元组相似度 ≥ 0.6):与全等重名分开,只报告。' +
1420
+ 'missingId 是缺稳定 id 的非日记笔记数:zk_new 新建的笔记自动写 id,老笔记只提示、不回填。' +
1230
1421
  'timeline 是日记时间轴:最近 90 天的空块 / 倒序 / 格式(11:5x)/ 位置(layered 用 ##、或在 ## Events 外)问题,只报告不改文件。' +
1231
1422
  'total / counts 按全量算,items 里每篇最多 50 条明细,整个桶最多 50 篇;skipped 是过大或读不到而没检查的篇数。' +
1232
1423
  'indexHint=true 表示笔记(不含日记)已到 150 篇而根目录还没有 INDEX.md(只是提示,不生成静态索引)。' +
@@ -1251,6 +1442,7 @@ export function buildTools(workspaceOf = () => processWorkspace()) {
1251
1442
  schema: objSchema({
1252
1443
  notebook: { type: 'string' },
1253
1444
  notes: { type: 'number' },
1445
+ missingId: { type: 'number' },
1254
1446
  truncated: { type: 'boolean' },
1255
1447
  completeness: { type: 'string', enum: ['complete', 'partial', 'unknown'] },
1256
1448
  scanLimit: { type: 'number' },
@@ -1271,7 +1463,7 @@ export function buildTools(workspaceOf = () => processWorkspace()) {
1271
1463
  timeline: LINT_TIMELINE,
1272
1464
  indexHint: { type: 'boolean' },
1273
1465
  indexLag: { type: 'string' },
1274
- }, ['notebook', 'notes', 'truncated', 'completeness', 'scanLimit', 'staleDays', 'parseErrors', 'orphans', 'brokenLinks', 'stale', 'tagless', 'oneWayLinks', 'duplicateTitles', 'similarTitles', 'memoryLinks', 'incomplete', 'tags', 'template', 'persona', 'timeline', 'indexHint', 'indexLag']),
1466
+ }, ['notebook', 'notes', 'missingId', 'truncated', 'completeness', 'scanLimit', 'staleDays', 'parseErrors', 'orphans', 'brokenLinks', 'stale', 'tagless', 'oneWayLinks', 'duplicateTitles', 'similarTitles', 'memoryLinks', 'incomplete', 'tags', 'template', 'persona', 'timeline', 'indexHint', 'indexLag']),
1275
1467
  },
1276
1468
  async run(args, env) {
1277
1469
  const cfg = configFor(env.workspace, env.sessionId);
@@ -1355,6 +1547,7 @@ export function buildTools(workspaceOf = () => processWorkspace()) {
1355
1547
  'backlog 是窗口外仍未晋升的笔记(按被引数),漏做一次不会永久掉队。' +
1356
1548
  '库超过全图统计上限时不再建全图统计入链(默认 2000 篇,设置页可调;graphBudget 给出生效值):' +
1357
1549
  'graphSkipped=true,cited / citedBy / topCited 为空 —— 那是「没算」,不是「没人引」。' +
1550
+ 'missingId 是缺稳定 id 的非日记笔记数(只提示、不回填);MEMORY 里可以用 [[<id>]] 当来源,改名后仍指向同一篇。' +
1358
1551
  'memory 给记忆余量(内容词 + 提示 = 总词,余量按总词算,可以为负);retireCandidates 给「可考虑退役」的条目' +
1359
1552
  '(来源归档 / 不存在、超过 ' + STALE_DAYS + ' 天未复核;显式写 archive/ 的有意引用不算)。' +
1360
1553
  'days 省略时窗口 = 距 DREAMS.md「上次做梦」的天数(没有则 7 天)。' +
@@ -1376,6 +1569,7 @@ export function buildTools(workspaceOf = () => processWorkspace()) {
1376
1569
  scanLimit: { type: 'number' },
1377
1570
  graphSkipped: { type: 'boolean' },
1378
1571
  graphBudget: { type: 'number' },
1572
+ missingId: { type: 'number' },
1379
1573
  memory: objSchema({
1380
1574
  words: { type: 'number' },
1381
1575
  personaWords: { type: 'number' },
@@ -1441,7 +1635,7 @@ export function buildTools(workspaceOf = () => processWorkspace()) {
1441
1635
  reason: { type: 'string', enum: ['stale', 'source-missing', 'source-superseded'] },
1442
1636
  }, ['entry', 'date', 'age', 'reason']),
1443
1637
  },
1444
- }, ['notebook', 'windowDays', 'since', 'truncated', 'completeness', 'scanLimit', 'graphSkipped', 'graphBudget', 'memory', 'counts', 'newNotes', 'alreadyPromoted', 'backlog', 'rejected', 'topCited', 'dailyLooseEnds', 'retireCandidates']),
1638
+ }, ['notebook', 'windowDays', 'since', 'truncated', 'completeness', 'scanLimit', 'graphSkipped', 'graphBudget', 'missingId', 'memory', 'counts', 'newNotes', 'alreadyPromoted', 'backlog', 'rejected', 'topCited', 'dailyLooseEnds', 'retireCandidates']),
1445
1639
  },
1446
1640
  async run(args, env) {
1447
1641
  const cfg = configFor(env.workspace, env.sessionId);
@@ -1462,6 +1656,8 @@ export function buildTools(workspaceOf = () => processWorkspace()) {
1462
1656
  lines.push('记忆:内容 ' + v.memory.words + '/' + v.memory.budget + ' 词 + 提示 ' + promptWords +
1463
1657
  ' = ' + memoryTotal + ' 词(余 ' + v.memory.headroom + ')' +
1464
1658
  (v.memory.personaWords > 0 ? ' · 人格 ' + v.memory.personaWords + ' 词(单独注入,不计入记忆预算)' : ''));
1659
+ if (v.missingId > 0)
1660
+ lines.push('· 稳定 ID:' + v.missingId + ' 篇没有 id — 新笔记自动写入,老笔记只提示、不回填(§9.2)');
1465
1661
  if (v.retireCandidates.length) {
1466
1662
  lines.push('可考虑退役:');
1467
1663
  for (const c of v.retireCandidates.slice(0, 10)) {
@@ -1559,18 +1755,39 @@ export function buildTools(workspaceOf = () => processWorkspace()) {
1559
1755
  },
1560
1756
  completeness: { type: 'string', enum: ['complete', 'partial', 'unknown'] },
1561
1757
  scanLimit: { type: 'number' },
1562
- }, ['notebook', 'defaultNotebook', 'pinned', 'notes', 'tags', 'brokenLinks', 'orphans', 'archived', 'superseded', 'byDir', 'byTag', 'completeness', 'scanLimit']),
1758
+ /** 本地聚合计数(plan §14.4):只看「入口 / 一跳」这条路有没有被用上,不记查询词 */
1759
+ usage: objSchema({
1760
+ since: { type: 'string' },
1761
+ search: { type: 'number' },
1762
+ query: { type: 'number' },
1763
+ recall: { type: 'number' },
1764
+ walk: { type: 'number' },
1765
+ entryPoints: { type: 'number' },
1766
+ counterEntries: { type: 'number' },
1767
+ }, ['since', 'search', 'query', 'recall', 'walk', 'entryPoints', 'counterEntries']),
1768
+ }, ['notebook', 'defaultNotebook', 'pinned', 'notes', 'tags', 'brokenLinks', 'orphans', 'archived', 'superseded', 'byDir', 'byTag', 'completeness', 'scanLimit', 'usage']),
1563
1769
  },
1564
1770
  async run(_args, env) {
1565
1771
  const cfg = configFor(env.workspace, env.sessionId);
1566
1772
  await ensureNotebook(cfg, env.signal);
1567
1773
  const stats = await notebookStats(cfg, env.signal);
1568
1774
  const state = sessionState(env.workspace, env.sessionId);
1775
+ const usage = readUsage(cfg);
1776
+ const count = (key) => usage.counts[key] ?? 0;
1569
1777
  return {
1570
1778
  notebook: cfg.notebook,
1571
1779
  defaultNotebook: state.defaultName,
1572
1780
  pinned: state.diverged ? state.pinned : '',
1573
1781
  ...stats,
1782
+ usage: {
1783
+ since: usage.since,
1784
+ search: count('search'),
1785
+ query: count('query'),
1786
+ recall: count('recall'),
1787
+ walk: count('walk'),
1788
+ entryPoints: count('entryPoints'),
1789
+ counterEntries: count('counterEntries'),
1790
+ },
1574
1791
  };
1575
1792
  },
1576
1793
  render(_args, value) {
@@ -1588,9 +1805,13 @@ export function buildTools(workspaceOf = () => processWorkspace()) {
1588
1805
  const partial = v.completeness === 'partial'
1589
1806
  ? `\n⚠️ 只扫描了前 ${v.scanLimit} 篇:上面的数字是下限`
1590
1807
  : v.completeness === 'unknown' ? '\n⚠️ 扫描结果无法完整解析:上面的数字可能偏少' : '';
1808
+ const usage = v.usage && (v.usage.walk || v.usage.entryPoints || v.usage.counterEntries || v.usage.recall)
1809
+ ? `\n入口 / 一跳:walk ${v.usage.walk} 次 · 召回 ${v.usage.recall} 次 · 入口回显 ${v.usage.entryPoints} 次 · 死胡同提醒 ${v.usage.counterEntries} 次` +
1810
+ (v.usage.since ? `(自 ${v.usage.since.slice(0, 10)})` : '')
1811
+ : '\n入口 / 一跳:还没有计数(zk_walk / zk_recall / 入口与死胡同提醒都没被用过)';
1591
1812
  return text(`笔记本 ${v.notebook}${drift}\n` +
1592
1813
  `笔记 ${atLeast}${v.notes} 篇 · 标签 ${atLeast}${v.tags} 个 · 断链 ${v.brokenLinks} 篇 · 孤立 ${v.orphans} 篇 · 归档 ${atLeast}${v.archived} 篇(superseded ${atLeast}${v.superseded})` +
1593
- dirs + tags + partial);
1814
+ dirs + tags + partial + usage);
1594
1815
  },
1595
1816
  }),
1596
1817
  t({
@@ -13,12 +13,12 @@
13
13
  *
14
14
  * 长度是设计约束:AGENTS.md 属于注入预算(默认 500 词,中文 2 字 = 1 词)且**永不截断**,
15
15
  * 模板自己吃掉过半预算,USER / MEMORY 就没位置了 —— 所以这里只留规则,不写教程。
16
- * 目标 ≤190 词(AGENTS_TEMPLATE 实测 180、AGENTS_TEMPLATE_FLAT 实测 80),单测里锁住。
16
+ * 目标 ≤190 词(AGENTS_TEMPLATE 实测 190、AGENTS_TEMPLATE_FLAT 实测 88),单测里锁住。
17
17
  * 首行 `<!-- zdiary-template: vN -->` 是版本标记:lint 据此报告「老库的 AGENTS.md 是旧版」,
18
18
  * 只报告不覆盖(模板允许用户改)。
19
19
  */
20
- /** 模板版本:改模板就 +1;lint 用它判断老库是否还在用旧模板(v9:改 MEMORY 前看 zk_context 余量) */
21
- export const TEMPLATE_VERSION = 9;
20
+ /** 模板版本:改模板就 +1;lint 用它判断老库是否还在用旧模板(v10:写之前加 zk_walk 一跳) */
21
+ export const TEMPLATE_VERSION = 10;
22
22
  /** 首行版本标记(实测 4 词);不许带日期 —— 带日期的写法实测 6 词,白花 2 词 */
23
23
  export const TEMPLATE_MARK = `<!-- zdiary-template: v${TEMPLATE_VERSION} -->`;
24
24
  /** 版本标记的正则(本文件内用;外部只通过 `templateVersionOf` 取数,免得又一个口径) */
@@ -38,6 +38,7 @@ export function templateVersionOf(body) {
38
38
  export const TEMPLATE_SENTINELS = {
39
39
  8: { required: ['先 read 核对来源'], forbidden: ['DSH 不会自动加载', '从底部往前丢'] },
40
40
  9: { required: ['先 read 核对来源', '改 MEMORY 前看 zk_context'], forbidden: ['DSH 不会自动加载', '从底部往前丢'] },
41
+ 10: { required: ['先 read 核对来源', '改 MEMORY 前看 zk_context', 'zk_walk'], forbidden: ['DSH 不会自动加载', '从底部往前丢'] },
41
42
  };
42
43
  export const AGENTS_TEMPLATE = `${TEMPLATE_MARK}
43
44
 
@@ -55,7 +56,7 @@ notes/{concepts,entities,patterns}/ 原子笔记 · archive/ 废弃(不删)
55
56
 
56
57
  ## 写之前
57
58
 
58
- 1. zk_query / zk_search 查重(中文查 tags)。
59
+ 1. zk_query / zk_search 查重,zk_walk 一跳(中文查 tags)。
59
60
  2. 一条笔记一件事,标题即结论;文件名用 zk_new 的 name(8–14 字);来源给 type=source、结论给 type=concept(目录跟 type 走,别落 notes/ 根),zk_link 相连。
60
61
  3. 结论过时用 zk_supersede(默认预演,带 reason):不删文件、不改旧结论。
61
62
  4. 改已有笔记前读 WORKFLOW.md:先列清单等确认,再按三分类动手。
@@ -77,7 +78,7 @@ export const AGENTS_TEMPLATE_FLAT = `${TEMPLATE_MARK}
77
78
 
78
79
  ## 写之前
79
80
 
80
- 1. zk_search 查重;中文必打 tags(FTS 不切中文)。
81
+ 1. zk_search 查重,zk_walk 一跳;中文必打 tags(FTS 不切中文)。
81
82
  2. 一笔记一件事,标题即结论;文件名 8–14 字。
82
83
  3. 结论过时用 zk_supersede(默认预演,带 reason)。
83
84