@jjh32456/longlive 1.8.12 → 2.0.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 (83) hide show
  1. package/CHANGELOG.md +232 -202
  2. package/QUICKSTART.md +10 -11
  3. package/README.en.md +13 -4
  4. package/README.md +42 -11
  5. package/SPEC.md +3 -3
  6. package/build-info.json +231 -121
  7. package/cordis.patch.yml +32 -1
  8. package/docs/ARCHITECTURE.md +1 -1
  9. package/docs/AUTO-RECALL.md +1 -1
  10. package/docs/CONFIG.md +41 -9
  11. package/docs/FAQ.md +7 -7
  12. package/docs/FEATURES.md +6 -6
  13. package/docs/OPERATIONS.md +1 -1
  14. package/docs/PANEL-INTEGRATION.md +1 -1
  15. package/docs/PRIVACY.md +5 -5
  16. package/docs/QUICKSTART.md +3 -3
  17. package/docs/README.en.md +4 -2
  18. package/docs/TROUBLESHOOTING.md +4 -4
  19. package/package.json +6 -3
  20. package/runbook.md +3 -3
  21. package/scripts/migrate-200.mjs +8 -0
  22. package/scripts/migrate-lifecycle.mjs +2 -2
  23. package/src/answer/claim-guard.mjs +234 -0
  24. package/src/backup.js +165 -1
  25. package/src/config.js +18 -7
  26. package/src/features.js +128 -5
  27. package/src/handoff/index.js +133 -0
  28. package/src/handoff/model.js +48 -0
  29. package/src/identity/handover.js +203 -15
  30. package/src/identity/inject-position.js +3 -1
  31. package/src/memory/a1-migration.js +72 -6
  32. package/src/memory/archive-cold-state.mjs +794 -0
  33. package/src/memory/archive-staging.mjs +305 -0
  34. package/src/memory/archive.mjs +415 -0
  35. package/src/memory/capture-host.js +71 -2
  36. package/src/memory/capture.js +45 -6
  37. package/src/memory/catchup.mjs +534 -0
  38. package/src/memory/conclusion-distill.js +51 -2
  39. package/src/memory/conclusion-drafts.js +7 -3
  40. package/src/memory/conflicts.js +915 -2
  41. package/src/memory/consolidate.js +20 -1
  42. package/src/memory/forget-v2.js +272 -2
  43. package/src/memory/forget.js +20 -1
  44. package/src/memory/frames-activation.js +3 -1
  45. package/src/memory/fts-query.js +2 -2
  46. package/src/memory/index.js +80 -7
  47. package/src/memory/land.mjs +743 -0
  48. package/src/memory/lifecycle.js +128 -0
  49. package/src/memory/maintenance.js +386 -22
  50. package/src/memory/memory-health.mjs +607 -0
  51. package/src/memory/migrate-200.js +1681 -0
  52. package/src/memory/migrate-lifecycle.js +3 -3
  53. package/src/memory/procedure-candidate.mjs +377 -0
  54. package/src/memory/procedure.js +20 -1
  55. package/src/memory/prospective-memory.mjs +362 -0
  56. package/src/memory/recall-feedback.mjs +406 -0
  57. package/src/memory/recall-v2.js +13 -1
  58. package/src/memory/recall.js +102 -1
  59. package/src/memory/reinforce.js +138 -2
  60. package/src/memory/retention.js +34 -0
  61. package/src/memory/turn-budget.mjs +290 -0
  62. package/src/memory/wake-bridge.mjs +2999 -0
  63. package/src/memory/working-frame.js +271 -8
  64. package/src/metrics/classify.mjs +3 -1
  65. package/src/recall/archive-config.mjs +130 -0
  66. package/src/recall/archive-fallback.mjs +174 -19
  67. package/src/recall/archive-search.mjs +3 -0
  68. package/src/recall/archive-state.mjs +588 -0
  69. package/src/recall/brain.mjs +501 -0
  70. package/src/recall/current-line.mjs +110 -0
  71. package/src/recall/edges.js +21 -2
  72. package/src/recall/explain.mjs +10 -0
  73. package/src/recall/gate-log.mjs +280 -0
  74. package/src/recall/gate-metrics.mjs +191 -0
  75. package/src/recall/index.js +322 -21
  76. package/src/recall/inject-order.mjs +3 -1
  77. package/src/recall/recall-core.mjs +47 -2
  78. package/src/recall/turn-budget-inject.mjs +154 -0
  79. package/src/retention/cold-gate.mjs +146 -0
  80. package/src/retention/config.js +58 -1
  81. package/src/retention/index.js +193 -35
  82. package/src/router/design-headings.json +10 -10
  83. package/src/tools.js +122 -6
@@ -0,0 +1,607 @@
1
+ // src/memory/memory-health.mjs — D21 记忆体检:唯一 health producer。
2
+ //
3
+ // 契约来源:V0.5.2-MERGE-PLAN v3.6.4 §4⑩ / §14 D21 行 / §19 状态文件上界;
4
+ // DESIGN v0.5.1 §9.13 / §16「体检」。
5
+ // 写:`<memoryRoot>/.longlive/hardgate/health-YYYY-MM-DD.json`(tmp→fsync→rename,
6
+ // 同日重算覆盖:最新 generatedAt 为准;失败保留旧文件);
7
+ // schema `hardgate-health/v1` =
8
+ // { schema, date, generatedAt, status:'ok'|'empty'|'error',
9
+ // counts:{write,inject,skip,zeroHit,distill,candidates,historical,budget,errors},
10
+ // review, forget, sources:[{name,sha256,rows}], errorCodes };
11
+ // 只读 gate-log / land-log / recall gate 行(本模块不写 gate-log,不写 hg.d21.fail);
12
+ // 零数据写 status:'empty' + 计数 0 的空态文件(不许缺失);≤64 KiB;保留 90 个日文件;
13
+ // 拒 symlink;坏 JSON 不归零(保留旧文件 + errorCodes + stderr);目录缺=healthPresent:null,
14
+ // 文件缺=healthPresent:false(体检未产生)。
15
+ // v1 失败通道:health 文件 errorCodes(E_HEALTH_WRITE_FAILED / E_HEALTH_READ_FAILED)+ stderr;
16
+ // 不扩 gate 闭枚举(不写 hg.d21.fail)。
17
+
18
+ import crypto from 'node:crypto';
19
+ import fs from 'node:fs';
20
+ import path from 'node:path';
21
+
22
+ import { nextLocalMidnight } from './maintenance.js';
23
+
24
+ export const BATCH = 'G';
25
+ export const MODULE = 'memory/memory-health.mjs';
26
+ export const HEALTH_SCHEMA = 'hardgate-health/v1';
27
+ export const HEALTH_DIR_REL = '.longlive/hardgate';
28
+ export const HEALTH_FILE_PREFIX = 'health-';
29
+ export const HEALTH_FILE_SUFFIX = '.json';
30
+ export const MAX_BYTES = 65536;
31
+ export const KEEP_DAYS = 90;
32
+ export const INJECT_BUDGET_CHARS = 2000;
33
+ export const STATUSES = Object.freeze(['ok', 'empty', 'error']);
34
+ export const ERROR_CODES = Object.freeze(['E_HEALTH_WRITE_FAILED', 'E_HEALTH_READ_FAILED']);
35
+ /** 兼容占位:已实装(fail-closed 占位扫描按 SKELETON.implemented 判)。 */
36
+ export const UNIMPLEMENTED_CODE = 'E_HG_MEMORY_HEALTH_UNIMPLEMENTED';
37
+ export const SKELETON = Object.freeze({
38
+ version: '2.0.0',
39
+ failClosed: true,
40
+ batch: BATCH,
41
+ implemented: true,
42
+ });
43
+ export const UNSET = Object.freeze({ status: 'UNSET' });
44
+
45
+ /** 只读来源(相对 memoryRoot);gate-log / land-log 是 §4⑩ 点名的两个日志。 */
46
+ export const LAND_LOG_REL = '.longlive/hardgate/land-log.jsonl';
47
+ export const GATE_LOG_REL = '.longlive/hardgate/gate-log.jsonl';
48
+ export const CONFLICT_CANDIDATES_REL = '.longlive/hardgate/conflict-candidates.jsonl';
49
+ export const PROCEDURE_CANDIDATES_REL = '.longlive/hardgate/procedure-candidates.jsonl';
50
+ export const FORGET_SUGGESTIONS_REL = '.longlive/hardgate/forget-suggestions.jsonl';
51
+
52
+ const LOG_SOURCES = Object.freeze([
53
+ Object.freeze({ name: 'land-log.jsonl', rel: LAND_LOG_REL, kind: 'land' }),
54
+ Object.freeze({ name: 'gate-log.jsonl', rel: GATE_LOG_REL, kind: 'gate' }),
55
+ Object.freeze({ name: 'conflict-candidates.jsonl', rel: CONFLICT_CANDIDATES_REL, kind: 'conflict-candidates' }),
56
+ Object.freeze({ name: 'procedure-candidates.jsonl', rel: PROCEDURE_CANDIDATES_REL, kind: 'procedure-candidates' }),
57
+ ]);
58
+
59
+ function healthError(code, message, details) {
60
+ const error = new Error(message);
61
+ error.code = ERROR_CODES.includes(code) ? code : 'E_HEALTH_READ_FAILED';
62
+ if (details !== undefined) error.details = details;
63
+ return error;
64
+ }
65
+
66
+ function warn(logger, code, detail) {
67
+ // 失败通道(v1):写 health 文件 errorCodes + stderr;不写 hg.d21.fail 门事件。
68
+ const message = `[longlive] memory-health ${code}: ${detail}`;
69
+ if (typeof logger === 'function') {
70
+ try { logger(message); } catch { /* logger 不得影响体检 */ }
71
+ return;
72
+ }
73
+ if (logger !== null && typeof logger === 'object' && typeof logger.warn === 'function') {
74
+ try { logger.warn(code, detail); } catch { /* logger 不得影响体检 */ }
75
+ return;
76
+ }
77
+ try { process.stderr.write(message + '\n'); } catch { /* stderr 不可用时不阻断 */ }
78
+ }
79
+
80
+ function rootOf(memoryRoot) {
81
+ const root = String(memoryRoot ?? '').trim();
82
+ if (root === '') throw healthError('E_HEALTH_READ_FAILED', 'memory-health 需要 memoryRoot');
83
+ return path.resolve(root);
84
+ }
85
+
86
+ function nowMsOf(now) {
87
+ if (now instanceof Date && Number.isFinite(now.getTime())) return now.getTime();
88
+ if (typeof now === 'function') {
89
+ const value = now();
90
+ const iso = nowMsOf(value);
91
+ return iso;
92
+ }
93
+ if (typeof now === 'number' && Number.isFinite(now)) return now;
94
+ if (typeof now === 'string' && Number.isFinite(Date.parse(now))) return Date.parse(now);
95
+ return Date.now();
96
+ }
97
+
98
+ /** 本地(Asia/Shanghai,+08:00)日期 YYYY-MM-DD;与夹具 harness todayOf 同口径。 */
99
+ export function localDateOf(now) {
100
+ const ms = nowMsOf(now);
101
+ return new Date(ms + 8 * 60 * 60 * 1000).toISOString().slice(0, 10);
102
+ }
103
+
104
+ export function healthDirOf(memoryRoot) {
105
+ return path.join(rootOf(memoryRoot), ...HEALTH_DIR_REL.split('/'));
106
+ }
107
+
108
+ export function healthFilePath(memoryRoot, date) {
109
+ const day = String(date ?? localDateOf(Date.now()));
110
+ if (!/^\d{4}-\d{2}-\d{2}$/.test(day)) throw healthError('E_HEALTH_WRITE_FAILED', `health 日期非法:${day}`);
111
+ return path.join(healthDirOf(memoryRoot), `${HEALTH_FILE_PREFIX}${day}${HEALTH_FILE_SUFFIX}`);
112
+ }
113
+
114
+ function sha256Of(buf) {
115
+ return crypto.createHash('sha256').update(buf).digest('hex');
116
+ }
117
+
118
+ function readJsonlFile(absPath) {
119
+ if (!fs.existsSync(absPath)) return { exists: false, rows: [], sha256: null, bytes: 0 };
120
+ const buf = fs.readFileSync(absPath);
121
+ const rows = [];
122
+ const text = buf.toString('utf8');
123
+ for (const [index, line] of text.split(/\r?\n/).entries()) {
124
+ if (line.trim() === '') continue;
125
+ try {
126
+ rows.push(JSON.parse(line));
127
+ } catch (error) {
128
+ throw healthError('E_HEALTH_READ_FAILED', `坏 JSON:${absPath}:${index + 1}`, {
129
+ file: absPath, line: index + 1, reason: String(error?.message ?? error),
130
+ });
131
+ }
132
+ }
133
+ return { exists: true, rows, sha256: sha256Of(buf), bytes: buf.length };
134
+ }
135
+
136
+ function lstatOrNull(absPath) {
137
+ try { return fs.lstatSync(absPath); } catch (error) {
138
+ if (error && error.code === 'ENOENT') return null;
139
+ throw healthError('E_HEALTH_READ_FAILED', `无法读取 ${absPath}: ${error?.code ?? error}`);
140
+ }
141
+ }
142
+
143
+ function assertNotSymlink(absPath) {
144
+ const stat = lstatOrNull(absPath);
145
+ if (stat && stat.isSymbolicLink()) {
146
+ throw healthError('E_HEALTH_WRITE_FAILED', `拒绝写 symlink:${absPath}`);
147
+ }
148
+ return stat;
149
+ }
150
+
151
+ /** 汇总行(夹具行 / 真实 land-log 行 / gate-log 行都吃)。 */
152
+ export function summarizeRows(rows) {
153
+ const counts = { write: 0, inject: 0, skip: 0, zeroHit: 0, distill: 0, candidates: 0, historical: 0, budget: INJECT_BUDGET_CHARS, errors: 0 };
154
+ const errorCodes = [];
155
+ const list = Array.isArray(rows) ? rows : [];
156
+ let recallRows = 0;
157
+ let gateRecallRows = 0;
158
+ let landRows = 0;
159
+ for (const row of list) {
160
+ if (row === null || typeof row !== 'object') continue;
161
+ const kind = String(row.kind ?? '');
162
+ const gate = String(row.gate ?? '');
163
+ const decision = String(row.decision ?? '');
164
+ const isGateRow = kind === 'gate' || (gate !== '' && decision !== '');
165
+ if (kind === 'land' || (typeof row.landed === 'boolean' && gate === '')) {
166
+ landRows += 1;
167
+ const writes = Number(row.writes);
168
+ counts.write += Number.isFinite(writes) ? writes : (row.landed === true ? 1 : 0);
169
+ continue;
170
+ }
171
+ if (kind === 'recall') {
172
+ recallRows += 1;
173
+ counts.inject += Number.isFinite(Number(row.injected)) ? Number(row.injected) : (decision === 'ok' ? 1 : 0);
174
+ counts.skip += Number.isFinite(Number(row.skipped)) ? Number(row.skipped) : (decision === 'skip' ? 1 : 0);
175
+ counts.zeroHit += row.zeroHit === true || decision === 'zero-hit' ? 1 : 0;
176
+ counts.historical += Number.isFinite(Number(row.historical)) ? Number(row.historical) : 0;
177
+ continue;
178
+ }
179
+ if (kind === 'distill') { counts.distill += 1; continue; }
180
+ if (kind === 'conflict-candidates' || kind === 'procedure-candidates' || kind === 'candidates') { counts.candidates += 1; continue; }
181
+ if (isGateRow) {
182
+ if (gate === 'recall') gateRecallRows += 1;
183
+ if (decision === 'fail') {
184
+ counts.errors += 1;
185
+ if (typeof row.code === 'string' && row.code !== '') errorCodes.push(row.code);
186
+ }
187
+ continue;
188
+ }
189
+ }
190
+ // 真实 recall 只发 gate-log 行(gate:'recall',decision 枚举见 gate-log.mjs);
191
+ // 没有 kind:'recall' 行时用它派生 inject/skip/zeroHit。
192
+ if (recallRows === 0 && gateRecallRows > 0) {
193
+ for (const row of list) {
194
+ if (String(row.gate ?? '') !== 'recall') continue;
195
+ const decision = String(row.decision ?? '');
196
+ if (decision === 'ok') counts.inject += 1;
197
+ else if (decision === 'skip') counts.skip += 1;
198
+ else if (decision === 'zero-hit') counts.zeroHit += 1;
199
+ }
200
+ }
201
+ return { counts, errorCodes, rowCounts: { land: landRows, recall: recallRows, gateRecall: gateRecallRows } };
202
+ }
203
+
204
+ function emptyStateDoc(date, generatedAt) {
205
+ return {
206
+ schema: HEALTH_SCHEMA,
207
+ date,
208
+ generatedAt,
209
+ status: 'empty',
210
+ counts: { write: 0, inject: 0, skip: 0, zeroHit: 0, distill: 0, candidates: 0, historical: 0, budget: INJECT_BUDGET_CHARS, errors: 0 },
211
+ review: { due: 0, injected: 0 },
212
+ forget: { suggestions: 0 },
213
+ sources: [],
214
+ errorCodes: [],
215
+ };
216
+ }
217
+
218
+ function existingHealthDoc(memoryRoot, date) {
219
+ const file = healthFilePath(memoryRoot, date);
220
+ if (!fs.existsSync(file)) return null;
221
+ try {
222
+ return { file, doc: JSON.parse(fs.readFileSync(file, 'utf8')) };
223
+ } catch {
224
+ return { file, doc: null };
225
+ }
226
+ }
227
+
228
+ /**
229
+ * 原子写:tmp → fsync → rename。拒 symlink;超 64 KiB 抛 E_HEALTH_WRITE_FAILED。
230
+ * 返回写入字节数与文件路径。
231
+ */
232
+ export function writeHealthDoc(memoryRoot, doc, options = {}) {
233
+ const dir = healthDirOf(memoryRoot);
234
+ const file = healthFilePath(memoryRoot, doc.date);
235
+ ensureHealthDir(dir);
236
+ assertNotSymlink(file);
237
+ const body = JSON.stringify(doc, null, 2) + '\n';
238
+ const bytes = Buffer.byteLength(body, 'utf8');
239
+ if (bytes > MAX_BYTES) {
240
+ throw healthError('E_HEALTH_WRITE_FAILED', `health 文件超 ${MAX_BYTES} B:${bytes}`);
241
+ }
242
+ const tmp = path.join(dir, `.${path.basename(file)}.${process.pid}.${Date.now()}.tmp`);
243
+ assertNotSymlink(tmp);
244
+ const fd = fs.openSync(tmp, 'wx');
245
+ try {
246
+ fs.writeFileSync(fd, body, 'utf8');
247
+ fs.fsyncSync(fd);
248
+ } finally {
249
+ fs.closeSync(fd);
250
+ }
251
+ fs.renameSync(tmp, file);
252
+ if (options.prune !== false) pruneHealthFiles(memoryRoot);
253
+ return { file, bytes };
254
+ }
255
+
256
+ function ensureHealthDir(dir) {
257
+ if (fs.existsSync(dir)) {
258
+ const stat = assertNotSymlink(dir);
259
+ if (!stat.isDirectory()) throw healthError('E_HEALTH_WRITE_FAILED', `health 目录不是目录:${dir}`);
260
+ return;
261
+ }
262
+ fs.mkdirSync(dir, { recursive: true });
263
+ }
264
+
265
+ /** 保留最近 KEEP_DAYS 个 health-YYYY-MM-DD.json(按日期名排序,多的删旧的)。 */
266
+ export function pruneHealthFiles(memoryRoot, options = {}) {
267
+ const dir = healthDirOf(memoryRoot);
268
+ const keep = Number.isFinite(Number(options.keep)) ? Math.max(1, Number(options.keep)) : KEEP_DAYS;
269
+ if (!fs.existsSync(dir) || assertNotSymlink(dir).isDirectory() !== true) return { removed: [] };
270
+ const files = fs.readdirSync(dir)
271
+ .filter((name) => new RegExp(`^${HEALTH_FILE_PREFIX}\\d{4}-\\d{2}-\\d{2}${HEALTH_FILE_SUFFIX.replace('.', '\\.')}$`).test(name))
272
+ .sort();
273
+ const removed = [];
274
+ while (files.length > keep) {
275
+ const name = files.shift();
276
+ const abs = path.join(dir, name);
277
+ try {
278
+ fs.unlinkSync(abs);
279
+ removed.push(name);
280
+ } catch (error) {
281
+ throw healthError('E_HEALTH_WRITE_FAILED', `保留策略删除失败:${abs}: ${error?.code ?? error}`);
282
+ }
283
+ }
284
+ return { removed };
285
+ }
286
+
287
+ /** 只读读取某日 health 文件(面板/夹具用)。 */
288
+ export function readHealth(memoryRoot, options = {}) {
289
+ const date = String(options.date ?? localDateOf(options.now ?? Date.now()));
290
+ const dir = healthDirOf(memoryRoot);
291
+ if (!fs.existsSync(dir)) return { healthPresent: null, date, dir };
292
+ if (assertNotSymlink(dir).isDirectory() !== true) return { healthPresent: null, date, dir };
293
+ const file = healthFilePath(memoryRoot, date);
294
+ if (!fs.existsSync(file)) return { healthPresent: false, date, file };
295
+ try {
296
+ return { healthPresent: true, date, file, doc: JSON.parse(fs.readFileSync(file, 'utf8')) };
297
+ } catch (error) {
298
+ return { healthPresent: true, date, file, doc: null, code: 'E_HEALTH_READ_FAILED', reason: String(error?.message ?? error) };
299
+ }
300
+ }
301
+
302
+ function readDiskSources(memoryRoot) {
303
+ const root = rootOf(memoryRoot);
304
+ const rows = [];
305
+ const sources = [];
306
+ const errorCodes = [];
307
+ for (const source of LOG_SOURCES) {
308
+ const abs = path.join(root, ...source.rel.split('/'));
309
+ let read;
310
+ try {
311
+ read = readJsonlFile(abs);
312
+ } catch (error) {
313
+ errorCodes.push(error.code);
314
+ throw Object.assign(error, { errorCodes });
315
+ }
316
+ if (!read.exists) continue;
317
+ rows.push(...read.rows.map((row) => ({ ...row, kind: source.kind })));
318
+ sources.push({ name: source.name, sha256: read.sha256, rows: read.rows.length });
319
+ }
320
+ return { rows, sources, errorCodes };
321
+ }
322
+
323
+ function readCountsFromStateFiles(memoryRoot) {
324
+ const root = rootOf(memoryRoot);
325
+ const read = (rel) => {
326
+ const abs = path.join(root, ...rel.split('/'));
327
+ if (!fs.existsSync(abs)) return null;
328
+ try { return readJsonlFile(abs); } catch { return null; }
329
+ };
330
+ const forget = read(FORGET_SUGGESTIONS_REL);
331
+ return {
332
+ review: { due: 0, injected: 0 },
333
+ forget: { suggestions: forget ? forget.rows.length : 0 },
334
+ };
335
+ }
336
+
337
+ /**
338
+ * 体检主入口:读只读日志 → 汇总九组 counts → 原子写 health-<date>.json。
339
+ * input: { memoryRoot, now?, logs?, logger?, prune? }
340
+ * logs 给定时按夹具行汇总(不读盘);否则读 land-log/gate-log/candidate 文件。
341
+ * 返回 { ok:true, status, date, file, bytes, counts, sources, errorCodes };
342
+ * 读失败返回 { ok:false, code:'E_HEALTH_READ_FAILED', keptOld:boolean, file? }(不写零)。
343
+ */
344
+ export function buildMemoryHealth(input = {}) {
345
+ const memoryRoot = input.memoryRoot;
346
+ const logger = input.logger;
347
+ const atMs = nowMsOf(input.now);
348
+ const date = localDateOf(atMs);
349
+ const generatedAt = new Date(atMs).toISOString();
350
+ let root;
351
+ try {
352
+ root = rootOf(memoryRoot);
353
+ } catch (error) {
354
+ warn(logger, error.code, error.message);
355
+ return { ok: false, code: error.code, status: 'error', errorCodes: [error.code], date };
356
+ }
357
+ let rows;
358
+ let sources;
359
+ if (Array.isArray(input.logs)) {
360
+ rows = input.logs.slice();
361
+ sources = [{ name: 'fixture-logs', sha256: sha256Of(Buffer.from(JSON.stringify(input.logs), 'utf8')), rows: rows.length }];
362
+ } else {
363
+ try {
364
+ const read = readDiskSources(root);
365
+ rows = read.rows;
366
+ sources = read.sources;
367
+ } catch (error) {
368
+ const code = ERROR_CODES.includes(error?.code) ? error.code : 'E_HEALTH_READ_FAILED';
369
+ warn(logger, code, error?.message ?? String(error));
370
+ const existing = existingHealthDoc(root, date);
371
+ return { ok: false, code, status: 'error', errorCodes: [code], date, keptOld: existing !== null, file: existing ? existing.file : null };
372
+ }
373
+ }
374
+ const { counts } = summarizeRows(rows);
375
+ const extra = readCountsFromStateFiles(root);
376
+ const hasData = rows.length > 0
377
+ || counts.write > 0 || counts.inject > 0 || counts.skip > 0 || counts.zeroHit > 0
378
+ || counts.distill > 0 || counts.candidates > 0 || counts.errors > 0;
379
+ const doc = {
380
+ schema: HEALTH_SCHEMA,
381
+ date,
382
+ generatedAt,
383
+ status: hasData ? 'ok' : 'empty',
384
+ counts,
385
+ review: extra.review,
386
+ forget: extra.forget,
387
+ sources,
388
+ errorCodes: [],
389
+ };
390
+ try {
391
+ const written = writeHealthDoc(root, doc, { prune: input.prune });
392
+ return { ok: true, status: doc.status, date, file: written.file, bytes: written.bytes, counts, sources, errorCodes: [] };
393
+ } catch (error) {
394
+ const code = ERROR_CODES.includes(error?.code) ? error.code : 'E_HEALTH_WRITE_FAILED';
395
+ warn(logger, code, error?.message ?? String(error));
396
+ const existing = existingHealthDoc(root, date);
397
+ return { ok: false, code, status: 'error', errorCodes: [code], date, keptOld: existing !== null, file: existing ? existing.file : null };
398
+ }
399
+ }
400
+
401
+ export const memoryHealth = buildMemoryHealth;
402
+ export const computeHealth = buildMemoryHealth;
403
+ export const computeMemoryHealth = buildMemoryHealth;
404
+
405
+ export const compute = buildMemoryHealth;
406
+
407
+ export const build = buildMemoryHealth;
408
+
409
+ /** 旧版 UTC 边界调度器(保留给脚本/手动调用);D21 接线用下方 registerDailyHealth(本地午夜 + 同日节流)。 */
410
+ export function createHealthScheduler(options = {}) {
411
+ const memoryRoot = options.memoryRoot;
412
+ const timers = options.timers && typeof options.timers.setTimeout === 'function' ? options.timers : { setTimeout, clearTimeout };
413
+ const now = options.now;
414
+ const logger = options.logger;
415
+ const startupDelayMs = Number.isFinite(Number(options.startupDelayMs)) ? Math.max(0, Number(options.startupDelayMs)) : 1500;
416
+ let timer = null;
417
+ let started = false;
418
+ let lastRun = null;
419
+ const runOnce = () => {
420
+ const result = buildMemoryHealth({ memoryRoot, now, logger });
421
+ lastRun = { at: new Date(nowMsOf(now)).toISOString(), ok: result.ok === true, status: result.status, code: result.code ?? null };
422
+ return result;
423
+ };
424
+ const nextMidnightDelay = () => {
425
+ const ms = nowMsOf(now);
426
+ const dayMs = 24 * 60 * 60 * 1000;
427
+ const next = Math.floor(ms / dayMs) * dayMs + dayMs + 1000;
428
+ return Math.max(1000, next - ms);
429
+ };
430
+ const schedule = () => {
431
+ if (!started) return;
432
+ timer = timers.setTimeout(() => {
433
+ if (!started) return;
434
+ runOnce();
435
+ schedule();
436
+ }, nextMidnightDelay());
437
+ };
438
+ return {
439
+ start() {
440
+ if (started) return { started: false, reason: 'already-started' };
441
+ started = true;
442
+ timer = timers.setTimeout(() => {
443
+ if (!started) return;
444
+ runOnce();
445
+ schedule();
446
+ }, startupDelayMs);
447
+ return { started: true, startupDelayMs, nextMidnightDelay: nextMidnightDelay() };
448
+ },
449
+ stop() {
450
+ started = false;
451
+ if (timer && typeof timers.clearTimeout === 'function') timers.clearTimeout(timer);
452
+ timer = null;
453
+ return { stopped: true };
454
+ },
455
+ runOnce,
456
+ health() { return lastRun; },
457
+ };
458
+ }
459
+
460
+ /**
461
+ * D21 §14 接线用:每日体检 job(features.js 在 memoryV2 打开且有 memoryRoot 时注册)。
462
+ *
463
+ * 语义:
464
+ * - 单 timer:启动后轻量跑一次,此后每日本地午夜一次;`start()`/`stop()` 幂等;
465
+ * - 同日最多落一份文件:同一天第二次 runOnce 直接跳过(不重写 health 文件);
466
+ * - 成功走 buildMemoryHealth(原子写 + 默认 prune 保留 90 份);
467
+ * - 失败不抛:把 errorCodes 写进 health 文件(当日文件存在则保留 counts 只追加
468
+ * status/errorCodes;不存在则写 status:'error' 的占位,明确「体检失败、counts 未采到」),
469
+ * 并走 stderr/logger;不写 gate 事件(v1 失败通道约定)。
470
+ */
471
+ export function registerDailyHealth(options = {}) {
472
+ const memoryRoot = options.memoryRoot;
473
+ const timers = options.timers && typeof options.timers.setTimeout === 'function'
474
+ ? options.timers
475
+ : { setTimeout, clearTimeout };
476
+ const now = options.now;
477
+ const logger = options.logger;
478
+ const startupDelayMs = Number.isFinite(Number(options.startupDelayMs))
479
+ ? Math.max(0, Number(options.startupDelayMs))
480
+ : 1500;
481
+ let timer = null;
482
+ let started = false;
483
+ let lastDate = null;
484
+ let lastRun = null;
485
+ const enabled = typeof memoryRoot === 'string' && memoryRoot.trim() !== '';
486
+
487
+ const errorCodesOf = (result) => (Array.isArray(result?.errorCodes) && result.errorCodes.length > 0
488
+ ? result.errorCodes.filter((code) => typeof code === 'string' && code !== '')
489
+ : ['E_HEALTH_READ_FAILED']);
490
+
491
+ /** 失败落盘:health 文件必须带 errorCodes;保留既有 counts(不归零)。 */
492
+ const annotateFailure = (result, atMs) => {
493
+ try {
494
+ const date = typeof result?.date === 'string' ? result.date : localDateOf(atMs);
495
+ const existing = existingHealthDoc(memoryRoot, date);
496
+ const base = existing && existing.doc && typeof existing.doc === 'object'
497
+ ? existing.doc
498
+ : {
499
+ schema: HEALTH_SCHEMA,
500
+ date,
501
+ status: 'error',
502
+ counts: {
503
+ write: 0, inject: 0, skip: 0, zeroHit: 0, distill: 0, candidates: 0, historical: 0, budget: INJECT_BUDGET_CHARS, errors: 0,
504
+ },
505
+ review: { due: 0, injected: 0 },
506
+ forget: { suggestions: 0 },
507
+ sources: [],
508
+ errorCodes: [],
509
+ };
510
+ const mergedCodes = [...new Set([
511
+ ...(Array.isArray(base.errorCodes) ? base.errorCodes : []),
512
+ ...errorCodesOf(result),
513
+ ])];
514
+ const doc = {
515
+ ...base,
516
+ date,
517
+ status: 'error',
518
+ generatedAt: new Date(atMs).toISOString(),
519
+ failedAt: new Date(atMs).toISOString(),
520
+ errorCodes: mergedCodes,
521
+ };
522
+ const written = writeHealthDoc(memoryRoot, doc, { prune: true });
523
+ return written.file;
524
+ } catch (error) {
525
+ warn(logger, ERROR_CODES.includes(error?.code) ? error.code : 'E_HEALTH_WRITE_FAILED', error?.message ?? String(error));
526
+ return null;
527
+ }
528
+ };
529
+
530
+ const runOnce = () => {
531
+ const atMs = nowMsOf(now);
532
+ const date = localDateOf(atMs);
533
+ if (lastDate === date) {
534
+ lastRun = { at: new Date(atMs).toISOString(), date, skipped: true, reason: 'already-ran-today' };
535
+ return { ok: true, skipped: true, reason: 'already-ran-today', date };
536
+ }
537
+ let result;
538
+ try {
539
+ result = buildMemoryHealth({ memoryRoot, now: atMs, logger });
540
+ } catch (error) {
541
+ const code = ERROR_CODES.includes(error?.code) ? error.code : 'E_HEALTH_WRITE_FAILED';
542
+ warn(logger, code, error?.message ?? String(error));
543
+ result = { ok: false, code, status: 'error', errorCodes: [code], date };
544
+ }
545
+ let file = typeof result?.file === 'string' ? result.file : null;
546
+ if (result?.ok === false) file = annotateFailure(result, atMs) ?? file;
547
+ lastDate = date;
548
+ lastRun = {
549
+ at: new Date(atMs).toISOString(),
550
+ date,
551
+ ok: result?.ok === true,
552
+ status: result?.status ?? 'error',
553
+ code: result?.code ?? null,
554
+ errorCodes: errorCodesOf(result),
555
+ file,
556
+ };
557
+ return result;
558
+ };
559
+
560
+ const nextDelayMs = () => {
561
+ const ms = nowMsOf(now);
562
+ return Math.max(1000, nextLocalMidnight(new Date(ms)).getTime() - ms);
563
+ };
564
+
565
+ const arm = (ms) => {
566
+ timer = timers.setTimeout(() => {
567
+ if (!started) return;
568
+ try {
569
+ runOnce();
570
+ } catch (error) {
571
+ // runOnce 自身已兜底;这一层只保证 timer 回调永不把异常抛进宿主。
572
+ warn(logger, 'E_HEALTH_WRITE_FAILED', error?.message ?? String(error));
573
+ }
574
+ schedule();
575
+ }, ms);
576
+ if (timer && typeof timer.unref === 'function') timer.unref();
577
+ };
578
+
579
+ function schedule() {
580
+ if (!started) return;
581
+ arm(nextDelayMs());
582
+ }
583
+
584
+ return {
585
+ enabled,
586
+ startupDelayMs,
587
+ memoryRoot: memoryRoot ?? null,
588
+ start() {
589
+ if (!enabled) return { started: false, reason: 'no-memory-root' };
590
+ if (started) return { started: false, reason: 'already-started' };
591
+ started = true;
592
+ arm(startupDelayMs);
593
+ return { started: true, startupDelayMs, nextRunAt: new Date(nowMsOf(now) + nextDelayMs()).toISOString() };
594
+ },
595
+ stop() {
596
+ const was = started;
597
+ started = false;
598
+ if (timer && typeof timers.clearTimeout === 'function') timers.clearTimeout(timer);
599
+ timer = null;
600
+ return { stopped: was };
601
+ },
602
+ runOnce,
603
+ status() { return lastRun; },
604
+ };
605
+ }
606
+
607
+ export { summarizeRows as summarizeHealthRows };