dsh-zdiary-kit 3.3.0 → 3.6.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.
@@ -43,8 +43,9 @@ const LINT_ONE_WAY = objSchema({
43
43
  bodyOnly: { type: 'number' },
44
44
  linksOnly: { type: 'boolean' },
45
45
  edgesTruncated: { type: 'boolean' },
46
+ completeness: { type: 'string', enum: ['complete', 'partial', 'unknown'] },
46
47
  items: { type: 'array', items: LINT_ONE_WAY_ITEM },
47
- }, ['total', 'edges', 'bodyOnly', 'linksOnly', 'edgesTruncated', 'items']);
48
+ }, ['total', 'edges', 'bodyOnly', 'linksOnly', 'edgesTruncated', 'completeness', 'items']);
48
49
  const LINT_STALE = objSchema({
49
50
  total: { type: 'number' },
50
51
  items: {
@@ -63,6 +64,8 @@ const LINT_DUPLICATE = objSchema({
63
64
  const LINT_SIMILAR = objSchema({
64
65
  total: { type: 'number' },
65
66
  truncated: { type: 'boolean' },
67
+ completeness: { type: 'string', enum: ['complete', 'partial', 'unknown'] },
68
+ droppedGroups: { type: 'number' },
66
69
  items: {
67
70
  type: 'array',
68
71
  items: objSchema({
@@ -71,7 +74,7 @@ const LINT_SIMILAR = objSchema({
71
74
  score: { type: 'number' },
72
75
  }, ['titles', 'paths', 'score']),
73
76
  },
74
- }, ['total', 'truncated', 'items']);
77
+ }, ['total', 'truncated', 'completeness', 'droppedGroups', 'items']);
75
78
  /** 记忆层体检:MEMORY.md / USER.md 里的来源链是否还指向活笔记 */
76
79
  const LINT_MEMORY = objSchema({
77
80
  files: { type: 'number' },
@@ -380,6 +383,9 @@ export function buildTools(workspaceOf = () => processWorkspace()) {
380
383
  notebook: { type: 'string' },
381
384
  count: { type: 'number' },
382
385
  matchStrategy: { type: 'string', enum: ['fts', 'regex', 'mixed'] },
386
+ completeness: { type: 'string', enum: ['complete', 'partial', 'unknown'] },
387
+ hasMore: { type: 'boolean' },
388
+ scanned: { type: 'number' },
383
389
  notes: {
384
390
  type: 'array',
385
391
  items: objSchema({
@@ -391,7 +397,7 @@ export function buildTools(workspaceOf = () => processWorkspace()) {
391
397
  lead: { type: 'string' },
392
398
  }, ['title', 'path', 'absPath', 'tags', 'created', 'lead']),
393
399
  },
394
- }, ['notebook', 'count', 'matchStrategy', 'notes']),
400
+ }, ['notebook', 'count', 'matchStrategy', 'completeness', 'hasMore', 'scanned', 'notes']),
395
401
  },
396
402
  async run(args, env) {
397
403
  const cfg = configFor(env.workspace, env.sessionId);
@@ -410,17 +416,25 @@ export function buildTools(workspaceOf = () => processWorkspace()) {
410
416
  notebook: cfg.notebook,
411
417
  count: result.notes.length,
412
418
  matchStrategy: result.matchStrategy,
419
+ completeness: result.completeness,
420
+ hasMore: result.hasMore,
421
+ scanned: result.scanned,
413
422
  notes: result.notes.map((n) => ({ title: n.title, path: n.path, absPath: n.absPath, tags: n.tags, created: dateOnly(n.created), lead: n.lead })),
414
423
  };
415
424
  },
416
425
  render(_args, value) {
417
426
  const v = value;
418
- if (!v.count)
419
- return text(`没有匹配的笔记(笔记本 ${v.notebook})`);
427
+ if (!v.count) {
428
+ return text(`没有匹配的笔记(笔记本 ${v.notebook})` +
429
+ (v.completeness === 'unknown' ? ';但这次检索结果无法完整解析,不能当作「库里没有」' : ''));
430
+ }
420
431
  const how = v.matchStrategy === 'mixed'
421
432
  ? '(中文:全文 + 子串合并,已补上全文索引漏掉的)'
422
433
  : v.matchStrategy === 'regex' ? '(全文无结果,已退回子串匹配)' : '';
423
- return text(`${v.count} 条(笔记本 ${v.notebook})${how}\n` + v.notes.map(noteLine).join('\n'));
434
+ const tail = v.completeness === 'unknown'
435
+ ? '\n⚠️ 无法确认结果是否完整(解析失败 / 补充检索失败),先别把它当成全部命中'
436
+ : v.hasMore ? `\n⚠️ 还有更多匹配没返回(已检查 ${v.scanned} 条候选);要更全就提高 limit 或加过滤条件` : '';
437
+ return text(`${v.count} 条(笔记本 ${v.notebook})${how}\n` + v.notes.map(noteLine).join('\n') + tail);
424
438
  },
425
439
  }),
426
440
  t({
@@ -450,6 +464,9 @@ export function buildTools(workspaceOf = () => processWorkspace()) {
450
464
  schema: objSchema({
451
465
  notebook: { type: 'string' },
452
466
  count: { type: 'number' },
467
+ completeness: { type: 'string', enum: ['complete', 'partial', 'unknown'] },
468
+ hasMore: { type: 'boolean' },
469
+ scanned: { type: 'number' },
453
470
  notes: {
454
471
  type: 'array',
455
472
  items: objSchema({
@@ -465,13 +482,13 @@ export function buildTools(workspaceOf = () => processWorkspace()) {
465
482
  archived: { type: 'boolean' },
466
483
  }, ['title', 'path', 'absPath', 'type', 'status', 'authority', 'tags', 'created', 'lead', 'archived']),
467
484
  },
468
- }, ['notebook', 'count', 'notes']),
485
+ }, ['notebook', 'count', 'completeness', 'hasMore', 'scanned', 'notes']),
469
486
  },
470
487
  async run(args, env) {
471
488
  const cfg = configFor(env.workspace, env.sessionId);
472
489
  await ensureNotebook(cfg, env.signal);
473
490
  const includeArchived = args.include_archived === true;
474
- const notes = await searchNotes(cfg, {
491
+ const result = await searchNotesDetailed(cfg, {
475
492
  query: args.query ? String(args.query) : undefined,
476
493
  tags: Array.isArray(args.tags) ? args.tags.map(String) : undefined,
477
494
  paths: Array.isArray(args.dirs) ? args.dirs.map(String) : undefined,
@@ -486,9 +503,13 @@ export function buildTools(workspaceOf = () => processWorkspace()) {
486
503
  limit: args.limit === undefined ? 10 : Number(args.limit),
487
504
  sort: args.sort ? String(args.sort) : 'created-desc',
488
505
  }, env.signal);
506
+ const notes = result.notes;
489
507
  return {
490
508
  notebook: cfg.notebook,
491
509
  count: notes.length,
510
+ completeness: result.completeness,
511
+ hasMore: result.hasMore,
512
+ scanned: result.scanned,
492
513
  notes: notes.map((n) => ({
493
514
  title: n.title,
494
515
  path: n.path,
@@ -506,13 +527,18 @@ export function buildTools(workspaceOf = () => processWorkspace()) {
506
527
  },
507
528
  render(_args, value) {
508
529
  const v = value;
509
- if (!v.count)
510
- return text(`没有匹配的笔记(笔记本 ${v.notebook})`);
530
+ if (!v.count) {
531
+ return text(`没有匹配的笔记(笔记本 ${v.notebook})` +
532
+ (v.completeness === 'unknown' ? ';但这次检索结果无法完整解析,不能当作「记忆里没有」' : ''));
533
+ }
534
+ const tail = v.completeness === 'unknown'
535
+ ? '\n⚠️ 无法确认结果是否完整(解析失败 / 补充检索失败),先别把它当成全部命中'
536
+ : v.hasMore ? `\n⚠️ 还有更多匹配没返回(已检查 ${v.scanned} 条候选);要更全就提高 limit 或缩小过滤范围` : '';
511
537
  const lines = v.notes.map((n, i) => {
512
538
  const badges = [String(n.type || '—'), String(n.status || 'no-status'), n.archived ? '已归档' : ''].filter(Boolean);
513
539
  return `${i + 1}. ${String(n.title)} [${badges.join(' · ')}]\n ${String(n.absPath || n.path)} · ${String(n.created)}${String(n.lead) ? '\n ' + String(n.lead) : ''}`;
514
540
  });
515
- return text(`${v.count} 条(笔记本 ${v.notebook})\n` + lines.join('\n'));
541
+ return text(`${v.count} 条(笔记本 ${v.notebook})\n` + lines.join('\n') + tail);
516
542
  },
517
543
  }),
518
544
  t({
@@ -1042,8 +1068,9 @@ export function buildTools(workspaceOf = () => processWorkspace()) {
1042
1068
  'edges 是全部单向边数(items 截到 50 条时仍计全量),bodyOnly 是正文引用(不在 ## Links / ## 链接 小节)的单向边数。' +
1043
1069
  'links_only=true 时只列 Links 小节的单向链接,正文引用只进 bodyOnly,适合把桶当可修清单。' +
1044
1070
  'S 或 X 是日记的边不算 —— 日记天然是出边,回链它没有意义。' +
1045
- '笔记数触到扫描上限只会漏报;但 oneWayLinks.edgesTruncated=true 表示建图笔记载入触顶、边集可能不完整 —— ' +
1046
- '缺掉的回链边会把双向误判成单向,这是唯一可能误报的截断,看到它先归档旧笔记再重跑。' +
1071
+ '笔记数触到扫描上限只会漏报;但 oneWayLinks.edgesTruncated=true 表示边集可能不完整(小库建图触顶,' +
1072
+ '或大库按篇反查触到 50 目标 / 60 子进程的上限)—— 缺掉的回链边会把双向误判成单向,' +
1073
+ '这是唯一可能误报的截断,看到它先缩小排查范围再重跑。' +
1047
1074
  '只读:不改任何笔记。拿到清单后自己判断先修哪个,再用 zk_link / zk_append / zk_supersede 动手。',
1048
1075
  parameters: {
1049
1076
  type: 'object',
@@ -1058,6 +1085,8 @@ export function buildTools(workspaceOf = () => processWorkspace()) {
1058
1085
  notebook: { type: 'string' },
1059
1086
  notes: { type: 'number' },
1060
1087
  truncated: { type: 'boolean' },
1088
+ completeness: { type: 'string', enum: ['complete', 'partial', 'unknown'] },
1089
+ scanLimit: { type: 'number' },
1061
1090
  staleDays: { type: 'number' },
1062
1091
  parseErrors: LINT_PARSE,
1063
1092
  orphans: LINT_BUCKET,
@@ -1074,7 +1103,8 @@ export function buildTools(workspaceOf = () => processWorkspace()) {
1074
1103
  persona: LINT_PERSONA,
1075
1104
  timeline: LINT_TIMELINE,
1076
1105
  indexHint: { type: 'boolean' },
1077
- }, ['notebook', 'notes', 'truncated', 'staleDays', 'parseErrors', 'orphans', 'brokenLinks', 'stale', 'tagless', 'oneWayLinks', 'duplicateTitles', 'similarTitles', 'memoryLinks', 'incomplete', 'tags', 'template', 'persona', 'timeline', 'indexHint']),
1106
+ indexLag: { type: 'string' },
1107
+ }, ['notebook', 'notes', 'truncated', 'completeness', 'scanLimit', 'staleDays', 'parseErrors', 'orphans', 'brokenLinks', 'stale', 'tagless', 'oneWayLinks', 'duplicateTitles', 'similarTitles', 'memoryLinks', 'incomplete', 'tags', 'template', 'persona', 'timeline', 'indexHint', 'indexLag']),
1078
1108
  },
1079
1109
  async run(args, env) {
1080
1110
  const cfg = configFor(env.workspace, env.sessionId);
@@ -1127,12 +1157,23 @@ export function buildTools(workspaceOf = () => processWorkspace()) {
1127
1157
  if (memLine)
1128
1158
  lines.push(memLine);
1129
1159
  lines.push(...formatLintExtras(v));
1130
- if (v.similarTitles.truncated)
1131
- lines.push('⚠️ 疑似重复只比较了部分笔记(同目录超过 300 篇或扫描触顶):可能漏报');
1132
- if (v.truncated)
1133
- lines.push('⚠️ 笔记数触到扫描上限:结果不完整(只会漏报,不会误报),先归档旧笔记再跑一次');
1134
- if (oneWay.edgesTruncated)
1160
+ if (v.similarTitles.completeness === 'partial') {
1161
+ lines.push('⚠️ 疑似重复只比较了部分笔记:可能漏报' +
1162
+ (v.similarTitles.droppedGroups > 0 ? '(' + v.similarTitles.droppedGroups + ' 组超过 300 篇,只比较了前 300 篇)' : '') +
1163
+ (v.completeness === 'partial' ? '(笔记扫描触顶)' : ''));
1164
+ }
1165
+ if (v.completeness === 'partial') {
1166
+ lines.push('⚠️ 笔记数触到扫描上限(' + v.scanLimit + ' 篇):结果不完整(只会漏报,不会误报),先归档旧笔记再跑一次');
1167
+ }
1168
+ else if (v.completeness === 'unknown') {
1169
+ lines.push('⚠️ 扫描结果无法完整解析:下面的数字不能当成全部(可能少报)');
1170
+ }
1171
+ if (oneWay.completeness === 'partial')
1135
1172
  lines.push('⚠️ 建图笔记载入触到上限:单向链接可能误报(回链边未加载),先归档旧笔记再跑一次');
1173
+ else if (oneWay.completeness === 'unknown')
1174
+ lines.push('⚠️ 无法确认单向链接的边集是否完整(旧版 zk 未给出载入篇数):可能误报');
1175
+ if (v.indexLag)
1176
+ lines.push('⚠️ 索引可能落后:' + v.indexLag);
1136
1177
  lines.push('(只报告,没有改动任何文件)');
1137
1178
  return text(lines.join('\n'));
1138
1179
  },
@@ -1145,6 +1186,8 @@ export function buildTools(workspaceOf = () => processWorkspace()) {
1145
1186
  '会读 MEMORY.md:已经晋升过的(`[[链接]]` 命中或条目里写了标题)移出候选、进 alreadyPromoted —— 不会每周原样重复。' +
1146
1187
  '退役行里的旧标题不再算已晋升,但 `→ [[新结论]]` 仍算。' +
1147
1188
  'backlog 是窗口外仍未晋升的笔记(按被引数),漏做一次不会永久掉队。' +
1189
+ '库超过全图统计上限时不再建全图统计入链(默认 2000 篇,设置页可调;graphBudget 给出生效值):' +
1190
+ 'graphSkipped=true,cited / citedBy / topCited 为空 —— 那是「没算」,不是「没人引」。' +
1148
1191
  'memory 给记忆余量(内容词 + 提示 = 总词,余量按总词算,可以为负);retireCandidates 给「可考虑退役」的条目' +
1149
1192
  '(来源归档 / 不存在、超过 ' + STALE_DAYS + ' 天未复核;显式写 archive/ 的有意引用不算)。' +
1150
1193
  'days 省略时窗口 = 距 DREAMS.md「上次做梦」的天数(没有则 7 天)。' +
@@ -1162,6 +1205,10 @@ export function buildTools(workspaceOf = () => processWorkspace()) {
1162
1205
  windowDays: { type: 'number' },
1163
1206
  since: { type: 'string' },
1164
1207
  truncated: { type: 'boolean' },
1208
+ completeness: { type: 'string', enum: ['complete', 'partial', 'unknown'] },
1209
+ scanLimit: { type: 'number' },
1210
+ graphSkipped: { type: 'boolean' },
1211
+ graphBudget: { type: 'number' },
1165
1212
  memory: objSchema({
1166
1213
  words: { type: 'number' },
1167
1214
  personaWords: { type: 'number' },
@@ -1223,7 +1270,7 @@ export function buildTools(workspaceOf = () => processWorkspace()) {
1223
1270
  reason: { type: 'string', enum: ['stale', 'source-missing', 'source-superseded'] },
1224
1271
  }, ['entry', 'date', 'age', 'reason']),
1225
1272
  },
1226
- }, ['notebook', 'windowDays', 'since', 'truncated', 'memory', 'counts', 'newNotes', 'alreadyPromoted', 'backlog', 'rejected', 'topCited', 'dailyLooseEnds', 'retireCandidates']),
1273
+ }, ['notebook', 'windowDays', 'since', 'truncated', 'completeness', 'scanLimit', 'graphSkipped', 'graphBudget', 'memory', 'counts', 'newNotes', 'alreadyPromoted', 'backlog', 'rejected', 'topCited', 'dailyLooseEnds', 'retireCandidates']),
1227
1274
  },
1228
1275
  async run(args, env) {
1229
1276
  const cfg = configFor(env.workspace, env.sessionId);
@@ -1304,8 +1351,13 @@ export function buildTools(workspaceOf = () => processWorkspace()) {
1304
1351
  }
1305
1352
  if (!v.newNotes.length && !v.dailyLooseEnds.length && !v.topCited.length)
1306
1353
  lines.push('这个窗口里没有新材料。');
1307
- if (v.truncated)
1308
- lines.push('⚠️ 笔记数触到扫描上限:窗口与排名都不完整');
1354
+ if (v.completeness === 'partial')
1355
+ lines.push('⚠️ 笔记数触到扫描上限(' + v.scanLimit + ' 篇):窗口与排名都不完整');
1356
+ else if (v.completeness === 'unknown')
1357
+ lines.push('⚠️ 扫描结果无法完整解析:窗口与排名可能不完整');
1358
+ if (v.graphSkipped) {
1359
+ lines.push('⚠️ 库超过全图统计上限(' + v.graphBudget + ' 篇),这次没统计入链:被引数与 topCited 是空的,不代表没人引用;可在设置页调整「全图统计上限(篇)」(graphBudgetNotes)');
1360
+ }
1309
1361
  lines.push('(只报告:MEMORY.md / DREAMS.md 由你按 AGENTS.md 写)');
1310
1362
  return text(lines.join('\n'));
1311
1363
  },
@@ -1334,7 +1386,9 @@ export function buildTools(workspaceOf = () => processWorkspace()) {
1334
1386
  type: 'array',
1335
1387
  items: objSchema({ tag: { type: 'string' }, count: { type: 'number' } }, ['tag', 'count']),
1336
1388
  },
1337
- }, ['notebook', 'defaultNotebook', 'pinned', 'notes', 'tags', 'brokenLinks', 'orphans', 'archived', 'superseded', 'byDir', 'byTag']),
1389
+ completeness: { type: 'string', enum: ['complete', 'partial', 'unknown'] },
1390
+ scanLimit: { type: 'number' },
1391
+ }, ['notebook', 'defaultNotebook', 'pinned', 'notes', 'tags', 'brokenLinks', 'orphans', 'archived', 'superseded', 'byDir', 'byTag', 'completeness', 'scanLimit']),
1338
1392
  },
1339
1393
  async run(_args, env) {
1340
1394
  const cfg = configFor(env.workspace, env.sessionId);
@@ -1359,9 +1413,13 @@ export function buildTools(workspaceOf = () => processWorkspace()) {
1359
1413
  const tags = v.byTag.length
1360
1414
  ? '\n标签:' + v.byTag.map((t) => `#${t.tag} ${t.count}`).join(' · ')
1361
1415
  : '';
1416
+ const atLeast = v.completeness === 'complete' ? '' : '≥';
1417
+ const partial = v.completeness === 'partial'
1418
+ ? `\n⚠️ 只扫描了前 ${v.scanLimit} 篇:上面的数字是下限`
1419
+ : v.completeness === 'unknown' ? '\n⚠️ 扫描结果无法完整解析:上面的数字可能偏少' : '';
1362
1420
  return text(`笔记本 ${v.notebook}${drift}\n` +
1363
- `笔记 ${v.notes} 篇 · 标签 ${v.tags} 个 · 断链 ${v.brokenLinks} 篇 · 孤立 ${v.orphans} 篇 · 归档 ${v.archived} 篇(superseded ${v.superseded})` +
1364
- dirs + tags);
1421
+ `笔记 ${atLeast}${v.notes} 篇 · 标签 ${atLeast}${v.tags} 个 · 断链 ${v.brokenLinks} 篇 · 孤立 ${v.orphans} 篇 · 归档 ${atLeast}${v.archived} 篇(superseded ${atLeast}${v.superseded})` +
1422
+ dirs + tags + partial);
1365
1423
  },
1366
1424
  }),
1367
1425
  t({
package/dist/lib/dream.js CHANGED
@@ -13,7 +13,7 @@
13
13
  */
14
14
  import fs from 'node:fs';
15
15
  import path from 'node:path';
16
- import { allNotes, graphEdges, localDate, MAX_SCAN } from './zk.js';
16
+ import { GRAPH_BUDGET_NOTES, graphEdges, localDate, scanNotes } from './zk.js';
17
17
  import { parseFrontmatter } from './frontmatter.js';
18
18
  // memory.ts 也 import 本模块(DREAM_INTERVAL_DAYS / daysSinceDream):这里是运行期才取用,
19
19
  // 循环引用在 ESM 下安全 —— 不要在模块顶层调用 memoryUsage。
@@ -286,8 +286,13 @@ export async function dreamNotebook(cfg, opts = {}, signal) {
286
286
  const windowDays = windowDaysOf(cfg, now, opts.days);
287
287
  const sinceMs = now.getTime() - windowDays * 86_400_000;
288
288
  // 顺序跑:两个 zk 进程同时补索引会撞 SQLite 写锁(lint 里同样处理)
289
- const notes = await allNotes(cfg, {}, signal);
290
- const edges = (await graphEdges(cfg, signal)).edges;
289
+ const scan = await scanNotes(cfg, {}, signal);
290
+ const notes = scan.notes;
291
+ // 全图在 10k 上 26–31 s / 17 MB(plan §0.5.1):超过预算就不建,并显式告诉调用方。
292
+ // 预算来自配置(设置页可调);opts.graphBudget 只给测试覆盖。
293
+ const graphBudget = Math.max(0, Math.trunc(opts.graphBudget ?? cfg.graphBudgetNotes ?? GRAPH_BUDGET_NOTES));
294
+ const graphReady = notes.length <= graphBudget;
295
+ const edges = graphReady ? (await graphEdges(cfg, signal)).edges : [];
291
296
  // 入链来源按目标分组:既算「被引几次」,也给 dream 一份上下文(谁在引它)
292
297
  const inbound = new Map();
293
298
  for (const edge of edges) {
@@ -415,7 +420,11 @@ export async function dreamNotebook(cfg, opts = {}, signal) {
415
420
  notebook: cfg.notebook,
416
421
  windowDays,
417
422
  since: localDate(new Date(sinceMs).toISOString()),
418
- truncated: notes.length >= MAX_SCAN,
423
+ truncated: scan.completeness !== 'complete',
424
+ completeness: scan.completeness,
425
+ scanLimit: scan.limit,
426
+ graphSkipped: !graphReady,
427
+ graphBudget,
419
428
  counts: {
420
429
  window: windowNotes.length,
421
430
  daily: windowNotes.filter((n) => isUnder(n.path, cfg.dailyDir)).length,
package/dist/lib/exec.js CHANGED
@@ -2,14 +2,22 @@
2
2
  import { execFile } from 'node:child_process';
3
3
  import fs from 'node:fs';
4
4
  import path from 'node:path';
5
+ /**
6
+ * 成本表用的进程内计数(scripts/bench.ts):起了几次子进程、子进程回了多少字节。
7
+ * 生产路径只多两次整数加法,没有其它影响;bench 在每次用例前清零。
8
+ */
9
+ export const execStats = { calls: 0, bytes: 0 };
5
10
  export class ExecError extends Error {
6
11
  code;
7
12
  stderr;
8
- constructor(message, code, stderr) {
13
+ /** 被我们自己的超时 / abort 杀掉(不是子进程自己退出)—— 建索引超时要靠它区分 */
14
+ killed;
15
+ constructor(message, code, stderr, killed = false) {
9
16
  super(message);
10
17
  this.name = 'ExecError';
11
18
  this.code = code;
12
19
  this.stderr = stderr;
20
+ this.killed = killed;
13
21
  }
14
22
  }
15
23
  /** 跑一个可执行文件,返回 { code, stdout, stderr };ENOENT / 超时会 throw */
@@ -26,10 +34,13 @@ export function run(exe, args, opts = {}) {
26
34
  }, (err, stdout, stderr) => {
27
35
  const out = String(stdout ?? '');
28
36
  const errText = String(stderr ?? '');
37
+ execStats.calls += 1;
38
+ execStats.bytes += Buffer.byteLength(out) + Buffer.byteLength(errText);
29
39
  if (err) {
30
40
  const code = typeof err.code === 'number' ? err.code : null;
31
41
  const hint = code === null ? String(err.message ?? err) : '';
32
- reject(new ExecError(hint || (errText.trim() || `exit ${code}`), code, errText));
42
+ const killed = err.killed === true;
43
+ reject(new ExecError(hint || (errText.trim() || `exit ${code}`), code, errText, killed));
33
44
  return;
34
45
  }
35
46
  resolve({ code: 0, stdout: out, stderr: errText });
package/dist/lib/lint.js CHANGED
@@ -1,8 +1,9 @@
1
1
  /**
2
2
  * 巡检(M3):只报告,不改任何笔记(计划 §3 D5)。
3
3
  *
4
- * 一次 `zk list` 拿全量,再用 zk 原生的两个过滤器(孤儿 / 断链)各跑一次进程,外加一次 `zk graph` 拿全库的边;
5
- * 「陈旧」「重名」「单向链接」在 JS 里算。200 条笔记上 5 次进程就够 —— 不允许按笔记逐条跑 zk。
4
+ * 一次 `zk list` 拿全量,再用 zk 原生的几个过滤器(孤儿 / 断链 / 无标签 / 缺回链)各跑一次进程;
5
+ * 「陈旧」「重名」在 JS 里算,单向链接小库用一次 `zk graph` 的边、大库按篇反查(见 `oneWayByQueries`)。
6
+ * 200 条笔记上 5 次进程就够 —— 大库那条路也按「问题数」而不是「篇数」计费。
6
7
  *
7
8
  * 「陈旧」为什么自己算:zk 的 `stale` 不是内置过滤器,`zk list stale` 只在你自己的
8
9
  * `[filter]` 里定义过才存在(Z3 只说了位置参数语法,没说它是内置的)。所以阈值由插件定。
@@ -12,7 +13,7 @@
12
13
  *
13
14
  * 「单向链接」为什么自己算:zk 的 `--missing-backlink` 是「至少有一条单向链接」(S 链 X、X 不回链),
14
15
  * 而日记天然是一串出边 —— 日记提过的每篇笔记都会常年挂在桶里。那不是「笔记没接上」,是正常的引用方向。
15
- * 所以改成在 `zk graph` 的边上算,只报**非日记来源**的单向链接。
16
+ * 所以在边上自己算,只报**非日记来源**的单向链接。
16
17
  *
17
18
  * 解析失败单列一桶:frontmatter 写坏(典型是 `tags: [#你好世界]`,`#` 不是 tag 前缀)时
18
19
  * zk 只在 stderr 吭一声就跳过那篇,它于是从索引里消失 —— 搜不到,也不进上面任何一个桶。
@@ -23,7 +24,7 @@
23
24
  */
24
25
  import fs from 'node:fs';
25
26
  import path from 'node:path';
26
- import { allNotes, graphEdges, localDate, MAX_SCAN, notesWithFlag, parseErrorWarnings } from './zk.js';
27
+ import { backlinksOf, GRAPH_BUDGET_NOTES, graphEdges, indexLagHint, localDate, MAX_SCAN, scanNotes, scanNotesWithFlag, outlinksOf, parseErrorWarnings, } from './zk.js';
27
28
  import { normalizeTitle, resolveWikiTarget, WIKI_LINK, wikiIndex } from './wikilink.js';
28
29
  import { parseFrontmatter } from './frontmatter.js';
29
30
  import { daysSinceDate, entryDate, isRetiredEntry, memoryFormatDebt, splitMemoryEntries } from './memory-format.js';
@@ -34,6 +35,12 @@ import { isDayString } from './dates.js';
34
35
  import { similarKeyOf, similarScore } from './similar.js';
35
36
  /** 每类最多回多少条(计划 §4 M3);总数另给 */
36
37
  export const MAX_ITEMS = 50;
38
+ /**
39
+ * 大库按篇反查的上限(plan §9.3):目标数 50、子进程 60,取先到者(每个目标要 2 个进程,
40
+ * 实际约 30 个目标;10k 库上每个约 0.45 s)。超了就报 `edgesTruncated`,不静默少报。
41
+ */
42
+ const MAX_ONE_WAY_TARGETS = 50;
43
+ const MAX_ONE_WAY_QUERIES = 60;
37
44
  /** 时间轴只扫最近多少天(计划 §2 D4):一年日记会报几百条旧问题,把今天的问题挤出 50 条上限 */
38
45
  export const TIMELINE_WINDOW_DAYS = 90;
39
46
  /** 超过这个大小的日记不读(doctor / lint 不该把 2 GiB 的日志拉进内存):跳过并计入 skipped */
@@ -84,11 +91,13 @@ export function similarTitles(notes, scanTruncated, max = MAX_ITEMS) {
84
91
  groups.set(dir, list);
85
92
  }
86
93
  let truncated = scanTruncated;
94
+ let droppedGroups = 0;
87
95
  const found = [];
88
96
  for (const group of groups.values()) {
89
97
  let list = group;
90
98
  if (list.length > SIMILAR_GROUP_MAX) {
91
99
  truncated = true;
100
+ droppedGroups += 1;
92
101
  list = list.slice(0, SIMILAR_GROUP_MAX);
93
102
  }
94
103
  for (let i = 0; i < list.length; i++) {
@@ -111,7 +120,8 @@ export function similarTitles(notes, scanTruncated, max = MAX_ITEMS) {
111
120
  }
112
121
  }
113
122
  found.sort((a, b) => b.score - a.score || a.paths[0].localeCompare(b.paths[0]));
114
- return { total: found.length, truncated, items: found.slice(0, max) };
123
+ const completeness = truncated ? 'partial' : 'complete';
124
+ return { total: found.length, truncated, completeness, droppedGroups, items: found.slice(0, max) };
115
125
  }
116
126
  /** 注入的三份 meta 里只有 MEMORY / USER 会写来源链接;AGENTS 是规则,不查 */
117
127
  const MEMORY_LINK_FILES = ['MEMORY.md', 'USER.md'];
@@ -666,14 +676,17 @@ export async function lintNotebook(cfg, opts = {}, signal) {
666
676
  const warnings = [];
667
677
  const dailyAbs = path.resolve(cfg.notebook, cfg.dailyDir);
668
678
  const isDaily = (abs) => path.resolve(abs) === dailyAbs || path.resolve(abs).startsWith(dailyAbs + path.sep);
669
- const notes = await allNotes(cfg, { warnings }, signal);
670
- const orphanAbs = await notesWithFlag(cfg, '--orphan', signal);
671
- const brokenAbs = await notesWithFlag(cfg, '--broken-links', signal);
672
- const taglessAbs = await notesWithFlag(cfg, '--tagless', signal);
673
- const graph = await graphEdges(cfg, signal);
674
- const edges = graph.edges;
675
- // 图里的路径是笔记本相对:先拼回绝对路径再判断是不是日记(isDaily 收的是绝对路径)
676
- const oneWay = oneWayLinks(edges, notes, (p) => isDaily(path.resolve(cfg.notebook, p)));
679
+ const scan = await scanNotes(cfg, { warnings }, signal);
680
+ const notes = scan.notes;
681
+ const orphanScan = await scanNotesWithFlag(cfg, '--orphan', signal);
682
+ const brokenScan = await scanNotesWithFlag(cfg, '--broken-links', signal);
683
+ const taglessScan = await scanNotesWithFlag(cfg, '--tagless', signal);
684
+ const orphanAbs = orphanScan.paths;
685
+ const brokenAbs = brokenScan.paths;
686
+ const taglessAbs = taglessScan.paths;
687
+ // 任一过滤器触顶都意味着对应桶少了;三态取最坏值(partial > unknown > complete)
688
+ const worst = (values) => values.includes('partial') ? 'partial' : values.includes('unknown') ? 'unknown' : 'complete';
689
+ const completeness = worst([scan.completeness, orphanScan.completeness, brokenScan.completeness, taglessScan.completeness]);
677
690
  // 别用 `path.resolve(n.absPath || n.path)`:absPath 缺失时相对路径会按进程 cwd 解析,键就错了。
678
691
  const byAbs = new Map(notes.map((n) => [n.absPath ? path.resolve(n.absPath) : path.resolve(cfg.notebook, n.path), n]));
679
692
  const byPath = new Map(notes.map((n) => [n.path, n]));
@@ -721,11 +734,127 @@ export async function lintNotebook(cfg, opts = {}, signal) {
721
734
  return 'body';
722
735
  return starts.some((s) => s >= section.start && s < section.end) ? 'links' : 'body';
723
736
  };
737
+ // ── 单向链接:小库一次全图;大库按篇反查(plan §0.5.1 结论 3)─────────────
738
+ // 全图在 10k / 1 链要 26–31 s / 17 MB,2–5 链会直接超过 60 s 超时;
739
+ // 单篇反链已经走 `backlinksOf`,巡检在超过预算时也走同一条路。
740
+ const sourceTextCache = new Map();
741
+ const sourceText = (rel) => {
742
+ const cached = sourceTextCache.get(rel);
743
+ if (cached !== undefined)
744
+ return cached;
745
+ let text = '';
746
+ try {
747
+ text = fs.readFileSync(path.resolve(cfg.notebook, rel), 'utf8');
748
+ }
749
+ catch {
750
+ text = '';
751
+ }
752
+ sourceTextCache.set(rel, text);
753
+ return text;
754
+ };
755
+ /** 按篇反查没有 snippetStart:自己扫源文件,判断链接写在 Links 小节还是正文 */
756
+ const linkWhereOf = (sourceRel, targetRel) => {
757
+ const text = sourceText(sourceRel);
758
+ if (!text)
759
+ return 'body';
760
+ const keys = new Set([targetRel, targetRel.replace(/\.md$/i, ''), path.basename(targetRel, path.extname(targetRel)), byPath.get(targetRel)?.title ?? '']
761
+ .map((k) => normalizeTitle(k))
762
+ .filter(Boolean));
763
+ const head = /^##[ \t]+(?:Links|链接)[ \t]*\r?$/m.exec(text);
764
+ let start = -1;
765
+ let end = -1;
766
+ if (head) {
767
+ start = head.index + head[0].length;
768
+ const next = /^#{1,2}[ \t]+\S/m.exec(text.slice(start));
769
+ end = next ? start + next.index : text.length;
770
+ }
771
+ for (const m of text.matchAll(WIKI_LINK)) {
772
+ if (!keys.has(normalizeTitle(String(m[1] ?? ''))))
773
+ continue;
774
+ const at = m.index ?? 0;
775
+ if (start >= 0 && at >= start && at < end)
776
+ return 'links';
777
+ }
778
+ return 'body';
779
+ };
780
+ /**
781
+ * 大库的单向链接:zk 先给「缺回链的目标」(一次 `--missing-backlink`),
782
+ * 再对每个目标 `--link-to` 取来源、对每个来源 `--linked-by` 判回链(缓存)。
783
+ * 成本随问题数增长,而不是随库大小增长;触到上限就报 partial,不静默少报。
784
+ */
785
+ const oneWayByQueries = async () => {
786
+ let left = MAX_ONE_WAY_QUERIES;
787
+ const spend = () => (left > 0 ? ((left -= 1), true) : false);
788
+ const missing = await scanNotesWithFlag(cfg, '--missing-backlink', signal);
789
+ let truncated = missing.completeness !== 'complete';
790
+ const targets = missing.paths
791
+ .map((abs) => path.relative(cfg.notebook, abs).split(path.sep).join('/'))
792
+ .filter((rel) => byPath.has(rel) && !isDaily(path.resolve(cfg.notebook, rel)))
793
+ .sort((a, b) => a.localeCompare(b));
794
+ const capped = targets.slice(0, MAX_ONE_WAY_TARGETS);
795
+ if (targets.length > capped.length)
796
+ truncated = true;
797
+ const rows = [];
798
+ for (const target of capped) {
799
+ if (!spend()) {
800
+ truncated = true;
801
+ break;
802
+ }
803
+ const back = await backlinksOf(cfg, target, { limit: MAX_SCAN }, signal);
804
+ if (back.truncated)
805
+ truncated = true;
806
+ if (!back.notes.length)
807
+ continue;
808
+ if (!spend()) {
809
+ truncated = true;
810
+ break;
811
+ }
812
+ // 回链方向是 T → S:取目标自己的出链,看它有没有连回来源
813
+ const linked = await outlinksOf(cfg, target, { limit: MAX_SCAN }, signal);
814
+ if (linked.truncated)
815
+ truncated = true;
816
+ const outs = new Set(linked.notes.map((n) => n.path));
817
+ const from = [];
818
+ for (const note of back.notes) {
819
+ if (note.path === target || isDaily(path.resolve(cfg.notebook, note.path)))
820
+ continue;
821
+ if (outs.has(note.path))
822
+ continue;
823
+ from.push({ path: note.path, where: linkWhereOf(note.path, target) });
824
+ }
825
+ if (from.length)
826
+ rows.push({ target, from: from.sort((a, b) => a.path.localeCompare(b.path)) });
827
+ }
828
+ return { rows, truncated };
829
+ };
830
+ // 预算来自配置(设置页可调);opts.graphBudget 只给测试覆盖
831
+ const graphBudget = Math.max(0, Math.trunc(opts.graphBudget ?? cfg.graphBudgetNotes ?? GRAPH_BUDGET_NOTES));
832
+ const oneWayRows = [];
833
+ let oneWayTruncated = false;
834
+ let oneWayCompleteness = 'complete';
835
+ if (notes.length <= graphBudget) {
836
+ const graph = await graphEdges(cfg, signal);
837
+ oneWayTruncated = graph.truncated;
838
+ oneWayCompleteness = graph.completeness;
839
+ // 图里的路径是笔记本相对:先拼回绝对路径再判断是不是日记(isDaily 收的是绝对路径)
840
+ for (const row of oneWayLinks(graph.edges, notes, (p) => isDaily(path.resolve(cfg.notebook, p)))) {
841
+ oneWayRows.push({
842
+ target: row.target,
843
+ from: row.from.map((s) => ({ path: s.path, where: whereOf(s.path, s.snippetStarts) })),
844
+ });
845
+ }
846
+ }
847
+ else {
848
+ const scanned = await oneWayByQueries();
849
+ oneWayRows.push(...scanned.rows);
850
+ oneWayTruncated = scanned.truncated;
851
+ oneWayCompleteness = scanned.truncated ? 'partial' : 'complete';
852
+ }
724
853
  const linksOnly = opts.linksOnly === true;
725
854
  const oneWayItems = [];
726
855
  let oneWayEdges = 0;
727
856
  let bodyOnly = 0;
728
- for (const row of oneWay) {
857
+ for (const row of oneWayRows) {
729
858
  // 目标也不报日记:普通笔记链到日记("今天做了 X")同样是正常引用方向,
730
859
  // 要求日记回链每篇被提到的笔记,跟要求笔记回链日记是同一个问题。
731
860
  if (isDaily(path.resolve(cfg.notebook, row.target)))
@@ -738,7 +867,7 @@ export async function lintNotebook(cfg, opts = {}, signal) {
738
867
  const body = [];
739
868
  for (const source of row.from) {
740
869
  all.push(source.path);
741
- if (whereOf(source.path, source.snippetStarts) === 'links')
870
+ if (source.where === 'links')
742
871
  links.push(source.path);
743
872
  else
744
873
  body.push(source.path);
@@ -772,11 +901,12 @@ export async function lintNotebook(cfg, opts = {}, signal) {
772
901
  edges: oneWayEdges,
773
902
  bodyOnly,
774
903
  linksOnly,
775
- edgesTruncated: graph.truncated,
904
+ edgesTruncated: oneWayTruncated,
905
+ completeness: oneWayCompleteness,
776
906
  items: oneWayItems.slice(0, MAX_ITEMS),
777
907
  };
778
908
  const parseErrors = parseErrorWarnings(cfg, warnings);
779
- const scanTruncated = notes.length >= MAX_SCAN;
909
+ const scanTruncated = completeness !== 'complete';
780
910
  const staleNotes = notes
781
911
  .map((n) => ({ note: n, at: Date.parse(n.modified) }))
782
912
  .filter((x) => Number.isFinite(x.at) && x.at < cutoff)
@@ -796,6 +926,8 @@ export async function lintNotebook(cfg, opts = {}, signal) {
796
926
  notebook: cfg.notebook,
797
927
  notes: notes.length,
798
928
  truncated: scanTruncated,
929
+ completeness,
930
+ scanLimit: scan.limit,
799
931
  staleDays,
800
932
  parseErrors: { total: parseErrors.length, items: parseErrors.slice(0, MAX_ITEMS) },
801
933
  orphans: bucket(orphanAbs.filter((abs) => !isDaily(abs))),
@@ -816,5 +948,7 @@ export async function lintNotebook(cfg, opts = {}, signal) {
816
948
  timeline: timelineStatus(cfg, now),
817
949
  // 150 篇(不含日记)是检索开始变糊的拐点:提示一下,不生成静态索引(会过期,还要决定谁更新)
818
950
  indexHint: nonDaily.length >= 150 && !fs.existsSync(path.join(cfg.notebook, 'INDEX.md')),
951
+ // 放在最后算:前面的读命令已经把 pending 的 dirty 补掉了,剩下的是「补不上 / 外部编辑」
952
+ indexLag: indexLagHint(cfg) ?? '',
819
953
  };
820
954
  }
@@ -11,7 +11,7 @@
11
11
  */
12
12
  import fs from 'node:fs';
13
13
  import path from 'node:path';
14
- import { assertNotArchiveCreate, ZkError, zk } from './zk.js';
14
+ import { assertNotArchiveCreate, indexPolicy, ZkError, zk } from './zk.js';
15
15
  import { AGENTS_TEMPLATE, AGENTS_TEMPLATE_FLAT, WORKFLOW_TEMPLATE } from './agents-template.js';
16
16
  import { PERSONA_TEMPLATE } from './persona-template.js';
17
17
  import { effectivePaths, isPluginOwned, normGroupPath, parseGroupBlocks, sameGroupPath, samePaths } from './notebook-config.js';
@@ -367,7 +367,9 @@ export async function ensureNotebook(cfg, signal, opts = {}) {
367
367
  const configFile = path.join(cfg.notebook, '.zk', 'config.toml');
368
368
  let initialized = false;
369
369
  if (!fs.existsSync(configFile)) {
370
- await zk(cfg, ['init', cfg.notebook], { signal, timeoutMs: 120_000 });
370
+ // init 会把目录里已有的笔记一起索引进空库 —— 10k / 1 链实测 202 s,
371
+ // 原来的 120 s 会把进程杀在写事务里,留下半库。这里直接给建库预算(M5.0a)。
372
+ await zk(cfg, ['init', cfg.notebook], { signal, timeoutMs: indexPolicy.buildTimeoutMs });
371
373
  initialized = true;
372
374
  }
373
375
  const templatesWritten = layered