@ddtcorex/dsh-maestro-core 0.12.0 → 0.13.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/README.md +2 -2
- package/lib/boot-lock.d.ts +1 -1
- package/lib/boot-lock.js +1 -1
- package/lib/cli.d.ts +0 -30
- package/lib/cli.js +2 -202
- package/lib/daemon-freshness.d.ts +4 -4
- package/lib/daemon-freshness.js +4 -4
- package/lib/guard/rules.js +1 -3
- package/lib/health-poller.js +3 -3
- package/lib/notifier.js +1 -1
- package/lib/report.js +0 -2
- package/lib/restart-exec.d.ts +1 -1
- package/lib/restart-exec.js +1 -1
- package/lib/restart-guards.d.ts +0 -1
- package/lib/restart-guards.js +1 -11
- package/lib/restart-tool.d.ts +7 -25
- package/lib/restart-tool.js +11 -85
- package/lib/restart-web.d.ts +1 -1
- package/lib/restart-web.js +1 -1
- package/lib/supervisor.d.ts +2 -27
- package/lib/supervisor.js +32 -71
- package/package.json +1 -1
- package/skills/dsh-safe-restart/SKILL.md +5 -5
- package/skills/dsh-safe-restart/scripts/restart-dsh-web.sh +2 -2
- package/src/host/boot-lock.ts +1 -1
- package/src/host/cli.ts +2 -172
- package/src/host/daemon-freshness.ts +4 -4
- package/src/host/guard/rules.ts +1 -3
- package/src/host/health-poller.ts +3 -3
- package/src/host/notifier.ts +1 -1
- package/src/host/report.ts +0 -2
- package/src/host/restart-exec.ts +1 -1
- package/src/host/restart-guards.ts +1 -12
- package/src/host/restart-tool.ts +12 -75
- package/src/host/restart-web.ts +1 -1
- package/src/host/supervisor.ts +38 -84
- package/lib/snapshot.d.ts +0 -60
- package/lib/snapshot.js +0 -359
- package/src/host/snapshot.ts +0 -338
package/lib/snapshot.js
DELETED
|
@@ -1,359 +0,0 @@
|
|
|
1
|
-
import * as fs from 'node:fs';
|
|
2
|
-
import * as path from 'node:path';
|
|
3
|
-
import * as crypto from 'node:crypto';
|
|
4
|
-
/**
|
|
5
|
-
* Entries under the harness home directory that the last-known-good snapshot
|
|
6
|
-
* deliberately never copies.
|
|
7
|
-
*
|
|
8
|
-
* The LKG exists to recover a boot that fails while loading the plugin tree, so
|
|
9
|
-
* it holds boot **configuration**: `profiles/` (the plugin tree with its
|
|
10
|
-
* lockfile, `cordis.patch.yml` and sidecars), the per-plugin config directories
|
|
11
|
-
* and the settings documents. Everything below is runtime **data** — it is
|
|
12
|
-
* written continuously while `dsh web` runs, so restoring a snapshot of it can
|
|
13
|
-
* only lose newer state, and some of it is hostile to a bulk copy:
|
|
14
|
-
*
|
|
15
|
-
* - `sessions/` — append-only transcripts. Restoring a stale copy over live
|
|
16
|
-
* sessions drops every turn recorded after the snapshot, i.e. the recovery
|
|
17
|
-
* path would lose the log it is supposed to protect.
|
|
18
|
-
* - `attachments/` — content-addressed blobs stored mode `0400`. That read-only
|
|
19
|
-
* bit is exactly what made the 2026-09-13 rollback abort with
|
|
20
|
-
* `EACCES: Permission denied '.../attachments/v1/objects/f8'`.
|
|
21
|
-
* - `plugins-src/` — plugin source cache, re-fetched on demand (~400 MB host).
|
|
22
|
-
* - `.supervisor/` — the LKG root itself lives inside the DSH home, so copying
|
|
23
|
-
* it would recurse into every retained snapshot.
|
|
24
|
-
*
|
|
25
|
-
* This list is data, not a heuristic: the copy loop and the restore loop both
|
|
26
|
-
* consult `isLkgExcluded()`, and the table test pins the rule.
|
|
27
|
-
*/
|
|
28
|
-
export const LKG_EXCLUDED_ENTRIES = [
|
|
29
|
-
'sessions',
|
|
30
|
-
'attachments',
|
|
31
|
-
'plugins-src',
|
|
32
|
-
'.supervisor',
|
|
33
|
-
];
|
|
34
|
-
/**
|
|
35
|
-
* True when a path relative to the harness home must never enter (or leave) the LKG.
|
|
36
|
-
*
|
|
37
|
-
* The named entries match the first path segment; `*.log` matches by basename
|
|
38
|
-
* anywhere, because append-only logs are data at any depth and a restored stale
|
|
39
|
-
* `dsh-web.log` would poison the boot-boundary scan.
|
|
40
|
-
*/
|
|
41
|
-
export function isLkgExcluded(relPath) {
|
|
42
|
-
const normalized = relPath.replace(/\\/g, '/').replace(/^\.\//, '').replace(/^\/+/, '');
|
|
43
|
-
const segments = normalized.split('/').filter(s => s.length > 0 && s !== '.');
|
|
44
|
-
if (!segments.length)
|
|
45
|
-
return false;
|
|
46
|
-
if (LKG_EXCLUDED_ENTRIES.includes(segments[0]))
|
|
47
|
-
return true;
|
|
48
|
-
return segments[segments.length - 1].endsWith('.log');
|
|
49
|
-
}
|
|
50
|
-
function sha256File(filePath) {
|
|
51
|
-
const data = fs.readFileSync(filePath);
|
|
52
|
-
return crypto.createHash('sha256').update(data).digest('hex');
|
|
53
|
-
}
|
|
54
|
-
function walkFiles(dir, base = dir) {
|
|
55
|
-
const out = [];
|
|
56
|
-
for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
|
|
57
|
-
const full = path.join(dir, entry.name);
|
|
58
|
-
if (entry.isDirectory())
|
|
59
|
-
out.push(...walkFiles(full, base));
|
|
60
|
-
else if (entry.isFile())
|
|
61
|
-
out.push(path.relative(base, full));
|
|
62
|
-
}
|
|
63
|
-
return out;
|
|
64
|
-
}
|
|
65
|
-
/** Human-readable, bounded reason for a per-entry copy failure. */
|
|
66
|
-
export function failureReason(e) {
|
|
67
|
-
const err = e;
|
|
68
|
-
const code = typeof err?.code === 'string' && err.code ? `${err.code}: ` : '';
|
|
69
|
-
const message = typeof err?.message === 'string' ? err.message : String(e);
|
|
70
|
-
return `${code}${message}`.slice(0, 300);
|
|
71
|
-
}
|
|
72
|
-
/**
|
|
73
|
-
* Copy one snapshot entry, collecting — never throwing — per-entry failures
|
|
74
|
-
* (D2). `fs.cpSync` aborts the whole snapshot on the first unreadable object,
|
|
75
|
-
* which is precisely how one 0400 attachment file stopped the rollback that
|
|
76
|
-
* exists to rescue a broken boot.
|
|
77
|
-
*/
|
|
78
|
-
function copyEntry(state, src, dest, rel) {
|
|
79
|
-
if (isLkgExcluded(rel))
|
|
80
|
-
return;
|
|
81
|
-
let st;
|
|
82
|
-
try {
|
|
83
|
-
st = fs.lstatSync(src);
|
|
84
|
-
}
|
|
85
|
-
catch (e) {
|
|
86
|
-
state.skipped.push({ path: rel, reason: failureReason(e) });
|
|
87
|
-
return;
|
|
88
|
-
}
|
|
89
|
-
if (st.isDirectory()) {
|
|
90
|
-
let names;
|
|
91
|
-
try {
|
|
92
|
-
// Directory modes are replicated only in their permission-to-traverse
|
|
93
|
-
// sense: the snapshot itself must stay readable/removable even when the
|
|
94
|
-
// source directory is not (a 0000 source dir must not produce a snapshot
|
|
95
|
-
// that nothing — including retention — can delete).
|
|
96
|
-
fs.mkdirSync(dest, { recursive: true, mode: (st.mode & 0o7777) | 0o700 });
|
|
97
|
-
names = fs.readdirSync(src);
|
|
98
|
-
}
|
|
99
|
-
catch (e) {
|
|
100
|
-
state.skipped.push({ path: rel, reason: failureReason(e) });
|
|
101
|
-
return;
|
|
102
|
-
}
|
|
103
|
-
for (const name of names) {
|
|
104
|
-
copyEntry(state, path.join(src, name), path.join(dest, name), rel ? `${rel}/${name}` : name);
|
|
105
|
-
}
|
|
106
|
-
return;
|
|
107
|
-
}
|
|
108
|
-
if (st.isSymbolicLink()) {
|
|
109
|
-
try {
|
|
110
|
-
const link = fs.readlinkSync(src);
|
|
111
|
-
fs.mkdirSync(path.dirname(dest), { recursive: true });
|
|
112
|
-
try {
|
|
113
|
-
fs.unlinkSync(dest);
|
|
114
|
-
}
|
|
115
|
-
catch { }
|
|
116
|
-
fs.symlinkSync(link, dest);
|
|
117
|
-
state.copied++;
|
|
118
|
-
}
|
|
119
|
-
catch (e) {
|
|
120
|
-
state.skipped.push({ path: rel, reason: failureReason(e) });
|
|
121
|
-
}
|
|
122
|
-
return;
|
|
123
|
-
}
|
|
124
|
-
if (st.isFile()) {
|
|
125
|
-
try {
|
|
126
|
-
fs.mkdirSync(path.dirname(dest), { recursive: true });
|
|
127
|
-
state.copyFile(src, dest, st.mode & 0o7777);
|
|
128
|
-
state.copied++;
|
|
129
|
-
}
|
|
130
|
-
catch (e) {
|
|
131
|
-
state.skipped.push({ path: rel, reason: failureReason(e) });
|
|
132
|
-
}
|
|
133
|
-
}
|
|
134
|
-
// Sockets/FIFOs/devices are not boot configuration: ignored on purpose.
|
|
135
|
-
}
|
|
136
|
-
export async function writeLKG(dshHome, lkgRoot, deps = {}) {
|
|
137
|
-
// Dedupe: skip snapshot if current state identical to latest LKG (prevents 5-min unconditional growth)
|
|
138
|
-
try {
|
|
139
|
-
if (await isDuplicateLKG(dshHome, lkgRoot)) {
|
|
140
|
-
const entries = fs.readdirSync(lkgRoot).filter((n) => {
|
|
141
|
-
try {
|
|
142
|
-
return fs.statSync(path.join(lkgRoot, n)).isDirectory();
|
|
143
|
-
}
|
|
144
|
-
catch {
|
|
145
|
-
return false;
|
|
146
|
-
}
|
|
147
|
-
}).sort();
|
|
148
|
-
const latest = entries[entries.length - 1];
|
|
149
|
-
const manifestPath = path.join(lkgRoot, latest, 'manifest.json');
|
|
150
|
-
const manifest = JSON.parse(fs.readFileSync(manifestPath, 'utf-8'));
|
|
151
|
-
return { ts: latest, files: manifest.files?.length ?? 0, skipped: [] };
|
|
152
|
-
}
|
|
153
|
-
}
|
|
154
|
-
catch { }
|
|
155
|
-
const ts = new Date().toISOString().replace(/[:.]/g, '-');
|
|
156
|
-
const dest = path.join(lkgRoot, ts);
|
|
157
|
-
try {
|
|
158
|
-
fs.mkdirSync(dest, { recursive: true });
|
|
159
|
-
}
|
|
160
|
-
catch (e) {
|
|
161
|
-
// No snapshot is better than an exception thrown into the rollback path.
|
|
162
|
-
return { ts, files: 0, skipped: [{ path: lkgRoot, reason: failureReason(e) }] };
|
|
163
|
-
}
|
|
164
|
-
const state = {
|
|
165
|
-
dshHome,
|
|
166
|
-
copyFile: deps.copyFile ?? ((src, dst, mode) => {
|
|
167
|
-
fs.copyFileSync(src, dst);
|
|
168
|
-
try {
|
|
169
|
-
fs.chmodSync(dst, mode);
|
|
170
|
-
}
|
|
171
|
-
catch { }
|
|
172
|
-
}),
|
|
173
|
-
copied: 0,
|
|
174
|
-
skipped: [],
|
|
175
|
-
};
|
|
176
|
-
// Copy only the boot configuration (D1), one entry at a time so a single
|
|
177
|
-
// unreadable file is recorded and skipped instead of aborting the snapshot (D2).
|
|
178
|
-
let topLevel = [];
|
|
179
|
-
try {
|
|
180
|
-
if (fs.existsSync(dshHome))
|
|
181
|
-
topLevel = fs.readdirSync(dshHome);
|
|
182
|
-
}
|
|
183
|
-
catch (e) {
|
|
184
|
-
state.skipped.push({ path: '.', reason: failureReason(e) });
|
|
185
|
-
}
|
|
186
|
-
for (const entry of topLevel) {
|
|
187
|
-
copyEntry(state, path.join(dshHome, entry), path.join(dest, entry), entry);
|
|
188
|
-
}
|
|
189
|
-
let fileList = [];
|
|
190
|
-
try {
|
|
191
|
-
fileList = fs.existsSync(dest) ? walkFiles(dest) : [];
|
|
192
|
-
}
|
|
193
|
-
catch (e) {
|
|
194
|
-
state.skipped.push({ path: 'manifest', reason: failureReason(e) });
|
|
195
|
-
}
|
|
196
|
-
const manifest = {
|
|
197
|
-
ts,
|
|
198
|
-
files: fileList
|
|
199
|
-
.filter(f => f !== 'manifest.json')
|
|
200
|
-
.map(f => ({ path: f, sha256: sha256File(path.join(dest, f)) })),
|
|
201
|
-
};
|
|
202
|
-
try {
|
|
203
|
-
fs.writeFileSync(path.join(dest, 'manifest.json'), JSON.stringify(manifest, null, 2));
|
|
204
|
-
}
|
|
205
|
-
catch (e) {
|
|
206
|
-
state.skipped.push({ path: 'manifest.json', reason: failureReason(e) });
|
|
207
|
-
}
|
|
208
|
-
// Retention: keep only 3 most recent, plus age (7d) and size (5GB) caps — prevents unbounded 40GB+ growth
|
|
209
|
-
await rotateLKG(lkgRoot, 3).catch(() => { });
|
|
210
|
-
await pruneByAge(lkgRoot, 7 * 24 * 60 * 60 * 1000).catch(() => { });
|
|
211
|
-
await pruneBySize(lkgRoot, 5 * 1024 * 1024 * 1024).catch(() => { });
|
|
212
|
-
return { ts, files: state.copied, skipped: state.skipped };
|
|
213
|
-
}
|
|
214
|
-
export async function pruneByAge(root, maxAgeMs) {
|
|
215
|
-
if (!fs.existsSync(root))
|
|
216
|
-
return;
|
|
217
|
-
const now = Date.now();
|
|
218
|
-
const entries = fs.readdirSync(root).filter((n) => {
|
|
219
|
-
try {
|
|
220
|
-
return fs.statSync(path.join(root, n)).isDirectory();
|
|
221
|
-
}
|
|
222
|
-
catch {
|
|
223
|
-
return false;
|
|
224
|
-
}
|
|
225
|
-
});
|
|
226
|
-
for (const name of entries) {
|
|
227
|
-
try {
|
|
228
|
-
const tsStr = name.replace(/^(\d{4})-(\d{2})-(\d{2})T(\d{2})-(\d{2})-(\d{2})-(\d+)Z$/, '$1-$2-$3T$4:$5:$6.$7Z');
|
|
229
|
-
const ts = Date.parse(tsStr);
|
|
230
|
-
if (!isNaN(ts) && now - ts > maxAgeMs) {
|
|
231
|
-
fs.rmSync(path.join(root, name), { recursive: true, force: true });
|
|
232
|
-
}
|
|
233
|
-
}
|
|
234
|
-
catch { }
|
|
235
|
-
}
|
|
236
|
-
}
|
|
237
|
-
export async function pruneBySize(root, maxBytes) {
|
|
238
|
-
if (!fs.existsSync(root))
|
|
239
|
-
return;
|
|
240
|
-
const entries = fs.readdirSync(root).filter((n) => {
|
|
241
|
-
try {
|
|
242
|
-
return fs.statSync(path.join(root, n)).isDirectory();
|
|
243
|
-
}
|
|
244
|
-
catch {
|
|
245
|
-
return false;
|
|
246
|
-
}
|
|
247
|
-
}).sort();
|
|
248
|
-
let total = 0;
|
|
249
|
-
const sizes = [];
|
|
250
|
-
for (const name of entries) {
|
|
251
|
-
try {
|
|
252
|
-
const p = path.join(root, name);
|
|
253
|
-
let size = 0;
|
|
254
|
-
for (const f of walkFiles(p)) {
|
|
255
|
-
try {
|
|
256
|
-
size += fs.statSync(path.join(p, f)).size;
|
|
257
|
-
}
|
|
258
|
-
catch { }
|
|
259
|
-
}
|
|
260
|
-
sizes.push({ name, size });
|
|
261
|
-
total += size;
|
|
262
|
-
}
|
|
263
|
-
catch { }
|
|
264
|
-
}
|
|
265
|
-
for (const { name, size } of sizes) {
|
|
266
|
-
if (total <= maxBytes)
|
|
267
|
-
break;
|
|
268
|
-
try {
|
|
269
|
-
fs.rmSync(path.join(root, name), { recursive: true, force: true });
|
|
270
|
-
total -= size;
|
|
271
|
-
}
|
|
272
|
-
catch { }
|
|
273
|
-
}
|
|
274
|
-
}
|
|
275
|
-
export async function isDuplicateLKG(dshHome, lkgRoot) {
|
|
276
|
-
// Lightweight dedupe: if latest snapshot is <5 minutes old, skip (prevents 5-min unconditional growth)
|
|
277
|
-
// Full hash check is too heavy (would read 500MB+ each tick) and caused status timeouts
|
|
278
|
-
if (!fs.existsSync(lkgRoot))
|
|
279
|
-
return false;
|
|
280
|
-
const entries = fs.readdirSync(lkgRoot).filter((n) => {
|
|
281
|
-
try {
|
|
282
|
-
return fs.statSync(path.join(lkgRoot, n)).isDirectory();
|
|
283
|
-
}
|
|
284
|
-
catch {
|
|
285
|
-
return false;
|
|
286
|
-
}
|
|
287
|
-
}).sort();
|
|
288
|
-
if (!entries.length)
|
|
289
|
-
return false;
|
|
290
|
-
const latestName = entries[entries.length - 1];
|
|
291
|
-
try {
|
|
292
|
-
const tsStr = latestName.replace(/^(\d{4})-(\d{2})-(\d{2})T(\d{2})-(\d{2})-(\d{2})-(\d+)Z$/, '$1-$2-$3T$4:$5:$6.$7Z');
|
|
293
|
-
const ts = Date.parse(tsStr);
|
|
294
|
-
if (!isNaN(ts) && Date.now() - ts < 5 * 60 * 1000) {
|
|
295
|
-
// If latest is recent and DSH home hasn't changed in mtime, consider duplicate
|
|
296
|
-
// Quick check: compare latest snapshot's mtime vs DSH home's newest file mtime
|
|
297
|
-
const latestPath = path.join(lkgRoot, latestName);
|
|
298
|
-
const latestMtime = fs.statSync(latestPath).mtimeMs;
|
|
299
|
-
let newestFileMtime = 0;
|
|
300
|
-
if (fs.existsSync(dshHome)) {
|
|
301
|
-
for (const entry of fs.readdirSync(dshHome)) {
|
|
302
|
-
// Same scope as the copy loop: runtime data changes constantly and
|
|
303
|
-
// must not defeat the dedupe for the configuration being snapshotted.
|
|
304
|
-
if (isLkgExcluded(entry))
|
|
305
|
-
continue;
|
|
306
|
-
try {
|
|
307
|
-
const s = fs.statSync(path.join(dshHome, entry));
|
|
308
|
-
if (s.mtimeMs > newestFileMtime)
|
|
309
|
-
newestFileMtime = s.mtimeMs;
|
|
310
|
-
}
|
|
311
|
-
catch { }
|
|
312
|
-
}
|
|
313
|
-
}
|
|
314
|
-
if (newestFileMtime > 0 && newestFileMtime < latestMtime)
|
|
315
|
-
return true;
|
|
316
|
-
}
|
|
317
|
-
}
|
|
318
|
-
catch { }
|
|
319
|
-
return false;
|
|
320
|
-
}
|
|
321
|
-
export async function verifyLKG(lkgPath) {
|
|
322
|
-
const manifestPath = path.join(lkgPath, 'manifest.json');
|
|
323
|
-
if (!fs.existsSync(manifestPath))
|
|
324
|
-
return false;
|
|
325
|
-
try {
|
|
326
|
-
const manifest = JSON.parse(fs.readFileSync(manifestPath, 'utf-8'));
|
|
327
|
-
for (const entry of manifest.files) {
|
|
328
|
-
const filePath = path.join(lkgPath, entry.path);
|
|
329
|
-
if (!fs.existsSync(filePath))
|
|
330
|
-
return false;
|
|
331
|
-
const hash = sha256File(filePath);
|
|
332
|
-
if (hash !== entry.sha256)
|
|
333
|
-
return false;
|
|
334
|
-
}
|
|
335
|
-
return true;
|
|
336
|
-
}
|
|
337
|
-
catch {
|
|
338
|
-
return false;
|
|
339
|
-
}
|
|
340
|
-
}
|
|
341
|
-
export async function rotateLKG(lkgRoot, keep = 3) {
|
|
342
|
-
if (!fs.existsSync(lkgRoot))
|
|
343
|
-
return;
|
|
344
|
-
const entries = fs.readdirSync(lkgRoot).filter((n) => {
|
|
345
|
-
try {
|
|
346
|
-
return fs.statSync(path.join(lkgRoot, n)).isDirectory();
|
|
347
|
-
}
|
|
348
|
-
catch {
|
|
349
|
-
return false;
|
|
350
|
-
}
|
|
351
|
-
}).sort();
|
|
352
|
-
const toDelete = entries.slice(0, Math.max(0, entries.length - keep));
|
|
353
|
-
for (const name of toDelete) {
|
|
354
|
-
fs.rmSync(path.join(lkgRoot, name), { recursive: true, force: true });
|
|
355
|
-
}
|
|
356
|
-
}
|
|
357
|
-
export async function writeFailed(dshHome, failedRoot) {
|
|
358
|
-
return writeLKG(dshHome, failedRoot);
|
|
359
|
-
}
|
package/src/host/snapshot.ts
DELETED
|
@@ -1,338 +0,0 @@
|
|
|
1
|
-
import * as fs from 'node:fs'
|
|
2
|
-
import * as path from 'node:path'
|
|
3
|
-
import * as crypto from 'node:crypto'
|
|
4
|
-
|
|
5
|
-
interface ManifestEntry { path: string; sha256: string }
|
|
6
|
-
interface Manifest { ts: string; files: ManifestEntry[] }
|
|
7
|
-
|
|
8
|
-
export interface SnapshotResult {
|
|
9
|
-
ts: string
|
|
10
|
-
/** Files (and symlinks) copied into this snapshot. */
|
|
11
|
-
files: number
|
|
12
|
-
/** Entries that could not be copied; the snapshot stays usable either way. */
|
|
13
|
-
skipped: Array<{ path: string; reason: string }>
|
|
14
|
-
}
|
|
15
|
-
|
|
16
|
-
export interface SnapshotDeps {
|
|
17
|
-
/**
|
|
18
|
-
* Copy one regular file, preserving `mode`. Injectable so a failing entry
|
|
19
|
-
* (the EACCES a read-only attachment object produces) can be table-tested
|
|
20
|
-
* without depending on the host's uid or filesystem quirks.
|
|
21
|
-
*/
|
|
22
|
-
copyFile?: (src: string, dest: string, mode: number) => void
|
|
23
|
-
}
|
|
24
|
-
|
|
25
|
-
/**
|
|
26
|
-
* Entries under the harness home directory that the last-known-good snapshot
|
|
27
|
-
* deliberately never copies.
|
|
28
|
-
*
|
|
29
|
-
* The LKG exists to recover a boot that fails while loading the plugin tree, so
|
|
30
|
-
* it holds boot **configuration**: `profiles/` (the plugin tree with its
|
|
31
|
-
* lockfile, `cordis.patch.yml` and sidecars), the per-plugin config directories
|
|
32
|
-
* and the settings documents. Everything below is runtime **data** — it is
|
|
33
|
-
* written continuously while `dsh web` runs, so restoring a snapshot of it can
|
|
34
|
-
* only lose newer state, and some of it is hostile to a bulk copy:
|
|
35
|
-
*
|
|
36
|
-
* - `sessions/` — append-only transcripts. Restoring a stale copy over live
|
|
37
|
-
* sessions drops every turn recorded after the snapshot, i.e. the recovery
|
|
38
|
-
* path would lose the log it is supposed to protect.
|
|
39
|
-
* - `attachments/` — content-addressed blobs stored mode `0400`. That read-only
|
|
40
|
-
* bit is exactly what made the 2026-09-13 rollback abort with
|
|
41
|
-
* `EACCES: Permission denied '.../attachments/v1/objects/f8'`.
|
|
42
|
-
* - `plugins-src/` — plugin source cache, re-fetched on demand (~400 MB host).
|
|
43
|
-
* - `.supervisor/` — the LKG root itself lives inside the DSH home, so copying
|
|
44
|
-
* it would recurse into every retained snapshot.
|
|
45
|
-
*
|
|
46
|
-
* This list is data, not a heuristic: the copy loop and the restore loop both
|
|
47
|
-
* consult `isLkgExcluded()`, and the table test pins the rule.
|
|
48
|
-
*/
|
|
49
|
-
export const LKG_EXCLUDED_ENTRIES: readonly string[] = [
|
|
50
|
-
'sessions',
|
|
51
|
-
'attachments',
|
|
52
|
-
'plugins-src',
|
|
53
|
-
'.supervisor',
|
|
54
|
-
]
|
|
55
|
-
|
|
56
|
-
/**
|
|
57
|
-
* True when a path relative to the harness home must never enter (or leave) the LKG.
|
|
58
|
-
*
|
|
59
|
-
* The named entries match the first path segment; `*.log` matches by basename
|
|
60
|
-
* anywhere, because append-only logs are data at any depth and a restored stale
|
|
61
|
-
* `dsh-web.log` would poison the boot-boundary scan.
|
|
62
|
-
*/
|
|
63
|
-
export function isLkgExcluded(relPath: string): boolean {
|
|
64
|
-
const normalized = relPath.replace(/\\/g, '/').replace(/^\.\//, '').replace(/^\/+/, '')
|
|
65
|
-
const segments = normalized.split('/').filter(s => s.length > 0 && s !== '.')
|
|
66
|
-
if (!segments.length) return false
|
|
67
|
-
if (LKG_EXCLUDED_ENTRIES.includes(segments[0]!)) return true
|
|
68
|
-
return segments[segments.length - 1]!.endsWith('.log')
|
|
69
|
-
}
|
|
70
|
-
|
|
71
|
-
function sha256File(filePath: string): string {
|
|
72
|
-
const data = fs.readFileSync(filePath)
|
|
73
|
-
return crypto.createHash('sha256').update(data).digest('hex')
|
|
74
|
-
}
|
|
75
|
-
|
|
76
|
-
function walkFiles(dir: string, base: string = dir): string[] {
|
|
77
|
-
const out: string[] = []
|
|
78
|
-
for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
|
|
79
|
-
const full = path.join(dir, entry.name)
|
|
80
|
-
if (entry.isDirectory()) out.push(...walkFiles(full, base))
|
|
81
|
-
else if (entry.isFile()) out.push(path.relative(base, full))
|
|
82
|
-
}
|
|
83
|
-
return out
|
|
84
|
-
}
|
|
85
|
-
|
|
86
|
-
/** Human-readable, bounded reason for a per-entry copy failure. */
|
|
87
|
-
export function failureReason(e: unknown): string {
|
|
88
|
-
const err = e as any
|
|
89
|
-
const code = typeof err?.code === 'string' && err.code ? `${err.code}: ` : ''
|
|
90
|
-
const message = typeof err?.message === 'string' ? err.message : String(e)
|
|
91
|
-
return `${code}${message}`.slice(0, 300)
|
|
92
|
-
}
|
|
93
|
-
|
|
94
|
-
interface CopyState {
|
|
95
|
-
dshHome: string
|
|
96
|
-
copyFile: (src: string, dest: string, mode: number) => void
|
|
97
|
-
copied: number
|
|
98
|
-
skipped: Array<{ path: string; reason: string }>
|
|
99
|
-
}
|
|
100
|
-
|
|
101
|
-
/**
|
|
102
|
-
* Copy one snapshot entry, collecting — never throwing — per-entry failures
|
|
103
|
-
* (D2). `fs.cpSync` aborts the whole snapshot on the first unreadable object,
|
|
104
|
-
* which is precisely how one 0400 attachment file stopped the rollback that
|
|
105
|
-
* exists to rescue a broken boot.
|
|
106
|
-
*/
|
|
107
|
-
function copyEntry(state: CopyState, src: string, dest: string, rel: string): void {
|
|
108
|
-
if (isLkgExcluded(rel)) return
|
|
109
|
-
let st: fs.Stats
|
|
110
|
-
try {
|
|
111
|
-
st = fs.lstatSync(src)
|
|
112
|
-
} catch (e) {
|
|
113
|
-
state.skipped.push({ path: rel, reason: failureReason(e) })
|
|
114
|
-
return
|
|
115
|
-
}
|
|
116
|
-
if (st.isDirectory()) {
|
|
117
|
-
let names: string[]
|
|
118
|
-
try {
|
|
119
|
-
// Directory modes are replicated only in their permission-to-traverse
|
|
120
|
-
// sense: the snapshot itself must stay readable/removable even when the
|
|
121
|
-
// source directory is not (a 0000 source dir must not produce a snapshot
|
|
122
|
-
// that nothing — including retention — can delete).
|
|
123
|
-
fs.mkdirSync(dest, { recursive: true, mode: (st.mode & 0o7777) | 0o700 })
|
|
124
|
-
names = fs.readdirSync(src)
|
|
125
|
-
} catch (e) {
|
|
126
|
-
state.skipped.push({ path: rel, reason: failureReason(e) })
|
|
127
|
-
return
|
|
128
|
-
}
|
|
129
|
-
for (const name of names) {
|
|
130
|
-
copyEntry(state, path.join(src, name), path.join(dest, name), rel ? `${rel}/${name}` : name)
|
|
131
|
-
}
|
|
132
|
-
return
|
|
133
|
-
}
|
|
134
|
-
if (st.isSymbolicLink()) {
|
|
135
|
-
try {
|
|
136
|
-
const link = fs.readlinkSync(src)
|
|
137
|
-
fs.mkdirSync(path.dirname(dest), { recursive: true })
|
|
138
|
-
try { fs.unlinkSync(dest) } catch {}
|
|
139
|
-
fs.symlinkSync(link, dest)
|
|
140
|
-
state.copied++
|
|
141
|
-
} catch (e) {
|
|
142
|
-
state.skipped.push({ path: rel, reason: failureReason(e) })
|
|
143
|
-
}
|
|
144
|
-
return
|
|
145
|
-
}
|
|
146
|
-
if (st.isFile()) {
|
|
147
|
-
try {
|
|
148
|
-
fs.mkdirSync(path.dirname(dest), { recursive: true })
|
|
149
|
-
state.copyFile(src, dest, st.mode & 0o7777)
|
|
150
|
-
state.copied++
|
|
151
|
-
} catch (e) {
|
|
152
|
-
state.skipped.push({ path: rel, reason: failureReason(e) })
|
|
153
|
-
}
|
|
154
|
-
}
|
|
155
|
-
// Sockets/FIFOs/devices are not boot configuration: ignored on purpose.
|
|
156
|
-
}
|
|
157
|
-
|
|
158
|
-
export async function writeLKG(dshHome: string, lkgRoot: string, deps: SnapshotDeps = {}): Promise<SnapshotResult> {
|
|
159
|
-
// Dedupe: skip snapshot if current state identical to latest LKG (prevents 5-min unconditional growth)
|
|
160
|
-
try {
|
|
161
|
-
if (await isDuplicateLKG(dshHome, lkgRoot)) {
|
|
162
|
-
const entries = fs.readdirSync(lkgRoot).filter((n: string) => {
|
|
163
|
-
try { return fs.statSync(path.join(lkgRoot, n)).isDirectory() } catch { return false }
|
|
164
|
-
}).sort()
|
|
165
|
-
const latest = entries[entries.length - 1]
|
|
166
|
-
const manifestPath = path.join(lkgRoot, latest, 'manifest.json')
|
|
167
|
-
const manifest: Manifest = JSON.parse(fs.readFileSync(manifestPath, 'utf-8'))
|
|
168
|
-
return { ts: latest, files: manifest.files?.length ?? 0, skipped: [] }
|
|
169
|
-
}
|
|
170
|
-
} catch {}
|
|
171
|
-
|
|
172
|
-
const ts = new Date().toISOString().replace(/[:.]/g, '-')
|
|
173
|
-
const dest = path.join(lkgRoot, ts)
|
|
174
|
-
try {
|
|
175
|
-
fs.mkdirSync(dest, { recursive: true })
|
|
176
|
-
} catch (e) {
|
|
177
|
-
// No snapshot is better than an exception thrown into the rollback path.
|
|
178
|
-
return { ts, files: 0, skipped: [{ path: lkgRoot, reason: failureReason(e) }] }
|
|
179
|
-
}
|
|
180
|
-
|
|
181
|
-
const state: CopyState = {
|
|
182
|
-
dshHome,
|
|
183
|
-
copyFile: deps.copyFile ?? ((src, dst, mode) => {
|
|
184
|
-
fs.copyFileSync(src, dst)
|
|
185
|
-
try { fs.chmodSync(dst, mode) } catch {}
|
|
186
|
-
}),
|
|
187
|
-
copied: 0,
|
|
188
|
-
skipped: [],
|
|
189
|
-
}
|
|
190
|
-
|
|
191
|
-
// Copy only the boot configuration (D1), one entry at a time so a single
|
|
192
|
-
// unreadable file is recorded and skipped instead of aborting the snapshot (D2).
|
|
193
|
-
let topLevel: string[] = []
|
|
194
|
-
try {
|
|
195
|
-
if (fs.existsSync(dshHome)) topLevel = fs.readdirSync(dshHome)
|
|
196
|
-
} catch (e) {
|
|
197
|
-
state.skipped.push({ path: '.', reason: failureReason(e) })
|
|
198
|
-
}
|
|
199
|
-
for (const entry of topLevel) {
|
|
200
|
-
copyEntry(state, path.join(dshHome, entry), path.join(dest, entry), entry)
|
|
201
|
-
}
|
|
202
|
-
|
|
203
|
-
let fileList: string[] = []
|
|
204
|
-
try {
|
|
205
|
-
fileList = fs.existsSync(dest) ? walkFiles(dest) : []
|
|
206
|
-
} catch (e) {
|
|
207
|
-
state.skipped.push({ path: 'manifest', reason: failureReason(e) })
|
|
208
|
-
}
|
|
209
|
-
const manifest: Manifest = {
|
|
210
|
-
ts,
|
|
211
|
-
files: fileList
|
|
212
|
-
.filter(f => f !== 'manifest.json')
|
|
213
|
-
.map(f => ({ path: f, sha256: sha256File(path.join(dest, f)) })),
|
|
214
|
-
}
|
|
215
|
-
try {
|
|
216
|
-
fs.writeFileSync(path.join(dest, 'manifest.json'), JSON.stringify(manifest, null, 2))
|
|
217
|
-
} catch (e) {
|
|
218
|
-
state.skipped.push({ path: 'manifest.json', reason: failureReason(e) })
|
|
219
|
-
}
|
|
220
|
-
|
|
221
|
-
// Retention: keep only 3 most recent, plus age (7d) and size (5GB) caps — prevents unbounded 40GB+ growth
|
|
222
|
-
await rotateLKG(lkgRoot, 3).catch(() => {})
|
|
223
|
-
await pruneByAge(lkgRoot, 7 * 24 * 60 * 60 * 1000).catch(() => {})
|
|
224
|
-
await pruneBySize(lkgRoot, 5 * 1024 * 1024 * 1024).catch(() => {})
|
|
225
|
-
|
|
226
|
-
return { ts, files: state.copied, skipped: state.skipped }
|
|
227
|
-
}
|
|
228
|
-
|
|
229
|
-
export async function pruneByAge(root: string, maxAgeMs: number): Promise<void> {
|
|
230
|
-
if (!fs.existsSync(root)) return
|
|
231
|
-
const now = Date.now()
|
|
232
|
-
const entries = fs.readdirSync(root).filter((n: string) => {
|
|
233
|
-
try { return fs.statSync(path.join(root, n)).isDirectory() } catch { return false }
|
|
234
|
-
})
|
|
235
|
-
for (const name of entries) {
|
|
236
|
-
try {
|
|
237
|
-
const tsStr = name.replace(/^(\d{4})-(\d{2})-(\d{2})T(\d{2})-(\d{2})-(\d{2})-(\d+)Z$/, '$1-$2-$3T$4:$5:$6.$7Z')
|
|
238
|
-
const ts = Date.parse(tsStr)
|
|
239
|
-
if (!isNaN(ts) && now - ts > maxAgeMs) {
|
|
240
|
-
fs.rmSync(path.join(root, name), { recursive: true, force: true })
|
|
241
|
-
}
|
|
242
|
-
} catch {}
|
|
243
|
-
}
|
|
244
|
-
}
|
|
245
|
-
|
|
246
|
-
export async function pruneBySize(root: string, maxBytes: number): Promise<void> {
|
|
247
|
-
if (!fs.existsSync(root)) return
|
|
248
|
-
const entries = fs.readdirSync(root).filter((n: string) => {
|
|
249
|
-
try { return fs.statSync(path.join(root, n)).isDirectory() } catch { return false }
|
|
250
|
-
}).sort()
|
|
251
|
-
let total = 0
|
|
252
|
-
const sizes: Array<{ name: string; size: number }> = []
|
|
253
|
-
for (const name of entries) {
|
|
254
|
-
try {
|
|
255
|
-
const p = path.join(root, name)
|
|
256
|
-
let size = 0
|
|
257
|
-
for (const f of walkFiles(p)) {
|
|
258
|
-
try { size += fs.statSync(path.join(p, f)).size } catch {}
|
|
259
|
-
}
|
|
260
|
-
sizes.push({ name, size })
|
|
261
|
-
total += size
|
|
262
|
-
} catch {}
|
|
263
|
-
}
|
|
264
|
-
for (const { name, size } of sizes) {
|
|
265
|
-
if (total <= maxBytes) break
|
|
266
|
-
try {
|
|
267
|
-
fs.rmSync(path.join(root, name), { recursive: true, force: true })
|
|
268
|
-
total -= size
|
|
269
|
-
} catch {}
|
|
270
|
-
}
|
|
271
|
-
}
|
|
272
|
-
|
|
273
|
-
export async function isDuplicateLKG(dshHome: string, lkgRoot: string): Promise<boolean> {
|
|
274
|
-
// Lightweight dedupe: if latest snapshot is <5 minutes old, skip (prevents 5-min unconditional growth)
|
|
275
|
-
// Full hash check is too heavy (would read 500MB+ each tick) and caused status timeouts
|
|
276
|
-
if (!fs.existsSync(lkgRoot)) return false
|
|
277
|
-
const entries = fs.readdirSync(lkgRoot).filter((n: string) => {
|
|
278
|
-
try { return fs.statSync(path.join(lkgRoot, n)).isDirectory() } catch { return false }
|
|
279
|
-
}).sort()
|
|
280
|
-
if (!entries.length) return false
|
|
281
|
-
const latestName = entries[entries.length - 1]
|
|
282
|
-
try {
|
|
283
|
-
const tsStr = latestName.replace(/^(\d{4})-(\d{2})-(\d{2})T(\d{2})-(\d{2})-(\d{2})-(\d+)Z$/, '$1-$2-$3T$4:$5:$6.$7Z')
|
|
284
|
-
const ts = Date.parse(tsStr)
|
|
285
|
-
if (!isNaN(ts) && Date.now() - ts < 5 * 60 * 1000) {
|
|
286
|
-
// If latest is recent and DSH home hasn't changed in mtime, consider duplicate
|
|
287
|
-
// Quick check: compare latest snapshot's mtime vs DSH home's newest file mtime
|
|
288
|
-
const latestPath = path.join(lkgRoot, latestName)
|
|
289
|
-
const latestMtime = fs.statSync(latestPath).mtimeMs
|
|
290
|
-
let newestFileMtime = 0
|
|
291
|
-
if (fs.existsSync(dshHome)) {
|
|
292
|
-
for (const entry of fs.readdirSync(dshHome)) {
|
|
293
|
-
// Same scope as the copy loop: runtime data changes constantly and
|
|
294
|
-
// must not defeat the dedupe for the configuration being snapshotted.
|
|
295
|
-
if (isLkgExcluded(entry)) continue
|
|
296
|
-
try {
|
|
297
|
-
const s = fs.statSync(path.join(dshHome, entry))
|
|
298
|
-
if (s.mtimeMs > newestFileMtime) newestFileMtime = s.mtimeMs
|
|
299
|
-
} catch {}
|
|
300
|
-
}
|
|
301
|
-
}
|
|
302
|
-
if (newestFileMtime > 0 && newestFileMtime < latestMtime) return true
|
|
303
|
-
}
|
|
304
|
-
} catch {}
|
|
305
|
-
return false
|
|
306
|
-
}
|
|
307
|
-
|
|
308
|
-
export async function verifyLKG(lkgPath: string): Promise<boolean> {
|
|
309
|
-
const manifestPath = path.join(lkgPath, 'manifest.json')
|
|
310
|
-
if (!fs.existsSync(manifestPath)) return false
|
|
311
|
-
try {
|
|
312
|
-
const manifest: Manifest = JSON.parse(fs.readFileSync(manifestPath, 'utf-8'))
|
|
313
|
-
for (const entry of manifest.files) {
|
|
314
|
-
const filePath = path.join(lkgPath, entry.path)
|
|
315
|
-
if (!fs.existsSync(filePath)) return false
|
|
316
|
-
const hash = sha256File(filePath)
|
|
317
|
-
if (hash !== entry.sha256) return false
|
|
318
|
-
}
|
|
319
|
-
return true
|
|
320
|
-
} catch {
|
|
321
|
-
return false
|
|
322
|
-
}
|
|
323
|
-
}
|
|
324
|
-
|
|
325
|
-
export async function rotateLKG(lkgRoot: string, keep = 3): Promise<void> {
|
|
326
|
-
if (!fs.existsSync(lkgRoot)) return
|
|
327
|
-
const entries = fs.readdirSync(lkgRoot).filter((n: string) => {
|
|
328
|
-
try { return fs.statSync(path.join(lkgRoot, n)).isDirectory() } catch { return false }
|
|
329
|
-
}).sort()
|
|
330
|
-
const toDelete = entries.slice(0, Math.max(0, entries.length - keep))
|
|
331
|
-
for (const name of toDelete) {
|
|
332
|
-
fs.rmSync(path.join(lkgRoot, name), { recursive: true, force: true })
|
|
333
|
-
}
|
|
334
|
-
}
|
|
335
|
-
|
|
336
|
-
export async function writeFailed(dshHome: string, failedRoot: string): Promise<SnapshotResult> {
|
|
337
|
-
return writeLKG(dshHome, failedRoot)
|
|
338
|
-
}
|