dsh-zdiary-kit 3.4.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.
package/README.md CHANGED
@@ -1,4 +1,4 @@
1
- # dsh-zdiary-kit 3.4.0
1
+ # dsh-zdiary-kit 3.6.0
2
2
 
3
3
  > 给 [DSH](https://github.com/deepseek-ai/deepseek-harness) 装一个**内置 [zk](https://github.com/zk-org/zk) 的知识库 / 日记本**:
4
4
  > 插件提供一键安装 zk(官方 release;设置页按钮或 `zk-kit install`)、自动建笔记本(zk init + 日记模板 + 日记 group),
@@ -304,6 +304,25 @@ zk-kit groups --fix # 只改 dsh-zdiary-kit 自己写的 group:paths 行
304
304
  与根目录的 `AGENTS.md` / `MEMORY.md` / `USER.md` / `DREAMS.md` / `INDEX.md` / `WORKFLOW.md` 不进检索与笔记 / 标签 / 断链 / 孤立统计;
305
305
  `archive/` 的归档数由 `zk_stats` 单独统计(`archived` / `superseded`)。`-x` 传绝对路径:它是相对 cwd 解析的,传相对名在换工作目录后会静默失效。
306
306
 
307
+ ## 索引与「写后可读」
308
+
309
+ zk 的索引(`.zk/notebook.db`)是缓存:文件落盘不等于能搜到。插件在写入**落盘之后**记一个 dirty 标记
310
+ (`.zk/dsh-index-state.json` 里的 `generation` / `indexedGeneration`),下一次任何读(检索 / `zk_lint` / `zk_dream` / `zk_stats`)
311
+ 之前先补一次增量 `zk index`,最多等 15 秒:
312
+
313
+ - 建完 → 这次读到的就是新内容(`zk_append`、`zk_link`、`zk_new` 带 `summary`、改名、归档都覆盖);
314
+ - 建不完 / 失败 / 另一个进程正在建 → 这次读「**完整但可能过期**」的索引,并打一条
315
+ `[zdiary] 索引刷新还没完成…`(同一次写入只打一遍);dirty 保留,下次读再补;
316
+ - 半库不读:db 不完整(missing / interrupted)时 flush 不接手,交给冷建守卫 —— 小库自己补完,
317
+ 大库报「索引在建」,绝不退回读半截索引。
318
+
319
+ 读路径与「重建索引」共用一把跨进程锁(`.zk/dsh-index.lock`),所以插件进程和 `zk-kit` 命令行不会同时跑两个 `zk index`
320
+ (两个并发只会撞 SQLite 写锁)。
321
+
322
+ **外部编辑**(编辑器 / agent 原生 `Edit`,不经 `zk_*`)插件感知不到:`zk-kit doctor` / `zk_lint` 只按笔记本顶层目录的
323
+ mtime 粗判 —— 新增 / 删除 / 改名会提示「索引可能落后」,**改已有笔记的正文不会**(目录 mtime 不变)。
324
+ 改完正文要让 `zk_search` 搜到,点一次「重建索引」;文件内容本身没有被动过。
325
+
307
326
  ## zk 从哪来(优先级)
308
327
 
309
328
  1. 设置页「zk 路径」(显式指定,最优先)
@@ -391,7 +410,7 @@ zk-kit doctor # 自检:zk / 笔记本 / 模板 / group
391
410
  | 设置页 404 | `cordis.patch.yml` 里的 `name:` 与安装后的包名不一致 |
392
411
  | 设置页 503 | 宿主没有 `connection` 服务,信任栅栏按 fail-closed 拒绝(工具不受影响) |
393
412
  | 安装 zk 报「解包失败」 | 系统没有 `tar`;手动解包后把 `zk` 放进 `~/.dsh/zdiary/bin` |
394
- | 搜索结果不全 | 索引落后:点「重建索引」(`zk index`),或确认文件没被 `.zk/config.toml` 的 `exclude` 排除 |
413
+ | 搜索结果不全 | 先看两点:① 刚写过的内容(`zk_append` / `zk_link` / `zk_new` 带 `summary` / 改名 / 归档)本来会在下一次读之前自动补一次增量索引;补不上或别的进程正在建时,日志里会有 `[zdiary] 索引刷新还没完成…`,dirty 会留到下次读再补。② 真正补不上就点「重建索引」(`zk index`),或确认文件没被 `.zk/config.toml` 的 `exclude` 排除。**外部直接编辑(不经过 `zk_*`)改已有笔记的正文,插件不会感知**:`zk-kit doctor` / `zk_lint` 只按顶层目录 mtime 粗判「索引可能落后」,新增 / 删除 / 改名才触发,改正文不触发 —— 改完正文要能搜到就点一次「重建索引」 |
395
414
  | 工具报「索引还没建好 / 索引不完整」 | 大库第一次建索引,或上次建到一半被中断:插件在后台跑 `zk index`,最多先等 15 秒就返回,过一会儿重试即可;**不要同时再手动跑 `zk index`**。反复失败就点「重建索引」看完整报错 |
396
415
  | 自检报「✗ 长期记忆:N/预算 词」 | AGENTS + USER + MEMORY 写太长:先压缩,或在设置页调高「注入预算」(超预算时注入先丢 MEMORY 里日期最旧的条目,一条日期都没有才退回从末尾往前丢) |
397
416
  | 体检报「记忆链接:N 条失效」 | `MEMORY.md` / `USER.md` 里的 `[[来源]]` 指向的笔记已归档或删除:改成 `archive/` 下的新路径,或改指活笔记;显式写 `archive/` 的链接不算失效 |
@@ -423,7 +442,7 @@ zk-kit doctor # 自检:zk / 笔记本 / 模板 / group
423
442
  `bun run fixture`(生成 1k / 10k 规模夹具,比例与边界样本见 `docs/plan.md` §0.5;
424
443
  `--links-per-note` 决定链接密度 —— 建索引成本主要花在链接上,产出目录自带 `.zk/config.toml`,进去 `zk index` 即可)·
425
444
  `bun run bench`(成本表:逐用例真起 zk,记子进程数 / 回传字节 / 峰值 RSS / p50 / p95;默认 1k、3 轮)
426
- - **耗时差两个数量级**:`bun run test` 约 50 s(208 个用例,真起 zk);`fixture` 百毫秒级;`bench` 默认 1k 约十几秒,
445
+ - **耗时差两个数量级**:`bun run test` 约 100 s(223 个用例,真起 zk;机器快慢能差一倍);`fixture` 百毫秒级;`bench` 默认 1k 约十几秒,
427
446
  10k 上光一条 `graph.full` 就是 30 s、冷建索引几分钟。所以 `bench` **不在** `check` / CI 里,跟测试完全分开,不会因为你跑测试而变慢。
428
447
  - `bun run test` 会先按插件自己的顺序找 zk(配置 → `ZK_BIN` → PATH → `~/.dsh/zdiary/bin`),跑完要求 **skip = 0**:
429
448
  集成测试跳过一律按失败处理,否则「全绿」可能是「什么都没跑」。要换 zk 就 `ZK_BIN=/path/to/zk bun run check`。
package/dist/cli.js CHANGED
@@ -9,7 +9,7 @@ import { CFG_FILE } from './config/paths.js';
9
9
  import { NOTE_KINDS, ensureNotebook, fixGroupConfig, groupOverlapNotes, newNoteDir, structureStatus } from './lib/notebook.js';
10
10
  import { buildMemoryPayload, formatFileShares } from './lib/memory.js';
11
11
  import { installZk, sourceLabel } from './lib/install.js';
12
- import { resolveZk, searchNotesDetailed, queryNotes, createNote, readNote, findNote, appendToNote, ensureDailyNote, appendDaily, linkNotes, notebookStats, indexNotebook, withTags, taglessCjkWarning, hasNotebook, localDate, ZkError, allNotes, parseErrorWarnings, } from './lib/zk.js';
12
+ import { resolveZk, searchNotesDetailed, queryNotes, createNote, readNote, findNote, appendToNote, ensureDailyNote, appendDaily, linkNotes, notebookStats, indexNotebook, indexPolicy, withTags, taglessCjkWarning, hasNotebook, localDate, ZkError, allNotes, parseErrorWarnings, indexLagHint, } from './lib/zk.js';
13
13
  import { formatLintExtras, formatMemoryLinks, lintNotebook, personaStatus, timelineStatus } from './lib/lint.js';
14
14
  import { dreamNotebook, STALE_DAYS } from './lib/dream.js';
15
15
  const HELP = `zk-kit —— dsh-zdiary-kit 的命令行
@@ -173,12 +173,19 @@ function lintReport(r) {
173
173
  if (memLine)
174
174
  lines.push(memLine);
175
175
  lines.push(...formatLintExtras(r));
176
- if (r.similarTitles.truncated)
177
- lines.push('⚠️ 疑似重复只比较了部分笔记(同目录超过 300 篇或扫描触顶):可能漏报');
178
- if (r.truncated)
179
- lines.push('⚠️ 笔记数触到扫描上限:结果不完整(只会漏报,不会误报)');
180
- if (oneWay.edgesTruncated)
176
+ if (r.similarTitles.completeness === 'partial') {
177
+ lines.push('⚠️ 疑似重复只比较了部分笔记:可能漏报' +
178
+ (r.similarTitles.droppedGroups > 0 ? `(${r.similarTitles.droppedGroups} 组超过 300 篇,只比较了前 300 篇)` : '') +
179
+ (r.completeness === 'partial' ? '(笔记扫描触顶)' : ''));
180
+ }
181
+ if (r.completeness === 'partial')
182
+ lines.push(`⚠️ 笔记数触到扫描上限(${r.scanLimit} 篇):结果不完整(只会漏报,不会误报)`);
183
+ else if (r.completeness === 'unknown')
184
+ lines.push('⚠️ 扫描结果无法完整解析:下面的数字不能当成全部(可能少报)');
185
+ if (oneWay.completeness === 'partial')
181
186
  lines.push('⚠️ 建图笔记载入触到上限:单向链接可能误报(回链边未加载)');
187
+ else if (oneWay.completeness === 'unknown')
188
+ lines.push('⚠️ 无法确认单向链接的边集是否完整(旧版 zk 未给出载入篇数):可能误报');
182
189
  lines.push('(只报告,没有改动任何文件)');
183
190
  return lines.join('\n');
184
191
  }
@@ -250,8 +257,10 @@ function dreamReport(r) {
250
257
  }
251
258
  if (!r.newNotes.length && !r.dailyLooseEnds.length && !r.topCited.length)
252
259
  lines.push('这个窗口里没有新材料。');
253
- if (r.truncated)
254
- lines.push('⚠️ 笔记数触到扫描上限:窗口与排名都不完整');
260
+ if (r.completeness === 'partial')
261
+ lines.push(`⚠️ 笔记数触到扫描上限(${r.scanLimit} 篇):窗口与排名都不完整`);
262
+ else if (r.completeness === 'unknown')
263
+ lines.push('⚠️ 扫描结果无法完整解析:窗口与排名可能不完整');
255
264
  if (r.graphSkipped) {
256
265
  lines.push(`⚠️ 库超过全图统计上限(${r.graphBudget} 篇),这次没统计入链:被引数与 topCited 是空的,不代表没人引用;可在设置页调整「全图统计上限(篇)」(graphBudgetNotes)`);
257
266
  }
@@ -399,6 +408,10 @@ async function doctor() {
399
408
  try {
400
409
  const s = await notebookStats(cfg);
401
410
  rows.push(`✓ 索引:${s.notes} 篇笔记 / ${s.tags} 个标签 / 断链 ${s.brokenLinks} / 孤立 ${s.orphans}`);
411
+ // 外部编辑(不经过工具)没有 dirty 标记:靠 db 与目录的 mtime 粗判,只提示不自动重建
412
+ const lag = indexLagHint(cfg);
413
+ if (lag)
414
+ rows.push(`⚠️ 索引可能落后:${lag}`);
402
415
  // frontmatter 写坏的笔记不在索引里:zk 只在 stderr 吭一声,不主动收就永远没人知道
403
416
  const warnings = [];
404
417
  await allNotes(cfg, { warnings });
@@ -592,7 +605,8 @@ async function main() {
592
605
  return;
593
606
  }
594
607
  case 'index': {
595
- await indexNotebook(cfg);
608
+ // 显式重建:别的进程在建就等它(等满 waitMs),不另起第二个 zk index
609
+ await indexNotebook(cfg, undefined, { lockWaitMs: indexPolicy.waitMs });
596
610
  print(json ? { ok: true } : '✓ 索引已重建', json);
597
611
  return;
598
612
  }
@@ -4,7 +4,7 @@
4
4
  * 设计边界(和设置页的写 API 完全分开):
5
5
  * · 只挂 4 条 GET 路由,全部在 /dsh-zdiary-kit 下,和 DSH 同端口,不自己 listen;
6
6
  * · 方法门:GET / HEAD 以外一律 405,默认拒绝 —— 不是「没写 POST 就算只读」;
7
- * · 副作用门:只调 hasNotebook / allNotes / searchNotes / readNote / backlinksOf,
7
+ * · 副作用门:只调 hasNotebook / scanNotes / searchNotes / readNote / backlinksOf,
8
8
  * **不调 ensureNotebook**(那会建库)、不跑 init / index / install;
9
9
  * · 面门:不读 /api/settings 的 snapshot,不返回 zkPath / 配置文件路径 / absPath;
10
10
  * · 地址门:只认回环(Host + 对端地址),DSH 绑到 0.0.0.0 时视图也不会跟着上网。
@@ -15,7 +15,7 @@ import fs from 'node:fs';
15
15
  import path from 'node:path';
16
16
  import { isLoopback, json, ROUTE_BASE } from '../../lib/http.js';
17
17
  import { config } from '../../config/store.js';
18
- import { absPathOf, allNotes, backlinksOf, hasNotebook, isUnderDir, localDate, readNote, searchNotes, ZkError } from '../../lib/zk.js';
18
+ import { absPathOf, backlinksOf, hasNotebook, isUnderDir, localDate, readNote, scanNotes, searchNotes, ZkError } from '../../lib/zk.js';
19
19
  import { isMetaPath } from '../../lib/meta.js';
20
20
  import { buildMemoryPayload, formatFileShares } from '../../lib/memory.js';
21
21
  import { RETIRED_ENTRY_RE } from '../../lib/memory-format.js';
@@ -29,8 +29,6 @@ const VIEW = `${BASE}/view`;
29
29
  const FEED = `${BASE}/feed.xml`;
30
30
  const API_NOTES = `${BASE}/api/notes`;
31
31
  const API_NOTE = `${BASE}/api/note`;
32
- /** 一次索引最多载入多少篇(超出只在页脚说明,不静默装作全量) */
33
- const INDEX_LIMIT = 2000;
34
32
  /** 页面 / API 单篇正文上限:日记再长也不该把浏览器拖死 */
35
33
  const MAX_CONTENT = 200_000;
36
34
  /** 磁盘文件上限:超过就不读(readNote 会把整篇读进内存) */
@@ -176,8 +174,13 @@ function noteTable(notes) {
176
174
  function searchForm(value = '') {
177
175
  return `<form class="search" method="get" action="${VIEW}"><input type="search" name="q" value="${esc(value)}" placeholder="搜索标题、正文…" aria-label="搜索"><button type="submit">搜索</button></form>`;
178
176
  }
177
+ /** 首页 / 标签页要「有没有扫全」;MAX_SCAN 是唯一的载入上限(不再用 2000 截断计数) */
178
+ async function loadScan(cfg) {
179
+ return scanNotes(cfg);
180
+ }
181
+ /** 只需要笔记的调用方(搜索兜底 / 记忆页反链解析) */
179
182
  async function loadAll(cfg) {
180
- return allNotes(cfg, { limit: INDEX_LIMIT });
183
+ return (await loadScan(cfg)).notes;
181
184
  }
182
185
  /** 搜索 / 标签走 zk;`q` 与 `tag` 同时给就是两个条件一起收(zk 按 AND 处理,不静默忽略其中一个) */
183
186
  async function pickNotes(cfg, opts) {
@@ -188,14 +191,16 @@ async function pickNotes(cfg, opts) {
188
191
  }
189
192
  // ── 页面 ──────────────────────────────────────────────────────────────
190
193
  async function handleHome(res, cfg) {
191
- const all = await loadAll(cfg);
194
+ const scan = await loadScan(cfg);
195
+ const all = scan.notes;
196
+ const atLeast = scan.completeness === 'complete' ? '' : '≥';
192
197
  const recent = [...all].sort(byModified).slice(0, 30);
193
198
  const journal = all.filter((note) => isUnderDir(note.path, cfg.dailyDir) || note.type === 'daily').sort(byModified).slice(0, 10);
194
199
  const tags = tagCounts(all);
195
200
  const body = [
196
201
  `<h1>${esc(cfg.active || 'zdiary')}</h1>`,
197
202
  searchForm(),
198
- `<p class="meta">${all.length} 篇笔记 · ${tags.length} 个标签 · 只读</p>`,
203
+ `<p class="meta">${atLeast}${all.length} 篇笔记 · ${atLeast}${tags.length} 个标签 · 只读</p>`,
199
204
  '<h2>最近更新</h2>',
200
205
  noteTable(recent),
201
206
  '<h2>日记</h2>',
@@ -205,7 +210,9 @@ async function handleHome(res, cfg) {
205
210
  ? `<p class="tags">${tags.slice(0, 80).map(([tag, count]) => `<a href="${esc(viewHref({ p: 'tag', tag }))}">#${esc(tag)}</a><span class="count">${count}</span>`).join(' · ')}</p>`
206
211
  : '<p class="meta">还没有标签。</p>',
207
212
  ].join('\n');
208
- const note = all.length >= INDEX_LIMIT ? `只载入了最近 ${INDEX_LIMIT} 篇;更早的请用搜索。` : undefined;
213
+ const note = scan.completeness === 'partial'
214
+ ? `只扫描了前 ${scan.limit} 篇(库更大);更早的请用搜索。`
215
+ : scan.completeness === 'unknown' ? '索引结果无法完整解析:下面的数字可能偏少。' : undefined;
209
216
  sendHtml(res, 200, shell(cfg, '首页', body, note));
210
217
  }
211
218
  async function handleSearch(res, cfg, q) {
@@ -262,11 +269,12 @@ function renderMemoryBody(body, linkFor) {
262
269
  * 载荷预览只转义展示(与 zk_context 同源),不提供编辑 —— 写仍然只走 zk_* / 编辑器。
263
270
  */
264
271
  async function handleMemory(res, cfg) {
265
- let all = [];
272
+ let scan = null;
266
273
  try {
267
- all = await loadAll(cfg);
274
+ scan = await loadScan(cfg);
268
275
  }
269
276
  catch { /* 索引挂了也能读记忆,双链退化成纯文字 */ }
277
+ const all = scan?.notes ?? [];
270
278
  const linkFor = linkResolver(all);
271
279
  const read = (name) => {
272
280
  try {
@@ -334,6 +342,9 @@ async function handleMemory(res, cfg) {
334
342
  '<h1>记忆</h1>',
335
343
  `<p class="meta">${esc(usage)}</p>`,
336
344
  formatLine ? `<p class="meta">${esc(formatLine)}</p>` : '',
345
+ scan && scan.completeness !== 'complete'
346
+ ? `<p class="meta">${scan.completeness === 'partial' ? `只扫描了前 ${scan.limit} 篇:页面里的双链可能没解析到更早的笔记。` : '索引结果无法完整解析:页面里的双链可能不完整。'}</p>`
347
+ : '',
337
348
  '<p class="meta">根目录 meta 由人和 agent 直接编辑,不进检索;这里只读,不提供编辑。</p>',
338
349
  `<h2>人格</h2>`,
339
350
  `<p class="meta">${esc(personaSummary)}</p>`,
@@ -360,12 +371,15 @@ async function handleMemory(res, cfg) {
360
371
  sendHtml(res, 200, shell(cfg, '记忆', body));
361
372
  }
362
373
  async function handleTags(res, cfg) {
363
- const notes = await loadAll(cfg);
374
+ const scan = await loadScan(cfg);
375
+ const notes = scan.notes;
376
+ const atLeast = scan.completeness === 'complete' ? '' : '≥';
364
377
  const tags = tagCounts(notes);
365
378
  const body = [
366
379
  `<p class="crumb"><a href="${VIEW}">首页</a> / 标签</p>`,
367
380
  '<h1>标签</h1>',
368
- `<p class="meta">${tags.length} 个标签 · ${notes.length} 篇笔记</p>`,
381
+ `<p class="meta">${atLeast}${tags.length} 个标签 · ${atLeast}${notes.length} 篇笔记` +
382
+ (scan.completeness === 'complete' ? '' : `(只扫描了前 ${scan.limit} 篇)`) + '</p>',
369
383
  tags.length
370
384
  ? `<p class="tags">${tags.map(([tag, count]) => `<a href="${esc(viewHref({ p: 'tag', tag }))}">#${esc(tag)}</a><span class="count">${count}</span>`).join(' · ')}</p>`
371
385
  : '<p class="meta">还没有标签。</p>',
@@ -18,7 +18,7 @@ import { ensureNotebook, structureStatus, writeAgentsTemplate, writePersonaTempl
18
18
  import { buildMemoryPayload, formatFileShares } from '../../lib/memory.js';
19
19
  import { personaStatus } from '../../lib/lint.js';
20
20
  import { installZk, sourceLabel } from '../../lib/install.js';
21
- import { hasNotebook, indexNotebook, notebookStats, resolveZk } from '../../lib/zk.js';
21
+ import { hasNotebook, indexNotebook, indexPolicy, notebookStats, resolveZk } from '../../lib/zk.js';
22
22
  const P = `${ROUTE_BASE}/api`;
23
23
  async function zkStatus(cfg) {
24
24
  const loc = await resolveZk(cfg);
@@ -214,7 +214,8 @@ export function registerSettings({ route, isTrusted }) {
214
214
  }
215
215
  const cfg = config();
216
216
  try {
217
- await indexNotebook(cfg);
217
+ // 显式重建:别的进程在建就等它(等满 waitMs),不另起第二个 zk index
218
+ await indexNotebook(cfg, undefined, { lockWaitMs: indexPolicy.waitMs });
218
219
  json(res, 200, { ok: true, ...(await snapshot(cfg)) });
219
220
  }
220
221
  catch (err) {
@@ -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({
@@ -1059,6 +1085,8 @@ export function buildTools(workspaceOf = () => processWorkspace()) {
1059
1085
  notebook: { type: 'string' },
1060
1086
  notes: { type: 'number' },
1061
1087
  truncated: { type: 'boolean' },
1088
+ completeness: { type: 'string', enum: ['complete', 'partial', 'unknown'] },
1089
+ scanLimit: { type: 'number' },
1062
1090
  staleDays: { type: 'number' },
1063
1091
  parseErrors: LINT_PARSE,
1064
1092
  orphans: LINT_BUCKET,
@@ -1075,7 +1103,8 @@ export function buildTools(workspaceOf = () => processWorkspace()) {
1075
1103
  persona: LINT_PERSONA,
1076
1104
  timeline: LINT_TIMELINE,
1077
1105
  indexHint: { type: 'boolean' },
1078
- }, ['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']),
1079
1108
  },
1080
1109
  async run(args, env) {
1081
1110
  const cfg = configFor(env.workspace, env.sessionId);
@@ -1128,12 +1157,23 @@ export function buildTools(workspaceOf = () => processWorkspace()) {
1128
1157
  if (memLine)
1129
1158
  lines.push(memLine);
1130
1159
  lines.push(...formatLintExtras(v));
1131
- if (v.similarTitles.truncated)
1132
- lines.push('⚠️ 疑似重复只比较了部分笔记(同目录超过 300 篇或扫描触顶):可能漏报');
1133
- if (v.truncated)
1134
- lines.push('⚠️ 笔记数触到扫描上限:结果不完整(只会漏报,不会误报),先归档旧笔记再跑一次');
1135
- 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')
1136
1172
  lines.push('⚠️ 建图笔记载入触到上限:单向链接可能误报(回链边未加载),先归档旧笔记再跑一次');
1173
+ else if (oneWay.completeness === 'unknown')
1174
+ lines.push('⚠️ 无法确认单向链接的边集是否完整(旧版 zk 未给出载入篇数):可能误报');
1175
+ if (v.indexLag)
1176
+ lines.push('⚠️ 索引可能落后:' + v.indexLag);
1137
1177
  lines.push('(只报告,没有改动任何文件)');
1138
1178
  return text(lines.join('\n'));
1139
1179
  },
@@ -1165,6 +1205,8 @@ export function buildTools(workspaceOf = () => processWorkspace()) {
1165
1205
  windowDays: { type: 'number' },
1166
1206
  since: { type: 'string' },
1167
1207
  truncated: { type: 'boolean' },
1208
+ completeness: { type: 'string', enum: ['complete', 'partial', 'unknown'] },
1209
+ scanLimit: { type: 'number' },
1168
1210
  graphSkipped: { type: 'boolean' },
1169
1211
  graphBudget: { type: 'number' },
1170
1212
  memory: objSchema({
@@ -1228,7 +1270,7 @@ export function buildTools(workspaceOf = () => processWorkspace()) {
1228
1270
  reason: { type: 'string', enum: ['stale', 'source-missing', 'source-superseded'] },
1229
1271
  }, ['entry', 'date', 'age', 'reason']),
1230
1272
  },
1231
- }, ['notebook', 'windowDays', 'since', 'truncated', 'graphSkipped', 'graphBudget', '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']),
1232
1274
  },
1233
1275
  async run(args, env) {
1234
1276
  const cfg = configFor(env.workspace, env.sessionId);
@@ -1309,8 +1351,10 @@ export function buildTools(workspaceOf = () => processWorkspace()) {
1309
1351
  }
1310
1352
  if (!v.newNotes.length && !v.dailyLooseEnds.length && !v.topCited.length)
1311
1353
  lines.push('这个窗口里没有新材料。');
1312
- if (v.truncated)
1313
- lines.push('⚠️ 笔记数触到扫描上限:窗口与排名都不完整');
1354
+ if (v.completeness === 'partial')
1355
+ lines.push('⚠️ 笔记数触到扫描上限(' + v.scanLimit + ' 篇):窗口与排名都不完整');
1356
+ else if (v.completeness === 'unknown')
1357
+ lines.push('⚠️ 扫描结果无法完整解析:窗口与排名可能不完整');
1314
1358
  if (v.graphSkipped) {
1315
1359
  lines.push('⚠️ 库超过全图统计上限(' + v.graphBudget + ' 篇),这次没统计入链:被引数与 topCited 是空的,不代表没人引用;可在设置页调整「全图统计上限(篇)」(graphBudgetNotes)');
1316
1360
  }
@@ -1342,7 +1386,9 @@ export function buildTools(workspaceOf = () => processWorkspace()) {
1342
1386
  type: 'array',
1343
1387
  items: objSchema({ tag: { type: 'string' }, count: { type: 'number' } }, ['tag', 'count']),
1344
1388
  },
1345
- }, ['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']),
1346
1392
  },
1347
1393
  async run(_args, env) {
1348
1394
  const cfg = configFor(env.workspace, env.sessionId);
@@ -1367,9 +1413,13 @@ export function buildTools(workspaceOf = () => processWorkspace()) {
1367
1413
  const tags = v.byTag.length
1368
1414
  ? '\n标签:' + v.byTag.map((t) => `#${t.tag} ${t.count}`).join(' · ')
1369
1415
  : '';
1416
+ const atLeast = v.completeness === 'complete' ? '' : '≥';
1417
+ const partial = v.completeness === 'partial'
1418
+ ? `\n⚠️ 只扫描了前 ${v.scanLimit} 篇:上面的数字是下限`
1419
+ : v.completeness === 'unknown' ? '\n⚠️ 扫描结果无法完整解析:上面的数字可能偏少' : '';
1370
1420
  return text(`笔记本 ${v.notebook}${drift}\n` +
1371
- `笔记 ${v.notes} 篇 · 标签 ${v.tags} 个 · 断链 ${v.brokenLinks} 篇 · 孤立 ${v.orphans} 篇 · 归档 ${v.archived} 篇(superseded ${v.superseded})` +
1372
- dirs + tags);
1421
+ `笔记 ${atLeast}${v.notes} 篇 · 标签 ${atLeast}${v.tags} 个 · 断链 ${v.brokenLinks} 篇 · 孤立 ${v.orphans} 篇 · 归档 ${atLeast}${v.archived} 篇(superseded ${atLeast}${v.superseded})` +
1422
+ dirs + tags + partial);
1373
1423
  },
1374
1424
  }),
1375
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, GRAPH_BUDGET_NOTES, 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,7 +286,8 @@ 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);
289
+ const scan = await scanNotes(cfg, {}, signal);
290
+ const notes = scan.notes;
290
291
  // 全图在 10k 上 26–31 s / 17 MB(plan §0.5.1):超过预算就不建,并显式告诉调用方。
291
292
  // 预算来自配置(设置页可调);opts.graphBudget 只给测试覆盖。
292
293
  const graphBudget = Math.max(0, Math.trunc(opts.graphBudget ?? cfg.graphBudgetNotes ?? GRAPH_BUDGET_NOTES));
@@ -419,7 +420,9 @@ export async function dreamNotebook(cfg, opts = {}, signal) {
419
420
  notebook: cfg.notebook,
420
421
  windowDays,
421
422
  since: localDate(new Date(sinceMs).toISOString()),
422
- truncated: notes.length >= MAX_SCAN,
423
+ truncated: scan.completeness !== 'complete',
424
+ completeness: scan.completeness,
425
+ scanLimit: scan.limit,
423
426
  graphSkipped: !graphReady,
424
427
  graphBudget,
425
428
  counts: {