@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.
Files changed (47) hide show
  1. package/CHANGELOG.md +79 -0
  2. package/QUICKSTART.md +7 -7
  3. package/README.en.md +13 -1
  4. package/README.md +26 -8
  5. package/SPEC.md +6 -5
  6. package/build-info.json +132 -67
  7. package/cordis.patch.yml +1 -0
  8. package/docs/ARCHITECTURE.md +6 -3
  9. package/docs/CONFIG.md +25 -1
  10. package/docs/FAQ.md +2 -2
  11. package/docs/FEATURES.md +104 -2
  12. package/docs/INDEX-FRESHNESS.md +8 -1
  13. package/docs/OPERATIONS.md +63 -2
  14. package/docs/QUICKSTART.md +2 -2
  15. package/docs/README.en.md +1 -1
  16. package/docs/TROUBLESHOOTING.md +1 -1
  17. package/package.json +10 -2
  18. package/scripts/assert-install.mjs +124 -0
  19. package/scripts/backlog-report.mjs +98 -0
  20. package/scripts/install-230.mjs +787 -0
  21. package/scripts/lib/eng-common.mjs +428 -0
  22. package/scripts/rebuild-index.mjs +148 -0
  23. package/scripts/restore-drill.mjs +351 -0
  24. package/scripts/run-autoresolve.mjs +123 -0
  25. package/scripts/watchdog-230.mjs +379 -0
  26. package/src/features.js +14 -0
  27. package/src/gate/action-gate.js +234 -45
  28. package/src/memory/backup-retention.mjs +823 -0
  29. package/src/memory/cards.js +73 -12
  30. package/src/memory/conflict-scan.mjs +356 -0
  31. package/src/memory/conflicts.js +202 -9
  32. package/src/memory/consolidate.js +100 -13
  33. package/src/memory/decay.js +133 -19
  34. package/src/memory/event-index.js +62 -4
  35. package/src/memory/forget-scheduler.mjs +303 -0
  36. package/src/memory/forget-v2.js +94 -8
  37. package/src/memory/index-cache.mjs +216 -0
  38. package/src/memory/index.js +149 -15
  39. package/src/memory/lock.js +53 -12
  40. package/src/memory/maintenance.js +172 -17
  41. package/src/memory/recall-feedback.mjs +159 -17
  42. package/src/memory/state.js +446 -38
  43. package/src/memory/task-state.mjs +569 -0
  44. package/src/recall/brain.mjs +8 -1
  45. package/src/recall/continuity-volatile.mjs +131 -1
  46. package/src/tools.js +108 -33
  47. package/src/ui/routes-readonly.js +63 -5
@@ -33,6 +33,18 @@ export const DECAY_POLICY = Object.freeze({
33
33
  mergeNoiseOnly: true,
34
34
  });
35
35
 
36
+ /**
37
+ * 2.3.0 W2.3:衰减公式(可见文本,报告/返回值里直接带着它)。
38
+ * 记录分支:decayed = ageDays > unreferencedDays && strength <= 3 && useCount === 0
39
+ * 卡片分支:fields.last_used 超过 unreferencedDays 且不是核心卡(salience>=5)/锁定卡 → distill 提案;
40
+ * 阈值语义是 strict(`>` 而不是 `>=`)。公式只提案,不删除、不改写任何卡片。
41
+ */
42
+ export const DECAY_FORMULA = 'decayed = ageDays > unreferencedDays && strength <= 3 && useCount === 0(strict: > 不是 >=)';
43
+ export const DECAY_LIMITS = Object.freeze({
44
+ unreferencedDays: Object.freeze({ min: 1, max: 3650 }),
45
+ dailyCap: Object.freeze({ min: 1, max: 1000 }),
46
+ });
47
+
36
48
  const DAY_MS = 24 * 60 * 60 * 1000;
37
49
  const ISO_DAY_RE = /^\d{4}-\d{2}-\d{2}$/;
38
50
 
@@ -63,61 +75,163 @@ function contentKeyOf(record) {
63
75
  return sha256Text(norm(raw));
64
76
  }
65
77
 
78
+ function clampInt(value, fallback, range) {
79
+ const number = Number(value);
80
+ if (!Number.isFinite(number) || !Number.isInteger(number)) return fallback;
81
+ return Math.min(range.max, Math.max(range.min, number));
82
+ }
83
+
84
+ /**
85
+ * 2.3.0 W2.3:把 raw config 的衰减策略归一化成显式 policy(默认 = DECAY_POLICY)。
86
+ * 只读 `config.decay` / `config.autoMaintenance.decay` 这两个整块 passthrough 键
87
+ * (与 recall links / proactive / handoff / tiering 同法:不新增 schemastery 叶子,
88
+ * 设置面板 leaf 数不变)。可配字段:unreferencedDays(1..3650)、dailyCap(1..1000)、
89
+ * mergeNoiseOnly(boolean)。越界/非法值 clamp 回默认,不抛错。
90
+ */
91
+ export function normalizeDecayPolicy(raw = {}) {
92
+ const source = raw && typeof raw === 'object' && !Array.isArray(raw) ? raw : {};
93
+ return Object.freeze({
94
+ unreferencedDays: clampInt(source.unreferencedDays, DECAY_POLICY.unreferencedDays, DECAY_LIMITS.unreferencedDays),
95
+ dailyCap: clampInt(source.dailyCap, DECAY_POLICY.dailyCap, DECAY_LIMITS.dailyCap),
96
+ mergeNoiseOnly: typeof source.mergeNoiseOnly === 'boolean' ? source.mergeNoiseOnly : DECAY_POLICY.mergeNoiseOnly,
97
+ strict: DECAY_POLICY.strict,
98
+ formula: DECAY_FORMULA,
99
+ });
100
+ }
101
+
102
+ /**
103
+ * config + 显式参数 → 最终 policy。优先级:显式参数(days/cap)> config.decay >
104
+ * config.autoMaintenance.decay > DECAY_POLICY 默认。返回值带 source,报告里可核。
105
+ */
106
+ export function decayPolicyFromConfig(config = {}, overrides = {}) {
107
+ let raw = null;
108
+ let source = 'default';
109
+ const top = config?.decay;
110
+ const nested = config?.autoMaintenance?.decay;
111
+ if (top && typeof top === 'object' && !Array.isArray(top)) {
112
+ raw = top;
113
+ source = 'config.decay';
114
+ } else if (nested && typeof nested === 'object' && !Array.isArray(nested)) {
115
+ raw = nested;
116
+ source = 'autoMaintenance.decay';
117
+ }
118
+ const policy = normalizeDecayPolicy(raw ?? {});
119
+ const out = { ...policy, source };
120
+ const hasDays = overrides?.days !== undefined && overrides?.days !== null;
121
+ const hasCap = overrides?.cap !== undefined && overrides?.cap !== null;
122
+ if (hasDays) out.unreferencedDays = clampInt(overrides.days, policy.unreferencedDays, DECAY_LIMITS.unreferencedDays);
123
+ if (hasCap) out.dailyCap = clampInt(overrides.cap, policy.dailyCap, DECAY_LIMITS.dailyCap);
124
+ if (hasDays || hasCap) out.source = `${source}+args`;
125
+ return Object.freeze(out);
126
+ }
127
+
66
128
  /** Pure decay score for one assertion/card: older + weaker => more decayed. */
67
- export function decayScore(record, now = new Date()) {
129
+ export function decayScore(record, now = new Date(), policy = DECAY_POLICY) {
130
+ const unreferencedDays = clampInt(policy?.unreferencedDays, DECAY_POLICY.unreferencedDays, DECAY_LIMITS.unreferencedDays);
68
131
  const day = record?.lastUsed ?? record?.last_used ?? record?.createdAt ?? null;
69
132
  const ageDays = day === null ? null : daysSince(day, now);
70
133
  const strength = Number.isFinite(record?.strength) ? Number(record.strength) : 3;
71
134
  const useCount = Number.isInteger(record?.useCount) ? record.useCount : 0;
72
- return { ageDays, strength, useCount, decayed: ageDays !== null && ageDays > DECAY_POLICY.unreferencedDays && strength <= 3 && useCount === 0 };
135
+ return {
136
+ ageDays,
137
+ strength,
138
+ useCount,
139
+ threshold: unreferencedDays,
140
+ decayed: ageDays !== null && ageDays > unreferencedDays && strength <= 3 && useCount === 0,
141
+ };
73
142
  }
74
143
 
75
144
  /**
76
- * Time-decay proposals (read-only): same-topic records unreferenced for >90 days
77
- * become distill candidates. Never deletes, never writes.
145
+ * Time-decay proposals (read-only): same-topic records/cards unreferenced for
146
+ * >unreferencedDays become distill candidates. Never deletes, never writes.
147
+ *
148
+ * 2.3.0 W2.3:①策略可配(raw passthrough,见 decayPolicyFromConfig / DECAY_FORMULA);
149
+ * ②cards 分支补齐核心卡(salience>=5)/锁定卡/无日期免疫,并修掉「last_used=null 被
150
+ * dayOf 当成 1970 年、算出 2 万天」的老问题——无日期只能进 immune,绝不出提案。
78
151
  */
79
- export function proposeDecay({ records = [], cards = [], now = new Date(), days = DECAY_POLICY.unreferencedDays, cap = DECAY_POLICY.dailyCap } = {}) {
152
+ export function proposeDecay({ records = [], cards = [], now = new Date(), days, cap, policy, config, root } = {}) {
153
+ const resolved = policy && typeof policy === 'object'
154
+ ? { ...decayPolicyFromConfig({}, {}), ...policy }
155
+ : decayPolicyFromConfig(config, { days, cap });
156
+ const limitDays = clampInt(resolved.unreferencedDays, DECAY_POLICY.unreferencedDays, DECAY_LIMITS.unreferencedDays);
157
+ const limitCap = clampInt(resolved.dailyCap, DECAY_POLICY.dailyCap, DECAY_LIMITS.dailyCap);
80
158
  const topics = new Map();
81
159
  const immune = [];
160
+ const bucketOf = (topic) => {
161
+ const bucket = topics.get(topic) ?? { topic, ids: [], ageDays: 0, recordCount: 0, cardCount: 0 };
162
+ topics.set(topic, bucket);
163
+ return bucket;
164
+ };
82
165
  for (const record of records) {
83
166
  const topic = norm(record?.subject?.entity ?? record?.subject ?? record?.topic ?? record?.kind ?? 'unknown');
84
167
  const references = Array.isArray(record?.referencedBy) ? record.referencedBy : [];
85
168
  const day = record?.lastUsed ?? record?.last_used ?? null;
86
169
  const ageDays = day === null ? null : daysSince(day, now);
87
- if (Number(record?.salience) >= 5 || record?.state === 'locked' || references.length > 0 || ageDays === null || ageDays <= days) {
88
- immune.push({ id: record?.id ?? null, reason: ageDays === null ? 'no-date' : ageDays <= days ? `age=${ageDays}<=${days}` : 'protected-or-referenced' });
170
+ if (Number(record?.salience) >= 5 || record?.state === 'locked' || references.length > 0 || ageDays === null || ageDays <= limitDays) {
171
+ immune.push({ id: record?.id ?? null, reason: ageDays === null ? 'no-date' : ageDays <= limitDays ? `age=${ageDays}<=${limitDays}` : 'protected-or-referenced' });
89
172
  continue;
90
173
  }
91
- const bucket = topics.get(topic) ?? { topic, ids: [], ageDays };
174
+ const bucket = bucketOf(topic);
92
175
  bucket.ids.push(record.id);
176
+ bucket.recordCount += 1;
93
177
  bucket.ageDays = Math.max(bucket.ageDays, ageDays);
94
- topics.set(topic, bucket);
95
178
  }
96
179
  for (const card of cards) {
97
- if (isProtectedPath({ memoryRoot: card.memoryRoot ?? '', relPath: card.rel ?? '' })) {
98
- immune.push({ id: card.rel ?? null, reason: 'protected-card' });
180
+ const rel = card.rel ?? '';
181
+ const cardRoot = card.memoryRoot ?? root ?? '';
182
+ if (cardRoot !== '' && isProtectedPath({ memoryRoot: cardRoot, relPath: rel })) {
183
+ immune.push({ id: rel || null, reason: 'protected-card' });
184
+ continue;
185
+ }
186
+ const salience = Number(card.fields?.salience ?? card.salience);
187
+ if (Number.isFinite(salience) && salience >= 5) {
188
+ immune.push({ id: rel || null, reason: 'core-card' });
99
189
  continue;
100
190
  }
191
+ if (card.status === 'locked' || card.fields?.status === 'locked') {
192
+ immune.push({ id: rel || null, reason: 'locked-card' });
193
+ continue;
194
+ }
195
+ const rawDay = card.fields?.last_used ?? card.last_used ?? null;
196
+ if (rawDay === null || rawDay === undefined || rawDay === '') {
197
+ immune.push({ id: rel || null, reason: 'no-date' });
198
+ continue;
199
+ }
200
+ const ageDays = daysSince(rawDay, now);
201
+ if (ageDays === null) {
202
+ immune.push({ id: rel || null, reason: 'no-date' });
203
+ continue;
204
+ }
205
+ if (ageDays <= limitDays) continue;
101
206
  const topic = norm(card.fields?.tags?.[0] ?? card.title ?? 'unknown');
102
- const ageDays = daysSince(card.fields?.last_used ?? null, now);
103
- if (ageDays === null || ageDays <= days) continue;
104
- const bucket = topics.get(topic) ?? { topic, ids: [], ageDays };
105
- bucket.ids.push(card.rel);
207
+ const bucket = bucketOf(topic);
208
+ bucket.ids.push(rel);
209
+ bucket.cardCount += 1;
106
210
  bucket.ageDays = Math.max(bucket.ageDays, ageDays);
107
- topics.set(topic, bucket);
108
211
  }
109
212
  const proposals = [...topics.values()]
110
213
  .filter((bucket) => bucket.ids.length > 0)
111
214
  .sort((left, right) => right.ageDays - left.ageDays)
112
- .slice(0, cap)
215
+ .slice(0, limitCap)
113
216
  .map((bucket) => ({
114
217
  action: 'distill',
115
218
  topic: bucket.topic,
116
219
  sourceIds: [...bucket.ids].sort(),
220
+ records: bucket.recordCount,
221
+ cards: bucket.cardCount,
117
222
  ageDays: bucket.ageDays,
118
- reason: `同主题 ${bucket.ids.length} 条事件 ${bucket.ageDays} 天未被引用(>${days})→ 可合成为 distill 摘要(原文保留)`,
223
+ reason: `同主题 ${bucket.ids.length} 条事件(记录 ${bucket.recordCount} / 卡片 ${bucket.cardCount})${bucket.ageDays} 天未被引用(>${limitDays})→ 可合成为 distill 摘要(原文保留)`,
119
224
  }));
120
- return { schema: DECAY_SCHEMA, policy: { ...DECAY_POLICY, days, cap }, proposals, immune, executed: false };
225
+ const policyView = {
226
+ ...DECAY_POLICY,
227
+ ...resolved,
228
+ unreferencedDays: limitDays,
229
+ dailyCap: limitCap,
230
+ days: limitDays,
231
+ cap: limitCap,
232
+ formula: DECAY_FORMULA,
233
+ };
234
+ return { schema: DECAY_SCHEMA, policy: policyView, proposals, immune, executed: false };
121
235
  }
122
236
 
123
237
  /** Duplicate groups by normalized content: keep first, mark the rest duplicateOf. */
@@ -1506,7 +1506,11 @@ export function buildIndexFromSessions(options = {}) {
1506
1506
  }
1507
1507
  eventsIndexed += 1;
1508
1508
  }
1509
- fs.writeFileSync(path.join(paths.framesDir, `${sessionId}.json`), `${JSON.stringify({
1509
+ fs.mkdirSync(paths.framesDir, { recursive: true });
1510
+ // ⑤ 崩溃一致性:frames/*.json 与 build-state.json 都走 tmp+rename。
1511
+ // ③ chunk 级时间戳:每个 turn(chunk)记录自己的真实起止时间,而不是
1512
+ // 让读取端拿整个会话文件的 mtime 冒充。
1513
+ writeJsonAtomic(path.join(paths.framesDir, `${sessionId}.json`), {
1510
1514
  schema: 'frames/v1',
1511
1515
  sessionId,
1512
1516
  sessionDigest,
@@ -1519,8 +1523,11 @@ export function buildIndexFromSessions(options = {}) {
1519
1523
  seqStart: record.seqStart,
1520
1524
  seqEnd: record.seqEnd,
1521
1525
  frames: record.frameIndexes,
1526
+ timeStart: record.timeStart ?? null,
1527
+ timeEnd: record.timeEnd ?? null,
1528
+ chunkAt: Number.isFinite(record.timeEnd) ? new Date(record.timeEnd).toISOString() : null,
1522
1529
  })),
1523
- }, null, 2)}\n`, 'utf8');
1530
+ });
1524
1531
  built.push({
1525
1532
  sessionId,
1526
1533
  dirSessionId: log.sessionId,
@@ -1558,6 +1565,8 @@ export function buildIndexFromSessions(options = {}) {
1558
1565
  lastTurn: entry.lastTurn,
1559
1566
  header: entry.header,
1560
1567
  sessionDigest: entry.sessionDigest,
1568
+ // 记下源文件:增量构建才能发现“会话已被删除”,而不是把幽灵行一直留在库里。
1569
+ file: entry.file ?? null,
1561
1570
  })),
1562
1571
  duplicates,
1563
1572
  errors,
@@ -1573,7 +1582,7 @@ export function buildIndexFromSessions(options = {}) {
1573
1582
  },
1574
1583
  generatedAt: nowIso(now),
1575
1584
  };
1576
- fs.writeFileSync(paths.buildState, `${JSON.stringify(buildState, null, 2)}\n`, 'utf8');
1585
+ writeJsonAtomic(paths.buildState, buildState);
1577
1586
  index.setMeta('build_state_at', buildState.builtAt);
1578
1587
  const finalStats = index.stats();
1579
1588
  index.close();
@@ -1650,6 +1659,28 @@ function readFromOffset(file, offset) {
1650
1659
  }
1651
1660
  }
1652
1661
 
1662
+ /**
1663
+ * ⑤ 崩溃一致性:JSON 文件先写同目录 tmp、读回校验、再 rename 覆盖。
1664
+ * 进程在任意点被杀,磁盘上要么是完整旧文件,要么是完整新文件,不会半截。
1665
+ */
1666
+ function writeJsonAtomic(file, value) {
1667
+ fs.mkdirSync(path.dirname(file), { recursive: true });
1668
+ const payload = `${JSON.stringify(value, null, 2)}\n`;
1669
+ const tmp = `${file}.tmp-${process.pid}-${Date.now()}`;
1670
+ try {
1671
+ fs.writeFileSync(tmp, payload, 'utf8');
1672
+ const staged = fs.readFileSync(tmp, 'utf8');
1673
+ if (staged !== payload) throw new IndexError('E_INDEX_TMP_VERIFY', `tmp 写入校验失败:${tmp}`);
1674
+ fs.renameSync(tmp, file);
1675
+ } catch (error) {
1676
+ try {
1677
+ if (fs.existsSync(tmp)) fs.rmSync(tmp, { force: true });
1678
+ } catch { /* 尽力清理 */ }
1679
+ throw error;
1680
+ }
1681
+ return { file, bytes: Buffer.byteLength(payload) };
1682
+ }
1683
+
1653
1684
  /**
1654
1685
  * Incremental build: unchanged logs are skipped; appended logs read ONLY the new
1655
1686
  * tail frames (from build-state.logBytes) and index just the new turns. Any doubt
@@ -1722,6 +1753,7 @@ export function buildIndexIncremental(options = {}) {
1722
1753
  lastTurn: records.length > 0 ? records[records.length - 1].turn : -1,
1723
1754
  header: { id: parsed.header?.id ?? null, cwd: parsed.header?.cwd ?? null },
1724
1755
  sessionDigest: deriveMessagesDigest(parsed.header, parsed.events).sha256,
1756
+ file: log.file,
1725
1757
  });
1726
1758
  stats.turns += records.length;
1727
1759
  stats.inserted += inserted;
@@ -1788,6 +1820,7 @@ export function buildIndexIncremental(options = {}) {
1788
1820
  logMtimeMs: stat.mtimeMs,
1789
1821
  lastSeq: tail.events[tail.events.length - 1].seq,
1790
1822
  lastTurn: records.length > 0 ? records[records.length - 1].turn : stateEntry.lastTurn,
1823
+ file: log.file,
1791
1824
  });
1792
1825
  stats.sessionsAppended += 1;
1793
1826
  stats.turns += records.length;
@@ -1803,6 +1836,31 @@ export function buildIndexIncremental(options = {}) {
1803
1836
  }
1804
1837
  }
1805
1838
 
1839
+ // ⑤ 增量维护的一部分:会话文件已被删掉时,把它的行从索引里撤掉(只撤
1840
+ // 本轮扫描根之内的、且 build-state 记过源文件的条目;旧 state 没有 file
1841
+ // 字段就不猜,避免误删)。
1842
+ const pruned = [];
1843
+ if (options.pruneMissing !== false) {
1844
+ const scannedRoots = sessionRoots
1845
+ .filter((root) => typeof root === 'string' && root !== '')
1846
+ .map((root) => path.resolve(root));
1847
+ for (const [dirSessionId, entry] of [...stateBySession.entries()]) {
1848
+ if (!entry || typeof entry.file !== 'string' || entry.file === '') continue;
1849
+ const abs = path.resolve(entry.file);
1850
+ const underScanned = scannedRoots.some((root) => abs === root || abs.startsWith(`${root}${path.sep}`));
1851
+ if (!underScanned || fs.existsSync(abs)) continue;
1852
+ try {
1853
+ index.deleteSession(entry.sessionId);
1854
+ } catch {
1855
+ /* 单会话删除失败不阻塞其余会话;账里记 pruned 直到成功 */
1856
+ continue;
1857
+ }
1858
+ stateBySession.delete(dirSessionId);
1859
+ pruned.push({ sessionId: entry.sessionId, file: entry.file });
1860
+ }
1861
+ }
1862
+ stats.pruned = pruned.length;
1863
+
1806
1864
  stats.errors = errors.length;
1807
1865
  const buildState = {
1808
1866
  schema: 'events-build-state/v1',
@@ -1816,7 +1874,7 @@ export function buildIndexIncremental(options = {}) {
1816
1874
  stats,
1817
1875
  durationMs: Date.now() - started,
1818
1876
  };
1819
- fs.writeFileSync(paths.buildState, JSON.stringify(buildState, null, 2) + '\n', 'utf8');
1877
+ writeJsonAtomic(paths.buildState, buildState);
1820
1878
  index.setMeta('build_state_at', buildState.builtAt);
1821
1879
  const finalStats = index.stats();
1822
1880
  index.close();
@@ -0,0 +1,303 @@
1
+ // src/memory/forget-scheduler.mjs — 2.3.0 W2.3:自动遗忘/衰减每日调度槽
2
+ //
3
+ // 分工(与 maintenance.js B2 的边界,maintenance.js 归 lane-230-conflict 独占,本模块不碰它):
4
+ // * B2(maintenance.js)已经每天跑一次 `memory_forget`(无 confirm = dry-run),并把
5
+ // forget-pending-<YYYYMMDD>.md 写进 .longlive/reports/;
6
+ // * 本模块补在 B2 之后,把「衰减/蒸馏提案」也纳入每日维护,并输出一份**合并、可读、脱敏**的
7
+ // forget-decay-pending-<YYYYMMDD>.md;合流时 maintenance.js 只需在 B2 内调用
8
+ // `runForgetDecayScheduler({ root, config, now: at, day, forgetResult: result })` 一次。
9
+ //
10
+ // 执行边界(写死,不靠调用方自觉):
11
+ // * 自动链路只允许 dry-run:memory_forget 的 confirm 一律不传;若拿到的结果不是
12
+ // `dryRun === true && applied === false`,直接抛 E_FORGET_SCHEDULER_EXECUTED(fail-closed)。
13
+ // * tombstone / epochs 的移动只能人工触发:`memory_forget { confirm: "FORGET" }`,且需要宿主
14
+ // auditKey(env 或 .longlive/.hostkey);本模块永不 rename、永不删除、永不改写卡片。
15
+ // * 报告只写 .longlive/reports/ 下的一份 markdown;报告字段白名单见 REPORT_POLICY。
16
+ //
17
+ // 隐私(报告脱敏):
18
+ // * 只写相对路径 / 计数 / 天数 / 原因码;不写绝对路径(不含 memoryRoot)、不写卡片正文、
19
+ // 不写 tags、不写会话 id、不写 tool-output 内容;文件里的 uuid 形态 id 一律省略。
20
+ // * scanReportPrivacy() 会把渲染结果再扫一遍,命中绝对路径/宿主 home/uuid → privacy.ok=false,
21
+ // 由调用方(与回执)如实上报,不静默放行。
22
+
23
+ import path from 'node:path';
24
+
25
+ import { DECAY_FORMULA, decayPolicyFromConfig, proposeDecay } from './decay.js';
26
+ import { CONFIRM_WORD, memoryForget } from './forget.js';
27
+ import { dayString, isDayString, isoStamp } from './frontmatter.js';
28
+ import { scanCards } from './index.js';
29
+ import { memoryError, memoryRootFromConfig, relativePath, resolveInside } from './paths.js';
30
+ import { listRecords } from './records.js';
31
+ import { ensureDir, REPORTS_DIR, writeFileAtomic } from './state.js';
32
+
33
+ export const FORGET_SCHEDULER_SCHEMA = 'forget-scheduler/v1';
34
+ export const DECAY_PENDING_PREFIX = 'forget-decay-pending-';
35
+ export const DECAY_PENDING_MAX_PROPOSALS = 50;
36
+ export const DECAY_PENDING_MAX_FORGET = 50;
37
+ export const REPORT_PRIVACY_SCHEMA = 'forget-report-privacy/v1';
38
+ export const CONFIRM_REQUIREMENT =
39
+ '执行边界:自动维护永不执行;立碑/降级只能人工 `memory_forget { confirm: "FORGET" }`,并需要宿主 auditKey(env 或 .longlive/.hostkey)';
40
+
41
+ /** 报告字段白名单(渲染器只允许写这些形态;改这里等于改隐私契约)。 */
42
+ export const REPORT_POLICY = Object.freeze({
43
+ absolutePaths: false,
44
+ memoryRootPath: false,
45
+ cardBodies: false,
46
+ tags: false,
47
+ sessionIds: false,
48
+ toolOutput: false,
49
+ recordIds: false,
50
+ });
51
+
52
+ const UUID_RE = /\b[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\b/i;
53
+ const ABS_WIN_RE = /[A-Za-z]:[\\/]/;
54
+
55
+ /** 报告文件名(相对 memoryRoot):.longlive/reports/forget-decay-pending-<day>.md */
56
+ export function decayPendingReportRel(day) {
57
+ const dayStr = isDayString(day) ? day : String(day ?? '');
58
+ if (!isDayString(dayStr)) throw memoryError('E_FORGET_SCHEDULER_DAY', `day 必须是 YYYY-MM-DD:${day}`);
59
+ return `.longlive/${REPORTS_DIR}/${DECAY_PENDING_PREFIX}${dayStr}.md`;
60
+ }
61
+
62
+ export function decayPendingReportPath(root, day) {
63
+ return resolveInside(root, decayPendingReportRel(day));
64
+ }
65
+
66
+ function kindLabel(kind) {
67
+ if (kind === 'tombstone') return '立碑(archive/tombstones/)';
68
+ if (kind === 'epochs') return '降级(epochs/)';
69
+ return String(kind ?? 'unknown');
70
+ }
71
+
72
+ function reasonCounts(items, reasonOf = (item) => item?.reason) {
73
+ const counts = new Map();
74
+ for (const item of Array.isArray(items) ? items : []) {
75
+ const reason = String(reasonOf(item) ?? 'unknown');
76
+ counts.set(reason, (counts.get(reason) ?? 0) + 1);
77
+ }
78
+ return [...counts.entries()].sort((left, right) => right[1] - left[1] || left[0].localeCompare(right[0]));
79
+ }
80
+
81
+ /** 只保留「像 memoryRoot 内相对路径」的来源 id;记录 uuid/绝对路径一律不写进报告。 */
82
+ function relativeSourceIds(ids) {
83
+ const kept = [];
84
+ let omitted = 0;
85
+ for (const id of Array.isArray(ids) ? ids : []) {
86
+ const text = String(id ?? '');
87
+ if (text === '' || ABS_WIN_RE.test(text) || text.includes('\\') || text.includes('..') || !text.includes('/')) {
88
+ omitted += 1;
89
+ continue;
90
+ }
91
+ kept.push(text);
92
+ }
93
+ return { kept, omitted };
94
+ }
95
+
96
+ /**
97
+ * 纯渲染:遗忘 dry-run 结果 + 衰减提案 → markdown 报告。
98
+ * 不读磁盘、不带 root、不带卡片正文/tags/session id(隐私白名单见 REPORT_POLICY)。
99
+ */
100
+ export function renderForgetDecayPending({ day, at = new Date(), forget = null, decay = null } = {}) {
101
+ const dayStr = isDayString(day) ? day : dayString(at);
102
+ const forgetResult = forget ?? {};
103
+ const decayResult = decay ?? { proposals: [], immune: [] };
104
+ const forgetProposals = Array.isArray(forgetResult.proposals) ? forgetResult.proposals : [];
105
+ const forgetTombstones = forgetProposals.filter((item) => item?.kind === 'tombstone').length;
106
+ const forgetEpochs = forgetProposals.filter((item) => item?.kind === 'epochs').length;
107
+ const decayProposals = Array.isArray(decayResult.proposals) ? decayResult.proposals : [];
108
+ const decayPolicy = decayResult.policy ?? decayPolicyFromConfig({});
109
+ const lines = [];
110
+
111
+ lines.push(`# 遗忘 / 衰减待确认 · ${dayStr}`, '');
112
+ lines.push(`> 自动维护生成于 ${isoStamp(at)};**没有移动、删除或改写任何卡片**。`);
113
+ lines.push(`> ${CONFIRM_REQUIREMENT}。`, '');
114
+ lines.push('## 摘要', '');
115
+ lines.push(`- 遗忘 dry-run:扫描卡片 ${forgetResult.scanned ?? 0} 张 → 待确认提案 ${forgetProposals.length} 个(立碑 ${forgetTombstones} / 降级 ${forgetEpochs}),核心免疫 ${(forgetResult.immune ?? []).length},无日期 ${(forgetResult.undated ?? []).length}`);
116
+ lines.push(`- 衰减(蒸馏)提案:${decayProposals.length} 组,上限 ${decayPolicy.dailyCap ?? 50} 组/天,阈值 >${decayPolicy.unreferencedDays ?? 90} 天未引用;策略来源 ${decayPolicy.source ?? 'default'}`);
117
+ lines.push(`- 免疫/跳过:遗忘 ${(forgetResult.immune ?? []).length + (forgetResult.undated ?? []).length} 项;衰减 ${(decayResult.immune ?? []).length} 项`);
118
+ lines.push(`- 公式:\`${decayPolicy.formula ?? DECAY_FORMULA}\``);
119
+ lines.push(`- 报告隐私:只含相对路径/计数/天数/原因码(不含绝对路径、正文、tags、会话 id、record uuid)`, '');
120
+
121
+ lines.push('## 一、遗忘提案(dry-run,需人工确认)', '');
122
+ if (forgetProposals.length === 0) {
123
+ lines.push('今天没有到期的遗忘提案。', '');
124
+ } else {
125
+ const shown = forgetProposals.slice(0, DECAY_PENDING_MAX_FORGET);
126
+ shown.forEach((proposal, index) => {
127
+ lines.push(`### ${index + 1}. \`${proposal.path ?? '-'}\``);
128
+ lines.push(`- 动作:${kindLabel(proposal.kind)}`);
129
+ lines.push(`- 年龄:${proposal.ageDays ?? '-'} 天(last_used: ${proposal.last_used ?? '-'},strength: ${proposal.strength ?? '-'},salience: ${proposal.salience ?? '-'})`);
130
+ lines.push(`- 目标位置:\`${proposal.destRel ?? '-'}\``);
131
+ lines.push(`- 依据:${proposal.reason ?? '-'}`);
132
+ lines.push('');
133
+ });
134
+ if (forgetProposals.length > shown.length) {
135
+ lines.push(`(报告只列前 ${shown.length} 条;完整列表见同日的 B2 forget-pending 报告)`, '');
136
+ }
137
+ const immuneRows = reasonCounts(forgetResult.immune, (item) => item?.reason);
138
+ if (immuneRows.length > 0) {
139
+ lines.push('### 核心免疫 / 跳过', '');
140
+ for (const [reason, count] of immuneRows) lines.push(`- ${reason}:${count}`);
141
+ lines.push('');
142
+ }
143
+ }
144
+
145
+ lines.push('## 二、衰减(蒸馏)提案(只提案,不执行)', '');
146
+ if (decayProposals.length === 0) {
147
+ lines.push('没有超过阈值的同主题衰减分组。', '');
148
+ } else {
149
+ decayProposals.forEach((proposal, index) => {
150
+ const sources = relativeSourceIds(proposal.sourceIds);
151
+ lines.push(`### ${index + 1}. 分组 #${index + 1}(源 ${proposal.sourceIds?.length ?? 0} 条:记录 ${proposal.records ?? 0} / 卡片 ${proposal.cards ?? 0})`);
152
+ lines.push(`- 最老:${proposal.ageDays ?? '-'} 天未引用(阈值 >${decayPolicy.unreferencedDays ?? 90})`);
153
+ lines.push(`- 来源路径:${sources.kept.length > 0 ? sources.kept.map((rel) => `\`${rel}\``).join('、') : '(无)'}${sources.omitted > 0 ? `(另有 ${sources.omitted} 条记录 id 已省略)` : ''}`);
154
+ lines.push(`- 下游动作:人工确认后交给 distill(原文保留,不删除)`);
155
+ lines.push('');
156
+ });
157
+ const decayImmune = reasonCounts(decayResult.immune, (item) => item?.reason);
158
+ if (decayImmune.length > 0) {
159
+ lines.push('### 衰减免疫 / 跳过', '');
160
+ for (const [reason, count] of decayImmune) lines.push(`- ${reason}:${count}`);
161
+ lines.push('');
162
+ }
163
+ }
164
+
165
+ lines.push('## 三、执行方式(人工边界)', '');
166
+ lines.push(`1. 复核本报告的每条提案(路径/年龄/依据)。`);
167
+ lines.push(`2. 遗忘执行:\`memory_forget { "confirm": "${CONFIRM_WORD}" }\`,宿主 auditKey 必须可用;执行会先备份(sha256 校验)→ 写 tombstones.md 三问 → rename 进 epochs/ 或 archive/tombstones/,不会删除。`);
168
+ lines.push(`3. 衰减执行:人工确认后走 distill(本模块只出提案;原文保留)。`);
169
+ lines.push(`4. 自动维护链路永不执行本报告里的任何提案。`, '');
170
+
171
+ return lines.join('\n');
172
+ }
173
+
174
+ /**
175
+ * 扫描报告文本,确认没有绝对路径 / 宿主 home / uuid 形态 id 泄漏。
176
+ * @returns {{schema:string, ok:boolean, leaks:string[], policy:object}}
177
+ */
178
+ export function scanReportPrivacy(text, { root = '' } = {}) {
179
+ const body = String(text ?? '');
180
+ const leaks = [];
181
+ const absRoot = String(root ?? '');
182
+ if (absRoot !== '') {
183
+ if (body.includes(absRoot) || body.includes(absRoot.replace(/\\/g, '/'))) leaks.push('absolute-root');
184
+ }
185
+ if (ABS_WIN_RE.test(body)) leaks.push('windows-absolute-path');
186
+ const home = String(process.env.USERPROFILE ?? process.env.HOME ?? '');
187
+ if (home !== '' && (body.includes(home) || body.includes(home.replace(/\\/g, '/')))) leaks.push('home-path');
188
+ if (UUID_RE.test(body)) leaks.push('uuid-like-id');
189
+ return { schema: REPORT_PRIVACY_SCHEMA, ok: leaks.length === 0, leaks, policy: REPORT_POLICY };
190
+ }
191
+
192
+ /**
193
+ * 每日遗忘/衰减槽(只读提案 + 脱敏报告)。
194
+ *
195
+ * @param {object} options
196
+ * @param {string} [options.root] memoryRoot;缺省从 config 解析
197
+ * @param {object} [options.config] 同一份 raw config(decay/forgetV2 整块 passthrough 从这里读)
198
+ * @param {Date|string|number} [options.now]
199
+ * @param {string} [options.day] YYYY-MM-DD 覆盖(默认取 now 的本地日)
200
+ * @param {Function} [options.forget] 注入点(默认 forget.js 的 memoryForget;测试可替换)
201
+ * @param {object} [options.forgetResult] 复用 maintenance.js B2 已跑出的 dry-run 结果,避免重复扫描
202
+ * @param {Function} [options.logger]
203
+ */
204
+ export function runForgetDecayScheduler({
205
+ root = null,
206
+ config = {},
207
+ now = new Date(),
208
+ day = null,
209
+ forget = memoryForget,
210
+ forgetResult = null,
211
+ logger = null,
212
+ } = {}) {
213
+ const memoryRoot = String(root ?? memoryRootFromConfig(config));
214
+ const at = now instanceof Date ? now : new Date(now);
215
+ if (Number.isNaN(at.getTime())) throw memoryError('E_FORGET_SCHEDULER_TIME', 'now 不是合法时间');
216
+ const dayStr = isDayString(day) ? day : dayString(at);
217
+
218
+ let forgetRun = forgetResult;
219
+ if (forgetRun === null || forgetRun === undefined) {
220
+ forgetRun = forget({}, { memoryRoot, now: at });
221
+ }
222
+ if (!forgetRun || forgetRun.ok === false) {
223
+ throw memoryError('E_FORGET_SCHEDULER_FORGET_FAILED', '遗忘 dry-run 没有返回 ok:true,拒绝出报告');
224
+ }
225
+ if (forgetRun.dryRun !== true || forgetRun.applied === true) {
226
+ throw memoryError(
227
+ 'E_FORGET_SCHEDULER_EXECUTED',
228
+ `自动维护只允许 memory_forget dry-run;拿到 dryRun=${String(forgetRun.dryRun)} applied=${String(forgetRun.applied)}。执行只能人工 confirm:"${CONFIRM_WORD}"`,
229
+ );
230
+ }
231
+
232
+ let cards = [];
233
+ try {
234
+ cards = scanCards(memoryRoot).map((card) => ({ ...card, memoryRoot }));
235
+ } catch (error) {
236
+ if (logger) logger(`forget-scheduler: 扫描卡片失败(按 0 张继续):${error?.message ?? error}`);
237
+ cards = [];
238
+ }
239
+ let records = [];
240
+ try {
241
+ records = listRecords({ memoryRoot, limit: 5000 }).items;
242
+ } catch (error) {
243
+ if (logger) logger(`forget-scheduler: 读 records 失败(按 0 条继续):${error?.message ?? error}`);
244
+ records = [];
245
+ }
246
+
247
+ const decay = proposeDecay({ records, cards, now: at, config, root: memoryRoot });
248
+ const rel = decayPendingReportRel(dayStr);
249
+ const text = renderForgetDecayPending({ day: dayStr, at, forget: forgetRun, decay });
250
+ const privacy = scanReportPrivacy(text, { root: memoryRoot });
251
+ if (!privacy.ok) {
252
+ // 不静默放行:报告照写(供人核对),但返回值明确标记隐私审计失败。
253
+ if (logger) logger(`forget-scheduler: 报告隐私扫描命中 ${privacy.leaks.join(',')}`);
254
+ }
255
+ ensureDir(memoryRoot, path.posix.dirname(rel));
256
+ const written = writeFileAtomic(memoryRoot, rel, text, { backup: false, now: at });
257
+ const forgetProposals = Array.isArray(forgetRun.proposals) ? forgetRun.proposals : [];
258
+ const decayPolicy = decay.policy;
259
+
260
+ return {
261
+ ok: true,
262
+ schema: FORGET_SCHEDULER_SCHEMA,
263
+ status: 'dry-run',
264
+ dryRun: true,
265
+ applied: false,
266
+ root: memoryRoot,
267
+ day: dayStr,
268
+ at: at.toISOString(),
269
+ forget: {
270
+ status: String(forgetRun.status ?? 'dry-run'),
271
+ scanned: forgetRun.scanned ?? 0,
272
+ proposals: forgetProposals.length,
273
+ tombstones: forgetProposals.filter((item) => item?.kind === 'tombstone').length,
274
+ epochs: forgetProposals.filter((item) => item?.kind === 'epochs').length,
275
+ immune: (forgetRun.immune ?? []).length,
276
+ undated: (forgetRun.undated ?? []).length,
277
+ dryRunRecorded: forgetRun.dryRunRecorded === true,
278
+ },
279
+ decay: {
280
+ proposals: decay.proposals.length,
281
+ immune: decay.immune.length,
282
+ policy: decayPolicy,
283
+ formula: decayPolicy.formula,
284
+ },
285
+ report: {
286
+ rel,
287
+ path: resolveInside(memoryRoot, rel),
288
+ sha256: written.sha256,
289
+ bytes: written.bytes,
290
+ privacy,
291
+ },
292
+ requiresHumanConfirm: true,
293
+ confirmWord: CONFIRM_WORD,
294
+ message:
295
+ `dry-run:遗忘提案 ${forgetProposals.length}(立碑 ${forgetProposals.filter((item) => item?.kind === 'tombstone').length} / 降级 ${forgetProposals.filter((item) => item?.kind === 'epochs').length}),` +
296
+ `衰减提案 ${decay.proposals.length} 组(>${decayPolicy.unreferencedDays} 天),报告 ${rel}(${written.bytes} B,隐私 ${privacy.ok ? 'ok' : `命中 ${privacy.leaks.join(',')}`});执行需人工 confirm:"${CONFIRM_WORD}"`,
297
+ };
298
+ }
299
+
300
+ /** maintenance.js 合流用的薄别名(语义更贴近「写 pending 报告」)。 */
301
+ export function writeForgetDecayPending(options = {}) {
302
+ return runForgetDecayScheduler(options);
303
+ }