dsh-zdiary-kit 0.8.3 → 0.9.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 +36 -7
- package/dist/cli.js +112 -11
- package/dist/config/store.js +37 -0
- package/dist/features/settings/client.js +21 -5
- package/dist/features/settings/feature.js +38 -12
- package/dist/features/zk-tools/feature.js +47 -4
- package/dist/lib/agents-template.js +3 -3
- package/dist/lib/dream.js +69 -1
- package/dist/lib/lint.js +36 -33
- package/dist/lib/memory-format.js +100 -0
- package/dist/lib/memory.js +81 -13
- package/dist/lib/notebook-config.js +188 -0
- package/dist/lib/notebook.js +324 -7
- package/docs/features/memory.md +32 -12
- package/docs/features/provisioning.md +32 -5
- package/docs/features/settings.md +9 -2
- package/docs/features/zk-tools.md +11 -2
- package/package.json +1 -1
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
|
}
|
package/dist/lib/lint.js
CHANGED
|
@@ -26,6 +26,7 @@ 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';
|
|
30
31
|
/** 每类最多回多少条(计划 §4 M3);总数另给 */
|
|
31
32
|
export const MAX_ITEMS = 50;
|
|
@@ -144,31 +145,6 @@ export function similarTitles(notes, scanTruncated, max = MAX_ITEMS) {
|
|
|
144
145
|
/** 注入的三份 meta 里只有 MEMORY / USER 会写来源链接;AGENTS 是规则,不查 */
|
|
145
146
|
const MEMORY_LINK_FILES = ['MEMORY.md', 'USER.md'];
|
|
146
147
|
/** 按列表条目切分(含缩进续行):只有条目才谈得上「没附来源」 */
|
|
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
148
|
function collapse(text, max = 100) {
|
|
173
149
|
const one = text.replace(/\s+/g, ' ').trim();
|
|
174
150
|
return one.length > max ? one.slice(0, max) + '…' : one;
|
|
@@ -183,9 +159,13 @@ function collapse(text, max = 100) {
|
|
|
183
159
|
* 纯机械解析:路径优先(原路径 → 加 .md → archive/ 下同名),退而按标题/文件名匹配**活笔记**;
|
|
184
160
|
* 归档标题不反查 —— 归档默认不进检索,这里再造一套索引就成了第二真相。「语义重复」也不查。
|
|
185
161
|
*/
|
|
186
|
-
export function memoryLinkIssues(cfg, notes,
|
|
162
|
+
export function memoryLinkIssues(cfg, notes, opts = {}) {
|
|
163
|
+
const max = opts.max ?? MAX_ITEMS;
|
|
164
|
+
const staleDays = Math.min(3650, Math.max(1, Math.trunc(opts.staleDays ?? 90)));
|
|
165
|
+
const now = opts.now ?? new Date();
|
|
187
166
|
const index = wikiIndex(notes);
|
|
188
167
|
const items = [];
|
|
168
|
+
const staleItems = [];
|
|
189
169
|
const seen = new Set();
|
|
190
170
|
let files = 0;
|
|
191
171
|
let links = 0;
|
|
@@ -193,6 +173,7 @@ export function memoryLinkIssues(cfg, notes, max = MAX_ITEMS) {
|
|
|
193
173
|
let undated = 0;
|
|
194
174
|
let retired = 0;
|
|
195
175
|
let retiredBroken = 0;
|
|
176
|
+
let staleTotal = 0;
|
|
196
177
|
for (const name of MEMORY_LINK_FILES) {
|
|
197
178
|
let body = '';
|
|
198
179
|
try {
|
|
@@ -221,14 +202,14 @@ export function memoryLinkIssues(cfg, notes, max = MAX_ITEMS) {
|
|
|
221
202
|
items.push({ source: name, entry: collapse(line), link: target, reason: issue.reason, path: issue.path });
|
|
222
203
|
}
|
|
223
204
|
}
|
|
224
|
-
// 只对 MEMORY.md 数「没附来源 / 没日期 /
|
|
205
|
+
// 只对 MEMORY.md 数「没附来源 / 没日期 / 退役 / 陈旧」:USER.md 是偏好清单,大多数条目本来就没有来源
|
|
225
206
|
if (name === 'MEMORY.md') {
|
|
226
|
-
for (const entry of
|
|
207
|
+
for (const entry of splitMemoryEntries(body)) {
|
|
227
208
|
const first = entry.split('\n', 1)[0] ?? '';
|
|
228
209
|
if (!entry.includes('[['))
|
|
229
210
|
unlinked += 1;
|
|
230
|
-
//
|
|
231
|
-
if (
|
|
211
|
+
// 退役行:磁盘保留、注入从 0.9 起省略(D3),只核对它指向的新结论是否还活着
|
|
212
|
+
if (isRetiredEntry(entry)) {
|
|
232
213
|
retired += 1;
|
|
233
214
|
const next = /→\s*\[\[([^\]|#]+)/.exec(entry);
|
|
234
215
|
const resolved = next ? resolveWikiTarget(cfg, String(next[1] ?? '').trim(), index) : null;
|
|
@@ -236,12 +217,32 @@ export function memoryLinkIssues(cfg, notes, max = MAX_ITEMS) {
|
|
|
236
217
|
retiredBroken += 1;
|
|
237
218
|
continue;
|
|
238
219
|
}
|
|
239
|
-
|
|
220
|
+
// 日期要真校验:`2026-99-99` 既不算「有日期」,也不该在陈旧里报一次
|
|
221
|
+
const date = entryDate(entry);
|
|
222
|
+
if (!date) {
|
|
240
223
|
undated += 1;
|
|
224
|
+
continue;
|
|
225
|
+
}
|
|
226
|
+
const age = daysSinceDate(date, now);
|
|
227
|
+
if (age !== null && age > staleDays) {
|
|
228
|
+
staleTotal += 1;
|
|
229
|
+
if (staleItems.length < max)
|
|
230
|
+
staleItems.push({ entry: collapse(first), date, age });
|
|
231
|
+
}
|
|
241
232
|
}
|
|
242
233
|
}
|
|
243
234
|
}
|
|
244
|
-
return {
|
|
235
|
+
return {
|
|
236
|
+
files,
|
|
237
|
+
links,
|
|
238
|
+
total: items.length,
|
|
239
|
+
unlinked,
|
|
240
|
+
undated,
|
|
241
|
+
retired,
|
|
242
|
+
retiredBroken,
|
|
243
|
+
stale: { total: staleTotal, staleDays, items: staleItems },
|
|
244
|
+
items: items.slice(0, max),
|
|
245
|
+
};
|
|
245
246
|
}
|
|
246
247
|
/**
|
|
247
248
|
* 一行「记忆链接」摘要:`zk-kit lint` 与 `zk_lint` 共用,免得两处各写一遍文案、
|
|
@@ -270,6 +271,8 @@ export function formatMemoryLinks(bucket) {
|
|
|
270
271
|
? `${bucket.retired} 条已退役,其中 ${bucket.retiredBroken} 条的新结论不是活笔记`
|
|
271
272
|
: `${bucket.retired} 条已退役`);
|
|
272
273
|
}
|
|
274
|
+
if (bucket.stale.total > 0)
|
|
275
|
+
parts.push(`${bucket.stale.total} 条超过 ${bucket.stale.staleDays} 天未复核`);
|
|
273
276
|
return `${bucket.total === 0 && bucket.retiredBroken === 0 ? '✓' : '✗'} 记忆链接:${parts.join('|')}`;
|
|
274
277
|
}
|
|
275
278
|
/**
|
|
@@ -600,7 +603,7 @@ export async function lintNotebook(cfg, opts = {}, signal) {
|
|
|
600
603
|
duplicateTitles: duplicateTitles(notes),
|
|
601
604
|
// 日记按天写,标题就是日期:同类比较只会产出一堆误报(见 similarTitles 的注释)
|
|
602
605
|
similarTitles: similarTitles(nonDaily, scanTruncated),
|
|
603
|
-
memoryLinks: memoryLinkIssues(cfg, notes),
|
|
606
|
+
memoryLinks: memoryLinkIssues(cfg, notes, { staleDays, now }),
|
|
604
607
|
incomplete: cfg.structure === 'layered'
|
|
605
608
|
? incompleteFrontmatter(cfg, notes, (rel) => isDaily(path.resolve(cfg.notebook, rel)), scanTruncated)
|
|
606
609
|
: { total: 0, truncated: false, byField: { type: 0, status: 0, authority: 0 }, items: [] },
|
|
@@ -0,0 +1,100 @@
|
|
|
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
|
+
/** 只认能机械解析的日期:`YYYY-MM-DD` 且真校验(不是正则通过就算) */
|
|
15
|
+
const DATE = /\b(\d{4})-(\d{2})-(\d{2})\b/;
|
|
16
|
+
function validDate(y, m, d) {
|
|
17
|
+
const year = Number(y);
|
|
18
|
+
const month = Number(m);
|
|
19
|
+
const day = Number(d);
|
|
20
|
+
const at = new Date(year, month - 1, day);
|
|
21
|
+
return at.getFullYear() === year && at.getMonth() === month - 1 && at.getDate() === day;
|
|
22
|
+
}
|
|
23
|
+
function firstLine(entry) {
|
|
24
|
+
return entry.split('\n', 1)[0] ?? '';
|
|
25
|
+
}
|
|
26
|
+
/** 列表条目(含缩进续行)。没有列表项的散文不算条目 —— 那是截断按段落处理的事 */
|
|
27
|
+
export function splitMemoryEntries(body) {
|
|
28
|
+
const out = [];
|
|
29
|
+
let current = null;
|
|
30
|
+
const flush = () => {
|
|
31
|
+
if (current)
|
|
32
|
+
out.push(current.join('\n'));
|
|
33
|
+
current = null;
|
|
34
|
+
};
|
|
35
|
+
for (const line of String(body ?? '').split('\n')) {
|
|
36
|
+
if (LIST_ITEM.test(line)) {
|
|
37
|
+
flush();
|
|
38
|
+
current = [line];
|
|
39
|
+
}
|
|
40
|
+
else if (current && /^\s+\S/.test(line)) {
|
|
41
|
+
current.push(line);
|
|
42
|
+
}
|
|
43
|
+
else {
|
|
44
|
+
flush();
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
flush();
|
|
48
|
+
return out;
|
|
49
|
+
}
|
|
50
|
+
/** true = 条目首行是 `[superseded …]`(大小写不敏感,必须带 i) */
|
|
51
|
+
export function isRetiredEntry(entry) {
|
|
52
|
+
return RETIRED.test(firstLine(entry));
|
|
53
|
+
}
|
|
54
|
+
/** 条目首行里的日期;没有或不合法返回 null(`2026-99-99` 不猜成 12 月) */
|
|
55
|
+
export function entryDate(entry) {
|
|
56
|
+
const m = DATE.exec(firstLine(entry));
|
|
57
|
+
if (!m)
|
|
58
|
+
return null;
|
|
59
|
+
return validDate(m[1], m[2], m[3]) ? `${m[1]}-${m[2]}-${m[3]}` : null;
|
|
60
|
+
}
|
|
61
|
+
/**
|
|
62
|
+
* 去掉退役条目(整条,不留半行),返回正文与删掉的条数。
|
|
63
|
+
* 磁盘上的文件不动 —— 省略只发生在注入路径上;记忆页 / git 仍看得到它们。
|
|
64
|
+
*/
|
|
65
|
+
export function stripRetiredEntries(body) {
|
|
66
|
+
const out = [];
|
|
67
|
+
let count = 0;
|
|
68
|
+
let skipping = false;
|
|
69
|
+
for (const line of String(body ?? '').split('\n')) {
|
|
70
|
+
if (LIST_ITEM.test(line)) {
|
|
71
|
+
skipping = RETIRED.test(line);
|
|
72
|
+
if (skipping) {
|
|
73
|
+
count += 1;
|
|
74
|
+
continue;
|
|
75
|
+
}
|
|
76
|
+
out.push(line);
|
|
77
|
+
continue;
|
|
78
|
+
}
|
|
79
|
+
if (skipping) {
|
|
80
|
+
// 续行与紧随的空行跟着整条一起走:删条不留空洞
|
|
81
|
+
if (!line.trim() || /^\s+\S/.test(line))
|
|
82
|
+
continue;
|
|
83
|
+
skipping = false;
|
|
84
|
+
}
|
|
85
|
+
out.push(line);
|
|
86
|
+
}
|
|
87
|
+
return { body: out.join('\n').replace(/\n{3,}/g, '\n\n').trim(), count };
|
|
88
|
+
}
|
|
89
|
+
/**
|
|
90
|
+
* 距某天几个本地日历天(不是毫秒差 / 86400000 再取整 —— 夏时制会算出 6.958 天)。
|
|
91
|
+
* 日期不合法返回 null;未来日期返回负数(调用方自己决定怎么报)。
|
|
92
|
+
*/
|
|
93
|
+
export function daysSinceDate(date, now = new Date()) {
|
|
94
|
+
const m = /^(\d{4})-(\d{2})-(\d{2})$/.exec(String(date ?? '').trim());
|
|
95
|
+
if (!m || !validDate(m[1], m[2], m[3]))
|
|
96
|
+
return null;
|
|
97
|
+
const at = new Date(Number(m[1]), Number(m[2]) - 1, Number(m[3]));
|
|
98
|
+
const today = new Date(now.getFullYear(), now.getMonth(), now.getDate());
|
|
99
|
+
return Math.round((today.getTime() - at.getTime()) / 86_400_000);
|
|
100
|
+
}
|
package/dist/lib/memory.js
CHANGED
|
@@ -7,8 +7,9 @@
|
|
|
7
7
|
* · 预算按**总载荷**算,不是只卡 MEMORY.md;
|
|
8
8
|
* · 切分按三级降级:`##` 小节 → 顶层列表项 → 空行段落。只有 `##` 一级时,
|
|
9
9
|
* `# 记忆` + 要点列表(最常见的写法)一个小节都切不出来,预算会整个失效 —— 见 P0-1;
|
|
10
|
-
* · 截断顺序纯机械:先丢 MEMORY
|
|
11
|
-
*
|
|
10
|
+
* · 截断顺序纯机械:先丢 MEMORY 里**日期最旧**的一条(都没有日期才退回尾部整条),
|
|
11
|
+
* 再丢 USER 的尾部整段,最后各自只留首段;AGENTS.md 是硬规则,永不截断(单独超预算时只告警);
|
|
12
|
+
* · 退役条目(`- [superseded …]`)磁盘保留、注入省略 —— 它们按约定退役,不该继续占预算;
|
|
12
13
|
* · 丢掉的段落留一份**目录**(段落标题,计入预算),agent 用 zk_read 取回正文 ——
|
|
13
14
|
* 选哪段是 agent 按当前任务判断,插件只搬运目录,不猜相关性;
|
|
14
15
|
* · 中文按「1 词 / 2 字」计 —— 空白切分在中文上严重低估,预算会变成装饰。
|
|
@@ -22,6 +23,7 @@ import fs from 'node:fs';
|
|
|
22
23
|
import path from 'node:path';
|
|
23
24
|
import { DREAM_INTERVAL_DAYS, daysSinceDream, lastDreamDate } from './dream.js';
|
|
24
25
|
import { fileStamp } from './file-stamp.js';
|
|
26
|
+
import { entryDate, splitMemoryEntries, stripRetiredEntries } from './memory-format.js';
|
|
25
27
|
import { MEMORY_META_FILES } from './meta.js';
|
|
26
28
|
/** vault 根目录下、按优先级排列的三份 meta 文件(定义在 lib/meta.ts,这里只挂个本地名) */
|
|
27
29
|
export const META_FILES = MEMORY_META_FILES;
|
|
@@ -149,6 +151,25 @@ function firstSection(body) {
|
|
|
149
151
|
const split = splitSections(body);
|
|
150
152
|
return joinSections({ head: split.head, sections: split.sections.slice(0, 1), mode: split.mode });
|
|
151
153
|
}
|
|
154
|
+
/**
|
|
155
|
+
* 下一个该丢的条目:能解析出日期时选**最旧**的一条(同日期按位置靠后的先丢);
|
|
156
|
+
* 一条日期都解析不出来返回 null —— 调用方退回尾部丢,老库行为不变(D2.6)。
|
|
157
|
+
*
|
|
158
|
+
* 为什么按日期而不是位置:条目约定是「新结论写顶部」,但没人能保证每次都守;
|
|
159
|
+
* 按位置丢会把最新结论先删掉,而那正好是最该留的。
|
|
160
|
+
*/
|
|
161
|
+
function oldestIndex(split) {
|
|
162
|
+
let best = null;
|
|
163
|
+
for (const [index, section] of split.sections.entries()) {
|
|
164
|
+
const date = entryDate(section);
|
|
165
|
+
if (!date)
|
|
166
|
+
continue;
|
|
167
|
+
if (!best || date < best.date || (date === best.date && index > best.index)) {
|
|
168
|
+
best = { index, date };
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
return best?.index ?? null;
|
|
172
|
+
}
|
|
152
173
|
function sectionTitle(section, mode) {
|
|
153
174
|
const first = section.split('\n', 1)[0] ?? '';
|
|
154
175
|
const raw = mode === 'sections'
|
|
@@ -283,16 +304,26 @@ export function buildMemoryPayload(cfg) {
|
|
|
283
304
|
function computePayload(cfg) {
|
|
284
305
|
const budget = cfg.memoryBudgetWords;
|
|
285
306
|
const files = readMeta(cfg);
|
|
307
|
+
// 磁盘原文:files[].originalWords 与记忆页的对齐点,退役条目也算在里面
|
|
308
|
+
const diskWords = new Map(files.map((f) => [f.name, countWords(f.body)]));
|
|
286
309
|
const original = new Map(files.map((f) => [f.name, f.body]));
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
310
|
+
// 退役条目:磁盘保留、注入省略(D3)。先去掉,后面的截断只面对活条目。
|
|
311
|
+
const omitted = stripRetiredEntries(original.get('MEMORY.md') ?? '');
|
|
312
|
+
if (omitted.count > 0)
|
|
313
|
+
original.set('MEMORY.md', omitted.body);
|
|
314
|
+
// 去掉退役行之后的内容词数:用来算「截断了多少」,不把省略算成截断
|
|
315
|
+
const contentWords = new Map(files.map((f) => [f.name, countWords(original.get(f.name) ?? '')]));
|
|
316
|
+
// 截断会改写这份计数;contentWords 保留原值,给 truncatedWords 与 files 用
|
|
317
|
+
const words = new Map(contentWords);
|
|
290
318
|
const total = () => [...words.values()].reduce((a, b) => a + b, 0);
|
|
291
|
-
//
|
|
319
|
+
// 截断前的 MEMORY 正文:报告「有多少条没日期」要在丢之前数
|
|
320
|
+
const memorySource = original.get('MEMORY.md') ?? '';
|
|
321
|
+
// ── 机械截断:MEMORY 最旧条目 → USER 尾段 → 各留首段 ──────────────
|
|
292
322
|
// 丢掉的段落留一份目录(段落标题),让 agent 能按当前任务用 zk_read 取回。
|
|
293
323
|
// 目录自己也要占预算,所以每丢一段都把它算进去;目录有上限,循环一定收敛。
|
|
294
324
|
const dropped = [];
|
|
295
325
|
const tocCap = tocCapOf(budget);
|
|
326
|
+
let fellBack = false;
|
|
296
327
|
for (const name of ['MEMORY.md', 'USER.md']) {
|
|
297
328
|
if (total() + countWords(tocText(dropped, tocCap)) <= budget)
|
|
298
329
|
break;
|
|
@@ -300,12 +331,23 @@ function computePayload(cfg) {
|
|
|
300
331
|
const mine = [];
|
|
301
332
|
const over = () => total() + countWords(tocText([...dropped, ...mine], tocCap)) > budget;
|
|
302
333
|
while (over() && split.sections.length > 1) {
|
|
303
|
-
|
|
304
|
-
|
|
334
|
+
// MEMORY 按「最旧日期」丢;解析不出日期(或这是 USER)就退回尾部,行为与 0.8.3 一致
|
|
335
|
+
let index = split.sections.length - 1;
|
|
336
|
+
if (name === 'MEMORY.md') {
|
|
337
|
+
const oldest = oldestIndex(split);
|
|
338
|
+
if (oldest === null)
|
|
339
|
+
fellBack = true;
|
|
340
|
+
else
|
|
341
|
+
index = oldest;
|
|
342
|
+
}
|
|
343
|
+
const section = split.sections.splice(index, 1)[0];
|
|
344
|
+
mine.push({ name, title: sectionTitle(section, split.mode), order: index });
|
|
305
345
|
const body = joinSections(split);
|
|
306
346
|
original.set(name, body);
|
|
307
347
|
words.set(name, countWords(body));
|
|
308
348
|
}
|
|
349
|
+
// 按原文件位置重建目录,而不是按丢弃顺序 —— 目录要能对上文件
|
|
350
|
+
mine.sort((a, b) => (a.order ?? 0) - (b.order ?? 0));
|
|
309
351
|
dropped.push(...mine);
|
|
310
352
|
}
|
|
311
353
|
if (total() + countWords(tocText(dropped, tocCap)) > budget) {
|
|
@@ -321,15 +363,26 @@ function computePayload(cfg) {
|
|
|
321
363
|
const present = files.filter((f) => (original.get(f.name) ?? '').length > 0);
|
|
322
364
|
const bodies = present.map((f) => `## ${f.name}\n\n${escapeFrame(original.get(f.name) ?? '')}`);
|
|
323
365
|
const keptWords = total();
|
|
324
|
-
|
|
325
|
-
const
|
|
366
|
+
// 退役条目不算截断:它按约定退役,不是被预算挤掉的
|
|
367
|
+
const omittedNote = omitted.count > 0 ? `已省略 ${omitted.count} 条退役条目(见 MEMORY.md)` : '';
|
|
368
|
+
// 这条提示本身也要吃饭(D3.2):不把它算进 words,报出来的用量就会少一截
|
|
369
|
+
let finalWords = keptWords + countWords(toc) + countWords(omittedNote);
|
|
370
|
+
const contentSum = files.reduce((sum, f) => sum + (contentWords.get(f.name) ?? 0), 0);
|
|
326
371
|
// 报「正文被截掉多少」,不是净减少:目录也会占词,混在一起会让人以为没丢多少
|
|
327
|
-
const truncatedWords = Math.max(0,
|
|
372
|
+
const truncatedWords = Math.max(0, contentSum - keptWords);
|
|
328
373
|
let text = '';
|
|
329
374
|
if (bodies.length > 0) {
|
|
330
375
|
const notes = [];
|
|
331
376
|
if (truncatedWords > 0)
|
|
332
377
|
notes.push(`已截断 ${truncatedWords} 词`);
|
|
378
|
+
if (omittedNote)
|
|
379
|
+
notes.push(omittedNote);
|
|
380
|
+
// 一条日期都没有只能按位置丢:说出来,别让人以为是按日期挑的(D2.5)
|
|
381
|
+
if (fellBack && truncatedWords > 0) {
|
|
382
|
+
const undated = splitMemoryEntries(memorySource).filter((entry) => !entryDate(entry)).length;
|
|
383
|
+
if (undated > 0)
|
|
384
|
+
notes.push(`MEMORY 有 ${undated} 条没日期,只能按位置丢`);
|
|
385
|
+
}
|
|
333
386
|
// 目录放不下时至少留一句指路;否则被丢掉的段落对模型完全不可见
|
|
334
387
|
if (!toc && dropped.length > 0) {
|
|
335
388
|
const names = [...new Set(dropped.map((d) => d.name))];
|
|
@@ -390,8 +443,23 @@ function computePayload(cfg) {
|
|
|
390
443
|
name: f.name,
|
|
391
444
|
present: f.body.length > 0,
|
|
392
445
|
words: words.get(f.name) ?? 0,
|
|
393
|
-
// files[].body 始终是原文件内容(截断只改 original
|
|
394
|
-
originalWords:
|
|
446
|
+
// files[].body 始终是原文件内容(截断只改 original 副本);退役条目也算在原文里
|
|
447
|
+
originalWords: diskWords.get(f.name) ?? 0,
|
|
395
448
|
})),
|
|
396
449
|
};
|
|
397
450
|
}
|
|
451
|
+
/**
|
|
452
|
+
* 记忆用量(D4)。只是 `buildMemoryPayload` 的投影 —— 不重读、不重算,
|
|
453
|
+
* 否则就是第三个计数口径,doctor / 设置页 / dream 三处迟早对不上。
|
|
454
|
+
*/
|
|
455
|
+
export function memoryUsage(cfg) {
|
|
456
|
+
const payload = buildMemoryPayload(cfg);
|
|
457
|
+
const totalWords = countWords(payload.text);
|
|
458
|
+
return {
|
|
459
|
+
words: payload.words,
|
|
460
|
+
totalWords,
|
|
461
|
+
budget: payload.budget,
|
|
462
|
+
headroom: payload.budget - totalWords,
|
|
463
|
+
files: payload.files,
|
|
464
|
+
};
|
|
465
|
+
}
|