dsh-zdiary-kit 0.9.0 → 0.10.1

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.9.0
1
+ # dsh-zdiary-kit 0.10.1
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` | 切换**本会话**用的笔记本(只影响这个会话,不改全局默认);不带参数就列出现有的与当前固定的 |
@@ -54,6 +54,19 @@ DSH 自带的 AGENTS.md 加载只看「项目根 → 当前目录」链,**不
54
54
  `zk-kit init --with-agents`,或在设置页点「写入 AGENTS.md 模板」—— 已存在的文件绝不覆盖。
55
55
  模板首行有 `<!-- zdiary-template: vN -->` 版本标记:老库的 `AGENTS.md` 是旧版时 `zk_lint` 只提示,不自动改。
56
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
+ 设置页的按钮不依赖 zk 初始化:笔记本还没建好时也能先写两份契约(只建根目录与文件,不碰 `.zk`),
64
+ 写完会提醒你仍需要点「初始化 / 补建」建库。
65
+ `POLICY.md` 的解析与强制执行属于下一批(M3);本批只存契约、注入、体检、展示 ——
66
+ `publish` / `spend` 这类外部动作由 `bili_*` 等工具自己读同一份契约执行,插件不假装能管住别的插件。
67
+ **边界**:M1 是「一本笔记本一份」契约;多个 agent 共用一个库时先别启用,等 M4 的 per-agent persona ——
68
+ 否则 A 的人格会串到 B。
69
+
57
70
  维护用 `zk_lint`(结构体检 + 记忆链接核对)和 `zk_dream`(晋升候选 / 拒绝原因 / 未完成项):两个工具都**只读**,
58
71
  写 `MEMORY.md` / `DREAMS.md` 由 agent 按 `AGENTS.md` 自己决定 —— 机械活留在插件,语义判断留在可审计的地方。
59
72
  `zk_dream` 会先读一遍 `MEMORY.md`:已经晋升过的(`[[链接]]` 命中,或条目里直接写了标题)移出候选、单列「已在 MEMORY」,
@@ -100,7 +113,7 @@ dsh plugin --profile web add "link:/path/to/dsh-zdiary-kit"
100
113
  **安装内置 zk**(从 GitHub 官方 release 下 `zk-v<版本>-<平台>.tar.gz`,解到 `~/.dsh/zdiary/bin`,
101
114
  装完真跑一次 `zk --version` 才算成功)。装完会回显下载源:设了 `ZK_DOWNLOAD_BASE` 就明确标成
102
115
  「自定义镜像」并给出实际 URL —— 上游 release 不带校验和,至少让你知道刚才信任了谁;
103
- 3. 点 **自检** 看七项:zk、笔记本、日记模板、日记 group、结构、长期记忆、索引。
116
+ 3. 点 **自检** 看八项:zk、笔记本、日记模板、日记 group、结构、长期记忆、角色契约、索引。
104
117
  zk / 索引会真起进程,笔记本 / 模板 / group / 结构直接读磁盘与配置,长期记忆会重算一遍载荷。
105
118
 
106
119
  ## 设置页里有什么
@@ -292,6 +305,8 @@ zk-kit groups --fix # 只改 dsh-zdiary-kit 自己写的 group:paths 行
292
305
  ```bash
293
306
  zk-kit init # 建库 / 补齐目录、模板、group、AGENTS.md(幂等)
294
307
  zk-kit init --with-agents # flat 库也写一份精简版 AGENTS.md(已存在不覆盖)
308
+ zk-kit init --with-contract # 写 PERSONA.md / POLICY.md 契约模板(缺了才写,已存在不覆盖)
309
+ zk-kit contract # 契约状态:用量 / 预算 / 体检(只读)
295
310
  zk-kit groups # 对照配置与 .zk/config.toml 的 group(默认 dry-run)
296
311
  zk-kit groups --fix # 只改插件建的 group 的 paths / 组头(写前备份 .zk/config.toml.bak)
297
312
  zk-kit new --title "示例笔记" --body "正文" --tags demo --type concept
package/dist/cli.js CHANGED
@@ -10,14 +10,16 @@ import { NOTE_KINDS, ensureNotebook, fixGroupConfig, groupOverlapNotes, newNoteD
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';
13
+ import { formatLintExtras, formatMemoryLinks, lintNotebook, contractStatus } from './lib/lint.js';
14
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 契约模板(缺了才写)
20
21
  zk-kit groups [--fix] [--dry-run] 对照配置与 .zk/config.toml 的 group(默认 dry-run;--fix 只改插件建的 paths,写前备份)
22
+ zk-kit contract 契约状态:PERSONA.md / POLICY.md 的用量 / 预算 / 体检(只读)
21
23
  zk-kit new --title T [--name 文件名] [--summary 摘要] [--body B] [--tags a,b] [--dir notes] [--type source|concept|entity|pattern]
22
24
  zk-kit search [词] [--tags a,b] [--since 日期] [--limit 5] [--json]
23
25
  zk-kit read <路径> | --query 词 [--max-chars n] [--json]
@@ -184,8 +186,12 @@ function dreamReport(r) {
184
186
  const lines = [
185
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}`,
186
188
  ];
187
- // 余量按总词算:只报内容词等于说「还有 10 词」,而框与提示早就把它吃完了
188
- lines.push(`记忆:内容 ${r.memory.words}/${r.memory.budget} 词 + 提示 ${r.memory.totalWords - r.memory.words} = ${r.memory.totalWords} 词(余 ${r.memory.headroom})`);
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} 词(单独注入,不计入记忆预算)` : ''));
189
195
  if (r.retireCandidates.length) {
190
196
  lines.push('可考虑退役:');
191
197
  for (const c of r.retireCandidates.slice(0, 10)) {
@@ -355,7 +361,20 @@ async function doctor() {
355
361
  rows.push(present.length === 0
356
362
  ? '✓ 记忆:暂未启用(根目录没有 AGENTS.md / USER.md / MEMORY.md)'
357
363
  : `${payload.words <= payload.budget ? '✓' : '✗'} 记忆:${payload.words}/${payload.budget} 词(${formatFileShares(payload.files, payload.tocWords)})` +
358
- (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
+ }
359
378
  if (exists) {
360
379
  // 记忆在跑、但没有工作约定:默认安装里这是常态(flat 不自动写 AGENTS.md),
361
380
  // 代价是「每条结论附来源 / 中文打 tags / 每周整理」四条约定与周提醒全都不生效。
@@ -384,8 +403,9 @@ async function doctor() {
384
403
  }
385
404
  }
386
405
  console.log(rows.join('\n'));
387
- // ⚠️ 是内容问题(笔记写坏了),不是装坏了 —— 别让它把 doctor 的退出码翻掉
388
- return rows.every((r) => r.startsWith('✓') || r.startsWith('⚠️'));
406
+ // ⚠️ 是内容问题(笔记写坏了),不是装坏了 —— 别让它把 doctor 的退出码翻掉;
407
+ // · 是「未启用 / 未配置」(如契约文件缺失):同样不算装坏
408
+ return rows.every((r) => r.startsWith('✓') || r.startsWith('⚠️') || r.startsWith('·'));
389
409
  }
390
410
  async function main() {
391
411
  const argv = process.argv.slice(2);
@@ -411,13 +431,40 @@ async function main() {
411
431
  }
412
432
  case 'init': {
413
433
  const withAgents = flags['with-agents'] === true || flags['with-agents'] === 'true';
414
- 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 });
415
436
  print(json ? r : `笔记本 ${r.notebook}(结构 ${cfg.structure})\n` +
416
437
  `初始化:${r.initialized ? '是' : '已是笔记本'} · 目录:${r.dirsCreated.length ? '新建 ' + r.dirsCreated.join('、') : '已齐全'}\n` +
417
- `模板:${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 不写')}` +
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)'}` +
418
439
  (r.groupWarnings.length ? `\n⚠️ ${r.groupWarnings.join('\n⚠️ ')}` : ''), json);
419
440
  return;
420
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
+ }
421
468
  case 'groups': {
422
469
  const fix = flags.fix === true || flags.fix === 'true';
423
470
  const dryRun = flags['dry-run'] === true || flags['dry-run'] === 'true';
@@ -42,6 +42,9 @@ export const DEFAULTS = {
42
42
  defaultTags: [],
43
43
  maxReadChars: 20_000,
44
44
  memoryBudgetWords: 500,
45
+ contractBudgetWords: 240,
46
+ sceneBudgetWords: 80,
47
+ totalPromptBudgetWords: 900,
45
48
  archiveDir: 'archive',
46
49
  zkVersion: '0.15.7',
47
50
  zkPath: '',
@@ -137,6 +140,9 @@ export function normalizeConfig(raw, workspace = processWorkspace()) {
137
140
  defaultTags: tags(src.defaultTags),
138
141
  maxReadChars: clamp(Number(src.maxReadChars), 1000, 200_000, DEFAULTS.maxReadChars),
139
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),
140
146
  archiveDir: relativeDir(src.archiveDir, DEFAULTS.archiveDir),
141
147
  zkVersion: /^\d+\.\d+\.\d+$/.test(String(src.zkVersion ?? '').trim().replace(/^v/i, ''))
142
148
  ? String(src.zkVersion).trim().replace(/^v/i, '')
@@ -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
  }
@@ -61,6 +61,9 @@ window.__ModuleLoader__?.load({
61
61
  { group: '目录与 group', key: 'dailyGroup', label: '日记 group 名', hint: 'zk 配置里的 [group."…"],默认 daily —— 初始化时会自动补上;所有笔记本共用' },
62
62
  { group: '目录与 group', key: 'archiveDir', label: '归档目录', hint: 'supersede 之后笔记搬到这里(保留原相对路径,不删除),默认 archive;所有笔记本共用。旧归档目录非空时拒绝改动 —— 插件不会自动迁移文件' },
63
63
  { group: '记忆', key: 'memoryBudgetWords', label: '注入预算(词)', hint: 'AGENTS.md + USER.md + MEMORY.md 的合计上限,默认 500(中文按 2 字 1 词)。超了先丢 MEMORY 里日期最旧的条目(一条日期都没有才退回从尾部丢),并回显截断了多少' },
64
+ { group: '记忆', key: 'contractBudgetWords', label: '契约预算(词)', hint: 'PERSONA.md + POLICY.md 的合计上限,默认 240(50-800)。契约是硬规则,永远注入、不参与截断;超了只告警' },
65
+ { group: '记忆', key: 'sceneBudgetWords', label: '场景预算(词)', hint: '运行时场景块(STATE)的上限,默认 80;不计入记忆预算,过期不注入' },
66
+ { group: '记忆', key: 'totalPromptBudgetWords', label: '总 prompt 预算(词)', hint: '启用契约后按实际载荷(含框与提示)检查,默认 900;超了只告警并点名,不自动截契约。没有契约的库不产生这条告警' },
64
67
  { group: '写入', key: 'defaultTagsText', label: '默认标签', hint: '新笔记自动追加的标签,逗号分隔,不带 #(可空)' },
65
68
  { group: '写入', key: 'maxReadChars', label: 'zk_read 单次上限(字符)', hint: '默认 20000;超了会截断并明确告知模型' },
66
69
  { group: 'zk', key: 'zkPath', label: 'zk 路径(可空)', hint: '空 = 自动找:配置 → $ZK_BIN → PATH → 插件内置(~/.dsh/zdiary/bin)' },
@@ -201,6 +204,20 @@ window.__ModuleLoader__?.load({
201
204
  setOkMsg('✓ 索引已重建');
202
205
  if (name === 'agents')
203
206
  setOkMsg(d.result?.written === true ? '✓ 已写入 AGENTS.md 模板' : '✓ AGENTS.md 已存在,没有覆盖');
207
+ if (name === 'contract') {
208
+ const res = d.result;
209
+ const r = res || {};
210
+ const parts = [];
211
+ if (r.personaWritten)
212
+ parts.push('写入 PERSONA.md');
213
+ else
214
+ parts.push('PERSONA.md 已存在,没有覆盖');
215
+ if (r.policyWritten)
216
+ parts.push('写入 POLICY.md');
217
+ else
218
+ parts.push('POLICY.md 已存在,没有覆盖');
219
+ setOkMsg('✓ ' + parts.join(' · ') + (d.warn ? '\n⚠️ ' + d.warn : ''));
220
+ }
204
221
  }
205
222
  catch (e) {
206
223
  setErr(String(e.message || e));
@@ -269,7 +286,11 @@ window.__ModuleLoader__?.load({
269
286
  setNbPath('');
270
287
  };
271
288
  if (!cfg) {
272
- return h('div', { className: 'zdk' }, h('h3', { className: 'zdk-title' }, '知识库(zk)'), busy ? h('div', { className: 'zdk-hint' }, '读取中…') : err ? h('div', { className: 'zdk-err' }, err) : null);
289
+ // 读取失败也要有出路:以前这里只有一行红字,整个 section 没有一个可点项
290
+ const failure = err
291
+ ? h('div', null, h('div', { className: 'zdk-err' }, err), h('div', { className: 'zdk-actions' }, h('button', { className: 'zdk-btn zdk-btn2', onClick: load, disabled: !!busy }, '重试')))
292
+ : null;
293
+ return h('div', { className: 'zdk' }, h('h3', { className: 'zdk-title' }, '知识库(zk)'), busy ? h('div', { className: 'zdk-hint' }, '读取中…') : failure);
273
294
  }
274
295
  const dirty = saved !== JSON.stringify({ ...cfg, defaultTags: tagsText.split(/[,,]/).map((s) => s.trim()).filter(Boolean) });
275
296
  const input = { className: 'zdk-input', autoComplete: 'off', spellCheck: false };
@@ -327,6 +348,8 @@ window.__ModuleLoader__?.load({
327
348
  : needsBuild
328
349
  ? `补建 ${savedActive} 的目录`
329
350
  : `初始化 / 补建 ${savedActive}`;
351
+ // 契约按钮不按 notebook.exists 隐藏:契约不依赖 .zk,
352
+ // 这样自检里的「点「写入契约模板」」任何状态下都有对应的可点项。
330
353
  return h('div', { className: 'zdk' }, h('h3', { className: 'zdk-title' }, '知识库(zk)'), h('p', { className: 'zdk-intro' }, '把你的 zk 笔记本接进 DSH:agent 用 zk_* 工具搜索、读写笔记与日记,双链交给 zk 索引。' +
331
354
  '没装 zk 就让插件装一个 —— 第一次调用工具时会自动建好笔记本,不需要先来这里点任何按钮。'), statusLine ? h('div', { className: 'zdk-hint' }, '📚 ' + statusLine) : null, memoryLine ? h('div', { className: 'zdk-hint' }, '🧠 ' + memoryLine) : null, configWarn
332
355
  ? h('div', { className: 'zdk-err' }, '⚠️ ' + configWarn +
@@ -358,7 +381,7 @@ window.__ModuleLoader__?.load({
358
381
  onChange: (e) => setNotebookStructure(name, e.target.value),
359
382
  }, h('option', { value: 'flat' }, 'flat'), h('option', { value: 'layered' }, 'layered')), h('button', { className: 'zdk-btn zdk-btn2', onClick: () => removeNotebook(name), disabled: nbNames.length <= 1 || !!busy }, '删除')))), h('div', { className: 'zdk-row' }, h('div', null, h('div', { className: 'zdk-label' }, '新增笔记本'), h('div', { className: 'zdk-hint' }, '名字只接受字母、数字、_ 与 -(1-32 字符);路径空着就是 <工作区>/zdiary,结构跟当前笔记本一致。改完点「保存」')), h('div', { style: { display: 'flex', gap: '6px', alignItems: 'center' } }, h('input', { ...input, style: { minWidth: '0', width: '110px' }, placeholder: '名字', value: nbName, onChange: (e) => setNbName(e.target.value) }), h('input', { ...input, style: { minWidth: '0', width: '190px' }, placeholder: '路径', value: nbPath, onChange: (e) => setNbPath(e.target.value) }), h('button', { className: 'zdk-btn zdk-btn2', onClick: addNotebook, disabled: !nbName.trim() || !!busy }, '新增')))), ...groups.map((g) => h('div', { key: g }, h('div', { className: 'zdk-group' }, GROUP_LABELS[g] || g), h('div', null, FIELDS.filter((f) => f.group === g).map((f) => h('div', { className: 'zdk-row', key: f.key }, h('div', null, h('div', { className: 'zdk-label' }, f.label), h('div', { className: 'zdk-hint' }, f.hint)), control(f)))))), h('div', { className: 'zdk-actions' }, h('button', { className: 'zdk-btn', onClick: save, disabled: !!busy }, busy === 'save' ? '保存中…' : '保存'), h('button', { className: 'zdk-btn zdk-btn2', onClick: () => action('init', 'init'), disabled: !!busy }, busy === 'init' ? '处理中…' : initLabel), structure && snap?.notebook.exists && !structure.agents.present
360
383
  ? h('button', { className: 'zdk-btn zdk-btn2', onClick: () => action('agents', 'agents'), disabled: !!busy }, busy === 'agents' ? '写入中…' : '写入 AGENTS.md 模板')
361
- : null, h('button', { className: 'zdk-btn zdk-btn2', onClick: () => action('index', 'index'), disabled: !!busy }, busy === 'index' ? '索引进…' : '重建索引'), h('button', { className: 'zdk-btn zdk-btn2', onClick: () => action('install', 'install'), disabled: !!busy }, busy === 'install' ? '下载中…' : '安装内置 zk'), h('button', { className: 'zdk-btn zdk-btn2', onClick: selftest, disabled: !!busy }, busy === 'selftest' ? '自检中…' : '自检'), h('a', { className: 'zdk-btn zdk-btn2', href: '/dsh-zdiary-kit/view', target: '_blank', rel: 'noopener noreferrer', style: { display: 'inline-flex', alignItems: 'center', textDecoration: 'none' } }, '只读视图'), h('button', { className: 'zdk-btn zdk-btn2', onClick: load, disabled: !!busy }, '刷新'), dirty ? h('span', { style: { marginLeft: '10px', color: '#ffb020', fontSize: '13px', alignSelf: 'center' } }, '● 有改动还没保存') : null), okMsg ? h('div', { className: 'zdk-ok' }, okMsg) : null, err ? h('div', { className: 'zdk-err' }, err) : null, out ? h('div', { className: 'zdk-out' }, out) : null, snap?.countsError ? h('div', { className: 'zdk-err' }, '计数失败:' + snap.countsError) : null, h('div', { className: 'zdk-hint' }, `配置:${snap?.configPath || '~/.dsh/zdiary/zdiary.config.json'}\n` +
384
+ : null, h('button', { className: 'zdk-btn zdk-btn2', onClick: () => action('contract', 'contract'), disabled: !!busy }, busy === 'contract' ? '写入中…' : '写入契约模板'), h('button', { className: 'zdk-btn zdk-btn2', onClick: () => action('index', 'index'), disabled: !!busy }, busy === 'index' ? '索引进…' : '重建索引'), h('button', { className: 'zdk-btn zdk-btn2', onClick: () => action('install', 'install'), disabled: !!busy }, busy === 'install' ? '下载中…' : '安装内置 zk'), h('button', { className: 'zdk-btn zdk-btn2', onClick: selftest, disabled: !!busy }, busy === 'selftest' ? '自检中…' : '自检'), h('a', { className: 'zdk-btn zdk-btn2', href: '/dsh-zdiary-kit/view', target: '_blank', rel: 'noopener noreferrer', style: { display: 'inline-flex', alignItems: 'center', textDecoration: 'none' } }, '只读视图'), h('button', { className: 'zdk-btn zdk-btn2', onClick: load, disabled: !!busy }, '刷新'), dirty ? h('span', { style: { marginLeft: '10px', color: '#ffb020', fontSize: '13px', alignSelf: 'center' } }, '● 有改动还没保存') : null), okMsg ? h('div', { className: 'zdk-ok' }, okMsg) : null, err ? h('div', { className: 'zdk-err' }, err) : null, out ? h('div', { className: 'zdk-out' }, out) : null, snap?.countsError ? h('div', { className: 'zdk-err' }, '计数失败:' + snap.countsError) : null, h('div', { className: 'zdk-hint' }, `配置:${snap?.configPath || '~/.dsh/zdiary/zdiary.config.json'}\n` +
362
385
  '工具的用法:zk_search 查 → zk_read 读 → zk_new 新建 → zk_daily 写日记 → zk_link 连双链;zk_stats 看规模。'));
363
386
  }
364
387
  function apply(ctx) {
@@ -14,8 +14,9 @@ import path from 'node:path';
14
14
  import { json, readBody, ROUTE_BASE } from '../../lib/http.js';
15
15
  import { CFG_FILE, processWorkspace } from '../../config/paths.js';
16
16
  import { ArchiveDirChangeError, config, configStamp, ConfigConflictError, writeConfig } from '../../config/store.js';
17
- import { ensureNotebook, structureStatus, writeAgentsTemplate } from '../../lib/notebook.js';
17
+ import { ensureNotebook, structureStatus, writeAgentsTemplate, writeContractTemplates } from '../../lib/notebook.js';
18
18
  import { buildMemoryPayload, formatFileShares } from '../../lib/memory.js';
19
+ import { contractStatus } from '../../lib/lint.js';
19
20
  import { installZk, sourceLabel } from '../../lib/install.js';
20
21
  import { hasNotebook, indexNotebook, notebookStats, resolveZk } from '../../lib/zk.js';
21
22
  const P = `${ROUTE_BASE}/api`;
@@ -52,8 +53,10 @@ async function snapshot(cfg) {
52
53
  words: payload.words,
53
54
  budget: payload.budget,
54
55
  truncatedWords: payload.truncatedWords,
56
+ retiredWords: payload.retiredWords,
55
57
  tocWords: payload.tocWords,
56
58
  files: payload.files,
59
+ contract: payload.contract,
57
60
  };
58
61
  }
59
62
  catch {
@@ -235,6 +238,27 @@ export function registerSettings({ route, isTrusted }) {
235
238
  json(res, 400, { ok: false, error: err instanceof Error ? err.message : String(err) });
236
239
  }
237
240
  });
241
+ // ── 写入契约模板(PERSONA.md / POLICY.md;opt-in,已存在不覆盖)──
242
+ route(`${P}/contract`, async (req, res) => {
243
+ if (!requireTrusted(req, res))
244
+ return;
245
+ if (req.method !== 'POST') {
246
+ json(res, 405, { ok: false, error: '只支持 POST' });
247
+ return;
248
+ }
249
+ const cfg = config();
250
+ try {
251
+ const result = writeContractTemplates(cfg);
252
+ // 契约不依赖 zk:允许在建库前先写。缺 .zk/config.toml 时明确提醒下一步,
253
+ // 别让人以为写完契约笔记本就建好了。文案不区分「这次写没写」:
254
+ // 第二次点击时两份都已存在(false/false),说「已写入」会和「已存在,没有覆盖」自相矛盾。
255
+ const warn = hasNotebook(cfg) ? null : '契约已就位(缺的才写,已存在不覆盖),但这还不是 zk 笔记本(缺 .zk/config.toml)—— 点「初始化 / 补建」建库';
256
+ json(res, 200, { ok: true, result, warn, ...(await snapshot(cfg)) });
257
+ }
258
+ catch (err) {
259
+ json(res, 400, { ok: false, error: err instanceof Error ? err.message : String(err) });
260
+ }
261
+ });
238
262
  // ── 安装内置 zk(官方 release → 插件 bin 目录 → 真跑一次)──
239
263
  route(`${P}/install`, async (req, res) => {
240
264
  if (!requireTrusted(req, res))
@@ -337,7 +361,25 @@ export function registerSettings({ route, isTrusted }) {
337
361
  detail: present.length === 0
338
362
  ? '未启用:根目录没有 AGENTS.md / USER.md / MEMORY.md(layered 初始化会写一份 AGENTS.md 模板)'
339
363
  : `${payload.words}/${payload.budget} 词 · ${formatFileShares(payload.files, payload.tocWords)}` +
340
- (payload.truncatedWords > 0 ? `,已截断 ${payload.truncatedWords} 词` : ''),
364
+ (payload.truncatedWords > 0 ? `,已截断 ${payload.truncatedWords} 词` : '') +
365
+ (payload.retiredWords > 0 ? `,退役省略 ${payload.retiredWords} 词` : ''),
366
+ });
367
+ const c = payload.contract;
368
+ // 缺文件 = 未启用(不算错);只有超预算才是 ✗(契约不截断)。
369
+ // 只启用一半 / 旧版 / 占位符不翻转 ok,但必须在 detail 里说出来 —— 自检不能比 doctor 还宽。
370
+ const contractIssues = c.present ? contractStatus(cfg).items : [];
371
+ const contractIssueText = contractIssues.map((i) => `${i.file} ${i.detail}`).join(';');
372
+ items.push({
373
+ name: '角色契约',
374
+ ok: !c.overBudget,
375
+ detail: c.present
376
+ ? `正文(含标题)${c.contentWords}/${c.budget} 词(${c.files.filter((f) => f.present).map((f) => `${f.name} ${f.words} 词`).join(' · ')})` +
377
+ (c.overBudget ? `,超 ${c.overWords} 词(契约不截断,请缩减或调大契约预算)` : '') +
378
+ (contractIssueText ? `;⚠️ ${contractIssueText}` : '')
379
+ : exists
380
+ ? '未启用:根目录没有 PERSONA.md / POLICY.md(点「写入契约模板」,缺文件不算错)'
381
+ // 契约不依赖 .zk:按钮在被测页面上始终可见,所以先写契约也是合法下一步
382
+ : '未启用:根目录没有 PERSONA.md / POLICY.md(点「写入契约模板」可先写;再点「初始化 / 补建」建库,缺文件不算错)',
341
383
  });
342
384
  }
343
385
  catch (err) {