dsh-zdiary-kit 3.8.0 → 3.10.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 的公共入口):16 个内置工具 + `[alias]` 别名工具,全部经 lib/zk.ts。
3
3
  *
4
4
  * 设计要点:
5
5
  * · 除 zk_context(只读 meta 文件,不依赖 zk)外,每个工具进来先 ensureNotebook —— 第一次调用就自动建好笔记本,用户不用先点设置页;
@@ -15,10 +15,16 @@ 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, scanNotes, 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';
25
+ import { bumpRecall } from '../../lib/recall-signal.js';
26
+ import { wikiIndex } from '../../lib/wikilink.js';
27
+ import { writeMemory } from '../../lib/memory-write.js';
22
28
  import { META_NAMES } from '../../lib/meta.js';
23
29
  import { formatLintExtras, formatMemoryLinks, lintNotebook } from '../../lib/lint.js';
24
30
  import { dreamNotebook, STALE_DAYS } from '../../lib/dream.js';
@@ -39,6 +45,26 @@ const objSchema = (properties, required) => ({
39
45
  });
40
46
  /** lint 输出的三个共用形状(每类最多 50 条 + 总数) */
41
47
  const LINT_ENTRY = objSchema({ title: { type: 'string' }, path: { type: 'string' } }, ['title', 'path']);
48
+ /** R9:MEMORY.md 的活条目 → 入口(`via: query` 的来源可以不在本次结果里) */
49
+ const ENTRY_POINT = objSchema({
50
+ entry: { type: 'string' },
51
+ title: { type: 'string' },
52
+ path: { type: 'string' },
53
+ absPath: { type: 'string' },
54
+ via: { type: 'string', enum: ['query', 'result'] },
55
+ /** false = 标题 / id 写法且不在本批结果里:只有入口名,落地交给 zk_walk */
56
+ resolved: { type: 'boolean' },
57
+ }, ['entry', 'title', 'via', 'resolved']);
58
+ /** 死胡同探针:归档里同名的废弃结论(不是第二份结果列表) */
59
+ const COUNTER_ENTRY = objSchema({
60
+ matched: { type: 'string' },
61
+ title: { type: 'string' },
62
+ path: { type: 'string' },
63
+ absPath: { type: 'string' },
64
+ reason: { type: 'string' },
65
+ supersededBy: { type: 'string' },
66
+ score: { type: 'number' },
67
+ }, ['matched', 'title', 'path', 'absPath', 'reason', 'supersededBy', 'score']);
42
68
  const LINT_BUCKET = objSchema({ total: { type: 'number' }, items: { type: 'array', items: LINT_ENTRY } }, ['total', 'items']);
43
69
  const LINT_ONE_WAY_ITEM = objSchema({
44
70
  title: { type: 'string' },
@@ -270,9 +296,14 @@ function withElsewhere(err, cfg, workspace, rel) {
270
296
  function tagSuffix(record) {
271
297
  return record.tags.length ? ' · ' + record.tags.map((t) => '#' + t).join(' ') : '';
272
298
  }
273
- /** R2:snippet 比 lead 多带命中上下文时才替换它,否则维持原输出 */
299
+ /** 15.6:先用 summary(## Summary 首段),空串再按 R2 口径退回 snippet / lead */
274
300
  function detailOf(n) {
275
- return n.snippet && n.snippet !== n.lead ? n.snippet : (n.lead ?? '');
301
+ return n.summary || (n.snippet && n.snippet !== n.lead ? n.snippet : (n.lead ?? ''));
302
+ }
303
+ /** 死胡同提醒(措辞与 `zk-kit search` 共用一份);没有就一个字都不加 */
304
+ function counterBlockOf(entries, truncated, zeroHit) {
305
+ const body = describeCounterEntries({ entries: entries ?? [], truncated: truncated === true }, { zeroHit });
306
+ return body ? '\n\n' + body : '';
276
307
  }
277
308
  function noteLine(n, index) {
278
309
  const head = `${index + 1}. ${n.title || n.path}`;
@@ -378,7 +409,9 @@ export function buildTools(workspaceOf = () => processWorkspace()) {
378
409
  description: '在 zk 知识库里搜索笔记(全文 / 标签 / 日期 / 断链 / 孤立笔记),返回标题、相对路径、绝对路径、标签、创建日、摘要与命中片段。' +
379
410
  '找到后用原生 read 读全文:notes[].absPath 可以直接传给 read。写笔记前先用它查重。' +
380
411
  '中文会自动并用子串,多词按覆盖度合并(FTS 不切中文):matchStrategy 说明这次用了 fts / regex / mixed,mixed 表示补到了全文索引漏掉的笔记。' +
381
- '有 query 时默认按 FTS 相关性排序,显式给 sort 才改顺序。',
412
+ '有 query 时默认按 FTS 相关性排序,显式给 sort 才改顺序。' +
413
+ '结果还带 entryPoints(MEMORY 的活条目:via=query 表示这条结论跟查询有关,来源可以不在本次结果里)' +
414
+ '与 counterEntries(归档里同名旧结论 + 废弃原因,先看它别把废掉的结论重新提出来)。',
382
415
  parameters: {
383
416
  type: 'object',
384
417
  properties: {
@@ -413,17 +446,27 @@ export function buildTools(workspaceOf = () => processWorkspace()) {
413
446
  created: { type: 'string' },
414
447
  lead: { type: 'string' },
415
448
  words: { type: 'number' },
449
+ /** 15.6:`## Summary` 首段 / frontmatter summary;老笔记为空串 */
450
+ summary: { type: 'string' },
416
451
  /** 命中片段,没有时整个键不出现(避免 undefined 让宿主判 invalid output) */
417
452
  snippet: { type: 'string' },
418
453
  }, ['title', 'path', 'absPath', 'tags', 'created', 'lead']),
419
454
  },
455
+ /** R9:只在有命中且 MEMORY 里有对应活条目时出现 */
456
+ entryPoints: { type: 'array', items: ENTRY_POINT },
457
+ /** 入口超过上限时出现(true),不静默少列 */
458
+ entryPointsTruncated: { type: 'boolean' },
459
+ /** 死胡同探针:归档里同名的废弃结论(零子进程;只提示,不改结果集) */
460
+ counterEntries: { type: 'array', items: COUNTER_ENTRY },
461
+ counterEntriesTruncated: { type: 'boolean' },
420
462
  }, ['notebook', 'count', 'matchStrategy', 'completeness', 'hasMore', 'scanned', 'notes']),
421
463
  },
422
464
  async run(args, env) {
423
465
  const cfg = configFor(env.workspace, env.sessionId);
424
466
  await ensureNotebook(cfg);
467
+ const query = args.query ? String(args.query) : undefined;
425
468
  const result = await searchNotesDetailed(cfg, {
426
- query: args.query ? String(args.query) : undefined,
469
+ query,
427
470
  tags: Array.isArray(args.tags) ? args.tags.map(String) : undefined,
428
471
  since: args.since ? String(args.since) : undefined,
429
472
  until: args.until ? String(args.until) : undefined,
@@ -433,6 +476,16 @@ export function buildTools(workspaceOf = () => processWorkspace()) {
433
476
  // R1:有 query 且没显式给 sort → relevance(不传 --sort,保住 FTS 相关性顺序)
434
477
  sort: args.sort ? String(args.sort) : (args.query ? 'relevance' : 'created-desc'),
435
478
  });
479
+ // R9:查询命中的 MEMORY 条目 → 入口(来源可以不在本批结果里);先只读,不新增 zk 进程
480
+ const { points: entryPoints, truncated: entryPointsTruncated } = entryPointsOf(cfg, result.notes, { query });
481
+ const counters = archivedCounterparts(cfg, result.notes, { query });
482
+ bumpUsage(cfg, [
483
+ 'search',
484
+ ...(entryPoints.length ? ['entryPoints'] : []),
485
+ ...(counters.entries.length ? ['counterEntries'] : []),
486
+ ]);
487
+ // 15.2:只记 path / 日期 / 检索种类,不记查询词;默认关时零写入
488
+ bumpRecall(cfg, result.notes.map((n) => ({ path: n.path, title: n.title })), 'search');
436
489
  return {
437
490
  notebook: cfg.notebook,
438
491
  count: result.notes.length,
@@ -443,17 +496,22 @@ export function buildTools(workspaceOf = () => processWorkspace()) {
443
496
  ...(result.total === undefined ? {} : { total: result.total }),
444
497
  notes: result.notes.map((n) => ({
445
498
  title: n.title, path: n.path, absPath: n.absPath, tags: n.tags,
446
- created: dateOnly(n.created), lead: n.lead, words: n.words,
499
+ created: dateOnly(n.created), lead: n.lead, words: n.words, summary: n.summary,
447
500
  ...(n.snippet ? { snippet: n.snippet } : {}),
448
501
  })),
502
+ ...(entryPoints.length ? { entryPoints } : {}),
503
+ ...(entryPointsTruncated ? { entryPointsTruncated } : {}),
504
+ ...(counters.entries.length ? { counterEntries: counters.entries } : {}),
505
+ ...(counters.truncated ? { counterEntriesTruncated: true } : {}),
449
506
  };
450
507
  },
451
508
  render(args, value) {
452
509
  const v = value;
510
+ const counters = counterBlockOf(v.counterEntries, v.counterEntriesTruncated, v.count === 0);
453
511
  if (!v.count) {
454
512
  return text(`没有匹配的笔记(笔记本 ${v.notebook})` +
455
513
  zeroHitHint(args, '或按 tags 查') +
456
- (v.completeness === 'unknown' ? ';但这次检索结果无法完整解析,不能当作「库里没有」' : ''));
514
+ (v.completeness === 'unknown' ? ';但这次检索结果无法完整解析,不能当作「库里没有」' : '') + entryPointLines(v.entryPoints, { truncated: v.entryPointsTruncated }) + counters);
457
515
  }
458
516
  const how = v.matchStrategy === 'mixed'
459
517
  ? '(中文:全文 + 子串合并,已补上全文索引漏掉的)'
@@ -461,7 +519,8 @@ export function buildTools(workspaceOf = () => processWorkspace()) {
461
519
  const tail = v.completeness === 'unknown'
462
520
  ? '\n⚠️ 无法确认结果是否完整(解析失败 / 补充检索失败),先别把它当成全部命中'
463
521
  : v.hasMore ? `\n⚠️ 还有更多匹配没返回(已检查 ${v.scanned} 条候选);要更全就提高 limit 或加过滤条件` : '';
464
- return text(`${v.count} 条(笔记本 ${v.notebook})${how}\n` + v.notes.map(noteLine).join('\n') + tail);
522
+ return text(`${v.count} 条(笔记本 ${v.notebook})${how}\n` + v.notes.map(noteLine).join('\n') +
523
+ entryPointLines(v.entryPoints, { truncated: v.entryPointsTruncated }) + tail + counters);
465
524
  },
466
525
  }),
467
526
  t({
@@ -469,7 +528,7 @@ export function buildTools(workspaceOf = () => processWorkspace()) {
469
528
  description: '结构化检索记忆:按 type(daily/source/concept/entity/pattern)、status(active/superseded)、标签、目录、日期、断链、孤立过滤。' +
470
529
  '默认只看 active 且不含归档;传 include_archived: true 会连归档一起查,此时未显式给 status 就不再默认过滤 active。' +
471
530
  '中文会自动并用子串,多词按覆盖度合并;有 query 时默认按 FTS 相关性排序。' +
472
- '这是查「记忆里有什么」的主入口。',
531
+ '这是查「记忆里有什么」的主入口。entryPoints / counterEntries 与 zk_search 同口径。',
473
532
  parameters: {
474
533
  type: 'object',
475
534
  properties: {
@@ -510,18 +569,28 @@ export function buildTools(workspaceOf = () => processWorkspace()) {
510
569
  created: { type: 'string' },
511
570
  lead: { type: 'string' },
512
571
  words: { type: 'number' },
572
+ /** 15.6:`## Summary` 首段 / frontmatter summary;老笔记为空串 */
573
+ summary: { type: 'string' },
513
574
  snippet: { type: 'string' },
514
575
  archived: { type: 'boolean' },
515
576
  }, ['title', 'path', 'absPath', 'type', 'status', 'authority', 'tags', 'created', 'lead', 'archived']),
516
577
  },
578
+ /** R9:只在有命中且 MEMORY 里有对应活条目时出现 */
579
+ entryPoints: { type: 'array', items: ENTRY_POINT },
580
+ /** 入口超过上限时出现(true),不静默少列 */
581
+ entryPointsTruncated: { type: 'boolean' },
582
+ /** 死胡同探针:归档里同名的废弃结论(include_archived 时不重复报) */
583
+ counterEntries: { type: 'array', items: COUNTER_ENTRY },
584
+ counterEntriesTruncated: { type: 'boolean' },
517
585
  }, ['notebook', 'count', 'completeness', 'hasMore', 'scanned', 'notes']),
518
586
  },
519
587
  async run(args, env) {
520
588
  const cfg = configFor(env.workspace, env.sessionId);
521
589
  await ensureNotebook(cfg, env.signal);
522
590
  const includeArchived = args.include_archived === true;
591
+ const query = args.query ? String(args.query) : undefined;
523
592
  const result = await searchNotesDetailed(cfg, {
524
- query: args.query ? String(args.query) : undefined,
593
+ query,
525
594
  tags: Array.isArray(args.tags) ? args.tags.map(String) : undefined,
526
595
  paths: Array.isArray(args.dirs) ? args.dirs.map(String) : undefined,
527
596
  type: args.type ? [String(args.type)] : undefined,
@@ -537,6 +606,17 @@ export function buildTools(workspaceOf = () => processWorkspace()) {
537
606
  sort: args.sort ? String(args.sort) : (args.query ? 'relevance' : 'created-desc'),
538
607
  }, env.signal);
539
608
  const notes = result.notes;
609
+ // R9:与 zk_search 共用同一份计算(查询命中的来源可以不在本批结果里;零子进程)
610
+ const { points: entryPoints, truncated: entryPointsTruncated } = entryPointsOf(cfg, notes, { query });
611
+ const counters = includeArchived
612
+ ? { entries: [], scanned: 0, truncated: false }
613
+ : archivedCounterparts(cfg, notes, { query });
614
+ bumpUsage(cfg, [
615
+ 'query',
616
+ ...(entryPoints.length ? ['entryPoints'] : []),
617
+ ...(counters.entries.length ? ['counterEntries'] : []),
618
+ ]);
619
+ bumpRecall(cfg, notes.map((n) => ({ path: n.path, title: n.title })), 'query');
540
620
  return {
541
621
  notebook: cfg.notebook,
542
622
  count: notes.length,
@@ -556,27 +636,34 @@ export function buildTools(workspaceOf = () => processWorkspace()) {
556
636
  created: dateOnly(n.created),
557
637
  lead: n.lead,
558
638
  words: n.words,
639
+ summary: n.summary,
559
640
  ...(n.snippet ? { snippet: n.snippet } : {}),
560
641
  archived: n.path.startsWith(cfg.archiveDir + '/'),
561
642
  })),
643
+ ...(entryPoints.length ? { entryPoints } : {}),
644
+ ...(entryPointsTruncated ? { entryPointsTruncated } : {}),
645
+ ...(counters.entries.length ? { counterEntries: counters.entries } : {}),
646
+ ...(counters.truncated ? { counterEntriesTruncated: true } : {}),
562
647
  };
563
648
  },
564
649
  render(args, value) {
565
650
  const v = value;
651
+ const counters = counterBlockOf(v.counterEntries, v.counterEntriesTruncated, v.count === 0);
566
652
  if (!v.count) {
567
653
  return text(`没有匹配的笔记(笔记本 ${v.notebook})` +
568
654
  zeroHitHint(args, '或给 tags 参数按标签查') +
569
- (v.completeness === 'unknown' ? ';但这次检索结果无法完整解析,不能当作「记忆里没有」' : ''));
655
+ (v.completeness === 'unknown' ? ';但这次检索结果无法完整解析,不能当作「记忆里没有」' : '') + entryPointLines(v.entryPoints, { truncated: v.entryPointsTruncated }) + counters);
570
656
  }
571
657
  const tail = v.completeness === 'unknown'
572
658
  ? '\n⚠️ 无法确认结果是否完整(解析失败 / 补充检索失败),先别把它当成全部命中'
573
659
  : v.hasMore ? `\n⚠️ 还有更多匹配没返回(已检查 ${v.scanned} 条候选);要更全就提高 limit 或缩小过滤范围` : '';
574
660
  const lines = v.notes.map((n, i) => {
575
661
  const badges = [String(n.type || '—'), String(n.status || 'no-status'), n.archived ? '已归档' : ''].filter(Boolean);
576
- const detail = detailOf({ lead: String(n.lead ?? ''), snippet: String(n.snippet ?? '') });
662
+ const detail = detailOf({ summary: String(n.summary ?? ''), lead: String(n.lead ?? ''), snippet: String(n.snippet ?? '') });
577
663
  return `${i + 1}. ${String(n.title)} [${badges.join(' · ')}]\n ${String(n.absPath || n.path)} · ${String(n.created)}${detail ? '\n ' + detail : ''}`;
578
664
  });
579
- return text(`${v.count} 条(笔记本 ${v.notebook})\n` + lines.join('\n') + tail);
665
+ return text(`${v.count} 条(笔记本 ${v.notebook})\n` + lines.join('\n') +
666
+ entryPointLines(v.entryPoints, { truncated: v.entryPointsTruncated }) + tail + counters);
580
667
  },
581
668
  }),
582
669
  t({
@@ -617,11 +704,23 @@ export function buildTools(workspaceOf = () => processWorkspace()) {
617
704
  title: { type: 'string' },
618
705
  path: { type: 'string' },
619
706
  absPath: { type: 'string' },
707
+ /** 15.6:`## Summary` 首段 / frontmatter summary;老笔记为空串 */
708
+ summary: { type: 'string' },
620
709
  included: { type: 'boolean' },
621
710
  reason: { type: 'string', enum: ['included', 'duplicate', 'empty', 'over-budget'] },
622
711
  }, ['title', 'path', 'absPath', 'included', 'reason']),
623
712
  },
624
- }, ['notebook', 'text', 'used', 'budget', 'completeness', 'hasMore', 'notes']),
713
+ /** R9:与 zk_search / zk_query 共用同一份计算(没有就是空数组,不另算) */
714
+ entryPoints: { type: 'array', items: ENTRY_POINT },
715
+ /** 入口超过上限(true),不静默少列 */
716
+ entryPointsTruncated: { type: 'boolean' },
717
+ /** true = via=query 的入口已写进 text(占同一份预算);false 时正文里没有它们 */
718
+ entryPointsInText: { type: 'boolean' },
719
+ /** 死胡同探针:归档里同名的废弃结论 */
720
+ counterEntries: { type: 'array', items: COUNTER_ENTRY },
721
+ counterEntriesTruncated: { type: 'boolean' },
722
+ }, ['notebook', 'text', 'used', 'budget', 'completeness', 'hasMore', 'notes',
723
+ 'entryPoints', 'entryPointsTruncated', 'counterEntries', 'counterEntriesTruncated']),
625
724
  },
626
725
  async run(args, env) {
627
726
  const cfg = configFor(env.workspace, env.sessionId);
@@ -648,24 +747,128 @@ export function buildTools(workspaceOf = () => processWorkspace()) {
648
747
  const v = value;
649
748
  const kept = v.notes.filter((n) => n.included).length;
650
749
  const dropped = v.notes.length - kept;
750
+ const counters = counterBlockOf(v.counterEntries, v.counterEntriesTruncated, v.notes.length === 0);
651
751
  if (!v.notes.length) {
652
752
  return text(`没有匹配的笔记(笔记本 ${v.notebook})` +
653
753
  zeroHitHint(args, '或按 tags 查') +
654
- (v.completeness === 'unknown' ? ';但这次检索结果无法完整解析,不能当作「库里没有」' : ''));
754
+ (v.completeness === 'unknown' ? ';但这次检索结果无法完整解析,不能当作「库里没有」' : '') + entryPointLines(v.entryPoints, { truncated: v.entryPointsTruncated }) + counters);
655
755
  }
656
756
  const lines = [`召回装配:${v.used}/${v.budget} 词 · 收录 ${kept}/${v.notes.length} 篇(笔记本 ${v.notebook})`];
657
757
  if (v.text)
658
758
  lines.push('', v.text);
659
759
  if (dropped)
660
760
  lines.push(`(${dropped} 篇没放进去:整条丢弃,没有切半句;原因见 notes[].reason)`);
761
+ // `via: 'query'` 的入口已经写进 text(排在装配正文之前);只有预算放不下时才会在这里补回。
762
+ // 状态取自 assembleRecall 的 `entryPointsInText`,不从 text 里嗅字符串 —— 笔记正文也可能含那串字。
763
+ const points = entryPointLines(v.entryPoints, {
764
+ truncated: v.entryPointsTruncated,
765
+ skipQuery: v.entryPointsInText,
766
+ });
767
+ if (points)
768
+ lines.push(points.trimStart());
661
769
  const tail = v.completeness === 'unknown'
662
770
  ? '⚠️ 无法确认结果是否完整(解析失败 / 补充检索失败),先别把它当成全部命中'
663
771
  : v.hasMore ? '⚠️ 还有更多匹配没返回;要提高 limit 或缩小过滤范围' : '';
664
772
  if (tail)
665
773
  lines.push(tail);
774
+ if (counters)
775
+ lines.push(counters.trimStart());
666
776
  return text(lines.join('\n'));
667
777
  },
668
778
  }),
779
+ t({
780
+ name: 'zk_walk',
781
+ description: '从一篇笔记出发走一跳邻居(只读):direction=both 同时看反链与出链,in=谁链到它,out=它链到谁。' +
782
+ '种子写相对笔记本的路径、绝对路径,或精确标题 / 稳定 id([[标题]] / [[id]] 也认);不精确命中就返回空,不会退回全库。' +
783
+ '按篇反查、不建全图,成本与库规模基本无关;limit 硬顶 200,触顶 completeness=partial(邻居没列全,不代表没有)。' +
784
+ '每条邻居带 section / linkLine:那条边所在的小节与那一行 —— 没有它,同一篇种子的出链只有一串标题。' +
785
+ '只回标题 / 路径 / absPath / 摘要 / 那一行,全文仍用原生 read 读 absPath;不改标题、不自动 link、不写任何文件。',
786
+ parameters: {
787
+ type: 'object',
788
+ properties: {
789
+ path: S.str('种子笔记:相对笔记本的路径、绝对路径,或精确标题 / 稳定 id(也认 [[标题]] / [[id]])'),
790
+ direction: S.enum('走哪个方向:both 反链 + 出链,in 只看谁链到它,out 只看它链到谁(默认 both)', ['both', 'in', 'out']),
791
+ limit: S.num('每个方向最多几条(1-200,默认 10)'),
792
+ include_archived: S.bool('连 archive/ 里的废弃笔记一起看(默认 false)'),
793
+ },
794
+ required: ['path'],
795
+ additionalProperties: false,
796
+ },
797
+ output: {
798
+ schema: objSchema({
799
+ notebook: { type: 'string' },
800
+ /** 种子解析失败时整个键不出现(null 过不了 object 校验,不拿空对象冒充) */
801
+ seed: objSchema({ title: { type: 'string' }, path: { type: 'string' }, absPath: { type: 'string' } }, ['title', 'path', 'absPath']),
802
+ direction: { type: 'string', enum: ['both', 'in', 'out'] },
803
+ count: { type: 'number' },
804
+ truncated: { type: 'boolean' },
805
+ /** 只有 complete / partial:按篇反查没有产生 unknown 的路径 */
806
+ completeness: { type: 'string', enum: ['complete', 'partial'] },
807
+ notes: {
808
+ type: 'array',
809
+ items: objSchema({
810
+ title: { type: 'string' },
811
+ path: { type: 'string' },
812
+ absPath: { type: 'string' },
813
+ relation: { type: 'string', enum: ['in', 'out'] },
814
+ lead: { type: 'string' },
815
+ /** 这条边所在的 `##` / `###` 小节;找不到时键不出现(plan §14.1) */
816
+ section: { type: 'string' },
817
+ /** 这条边的那一行(压空白、截 160 码点):没有它,同一篇种子的出链长得一模一样 */
818
+ linkLine: { type: 'string' },
819
+ }, ['title', 'path', 'absPath', 'relation', 'lead']),
820
+ },
821
+ }, ['notebook', 'direction', 'count', 'truncated', 'completeness', 'notes']),
822
+ },
823
+ async run(args, env) {
824
+ const cfg = configFor(env.workspace, env.sessionId);
825
+ await ensureNotebook(cfg, env.signal);
826
+ const seed = args.path === undefined || args.path === null ? '' : String(args.path);
827
+ if (!seed.trim())
828
+ throw new ZkError('种子不能为空', '给 path:相对笔记本的路径,或精确标题 / id');
829
+ const direction = (args.direction === undefined ? 'both' : String(args.direction));
830
+ const r = await walkFrom(cfg, {
831
+ seed,
832
+ direction,
833
+ limit: args.limit === undefined ? 10 : Number(args.limit),
834
+ includeArchived: args.include_archived === true,
835
+ }, env.signal);
836
+ bumpUsage(cfg, ['walk']);
837
+ return {
838
+ notebook: cfg.notebook,
839
+ ...(r.seed ? { seed: r.seed } : {}),
840
+ direction,
841
+ count: r.notes.length,
842
+ truncated: r.truncated,
843
+ completeness: r.completeness,
844
+ notes: r.notes,
845
+ };
846
+ },
847
+ render(args, value) {
848
+ const v = value;
849
+ if (!v.seed) {
850
+ return text(`没找到种子笔记:${String(args.path ?? '')}\n` +
851
+ '要写相对 / 绝对路径,或精确标题 / 稳定 id;不精确匹配时不猜(不会退回全库)');
852
+ }
853
+ const label = v.seed.title && v.seed.title !== v.seed.path ? `${v.seed.title} · ${v.seed.path}` : v.seed.path;
854
+ if (!v.count) {
855
+ return text(`「${label}」没有 ${v.direction === 'both' ? '入链或出链' : v.direction === 'in' ? '入链' : '出链'}邻居(笔记本 ${v.notebook})`);
856
+ }
857
+ const lines = v.notes.map((n, i) => {
858
+ const arrow = n.relation === 'in' ? '← 链向本篇' : '→ 本篇链到';
859
+ const detail = detailOf({ lead: n.lead });
860
+ // 先给「为什么这条边存在」,再给摘要:同一篇种子的出链摘要往往逐字相同
861
+ const why = n.linkLine || n.section
862
+ ? `\n ${n.section ? `〔${n.section}〕` : '〔无小节〕'} ${n.linkLine ?? ''}`.trimEnd()
863
+ : '';
864
+ return `${i + 1}. ${arrow} ${n.title || n.path}${why}\n ${n.absPath || n.path}${detail ? '\n ' + detail : ''}`;
865
+ });
866
+ const tail = v.truncated
867
+ ? '\n⚠️ 邻居没列全(触到 limit);这不代表只有这些,要提高 limit 再走一次'
868
+ : '';
869
+ return text(`${v.count} 篇 1 跳邻居(种子 ${label} · 笔记本 ${v.notebook})\n` + lines.join('\n') + tail);
870
+ },
871
+ }),
669
872
  t({
670
873
  name: 'zk_new',
671
874
  description: '新建一篇笔记(zk 负责生成文件名、套用模板、写入索引)。适合记下一个概念、决定、来源或想法;' +
@@ -1217,6 +1420,122 @@ export function buildTools(workspaceOf = () => processWorkspace()) {
1217
1420
  return text(drift + head + persona + totals + capacity + (v.text ? '\n\n' + v.text : ''));
1218
1421
  },
1219
1422
  }),
1423
+ t({
1424
+ name: 'zk_memory_write',
1425
+ description: '写记忆的第一个工具:往 MEMORY.md / USER.md 末尾追加一条结论。默认 dry_run: true,只预演、不动盘;' +
1426
+ '确认后传 dry_run: false 才真写(可把预演返回的 stamp 放进 expect_stamp,挡住「预演之后有人改过」)。' +
1427
+ '调用方给完整条目正文,插件只做机械门:必须是一条带 YYYY-MM-DD 与 [[来源]] 的顶层列表项、来源要解析到活笔记、' +
1428
+ '新增不能让注入载荷超预算(超了给结构化错误 + dropCandidates,绝不静默截断)。' +
1429
+ 'action: retire 追加 `- [superseded …]` 标记(退役条目不进注入,不做容量门)。' +
1430
+ '不替换、不合并、不自动补日期 / 来源、不提议退役哪条 —— 语义判断全归调用方;' +
1431
+ '每次真实写入把 pre-image 摘要与一行 diff 追加到 DREAMS.md 供周审复核。' +
1432
+ '想改已有条目仍用原生 edit;本工具只往末尾追加。',
1433
+ parameters: {
1434
+ type: 'object',
1435
+ properties: {
1436
+ target: S.enum('写哪份:MEMORY 或 USER(根目录 MEMORY.md / USER.md)', ['MEMORY', 'USER']),
1437
+ action: S.enum('add(默认)= 追加一条现行结论;retire = 追加一条退役标记', ['add', 'retire']),
1438
+ entry: S.str('完整条目正文,例:`- **结论。** 2026-11-12(来源:[[笔记标题]])`;插件不改一个字'),
1439
+ dry_run: S.bool('true(默认)= 只预演、不改盘;false = 真的写'),
1440
+ expect_stamp: S.str('可选:预演返回的 stamp,带回来挡并发改动'),
1441
+ },
1442
+ required: ['entry'],
1443
+ additionalProperties: false,
1444
+ },
1445
+ output: {
1446
+ schema: objSchema({
1447
+ notebook: { type: 'string' },
1448
+ accepted: { type: 'boolean' },
1449
+ rejection: { type: 'string' },
1450
+ detail: { type: 'string' },
1451
+ target: { type: 'string' },
1452
+ action: { type: 'string', enum: ['add', 'retire'] },
1453
+ dryRun: { type: 'boolean' },
1454
+ performed: { type: 'boolean' },
1455
+ source: { type: 'string' },
1456
+ sourceTarget: { type: 'string' },
1457
+ stamp: { type: 'string' },
1458
+ words: { type: 'number' },
1459
+ budget: { type: 'number' },
1460
+ headroom: { type: 'number' },
1461
+ extraWords: { type: 'number' },
1462
+ wouldTruncate: { type: 'boolean' },
1463
+ needToFree: { type: 'number' },
1464
+ dropCandidates: {
1465
+ type: 'array',
1466
+ items: objSchema({
1467
+ title: { type: 'string' },
1468
+ date: { type: 'string' },
1469
+ words: { type: 'number' },
1470
+ reason: { type: 'string', enum: ['oldest', 'same-date', 'undated'] },
1471
+ }, ['title', 'date', 'words', 'reason']),
1472
+ },
1473
+ beforeWords: { type: 'number' },
1474
+ afterWords: { type: 'number' },
1475
+ diff: { type: 'string' },
1476
+ indexComplete: { type: 'boolean' },
1477
+ }, ['notebook', 'accepted', 'rejection', 'detail', 'target', 'action', 'dryRun', 'performed',
1478
+ 'source', 'sourceTarget', 'stamp', 'words', 'budget', 'headroom', 'extraWords', 'wouldTruncate',
1479
+ 'needToFree', 'dropCandidates', 'beforeWords', 'afterWords', 'diff', 'indexComplete']),
1480
+ },
1481
+ async run(args, env) {
1482
+ const cfg = configFor(env.workspace, env.sessionId);
1483
+ // 不 ensureNotebook:预演不该顺手建库。索引只为核实 [[来源]],扫不全就只放路径式来源过。
1484
+ let index = { byTitle: new Map(), byId: new Map() };
1485
+ let indexComplete = false;
1486
+ if (hasNotebook(cfg)) {
1487
+ try {
1488
+ const scan = await scanNotes(cfg, {}, env.signal);
1489
+ index = wikiIndex(scan.notes);
1490
+ indexComplete = scan.completeness === 'complete';
1491
+ }
1492
+ catch { /* 索引不可用时退化为「只有路径式来源能过」,不装作全库可解析 */ }
1493
+ }
1494
+ const r = writeMemory(cfg, {
1495
+ target: (args.target ? String(args.target) : 'MEMORY'),
1496
+ action: (args.action ? String(args.action) : 'add'),
1497
+ entry: String(args.entry ?? ''),
1498
+ dryRun: args.dry_run !== false,
1499
+ expectStamp: args.expect_stamp ? String(args.expect_stamp) : undefined,
1500
+ index,
1501
+ indexComplete,
1502
+ });
1503
+ return { notebook: cfg.notebook, ...r };
1504
+ },
1505
+ render(_args, value) {
1506
+ const v = value;
1507
+ const lines = [];
1508
+ if (!v.accepted) {
1509
+ lines.push(`已拒绝(${v.rejection}):${v.detail}`);
1510
+ if (v.rejection === 'over-budget') {
1511
+ lines.push(`当前记忆 ${v.words}/${v.budget} 词,余 ${v.headroom} 词;拟新增 ${v.extraWords} 词,需先腾出 ${v.needToFree} 词。`);
1512
+ if (v.dropCandidates.length) {
1513
+ lines.push('会让位的条目(插件不替你退役):');
1514
+ for (const c of v.dropCandidates)
1515
+ lines.push(` · ${c.title}(${c.words} 词 · ${c.reason}${c.date ? ' · ' + c.date : ''})`);
1516
+ }
1517
+ }
1518
+ return text(lines.join('\n'));
1519
+ }
1520
+ if (v.dryRun) {
1521
+ lines.push(`预演通过(没有动任何文件):将往 ${v.target} 追加一条。`);
1522
+ lines.push(v.diff);
1523
+ }
1524
+ else {
1525
+ lines.push(`已写入 ${v.target}:${v.diff}`);
1526
+ lines.push('pre-image 摘要与这行 diff 已追加到 DREAMS.md,供周审复核。');
1527
+ }
1528
+ lines.push(`来源:[[${v.sourceTarget}]] → ${v.source || '(未解析)'}`);
1529
+ lines.push(`容量:记忆 ${v.words}/${v.budget} 词,余 ${v.headroom} 词` +
1530
+ (v.action === 'add' ? ` · 本次新增 ${v.extraWords} 词` : ' · 退役标记不占注入预算') +
1531
+ ` · 文件词数 ${v.beforeWords} → ${v.afterWords}`);
1532
+ if (!v.indexComplete)
1533
+ lines.push('⚠️ 活笔记索引没扫全,本次只核实了路径式来源。');
1534
+ if (v.dryRun)
1535
+ lines.push(`确认后传 dry_run: false 执行;建议带上 expect_stamp: "${v.stamp}"。`);
1536
+ return text(lines.join('\n'));
1537
+ },
1538
+ }),
1220
1539
  t({
1221
1540
  name: 'zk_lint',
1222
1541
  description: '给知识库做体检:断链 / 孤儿 / 无标签 / 单向链接 / 陈旧(N 天没改)/ 重名标题,每类最多 50 条并给总数。' +
@@ -1426,6 +1745,9 @@ export function buildTools(workspaceOf = () => processWorkspace()) {
1426
1745
  dailyMentions: { type: 'number' },
1427
1746
  daysMentioned: { type: 'number' },
1428
1747
  lastMentioned: { type: 'string' },
1748
+ /** 15.2:仅在召回信号生效时出现(可选,默认关时输出逐字节不变) */
1749
+ recallDays: { type: 'number' },
1750
+ recallKinds: { type: 'number' },
1429
1751
  }, ['title', 'path', 'cited', 'dailyMentions', 'daysMentioned', 'lastMentioned']),
1430
1752
  },
1431
1753
  dailyLooseEnds: {
@@ -1445,6 +1767,8 @@ export function buildTools(workspaceOf = () => processWorkspace()) {
1445
1767
  reason: { type: 'string', enum: ['stale', 'source-missing', 'source-superseded'] },
1446
1768
  }, ['entry', 'date', 'age', 'reason']),
1447
1769
  },
1770
+ /** 15.2:仅在召回信号生效时出现;固定比例、与分数无关的窗口外抽样 */
1771
+ auditSamples: { type: 'array', items: DREAM_CANDIDATE },
1448
1772
  }, ['notebook', 'windowDays', 'since', 'truncated', 'completeness', 'scanLimit', 'graphSkipped', 'graphBudget', 'missingId', 'memory', 'counts', 'newNotes', 'alreadyPromoted', 'backlog', 'rejected', 'topCited', 'dailyLooseEnds', 'retireCandidates']),
1449
1773
  },
1450
1774
  async run(args, env) {
@@ -1526,7 +1850,12 @@ export function buildTools(workspaceOf = () => processWorkspace()) {
1526
1850
  (c.daysMentioned > 0 ? ' · 日记 ' + c.daysMentioned + ' 天(最近 ' + c.lastMentioned + ')' : ''));
1527
1851
  }
1528
1852
  }
1529
- if (!v.newNotes.length && !v.dailyLooseEnds.length && !v.topCited.length)
1853
+ if (v.auditSamples?.length) {
1854
+ lines.push('审计抽样(与分数无关,固定比例):');
1855
+ for (const n of v.auditSamples.slice(0, 10))
1856
+ lines.push(' · ' + (n.title || n.path) + '(' + n.path + ')');
1857
+ }
1858
+ if (!v.newNotes.length && !v.dailyLooseEnds.length && !v.topCited.length && !v.auditSamples?.length)
1530
1859
  lines.push('这个窗口里没有新材料。');
1531
1860
  if (v.completeness === 'partial')
1532
1861
  lines.push('⚠️ 笔记数触到扫描上限(' + v.scanLimit + ' 篇):窗口与排名都不完整');
@@ -1565,18 +1894,39 @@ export function buildTools(workspaceOf = () => processWorkspace()) {
1565
1894
  },
1566
1895
  completeness: { type: 'string', enum: ['complete', 'partial', 'unknown'] },
1567
1896
  scanLimit: { type: 'number' },
1568
- }, ['notebook', 'defaultNotebook', 'pinned', 'notes', 'tags', 'brokenLinks', 'orphans', 'archived', 'superseded', 'byDir', 'byTag', 'completeness', 'scanLimit']),
1897
+ /** 本地聚合计数(plan §14.4):只看「入口 / 一跳」这条路有没有被用上,不记查询词 */
1898
+ usage: objSchema({
1899
+ since: { type: 'string' },
1900
+ search: { type: 'number' },
1901
+ query: { type: 'number' },
1902
+ recall: { type: 'number' },
1903
+ walk: { type: 'number' },
1904
+ entryPoints: { type: 'number' },
1905
+ counterEntries: { type: 'number' },
1906
+ }, ['since', 'search', 'query', 'recall', 'walk', 'entryPoints', 'counterEntries']),
1907
+ }, ['notebook', 'defaultNotebook', 'pinned', 'notes', 'tags', 'brokenLinks', 'orphans', 'archived', 'superseded', 'byDir', 'byTag', 'completeness', 'scanLimit', 'usage']),
1569
1908
  },
1570
1909
  async run(_args, env) {
1571
1910
  const cfg = configFor(env.workspace, env.sessionId);
1572
1911
  await ensureNotebook(cfg, env.signal);
1573
1912
  const stats = await notebookStats(cfg, env.signal);
1574
1913
  const state = sessionState(env.workspace, env.sessionId);
1914
+ const usage = readUsage(cfg);
1915
+ const count = (key) => usage.counts[key] ?? 0;
1575
1916
  return {
1576
1917
  notebook: cfg.notebook,
1577
1918
  defaultNotebook: state.defaultName,
1578
1919
  pinned: state.diverged ? state.pinned : '',
1579
1920
  ...stats,
1921
+ usage: {
1922
+ since: usage.since,
1923
+ search: count('search'),
1924
+ query: count('query'),
1925
+ recall: count('recall'),
1926
+ walk: count('walk'),
1927
+ entryPoints: count('entryPoints'),
1928
+ counterEntries: count('counterEntries'),
1929
+ },
1580
1930
  };
1581
1931
  },
1582
1932
  render(_args, value) {
@@ -1594,9 +1944,13 @@ export function buildTools(workspaceOf = () => processWorkspace()) {
1594
1944
  const partial = v.completeness === 'partial'
1595
1945
  ? `\n⚠️ 只扫描了前 ${v.scanLimit} 篇:上面的数字是下限`
1596
1946
  : v.completeness === 'unknown' ? '\n⚠️ 扫描结果无法完整解析:上面的数字可能偏少' : '';
1947
+ const usage = v.usage && (v.usage.walk || v.usage.entryPoints || v.usage.counterEntries || v.usage.recall)
1948
+ ? `\n入口 / 一跳:walk ${v.usage.walk} 次 · 召回 ${v.usage.recall} 次 · 入口回显 ${v.usage.entryPoints} 次 · 死胡同提醒 ${v.usage.counterEntries} 次` +
1949
+ (v.usage.since ? `(自 ${v.usage.since.slice(0, 10)})` : '')
1950
+ : '\n入口 / 一跳:还没有计数(zk_walk / zk_recall / 入口与死胡同提醒都没被用过)';
1597
1951
  return text(`笔记本 ${v.notebook}${drift}\n` +
1598
1952
  `笔记 ${atLeast}${v.notes} 篇 · 标签 ${atLeast}${v.tags} 个 · 断链 ${v.brokenLinks} 篇 · 孤立 ${v.orphans} 篇 · 归档 ${atLeast}${v.archived} 篇(superseded ${atLeast}${v.superseded})` +
1599
- dirs + tags + partial);
1953
+ dirs + tags + partial + usage);
1600
1954
  },
1601
1955
  }),
1602
1956
  t({