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.
@@ -146,6 +146,18 @@ const LINT_TEMPLATE = objSchema({
146
146
  stale: { type: 'boolean' },
147
147
  currentText: { type: 'string' },
148
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']);
149
161
  /** 晋升候选的共用形状:newNotes / alreadyPromoted / backlog 三栏一致 */
150
162
  const DREAM_CANDIDATE = objSchema({
151
163
  title: { type: 'string' },
@@ -858,6 +870,7 @@ export function buildTools(workspaceOf = () => processWorkspace()) {
858
870
  t({
859
871
  name: 'zk_context',
860
872
  description: '读知识库根目录的长期约定与记忆(AGENTS.md / USER.md / MEMORY.md),按注入预算截断后返回;' +
873
+ '角色契约与自主权契约(PERSONA.md / POLICY.md)单独成段、在记忆段之前、不参与截断。' +
861
874
  '同时列出已配置的笔记本(名字 / 路径 / 结构 / 当前)。' +
862
875
  '宿主支持注入时这些内容每轮已自动进入系统提示;宿主不支持、或想核对「被截断了多少」时用它。',
863
876
  parameters: { type: 'object', properties: {}, additionalProperties: false },
@@ -868,7 +881,32 @@ export function buildTools(workspaceOf = () => processWorkspace()) {
868
881
  budget: { type: 'number' },
869
882
  ratio: { type: 'number' },
870
883
  truncatedWords: { type: 'number' },
884
+ retiredWords: { type: 'number' },
871
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']),
872
910
  notebook: { type: 'string' },
873
911
  defaultNotebook: { type: 'string' },
874
912
  pinned: { type: 'string' },
@@ -888,9 +926,10 @@ export function buildTools(workspaceOf = () => processWorkspace()) {
888
926
  present: { type: 'boolean' },
889
927
  words: { type: 'number' },
890
928
  originalWords: { type: 'number' },
891
- }, ['name', 'present', 'words', 'originalWords']),
929
+ retiredWords: { type: 'number' },
930
+ }, ['name', 'present', 'words', 'originalWords', 'retiredWords']),
892
931
  },
893
- }, ['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']),
894
933
  },
895
934
  async run(_args, env) {
896
935
  // 不 ensureNotebook:读记忆不该依赖 zk,笔记本不存在时就是空载荷
@@ -918,8 +957,13 @@ export function buildTools(workspaceOf = () => processWorkspace()) {
918
957
  (others.length ? `\n另有:${others.map((n) => `${n.name}(${n.structure})`).join('、')} —— zk_use 切换本会话` : '')
919
958
  : `笔记本「${v.notebook}」`;
920
959
  if (!v.text)
921
- return text(drift + head + `\n\n知识库根目录没有 ${META_FILES.join(' / ')}(或都是空的)。`);
922
- 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);
923
967
  },
924
968
  }),
925
969
  t({
@@ -967,8 +1011,9 @@ export function buildTools(workspaceOf = () => processWorkspace()) {
967
1011
  incomplete: LINT_INCOMPLETE,
968
1012
  tags: LINT_TAGS,
969
1013
  template: LINT_TEMPLATE,
1014
+ contract: LINT_CONTRACT,
970
1015
  indexHint: { type: 'boolean' },
971
- }, ['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']),
972
1017
  },
973
1018
  async run(args, env) {
974
1019
  const cfg = configFor(env.workspace, env.sessionId);
@@ -1058,10 +1103,11 @@ export function buildTools(workspaceOf = () => processWorkspace()) {
1058
1103
  truncated: { type: 'boolean' },
1059
1104
  memory: objSchema({
1060
1105
  words: { type: 'number' },
1106
+ contractWords: { type: 'number' },
1061
1107
  totalWords: { type: 'number' },
1062
1108
  budget: { type: 'number' },
1063
1109
  headroom: { type: 'number' },
1064
- }, ['words', 'totalWords', 'budget', 'headroom']),
1110
+ }, ['words', 'contractWords', 'totalWords', 'budget', 'headroom']),
1065
1111
  counts: objSchema({
1066
1112
  window: { type: 'number' },
1067
1113
  daily: { type: 'number' },
@@ -1120,9 +1166,13 @@ export function buildTools(workspaceOf = () => processWorkspace()) {
1120
1166
  ' 篇(日记 ' + v.counts.daily + ')· 候选 ' + v.counts.candidates + ' · 拒绝 ' + v.counts.rejected +
1121
1167
  ' · 未完成 ' + v.counts.looseEnds + ' · 已晋升 ' + v.counts.promoted + ' · 积压 ' + v.counts.backlog,
1122
1168
  ];
1123
- // 余量按总词算(框 + 提示 + notice 都算):只报内容词等于说「还有 15 词」,而提示早把它吃完了
1124
- lines.push('记忆:内容 ' + v.memory.words + '/' + v.memory.budget + ' 词 + 提示 ' +
1125
- (v.memory.totalWords - v.memory.words) + ' = ' + v.memory.totalWords + ' 词(余 ' + v.memory.headroom + ')');
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 + ' 词(单独注入,不计入记忆预算)' : ''));
1126
1176
  if (v.retireCandidates.length) {
1127
1177
  lines.push('可考虑退役:');
1128
1178
  for (const c of v.retireCandidates.slice(0, 10)) {
package/dist/lib/lint.js CHANGED
@@ -28,6 +28,7 @@ import { normalizeTitle, resolveWikiTarget, WIKI_LINK, wikiIndex } from './wikil
28
28
  import { parseFrontmatter } from './frontmatter.js';
29
29
  import { daysSinceDate, entryDate, isRetiredEntry, splitMemoryEntries } from './memory-format.js';
30
30
  import { AGENTS_TEMPLATE, AGENTS_TEMPLATE_FLAT, TEMPLATE_VERSION } from './agents-template.js';
31
+ import { PERSONA_TEMPLATE_VERSION, POLICY_TEMPLATE_VERSION } from './persona-template.js';
31
32
  /** 每类最多回多少条(计划 §4 M3);总数另给 */
32
33
  export const MAX_ITEMS = 50;
33
34
  /** 标题归一化与链接解析在 `lib/wikilink.ts`(dream 也用同一套);这里保留导出,免得调用方跟着搬 */
@@ -281,6 +282,14 @@ export function formatMemoryLinks(bucket) {
281
282
  */
282
283
  export function formatLintExtras(r) {
283
284
  const lines = [];
285
+ // 两份都没有 = 契约未启用(默认状态):不报错、不占行。只启用一半(缺一份)或
286
+ // 有旧版 / 占位符时才提醒 —— 否则每个老库每次 lint 都多一条永久 ⚠️,反而训练人忽略告警。
287
+ const missing = r.contract.items.filter((i) => i.kind === 'missing');
288
+ const bothMissing = missing.length > 1 && missing.length === r.contract.items.length;
289
+ if (!bothMissing && r.contract.items.length > 0) {
290
+ lines.push(`⚠️ 契约:${r.contract.items.map((i) => `${i.file} ${i.detail}`).join(';')}` +
291
+ '|只报告:缺一份 = 尚未启用完整契约,占位符与旧版由人按需处理');
292
+ }
284
293
  if (r.incomplete.total > 0) {
285
294
  lines.push(`✗ frontmatter 缺字段:${r.incomplete.total} 篇 — ` +
286
295
  r.incomplete.items.slice(0, 5).map((i) => `${i.path}(缺 ${i.missing.join('/')})`).join('、') +
@@ -431,6 +440,47 @@ export function tagHygiene(notes, max = 20) {
431
440
  };
432
441
  }
433
442
  const TEMPLATE_MARK_RE = /<!--\s*zdiary-template:\s*v(\d+)\s*-->/;
443
+ const PERSONA_MARK_RE = /<!--\s*zdiary-persona:\s*v(\d+)\s*-->/;
444
+ const POLICY_MARK_RE = /<!--\s*zdiary-policy:\s*v(\d+)\s*-->/;
445
+ const PLACEHOLDER_RE = /\{\{\s*[^}]+\s*\}\}/g;
446
+ /**
447
+ * 契约体检(M1):缺文件 = 未启用(不算错,但要让 zk_lint 可见);
448
+ * 旧版 = 版本标记比当前模板旧(只报告,不覆盖 —— 契约允许人改);
449
+ * 占位符 = 模板里的 {{...}} 还没填(“未填”是机械可发现的“未启用一半”状态)。
450
+ */
451
+ export function contractStatus(cfg) {
452
+ const items = [];
453
+ const files = [
454
+ { name: 'PERSONA.md', mark: PERSONA_MARK_RE, current: PERSONA_TEMPLATE_VERSION },
455
+ { name: 'POLICY.md', mark: POLICY_MARK_RE, current: POLICY_TEMPLATE_VERSION },
456
+ ];
457
+ for (const f of files) {
458
+ let body = '';
459
+ try {
460
+ body = fs.readFileSync(path.join(cfg.notebook, f.name), 'utf8');
461
+ }
462
+ catch {
463
+ items.push({ file: f.name, kind: 'missing', detail: '根目录没有这份文件(zk-kit init --with-contract 或设置页可写入模板)' });
464
+ continue;
465
+ }
466
+ const hit = f.mark.exec(body);
467
+ const version = hit ? Number(hit[1]) : 0;
468
+ if (version !== f.current) {
469
+ items.push({
470
+ file: f.name,
471
+ kind: 'old',
472
+ detail: version === 0
473
+ ? `没有版本标记(当前 v${f.current})`
474
+ : `是旧版 v${version}(当前 v${f.current})`,
475
+ });
476
+ }
477
+ const placeholders = [...new Set(body.match(PLACEHOLDER_RE) ?? [])];
478
+ if (placeholders.length > 0) {
479
+ items.push({ file: f.name, kind: 'placeholder', detail: `还有未填的占位符:${placeholders.join('、')}` });
480
+ }
481
+ }
482
+ return { total: items.length, items };
483
+ }
434
484
  /**
435
485
  * 模板版本(P2-15):模板是行为契约,不是静态文档 —— 它每轮注入,写错一句就是每轮都在执行错规则。
436
486
  * 但模板允许用户改,不能自动覆盖;版本标记把「过期」变成可发现状态,只报告。
@@ -609,6 +659,7 @@ export async function lintNotebook(cfg, opts = {}, signal) {
609
659
  : { total: 0, truncated: false, byField: { type: 0, status: 0, authority: 0 }, items: [] },
610
660
  tags: tagHygiene(notes),
611
661
  template: templateStatus(cfg),
662
+ contract: contractStatus(cfg),
612
663
  // 150 篇(不含日记)是检索开始变糊的拐点:提示一下,不生成静态索引(会过期,还要决定谁更新)
613
664
  indexHint: nonDaily.length >= 150 && !fs.existsSync(path.join(cfg.notebook, 'INDEX.md')),
614
665
  };
@@ -11,6 +11,8 @@
11
11
  const LIST_ITEM = /^(?:[-*+]|\d+[.)])\s+/;
12
12
  /** 退役条目:`- [superseded 2026-01-01] 旧结论 → [[新结论]]`。必须带 `i`,与 lint 同口径 */
13
13
  const RETIRED = /^\s*(?:[-*+]|\d+[.)])\s+\[superseded\b/i;
14
+ /** 行级口径(记忆页徽标用);与 RETIRED 同一份 */
15
+ export const RETIRED_ENTRY_RE = RETIRED;
14
16
  /** 只认能机械解析的日期:`YYYY-MM-DD` 且真校验(不是正则通过就算) */
15
17
  const DATE = /\b(\d{4})-(\d{2})-(\d{2})\b/;
16
18
  function validDate(y, m, d) {
@@ -2,6 +2,8 @@
2
2
  * 记忆注入(M1):读 vault 根目录的 AGENTS.md / USER.md / MEMORY.md,
3
3
  * 按 `memoryBudgetWords` 截断,渲染成一段可注入系统提示的文本。
4
4
  * 另读 DREAMS.md 的「上次做梦」一行(不进正文、不计预算),给周节奏一句机械提醒。
5
+ * 契约层(PERSONA.md / POLICY.md)单独一段注入、永远在记忆段之前、不参与截断,
6
+ * 超预算只告警;缺文件 = 未启用,0.9 的老库逐字节不变。
5
7
  *
6
8
  * 硬约定(与 docs/plan-memory-layers.md §3 D6 一致):
7
9
  * · 预算按**总载荷**算,不是只卡 MEMORY.md;
@@ -24,19 +26,21 @@ import path from 'node:path';
24
26
  import { DREAM_INTERVAL_DAYS, daysSinceDream, lastDreamDate } from './dream.js';
25
27
  import { fileStamp } from './file-stamp.js';
26
28
  import { entryDate, splitMemoryEntries, stripRetiredEntries } from './memory-format.js';
27
- import { MEMORY_META_FILES } from './meta.js';
29
+ import { CONTRACT_META_FILES, MEMORY_META_FILES } from './meta.js';
28
30
  /** vault 根目录下、按优先级排列的三份 meta 文件(定义在 lib/meta.ts,这里只挂个本地名) */
29
31
  export const META_FILES = MEMORY_META_FILES;
30
32
  const CJK = /[\u3040-\u30ff\u3400-\u4dbf\u4e00-\u9fff\uf900-\ufaff\uac00-\ud7af]/g;
31
- /** 给 doctor / 设置页共用:`AGENTS 193 · USER 30 · MEMORY 22(原 82)` */
33
+ /** 给 doctor / 设置页共用:`AGENTS 193 · USER 30 · MEMORY 22(原 82)(退役 10)`。
34
+ * 「原 X」只反映截断(已扣退役);退役是磁盘保留、注入省略,单列一个括号 —— 两者不再混成一个数。 */
32
35
  export function formatFileShares(files, tocWords = 0) {
33
36
  const parts = files
34
- .filter((f) => f.present)
37
+ .filter((f) => f.present || f.retiredWords > 0)
35
38
  .map((f) => {
36
39
  const label = f.name.replace(/\.md$/i, '');
37
- return f.originalWords > f.words
38
- ? `${label} ${f.words}(原 ${f.originalWords})`
39
- : `${label} ${f.words}`;
40
+ const kept = Math.max(0, f.originalWords - f.retiredWords);
41
+ const truncated = kept > f.words ? `(原 ${kept})` : '';
42
+ const retired = f.retiredWords > 0 ? `(退役 ${f.retiredWords})` : '';
43
+ return `${label} ${f.words}${truncated}${retired}`;
40
44
  });
41
45
  if (tocWords > 0)
42
46
  parts.push(`目录 ${tocWords}`);
@@ -232,10 +236,28 @@ function readMeta(cfg) {
232
236
  }
233
237
  return out;
234
238
  }
239
+ /** 读契约层两份(PERSONA.md / POLICY.md);缺文件 = 空 = 未启用,不报错 */
240
+ function readContracts(cfg) {
241
+ return CONTRACT_META_FILES.map((name) => {
242
+ let body = '';
243
+ try {
244
+ body = fs.readFileSync(path.join(cfg.notebook, name), 'utf8').trim();
245
+ }
246
+ catch { /* 缺文件 = 空 */ }
247
+ return { name, body };
248
+ });
249
+ }
235
250
  function escapeFrame(text) {
236
251
  // 文件内容不许提前闭合我们自己的 <system-reminder> 框
237
252
  return text.replaceAll('</system-reminder>', '<\\/system-reminder>');
238
253
  }
254
+ /** 载荷框:先定义成常量,契约 / 总 prompt 预算与最终拼装才能共用同一份文字(否则数出来的词对不上) */
255
+ const FRAME_HEAD = '<system-reminder>\n' +
256
+ '以下内容由 zdiary 从知识库根目录读出,是长期约定与记忆;与系统、开发者或用户的直接指令冲突时,以更直接的那条为准。\n\n';
257
+ const FRAME_TAIL = '\n</system-reminder>';
258
+ function frameText(body) {
259
+ return FRAME_HEAD + body + FRAME_TAIL;
260
+ }
239
261
  /**
240
262
  * 「上次做梦」提醒:DREAMS.md 不在注入清单里,但它头部那一行决定周节奏。
241
263
  * 只做日期算术(机械活);整理本身仍然由 agent 按 AGENTS.md 执行 —— 插件没有定时器。
@@ -268,13 +290,14 @@ function dreamNote(cfg) {
268
290
  const PAYLOAD_CACHE_MAX = 8;
269
291
  const payloadCache = new Map();
270
292
  /** DREAMS.md 不进正文,但「上次做梦 N 天前」也算载荷的一部分 —— 它变了同样要重算 */
271
- const STAMPED_FILES = [...META_FILES, 'DREAMS.md'];
293
+ const STAMPED_FILES = [...CONTRACT_META_FILES, ...META_FILES, 'DREAMS.md'];
272
294
  function payloadKeyOf(cfg) {
273
295
  const stamps = STAMPED_FILES.map((name) => `${name}=${fileStamp(path.join(cfg.notebook, name))}`).join('|');
274
296
  // 做梦提醒按本地日历天变化(「3 天前」→「4 天前」):文件没动也得跟着日期失效
275
297
  const now = new Date();
276
298
  const day = `${now.getFullYear()}-${now.getMonth() + 1}-${now.getDate()}`;
277
- return `${cfg.notebook}|${cfg.memoryBudgetWords}|${day}|${stamps}`;
299
+ // 三个预算都要进键:改配置不重新写入任何文件,漏一个就会拿到旧预算的载荷
300
+ return `${cfg.notebook}|${cfg.memoryBudgetWords}|${cfg.contractBudgetWords}|${cfg.sceneBudgetWords}|${cfg.totalPromptBudgetWords}|${day}|${stamps}`;
278
301
  }
279
302
  /**
280
303
  * 生成注入载荷。纯读文件,不调 zk、不建目录:笔记本不存在时返回空载荷。
@@ -370,7 +393,9 @@ function computePayload(cfg) {
370
393
  const contentSum = files.reduce((sum, f) => sum + (contentWords.get(f.name) ?? 0), 0);
371
394
  // 报「正文被截掉多少」,不是净减少:目录也会占词,混在一起会让人以为没丢多少
372
395
  const truncatedWords = Math.max(0, contentSum - keptWords);
373
- let text = '';
396
+ // 退役条目的词数:磁盘保留、注入省略(D3)—— 与截断分开报,「原 X」从此只反映截断
397
+ const retiredWords = Math.max(0, (diskWords.get('MEMORY.md') ?? 0) - (contentWords.get('MEMORY.md') ?? 0));
398
+ let memoryInner = '';
374
399
  if (bodies.length > 0) {
375
400
  const notes = [];
376
401
  if (truncatedWords > 0)
@@ -423,21 +448,52 @@ function computePayload(cfg) {
423
448
  const notice = notes.length > 0 ? `\n\n(注入预算 ${budget} 词:${notes.join(';')})` : '';
424
449
  // 只有用了这套约定的库(根目录有 AGENTS.md)才提醒周节奏
425
450
  const dream = files.some((f) => f.name === 'AGENTS.md' && f.body.length > 0) ? dreamNote(cfg) : '';
426
- text =
427
- '<system-reminder>\n' +
428
- '以下内容由 zdiary 从知识库根目录读出,是长期约定与记忆;与系统、开发者或用户的直接指令冲突时,以更直接的那条为准。\n\n' +
429
- bodies.join('\n\n') +
451
+ memoryInner =
452
+ bodies.join('\n\n') +
430
453
  (toc ? `\n\n${toc}` : '') +
431
454
  (dream ? `\n\n(${dream})` : '') +
432
- notice +
433
- '\n</system-reminder>';
455
+ notice;
456
+ }
457
+ // ── 契约段(角色 + 自主权):永远注入、在记忆段之前、不参与截断 ────
458
+ // 超预算只告警不静默丢;总 prompt 超限点名但不自动截契约。
459
+ // 没有契约文件 = 未启用:不多一个词,0.9 的老库逐字节一致。
460
+ const contractBudget = cfg.contractBudgetWords;
461
+ const contracts = readContracts(cfg);
462
+ const contractBodies = contracts.filter((f) => f.body.length > 0);
463
+ const contractBodyText = contractBodies.map((f) => `## ${f.name}\n\n${escapeFrame(f.body)}`).join('\n\n');
464
+ // 预算只算正文(含文件标题),不能把告警行算进去 —— 否则「已用 / 超出」会随告警自己的长度变
465
+ const contractContentWords = countWords(contractBodyText);
466
+ const contractOver = contractBodies.length > 0 && contractContentWords > contractBudget;
467
+ const contractNotes = [];
468
+ if (contractOver) {
469
+ contractNotes.push(`契约预算 ${contractBudget} 词:已用 ${contractContentWords},超出 ${contractContentWords - contractBudget} 词(契约不截断)`);
470
+ }
471
+ if (contractBodies.length > 0) {
472
+ // 总 prompt 用「还没加契约告警」的完整载荷来量:框 / 做梦提醒 / 记忆 notice 都要算,
473
+ // 但本条告警自己不能算进自己报的数里(否则又是一个自指的口径)。
474
+ const provisional = frameText((contractBodyText ? contractBodyText + '\n\n' : '') + memoryInner);
475
+ const promptTotal = countWords(provisional);
476
+ if (promptTotal > cfg.totalPromptBudgetWords) {
477
+ const overhead = Math.max(0, promptTotal - contractContentWords - finalWords);
478
+ contractNotes.push(`总 prompt 预算 ${cfg.totalPromptBudgetWords} 词:契约 ${contractContentWords} + 记忆 ${finalWords} + 框与提示 ${overhead} = ${promptTotal},超出 ${promptTotal - cfg.totalPromptBudgetWords}`);
479
+ }
434
480
  }
481
+ const contractText = contractBodyText + (contractNotes.length > 0 ? `\n\n(${contractNotes.join(';')})` : '');
482
+ const contractWords = countWords(contractText);
483
+ let text = '';
484
+ if (memoryInner || contractText) {
485
+ text = frameText((contractText ? contractText + '\n\n' : '') + memoryInner);
486
+ }
487
+ // 模型真正收到的总量与开销:口径与 memoryUsage / D9 的载荷预览同源
488
+ const totalWords = countWords(text);
489
+ const sceneWords = 0; // M1 只落形状:M3 起由 STATE 填
435
490
  return {
436
491
  text,
437
492
  words: finalWords,
438
493
  budget,
439
494
  ratio: budget > 0 ? Math.round((finalWords / budget) * 100) / 100 : 0,
440
495
  truncatedWords,
496
+ retiredWords,
441
497
  tocWords: countWords(toc),
442
498
  files: files.map((f) => ({
443
499
  name: f.name,
@@ -445,7 +501,21 @@ function computePayload(cfg) {
445
501
  words: words.get(f.name) ?? 0,
446
502
  // files[].body 始终是原文件内容(截断只改 original 副本);退役条目也算在原文里
447
503
  originalWords: diskWords.get(f.name) ?? 0,
504
+ retiredWords: f.name === 'MEMORY.md' ? retiredWords : 0,
448
505
  })),
506
+ contract: {
507
+ present: contractBodies.length > 0,
508
+ contentWords: contractContentWords,
509
+ words: contractWords,
510
+ noticeWords: Math.max(0, contractWords - contractContentWords),
511
+ budget: contractBudget,
512
+ overBudget: contractOver,
513
+ overWords: Math.max(0, contractContentWords - contractBudget),
514
+ files: contracts.map((f) => ({ name: f.name, present: f.body.length > 0, words: countWords(f.body) })),
515
+ },
516
+ scene: { present: false, expired: false, words: sceneWords },
517
+ totalWords,
518
+ overheadWords: Math.max(0, totalWords - contractContentWords - finalWords - sceneWords),
449
519
  };
450
520
  }
451
521
  /**
@@ -454,12 +524,13 @@ function computePayload(cfg) {
454
524
  */
455
525
  export function memoryUsage(cfg) {
456
526
  const payload = buildMemoryPayload(cfg);
457
- const totalWords = countWords(payload.text);
458
527
  return {
459
528
  words: payload.words,
460
- totalWords,
529
+ contractWords: payload.contract.words,
530
+ totalWords: payload.totalWords,
461
531
  budget: payload.budget,
462
- headroom: payload.budget - totalWords,
532
+ // 契约是独立层:整段(含它的告警)都不该占记忆预算,否则 dream 会误报「余量」
533
+ headroom: payload.budget - (payload.totalWords - payload.contract.words),
463
534
  files: payload.files,
464
535
  };
465
536
  }
package/dist/lib/meta.js CHANGED
@@ -1,14 +1,20 @@
1
1
  /**
2
2
  * 笔记本根目录的 meta 文件:唯一定义处(计划 §7「工具层只放一个常量」)。
3
3
  *
4
- * 三份被注入(MEMORY_META_FILES,按注入顺序),六份一律不进检索与统计(META_NAMES)。
5
- * 为什么要拆:注入只读三份,排除要连 DREAMS.md / INDEX.md / WORKFLOW.md 一起排;
6
- * 两份清单共用一个真相,才不会出现「新加一份 meta 忘了排除」。
4
+ * 三份被注入记忆段(MEMORY_META_FILES,按注入顺序),两份契约(CONTRACT_META_FILES)单独注入、
5
+ * 永远在记忆段之前;八份一律不进检索与统计(META_NAMES)。
6
+ * 为什么要拆:注入清单与排除清单共用一份真相,才不会出现「新加一份 meta 忘了排除」。
7
+ *
8
+ * 契约文件(PERSONA.md / POLICY.md)与 MEMORY 同级:根目录 meta,人类所有;
9
+ * 工具不能写、不能搬(zk 层的 isMetaPath 守卫自动覆盖)。缺文件 = 未启用,不报错。
10
+ * 迁移说明:根目录曾有同名普通笔记的库,需要改名或移入子目录。
7
11
  */
8
12
  /** 会被注入系统提示的三份,顺序即注入顺序 */
9
13
  export const MEMORY_META_FILES = ['AGENTS.md', 'USER.md', 'MEMORY.md'];
14
+ /** 契约层两份(角色契约 / 自主权契约),人类所有,缺文件 = 未启用 */
15
+ export const CONTRACT_META_FILES = ['PERSONA.md', 'POLICY.md'];
10
16
  /** 全部 meta 文件(不进检索 / 统计 / 追加写入) */
11
- export const META_NAMES = ['AGENTS.md', 'MEMORY.md', 'USER.md', 'DREAMS.md', 'INDEX.md', 'WORKFLOW.md'];
17
+ export const META_NAMES = ['AGENTS.md', 'MEMORY.md', 'USER.md', 'DREAMS.md', 'INDEX.md', 'WORKFLOW.md', 'PERSONA.md', 'POLICY.md'];
12
18
  /** 相对路径是不是根目录的 meta 文件(只认根目录;子目录里的同名文件是普通笔记) */
13
19
  export function isMetaPath(rel) {
14
20
  const normalized = String(rel ?? '').replace(/\\/g, '/').replace(/^\.\//, '');
@@ -13,6 +13,7 @@ import fs from 'node:fs';
13
13
  import path from 'node:path';
14
14
  import { ZkError, zk } from './zk.js';
15
15
  import { AGENTS_TEMPLATE, AGENTS_TEMPLATE_FLAT, WORKFLOW_TEMPLATE } from './agents-template.js';
16
+ import { PERSONA_TEMPLATE, POLICY_TEMPLATE } from './persona-template.js';
16
17
  import { effectivePaths, isPluginOwned, normGroupPath, parseGroupBlocks, sameGroupPath, samePaths } from './notebook-config.js';
17
18
  export { AGENTS_TEMPLATE, AGENTS_TEMPLATE_FLAT, WORKFLOW_TEMPLATE } from './agents-template.js';
18
19
  export const DAILY_TEMPLATE = `# {{format-date now "%Y-%m-%d"}}
@@ -338,6 +339,26 @@ export function writeAgentsTemplate(cfg) {
338
339
  fs.writeFileSync(file, cfg.structure === 'layered' ? AGENTS_TEMPLATE : AGENTS_TEMPLATE_FLAT, 'utf8');
339
340
  return true;
340
341
  }
342
+ /**
343
+ * 写根目录契约模板(PERSONA.md / POLICY.md;缺了才写,已存在绝不覆盖 —— 契约允许人改)。
344
+ * 只走显式 opt-in(zk-kit init --with-contract / 设置页按钮):默认升级不多一个文件。
345
+ *
346
+ * 先 mkdir 再写:设置页的按钮在笔记本还没初始化时也可点(「先定角色、再建库」是合法顺序)。
347
+ * 这里只建目录与两份契约,不碰 .zk / 模板 / 笔记;之后 ensureNotebook 幂等接管同一目录。
348
+ */
349
+ export function writeContractTemplates(cfg) {
350
+ const persona = path.join(cfg.notebook, 'PERSONA.md');
351
+ const policy = path.join(cfg.notebook, 'POLICY.md');
352
+ const personaWritten = !fs.existsSync(persona);
353
+ const policyWritten = !fs.existsSync(policy);
354
+ if (personaWritten || policyWritten)
355
+ fs.mkdirSync(cfg.notebook, { recursive: true });
356
+ if (personaWritten)
357
+ fs.writeFileSync(persona, PERSONA_TEMPLATE, 'utf8');
358
+ if (policyWritten)
359
+ fs.writeFileSync(policy, POLICY_TEMPLATE, 'utf8');
360
+ return { personaWritten, policyWritten };
361
+ }
341
362
  /** 建好(或补好)笔记本;返回每一步各自做了没有,设置页直接展示 */
342
363
  export async function ensureNotebook(cfg, signal, opts = {}) {
343
364
  const layered = cfg.structure === 'layered';
@@ -360,6 +381,10 @@ export async function ensureNotebook(cfg, signal, opts = {}) {
360
381
  // layered 自动写;flat 只有显式 withAgents 才写 —— 0.1.0 的 vault 升级过来必须一个文件都不多(M0)。
361
382
  // 不写的话,默认安装既没有约定、也没有周节奏提醒(P1-6),所以要有一个 opt-in 入口。
362
383
  const agentsWritten = layered || opts.withAgents === true ? writeAgentsTemplate(cfg) : false;
384
+ // 契约层(角色 / 自主权)只走显式 opt-in:两种结构都不自动多两个文件(D10)。
385
+ const contractWritten = opts.withContract === true
386
+ ? writeContractTemplates(cfg)
387
+ : { personaWritten: false, policyWritten: false };
363
388
  // WORKFLOW.md 是「动已有笔记」时才读的细则:不注入(省预算),但不进检索(是 meta)
364
389
  const workflowFile = path.join(cfg.notebook, 'WORKFLOW.md');
365
390
  let workflowWritten = false;
@@ -417,6 +442,8 @@ export async function ensureNotebook(cfg, signal, opts = {}) {
417
442
  groupWarnings,
418
443
  agentsWritten,
419
444
  workflowWritten,
445
+ personaWritten: contractWritten.personaWritten,
446
+ policyWritten: contractWritten.policyWritten,
420
447
  };
421
448
  }
422
449
  const escapeRe = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
@@ -0,0 +1,70 @@
1
+ /**
2
+ * 根目录 PERSONA.md / POLICY.md 模板:opt-in 写入(`zk-kit init --with-contract`、
3
+ * 设置页「写入角色契约模板」、ensureNotebook(..., { withContract: true })),已存在绝不覆盖。
4
+ *
5
+ * 与 AGENTS.md 模板同一条规矩:首行版本标记独立(`zdiary-persona` / `zdiary-policy`,
6
+ * 不复用 zdiary-template —— AGENTS 改版不该让契约误报旧版)。
7
+ * 版本标记后**紧跟** frontmatter:M3 解析 POLICY / PERSONA 前先 `stripContractMarker()`,
8
+ * 再复用 `lib/frontmatter` —— 不要让「机器可读字段」依赖一个只在本模块才认的自定义语法。
9
+ * 缺文件 = 未启用,不报错;doctor / zk_lint 只给只读提示。
10
+ *
11
+ * 长度是设计约束:两份合计默认预算 240 词(contractBudgetWords,中文 2 字 = 1 词),
12
+ * 契约不参与截断,超了只告警 —— 所以模板只留骨架,占位符 `{{...}}` 由人填,
13
+ * lint 据此报告「未填」。
14
+ */
15
+ /** PERSONA.md 模板版本:改模板就 +1(独立于 TEMPLATE_VERSION) */
16
+ export const PERSONA_TEMPLATE_VERSION = 2;
17
+ /** POLICY.md 模板版本:改模板就 +1 */
18
+ export const POLICY_TEMPLATE_VERSION = 2;
19
+ /**
20
+ * 去掉首行契约版本标记,剩下的可以直接交给 `parseFrontmatter()`。
21
+ * M3 的 policy / persona 解析必须走这里,别自己再写一套「跳过第几行」的规则。
22
+ */
23
+ export function stripContractMarker(body) {
24
+ return String(body ?? '').replace(/^\uFEFF?\s*<!--\s*zdiary-(?:persona|policy):\s*v\d+\s*-->\s*\r?\n?/, '');
25
+ }
26
+ export const PERSONA_TEMPLATE = `<!-- zdiary-persona: v${PERSONA_TEMPLATE_VERSION} -->
27
+ ---
28
+ name: {{name}}
29
+ role: {{role}}
30
+ updated: {{updated}}
31
+ ---
32
+
33
+ # 角色契约
34
+
35
+ > zdiary 生成;人类所有。永远注入、不参与截断。git diff 可审。
36
+
37
+ ## 语气与边界
38
+
39
+ - 语气:{{tone}}
40
+ - 边界:{{boundaries}}
41
+
42
+ ## 口头禅
43
+
44
+ - 待填
45
+
46
+ ## 禁用表达
47
+
48
+ - 待填
49
+ `;
50
+ export const POLICY_TEMPLATE = `<!-- zdiary-policy: v${POLICY_TEMPLATE_VERSION} -->
51
+ ---
52
+ version: 1
53
+ updated: {{updated}}
54
+ audit: DREAMS.md
55
+ ---
56
+
57
+ # 自主权契约
58
+
59
+ > zdiary 生成;人类所有。插件只做最小检查;publish / spend 等动作工具自己读、自己执行。
60
+
61
+ | action | level | approval | reversible |
62
+ |---|---|---|---|
63
+ | read-note | auto | none | yes |
64
+ | write-note | auto | none | yes |
65
+ | publish | ask | human | no |
66
+ | spend | ask | human | no |
67
+ | edit-persona | forbidden | human | yes |
68
+ | edit-memory | forbidden | human | yes |
69
+ | impersonate-human | forbidden | human | no |
70
+ `;