@jjh32456/longlive 2.2.0 → 2.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +79 -0
- package/QUICKSTART.md +7 -7
- package/README.en.md +13 -1
- package/README.md +26 -8
- package/SPEC.md +6 -5
- package/build-info.json +132 -67
- package/cordis.patch.yml +1 -0
- package/docs/ARCHITECTURE.md +6 -3
- package/docs/CONFIG.md +25 -1
- package/docs/FAQ.md +2 -2
- package/docs/FEATURES.md +104 -2
- package/docs/INDEX-FRESHNESS.md +8 -1
- package/docs/OPERATIONS.md +63 -2
- package/docs/QUICKSTART.md +2 -2
- package/docs/README.en.md +1 -1
- package/docs/TROUBLESHOOTING.md +1 -1
- package/package.json +10 -2
- package/scripts/assert-install.mjs +124 -0
- package/scripts/backlog-report.mjs +98 -0
- package/scripts/install-230.mjs +787 -0
- package/scripts/lib/eng-common.mjs +428 -0
- package/scripts/rebuild-index.mjs +148 -0
- package/scripts/restore-drill.mjs +351 -0
- package/scripts/run-autoresolve.mjs +123 -0
- package/scripts/watchdog-230.mjs +379 -0
- package/src/features.js +14 -0
- package/src/gate/action-gate.js +234 -45
- package/src/memory/backup-retention.mjs +823 -0
- package/src/memory/cards.js +73 -12
- package/src/memory/conflict-scan.mjs +356 -0
- package/src/memory/conflicts.js +202 -9
- package/src/memory/consolidate.js +100 -13
- package/src/memory/decay.js +133 -19
- package/src/memory/event-index.js +62 -4
- package/src/memory/forget-scheduler.mjs +303 -0
- package/src/memory/forget-v2.js +94 -8
- package/src/memory/index-cache.mjs +216 -0
- package/src/memory/index.js +149 -15
- package/src/memory/lock.js +53 -12
- package/src/memory/maintenance.js +172 -17
- package/src/memory/recall-feedback.mjs +159 -17
- package/src/memory/state.js +446 -38
- package/src/memory/task-state.mjs +569 -0
- package/src/recall/brain.mjs +8 -1
- package/src/recall/continuity-volatile.mjs +131 -1
- package/src/tools.js +108 -33
- package/src/ui/routes-readonly.js +63 -5
|
@@ -0,0 +1,823 @@
|
|
|
1
|
+
// src/memory/backup-retention.mjs — 2.3.0 / W1-2:备份保留策略、去重、UTF-8 清单、根文件快照。
|
|
2
|
+
//
|
|
3
|
+
// 现状(2.2.0):`state.js#writeFileAtomic` 每次写入都把旧文件整份复制到
|
|
4
|
+
// `<memoryRoot>/.longlive/backups/`,没有上限、没有去重、也没有清单;真实记忆根
|
|
5
|
+
// 实测已到 17,116 个文件 / 2,941 MB(内部实测记录)。
|
|
6
|
+
//
|
|
7
|
+
// 本模块只做"备份这一侧"的事,不碰 state 的读写语义(那在 state.js):
|
|
8
|
+
// * `planRetention()` — 纯函数保留计划:按天(默认 30)→ 按体积(默认 ≤2 GiB)→ 按 sha 去重;
|
|
9
|
+
// 每个 base(memory-state / INDEX / …)的最新一份永不被删。
|
|
10
|
+
// * `ensureManagedBackup()`— 单文件备份入口(state.js 的 backupInto/backupFile 走这里):
|
|
11
|
+
// 先查清单,同 base 同 sha 直接复用(增量/去重),否则复制并逐字节校验。
|
|
12
|
+
// * `snapshotRootFiles()` — 补备份范围:根文件 status.json / INDEX.md / STATE.md / POLICY.md 等
|
|
13
|
+
// (真实根 18 项里体积大的可选跳过)。
|
|
14
|
+
// * `runBackupRetention()` — 执行保留计划(默认 dryRun=false)+ 重建清单 + 写 UTF-8 SHA256SUMS。
|
|
15
|
+
// * `runBackupMaintenance()`— 给 state 写路径用的"到点才跑"门(默认 6h 保留 / 24h 根快照),
|
|
16
|
+
// 失败由调用方吞掉,绝不拖垮 state 写入。
|
|
17
|
+
//
|
|
18
|
+
// 清单位置:`<memoryRoot>/.longlive/backup-meta/`(**不放进 backups/ 目录本身**,
|
|
19
|
+
// 否则任何按目录列举的既有断言都会被清单文件污染)。清单内容为 UTF-8 JSON +
|
|
20
|
+
// GNU `SHA256SUMS` 文本,中文文件名原样写入(不做 `?`/`\uXXXX` 转义)。
|
|
21
|
+
//
|
|
22
|
+
// 通用性:只用 node:fs / node:path / node:crypto 与相对路径;零绝对盘符、零本机路径。
|
|
23
|
+
|
|
24
|
+
import crypto from 'node:crypto';
|
|
25
|
+
import fs from 'node:fs';
|
|
26
|
+
import path from 'node:path';
|
|
27
|
+
|
|
28
|
+
import { memoryError, relativePath, resolveInside } from './paths.js';
|
|
29
|
+
|
|
30
|
+
export const BACKUP_META_VERSION = 1;
|
|
31
|
+
export const BACKUP_META_DIR = '.longlive/backup-meta';
|
|
32
|
+
export const BACKUP_RETENTION_STATE = '.longlive/backup-retention.json';
|
|
33
|
+
export const BACKUP_MANIFEST_FILE = 'manifest.json';
|
|
34
|
+
export const BACKUP_CHECKSUMS_FILE = 'SHA256SUMS';
|
|
35
|
+
/** Default backup directory, relative to the memory root (`state.js#backupsDir`). */
|
|
36
|
+
export const DEFAULT_BACKUP_DIR = '.longlive/backups';
|
|
37
|
+
|
|
38
|
+
const MIB = 1024 * 1024;
|
|
39
|
+
const HOUR_MS = 60 * 60 * 1000;
|
|
40
|
+
const DAY_MS = 24 * HOUR_MS;
|
|
41
|
+
|
|
42
|
+
/** 默认保留策略:30 天 / ≤2 GiB(OPTIMIZATION-220 A1 的验收口径)。 */
|
|
43
|
+
export const DEFAULT_RETENTION = Object.freeze({
|
|
44
|
+
maxAgeDays: 30,
|
|
45
|
+
maxBytes: 2 * 1024 * MIB,
|
|
46
|
+
intervalMs: 6 * HOUR_MS,
|
|
47
|
+
snapshotIntervalMs: 24 * HOUR_MS,
|
|
48
|
+
keepLatestPerBase: true,
|
|
49
|
+
maxRootSnapshotBytes: 8 * MIB,
|
|
50
|
+
maxHashFiles: 2000,
|
|
51
|
+
maxFiles: 5000,
|
|
52
|
+
});
|
|
53
|
+
|
|
54
|
+
/**
|
|
55
|
+
* 补进备份范围的根文件。`memory-state.json` 不在此列:它是 state 写路径自己的文件,
|
|
56
|
+
* 已由 writeFileAtomic 的备份覆盖;这里只补"根上不在 .longlive 下"的长期文件。
|
|
57
|
+
*/
|
|
58
|
+
export const ROOT_SNAPSHOT_FILES = Object.freeze([
|
|
59
|
+
'status.json',
|
|
60
|
+
'INDEX.md',
|
|
61
|
+
'STATE.md',
|
|
62
|
+
'POLICY.md',
|
|
63
|
+
'IDENTITY.md',
|
|
64
|
+
'FORGETTING.md',
|
|
65
|
+
'budget.log',
|
|
66
|
+
'tombstones.md',
|
|
67
|
+
'flow/current.md',
|
|
68
|
+
]);
|
|
69
|
+
|
|
70
|
+
export function sha256Buffer(buffer) {
|
|
71
|
+
return crypto.createHash('sha256').update(buffer).digest('hex');
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
export function sha256File(file) {
|
|
75
|
+
return sha256Buffer(fs.readFileSync(file));
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
export function sha256Text(text) {
|
|
79
|
+
return sha256Buffer(Buffer.from(String(text), 'utf8'));
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/** Same token shape as `state.js#stampToken`, so backup names sort chronologically. */
|
|
83
|
+
export function stampToken(date = new Date()) {
|
|
84
|
+
return date.toISOString().replace(/[-:]/g, '').replace('T', '-').replace(/\..+$/, '') +
|
|
85
|
+
`-${String(date.getUTCMilliseconds()).padStart(3, '0')}`;
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/** `memory-state.20261205-131122-045.json` -> `{ base: 'memory-state', ext: '.json' }` */
|
|
89
|
+
export function deriveBase(name) {
|
|
90
|
+
const ext = path.extname(name);
|
|
91
|
+
const stem = ext ? name.slice(0, -ext.length) : name;
|
|
92
|
+
const match = /^(.*?)\.\d{8}-\d{6}-\d{3}(?:-\d+)?$/.exec(stem);
|
|
93
|
+
return { base: match ? match[1] : stem, ext: ext || '' };
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
function collisionFree(dir, base, stamp, ext) {
|
|
97
|
+
let candidate = path.join(dir, `${base}.${stamp}${ext}`);
|
|
98
|
+
let index = 2;
|
|
99
|
+
while (fs.existsSync(candidate)) {
|
|
100
|
+
candidate = path.join(dir, `${base}.${stamp}-${index}${ext}`);
|
|
101
|
+
index += 1;
|
|
102
|
+
}
|
|
103
|
+
return candidate;
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
/** Resolve a backup directory (relative to root or absolute-inside-root). */
|
|
107
|
+
export function resolveBackupDir(root, dir) {
|
|
108
|
+
return resolveInside(root, dir);
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
function metaKeyOf(root, dirAbs) {
|
|
112
|
+
const rel = relativePath(root, dirAbs) || '.';
|
|
113
|
+
return sha256Text(rel).slice(0, 16);
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
export function metaPaths(root, dirAbs) {
|
|
117
|
+
const abs = resolveBackupDir(root, dirAbs);
|
|
118
|
+
const base = path.join(BACKUP_META_DIR, metaKeyOf(root, abs));
|
|
119
|
+
return {
|
|
120
|
+
dir: abs,
|
|
121
|
+
json: resolveInside(root, `${base}.json`),
|
|
122
|
+
jsonl: resolveInside(root, `${base}.jsonl`),
|
|
123
|
+
checksums: resolveInside(root, `${base}.SHA256SUMS`),
|
|
124
|
+
};
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
function writeFileDurable(abs, text) {
|
|
128
|
+
fs.mkdirSync(path.dirname(abs), { recursive: true });
|
|
129
|
+
const tmp = `${abs}.tmp-${process.pid}-${Date.now()}`;
|
|
130
|
+
fs.writeFileSync(tmp, text, 'utf8');
|
|
131
|
+
fs.renameSync(tmp, abs);
|
|
132
|
+
return abs;
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
// ---------------------------------------------------------------------------
|
|
136
|
+
// 保留计划(纯函数,可单测)
|
|
137
|
+
// ---------------------------------------------------------------------------
|
|
138
|
+
|
|
139
|
+
/**
|
|
140
|
+
* Compute which backup files to keep and which to remove.
|
|
141
|
+
*
|
|
142
|
+
* `entries`: `[{ name, bytes, mtimeMs, base, sha256? }]`. `sha256` is optional;
|
|
143
|
+
* when absent the dedupe pass is skipped. Steps, in order:
|
|
144
|
+
* 1. 每个 base 的最新一份标记为 protected(永不在 2/3 步被删);
|
|
145
|
+
* 2. 超过 maxAgeDays 的删除;3. 总体积超 maxBytes 时从最旧的开始删;
|
|
146
|
+
* 4. 同 base + 同 sha 只留最新一份(其余算 duplicate)。
|
|
147
|
+
*
|
|
148
|
+
* Returns `{ keep, remove, duplicates, before, after, protectedNames, options }`.
|
|
149
|
+
*/
|
|
150
|
+
export function planRetention(entries, options = {}) {
|
|
151
|
+
const opts = normalizeRetentionOptions(options);
|
|
152
|
+
const nowMs = planNowMs(opts.now);
|
|
153
|
+
const list = Array.isArray(entries) ? entries.filter((entry) => entry && typeof entry.name === 'string') : [];
|
|
154
|
+
const remove = new Map();
|
|
155
|
+
const decisions = new Map();
|
|
156
|
+
|
|
157
|
+
const latestByBase = new Map();
|
|
158
|
+
for (const entry of list) {
|
|
159
|
+
const base = typeof entry.base === 'string' ? entry.base : deriveBase(entry.name).base;
|
|
160
|
+
const current = latestByBase.get(base);
|
|
161
|
+
const mtime = Number(entry.mtimeMs) || 0;
|
|
162
|
+
if (!current || mtime > (Number(current.mtimeMs) || 0) || (mtime === (Number(current.mtimeMs) || 0) && entry.name > current.name)) {
|
|
163
|
+
latestByBase.set(base, entry);
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
const protectedNames = new Set([...latestByBase.values()].map((entry) => entry.name));
|
|
167
|
+
|
|
168
|
+
// 1) age
|
|
169
|
+
for (const entry of list) {
|
|
170
|
+
const mtime = Number(entry.mtimeMs);
|
|
171
|
+
const age = Number.isFinite(mtime) && mtime > 0 ? nowMs - mtime : Infinity;
|
|
172
|
+
if (age > opts.maxAgeDays * DAY_MS && !protectedNames.has(entry.name)) {
|
|
173
|
+
remove.set(entry.name, 'age');
|
|
174
|
+
decisions.set(entry.name, `age>${opts.maxAgeDays}d`);
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
// 2) size cap (oldest first, never the latest of a base)
|
|
179
|
+
const keptAfterAge = () => list.filter((entry) => !remove.has(entry.name));
|
|
180
|
+
let bytes = keptAfterAge().reduce((sum, entry) => sum + (Number(entry.bytes) || 0), 0);
|
|
181
|
+
if (bytes > opts.maxBytes) {
|
|
182
|
+
const removable = keptAfterAge()
|
|
183
|
+
.filter((entry) => !protectedNames.has(entry.name))
|
|
184
|
+
.sort((a, b) => (Number(a.mtimeMs) || 0) - (Number(b.mtimeMs) || 0) || a.name.localeCompare(b.name));
|
|
185
|
+
for (const entry of removable) {
|
|
186
|
+
if (bytes <= opts.maxBytes) break;
|
|
187
|
+
remove.set(entry.name, 'size');
|
|
188
|
+
decisions.set(entry.name, `size-cap>${opts.maxBytes}`);
|
|
189
|
+
bytes -= Number(entry.bytes) || 0;
|
|
190
|
+
}
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
// 3) sha dedupe (only for entries that survived age/size and carry a sha)
|
|
194
|
+
const duplicates = [];
|
|
195
|
+
const byContent = new Map();
|
|
196
|
+
for (const entry of list) {
|
|
197
|
+
if (remove.has(entry.name) || typeof entry.sha256 !== 'string') continue;
|
|
198
|
+
const base = typeof entry.base === 'string' ? entry.base : deriveBase(entry.name).base;
|
|
199
|
+
const key = `${base}\0${entry.sha256}`;
|
|
200
|
+
const rows = byContent.get(key) ?? [];
|
|
201
|
+
rows.push(entry);
|
|
202
|
+
byContent.set(key, rows);
|
|
203
|
+
}
|
|
204
|
+
for (const rows of byContent.values()) {
|
|
205
|
+
if (rows.length < 2) continue;
|
|
206
|
+
rows.sort((a, b) => (Number(b.mtimeMs) || 0) - (Number(a.mtimeMs) || 0) || b.name.localeCompare(a.name));
|
|
207
|
+
for (const entry of rows.slice(1)) {
|
|
208
|
+
remove.set(entry.name, 'duplicate');
|
|
209
|
+
decisions.set(entry.name, `duplicate-of:${rows[0].name}`);
|
|
210
|
+
duplicates.push({ name: entry.name, keep: rows[0].name });
|
|
211
|
+
}
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
const keep = list.filter((entry) => !remove.has(entry.name));
|
|
215
|
+
const afterBytes = keep.reduce((sum, entry) => sum + (Number(entry.bytes) || 0), 0);
|
|
216
|
+
const beforeBytes = list.reduce((sum, entry) => sum + (Number(entry.bytes) || 0), 0);
|
|
217
|
+
return {
|
|
218
|
+
keep,
|
|
219
|
+
remove: [...remove.entries()].map(([name, reason]) => ({ name, reason, decision: decisions.get(name) ?? reason })),
|
|
220
|
+
duplicates,
|
|
221
|
+
protectedNames: [...protectedNames].sort(),
|
|
222
|
+
before: { files: list.length, bytes: beforeBytes },
|
|
223
|
+
after: { files: keep.length, bytes: afterBytes },
|
|
224
|
+
options: {
|
|
225
|
+
maxAgeDays: opts.maxAgeDays,
|
|
226
|
+
maxBytes: opts.maxBytes,
|
|
227
|
+
keepLatestPerBase: opts.keepLatestPerBase,
|
|
228
|
+
},
|
|
229
|
+
};
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
// ---------------------------------------------------------------------------
|
|
233
|
+
// 清单:UTF-8 JSON + GNU SHA256SUMS(中文名不做 `?` 转义)
|
|
234
|
+
// ---------------------------------------------------------------------------
|
|
235
|
+
|
|
236
|
+
export function readJsonSafe(file) {
|
|
237
|
+
try {
|
|
238
|
+
const text = fs.readFileSync(file, 'utf8').replace(/^\uFEFF/, '');
|
|
239
|
+
if (text.trim() === '') return null;
|
|
240
|
+
return JSON.parse(text);
|
|
241
|
+
} catch {
|
|
242
|
+
return null;
|
|
243
|
+
}
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
/**
|
|
247
|
+
* Read one backup manifest snapshot. Returns `null` when absent/broken.
|
|
248
|
+
* Entries are normalised to `{ name, rel, sha256, bytes, mtimeMs, base, kind }`.
|
|
249
|
+
*/
|
|
250
|
+
export function readBackupManifest(root, dirAbs) {
|
|
251
|
+
const paths = metaPaths(root, dirAbs);
|
|
252
|
+
const raw = readJsonSafe(paths.json);
|
|
253
|
+
if (!raw || !Array.isArray(raw.entries)) return null;
|
|
254
|
+
const entries = raw.entries
|
|
255
|
+
.filter((entry) => entry && typeof entry.name === 'string')
|
|
256
|
+
.map((entry) => {
|
|
257
|
+
const derived = deriveBase(entry.name);
|
|
258
|
+
return {
|
|
259
|
+
name: entry.name,
|
|
260
|
+
rel: typeof entry.rel === 'string' ? entry.rel : relativePath(root, path.join(paths.dir, entry.name)),
|
|
261
|
+
sha256: typeof entry.sha256 === 'string' ? entry.sha256 : null,
|
|
262
|
+
bytes: Number.isFinite(Number(entry.bytes)) ? Number(entry.bytes) : null,
|
|
263
|
+
mtimeMs: Number.isFinite(Number(entry.mtimeMs)) ? Number(entry.mtimeMs) : null,
|
|
264
|
+
base: typeof entry.base === 'string' ? entry.base : derived.base,
|
|
265
|
+
kind: typeof entry.kind === 'string' ? entry.kind : 'file',
|
|
266
|
+
source: typeof entry.source === 'string' ? entry.source : null,
|
|
267
|
+
};
|
|
268
|
+
});
|
|
269
|
+
return { version: raw.version ?? BACKUP_META_VERSION, generatedAt: raw.generatedAt ?? null, dir: relativePath(root, paths.dir), entries };
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
function foldManifestJournal(text) {
|
|
273
|
+
const entries = new Map();
|
|
274
|
+
for (const line of String(text).split('\n')) {
|
|
275
|
+
if (line.trim() === '') continue;
|
|
276
|
+
let row = null;
|
|
277
|
+
try {
|
|
278
|
+
row = JSON.parse(line);
|
|
279
|
+
} catch {
|
|
280
|
+
continue;
|
|
281
|
+
}
|
|
282
|
+
if (!row || typeof row.name !== 'string') continue;
|
|
283
|
+
if (row.__removed === true) {
|
|
284
|
+
entries.delete(row.name);
|
|
285
|
+
continue;
|
|
286
|
+
}
|
|
287
|
+
const derived = deriveBase(row.name);
|
|
288
|
+
entries.set(row.name, {
|
|
289
|
+
name: row.name,
|
|
290
|
+
rel: typeof row.rel === 'string' ? row.rel : null,
|
|
291
|
+
sha256: typeof row.sha256 === 'string' ? row.sha256 : null,
|
|
292
|
+
bytes: Number.isFinite(Number(row.bytes)) ? Number(row.bytes) : null,
|
|
293
|
+
mtimeMs: Number.isFinite(Number(row.mtimeMs)) ? Number(row.mtimeMs) : null,
|
|
294
|
+
base: typeof row.base === 'string' ? row.base : derived.base,
|
|
295
|
+
kind: typeof row.kind === 'string' ? row.kind : 'file',
|
|
296
|
+
source: typeof row.source === 'string' ? row.source : null,
|
|
297
|
+
});
|
|
298
|
+
}
|
|
299
|
+
return [...entries.values()];
|
|
300
|
+
}
|
|
301
|
+
|
|
302
|
+
const manifestCache = new Map();
|
|
303
|
+
|
|
304
|
+
/** All known entries for a backup dir: journal lines folded over the snapshot. */
|
|
305
|
+
export function listManifestEntries(root, dirAbs) {
|
|
306
|
+
const paths = metaPaths(root, dirAbs);
|
|
307
|
+
let journal = '';
|
|
308
|
+
try {
|
|
309
|
+
journal = fs.readFileSync(paths.jsonl, 'utf8');
|
|
310
|
+
} catch {
|
|
311
|
+
journal = '';
|
|
312
|
+
}
|
|
313
|
+
const snapshot = readBackupManifest(root, dirAbs);
|
|
314
|
+
const map = new Map();
|
|
315
|
+
for (const entry of snapshot?.entries ?? []) map.set(entry.name, entry);
|
|
316
|
+
for (const entry of foldManifestJournal(journal)) map.set(entry.name, entry);
|
|
317
|
+
return [...map.values()];
|
|
318
|
+
}
|
|
319
|
+
|
|
320
|
+
function cachedManifestEntries(root, dirAbs) {
|
|
321
|
+
const key = resolveBackupDir(root, dirAbs);
|
|
322
|
+
const cached = manifestCache.get(key);
|
|
323
|
+
const now = Date.now();
|
|
324
|
+
if (cached && now - cached.at < 60_000) return cached.entries;
|
|
325
|
+
const entries = listManifestEntries(root, dirAbs);
|
|
326
|
+
manifestCache.set(key, { at: now, entries });
|
|
327
|
+
return entries;
|
|
328
|
+
}
|
|
329
|
+
|
|
330
|
+
export function invalidateManifestCache(root, dirAbs) {
|
|
331
|
+
manifestCache.delete(resolveBackupDir(root, dirAbs));
|
|
332
|
+
}
|
|
333
|
+
|
|
334
|
+
/** Append one entry to the dir's manifest journal (cheap; compacted on retention). */
|
|
335
|
+
export function appendManifestEntry(root, dirAbs, entry) {
|
|
336
|
+
const paths = metaPaths(root, dirAbs);
|
|
337
|
+
fs.mkdirSync(path.dirname(paths.jsonl), { recursive: true });
|
|
338
|
+
fs.appendFileSync(paths.jsonl, `${JSON.stringify(entry)}\n`, 'utf8');
|
|
339
|
+
invalidateManifestCache(root, dirAbs);
|
|
340
|
+
return paths.jsonl;
|
|
341
|
+
}
|
|
342
|
+
|
|
343
|
+
/**
|
|
344
|
+
* Rewrite the snapshot (`manifest.json`) from the folded journal plus (when
|
|
345
|
+
* given) the currently listed backup files, so legacy backups written before
|
|
346
|
+
* 2.3.0 are registered as well.
|
|
347
|
+
*/
|
|
348
|
+
export function writeBackupManifest(root, dirAbs, { now = new Date(), entries = null } = {}) {
|
|
349
|
+
const paths = metaPaths(root, dirAbs);
|
|
350
|
+
const map = new Map();
|
|
351
|
+
for (const entry of listManifestEntries(root, dirAbs)) map.set(entry.name, entry);
|
|
352
|
+
for (const entry of Array.isArray(entries) ? entries : []) {
|
|
353
|
+
if (!entry || typeof entry.name !== 'string') continue;
|
|
354
|
+
const previous = map.get(entry.name);
|
|
355
|
+
map.set(entry.name, {
|
|
356
|
+
name: entry.name,
|
|
357
|
+
rel: entry.rel ?? previous?.rel ?? relativePath(root, path.join(paths.dir, entry.name)),
|
|
358
|
+
sha256: entry.sha256 ?? previous?.sha256 ?? null,
|
|
359
|
+
bytes: Number.isFinite(Number(entry.bytes)) ? Number(entry.bytes) : (previous?.bytes ?? null),
|
|
360
|
+
mtimeMs: Number.isFinite(Number(entry.mtimeMs)) ? Number(entry.mtimeMs) : (previous?.mtimeMs ?? null),
|
|
361
|
+
base: entry.base ?? previous?.base ?? deriveBase(entry.name).base,
|
|
362
|
+
kind: entry.kind ?? previous?.kind ?? 'file',
|
|
363
|
+
source: entry.source ?? previous?.source ?? null,
|
|
364
|
+
});
|
|
365
|
+
}
|
|
366
|
+
const rows = [...map.values()].sort((a, b) => a.name.localeCompare(b.name));
|
|
367
|
+
const body = {
|
|
368
|
+
version: BACKUP_META_VERSION,
|
|
369
|
+
dir: relativePath(root, paths.dir),
|
|
370
|
+
generatedAt: now.toISOString(),
|
|
371
|
+
entries: rows,
|
|
372
|
+
};
|
|
373
|
+
writeFileDurable(paths.json, `${JSON.stringify(body, null, 2)}\n`);
|
|
374
|
+
if (fs.existsSync(paths.jsonl)) fs.writeFileSync(paths.jsonl, '', 'utf8');
|
|
375
|
+
invalidateManifestCache(root, dirAbs);
|
|
376
|
+
return { path: paths.json, entries: rows };
|
|
377
|
+
}
|
|
378
|
+
|
|
379
|
+
/**
|
|
380
|
+
* Write a GNU-format `SHA256SUMS` file next to the manifest, with the file
|
|
381
|
+
* names written as UTF-8 (no ASCII escaping, no `?` replacement).
|
|
382
|
+
*/
|
|
383
|
+
export function writeChecksumsFile(root, dirAbs, entries, { generatedAt = new Date() } = {}) {
|
|
384
|
+
const paths = metaPaths(root, dirAbs);
|
|
385
|
+
const rows = (Array.isArray(entries) ? entries : [])
|
|
386
|
+
.filter((entry) => entry && typeof entry.name === 'string' && typeof entry.sha256 === 'string')
|
|
387
|
+
.sort((a, b) => a.name.localeCompare(b.name));
|
|
388
|
+
const lines = rows.map((entry) => `${entry.sha256} ${entry.name}`);
|
|
389
|
+
const header = `# longlive backup checksums v1 — ${generatedAt.toISOString()} — files=${rows.length}\n`;
|
|
390
|
+
writeFileDurable(paths.checksums, `${header}${lines.join('\n')}${lines.length > 0 ? '\n' : ''}`);
|
|
391
|
+
return { path: paths.checksums, count: rows.length, names: rows.map((entry) => entry.name) };
|
|
392
|
+
}
|
|
393
|
+
|
|
394
|
+
/** Parse a GNU `sha256sum` file (2-space separator); UTF-8 names are preserved. */
|
|
395
|
+
export function parseChecksumsFile(file) {
|
|
396
|
+
let text = '';
|
|
397
|
+
try {
|
|
398
|
+
text = fs.readFileSync(file, 'utf8').replace(/^\uFEFF/, '');
|
|
399
|
+
} catch {
|
|
400
|
+
return [];
|
|
401
|
+
}
|
|
402
|
+
const out = [];
|
|
403
|
+
for (const line of text.split('\n')) {
|
|
404
|
+
if (line.trim() === '' || line.startsWith('#')) continue;
|
|
405
|
+
const match = /^([0-9a-f]{64})[ \t]{2}(.+)$/.exec(line);
|
|
406
|
+
if (match) out.push({ sha256: match[1], name: match[2] });
|
|
407
|
+
}
|
|
408
|
+
return out;
|
|
409
|
+
}
|
|
410
|
+
|
|
411
|
+
// ---------------------------------------------------------------------------
|
|
412
|
+
// 单文件备份(去重 / 增量)
|
|
413
|
+
// ---------------------------------------------------------------------------
|
|
414
|
+
|
|
415
|
+
function listDirectoryFiles(dirAbs) {
|
|
416
|
+
let entries = [];
|
|
417
|
+
try {
|
|
418
|
+
entries = fs.readdirSync(dirAbs, { withFileTypes: true });
|
|
419
|
+
} catch (error) {
|
|
420
|
+
if (error?.code === 'ENOENT') return [];
|
|
421
|
+
throw memoryError('E_BACKUP_LIST', `读不到备份目录:${dirAbs}`, error);
|
|
422
|
+
}
|
|
423
|
+
const rows = [];
|
|
424
|
+
for (const entry of entries) {
|
|
425
|
+
if (!entry.isFile()) continue;
|
|
426
|
+
if (entry.name === BACKUP_MANIFEST_FILE || entry.name === BACKUP_CHECKSUMS_FILE) continue;
|
|
427
|
+
if (entry.name.startsWith('.') || entry.name.includes('.tmp-')) continue;
|
|
428
|
+
const abs = path.join(dirAbs, entry.name);
|
|
429
|
+
let stat = null;
|
|
430
|
+
try {
|
|
431
|
+
stat = fs.statSync(abs);
|
|
432
|
+
} catch {
|
|
433
|
+
continue;
|
|
434
|
+
}
|
|
435
|
+
const derived = deriveBase(entry.name);
|
|
436
|
+
rows.push({ name: entry.name, path: abs, bytes: stat.size, mtimeMs: stat.mtimeMs, base: derived.base, ext: derived.ext, sha256: null });
|
|
437
|
+
}
|
|
438
|
+
return rows.sort((a, b) => a.name.localeCompare(b.name));
|
|
439
|
+
}
|
|
440
|
+
|
|
441
|
+
/** List backup files (no sha computed here; retention computes it for survivors). */
|
|
442
|
+
export function listBackups(root, dirAbs) {
|
|
443
|
+
return listDirectoryFiles(resolveBackupDir(root, dirAbs));
|
|
444
|
+
}
|
|
445
|
+
|
|
446
|
+
function validExistingBackup(dirAbs, name, wantSha) {
|
|
447
|
+
const abs = path.join(dirAbs, name);
|
|
448
|
+
try {
|
|
449
|
+
const stat = fs.lstatSync(abs);
|
|
450
|
+
if (!stat.isFile()) return false;
|
|
451
|
+
if (sha256File(abs) !== wantSha) return false;
|
|
452
|
+
return true;
|
|
453
|
+
} catch {
|
|
454
|
+
return false;
|
|
455
|
+
}
|
|
456
|
+
}
|
|
457
|
+
|
|
458
|
+
/**
|
|
459
|
+
* Copy one file into a backup directory with sha256 dedupe.
|
|
460
|
+
*
|
|
461
|
+
* Returns `{ path, rel, sha256, bytes, deduped }`. When an existing backup of
|
|
462
|
+
* the same base name already has the same sha256, no copy is made.
|
|
463
|
+
* On copy-integrity failure the partial copy is removed and `E_BACKUP_VERIFY`
|
|
464
|
+
* is thrown (same contract as the old `state.js#backupInto`).
|
|
465
|
+
*/
|
|
466
|
+
export function ensureManagedBackup(root, file, options = {}) {
|
|
467
|
+
const dir = options.dir ?? DEFAULT_BACKUP_DIR;
|
|
468
|
+
const now = options.now instanceof Date ? options.now : new Date();
|
|
469
|
+
const sourceBase = options.base ?? (() => {
|
|
470
|
+
const ext = path.extname(file);
|
|
471
|
+
return path.basename(file, ext) || 'file';
|
|
472
|
+
})();
|
|
473
|
+
const dirAbs = resolveBackupDir(root, dir);
|
|
474
|
+
const abs = resolveInside(root, file);
|
|
475
|
+
let stat = null;
|
|
476
|
+
try {
|
|
477
|
+
stat = fs.lstatSync(abs);
|
|
478
|
+
} catch (error) {
|
|
479
|
+
throw memoryError('E_BACKUP_SOURCE', `备份源不存在:${abs}`, error);
|
|
480
|
+
}
|
|
481
|
+
if (!stat.isFile()) throw memoryError('E_BACKUP_SOURCE', `备份源不是普通文件:${abs}`);
|
|
482
|
+
const want = sha256File(abs);
|
|
483
|
+
const base = sourceBase;
|
|
484
|
+
|
|
485
|
+
if (options.dedupe !== false) {
|
|
486
|
+
const known = cachedManifestEntries(root, dirAbs).find((entry) => entry.base === base && entry.sha256 === want);
|
|
487
|
+
if (known && validExistingBackup(dirAbs, known.name, want)) {
|
|
488
|
+
return { path: path.join(dirAbs, known.name), rel: relativePath(root, path.join(dirAbs, known.name)), sha256: want, bytes: stat.size, deduped: true };
|
|
489
|
+
}
|
|
490
|
+
// Before the dir is adopted (no manifest yet) legacy per-file backups still
|
|
491
|
+
// get sha dedupe, but only in a bounded scan: on a huge legacy dir we skip
|
|
492
|
+
// it (the retention pass adopts and prunes the dir on the same write).
|
|
493
|
+
const scanned = dedupeScan(dirAbs, base, want, stat.size);
|
|
494
|
+
if (scanned) {
|
|
495
|
+
return { path: path.join(dirAbs, scanned), rel: relativePath(root, path.join(dirAbs, scanned)), sha256: want, bytes: stat.size, deduped: true };
|
|
496
|
+
}
|
|
497
|
+
}
|
|
498
|
+
|
|
499
|
+
fs.mkdirSync(dirAbs, { recursive: true });
|
|
500
|
+
const ext = path.extname(abs) || '.md';
|
|
501
|
+
const dest = collisionFree(dirAbs, base, stampToken(now), ext);
|
|
502
|
+
fs.copyFileSync(abs, dest);
|
|
503
|
+
const got = sha256File(dest);
|
|
504
|
+
if (got !== want) {
|
|
505
|
+
try {
|
|
506
|
+
fs.unlinkSync(dest);
|
|
507
|
+
} catch {
|
|
508
|
+
/* best effort: never mask the verification error below */
|
|
509
|
+
}
|
|
510
|
+
throw memoryError('E_BACKUP_VERIFY', `备份校验失败:${path.basename(dest)} 与源文件 sha256 不一致`);
|
|
511
|
+
}
|
|
512
|
+
const entry = {
|
|
513
|
+
name: path.basename(dest),
|
|
514
|
+
rel: relativePath(root, dest),
|
|
515
|
+
sha256: got,
|
|
516
|
+
bytes: stat.size,
|
|
517
|
+
mtimeMs: now.getTime(),
|
|
518
|
+
base,
|
|
519
|
+
kind: options.kind ?? 'file',
|
|
520
|
+
source: options.source ?? relativePath(root, abs),
|
|
521
|
+
};
|
|
522
|
+
try {
|
|
523
|
+
// Only a directory already adopted by the retention pass (manifest/journal
|
|
524
|
+
// exists) keeps a manifest; a legacy per-file backup dir stays byte-identical
|
|
525
|
+
// to 2.2.0 (no new meta files appear just because a card was backed up).
|
|
526
|
+
const paths = metaPaths(root, dirAbs);
|
|
527
|
+
const managed = options.manifest !== false && (fs.existsSync(paths.json) || fs.existsSync(paths.jsonl));
|
|
528
|
+
if (managed) appendManifestEntry(root, dirAbs, entry);
|
|
529
|
+
} catch {
|
|
530
|
+
/* manifest is an optimisation; the backup copy already verified on disk */
|
|
531
|
+
}
|
|
532
|
+
return { path: dest, rel: entry.rel, sha256: got, bytes: stat.size, deduped: false };
|
|
533
|
+
}
|
|
534
|
+
|
|
535
|
+
/**
|
|
536
|
+
* Bounded sha dedupe scan for a not-yet-adopted backup dir: <=200 entries,
|
|
537
|
+
* same base prefix and same size first, then sha256. Keeps the 2.2.0 "one copy
|
|
538
|
+
* per write" contract for small roots while still skipping identical bytes.
|
|
539
|
+
*/
|
|
540
|
+
function dedupeScan(dirAbs, base, want, size) {
|
|
541
|
+
let names = [];
|
|
542
|
+
try {
|
|
543
|
+
names = fs.readdirSync(dirAbs);
|
|
544
|
+
} catch {
|
|
545
|
+
return null;
|
|
546
|
+
}
|
|
547
|
+
if (names.length > 200) return null;
|
|
548
|
+
for (const name of names) {
|
|
549
|
+
if (!name.startsWith(`${base}.`)) continue;
|
|
550
|
+
const abs = path.join(dirAbs, name);
|
|
551
|
+
try {
|
|
552
|
+
const stat = fs.statSync(abs);
|
|
553
|
+
if (!stat.isFile() || stat.size !== size) continue;
|
|
554
|
+
if (sha256File(abs) === want) return name;
|
|
555
|
+
} catch {
|
|
556
|
+
/* a stale/unreadable candidate must not break the backup path */
|
|
557
|
+
}
|
|
558
|
+
}
|
|
559
|
+
return null;
|
|
560
|
+
}
|
|
561
|
+
|
|
562
|
+
/** Back up the long-lived root files (status.json / INDEX.md / STATE.md / POLICY.md …). */
|
|
563
|
+
export function snapshotRootFiles(root, { dir = DEFAULT_BACKUP_DIR, now = new Date(), files = ROOT_SNAPSHOT_FILES, maxBytes = DEFAULT_RETENTION.maxRootSnapshotBytes } = {}) {
|
|
564
|
+
const copied = [];
|
|
565
|
+
const skipped = [];
|
|
566
|
+
let bytes = 0;
|
|
567
|
+
for (const rel of files) {
|
|
568
|
+
let abs = null;
|
|
569
|
+
try {
|
|
570
|
+
abs = resolveInside(root, rel);
|
|
571
|
+
const stat = fs.lstatSync(abs);
|
|
572
|
+
if (stat.isSymbolicLink() || !stat.isFile()) {
|
|
573
|
+
skipped.push({ rel, reason: 'not-a-regular-file' });
|
|
574
|
+
continue;
|
|
575
|
+
}
|
|
576
|
+
if (stat.size > maxBytes) {
|
|
577
|
+
skipped.push({ rel, reason: `too-large>${maxBytes}` });
|
|
578
|
+
continue;
|
|
579
|
+
}
|
|
580
|
+
} catch {
|
|
581
|
+
skipped.push({ rel, reason: 'missing' });
|
|
582
|
+
continue;
|
|
583
|
+
}
|
|
584
|
+
const result = ensureManagedBackup(root, rel, { dir, now, kind: 'root', base: path.basename(rel, path.extname(rel)) || path.basename(rel), source: rel });
|
|
585
|
+
copied.push({ rel, backup: result.rel, sha256: result.sha256, deduped: result.deduped });
|
|
586
|
+
if (!result.deduped) bytes += result.bytes;
|
|
587
|
+
}
|
|
588
|
+
return { copied, skipped, bytes };
|
|
589
|
+
}
|
|
590
|
+
|
|
591
|
+
// ---------------------------------------------------------------------------
|
|
592
|
+
// 执行保留
|
|
593
|
+
// ---------------------------------------------------------------------------
|
|
594
|
+
|
|
595
|
+
export function normalizeRetentionOptions(raw = {}) {
|
|
596
|
+
const source = raw && typeof raw === 'object' ? raw : {};
|
|
597
|
+
const nested = source.retention && typeof source.retention === 'object' ? source.retention : {};
|
|
598
|
+
const pick = (key) => (nested[key] !== undefined ? nested[key] : source[key]);
|
|
599
|
+
const num = (value, fallback, min) => {
|
|
600
|
+
const n = Number(value);
|
|
601
|
+
return Number.isFinite(n) && n >= min ? n : fallback;
|
|
602
|
+
};
|
|
603
|
+
const maxAgeDays = pick('maxAgeDays');
|
|
604
|
+
const maxBytes = pick('maxBytes');
|
|
605
|
+
const intervalMs = pick('intervalMs');
|
|
606
|
+
const snapshotIntervalMs = pick('snapshotIntervalMs');
|
|
607
|
+
const maxRootSnapshotBytes = pick('maxRootSnapshotBytes');
|
|
608
|
+
const maxHashFiles = pick('maxHashFiles');
|
|
609
|
+
const maxFiles = pick('maxFiles');
|
|
610
|
+
const now = source.now instanceof Date ? source.now : (nested.now instanceof Date ? nested.now : new Date());
|
|
611
|
+
return {
|
|
612
|
+
now,
|
|
613
|
+
maxAgeDays: num(maxAgeDays, DEFAULT_RETENTION.maxAgeDays, 0),
|
|
614
|
+
maxBytes: num(maxBytes, DEFAULT_RETENTION.maxBytes, 0),
|
|
615
|
+
intervalMs: num(intervalMs, DEFAULT_RETENTION.intervalMs, 0),
|
|
616
|
+
snapshotIntervalMs: num(snapshotIntervalMs, DEFAULT_RETENTION.snapshotIntervalMs, 0),
|
|
617
|
+
maxRootSnapshotBytes: num(maxRootSnapshotBytes, DEFAULT_RETENTION.maxRootSnapshotBytes, 0),
|
|
618
|
+
maxHashFiles: num(maxHashFiles, DEFAULT_RETENTION.maxHashFiles, 1),
|
|
619
|
+
maxFiles: num(maxFiles, DEFAULT_RETENTION.maxFiles, 1),
|
|
620
|
+
keepLatestPerBase: pick('keepLatestPerBase') === undefined ? DEFAULT_RETENTION.keepLatestPerBase : Boolean(pick('keepLatestPerBase')),
|
|
621
|
+
raw: source,
|
|
622
|
+
};
|
|
623
|
+
}
|
|
624
|
+
|
|
625
|
+
function planNowMs(now) {
|
|
626
|
+
if (now instanceof Date) return now.getTime();
|
|
627
|
+
const value = Number(now);
|
|
628
|
+
return Number.isFinite(value) ? value : Date.now();
|
|
629
|
+
}
|
|
630
|
+
|
|
631
|
+
/**
|
|
632
|
+
* Run the retention plan on `<root>/<dir>`: compute the plan, delete removals
|
|
633
|
+
* (unless dryRun), rebuild the manifest snapshot, and rewrite SHA256SUMS in UTF-8.
|
|
634
|
+
*
|
|
635
|
+
* `maxHashFiles` bounds the hashing cost on a huge legacy dir (real roots can
|
|
636
|
+
* start at ~17k files); above it the sha pass and checksums are skipped and the
|
|
637
|
+
* report says so instead of silently spending minutes reading backups.
|
|
638
|
+
*/
|
|
639
|
+
export function runBackupRetention(root, { dir = DEFAULT_BACKUP_DIR, options = {}, dryRun = false, now = new Date() } = {}) {
|
|
640
|
+
const opts = normalizeRetentionOptions({ ...options, now: options?.now instanceof Date ? options.now : now });
|
|
641
|
+
const dirAbs = resolveBackupDir(root, dir);
|
|
642
|
+
const listed = listBackups(root, dirAbs);
|
|
643
|
+
const maxHashFiles = Number.isFinite(Number(opts.maxHashFiles)) ? Number(opts.maxHashFiles) : DEFAULT_RETENTION.maxHashFiles;
|
|
644
|
+
const first = planRetention(listed, opts);
|
|
645
|
+
let hashSkipped = false;
|
|
646
|
+
if (listed.length <= maxHashFiles) {
|
|
647
|
+
const survivors = new Set(first.keep.map((entry) => entry.name));
|
|
648
|
+
for (const entry of listed) {
|
|
649
|
+
if (!survivors.has(entry.name)) continue;
|
|
650
|
+
try {
|
|
651
|
+
entry.sha256 = sha256File(entry.path);
|
|
652
|
+
} catch {
|
|
653
|
+
entry.sha256 = null;
|
|
654
|
+
}
|
|
655
|
+
}
|
|
656
|
+
} else {
|
|
657
|
+
hashSkipped = true;
|
|
658
|
+
}
|
|
659
|
+
const finalPlan = planRetention(listed, opts);
|
|
660
|
+
const removed = [];
|
|
661
|
+
if (!dryRun) {
|
|
662
|
+
for (const row of finalPlan.remove) {
|
|
663
|
+
const abs = path.join(dirAbs, row.name);
|
|
664
|
+
try {
|
|
665
|
+
const stat = fs.lstatSync(abs);
|
|
666
|
+
if (!stat.isFile() || stat.isSymbolicLink()) continue;
|
|
667
|
+
fs.rmSync(abs, { force: true });
|
|
668
|
+
removed.push(row);
|
|
669
|
+
appendManifestEntry(root, dirAbs, { name: row.name, __removed: true, reason: row.reason });
|
|
670
|
+
} catch {
|
|
671
|
+
/* a concurrently removed file is already in the desired state */
|
|
672
|
+
}
|
|
673
|
+
}
|
|
674
|
+
const keptRows = listed.filter((entry) => finalPlan.keep.some((item) => item.name === entry.name));
|
|
675
|
+
writeBackupManifest(root, dirAbs, { now: opts.now, entries: keptRows });
|
|
676
|
+
const keptEntries = listManifestEntries(root, dirAbs)
|
|
677
|
+
.filter((entry) => fs.existsSync(path.join(dirAbs, entry.name)))
|
|
678
|
+
.map((entry) => ({
|
|
679
|
+
...entry,
|
|
680
|
+
sha256: entry.sha256 ?? (() => {
|
|
681
|
+
try {
|
|
682
|
+
return sha256File(path.join(dirAbs, entry.name));
|
|
683
|
+
} catch {
|
|
684
|
+
return null;
|
|
685
|
+
}
|
|
686
|
+
})(),
|
|
687
|
+
}));
|
|
688
|
+
if (keptEntries.length <= maxHashFiles) writeChecksumsFile(root, dirAbs, keptEntries, { generatedAt: opts.now });
|
|
689
|
+
else appendManifestEntry(root, dirAbs, { name: '.checksums-deferred', __removed: false, skipped: true, count: keptEntries.length });
|
|
690
|
+
}
|
|
691
|
+
return {
|
|
692
|
+
ok: true,
|
|
693
|
+
dryRun,
|
|
694
|
+
dir: relativePath(root, dirAbs),
|
|
695
|
+
policy: finalPlan.options,
|
|
696
|
+
before: finalPlan.before,
|
|
697
|
+
after: finalPlan.after,
|
|
698
|
+
keep: finalPlan.keep.map((entry) => entry.name),
|
|
699
|
+
remove: finalPlan.remove,
|
|
700
|
+
duplicates: finalPlan.duplicates,
|
|
701
|
+
removed: removed.map((entry) => entry.name),
|
|
702
|
+
hashSkipped,
|
|
703
|
+
freedBytes: removed.reduce((sum, entry) => {
|
|
704
|
+
const matched = listed.find((item) => item.name === entry.name);
|
|
705
|
+
return sum + (Number(matched?.bytes) || 0);
|
|
706
|
+
}, 0),
|
|
707
|
+
};
|
|
708
|
+
}
|
|
709
|
+
|
|
710
|
+
// ---------------------------------------------------------------------------
|
|
711
|
+
// "到点才跑"门(接在 state 写路径上)
|
|
712
|
+
// ---------------------------------------------------------------------------
|
|
713
|
+
|
|
714
|
+
export function readRetentionState(root) {
|
|
715
|
+
const raw = readJsonSafe(resolveInside(root, BACKUP_RETENTION_STATE));
|
|
716
|
+
if (!raw || typeof raw !== 'object') return { lastRunAt: null, lastSnapshotAt: null };
|
|
717
|
+
return {
|
|
718
|
+
lastRunAt: typeof raw.lastRunAt === 'string' ? raw.lastRunAt : null,
|
|
719
|
+
lastSnapshotAt: typeof raw.lastSnapshotAt === 'string' ? raw.lastSnapshotAt : null,
|
|
720
|
+
};
|
|
721
|
+
}
|
|
722
|
+
|
|
723
|
+
function writeRetentionState(root, state) {
|
|
724
|
+
writeFileDurable(resolveInside(root, BACKUP_RETENTION_STATE), `${JSON.stringify({ version: BACKUP_META_VERSION, ...state }, null, 2)}\n`);
|
|
725
|
+
}
|
|
726
|
+
|
|
727
|
+
/**
|
|
728
|
+
* Fusion point for the state write path: called after a successful state write,
|
|
729
|
+
* runs at most once per `intervalMs` (retention) / `snapshotIntervalMs` (root files).
|
|
730
|
+
* Never throws for backup-side problems — the caller must not lose a state write
|
|
731
|
+
* because a backup housekeeping step failed.
|
|
732
|
+
*/
|
|
733
|
+
export function runBackupMaintenance(root, { dir = DEFAULT_BACKUP_DIR, options = {}, force = false, snapshot = true, now = new Date() } = {}) {
|
|
734
|
+
const opts = normalizeRetentionOptions({ ...options, now: options?.now instanceof Date ? options.now : now });
|
|
735
|
+
const nowMs = opts.now.getTime();
|
|
736
|
+
const current = readRetentionState(root);
|
|
737
|
+
const due = force || current.lastRunAt == null || nowMs - Date.parse(current.lastRunAt) >= opts.intervalMs || !Number.isFinite(Date.parse(current.lastRunAt));
|
|
738
|
+
const snapshotDue = snapshot && (force || current.lastSnapshotAt == null || nowMs - Date.parse(current.lastSnapshotAt) >= opts.snapshotIntervalMs || !Number.isFinite(Date.parse(current.lastSnapshotAt)));
|
|
739
|
+
if (!due && !snapshotDue) return { ok: true, ran: false, reason: 'not-due' };
|
|
740
|
+
|
|
741
|
+
let rootSnapshot = { copied: [], skipped: [], bytes: 0 };
|
|
742
|
+
if (snapshotDue) {
|
|
743
|
+
try {
|
|
744
|
+
rootSnapshot = snapshotRootFiles(root, { dir, now: opts.now, maxBytes: opts.maxRootSnapshotBytes });
|
|
745
|
+
} catch (error) {
|
|
746
|
+
rootSnapshot = { copied: [], skipped: [], bytes: 0, error: String(error?.message ?? error) };
|
|
747
|
+
}
|
|
748
|
+
}
|
|
749
|
+
let retention = { ok: true, ran: false };
|
|
750
|
+
if (due) {
|
|
751
|
+
try {
|
|
752
|
+
retention = runBackupRetention(root, { dir, options: opts, now: opts.now });
|
|
753
|
+
retention.ran = true;
|
|
754
|
+
} catch (error) {
|
|
755
|
+
retention = { ok: false, ran: false, error: String(error?.message ?? error) };
|
|
756
|
+
}
|
|
757
|
+
}
|
|
758
|
+
try {
|
|
759
|
+
writeRetentionState(root, {
|
|
760
|
+
lastRunAt: due ? opts.now.toISOString() : current.lastRunAt,
|
|
761
|
+
lastSnapshotAt: snapshotDue ? opts.now.toISOString() : current.lastSnapshotAt,
|
|
762
|
+
dir,
|
|
763
|
+
removed: retention?.removed?.length ?? 0,
|
|
764
|
+
rootFiles: rootSnapshot.copied.length,
|
|
765
|
+
});
|
|
766
|
+
} catch {
|
|
767
|
+
/* see doc comment: housekeeping must never break the state write */
|
|
768
|
+
}
|
|
769
|
+
return { ok: true, ran: true, retention, rootSnapshot };
|
|
770
|
+
}
|
|
771
|
+
|
|
772
|
+
/**
|
|
773
|
+
* Adoption gate for the state write path.
|
|
774
|
+
*
|
|
775
|
+
* A fresh/legacy backup directory is only "managed" once it already needs it:
|
|
776
|
+
* over `maxFiles`, over `maxBytes`, or containing something older than
|
|
777
|
+
* `maxAgeDays`. This keeps the write path side-effect-free for small stores
|
|
778
|
+
* (2.2.0 tests and newly created roots keep their exact file counts) while the
|
|
779
|
+
* real memory root — measured at 17,116 files / 2,941 MB — is adopted on the
|
|
780
|
+
* first state write and pruned from then on. Once a manifest exists the regular
|
|
781
|
+
* `runBackupMaintenance` interval gate takes over.
|
|
782
|
+
*/
|
|
783
|
+
export function backupStoreNeedsMaintenance(root, { dir = DEFAULT_BACKUP_DIR, options = {}, now = new Date() } = {}) {
|
|
784
|
+
const opts = normalizeRetentionOptions({ ...options, now: options?.now instanceof Date ? options.now : now });
|
|
785
|
+
const dirAbs = resolveBackupDir(root, dir);
|
|
786
|
+
let paths = null;
|
|
787
|
+
try {
|
|
788
|
+
paths = metaPaths(root, dirAbs);
|
|
789
|
+
} catch {
|
|
790
|
+
return false;
|
|
791
|
+
}
|
|
792
|
+
if (fs.existsSync(paths.json) || fs.existsSync(paths.jsonl)) return true;
|
|
793
|
+
|
|
794
|
+
let names = [];
|
|
795
|
+
try {
|
|
796
|
+
names = fs.readdirSync(dirAbs).filter((name) => {
|
|
797
|
+
try {
|
|
798
|
+
return fs.lstatSync(path.join(dirAbs, name)).isFile();
|
|
799
|
+
} catch {
|
|
800
|
+
return false;
|
|
801
|
+
}
|
|
802
|
+
});
|
|
803
|
+
} catch {
|
|
804
|
+
return false;
|
|
805
|
+
}
|
|
806
|
+
if (names.length === 0) return false;
|
|
807
|
+
if (names.length > opts.maxFiles) return true;
|
|
808
|
+
|
|
809
|
+
let bytes = 0;
|
|
810
|
+
let oldest = Infinity;
|
|
811
|
+
for (const name of names) {
|
|
812
|
+
try {
|
|
813
|
+
const stat = fs.statSync(path.join(dirAbs, name));
|
|
814
|
+
bytes += stat.size;
|
|
815
|
+
if (stat.mtimeMs < oldest) oldest = stat.mtimeMs;
|
|
816
|
+
} catch {
|
|
817
|
+
/* ignore a file that vanished mid-scan */
|
|
818
|
+
}
|
|
819
|
+
}
|
|
820
|
+
if (bytes > opts.maxBytes) return true;
|
|
821
|
+
if (Number.isFinite(oldest) && opts.now.getTime() - oldest > opts.maxAgeDays * 24 * 60 * 60 * 1000) return true;
|
|
822
|
+
return false;
|
|
823
|
+
}
|