@jjh32456/longlive 1.8.12 → 2.1.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 (92) hide show
  1. package/CHANGELOG.md +258 -202
  2. package/QUICKSTART.md +10 -11
  3. package/README.en.md +13 -4
  4. package/README.md +61 -18
  5. package/SPEC.md +3 -3
  6. package/build-info.json +259 -129
  7. package/cordis.patch.yml +32 -1
  8. package/docs/ANSWER-GUARD.md +1 -1
  9. package/docs/ARCHITECTURE.md +3 -3
  10. package/docs/AUTO-RECALL-WIRING.md +5 -3
  11. package/docs/AUTO-RECALL.md +10 -4
  12. package/docs/CONFIG.md +46 -11
  13. package/docs/ERRORS.md +1 -1
  14. package/docs/FAQ.md +9 -9
  15. package/docs/FEATURES.md +19 -16
  16. package/docs/OPERATIONS.md +3 -3
  17. package/docs/PANEL-INTEGRATION.md +1 -1
  18. package/docs/PRIVACY.md +6 -6
  19. package/docs/QUICKSTART.md +5 -5
  20. package/docs/README.en.md +5 -3
  21. package/docs/TOOLS.md +1 -1
  22. package/docs/TROUBLESHOOTING.md +4 -4
  23. package/package.json +6 -3
  24. package/runbook.md +3 -3
  25. package/scripts/migrate-200.mjs +8 -0
  26. package/scripts/migrate-lifecycle.mjs +2 -2
  27. package/src/answer/claim-guard.mjs +234 -0
  28. package/src/backup.js +165 -1
  29. package/src/config.js +18 -7
  30. package/src/features.js +132 -5
  31. package/src/handoff/index.js +133 -0
  32. package/src/handoff/model.js +48 -0
  33. package/src/identity/handover.js +203 -15
  34. package/src/identity/inject-position.js +3 -1
  35. package/src/index.js +2 -2
  36. package/src/memory/a1-migration.js +72 -6
  37. package/src/memory/archive-cold-state.mjs +794 -0
  38. package/src/memory/archive-staging.mjs +305 -0
  39. package/src/memory/archive.mjs +415 -0
  40. package/src/memory/capture-host.js +71 -2
  41. package/src/memory/capture.js +45 -6
  42. package/src/memory/catchup.mjs +534 -0
  43. package/src/memory/conclusion-distill.js +51 -2
  44. package/src/memory/conclusion-drafts.js +7 -3
  45. package/src/memory/conflicts.js +915 -2
  46. package/src/memory/consolidate.js +20 -1
  47. package/src/memory/forget-v2.js +272 -2
  48. package/src/memory/forget.js +20 -1
  49. package/src/memory/frames-activation.js +3 -1
  50. package/src/memory/fts-query.js +2 -2
  51. package/src/memory/index.js +80 -7
  52. package/src/memory/land.mjs +743 -0
  53. package/src/memory/lifecycle.js +128 -0
  54. package/src/memory/maintenance.js +386 -22
  55. package/src/memory/memory-health.mjs +607 -0
  56. package/src/memory/memory-reader.mjs +1003 -0
  57. package/src/memory/migrate-200.js +1681 -0
  58. package/src/memory/migrate-lifecycle.js +3 -3
  59. package/src/memory/procedure-candidate.mjs +377 -0
  60. package/src/memory/procedure.js +20 -1
  61. package/src/memory/prospective-memory.mjs +362 -0
  62. package/src/memory/recall-feedback.mjs +406 -0
  63. package/src/memory/recall-v2.js +13 -1
  64. package/src/memory/recall.js +102 -1
  65. package/src/memory/reinforce.js +138 -2
  66. package/src/memory/retention.js +34 -0
  67. package/src/memory/turn-budget.mjs +290 -0
  68. package/src/memory/wake-bridge.mjs +2999 -0
  69. package/src/memory/working-frame.js +271 -8
  70. package/src/metrics/classify.mjs +3 -1
  71. package/src/recall/archive-config.mjs +130 -0
  72. package/src/recall/archive-fallback.mjs +174 -19
  73. package/src/recall/archive-search.mjs +3 -0
  74. package/src/recall/archive-state.mjs +588 -0
  75. package/src/recall/brain.mjs +501 -0
  76. package/src/recall/continuity-log.mjs +435 -0
  77. package/src/recall/continuity-volatile.mjs +1001 -0
  78. package/src/recall/current-line.mjs +110 -0
  79. package/src/recall/edges.js +21 -2
  80. package/src/recall/explain.mjs +10 -0
  81. package/src/recall/gate-log.mjs +280 -0
  82. package/src/recall/gate-metrics.mjs +191 -0
  83. package/src/recall/index.js +663 -29
  84. package/src/recall/inject-order.mjs +3 -1
  85. package/src/recall/link-fastpath.mjs +662 -0
  86. package/src/recall/recall-core.mjs +74 -2
  87. package/src/recall/turn-budget-inject.mjs +154 -0
  88. package/src/retention/cold-gate.mjs +146 -0
  89. package/src/retention/config.js +58 -1
  90. package/src/retention/index.js +193 -35
  91. package/src/router/design-headings.json +10 -10
  92. package/src/tools.js +122 -6
@@ -0,0 +1,305 @@
1
+ // src/memory/archive-staging.mjs — B7b 草案:staging 过期归档(d4 唯一红 gateOn.staging.archived)。
2
+ //
3
+ // 背景(lead m00148 + d1d8 报告 + lead m00501 裁决输入):2.0.0 里 archive.mjs 的
4
+ // archiveTurn/maybeAutoRunArchive 没有任何调用点,src 也没有 staging 扫龄代码,所以 d4
5
+ // 门开用例 `staging.archived` 恒红。
6
+ //
7
+ // 裁决(B7B-DRAFT-REPORT.md §裁决,依据 DESIGN.v0.3:120 / DESIGN.v0.4.snapshot:89):
8
+ // - staging 过期 > 7 天未批 → 清退到 `.longlive/archive/staging-expired/`(不可召回),
9
+ // 这是 DESIGN 明文的规范目的地;
10
+ // - `topics/archive/<YYYY-MM>/` 是 L2 活跃卡归档(lifecycle.js:211 / archiveTurn),
11
+ // staging 清退**不走** archiveTurn、不写 topics/archive,避免两套语义混在一个函数里;
12
+ // - d4 断言「`.longlive/archive` 下有副本」为递归判定,`.longlive/archive/staging-expired/`
13
+ // 天然满足 → 夹具无需改期望,也没有适配层;
14
+ // - 调用点 = `runConclusionDistillJob`(lead m00501:staging>7 天归档放进蒸馏 job,
15
+ // catchup 不直接调归档);job 是同步函数,故本模块全同步、零 archive.mjs 依赖
16
+ // (staging 不在 scanCards 召回面,无需重建 INDEX / 写 edges)。
17
+ //
18
+ // 扫龄判据:`.longlive/staging/**/*.md`;年龄取 frontmatter `date:`(YYYY-MM-DD)优先,
19
+ // 缺失/非法才退回 mtime;ageDays = (now - date) / 86400000;严格 > ttlDays(默认 7)才清退;
20
+ // 非 .md、`_` 前缀、`..` 越界、符号链接一律跳过并记 skipped。
21
+ import fs from 'node:fs';
22
+ import path from 'node:path';
23
+ import { createHash } from 'node:crypto';
24
+
25
+ export const STAGING_REL = '.longlive/staging';
26
+ export const STAGING_ARCHIVE_REL = '.longlive/archive/staging-expired';
27
+ export const STAGING_TTL_DAYS = 7;
28
+ export const STAGING_SWEEP_LIMIT = 100;
29
+ export const STAGING_SWEEP_SCHEMA = 'archive-staging-sweep/v1';
30
+ export const STAGING_SKIP_REASONS = Object.freeze([
31
+ 'not-markdown',
32
+ 'underscore-prefix',
33
+ 'symlink',
34
+ 'outside-root',
35
+ 'unreadable',
36
+ 'fresh',
37
+ 'limit',
38
+ ]);
39
+ const DAY_MS = 24 * 60 * 60 * 1000;
40
+ const DATE_RE = /^(\d{4})-(\d{2})-(\d{2})/u;
41
+
42
+ function cleanText(value) {
43
+ return typeof value === 'string' && value.trim() !== '' ? value.trim() : null;
44
+ }
45
+
46
+ function toDate(now) {
47
+ const at = now instanceof Date ? now : new Date(now ?? Date.now());
48
+ return Number.isNaN(at.getTime()) ? new Date() : at;
49
+ }
50
+
51
+ function normRel(value) {
52
+ return String(value ?? '').replace(/\\/g, '/').replace(/^\/+/u, '');
53
+ }
54
+
55
+ function sha256Text(text) {
56
+ return createHash('sha256').update(String(text), 'utf8').digest('hex');
57
+ }
58
+
59
+ function frontmatterDate(text) {
60
+ const src = typeof text === 'string' ? text : '';
61
+ const block = /^---[ \t]*\r?\n([\s\S]*?)\r?\n---[ \t]*(\r?\n|$)/u.exec(src);
62
+ if (!block) return null;
63
+ const line = /^[ \t]*date[ \t]*:[ \t]*(.+)$/m.exec(block[1]);
64
+ if (!line) return null;
65
+ const raw = line[1].trim().replace(/^["']|["']$/gu, '');
66
+ const match = DATE_RE.exec(raw);
67
+ if (!match) return null;
68
+ const ms = Date.parse(`${match[1]}-${match[2]}-${match[3]}T00:00:00Z`);
69
+ return Number.isFinite(ms) ? ms : null;
70
+ }
71
+
72
+ function ageDaysOf(nowMs, thenMs) {
73
+ return (nowMs - thenMs) / DAY_MS;
74
+ }
75
+
76
+ /** 在 frontmatter 里写入/更新清退标记;无 frontmatter 则新建。读写均为 UTF-8 文本。 */
77
+ function withArchivedFrontmatter(text, { at, fromRel, toRel }) {
78
+ const stamp = at.toISOString();
79
+ const fields = [
80
+ 'lifecycle: historical',
81
+ `archived_at: ${stamp}`,
82
+ 'archived_reason: staging-expired',
83
+ `archived_from: ${fromRel}`,
84
+ `archived_to: ${toRel}`,
85
+ ];
86
+ const block = /^---[ \t]*\r?\n([\s\S]*?)\r?\n---[ \t]*(\r?\n|$)/u.exec(text);
87
+ if (!block) return `---\n${fields.join('\n')}\n---\n${text}`;
88
+ let body = block[1];
89
+ for (const line of fields) {
90
+ const key = line.slice(0, line.indexOf(':'));
91
+ const re = new RegExp(`^[ \\t]*${key}[ \\t]*:.*$`, 'mu');
92
+ body = re.test(body) ? body.replace(re, line) : `${body}\n${line}`;
93
+ }
94
+ const tail = text.slice(block[0].length);
95
+ return `---\n${body}\n---\n${tail}`;
96
+ }
97
+
98
+ /**
99
+ * 只读扫描:不移动任何文件。
100
+ * 返回 {schema, root, stagingRoot, ttlDays, limit, scanned, expired, limited, candidates[], skipped[]}。
101
+ * 候选按 rel 升序(确定性),最多 limit 条(多出来的记 skipped reason:'limit')。
102
+ */
103
+ export function scanExpiredStaging({ memoryRoot, now = new Date(), ttlDays = STAGING_TTL_DAYS, limit = STAGING_SWEEP_LIMIT } = {}) {
104
+ const root = cleanText(memoryRoot);
105
+ if (root === null) throw new Error('scanExpiredStaging: memoryRoot 为空');
106
+ const resolvedRoot = path.resolve(root);
107
+ const stagingRoot = path.join(resolvedRoot, ...STAGING_REL.split('/'));
108
+ const nowMs = toDate(now).getTime();
109
+ const ttl = Number.isFinite(ttlDays) ? Math.max(0, Math.floor(ttlDays)) : STAGING_TTL_DAYS;
110
+ const max = Number.isFinite(limit) ? Math.max(1, Math.floor(limit)) : STAGING_SWEEP_LIMIT;
111
+ const files = [];
112
+ const skipped = [];
113
+
114
+ function walk(dir) {
115
+ let entries;
116
+ try {
117
+ entries = fs.readdirSync(dir, { withFileTypes: true });
118
+ } catch (error) {
119
+ if (error?.code === 'ENOENT') return;
120
+ throw error;
121
+ }
122
+ for (const entry of entries.sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0))) {
123
+ const abs = path.join(dir, entry.name);
124
+ if (entry.isSymbolicLink()) {
125
+ skipped.push({ rel: normRel(path.relative(resolvedRoot, abs)), reason: 'symlink' });
126
+ continue;
127
+ }
128
+ if (entry.isDirectory()) {
129
+ walk(abs);
130
+ continue;
131
+ }
132
+ if (!entry.isFile()) continue;
133
+ const rel = normRel(path.relative(resolvedRoot, abs));
134
+ if (rel.split('/').some((seg) => seg === '..')) {
135
+ skipped.push({ rel, reason: 'outside-root' });
136
+ continue;
137
+ }
138
+ if (!/\.md$/iu.test(entry.name)) {
139
+ skipped.push({ rel, reason: 'not-markdown' });
140
+ continue;
141
+ }
142
+ if (entry.name.startsWith('_')) {
143
+ skipped.push({ rel, reason: 'underscore-prefix' });
144
+ continue;
145
+ }
146
+ let stat;
147
+ let text;
148
+ try {
149
+ stat = fs.statSync(abs);
150
+ text = fs.readFileSync(abs, 'utf8');
151
+ } catch {
152
+ skipped.push({ rel, reason: 'unreadable' });
153
+ continue;
154
+ }
155
+ const fmMs = frontmatterDate(text);
156
+ const thenMs = fmMs !== null ? fmMs : stat.mtimeMs;
157
+ const dateSource = fmMs !== null ? 'frontmatter' : 'mtime';
158
+ const ageDays = ageDaysOf(nowMs, thenMs);
159
+ files.push({
160
+ rel,
161
+ abs,
162
+ bytes: stat.size,
163
+ mtimeMs: Math.trunc(stat.mtimeMs),
164
+ dateMs: thenMs,
165
+ dateSource,
166
+ ageDays: Math.round(ageDays * 1000) / 1000,
167
+ });
168
+ }
169
+ }
170
+ try {
171
+ walk(stagingRoot);
172
+ } catch (error) {
173
+ return {
174
+ schema: STAGING_SWEEP_SCHEMA,
175
+ root: resolvedRoot,
176
+ stagingRoot,
177
+ ttlDays: ttl,
178
+ limit: max,
179
+ scanned: 0,
180
+ expired: 0,
181
+ limited: 0,
182
+ candidates: [],
183
+ skipped,
184
+ reasons: { dirUnreadable: String(error?.message ?? error).slice(0, 200) },
185
+ };
186
+ }
187
+
188
+ const expired = files.filter((row) => row.ageDays > ttl);
189
+ expired.sort((a, b) => (a.rel < b.rel ? -1 : a.rel > b.rel ? 1 : 0));
190
+ const candidates = [];
191
+ let limited = 0;
192
+ for (const row of expired) {
193
+ if (candidates.length >= max) {
194
+ limited += 1;
195
+ skipped.push({ rel: row.rel, reason: 'limit' });
196
+ continue;
197
+ }
198
+ candidates.push(row);
199
+ }
200
+ return {
201
+ schema: STAGING_SWEEP_SCHEMA,
202
+ root: resolvedRoot,
203
+ stagingRoot,
204
+ ttlDays: ttl,
205
+ limit: max,
206
+ scanned: files.length,
207
+ expired: expired.length,
208
+ limited,
209
+ candidates,
210
+ skipped,
211
+ };
212
+ }
213
+
214
+ /**
215
+ * 过期清退:dryRun 只回报计划;否则逐条把 staging 卡移到
216
+ * `<memoryRoot>/.longlive/archive/staging-expired/<YYYY-MM>/<basename>`:
217
+ * 1) 目标已存在且内容 sha 相同 → 视为已归档(幂等),移除 staging 源文件;
218
+ * 2) 目标已存在但内容不同 → 该条记 failed(code E_HG_ARCHIVE_TARGET_COLLISION),不动源文件;
219
+ * 3) 写目标(含 lifecycle: historical / archived_* frontmatter)+ fsync 后删源。
220
+ * 单条失败不中断整批;返回 {schema, ok, dryRun, ttlDays, scanned, expired, archived[], failed[], skipped[]}。
221
+ */
222
+ export function sweepExpiredStaging({
223
+ memoryRoot,
224
+ now = new Date(),
225
+ ttlDays = STAGING_TTL_DAYS,
226
+ limit = STAGING_SWEEP_LIMIT,
227
+ dryRun = true,
228
+ } = {}) {
229
+ const at = toDate(now);
230
+ const scan = scanExpiredStaging({ memoryRoot, now: at, ttlDays, limit });
231
+ const result = {
232
+ schema: STAGING_SWEEP_SCHEMA,
233
+ ok: true,
234
+ dryRun: dryRun !== false,
235
+ archiveRel: STAGING_ARCHIVE_REL,
236
+ ttlDays: scan.ttlDays,
237
+ scanned: scan.scanned,
238
+ expired: scan.expired ?? scan.candidates.length,
239
+ candidates: scan.candidates.map((row) => row.rel),
240
+ archived: [],
241
+ failed: [],
242
+ skipped: scan.skipped,
243
+ };
244
+ if (result.dryRun) return result;
245
+ const month = at.toISOString().slice(0, 7);
246
+ for (const row of scan.candidates) {
247
+ const base = path.basename(row.rel);
248
+ const toRel = `${STAGING_ARCHIVE_REL}/${month}/${base}`;
249
+ const toAbs = path.join(scan.root, ...toRel.split('/'));
250
+ try {
251
+ const sourceText = fs.readFileSync(row.abs, 'utf8');
252
+ const stamped = withArchivedFrontmatter(sourceText, { at, fromRel: row.rel, toRel });
253
+ const targetText = stamped;
254
+ const targetSha = sha256Text(targetText);
255
+ if (fs.existsSync(toAbs)) {
256
+ const existing = fs.readFileSync(toAbs, 'utf8');
257
+ if (sha256Text(existing) !== targetSha) {
258
+ result.ok = false;
259
+ result.failed.push({
260
+ rel: row.rel,
261
+ code: 'E_HG_ARCHIVE_TARGET_COLLISION',
262
+ message: `目标已存在且内容不同: ${toRel}`,
263
+ });
264
+ continue;
265
+ }
266
+ fs.unlinkSync(row.abs);
267
+ result.archived.push({ rel: row.rel, to: toRel, bytes: Buffer.byteLength(targetText), ageDays: row.ageDays, alreadyArchived: true });
268
+ continue;
269
+ }
270
+ fs.mkdirSync(path.dirname(toAbs), { recursive: true });
271
+ fs.writeFileSync(toAbs, targetText, { encoding: 'utf8', flag: 'wx' });
272
+ fs.unlinkSync(row.abs);
273
+ result.archived.push({ rel: row.rel, to: toRel, bytes: Buffer.byteLength(targetText), ageDays: row.ageDays, alreadyArchived: false });
274
+ } catch (error) {
275
+ result.ok = false;
276
+ result.failed.push({
277
+ rel: row.rel,
278
+ code: error?.code ?? 'E_HG_ARCHIVE_FAILED',
279
+ message: String(error?.message ?? error).slice(0, 300),
280
+ });
281
+ }
282
+ }
283
+ return result;
284
+ }
285
+
286
+ /**
287
+ * 供 `runConclusionDistillJob` 调用(lead m00501 裁决的调用点):同步、不抛,
288
+ * 返回摘要;失败只记 code/message,不阻断蒸馏。ttlDays 允许 `config.conclusionDraft.stagingTtlDays`
289
+ * 覆盖(缺省 7)。
290
+ */
291
+ export function archiveExpiredStagingJob({ memoryRoot, now = new Date(), ttlDays = STAGING_TTL_DAYS, dryRun = false } = {}) {
292
+ try {
293
+ const swept = sweepExpiredStaging({ memoryRoot, now, ttlDays, dryRun });
294
+ return { ok: swept.ok !== false, ...swept };
295
+ } catch (error) {
296
+ return {
297
+ schema: STAGING_SWEEP_SCHEMA,
298
+ ok: false,
299
+ code: error?.code ?? 'E_HG_ARCHIVE_FAILED',
300
+ message: String(error?.message ?? error).slice(0, 300),
301
+ archived: [],
302
+ failed: [],
303
+ };
304
+ }
305
+ }