@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.
- package/CHANGELOG.md +258 -202
- package/QUICKSTART.md +10 -11
- package/README.en.md +13 -4
- package/README.md +61 -18
- package/SPEC.md +3 -3
- package/build-info.json +259 -129
- package/cordis.patch.yml +32 -1
- package/docs/ANSWER-GUARD.md +1 -1
- package/docs/ARCHITECTURE.md +3 -3
- package/docs/AUTO-RECALL-WIRING.md +5 -3
- package/docs/AUTO-RECALL.md +10 -4
- package/docs/CONFIG.md +46 -11
- package/docs/ERRORS.md +1 -1
- package/docs/FAQ.md +9 -9
- package/docs/FEATURES.md +19 -16
- package/docs/OPERATIONS.md +3 -3
- package/docs/PANEL-INTEGRATION.md +1 -1
- package/docs/PRIVACY.md +6 -6
- package/docs/QUICKSTART.md +5 -5
- package/docs/README.en.md +5 -3
- package/docs/TOOLS.md +1 -1
- 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 +132 -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/index.js +2 -2
- 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/memory-reader.mjs +1003 -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/continuity-log.mjs +435 -0
- package/src/recall/continuity-volatile.mjs +1001 -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 +663 -29
- package/src/recall/inject-order.mjs +3 -1
- package/src/recall/link-fastpath.mjs +662 -0
- package/src/recall/recall-core.mjs +74 -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,794 @@
|
|
|
1
|
+
// src/memory/archive-cold-state.mjs — B7b 草案:冷层归档状态机(scan→approve#1→copy→verify→approve#2→migrated→才可删)
|
|
2
|
+
//
|
|
3
|
+
// 契约(V0.5.2-RETENTION-PATCH.md §3 L19-20 / §4 L22-31,B37-SCOPE.md B7b):
|
|
4
|
+
// scan → manifest(逐文件 sha256)→ approve#1(用户)→ copy 到冷盘(J:)→
|
|
5
|
+
// 回读 sha → approve#2(用户,含 manifest sha + approve#1 id)→ 才允许删除原文件。
|
|
6
|
+
// 缺任一 approve / 顺序错 / manifest sha 不符 / 冷副本被篡改 → fail-closed,
|
|
7
|
+
// 不删原件、不降级、不写 C: 影子副本(错误码见 COLD_CODES)。
|
|
8
|
+
//
|
|
9
|
+
// 状态落盘:**只写** `<memoryRoot>/.longlive/archive-state.json`(archive-state/v1,
|
|
10
|
+
// 唯一写入方仍是 src/recall/archive-state.mjs;本模块通过它的 writeArchiveState 写,
|
|
11
|
+
// 不另造第二份状态文件)。字段(与冻结契约同名):
|
|
12
|
+
// phase ∈ idle|scanned|approved1|copied|approved2|migrated
|
|
13
|
+
// approve1At / approve2At(ISO 时间)、coldManifestSha(64-hex)、migrated(bool)
|
|
14
|
+
// + approve1Id / approve2Id / migratedAt / coldLayer / reconcile(派生的审计附属字段)
|
|
15
|
+
// manifest 落盘:`.longlive/hardgate/cold-manifest.json`(cold-manifest/v1)。
|
|
16
|
+
// 删除 WAL:`.longlive/hardgate/cold-intents.jsonl`(intent/done 两行式)——T2 半途
|
|
17
|
+
// kill -9 后重启 reconcile 只标 incomplete,不重删、不产生无账删除。
|
|
18
|
+
//
|
|
19
|
+
// 本模块不渲染、不注入、不写记忆正文;所有写入都限制在 memoryRoot 与显式冷盘根内。
|
|
20
|
+
|
|
21
|
+
import fs from 'node:fs';
|
|
22
|
+
import path from 'node:path';
|
|
23
|
+
import crypto from 'node:crypto';
|
|
24
|
+
|
|
25
|
+
import {
|
|
26
|
+
ARCHIVE_STATE_REL,
|
|
27
|
+
readArchiveState,
|
|
28
|
+
writeArchiveState,
|
|
29
|
+
sha256Hex,
|
|
30
|
+
} from '../recall/archive-state.mjs';
|
|
31
|
+
|
|
32
|
+
export const MODULE = 'memory/archive-cold-state.mjs';
|
|
33
|
+
export const COLD_MANIFEST_SCHEMA = 'cold-manifest/v1';
|
|
34
|
+
export const COLD_MANIFEST_REL = '.longlive/hardgate/cold-manifest.json';
|
|
35
|
+
export const COLD_INTENTS_REL = '.longlive/hardgate/cold-intents.jsonl';
|
|
36
|
+
export const COLD_STATE_REL = ARCHIVE_STATE_REL;
|
|
37
|
+
export const COLD_PHASES = Object.freeze(['idle', 'scanned', 'approved1', 'copied', 'approved2', 'migrated']);
|
|
38
|
+
|
|
39
|
+
export const COLD_CODES = Object.freeze({
|
|
40
|
+
approvalRequired: 'E_HG_ARCHIVE_APPROVAL_REQUIRED',
|
|
41
|
+
approvalOrder: 'E_HG_ARCHIVE_APPROVAL_ORDER',
|
|
42
|
+
coldMismatch: 'E_HG_ARCHIVE_COLD_MISMATCH',
|
|
43
|
+
coldTampered: 'E_HG_ARCHIVE_COLD_TAMPERED',
|
|
44
|
+
coldRootMissing: 'E_HG_ARCHIVE_COLD_ROOT_MISSING',
|
|
45
|
+
manifestStale: 'E_HG_ARCHIVE_MANIFEST_STALE',
|
|
46
|
+
offline: 'E_HG_ARCHIVE_OFFLINE',
|
|
47
|
+
unmigrated: 'E_HG_RETENTION_UNMIGRATED',
|
|
48
|
+
stateCorrupt: 'E_HG_ARCHIVE_STATE_CORRUPT',
|
|
49
|
+
});
|
|
50
|
+
|
|
51
|
+
export function coldError(code, message, details = {}) {
|
|
52
|
+
const error = new Error(String(message ?? code));
|
|
53
|
+
error.code = String(code);
|
|
54
|
+
error.details = details;
|
|
55
|
+
return error;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
function cleanText(value) {
|
|
59
|
+
return typeof value === 'string' && value.trim() !== '' ? value.trim() : null;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
function toDate(now) {
|
|
63
|
+
const at = now instanceof Date ? now : new Date(now ?? Date.now());
|
|
64
|
+
return Number.isNaN(at.getTime()) ? new Date() : at;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
function iso(now) {
|
|
68
|
+
return toDate(now).toISOString();
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
function isInside(root, target) {
|
|
72
|
+
const rel = path.relative(path.resolve(root), path.resolve(target));
|
|
73
|
+
return rel === '' || (!rel.startsWith('..') && !path.isAbsolute(rel));
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
function normRel(value) {
|
|
77
|
+
return String(value ?? '').replace(/\\/g, '/').replace(/^\/+/, '');
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
function assertRelSafe(rel) {
|
|
81
|
+
const clean = normRel(rel);
|
|
82
|
+
if (clean === '' || clean.includes('\u0000') || clean.startsWith('../') || clean.includes('/../') || path.isAbsolute(clean)) {
|
|
83
|
+
throw coldError(COLD_CODES.coldMismatch, `非法清单路径:${String(rel)}`, { rel });
|
|
84
|
+
}
|
|
85
|
+
return clean;
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
function resolveRoot(memoryRoot) {
|
|
89
|
+
const root = cleanText(memoryRoot);
|
|
90
|
+
if (root === null) throw coldError(COLD_CODES.stateCorrupt, 'memoryRoot 为空');
|
|
91
|
+
return path.resolve(root);
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
export function sha256File(file) {
|
|
95
|
+
return crypto.createHash('sha256').update(fs.readFileSync(file)).digest('hex');
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
// ---------------------------------------------------------------------------
|
|
99
|
+
// manifest
|
|
100
|
+
// ---------------------------------------------------------------------------
|
|
101
|
+
|
|
102
|
+
/** 逐文件扫描 → 确定性 manifest(files 按 rel 排序;manifestSha256 = canonical JSON sha)。 */
|
|
103
|
+
export function planColdManifest({ memoryRoot, layer = 'handoff', entries = [], now = new Date() } = {}) {
|
|
104
|
+
const root = resolveRoot(memoryRoot);
|
|
105
|
+
const files = [];
|
|
106
|
+
for (const entry of Array.isArray(entries) ? entries : []) {
|
|
107
|
+
const rel = assertRelSafe(entry && typeof entry === 'object' ? entry.rel : entry);
|
|
108
|
+
const abs = path.join(root, rel);
|
|
109
|
+
if (!isInside(root, abs)) throw coldError(COLD_CODES.coldMismatch, `清单路径越出 memoryRoot:${rel}`, { rel });
|
|
110
|
+
let stat;
|
|
111
|
+
try {
|
|
112
|
+
stat = fs.statSync(abs);
|
|
113
|
+
} catch {
|
|
114
|
+
throw coldError(COLD_CODES.coldMismatch, `清单文件不存在:${rel}`, { rel });
|
|
115
|
+
}
|
|
116
|
+
if (!stat.isFile()) throw coldError(COLD_CODES.coldMismatch, `清单项不是文件:${rel}`, { rel });
|
|
117
|
+
const sha256 = sha256File(abs);
|
|
118
|
+
const expected = entry && typeof entry === 'object' ? cleanText(entry.sha256) : null;
|
|
119
|
+
if (expected !== null && expected !== sha256) {
|
|
120
|
+
throw coldError(COLD_CODES.coldTampered, `源文件 sha256 与调用方声明不符:${rel}`, { rel, expected, actual: sha256 });
|
|
121
|
+
}
|
|
122
|
+
files.push({ rel, bytes: stat.size, mtimeMs: Math.trunc(stat.mtimeMs), sha256 });
|
|
123
|
+
}
|
|
124
|
+
files.sort((a, b) => (a.rel < b.rel ? -1 : a.rel > b.rel ? 1 : 0));
|
|
125
|
+
const canonical = {
|
|
126
|
+
schema: COLD_MANIFEST_SCHEMA,
|
|
127
|
+
layer: String(layer),
|
|
128
|
+
files,
|
|
129
|
+
count: files.length,
|
|
130
|
+
totalBytes: files.reduce((sum, row) => sum + row.bytes, 0),
|
|
131
|
+
};
|
|
132
|
+
const manifestSha256 = sha256Hex(Buffer.from(JSON.stringify(canonical), 'utf8'));
|
|
133
|
+
const manifest = { ...canonical, generatedAt: iso(now), manifestSha256 };
|
|
134
|
+
const manifestPath = path.join(root, COLD_MANIFEST_REL);
|
|
135
|
+
const payload = `${JSON.stringify(manifest, null, 2)}\n`;
|
|
136
|
+
const tmp = `${manifestPath}.tmp-${process.pid}-${Date.now()}`;
|
|
137
|
+
fs.mkdirSync(path.dirname(manifestPath), { recursive: true });
|
|
138
|
+
const fd = fs.openSync(tmp, 'wx');
|
|
139
|
+
try {
|
|
140
|
+
fs.writeSync(fd, payload);
|
|
141
|
+
fs.fsyncSync(fd);
|
|
142
|
+
} finally {
|
|
143
|
+
fs.closeSync(fd);
|
|
144
|
+
}
|
|
145
|
+
fs.renameSync(tmp, manifestPath);
|
|
146
|
+
const fileSha256 = sha256Hex(Buffer.from(payload, 'utf8'));
|
|
147
|
+
|
|
148
|
+
// 状态推进:idle/新清单 → scanned;同一清单重复扫描幂等(不改已 approve 的字段)。
|
|
149
|
+
const current = readColdState({ memoryRoot: root });
|
|
150
|
+
const cold = current.cold;
|
|
151
|
+
if (cold.coldManifestSha === manifestSha256 && cold.phase !== 'idle') {
|
|
152
|
+
// 同一清单重复 scan:幂等返回(不重置已 approve 的字段)。
|
|
153
|
+
return { ok: true, manifest, manifestSha256, fileSha256, manifestPath, state: cold, alreadyScanned: true };
|
|
154
|
+
}
|
|
155
|
+
if (cold.migrated === true && cold.coldManifestSha === manifestSha256) {
|
|
156
|
+
return { ok: true, manifest, manifestSha256, fileSha256, manifestPath, state: cold, alreadyScanned: true };
|
|
157
|
+
}
|
|
158
|
+
if (cold.migrated === true && cold.coldManifestSha !== manifestSha256) {
|
|
159
|
+
throw coldError(COLD_CODES.manifestStale, '已有 migrated 状态但清单 sha 不同:拒绝静默重扫(先重新走 approve)', {
|
|
160
|
+
stateManifestSha: cold.coldManifestSha,
|
|
161
|
+
manifestSha256,
|
|
162
|
+
});
|
|
163
|
+
}
|
|
164
|
+
const next = {
|
|
165
|
+
...cold,
|
|
166
|
+
phase: 'scanned',
|
|
167
|
+
coldManifestSha: manifestSha256,
|
|
168
|
+
approve1At: null,
|
|
169
|
+
approve1Id: null,
|
|
170
|
+
approve2At: null,
|
|
171
|
+
approve2Id: null,
|
|
172
|
+
migrated: false,
|
|
173
|
+
migratedAt: null,
|
|
174
|
+
coldLayer: String(layer),
|
|
175
|
+
};
|
|
176
|
+
writeColdState({ memoryRoot: root, cold: next, now });
|
|
177
|
+
return { ok: true, manifest, manifestSha256, fileSha256, manifestPath, state: next };
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
/** 读回放盘 manifest(只读)。 */
|
|
181
|
+
export function readColdManifest({ memoryRoot, manifestPath = null } = {}) {
|
|
182
|
+
const root = resolveRoot(memoryRoot);
|
|
183
|
+
const file = cleanText(manifestPath) ?? path.join(root, COLD_MANIFEST_REL);
|
|
184
|
+
let text;
|
|
185
|
+
try {
|
|
186
|
+
text = fs.readFileSync(file, 'utf8');
|
|
187
|
+
} catch (error) {
|
|
188
|
+
return { ok: false, reason: error?.code === 'ENOENT' ? 'manifest-missing' : 'manifest-unreadable', path: file, manifest: null, manifestSha256: null, fileSha256: null };
|
|
189
|
+
}
|
|
190
|
+
let manifest;
|
|
191
|
+
try {
|
|
192
|
+
manifest = JSON.parse(text);
|
|
193
|
+
} catch {
|
|
194
|
+
return { ok: false, reason: 'manifest-invalid-json', path: file, manifest: null, manifestSha256: null, fileSha256: null };
|
|
195
|
+
}
|
|
196
|
+
const canonical = {
|
|
197
|
+
schema: manifest?.schema,
|
|
198
|
+
layer: manifest?.layer,
|
|
199
|
+
files: Array.isArray(manifest?.files) ? manifest.files : [],
|
|
200
|
+
count: Number(manifest?.count),
|
|
201
|
+
totalBytes: Number(manifest?.totalBytes),
|
|
202
|
+
};
|
|
203
|
+
const manifestSha256 = sha256Hex(Buffer.from(JSON.stringify(canonical), 'utf8'));
|
|
204
|
+
if (canonical.schema !== COLD_MANIFEST_SCHEMA || !Array.isArray(manifest?.files)) {
|
|
205
|
+
return { ok: false, reason: 'manifest-schema', path: file, manifest, manifestSha256, fileSha256: sha256Hex(Buffer.from(text, 'utf8')) };
|
|
206
|
+
}
|
|
207
|
+
return {
|
|
208
|
+
ok: true,
|
|
209
|
+
reason: 'ok',
|
|
210
|
+
path: file,
|
|
211
|
+
manifest,
|
|
212
|
+
manifestSha256,
|
|
213
|
+
recordedSha256: cleanText(manifest?.manifestSha256),
|
|
214
|
+
manifestShaMatches: cleanText(manifest?.manifestSha256) === manifestSha256,
|
|
215
|
+
fileSha256: sha256Hex(Buffer.from(text, 'utf8')),
|
|
216
|
+
};
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
// ---------------------------------------------------------------------------
|
|
220
|
+
// state(archive-state/v1 的扩展字段;单一写入方是 recall/archive-state.mjs)
|
|
221
|
+
// ---------------------------------------------------------------------------
|
|
222
|
+
|
|
223
|
+
export function coldStatePathOf(memoryRoot, statePath = null) {
|
|
224
|
+
const override = cleanText(statePath);
|
|
225
|
+
if (override !== null) return path.isAbsolute(override) ? override : path.join(resolveRoot(memoryRoot), override);
|
|
226
|
+
return path.join(resolveRoot(memoryRoot), COLD_STATE_REL);
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
export const EMPTY_COLD_STATE = Object.freeze({
|
|
230
|
+
phase: 'idle',
|
|
231
|
+
approve1At: null,
|
|
232
|
+
approve1Id: null,
|
|
233
|
+
approve2At: null,
|
|
234
|
+
approve2Id: null,
|
|
235
|
+
coldManifestSha: null,
|
|
236
|
+
migrated: false,
|
|
237
|
+
migratedAt: null,
|
|
238
|
+
coldLayer: null,
|
|
239
|
+
reconcile: null,
|
|
240
|
+
});
|
|
241
|
+
|
|
242
|
+
export function readColdState({ memoryRoot, statePath = null } = {}) {
|
|
243
|
+
const file = coldStatePathOf(memoryRoot, statePath);
|
|
244
|
+
const read = readArchiveState(file);
|
|
245
|
+
const base = read.ok ? read.state : null;
|
|
246
|
+
if (read.ok === true && base === null) {
|
|
247
|
+
// 状态文件缺失:冷档已配置但尚未 scan —— 是「未迁移」,不是「状态损坏」。
|
|
248
|
+
// 门禁据此返回 E_HG_RETENTION_UNMIGRATED(D11 T4/P5),不得降级成 MIGRATE_MISMATCH。
|
|
249
|
+
return {
|
|
250
|
+
ok: true,
|
|
251
|
+
exists: false,
|
|
252
|
+
path: file,
|
|
253
|
+
reason: read.reason ?? 'state-missing',
|
|
254
|
+
base: null,
|
|
255
|
+
cold: { ...EMPTY_COLD_STATE },
|
|
256
|
+
};
|
|
257
|
+
}
|
|
258
|
+
if (read.ok !== true || base === null) {
|
|
259
|
+
return {
|
|
260
|
+
ok: false,
|
|
261
|
+
exists: read.exists === true,
|
|
262
|
+
path: file,
|
|
263
|
+
reason: read.reason ?? 'state-unreadable',
|
|
264
|
+
base,
|
|
265
|
+
cold: { ...EMPTY_COLD_STATE },
|
|
266
|
+
};
|
|
267
|
+
}
|
|
268
|
+
const cold = {
|
|
269
|
+
phase: COLD_PHASES.includes(base.phase) ? base.phase : 'idle',
|
|
270
|
+
approve1At: cleanText(base.approve1At),
|
|
271
|
+
approve1Id: cleanText(base.approve1Id),
|
|
272
|
+
approve2At: cleanText(base.approve2At),
|
|
273
|
+
approve2Id: cleanText(base.approve2Id),
|
|
274
|
+
coldManifestSha: cleanText(base.coldManifestSha) && /^[0-9a-f]{64}$/u.test(base.coldManifestSha) ? base.coldManifestSha : null,
|
|
275
|
+
migrated: base.migrated === true,
|
|
276
|
+
migratedAt: cleanText(base.migratedAt),
|
|
277
|
+
coldLayer: cleanText(base.coldLayer),
|
|
278
|
+
reconcile: base.reconcile && typeof base.reconcile === 'object' ? base.reconcile : null,
|
|
279
|
+
};
|
|
280
|
+
return { ok: true, exists: true, path: file, reason: null, base, cold };
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
/**
|
|
284
|
+
* 写状态:只经 recall/archive-state.mjs 的原子写;失败抛错(fail-closed,调用方不得继续删)。
|
|
285
|
+
*
|
|
286
|
+
* archive-reconcile 契约(sha 732ae187,§0-2/§0-4):
|
|
287
|
+
* 1) state 唯一路径 = `<memoryRoot>/.longlive/archive-state.json`(ARCHIVE_STATE_REL),root 级;
|
|
288
|
+
* 2) 冷迁移 manifest sha 写 `coldManifestSha`,**不得占用 `manifestSha`**——后者由 B5 探针写入、
|
|
289
|
+
* 供冷召回比对 digest manifest 字节 sha(archive-fallback 消费者);
|
|
290
|
+
* 3) 写前读取现有 state 合并,保留 B5 探针字段(status/at/freeBytes/manifestPath/manifestSha/
|
|
291
|
+
* indexReady/archiveRoot/volumeGuid/producer),绝不整份覆盖。
|
|
292
|
+
*/
|
|
293
|
+
export function writeColdState({ memoryRoot, cold = null, statePath = null, now = new Date() } = {}) {
|
|
294
|
+
const root = resolveRoot(memoryRoot);
|
|
295
|
+
const file = coldStatePathOf(root, statePath);
|
|
296
|
+
const mergedCold = { ...EMPTY_COLD_STATE, ...(cold ?? {}) };
|
|
297
|
+
const existing = readArchiveState(file);
|
|
298
|
+
const base = existing.ok === true && existing.state ? existing.state : null;
|
|
299
|
+
const state = {
|
|
300
|
+
schema: 'archive-state/v1',
|
|
301
|
+
// B5 探针字段:有旧 state 就原样保留;无旧 state 时给最小合法壳(status 枚举不允许 null)。
|
|
302
|
+
status: base?.status ?? 'ok',
|
|
303
|
+
code: base?.code ?? null,
|
|
304
|
+
archiveRoot: base?.archiveRoot ?? cleanText(mergedCold.coldRoot) ?? null,
|
|
305
|
+
volumeGuid: base?.volumeGuid ?? null,
|
|
306
|
+
at: base?.at ?? iso(now),
|
|
307
|
+
freeBytes: base?.freeBytes ?? null,
|
|
308
|
+
manifestPath: base?.manifestPath ?? null,
|
|
309
|
+
manifestSha: base?.manifestSha ?? null,
|
|
310
|
+
indexReady: base?.indexReady ?? null,
|
|
311
|
+
producer: base?.producer ?? 'archive-cold-state',
|
|
312
|
+
// B7b 扩展:全部为标量/小数组(reconcile 已在 normalize 截 20 条),仍满足 ≤4 KiB 契约。
|
|
313
|
+
phase: mergedCold.phase,
|
|
314
|
+
approve1At: mergedCold.approve1At ?? null,
|
|
315
|
+
approve2At: mergedCold.approve2At ?? null,
|
|
316
|
+
approve1Id: mergedCold.approve1Id ?? null,
|
|
317
|
+
approve2Id: mergedCold.approve2Id ?? null,
|
|
318
|
+
coldManifestSha: mergedCold.coldManifestSha ?? null,
|
|
319
|
+
migrated: mergedCold.migrated === true,
|
|
320
|
+
migratedAt: mergedCold.migratedAt ?? null,
|
|
321
|
+
coldLayer: mergedCold.coldLayer ?? null,
|
|
322
|
+
reconcile: mergedCold.reconcile ?? null,
|
|
323
|
+
};
|
|
324
|
+
const written = writeArchiveState(file, state, { memoryRoot: root, now: toDate(now) });
|
|
325
|
+
if (written.ok !== true) {
|
|
326
|
+
throw coldError(COLD_CODES.stateCorrupt, `archive-state 写入失败:${written.error?.code ?? 'unknown'}`, { error: written.error ?? null });
|
|
327
|
+
}
|
|
328
|
+
return { ok: true, path: file, sha256: written.sha256, state, cold: mergedCold };
|
|
329
|
+
}
|
|
330
|
+
|
|
331
|
+
function requireState(coldStateOrCtx) {
|
|
332
|
+
if (coldStateOrCtx && coldStateOrCtx.ok === true && coldStateOrCtx.cold) return coldStateOrCtx;
|
|
333
|
+
if (coldStateOrCtx && coldStateOrCtx.cold) return coldStateOrCtx;
|
|
334
|
+
throw coldError(COLD_CODES.stateCorrupt, '缺少可读的冷档状态(先 scan)');
|
|
335
|
+
}
|
|
336
|
+
|
|
337
|
+
// ---------------------------------------------------------------------------
|
|
338
|
+
// approve#1 / copy+verify / approve#2 / migrated
|
|
339
|
+
// ---------------------------------------------------------------------------
|
|
340
|
+
|
|
341
|
+
export function approveColdOnce({ memoryRoot, manifestSha = null, by = 'operator', now = new Date(), statePath = null } = {}) {
|
|
342
|
+
const root = resolveRoot(memoryRoot);
|
|
343
|
+
const current = readColdState({ memoryRoot: root, statePath });
|
|
344
|
+
const cold = current.cold;
|
|
345
|
+
if (cold.migrated === true) {
|
|
346
|
+
return { ok: true, alreadyApproved: true, cold };
|
|
347
|
+
}
|
|
348
|
+
if (cold.approve2At !== null) {
|
|
349
|
+
throw coldError(COLD_CODES.approvalOrder, 'approve#2 已存在:approve#1 不重复', { phase: cold.phase });
|
|
350
|
+
}
|
|
351
|
+
const manifest = readColdManifest({ memoryRoot: root });
|
|
352
|
+
if (!manifest.ok) throw coldError(COLD_CODES.coldMismatch, `manifest 不可验:${manifest.reason}`, { reason: manifest.reason });
|
|
353
|
+
const sha = cleanText(manifestSha) ?? manifest.manifestSha256;
|
|
354
|
+
if (cold.coldManifestSha === null) throw coldError(COLD_CODES.approvalRequired, '尚未 scan:缺 coldManifestSha', { reason: 'scan-missing' });
|
|
355
|
+
if (sha !== cold.coldManifestSha) throw coldError(COLD_CODES.coldMismatch, 'approve#1 的 manifest sha 与状态不一致', { expected: cold.coldManifestSha, actual: sha });
|
|
356
|
+
if (manifest.manifestSha256 !== cold.coldManifestSha) throw coldError(COLD_CODES.manifestStale, '盘上 manifest 已变化(重扫后再 approve)', { state: cold.coldManifestSha, disk: manifest.manifestSha256 });
|
|
357
|
+
const at = iso(now);
|
|
358
|
+
if (cold.approve1At !== null) {
|
|
359
|
+
if (cold.approve1At === at && cold.approve1Id !== null) return { ok: true, alreadyApproved: true, cold };
|
|
360
|
+
return { ok: true, alreadyApproved: true, cold };
|
|
361
|
+
}
|
|
362
|
+
const approve1Id = sha256Hex(Buffer.from(`${cold.coldManifestSha}|${String(by)}|${at}`, 'utf8')).slice(0, 16);
|
|
363
|
+
const next = { ...cold, phase: 'approved1', approve1At: at, approve1Id };
|
|
364
|
+
const written = writeColdState({ memoryRoot: root, cold: next, statePath, now });
|
|
365
|
+
return { ok: true, alreadyApproved: false, approve1Id, cold: written.cold };
|
|
366
|
+
}
|
|
367
|
+
|
|
368
|
+
/** 复制清单文件到冷盘并回读 sha256;任何不一致 → 抛 COLD_TAMPERED(不删原件、不写 C: 副本)。 */
|
|
369
|
+
export function copyColdFiles({ memoryRoot, coldRoot, manifest = null, now = new Date(), dryRun = false } = {}) {
|
|
370
|
+
const root = resolveRoot(memoryRoot);
|
|
371
|
+
const cold = cleanText(coldRoot);
|
|
372
|
+
if (cold === null) throw coldError(COLD_CODES.coldRootMissing, '冷盘根未配置(recall.archiveRoot 为空)');
|
|
373
|
+
const coldAbs = path.resolve(cold);
|
|
374
|
+
if (isInside(root, coldAbs)) {
|
|
375
|
+
throw coldError(COLD_CODES.coldMismatch, '冷盘根不得位于 memoryRoot 内(禁止写 C: 影子副本)', { coldRoot: coldAbs });
|
|
376
|
+
}
|
|
377
|
+
let planner = manifest;
|
|
378
|
+
if (planner === null) {
|
|
379
|
+
const read = readColdManifest({ memoryRoot: root });
|
|
380
|
+
if (!read.ok) throw coldError(COLD_CODES.coldMismatch, `manifest 不可验:${read.reason}`, { reason: read.reason });
|
|
381
|
+
planner = read.manifest;
|
|
382
|
+
}
|
|
383
|
+
const layer = cleanText(planner?.layer) ?? 'handoff';
|
|
384
|
+
const copied = [];
|
|
385
|
+
const planned = [];
|
|
386
|
+
const mismatches = [];
|
|
387
|
+
for (const entry of Array.isArray(planner?.files) ? planner.files : []) {
|
|
388
|
+
const rel = assertRelSafe(entry.rel);
|
|
389
|
+
const source = path.join(root, rel);
|
|
390
|
+
if (!isInside(root, source) || !fs.existsSync(source)) {
|
|
391
|
+
mismatches.push({ rel, code: COLD_CODES.coldTampered, reason: 'source-missing' });
|
|
392
|
+
continue;
|
|
393
|
+
}
|
|
394
|
+
const actual = sha256File(source);
|
|
395
|
+
if (actual !== entry.sha256) {
|
|
396
|
+
mismatches.push({ rel, code: COLD_CODES.coldTampered, reason: 'source-sha-changed', expected: entry.sha256, actual });
|
|
397
|
+
continue;
|
|
398
|
+
}
|
|
399
|
+
const dest = path.join(coldAbs, layer, rel);
|
|
400
|
+
if (!isInside(path.join(coldAbs, layer), dest)) {
|
|
401
|
+
mismatches.push({ rel, code: COLD_CODES.coldMismatch, reason: 'cold-path-escape' });
|
|
402
|
+
continue;
|
|
403
|
+
}
|
|
404
|
+
planned.push({ rel, source, dest, sha256: entry.sha256, bytes: entry.bytes });
|
|
405
|
+
if (dryRun) continue;
|
|
406
|
+
fs.mkdirSync(path.dirname(dest), { recursive: true });
|
|
407
|
+
const tmp = `${dest}.tmp-${process.pid}-${Date.now()}`;
|
|
408
|
+
try {
|
|
409
|
+
const fd = fs.openSync(tmp, 'wx');
|
|
410
|
+
try {
|
|
411
|
+
fs.writeSync(fd, fs.readFileSync(source));
|
|
412
|
+
fs.fsyncSync(fd);
|
|
413
|
+
} finally {
|
|
414
|
+
fs.closeSync(fd);
|
|
415
|
+
}
|
|
416
|
+
fs.renameSync(tmp, dest);
|
|
417
|
+
} catch (error) {
|
|
418
|
+
try { fs.unlinkSync(tmp); } catch { /* best effort */ }
|
|
419
|
+
mismatches.push({ rel, code: COLD_CODES.coldMismatch, reason: 'copy-failed', message: String(error?.message ?? error).slice(0, 200) });
|
|
420
|
+
continue;
|
|
421
|
+
}
|
|
422
|
+
const readback = sha256File(dest);
|
|
423
|
+
if (readback !== entry.sha256) {
|
|
424
|
+
mismatches.push({ rel, code: COLD_CODES.coldTampered, reason: 'cold-readback-mismatch', expected: entry.sha256, actual: readback });
|
|
425
|
+
continue;
|
|
426
|
+
}
|
|
427
|
+
copied.push({ rel, sha256: entry.sha256, bytes: entry.bytes, dest });
|
|
428
|
+
}
|
|
429
|
+
if (mismatches.length > 0) {
|
|
430
|
+
throw coldError(COLD_CODES.coldTampered, `冷盘复制/回读校验失败(${mismatches.length} 项):原件未删除`, {
|
|
431
|
+
mismatches,
|
|
432
|
+
copied: copied.map((row) => row.rel),
|
|
433
|
+
});
|
|
434
|
+
}
|
|
435
|
+
return { ok: true, dryRun, layer, coldRoot: coldAbs, planned: planned.map((row) => row.rel), copied: copied.map((row) => row.rel), verified: copied.length };
|
|
436
|
+
}
|
|
437
|
+
|
|
438
|
+
/** 回读冷盘副本并逐文件校验(T4/T5 用;不复制、不删除)。 */
|
|
439
|
+
export function verifyColdCopies({ memoryRoot, coldRoot, manifestSha = null, manifest = null } = {}) {
|
|
440
|
+
const root = resolveRoot(memoryRoot);
|
|
441
|
+
const cold = cleanText(coldRoot);
|
|
442
|
+
if (cold === null) return { ok: false, code: COLD_CODES.coldRootMissing, reason: 'cold-root-missing', mismatches: [] };
|
|
443
|
+
let planner = manifest;
|
|
444
|
+
if (planner === null) {
|
|
445
|
+
const read = readColdManifest({ memoryRoot: root });
|
|
446
|
+
if (!read.ok) return { ok: false, code: COLD_CODES.coldMismatch, reason: read.reason, mismatches: [] };
|
|
447
|
+
planner = read.manifest;
|
|
448
|
+
}
|
|
449
|
+
if (manifestSha !== null && readColdManifest({ memoryRoot: root }).manifestSha256 !== manifestSha) {
|
|
450
|
+
return { ok: false, code: COLD_CODES.manifestStale, reason: 'manifest-sha-mismatch', mismatches: [] };
|
|
451
|
+
}
|
|
452
|
+
const layer = cleanText(planner?.layer) ?? 'handoff';
|
|
453
|
+
const mismatches = [];
|
|
454
|
+
let verified = 0;
|
|
455
|
+
for (const entry of Array.isArray(planner?.files) ? planner.files : []) {
|
|
456
|
+
const rel = assertRelSafe(entry.rel);
|
|
457
|
+
const dest = path.join(path.resolve(cold), layer, rel);
|
|
458
|
+
if (!fs.existsSync(dest)) {
|
|
459
|
+
mismatches.push({ rel, code: COLD_CODES.coldTampered, reason: 'cold-copy-missing' });
|
|
460
|
+
continue;
|
|
461
|
+
}
|
|
462
|
+
const actual = sha256File(dest);
|
|
463
|
+
if (actual !== entry.sha256) {
|
|
464
|
+
mismatches.push({ rel, code: COLD_CODES.coldTampered, reason: 'cold-copy-sha-mismatch', expected: entry.sha256, actual });
|
|
465
|
+
continue;
|
|
466
|
+
}
|
|
467
|
+
verified += 1;
|
|
468
|
+
}
|
|
469
|
+
if (mismatches.length > 0) return { ok: false, code: COLD_CODES.coldTampered, reason: 'cold-copy-tampered', mismatches, verified };
|
|
470
|
+
return { ok: true, code: null, reason: 'ok', verified, mismatches: [] };
|
|
471
|
+
}
|
|
472
|
+
|
|
473
|
+
export function approveColdWithManifest({
|
|
474
|
+
memoryRoot,
|
|
475
|
+
manifestSha = null,
|
|
476
|
+
approve1Id = null,
|
|
477
|
+
by = 'operator',
|
|
478
|
+
now = new Date(),
|
|
479
|
+
statePath = null,
|
|
480
|
+
coldRoot = null,
|
|
481
|
+
} = {}) {
|
|
482
|
+
const root = resolveRoot(memoryRoot);
|
|
483
|
+
const current = readColdState({ memoryRoot: root, statePath });
|
|
484
|
+
const cold = current.cold;
|
|
485
|
+
if (cold.migrated === true) {
|
|
486
|
+
return { ok: true, alreadyApproved: true, cold };
|
|
487
|
+
}
|
|
488
|
+
if (cleanText(cold.approve1At) === null) {
|
|
489
|
+
throw coldError(COLD_CODES.approvalRequired, '缺 approve#1:必须先完成第一次 approve', { reason: 'approve1-missing', phase: cold.phase });
|
|
490
|
+
}
|
|
491
|
+
if (cleanText(approve1Id) === null || approve1Id !== cold.approve1Id) {
|
|
492
|
+
throw coldError(COLD_CODES.approvalOrder, 'approve#2 的 approve1 id 与 approve#1 不符', { reason: 'approve1-id-mismatch', expected: cold.approve1Id, actual: approve1Id });
|
|
493
|
+
}
|
|
494
|
+
const sha = cleanText(manifestSha) ?? cold.coldManifestSha;
|
|
495
|
+
if (cold.coldManifestSha === null || sha !== cold.coldManifestSha) {
|
|
496
|
+
throw coldError(COLD_CODES.coldMismatch, 'approve#2 的 manifest sha 与状态不一致(可能换了清单)', {
|
|
497
|
+
reason: 'manifest-sha-mismatch',
|
|
498
|
+
expected: cold.coldManifestSha,
|
|
499
|
+
actual: sha,
|
|
500
|
+
});
|
|
501
|
+
}
|
|
502
|
+
const disk = readColdManifest({ memoryRoot: root });
|
|
503
|
+
if (!disk.ok || disk.manifestSha256 !== cold.coldManifestSha) {
|
|
504
|
+
throw coldError(COLD_CODES.manifestStale, '盘上 manifest 与状态不一致(重扫后再走两次 approve)', {
|
|
505
|
+
reason: 'manifest-stale',
|
|
506
|
+
state: cold.coldManifestSha,
|
|
507
|
+
disk: disk.ok ? disk.manifestSha256 : disk.reason,
|
|
508
|
+
});
|
|
509
|
+
}
|
|
510
|
+
// scan→approve#2 之间源文件若被改,manifest 已失效:approve#2 必须拒绝(D11 T4)。
|
|
511
|
+
const sourceMismatch = [];
|
|
512
|
+
for (const row of disk.manifest.files ?? []) {
|
|
513
|
+
try {
|
|
514
|
+
const actual = sha256File(path.join(root, row.rel));
|
|
515
|
+
if (actual !== row.sha256) sourceMismatch.push({ rel: row.rel, expected: row.sha256, actual });
|
|
516
|
+
} catch {
|
|
517
|
+
sourceMismatch.push({ rel: row.rel, expected: row.sha256, actual: null });
|
|
518
|
+
}
|
|
519
|
+
}
|
|
520
|
+
if (sourceMismatch.length > 0) {
|
|
521
|
+
throw coldError(COLD_CODES.manifestStale, 'scan 之后源文件被改:approve#2 拒绝(重扫后再走两次 approve)', {
|
|
522
|
+
reason: 'source-changed-after-scan',
|
|
523
|
+
mismatches: sourceMismatch,
|
|
524
|
+
});
|
|
525
|
+
}
|
|
526
|
+
if (cleanText(coldRoot) !== null) {
|
|
527
|
+
const copies = verifyColdCopies({ memoryRoot: root, coldRoot, manifest: disk.manifest });
|
|
528
|
+
if (!copies.ok) {
|
|
529
|
+
throw coldError(copies.code ?? COLD_CODES.coldTampered, `冷副本校验失败:${copies.reason}`, { mismatches: copies.mismatches });
|
|
530
|
+
}
|
|
531
|
+
}
|
|
532
|
+
const at = iso(now);
|
|
533
|
+
if (cold.approve1At !== null && new Date(cold.approve1At).getTime() > toDate(now).getTime()) {
|
|
534
|
+
throw coldError(COLD_CODES.approvalOrder, 'approve#1 时间晚于 approve#2(顺序错)', { reason: 'approve1-after-approve2' });
|
|
535
|
+
}
|
|
536
|
+
if (cold.approve2At !== null) return { ok: true, alreadyApproved: true, cold };
|
|
537
|
+
const approve2Id = sha256Hex(Buffer.from(`${cold.coldManifestSha}|${cold.approve1Id}|${String(by)}|${at}`, 'utf8')).slice(0, 16);
|
|
538
|
+
const next = { ...cold, phase: 'approved2', approve2At: at, approve2Id };
|
|
539
|
+
const written = writeColdState({ memoryRoot: root, cold: next, statePath, now });
|
|
540
|
+
return { ok: true, alreadyApproved: false, approve2Id, cold: written.cold };
|
|
541
|
+
}
|
|
542
|
+
|
|
543
|
+
/** 迁移完成标记:只有 approve#1 + approve#2 都齐才允许 migrated=true。 */
|
|
544
|
+
export function markColdMigrated({ memoryRoot, manifestSha = null, now = new Date(), statePath = null, coldRoot = null } = {}) {
|
|
545
|
+
const root = resolveRoot(memoryRoot);
|
|
546
|
+
const current = readColdState({ memoryRoot: root, statePath });
|
|
547
|
+
const cold = current.cold;
|
|
548
|
+
if (cold.migrated === true) return { ok: true, alreadyMigrated: true, cold };
|
|
549
|
+
if (cold.approve1At === null) throw coldError(COLD_CODES.approvalRequired, '缺 approve#1:拒绝标记 migrated', { reason: 'approve1-missing' });
|
|
550
|
+
if (cold.approve2At === null) throw coldError(COLD_CODES.approvalRequired, '缺 approve#2:拒绝标记 migrated', { reason: 'approve2-missing' });
|
|
551
|
+
const sha = cleanText(manifestSha) ?? cold.coldManifestSha;
|
|
552
|
+
if (cold.coldManifestSha === null || sha !== cold.coldManifestSha) {
|
|
553
|
+
throw coldError(COLD_CODES.coldMismatch, 'migrated 标记的 manifest sha 不一致', { reason: 'manifest-sha-mismatch' });
|
|
554
|
+
}
|
|
555
|
+
const disk = readColdManifest({ memoryRoot: root });
|
|
556
|
+
if (!disk.ok || disk.manifestSha256 !== cold.coldManifestSha) {
|
|
557
|
+
throw coldError(COLD_CODES.manifestStale, '盘上 manifest 已变化:拒绝标记 migrated', { reason: 'manifest-stale' });
|
|
558
|
+
}
|
|
559
|
+
if (cleanText(coldRoot) !== null) {
|
|
560
|
+
const copies = verifyColdCopies({ memoryRoot: root, coldRoot, manifest: disk.manifest });
|
|
561
|
+
if (!copies.ok) throw coldError(copies.code ?? COLD_CODES.coldTampered, `冷副本校验失败:${copies.reason}`, { mismatches: copies.mismatches });
|
|
562
|
+
}
|
|
563
|
+
const at = iso(now);
|
|
564
|
+
const next = { ...cold, phase: 'migrated', migrated: true, migratedAt: at };
|
|
565
|
+
const written = writeColdState({ memoryRoot: root, cold: next, statePath, now });
|
|
566
|
+
return { ok: true, alreadyMigrated: false, cold: written.cold };
|
|
567
|
+
}
|
|
568
|
+
|
|
569
|
+
// ---------------------------------------------------------------------------
|
|
570
|
+
// 删除门禁 + WAL(T2/T4)
|
|
571
|
+
// ---------------------------------------------------------------------------
|
|
572
|
+
|
|
573
|
+
export function gateColdDeletion({
|
|
574
|
+
memoryRoot,
|
|
575
|
+
rel,
|
|
576
|
+
sha256 = null,
|
|
577
|
+
statePath = null,
|
|
578
|
+
coldRoot = null,
|
|
579
|
+
failOpen = false,
|
|
580
|
+
online = true,
|
|
581
|
+
} = {}) {
|
|
582
|
+
const root = resolveRoot(memoryRoot);
|
|
583
|
+
const cleanRel = normRel(rel);
|
|
584
|
+
const deny = (code, reason, extra = {}) => ({ allowed: false, code, reason, rel: cleanRel, ...extra });
|
|
585
|
+
if (online === false) {
|
|
586
|
+
return deny(COLD_CODES.offline, failOpen === true ? 'archive-offline-failopen' : 'archive-offline', { failOpen: failOpen === true });
|
|
587
|
+
}
|
|
588
|
+
const current = readColdState({ memoryRoot: root, statePath });
|
|
589
|
+
if (!current.ok) return deny(COLD_CODES.stateCorrupt, `state-unreadable:${current.reason}`, { phase: current.cold.phase });
|
|
590
|
+
const cold = current.cold;
|
|
591
|
+
if (cold.migrated !== true) {
|
|
592
|
+
return deny(COLD_CODES.unmigrated, 'not-migrated', { phase: cold.phase });
|
|
593
|
+
}
|
|
594
|
+
const disk = readColdManifest({ memoryRoot: root });
|
|
595
|
+
if (!disk.ok) return deny(COLD_CODES.coldMismatch, `manifest-unverifiable:${disk.reason}`);
|
|
596
|
+
if (cold.coldManifestSha === null || disk.manifestSha256 !== cold.coldManifestSha) {
|
|
597
|
+
return deny(COLD_CODES.manifestStale, 'manifest-sha-mismatch', { state: cold.coldManifestSha, disk: disk.manifestSha256 });
|
|
598
|
+
}
|
|
599
|
+
const entry = (disk.manifest.files ?? []).find((row) => normRel(row.rel) === cleanRel);
|
|
600
|
+
if (!entry) return deny(COLD_CODES.coldMismatch, 'not-in-manifest');
|
|
601
|
+
if (cleanText(sha256) !== null && sha256 !== entry.sha256) {
|
|
602
|
+
return deny(COLD_CODES.coldTampered, 'source-sha-changed', { expected: entry.sha256, actual: sha256 });
|
|
603
|
+
}
|
|
604
|
+
if (cleanText(coldRoot) !== null) {
|
|
605
|
+
const dest = path.join(path.resolve(coldRoot), String(disk.manifest.layer ?? 'handoff'), cleanRel);
|
|
606
|
+
if (!fs.existsSync(dest)) return deny(COLD_CODES.coldTampered, 'cold-copy-missing');
|
|
607
|
+
const actual = sha256File(dest);
|
|
608
|
+
if (actual !== entry.sha256) return deny(COLD_CODES.coldTampered, 'cold-copy-sha-mismatch', { expected: entry.sha256, actual });
|
|
609
|
+
}
|
|
610
|
+
return { allowed: true, code: null, reason: 'ok', rel: cleanRel, manifestSha: cold.coldManifestSha, sha256: entry.sha256 };
|
|
611
|
+
}
|
|
612
|
+
|
|
613
|
+
/**
|
|
614
|
+
* 层级冷档门禁(T4/P5):不针对单个文件,只看「整体是否已迁移」。
|
|
615
|
+
* 供 retention/cold-gate.mjs 与 janitor 使用;不删任何文件。
|
|
616
|
+
* 返回 {allowed, code, reason, phase, manifestSha, manifest, cold}。
|
|
617
|
+
*/
|
|
618
|
+
export function gateColdArchive({
|
|
619
|
+
memoryRoot,
|
|
620
|
+
cold = null,
|
|
621
|
+
statePath = null,
|
|
622
|
+
online = true,
|
|
623
|
+
failOpen = false,
|
|
624
|
+
expectedManifestSha = null,
|
|
625
|
+
} = {}) {
|
|
626
|
+
const root = resolveRoot(memoryRoot);
|
|
627
|
+
let current = null;
|
|
628
|
+
if (cold && typeof cold === 'object') {
|
|
629
|
+
current = { ok: true, cold: { ...EMPTY_COLD_STATE, ...cold } };
|
|
630
|
+
} else {
|
|
631
|
+
current = readColdState({ memoryRoot: root, statePath });
|
|
632
|
+
}
|
|
633
|
+
if (current.ok !== true) {
|
|
634
|
+
return { allowed: false, code: COLD_CODES.stateCorrupt, reason: `state-unreadable:${current.reason}`, phase: current.cold?.phase ?? 'unknown' };
|
|
635
|
+
}
|
|
636
|
+
const state = current.cold;
|
|
637
|
+
if (online === false) {
|
|
638
|
+
return {
|
|
639
|
+
allowed: false,
|
|
640
|
+
code: COLD_CODES.offline,
|
|
641
|
+
reason: failOpen === true ? 'archive-offline-failopen' : 'archive-offline',
|
|
642
|
+
phase: state.phase,
|
|
643
|
+
};
|
|
644
|
+
}
|
|
645
|
+
if (state.migrated !== true) {
|
|
646
|
+
return { allowed: false, code: COLD_CODES.unmigrated, reason: 'not-migrated', phase: state.phase };
|
|
647
|
+
}
|
|
648
|
+
const disk = readColdManifest({ memoryRoot: root });
|
|
649
|
+
if (!disk.ok) {
|
|
650
|
+
return { allowed: false, code: COLD_CODES.coldMismatch, reason: `manifest-unverifiable:${disk.reason}`, phase: state.phase };
|
|
651
|
+
}
|
|
652
|
+
if (state.coldManifestSha === null || disk.manifestSha256 !== state.coldManifestSha) {
|
|
653
|
+
return {
|
|
654
|
+
allowed: false,
|
|
655
|
+
code: COLD_CODES.manifestStale,
|
|
656
|
+
reason: 'manifest-sha-mismatch',
|
|
657
|
+
phase: state.phase,
|
|
658
|
+
stateManifestSha: state.coldManifestSha,
|
|
659
|
+
diskManifestSha: disk.manifestSha256,
|
|
660
|
+
};
|
|
661
|
+
}
|
|
662
|
+
if (cleanText(expectedManifestSha) !== null && expectedManifestSha !== state.coldManifestSha) {
|
|
663
|
+
return {
|
|
664
|
+
allowed: false,
|
|
665
|
+
code: COLD_CODES.manifestStale,
|
|
666
|
+
reason: 'state-manifest-sha-mismatch',
|
|
667
|
+
phase: state.phase,
|
|
668
|
+
expected: expectedManifestSha,
|
|
669
|
+
actual: state.coldManifestSha,
|
|
670
|
+
};
|
|
671
|
+
}
|
|
672
|
+
return {
|
|
673
|
+
allowed: true,
|
|
674
|
+
code: null,
|
|
675
|
+
reason: 'ok',
|
|
676
|
+
phase: state.phase,
|
|
677
|
+
manifestSha: state.coldManifestSha,
|
|
678
|
+
manifest: disk.manifest,
|
|
679
|
+
cold: state,
|
|
680
|
+
};
|
|
681
|
+
}
|
|
682
|
+
|
|
683
|
+
function intentsPathOf(memoryRoot) {
|
|
684
|
+
return path.join(resolveRoot(memoryRoot), COLD_INTENTS_REL);
|
|
685
|
+
}
|
|
686
|
+
|
|
687
|
+
function appendIntent(memoryRoot, row) {
|
|
688
|
+
const file = intentsPathOf(memoryRoot);
|
|
689
|
+
fs.mkdirSync(path.dirname(file), { recursive: true });
|
|
690
|
+
const fd = fs.openSync(file, 'a');
|
|
691
|
+
try {
|
|
692
|
+
fs.writeSync(fd, `${JSON.stringify(row)}\n`);
|
|
693
|
+
fs.fsyncSync(fd);
|
|
694
|
+
} finally {
|
|
695
|
+
fs.closeSync(fd);
|
|
696
|
+
}
|
|
697
|
+
return file;
|
|
698
|
+
}
|
|
699
|
+
|
|
700
|
+
export function beginColdDelete({ memoryRoot, rel, sha256 = null, now = new Date() } = {}) {
|
|
701
|
+
const cleanRel = assertRelSafe(rel);
|
|
702
|
+
return appendIntent(memoryRoot, { op: 'intent', rel: cleanRel, sha256: cleanText(sha256), at: iso(now) });
|
|
703
|
+
}
|
|
704
|
+
|
|
705
|
+
export function finishColdDelete({ memoryRoot, rel, sha256 = null, ok = true, now = new Date() } = {}) {
|
|
706
|
+
const cleanRel = assertRelSafe(rel);
|
|
707
|
+
return appendIntent(memoryRoot, { op: 'done', rel: cleanRel, sha256: cleanText(sha256), ok: ok === true, at: iso(now) });
|
|
708
|
+
}
|
|
709
|
+
|
|
710
|
+
/** 重启对账:intent 无 done 且目标已不存在 → incomplete(不重删);目标存在 → pending(等下一次)。 */
|
|
711
|
+
export function reconcileColdIntents({ memoryRoot } = {}) {
|
|
712
|
+
const root = resolveRoot(memoryRoot);
|
|
713
|
+
const file = intentsPathOf(root);
|
|
714
|
+
let text = '';
|
|
715
|
+
try {
|
|
716
|
+
text = fs.readFileSync(file, 'utf8');
|
|
717
|
+
} catch (error) {
|
|
718
|
+
if (error?.code === 'ENOENT') return { ok: true, pending: [], incomplete: [], completed: [], corrupt: [], path: file };
|
|
719
|
+
return { ok: false, code: COLD_CODES.stateCorrupt, reason: 'intents-unreadable', pending: [], incomplete: [], completed: [], corrupt: [], path: file };
|
|
720
|
+
}
|
|
721
|
+
const pending = new Map();
|
|
722
|
+
const completed = [];
|
|
723
|
+
const corrupt = [];
|
|
724
|
+
for (const line of text.split('\n')) {
|
|
725
|
+
if (line.trim() === '') continue;
|
|
726
|
+
let row;
|
|
727
|
+
try {
|
|
728
|
+
row = JSON.parse(line);
|
|
729
|
+
} catch {
|
|
730
|
+
corrupt.push(line.slice(0, 200));
|
|
731
|
+
continue;
|
|
732
|
+
}
|
|
733
|
+
const rel = normRel(row?.rel);
|
|
734
|
+
if (rel === '') { corrupt.push(line.slice(0, 200)); continue; }
|
|
735
|
+
if (row.op === 'intent') pending.set(rel, { rel, sha256: cleanText(row.sha256), at: cleanText(row.at) });
|
|
736
|
+
else if (row.op === 'done' && pending.has(rel)) { pending.delete(rel); completed.push(rel); }
|
|
737
|
+
}
|
|
738
|
+
const incomplete = [];
|
|
739
|
+
for (const [rel, intent] of pending) {
|
|
740
|
+
const abs = path.join(root, rel);
|
|
741
|
+
if (!fs.existsSync(abs)) incomplete.push({ ...intent, reason: 'intent-without-final' });
|
|
742
|
+
}
|
|
743
|
+
return { ok: true, pending: [...pending.values()].filter((row) => fs.existsSync(path.join(root, row.rel))), incomplete, completed, corrupt, path: file };
|
|
744
|
+
}
|
|
745
|
+
|
|
746
|
+
/** 迁移完成后删原件:先门禁(T4/T5)→ intent → 删 → done;dryRun 只回报不放行删除。 */
|
|
747
|
+
export function deleteOriginalAfterMigrate({
|
|
748
|
+
memoryRoot,
|
|
749
|
+
rel,
|
|
750
|
+
sha256 = null,
|
|
751
|
+
statePath = null,
|
|
752
|
+
coldRoot = null,
|
|
753
|
+
now = new Date(),
|
|
754
|
+
dryRun = false,
|
|
755
|
+
failOpen = false,
|
|
756
|
+
online = true,
|
|
757
|
+
} = {}) {
|
|
758
|
+
const root = resolveRoot(memoryRoot);
|
|
759
|
+
const cleanRel = normRel(rel);
|
|
760
|
+
const abs = path.join(root, cleanRel);
|
|
761
|
+
if (!fs.existsSync(abs)) {
|
|
762
|
+
// 幂等:已经删过(或文件从未存在)→ 不重删、不写 intent、不报成功删除。
|
|
763
|
+
return { deleted: false, alreadyDeleted: true, dryRun, reason: 'already-deleted', rel: cleanRel, gate: { allowed: true, code: null, reason: 'already-deleted' } };
|
|
764
|
+
}
|
|
765
|
+
const gate = gateColdDeletion({ memoryRoot: root, rel, sha256, statePath, coldRoot, failOpen, online });
|
|
766
|
+
if (!gate.allowed) return { deleted: false, dryRun, gate };
|
|
767
|
+
if (dryRun) return { deleted: false, dryRun: true, gate };
|
|
768
|
+
beginColdDelete({ memoryRoot: root, rel, sha256: gate.sha256, now });
|
|
769
|
+
try {
|
|
770
|
+
fs.rmSync(path.join(root, gate.rel), { force: true });
|
|
771
|
+
} catch (error) {
|
|
772
|
+
finishColdDelete({ memoryRoot: root, rel, sha256: gate.sha256, ok: false, now });
|
|
773
|
+
throw coldError(COLD_CODES.stateCorrupt, `删除失败:${String(error?.message ?? error).slice(0, 200)}`, { rel });
|
|
774
|
+
}
|
|
775
|
+
finishColdDelete({ memoryRoot: root, rel, sha256: gate.sha256, ok: true, now });
|
|
776
|
+
return { deleted: true, dryRun: false, gate };
|
|
777
|
+
}
|
|
778
|
+
|
|
779
|
+
/** 全流程辅助(提案侧/夹具用):scan→approve1→copy→approve2→migrated(不等同于用户交互顺序)。 */
|
|
780
|
+
export function coldMovePlan({ memoryRoot, coldRoot, layer = 'handoff', entries, by = 'operator', now = new Date() } = {}) {
|
|
781
|
+
const planned = planColdManifest({ memoryRoot, layer, entries, now });
|
|
782
|
+
const approved1 = approveColdOnce({ memoryRoot, manifestSha: planned.manifestSha256, by, now });
|
|
783
|
+
const copy = copyColdFiles({ memoryRoot, coldRoot, manifest: planned.manifest });
|
|
784
|
+
const approved2 = approveColdWithManifest({
|
|
785
|
+
memoryRoot,
|
|
786
|
+
manifestSha: planned.manifestSha256,
|
|
787
|
+
approve1Id: approved1.approve1Id ?? approved1.cold.approve1Id,
|
|
788
|
+
by,
|
|
789
|
+
now,
|
|
790
|
+
coldRoot,
|
|
791
|
+
});
|
|
792
|
+
const migrated = markColdMigrated({ memoryRoot, manifestSha: planned.manifestSha256, now, coldRoot });
|
|
793
|
+
return { planned, approved1, copy, approved2, migrated, state: migrated.cold };
|
|
794
|
+
}
|