@jjh32456/longlive 2.2.0 → 2.3.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/CHANGELOG.md +79 -0
- package/QUICKSTART.md +7 -7
- package/README.en.md +13 -1
- package/README.md +26 -8
- package/SPEC.md +6 -5
- package/build-info.json +132 -67
- package/cordis.patch.yml +1 -0
- package/docs/ARCHITECTURE.md +6 -3
- package/docs/CONFIG.md +25 -1
- package/docs/FAQ.md +2 -2
- package/docs/FEATURES.md +104 -2
- package/docs/INDEX-FRESHNESS.md +8 -1
- package/docs/OPERATIONS.md +63 -2
- package/docs/QUICKSTART.md +2 -2
- package/docs/README.en.md +1 -1
- package/docs/TROUBLESHOOTING.md +1 -1
- package/package.json +10 -2
- package/scripts/assert-install.mjs +124 -0
- package/scripts/backlog-report.mjs +98 -0
- package/scripts/install-230.mjs +787 -0
- package/scripts/lib/eng-common.mjs +428 -0
- package/scripts/rebuild-index.mjs +148 -0
- package/scripts/restore-drill.mjs +351 -0
- package/scripts/run-autoresolve.mjs +123 -0
- package/scripts/watchdog-230.mjs +379 -0
- package/src/features.js +14 -0
- package/src/gate/action-gate.js +234 -45
- package/src/memory/backup-retention.mjs +823 -0
- package/src/memory/cards.js +73 -12
- package/src/memory/conflict-scan.mjs +356 -0
- package/src/memory/conflicts.js +202 -9
- package/src/memory/consolidate.js +100 -13
- package/src/memory/decay.js +133 -19
- package/src/memory/event-index.js +62 -4
- package/src/memory/forget-scheduler.mjs +303 -0
- package/src/memory/forget-v2.js +94 -8
- package/src/memory/index-cache.mjs +216 -0
- package/src/memory/index.js +149 -15
- package/src/memory/lock.js +53 -12
- package/src/memory/maintenance.js +172 -17
- package/src/memory/recall-feedback.mjs +159 -17
- package/src/memory/state.js +446 -38
- package/src/memory/task-state.mjs +569 -0
- package/src/recall/brain.mjs +8 -1
- package/src/recall/continuity-volatile.mjs +131 -1
- package/src/tools.js +108 -33
- package/src/ui/routes-readonly.js +63 -5
package/src/memory/forget-v2.js
CHANGED
|
@@ -40,17 +40,26 @@ export function isPureNoisePath(relPath) {
|
|
|
40
40
|
}
|
|
41
41
|
|
|
42
42
|
/**
|
|
43
|
-
* 选择性遗忘评分(D13 唯一公式源):score = salience*
|
|
43
|
+
* 选择性遗忘评分(D13 唯一公式源):score = salience*salienceWeight + strength*strengthWeight
|
|
44
|
+
* + recencyWindowDays/(recencyWindowDays+ageDays)。默认权重 (2,1,30) 与 D13 原公式逐字节等价。
|
|
44
45
|
*
|
|
45
46
|
* 原始分、全程不四舍五入;参数缺失/非法返回 null(绝不返回 0 冒充有效分)。
|
|
46
|
-
*
|
|
47
|
+
* 阈值比较一律用本函数原始返回值,展示层才允许 toFixed(2)。
|
|
48
|
+
* 2.3.0 W2.3:policy 可选(raw passthrough,见 normalizeForgetScorePolicy),不传时行为不变。
|
|
47
49
|
*/
|
|
48
|
-
export function score({ salience, strength, ageDays } = {}) {
|
|
50
|
+
export function score({ salience, strength, ageDays } = {}, policy = null) {
|
|
49
51
|
const s = Number(salience);
|
|
50
52
|
const t = Number(strength);
|
|
51
53
|
const a = Number(ageDays);
|
|
52
54
|
if (!Number.isFinite(s) || !Number.isFinite(t) || !Number.isFinite(a) || a < 0) return null;
|
|
53
|
-
|
|
55
|
+
const weights = policy && typeof policy === 'object' ? policy : {};
|
|
56
|
+
const salienceWeight = Number(weights.salienceWeight ?? 2);
|
|
57
|
+
const strengthWeight = Number(weights.strengthWeight ?? 1);
|
|
58
|
+
const recencyWindowDays = Number(weights.recencyWindowDays ?? 30);
|
|
59
|
+
const safeSalienceWeight = Number.isFinite(salienceWeight) ? salienceWeight : 2;
|
|
60
|
+
const safeStrengthWeight = Number.isFinite(strengthWeight) ? strengthWeight : 1;
|
|
61
|
+
const safeRecencyWindow = Number.isFinite(recencyWindowDays) && recencyWindowDays > 0 ? recencyWindowDays : 30;
|
|
62
|
+
return s * safeSalienceWeight + t * safeStrengthWeight + safeRecencyWindow / (safeRecencyWindow + a);
|
|
54
63
|
}
|
|
55
64
|
|
|
56
65
|
/** 计划 §4② 术语里的别名;两个名字指向同一实现。 */
|
|
@@ -65,6 +74,71 @@ export const SUGGESTION_AGE_DAYS_MIN = 30;
|
|
|
65
74
|
export const SUGGESTION_SALIENCE_BELOW = 4;
|
|
66
75
|
export const SUGGESTION_GATE_EVENT = 'hg.d13.fail';
|
|
67
76
|
|
|
77
|
+
/**
|
|
78
|
+
* 2.3.0 W2.3:遗忘评分策略默认值(可见;公式与阈值都在返回值里暴露)。
|
|
79
|
+
* 与上面的 D13 常量逐项一致——不配置时行为与 2.2.x 完全相同。
|
|
80
|
+
*/
|
|
81
|
+
export const FORGET_SCORE_FORMULA =
|
|
82
|
+
'score = salience * salienceWeight + strength * strengthWeight + recencyWindowDays / (recencyWindowDays + ageDays);原始分不四舍五入,非法参数返回 null';
|
|
83
|
+
export const FORGET_SCORE_POLICY = Object.freeze({
|
|
84
|
+
salienceWeight: 2,
|
|
85
|
+
strengthWeight: 1,
|
|
86
|
+
recencyWindowDays: 30,
|
|
87
|
+
threshold: SCORE_THRESHOLD,
|
|
88
|
+
ageDaysMin: SUGGESTION_AGE_DAYS_MIN,
|
|
89
|
+
salienceBelow: SUGGESTION_SALIENCE_BELOW,
|
|
90
|
+
maxItems: SUGGESTION_MAX_ITEMS,
|
|
91
|
+
retentionDays: SUGGESTION_RETENTION_DAYS,
|
|
92
|
+
formula: FORGET_SCORE_FORMULA,
|
|
93
|
+
});
|
|
94
|
+
export const FORGET_SCORE_LIMITS = Object.freeze({
|
|
95
|
+
salienceWeight: Object.freeze({ min: 0, max: 10 }),
|
|
96
|
+
strengthWeight: Object.freeze({ min: 0, max: 10 }),
|
|
97
|
+
recencyWindowDays: Object.freeze({ min: 1, max: 3650 }),
|
|
98
|
+
threshold: Object.freeze({ min: 0, max: 100 }),
|
|
99
|
+
ageDaysMin: Object.freeze({ min: 0, max: 36500 }),
|
|
100
|
+
salienceBelow: Object.freeze({ min: 0, max: 10 }),
|
|
101
|
+
});
|
|
102
|
+
|
|
103
|
+
function clampNumber(value, fallback, range, integer = false) {
|
|
104
|
+
const number = Number(value);
|
|
105
|
+
if (!Number.isFinite(number)) return fallback;
|
|
106
|
+
const bounded = Math.min(range.max, Math.max(range.min, number));
|
|
107
|
+
return integer ? Math.round(bounded) : bounded;
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
/**
|
|
111
|
+
* 2.3.0 W2.3:把 raw config 的遗忘评分策略归一化(整块 passthrough,不新增 schemastery 叶子)。
|
|
112
|
+
* 只读 `config.forgetV2` / `config.autoMaintenance.forgetV2`;越界/非法值 clamp 回默认,不抛错。
|
|
113
|
+
*/
|
|
114
|
+
export function normalizeForgetScorePolicy(raw = {}) {
|
|
115
|
+
const source = raw && typeof raw === 'object' && !Array.isArray(raw) ? raw : {};
|
|
116
|
+
return Object.freeze({
|
|
117
|
+
salienceWeight: clampNumber(source.salienceWeight, FORGET_SCORE_POLICY.salienceWeight, FORGET_SCORE_LIMITS.salienceWeight, true),
|
|
118
|
+
strengthWeight: clampNumber(source.strengthWeight, FORGET_SCORE_POLICY.strengthWeight, FORGET_SCORE_LIMITS.strengthWeight, true),
|
|
119
|
+
recencyWindowDays: clampNumber(source.recencyWindowDays, FORGET_SCORE_POLICY.recencyWindowDays, FORGET_SCORE_LIMITS.recencyWindowDays, true),
|
|
120
|
+
threshold: clampNumber(source.threshold, FORGET_SCORE_POLICY.threshold, FORGET_SCORE_LIMITS.threshold),
|
|
121
|
+
ageDaysMin: clampNumber(source.ageDaysMin, FORGET_SCORE_POLICY.ageDaysMin, FORGET_SCORE_LIMITS.ageDaysMin, true),
|
|
122
|
+
salienceBelow: clampNumber(source.salienceBelow, FORGET_SCORE_POLICY.salienceBelow, FORGET_SCORE_LIMITS.salienceBelow, true),
|
|
123
|
+
maxItems: FORGET_SCORE_POLICY.maxItems,
|
|
124
|
+
retentionDays: FORGET_SCORE_POLICY.retentionDays,
|
|
125
|
+
formula: FORGET_SCORE_FORMULA,
|
|
126
|
+
});
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
/** config → 遗忘评分 policy;source 供报告/回执核对(default / config.forgetV2 / autoMaintenance.forgetV2)。 */
|
|
130
|
+
export function forgetScorePolicyFromConfig(config = {}) {
|
|
131
|
+
const top = config?.forgetV2;
|
|
132
|
+
if (top && typeof top === 'object' && !Array.isArray(top)) {
|
|
133
|
+
return Object.freeze({ ...normalizeForgetScorePolicy(top), source: 'config.forgetV2' });
|
|
134
|
+
}
|
|
135
|
+
const nested = config?.autoMaintenance?.forgetV2;
|
|
136
|
+
if (nested && typeof nested === 'object' && !Array.isArray(nested)) {
|
|
137
|
+
return Object.freeze({ ...normalizeForgetScorePolicy(nested), source: 'autoMaintenance.forgetV2' });
|
|
138
|
+
}
|
|
139
|
+
return Object.freeze({ ...FORGET_SCORE_POLICY, source: 'default' });
|
|
140
|
+
}
|
|
141
|
+
|
|
68
142
|
const DAY_MS = 24 * 60 * 60 * 1000;
|
|
69
143
|
|
|
70
144
|
function gateFail(root, code, message, extra = {}) {
|
|
@@ -203,6 +277,8 @@ export function proposeForget(args = {}, config = {}) {
|
|
|
203
277
|
? config.now
|
|
204
278
|
: new Date(config.now ?? args.now ?? Date.now());
|
|
205
279
|
const todayDay = isDayString(config.today) ? config.today : dayString(at);
|
|
280
|
+
// 2.3.0 W2.3:评分策略 raw passthrough(默认 = D13 常量,不配置时行为不变)。
|
|
281
|
+
const scorePolicy = forgetScorePolicyFromConfig(config);
|
|
206
282
|
|
|
207
283
|
let cards;
|
|
208
284
|
try {
|
|
@@ -248,12 +324,12 @@ export function proposeForget(args = {}, config = {}) {
|
|
|
248
324
|
missingMeta += 1;
|
|
249
325
|
continue;
|
|
250
326
|
}
|
|
251
|
-
const value = score({ salience: meta.salience, strength: meta.strength, ageDays });
|
|
327
|
+
const value = score({ salience: meta.salience, strength: meta.strength, ageDays }, scorePolicy);
|
|
252
328
|
if (value == null) {
|
|
253
329
|
missingMeta += 1;
|
|
254
330
|
continue;
|
|
255
331
|
}
|
|
256
|
-
if (!(value <
|
|
332
|
+
if (!(value < scorePolicy.threshold && meta.salience < scorePolicy.salienceBelow && ageDays > scorePolicy.ageDaysMin)) {
|
|
257
333
|
skipped += 1;
|
|
258
334
|
continue;
|
|
259
335
|
}
|
|
@@ -261,7 +337,7 @@ export function proposeForget(args = {}, config = {}) {
|
|
|
261
337
|
schema: FORGET_SUGGESTIONS_SCHEMA,
|
|
262
338
|
rel: card.rel,
|
|
263
339
|
score: value,
|
|
264
|
-
threshold:
|
|
340
|
+
threshold: scorePolicy.threshold,
|
|
265
341
|
salience: meta.salience,
|
|
266
342
|
strength: meta.strength,
|
|
267
343
|
ageDays,
|
|
@@ -292,7 +368,17 @@ export function proposeForget(args = {}, config = {}) {
|
|
|
292
368
|
return {
|
|
293
369
|
...base,
|
|
294
370
|
autoApply: false,
|
|
295
|
-
scoreThreshold:
|
|
371
|
+
scoreThreshold: scorePolicy.threshold,
|
|
372
|
+
scorePolicy: {
|
|
373
|
+
source: scorePolicy.source,
|
|
374
|
+
salienceWeight: scorePolicy.salienceWeight,
|
|
375
|
+
strengthWeight: scorePolicy.strengthWeight,
|
|
376
|
+
recencyWindowDays: scorePolicy.recencyWindowDays,
|
|
377
|
+
threshold: scorePolicy.threshold,
|
|
378
|
+
ageDaysMin: scorePolicy.ageDaysMin,
|
|
379
|
+
salienceBelow: scorePolicy.salienceBelow,
|
|
380
|
+
formula: scorePolicy.formula,
|
|
381
|
+
},
|
|
296
382
|
scanned: cards.length,
|
|
297
383
|
missingMeta,
|
|
298
384
|
immune,
|
|
@@ -0,0 +1,216 @@
|
|
|
1
|
+
// src/memory/index-cache.mjs — INDEX 重建缓存(2.3.0 W3 索引 lane)。
|
|
2
|
+
//
|
|
3
|
+
// 这一层只服务于「索引重建」:它不读原曲、不写卡片、不改 INDEX.md 的格式,
|
|
4
|
+
// 只把上一次重建的扫描结果(每张卡的 row 与文件签名)落到
|
|
5
|
+
// `<memoryRoot>/.longlive/index/index-cache.json`,下一次重建据此跳过没变化的
|
|
6
|
+
// 文件。四个刻意分开的设计点,对应 RT 审计里的四类索引缺陷:
|
|
7
|
+
//
|
|
8
|
+
// ① 声明文件(declared files):缓存里每一轮声明过的卡文件,下一轮重建必须
|
|
9
|
+
// 用 fileExists 复核它是否还在 —— 删掉的卡不能靠缓存留幽灵行;新出现的
|
|
10
|
+
// 卡(journal 追加、topics 新增)必须整份读入,不能被缓存挡掉。
|
|
11
|
+
// ② mtime 预筛:签名 = mtimeMs + ctimeMs + size。只比 mtime/size 会漏掉
|
|
12
|
+
// “同长度原地改写 + utimes 还原 mtime”的卡,所以 ctime 也进签名;未变化
|
|
13
|
+
// 的文件不再 open/read/parse,只有变化的那几个被读。
|
|
14
|
+
// ③ chunk 级时间戳:每张卡(chunk)记录自己的真实 mtime(chunkAtMs),
|
|
15
|
+
// dataThroughAt 取这些 chunk mtime 的最大值 —— 不是“这一轮扫描开始的
|
|
16
|
+
// 时间”,也不是 INDEX.md 自己的文件级时间。
|
|
17
|
+
// ④ 统一 getHash:页面自算 hash、缓存 key、state 里记录的 indexHash 全部走
|
|
18
|
+
// 同一个规范化函数(CRLF→LF 后 sha256),避免两套哈希口径对不上。
|
|
19
|
+
//
|
|
20
|
+
// 隐私:缓存只存 INDEX 行本身已有的字段(标题/一句话/路径/salience/strength/
|
|
21
|
+
// status/last_used)与文件签名,不存正文、不存绝对路径、不存本机私有串;
|
|
22
|
+
// local_only 卡的 summary 已经是 <hidden>,进缓存也不会泄露正文。
|
|
23
|
+
|
|
24
|
+
import crypto from 'node:crypto';
|
|
25
|
+
import fs from 'node:fs';
|
|
26
|
+
import path from 'node:path';
|
|
27
|
+
|
|
28
|
+
import { relativePath } from './paths.js';
|
|
29
|
+
|
|
30
|
+
export const INDEX_CACHE_SCHEMA = 'index-cache/v1';
|
|
31
|
+
export const INDEX_CACHE_DIR_PARTS = Object.freeze(['.longlive', 'index']);
|
|
32
|
+
export const INDEX_CACHE_FILE = 'index-cache.json';
|
|
33
|
+
|
|
34
|
+
/** 统一文本规范化:CRLF/CR → LF。所有哈希都先过这一个函数。 */
|
|
35
|
+
export function normalizeIndexText(text) {
|
|
36
|
+
return String(text ?? '').replace(/\r\n?/gu, '\n');
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/** 唯一哈希入口:页面自算 hash 与缓存/state 记录必须都用它。 */
|
|
40
|
+
export function getHash(text) {
|
|
41
|
+
return crypto.createHash('sha256').update(normalizeIndexText(text), 'utf8').digest('hex');
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
export function indexCachePath(root) {
|
|
45
|
+
return path.join(path.resolve(String(root ?? '')), ...INDEX_CACHE_DIR_PARTS, INDEX_CACHE_FILE);
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/** 声明文件存在性检查:存在且是普通文件才算。 */
|
|
49
|
+
export function fileExists(file) {
|
|
50
|
+
try {
|
|
51
|
+
return fs.statSync(file).isFile();
|
|
52
|
+
} catch {
|
|
53
|
+
return false;
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/**
|
|
58
|
+
* 文件签名:mtime + ctime + size。
|
|
59
|
+
* ctime 用来抓“同长度 + 同 mtime”的改写(utimes 会改 ctime,改不了 ctime)。
|
|
60
|
+
*/
|
|
61
|
+
export function fileSignature(abs) {
|
|
62
|
+
const stat = fs.statSync(abs);
|
|
63
|
+
return { mtimeMs: stat.mtimeMs, ctimeMs: stat.ctimeMs, size: stat.size };
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
function emptyCache(file) {
|
|
67
|
+
return {
|
|
68
|
+
schema: INDEX_CACHE_SCHEMA,
|
|
69
|
+
entries: {},
|
|
70
|
+
file,
|
|
71
|
+
};
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/** 读缓存:缺失/坏文件都降级成空缓存(不抛),并标 corrupt 让调用端记账。 */
|
|
75
|
+
export function loadIndexCache(root) {
|
|
76
|
+
const file = indexCachePath(root);
|
|
77
|
+
let raw = '';
|
|
78
|
+
try {
|
|
79
|
+
raw = fs.readFileSync(file, 'utf8');
|
|
80
|
+
} catch {
|
|
81
|
+
return { ...emptyCache(file), ok: true, missing: true, corrupt: false };
|
|
82
|
+
}
|
|
83
|
+
try {
|
|
84
|
+
const parsed = JSON.parse(raw);
|
|
85
|
+
if (parsed?.schema !== INDEX_CACHE_SCHEMA || parsed.entries === null || typeof parsed.entries !== 'object') {
|
|
86
|
+
return { ...emptyCache(file), ok: false, missing: false, corrupt: true };
|
|
87
|
+
}
|
|
88
|
+
return {
|
|
89
|
+
schema: INDEX_CACHE_SCHEMA,
|
|
90
|
+
entries: parsed.entries,
|
|
91
|
+
file,
|
|
92
|
+
ok: true,
|
|
93
|
+
missing: false,
|
|
94
|
+
corrupt: false,
|
|
95
|
+
builtAt: typeof parsed.builtAt === 'string' ? parsed.builtAt : null,
|
|
96
|
+
};
|
|
97
|
+
} catch {
|
|
98
|
+
return { ...emptyCache(file), ok: false, missing: false, corrupt: true };
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
/**
|
|
103
|
+
* 写缓存:tmp + rename(崩溃时要么旧内容要么新内容,不会半截)。
|
|
104
|
+
* 返回 {file, bytes};失败抛错,由调用端决定是降级还是失败(当前降级)。
|
|
105
|
+
*/
|
|
106
|
+
export function saveIndexCache(root, cache) {
|
|
107
|
+
const file = indexCachePath(root);
|
|
108
|
+
const payload = `${JSON.stringify({
|
|
109
|
+
schema: INDEX_CACHE_SCHEMA,
|
|
110
|
+
builtAt: typeof cache?.builtAt === 'string' ? cache.builtAt : new Date().toISOString(),
|
|
111
|
+
entries: cache?.entries ?? {},
|
|
112
|
+
})}\n`;
|
|
113
|
+
fs.mkdirSync(path.dirname(file), { recursive: true });
|
|
114
|
+
const tmp = `${file}.tmp-${process.pid}-${Date.now()}`;
|
|
115
|
+
try {
|
|
116
|
+
fs.writeFileSync(tmp, payload, 'utf8');
|
|
117
|
+
const staged = fs.readFileSync(tmp, 'utf8');
|
|
118
|
+
if (staged !== payload) throw new Error(`index-cache 写入校验失败:${tmp}`);
|
|
119
|
+
fs.renameSync(tmp, file);
|
|
120
|
+
} catch (error) {
|
|
121
|
+
try {
|
|
122
|
+
if (fs.existsSync(tmp)) fs.unlinkSync(tmp);
|
|
123
|
+
} catch { /* 尽力清理,重要的是把原错误抛回去 */ }
|
|
124
|
+
throw error;
|
|
125
|
+
}
|
|
126
|
+
return { file, bytes: Buffer.byteLength(payload) };
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
function toRel(root, abs) {
|
|
130
|
+
return relativePath(root, abs).replace(/\\/g, '/');
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
/**
|
|
134
|
+
* 扫描计划:把「要扫的文件列表」和上一轮缓存对比,分出
|
|
135
|
+
* read —— 签名变了 / 新文件 / full 重建,必须真读
|
|
136
|
+
* reused —— 签名没变,直接复用缓存里的 row
|
|
137
|
+
* removed —— 上一轮声明过、这一轮文件确实不在了(fileExists 复核)
|
|
138
|
+
* dataThroughMs —— 本轮能证明看到的最新 chunk mtime
|
|
139
|
+
*/
|
|
140
|
+
export function planIndexScan({ root = '', files = [], cache = null, full = false } = {}) {
|
|
141
|
+
const entries = cache && typeof cache.entries === 'object' && cache.entries !== null ? cache.entries : {};
|
|
142
|
+
const nextEntries = {};
|
|
143
|
+
const read = [];
|
|
144
|
+
const reused = [];
|
|
145
|
+
const removed = [];
|
|
146
|
+
const seen = new Set();
|
|
147
|
+
let dataThroughMs = 0;
|
|
148
|
+
for (const abs of Array.isArray(files) ? files : []) {
|
|
149
|
+
const rel = toRel(root, abs);
|
|
150
|
+
seen.add(rel);
|
|
151
|
+
let signature;
|
|
152
|
+
try {
|
|
153
|
+
signature = fileSignature(abs);
|
|
154
|
+
} catch {
|
|
155
|
+
// 读不到签名的文件不声明:下一轮它会以“新文件”身份重试,而不是留幽灵。
|
|
156
|
+
continue;
|
|
157
|
+
}
|
|
158
|
+
const previous = full ? null : entries[rel];
|
|
159
|
+
const unchanged = previous !== null
|
|
160
|
+
&& typeof previous === 'object'
|
|
161
|
+
&& previous.mtimeMs === signature.mtimeMs
|
|
162
|
+
&& previous.ctimeMs === signature.ctimeMs
|
|
163
|
+
&& previous.size === signature.size
|
|
164
|
+
&& previous.row !== null
|
|
165
|
+
&& typeof previous.row === 'object';
|
|
166
|
+
if (unchanged) {
|
|
167
|
+
reused.push(rel);
|
|
168
|
+
nextEntries[rel] = { ...previous, chunkAtMs: signature.mtimeMs };
|
|
169
|
+
dataThroughMs = Math.max(dataThroughMs, signature.mtimeMs);
|
|
170
|
+
} else {
|
|
171
|
+
read.push({ rel, abs, signature });
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
// ① 声明文件复核:上一轮声明过、这一轮没扫到的,先用 fileExists 确认是否真没了。
|
|
175
|
+
for (const rel of Object.keys(entries)) {
|
|
176
|
+
if (seen.has(rel)) continue;
|
|
177
|
+
const abs = path.join(path.resolve(String(root ?? '')), ...rel.split('/'));
|
|
178
|
+
if (fileExists(abs)) continue; // 文件还在,只是被 dirs 过滤掉(如 archive/)——不算删除
|
|
179
|
+
removed.push(rel);
|
|
180
|
+
}
|
|
181
|
+
return { entries: nextEntries, read, reused, removed, dataThroughMs, full: full === true, relOf: toRel };
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
/**
|
|
185
|
+
* 缓存行 ↔ 卡片最小投影:只保留 buildGeneratedSection 排序与出表要用的字段。
|
|
186
|
+
* 正文(body)刻意不进缓存 —— 缓存不是第二份记忆。
|
|
187
|
+
*/
|
|
188
|
+
export function cardToCacheRow(card) {
|
|
189
|
+
return {
|
|
190
|
+
rel: card.rel,
|
|
191
|
+
title: card.title,
|
|
192
|
+
summary: card.summary,
|
|
193
|
+
legacy: card.legacy === true,
|
|
194
|
+
salience: card.fields?.salience,
|
|
195
|
+
strength: card.fields?.strength,
|
|
196
|
+
status: card.fields?.status,
|
|
197
|
+
lastUsed: card.fields?.last_used ?? '',
|
|
198
|
+
};
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
/** 把缓存行还原成 buildGeneratedSection 能吃的卡片形状。 */
|
|
202
|
+
export function cacheRowToCard(row) {
|
|
203
|
+
return {
|
|
204
|
+
rel: row.rel,
|
|
205
|
+
title: row.title,
|
|
206
|
+
summary: row.summary,
|
|
207
|
+
legacy: row.legacy === true,
|
|
208
|
+
fields: {
|
|
209
|
+
salience: row.salience,
|
|
210
|
+
strength: row.strength,
|
|
211
|
+
status: row.status,
|
|
212
|
+
last_used: row.lastUsed ?? '',
|
|
213
|
+
},
|
|
214
|
+
procedure: false,
|
|
215
|
+
};
|
|
216
|
+
}
|
package/src/memory/index.js
CHANGED
|
@@ -22,6 +22,14 @@ import {
|
|
|
22
22
|
} from './state.js';
|
|
23
23
|
import { PROCEDURES_DIR, scanProcedures } from './procedure.js';
|
|
24
24
|
import { getIndexFreshness } from './index-freshness.js';
|
|
25
|
+
import {
|
|
26
|
+
cacheRowToCard,
|
|
27
|
+
cardToCacheRow,
|
|
28
|
+
getHash,
|
|
29
|
+
loadIndexCache,
|
|
30
|
+
planIndexScan,
|
|
31
|
+
saveIndexCache,
|
|
32
|
+
} from './index-cache.mjs';
|
|
25
33
|
|
|
26
34
|
export const BEGIN_GENERATED = '<!-- BEGIN GENERATED -->';
|
|
27
35
|
export const END_GENERATED = '<!-- END GENERATED -->';
|
|
@@ -215,25 +223,80 @@ function shouldSkipScanRel(rel) {
|
|
|
215
223
|
return false;
|
|
216
224
|
}
|
|
217
225
|
|
|
218
|
-
/**
|
|
219
|
-
export function
|
|
220
|
-
const
|
|
221
|
-
const
|
|
222
|
-
for (const dir of
|
|
226
|
+
/** 扫描面文件清单(abs):topics/(含 topics/auto/)与 journal/,archive 除外。 */
|
|
227
|
+
export function scanFileList(root, dirs = SCAN_DIRS) {
|
|
228
|
+
const out = [];
|
|
229
|
+
const list = Array.isArray(dirs) && dirs.length > 0 ? dirs : SCAN_DIRS;
|
|
230
|
+
for (const dir of list) {
|
|
223
231
|
for (const abs of listMarkdownFiles(root, dir)) {
|
|
224
232
|
const rel = relativePath(root, abs);
|
|
225
233
|
if (shouldSkipScanRel(rel)) continue;
|
|
226
|
-
|
|
234
|
+
out.push(abs);
|
|
227
235
|
}
|
|
228
236
|
}
|
|
229
|
-
|
|
237
|
+
return out;
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
function sortCards(cards) {
|
|
241
|
+
return cards.sort((left, right) => {
|
|
230
242
|
if (right.fields.salience !== left.fields.salience) return right.fields.salience - left.fields.salience;
|
|
231
243
|
const leftUsed = left.fields.last_used ?? '';
|
|
232
244
|
const rightUsed = right.fields.last_used ?? '';
|
|
233
245
|
if (rightUsed !== leftUsed) return rightUsed.localeCompare(leftUsed);
|
|
234
246
|
return left.rel.localeCompare(right.rel);
|
|
235
247
|
});
|
|
236
|
-
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
/** All cards under `topics/` (incl. `topics/auto/`) and `journal/`, archive excluded. */
|
|
251
|
+
export function scanCards(root, options = {}) {
|
|
252
|
+
const cards = scanFileList(root, options?.dirs).map((abs) => readCard(root, abs));
|
|
253
|
+
return sortCards(cards);
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
/**
|
|
257
|
+
* mtime 预筛版扫描:未变化的卡直接用缓存里的行,不 open / 不 read / 不解析。
|
|
258
|
+
* 返回 {cards, stats, entries, dataThroughMs};stats 让调用端(和测试)能看到
|
|
259
|
+
* 这一轮到底读了几张、复用了几张、删掉几张。
|
|
260
|
+
*/
|
|
261
|
+
export function scanCardsWithCache(root, options = {}) {
|
|
262
|
+
const dirs = Array.isArray(options?.dirs) && options.dirs.length > 0 ? options.dirs : SCAN_DIRS;
|
|
263
|
+
const full = options?.full === true;
|
|
264
|
+
const cache = options?.cache === null ? null : (options?.cache ?? loadIndexCache(root));
|
|
265
|
+
const files = scanFileList(root, dirs);
|
|
266
|
+
const plan = planIndexScan({ root, files, cache, full });
|
|
267
|
+
const cards = [];
|
|
268
|
+
for (const item of plan.read) {
|
|
269
|
+
const card = readCard(root, item.abs);
|
|
270
|
+
cards.push(card);
|
|
271
|
+
plan.entries[item.rel] = {
|
|
272
|
+
mtimeMs: item.signature.mtimeMs,
|
|
273
|
+
ctimeMs: item.signature.ctimeMs,
|
|
274
|
+
size: item.signature.size,
|
|
275
|
+
chunkAtMs: item.signature.mtimeMs,
|
|
276
|
+
row: cardToCacheRow(card),
|
|
277
|
+
};
|
|
278
|
+
plan.dataThroughMs = Math.max(plan.dataThroughMs, item.signature.mtimeMs);
|
|
279
|
+
}
|
|
280
|
+
for (const rel of plan.reused) {
|
|
281
|
+
const entry = plan.entries[rel];
|
|
282
|
+
if (!entry || !entry.row) continue;
|
|
283
|
+
cards.push(cacheRowToCard(entry.row));
|
|
284
|
+
}
|
|
285
|
+
return {
|
|
286
|
+
cards: sortCards(cards),
|
|
287
|
+
entries: plan.entries,
|
|
288
|
+
dataThroughMs: plan.dataThroughMs,
|
|
289
|
+
stats: {
|
|
290
|
+
filesScanned: files.length,
|
|
291
|
+
filesRead: plan.read.length,
|
|
292
|
+
filesReused: plan.reused.length,
|
|
293
|
+
filesRemoved: plan.removed.length,
|
|
294
|
+
removed: plan.removed,
|
|
295
|
+
cacheHit: full === false && plan.read.length === 0 && plan.reused.length > 0,
|
|
296
|
+
// ③ chunk 级时间戳:dataThroughAt 是这些 chunk mtime 的最大值。
|
|
297
|
+
dataThroughAt: plan.dataThroughMs > 0 ? new Date(plan.dataThroughMs).toISOString() : null,
|
|
298
|
+
},
|
|
299
|
+
};
|
|
237
300
|
}
|
|
238
301
|
|
|
239
302
|
function cell(value) {
|
|
@@ -346,7 +409,12 @@ export function memoryIndex(args = {}, config = {}) {
|
|
|
346
409
|
const root = memoryRootFromConfig(config);
|
|
347
410
|
const now = config.now instanceof Date ? config.now : new Date();
|
|
348
411
|
const apply = args.apply === true;
|
|
349
|
-
const
|
|
412
|
+
const full = args.full === true;
|
|
413
|
+
const scanned = scanCardsWithCache(root, {
|
|
414
|
+
full,
|
|
415
|
+
cache: args.cache === null ? null : args.cache,
|
|
416
|
+
});
|
|
417
|
+
const core = scanned.cards;
|
|
350
418
|
const { cards: procedures, invalid: invalidCards } = scanProcedures(root);
|
|
351
419
|
const cards = [...core, ...procedures.map((card) => ({ ...card, procedure: true }))];
|
|
352
420
|
const rawPolicy = scanRawPolicy(root);
|
|
@@ -364,6 +432,8 @@ export function memoryIndex(args = {}, config = {}) {
|
|
|
364
432
|
// A generated timestamp alone is not a content change; capture/ifChanged must
|
|
365
433
|
// not rewrite/back up INDEX.md on every turn just because time moved.
|
|
366
434
|
const contentChanged = withoutGeneratedStamp(before) !== withoutGeneratedStamp(after);
|
|
435
|
+
// ④ 页面自算 hash 与 getHash:这里算出来的就是 state/缓存里记的那个 hash。
|
|
436
|
+
const pageHash = getHash(after);
|
|
367
437
|
const base = {
|
|
368
438
|
root,
|
|
369
439
|
indexPath,
|
|
@@ -375,6 +445,8 @@ export function memoryIndex(args = {}, config = {}) {
|
|
|
375
445
|
...counts,
|
|
376
446
|
changed,
|
|
377
447
|
contentChanged,
|
|
448
|
+
indexHash: pageHash,
|
|
449
|
+
scan: scanned.stats,
|
|
378
450
|
generated: section,
|
|
379
451
|
};
|
|
380
452
|
|
|
@@ -390,26 +462,60 @@ export function memoryIndex(args = {}, config = {}) {
|
|
|
390
462
|
message:
|
|
391
463
|
`dry-run:扫描到 ${cards.length} 张卡(legacy ${legacy},程序性 ${procedures.length}` +
|
|
392
464
|
`${invalid > 0 ? `,坏卡 ${invalid}` : ''});raw 策略=${rawPolicy.policy}` +
|
|
465
|
+
`;读取 ${scanned.stats.filesRead} / 复用 ${scanned.stats.filesReused} / 移除 ${scanned.stats.filesRemoved}` +
|
|
393
466
|
`→ ${changed ? 'INDEX.md 会变化' : 'INDEX.md 已是最新'};加 apply:true 才落盘`,
|
|
394
467
|
};
|
|
395
468
|
}
|
|
396
469
|
|
|
397
|
-
|
|
470
|
+
// F5(记忆索引幂等):默认只在“生成段内容真的变了”时才重写 INDEX.md。
|
|
471
|
+
// 只看自动生成的时间戳会每次都换 sha、每次都堆一份备份;`ifChanged:false`
|
|
472
|
+
// 仍可强制重写(供需要刷新戳的显式场景用)。
|
|
473
|
+
const ifChanged = args.ifChanged !== false;
|
|
474
|
+
if (ifChanged && !contentChanged) {
|
|
475
|
+
// F5(记忆索引幂等):apply 已执行,但 INDEX.md 本来就没有内容变化 —— 不重写文件、
|
|
476
|
+
// 不新增 INDEX 备份(只更新时间戳会换 sha、每次都堆一份备份,这是 RT 审计的 F5)。
|
|
477
|
+
//
|
|
478
|
+
// 兼容语义(2.2 起就有的约定):applied 表示“这次 apply 请求被受理并执行”,
|
|
479
|
+
// 不代表“必然重写了文件”;是否真的动盘看 changed / contentChanged / status。
|
|
480
|
+
//
|
|
481
|
+
// N8:即使不重写 INDEX,“当前内容已复核为最新”也必须推进 indexBuiltAt。否则 capture
|
|
482
|
+
// 每轮的正常写入会被 indexLagMs 误判成索引落后,>5 分钟后健康度假性变 stale。
|
|
398
483
|
updateState(root, {
|
|
484
|
+
indexBuiltAt: now.toISOString(),
|
|
399
485
|
indexLastRefreshAt: now.toISOString(),
|
|
486
|
+
// ③ 即使内容没变也要把 dataThrough 记成真实 chunk 时间(卡片 mtime),
|
|
487
|
+
// 不是“这一轮扫描的开始时间”,否则新鲜度 lag 会假性增长。
|
|
488
|
+
indexDataAt: scanned.stats.dataThroughAt ?? now.toISOString(),
|
|
489
|
+
indexHash: pageHash,
|
|
400
490
|
indexFreshness: 'fresh',
|
|
401
491
|
indexLastError: null,
|
|
402
492
|
}, { now });
|
|
493
|
+
persistCache(root, scanned, { full, now });
|
|
494
|
+
// 手动 apply 即使没写盘也要在 audit.log 留账,否则「我跑过重建没有」无从审计。
|
|
495
|
+
appendAudit(root, {
|
|
496
|
+
action: 'memory_index',
|
|
497
|
+
object: INDEX_FILE,
|
|
498
|
+
result:
|
|
499
|
+
`cards=${cards.length} legacy=${legacy} procedures=${procedures.length} invalid=${invalid} ` +
|
|
500
|
+
`raw=${rawPolicy.policy} unchanged=1 hash=${pageHash.slice(0, 16)} ` +
|
|
501
|
+
`read=${scanned.stats.filesRead} reused=${scanned.stats.filesReused} removed=${scanned.stats.filesRemoved}`,
|
|
502
|
+
now,
|
|
503
|
+
});
|
|
403
504
|
const freshness = getIndexFreshness({ memoryRoot: root, now });
|
|
404
505
|
return {
|
|
405
506
|
...base,
|
|
406
507
|
ok: true,
|
|
407
508
|
status: 'unchanged',
|
|
408
509
|
dryRun: false,
|
|
409
|
-
applied:
|
|
510
|
+
applied: true,
|
|
511
|
+
// 盘上的 INDEX.md 没有被改写:幂等判据就报 false;生成戳本会变不代表内容变了。
|
|
512
|
+
changed: false,
|
|
513
|
+
stateWritten: true,
|
|
410
514
|
freshness,
|
|
411
515
|
indexBuiltAt: freshness.generatedAt,
|
|
412
|
-
message:
|
|
516
|
+
message:
|
|
517
|
+
`INDEX.md 已是最新(${cards.length} 行),未重写、未新增备份(幂等);` +
|
|
518
|
+
`本轮读取 ${scanned.stats.filesRead} / 复用 ${scanned.stats.filesReused} 个文件,新鲜度记账已刷新。`,
|
|
413
519
|
};
|
|
414
520
|
}
|
|
415
521
|
|
|
@@ -418,18 +524,28 @@ export function memoryIndex(args = {}, config = {}) {
|
|
|
418
524
|
if (readBack !== after) {
|
|
419
525
|
throw memoryError('E_INDEX_VERIFY', `INDEX.md 写入后读回不一致:${indexPath}`);
|
|
420
526
|
}
|
|
527
|
+
const readBackHash = getHash(readBack);
|
|
528
|
+
if (readBackHash !== pageHash) {
|
|
529
|
+
throw memoryError('E_INDEX_HASH_VERIFY', `INDEX.md 读回 hash 与写入前不一致:${pageHash} != ${readBackHash}`);
|
|
530
|
+
}
|
|
531
|
+
const dataThroughAt = scanned.stats.dataThroughAt ?? now.toISOString();
|
|
421
532
|
updateState(root, {
|
|
422
533
|
indexBuiltAt: now.toISOString(),
|
|
423
|
-
indexDataAt:
|
|
534
|
+
indexDataAt: dataThroughAt,
|
|
535
|
+
indexHash: readBackHash,
|
|
424
536
|
indexFreshness: 'fresh',
|
|
425
537
|
indexLagMs: 0,
|
|
426
538
|
indexLastRefreshAt: now.toISOString(),
|
|
427
539
|
indexLastError: null,
|
|
428
540
|
}, { now });
|
|
541
|
+
persistCache(root, scanned, { full, now });
|
|
429
542
|
appendAudit(root, {
|
|
430
543
|
action: 'memory_index',
|
|
431
544
|
object: INDEX_FILE,
|
|
432
|
-
result:
|
|
545
|
+
result:
|
|
546
|
+
`cards=${cards.length} legacy=${legacy} procedures=${procedures.length} invalid=${invalid} ` +
|
|
547
|
+
`raw=${rawPolicy.policy} changed=${changed} hash=${readBackHash.slice(0, 16)} ` +
|
|
548
|
+
`read=${scanned.stats.filesRead} reused=${scanned.stats.filesReused} removed=${scanned.stats.filesRemoved}`,
|
|
433
549
|
now,
|
|
434
550
|
});
|
|
435
551
|
const freshness = getIndexFreshness({ memoryRoot: root, now });
|
|
@@ -446,10 +562,28 @@ export function memoryIndex(args = {}, config = {}) {
|
|
|
446
562
|
indexBuiltAt: now.toISOString(),
|
|
447
563
|
message:
|
|
448
564
|
`已重建 INDEX.md:${cards.length} 行(legacy ${legacy},程序性 ${procedures.length}` +
|
|
449
|
-
`${invalid > 0 ? `,坏卡 ${invalid}` : ''}
|
|
565
|
+
`${invalid > 0 ? `,坏卡 ${invalid}` : ''}),读取 ${scanned.stats.filesRead} / 复用 ${scanned.stats.filesReused} 个文件` +
|
|
566
|
+
`,备份 ${write.backupRel ?? '(首次创建,无旧文件)'}`,
|
|
450
567
|
};
|
|
451
568
|
}
|
|
452
569
|
|
|
570
|
+
/**
|
|
571
|
+
* 缓存落盘失败不致命:索引本体已经写好,缓存只是下一次提速的附件。
|
|
572
|
+
* 返回 {saved, error},调用端保留在 scan 里即可。
|
|
573
|
+
*/
|
|
574
|
+
function persistCache(root, scanned, { full, now }) {
|
|
575
|
+
try {
|
|
576
|
+
saveIndexCache(root, {
|
|
577
|
+
entries: scanned.entries,
|
|
578
|
+
builtAt: (now instanceof Date ? now : new Date()).toISOString(),
|
|
579
|
+
full,
|
|
580
|
+
});
|
|
581
|
+
return { saved: true };
|
|
582
|
+
} catch (error) {
|
|
583
|
+
return { saved: false, error: error?.message ?? String(error) };
|
|
584
|
+
}
|
|
585
|
+
}
|
|
586
|
+
|
|
453
587
|
/** Read the generated region of an INDEX.md text, or null when absent. */
|
|
454
588
|
export function extractGeneratedSection(text) {
|
|
455
589
|
const source = String(text ?? '');
|