dsh-zdiary-kit 0.8.3 → 0.10.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +51 -9
- package/dist/cli.js +165 -17
- package/dist/config/store.js +43 -0
- package/dist/features/readonly/feature.js +104 -15
- package/dist/features/settings/client.js +40 -5
- package/dist/features/settings/feature.js +75 -14
- package/dist/features/zk-tools/feature.js +102 -9
- package/dist/lib/agents-template.js +3 -3
- package/dist/lib/dream.js +69 -1
- package/dist/lib/lint.js +87 -33
- package/dist/lib/memory-format.js +102 -0
- package/dist/lib/memory.js +167 -28
- package/dist/lib/meta.js +10 -4
- package/dist/lib/notebook-config.js +188 -0
- package/dist/lib/notebook.js +346 -7
- package/dist/lib/persona-template.js +70 -0
- package/docs/features/memory.md +65 -17
- package/docs/features/provisioning.md +46 -7
- package/docs/features/readonly.md +11 -4
- package/docs/features/settings.md +21 -6
- package/docs/features/zk-tools.md +22 -5
- package/package.json +3 -2
package/dist/lib/lint.js
CHANGED
|
@@ -26,7 +26,9 @@ import path from 'node:path';
|
|
|
26
26
|
import { allNotes, graphEdges, localDate, MAX_SCAN, notesWithFlag, parseErrorWarnings } from './zk.js';
|
|
27
27
|
import { normalizeTitle, resolveWikiTarget, WIKI_LINK, wikiIndex } from './wikilink.js';
|
|
28
28
|
import { parseFrontmatter } from './frontmatter.js';
|
|
29
|
+
import { daysSinceDate, entryDate, isRetiredEntry, splitMemoryEntries } from './memory-format.js';
|
|
29
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';
|
|
30
32
|
/** 每类最多回多少条(计划 §4 M3);总数另给 */
|
|
31
33
|
export const MAX_ITEMS = 50;
|
|
32
34
|
/** 标题归一化与链接解析在 `lib/wikilink.ts`(dream 也用同一套);这里保留导出,免得调用方跟着搬 */
|
|
@@ -144,31 +146,6 @@ export function similarTitles(notes, scanTruncated, max = MAX_ITEMS) {
|
|
|
144
146
|
/** 注入的三份 meta 里只有 MEMORY / USER 会写来源链接;AGENTS 是规则,不查 */
|
|
145
147
|
const MEMORY_LINK_FILES = ['MEMORY.md', 'USER.md'];
|
|
146
148
|
/** 按列表条目切分(含缩进续行):只有条目才谈得上「没附来源」 */
|
|
147
|
-
function listEntries(body) {
|
|
148
|
-
const out = [];
|
|
149
|
-
let current = null;
|
|
150
|
-
const flush = () => {
|
|
151
|
-
if (current)
|
|
152
|
-
out.push(current.join('\n'));
|
|
153
|
-
current = null;
|
|
154
|
-
};
|
|
155
|
-
for (const line of String(body ?? '').split('\n')) {
|
|
156
|
-
if (/^\s*(?:[-*+]|\d+[.)])\s+/.test(line)) {
|
|
157
|
-
flush();
|
|
158
|
-
current = [line];
|
|
159
|
-
}
|
|
160
|
-
else if (current && /^\s+\S/.test(line)) {
|
|
161
|
-
current.push(line);
|
|
162
|
-
}
|
|
163
|
-
else {
|
|
164
|
-
flush();
|
|
165
|
-
}
|
|
166
|
-
}
|
|
167
|
-
flush();
|
|
168
|
-
return out;
|
|
169
|
-
}
|
|
170
|
-
/** 记忆条目的观察日期(P1-3):只认 YYYY-MM-DD 这种能机械解析的形状 */
|
|
171
|
-
const DATE_IN_LINE = /\b\d{4}-\d{2}-\d{2}\b/;
|
|
172
149
|
function collapse(text, max = 100) {
|
|
173
150
|
const one = text.replace(/\s+/g, ' ').trim();
|
|
174
151
|
return one.length > max ? one.slice(0, max) + '…' : one;
|
|
@@ -183,9 +160,13 @@ function collapse(text, max = 100) {
|
|
|
183
160
|
* 纯机械解析:路径优先(原路径 → 加 .md → archive/ 下同名),退而按标题/文件名匹配**活笔记**;
|
|
184
161
|
* 归档标题不反查 —— 归档默认不进检索,这里再造一套索引就成了第二真相。「语义重复」也不查。
|
|
185
162
|
*/
|
|
186
|
-
export function memoryLinkIssues(cfg, notes,
|
|
163
|
+
export function memoryLinkIssues(cfg, notes, opts = {}) {
|
|
164
|
+
const max = opts.max ?? MAX_ITEMS;
|
|
165
|
+
const staleDays = Math.min(3650, Math.max(1, Math.trunc(opts.staleDays ?? 90)));
|
|
166
|
+
const now = opts.now ?? new Date();
|
|
187
167
|
const index = wikiIndex(notes);
|
|
188
168
|
const items = [];
|
|
169
|
+
const staleItems = [];
|
|
189
170
|
const seen = new Set();
|
|
190
171
|
let files = 0;
|
|
191
172
|
let links = 0;
|
|
@@ -193,6 +174,7 @@ export function memoryLinkIssues(cfg, notes, max = MAX_ITEMS) {
|
|
|
193
174
|
let undated = 0;
|
|
194
175
|
let retired = 0;
|
|
195
176
|
let retiredBroken = 0;
|
|
177
|
+
let staleTotal = 0;
|
|
196
178
|
for (const name of MEMORY_LINK_FILES) {
|
|
197
179
|
let body = '';
|
|
198
180
|
try {
|
|
@@ -221,14 +203,14 @@ export function memoryLinkIssues(cfg, notes, max = MAX_ITEMS) {
|
|
|
221
203
|
items.push({ source: name, entry: collapse(line), link: target, reason: issue.reason, path: issue.path });
|
|
222
204
|
}
|
|
223
205
|
}
|
|
224
|
-
// 只对 MEMORY.md 数「没附来源 / 没日期 /
|
|
206
|
+
// 只对 MEMORY.md 数「没附来源 / 没日期 / 退役 / 陈旧」:USER.md 是偏好清单,大多数条目本来就没有来源
|
|
225
207
|
if (name === 'MEMORY.md') {
|
|
226
|
-
for (const entry of
|
|
208
|
+
for (const entry of splitMemoryEntries(body)) {
|
|
227
209
|
const first = entry.split('\n', 1)[0] ?? '';
|
|
228
210
|
if (!entry.includes('[['))
|
|
229
211
|
unlinked += 1;
|
|
230
|
-
//
|
|
231
|
-
if (
|
|
212
|
+
// 退役行:磁盘保留、注入从 0.9 起省略(D3),只核对它指向的新结论是否还活着
|
|
213
|
+
if (isRetiredEntry(entry)) {
|
|
232
214
|
retired += 1;
|
|
233
215
|
const next = /→\s*\[\[([^\]|#]+)/.exec(entry);
|
|
234
216
|
const resolved = next ? resolveWikiTarget(cfg, String(next[1] ?? '').trim(), index) : null;
|
|
@@ -236,12 +218,32 @@ export function memoryLinkIssues(cfg, notes, max = MAX_ITEMS) {
|
|
|
236
218
|
retiredBroken += 1;
|
|
237
219
|
continue;
|
|
238
220
|
}
|
|
239
|
-
|
|
221
|
+
// 日期要真校验:`2026-99-99` 既不算「有日期」,也不该在陈旧里报一次
|
|
222
|
+
const date = entryDate(entry);
|
|
223
|
+
if (!date) {
|
|
240
224
|
undated += 1;
|
|
225
|
+
continue;
|
|
226
|
+
}
|
|
227
|
+
const age = daysSinceDate(date, now);
|
|
228
|
+
if (age !== null && age > staleDays) {
|
|
229
|
+
staleTotal += 1;
|
|
230
|
+
if (staleItems.length < max)
|
|
231
|
+
staleItems.push({ entry: collapse(first), date, age });
|
|
232
|
+
}
|
|
241
233
|
}
|
|
242
234
|
}
|
|
243
235
|
}
|
|
244
|
-
return {
|
|
236
|
+
return {
|
|
237
|
+
files,
|
|
238
|
+
links,
|
|
239
|
+
total: items.length,
|
|
240
|
+
unlinked,
|
|
241
|
+
undated,
|
|
242
|
+
retired,
|
|
243
|
+
retiredBroken,
|
|
244
|
+
stale: { total: staleTotal, staleDays, items: staleItems },
|
|
245
|
+
items: items.slice(0, max),
|
|
246
|
+
};
|
|
245
247
|
}
|
|
246
248
|
/**
|
|
247
249
|
* 一行「记忆链接」摘要:`zk-kit lint` 与 `zk_lint` 共用,免得两处各写一遍文案、
|
|
@@ -270,6 +272,8 @@ export function formatMemoryLinks(bucket) {
|
|
|
270
272
|
? `${bucket.retired} 条已退役,其中 ${bucket.retiredBroken} 条的新结论不是活笔记`
|
|
271
273
|
: `${bucket.retired} 条已退役`);
|
|
272
274
|
}
|
|
275
|
+
if (bucket.stale.total > 0)
|
|
276
|
+
parts.push(`${bucket.stale.total} 条超过 ${bucket.stale.staleDays} 天未复核`);
|
|
273
277
|
return `${bucket.total === 0 && bucket.retiredBroken === 0 ? '✓' : '✗'} 记忆链接:${parts.join('|')}`;
|
|
274
278
|
}
|
|
275
279
|
/**
|
|
@@ -278,6 +282,14 @@ export function formatMemoryLinks(bucket) {
|
|
|
278
282
|
*/
|
|
279
283
|
export function formatLintExtras(r) {
|
|
280
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
|
+
}
|
|
281
293
|
if (r.incomplete.total > 0) {
|
|
282
294
|
lines.push(`✗ frontmatter 缺字段:${r.incomplete.total} 篇 — ` +
|
|
283
295
|
r.incomplete.items.slice(0, 5).map((i) => `${i.path}(缺 ${i.missing.join('/')})`).join('、') +
|
|
@@ -428,6 +440,47 @@ export function tagHygiene(notes, max = 20) {
|
|
|
428
440
|
};
|
|
429
441
|
}
|
|
430
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
|
+
}
|
|
431
484
|
/**
|
|
432
485
|
* 模板版本(P2-15):模板是行为契约,不是静态文档 —— 它每轮注入,写错一句就是每轮都在执行错规则。
|
|
433
486
|
* 但模板允许用户改,不能自动覆盖;版本标记把「过期」变成可发现状态,只报告。
|
|
@@ -600,12 +653,13 @@ export async function lintNotebook(cfg, opts = {}, signal) {
|
|
|
600
653
|
duplicateTitles: duplicateTitles(notes),
|
|
601
654
|
// 日记按天写,标题就是日期:同类比较只会产出一堆误报(见 similarTitles 的注释)
|
|
602
655
|
similarTitles: similarTitles(nonDaily, scanTruncated),
|
|
603
|
-
memoryLinks: memoryLinkIssues(cfg, notes),
|
|
656
|
+
memoryLinks: memoryLinkIssues(cfg, notes, { staleDays, now }),
|
|
604
657
|
incomplete: cfg.structure === 'layered'
|
|
605
658
|
? incompleteFrontmatter(cfg, notes, (rel) => isDaily(path.resolve(cfg.notebook, rel)), scanTruncated)
|
|
606
659
|
: { total: 0, truncated: false, byField: { type: 0, status: 0, authority: 0 }, items: [] },
|
|
607
660
|
tags: tagHygiene(notes),
|
|
608
661
|
template: templateStatus(cfg),
|
|
662
|
+
contract: contractStatus(cfg),
|
|
609
663
|
// 150 篇(不含日记)是检索开始变糊的拐点:提示一下,不生成静态索引(会过期,还要决定谁更新)
|
|
610
664
|
indexHint: nonDaily.length >= 150 && !fs.existsSync(path.join(cfg.notebook, 'INDEX.md')),
|
|
611
665
|
};
|
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 记忆条目的格式口径(唯一一份):memory / dream / lint 都从这里取,
|
|
3
|
+
* 免得「什么算退役」「哪一天算日期」三处各写一遍、下次改措辞只改到一半。
|
|
4
|
+
*
|
|
5
|
+
* 只做机械解析,不做语义判断:
|
|
6
|
+
* · 条目 = 顶层列表项 + 它的缩进续行(与 MEMORY.md 的书写约定一致);
|
|
7
|
+
* · 退役 = 首行 `- [superseded …]`(大小写不敏感);
|
|
8
|
+
* · 日期 = 首行里的 `YYYY-MM-DD`,且必须是真实存在的日期(`2026-99-99` 不算)。
|
|
9
|
+
*/
|
|
10
|
+
/** 顶层列表项;缩进的子项算续行,不另起一条 */
|
|
11
|
+
const LIST_ITEM = /^(?:[-*+]|\d+[.)])\s+/;
|
|
12
|
+
/** 退役条目:`- [superseded 2026-01-01] 旧结论 → [[新结论]]`。必须带 `i`,与 lint 同口径 */
|
|
13
|
+
const RETIRED = /^\s*(?:[-*+]|\d+[.)])\s+\[superseded\b/i;
|
|
14
|
+
/** 行级口径(记忆页徽标用);与 RETIRED 同一份 */
|
|
15
|
+
export const RETIRED_ENTRY_RE = RETIRED;
|
|
16
|
+
/** 只认能机械解析的日期:`YYYY-MM-DD` 且真校验(不是正则通过就算) */
|
|
17
|
+
const DATE = /\b(\d{4})-(\d{2})-(\d{2})\b/;
|
|
18
|
+
function validDate(y, m, d) {
|
|
19
|
+
const year = Number(y);
|
|
20
|
+
const month = Number(m);
|
|
21
|
+
const day = Number(d);
|
|
22
|
+
const at = new Date(year, month - 1, day);
|
|
23
|
+
return at.getFullYear() === year && at.getMonth() === month - 1 && at.getDate() === day;
|
|
24
|
+
}
|
|
25
|
+
function firstLine(entry) {
|
|
26
|
+
return entry.split('\n', 1)[0] ?? '';
|
|
27
|
+
}
|
|
28
|
+
/** 列表条目(含缩进续行)。没有列表项的散文不算条目 —— 那是截断按段落处理的事 */
|
|
29
|
+
export function splitMemoryEntries(body) {
|
|
30
|
+
const out = [];
|
|
31
|
+
let current = null;
|
|
32
|
+
const flush = () => {
|
|
33
|
+
if (current)
|
|
34
|
+
out.push(current.join('\n'));
|
|
35
|
+
current = null;
|
|
36
|
+
};
|
|
37
|
+
for (const line of String(body ?? '').split('\n')) {
|
|
38
|
+
if (LIST_ITEM.test(line)) {
|
|
39
|
+
flush();
|
|
40
|
+
current = [line];
|
|
41
|
+
}
|
|
42
|
+
else if (current && /^\s+\S/.test(line)) {
|
|
43
|
+
current.push(line);
|
|
44
|
+
}
|
|
45
|
+
else {
|
|
46
|
+
flush();
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
flush();
|
|
50
|
+
return out;
|
|
51
|
+
}
|
|
52
|
+
/** true = 条目首行是 `[superseded …]`(大小写不敏感,必须带 i) */
|
|
53
|
+
export function isRetiredEntry(entry) {
|
|
54
|
+
return RETIRED.test(firstLine(entry));
|
|
55
|
+
}
|
|
56
|
+
/** 条目首行里的日期;没有或不合法返回 null(`2026-99-99` 不猜成 12 月) */
|
|
57
|
+
export function entryDate(entry) {
|
|
58
|
+
const m = DATE.exec(firstLine(entry));
|
|
59
|
+
if (!m)
|
|
60
|
+
return null;
|
|
61
|
+
return validDate(m[1], m[2], m[3]) ? `${m[1]}-${m[2]}-${m[3]}` : null;
|
|
62
|
+
}
|
|
63
|
+
/**
|
|
64
|
+
* 去掉退役条目(整条,不留半行),返回正文与删掉的条数。
|
|
65
|
+
* 磁盘上的文件不动 —— 省略只发生在注入路径上;记忆页 / git 仍看得到它们。
|
|
66
|
+
*/
|
|
67
|
+
export function stripRetiredEntries(body) {
|
|
68
|
+
const out = [];
|
|
69
|
+
let count = 0;
|
|
70
|
+
let skipping = false;
|
|
71
|
+
for (const line of String(body ?? '').split('\n')) {
|
|
72
|
+
if (LIST_ITEM.test(line)) {
|
|
73
|
+
skipping = RETIRED.test(line);
|
|
74
|
+
if (skipping) {
|
|
75
|
+
count += 1;
|
|
76
|
+
continue;
|
|
77
|
+
}
|
|
78
|
+
out.push(line);
|
|
79
|
+
continue;
|
|
80
|
+
}
|
|
81
|
+
if (skipping) {
|
|
82
|
+
// 续行与紧随的空行跟着整条一起走:删条不留空洞
|
|
83
|
+
if (!line.trim() || /^\s+\S/.test(line))
|
|
84
|
+
continue;
|
|
85
|
+
skipping = false;
|
|
86
|
+
}
|
|
87
|
+
out.push(line);
|
|
88
|
+
}
|
|
89
|
+
return { body: out.join('\n').replace(/\n{3,}/g, '\n\n').trim(), count };
|
|
90
|
+
}
|
|
91
|
+
/**
|
|
92
|
+
* 距某天几个本地日历天(不是毫秒差 / 86400000 再取整 —— 夏时制会算出 6.958 天)。
|
|
93
|
+
* 日期不合法返回 null;未来日期返回负数(调用方自己决定怎么报)。
|
|
94
|
+
*/
|
|
95
|
+
export function daysSinceDate(date, now = new Date()) {
|
|
96
|
+
const m = /^(\d{4})-(\d{2})-(\d{2})$/.exec(String(date ?? '').trim());
|
|
97
|
+
if (!m || !validDate(m[1], m[2], m[3]))
|
|
98
|
+
return null;
|
|
99
|
+
const at = new Date(Number(m[1]), Number(m[2]) - 1, Number(m[3]));
|
|
100
|
+
const today = new Date(now.getFullYear(), now.getMonth(), now.getDate());
|
|
101
|
+
return Math.round((today.getTime() - at.getTime()) / 86_400_000);
|
|
102
|
+
}
|
package/dist/lib/memory.js
CHANGED
|
@@ -2,13 +2,16 @@
|
|
|
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;
|
|
8
10
|
* · 切分按三级降级:`##` 小节 → 顶层列表项 → 空行段落。只有 `##` 一级时,
|
|
9
11
|
* `# 记忆` + 要点列表(最常见的写法)一个小节都切不出来,预算会整个失效 —— 见 P0-1;
|
|
10
|
-
* · 截断顺序纯机械:先丢 MEMORY
|
|
11
|
-
*
|
|
12
|
+
* · 截断顺序纯机械:先丢 MEMORY 里**日期最旧**的一条(都没有日期才退回尾部整条),
|
|
13
|
+
* 再丢 USER 的尾部整段,最后各自只留首段;AGENTS.md 是硬规则,永不截断(单独超预算时只告警);
|
|
14
|
+
* · 退役条目(`- [superseded …]`)磁盘保留、注入省略 —— 它们按约定退役,不该继续占预算;
|
|
12
15
|
* · 丢掉的段落留一份**目录**(段落标题,计入预算),agent 用 zk_read 取回正文 ——
|
|
13
16
|
* 选哪段是 agent 按当前任务判断,插件只搬运目录,不猜相关性;
|
|
14
17
|
* · 中文按「1 词 / 2 字」计 —— 空白切分在中文上严重低估,预算会变成装饰。
|
|
@@ -22,19 +25,22 @@ import fs from 'node:fs';
|
|
|
22
25
|
import path from 'node:path';
|
|
23
26
|
import { DREAM_INTERVAL_DAYS, daysSinceDream, lastDreamDate } from './dream.js';
|
|
24
27
|
import { fileStamp } from './file-stamp.js';
|
|
25
|
-
import {
|
|
28
|
+
import { entryDate, splitMemoryEntries, stripRetiredEntries } from './memory-format.js';
|
|
29
|
+
import { CONTRACT_META_FILES, MEMORY_META_FILES } from './meta.js';
|
|
26
30
|
/** vault 根目录下、按优先级排列的三份 meta 文件(定义在 lib/meta.ts,这里只挂个本地名) */
|
|
27
31
|
export const META_FILES = MEMORY_META_FILES;
|
|
28
32
|
const CJK = /[\u3040-\u30ff\u3400-\u4dbf\u4e00-\u9fff\uf900-\ufaff\uac00-\ud7af]/g;
|
|
29
|
-
/** 给 doctor / 设置页共用:`AGENTS 193 · USER 30 · MEMORY 22(原 82
|
|
33
|
+
/** 给 doctor / 设置页共用:`AGENTS 193 · USER 30 · MEMORY 22(原 82)(退役 10)`。
|
|
34
|
+
* 「原 X」只反映截断(已扣退役);退役是磁盘保留、注入省略,单列一个括号 —— 两者不再混成一个数。 */
|
|
30
35
|
export function formatFileShares(files, tocWords = 0) {
|
|
31
36
|
const parts = files
|
|
32
|
-
.filter((f) => f.present)
|
|
37
|
+
.filter((f) => f.present || f.retiredWords > 0)
|
|
33
38
|
.map((f) => {
|
|
34
39
|
const label = f.name.replace(/\.md$/i, '');
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
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}`;
|
|
38
44
|
});
|
|
39
45
|
if (tocWords > 0)
|
|
40
46
|
parts.push(`目录 ${tocWords}`);
|
|
@@ -149,6 +155,25 @@ function firstSection(body) {
|
|
|
149
155
|
const split = splitSections(body);
|
|
150
156
|
return joinSections({ head: split.head, sections: split.sections.slice(0, 1), mode: split.mode });
|
|
151
157
|
}
|
|
158
|
+
/**
|
|
159
|
+
* 下一个该丢的条目:能解析出日期时选**最旧**的一条(同日期按位置靠后的先丢);
|
|
160
|
+
* 一条日期都解析不出来返回 null —— 调用方退回尾部丢,老库行为不变(D2.6)。
|
|
161
|
+
*
|
|
162
|
+
* 为什么按日期而不是位置:条目约定是「新结论写顶部」,但没人能保证每次都守;
|
|
163
|
+
* 按位置丢会把最新结论先删掉,而那正好是最该留的。
|
|
164
|
+
*/
|
|
165
|
+
function oldestIndex(split) {
|
|
166
|
+
let best = null;
|
|
167
|
+
for (const [index, section] of split.sections.entries()) {
|
|
168
|
+
const date = entryDate(section);
|
|
169
|
+
if (!date)
|
|
170
|
+
continue;
|
|
171
|
+
if (!best || date < best.date || (date === best.date && index > best.index)) {
|
|
172
|
+
best = { index, date };
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
return best?.index ?? null;
|
|
176
|
+
}
|
|
152
177
|
function sectionTitle(section, mode) {
|
|
153
178
|
const first = section.split('\n', 1)[0] ?? '';
|
|
154
179
|
const raw = mode === 'sections'
|
|
@@ -211,10 +236,28 @@ function readMeta(cfg) {
|
|
|
211
236
|
}
|
|
212
237
|
return out;
|
|
213
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
|
+
}
|
|
214
250
|
function escapeFrame(text) {
|
|
215
251
|
// 文件内容不许提前闭合我们自己的 <system-reminder> 框
|
|
216
252
|
return text.replaceAll('</system-reminder>', '<\\/system-reminder>');
|
|
217
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
|
+
}
|
|
218
261
|
/**
|
|
219
262
|
* 「上次做梦」提醒:DREAMS.md 不在注入清单里,但它头部那一行决定周节奏。
|
|
220
263
|
* 只做日期算术(机械活);整理本身仍然由 agent 按 AGENTS.md 执行 —— 插件没有定时器。
|
|
@@ -247,13 +290,14 @@ function dreamNote(cfg) {
|
|
|
247
290
|
const PAYLOAD_CACHE_MAX = 8;
|
|
248
291
|
const payloadCache = new Map();
|
|
249
292
|
/** DREAMS.md 不进正文,但「上次做梦 N 天前」也算载荷的一部分 —— 它变了同样要重算 */
|
|
250
|
-
const STAMPED_FILES = [...META_FILES, 'DREAMS.md'];
|
|
293
|
+
const STAMPED_FILES = [...CONTRACT_META_FILES, ...META_FILES, 'DREAMS.md'];
|
|
251
294
|
function payloadKeyOf(cfg) {
|
|
252
295
|
const stamps = STAMPED_FILES.map((name) => `${name}=${fileStamp(path.join(cfg.notebook, name))}`).join('|');
|
|
253
296
|
// 做梦提醒按本地日历天变化(「3 天前」→「4 天前」):文件没动也得跟着日期失效
|
|
254
297
|
const now = new Date();
|
|
255
298
|
const day = `${now.getFullYear()}-${now.getMonth() + 1}-${now.getDate()}`;
|
|
256
|
-
|
|
299
|
+
// 三个预算都要进键:改配置不重新写入任何文件,漏一个就会拿到旧预算的载荷
|
|
300
|
+
return `${cfg.notebook}|${cfg.memoryBudgetWords}|${cfg.contractBudgetWords}|${cfg.sceneBudgetWords}|${cfg.totalPromptBudgetWords}|${day}|${stamps}`;
|
|
257
301
|
}
|
|
258
302
|
/**
|
|
259
303
|
* 生成注入载荷。纯读文件,不调 zk、不建目录:笔记本不存在时返回空载荷。
|
|
@@ -283,16 +327,26 @@ export function buildMemoryPayload(cfg) {
|
|
|
283
327
|
function computePayload(cfg) {
|
|
284
328
|
const budget = cfg.memoryBudgetWords;
|
|
285
329
|
const files = readMeta(cfg);
|
|
330
|
+
// 磁盘原文:files[].originalWords 与记忆页的对齐点,退役条目也算在里面
|
|
331
|
+
const diskWords = new Map(files.map((f) => [f.name, countWords(f.body)]));
|
|
286
332
|
const original = new Map(files.map((f) => [f.name, f.body]));
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
333
|
+
// 退役条目:磁盘保留、注入省略(D3)。先去掉,后面的截断只面对活条目。
|
|
334
|
+
const omitted = stripRetiredEntries(original.get('MEMORY.md') ?? '');
|
|
335
|
+
if (omitted.count > 0)
|
|
336
|
+
original.set('MEMORY.md', omitted.body);
|
|
337
|
+
// 去掉退役行之后的内容词数:用来算「截断了多少」,不把省略算成截断
|
|
338
|
+
const contentWords = new Map(files.map((f) => [f.name, countWords(original.get(f.name) ?? '')]));
|
|
339
|
+
// 截断会改写这份计数;contentWords 保留原值,给 truncatedWords 与 files 用
|
|
340
|
+
const words = new Map(contentWords);
|
|
290
341
|
const total = () => [...words.values()].reduce((a, b) => a + b, 0);
|
|
291
|
-
//
|
|
342
|
+
// 截断前的 MEMORY 正文:报告「有多少条没日期」要在丢之前数
|
|
343
|
+
const memorySource = original.get('MEMORY.md') ?? '';
|
|
344
|
+
// ── 机械截断:MEMORY 最旧条目 → USER 尾段 → 各留首段 ──────────────
|
|
292
345
|
// 丢掉的段落留一份目录(段落标题),让 agent 能按当前任务用 zk_read 取回。
|
|
293
346
|
// 目录自己也要占预算,所以每丢一段都把它算进去;目录有上限,循环一定收敛。
|
|
294
347
|
const dropped = [];
|
|
295
348
|
const tocCap = tocCapOf(budget);
|
|
349
|
+
let fellBack = false;
|
|
296
350
|
for (const name of ['MEMORY.md', 'USER.md']) {
|
|
297
351
|
if (total() + countWords(tocText(dropped, tocCap)) <= budget)
|
|
298
352
|
break;
|
|
@@ -300,12 +354,23 @@ function computePayload(cfg) {
|
|
|
300
354
|
const mine = [];
|
|
301
355
|
const over = () => total() + countWords(tocText([...dropped, ...mine], tocCap)) > budget;
|
|
302
356
|
while (over() && split.sections.length > 1) {
|
|
303
|
-
|
|
304
|
-
|
|
357
|
+
// MEMORY 按「最旧日期」丢;解析不出日期(或这是 USER)就退回尾部,行为与 0.8.3 一致
|
|
358
|
+
let index = split.sections.length - 1;
|
|
359
|
+
if (name === 'MEMORY.md') {
|
|
360
|
+
const oldest = oldestIndex(split);
|
|
361
|
+
if (oldest === null)
|
|
362
|
+
fellBack = true;
|
|
363
|
+
else
|
|
364
|
+
index = oldest;
|
|
365
|
+
}
|
|
366
|
+
const section = split.sections.splice(index, 1)[0];
|
|
367
|
+
mine.push({ name, title: sectionTitle(section, split.mode), order: index });
|
|
305
368
|
const body = joinSections(split);
|
|
306
369
|
original.set(name, body);
|
|
307
370
|
words.set(name, countWords(body));
|
|
308
371
|
}
|
|
372
|
+
// 按原文件位置重建目录,而不是按丢弃顺序 —— 目录要能对上文件
|
|
373
|
+
mine.sort((a, b) => (a.order ?? 0) - (b.order ?? 0));
|
|
309
374
|
dropped.push(...mine);
|
|
310
375
|
}
|
|
311
376
|
if (total() + countWords(tocText(dropped, tocCap)) > budget) {
|
|
@@ -321,15 +386,28 @@ function computePayload(cfg) {
|
|
|
321
386
|
const present = files.filter((f) => (original.get(f.name) ?? '').length > 0);
|
|
322
387
|
const bodies = present.map((f) => `## ${f.name}\n\n${escapeFrame(original.get(f.name) ?? '')}`);
|
|
323
388
|
const keptWords = total();
|
|
324
|
-
|
|
325
|
-
const
|
|
389
|
+
// 退役条目不算截断:它按约定退役,不是被预算挤掉的
|
|
390
|
+
const omittedNote = omitted.count > 0 ? `已省略 ${omitted.count} 条退役条目(见 MEMORY.md)` : '';
|
|
391
|
+
// 这条提示本身也要吃饭(D3.2):不把它算进 words,报出来的用量就会少一截
|
|
392
|
+
let finalWords = keptWords + countWords(toc) + countWords(omittedNote);
|
|
393
|
+
const contentSum = files.reduce((sum, f) => sum + (contentWords.get(f.name) ?? 0), 0);
|
|
326
394
|
// 报「正文被截掉多少」,不是净减少:目录也会占词,混在一起会让人以为没丢多少
|
|
327
|
-
const truncatedWords = Math.max(0,
|
|
328
|
-
|
|
395
|
+
const truncatedWords = Math.max(0, contentSum - keptWords);
|
|
396
|
+
// 退役条目的词数:磁盘保留、注入省略(D3)—— 与截断分开报,「原 X」从此只反映截断
|
|
397
|
+
const retiredWords = Math.max(0, (diskWords.get('MEMORY.md') ?? 0) - (contentWords.get('MEMORY.md') ?? 0));
|
|
398
|
+
let memoryInner = '';
|
|
329
399
|
if (bodies.length > 0) {
|
|
330
400
|
const notes = [];
|
|
331
401
|
if (truncatedWords > 0)
|
|
332
402
|
notes.push(`已截断 ${truncatedWords} 词`);
|
|
403
|
+
if (omittedNote)
|
|
404
|
+
notes.push(omittedNote);
|
|
405
|
+
// 一条日期都没有只能按位置丢:说出来,别让人以为是按日期挑的(D2.5)
|
|
406
|
+
if (fellBack && truncatedWords > 0) {
|
|
407
|
+
const undated = splitMemoryEntries(memorySource).filter((entry) => !entryDate(entry)).length;
|
|
408
|
+
if (undated > 0)
|
|
409
|
+
notes.push(`MEMORY 有 ${undated} 条没日期,只能按位置丢`);
|
|
410
|
+
}
|
|
333
411
|
// 目录放不下时至少留一句指路;否则被丢掉的段落对模型完全不可见
|
|
334
412
|
if (!toc && dropped.length > 0) {
|
|
335
413
|
const names = [...new Set(dropped.map((d) => d.name))];
|
|
@@ -370,28 +448,89 @@ function computePayload(cfg) {
|
|
|
370
448
|
const notice = notes.length > 0 ? `\n\n(注入预算 ${budget} 词:${notes.join(';')})` : '';
|
|
371
449
|
// 只有用了这套约定的库(根目录有 AGENTS.md)才提醒周节奏
|
|
372
450
|
const dream = files.some((f) => f.name === 'AGENTS.md' && f.body.length > 0) ? dreamNote(cfg) : '';
|
|
373
|
-
|
|
374
|
-
'
|
|
375
|
-
'以下内容由 zdiary 从知识库根目录读出,是长期约定与记忆;与系统、开发者或用户的直接指令冲突时,以更直接的那条为准。\n\n' +
|
|
376
|
-
bodies.join('\n\n') +
|
|
451
|
+
memoryInner =
|
|
452
|
+
bodies.join('\n\n') +
|
|
377
453
|
(toc ? `\n\n${toc}` : '') +
|
|
378
454
|
(dream ? `\n\n(${dream})` : '') +
|
|
379
|
-
notice
|
|
380
|
-
|
|
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
|
+
}
|
|
381
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 填
|
|
382
490
|
return {
|
|
383
491
|
text,
|
|
384
492
|
words: finalWords,
|
|
385
493
|
budget,
|
|
386
494
|
ratio: budget > 0 ? Math.round((finalWords / budget) * 100) / 100 : 0,
|
|
387
495
|
truncatedWords,
|
|
496
|
+
retiredWords,
|
|
388
497
|
tocWords: countWords(toc),
|
|
389
498
|
files: files.map((f) => ({
|
|
390
499
|
name: f.name,
|
|
391
500
|
present: f.body.length > 0,
|
|
392
501
|
words: words.get(f.name) ?? 0,
|
|
393
|
-
// files[].body 始终是原文件内容(截断只改 original
|
|
394
|
-
originalWords:
|
|
502
|
+
// files[].body 始终是原文件内容(截断只改 original 副本);退役条目也算在原文里
|
|
503
|
+
originalWords: diskWords.get(f.name) ?? 0,
|
|
504
|
+
retiredWords: f.name === 'MEMORY.md' ? retiredWords : 0,
|
|
395
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),
|
|
519
|
+
};
|
|
520
|
+
}
|
|
521
|
+
/**
|
|
522
|
+
* 记忆用量(D4)。只是 `buildMemoryPayload` 的投影 —— 不重读、不重算,
|
|
523
|
+
* 否则就是第三个计数口径,doctor / 设置页 / dream 三处迟早对不上。
|
|
524
|
+
*/
|
|
525
|
+
export function memoryUsage(cfg) {
|
|
526
|
+
const payload = buildMemoryPayload(cfg);
|
|
527
|
+
return {
|
|
528
|
+
words: payload.words,
|
|
529
|
+
contractWords: payload.contract.words,
|
|
530
|
+
totalWords: payload.totalWords,
|
|
531
|
+
budget: payload.budget,
|
|
532
|
+
// 契约是独立层:整段(含它的告警)都不该占记忆预算,否则 dream 会误报「余量」
|
|
533
|
+
headroom: payload.budget - (payload.totalWords - payload.contract.words),
|
|
534
|
+
files: payload.files,
|
|
396
535
|
};
|
|
397
536
|
}
|
package/dist/lib/meta.js
CHANGED
|
@@ -1,14 +1,20 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* 笔记本根目录的 meta 文件:唯一定义处(计划 §7「工具层只放一个常量」)。
|
|
3
3
|
*
|
|
4
|
-
*
|
|
5
|
-
*
|
|
6
|
-
*
|
|
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(/^\.\//, '');
|