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.
@@ -59,8 +59,11 @@ window.__ModuleLoader__?.load({
59
59
  { group: '目录与 group', key: 'notesDir', label: '笔记子目录', hint: '普通笔记放哪(相对笔记本),默认 notes —— 所有笔记本共用' },
60
60
  { group: '目录与 group', key: 'dailyDir', label: '日记子目录', hint: '日记放哪(相对笔记本),默认 journal;文件名由日期模板生成 —— 所有笔记本共用' },
61
61
  { group: '目录与 group', key: 'dailyGroup', label: '日记 group 名', hint: 'zk 配置里的 [group."…"],默认 daily —— 初始化时会自动补上;所有笔记本共用' },
62
- { group: '目录与 group', key: 'archiveDir', label: '归档目录', hint: 'supersede 之后笔记搬到这里(保留原相对路径,不删除),默认 archive;所有笔记本共用,改动后点「初始化 / 补建」' },
63
- { group: '记忆', key: 'memoryBudgetWords', label: '注入预算(词)', hint: 'AGENTS.md + USER.md + MEMORY.md 的合计上限,默认 500(中文按 2 字 1 词)。超了先丢 MEMORY 尾部整段,并回显截断了多少' },
62
+ { group: '目录与 group', key: 'archiveDir', label: '归档目录', hint: 'supersede 之后笔记搬到这里(保留原相对路径,不删除),默认 archive;所有笔记本共用。旧归档目录非空时拒绝改动 —— 插件不会自动迁移文件' },
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)' },
@@ -195,12 +198,26 @@ window.__ModuleLoader__?.load({
195
198
  parts.push('写入 WORKFLOW.md');
196
199
  if (r.configPatched && !(r.templatesWritten && r.templatesWritten.length) && !(r.dirsCreated && r.dirsCreated.length))
197
200
  parts.push('补齐 group');
198
- setOkMsg('✓ ' + parts.join(' · '));
201
+ setOkMsg('✓ ' + parts.join(' · ') + (d.warn ? '\n⚠️ ' + d.warn : ''));
199
202
  }
200
203
  if (name === 'index')
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(' · '));
220
+ }
204
221
  }
205
222
  catch (e) {
206
223
  setErr(String(e.message || e));
@@ -306,6 +323,17 @@ window.__ModuleLoader__?.load({
306
323
  : structure.mode === 'flat' && structure.extra.length
307
324
  ? `盘上有分层目录(${structure.extra.join('、')}),但配置是 flat —— 新建笔记会落在 notes/ 根,不套模板`
308
325
  : '';
326
+ // group 与配置不一致不会自己好:改目录 / 改 dailyGroup 后要显式跑 groups --fix
327
+ const groupBroken = (structure?.groups || []).filter((g) => !g.present || !g.pathsOk);
328
+ // 多行数组 / 重复组等解析失败不是 --fix 能修的;缺 group(present=false)仍可补建
329
+ const groupNeedsManual = groupBroken.some((g) => g.present && g.actualPaths === null);
330
+ // 也可能只是路径互相重叠(配置本身冲突):那时没有「坏掉的组」,只有一条说明
331
+ const groupWarnText = snap?.notebook.exists && structure?.groupsOk === false
332
+ ? groupBroken.length
333
+ ? `配置与 .zk/config.toml 的 group 不一致(${groupBroken.map((g) => g.name).join('、')})`
334
+ : (structure.groupWarnings?.[0] ?? 'group 路径互相重叠')
335
+ : '';
336
+ const configWarn = [structureWarn, groupWarnText].filter(Boolean).join(';');
309
337
  // 底部只留一个按钮:没建过就叫「初始化」,缺东西就叫「补建」,都带上当前笔记本名。
310
338
  // 用已保存的 active 而不是 cfg.active —— 按钮执行的是服务端已落盘的那份配置。
311
339
  const savedActive = snap?.config?.active || cfg.active;
@@ -317,8 +345,13 @@ window.__ModuleLoader__?.load({
317
345
  ? `补建 ${savedActive} 的目录`
318
346
  : `初始化 / 补建 ${savedActive}`;
319
347
  return h('div', { className: 'zdk' }, h('h3', { className: 'zdk-title' }, '知识库(zk)'), h('p', { className: 'zdk-intro' }, '把你的 zk 笔记本接进 DSH:agent 用 zk_* 工具搜索、读写笔记与日记,双链交给 zk 索引。' +
320
- '没装 zk 就让插件装一个 —— 第一次调用工具时会自动建好笔记本,不需要先来这里点任何按钮。'), statusLine ? h('div', { className: 'zdk-hint' }, '📚 ' + statusLine) : null, memoryLine ? h('div', { className: 'zdk-hint' }, '🧠 ' + memoryLine) : null, structureWarn
321
- ? h('div', { className: 'zdk-err' }, '⚠️ ' + structureWarn + ' —— 点底部「' + initLabel + '」')
348
+ '没装 zk 就让插件装一个 —— 第一次调用工具时会自动建好笔记本,不需要先来这里点任何按钮。'), statusLine ? h('div', { className: 'zdk-hint' }, '📚 ' + statusLine) : null, memoryLine ? h('div', { className: 'zdk-hint' }, '🧠 ' + memoryLine) : null, configWarn
349
+ ? h('div', { className: 'zdk-err' }, '⚠️ ' + configWarn +
350
+ (groupBroken.length
351
+ ? groupNeedsManual
352
+ ? ' —— 有 paths 解析不了,请手动编辑 .zk/config.toml'
353
+ : ' —— 跑 zk-kit groups --fix'
354
+ : groupWarnText ? '' : ' —— 点底部「' + initLabel + '」'))
322
355
  : null, h('div', null, h('div', { className: 'zdk-group' }, '笔记本 · 每个笔记本自己的路径与结构'), h('div', { className: 'zdk-row' }, h('div', null, h('div', { className: 'zdk-label' }, '当前笔记本'), h('div', { className: 'zdk-hint' }, '这里是**新会话的默认值**:每个会话第一次用 zk_* 时会把当时的值固定下来,之后各走各的。' +
323
356
  '改这里不会带着已经跑着的会话走 —— 要让某个会话跟过去,在那个会话里说「切到 X 库」(zk_use)。\n' +
324
357
  '路径与结构是每个笔记本自己的;笔记/日记子目录、归档目录、注入预算是全局的。\n' +
@@ -342,6 +375,8 @@ window.__ModuleLoader__?.load({
342
375
  onChange: (e) => setNotebookStructure(name, e.target.value),
343
376
  }, 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
344
377
  ? h('button', { className: 'zdk-btn zdk-btn2', onClick: () => action('agents', 'agents'), disabled: !!busy }, busy === 'agents' ? '写入中…' : '写入 AGENTS.md 模板')
378
+ : null, snap?.notebook.exists
379
+ ? h('button', { className: 'zdk-btn zdk-btn2', onClick: () => action('contract', 'contract'), disabled: !!busy }, busy === 'contract' ? '写入中…' : '写入契约模板')
345
380
  : 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` +
346
381
  '工具的用法:zk_search 查 → zk_read 读 → zk_new 新建 → zk_daily 写日记 → zk_link 连双链;zk_stats 看规模。'));
347
382
  }
@@ -13,9 +13,10 @@ import fs from 'node:fs';
13
13
  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
- import { config, configStamp, ConfigConflictError, writeConfig } from '../../config/store.js';
17
- import { ensureNotebook, structureStatus, writeAgentsTemplate } from '../../lib/notebook.js';
16
+ import { ArchiveDirChangeError, config, configStamp, ConfigConflictError, writeConfig } from '../../config/store.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 {
@@ -121,6 +124,18 @@ export function registerSettings({ route, isTrusted }) {
121
124
  });
122
125
  return;
123
126
  }
127
+ if (err instanceof ArchiveDirChangeError) {
128
+ const latest = config();
129
+ json(res, 400, {
130
+ ok: false,
131
+ error: err.message,
132
+ config: latest,
133
+ configPath: CFG_FILE,
134
+ stamp: configStamp(),
135
+ ...(await snapshot(latest)),
136
+ });
137
+ return;
138
+ }
124
139
  throw err;
125
140
  }
126
141
  const warn = [];
@@ -155,6 +170,10 @@ export function registerSettings({ route, isTrusted }) {
155
170
  if (exists && st.mode === 'flat' && st.extra.length) {
156
171
  warn.push(`盘上有分层目录(${st.extra.join('、')}),但配置是 flat —— 新建笔记会落在 ${next.notesDir}/ 根`);
157
172
  }
173
+ // 改目录不改 group 是最常见的静默坏法:group 的 paths 还指着旧目录,zk 就不按模板归组
174
+ if (exists && !st.groupsOk && st.groupWarnings.length) {
175
+ warn.push('配置与 .zk/config.toml 的 group 不一致:' + st.groupWarnings.join(';'));
176
+ }
158
177
  json(res, 200, { ok: true, config: next, configPath: CFG_FILE, stamp: configStamp(), warn: warn.length ? warn.join(';') : null, ...(await snapshot(next)) });
159
178
  });
160
179
  // ── 状态 ──
@@ -177,7 +196,8 @@ export function registerSettings({ route, isTrusted }) {
177
196
  const cfg = config();
178
197
  try {
179
198
  const result = await ensureNotebook(cfg);
180
- json(res, 200, { ok: true, result, ...(await snapshot(cfg)) });
199
+ const warn = result.groupWarnings.length ? result.groupWarnings.join(';') : null;
200
+ json(res, 200, { ok: true, result, warn, ...(await snapshot(cfg)) });
181
201
  }
182
202
  catch (err) {
183
203
  json(res, 400, { ok: false, error: err instanceof Error ? err.message : String(err) });
@@ -218,6 +238,23 @@ export function registerSettings({ route, isTrusted }) {
218
238
  json(res, 400, { ok: false, error: err instanceof Error ? err.message : String(err) });
219
239
  }
220
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
+ json(res, 200, { ok: true, result, ...(await snapshot(cfg)) });
253
+ }
254
+ catch (err) {
255
+ json(res, 400, { ok: false, error: err instanceof Error ? err.message : String(err) });
256
+ }
257
+ });
221
258
  // ── 安装内置 zk(官方 release → 插件 bin 目录 → 真跑一次)──
222
259
  route(`${P}/install`, async (req, res) => {
223
260
  if (!requireTrusted(req, res))
@@ -273,20 +310,29 @@ export function registerSettings({ route, isTrusted }) {
273
310
  ok: fs.existsSync(templateFile),
274
311
  detail: fs.existsSync(templateFile) ? templateFile : '缺 .zk/templates/daily.md,点「初始化 / 补建」补上',
275
312
  });
276
- let groupOk = false;
277
- try {
278
- const toml = fs.readFileSync(path.join(cfg.notebook, '.zk', 'config.toml'), 'utf8');
279
- groupOk = new RegExp(`^\\[group\\."?${cfg.dailyGroup}"?\\]`, 'm').test(toml);
280
- }
281
- catch {
282
- groupOk = false;
283
- }
313
+ const st = structureStatus(cfg);
314
+ const dailyGroup = st.groups.find((group) => group.name === cfg.dailyGroup);
315
+ const dailyOk = !!dailyGroup && dailyGroup.present && dailyGroup.pathsOk;
316
+ // 自检覆盖全部期望 group 与路径冲突,不是只看 daily 自己能不能对上
317
+ const groupOk = st.groupsOk;
318
+ const otherBroken = st.groups.filter((group) => group.name !== cfg.dailyGroup && (!group.present || !group.pathsOk));
319
+ const overlapped = st.expectedOverlaps.length > 0 || st.actualOverlaps.length > 0;
284
320
  items.push({
285
321
  name: `日记 group(${cfg.dailyGroup})`,
286
322
  ok: groupOk,
287
- detail: groupOk ? `group."${cfg.dailyGroup}" → ${cfg.dailyDir}/` : '配置里没有这个 group,点「初始化 / 补建」补上',
323
+ detail: !dailyGroup
324
+ ? '当前结构没有这个 group'
325
+ : dailyGroup.present
326
+ ? dailyOk
327
+ ? `group."${cfg.dailyGroup}" → ${dailyGroup.actualPaths?.join('、')}` +
328
+ (otherBroken.length ? `;另有 ${otherBroken.length} 个 group 与配置不一致 —— 跑 zk-kit groups --fix` : '') +
329
+ (overlapped ? ';有 group 共用同一路径,zk 命中哪个模板不确定 —— 跑 zk-kit groups 看详情' : '')
330
+ : `期望 ${dailyGroup.expectedPaths.join('、')},实际 ${dailyGroup.actualPaths?.join('、') ?? '解析不了'}` +
331
+ (dailyGroup.actualPaths === null ? '(可能是多行数组)—— 手动编辑 .zk/config.toml' : ' —— 跑 zk-kit groups --fix')
332
+ : dailyGroup.conflict
333
+ ? `配置里没有这个 group(期望 ${dailyGroup.expectedPaths.join('、')}),路径已被 group "${dailyGroup.conflict}" 占用 —— 跑 zk-kit groups --fix`
334
+ : `配置里没有这个 group(期望 ${dailyGroup.expectedPaths.join('、')}),点「初始化 / 补建」补上`,
288
335
  });
289
- const st = structureStatus(cfg);
290
336
  const drift = st.mode === 'flat' && st.extra.length
291
337
  ? `;盘上有分层目录 ${st.extra.join('、')},新建笔记会落在 ${cfg.notesDir}/ 根`
292
338
  : '';
@@ -311,7 +357,22 @@ export function registerSettings({ route, isTrusted }) {
311
357
  detail: present.length === 0
312
358
  ? '未启用:根目录没有 AGENTS.md / USER.md / MEMORY.md(layered 初始化会写一份 AGENTS.md 模板)'
313
359
  : `${payload.words}/${payload.budget} 词 · ${formatFileShares(payload.files, payload.tocWords)}` +
314
- (payload.truncatedWords > 0 ? `,已截断 ${payload.truncatedWords} 词` : ''),
360
+ (payload.truncatedWords > 0 ? `,已截断 ${payload.truncatedWords} 词` : '') +
361
+ (payload.retiredWords > 0 ? `,退役省略 ${payload.retiredWords} 词` : ''),
362
+ });
363
+ const c = payload.contract;
364
+ // 缺文件 = 未启用(不算错);只有超预算才是 ✗(契约不截断)。
365
+ // 只启用一半 / 旧版 / 占位符不翻转 ok,但必须在 detail 里说出来 —— 自检不能比 doctor 还宽。
366
+ const contractIssues = c.present ? contractStatus(cfg).items : [];
367
+ const contractIssueText = contractIssues.map((i) => `${i.file} ${i.detail}`).join(';');
368
+ items.push({
369
+ name: '角色契约',
370
+ ok: !c.overBudget,
371
+ detail: c.present
372
+ ? `正文(含标题)${c.contentWords}/${c.budget} 词(${c.files.filter((f) => f.present).map((f) => `${f.name} ${f.words} 词`).join(' · ')})` +
373
+ (c.overBudget ? `,超 ${c.overWords} 词(契约不截断,请缩减或调大契约预算)` : '') +
374
+ (contractIssueText ? `;⚠️ ${contractIssueText}` : '')
375
+ : '未启用:根目录没有 PERSONA.md / POLICY.md(点「写入契约模板」,缺文件不算错)',
315
376
  });
316
377
  }
317
378
  catch (err) {
@@ -18,7 +18,7 @@ import { searchNotes, searchNotesDetailed, createNote, readNote, findNote, appen
18
18
  import { buildMemoryPayload, META_FILES } from '../../lib/memory.js';
19
19
  import { META_NAMES } from '../../lib/meta.js';
20
20
  import { formatLintExtras, formatMemoryLinks, lintNotebook } from '../../lib/lint.js';
21
- import { dreamNotebook } from '../../lib/dream.js';
21
+ import { dreamNotebook, STALE_DAYS } from '../../lib/dream.js';
22
22
  const text = (value) => [{ type: 'text', text: value }];
23
23
  const objSchema = (properties, required) => ({
24
24
  type: 'object',
@@ -79,6 +79,18 @@ const LINT_MEMORY = objSchema({
79
79
  undated: { type: 'number' },
80
80
  retired: { type: 'number' },
81
81
  retiredBroken: { type: 'number' },
82
+ stale: objSchema({
83
+ total: { type: 'number' },
84
+ staleDays: { type: 'number' },
85
+ items: {
86
+ type: 'array',
87
+ items: objSchema({
88
+ entry: { type: 'string' },
89
+ date: { type: 'string' },
90
+ age: { type: 'number' },
91
+ }, ['entry', 'date', 'age']),
92
+ },
93
+ }, ['total', 'staleDays', 'items']),
82
94
  items: {
83
95
  type: 'array',
84
96
  items: objSchema({
@@ -89,7 +101,7 @@ const LINT_MEMORY = objSchema({
89
101
  path: { type: 'string' },
90
102
  }, ['source', 'entry', 'link', 'reason', 'path']),
91
103
  },
92
- }, ['files', 'links', 'total', 'unlinked', 'undated', 'retired', 'retiredBroken', 'items']);
104
+ }, ['files', 'links', 'total', 'unlinked', 'undated', 'retired', 'retiredBroken', 'stale', 'items']);
93
105
  /** frontmatter 缺字段(P2-13) */
94
106
  const LINT_INCOMPLETE = objSchema({
95
107
  total: { type: 'number' },
@@ -134,6 +146,18 @@ const LINT_TEMPLATE = objSchema({
134
146
  stale: { type: 'boolean' },
135
147
  currentText: { type: 'string' },
136
148
  }, ['present', 'version', 'current', 'stale']);
149
+ /** 契约体检:缺失 / 旧版 / 未填占位符(只报告,不覆盖) */
150
+ const LINT_CONTRACT = objSchema({
151
+ total: { type: 'number' },
152
+ items: {
153
+ type: 'array',
154
+ items: objSchema({
155
+ file: { type: 'string', enum: ['PERSONA.md', 'POLICY.md'] },
156
+ kind: { type: 'string', enum: ['missing', 'old', 'placeholder'] },
157
+ detail: { type: 'string' },
158
+ }, ['file', 'kind', 'detail']),
159
+ },
160
+ }, ['total', 'items']);
137
161
  /** 晋升候选的共用形状:newNotes / alreadyPromoted / backlog 三栏一致 */
138
162
  const DREAM_CANDIDATE = objSchema({
139
163
  title: { type: 'string' },
@@ -846,6 +870,7 @@ export function buildTools(workspaceOf = () => processWorkspace()) {
846
870
  t({
847
871
  name: 'zk_context',
848
872
  description: '读知识库根目录的长期约定与记忆(AGENTS.md / USER.md / MEMORY.md),按注入预算截断后返回;' +
873
+ '角色契约与自主权契约(PERSONA.md / POLICY.md)单独成段、在记忆段之前、不参与截断。' +
849
874
  '同时列出已配置的笔记本(名字 / 路径 / 结构 / 当前)。' +
850
875
  '宿主支持注入时这些内容每轮已自动进入系统提示;宿主不支持、或想核对「被截断了多少」时用它。',
851
876
  parameters: { type: 'object', properties: {}, additionalProperties: false },
@@ -856,7 +881,32 @@ export function buildTools(workspaceOf = () => processWorkspace()) {
856
881
  budget: { type: 'number' },
857
882
  ratio: { type: 'number' },
858
883
  truncatedWords: { type: 'number' },
884
+ retiredWords: { type: 'number' },
859
885
  tocWords: { type: 'number' },
886
+ totalWords: { type: 'number' },
887
+ overheadWords: { type: 'number' },
888
+ contract: objSchema({
889
+ present: { type: 'boolean' },
890
+ contentWords: { type: 'number' },
891
+ words: { type: 'number' },
892
+ noticeWords: { type: 'number' },
893
+ budget: { type: 'number' },
894
+ overBudget: { type: 'boolean' },
895
+ overWords: { type: 'number' },
896
+ files: {
897
+ type: 'array',
898
+ items: objSchema({
899
+ name: { type: 'string' },
900
+ present: { type: 'boolean' },
901
+ words: { type: 'number' },
902
+ }, ['name', 'present', 'words']),
903
+ },
904
+ }, ['present', 'contentWords', 'words', 'noticeWords', 'budget', 'overBudget', 'overWords', 'files']),
905
+ scene: objSchema({
906
+ present: { type: 'boolean' },
907
+ expired: { type: 'boolean' },
908
+ words: { type: 'number' },
909
+ }, ['present', 'expired', 'words']),
860
910
  notebook: { type: 'string' },
861
911
  defaultNotebook: { type: 'string' },
862
912
  pinned: { type: 'string' },
@@ -876,9 +926,10 @@ export function buildTools(workspaceOf = () => processWorkspace()) {
876
926
  present: { type: 'boolean' },
877
927
  words: { type: 'number' },
878
928
  originalWords: { type: 'number' },
879
- }, ['name', 'present', 'words', 'originalWords']),
929
+ retiredWords: { type: 'number' },
930
+ }, ['name', 'present', 'words', 'originalWords', 'retiredWords']),
880
931
  },
881
- }, ['text', 'words', 'budget', 'ratio', 'truncatedWords', 'tocWords', 'notebook', 'defaultNotebook', 'pinned', 'notebooks', 'files']),
932
+ }, ['text', 'words', 'budget', 'ratio', 'truncatedWords', 'retiredWords', 'tocWords', 'totalWords', 'overheadWords', 'contract', 'scene', 'notebook', 'defaultNotebook', 'pinned', 'notebooks', 'files']),
882
933
  },
883
934
  async run(_args, env) {
884
935
  // 不 ensureNotebook:读记忆不该依赖 zk,笔记本不存在时就是空载荷
@@ -906,8 +957,13 @@ export function buildTools(workspaceOf = () => processWorkspace()) {
906
957
  (others.length ? `\n另有:${others.map((n) => `${n.name}(${n.structure})`).join('、')} —— zk_use 切换本会话` : '')
907
958
  : `笔记本「${v.notebook}」`;
908
959
  if (!v.text)
909
- return text(drift + head + `\n\n知识库根目录没有 ${META_FILES.join(' / ')}(或都是空的)。`);
910
- return text(drift + head + '\n\n' + v.text);
960
+ return text(drift + head + `\n\n知识库根目录没有 ${META_FILES.join(' / ')}(或都是空的),也没有 PERSONA.md / POLICY.md 契约。`);
961
+ const contract = v.contract?.present
962
+ ? `\n\n契约:正文(含标题)${v.contract.contentWords}/${v.contract.budget} 词` +
963
+ `(${v.contract.files.filter((f) => f.present).map((f) => `${f.name} ${f.words} 词`).join(' · ')})` +
964
+ (v.contract.overBudget ? `,超 ${v.contract.overWords} 词(契约不截断)` : '')
965
+ : '\n\n契约:未启用(根目录没有 PERSONA.md / POLICY.md)';
966
+ return text(drift + head + contract + '\n\n' + v.text);
911
967
  },
912
968
  }),
913
969
  t({
@@ -916,7 +972,7 @@ export function buildTools(workspaceOf = () => processWorkspace()) {
916
972
  'frontmatter 解析失败的笔记单列一类:它们进不了索引,别的项统计不到,先修它们再看其余。' +
917
973
  'memoryLinks 查 MEMORY.md / USER.md 里的 [[来源链接]] 是否还指向活笔记(已废弃 / 不存在)—— ' +
918
974
  'supersede 不会重写 meta 文件里的链接,这类漂移 broken-links 看不见;另数没附链接(unlinked)、' +
919
- '没写日期(undated)、已退役(retired)与退役后新结论失效(retiredBroken)的条目。' +
975
+ '没写日期(undated)、已退役(retired)、退役后新结论失效(retiredBroken)与超过 90 天没复核(stale)的条目。' +
920
976
  'incomplete 是 frontmatter 缺 type / status / authority 的笔记:缺失被索引落成空串,机械门会静默失效。' +
921
977
  'tags 查标签卫生(大小写变体 / 单例,标签总数 ≥ 30 才报);template 说根目录 AGENTS.md 是不是当前版本。' +
922
978
  'similarTitles 是「改一两个字」的疑似重复(同目录、二元组相似度 ≥ 0.6):与全等重名分开,只报告。' +
@@ -955,8 +1011,9 @@ export function buildTools(workspaceOf = () => processWorkspace()) {
955
1011
  incomplete: LINT_INCOMPLETE,
956
1012
  tags: LINT_TAGS,
957
1013
  template: LINT_TEMPLATE,
1014
+ contract: LINT_CONTRACT,
958
1015
  indexHint: { type: 'boolean' },
959
- }, ['notebook', 'notes', 'truncated', 'staleDays', 'parseErrors', 'orphans', 'brokenLinks', 'stale', 'tagless', 'oneWayLinks', 'duplicateTitles', 'similarTitles', 'memoryLinks', 'incomplete', 'tags', 'template', 'indexHint']),
1016
+ }, ['notebook', 'notes', 'truncated', 'staleDays', 'parseErrors', 'orphans', 'brokenLinks', 'stale', 'tagless', 'oneWayLinks', 'duplicateTitles', 'similarTitles', 'memoryLinks', 'incomplete', 'tags', 'template', 'contract', 'indexHint']),
960
1017
  },
961
1018
  async run(args, env) {
962
1019
  const cfg = configFor(env.workspace, env.sessionId);
@@ -1025,7 +1082,10 @@ export function buildTools(workspaceOf = () => processWorkspace()) {
1025
1082
  'daily 里没划掉的 Loose ends、被引用最多的笔记。候选带正文摘要(lead)与入链来源(citedBy),方便重放上下文。' +
1026
1083
  'topCited 先按「被日记提到几天」排(使用信号),入链数只作并列次序;没有日记时退化为原排序。' +
1027
1084
  '会读 MEMORY.md:已经晋升过的(`[[链接]]` 命中或条目里写了标题)移出候选、进 alreadyPromoted —— 不会每周原样重复。' +
1085
+ '退役行里的旧标题不再算已晋升,但 `→ [[新结论]]` 仍算。' +
1028
1086
  'backlog 是窗口外仍未晋升的笔记(按被引数),漏做一次不会永久掉队。' +
1087
+ 'memory 给记忆余量(内容词 + 提示 = 总词,余量按总词算,可以为负);retireCandidates 给「可考虑退役」的条目' +
1088
+ '(来源归档 / 不存在、超过 ' + STALE_DAYS + ' 天未复核;显式写 archive/ 的有意引用不算)。' +
1029
1089
  'days 省略时窗口 = 距 DREAMS.md「上次做梦」的天数(没有则 7 天)。' +
1030
1090
  '只返回材料:写 MEMORY.md / DREAMS.md 由你按 AGENTS.md 决定,这个工具不写任何文件。',
1031
1091
  parameters: {
@@ -1041,6 +1101,13 @@ export function buildTools(workspaceOf = () => processWorkspace()) {
1041
1101
  windowDays: { type: 'number' },
1042
1102
  since: { type: 'string' },
1043
1103
  truncated: { type: 'boolean' },
1104
+ memory: objSchema({
1105
+ words: { type: 'number' },
1106
+ contractWords: { type: 'number' },
1107
+ totalWords: { type: 'number' },
1108
+ budget: { type: 'number' },
1109
+ headroom: { type: 'number' },
1110
+ }, ['words', 'contractWords', 'totalWords', 'budget', 'headroom']),
1044
1111
  counts: objSchema({
1045
1112
  window: { type: 'number' },
1046
1113
  daily: { type: 'number' },
@@ -1076,7 +1143,16 @@ export function buildTools(workspaceOf = () => processWorkspace()) {
1076
1143
  items: { type: 'array', items: { type: 'string' } },
1077
1144
  }, ['path', 'date', 'items']),
1078
1145
  },
1079
- }, ['notebook', 'windowDays', 'since', 'truncated', 'counts', 'newNotes', 'alreadyPromoted', 'backlog', 'rejected', 'topCited', 'dailyLooseEnds']),
1146
+ retireCandidates: {
1147
+ type: 'array',
1148
+ items: objSchema({
1149
+ entry: { type: 'string' },
1150
+ date: { type: 'string' },
1151
+ age: { type: 'number' },
1152
+ reason: { type: 'string', enum: ['stale', 'source-missing', 'source-superseded'] },
1153
+ }, ['entry', 'date', 'age', 'reason']),
1154
+ },
1155
+ }, ['notebook', 'windowDays', 'since', 'truncated', 'memory', 'counts', 'newNotes', 'alreadyPromoted', 'backlog', 'rejected', 'topCited', 'dailyLooseEnds', 'retireCandidates']),
1080
1156
  },
1081
1157
  async run(args, env) {
1082
1158
  const cfg = configFor(env.workspace, env.sessionId);
@@ -1090,6 +1166,23 @@ export function buildTools(workspaceOf = () => processWorkspace()) {
1090
1166
  ' 篇(日记 ' + v.counts.daily + ')· 候选 ' + v.counts.candidates + ' · 拒绝 ' + v.counts.rejected +
1091
1167
  ' · 未完成 ' + v.counts.looseEnds + ' · 已晋升 ' + v.counts.promoted + ' · 积压 ' + v.counts.backlog,
1092
1168
  ];
1169
+ // 余量按记忆侧总词算(框 + 提示 + notice 都算):只报内容词等于说「还有 15 词」,而提示早把它吃完了。
1170
+ // 契约单独注入,先从 totalWords 里扣掉 —— 它不占记忆预算,也不该被叫成「提示」。
1171
+ const memoryTotal = v.memory.totalWords - v.memory.contractWords;
1172
+ const promptWords = Math.max(0, memoryTotal - v.memory.words);
1173
+ lines.push('记忆:内容 ' + v.memory.words + '/' + v.memory.budget + ' 词 + 提示 ' + promptWords +
1174
+ ' = ' + memoryTotal + ' 词(余 ' + v.memory.headroom + ')' +
1175
+ (v.memory.contractWords > 0 ? ' · 契约 ' + v.memory.contractWords + ' 词(单独注入,不计入记忆预算)' : ''));
1176
+ if (v.retireCandidates.length) {
1177
+ lines.push('可考虑退役:');
1178
+ for (const c of v.retireCandidates.slice(0, 10)) {
1179
+ const when = c.date ? c.date + '(' + c.age + ' 天)' : '无日期';
1180
+ const why = c.reason === 'stale'
1181
+ ? '超过 ' + STALE_DAYS + ' 天未复核'
1182
+ : c.reason === 'source-superseded' ? '来源已归档' : '来源不存在';
1183
+ lines.push(' · ' + c.entry + ' — ' + when + ' · ' + why);
1184
+ }
1185
+ }
1093
1186
  if (v.newNotes.length) {
1094
1187
  lines.push('晋升候选:');
1095
1188
  for (const [i, n] of v.newNotes.slice(0, 10).entries()) {
@@ -13,12 +13,12 @@
13
13
  *
14
14
  * 长度是设计约束:AGENTS.md 属于注入预算(默认 500 词,中文 2 字 = 1 词)且**永不截断**,
15
15
  * 模板自己吃掉过半预算,USER / MEMORY 就没位置了 —— 所以这里只留规则,不写教程。
16
- * 目标 ≤190 词(AGENTS_TEMPLATE 实测 186、AGENTS_TEMPLATE_FLAT 实测 88),单测里锁住。
16
+ * 目标 ≤190 词(AGENTS_TEMPLATE 实测 187、AGENTS_TEMPLATE_FLAT 实测 88),单测里锁住。
17
17
  * 首行 `<!-- zdiary-template: vN -->` 是版本标记:lint 据此报告「老库的 AGENTS.md 是旧版」,
18
18
  * 只报告不覆盖(模板允许用户改)。
19
19
  */
20
20
  /** 模板版本:改模板就 +1;lint 用它判断老库是否还在用旧契约(v2:去掉 inbox/) */
21
- export const TEMPLATE_VERSION = 2;
21
+ export const TEMPLATE_VERSION = 3;
22
22
  /** 首行版本标记(实测 4 词);不许带日期 —— 带日期的写法实测 6 词,白花 2 词 */
23
23
  export const TEMPLATE_MARK = `<!-- zdiary-template: v${TEMPLATE_VERSION} -->`;
24
24
  export const AGENTS_TEMPLATE = `${TEMPLATE_MARK}
@@ -48,7 +48,7 @@ notes/{concepts,entities,patterns}/ 原子笔记 · archive/ 废弃(不删)
48
48
 
49
49
  每周:DREAMS.md 写「上次做梦:YYYY-MM-DD」;到期 zk_lint → zk_dream → 人裁决改 MEMORY。
50
50
  MEMORY.md 每条:结论(YYYY-MM-DD)[[来源路径]];退役写 - [superseded YYYY-MM-DD] 旧结论 → [[新结论]],行不删。
51
- 新条目写顶部;超预算从底部往前丢。
51
+ 新条目写顶部;超预算按日期丢最旧的一条。
52
52
  `;
53
53
  /**
54
54
  * flat 结构用的模板:不出现 raw / inbox / archive / WORKFLOW.md 这些 flat 没有的路径。
package/dist/lib/dream.js CHANGED
@@ -15,6 +15,10 @@ import fs from 'node:fs';
15
15
  import path from 'node:path';
16
16
  import { allNotes, graphEdges, localDate, MAX_SCAN } from './zk.js';
17
17
  import { parseFrontmatter } from './frontmatter.js';
18
+ // memory.ts 也 import 本模块(DREAM_INTERVAL_DAYS / daysSinceDream):这里是运行期才取用,
19
+ // 循环引用在 ESM 下安全 —— 不要在模块顶层调用 memoryUsage。
20
+ import { memoryUsage } from './memory.js';
21
+ import { daysSinceDate, entryDate, isRetiredEntry, splitMemoryEntries, stripRetiredEntries } from './memory-format.js';
18
22
  import { normalizeTitle, resolveWikiTarget, WIKI_LINK, wikiIndex } from './wikilink.js';
19
23
  /** 每栏最多回多少条(计划 §4 M3 的 50 条上限) */
20
24
  export const MAX_ITEMS = 50;
@@ -56,6 +60,10 @@ export function daysSinceDream(last, now = new Date()) {
56
60
  const today = new Date(now.getFullYear(), now.getMonth(), now.getDate());
57
61
  return Math.round((today.getTime() - at.getTime()) / 86_400_000);
58
62
  }
63
+ /** 超过多少天没复核算「可考虑退役」(只做机械年龄判断) */
64
+ export const STALE_DAYS = 90;
65
+ /** 退役候选最多回几条:给材料,不是给清理清单 */
66
+ export const MAX_RETIRE = 10;
59
67
  /**
60
68
  * 从日记正文里取 Loose ends 小节。
61
69
  * `- [x]` 是已完成,不收;`- [ ]` 与普通列表项都收(划掉的状态比格式重要)。
@@ -156,6 +164,11 @@ function windowDaysOf(cfg, now, explicit) {
156
164
  * 为什么要有第二条:真机 MEMORY.md 7 条里 6 条是纯文字(没有链接),只按链接判会漏掉它们,
157
165
  * 而它们正是每周重复出现的候选来源。标题包含只做字符串比较、且要求标题 ≥ 6 字 ——
158
166
  * 短标题(「RAG」「额度」)在任意句子里都可能撞上,宁可重复报,不猜。
167
+ *
168
+ * 退役条目要分开处理(D3.3,顺序不能反):
169
+ * · 链接匹配用**原文** —— 退役行里的 `→ [[新结论]]` 是合法的「已晋升」指针;
170
+ * · 标题匹配用**去掉退役行之后**的正文 —— 退役行里的旧结论不该再算已晋升,
171
+ * 否则归档后复用同一标题的笔记会永远进不了候选。
159
172
  */
160
173
  function promotionsOf(cfg, notes) {
161
174
  const out = new Map();
@@ -174,7 +187,7 @@ function promotionsOf(cfg, notes) {
174
187
  if (hit.status === 'live' && hit.path)
175
188
  out.set(hit.path, 'link');
176
189
  }
177
- const lines = body.split('\n').map((line) => normalizeTitle(line)).filter(Boolean);
190
+ const lines = stripRetiredEntries(body).body.split('\n').map((line) => normalizeTitle(line)).filter(Boolean);
178
191
  for (const note of notes) {
179
192
  if (out.has(note.path))
180
193
  continue;
@@ -186,6 +199,59 @@ function promotionsOf(cfg, notes) {
186
199
  }
187
200
  return out;
188
201
  }
202
+ /**
203
+ * 退役候选(D4.3):只做机械规则,不判断「这条还有没有用」。
204
+ * · 有日期且超过 STALE_DAYS → stale;
205
+ * · 条目里的 `[[来源]]` 指向归档 / 不存在 → source-superseded / source-missing;
206
+ * · 显式写 `archive/` 的链接是有意引用旧结论(与 lint 同口径),不算来源断了;
207
+ * · 无日期、无链接的不算候选(它们已经由 lint 的 undated / unlinked 报告)。
208
+ */
209
+ function retireCandidatesOf(cfg, notes, now) {
210
+ let body = '';
211
+ try {
212
+ body = fs.readFileSync(path.join(cfg.notebook, 'MEMORY.md'), 'utf8');
213
+ }
214
+ catch {
215
+ return [];
216
+ }
217
+ const index = wikiIndex(notes);
218
+ const out = [];
219
+ const seen = new Set();
220
+ for (const entry of splitMemoryEntries(body)) {
221
+ if (isRetiredEntry(entry))
222
+ continue;
223
+ const date = entryDate(entry) ?? '';
224
+ const age = date ? (daysSinceDate(date, now) ?? -1) : -1;
225
+ let reason = null;
226
+ for (const match of entry.matchAll(WIKI_LINK)) {
227
+ const target = String(match[1] ?? '').trim();
228
+ if (!target)
229
+ continue;
230
+ const hit = resolveWikiTarget(cfg, target, index);
231
+ // 显式写 archive/ 的链接是有意引用(supersede 就是这样重写入链的):与 lint 一个口径,不算来源断了
232
+ if (hit.status === 'live' || hit.explicit)
233
+ continue;
234
+ reason = hit.status === 'archived' ? 'source-superseded' : 'source-missing';
235
+ break;
236
+ }
237
+ if (!reason && age > STALE_DAYS)
238
+ reason = 'stale';
239
+ if (!reason)
240
+ continue;
241
+ const summary = (entry.split('\n', 1)[0] ?? '')
242
+ .replace(/^\s*(?:[-*+]|\d+[.)])\s+/, '')
243
+ .replace(/\s+/g, ' ')
244
+ .trim();
245
+ const one = summary.length > 100 ? summary.slice(0, 100) + '…' : summary;
246
+ if (!one || seen.has(one))
247
+ continue;
248
+ seen.add(one);
249
+ out.push({ entry: one, date, age, reason });
250
+ }
251
+ // 越旧越靠前;无日期(-1)的排在最后(不假装它们更旧)
252
+ out.sort((a, b) => b.age - a.age || a.entry.localeCompare(b.entry));
253
+ return out.slice(0, MAX_RETIRE);
254
+ }
189
255
  export async function dreamNotebook(cfg, opts = {}, signal) {
190
256
  const now = opts.now ?? new Date();
191
257
  const windowDays = windowDaysOf(cfg, now, opts.days);
@@ -336,5 +402,7 @@ export async function dreamNotebook(cfg, opts = {}, signal) {
336
402
  rejected: rejected.slice(0, MAX_ITEMS),
337
403
  topCited,
338
404
  dailyLooseEnds,
405
+ memory: memoryUsage(cfg),
406
+ retireCandidates: retireCandidatesOf(cfg, notes, now),
339
407
  };
340
408
  }