@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.
- package/CHANGELOG.md +232 -202
- package/QUICKSTART.md +10 -11
- package/README.en.md +13 -4
- package/README.md +42 -11
- package/SPEC.md +3 -3
- package/build-info.json +231 -121
- package/cordis.patch.yml +32 -1
- package/docs/ARCHITECTURE.md +1 -1
- package/docs/AUTO-RECALL.md +1 -1
- package/docs/CONFIG.md +41 -9
- package/docs/FAQ.md +7 -7
- package/docs/FEATURES.md +6 -6
- package/docs/OPERATIONS.md +1 -1
- package/docs/PANEL-INTEGRATION.md +1 -1
- package/docs/PRIVACY.md +5 -5
- package/docs/QUICKSTART.md +3 -3
- package/docs/README.en.md +4 -2
- package/docs/TROUBLESHOOTING.md +4 -4
- package/package.json +6 -3
- package/runbook.md +3 -3
- package/scripts/migrate-200.mjs +8 -0
- package/scripts/migrate-lifecycle.mjs +2 -2
- package/src/answer/claim-guard.mjs +234 -0
- package/src/backup.js +165 -1
- package/src/config.js +18 -7
- package/src/features.js +128 -5
- package/src/handoff/index.js +133 -0
- package/src/handoff/model.js +48 -0
- package/src/identity/handover.js +203 -15
- package/src/identity/inject-position.js +3 -1
- package/src/memory/a1-migration.js +72 -6
- package/src/memory/archive-cold-state.mjs +794 -0
- package/src/memory/archive-staging.mjs +305 -0
- package/src/memory/archive.mjs +415 -0
- package/src/memory/capture-host.js +71 -2
- package/src/memory/capture.js +45 -6
- package/src/memory/catchup.mjs +534 -0
- package/src/memory/conclusion-distill.js +51 -2
- package/src/memory/conclusion-drafts.js +7 -3
- package/src/memory/conflicts.js +915 -2
- package/src/memory/consolidate.js +20 -1
- package/src/memory/forget-v2.js +272 -2
- package/src/memory/forget.js +20 -1
- package/src/memory/frames-activation.js +3 -1
- package/src/memory/fts-query.js +2 -2
- package/src/memory/index.js +80 -7
- package/src/memory/land.mjs +743 -0
- package/src/memory/lifecycle.js +128 -0
- package/src/memory/maintenance.js +386 -22
- package/src/memory/memory-health.mjs +607 -0
- package/src/memory/migrate-200.js +1681 -0
- package/src/memory/migrate-lifecycle.js +3 -3
- package/src/memory/procedure-candidate.mjs +377 -0
- package/src/memory/procedure.js +20 -1
- package/src/memory/prospective-memory.mjs +362 -0
- package/src/memory/recall-feedback.mjs +406 -0
- package/src/memory/recall-v2.js +13 -1
- package/src/memory/recall.js +102 -1
- package/src/memory/reinforce.js +138 -2
- package/src/memory/retention.js +34 -0
- package/src/memory/turn-budget.mjs +290 -0
- package/src/memory/wake-bridge.mjs +2999 -0
- package/src/memory/working-frame.js +271 -8
- package/src/metrics/classify.mjs +3 -1
- package/src/recall/archive-config.mjs +130 -0
- package/src/recall/archive-fallback.mjs +174 -19
- package/src/recall/archive-search.mjs +3 -0
- package/src/recall/archive-state.mjs +588 -0
- package/src/recall/brain.mjs +501 -0
- package/src/recall/current-line.mjs +110 -0
- package/src/recall/edges.js +21 -2
- package/src/recall/explain.mjs +10 -0
- package/src/recall/gate-log.mjs +280 -0
- package/src/recall/gate-metrics.mjs +191 -0
- package/src/recall/index.js +322 -21
- package/src/recall/inject-order.mjs +3 -1
- package/src/recall/recall-core.mjs +47 -2
- package/src/recall/turn-budget-inject.mjs +154 -0
- package/src/retention/cold-gate.mjs +146 -0
- package/src/retention/config.js +58 -1
- package/src/retention/index.js +193 -35
- package/src/router/design-headings.json +10 -10
- package/src/tools.js +122 -6
|
@@ -0,0 +1,588 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 2.0.0 W3b(M31/M32/N16)冷档状态写入方 —— archive-state/v1。
|
|
3
|
+
*
|
|
4
|
+
* 唯一写入方:每日维护 / 启动探针槽(features.js 的 autoMaintenance scheduler
|
|
5
|
+
* → maintenance.js runDailyMaintenanceSync 的 archiveState job)。冷 job 只
|
|
6
|
+
* 读它,不写它;插件 v1 也不 drain 冷档队列(只读计数 → not_run)。
|
|
7
|
+
*
|
|
8
|
+
* 契约(冻结计划 v3.6.4 §4⑧ / §19 / §20):
|
|
9
|
+
* - state 单文件 ≤4 KiB,字段只有标量:schema/status/code/archiveRoot/volumeGuid/
|
|
10
|
+
* at/freeBytes/manifestPath/manifestSha/indexReady/producer;不存文件清单/正文/用户名;
|
|
11
|
+
* - status ∈ {ok, offline, readonly, low-space, wrong-volume};code 是 A6 五码族的
|
|
12
|
+
* 对应码(ok 时为 null);
|
|
13
|
+
* - 原子写:tmp → openSync('wx') → writeSync → fsyncSync → close → 回读 JSON.parse →
|
|
14
|
+
* renameSync;既存文件 >4 KiB 先 rename .bak;超界写失败不落盘;
|
|
15
|
+
* - 写失败只发一行 gate-log(hg.state.archive-state.fail),**永不抛**;
|
|
16
|
+
* - 读:坏 JSON / 坏 schema / 坏 status → 返回 {ok:false, reason}(消费者按 offline 归并,
|
|
17
|
+
* 旧三码 STATE_INVALID/DIGEST_MISSING/DIGEST_INVALID 只作为 internal reason,不再对外);
|
|
18
|
+
* - 隐私:只存标量,archiveRoot 只存卷根(不存文件清单、不存正文)。
|
|
19
|
+
*
|
|
20
|
+
* 本模块不渲染、不注入;消费者是 src/recall/archive-fallback.mjs。
|
|
21
|
+
*/
|
|
22
|
+
|
|
23
|
+
import fs from 'node:fs';
|
|
24
|
+
import path from 'node:path';
|
|
25
|
+
import { createHash } from 'node:crypto';
|
|
26
|
+
|
|
27
|
+
import { appendGateLog } from './gate-log.mjs';
|
|
28
|
+
|
|
29
|
+
export const BATCH = 'F';
|
|
30
|
+
export const MODULE = 'recall/archive-state.mjs';
|
|
31
|
+
|
|
32
|
+
export const ARCHIVE_STATE_SCHEMA = 'archive-state/v1';
|
|
33
|
+
export const ARCHIVE_STATE_FILE = 'archive-state.json';
|
|
34
|
+
export const ARCHIVE_STATE_REL = '.longlive/archive-state.json';
|
|
35
|
+
export const ARCHIVE_DIGEST_REL = '.longlive/archive-digest';
|
|
36
|
+
export const ARCHIVE_DIGEST_MANIFEST = 'manifest.json';
|
|
37
|
+
export const ARCHIVE_DIGEST_INDEX = 'index.jsonl';
|
|
38
|
+
export const ARCHIVE_DIGEST_SCHEMA = 'archive-digest/v1';
|
|
39
|
+
export const ARCHIVE_STATE_MAX_BYTES = 4096;
|
|
40
|
+
|
|
41
|
+
/** A6 五码族(顺序即冻结计划 §4⑧ 的顺序)。 */
|
|
42
|
+
export const ARCHIVE_STATE_CODES = Object.freeze([
|
|
43
|
+
'E_HG_ARCHIVE_OFFLINE',
|
|
44
|
+
'E_HG_ARCHIVE_READONLY',
|
|
45
|
+
'E_HG_ARCHIVE_LOW_SPACE',
|
|
46
|
+
'E_HG_ARCHIVE_WRONG_VOLUME',
|
|
47
|
+
'E_HG_ARCHIVE_MIGRATE_MISMATCH',
|
|
48
|
+
]);
|
|
49
|
+
|
|
50
|
+
export const ARCHIVE_STATE_STATUSES = Object.freeze(['ok', 'offline', 'readonly', 'low-space', 'wrong-volume']);
|
|
51
|
+
|
|
52
|
+
/** v1 只允许抛这两条:offline(W5)与 manifest schema/index 不符(W6)。 */
|
|
53
|
+
export const ARCHIVE_STATE_THROWABLE_CODES = Object.freeze([
|
|
54
|
+
ARCHIVE_STATE_CODES[0],
|
|
55
|
+
ARCHIVE_STATE_CODES[4],
|
|
56
|
+
]);
|
|
57
|
+
|
|
58
|
+
const STATUS_TO_CODE = Object.freeze({
|
|
59
|
+
ok: null,
|
|
60
|
+
offline: ARCHIVE_STATE_CODES[0],
|
|
61
|
+
readonly: ARCHIVE_STATE_CODES[1],
|
|
62
|
+
'low-space': ARCHIVE_STATE_CODES[2],
|
|
63
|
+
'wrong-volume': ARCHIVE_STATE_CODES[3],
|
|
64
|
+
});
|
|
65
|
+
|
|
66
|
+
/**
|
|
67
|
+
* 低空间下限:spec 建议 10 GiB,但尚未冻结(计划 §4⑧ 裁决:常量非实测),因此默认
|
|
68
|
+
* null = 不判低空间(low-space 在 v1 是 not_run);探针允许 options.minFreeBytes 显式注入,
|
|
69
|
+
* 供测试与未来冻结值使用。
|
|
70
|
+
*/
|
|
71
|
+
export const ARCHIVE_MIN_FREE_BYTES = null;
|
|
72
|
+
|
|
73
|
+
export const ARCHIVE_STATE_STATUS_CODE = STATUS_TO_CODE;
|
|
74
|
+
export const ARCHIVE_STATE_PRODUCER = 'daily-maintenance';
|
|
75
|
+
export const ARCHIVE_QUEUE_REL = '.longlive/hardgate/archive-queue.jsonl';
|
|
76
|
+
export const ARCHIVE_QUEUE_MAX_LINES = 1000;
|
|
77
|
+
export const ARCHIVE_QUEUE_WINDOW_DAYS = 90;
|
|
78
|
+
|
|
79
|
+
export function archiveStateError(code, message, extra = {}) {
|
|
80
|
+
const error = new Error(String(message ?? code));
|
|
81
|
+
error.code = String(code);
|
|
82
|
+
return Object.assign(error, extra);
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
export function sha256Hex(value) {
|
|
86
|
+
const hash = createHash('sha256');
|
|
87
|
+
hash.update(value);
|
|
88
|
+
return hash.digest('hex');
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
function nowDate(now) {
|
|
92
|
+
const at = now instanceof Date ? now : new Date(now);
|
|
93
|
+
return Number.isNaN(at.getTime()) ? new Date() : at;
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
function isoStamp(at) {
|
|
97
|
+
return at.toISOString();
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
function cleanText(value) {
|
|
101
|
+
return typeof value === 'string' && value.trim() !== '' ? value.trim() : null;
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
export function archiveStatePathFor(memoryRoot) {
|
|
105
|
+
if (!cleanText(memoryRoot)) return null;
|
|
106
|
+
return path.join(String(memoryRoot), ARCHIVE_STATE_REL);
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
/**
|
|
110
|
+
* 纯校验/归一化:不做 IO。缺 schema 的旧文件按宽松处理(夹具与 v1 早期写方不带
|
|
111
|
+
* schema);schema 存在但不符 → 非法;status 必须在枚举内。
|
|
112
|
+
*/
|
|
113
|
+
/** B7b 冷层迁移 phase 枚举(与 memory/archive-cold-state.mjs 的 COLD_PHASES 对齐,本地定义避免循环 import)。 */
|
|
114
|
+
export const ARCHIVE_COLD_PHASES = Object.freeze(['idle', 'scanned', 'approved1', 'copied', 'approved2', 'migrated']);
|
|
115
|
+
|
|
116
|
+
export function normalizeArchiveState(raw) {
|
|
117
|
+
if (!raw || typeof raw !== 'object' || Array.isArray(raw)) {
|
|
118
|
+
return { ok: false, reason: 'state-shape' };
|
|
119
|
+
}
|
|
120
|
+
if (raw.schema !== undefined && raw.schema !== ARCHIVE_STATE_SCHEMA) {
|
|
121
|
+
return { ok: false, reason: 'state-schema' };
|
|
122
|
+
}
|
|
123
|
+
if (typeof raw.status !== 'string' || !ARCHIVE_STATE_STATUSES.includes(raw.status)) {
|
|
124
|
+
return { ok: false, reason: raw.status === undefined ? 'state-status-missing' : 'state-status-invalid' };
|
|
125
|
+
}
|
|
126
|
+
const manifestSha = cleanText(raw.manifestSha);
|
|
127
|
+
const state = {
|
|
128
|
+
schema: ARCHIVE_STATE_SCHEMA,
|
|
129
|
+
status: raw.status,
|
|
130
|
+
code: cleanText(raw.code) ?? STATUS_TO_CODE[raw.status],
|
|
131
|
+
archiveRoot: cleanText(raw.archiveRoot),
|
|
132
|
+
volumeGuid: cleanText(raw.volumeGuid),
|
|
133
|
+
at: cleanText(raw.at),
|
|
134
|
+
freeBytes: Number.isFinite(raw.freeBytes) ? Math.max(0, Math.trunc(raw.freeBytes)) : null,
|
|
135
|
+
manifestPath: cleanText(raw.manifestPath),
|
|
136
|
+
manifestSha: manifestSha !== null && /^[0-9a-f]{64}$/.test(manifestSha) ? manifestSha : null,
|
|
137
|
+
indexReady: raw.indexReady === true ? true : raw.indexReady === false ? false : null,
|
|
138
|
+
producer: cleanText(raw.producer) ?? ARCHIVE_STATE_PRODUCER,
|
|
139
|
+
};
|
|
140
|
+
// B7b:冷层迁移状态字段(version-tolerant)。旧 state 没有这些键时不凭空补写;
|
|
141
|
+
// 一旦任意一个出现,就按冻结契约补齐(phase 缺省 idle、migrated 缺省 false),
|
|
142
|
+
// 这样 writeArchiveState 的「normalize 即丢未知字段」不会把迁移进度抹掉。
|
|
143
|
+
const hasCold = ['phase', 'approve1At', 'approve2At', 'approve1Id', 'approve2Id', 'coldManifestSha', 'migrated', 'migratedAt', 'coldLayer', 'reconcile']
|
|
144
|
+
.some((key) => raw[key] !== undefined);
|
|
145
|
+
if (hasCold) {
|
|
146
|
+
const phase = cleanText(raw.phase);
|
|
147
|
+
state.phase = ARCHIVE_COLD_PHASES.includes(phase) ? phase : 'idle';
|
|
148
|
+
state.approve1At = cleanText(raw.approve1At);
|
|
149
|
+
state.approve2At = cleanText(raw.approve2At);
|
|
150
|
+
state.approve1Id = cleanText(raw.approve1Id);
|
|
151
|
+
state.approve2Id = cleanText(raw.approve2Id);
|
|
152
|
+
// archive-reconcile §0-2:冷迁移清单 sha 独立命名,绝不占用 manifestSha(B5 探针字段)。
|
|
153
|
+
const coldManifestSha = cleanText(raw.coldManifestSha);
|
|
154
|
+
state.coldManifestSha = coldManifestSha !== null && /^[0-9a-f]{64}$/.test(coldManifestSha) ? coldManifestSha : null;
|
|
155
|
+
state.migrated = raw.migrated === true;
|
|
156
|
+
state.migratedAt = cleanText(raw.migratedAt);
|
|
157
|
+
state.coldLayer = cleanText(raw.coldLayer);
|
|
158
|
+
state.reconcile = raw.reconcile && typeof raw.reconcile === 'object' && !Array.isArray(raw.reconcile)
|
|
159
|
+
? {
|
|
160
|
+
pending: Array.isArray(raw.reconcile.pending) ? raw.reconcile.pending.filter((item) => typeof item === 'string').slice(0, 20) : [],
|
|
161
|
+
incomplete: Array.isArray(raw.reconcile.incomplete) ? raw.reconcile.incomplete.filter((item) => typeof item === 'string').slice(0, 20) : [],
|
|
162
|
+
at: cleanText(raw.reconcile.at),
|
|
163
|
+
}
|
|
164
|
+
: null;
|
|
165
|
+
}
|
|
166
|
+
return { ok: true, state };
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
/**
|
|
170
|
+
* 读 state(只读)。缺文件 → {ok:true, state:null};坏文件/坏 schema/坏 status →
|
|
171
|
+
* {ok:false, code:ARCHIVE_STATE_CODES[0], reason}(消费者按 offline 归并)。
|
|
172
|
+
*/
|
|
173
|
+
export function readArchiveState(statePath) {
|
|
174
|
+
const file = cleanText(statePath);
|
|
175
|
+
if (file === null) return { ok: true, state: null, exists: false, path: null };
|
|
176
|
+
let text;
|
|
177
|
+
try {
|
|
178
|
+
text = fs.readFileSync(file, 'utf8');
|
|
179
|
+
} catch (error) {
|
|
180
|
+
if (error?.code === 'ENOENT') return { ok: true, state: null, exists: false, path: file };
|
|
181
|
+
return { ok: false, state: null, exists: true, path: file, code: ARCHIVE_STATE_CODES[0], reason: 'state-unreadable' };
|
|
182
|
+
}
|
|
183
|
+
let raw;
|
|
184
|
+
try {
|
|
185
|
+
raw = JSON.parse(text);
|
|
186
|
+
} catch {
|
|
187
|
+
return { ok: false, state: null, exists: true, path: file, code: ARCHIVE_STATE_CODES[0], reason: 'state-invalid-json' };
|
|
188
|
+
}
|
|
189
|
+
const normalized = normalizeArchiveState(raw);
|
|
190
|
+
if (!normalized.ok) {
|
|
191
|
+
return { ok: false, state: null, exists: true, path: file, code: ARCHIVE_STATE_CODES[0], reason: normalized.reason };
|
|
192
|
+
}
|
|
193
|
+
return { ok: true, state: normalized.state, exists: true, path: file, sha256: sha256Hex(text) };
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
function appendArchiveStateFailure(memoryRoot, code, message) {
|
|
197
|
+
const root = cleanText(memoryRoot);
|
|
198
|
+
if (root === null) return null;
|
|
199
|
+
try {
|
|
200
|
+
return appendGateLog(root, {
|
|
201
|
+
gate: 'hg.state.archive-state.fail',
|
|
202
|
+
decision: 'fail',
|
|
203
|
+
reason: String(message ?? code),
|
|
204
|
+
evidence: ['archive-state', String(code ?? '')],
|
|
205
|
+
code: String(code ?? ''),
|
|
206
|
+
});
|
|
207
|
+
} catch {
|
|
208
|
+
return null;
|
|
209
|
+
}
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
/**
|
|
213
|
+
* 原子写 state(唯一写入路径)。永不抛:失败 → {ok:false, error:{code,message}},并补一行
|
|
214
|
+
* gate-log hg.state.archive-state.fail(memoryRoot 缺失时无事件)。
|
|
215
|
+
*/
|
|
216
|
+
export function writeArchiveState(statePath, state, { memoryRoot = null, now = new Date() } = {}) {
|
|
217
|
+
const file = cleanText(statePath);
|
|
218
|
+
if (file === null) {
|
|
219
|
+
return { ok: false, error: { code: 'E_HG_ARCHIVE_STATE_PATH', message: 'statePath 为空' } };
|
|
220
|
+
}
|
|
221
|
+
const normalized = normalizeArchiveState(state);
|
|
222
|
+
if (!normalized.ok) {
|
|
223
|
+
const error = { code: 'E_HG_ARCHIVE_STATE_INVALID', message: normalized.reason };
|
|
224
|
+
appendArchiveStateFailure(memoryRoot, error.code, error.message);
|
|
225
|
+
return { ok: false, error };
|
|
226
|
+
}
|
|
227
|
+
const payload = `${JSON.stringify(normalized.state)}\n`;
|
|
228
|
+
const bytes = Buffer.byteLength(payload, 'utf8');
|
|
229
|
+
if (bytes > ARCHIVE_STATE_MAX_BYTES) {
|
|
230
|
+
const error = { code: 'E_HG_ARCHIVE_STATE_OVERSIZE', message: `state ${bytes} B > ${ARCHIVE_STATE_MAX_BYTES} B` };
|
|
231
|
+
appendArchiveStateFailure(memoryRoot, error.code, error.message);
|
|
232
|
+
return { ok: false, error };
|
|
233
|
+
}
|
|
234
|
+
const tmp = `${file}.tmp-${process.pid}-${Date.now()}`;
|
|
235
|
+
let backup = null;
|
|
236
|
+
try {
|
|
237
|
+
fs.mkdirSync(path.dirname(file), { recursive: true });
|
|
238
|
+
if (fs.existsSync(file)) {
|
|
239
|
+
const existing = fs.statSync(file);
|
|
240
|
+
if (existing.size > ARCHIVE_STATE_MAX_BYTES) {
|
|
241
|
+
backup = `${file}.bak-${nowDate(now).toISOString().replace(/[:.]/gu, '-')}`;
|
|
242
|
+
fs.renameSync(file, backup);
|
|
243
|
+
}
|
|
244
|
+
}
|
|
245
|
+
const fd = fs.openSync(tmp, 'wx');
|
|
246
|
+
try {
|
|
247
|
+
fs.writeSync(fd, payload);
|
|
248
|
+
fs.fsyncSync(fd);
|
|
249
|
+
} finally {
|
|
250
|
+
fs.closeSync(fd);
|
|
251
|
+
}
|
|
252
|
+
const readBack = JSON.parse(fs.readFileSync(tmp, 'utf8'));
|
|
253
|
+
if (!readBack || readBack.status !== normalized.state.status || readBack.schema !== ARCHIVE_STATE_SCHEMA) {
|
|
254
|
+
throw archiveStateError('E_HG_ARCHIVE_STATE_VERIFY', '回读校验失败');
|
|
255
|
+
}
|
|
256
|
+
fs.renameSync(tmp, file);
|
|
257
|
+
return { ok: true, path: file, bytes, sha256: sha256Hex(payload), state: readBack, backup };
|
|
258
|
+
} catch (error) {
|
|
259
|
+
try {
|
|
260
|
+
fs.unlinkSync(tmp);
|
|
261
|
+
} catch {
|
|
262
|
+
/* tmp 可能从未创建;清理失败不影响结论 */
|
|
263
|
+
}
|
|
264
|
+
const info = {
|
|
265
|
+
code: String(error?.code ?? 'E_HG_ARCHIVE_STATE_WRITE'),
|
|
266
|
+
message: String(error?.message ?? error),
|
|
267
|
+
};
|
|
268
|
+
appendArchiveStateFailure(memoryRoot, info.code, info.message);
|
|
269
|
+
return { ok: false, error: info, backup };
|
|
270
|
+
}
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
/**
|
|
274
|
+
* 读 digest manifest 并独立复算 manifestSha / 校验 index size+sha(只读,不抛)。
|
|
275
|
+
* digest 根默认在 memoryRoot/.longlive/archive-digest;memoryRoot 缺省时退回 archiveRoot。
|
|
276
|
+
*/
|
|
277
|
+
export function readArchiveManifest(memoryRoot, { archiveRoot = null } = {}) {
|
|
278
|
+
const base = cleanText(memoryRoot) ?? cleanText(archiveRoot);
|
|
279
|
+
if (base === null) {
|
|
280
|
+
return { ok: false, reason: 'no-memory-root', path: null, manifestSha: null, indexReady: false };
|
|
281
|
+
}
|
|
282
|
+
const digestDir = path.join(base, ARCHIVE_DIGEST_REL);
|
|
283
|
+
const manifestPath = path.join(digestDir, ARCHIVE_DIGEST_MANIFEST);
|
|
284
|
+
let raw;
|
|
285
|
+
try {
|
|
286
|
+
raw = fs.readFileSync(manifestPath);
|
|
287
|
+
} catch (error) {
|
|
288
|
+
return {
|
|
289
|
+
ok: false,
|
|
290
|
+
reason: error?.code === 'ENOENT' ? 'manifest-missing' : 'manifest-unreadable',
|
|
291
|
+
path: manifestPath,
|
|
292
|
+
manifestSha: null,
|
|
293
|
+
indexReady: false,
|
|
294
|
+
};
|
|
295
|
+
}
|
|
296
|
+
const manifestSha = sha256Hex(raw);
|
|
297
|
+
let manifest;
|
|
298
|
+
try {
|
|
299
|
+
manifest = JSON.parse(raw.toString('utf8'));
|
|
300
|
+
} catch {
|
|
301
|
+
return { ok: false, reason: 'manifest-invalid', path: manifestPath, manifestSha, indexReady: false };
|
|
302
|
+
}
|
|
303
|
+
if (!manifest || typeof manifest !== 'object' || Array.isArray(manifest) || manifest.schema !== ARCHIVE_DIGEST_SCHEMA) {
|
|
304
|
+
return { ok: false, reason: 'manifest-schema', path: manifestPath, manifestSha, indexReady: false };
|
|
305
|
+
}
|
|
306
|
+
const indexSha256 = typeof manifest.indexSha256 === 'string' ? manifest.indexSha256.toLowerCase() : '';
|
|
307
|
+
const indexBytes = Number(manifest.indexBytes);
|
|
308
|
+
if (!/^[0-9a-f]{64}$/.test(indexSha256) || !Number.isFinite(indexBytes) || indexBytes < 0) {
|
|
309
|
+
return { ok: false, reason: 'manifest-fields', path: manifestPath, manifestSha, indexReady: false };
|
|
310
|
+
}
|
|
311
|
+
const indexPath = path.join(digestDir, ARCHIVE_DIGEST_INDEX);
|
|
312
|
+
let index;
|
|
313
|
+
try {
|
|
314
|
+
index = fs.readFileSync(indexPath);
|
|
315
|
+
} catch {
|
|
316
|
+
return { ok: false, reason: 'index-missing', path: manifestPath, manifestSha, indexReady: false };
|
|
317
|
+
}
|
|
318
|
+
if (index.length !== indexBytes) {
|
|
319
|
+
return { ok: false, reason: 'index-size-mismatch', path: manifestPath, manifestSha, indexReady: false };
|
|
320
|
+
}
|
|
321
|
+
if (sha256Hex(index) !== indexSha256) {
|
|
322
|
+
return { ok: false, reason: 'index-sha-mismatch', path: manifestPath, manifestSha, indexReady: false };
|
|
323
|
+
}
|
|
324
|
+
return {
|
|
325
|
+
ok: true,
|
|
326
|
+
reason: 'ok',
|
|
327
|
+
path: manifestPath,
|
|
328
|
+
digestDir,
|
|
329
|
+
manifest,
|
|
330
|
+
manifestSha,
|
|
331
|
+
indexReady: true,
|
|
332
|
+
indexBytes,
|
|
333
|
+
indexSha256,
|
|
334
|
+
};
|
|
335
|
+
}
|
|
336
|
+
|
|
337
|
+
/**
|
|
338
|
+
* 探针:只读探测 archiveRoot(卷存在/可写/余量 + digest manifest)。不做任何写入。
|
|
339
|
+
* 返回 {ok:true, status, code, archiveRoot, freeBytes, manifestPath, manifestSha, indexReady, reason}。
|
|
340
|
+
*/
|
|
341
|
+
export function probeArchiveRoot(archiveRoot, { memoryRoot = null, now = new Date(), minFreeBytes = ARCHIVE_MIN_FREE_BYTES } = {}) {
|
|
342
|
+
const root = cleanText(archiveRoot);
|
|
343
|
+
const base = {
|
|
344
|
+
ok: true,
|
|
345
|
+
archiveRoot: root,
|
|
346
|
+
volumeGuid: null,
|
|
347
|
+
at: isoStamp(nowDate(now)),
|
|
348
|
+
freeBytes: null,
|
|
349
|
+
manifestPath: null,
|
|
350
|
+
manifestSha: null,
|
|
351
|
+
indexReady: false,
|
|
352
|
+
producer: ARCHIVE_STATE_PRODUCER,
|
|
353
|
+
};
|
|
354
|
+
if (root === null) {
|
|
355
|
+
return { ...base, status: 'offline', code: ARCHIVE_STATE_CODES[0], reason: 'root-missing' };
|
|
356
|
+
}
|
|
357
|
+
let stat;
|
|
358
|
+
try {
|
|
359
|
+
stat = fs.statSync(root);
|
|
360
|
+
} catch (error) {
|
|
361
|
+
return {
|
|
362
|
+
...base,
|
|
363
|
+
status: 'offline',
|
|
364
|
+
code: ARCHIVE_STATE_CODES[0],
|
|
365
|
+
reason: error?.code === 'ENOENT' ? 'root-missing' : 'root-unreadable',
|
|
366
|
+
};
|
|
367
|
+
}
|
|
368
|
+
if (typeof stat?.isDirectory === 'function' && !stat.isDirectory()) {
|
|
369
|
+
return { ...base, status: 'offline', code: ARCHIVE_STATE_CODES[0], reason: 'not-directory' };
|
|
370
|
+
}
|
|
371
|
+
let writable = true;
|
|
372
|
+
try {
|
|
373
|
+
fs.accessSync(root, fs.constants.W_OK);
|
|
374
|
+
} catch {
|
|
375
|
+
writable = false;
|
|
376
|
+
}
|
|
377
|
+
const manifest = readArchiveManifest(memoryRoot ?? root, { archiveRoot: root });
|
|
378
|
+
const probed = {
|
|
379
|
+
...base,
|
|
380
|
+
manifestPath: manifest.path ?? null,
|
|
381
|
+
manifestSha: manifest.manifestSha ?? null,
|
|
382
|
+
indexReady: manifest.indexReady === true,
|
|
383
|
+
};
|
|
384
|
+
if (!writable) {
|
|
385
|
+
return { ...probed, status: 'readonly', code: ARCHIVE_STATE_CODES[1], reason: 'root-readonly' };
|
|
386
|
+
}
|
|
387
|
+
let freeBytes = null;
|
|
388
|
+
try {
|
|
389
|
+
const statfs = fs.statfsSync(root);
|
|
390
|
+
const bsize = Number(statfs?.bsize);
|
|
391
|
+
const bavail = Number(statfs?.bavail);
|
|
392
|
+
if (Number.isFinite(bsize) && Number.isFinite(bavail) && bsize > 0 && bavail >= 0) {
|
|
393
|
+
freeBytes = Math.trunc(bsize * bavail);
|
|
394
|
+
}
|
|
395
|
+
} catch {
|
|
396
|
+
/* statfs 不可用(老 Node / 特殊卷)→ freeBytes=null,不判低空间 */
|
|
397
|
+
}
|
|
398
|
+
if (freeBytes !== null) probed.freeBytes = freeBytes;
|
|
399
|
+
const floor = Number(minFreeBytes);
|
|
400
|
+
if (Number.isFinite(floor) && floor > 0 && freeBytes !== null && freeBytes < floor) {
|
|
401
|
+
return { ...probed, status: 'low-space', code: ARCHIVE_STATE_CODES[2], reason: 'free-bytes-below-minimum' };
|
|
402
|
+
}
|
|
403
|
+
return { ...probed, status: 'ok', code: null, reason: manifest.ok === true ? 'ok' : (manifest.reason ?? 'digest-unavailable') };
|
|
404
|
+
}
|
|
405
|
+
|
|
406
|
+
/**
|
|
407
|
+
* 消费者门:把 state 映射成 A6 五码族的裁决(纯判断,不读盘)。
|
|
408
|
+
* - state 缺(未写过)→ {ok:true, configured:<archiveRoot 非空>, code:null, status:'unset'};
|
|
409
|
+
* - state 坏(JSON/schema/status 非法)→ {ok:false, code:OFFLINE, reason:'state-invalid'};
|
|
410
|
+
* - status → code 映射;ok → code null。
|
|
411
|
+
*/
|
|
412
|
+
export function evaluateArchiveGate(state, { archiveRoot = null } = {}) {
|
|
413
|
+
const configured = cleanText(archiveRoot) !== null || cleanText(state?.archiveRoot) !== null;
|
|
414
|
+
if (state === null || state === undefined) {
|
|
415
|
+
return { ok: true, configured, status: 'unset', code: null, reason: 'state-missing' };
|
|
416
|
+
}
|
|
417
|
+
const normalized = normalizeArchiveState(state);
|
|
418
|
+
if (!normalized.ok) {
|
|
419
|
+
return { ok: false, configured, status: 'invalid', code: ARCHIVE_STATE_CODES[0], reason: 'state-invalid', detail: normalized.reason };
|
|
420
|
+
}
|
|
421
|
+
const status = normalized.state.status;
|
|
422
|
+
return {
|
|
423
|
+
ok: true,
|
|
424
|
+
configured,
|
|
425
|
+
status,
|
|
426
|
+
code: STATUS_TO_CODE[status],
|
|
427
|
+
reason: status === 'ok' ? 'ok' : `status-${status}`,
|
|
428
|
+
state: normalized.state,
|
|
429
|
+
};
|
|
430
|
+
}
|
|
431
|
+
|
|
432
|
+
/** 冷档队列只读计数(v1 不 drain:写入方=冷 job,消费者=卷恢复后 drain;插件只计数)。 */
|
|
433
|
+
export function countArchiveQueue({ memoryRoot, now = new Date(), windowDays = ARCHIVE_QUEUE_WINDOW_DAYS, maxLines = ARCHIVE_QUEUE_MAX_LINES } = {}) {
|
|
434
|
+
const root = cleanText(memoryRoot);
|
|
435
|
+
const base = {
|
|
436
|
+
ok: true,
|
|
437
|
+
path: root === null ? null : path.join(root, ARCHIVE_QUEUE_REL),
|
|
438
|
+
exists: false,
|
|
439
|
+
lines: 0,
|
|
440
|
+
withinWindow: 0,
|
|
441
|
+
overLimit: false,
|
|
442
|
+
drain: false,
|
|
443
|
+
maxLines,
|
|
444
|
+
windowDays,
|
|
445
|
+
};
|
|
446
|
+
if (root === null) return base;
|
|
447
|
+
let text;
|
|
448
|
+
try {
|
|
449
|
+
text = fs.readFileSync(base.path, 'utf8');
|
|
450
|
+
} catch (error) {
|
|
451
|
+
return { ...base, reason: error?.code === 'ENOENT' ? 'queue-missing' : 'queue-unreadable' };
|
|
452
|
+
}
|
|
453
|
+
const at = nowDate(now).getTime();
|
|
454
|
+
const windowStart = at - Math.max(0, Number(windowDays) || 0) * 24 * 60 * 60 * 1000;
|
|
455
|
+
let lines = 0;
|
|
456
|
+
let withinWindow = 0;
|
|
457
|
+
for (const line of text.split(/\r?\n/)) {
|
|
458
|
+
if (line.trim() === '') continue;
|
|
459
|
+
lines += 1;
|
|
460
|
+
let row;
|
|
461
|
+
try {
|
|
462
|
+
row = JSON.parse(line);
|
|
463
|
+
} catch {
|
|
464
|
+
continue;
|
|
465
|
+
}
|
|
466
|
+
const rowMs = Date.parse(String(row?.at ?? ''));
|
|
467
|
+
if (Number.isFinite(rowMs) && rowMs >= windowStart) withinWindow += 1;
|
|
468
|
+
}
|
|
469
|
+
return { ...base, exists: true, lines, withinWindow, overLimit: lines > Number(maxLines || 0) };
|
|
470
|
+
}
|
|
471
|
+
|
|
472
|
+
// B7b 落地修复(test/archive-state.test.mjs P2 flake 根因):freeBytes 取自 statfs
|
|
473
|
+
// 的瞬时余量,同一卷上其它进程写入会让它在两次探测之间抖动(实测 300 次压测有 8 次
|
|
474
|
+
// 仅 freeBytes 相差 4 KiB–1.3 MiB,见 b7b-impl 报告「P2 flake 根因」)。新鲜度身份
|
|
475
|
+
// 判等改为 256 MiB 分桶:余量跨桶变化才重写(保留"余量明显变化要刷新"的语义),
|
|
476
|
+
// 同时不受并发写噪声影响;state 里仍写精确 freeBytes 供面板/低空间观测。
|
|
477
|
+
const FREE_BYTES_IDENTITY_BUCKET = 256 * 1024 * 1024;
|
|
478
|
+
|
|
479
|
+
function freeBytesIdentityEqual(a, b) {
|
|
480
|
+
if (a === b) return true;
|
|
481
|
+
if (!Number.isFinite(a) || !Number.isFinite(b)) return false;
|
|
482
|
+
return Math.floor(a / FREE_BYTES_IDENTITY_BUCKET) === Math.floor(b / FREE_BYTES_IDENTITY_BUCKET);
|
|
483
|
+
}
|
|
484
|
+
|
|
485
|
+
/**
|
|
486
|
+
* 每日维护/启动槽:探针 + 当日新鲜度判定 + 原子写 state。
|
|
487
|
+
* 永不抛(写失败已在 writeArchiveState 内转成 {ok:false} + gate-log)。
|
|
488
|
+
*/
|
|
489
|
+
export function probeAndWriteArchiveState({
|
|
490
|
+
memoryRoot,
|
|
491
|
+
archiveRoot = null,
|
|
492
|
+
archiveStatePath = null,
|
|
493
|
+
now = new Date(),
|
|
494
|
+
logger = null,
|
|
495
|
+
minFreeBytes = ARCHIVE_MIN_FREE_BYTES,
|
|
496
|
+
force = false,
|
|
497
|
+
} = {}) {
|
|
498
|
+
const root = cleanText(memoryRoot);
|
|
499
|
+
if (root === null) return { ok: false, written: false, reason: 'no-memory-root' };
|
|
500
|
+
const at = nowDate(now);
|
|
501
|
+
const statePath = cleanText(archiveStatePath) ?? archiveStatePathFor(root);
|
|
502
|
+
const queue = countArchiveQueue({ memoryRoot: root, now: at });
|
|
503
|
+
const archive = cleanText(archiveRoot);
|
|
504
|
+
if (archive === null) {
|
|
505
|
+
return {
|
|
506
|
+
ok: true,
|
|
507
|
+
written: false,
|
|
508
|
+
skipped: true,
|
|
509
|
+
reason: 'not-configured',
|
|
510
|
+
statePath,
|
|
511
|
+
queue,
|
|
512
|
+
};
|
|
513
|
+
}
|
|
514
|
+
const probed = probeArchiveRoot(archive, { memoryRoot: root, now: at, minFreeBytes });
|
|
515
|
+
const nextState = {
|
|
516
|
+
schema: ARCHIVE_STATE_SCHEMA,
|
|
517
|
+
status: probed.status,
|
|
518
|
+
code: probed.code ?? null,
|
|
519
|
+
archiveRoot: probed.archiveRoot,
|
|
520
|
+
volumeGuid: probed.volumeGuid ?? null,
|
|
521
|
+
at: probed.at,
|
|
522
|
+
freeBytes: probed.freeBytes,
|
|
523
|
+
manifestPath: probed.manifestPath,
|
|
524
|
+
manifestSha: probed.manifestSha,
|
|
525
|
+
indexReady: probed.indexReady === true,
|
|
526
|
+
producer: ARCHIVE_STATE_PRODUCER,
|
|
527
|
+
};
|
|
528
|
+
const existing = readArchiveState(statePath);
|
|
529
|
+
const today = isoStamp(at).slice(0, 10);
|
|
530
|
+
if (force !== true && existing.ok === true && existing.state !== null) {
|
|
531
|
+
const previous = existing.state;
|
|
532
|
+
const sameDay = typeof previous.at === 'string' && previous.at.slice(0, 10) === today;
|
|
533
|
+
const sameProbe = previous.status === nextState.status
|
|
534
|
+
&& previous.archiveRoot === nextState.archiveRoot
|
|
535
|
+
&& previous.manifestSha === nextState.manifestSha
|
|
536
|
+
&& previous.indexReady === nextState.indexReady
|
|
537
|
+
&& freeBytesIdentityEqual(previous.freeBytes, nextState.freeBytes);
|
|
538
|
+
if (sameDay && sameProbe) {
|
|
539
|
+
return {
|
|
540
|
+
ok: true,
|
|
541
|
+
written: false,
|
|
542
|
+
fresh: true,
|
|
543
|
+
reason: 'fresh',
|
|
544
|
+
status: previous.status,
|
|
545
|
+
code: previous.code ?? null,
|
|
546
|
+
statePath,
|
|
547
|
+
state: previous,
|
|
548
|
+
queue,
|
|
549
|
+
probe: probed,
|
|
550
|
+
};
|
|
551
|
+
}
|
|
552
|
+
}
|
|
553
|
+
const written = writeArchiveState(statePath, nextState, { memoryRoot: root, now: at });
|
|
554
|
+
if (written.ok !== true) {
|
|
555
|
+
if (typeof logger === 'function') {
|
|
556
|
+
try {
|
|
557
|
+
logger(`[archive-state] 写失败(${written.error?.code ?? 'E_HG_ARCHIVE_STATE_WRITE'})— ${written.error?.message ?? ''}`);
|
|
558
|
+
} catch {
|
|
559
|
+
/* logger 失败不影响维护链 */
|
|
560
|
+
}
|
|
561
|
+
}
|
|
562
|
+
return {
|
|
563
|
+
ok: false,
|
|
564
|
+
written: false,
|
|
565
|
+
reason: 'write-failed',
|
|
566
|
+
status: probed.status,
|
|
567
|
+
code: probed.code ?? null,
|
|
568
|
+
statePath,
|
|
569
|
+
error: written.error ?? null,
|
|
570
|
+
queue,
|
|
571
|
+
probe: probed,
|
|
572
|
+
};
|
|
573
|
+
}
|
|
574
|
+
return {
|
|
575
|
+
ok: true,
|
|
576
|
+
written: true,
|
|
577
|
+
reason: 'written',
|
|
578
|
+
status: nextState.status,
|
|
579
|
+
code: nextState.code,
|
|
580
|
+
statePath,
|
|
581
|
+
state: written.state,
|
|
582
|
+
bytes: written.bytes,
|
|
583
|
+
sha256: written.sha256,
|
|
584
|
+
backup: written.backup ?? null,
|
|
585
|
+
queue,
|
|
586
|
+
probe: probed,
|
|
587
|
+
};
|
|
588
|
+
}
|