dsh-zdiary-kit 3.9.0 → 3.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,4 +1,4 @@
1
- # dsh-zdiary-kit 3.9.0
1
+ # dsh-zdiary-kit 3.10.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),
@@ -21,6 +21,7 @@
21
21
  | `zk_supersede` | 废弃过时结论:标 `superseded` + 写 `reason` + 搬进 `archive/` + 重写能精确匹配的 `[[旧路径]]` 入链(其它写法列进 `missingLinks`);默认只预演;meta 文件不能废弃 |
22
22
  | `zk_rename` | 改名 / 换目录并修断链:入链(`[[…]]` 与 Markdown 链接,保留 `#锚点` 与 `\|别名`)按实际解析结果改到新路径,根目录 meta 里的 `[[来源]]` 一起改,被搬走那篇自己的相对 Markdown 链接按新位置重算;默认只预演 |
23
23
  | `zk_context` | 读知识库根目录的 `AGENTS.md` / `USER.md` / `MEMORY.md`(按注入预算截断)与角色人格 `PERSONA.md`(单独成段、不截断),并列出已配置的笔记本(名字 / 路径 / 结构 / 当前);宿主支持注入时这些内容每轮已自动带进系统提示。改 MEMORY 前用它看余量:`headroom` / `wouldTruncate` / `dropCandidates` 说明「再加一条会丢谁」,给 `proposed_entry` 或 `extra_words` 就能预估;同日条目按位置决胜(`sameDateCount`),不假装有使用频率 |
24
+ | `zk_memory_write` | 往 `MEMORY.md` / `USER.md` 末尾追加一条结论的**第一个 meta 写工具**;默认 `dry_run: true` 只预演、不动盘,`dry_run: false` 才真写(可带 `expect_stamp` 挡并发改动)。插件只做机械门:条目须是带 `YYYY-MM-DD` 与 `[[来源]]` 的顶层列表项、`[[来源]]` 要解析到活笔记、`add` 不能让注入载荷超预算(超了返回 `over-budget` + `dropCandidates`,**不静默截断**);`action: retire` 追加 `- [superseded …]` 标记(退役条目不进注入,不做容量门)。不改一个字、不合并 / 替换、不自动补日期 / 来源、不提议退役哪条;每次真实写入把 pre-image 摘要与一行 diff 追加到 `DREAMS.md` 供周审复核。改已有条目仍用原生 edit;`WORKFLOW.md` 里写了「改 MEMORY 先预演」 |
24
25
  | `zk_lint` | 体检:解析失败 / 断链 / 孤儿 / 无标签 / 单向链接 / 陈旧 / 重名标题 / 疑似重复标题 / 记忆链接失效 / frontmatter 缺字段 / 标签卫生 / 模板版本 / 人格(缺失·旧版·比插件新·标记与内容不符·未填占位符)/ 日记时间轴(最近 90 天的空块·倒序·格式·位置),每类最多 50 条;非日记笔记到 150 篇且没有 `INDEX.md` 时提示一句;另给 `missingId`(缺稳定 id 的非日记笔记数,只提示不回填);只报告不改写 |
25
26
  | `zk_dream` | 晋升材料:窗口新增(机械筛掉 `informal` 与无标签,带正文摘要与入链来源)、已在 MEMORY 的、窗口外积压、daily 未完成项、被引最多(先按「被日记提到几天」排);带 `missingId`(缺稳定 id 的非日记笔记数);只报告 |
26
27
  | `zk_stats` | 笔记数 / 标签数 / 断链 / 孤立 / 归档(superseded),顶层目录与前 10 个标签的实时分布;外加 `usage`:本地聚合计数(`walk` / `recall` / `entryPoints` / `counterEntries` 各用了几次,自某天起)—— 用来看「入口 + 一跳」这条路到底有没有被用上。只存计数,不记查询词、不记路径 |
@@ -81,8 +82,9 @@ DSH 自带的 AGENTS.md 加载只看「项目根 → 当前目录」链,**不
81
82
  **AGENTS.md 模板升到 v7**(精简模板):已有文件不会被覆盖,
82
83
  `zk_lint` 会把它报成旧版、并把新版全文附在报告里 —— 自己挑要哪几条搬过去。
83
84
 
84
- 维护用 `zk_lint`(结构体检 + 记忆链接核对)和 `zk_dream`(晋升候选 / 拒绝原因 / 未完成项):两个工具都**只读**,
85
- 写 `MEMORY.md` / `DREAMS.md` 由 agent 按 `AGENTS.md` 自己决定 —— 机械活留在插件,语义判断留在可审计的地方。
85
+ 维护用 `zk_lint`(结构体检 + 记忆链接核对)和 `zk_dream`(晋升候选 / 拒绝原因 / 未完成项):两个工具都**只读**;
86
+ 写 `MEMORY.md` / `DREAMS.md` 由 agent 按 `AGENTS.md` 自己决定(`zk_memory_write` 是唯一例外:按机械门往 `MEMORY.md`
87
+ 末尾追加一条结论,并自动往 `DREAMS.md` 追加改前摘要与 diff)—— 机械活留在插件,语义判断留在可审计的地方。
86
88
  `zk_dream` 会先读一遍 `MEMORY.md`:已经晋升过的(`[[链接]]` 命中,或条目里直接写了标题)移出候选、单列「已在 MEMORY」,
87
89
  不会每周原样重复(退役行里的旧标题不算已晋升,但退役行里的 `→ [[新结论]]` 仍算);
88
90
  窗口外仍未晋升的进 `backlog`,漏做一次不会永久掉队;不传 `days` 时窗口 = 距 `DREAMS.md`
@@ -461,13 +463,13 @@ zk-kit doctor # 自检:zk / 笔记本 / 模板 / group
461
463
  浏览器半边 `client.ts` 零 import,`postbuild` 把 tsc 补的 `export {}` 删掉,并检查没有顶层声明
462
464
  (DSH 会把多个插件的 `client.js` 拼进同一个 combo 脚本,顶层 `const` / `function` 会撞名导致插件不激活)。
463
465
  - `bun run typecheck` · `bun run build` · `bun run test`(真起 zk)·
464
- `bun run smoke`(加载 dist:15 个内置工具各跑一遍 + 12 条路由(设置 8 + 只读 4)都发真实请求(`/install` 只验非法版本,不下载),并检查输出 schema 在 DSH 支持的子集内)·
466
+ `bun run smoke`(加载 dist:16 个内置工具各跑一遍 + 12 条路由(设置 8 + 只读 4)都发真实请求(`/install` 只验非法版本,不下载),并检查输出 schema 在 DSH 支持的子集内)·
465
467
  `bun run docs`(把 README / docs 里 `zk-kit …` 代码块在临时 vault 上逐条真跑;`smoke` 末尾会带上)·
466
468
  `bun run fixture`(生成 1k / 10k 规模夹具;库规模 / 链接密度与各用例的 10k 实测、复跑方法见 `docs/bench-baseline.md`;
467
469
  `--links-per-note` 决定链接密度 —— 建索引成本主要花在链接上,产出目录自带 `.zk/config.toml`,进去 `zk index` 即可)·
468
470
  `bun run bench`(成本表:逐用例真起 zk,记子进程数 / 回传字节 / 峰值 RSS / p50 / p95 与库的篇数 / 链接数;默认 1k、3 轮;
469
471
  全量 10k 实测与复跑方法见 `docs/bench-baseline.md`)
470
- - **耗时差两个数量级**:`bun run test` 约 110 s(248 个用例,真起 zk;机器快慢能差一倍);`fixture` 百毫秒级;`bench` 默认 1k 约十几秒,
472
+ - **耗时差两个数量级**:`bun run test` 约 2 min(280 个用例,真起 zk;机器快慢能差一倍);`fixture` 百毫秒级;`bench` 默认 1k 约十几秒,
471
473
  10k 上光一条 `graph.full` 就是 30 s、冷建索引几分钟。所以 `bench` **不在** `check` / CI 里,跟测试完全分开,不会因为你跑测试而变慢。
472
474
  - `bun run test` 会先按插件自己的顺序找 zk(配置 → `ZK_BIN` → PATH → `~/.dsh/zdiary/bin`),跑完要求 **skip = 0**:
473
475
  集成测试跳过一律按失败处理,否则「全绿」可能是「什么都没跑」。要换 zk 就 `ZK_BIN=/path/to/zk bun run check`。
@@ -497,7 +499,7 @@ src/
497
499
  │ ├── dsh.ts # 宿主契约(纯类型,编译后为空)
498
500
  │ └── exec.ts / http.ts / json-file.ts
499
501
  ├── features/
500
- │ ├── zk-tools/feature.ts # 15 个内置工具 + [alias] 别名工具
502
+ │ ├── zk-tools/feature.ts # 16 个内置工具 + [alias] 别名工具
501
503
  │ ├── settings/ # 宿主 API + 浏览器 section
502
504
  │ └── readonly/ # 只读视图:GET-only 路由 + Web 1.0 渲染(无 JS)
503
505
  └── cli.ts # zk-kit 命令行
@@ -42,6 +42,7 @@ export const DEFAULTS = {
42
42
  defaultTags: [],
43
43
  maxReadChars: 20_000,
44
44
  aliasTools: false,
45
+ recallSignal: false,
45
46
  memoryBudgetWords: 500,
46
47
  personaBudgetWords: 240,
47
48
  graphBudgetNotes: 2_000,
@@ -148,6 +149,8 @@ export function normalizeConfig(raw, workspace = processWorkspace()) {
148
149
  // 只认 true / "true"(设置页与 CLI 传字符串):1 / "yes" / "false" 一律当未启用,
149
150
  // 免得拼错一个值就静默把别名注册成工具
150
151
  aliasTools: src.aliasTools === true || src.aliasTools === 'true',
152
+ // 同一个口径:只认 true / "true",拼错的值静默当未启用(sidecar 默认绝不落盘)
153
+ recallSignal: src.recallSignal === true || src.recallSignal === 'true',
151
154
  memoryBudgetWords: clamp(Number(src.memoryBudgetWords), 50, 2000, DEFAULTS.memoryBudgetWords),
152
155
  personaBudgetWords: clamp(Number(src.personaBudgetWords), 50, 800, DEFAULTS.personaBudgetWords),
153
156
  graphBudgetNotes,
@@ -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, backlinksOf, hasNotebook, isUnderDir, localDate, readNote, scanNotes, searchNotes, ZkError } from '../../lib/zk.js';
18
+ import { absPathOf, attachSummaries, 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';
@@ -162,14 +162,16 @@ function tagCounts(notes) {
162
162
  function tagLinks(tags) {
163
163
  return tags.map((tag) => `<a href="${esc(viewHref({ p: 'tag', tag }))}">#${esc(tag)}</a>`).join(' ');
164
164
  }
165
- function noteTable(notes) {
165
+ function noteTable(cfg, notes) {
166
166
  if (!notes.length)
167
167
  return '<p class="meta">没有笔记。</p>';
168
- const rows = notes.map((note) => {
168
+ // 15.6:scanNotes 来的结果没读过正文,只对这一批(recent / journal / 搜索 / 标签,都有界)补摘要
169
+ const rows = attachSummaries(cfg, notes).map((note) => {
169
170
  const date = localDate(note.modified || note.created) || '—';
170
- return `<tr><td class="meta">${esc(date)}</td><td><a href="${esc(noteHref(note.path))}">${esc(note.title || note.path)}</a></td><td class="meta">${tagLinks(note.tags)}</td></tr>`;
171
+ const brief = note.summary.length > 80 ? note.summary.slice(0, 80) + '…' : note.summary;
172
+ return `<tr><td class="meta">${esc(date)}</td><td><a href="${esc(noteHref(note.path))}">${esc(note.title || note.path)}</a></td><td class="meta">${esc(brief || '—')}</td><td class="meta">${tagLinks(note.tags)}</td></tr>`;
171
173
  }).join('');
172
- return `<table><tr><th>日期</th><th>标题</th><th>标签</th></tr>${rows}</table>`;
174
+ return `<table><tr><th>日期</th><th>标题</th><th>摘要</th><th>标签</th></tr>${rows}</table>`;
173
175
  }
174
176
  function searchForm(value = '') {
175
177
  return `<form class="search" method="get" action="${VIEW}"><input type="search" name="q" value="${esc(value)}" placeholder="搜索标题、正文…" aria-label="搜索"><button type="submit">搜索</button></form>`;
@@ -202,9 +204,9 @@ async function handleHome(res, cfg) {
202
204
  searchForm(),
203
205
  `<p class="meta">${atLeast}${all.length} 篇笔记 · ${atLeast}${tags.length} 个标签 · 只读</p>`,
204
206
  '<h2>最近更新</h2>',
205
- noteTable(recent),
207
+ noteTable(cfg, recent),
206
208
  '<h2>日记</h2>',
207
- noteTable(journal),
209
+ noteTable(cfg, journal),
208
210
  '<h2>标签</h2>',
209
211
  tags.length
210
212
  ? `<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>`
@@ -222,7 +224,7 @@ async function handleSearch(res, cfg, q) {
222
224
  `<h1>搜索:${esc(q)}</h1>`,
223
225
  searchForm(q),
224
226
  `<p class="meta">${notes.length} 条结果(最多 100 条)</p>`,
225
- noteTable(notes),
227
+ noteTable(cfg, notes),
226
228
  ].join('\n');
227
229
  sendHtml(res, 200, shell(cfg, `搜索 ${q}`, body));
228
230
  }
@@ -350,7 +352,7 @@ async function handleMemory(res, cfg) {
350
352
  `<p class="meta">${esc(personaSummary)}</p>`,
351
353
  ...personaSections,
352
354
  '<h2>用户</h2>',
353
- fileArticle('USER.md', '用户偏好;可以跨库共享。'),
355
+ fileArticle('USER.md', '用户偏好。'),
354
356
  '<h2>工作约定</h2>',
355
357
  fileArticle('AGENTS.md', '硬规则,永不截断;属于记忆预算。'),
356
358
  '<h2>记忆</h2>',
@@ -396,7 +398,7 @@ async function handleTag(res, cfg, tag) {
396
398
  `<p class="crumb"><a href="${VIEW}">首页</a> / <a href="${esc(viewHref({ p: 'tags' }))}">标签</a></p>`,
397
399
  `<h1>#${esc(tag)}</h1>`,
398
400
  `<p class="meta">${notes.length} 篇(最多 200 篇)</p>`,
399
- noteTable(notes),
401
+ noteTable(cfg, notes),
400
402
  ].join('\n');
401
403
  sendHtml(res, 200, shell(cfg, `#${tag}`, body));
402
404
  }
@@ -10,6 +10,7 @@
10
10
  * · 代码块先 stash 成占位符,避免里面的 ** / [ ] 被当成强调或链接。
11
11
  */
12
12
  import { ROUTE_BASE } from '../../lib/http.js';
13
+ import { fenceMarker } from '../../lib/fence.js';
13
14
  const ESCAPES = {
14
15
  '&': '&amp;',
15
16
  '<': '&lt;',
@@ -141,7 +142,6 @@ const UL = /^\s*[-*+]\s+(.*)$/;
141
142
  const OL = /^\s*\d+[.)]\s+(.*)$/;
142
143
  const QUOTE = /^\s*>\s?(.*)$/;
143
144
  const HEADING = /^(#{1,6})\s+(.*)$/;
144
- const FENCE = /^\s*```/;
145
145
  /** 独占一行的 HTML 注释:不渲染。模板首行就是 `<!-- zdiary-template: vN -->`(lint 的版本标记),
146
146
  * 转义后当段落显示等于把内部约定摆到页面最上面 */
147
147
  const HTML_COMMENT = /^\s*<!--[\s\S]*?-->\s*$/;
@@ -164,15 +164,20 @@ export function renderMarkdown(source, opts = {}) {
164
164
  };
165
165
  while (i < lines.length) {
166
166
  const line = lines[i] ?? '';
167
- if (FENCE.test(line)) {
167
+ const open = fenceMarker(line);
168
+ if (open) {
168
169
  flush();
169
- const lang = line.trim().slice(3).trim();
170
170
  i += 1;
171
171
  const code = [];
172
- while (i < lines.length && !FENCE.test(lines[i] ?? ''))
172
+ while (i < lines.length) {
173
+ const close = fenceMarker(lines[i] ?? '');
174
+ // 闭合必须同字符、长度 ≥ 开启行且不带语言标记:块里的 ```js 只是代码
175
+ if (close && close.char === open.char && close.len >= open.len && !close.info)
176
+ break;
173
177
  code.push(lines[i++] ?? '');
178
+ }
174
179
  i += 1;
175
- out.push(`<pre><code${lang ? ` class="language-${esc(lang)}"` : ''}>${esc(code.join('\n'))}</code></pre>`);
180
+ out.push(`<pre><code${open.info ? ` class="language-${esc(open.info)}"` : ''}>${esc(code.join('\n'))}</code></pre>`);
176
181
  continue;
177
182
  }
178
183
  // 整行跳过:不显示,也不 flush —— 它是不可见的元信息,不该把段落或列表从中间切开
@@ -64,6 +64,7 @@ window.__ModuleLoader__?.load({
64
64
  { group: '目录与 group', key: 'archiveDir', label: '归档目录', hint: 'supersede 之后笔记搬到这里(保留原相对路径,不删除),默认 archive;所有笔记本共用。旧归档目录非空时拒绝改动 —— 插件不会自动迁移文件' },
65
65
  { group: '记忆', key: 'memoryBudgetWords', label: '注入预算(词)', hint: 'AGENTS.md + USER.md + MEMORY.md 的合计上限,默认 500(中文按 2 字 1 词)。超了先丢 MEMORY 里日期最旧的条目(一条日期都没有才退回从尾部丢),并回显截断了多少' },
66
66
  { group: '记忆', key: 'personaBudgetWords', label: '人格上限(词)', hint: 'PERSONA.md 的上限,默认 240(50-800)。人格永远注入、不参与截断;超了只告警' },
67
+ { group: '记忆', key: 'recallSignal', label: '记录召回信号', hint: '默认关闭。打开后把 zk_search / zk_query / zk_recall 命中的笔记按 path 聚合进 .zk/dsh-recall.json(哪篇 / 哪天 / 哪类检索),供 topCited 排序、退役保护、同日淘汰与周审审计抽样使用。只存聚合计数,不记查询词、不记正文、不上报;关掉时不读不写,输出与老版一致', type: 'bool' },
67
68
  { group: '写入', key: 'defaultTagsText', label: '默认标签', hint: '新笔记自动追加的标签,逗号分隔,不带 #(可空)' },
68
69
  { group: '写入', key: 'maxReadChars', label: '单次读取上限(字符)', hint: '默认 20000;zk-kit read 与别名工具的输出超了会截断并明确告知模型' },
69
70
  { group: '工具', key: 'graphBudgetNotes', label: '全图统计上限(篇)', hint: '库超过这个篇数时不再建全图统计入链:zk_dream 跳过入链统计(graphSkipped),zk_lint 的单向链接改按篇反查。默认 2000(0-10000,0 = 永不建全图);上限 = 单次扫描上限,再高等于总是建全图。全图在 10k 上要 26–31 秒,调高前先确认等得起' },
@@ -1,5 +1,5 @@
1
1
  /**
2
- * zk 工具(feature 的公共入口):15 个内置工具 + `[alias]` 别名工具,全部经 lib/zk.ts。
2
+ * zk 工具(feature 的公共入口):16 个内置工具 + `[alias]` 别名工具,全部经 lib/zk.ts。
3
3
  *
4
4
  * 设计要点:
5
5
  * · 除 zk_context(只读 meta 文件,不依赖 zk)外,每个工具进来先 ensureNotebook —— 第一次调用就自动建好笔记本,用户不用先点设置页;
@@ -15,13 +15,16 @@ import { configFor, pinSession, sessionNotebook, sessionState } from '../../conf
15
15
  import { defaultNotebook, expandHome, processWorkspace, resolveInWorkspace } from '../../config/paths.js';
16
16
  import { S, validateArgs } from '../../lib/tool.js';
17
17
  import { ensureNotebook, newNoteDir } from '../../lib/notebook.js';
18
- import { searchNotes, searchNotesDetailed, createNote, appendToNote, ensureDailyNote, appendDaily, linkNotes, withTags, taglessCjkWarning, notebookStats, supersedeNote, renameNote, hasNotebook, isUnderDir, localDate as dateOnly, runAlias, hasCjk, walkFrom, ZkError, } from '../../lib/zk.js';
18
+ import { searchNotes, searchNotesDetailed, createNote, appendToNote, ensureDailyNote, appendDaily, linkNotes, withTags, taglessCjkWarning, notebookStats, supersedeNote, renameNote, hasNotebook, isUnderDir, localDate as dateOnly, runAlias, hasCjk, walkFrom, scanNotes, ZkError, } from '../../lib/zk.js';
19
19
  import { configuredAliases, readAliases } from '../../lib/alias.js';
20
20
  import { buildMemoryPayload, memoryCapacity, META_FILES } from '../../lib/memory.js';
21
21
  import { assembleRecall } from '../../lib/recall.js';
22
22
  import { entryPointLines, entryPointsOf } from '../../lib/entry-points.js';
23
23
  import { archivedCounterparts, describeCounterEntries } from '../../lib/archive-probe.js';
24
24
  import { bumpUsage, readUsage } from '../../lib/usage.js';
25
+ import { bumpRecall } from '../../lib/recall-signal.js';
26
+ import { wikiIndex } from '../../lib/wikilink.js';
27
+ import { writeMemory } from '../../lib/memory-write.js';
25
28
  import { META_NAMES } from '../../lib/meta.js';
26
29
  import { formatLintExtras, formatMemoryLinks, lintNotebook } from '../../lib/lint.js';
27
30
  import { dreamNotebook, STALE_DAYS } from '../../lib/dream.js';
@@ -293,9 +296,9 @@ function withElsewhere(err, cfg, workspace, rel) {
293
296
  function tagSuffix(record) {
294
297
  return record.tags.length ? ' · ' + record.tags.map((t) => '#' + t).join(' ') : '';
295
298
  }
296
- /** R2:snippet 比 lead 多带命中上下文时才替换它,否则维持原输出 */
299
+ /** 15.6:先用 summary(## Summary 首段),空串再按 R2 口径退回 snippet / lead */
297
300
  function detailOf(n) {
298
- return n.snippet && n.snippet !== n.lead ? n.snippet : (n.lead ?? '');
301
+ return n.summary || (n.snippet && n.snippet !== n.lead ? n.snippet : (n.lead ?? ''));
299
302
  }
300
303
  /** 死胡同提醒(措辞与 `zk-kit search` 共用一份);没有就一个字都不加 */
301
304
  function counterBlockOf(entries, truncated, zeroHit) {
@@ -443,6 +446,8 @@ export function buildTools(workspaceOf = () => processWorkspace()) {
443
446
  created: { type: 'string' },
444
447
  lead: { type: 'string' },
445
448
  words: { type: 'number' },
449
+ /** 15.6:`## Summary` 首段 / frontmatter summary;老笔记为空串 */
450
+ summary: { type: 'string' },
446
451
  /** 命中片段,没有时整个键不出现(避免 undefined 让宿主判 invalid output) */
447
452
  snippet: { type: 'string' },
448
453
  }, ['title', 'path', 'absPath', 'tags', 'created', 'lead']),
@@ -479,6 +484,8 @@ export function buildTools(workspaceOf = () => processWorkspace()) {
479
484
  ...(entryPoints.length ? ['entryPoints'] : []),
480
485
  ...(counters.entries.length ? ['counterEntries'] : []),
481
486
  ]);
487
+ // 15.2:只记 path / 日期 / 检索种类,不记查询词;默认关时零写入
488
+ bumpRecall(cfg, result.notes.map((n) => ({ path: n.path, title: n.title })), 'search');
482
489
  return {
483
490
  notebook: cfg.notebook,
484
491
  count: result.notes.length,
@@ -489,7 +496,7 @@ export function buildTools(workspaceOf = () => processWorkspace()) {
489
496
  ...(result.total === undefined ? {} : { total: result.total }),
490
497
  notes: result.notes.map((n) => ({
491
498
  title: n.title, path: n.path, absPath: n.absPath, tags: n.tags,
492
- created: dateOnly(n.created), lead: n.lead, words: n.words,
499
+ created: dateOnly(n.created), lead: n.lead, words: n.words, summary: n.summary,
493
500
  ...(n.snippet ? { snippet: n.snippet } : {}),
494
501
  })),
495
502
  ...(entryPoints.length ? { entryPoints } : {}),
@@ -562,6 +569,8 @@ export function buildTools(workspaceOf = () => processWorkspace()) {
562
569
  created: { type: 'string' },
563
570
  lead: { type: 'string' },
564
571
  words: { type: 'number' },
572
+ /** 15.6:`## Summary` 首段 / frontmatter summary;老笔记为空串 */
573
+ summary: { type: 'string' },
565
574
  snippet: { type: 'string' },
566
575
  archived: { type: 'boolean' },
567
576
  }, ['title', 'path', 'absPath', 'type', 'status', 'authority', 'tags', 'created', 'lead', 'archived']),
@@ -607,6 +616,7 @@ export function buildTools(workspaceOf = () => processWorkspace()) {
607
616
  ...(entryPoints.length ? ['entryPoints'] : []),
608
617
  ...(counters.entries.length ? ['counterEntries'] : []),
609
618
  ]);
619
+ bumpRecall(cfg, notes.map((n) => ({ path: n.path, title: n.title })), 'query');
610
620
  return {
611
621
  notebook: cfg.notebook,
612
622
  count: notes.length,
@@ -626,6 +636,7 @@ export function buildTools(workspaceOf = () => processWorkspace()) {
626
636
  created: dateOnly(n.created),
627
637
  lead: n.lead,
628
638
  words: n.words,
639
+ summary: n.summary,
629
640
  ...(n.snippet ? { snippet: n.snippet } : {}),
630
641
  archived: n.path.startsWith(cfg.archiveDir + '/'),
631
642
  })),
@@ -648,7 +659,7 @@ export function buildTools(workspaceOf = () => processWorkspace()) {
648
659
  : v.hasMore ? `\n⚠️ 还有更多匹配没返回(已检查 ${v.scanned} 条候选);要更全就提高 limit 或缩小过滤范围` : '';
649
660
  const lines = v.notes.map((n, i) => {
650
661
  const badges = [String(n.type || '—'), String(n.status || 'no-status'), n.archived ? '已归档' : ''].filter(Boolean);
651
- const detail = detailOf({ lead: String(n.lead ?? ''), snippet: String(n.snippet ?? '') });
662
+ const detail = detailOf({ summary: String(n.summary ?? ''), lead: String(n.lead ?? ''), snippet: String(n.snippet ?? '') });
652
663
  return `${i + 1}. ${String(n.title)} [${badges.join(' · ')}]\n ${String(n.absPath || n.path)} · ${String(n.created)}${detail ? '\n ' + detail : ''}`;
653
664
  });
654
665
  return text(`${v.count} 条(笔记本 ${v.notebook})\n` + lines.join('\n') +
@@ -693,6 +704,8 @@ export function buildTools(workspaceOf = () => processWorkspace()) {
693
704
  title: { type: 'string' },
694
705
  path: { type: 'string' },
695
706
  absPath: { type: 'string' },
707
+ /** 15.6:`## Summary` 首段 / frontmatter summary;老笔记为空串 */
708
+ summary: { type: 'string' },
696
709
  included: { type: 'boolean' },
697
710
  reason: { type: 'string', enum: ['included', 'duplicate', 'empty', 'over-budget'] },
698
711
  }, ['title', 'path', 'absPath', 'included', 'reason']),
@@ -1407,6 +1420,122 @@ export function buildTools(workspaceOf = () => processWorkspace()) {
1407
1420
  return text(drift + head + persona + totals + capacity + (v.text ? '\n\n' + v.text : ''));
1408
1421
  },
1409
1422
  }),
1423
+ t({
1424
+ name: 'zk_memory_write',
1425
+ description: '写记忆的第一个工具:往 MEMORY.md / USER.md 末尾追加一条结论。默认 dry_run: true,只预演、不动盘;' +
1426
+ '确认后传 dry_run: false 才真写(可把预演返回的 stamp 放进 expect_stamp,挡住「预演之后有人改过」)。' +
1427
+ '调用方给完整条目正文,插件只做机械门:必须是一条带 YYYY-MM-DD 与 [[来源]] 的顶层列表项、来源要解析到活笔记、' +
1428
+ '新增不能让注入载荷超预算(超了给结构化错误 + dropCandidates,绝不静默截断)。' +
1429
+ 'action: retire 追加 `- [superseded …]` 标记(退役条目不进注入,不做容量门)。' +
1430
+ '不替换、不合并、不自动补日期 / 来源、不提议退役哪条 —— 语义判断全归调用方;' +
1431
+ '每次真实写入把 pre-image 摘要与一行 diff 追加到 DREAMS.md 供周审复核。' +
1432
+ '想改已有条目仍用原生 edit;本工具只往末尾追加。',
1433
+ parameters: {
1434
+ type: 'object',
1435
+ properties: {
1436
+ target: S.enum('写哪份:MEMORY 或 USER(根目录 MEMORY.md / USER.md)', ['MEMORY', 'USER']),
1437
+ action: S.enum('add(默认)= 追加一条现行结论;retire = 追加一条退役标记', ['add', 'retire']),
1438
+ entry: S.str('完整条目正文,例:`- **结论。** 2026-11-12(来源:[[笔记标题]])`;插件不改一个字'),
1439
+ dry_run: S.bool('true(默认)= 只预演、不改盘;false = 真的写'),
1440
+ expect_stamp: S.str('可选:预演返回的 stamp,带回来挡并发改动'),
1441
+ },
1442
+ required: ['entry'],
1443
+ additionalProperties: false,
1444
+ },
1445
+ output: {
1446
+ schema: objSchema({
1447
+ notebook: { type: 'string' },
1448
+ accepted: { type: 'boolean' },
1449
+ rejection: { type: 'string' },
1450
+ detail: { type: 'string' },
1451
+ target: { type: 'string' },
1452
+ action: { type: 'string', enum: ['add', 'retire'] },
1453
+ dryRun: { type: 'boolean' },
1454
+ performed: { type: 'boolean' },
1455
+ source: { type: 'string' },
1456
+ sourceTarget: { type: 'string' },
1457
+ stamp: { type: 'string' },
1458
+ words: { type: 'number' },
1459
+ budget: { type: 'number' },
1460
+ headroom: { type: 'number' },
1461
+ extraWords: { type: 'number' },
1462
+ wouldTruncate: { type: 'boolean' },
1463
+ needToFree: { type: 'number' },
1464
+ dropCandidates: {
1465
+ type: 'array',
1466
+ items: objSchema({
1467
+ title: { type: 'string' },
1468
+ date: { type: 'string' },
1469
+ words: { type: 'number' },
1470
+ reason: { type: 'string', enum: ['oldest', 'same-date', 'undated'] },
1471
+ }, ['title', 'date', 'words', 'reason']),
1472
+ },
1473
+ beforeWords: { type: 'number' },
1474
+ afterWords: { type: 'number' },
1475
+ diff: { type: 'string' },
1476
+ indexComplete: { type: 'boolean' },
1477
+ }, ['notebook', 'accepted', 'rejection', 'detail', 'target', 'action', 'dryRun', 'performed',
1478
+ 'source', 'sourceTarget', 'stamp', 'words', 'budget', 'headroom', 'extraWords', 'wouldTruncate',
1479
+ 'needToFree', 'dropCandidates', 'beforeWords', 'afterWords', 'diff', 'indexComplete']),
1480
+ },
1481
+ async run(args, env) {
1482
+ const cfg = configFor(env.workspace, env.sessionId);
1483
+ // 不 ensureNotebook:预演不该顺手建库。索引只为核实 [[来源]],扫不全就只放路径式来源过。
1484
+ let index = { byTitle: new Map(), byId: new Map() };
1485
+ let indexComplete = false;
1486
+ if (hasNotebook(cfg)) {
1487
+ try {
1488
+ const scan = await scanNotes(cfg, {}, env.signal);
1489
+ index = wikiIndex(scan.notes);
1490
+ indexComplete = scan.completeness === 'complete';
1491
+ }
1492
+ catch { /* 索引不可用时退化为「只有路径式来源能过」,不装作全库可解析 */ }
1493
+ }
1494
+ const r = writeMemory(cfg, {
1495
+ target: (args.target ? String(args.target) : 'MEMORY'),
1496
+ action: (args.action ? String(args.action) : 'add'),
1497
+ entry: String(args.entry ?? ''),
1498
+ dryRun: args.dry_run !== false,
1499
+ expectStamp: args.expect_stamp ? String(args.expect_stamp) : undefined,
1500
+ index,
1501
+ indexComplete,
1502
+ });
1503
+ return { notebook: cfg.notebook, ...r };
1504
+ },
1505
+ render(_args, value) {
1506
+ const v = value;
1507
+ const lines = [];
1508
+ if (!v.accepted) {
1509
+ lines.push(`已拒绝(${v.rejection}):${v.detail}`);
1510
+ if (v.rejection === 'over-budget') {
1511
+ lines.push(`当前记忆 ${v.words}/${v.budget} 词,余 ${v.headroom} 词;拟新增 ${v.extraWords} 词,需先腾出 ${v.needToFree} 词。`);
1512
+ if (v.dropCandidates.length) {
1513
+ lines.push('会让位的条目(插件不替你退役):');
1514
+ for (const c of v.dropCandidates)
1515
+ lines.push(` · ${c.title}(${c.words} 词 · ${c.reason}${c.date ? ' · ' + c.date : ''})`);
1516
+ }
1517
+ }
1518
+ return text(lines.join('\n'));
1519
+ }
1520
+ if (v.dryRun) {
1521
+ lines.push(`预演通过(没有动任何文件):将往 ${v.target} 追加一条。`);
1522
+ lines.push(v.diff);
1523
+ }
1524
+ else {
1525
+ lines.push(`已写入 ${v.target}:${v.diff}`);
1526
+ lines.push('pre-image 摘要与这行 diff 已追加到 DREAMS.md,供周审复核。');
1527
+ }
1528
+ lines.push(`来源:[[${v.sourceTarget}]] → ${v.source || '(未解析)'}`);
1529
+ lines.push(`容量:记忆 ${v.words}/${v.budget} 词,余 ${v.headroom} 词` +
1530
+ (v.action === 'add' ? ` · 本次新增 ${v.extraWords} 词` : ' · 退役标记不占注入预算') +
1531
+ ` · 文件词数 ${v.beforeWords} → ${v.afterWords}`);
1532
+ if (!v.indexComplete)
1533
+ lines.push('⚠️ 活笔记索引没扫全,本次只核实了路径式来源。');
1534
+ if (v.dryRun)
1535
+ lines.push(`确认后传 dry_run: false 执行;建议带上 expect_stamp: "${v.stamp}"。`);
1536
+ return text(lines.join('\n'));
1537
+ },
1538
+ }),
1410
1539
  t({
1411
1540
  name: 'zk_lint',
1412
1541
  description: '给知识库做体检:断链 / 孤儿 / 无标签 / 单向链接 / 陈旧(N 天没改)/ 重名标题,每类最多 50 条并给总数。' +
@@ -1616,6 +1745,9 @@ export function buildTools(workspaceOf = () => processWorkspace()) {
1616
1745
  dailyMentions: { type: 'number' },
1617
1746
  daysMentioned: { type: 'number' },
1618
1747
  lastMentioned: { type: 'string' },
1748
+ /** 15.2:仅在召回信号生效时出现(可选,默认关时输出逐字节不变) */
1749
+ recallDays: { type: 'number' },
1750
+ recallKinds: { type: 'number' },
1619
1751
  }, ['title', 'path', 'cited', 'dailyMentions', 'daysMentioned', 'lastMentioned']),
1620
1752
  },
1621
1753
  dailyLooseEnds: {
@@ -1635,6 +1767,8 @@ export function buildTools(workspaceOf = () => processWorkspace()) {
1635
1767
  reason: { type: 'string', enum: ['stale', 'source-missing', 'source-superseded'] },
1636
1768
  }, ['entry', 'date', 'age', 'reason']),
1637
1769
  },
1770
+ /** 15.2:仅在召回信号生效时出现;固定比例、与分数无关的窗口外抽样 */
1771
+ auditSamples: { type: 'array', items: DREAM_CANDIDATE },
1638
1772
  }, ['notebook', 'windowDays', 'since', 'truncated', 'completeness', 'scanLimit', 'graphSkipped', 'graphBudget', 'missingId', 'memory', 'counts', 'newNotes', 'alreadyPromoted', 'backlog', 'rejected', 'topCited', 'dailyLooseEnds', 'retireCandidates']),
1639
1773
  },
1640
1774
  async run(args, env) {
@@ -1716,7 +1850,12 @@ export function buildTools(workspaceOf = () => processWorkspace()) {
1716
1850
  (c.daysMentioned > 0 ? ' · 日记 ' + c.daysMentioned + ' 天(最近 ' + c.lastMentioned + ')' : ''));
1717
1851
  }
1718
1852
  }
1719
- if (!v.newNotes.length && !v.dailyLooseEnds.length && !v.topCited.length)
1853
+ if (v.auditSamples?.length) {
1854
+ lines.push('审计抽样(与分数无关,固定比例):');
1855
+ for (const n of v.auditSamples.slice(0, 10))
1856
+ lines.push(' · ' + (n.title || n.path) + '(' + n.path + ')');
1857
+ }
1858
+ if (!v.newNotes.length && !v.dailyLooseEnds.length && !v.topCited.length && !v.auditSamples?.length)
1720
1859
  lines.push('这个窗口里没有新材料。');
1721
1860
  if (v.completeness === 'partial')
1722
1861
  lines.push('⚠️ 笔记数触到扫描上限(' + v.scanLimit + ' 篇):窗口与排名都不完整');
@@ -7,18 +7,18 @@
7
7
  * 或在设置页点「写入 AGENTS.md 模板」—— 否则默认安装既没有约定、也没有周节奏提醒。
8
8
  *
9
9
  * 为什么单独一个文件:它是「给人读的文档」,不是逻辑;放在这里也方便直接对照
10
- * docs/features/memory.md 的口径(检索词归宿 / 中文必打 tags)。
10
+ * docs/features/memory.md 的口径(检索词归宿 / 中文检索)。
11
11
  * 注意别让运行期消息只指向 docs/:插件发布后文档在 profile 的 node_modules 里,agent 够不着;
12
12
  * lint 的旧版提示直接带模板全文(见 lib/lint.ts 的 LintTemplateBucket.currentText)。
13
13
  *
14
14
  * 长度是设计约束:AGENTS.md 属于注入预算(默认 500 词,中文 2 字 = 1 词)且**永不截断**,
15
15
  * 模板自己吃掉过半预算,USER / MEMORY 就没位置了 —— 所以这里只留规则,不写教程。
16
- * 目标 ≤190 词(AGENTS_TEMPLATE 实测 190、AGENTS_TEMPLATE_FLAT 实测 88),单测里锁住。
16
+ * 目标 ≤190 词(AGENTS_TEMPLATE 实测 187、AGENTS_TEMPLATE_FLAT 实测 89),单测里锁住。
17
17
  * 首行 `<!-- zdiary-template: vN -->` 是版本标记:lint 据此报告「老库的 AGENTS.md 是旧版」,
18
18
  * 只报告不覆盖(模板允许用户改)。
19
19
  */
20
- /** 模板版本:改模板就 +1;lint 用它判断老库是否还在用旧模板(v10:写之前加 zk_walk 一跳) */
21
- export const TEMPLATE_VERSION = 10;
20
+ /** 模板版本:改模板就 +1;lint 用它判断老库是否还在用旧模板(v11:修过时的中文检索口径) */
21
+ export const TEMPLATE_VERSION = 11;
22
22
  /** 首行版本标记(实测 4 词);不许带日期 —— 带日期的写法实测 6 词,白花 2 词 */
23
23
  export const TEMPLATE_MARK = `<!-- zdiary-template: v${TEMPLATE_VERSION} -->`;
24
24
  /** 版本标记的正则(本文件内用;外部只通过 `templateVersionOf` 取数,免得又一个口径) */
@@ -39,6 +39,11 @@ export const TEMPLATE_SENTINELS = {
39
39
  8: { required: ['先 read 核对来源'], forbidden: ['DSH 不会自动加载', '从底部往前丢'] },
40
40
  9: { required: ['先 read 核对来源', '改 MEMORY 前看 zk_context'], forbidden: ['DSH 不会自动加载', '从底部往前丢'] },
41
41
  10: { required: ['先 read 核对来源', '改 MEMORY 前看 zk_context', 'zk_walk'], forbidden: ['DSH 不会自动加载', '从底部往前丢'] },
42
+ // v11:中文查正文已并用子串检索;「中文必打 tags / 只查正文会静默查空」是过时口径
43
+ 11: {
44
+ required: ['先 read 核对来源', '改 MEMORY 前看 zk_context', 'zk_walk', '中文查正文已并用子串检索'],
45
+ forbidden: ['DSH 不会自动加载', '从底部往前丢', '全文索引不切中文', 'FTS 不切中文', '中文查 tags'],
46
+ },
42
47
  };
43
48
  export const AGENTS_TEMPLATE = `${TEMPLATE_MARK}
44
49
 
@@ -52,11 +57,11 @@ notes/{concepts,entities,patterns}/ 原子笔记 · archive/ 废弃(不删)
52
57
  ## 检索词
53
58
 
54
59
  值得检索 → tags 或正文;不值得 → 不写。
55
- 中文必打 tags:全文索引不切中文,只查正文会静默查空、建重复笔记。
60
+ 中文查正文已并用子串检索;tags 用于组织与中文查重。
56
61
 
57
62
  ## 写之前
58
63
 
59
- 1. zk_query / zk_search 查重,zk_walk 一跳(中文查 tags)。
64
+ 1. zk_query / zk_search 查重,zk_walk 一跳(中文查正文或 tags)。
60
65
  2. 一条笔记一件事,标题即结论;文件名用 zk_new 的 name(8–14 字);来源给 type=source、结论给 type=concept(目录跟 type 走,别落 notes/ 根),zk_link 相连。
61
66
  3. 结论过时用 zk_supersede(默认预演,带 reason):不删文件、不改旧结论。
62
67
  4. 改已有笔记前读 WORKFLOW.md:先列清单等确认,再按三分类动手。
@@ -78,7 +83,7 @@ export const AGENTS_TEMPLATE_FLAT = `${TEMPLATE_MARK}
78
83
 
79
84
  ## 写之前
80
85
 
81
- 1. zk_search 查重,zk_walk 一跳;中文必打 tags(FTS 不切中文)。
86
+ 1. zk_search 查重,zk_walk 一跳;中文查正文已并用子串检索。
82
87
  2. 一笔记一件事,标题即结论;文件名 8–14 字。
83
88
  3. 结论过时用 zk_supersede(默认预演,带 reason)。
84
89
 
@@ -109,7 +114,8 @@ export const WORKFLOW_TEMPLATE = `${TEMPLATE_MARK}
109
114
 
110
115
  ## 改 MEMORY.md 之前
111
116
 
112
- 先看 zk_context 的 headroom 与 dropCandidates:余量不够就先退役 / 精简旧条目,别让新结论把最旧的挤掉。
117
+ 先用 zk_memory_write 预演(默认 dry_run):它会按同一份口径挡容量、日期与 [[来源]],不静默截断。
118
+ 再看 zk_context 的 headroom 与 dropCandidates:余量不够就先退役 / 精简旧条目,别让新结论把最旧的挤掉。
113
119
  给 proposed_entry 能预估会不会触发截断;同日条目按位置决胜(sameDateCount),插件不猜谁更常用。
114
120
 
115
121
  ## 动笔前必须出清单