dsh-zdiary-kit 3.2.0 → 3.4.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.2.0
1
+ # dsh-zdiary-kit 3.4.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),
@@ -12,7 +12,7 @@
12
12
  |---|---|
13
13
  | `zk_search` | 全文 / 标签 / 日期 / 断链 / 孤立笔记检索,返回标题、相对路径、绝对路径、标签、摘要;中文查询自动并用子串匹配(`matchStrategy` 说明用了 `fts` / `regex` / `mixed`,补上全文索引漏掉的笔记) |
14
14
  | `zk_query` | 结构化检索:按 type / status / 标签 / 目录 / 日期过滤,默认只看 active 且不含归档;`include_archived` 连归档一起查(此时未显式给 status 则不再默认过滤 active) |
15
- | `zk_new` | 新建原子笔记(zk 生成文件名、套模板、写索引),可带摘要、标签与双链;`summary` 填进模板的 `## Summary`(正文里已写了这一节就不动,返回 `summaryApplied: false`);`name` 可直接指定短文件名(不给则按标题生成,中文标题得到拼音长名);layered 下不给 `dir` 就按 `type` 落位(source → notes/sources),两者都没有、或给的 `dir` 不在任何 group 里都直接报错;`tags` 只补正文里没有的;flat 下按标题查重,重复直接报错;归档里有同名旧结论只警告并带出废弃原因;type / authority 只有 layered 模板会写进 frontmatter;`raw/`、`inbox/`、`archive/` 与根目录 meta 文件一律拒写(写进去会被排除出索引 / 被当成人写的工作面;归档只放 `zk_supersede` 搬进去的旧结论);中文笔记没有任何标签时在 `tagWarning` 里提示(只提示,不阻断) |
15
+ | `zk_new` | 新建原子笔记(zk 生成文件名、套模板、写索引),可带摘要、标签与双链;`summary` 填进模板的 `## Summary`(正文里已写了这一节就不动,返回 `summaryApplied: false`);`name` 可直接指定短文件名(不给则按标题生成,中文标题得到拼音长名);layered 下不给 `dir` 就按 `type` 落位(source → notes/sources),两者都没有、或给的 `dir` 不在任何 group 里都直接报错;`tags` 只补正文里没有的;flat 下按标题查重,重复直接报错;归档里有同名旧结论只警告并带出废弃原因;type / authority 只有 layered 模板会写进 frontmatter;`raw/`、`inbox/`、`archive/` 与根目录 meta 文件一律拒写(写进去会被排除出索引 / 被当成人写的工作面;归档只放 `zk_supersede` 搬进去的旧结论);同目录里有「改一两个字」的相似标题时在 `similar` 里提示(带分数,只提示、不阻断);中文笔记没有任何标签时在 `tagWarning` 里提示(只提示,不阻断) |
16
16
  | `zk_append` | 往已有笔记末尾续写(自动补空行,可先起二级标题);根目录 meta 文件拒写 |
17
17
  | `zk_daily` | 打开/创建某天的日记,并追加一条带时间的记录(layered 模板写进 `## Events` 的 `### HH:MM`,flat 追加到文件末尾的 `## HH:MM`) |
18
18
  | `zk_link` | 在两篇笔记间加 `[[…]]` 双链(已存在不重复加;目标不存在会给出候选;链接追加到文末,已有 Links/链接 小节则不重复起标题);meta 文件不作为来源或目标 |
@@ -89,9 +89,12 @@ DSH 自带的 AGENTS.md 加载只看「项目根 → 当前目录」链,**不
89
89
  日记是这个插件里唯一按时间记录真实工作的层,空信号只说明日记里没写过,不等于没被用过。
90
90
  `zk_dream` 还会回一行**记忆余量**(内容词 + 提示 = 总量,余量按总量算,可以为负)和「可考虑退役」的条目
91
91
  (来源已归档 / 不存在、或超过 90 天没复核)—— 只给材料,不写任何文件。
92
+ 库超过全图统计上限时不再建全图统计入链(默认 2000 篇,设置页「工具 → 全图统计上限」可调;
93
+ 0 = 永不建全图):结果带 `graphSkipped: true` 与生效的 `graphBudget`,
94
+ 被引数与 `topCited` 为空 —— 那是「没算」,不是「没人引」。
92
95
  `zk_lint` 会核对 `MEMORY.md` / `USER.md` 里的 `[[来源路径]]` 是否还指向活笔记 ——
93
96
  `zk_supersede` 只重写笔记之间的入链,meta 文件不在图里,链接不会跟着搬,`--broken-links` 也看不见。
94
- 改名同理:`zk_rename` 会把 `zk graph` 里的入链和根目录 meta 的 `[[来源]]` 一起改到新路径,被搬走那篇自己的相对 Markdown 链接也按新位置重算 —— 手工 `mv` 会一次断掉这三处。
97
+ 改名同理:`zk_rename` 会把入链(按篇反查 `--link-to`,不再建全图)和根目录 meta 的 `[[来源]]` 一起改到新路径,被搬走那篇自己的相对 Markdown 链接也按新位置重算 —— 手工 `mv` 会一次断掉这三处。
95
98
  插件不跑定时任务:`DREAMS.md` 开头写一行 `上次做梦:YYYY-MM-DD`,注入里就会按 7 天节奏提醒该整理
96
99
  (没做过就提示先跑一次;没有 `AGENTS.md` 的库不提醒)。
97
100
 
@@ -141,6 +144,7 @@ dsh plugin --profile web add "link:/path/to/dsh-zdiary-kit"
141
144
  | 记忆 | 注入预算(词) | AGENTS + USER + MEMORY 的合计上限,默认 500(中文按 2 字 1 词) |
142
145
  | 记忆 | 人格上限 | PERSONA.md 240(不截断、超了告警) |
143
146
  | 写入 | 默认标签 / 单次读取上限 | 新笔记自动带标签;`zk-kit read` 与别名工具的输出上限 |
147
+ | 工具 | 全图统计上限(篇) | 库超过这个篇数时不再建全图:`zk_dream` 跳过入链统计,`zk_lint` 的单向链接改按篇反查;默认 2000(0–10000,上限 = 扫描上限),0 = 永不建全图 |
144
148
  | 工具 | 把 `[alias]` 注册成工具 | 复选框,默认关。打开后 `.zk/config.toml` 的 `[alias]` 变成 `zk_<名>` 工具;**加载时才注册**,勾完保存要重载插件 |
145
149
  | zk | zk 路径 / 内置版本 | 路径空 = 自动找;版本默认 0.15.7 |
146
150
 
@@ -192,7 +196,7 @@ dsh plugin --profile web add "link:/path/to/dsh-zdiary-kit"
192
196
  (`~/.dsh/zdiary/sessions/`),之后改这里不会带动已开的会话;本会话换库在会话里说一声(`zk_use`)。名字不存在、非法时退回 `default`。
193
197
  - 顶层 `notebook` 与 `structure` 是**派生的**(`notebooks[active]` 解析后的绝对路径 / 该条目的结构),只在内存里、不落盘也不可写;可写的是条目里的 `notebooks[名].structure`(`zk-kit config set structure=…` 改的就是当前笔记本那一条)—— 磁盘上笔记本只有一个真相,就是 `notebooks` + `active`。
194
198
  老配置里那个单独的 `notebook` 字段(和全局 `structure`)读进来会**一次性**迁进 `notebooks.default`,之后不再互相覆盖。
195
- - **共享的是全局项**:笔记 / 日记子目录、`daily` group、归档目录、注入预算 —— 这些不按笔记本分开。
199
+ - **共享的是全局项**:笔记 / 日记子目录、`daily` group、归档目录、注入预算、全图统计上限 —— 这些不按笔记本分开。
196
200
  改子目录 / group 名后要跑 `zk-kit groups --fix` 让 `.zk/config.toml` 跟上;归档目录非空时不允许改(不自动迁移文件)。
197
201
 
198
202
  ```bash
@@ -388,6 +392,7 @@ zk-kit doctor # 自检:zk / 笔记本 / 模板 / group
388
392
  | 设置页 503 | 宿主没有 `connection` 服务,信任栅栏按 fail-closed 拒绝(工具不受影响) |
389
393
  | 安装 zk 报「解包失败」 | 系统没有 `tar`;手动解包后把 `zk` 放进 `~/.dsh/zdiary/bin` |
390
394
  | 搜索结果不全 | 索引落后:点「重建索引」(`zk index`),或确认文件没被 `.zk/config.toml` 的 `exclude` 排除 |
395
+ | 工具报「索引还没建好 / 索引不完整」 | 大库第一次建索引,或上次建到一半被中断:插件在后台跑 `zk index`,最多先等 15 秒就返回,过一会儿重试即可;**不要同时再手动跑 `zk index`**。反复失败就点「重建索引」看完整报错 |
391
396
  | 自检报「✗ 长期记忆:N/预算 词」 | AGENTS + USER + MEMORY 写太长:先压缩,或在设置页调高「注入预算」(超预算时注入先丢 MEMORY 里日期最旧的条目,一条日期都没有才退回从末尾往前丢) |
392
397
  | 体检报「记忆链接:N 条失效」 | `MEMORY.md` / `USER.md` 里的 `[[来源]]` 指向的笔记已归档或删除:改成 `archive/` 下的新路径,或改指活笔记;显式写 `archive/` 的链接不算失效 |
393
398
  | 体检报「N 个条目没写日期 / 已退役」 | 按 `AGENTS.md` 的格式补 `结论(YYYY-MM-DD)[[来源路径]]`;退役行写 `- [superseded …] 旧结论 → [[新结论]]`,行留着不删(注入时会省略退役条目,文件本身不动)。只报告 |
@@ -414,7 +419,12 @@ zk-kit doctor # 自检:zk / 笔记本 / 模板 / group
414
419
  (DSH 会把多个插件的 `client.js` 拼进同一个 combo 脚本,顶层 `const` / `function` 会撞名导致插件不激活)。
415
420
  - `bun run typecheck` · `bun run build` · `bun run test`(真起 zk)·
416
421
  `bun run smoke`(加载 dist:13 个内置工具各跑一遍 + 12 条路由(设置 8 + 只读 4)都发真实请求(`/install` 只验非法版本,不下载),并检查输出 schema 在 DSH 支持的子集内)·
417
- `bun run docs`(把 README / docs 里 `zk-kit …` 代码块在临时 vault 上逐条真跑;`smoke` 末尾会带上)
422
+ `bun run docs`(把 README / docs 里 `zk-kit …` 代码块在临时 vault 上逐条真跑;`smoke` 末尾会带上)·
423
+ `bun run fixture`(生成 1k / 10k 规模夹具,比例与边界样本见 `docs/plan.md` §0.5;
424
+ `--links-per-note` 决定链接密度 —— 建索引成本主要花在链接上,产出目录自带 `.zk/config.toml`,进去 `zk index` 即可)·
425
+ `bun run bench`(成本表:逐用例真起 zk,记子进程数 / 回传字节 / 峰值 RSS / p50 / p95;默认 1k、3 轮)
426
+ - **耗时差两个数量级**:`bun run test` 约 50 s(208 个用例,真起 zk);`fixture` 百毫秒级;`bench` 默认 1k 约十几秒,
427
+ 10k 上光一条 `graph.full` 就是 30 s、冷建索引几分钟。所以 `bench` **不在** `check` / CI 里,跟测试完全分开,不会因为你跑测试而变慢。
418
428
  - `bun run test` 会先按插件自己的顺序找 zk(配置 → `ZK_BIN` → PATH → `~/.dsh/zdiary/bin`),跑完要求 **skip = 0**:
419
429
  集成测试跳过一律按失败处理,否则「全绿」可能是「什么都没跑」。要换 zk 就 `ZK_BIN=/path/to/zk bun run check`。
420
430
  - `dist/` 随仓库提交:`dsh plugin add github:…` 不会触发安装时构建(pnpm 默认禁止 git 依赖跑构建脚本)。
package/dist/cli.js CHANGED
@@ -252,6 +252,9 @@ function dreamReport(r) {
252
252
  lines.push('这个窗口里没有新材料。');
253
253
  if (r.truncated)
254
254
  lines.push('⚠️ 笔记数触到扫描上限:窗口与排名都不完整');
255
+ if (r.graphSkipped) {
256
+ lines.push(`⚠️ 库超过全图统计上限(${r.graphBudget} 篇),这次没统计入链:被引数与 topCited 是空的,不代表没人引用;可在设置页调整「全图统计上限(篇)」(graphBudgetNotes)`);
257
+ }
255
258
  lines.push('(只报告:MEMORY.md / DREAMS.md 由你按 AGENTS.md 写)');
256
259
  return lines.join('\n');
257
260
  }
@@ -44,6 +44,7 @@ export const DEFAULTS = {
44
44
  aliasTools: false,
45
45
  memoryBudgetWords: 500,
46
46
  personaBudgetWords: 240,
47
+ graphBudgetNotes: 2_000,
47
48
  archiveDir: 'archive',
48
49
  zkVersion: '0.15.7',
49
50
  zkPath: '',
@@ -128,6 +129,12 @@ export function normalizeConfig(raw, workspace = processWorkspace()) {
128
129
  ? activeRaw
129
130
  : DEFAULT_NOTEBOOK_NAME in notebooks ? DEFAULT_NOTEBOOK_NAME : (Object.keys(notebooks)[0] ?? DEFAULT_NOTEBOOK_NAME);
130
131
  const entry = notebooks[active] ?? { path: '', structure: 'flat' };
132
+ // 空 / null / 非数字退回默认值;0 是合法值(= 永不建全图),别把「没填」当成 0
133
+ // 上限卡在 MAX_SCAN(10 000):篇数最多也就数到这么多,再高的预算等于「永远建全图」
134
+ const graphBudgetRaw = src.graphBudgetNotes;
135
+ const graphBudgetNotes = graphBudgetRaw === null || graphBudgetRaw === undefined || String(graphBudgetRaw).trim() === ''
136
+ ? DEFAULTS.graphBudgetNotes
137
+ : clamp(Number(graphBudgetRaw), 0, 10_000, DEFAULTS.graphBudgetNotes);
131
138
  return {
132
139
  notebook: notebookPath(entry.path, workspace),
133
140
  notebooks,
@@ -143,6 +150,7 @@ export function normalizeConfig(raw, workspace = processWorkspace()) {
143
150
  aliasTools: src.aliasTools === true || src.aliasTools === 'true',
144
151
  memoryBudgetWords: clamp(Number(src.memoryBudgetWords), 50, 2000, DEFAULTS.memoryBudgetWords),
145
152
  personaBudgetWords: clamp(Number(src.personaBudgetWords), 50, 800, DEFAULTS.personaBudgetWords),
153
+ graphBudgetNotes,
146
154
  archiveDir: relativeDir(src.archiveDir, DEFAULTS.archiveDir),
147
155
  zkVersion: /^\d+\.\d+\.\d+$/.test(String(src.zkVersion ?? '').trim().replace(/^v/i, ''))
148
156
  ? String(src.zkVersion).trim().replace(/^v/i, '')
@@ -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 / graphEdges,
7
+ * · 副作用门:只调 hasNotebook / allNotes / 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,10 +15,11 @@ 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, graphEdges, hasNotebook, isUnderDir, localDate, readNote, searchNotes, ZkError } from '../../lib/zk.js';
18
+ import { absPathOf, allNotes, backlinksOf, hasNotebook, isUnderDir, localDate, readNote, 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';
22
+ import { TEMPLATE_VERSION } from '../../lib/agents-template.js';
22
23
  import { parseFrontmatter } from '../../lib/frontmatter.js';
23
24
  import { stripPersonaMarker } from '../../lib/persona-template.js';
24
25
  import { esc, layout, renderMarkdown } from './html.js';
@@ -286,6 +287,21 @@ async function handleMemory(res, cfg) {
286
287
  const usage = `记忆 ${payload.words}/${payload.budget} 词(${shares || '三份都空'})` +
287
288
  (payload.truncatedWords > 0 ? ` · 已截断 ${payload.truncatedWords} 词` : '') +
288
289
  (payload.retiredWords > 0 ? ` · 退役省略 ${payload.retiredWords} 词` : '');
290
+ // 格式债(P1):用量下面单列一行 —— 周审入口要能一眼看到日期 / 来源 / 模板版本三处缺口。
291
+ // 数字取载荷里的 formatDebt / templateVersion(与注入同一份,不重读文件、不跑 lint);
292
+ // 不补日期、不猜来源;全干净就不写这一行。
293
+ const debt = payload.formatDebt;
294
+ const templateVersion = payload.templateVersion;
295
+ // 没有 AGENTS.md 时 templateVersion 也是 0:靠 files[].present 区分「没模板」与「旧模板」
296
+ const agentsPresent = payload.files.some((f) => f.name === 'AGENTS.md' && f.present);
297
+ const formatParts = [];
298
+ if (debt.undated > 0 || debt.unlinked > 0) {
299
+ formatParts.push(`${debt.undated}/${debt.total} 条没日期`, `${debt.unlinked} 条没来源`);
300
+ }
301
+ if (agentsPresent && templateVersion !== TEMPLATE_VERSION) {
302
+ formatParts.push(`AGENTS 模板 ${templateVersion === 0 ? '无版本标记' : `v${templateVersion}`}(当前 v${TEMPLATE_VERSION})`);
303
+ }
304
+ const formatLine = formatParts.length > 0 ? `格式:${formatParts.join(' · ')}` : '';
289
305
  // 人格段:超上限只告警
290
306
  const c = payload.persona;
291
307
  const personaSummary = c.present
@@ -317,6 +333,7 @@ async function handleMemory(res, cfg) {
317
333
  `<p class="crumb"><a href="${VIEW}">首页</a> / 记忆</p>`,
318
334
  '<h1>记忆</h1>',
319
335
  `<p class="meta">${esc(usage)}</p>`,
336
+ formatLine ? `<p class="meta">${esc(formatLine)}</p>` : '',
320
337
  '<p class="meta">根目录 meta 由人和 agent 直接编辑,不进检索;这里只读,不提供编辑。</p>',
321
338
  `<h2>人格</h2>`,
322
339
  `<p class="meta">${esc(personaSummary)}</p>`,
@@ -431,36 +448,14 @@ async function handleNote(res, cfg, rel) {
431
448
  catch { /* 索引挂了也能显示正文,双链退化成纯文字 */ }
432
449
  const linkFor = linkResolver(all);
433
450
  let backlinks = [];
451
+ let backlinksTruncated = false;
434
452
  try {
435
- const relPath = loaded.rel;
436
- const byPath = new Map(all.map((note) => [note.path, note]));
437
- const seen = new Set();
438
- for (const edge of (await graphEdges(cfg)).edges) {
439
- if (edge.targetPath !== relPath || edge.sourcePath === relPath)
440
- continue;
441
- if (seen.has(edge.sourcePath))
442
- continue;
443
- seen.add(edge.sourcePath);
444
- const hit = byPath.get(edge.sourcePath);
445
- backlinks.push(hit ?? {
446
- title: path.basename(edge.sourcePath).replace(NOTE_EXT, ''),
447
- path: edge.sourcePath,
448
- absPath: '',
449
- link: '',
450
- tags: [],
451
- created: '',
452
- modified: '',
453
- lead: '',
454
- words: 0,
455
- metadata: {},
456
- status: '',
457
- type: '',
458
- authority: '',
459
- });
460
- }
461
- backlinks = backlinks.sort((a, b) => a.title.localeCompare(b.title));
453
+ // 按篇反查(plan §0.5.1 结论 3):打开一篇笔记不该为全库建图(10k 要 26–31 s)
454
+ const found = await backlinksOf(cfg, loaded.rel);
455
+ backlinks = found.notes.sort((a, b) => a.title.localeCompare(b.title));
456
+ backlinksTruncated = found.truncated;
462
457
  }
463
- catch { /* 图读不出来就不显示反链 */ }
458
+ catch { /* 反链读不出来就不显示 */ }
464
459
  const content = loaded.doc.content.length > MAX_CONTENT
465
460
  ? loaded.doc.content.slice(0, MAX_CONTENT)
466
461
  : loaded.doc.content;
@@ -485,7 +480,10 @@ async function handleNote(res, cfg, rel) {
485
480
  `<article>${renderMarkdown(content, { linkFor, skipFirstH1: true })}</article>`,
486
481
  '<h2>反链</h2>',
487
482
  backlinks.length
488
- ? `<ul>${backlinks.slice(0, 100).map((note) => `<li><a href="${esc(noteHref(note.path))}">${esc(note.title || note.path)}</a></li>`).join('')}</ul>`
483
+ ? `<ul>${backlinks.slice(0, 100).map((note) => `<li><a href="${esc(noteHref(note.path))}">${esc(note.title || note.path)}</a></li>`).join('')}</ul>` +
484
+ (backlinksTruncated || backlinks.length > 100
485
+ ? `<p class="meta">${backlinksTruncated ? '反链超过 200 条' : `共 ${backlinks.length} 条`},这里只列前 100 条。</p>`
486
+ : '')
489
487
  : '<p class="meta">没有其它笔记链到这里。</p>',
490
488
  ].join('\n');
491
489
  sendHtml(res, 200, shell(cfg, loaded.doc.title || loaded.rel, body));
@@ -66,6 +66,7 @@ window.__ModuleLoader__?.load({
66
66
  { group: '记忆', key: 'personaBudgetWords', label: '人格上限(词)', hint: 'PERSONA.md 的上限,默认 240(50-800)。人格永远注入、不参与截断;超了只告警' },
67
67
  { group: '写入', key: 'defaultTagsText', label: '默认标签', hint: '新笔记自动追加的标签,逗号分隔,不带 #(可空)' },
68
68
  { group: '写入', key: 'maxReadChars', label: '单次读取上限(字符)', hint: '默认 20000;zk-kit read 与别名工具的输出超了会截断并明确告知模型' },
69
+ { group: '工具', key: 'graphBudgetNotes', label: '全图统计上限(篇)', hint: '库超过这个篇数时不再建全图统计入链:zk_dream 跳过入链统计(graphSkipped),zk_lint 的单向链接改按篇反查。默认 2000(0-10000,0 = 永不建全图);上限 = 单次扫描上限,再高等于总是建全图。全图在 10k 上要 26–31 秒,调高前先确认等得起' },
69
70
  { group: '工具', key: 'aliasTools', label: '把 [alias] 注册成工具', hint: '默认关闭。打开后,加载插件时把各笔记本 .zk/config.toml 的 [alias] 里未注释的别名注册成 zk_<名>,模型可以像调内置工具一样调它们。\n别名是 $SHELL -c 执行的任意命令 —— 打开等于把这些命令交给 agent,只在你信得过 config.toml 内容时开。\n交互式命令(edit / 带 --interactive)会卡到超时,不适合当工具。改完要重载插件(或重启 DSH)才会出现在工具列表里', type: 'bool' },
70
71
  { group: 'zk', key: 'zkPath', label: 'zk 路径(可空)', hint: '空 = 自动找:配置 → $ZK_BIN → PATH → 插件内置(~/.dsh/zdiary/bin)' },
71
72
  { group: 'zk', key: 'zkVersion', label: '内置 zk 版本', hint: '「安装内置 zk」下载的版本,默认 0.15.7;改完点安装即升级' },
@@ -526,6 +526,7 @@ export function buildTools(workspaceOf = () => processWorkspace()) {
526
526
  '归档里有同名旧结论不会拦,但会放进 archived(带 supersede-reason):先读它,别把同一个错误结论重新提出来。' +
527
527
  'type / authority 只有 layered 模板会写进 frontmatter。tags 会写成 #hashtag;links 里的目标会被追加成 wiki 双链。' +
528
528
  '中文笔记如果没有任何标签(入参 / 默认值 / 正文 hashtag 都没有),会在 tagWarning 里提示 —— 只提示,不阻断。' +
529
+ '同目录里有「改一两个字」的相似标题时会放进 similar(带分数):只提示,不阻断,也不自动建链接。' +
529
530
  '根目录 meta 文件(AGENTS / USER / MEMORY 等)与 raw/ 、inbox/ 不能写:前者会被当成人写的工作面,后两者会被排除出索引。',
530
531
  parameters: {
531
532
  type: 'object',
@@ -563,6 +564,14 @@ export function buildTools(workspaceOf = () => processWorkspace()) {
563
564
  reason: { type: 'string' },
564
565
  }, ['path', 'title', 'reason']),
565
566
  },
567
+ similar: {
568
+ type: 'array',
569
+ items: objSchema({
570
+ title: { type: 'string' },
571
+ path: { type: 'string' },
572
+ score: { type: 'number' },
573
+ }, ['title', 'path', 'score']),
574
+ },
566
575
  warnings: { type: 'array', items: { type: 'string' } },
567
576
  }, ['notebook', 'path', 'absPath', 'title', 'tags', 'links', 'summaryApplied', 'archived', 'warnings']),
568
577
  },
@@ -606,6 +615,7 @@ export function buildTools(workspaceOf = () => processWorkspace()) {
606
615
  return {
607
616
  notebook: cfg.notebook, path: created.path, absPath: created.absPath, title: created.title, tags, links,
608
617
  summaryApplied: created.summaryApplied, archived, warnings,
618
+ ...(created.similar.length ? { similar: created.similar } : {}),
609
619
  ...(created.summaryWarning ? { summaryWarning: created.summaryWarning } : {}),
610
620
  ...(tagWarning ? { tagWarning } : {}),
611
621
  };
@@ -621,6 +631,10 @@ export function buildTools(workspaceOf = () => processWorkspace()) {
621
631
  lines.push('⚠️ ' + v.summaryWarning);
622
632
  if (v.tagWarning)
623
633
  lines.push('⚠️ ' + v.tagWarning);
634
+ if (v.similar?.length) {
635
+ lines.push('⚠️ 疑似已有:' + v.similar.map((s) => `${s.title}(${s.path},${s.score.toFixed(2)})`).join('、') +
636
+ ' —— 先 read 确认是不是同一条;要合并就 zk_supersede,不要直接再写一遍');
637
+ }
624
638
  if (v.archived.length) {
625
639
  lines.push('⚠️ 归档里有同名旧结论:' + v.archived.map((h) => h.path + (h.reason ? `(废弃原因:${h.reason})` : '(没有记录废弃原因)')).join(';') +
626
640
  ' —— 先读它,确认不是同一个结论再复用标题');
@@ -924,6 +938,13 @@ export function buildTools(workspaceOf = () => processWorkspace()) {
924
938
  tocWords: { type: 'number' },
925
939
  totalWords: { type: 'number' },
926
940
  overheadWords: { type: 'number' },
941
+ // 格式债 / 模板版本:只读元数据,比 memoryUsage 的投影早一步就能拿到
942
+ formatDebt: objSchema({
943
+ total: { type: 'number' },
944
+ undated: { type: 'number' },
945
+ unlinked: { type: 'number' },
946
+ }, ['total', 'undated', 'unlinked']),
947
+ templateVersion: { type: 'number' },
927
948
  persona: objSchema({
928
949
  present: { type: 'boolean' },
929
950
  contentWords: { type: 'number' },
@@ -963,7 +984,7 @@ export function buildTools(workspaceOf = () => processWorkspace()) {
963
984
  retiredWords: { type: 'number' },
964
985
  }, ['name', 'present', 'words', 'originalWords', 'retiredWords']),
965
986
  },
966
- }, ['text', 'words', 'budget', 'ratio', 'truncatedWords', 'retiredWords', 'tocWords', 'totalWords', 'overheadWords', 'persona', 'notebook', 'defaultNotebook', 'pinned', 'notebooks', 'files']),
987
+ }, ['text', 'words', 'budget', 'ratio', 'truncatedWords', 'retiredWords', 'tocWords', 'totalWords', 'overheadWords', 'formatDebt', 'templateVersion', 'persona', 'notebook', 'defaultNotebook', 'pinned', 'notebooks', 'files']),
967
988
  },
968
989
  async run(_args, env) {
969
990
  // 不 ensureNotebook:读记忆不该依赖 zk,笔记本不存在时就是空载荷
@@ -1021,8 +1042,9 @@ export function buildTools(workspaceOf = () => processWorkspace()) {
1021
1042
  'edges 是全部单向边数(items 截到 50 条时仍计全量),bodyOnly 是正文引用(不在 ## Links / ## 链接 小节)的单向边数。' +
1022
1043
  'links_only=true 时只列 Links 小节的单向链接,正文引用只进 bodyOnly,适合把桶当可修清单。' +
1023
1044
  'S 或 X 是日记的边不算 —— 日记天然是出边,回链它没有意义。' +
1024
- '笔记数触到扫描上限只会漏报;但 oneWayLinks.edgesTruncated=true 表示建图笔记载入触顶、边集可能不完整 —— ' +
1025
- '缺掉的回链边会把双向误判成单向,这是唯一可能误报的截断,看到它先归档旧笔记再重跑。' +
1045
+ '笔记数触到扫描上限只会漏报;但 oneWayLinks.edgesTruncated=true 表示边集可能不完整(小库建图触顶,' +
1046
+ '或大库按篇反查触到 50 目标 / 60 子进程的上限)—— 缺掉的回链边会把双向误判成单向,' +
1047
+ '这是唯一可能误报的截断,看到它先缩小排查范围再重跑。' +
1026
1048
  '只读:不改任何笔记。拿到清单后自己判断先修哪个,再用 zk_link / zk_append / zk_supersede 动手。',
1027
1049
  parameters: {
1028
1050
  type: 'object',
@@ -1124,6 +1146,8 @@ export function buildTools(workspaceOf = () => processWorkspace()) {
1124
1146
  '会读 MEMORY.md:已经晋升过的(`[[链接]]` 命中或条目里写了标题)移出候选、进 alreadyPromoted —— 不会每周原样重复。' +
1125
1147
  '退役行里的旧标题不再算已晋升,但 `→ [[新结论]]` 仍算。' +
1126
1148
  'backlog 是窗口外仍未晋升的笔记(按被引数),漏做一次不会永久掉队。' +
1149
+ '库超过全图统计上限时不再建全图统计入链(默认 2000 篇,设置页可调;graphBudget 给出生效值):' +
1150
+ 'graphSkipped=true,cited / citedBy / topCited 为空 —— 那是「没算」,不是「没人引」。' +
1127
1151
  'memory 给记忆余量(内容词 + 提示 = 总词,余量按总词算,可以为负);retireCandidates 给「可考虑退役」的条目' +
1128
1152
  '(来源归档 / 不存在、超过 ' + STALE_DAYS + ' 天未复核;显式写 archive/ 的有意引用不算)。' +
1129
1153
  'days 省略时窗口 = 距 DREAMS.md「上次做梦」的天数(没有则 7 天)。' +
@@ -1141,6 +1165,8 @@ export function buildTools(workspaceOf = () => processWorkspace()) {
1141
1165
  windowDays: { type: 'number' },
1142
1166
  since: { type: 'string' },
1143
1167
  truncated: { type: 'boolean' },
1168
+ graphSkipped: { type: 'boolean' },
1169
+ graphBudget: { type: 'number' },
1144
1170
  memory: objSchema({
1145
1171
  words: { type: 'number' },
1146
1172
  personaWords: { type: 'number' },
@@ -1202,7 +1228,7 @@ export function buildTools(workspaceOf = () => processWorkspace()) {
1202
1228
  reason: { type: 'string', enum: ['stale', 'source-missing', 'source-superseded'] },
1203
1229
  }, ['entry', 'date', 'age', 'reason']),
1204
1230
  },
1205
- }, ['notebook', 'windowDays', 'since', 'truncated', 'memory', 'counts', 'newNotes', 'alreadyPromoted', 'backlog', 'rejected', 'topCited', 'dailyLooseEnds', 'retireCandidates']),
1231
+ }, ['notebook', 'windowDays', 'since', 'truncated', 'graphSkipped', 'graphBudget', 'memory', 'counts', 'newNotes', 'alreadyPromoted', 'backlog', 'rejected', 'topCited', 'dailyLooseEnds', 'retireCandidates']),
1206
1232
  },
1207
1233
  async run(args, env) {
1208
1234
  const cfg = configFor(env.workspace, env.sessionId);
@@ -1285,6 +1311,9 @@ export function buildTools(workspaceOf = () => processWorkspace()) {
1285
1311
  lines.push('这个窗口里没有新材料。');
1286
1312
  if (v.truncated)
1287
1313
  lines.push('⚠️ 笔记数触到扫描上限:窗口与排名都不完整');
1314
+ if (v.graphSkipped) {
1315
+ lines.push('⚠️ 库超过全图统计上限(' + v.graphBudget + ' 篇),这次没统计入链:被引数与 topCited 是空的,不代表没人引用;可在设置页调整「全图统计上限(篇)」(graphBudgetNotes)');
1316
+ }
1288
1317
  lines.push('(只报告:MEMORY.md / DREAMS.md 由你按 AGENTS.md 写)');
1289
1318
  return text(lines.join('\n'));
1290
1319
  },
@@ -21,6 +21,16 @@
21
21
  export const TEMPLATE_VERSION = 8;
22
22
  /** 首行版本标记(实测 4 词);不许带日期 —— 带日期的写法实测 6 词,白花 2 词 */
23
23
  export const TEMPLATE_MARK = `<!-- zdiary-template: v${TEMPLATE_VERSION} -->`;
24
+ /** 版本标记的正则(本文件内用;外部只通过 `templateVersionOf` 取数,免得又一个口径) */
25
+ const TEMPLATE_MARK_RE = /<!--\s*zdiary-template:\s*v(\d+)\s*-->/;
26
+ /**
27
+ * AGENTS.md 里的模板版本;没有标记返回 0。
28
+ * 只读标记、不校验正文哨兵 —— 哨兵是 lint 的事,记忆页只要一眼可读的版本号。
29
+ */
30
+ export function templateVersionOf(body) {
31
+ const hit = TEMPLATE_MARK_RE.exec(String(body ?? ''));
32
+ return hit ? Number(hit[1]) : 0;
33
+ }
24
34
  /**
25
35
  * 当前版本的正文哨兵:只查「标记已经是当前版本」的文件,用来发现
26
36
  * 「只把首行数字改成 vN、正文还是旧版」。
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 { allNotes, GRAPH_BUDGET_NOTES, graphEdges, localDate, MAX_SCAN } from './zk.js';
17
17
  import { parseFrontmatter } from './frontmatter.js';
18
18
  // memory.ts 也 import 本模块(DREAM_INTERVAL_DAYS / daysSinceDream):这里是运行期才取用,
19
19
  // 循环引用在 ESM 下安全 —— 不要在模块顶层调用 memoryUsage。
@@ -287,7 +287,11 @@ export async function dreamNotebook(cfg, opts = {}, signal) {
287
287
  const sinceMs = now.getTime() - windowDays * 86_400_000;
288
288
  // 顺序跑:两个 zk 进程同时补索引会撞 SQLite 写锁(lint 里同样处理)
289
289
  const notes = await allNotes(cfg, {}, signal);
290
- const edges = (await graphEdges(cfg, signal)).edges;
290
+ // 全图在 10k 上 26–31 s / 17 MB(plan §0.5.1):超过预算就不建,并显式告诉调用方。
291
+ // 预算来自配置(设置页可调);opts.graphBudget 只给测试覆盖。
292
+ const graphBudget = Math.max(0, Math.trunc(opts.graphBudget ?? cfg.graphBudgetNotes ?? GRAPH_BUDGET_NOTES));
293
+ const graphReady = notes.length <= graphBudget;
294
+ const edges = graphReady ? (await graphEdges(cfg, signal)).edges : [];
291
295
  // 入链来源按目标分组:既算「被引几次」,也给 dream 一份上下文(谁在引它)
292
296
  const inbound = new Map();
293
297
  for (const edge of edges) {
@@ -416,6 +420,8 @@ export async function dreamNotebook(cfg, opts = {}, signal) {
416
420
  windowDays,
417
421
  since: localDate(new Date(sinceMs).toISOString()),
418
422
  truncated: notes.length >= MAX_SCAN,
423
+ graphSkipped: !graphReady,
424
+ graphBudget,
419
425
  counts: {
420
426
  window: windowNotes.length,
421
427
  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 });