dsh-zdiary-kit 0.8.3 → 0.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 0.8.3
1
+ # dsh-zdiary-kit 0.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),
@@ -19,8 +19,8 @@
19
19
  | `zk_link` | 在两篇笔记间加 `[[…]]` 双链(已存在不重复加;目标不存在会给出候选;链接追加到文末,已有 Links/链接 小节则不重复起标题);meta 文件不作为来源或目标 |
20
20
  | `zk_supersede` | 废弃过时结论:标 `superseded` + 写 `reason` + 搬进 `archive/` + 重写能精确匹配的 `[[旧路径]]` 入链(其它写法列进 `missingLinks`);默认只预演;meta 文件不能废弃 |
21
21
  | `zk_rename` | 改名 / 换目录并修断链:入链(`[[…]]` 与 Markdown 链接,保留 `#锚点` 与 `\|别名`)按实际解析结果改到新路径,根目录 meta 里的 `[[来源]]` 一起改,被搬走那篇自己的相对 Markdown 链接按新位置重算;默认只预演 |
22
- | `zk_context` | 读知识库根目录的 `AGENTS.md` / `USER.md` / `MEMORY.md`(按注入预算截断),并列出已配置的笔记本(名字 / 路径 / 结构 / 当前);宿主支持注入时记忆每轮已自动带进系统提示 |
23
- | `zk_lint` | 体检:解析失败 / 断链 / 孤儿 / 无标签 / 单向链接 / 陈旧 / 重名标题 / 疑似重复标题 / 记忆链接失效 / frontmatter 缺字段 / 标签卫生 / 模板版本,每类最多 50 条;非日记笔记到 150 篇且没有 `INDEX.md` 时提示一句;只报告不改写 |
22
+ | `zk_context` | 读知识库根目录的 `AGENTS.md` / `USER.md` / `MEMORY.md`(按注入预算截断)与契约 `PERSONA.md` / `POLICY.md`(单独成段、不截断),并列出已配置的笔记本(名字 / 路径 / 结构 / 当前);宿主支持注入时这些内容每轮已自动带进系统提示 |
23
+ | `zk_lint` | 体检:解析失败 / 断链 / 孤儿 / 无标签 / 单向链接 / 陈旧 / 重名标题 / 疑似重复标题 / 记忆链接失效 / frontmatter 缺字段 / 标签卫生 / 模板版本 / 契约(缺失·旧版·未填占位符),每类最多 50 条;非日记笔记到 150 篇且没有 `INDEX.md` 时提示一句;只报告不改写 |
24
24
  | `zk_dream` | 晋升材料:窗口新增(机械筛掉 `informal` 与无标签,带正文摘要与入链来源)、已在 MEMORY 的、窗口外积压、daily 未完成项、被引最多(先按「被日记提到几天」排);只报告 |
25
25
  | `zk_stats` | 笔记数 / 标签数 / 断链 / 孤立 / 归档(superseded),以及顶层目录与前 10 个标签的实时分布 |
26
26
  | `zk_use` | 切换**本会话**用的笔记本(只影响这个会话,不改全局默认);不带参数就列出现有的与当前固定的 |
@@ -39,25 +39,41 @@ layered 下每篇笔记都要落在 group 里:`zk_new` 不给 `dir` 就按 `ty
39
39
 
40
40
  **长期记忆**:笔记本根目录放 `AGENTS.md`(工作约定)、`USER.md`(偏好)、`MEMORY.md`(精炼记忆),
41
41
  插件会在每个 step 把它们注入系统提示(预算默认 500 词,设置页「记忆 → 注入预算」可改;
42
- 超了先丢 MEMORY 的尾部,按 `##` 小节 → 顶层列表项 → 空行段落 三级降级切分(`# 记忆` + 要点列表这种最常见的写法也算数),
42
+ 超了先丢 MEMORY 里**日期最旧**的一条(都没写日期才退回从尾部往前丢),
43
+ 按 `##` 小节 → 顶层列表项 → 空行段落 三级降级切分(`# 记忆` + 要点列表这种最常见的写法也算数),
43
44
  丢掉的条目 / 段落留一份目录(标题)—— 需要时用 `zk_read MEMORY.md` 取回;
44
- 条目列表按条丢、从末尾往前,所以新条目若加在底部会先被丢;
45
+ 同日期按文件里靠后的先丢,所以带日期的条目不会因为写在底部就先被删;
45
46
  同时明确告诉你截了多少、谁已经没法再丢)。用到预算 80% 以上时还会回显一行「记忆已用 246/300 词(82%)」
46
47
  (数字已含这行提示本身)—— 先合并或退役旧条目,别等第一次截断。
47
48
  笔记本提示是单独的一段,不占这 500 词预算。
48
49
  DSH 自带的 AGENTS.md 加载只看「项目根 → 当前目录」链,**不会**读笔记本根目录,所以别指望宿主帮你加载 —— 是插件自己读、自己注入。
49
50
  记忆条目的格式约定在 `AGENTS.md` 里:每条写 `结论(YYYY-MM-DD)[[来源路径]]`;退役写成
50
- `- [superseded YYYY-MM-DD] 旧结论 → [[新结论]]`,行留在原处(`zk_lint` 会核对退役行指向的新结论是否还活着,但不会替你删)。
51
+ `- [superseded YYYY-MM-DD] 旧结论 → [[新结论]]`,行留在原处。注入时会**省略退役条目**(并回显省略了几条),
52
+ 但文件本身不动 —— git 与记忆页仍看得到「这里曾经有过什么」。
51
53
  `flat` 结构默认**不写** `AGENTS.md`(从 0.1.0 升级过来的库一个文件都不多);要约定与周提醒就显式
52
54
  `zk-kit init --with-agents`,或在设置页点「写入 AGENTS.md 模板」—— 已存在的文件绝不覆盖。
53
55
  模板首行有 `<!-- zdiary-template: vN -->` 版本标记:老库的 `AGENTS.md` 是旧版时 `zk_lint` 只提示,不自动改。
54
56
 
57
+ **角色契约**:根目录还可以放 `PERSONA.md`(名字 / 身份 / 语气 / 边界)与 `POLICY.md`(读 / 写 / 发布 / 花钱 / 对外发言的
58
+ `auto | ask | forbidden` 与审批入口)。两份与 `MEMORY.md` 同级:人和 agent 直接编辑,`zk_append` / `zk_new` 一律拒写,
59
+ **缺文件 = 未启用**(旧库行为一个词不变)。它们单独成段、永远在记忆段之前注入,**不参与记忆预算的截断**:
60
+ 契约是硬规则,超了只告警(`zk_context` / `doctor` / 记忆页都会点名),不会静默丢掉半份人设。
61
+ 三个预算可以分开调(设置页「记忆」组):记忆 500 · 契约 240 · 场景 80,总 prompt 默认 900(启用契约后按实际载荷检查,超了只告警点名;没有契约的库不多一个词)。
62
+ 写入是 opt-in:`zk-kit init --with-contract` 或设置页「写入契约模板」,已存在的文件绝不覆盖。
63
+ `POLICY.md` 的解析与强制执行属于下一批(M3);本批只存契约、注入、体检、展示 ——
64
+ `publish` / `spend` 这类外部动作由 `bili_*` 等工具自己读同一份契约执行,插件不假装能管住别的插件。
65
+ **边界**:M1 是「一本笔记本一份」契约;多个 agent 共用一个库时先别启用,等 M4 的 per-agent persona ——
66
+ 否则 A 的人格会串到 B。
67
+
55
68
  维护用 `zk_lint`(结构体检 + 记忆链接核对)和 `zk_dream`(晋升候选 / 拒绝原因 / 未完成项):两个工具都**只读**,
56
69
  写 `MEMORY.md` / `DREAMS.md` 由 agent 按 `AGENTS.md` 自己决定 —— 机械活留在插件,语义判断留在可审计的地方。
57
70
  `zk_dream` 会先读一遍 `MEMORY.md`:已经晋升过的(`[[链接]]` 命中,或条目里直接写了标题)移出候选、单列「已在 MEMORY」,
58
- 不会每周原样重复;窗口外仍未晋升的进 `backlog`,漏做一次不会永久掉队;不传 `days` 时窗口 = 距 `DREAMS.md`
71
+ 不会每周原样重复(退役行里的旧标题不算已晋升,但退役行里的 `→ [[新结论]]` 仍算);
72
+ 窗口外仍未晋升的进 `backlog`,漏做一次不会永久掉队;不传 `days` 时窗口 = 距 `DREAMS.md`
59
73
  「上次做梦」的天数(没有就 7 天)。被引排行先按「被日记提到几天」(`daysMentioned`)排,入链数只作并列次序 ——
60
74
  日记是这个插件里唯一按时间记录真实工作的层,空信号只说明日记里没写过,不等于没被用过。
75
+ `zk_dream` 还会回一行**记忆余量**(内容词 + 提示 = 总量,余量按总量算,可以为负)和「可考虑退役」的条目
76
+ (来源已归档 / 不存在、或超过 90 天没复核)—— 只给材料,不写任何文件。
61
77
  `zk_lint` 会核对 `MEMORY.md` / `USER.md` 里的 `[[来源路径]]` 是否还指向活笔记 ——
62
78
  `zk_supersede` 只重写笔记之间的入链,meta 文件不在图里,链接不会跟着搬,`--broken-links` 也看不见。
63
79
  改名同理:`zk_rename` 会把 `zk graph` 里的入链和根目录 meta 的 `[[来源]]` 一起改到新路径,被搬走那篇自己的相对 Markdown 链接也按新位置重算 —— 手工 `mv` 会一次断掉这三处。
@@ -160,6 +176,7 @@ dsh plugin --profile web add "link:/path/to/dsh-zdiary-kit"
160
176
  - 顶层 `notebook` 与 `structure` 是**派生的**(`notebooks[active]` 解析后的绝对路径 / 该条目的结构),只在内存里、不落盘也不可写;可写的是条目里的 `notebooks[名].structure`(`zk-kit config set structure=…` 改的就是当前笔记本那一条)—— 磁盘上笔记本只有一个真相,就是 `notebooks` + `active`。
161
177
  老配置里那个单独的 `notebook` 字段(和全局 `structure`)读进来会**一次性**迁进 `notebooks.default`,之后不再互相覆盖。
162
178
  - **共享的是全局项**:笔记 / 日记子目录、`daily` group、归档目录、注入预算 —— 这些不按笔记本分开。
179
+ 改子目录 / group 名后要跑 `zk-kit groups --fix` 让 `.zk/config.toml` 跟上;归档目录非空时不允许改(不自动迁移文件)。
163
180
 
164
181
  ```bash
165
182
  zk-kit notebooks # 列出所有笔记本(* 是当前那个;[flat/layered] 是各自的结构)
@@ -207,6 +224,26 @@ filename = '{{format-date now "%Y-%m-%d"}}'
207
224
  template = "daily.md"
208
225
  ```
209
226
 
227
+ ### 改了目录 / group 之后
228
+
229
+ 插件**不会自动重写**已有的 `[group.*]`:你改过 `notesDir` / `dailyDir` / `dailyGroup` 后,
230
+ `zk-kit init` 只追加缺失的 group,不会把旧 paths 改掉(也不会有两个 group 抢同一路径)。
231
+ 差异由 `doctor` / `groups` / 设置页报告,确认后用显式修复:
232
+
233
+ ```bash
234
+ zk-kit groups # 默认 dry-run:逐组打印期望 / 实际
235
+ zk-kit groups --fix # 只改 dsh-zdiary-kit 自己写的 group:paths 行或旧组头改名
236
+ ```
237
+
238
+ `--fix` 写前备份 `.zk/config.toml.bak`,只改 paths 与组头;自定义的 `template` / `extra` / 注释 / 别的 group 一字不动。
239
+ 两个 group 要落到**同一条路径**时它拒绝写(整轮不改,并在 `groups` / `doctor` / 设置页里报出来)——
240
+ 那样 zk 命中哪个模板就只剩实现细节了。父子目录不算冲突:`dailyDir=notes` 与 `notes/concepts` 可以共存;
241
+ 没写 `paths` 的 group 按同名目录算(zk 的语义),同样算抢同一路径。
242
+ `dailyGroup` 改名且 `dailyDir` 没变时,`--fix` 直接把旧组头改成新名字(连同 `.note` / `.extra` 子表),不追加第二个日记组。
243
+
244
+ `archiveDir` 是另一条硬规则:**旧归档目录非空时拒绝改**。插件不迁移归档文件,改了会让废弃笔记重新进入检索、
245
+ 统计也会把它们算成活跃 —— 先手动迁移,或保持原值。空目录 / 不存在的目录可以改。
246
+
210
247
  ### 分层结构(可选)
211
248
 
212
249
  给某个笔记本选 `layered`:设置页笔记本那一行的结构下拉,或切到它后 `zk-kit config set structure=layered`
@@ -266,6 +303,10 @@ template = "daily.md"
266
303
  ```bash
267
304
  zk-kit init # 建库 / 补齐目录、模板、group、AGENTS.md(幂等)
268
305
  zk-kit init --with-agents # flat 库也写一份精简版 AGENTS.md(已存在不覆盖)
306
+ zk-kit init --with-contract # 写 PERSONA.md / POLICY.md 契约模板(缺了才写,已存在不覆盖)
307
+ zk-kit contract # 契约状态:用量 / 预算 / 体检(只读)
308
+ zk-kit groups # 对照配置与 .zk/config.toml 的 group(默认 dry-run)
309
+ zk-kit groups --fix # 只改插件建的 group 的 paths / 组头(写前备份 .zk/config.toml.bak)
269
310
  zk-kit new --title "示例笔记" --body "正文" --tags demo --type concept
270
311
  zk-kit search --tags demo --limit 5
271
312
  zk-kit daily --entry "今天把 zk-kit 跑了一遍"
@@ -330,9 +371,10 @@ zk-kit doctor # 自检:zk / 笔记本 / 模板 / group
330
371
  | 设置页 503 | 宿主没有 `connection` 服务,信任栅栏按 fail-closed 拒绝(工具不受影响) |
331
372
  | 安装 zk 报「解包失败」 | 系统没有 `tar`;手动解包后把 `zk` 放进 `~/.dsh/zdiary/bin` |
332
373
  | 搜索结果不全 | 索引落后:点「重建索引」(`zk index`),或确认文件没被 `.zk/config.toml` 的 `exclude` 排除 |
333
- | 自检报「✗ 长期记忆:N/预算 词」 | AGENTS + USER + MEMORY 写太长:先压缩,或在设置页调高「注入预算」(超预算时注入会先丢 MEMORY 尾部,条目 / 段落按条从末尾往前丢) |
374
+ | 自检报「✗ 长期记忆:N/预算 词」 | AGENTS + USER + MEMORY 写太长:先压缩,或在设置页调高「注入预算」(超预算时注入先丢 MEMORY 里日期最旧的条目,一条日期都没有才退回从末尾往前丢) |
334
375
  | 体检报「记忆链接:N 条失效」 | `MEMORY.md` / `USER.md` 里的 `[[来源]]` 指向的笔记已归档或删除:改成 `archive/` 下的新路径,或改指活笔记;显式写 `archive/` 的链接不算失效 |
335
- | 体检报「N 个条目没写日期 / 已退役」 | 按 `AGENTS.md` 的格式补 `结论(YYYY-MM-DD)[[来源路径]]`;退役行写 `- [superseded …] 旧结论 → [[新结论]]`,行留着不删。只报告,注入仍按原文 |
376
+ | 体检报「N 个条目没写日期 / 已退役」 | 按 `AGENTS.md` 的格式补 `结论(YYYY-MM-DD)[[来源路径]]`;退役行写 `- [superseded …] 旧结论 → [[新结论]]`,行留着不删(注入时会省略退役条目,文件本身不动)。只报告 |
377
+ | 体检报「N 条超过 90 天未复核」 | 条目的日期太旧:确认结论还成立就改日期,否则按退役格式写一行 `- [superseded …]`。`zk_dream` 的「可考虑退役」会给同一批材料 |
336
378
  | 体检报「AGENTS.md 是旧版 / 无版本标记」 | 模板升级过,老库不会自动覆盖(可能有你自己的改动):`zk_lint` 的输出里会直接附上新版模板全文,按需合并到自己的 `AGENTS.md`;不合并也能用,只是少新加的约定 |
337
379
  | 体检报「疑似重复标题」 | 同目录里有两篇标题只差一两个字(二元组相似度 ≥ 0.6,或短标题被长标题包含)。只报告:确认是同一结论就用 `zk_supersede` 合并,不是就留着 |
338
380
  | 体检提示「笔记已到 150 篇(不含日记)」 | 检索开始变糊的拐点,但插件不生成 `INDEX.md`(静态索引会过期)。用 `zk_stats` 看目录 / 标签分布决定先读哪里;真要总索引就自己写,提示会消失 |
package/dist/cli.js CHANGED
@@ -6,17 +6,20 @@ import fs from 'node:fs';
6
6
  import path from 'node:path';
7
7
  import { config, writeConfig, selectNotebook, isNotebookName, CONFIG_KEYS } from './config/store.js';
8
8
  import { CFG_FILE } from './config/paths.js';
9
- import { NOTE_KINDS, ensureNotebook, newNoteDir, structureStatus } from './lib/notebook.js';
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
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';
13
- import { formatLintExtras, formatMemoryLinks, lintNotebook } from './lib/lint.js';
14
- import { dreamNotebook } from './lib/dream.js';
13
+ import { formatLintExtras, formatMemoryLinks, lintNotebook, contractStatus } from './lib/lint.js';
14
+ import { dreamNotebook, STALE_DAYS } from './lib/dream.js';
15
15
  const HELP = `zk-kit —— dsh-zdiary-kit 的命令行
16
16
 
17
17
  zk-kit doctor 自检:zk / 笔记本 / 模板 / group / 索引
18
18
  zk-kit install [版本] 安装内置 zk(默认取配置里的版本)
19
- zk-kit init [--with-agents] 建好(或补齐)笔记本;flat 下加 --with-agents 才写 AGENTS.md 模板
19
+ zk-kit init [--with-agents] [--with-contract]
20
+ 建好(或补齐)笔记本;flat 下加 --with-agents 才写 AGENTS.md 模板;--with-contract 写 PERSONA.md / POLICY.md 契约模板(缺了才写)
21
+ zk-kit groups [--fix] [--dry-run] 对照配置与 .zk/config.toml 的 group(默认 dry-run;--fix 只改插件建的 paths,写前备份)
22
+ zk-kit contract 契约状态:PERSONA.md / POLICY.md 的用量 / 预算 / 体检(只读)
20
23
  zk-kit new --title T [--name 文件名] [--summary 摘要] [--body B] [--tags a,b] [--dir notes] [--type source|concept|entity|pattern]
21
24
  zk-kit search [词] [--tags a,b] [--since 日期] [--limit 5] [--json]
22
25
  zk-kit read <路径> | --query 词 [--max-chars n] [--json]
@@ -183,6 +186,22 @@ function dreamReport(r) {
183
186
  const lines = [
184
187
  `做梦:近 ${r.windowDays} 天(自 ${r.since})— 窗口 ${r.counts.window} 篇(日记 ${r.counts.daily})· 候选 ${r.counts.candidates} · 拒绝 ${r.counts.rejected} · 未完成 ${r.counts.looseEnds} · 已晋升 ${r.counts.promoted} · 积压 ${r.counts.backlog}`,
185
188
  ];
189
+ // 余量按记忆侧总词算:只报内容词等于说「还有 10 词」,而框与提示早就把它吃完了;
190
+ // 契约单独注入、不占记忆预算,所以先从 totalWords 里扣掉,别把它叫成「提示」。
191
+ const memoryTotal = r.memory.totalWords - r.memory.contractWords;
192
+ const promptWords = Math.max(0, memoryTotal - r.memory.words);
193
+ lines.push(`记忆:内容 ${r.memory.words}/${r.memory.budget} 词 + 提示 ${promptWords} = ${memoryTotal} 词(余 ${r.memory.headroom})` +
194
+ (r.memory.contractWords > 0 ? ` · 契约 ${r.memory.contractWords} 词(单独注入,不计入记忆预算)` : ''));
195
+ if (r.retireCandidates.length) {
196
+ lines.push('可考虑退役:');
197
+ for (const c of r.retireCandidates.slice(0, 10)) {
198
+ const when = c.date ? `${c.date}(${c.age} 天)` : '无日期';
199
+ const why = c.reason === 'stale'
200
+ ? `超过 ${STALE_DAYS} 天未复核`
201
+ : c.reason === 'source-superseded' ? '来源已归档' : '来源不存在';
202
+ lines.push(` · ${c.entry} — ${when} · ${why}`);
203
+ }
204
+ }
186
205
  if (r.newNotes.length) {
187
206
  lines.push('晋升候选:');
188
207
  for (const [i, n] of r.newNotes.slice(0, 10).entries()) {
@@ -236,6 +255,70 @@ function dreamReport(r) {
236
255
  lines.push('(只报告:MEMORY.md / DREAMS.md 由你按 AGENTS.md 写)');
237
256
  return lines.join('\n');
238
257
  }
258
+ /** group 路径重叠:config = 配置本身冲突(⚠️),file = config.toml 里已经撞了(✗) */
259
+ function overlapLines(st) {
260
+ return groupOverlapNotes(st).map((note) => `${note.level === 'file' ? '✗' : '⚠️'} ${note.text}`);
261
+ }
262
+ function groupsReport(cfg, st, fixed) {
263
+ if (fixed) {
264
+ if (!fixed.changed) {
265
+ // 有 skip 就不是「没需要修的」—— 是「想修但修不了」,得说清哪一条没改
266
+ const skipped = fixed.updates.filter((update) => update.action === 'skip');
267
+ const lines = [`group 配置:${fixed.notebook} —— ${skipped.length ? '没有写文件' : '没有需要修的(未写文件)'}`];
268
+ for (const update of skipped)
269
+ lines.push(` · ${update.name}:未改 —— ${update.reason ?? ''}`);
270
+ for (const warning of fixed.warnings)
271
+ lines.push('⚠️ ' + warning);
272
+ return lines.join('\n');
273
+ }
274
+ const lines = [`已修复 group 配置:${fixed.notebook}(备份 ${fixed.backup})`];
275
+ for (const update of fixed.updates) {
276
+ if (update.action === 'paths') {
277
+ lines.push(` ✓ ${update.name}:${update.actualPaths?.join('、') ?? '解析不了'} → ${update.expectedPaths.join('、')}`);
278
+ }
279
+ else if (update.action === 'rename') {
280
+ lines.push(` ✓ ${update.from} → ${update.name}(只改组头,路径与模板不变)`);
281
+ }
282
+ else if (update.action === 'append') {
283
+ lines.push(` + ${update.name}:追加 ${update.expectedPaths.join('、')}`);
284
+ }
285
+ else {
286
+ lines.push(` · ${update.name}:未改 —— ${update.reason ?? ''}`);
287
+ }
288
+ }
289
+ lines.push(...overlapLines(st));
290
+ for (const warning of fixed.warnings)
291
+ lines.push('⚠️ ' + warning);
292
+ lines.push('(只改插件建的 group 的 paths / 组头;template / extra / 自定义 group 一字未动)');
293
+ return lines.join('\n');
294
+ }
295
+ const lines = [`group 配置:${cfg.notebook}${st.groupsOk ? '(与配置一致)' : ''}`];
296
+ if (!fs.existsSync(path.join(cfg.notebook, '.zk', 'config.toml'))) {
297
+ lines.push('✗ 还没有 .zk/config.toml —— 先跑 zk-kit init');
298
+ return lines.join('\n');
299
+ }
300
+ for (const group of st.groups) {
301
+ if (!group.present) {
302
+ lines.push(group.conflict
303
+ ? `✗ ${group.name}:缺(路径 ${group.expectedPaths.join('、')} 已被 group "${group.conflict}" 占用)`
304
+ : `✗ ${group.name}:缺(期望 ${group.expectedPaths.join('、')})`);
305
+ }
306
+ else if (group.duplicate) {
307
+ lines.push(`⚠️ ${group.name}:重复出现,解析不了`);
308
+ }
309
+ else if (!group.pathsOk) {
310
+ lines.push(`⚠️ ${group.name}:期望 ${group.expectedPaths.join('、')},实际 ${group.actualPaths?.join('、') ?? '解析不了'}` +
311
+ (group.actualPaths === null ? '(可能是多行数组,手动编辑 .zk/config.toml)' : ''));
312
+ }
313
+ else {
314
+ const template = group.templateOk ? '' : ` · template=${group.actualTemplate ?? '(无)'}(配置期望 ${group.expectedTemplate})`;
315
+ lines.push(`✓ ${group.name}:${group.actualPaths?.join('、')}${template}`);
316
+ }
317
+ }
318
+ lines.push(...overlapLines(st));
319
+ lines.push('(dry-run:不改文件;--fix 只改 dsh-zdiary-kit 建的 group 的 paths,写前备份 .zk/config.toml.bak)');
320
+ return lines.join('\n');
321
+ }
239
322
  async function doctor() {
240
323
  const cfg = config();
241
324
  const zk = await resolveZk(cfg);
@@ -245,15 +328,26 @@ async function doctor() {
245
328
  rows.push(`${exists ? '✓' : '✗'} 笔记本:${cfg.notebook}${exists ? '' : '(不是 zk 笔记本 —— 跑 zk-kit init)'}`);
246
329
  const template = path.join(cfg.notebook, '.zk', 'templates', 'daily.md');
247
330
  rows.push(`${fs.existsSync(template) ? '✓' : '✗'} 日记模板:${template}`);
248
- let group = false;
249
- try {
250
- group = new RegExp(`^\\[group\\."?${cfg.dailyGroup}"?\\]`, 'm').test(fs.readFileSync(path.join(cfg.notebook, '.zk', 'config.toml'), 'utf8'));
251
- }
252
- catch {
253
- group = false;
254
- }
255
- rows.push(`${group ? '✓' : '✗'} 日记 group:${cfg.dailyGroup} → ${cfg.dailyDir}/`);
256
331
  const st = structureStatus(cfg);
332
+ for (const group of st.groups) {
333
+ if (!group.present) {
334
+ rows.push(group.conflict
335
+ ? `✗ group ${group.name}:缺(期望 ${group.expectedPaths.join('、')},已被 group "${group.conflict}" 占用;跑 zk-kit groups --fix)`
336
+ : `✗ group ${group.name}:缺(期望 ${group.expectedPaths.join('、')};跑 zk-kit groups --fix)`);
337
+ }
338
+ else if (group.duplicate) {
339
+ rows.push(`⚠️ group ${group.name}:重复出现,解析不了 —— 手动检查 .zk/config.toml`);
340
+ }
341
+ else if (!group.pathsOk) {
342
+ rows.push(`⚠️ group ${group.name}:期望 ${group.expectedPaths.join('、')},实际 ${group.actualPaths?.join('、') ?? '解析不了'}` +
343
+ (group.actualPaths === null ? '(可能是多行数组 —— 手动编辑 .zk/config.toml)' : '(跑 zk-kit groups --fix)'));
344
+ }
345
+ else {
346
+ const templateNote = group.templateOk ? '' : ` · template=${group.actualTemplate ?? '(无)'}`;
347
+ rows.push(`✓ group ${group.name}:${group.actualPaths?.join('、')}${templateNote}`);
348
+ }
349
+ }
350
+ rows.push(...overlapLines(st));
257
351
  const structureOk = st.ready && (!st.agents.required || st.agents.present);
258
352
  const drift = st.mode === 'flat' && st.extra.length
259
353
  ? ` · ⚠️ 盘上有分层目录 ${st.extra.join('、')}:新建笔记会落在 ${cfg.notesDir}/ 根`
@@ -267,7 +361,20 @@ async function doctor() {
267
361
  rows.push(present.length === 0
268
362
  ? '✓ 记忆:暂未启用(根目录没有 AGENTS.md / USER.md / MEMORY.md)'
269
363
  : `${payload.words <= payload.budget ? '✓' : '✗'} 记忆:${payload.words}/${payload.budget} 词(${formatFileShares(payload.files, payload.tocWords)})` +
270
- (payload.truncatedWords > 0 ? `,已截断 ${payload.truncatedWords} 词` : ''));
364
+ (payload.truncatedWords > 0 ? `,已截断 ${payload.truncatedWords} 词` : '') +
365
+ (payload.retiredWords > 0 ? `,退役省略 ${payload.retiredWords} 词` : ''));
366
+ const c = payload.contract;
367
+ rows.push(c.present
368
+ ? `${c.overBudget ? '⚠️' : '✓'} 契约:正文(含标题)${c.contentWords}/${c.budget} 词(${c.files.filter((f) => f.present).map((f) => `${f.name} ${f.words} 词`).join(' · ')})` +
369
+ (c.overBudget ? `,超 ${c.overWords} 词(契约不截断)` : '')
370
+ : '· 契约:未启用(根目录没有 PERSONA.md / POLICY.md —— 跑 zk-kit init --with-contract)');
371
+ // 两份都没有 = 未启用,不值得再用一条 ⚠️ 重复上面那行;只启用一半 / 旧版 / 占位符才体检
372
+ if (c.present) {
373
+ const contractIssues = contractStatus(cfg).items;
374
+ if (contractIssues.length > 0) {
375
+ rows.push(`⚠️ 契约体检:${contractIssues.map((i) => `${i.file} ${i.detail}`).join(';')}`);
376
+ }
377
+ }
271
378
  if (exists) {
272
379
  // 记忆在跑、但没有工作约定:默认安装里这是常态(flat 不自动写 AGENTS.md),
273
380
  // 代价是「每条结论附来源 / 中文打 tags / 每周整理」四条约定与周提醒全都不生效。
@@ -296,8 +403,9 @@ async function doctor() {
296
403
  }
297
404
  }
298
405
  console.log(rows.join('\n'));
299
- // ⚠️ 是内容问题(笔记写坏了),不是装坏了 —— 别让它把 doctor 的退出码翻掉
300
- return rows.every((r) => r.startsWith('✓') || r.startsWith('⚠️'));
406
+ // ⚠️ 是内容问题(笔记写坏了),不是装坏了 —— 别让它把 doctor 的退出码翻掉;
407
+ // · 是「未启用 / 未配置」(如契约文件缺失):同样不算装坏
408
+ return rows.every((r) => r.startsWith('✓') || r.startsWith('⚠️') || r.startsWith('·'));
301
409
  }
302
410
  async function main() {
303
411
  const argv = process.argv.slice(2);
@@ -323,10 +431,50 @@ async function main() {
323
431
  }
324
432
  case 'init': {
325
433
  const withAgents = flags['with-agents'] === true || flags['with-agents'] === 'true';
326
- const r = await ensureNotebook(cfg, undefined, { withAgents });
434
+ const withContract = flags['with-contract'] === true || flags['with-contract'] === 'true';
435
+ const r = await ensureNotebook(cfg, undefined, { withAgents, withContract });
327
436
  print(json ? r : `笔记本 ${r.notebook}(结构 ${cfg.structure})\n` +
328
437
  `初始化:${r.initialized ? '是' : '已是笔记本'} · 目录:${r.dirsCreated.length ? '新建 ' + r.dirsCreated.join('、') : '已齐全'}\n` +
329
- `模板:${r.templatesWritten.length ? r.templatesWritten.join(' / ') : '已存在'} · group:${r.groupsAdded.length ? r.groupsAdded.join(' / ') : '已存在'} · AGENTS.md:${r.agentsWritten ? '已写入' : (cfg.structure === 'layered' || withAgents ? '已存在' : '未写(flat 要 --with-agents)')} · WORKFLOW.md:${r.workflowWritten ? '已写入' : (cfg.structure === 'layered' ? '已存在' : 'flat 不写')}`, json);
438
+ `模板:${r.templatesWritten.length ? r.templatesWritten.join(' / ') : '已存在'} · group:${r.groupsAdded.length ? r.groupsAdded.join(' / ') : '已存在'} · AGENTS.md:${r.agentsWritten ? '已写入' : (cfg.structure === 'layered' || withAgents ? '已存在' : '未写(flat 要 --with-agents)')} · WORKFLOW.md:${r.workflowWritten ? '已写入' : (cfg.structure === 'layered' ? '已存在' : 'flat 不写')} · 契约:${withContract ? (r.personaWritten ? '已写 PERSONA.md' : 'PERSONA.md 已存在') + ' / ' + (r.policyWritten ? '已写 POLICY.md' : 'POLICY.md 已存在') : '未写(要 --with-contract)'}` +
439
+ (r.groupWarnings.length ? `\n⚠️ ${r.groupWarnings.join('\n⚠️ ')}` : ''), json);
440
+ return;
441
+ }
442
+ case 'contract': {
443
+ const payload = buildMemoryPayload(cfg);
444
+ const c = payload.contract;
445
+ const issues = contractStatus(cfg);
446
+ if (!json) {
447
+ if (!c.present) {
448
+ print(`契约:未启用(根目录没有 PERSONA.md / POLICY.md)\n写入模板:zk-kit init --with-contract;写入后缺文件 = 未启用、不算错,占位符 {{...}} 由人填。`, false);
449
+ }
450
+ else {
451
+ const files = c.files.filter((f) => f.present).map((f) => `${f.name} ${f.words} 词`).join(' · ');
452
+ const lines = [
453
+ `契约:正文(含标题)${c.contentWords}/${c.budget} 词(${files})` +
454
+ (c.overBudget ? ` · 超 ${c.overWords} 词(契约不截断)` : ''),
455
+ `注入:${c.words} 词${c.noticeWords > 0 ? `(正文 ${c.contentWords} + 提示 ${c.noticeWords})` : ''} · 记忆段之前、永远注入、不参与截断`,
456
+ `总量:正文 契约 ${c.contentWords} + 记忆 ${payload.words} = ${c.contentWords + payload.words} 词;模型实际收到 ${payload.totalWords} 词(总 prompt 预算 ${cfg.totalPromptBudgetWords},超了只告警)`,
457
+ ];
458
+ for (const i of issues.items)
459
+ lines.push(`⚠️ ${i.file} ${i.detail}`);
460
+ print(lines.join('\n'), false);
461
+ }
462
+ }
463
+ else {
464
+ print({ contract: c, issues }, true);
465
+ }
466
+ return;
467
+ }
468
+ case 'groups': {
469
+ const fix = flags.fix === true || flags.fix === 'true';
470
+ const dryRun = flags['dry-run'] === true || flags['dry-run'] === 'true';
471
+ if (fix && !dryRun) {
472
+ const result = fixGroupConfig(cfg);
473
+ print(json ? { ...structureStatus(cfg), fix: result } : groupsReport(cfg, structureStatus(cfg), result), json);
474
+ return;
475
+ }
476
+ const st = structureStatus(cfg);
477
+ print(json ? { ...st, dryRun: true } : groupsReport(cfg, st, null), json);
330
478
  return;
331
479
  }
332
480
  case 'new': {
@@ -12,6 +12,8 @@
12
12
  * 老配置只有 `notebook`(或 structure 是全局键):读进来一次性迁进 `notebooks.default`,
13
13
  * 之后就不再有双向合并 —— notebooks 存在时,散落的 `notebook` 顶层键只当没看见。
14
14
  */
15
+ import fs from 'node:fs';
16
+ import path from 'node:path';
15
17
  import { CFG_FILE, CFG_LOCK, defaultNotebook, expandHome, processWorkspace, resolveInWorkspace } from './paths.js';
16
18
  import { fileStamp } from '../lib/file-stamp.js';
17
19
  import { withFileLockSync } from '../lib/lock.js';
@@ -40,6 +42,9 @@ export const DEFAULTS = {
40
42
  defaultTags: [],
41
43
  maxReadChars: 20_000,
42
44
  memoryBudgetWords: 500,
45
+ contractBudgetWords: 240,
46
+ sceneBudgetWords: 80,
47
+ totalPromptBudgetWords: 900,
43
48
  archiveDir: 'archive',
44
49
  zkVersion: '0.15.7',
45
50
  zkPath: '',
@@ -135,6 +140,9 @@ export function normalizeConfig(raw, workspace = processWorkspace()) {
135
140
  defaultTags: tags(src.defaultTags),
136
141
  maxReadChars: clamp(Number(src.maxReadChars), 1000, 200_000, DEFAULTS.maxReadChars),
137
142
  memoryBudgetWords: clamp(Number(src.memoryBudgetWords), 50, 2000, DEFAULTS.memoryBudgetWords),
143
+ contractBudgetWords: clamp(Number(src.contractBudgetWords), 50, 800, DEFAULTS.contractBudgetWords),
144
+ sceneBudgetWords: clamp(Number(src.sceneBudgetWords), 20, 400, DEFAULTS.sceneBudgetWords),
145
+ totalPromptBudgetWords: clamp(Number(src.totalPromptBudgetWords), 200, 5000, DEFAULTS.totalPromptBudgetWords),
138
146
  archiveDir: relativeDir(src.archiveDir, DEFAULTS.archiveDir),
139
147
  zkVersion: /^\d+\.\d+\.\d+$/.test(String(src.zkVersion ?? '').trim().replace(/^v/i, ''))
140
148
  ? String(src.zkVersion).trim().replace(/^v/i, '')
@@ -245,6 +253,30 @@ export function writeConfig(patch, workspace = processWorkspace(), opts = {}) {
245
253
  notebooks[active] = { ...entry, structure: structureOf(patch.structure, 'flat') };
246
254
  }
247
255
  const next = normalizeConfig({ ...merged, notebooks, active }, workspace);
256
+ // archiveDir 是全局项:旧归档目录非空时,任何一本已配置笔记本都不能直接改,
257
+ // 否则切到那本后旧归档不再被排除,废弃笔记会重新进入检索与统计。
258
+ if (next.archiveDir !== current.archiveDir) {
259
+ const checked = new Set();
260
+ for (const info of notebookInfos(next, workspace)) {
261
+ if (checked.has(info.path))
262
+ continue;
263
+ checked.add(info.path);
264
+ const oldAbs = path.join(info.path, current.archiveDir);
265
+ let entries;
266
+ try {
267
+ entries = fs.readdirSync(oldAbs);
268
+ }
269
+ catch (err) {
270
+ // 只有目录不存在才放行;没权限 / 路径类型异常都失败关闭,不能猜它是空的。
271
+ if (err.code === 'ENOENT')
272
+ continue;
273
+ throw err;
274
+ }
275
+ if (entries.length > 0) {
276
+ throw new ArchiveDirChangeError(current.archiveDir, next.archiveDir, oldAbs, entries.length);
277
+ }
278
+ }
279
+ }
248
280
  writeJson(CFG_FILE, toDisk(next));
249
281
  configCache = null;
250
282
  return next;
@@ -261,6 +293,17 @@ export class ConfigConflictError extends Error {
261
293
  this.name = 'ConfigConflictError';
262
294
  }
263
295
  }
296
+ /**
297
+ * archiveDir 从「空目录 / 不存在」改成别的值时被拒。
298
+ * 不是技术限制,是不让「改一个字符串」静默把旧归档放回检索:插件不迁移文件。
299
+ */
300
+ export class ArchiveDirChangeError extends Error {
301
+ constructor(oldDir, newDir, absPath, count) {
302
+ super(`archiveDir 从 "${oldDir}" 改成 "${newDir}" 被拒绝:旧归档目录 ${absPath} 里还有 ${count} 项。\n` +
303
+ '旧归档不会自动迁移,改完会让废弃笔记重新进入检索 —— 先手动迁移,或保持原值。');
304
+ this.name = 'ArchiveDirChangeError';
305
+ }
306
+ }
264
307
  /** 锁内用的干净读取:不吃 configCache,合并基线必须是磁盘上的现状 */
265
308
  function readConfigFresh(workspace) {
266
309
  return normalizeConfig(readJson(CFG_FILE, {}), workspace);
@@ -18,6 +18,9 @@ import { config } from '../../config/store.js';
18
18
  import { absPathOf, allNotes, graphEdges, 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
+ import { RETIRED_ENTRY_RE } from '../../lib/memory-format.js';
22
+ import { parseFrontmatter } from '../../lib/frontmatter.js';
23
+ import { stripContractMarker } from '../../lib/persona-template.js';
21
24
  import { esc, layout, renderMarkdown } from './html.js';
22
25
  const BASE = ROUTE_BASE;
23
26
  const VIEW = `${BASE}/view`;
@@ -214,12 +217,47 @@ async function handleSearch(res, cfg, q) {
214
217
  ].join('\n');
215
218
  sendHtml(res, 200, shell(cfg, `搜索 ${q}`, body));
216
219
  }
217
- /** 记忆页固定的四份文件:只从这个常量取名字,不接受路径参数(meta 仍然不能按路径打开) */
218
- const MEMORY_PAGE_FILES = ['AGENTS.md', 'USER.md', 'MEMORY.md', 'DREAMS.md'];
220
+ /** MEMORY.md 渲染:退役条目整条(含缩进续行)加删除线与徽标,其余照常渲染 */
221
+ function renderMemoryBody(body, linkFor) {
222
+ const lines = String(body).split('\n');
223
+ const out = [];
224
+ let plain = [];
225
+ const flush = () => {
226
+ if (plain.length > 0) {
227
+ out.push(renderMarkdown(plain.join('\n'), { linkFor, skipFirstH1: true }));
228
+ plain = [];
229
+ }
230
+ };
231
+ let i = 0;
232
+ while (i < lines.length) {
233
+ const line = lines[i] ?? '';
234
+ if (RETIRED_ENTRY_RE.test(line)) {
235
+ flush();
236
+ const retired = [];
237
+ while (i < lines.length) {
238
+ const l = lines[i] ?? '';
239
+ if (RETIRED_ENTRY_RE.test(l) || (retired.length > 0 && /^\s+\S/.test(l))) {
240
+ retired.push(l);
241
+ i += 1;
242
+ continue;
243
+ }
244
+ break;
245
+ }
246
+ out.push(`<div class="retired"><s>${retired.map((l) => esc(l)).join('<br>')}</s>` +
247
+ '<span class="badge">retired</span></div>');
248
+ continue;
249
+ }
250
+ plain.push(line);
251
+ i += 1;
252
+ }
253
+ flush();
254
+ return out.join('\n');
255
+ }
219
256
  /**
220
- * 记忆页(P1-5):人的周审需要一个入口 —— 当前记忆、预算、哪些被截断,都在这一页。
257
+ * 记忆页(P1-5 → D9):人的周审入口 —— 契约 / 用户 / 记忆 / 周审 / 场景五段 + 载荷预览。
221
258
  * 不走 `loadNote`:根目录 meta 被 `loadAll` 排除、也被 `loadNote` 明确拒绝;
222
259
  * 这里按常量直接读盘,再复用渲染层的转义与双链白名单。
260
+ * 载荷预览只转义展示(与 zk_context 同源),不提供编辑 —— 写仍然只走 zk_* / 编辑器。
223
261
  */
224
262
  async function handleMemory(res, cfg) {
225
263
  let all = [];
@@ -228,31 +266,82 @@ async function handleMemory(res, cfg) {
228
266
  }
229
267
  catch { /* 索引挂了也能读记忆,双链退化成纯文字 */ }
230
268
  const linkFor = linkResolver(all);
231
- const payload = buildMemoryPayload(cfg);
232
- const shares = formatFileShares(payload.files, payload.tocWords);
233
- const usage = `记忆 ${payload.words}/${payload.budget} 词(${shares || '三份都空'})` +
234
- (payload.truncatedWords > 0 ? ` · 已截断 ${payload.truncatedWords} 词` : '');
235
- const sections = MEMORY_PAGE_FILES.map((name) => {
236
- let body = '';
269
+ const read = (name) => {
237
270
  try {
238
- body = fs.readFileSync(path.join(cfg.notebook, name), 'utf8');
271
+ return fs.readFileSync(path.join(cfg.notebook, name), 'utf8');
239
272
  }
240
273
  catch {
241
- body = '';
274
+ return '';
242
275
  }
276
+ };
277
+ const fileArticle = (name, note) => {
278
+ const body = read(name);
279
+ return (note ? `<p class="meta">${note}</p>` : '') + (body.trim()
280
+ ? `<article>${renderMarkdown(body, { linkFor, skipFirstH1: true })}</article>`
281
+ : '<p class="meta">还没写。</p>');
282
+ };
283
+ const payload = buildMemoryPayload(cfg);
284
+ const shares = formatFileShares(payload.files, payload.tocWords);
285
+ const usage = `记忆 ${payload.words}/${payload.budget} 词(${shares || '三份都空'})` +
286
+ (payload.truncatedWords > 0 ? ` · 已截断 ${payload.truncatedWords} 词` : '') +
287
+ (payload.retiredWords > 0 ? ` · 退役省略 ${payload.retiredWords} 词` : '');
288
+ // 契约段:超预算只告警;forbidden 行的警示色等 M3 的 policy 解析
289
+ const c = payload.contract;
290
+ const contractSummary = c.present
291
+ ? c.files.filter((f) => f.present).map((f) => `${f.name} ${f.words} 词`).join(' · ') +
292
+ ` · 正文(含标题)${c.contentWords}/${c.budget} 词` +
293
+ (c.overBudget ? ` · ⚠️ 超 ${c.overWords} 词(契约不截断,请缩减或调 contractBudgetWords)` : '')
294
+ : '未启用:根目录没有 PERSONA.md / POLICY.md —— 初始化带 --with-contract 或在设置页写入模板;缺文件不算错。';
295
+ const contractSections = ['PERSONA.md', 'POLICY.md'].map((name) => {
296
+ // 版本标记与 frontmatter 是机器元数据:页面像笔记页一样剥掉,改成一行可读的字段
297
+ const body = stripContractMarker(read(name));
298
+ const fields = parseFrontmatter(body).fields;
299
+ const meta = Object.entries(fields).map(([key, value]) => `${key}: ${value}`).join(' · ');
243
300
  return [
244
- `<h2>${esc(name)}</h2>`,
301
+ `<h3>${esc(name)}</h3>`,
302
+ meta ? `<p class="meta">${esc(meta)}</p>` : '',
245
303
  body.trim()
246
304
  ? `<article>${renderMarkdown(body, { linkFor, skipFirstH1: true })}</article>`
247
305
  : '<p class="meta">还没写。</p>',
248
- ].join('\n');
306
+ ].filter(Boolean).join('\n');
249
307
  });
308
+ // 记忆段:退役行删除线 + 徽标(不再看起来像活条目)
309
+ const memoryBody = read('MEMORY.md');
310
+ const memorySection = memoryBody.trim()
311
+ ? `<article>${renderMemoryBody(memoryBody, linkFor)}</article>`
312
+ : '<p class="meta">还没写。</p>';
313
+ const dreamBody = read('DREAMS.md');
314
+ const scene = payload.scene;
315
+ const counts = `契约正文 ${c.contentWords} 词 · 记忆 ${payload.words} 词 · 场景 ${scene.words} 词 · 开销 ${payload.overheadWords} 词 = 总 ${payload.totalWords} 词`;
250
316
  const body = [
251
317
  `<p class="crumb"><a href="${VIEW}">首页</a> / 记忆</p>`,
252
318
  '<h1>记忆</h1>',
253
319
  `<p class="meta">${esc(usage)}</p>`,
254
- '<p class="meta">这四份文件由人和 agent 直接编辑,不进检索;这里只读。</p>',
255
- ...sections,
320
+ '<p class="meta">根目录 meta 由人和 agent 直接编辑,不进检索;这里只读,不提供编辑。</p>',
321
+ `<h2>契约</h2>`,
322
+ `<p class="meta">${esc(contractSummary)}</p>`,
323
+ ...contractSections,
324
+ '<h2>用户</h2>',
325
+ fileArticle('USER.md', '用户偏好;可以跨库共享。'),
326
+ '<h2>工作约定</h2>',
327
+ fileArticle('AGENTS.md', '硬规则,永不截断;属于记忆预算。'),
328
+ '<h2>记忆</h2>',
329
+ `<p class="meta">${esc(payload.files.filter((f) => f.name === 'MEMORY.md').map((f) => (f.retiredWords > 0 ? `退役 ${f.retiredWords} 词只留在磁盘,不注入` : '')).filter(Boolean).join(' · '))}</p>`,
330
+ memorySection,
331
+ '<h2>周审</h2>',
332
+ '<p class="meta">只有「上次做梦:YYYY-MM-DD」一行参与每周提醒,不注入正文;其余是周审记录。</p>',
333
+ dreamBody.trim()
334
+ ? `<article>${renderMarkdown(dreamBody, { linkFor, skipFirstH1: true })}</article>`
335
+ : '<p class="meta">还没写。</p>',
336
+ '<h2>场景</h2>',
337
+ scene.present
338
+ ? `<p class="meta">已注入 ${scene.words} 词(TTL 内)</p>`
339
+ : '<p class="meta">未配置:运行时状态(STATE)由宿主 / 运行时提供,过期或读不到就不注入;不写进 MEMORY.md。</p>',
340
+ '<h2>载荷预览</h2>',
341
+ `<p class="meta">这一轮模型实际收到的文本(转义展示、只读、与 zk_context 同源):${esc(counts)}</p>`,
342
+ payload.text
343
+ ? `<details><summary>展开</summary><pre>${esc(payload.text)}</pre></details>`
344
+ : '<p class="meta">空:没有可注入的内容。</p>',
256
345
  ].join('\n');
257
346
  sendHtml(res, 200, shell(cfg, '记忆', body));
258
347
  }