dsh-zdiary-kit 3.4.0 → 3.7.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 的公共入口):13 个内置工具 + `[alias]` 别名工具,全部经 lib/zk.ts。
2
+ * zk 工具(feature 的公共入口):14 个内置工具 + `[alias]` 别名工具,全部经 lib/zk.ts。
3
3
  *
4
4
  * 设计要点:
5
5
  * · 除 zk_context(只读 meta 文件,不依赖 zk)外,每个工具进来先 ensureNotebook —— 第一次调用就自动建好笔记本,用户不用先点设置页;
@@ -15,13 +15,22 @@ 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, 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, ZkError, } from '../../lib/zk.js';
19
19
  import { configuredAliases, readAliases } from '../../lib/alias.js';
20
- import { buildMemoryPayload, META_FILES } from '../../lib/memory.js';
20
+ import { buildMemoryPayload, memoryCapacity, META_FILES } from '../../lib/memory.js';
21
+ import { assembleRecall } from '../../lib/recall.js';
21
22
  import { META_NAMES } from '../../lib/meta.js';
22
23
  import { formatLintExtras, formatMemoryLinks, lintNotebook } from '../../lib/lint.js';
23
24
  import { dreamNotebook, STALE_DAYS } from '../../lib/dream.js';
24
25
  const text = (value) => [{ type: 'text', text: value }];
26
+ /** render 的 args 是 unknown:只取 query 判断要不要给中文 0 命中提示(R7) */
27
+ const queryOf = (args) => {
28
+ if (!args || typeof args !== 'object')
29
+ return '';
30
+ return String(args.query ?? '');
31
+ };
32
+ /** R7:中文 0 命中的「为什么空」提示;ASCII / 无 query 不加 */
33
+ const zeroHitHint = (args, extra) => hasCjk(queryOf(args)) ? `;中文全文不切词:换更短的词,${extra}` : '';
25
34
  const objSchema = (properties, required) => ({
26
35
  type: 'object',
27
36
  properties,
@@ -43,8 +52,9 @@ const LINT_ONE_WAY = objSchema({
43
52
  bodyOnly: { type: 'number' },
44
53
  linksOnly: { type: 'boolean' },
45
54
  edgesTruncated: { type: 'boolean' },
55
+ completeness: { type: 'string', enum: ['complete', 'partial', 'unknown'] },
46
56
  items: { type: 'array', items: LINT_ONE_WAY_ITEM },
47
- }, ['total', 'edges', 'bodyOnly', 'linksOnly', 'edgesTruncated', 'items']);
57
+ }, ['total', 'edges', 'bodyOnly', 'linksOnly', 'edgesTruncated', 'completeness', 'items']);
48
58
  const LINT_STALE = objSchema({
49
59
  total: { type: 'number' },
50
60
  items: {
@@ -63,6 +73,8 @@ const LINT_DUPLICATE = objSchema({
63
73
  const LINT_SIMILAR = objSchema({
64
74
  total: { type: 'number' },
65
75
  truncated: { type: 'boolean' },
76
+ completeness: { type: 'string', enum: ['complete', 'partial', 'unknown'] },
77
+ droppedGroups: { type: 'number' },
66
78
  items: {
67
79
  type: 'array',
68
80
  items: objSchema({
@@ -71,7 +83,7 @@ const LINT_SIMILAR = objSchema({
71
83
  score: { type: 'number' },
72
84
  }, ['titles', 'paths', 'score']),
73
85
  },
74
- }, ['total', 'truncated', 'items']);
86
+ }, ['total', 'truncated', 'completeness', 'droppedGroups', 'items']);
75
87
  /** 记忆层体检:MEMORY.md / USER.md 里的来源链是否还指向活笔记 */
76
88
  const LINT_MEMORY = objSchema({
77
89
  files: { type: 'number' },
@@ -258,10 +270,15 @@ function withElsewhere(err, cfg, workspace, rel) {
258
270
  function tagSuffix(record) {
259
271
  return record.tags.length ? ' · ' + record.tags.map((t) => '#' + t).join(' ') : '';
260
272
  }
273
+ /** R2:snippet 比 lead 多带命中上下文时才替换它,否则维持原输出 */
274
+ function detailOf(n) {
275
+ return n.snippet && n.snippet !== n.lead ? n.snippet : (n.lead ?? '');
276
+ }
261
277
  function noteLine(n, index) {
262
278
  const head = `${index + 1}. ${n.title || n.path}`;
263
279
  const meta = [n.absPath || n.path, dateOnly(n.created)].filter(Boolean).join(' · ');
264
- const lead = n.lead ? `\n ${n.lead}` : '';
280
+ const detail = detailOf(n);
281
+ const lead = detail ? `\n ${detail}` : '';
265
282
  return `${head}\n ${meta}${tagSuffix(n)}${lead}`;
266
283
  }
267
284
  function def(spec, workspaceOf) {
@@ -358,20 +375,21 @@ export function buildTools(workspaceOf = () => processWorkspace()) {
358
375
  const builtins = [
359
376
  t({
360
377
  name: 'zk_search',
361
- description: '在 zk 知识库里搜索笔记(全文 / 标签 / 日期 / 断链 / 孤立笔记),返回标题、相对路径、绝对路径、标签、创建日与摘要。' +
378
+ description: '在 zk 知识库里搜索笔记(全文 / 标签 / 日期 / 断链 / 孤立笔记),返回标题、相对路径、绝对路径、标签、创建日、摘要与命中片段。' +
362
379
  '找到后用原生 read 读全文:notes[].absPath 可以直接传给 read。写笔记前先用它查重。' +
363
- '中文查询会自动并用子串匹配(FTS 不切中文):matchStrategy 说明这次用了 fts / regex / mixed,mixed 表示补到了全文索引漏掉的笔记。',
380
+ '中文会自动并用子串,多词按覆盖度合并(FTS 不切中文):matchStrategy 说明这次用了 fts / regex / mixed,mixed 表示补到了全文索引漏掉的笔记。' +
381
+ '有 query 时默认按 FTS 相关性排序,显式给 sort 才改顺序。',
364
382
  parameters: {
365
383
  type: 'object',
366
384
  properties: {
367
- query: S.str('全文检索词(FTS,支持 "短语" 与 AND / OR;含中文时自动并用子串匹配补漏)'),
385
+ query: S.str('全文检索词(FTS,支持 "短语" 与 AND / OR;中文会自动并用子串,多词按覆盖度合并)'),
368
386
  tags: S.arr('按标签过滤(AND:必须同时带这些标签)', S.str('标签名,不带 #')),
369
387
  since: S.str('只看这个日期之后创建的笔记,自然语言或 ISO 日期,如 2026-01-01 / "last week"'),
370
388
  until: S.str('只看这个日期之前创建的笔记'),
371
389
  orphan: S.bool('只看没有任何反链的孤立笔记'),
372
390
  brokenLinks: S.bool('只看含有断链的笔记'),
373
391
  limit: S.num('最多返回几条(1-200,默认 10)'),
374
- sort: S.enum('排序方式', ['created-desc', 'created-asc', 'modified-desc', 'title-asc']),
392
+ sort: S.enum('排序方式;有 query 默认 relevance(按 FTS 相关性),无 query 回退 created-desc', ['relevance', 'created-desc', 'created-asc', 'modified-desc', 'title-asc']),
375
393
  },
376
394
  additionalProperties: false,
377
395
  },
@@ -380,6 +398,11 @@ export function buildTools(workspaceOf = () => processWorkspace()) {
380
398
  notebook: { type: 'string' },
381
399
  count: { type: 'number' },
382
400
  matchStrategy: { type: 'string', enum: ['fts', 'regex', 'mixed'] },
401
+ completeness: { type: 'string', enum: ['complete', 'partial', 'unknown'] },
402
+ hasMore: { type: 'boolean' },
403
+ scanned: { type: 'number' },
404
+ /** R2:只在能精确判定时给(completeness === complete) */
405
+ total: { type: 'number' },
383
406
  notes: {
384
407
  type: 'array',
385
408
  items: objSchema({
@@ -389,9 +412,12 @@ export function buildTools(workspaceOf = () => processWorkspace()) {
389
412
  tags: { type: 'array', items: { type: 'string' } },
390
413
  created: { type: 'string' },
391
414
  lead: { type: 'string' },
415
+ words: { type: 'number' },
416
+ /** 命中片段,没有时整个键不出现(避免 undefined 让宿主判 invalid output) */
417
+ snippet: { type: 'string' },
392
418
  }, ['title', 'path', 'absPath', 'tags', 'created', 'lead']),
393
419
  },
394
- }, ['notebook', 'count', 'matchStrategy', 'notes']),
420
+ }, ['notebook', 'count', 'matchStrategy', 'completeness', 'hasMore', 'scanned', 'notes']),
395
421
  },
396
422
  async run(args, env) {
397
423
  const cfg = configFor(env.workspace, env.sessionId);
@@ -404,34 +430,50 @@ export function buildTools(workspaceOf = () => processWorkspace()) {
404
430
  orphan: args.orphan === true,
405
431
  brokenLinks: args.brokenLinks === true,
406
432
  limit: args.limit === undefined ? 10 : Number(args.limit),
407
- sort: args.sort ? String(args.sort) : 'created-desc',
433
+ // R1:有 query 且没显式给 sort → relevance(不传 --sort,保住 FTS 相关性顺序)
434
+ sort: args.sort ? String(args.sort) : (args.query ? 'relevance' : 'created-desc'),
408
435
  });
409
436
  return {
410
437
  notebook: cfg.notebook,
411
438
  count: result.notes.length,
412
439
  matchStrategy: result.matchStrategy,
413
- notes: result.notes.map((n) => ({ title: n.title, path: n.path, absPath: n.absPath, tags: n.tags, created: dateOnly(n.created), lead: n.lead })),
440
+ completeness: result.completeness,
441
+ hasMore: result.hasMore,
442
+ scanned: result.scanned,
443
+ ...(result.total === undefined ? {} : { total: result.total }),
444
+ notes: result.notes.map((n) => ({
445
+ title: n.title, path: n.path, absPath: n.absPath, tags: n.tags,
446
+ created: dateOnly(n.created), lead: n.lead, words: n.words,
447
+ ...(n.snippet ? { snippet: n.snippet } : {}),
448
+ })),
414
449
  };
415
450
  },
416
- render(_args, value) {
451
+ render(args, value) {
417
452
  const v = value;
418
- if (!v.count)
419
- return text(`没有匹配的笔记(笔记本 ${v.notebook})`);
453
+ if (!v.count) {
454
+ return text(`没有匹配的笔记(笔记本 ${v.notebook})` +
455
+ zeroHitHint(args, '或按 tags 查') +
456
+ (v.completeness === 'unknown' ? ';但这次检索结果无法完整解析,不能当作「库里没有」' : ''));
457
+ }
420
458
  const how = v.matchStrategy === 'mixed'
421
459
  ? '(中文:全文 + 子串合并,已补上全文索引漏掉的)'
422
460
  : v.matchStrategy === 'regex' ? '(全文无结果,已退回子串匹配)' : '';
423
- return text(`${v.count} 条(笔记本 ${v.notebook})${how}\n` + v.notes.map(noteLine).join('\n'));
461
+ const tail = v.completeness === 'unknown'
462
+ ? '\n⚠️ 无法确认结果是否完整(解析失败 / 补充检索失败),先别把它当成全部命中'
463
+ : v.hasMore ? `\n⚠️ 还有更多匹配没返回(已检查 ${v.scanned} 条候选);要更全就提高 limit 或加过滤条件` : '';
464
+ return text(`${v.count} 条(笔记本 ${v.notebook})${how}\n` + v.notes.map(noteLine).join('\n') + tail);
424
465
  },
425
466
  }),
426
467
  t({
427
468
  name: 'zk_query',
428
469
  description: '结构化检索记忆:按 type(daily/source/concept/entity/pattern)、status(active/superseded)、标签、目录、日期、断链、孤立过滤。' +
429
470
  '默认只看 active 且不含归档;传 include_archived: true 会连归档一起查,此时未显式给 status 就不再默认过滤 active。' +
471
+ '中文会自动并用子串,多词按覆盖度合并;有 query 时默认按 FTS 相关性排序。' +
430
472
  '这是查「记忆里有什么」的主入口。',
431
473
  parameters: {
432
474
  type: 'object',
433
475
  properties: {
434
- query: S.str('全文检索词(中文召回不完整,尽量配合 tags 使用)'),
476
+ query: S.str('全文检索词(中文会自动并用子串,多词按覆盖度合并)'),
435
477
  tags: S.arr('按标签过滤(AND)', S.str('标签名,不带 #')),
436
478
  dirs: S.arr('只看这些目录(相对笔记本,如 notes/concepts)', S.str('相对目录')),
437
479
  type: S.enum('只要这个类型的笔记', ['daily', 'source', 'concept', 'entity', 'pattern']),
@@ -441,7 +483,7 @@ export function buildTools(workspaceOf = () => processWorkspace()) {
441
483
  orphan: S.bool('只看没有反链的孤立笔记'),
442
484
  brokenLinks: S.bool('只看含断链的笔记'),
443
485
  include_archived: S.bool('连 archive/ 里的废弃笔记一起查(默认 false)'),
444
- sort: S.enum('排序方式', ['created-desc', 'created-asc', 'modified-desc', 'title-asc']),
486
+ sort: S.enum('排序方式;有 query 默认 relevance(按 FTS 相关性),无 query 回退 created-desc', ['relevance', 'created-desc', 'created-asc', 'modified-desc', 'title-asc']),
445
487
  limit: S.num('最多返回几条(1-200,默认 10)'),
446
488
  },
447
489
  additionalProperties: false,
@@ -450,6 +492,11 @@ export function buildTools(workspaceOf = () => processWorkspace()) {
450
492
  schema: objSchema({
451
493
  notebook: { type: 'string' },
452
494
  count: { type: 'number' },
495
+ completeness: { type: 'string', enum: ['complete', 'partial', 'unknown'] },
496
+ hasMore: { type: 'boolean' },
497
+ scanned: { type: 'number' },
498
+ /** R2:只在能精确判定时给(completeness === complete) */
499
+ total: { type: 'number' },
453
500
  notes: {
454
501
  type: 'array',
455
502
  items: objSchema({
@@ -462,16 +509,18 @@ export function buildTools(workspaceOf = () => processWorkspace()) {
462
509
  tags: { type: 'array', items: { type: 'string' } },
463
510
  created: { type: 'string' },
464
511
  lead: { type: 'string' },
512
+ words: { type: 'number' },
513
+ snippet: { type: 'string' },
465
514
  archived: { type: 'boolean' },
466
515
  }, ['title', 'path', 'absPath', 'type', 'status', 'authority', 'tags', 'created', 'lead', 'archived']),
467
516
  },
468
- }, ['notebook', 'count', 'notes']),
517
+ }, ['notebook', 'count', 'completeness', 'hasMore', 'scanned', 'notes']),
469
518
  },
470
519
  async run(args, env) {
471
520
  const cfg = configFor(env.workspace, env.sessionId);
472
521
  await ensureNotebook(cfg, env.signal);
473
522
  const includeArchived = args.include_archived === true;
474
- const notes = await searchNotes(cfg, {
523
+ const result = await searchNotesDetailed(cfg, {
475
524
  query: args.query ? String(args.query) : undefined,
476
525
  tags: Array.isArray(args.tags) ? args.tags.map(String) : undefined,
477
526
  paths: Array.isArray(args.dirs) ? args.dirs.map(String) : undefined,
@@ -484,11 +533,17 @@ export function buildTools(workspaceOf = () => processWorkspace()) {
484
533
  brokenLinks: args.brokenLinks === true,
485
534
  includeArchived,
486
535
  limit: args.limit === undefined ? 10 : Number(args.limit),
487
- sort: args.sort ? String(args.sort) : 'created-desc',
536
+ // R1:有 query 且没显式给 sort → relevance
537
+ sort: args.sort ? String(args.sort) : (args.query ? 'relevance' : 'created-desc'),
488
538
  }, env.signal);
539
+ const notes = result.notes;
489
540
  return {
490
541
  notebook: cfg.notebook,
491
542
  count: notes.length,
543
+ completeness: result.completeness,
544
+ hasMore: result.hasMore,
545
+ scanned: result.scanned,
546
+ ...(result.total === undefined ? {} : { total: result.total }),
492
547
  notes: notes.map((n) => ({
493
548
  title: n.title,
494
549
  path: n.path,
@@ -500,19 +555,115 @@ export function buildTools(workspaceOf = () => processWorkspace()) {
500
555
  tags: n.tags,
501
556
  created: dateOnly(n.created),
502
557
  lead: n.lead,
558
+ words: n.words,
559
+ ...(n.snippet ? { snippet: n.snippet } : {}),
503
560
  archived: n.path.startsWith(cfg.archiveDir + '/'),
504
561
  })),
505
562
  };
506
563
  },
507
- render(_args, value) {
564
+ render(args, value) {
508
565
  const v = value;
509
- if (!v.count)
510
- return text(`没有匹配的笔记(笔记本 ${v.notebook})`);
566
+ if (!v.count) {
567
+ return text(`没有匹配的笔记(笔记本 ${v.notebook})` +
568
+ zeroHitHint(args, '或给 tags 参数按标签查') +
569
+ (v.completeness === 'unknown' ? ';但这次检索结果无法完整解析,不能当作「记忆里没有」' : ''));
570
+ }
571
+ const tail = v.completeness === 'unknown'
572
+ ? '\n⚠️ 无法确认结果是否完整(解析失败 / 补充检索失败),先别把它当成全部命中'
573
+ : v.hasMore ? `\n⚠️ 还有更多匹配没返回(已检查 ${v.scanned} 条候选);要更全就提高 limit 或缩小过滤范围` : '';
511
574
  const lines = v.notes.map((n, i) => {
512
575
  const badges = [String(n.type || '—'), String(n.status || 'no-status'), n.archived ? '已归档' : ''].filter(Boolean);
513
- return `${i + 1}. ${String(n.title)} [${badges.join(' · ')}]\n ${String(n.absPath || n.path)} · ${String(n.created)}${String(n.lead) ? '\n ' + String(n.lead) : ''}`;
576
+ const detail = detailOf({ lead: String(n.lead ?? ''), snippet: String(n.snippet ?? '') });
577
+ return `${i + 1}. ${String(n.title)} [${badges.join(' · ')}]\n ${String(n.absPath || n.path)} · ${String(n.created)}${detail ? '\n ' + detail : ''}`;
514
578
  });
515
- return text(`${v.count} 条(笔记本 ${v.notebook})\n` + lines.join('\n'));
579
+ return text(`${v.count} 条(笔记本 ${v.notebook})\n` + lines.join('\n') + tail);
580
+ },
581
+ }),
582
+ t({
583
+ name: 'zk_recall',
584
+ description: '召回装配:先按 query / 过滤条件检索(与 zk_search 同一套 R1–R3),再按词数预算把命中笔记拼成一段可直接读的上下文。' +
585
+ '每条带标题、路径、absPath 与全文词数,放不下就整条丢弃、不切半句;需要全文仍用原生 read 读 absPath。' +
586
+ 'budget 按 countWords 口径(中文 2 字 1 词),used 一定不超过 budget。' +
587
+ '不做语义判断 / 重排 / 跨回合去重;completeness 沿用检索三态,装配过的 ≠ 全部命中。',
588
+ parameters: {
589
+ type: 'object',
590
+ properties: {
591
+ query: S.str('全文检索词(中文自动并用子串、多词按覆盖度合并;不给则按过滤条件列最近的笔记)'),
592
+ tags: S.arr('按标签过滤(AND)', S.str('标签名,不带 #')),
593
+ since: S.str('只看这个日期之后创建的笔记'),
594
+ until: S.str('只看这个日期之前创建的笔记'),
595
+ orphan: S.bool('只看没有反链的孤立笔记'),
596
+ brokenLinks: S.bool('只看含断链的笔记'),
597
+ include_archived: S.bool('连 archive/ 里的废弃笔记一起查(默认 false)'),
598
+ type: S.enum('只要这个类型的笔记', ['daily', 'source', 'concept', 'entity', 'pattern']),
599
+ status: S.enum('只要这个状态(默认 active)', ['active', 'superseded']),
600
+ limit: S.num('候选检索条数(1-200,默认 30;装配只在这些候选里挑)'),
601
+ sort: S.enum('排序方式;有 query 默认 relevance(按 FTS 相关性),无 query 回退 created-desc', ['relevance', 'created-desc', 'created-asc', 'modified-desc', 'title-asc']),
602
+ budget: S.num('装配词数预算(默认 500,范围 1-5000;中文 2 字 1 词)'),
603
+ },
604
+ additionalProperties: false,
605
+ },
606
+ output: {
607
+ schema: objSchema({
608
+ notebook: { type: 'string' },
609
+ text: { type: 'string' },
610
+ used: { type: 'number' },
611
+ budget: { type: 'number' },
612
+ completeness: { type: 'string', enum: ['complete', 'partial', 'unknown'] },
613
+ hasMore: { type: 'boolean' },
614
+ notes: {
615
+ type: 'array',
616
+ items: objSchema({
617
+ title: { type: 'string' },
618
+ path: { type: 'string' },
619
+ absPath: { type: 'string' },
620
+ included: { type: 'boolean' },
621
+ reason: { type: 'string', enum: ['included', 'duplicate', 'empty', 'over-budget'] },
622
+ }, ['title', 'path', 'absPath', 'included', 'reason']),
623
+ },
624
+ }, ['notebook', 'text', 'used', 'budget', 'completeness', 'hasMore', 'notes']),
625
+ },
626
+ async run(args, env) {
627
+ const cfg = configFor(env.workspace, env.sessionId);
628
+ await ensureNotebook(cfg, env.signal);
629
+ const includeArchived = args.include_archived === true;
630
+ const r = await assembleRecall(cfg, {
631
+ query: args.query ? String(args.query) : undefined,
632
+ tags: Array.isArray(args.tags) ? args.tags.map(String) : undefined,
633
+ since: args.since ? String(args.since) : undefined,
634
+ until: args.until ? String(args.until) : undefined,
635
+ orphan: args.orphan === true,
636
+ brokenLinks: args.brokenLinks === true,
637
+ includeArchived,
638
+ type: args.type ? [String(args.type)] : undefined,
639
+ // 与 zk_query 同口径:默认只给活着的,显式 include_archived 时不再默认卡 active
640
+ status: args.status ? [String(args.status)] : includeArchived ? undefined : ['active'],
641
+ limit: args.limit === undefined ? undefined : Number(args.limit),
642
+ sort: args.sort ? String(args.sort) : undefined,
643
+ budget: args.budget === undefined ? undefined : Number(args.budget),
644
+ }, env.signal);
645
+ return { notebook: cfg.notebook, ...r };
646
+ },
647
+ render(args, value) {
648
+ const v = value;
649
+ const kept = v.notes.filter((n) => n.included).length;
650
+ const dropped = v.notes.length - kept;
651
+ if (!v.notes.length) {
652
+ return text(`没有匹配的笔记(笔记本 ${v.notebook})` +
653
+ zeroHitHint(args, '或按 tags 查') +
654
+ (v.completeness === 'unknown' ? ';但这次检索结果无法完整解析,不能当作「库里没有」' : ''));
655
+ }
656
+ const lines = [`召回装配:${v.used}/${v.budget} 词 · 收录 ${kept}/${v.notes.length} 篇(笔记本 ${v.notebook})`];
657
+ if (v.text)
658
+ lines.push('', v.text);
659
+ if (dropped)
660
+ lines.push(`(${dropped} 篇没放进去:整条丢弃,没有切半句;原因见 notes[].reason)`);
661
+ const tail = v.completeness === 'unknown'
662
+ ? '⚠️ 无法确认结果是否完整(解析失败 / 补充检索失败),先别把它当成全部命中'
663
+ : v.hasMore ? '⚠️ 还有更多匹配没返回;要提高 limit 或缩小过滤范围' : '';
664
+ if (tail)
665
+ lines.push(tail);
666
+ return text(lines.join('\n'));
516
667
  },
517
668
  }),
518
669
  t({
@@ -925,8 +1076,17 @@ export function buildTools(workspaceOf = () => processWorkspace()) {
925
1076
  description: '读知识库根目录的长期约定与记忆(AGENTS.md / USER.md / MEMORY.md),按注入预算截断后返回;' +
926
1077
  '角色人格(PERSONA.md)单独成段、在记忆段之前、不参与截断。' +
927
1078
  '同时列出已配置的笔记本(名字 / 路径 / 结构 / 当前)。' +
1079
+ '改 MEMORY.md 之前用它看余量:headroom / wouldTruncate / dropCandidates 说明「再加一条会丢谁」,' +
1080
+ '给 proposed_entry 或 extra_words 就能预估;同日条目按位置决胜(sameDateCount)。' +
928
1081
  '宿主支持注入时这些内容每轮已自动进入系统提示;宿主不支持、或想核对「被截断了多少」时用它。',
929
- parameters: { type: 'object', properties: {}, additionalProperties: false },
1082
+ parameters: {
1083
+ type: 'object',
1084
+ properties: {
1085
+ proposed_entry: S.str('打算写进 MEMORY.md 的新条目;按它估算会不会触发截断并预告会丢谁'),
1086
+ extra_words: S.num('新条目词数;给了就不按 proposed_entry 重算,直接按这个数估'),
1087
+ },
1088
+ additionalProperties: false,
1089
+ },
930
1090
  output: {
931
1091
  schema: objSchema({
932
1092
  text: { type: 'string' },
@@ -938,6 +1098,23 @@ export function buildTools(workspaceOf = () => processWorkspace()) {
938
1098
  tocWords: { type: 'number' },
939
1099
  totalWords: { type: 'number' },
940
1100
  overheadWords: { type: 'number' },
1101
+ // G1 / G4:写 MEMORY 前的容量(纯增量字段,旧客户端只是多看到几列)
1102
+ retiredEntries: { type: 'number' },
1103
+ headroom: { type: 'number' },
1104
+ extraWords: { type: 'number' },
1105
+ wouldTruncate: { type: 'boolean' },
1106
+ sameDateCount: { type: 'number' },
1107
+ format: { type: 'array', items: { type: 'string' } },
1108
+ suggestion: { type: 'string' },
1109
+ dropCandidates: {
1110
+ type: 'array',
1111
+ items: objSchema({
1112
+ title: { type: 'string' },
1113
+ date: { type: 'string' },
1114
+ words: { type: 'number' },
1115
+ reason: { type: 'string', enum: ['oldest', 'same-date', 'undated'] },
1116
+ }, ['title', 'date', 'words', 'reason']),
1117
+ },
941
1118
  // 格式债 / 模板版本:只读元数据,比 memoryUsage 的投影早一步就能拿到
942
1119
  formatDebt: objSchema({
943
1120
  total: { type: 'number' },
@@ -984,15 +1161,21 @@ export function buildTools(workspaceOf = () => processWorkspace()) {
984
1161
  retiredWords: { type: 'number' },
985
1162
  }, ['name', 'present', 'words', 'originalWords', 'retiredWords']),
986
1163
  },
987
- }, ['text', 'words', 'budget', 'ratio', 'truncatedWords', 'retiredWords', 'tocWords', 'totalWords', 'overheadWords', 'formatDebt', 'templateVersion', 'persona', 'notebook', 'defaultNotebook', 'pinned', 'notebooks', 'files']),
1164
+ }, ['text', 'words', 'budget', 'ratio', 'truncatedWords', 'retiredWords', 'tocWords', 'totalWords', 'overheadWords',
1165
+ 'retiredEntries', 'headroom', 'extraWords', 'wouldTruncate', 'sameDateCount', 'format', 'suggestion', 'dropCandidates',
1166
+ 'formatDebt', 'templateVersion', 'persona', 'notebook', 'defaultNotebook', 'pinned', 'notebooks', 'files']),
988
1167
  },
989
- async run(_args, env) {
1168
+ async run(args, env) {
990
1169
  // 不 ensureNotebook:读记忆不该依赖 zk,笔记本不存在时就是空载荷
991
1170
  const cfg = configFor(env.workspace, env.sessionId);
992
1171
  const state = sessionState(env.workspace, env.sessionId);
993
1172
  const payload = buildMemoryPayload(cfg);
994
1173
  return {
995
1174
  ...payload,
1175
+ ...memoryCapacity(cfg, {
1176
+ proposedEntry: args.proposed_entry ? String(args.proposed_entry) : undefined,
1177
+ extraWords: args.extra_words === undefined ? undefined : Number(args.extra_words),
1178
+ }),
996
1179
  notebook: state.active,
997
1180
  defaultNotebook: state.defaultName,
998
1181
  pinned: state.diverged ? state.pinned : '',
@@ -1012,8 +1195,18 @@ export function buildTools(workspaceOf = () => processWorkspace()) {
1012
1195
  ? `笔记本「${current.name}」(${current.structure})→ ${current.path}` +
1013
1196
  (others.length ? `\n另有:${others.map((n) => `${n.name}(${n.structure})`).join('、')} —— zk_use 切换本会话` : '')
1014
1197
  : `笔记本「${v.notebook}」`;
1198
+ // G1 / G4:写 MEMORY 前的余量、是否触发截断、同日决胜与「下一条会丢谁」
1199
+ const capacity = `\n\n容量:余 ${v.headroom} 词(记忆内容 ${v.words}/${v.budget},总载荷 ${v.totalWords})` +
1200
+ (v.extraWords > 0 ? ` · 拟新增 ${v.extraWords} 词${v.wouldTruncate ? '(会触发截断)' : ''}` : '') +
1201
+ (v.sameDateCount > 1 ? ` · ${v.sameDateCount} 条同日,按位置决胜` : '') +
1202
+ `\n${v.suggestion}` +
1203
+ (v.dropCandidates.length
1204
+ ? '\n下一条会丢的 MEMORY 条目(预告,磁盘不动):\n' +
1205
+ v.dropCandidates.map((c, i) => `${i + 1}. ${c.title}(${c.words} 词 · ${c.reason}${c.date ? ' · ' + c.date : ''})`).join('\n')
1206
+ : '');
1015
1207
  if (!v.text) {
1016
- return text(drift + head + `\n\n知识库根目录没有 ${META_FILES.join(' / ')}(或都是空的),也没有 PERSONA.md 人格文件。`);
1208
+ return text(drift + head + capacity +
1209
+ `\n\n知识库根目录没有 ${META_FILES.join(' / ')}(或都是空的),也没有 PERSONA.md 人格文件。`);
1017
1210
  }
1018
1211
  const persona = v.persona?.present
1019
1212
  ? `\n\n人格:正文(含标题)${v.persona.contentWords}/${v.persona.budget} 词` +
@@ -1021,7 +1214,7 @@ export function buildTools(workspaceOf = () => processWorkspace()) {
1021
1214
  (v.persona.overBudget ? `,超 ${v.persona.overWords} 词(人格不截断)` : '')
1022
1215
  : '\n\n人格:未启用(根目录没有 PERSONA.md)';
1023
1216
  const totals = `\n\n用量:记忆载荷 ${v.totalWords} 词(预算 ${v.budget})`;
1024
- return text(drift + head + persona + totals + (v.text ? '\n\n' + v.text : ''));
1217
+ return text(drift + head + persona + totals + capacity + (v.text ? '\n\n' + v.text : ''));
1025
1218
  },
1026
1219
  }),
1027
1220
  t({
@@ -1059,6 +1252,8 @@ export function buildTools(workspaceOf = () => processWorkspace()) {
1059
1252
  notebook: { type: 'string' },
1060
1253
  notes: { type: 'number' },
1061
1254
  truncated: { type: 'boolean' },
1255
+ completeness: { type: 'string', enum: ['complete', 'partial', 'unknown'] },
1256
+ scanLimit: { type: 'number' },
1062
1257
  staleDays: { type: 'number' },
1063
1258
  parseErrors: LINT_PARSE,
1064
1259
  orphans: LINT_BUCKET,
@@ -1075,7 +1270,8 @@ export function buildTools(workspaceOf = () => processWorkspace()) {
1075
1270
  persona: LINT_PERSONA,
1076
1271
  timeline: LINT_TIMELINE,
1077
1272
  indexHint: { type: 'boolean' },
1078
- }, ['notebook', 'notes', 'truncated', 'staleDays', 'parseErrors', 'orphans', 'brokenLinks', 'stale', 'tagless', 'oneWayLinks', 'duplicateTitles', 'similarTitles', 'memoryLinks', 'incomplete', 'tags', 'template', 'persona', 'timeline', 'indexHint']),
1273
+ 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']),
1079
1275
  },
1080
1276
  async run(args, env) {
1081
1277
  const cfg = configFor(env.workspace, env.sessionId);
@@ -1128,12 +1324,23 @@ export function buildTools(workspaceOf = () => processWorkspace()) {
1128
1324
  if (memLine)
1129
1325
  lines.push(memLine);
1130
1326
  lines.push(...formatLintExtras(v));
1131
- if (v.similarTitles.truncated)
1132
- lines.push('⚠️ 疑似重复只比较了部分笔记(同目录超过 300 篇或扫描触顶):可能漏报');
1133
- if (v.truncated)
1134
- lines.push('⚠️ 笔记数触到扫描上限:结果不完整(只会漏报,不会误报),先归档旧笔记再跑一次');
1135
- if (oneWay.edgesTruncated)
1327
+ if (v.similarTitles.completeness === 'partial') {
1328
+ lines.push('⚠️ 疑似重复只比较了部分笔记:可能漏报' +
1329
+ (v.similarTitles.droppedGroups > 0 ? '(' + v.similarTitles.droppedGroups + ' 组超过 300 篇,只比较了前 300 篇)' : '') +
1330
+ (v.completeness === 'partial' ? '(笔记扫描触顶)' : ''));
1331
+ }
1332
+ if (v.completeness === 'partial') {
1333
+ lines.push('⚠️ 笔记数触到扫描上限(' + v.scanLimit + ' 篇):结果不完整(只会漏报,不会误报),先归档旧笔记再跑一次');
1334
+ }
1335
+ else if (v.completeness === 'unknown') {
1336
+ lines.push('⚠️ 扫描结果无法完整解析:下面的数字不能当成全部(可能少报)');
1337
+ }
1338
+ if (oneWay.completeness === 'partial')
1136
1339
  lines.push('⚠️ 建图笔记载入触到上限:单向链接可能误报(回链边未加载),先归档旧笔记再跑一次');
1340
+ else if (oneWay.completeness === 'unknown')
1341
+ lines.push('⚠️ 无法确认单向链接的边集是否完整(旧版 zk 未给出载入篇数):可能误报');
1342
+ if (v.indexLag)
1343
+ lines.push('⚠️ 索引可能落后:' + v.indexLag);
1137
1344
  lines.push('(只报告,没有改动任何文件)');
1138
1345
  return text(lines.join('\n'));
1139
1346
  },
@@ -1165,6 +1372,8 @@ export function buildTools(workspaceOf = () => processWorkspace()) {
1165
1372
  windowDays: { type: 'number' },
1166
1373
  since: { type: 'string' },
1167
1374
  truncated: { type: 'boolean' },
1375
+ completeness: { type: 'string', enum: ['complete', 'partial', 'unknown'] },
1376
+ scanLimit: { type: 'number' },
1168
1377
  graphSkipped: { type: 'boolean' },
1169
1378
  graphBudget: { type: 'number' },
1170
1379
  memory: objSchema({
@@ -1173,6 +1382,10 @@ export function buildTools(workspaceOf = () => processWorkspace()) {
1173
1382
  totalWords: { type: 'number' },
1174
1383
  budget: { type: 'number' },
1175
1384
  headroom: { type: 'number' },
1385
+ /** G1:与 zk_lint.memoryLinks 同一口径的格式债 / 退役计数 */
1386
+ undated: { type: 'number' },
1387
+ unlinked: { type: 'number' },
1388
+ retired: { type: 'number' },
1176
1389
  files: {
1177
1390
  type: 'array',
1178
1391
  items: objSchema({
@@ -1183,7 +1396,7 @@ export function buildTools(workspaceOf = () => processWorkspace()) {
1183
1396
  retiredWords: { type: 'number' },
1184
1397
  }, ['name', 'present', 'words', 'originalWords', 'retiredWords']),
1185
1398
  },
1186
- }, ['words', 'personaWords', 'totalWords', 'budget', 'headroom', 'files']),
1399
+ }, ['words', 'personaWords', 'totalWords', 'budget', 'headroom', 'undated', 'unlinked', 'retired', 'files']),
1187
1400
  counts: objSchema({
1188
1401
  window: { type: 'number' },
1189
1402
  daily: { type: 'number' },
@@ -1228,7 +1441,7 @@ export function buildTools(workspaceOf = () => processWorkspace()) {
1228
1441
  reason: { type: 'string', enum: ['stale', 'source-missing', 'source-superseded'] },
1229
1442
  }, ['entry', 'date', 'age', 'reason']),
1230
1443
  },
1231
- }, ['notebook', 'windowDays', 'since', 'truncated', 'graphSkipped', 'graphBudget', 'memory', 'counts', 'newNotes', 'alreadyPromoted', 'backlog', 'rejected', 'topCited', 'dailyLooseEnds', 'retireCandidates']),
1444
+ }, ['notebook', 'windowDays', 'since', 'truncated', 'completeness', 'scanLimit', 'graphSkipped', 'graphBudget', 'memory', 'counts', 'newNotes', 'alreadyPromoted', 'backlog', 'rejected', 'topCited', 'dailyLooseEnds', 'retireCandidates']),
1232
1445
  },
1233
1446
  async run(args, env) {
1234
1447
  const cfg = configFor(env.workspace, env.sessionId);
@@ -1309,8 +1522,10 @@ export function buildTools(workspaceOf = () => processWorkspace()) {
1309
1522
  }
1310
1523
  if (!v.newNotes.length && !v.dailyLooseEnds.length && !v.topCited.length)
1311
1524
  lines.push('这个窗口里没有新材料。');
1312
- if (v.truncated)
1313
- lines.push('⚠️ 笔记数触到扫描上限:窗口与排名都不完整');
1525
+ if (v.completeness === 'partial')
1526
+ lines.push('⚠️ 笔记数触到扫描上限(' + v.scanLimit + ' 篇):窗口与排名都不完整');
1527
+ else if (v.completeness === 'unknown')
1528
+ lines.push('⚠️ 扫描结果无法完整解析:窗口与排名可能不完整');
1314
1529
  if (v.graphSkipped) {
1315
1530
  lines.push('⚠️ 库超过全图统计上限(' + v.graphBudget + ' 篇),这次没统计入链:被引数与 topCited 是空的,不代表没人引用;可在设置页调整「全图统计上限(篇)」(graphBudgetNotes)');
1316
1531
  }
@@ -1342,7 +1557,9 @@ export function buildTools(workspaceOf = () => processWorkspace()) {
1342
1557
  type: 'array',
1343
1558
  items: objSchema({ tag: { type: 'string' }, count: { type: 'number' } }, ['tag', 'count']),
1344
1559
  },
1345
- }, ['notebook', 'defaultNotebook', 'pinned', 'notes', 'tags', 'brokenLinks', 'orphans', 'archived', 'superseded', 'byDir', 'byTag']),
1560
+ completeness: { type: 'string', enum: ['complete', 'partial', 'unknown'] },
1561
+ scanLimit: { type: 'number' },
1562
+ }, ['notebook', 'defaultNotebook', 'pinned', 'notes', 'tags', 'brokenLinks', 'orphans', 'archived', 'superseded', 'byDir', 'byTag', 'completeness', 'scanLimit']),
1346
1563
  },
1347
1564
  async run(_args, env) {
1348
1565
  const cfg = configFor(env.workspace, env.sessionId);
@@ -1367,9 +1584,13 @@ export function buildTools(workspaceOf = () => processWorkspace()) {
1367
1584
  const tags = v.byTag.length
1368
1585
  ? '\n标签:' + v.byTag.map((t) => `#${t.tag} ${t.count}`).join(' · ')
1369
1586
  : '';
1587
+ const atLeast = v.completeness === 'complete' ? '' : '≥';
1588
+ const partial = v.completeness === 'partial'
1589
+ ? `\n⚠️ 只扫描了前 ${v.scanLimit} 篇:上面的数字是下限`
1590
+ : v.completeness === 'unknown' ? '\n⚠️ 扫描结果无法完整解析:上面的数字可能偏少' : '';
1370
1591
  return text(`笔记本 ${v.notebook}${drift}\n` +
1371
- `笔记 ${v.notes} 篇 · 标签 ${v.tags} 个 · 断链 ${v.brokenLinks} 篇 · 孤立 ${v.orphans} 篇 · 归档 ${v.archived} 篇(superseded ${v.superseded})` +
1372
- dirs + tags);
1592
+ `笔记 ${atLeast}${v.notes} 篇 · 标签 ${atLeast}${v.tags} 个 · 断链 ${v.brokenLinks} 篇 · 孤立 ${v.orphans} 篇 · 归档 ${atLeast}${v.archived} 篇(superseded ${atLeast}${v.superseded})` +
1593
+ dirs + tags + partial);
1373
1594
  },
1374
1595
  }),
1375
1596
  t({