barebox 0.1.0 → 0.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/src/overlay.js ADDED
@@ -0,0 +1,1012 @@
1
+ // overlay.js — M4 undo layer: per-run tracing paper over the real project.
2
+ // Writes land in a per-run upper (lower = project read-only); commit presses
3
+ // the merged view down, rollback drops the upper. Diff/commit walk the merged
4
+ // view with node inside the mount (`overlay-walk.js`): the one
5
+ // walker reads project, upper and merged view alike — no shell here. Commit
6
+ // stages into a bound folder, then swaps by journaled rename (aside, rmdir,
7
+ // mkdir writable, move in, chmod last); failure undoes in reverse, reporting
8
+ // "nothing was applied" or the exact steps not undone (commit folder kept).
9
+ // Rollback reports diff's answer, or raw upper paths when the project is
10
+ // gone. Conflict rule (pinned): `(lower != base) && (merged != lower)`;
11
+ // Q3 ignores + `.sbx-commit-` are invisible to the whole layer.
12
+ import { spawnSync } from 'node:child_process';
13
+ import { createHash, randomBytes } from 'node:crypto';
14
+ import {
15
+ existsSync, mkdirSync, readdirSync, lstatSync, statSync, accessSync, constants,
16
+ readFileSync, writeFileSync, rmSync, rmdirSync, chmodSync,
17
+ readlinkSync, renameSync, realpathSync,
18
+ } from 'node:fs';
19
+ import { join, dirname } from 'node:path';
20
+ import { fileURLToPath } from 'node:url';
21
+ import { assertAgentName, runtimeTempDir, runtimePaths, safe } from './runtime.js';
22
+
23
+ /** One reviewed file change: what the sandbox did at `path`, and whether the project changed underneath it mid-run.
24
+ *
25
+ * @typedef {object} OverlayChange
26
+ * @property {string} path project-relative path with `/` separators
27
+ * @property {string} status `added` | `modified` | `deleted` (`unknown`: rollback's raw fallback, which infers nothing)
28
+ * @property {boolean} conflict true when the project changed this path after the run started
29
+ * @property {string|null} reason why `conflict` is set, or null when clean
30
+ * @property {string} [type] merged-view kind: `f` file, `d` dir, `l` symlink (set unless deleted)
31
+ * @property {number} [mode] merged-view permission bits (set unless deleted)
32
+ * @property {string} [hash] sha256 of a merged-view regular file
33
+ * @property {string} [target] symlink target of a merged-view symlink
34
+ */
35
+
36
+ const MANIFEST_VERSION = 1;
37
+
38
+ const OVERLAY_MIN_BWRAP = [0, 11, 0];
39
+
40
+ /**
41
+ * Judge `bwrap --version` output for overlay support: `--overlay-src` / `--overlay` exist from bubblewrap 0.11.0.
42
+ *
43
+ * @param {string} versionOutput text printed by `bwrap --version` (for example `bubblewrap 0.12.0`)
44
+ * @returns {Error|null} null when the version is at least 0.11.0, otherwise the refusal to throw (unparseable output counts as `unknown`)
45
+ * @fails Never throws; returns the error instead.
46
+ */
47
+ export function overlaySupportError(versionOutput) {
48
+ const m = /bubblewrap\s+(\d+)\.(\d+)(?:\.(\d+))?/.exec(String(versionOutput));
49
+ if (m) {
50
+ const v = [Number(m[1]), Number(m[2]), Number(m[3] ?? 0)];
51
+ const ok = v[0] !== OVERLAY_MIN_BWRAP[0] ? v[0] > OVERLAY_MIN_BWRAP[0]
52
+ : v[1] !== OVERLAY_MIN_BWRAP[1] ? v[1] > OVERLAY_MIN_BWRAP[1]
53
+ : v[2] >= OVERLAY_MIN_BWRAP[2];
54
+ if (ok) return null;
55
+ }
56
+ return new Error(`the overlay needs bubblewrap >= 0.11.0 (found ${m ? m.slice(1).filter((x) => x !== undefined).join('.') : 'unknown'}): upgrade bubblewrap, or run without --overlay`);
57
+ }
58
+
59
+ /** @type {Error|null|undefined} */
60
+ let overlaySupport;
61
+
62
+ /**
63
+ * Refuse the overlay on a bubblewrap older than 0.11.0. Runs `bwrap --version` once per process.
64
+ *
65
+ * @returns {void}
66
+ * @fails Throws `the overlay needs bubblewrap >= 0.11.0 (found X)` when bwrap is older or its version is unreadable. A missing bwrap does not throw here: the real bwrap call then fails as it always did.
67
+ */
68
+ export function assertOverlaySupport() {
69
+ if (overlaySupport === undefined) {
70
+ const res = spawnSync('bwrap', ['--version'], { encoding: 'utf8' });
71
+ // Missing bwrap (ENOENT): no new message; the caller's own bwrap spawn fails as before.
72
+ overlaySupport = res.error ? null : overlaySupportError(res.stdout);
73
+ }
74
+ if (overlaySupport) throw overlaySupport;
75
+ }
76
+
77
+ /** Path segments invisible to the layer (Q3): never snapshotted, diffed, committed or deleted. */
78
+ export const DEFAULT_IGNORE = ['node_modules'];
79
+
80
+ /** First-segment prefix of one commit's staging folder: never walked; a leftover blocks the next operation. */
81
+ const COMMIT_PREFIX = '.sbx-commit-';
82
+
83
+ /** Refused commit: paths changed in the project mid-run. A conflict refusal is a phase-1 failure: nothing was applied — resolve and retry. */
84
+ export class OverlayConflictError extends Error {
85
+ /** @param {{path: string, status: string, reason: string|null}[]} conflicts conflicting changes */
86
+ constructor(conflicts) {
87
+ super(`sbx commit refused: ${conflicts.length} file(s) changed in the project ` +
88
+ `during the run: ${conflicts.map((c) => c.path).join(', ')} (nothing was applied)`);
89
+ this.code = 'SBX_CONFLICT';
90
+ /** @type {{path: string, status: string, reason: string|null}[]} */
91
+ this.conflicts = conflicts;
92
+ }
93
+ }
94
+
95
+ /** True when any `/`-separated segment of `rel` is ignored. */
96
+ function isIgnored(rel, ignore) {
97
+ return rel.split('/').some((seg) => ignore.has(seg));
98
+ }
99
+
100
+ /** True when `rel` is inside one commit's staging folder (invisible, like ignored segments). */
101
+ function isCommitDir(rel) {
102
+ const top = rel.includes('/') ? rel.slice(0, rel.indexOf('/')) : rel;
103
+ return top.startsWith(COMMIT_PREFIX);
104
+ }
105
+
106
+ /** Fingerprint: type + content (hash/target) + mode. Equal iff the visible file is identical. */
107
+ function fpOf(e) {
108
+ if (!e) return null;
109
+ return `${e.type}:${e.hash ?? e.target ?? ''}:${e.mode.toString(8)}`;
110
+ }
111
+
112
+ /**
113
+ * Build one manifest entry: the single definition of the fingerprint
114
+ * (type + content + mode), shared by the walker and by live re-checks.
115
+ *
116
+ * @param {string} abs absolute path to read
117
+ * @param {import('node:fs').Stats} st `lstat` of `abs`
118
+ * @param {boolean} [full] read content (hash file bytes, read link targets); false records type + mode only, for paths whose entry the host fills from elsewhere
119
+ * @returns {{ type: string, mode: number, hash?: string, target?: string }} the entry
120
+ */
121
+ function entryOf(abs, st, full = true) {
122
+ const type = kindOf(st);
123
+ if (type === 'f') {
124
+ return full
125
+ ? {
126
+ type, mode: st.mode & 0o7777,
127
+ hash: createHash('sha256').update(readFileSync(abs)).digest('hex'),
128
+ }
129
+ : { type, mode: st.mode & 0o7777 };
130
+ }
131
+ if (type === 'l') {
132
+ return full
133
+ ? { type, mode: st.mode & 0o7777, target: readlinkSync(abs) }
134
+ : { type, mode: st.mode & 0o7777 };
135
+ }
136
+ return { type, mode: st.mode & 0o7777 };
137
+ }
138
+
139
+ function kindOf(st) {
140
+ if (st.isFile()) return 'f';
141
+ if (st.isDirectory()) return 'd';
142
+ if (st.isSymbolicLink()) return 'l';
143
+ if (st.isFIFO()) return 'p';
144
+ if (st.isSocket()) return 's';
145
+ if (st.isCharacterDevice()) return 'c';
146
+ if (st.isBlockDevice()) return 'b';
147
+ return '?';
148
+ }
149
+
150
+ /** True for permission errors: the entry exists but cannot be read. */
151
+ function isPermErr(e) {
152
+ const code = /** @type {NodeJS.ErrnoException} */ (e).code;
153
+ return code === 'EACCES' || code === 'EPERM';
154
+ }
155
+
156
+ /**
157
+ * Refuse an unreadable entry loudly: name the path (sanitized — it may be
158
+ * agent-chosen) and say how to proceed. Never `chmod` to make it readable:
159
+ * that would change the modes a commit applies.
160
+ *
161
+ * @param {string} root directory being walked
162
+ * @param {string} rel project-relative path of the unreadable entry
163
+ * @param {unknown} cause the filesystem error
164
+ * @returns {never} always throws
165
+ */
166
+ function refuseUnreadable(root, rel, cause) {
167
+ const code = cause instanceof Error && /** @type {NodeJS.ErrnoException} */ (cause).code
168
+ ? /** @type {NodeJS.ErrnoException} */ (cause).code
169
+ : 'error';
170
+ throw new Error(`sbx: cannot read ${safe(rel)} in ${root} (${code}; ` +
171
+ `fix its permissions or run 'sbx rollback' to discard the run)`);
172
+ }
173
+
174
+ /** The one walker: project, upper, merged view. Skips ignored/commit dirs (never descended); strict UTF-8 names (non-UTF-8 refused loudly); unreadable entries are refused loudly (never chmodded readable).
175
+ *
176
+ * @param {string} root directory to walk
177
+ * @param {Set<string>} ignore path segments invisible to the layer
178
+ * @param {Set<string>|null} [hashOnly] when set, only these relative paths get full entries (hashes, link targets); every other path is still `lstat`ed but records type + mode only
179
+ * @returns {Map<string, {type: string, mode: number, hash?: string, target?: string}>}
180
+ */
181
+ export function walkLocal(root, ignore, hashOnly = null) {
182
+ /** @type {Map<string, {type: string, mode: number, hash?: string, target?: string}>} */
183
+ const out = new Map();
184
+ const utf8 = new TextDecoder('utf-8', { fatal: true });
185
+ const stack = [''];
186
+ while (stack.length) {
187
+ const dir = /** @type {string} */ (stack.pop());
188
+ /** @type {Buffer[]} */
189
+ let names;
190
+ try {
191
+ names = /** @type {Buffer[]} */ (/** @type {unknown} */ (readdirSync(join(root, dir), { encoding: 'buffer' })));
192
+ } catch (e) {
193
+ if (isPermErr(e)) refuseUnreadable(root, dir || '.', e);
194
+ throw e;
195
+ }
196
+ for (const raw of names) {
197
+ let name;
198
+ try {
199
+ name = utf8.decode(raw);
200
+ } catch {
201
+ throw new Error(`sbx: refusing non-UTF-8 filename in ${join(root, dir)} ` +
202
+ `(bytes ${raw.toString('hex')}; rename it and retry)`);
203
+ }
204
+ const rel = dir ? `${dir}/${name}` : name;
205
+ if (isIgnored(rel, ignore) || isCommitDir(rel)) continue;
206
+ let st;
207
+ try {
208
+ st = lstatSync(join(root, rel));
209
+ } catch (e) {
210
+ if (isPermErr(e)) refuseUnreadable(root, rel, e);
211
+ throw e;
212
+ }
213
+ if (kindOf(st) === 'd') {
214
+ out.set(rel, { type: 'd', mode: st.mode & 0o7777 });
215
+ stack.push(rel);
216
+ continue;
217
+ }
218
+ try {
219
+ out.set(rel, entryOf(join(root, rel), st, hashOnly === null || hashOnly.has(rel)));
220
+ } catch (e) {
221
+ if (isPermErr(e)) refuseUnreadable(root, rel, e);
222
+ throw e;
223
+ }
224
+ }
225
+ }
226
+ return out;
227
+ }
228
+
229
+ function conflictReason(status, inBase) {
230
+ if (status === 'modified') return 'changed in the project during the run';
231
+ if (status === 'added') return 'deleted in the project during the run';
232
+ return inBase
233
+ ? 'changed in the project during the run, deleted in the sandbox'
234
+ : 'created in the project during the run, deleted in the sandbox';
235
+ }
236
+
237
+ /** Union-compare base snapshot, project, and merged view into sorted changes; `merged == lower` is no change. */
238
+ function computeChanges(base, lower, merged) {
239
+ /** @type {OverlayChange[]} */
240
+ const changes = [];
241
+ const rels = new Set([...base.keys(), ...lower.keys(), ...merged.keys()]);
242
+ for (const rel of rels) {
243
+ const m = merged.get(rel);
244
+ const l = lower.get(rel);
245
+ if (fpOf(m) === fpOf(l)) continue;
246
+ const status = !m ? 'deleted' : !l ? 'added' : 'modified';
247
+ const conflict = fpOf(l) !== (base.get(rel) ?? null);
248
+ changes.push({
249
+ path: rel, status, conflict,
250
+ reason: conflict ? conflictReason(status, base.has(rel)) : null,
251
+ ...(m ? { type: m.type, mode: m.mode, hash: m.hash, target: m.target } : {}),
252
+ });
253
+ }
254
+ changes.sort((a, b) => (a.path < b.path ? -1 : a.path > b.path ? 1 : 0));
255
+ return changes;
256
+ }
257
+
258
+ // --- overlay record (upper + work + run-start snapshot) ---------------------
259
+
260
+ /** One commit's staging folder, or null. A leftover blocks diff/commit/setup until removed. */
261
+ function findCommitDir(proj) {
262
+ let names;
263
+ try {
264
+ names = readdirSync(proj);
265
+ } catch {
266
+ return null;
267
+ }
268
+ const hit = names.filter((n) => n.startsWith(COMMIT_PREFIX)).sort()[0];
269
+ return hit ? join(proj, hit) : null;
270
+ }
271
+
272
+ /** Refuse when a killed commit's folder is still in the project; names its path. */
273
+ function refuseLeftover(proj, op) {
274
+ const leftover = findCommitDir(proj);
275
+ if (leftover) {
276
+ throw new Error(`sbx: unfinished commit at ${leftover} blocks ${op} (a killed commit left it; remove it and retry)`);
277
+ }
278
+ }
279
+
280
+ /** True when the upper holds no visible entry: one shallow `readdir`, no recursion, no hashing. Any top-level name that is neither ignored nor a commit folder counts. Throws when the upper itself cannot be read, like the walk it replaces. */
281
+ function upperIsEmpty(upper, ignore) {
282
+ for (const name of readdirSync(upper)) {
283
+ if (isIgnored(name, ignore) || isCommitDir(name)) continue;
284
+ return false;
285
+ }
286
+ return true;
287
+ }
288
+
289
+ /**
290
+ * Make a tree listable and removable without changing what a report says:
291
+ * add owner read (files) or rwx (dirs), keeping every other bit, so a diff
292
+ * taken afterwards still reports the original modes on everything that was
293
+ * already readable. Never follows symlinks.
294
+ */
295
+ function chmodTree(p) {
296
+ const st = lstatSync(p);
297
+ if (st.isSymbolicLink()) return;
298
+ const want = (st.mode & 0o7777) | (st.isDirectory() ? 0o700 : 0o600);
299
+ if (want !== (st.mode & 0o7777)) chmodSync(p, want);
300
+ if (st.isDirectory()) {
301
+ for (const n of readdirSync(p)) chmodTree(join(p, n));
302
+ }
303
+ }
304
+
305
+ /** Empty a dir, tolerating mode-000 debris and whiteout orphans (chmod-then-rm, never following symlinks). */
306
+
307
+ function emptyDir(dir) {
308
+ mkdirSync(dir, { recursive: true });
309
+ for (const name of readdirSync(dir)) {
310
+ const p = join(dir, name);
311
+ try {
312
+ rmSync(p, { recursive: true, force: true });
313
+ } catch (e) {
314
+ if (/** @type {NodeJS.ErrnoException} */ (e).code === 'ENOENT') continue;
315
+ chmodTree(p);
316
+ rmSync(p, { recursive: true, force: true });
317
+ }
318
+ }
319
+ }
320
+
321
+ /** Read and validate the overlay record: missing reads as no-overlay, garbage as corrupt. */
322
+ function readRecord(manifest, runtime, agent) {
323
+ let text;
324
+ try {
325
+ text = readFileSync(manifest, 'utf8');
326
+ } catch {
327
+ throw noOverlayError(runtime, agent);
328
+ }
329
+ let m = null;
330
+ try {
331
+ m = JSON.parse(text);
332
+ } catch {
333
+ m = null;
334
+ }
335
+ if (!m || m.version !== MANIFEST_VERSION || typeof m.proj !== 'string' || typeof m.base !== 'object' || !m.base) {
336
+ throw new Error(`sbx: overlay record for agent '${agent}' is corrupt (${manifest}); remove it and retry`);
337
+ }
338
+ return m;
339
+ }
340
+
341
+ /** Prepare a fresh upper: refuse leftovers, snapshot the project as the conflict baseline. An empty upper re-snapshots. */
342
+ export function setupOverlay({ runtime, agent, proj, ignore = DEFAULT_IGNORE }) {
343
+ for (const [k, v] of Object.entries({ runtime, agent, proj })) {
344
+ if (typeof v !== 'string' || !v) throw new Error(`setupOverlay: ${k} must be a non-empty string`);
345
+ }
346
+ assertAgentName(agent);
347
+ const ign = new Set(ignore ?? DEFAULT_IGNORE);
348
+ statSync(proj); // missing project reports ENOENT here, leaving no overlay folders behind
349
+ const { base: basedir, upper, work, manifest } = runtimePaths(runtime).overlay(agent);
350
+ mkdirSync(upper, { recursive: true });
351
+ mkdirSync(work, { recursive: true });
352
+ for (const name of readdirSync(basedir)) {
353
+ if (name.startsWith('merged-')) rmSync(join(basedir, name), { recursive: true, force: true });
354
+ }
355
+ if (existsSync(manifest)) {
356
+ const prev = readRecord(manifest, runtime, agent);
357
+ if (prev.proj !== proj) {
358
+ throw new Error(`sbx: overlay for agent '${agent}' belongs to ${prev.proj}, not ${proj} (use a different agent or runtime)`);
359
+ }
360
+ }
361
+ if (!upperIsEmpty(upper, ign)) {
362
+ throw new Error(`sbx: agent '${agent}' has uncommitted overlay changes (review with 'sbx diff', then 'sbx commit' or 'sbx rollback')`);
363
+ }
364
+ refuseLeftover(proj, 'setup');
365
+ emptyDir(work); // kernel scratch: safe to drop, never user data
366
+ /** @type {Record<string, string|null>} */
367
+ const base = {};
368
+ for (const [rel, e] of walkLocal(proj, ign)) base[rel] = fpOf(e);
369
+ writeFileSync(manifest, JSON.stringify({
370
+ version: MANIFEST_VERSION, proj, ignore: [...ign], createdAt: new Date().toISOString(), base,
371
+ }));
372
+ return { upper, work };
373
+ }
374
+
375
+ function noOverlayError(runtime, agent) {
376
+ return Object.assign(
377
+ new Error(`sbx: no overlay for agent '${agent}' in ${runtime} ` +
378
+ `(no overlay record: no run with overlay here, or its changes were rolled back)`),
379
+ { code: 'SBX_NO_OVERLAY' });
380
+ }
381
+
382
+ function loadOverlay({ runtime, agent }) {
383
+ assertAgentName(agent);
384
+ const { base: scratch, upper, work, manifest } = runtimePaths(runtime).overlay(agent);
385
+ const m = readRecord(manifest, runtime, agent);
386
+ return {
387
+ scratch, upper, work, proj: /** @type {string} */ (m.proj),
388
+ ignore: new Set(/** @type {string[]} */ (m.ignore ?? [])),
389
+ base: new Map(Object.entries(/** @type {Record<string, string|null>} */ (m.base))),
390
+ };
391
+ }
392
+
393
+ // --- merged-view mount (the only reader of whiteouts/opaques) --------------
394
+
395
+ /** Run the walker inside one overlay mount; return its manifest. `src/` is bound read-only at its own path (same `walkLocal`, never shell); with `stageDir` (bound at `/sbx-new`) the walker also stages the listed files/symlinks. With `upperPaths` the walker hashes and stages only those relative paths and records the rest as type + mode stubs for the host to fill from the lower. The manifest and the path list travel as files in a folder bound read-write at `/sbx-out`: stdout carries no data, so there is no output cap, however many files the project holds. Scratch lives under the runtime dir, never /tmp.
396
+ *
397
+ * @param {object} opts
398
+ * @param {string} opts.lower project directory (overlay lower)
399
+ * @param {string} opts.upper overlay upper directory
400
+ * @param {string} opts.work overlay work directory
401
+ * @param {Set<string>} opts.ignore invisible path segments
402
+ * @param {string} opts.scratch scratch dir for mount points and walker output
403
+ * @param {string|null} [opts.stageDir] bound at `/sbx-new` for staging, or null
404
+ * @param {Set<string>|null} [opts.upperPaths] upper relative paths to hash and stage, or null for all
405
+ */
406
+ function bwrapWalk({ lower, upper, work, ignore, scratch, stageDir = null, upperPaths = null }) {
407
+ assertOverlaySupport();
408
+ mkdirSync(scratch, { recursive: true });
409
+ const merged = runtimeTempDir(scratch, 'merged');
410
+ const outDir = runtimeTempDir(scratch, 'walk');
411
+ const manifestFile = join(outDir, 'manifest.json');
412
+ if (upperPaths) writeFileSync(join(outDir, 'upper-paths.json'), JSON.stringify([...upperPaths]));
413
+ const srcDir = dirname(fileURLToPath(import.meta.url));
414
+ // The interpreter inside the mount is the node running barebox now —
415
+ // never a hardcoded path (nvm, volta and Linuxbrew keep node outside
416
+ // /usr). Its prefix is bound read-only when /usr does not already show it.
417
+ const node = realpathSync(process.execPath);
418
+ const underUsr = node === '/usr' || node.startsWith('/usr/');
419
+ const nodeParent = dirname(node);
420
+ const nodePrefix = nodeParent.endsWith('/bin') ? dirname(nodeParent) : nodeParent;
421
+ try {
422
+ // No output cap (stdout carries no data) and no time limit: the walk
423
+ // is finite (`lstat`, never following symlinks), and killing a commit's
424
+ // extraction halfway helps nobody.
425
+ // Mount order is the design, stated once here. bwrap applies mounts in
426
+ // argument order, so a later mount lands on top of an earlier one:
427
+ // a. host paths at their own paths, read-only — /usr (+ the /lib64
428
+ // symlink), srcDir, and nodePrefix when node isn't under /usr;
429
+ // b. then everything the walk creates — the overlay over <merged>,
430
+ // and the output folders.
431
+ // A host bind placed after the overlay would hide it whenever the
432
+ // prefix contains the runtime (nvm under $HOME, ~/bin/node) or the
433
+ // runtime sits under src/: the walker would see the bare mountpoint and
434
+ // read every file as deleted, and a commit would delete real files.
435
+ // Keep node's prefix at its own path: Linuxbrew's node carries an
436
+ // absolute interpreter and rpath under its prefix, and moving it to a
437
+ // fixed path like /sbx-node breaks loading. No prefix is refused: even
438
+ // `/` is correct, merely exposing the host read-only to our own walker.
439
+ const res = spawnSync('bwrap',
440
+ ['--die-with-parent', '--unshare-all', '--new-session',
441
+ '--ro-bind', '/usr', '/usr', '--symlink', 'usr/lib64', '/lib64',
442
+ '--ro-bind', srcDir, srcDir,
443
+ ...(underUsr ? [] : ['--ro-bind', nodePrefix, nodePrefix]),
444
+ '--overlay-src', lower, '--overlay', upper, work, merged,
445
+ '--bind', outDir, '/sbx-out',
446
+ ...(stageDir ? ['--bind', stageDir, '/sbx-new'] : []),
447
+ '--', node, join(srcDir, 'overlay-walk.js'),
448
+ merged, JSON.stringify([...ignore]),
449
+ join('/sbx-out', 'manifest.json'),
450
+ stageDir ? '/sbx-new' : '',
451
+ upperPaths ? join('/sbx-out', 'upper-paths.json') : ''],
452
+ { encoding: 'utf8' });
453
+ if (res.error) {
454
+ throw new Error(`sbx: could not start ${node} inside bwrap for the overlay walk: ${res.error.message}`);
455
+ }
456
+ if (res.status !== 0) {
457
+ throw new Error(`sbx: overlay walk failed (exit ${res.status}): ${(res.stderr || '').trim()}`);
458
+ }
459
+ /** @type {Map<string, {type: string, mode: number, hash?: string, target?: string}>} */
460
+ let out;
461
+ try {
462
+ out = new Map(JSON.parse(readFileSync(manifestFile, 'utf8')));
463
+ } catch {
464
+ throw new Error('sbx: overlay walk wrote no readable manifest (retry)');
465
+ }
466
+ // No relpath check: the keys come from our own walker's `readdir`
467
+ // names, which can never be `..` or absolute.
468
+ return out;
469
+ } finally {
470
+ rmSync(merged, { recursive: true, force: true });
471
+ rmSync(outDir, { recursive: true, force: true });
472
+ }
473
+ }
474
+
475
+ /** Walk the project and fingerprint it; mount the merged view unless the upper is empty (then merged IS the project). With `stageDir` the mount also stages the upper's files/symlinks there. The mount hashes only the upper's paths; every other merged entry is filled from the lower below. */
476
+ function snapLower(ov, stageDir = null) {
477
+ const lower = walkLocal(ov.proj, ov.ignore);
478
+ /** @type {Map<string, string|null>} */
479
+ const lowerFps = new Map([...lower].map(([rel, e]) => [rel, fpOf(e)]));
480
+ // One cheap upper walk, no hashing: an empty set reads as the project.
481
+ const upperPaths = new Set(walkLocal(ov.upper, ov.ignore, new Set()).keys());
482
+ const merged = upperPaths.size === 0 ? lower
483
+ : bwrapWalk({
484
+ lower: ov.proj, upper: ov.upper, work: ov.work, ignore: ov.ignore, scratch: ov.scratch, stageDir, upperPaths,
485
+ });
486
+ if (merged !== lower) {
487
+ // A merged path outside the upper IS the lower entry unchanged, so its
488
+ // fingerprint comes from the already-hashed lower instead of a second
489
+ // hash inside the mount. This holds because opaque folders and copy-up
490
+ // both land the path in the upper, and this overlay has no metacopy or
491
+ // redirect_dir (with them, the path would still be in the upper).
492
+ for (const [rel] of merged) {
493
+ if (!upperPaths.has(rel)) {
494
+ const le = lower.get(rel);
495
+ if (le) merged.set(rel, le);
496
+ }
497
+ }
498
+ }
499
+ return { lower, lowerFps, merged };
500
+ }
501
+
502
+ /**
503
+ * Review one run's tracing paper: every file the sandbox added, modified or deleted, each flagging a project change made after the run started.
504
+ *
505
+ * @param {object} opts
506
+ * @param {string} opts.runtime runtime dir holding the run's overlay (`<runtime>/overlay/<agent>`)
507
+ * @param {string} opts.agent agent name whose upper to read
508
+ * @returns {OverlayChange[]} one entry per added/modified/deleted path, each flagging a mid-run project change
509
+ * @when Reach for this to review one run's tracing paper: it lists every file the sandboxed run added, modified or deleted, flagging the ones the project changed meanwhile.
510
+ * @fails Throws when no overlay exists for the agent, when the project is gone, when a leftover commit folder blocks, when bubblewrap is older than 0.11.0, or when the overlay view cannot be mounted; never writes anything.
511
+ * @example
512
+ * import { diffOverlay } from "barebox";
513
+ * const changes = diffOverlay({ runtime: "/tmp/sbx-abc", agent: "agent" });
514
+ * for (const c of changes) console.log(c.status, c.path, c.conflict ? "(CONFLICT)" : "");
515
+ */
516
+ export function diffOverlay({ runtime, agent }) {
517
+ const ov = loadOverlay({ runtime, agent });
518
+ refuseLeftover(ov.proj, 'diff');
519
+ if (!existsSync(ov.proj)) {
520
+ throw new Error(`sbx: project ${ov.proj} is gone (cannot diff an overlay without its lower)`);
521
+ }
522
+ const { lower, merged } = snapLower(ov);
523
+ return computeChanges(ov.base, lower, merged);
524
+ }
525
+
526
+ // --- commit: stage, then swap by rename, with a journal ---------------------
527
+
528
+ const depthOf = (p) => p.split('/').length;
529
+
530
+ /** Merged-view mode minus setuid/setgid: a sandboxed setuid plant must never become host privilege. */
531
+ function stripCommitMode(mode) {
532
+ return mode & 0o1777;
533
+ }
534
+
535
+ function exoticName(type) {
536
+ if (type === 'p') return 'a fifo';
537
+ if (type === 's') return 'a socket';
538
+ if (type === 'c' || type === 'b') return 'a device node';
539
+ return 'an unknown file kind';
540
+ }
541
+
542
+ /** Fingerprint one project path now, or null when absent. ENOTDIR also reads as absent: a non-dir prefix (a file becoming a folder) cannot hold the path. */
543
+ export function fpNow(abs) {
544
+ let st;
545
+ try {
546
+ st = lstatSync(abs);
547
+ } catch (e) {
548
+ const code = /** @type {NodeJS.ErrnoException} */ (e).code;
549
+ if (code === 'ENOENT' || code === 'ENOTDIR') return null;
550
+ throw e;
551
+ }
552
+ return fpOf(entryOf(abs, st));
553
+ }
554
+
555
+ /**
556
+ * First path in `paths` whose live fingerprint differs from the snapshot
557
+ * (absent reads as null both sides), or null when nothing moved. A project
558
+ * edit landing between the diff and the swap would otherwise be silently
559
+ * overwritten, so `commitOverlay` refuses when this returns a path.
560
+ *
561
+ * @param {string} proj project directory
562
+ * @param {string[]} paths project-relative paths about to change
563
+ * @param {Map<string, string|null>} lowerFps snapshot fingerprints from the diff
564
+ * @returns {string|null} the first changed path, or null
565
+ */
566
+ export function changedSince(proj, paths, lowerFps) {
567
+ for (const p of paths) {
568
+ if (fpNow(join(proj, p)) !== (lowerFps.get(p) ?? null)) return p;
569
+ }
570
+ return null;
571
+ }
572
+
573
+ /** One journal entry (the single shape): a phase-2 step actually taken; undo runs these in reverse.
574
+ *
575
+ * @typedef {object} JournalEntry
576
+ * @property {string} op `aside` (original to `slot`) | `in` (staged content to dest) | `rmdir` | `mkdir` | `chmod` (restore `mode`)
577
+ * @property {string} path project-relative path the step touched
578
+ * @property {string} [slot] `aside`: backup path under `old/`
579
+ * @property {number} [mode] `rmdir`/`chmod`: the original mode to restore
580
+ */
581
+
582
+ /** Undo a journal in reverse, best effort: a failed step is recorded and the rest still runs. Returns exactly the steps left un-undone.
583
+ *
584
+ * @param {JournalEntry[]} journal steps taken, in order
585
+ * @param {string} proj project directory the steps were applied to
586
+ * @returns {string[]} `"<op> <path>"` for every step left un-undone, in undo order
587
+ */
588
+ export function undoJournal(journal, proj) {
589
+ /** @type {string[]} */
590
+ const notUndone = [];
591
+ for (let i = journal.length - 1; i >= 0; i--) {
592
+ const e = /** @type {JournalEntry} */ (journal[i]);
593
+ try {
594
+ const dest = join(proj, e.path);
595
+ if (e.op === 'in') {
596
+ rmSync(dest, { force: true });
597
+ } else if (e.op === 'aside') {
598
+ rmSync(dest, { recursive: true, force: true });
599
+ renameSync(/** @type {string} */ (e.slot), dest);
600
+ } else if (e.op === 'rmdir') {
601
+ try {
602
+ mkdirSync(dest);
603
+ } catch (err) {
604
+ // Already there (its removal never landed): restore the mode, count it undone.
605
+ if (/** @type {NodeJS.ErrnoException} */ (err).code !== 'EEXIST' || !lstatSync(dest).isDirectory()) throw err;
606
+ }
607
+ chmodSync(dest, /** @type {number} */ (e.mode));
608
+ } else if (e.op === 'mkdir') {
609
+ rmdirSync(dest);
610
+ } else {
611
+ chmodSync(dest, /** @type {number} */ (e.mode));
612
+ }
613
+ } catch {
614
+ notUndone.push(`${e.op} ${e.path}`);
615
+ }
616
+ }
617
+ return notUndone;
618
+ }
619
+
620
+ /**
621
+ * Press one run's tracing paper down: stage the merged view, then swap it into the project by rename. Applies everything or undoes it: a full undo reports "nothing was applied"; a partial one lists exactly the steps not undone, keeps the commit folder (originals in `old/`), and names its path.
622
+ *
623
+ * @param {object} opts
624
+ * @param {string} opts.runtime runtime dir holding the run's overlay (`<runtime>/overlay/<agent>`)
625
+ * @param {string} opts.agent agent name whose upper to commit
626
+ * @param {string} [opts.onConflict] `refuse` (default) throws before writing anything; `skip` commits the rest and reports the skipped paths
627
+ * @returns {{committed: string[], skipped: {path: string, reason: string}[]}} committed project-relative paths, plus conflicts left uncommitted under `skip`
628
+ * @when Reach for this to press one run's tracing paper down: it stages the sandbox's changes and swaps them into the project by rename, refusing loudly on mid-run conflicts.
629
+ * @fails Throws (writing nothing) when any changed file was also changed in the project mid-run, unless onConflict is `skip`; throws on unsupported file kinds, on a project that moved mid-commit, and when bubblewrap is older than 0.11.0. A phase-2 failure undoes every journaled step: a full undo reports `nothing was applied`, a partial one throws `SBX_COMMIT_FAILED` listing exactly the steps not undone and keeping the commit folder (originals in `old/`) named in the error. Setuid/setgid bits are stripped from committed modes; mtimes are not preserved. A killed commit leaves a folder that blocks the next diff/commit/setup until removed.
630
+ * @example
631
+ * import { commitOverlay } from "barebox";
632
+ * const { committed, skipped } = commitOverlay({ runtime: "/tmp/sbx-abc", agent: "agent" });
633
+ * console.log(`committed ${committed.length} file(s), skipped ${skipped.length}`);
634
+ */
635
+ export function commitOverlay({ runtime, agent, onConflict = 'refuse' }) {
636
+ if (onConflict !== 'refuse' && onConflict !== 'skip') {
637
+ throw new Error(`commitOverlay: onConflict must be 'refuse'|'skip', got ${JSON.stringify(onConflict)}`);
638
+ }
639
+ const ov = loadOverlay({ runtime, agent });
640
+ refuseLeftover(ov.proj, 'commit');
641
+ if (upperIsEmpty(ov.upper, ov.ignore)) return { committed: [], skipped: [] };
642
+ const commitDir = join(ov.proj, `${COMMIT_PREFIX}${process.pid}-${randomBytes(4).toString('hex')}`);
643
+ const newDir = join(commitDir, 'new');
644
+ const oldDir = join(commitDir, 'old');
645
+ mkdirSync(newDir, { recursive: true });
646
+ mkdirSync(oldDir, { recursive: true });
647
+ try {
648
+ const res = commitInDir(ov, newDir, oldDir, commitDir, onConflict);
649
+ rmSync(commitDir, { recursive: true, force: true });
650
+ return res;
651
+ } catch (e) {
652
+ throw finishFailedCommit(commitDir, e);
653
+ }
654
+ }
655
+
656
+ /**
657
+ * Decide what survives a failed commit: the staging folder is deleted only
658
+ * when the undo left nothing behind (`notUndone` empty — nothing was
659
+ * applied); otherwise it is kept, because `old/` holds the only copy of
660
+ * the originals, and the error names the folder. Returns the error to throw.
661
+ *
662
+ * @param {string} commitDir the run's staging folder in the project
663
+ * @param {unknown} failure whatever the commit threw (phase-1 refusals carry no `notUndone`)
664
+ * @returns {unknown} the failure, to throw
665
+ */
666
+ export function finishFailedCommit(commitDir, failure) {
667
+ const notUndone = failure instanceof Error && Array.isArray(
668
+ /** @type {{ notUndone?: unknown }} */ (failure).notUndone)
669
+ ? /** @type {unknown[]} */ (/** @type {{ notUndone?: unknown }} */ (failure).notUndone)
670
+ : [];
671
+ if (!notUndone.length) {
672
+ rmSync(commitDir, { recursive: true, force: true });
673
+ }
674
+ return failure;
675
+ }
676
+
677
+ /** Phase 1 (no project writes) then phase 2 (journaled renames). */
678
+ function commitInDir(ov, newDir, oldDir, commitDir, onConflict) {
679
+ // One mount: the manifest for the diff, plus every file/symlink staged.
680
+ const { lower, lowerFps, merged } = snapLower(ov, newDir);
681
+ const changes = computeChanges(ov.base, lower, merged);
682
+ const conflicts = changes.filter((c) => c.conflict);
683
+ if (conflicts.length && onConflict !== 'skip') throw new OverlayConflictError(conflicts);
684
+ const apply = onConflict === 'skip' ? changes.filter((c) => !c.conflict) : changes;
685
+ const skipped = onConflict === 'skip'
686
+ ? conflicts.map((c) => ({ path: c.path, reason: /** @type {string} */ (c.reason) }))
687
+ : [];
688
+ for (const c of apply) {
689
+ if (c.status !== 'deleted' && c.type !== 'f' && c.type !== 'd' && c.type !== 'l') {
690
+ throw new Error(`sbx: cannot commit ${c.path}: ${exoticName(/** @type {string} */ (c.type))} ` +
691
+ 'created inside the sandbox (remove it there and retry)');
692
+ }
693
+ }
694
+ // Re-check exactly the paths about to change, while nothing is (absent fingerprints as null both sides).
695
+ const moved = changedSince(ov.proj, apply.map((c) => c.path), lowerFps);
696
+ if (moved !== null) {
697
+ throw new Error(`sbx: project changed during commit at ${moved} (nothing was applied; retry)`);
698
+ }
699
+ /** @type {JournalEntry[]} */
700
+ const journal = [];
701
+ try {
702
+ swapIn(ov, apply, lower, newDir, oldDir, journal);
703
+ } catch (e) {
704
+ const cause = e instanceof Error ? e.message : String(e);
705
+ const at = e instanceof Error && /** @type {{commitPath?: string}} */ (e).commitPath
706
+ ? /** @type {string} */ (/** @type {{commitPath?: string}} */ (e).commitPath) : apply.map((c) => c.path).join(', ');
707
+ const notUndone = undoJournal(journal, ov.proj);
708
+ if (notUndone.length) {
709
+ throw Object.assign(
710
+ new Error(`sbx: commit failed at ${at} (${cause}): ` +
711
+ `not undone [${notUndone.join(', ')}] (originals are in ${oldDir}; commit folder kept: ${commitDir})`),
712
+ { code: 'SBX_COMMIT_FAILED', notUndone });
713
+ }
714
+ throw Object.assign(
715
+ new Error(`sbx: commit failed at ${at} (${cause}; nothing was applied)`),
716
+ { code: 'SBX_COMMIT_FAILED', notUndone });
717
+ }
718
+ // A skipped conflict stays on the paper; a full commit starts a fresh sheet, no-op included.
719
+ if (!skipped.length) {
720
+ emptyDir(ov.upper);
721
+ emptyDir(ov.work);
722
+ }
723
+ return { committed: apply.map((c) => c.path), skipped };
724
+ }
725
+
726
+ /**
727
+ * Fail with the path attached, so the phase-2 catcher can name it. A
728
+ * permission failure under a parent step 0 deliberately left alone names
729
+ * that parent and its foreign ownership.
730
+ *
731
+ * @returns {never} always throws
732
+ */
733
+ function swapFail(rel, cause, unowned) {
734
+ let msg = cause instanceof Error ? cause.message : String(cause);
735
+ const code = cause instanceof Error
736
+ ? /** @type {{ code?: string }} */ (cause).code
737
+ : undefined;
738
+ if ((code === 'EACCES' || code === 'EPERM') && unowned && unowned.size) {
739
+ for (let d = dirname(rel); ; d = dirname(d)) {
740
+ const key = d === '' ? '.' : d;
741
+ if (unowned.has(key)) {
742
+ msg += ` (parent '${key}' is not writable and not owned by you, so it was left alone)`;
743
+ break;
744
+ }
745
+ if (d === '.' || d === '' || d === '/') break;
746
+ }
747
+ }
748
+ throw Object.assign(new Error(msg), { commitPath: rel });
749
+ }
750
+
751
+ /** Phase 2: every step is one rename/mkdir/rmdir/chmod, journaled before the next runs. */
752
+ function swapIn(ov, apply, lower, newDir, oldDir, journal) {
753
+ let slots = 0;
754
+ const slotFor = () => join(oldDir, `s${slots++}`);
755
+ const deepFirst = [...apply].sort((a, b) => depthOf(b.path) - depthOf(a.path));
756
+ // 0. Read-only parents: a rename needs write permission on the parent
757
+ // folder, so a change inside a 0555 folder could never commit. Collect
758
+ // every parent a step renames into or out of, or mkdir/rmdirs in; for
759
+ // each one this process cannot write to but owns, journal the current
760
+ // mode and add u+w (step 5 sets the final mode). Parents it does not own
761
+ // are left alone: the op fails and is undone, naming them (see swapFail).
762
+ /** @type {Map<string, number>} */
763
+ const tempChmods = new Map();
764
+ /** @type {Set<string>} */
765
+ const unownedParents = new Set();
766
+ {
767
+ /** @type {Set<string>} */
768
+ const parents = new Set();
769
+ for (const c of apply) {
770
+ for (let d = dirname(c.path); ; d = dirname(d)) {
771
+ parents.add(d === '' ? '.' : d);
772
+ if (d === '.' || d === '' || d === '/') break;
773
+ }
774
+ }
775
+ const writable = (abs) => {
776
+ try {
777
+ accessSync(abs, constants.W_OK);
778
+ return true;
779
+ } catch {
780
+ return false;
781
+ }
782
+ };
783
+ for (const rel of parents) {
784
+ const abs = join(ov.proj, rel);
785
+ let st;
786
+ try {
787
+ st = statSync(abs); // follows links: the mode chmodded below is the target's
788
+ } catch {
789
+ continue; // missing: a later step fails loudly, as today
790
+ }
791
+ if (!st.isDirectory() || writable(abs)) continue;
792
+ const owned = typeof process.getuid === 'function' ? st.uid === process.getuid() : true;
793
+ if (!owned) {
794
+ unownedParents.add(rel);
795
+ continue;
796
+ }
797
+ const orig = st.mode & 0o7777;
798
+ try {
799
+ chmodSync(abs, orig | 0o200);
800
+ journal.push({ op: 'chmod', path: rel, mode: orig });
801
+ tempChmods.set(rel, orig);
802
+ } catch (e) {
803
+ swapFail(rel, e, unownedParents);
804
+ }
805
+ }
806
+ }
807
+ // 1. Move aside every file/symlink about to be deleted or replaced, deepest first (dirs go in step 2).
808
+ for (const c of deepFirst) {
809
+ const l = lower.get(c.path);
810
+ if (!l || l.type === 'd') continue;
811
+ try {
812
+ const slot = slotFor();
813
+ renameSync(join(ov.proj, c.path), slot);
814
+ journal.push({ op: 'aside', path: c.path, slot });
815
+ } catch (e) {
816
+ swapFail(c.path, e, unownedParents);
817
+ }
818
+ }
819
+ // 2. Remove deleted folders, deepest first. Only ignored content left is kept (Q3); replacing a
820
+ // folder that holds ignored content with a file/symlink is refused loudly.
821
+ for (const c of deepFirst) {
822
+ const l = lower.get(c.path);
823
+ if (l?.type !== 'd') continue;
824
+ if (c.status !== 'deleted' && c.type === 'd') continue;
825
+ try {
826
+ rmdirSync(join(ov.proj, c.path));
827
+ journal.push({ op: 'rmdir', path: c.path, mode: /** @type {number} */ (l.mode) });
828
+ } catch (e) {
829
+ const code = /** @type {NodeJS.ErrnoException} */ (e).code ?? '';
830
+ if (code === 'ENOENT') continue;
831
+ if (code === 'ENOTEMPTY' || code === 'EEXIST') {
832
+ if (c.status !== 'deleted') {
833
+ throw Object.assign(
834
+ new Error(`sbx: ${c.path} holds ignored content; cannot replace it ` +
835
+ `with a ${c.type === 'l' ? 'symlink' : 'file'}`),
836
+ { commitPath: c.path });
837
+ }
838
+ continue;
839
+ }
840
+ swapFail(c.path, e, unownedParents);
841
+ }
842
+ }
843
+ // 3. Create new folders, shallowest first, writable (final modes land in step 5).
844
+ /** @type {Set<string>} */
845
+ const needDirs = new Set();
846
+ for (const c of apply) {
847
+ if (c.status === 'deleted') continue;
848
+ const top = c.type === 'd' ? c.path : dirname(c.path);
849
+ if (top === '.' || !top) continue;
850
+ const segs = top.split('/');
851
+ for (let i = 1; i <= segs.length; i++) needDirs.add(segs.slice(0, i).join('/'));
852
+ }
853
+ for (const rel of [...needDirs].sort((a, b) => depthOf(a) - depthOf(b))) {
854
+ const dest = join(ov.proj, rel);
855
+ try {
856
+ if (existsSync(dest)) {
857
+ if (!lstatSync(dest).isDirectory()) throw new Error(`${rel} is not a directory`);
858
+ continue;
859
+ }
860
+ mkdirSync(dest);
861
+ chmodSync(dest, 0o700);
862
+ journal.push({ op: 'mkdir', path: rel });
863
+ } catch (e) {
864
+ swapFail(rel, e, unownedParents);
865
+ }
866
+ }
867
+ // 4. Move the staged files and symlinks in.
868
+ for (const c of apply) {
869
+ if (c.status === 'deleted' || c.type === 'd') continue;
870
+ try {
871
+ renameSync(join(newDir, c.path), join(ov.proj, c.path));
872
+ journal.push({ op: 'in', path: c.path });
873
+ } catch (e) {
874
+ swapFail(c.path, e, unownedParents);
875
+ }
876
+ }
877
+ // 5. Permissions last, deepest first: new folders, folder mode changes, file modes (setuid/setgid
878
+ // stripped). Symlinks are never chmodded — it would hit the target.
879
+ /** @type {Set<string>} */
880
+ const modeSet = new Set();
881
+ for (const c of deepFirst) {
882
+ if (c.status === 'deleted' || (c.type !== 'd' && c.type !== 'f')) continue;
883
+ const dest = join(ov.proj, c.path);
884
+ try {
885
+ const oldMode = lstatSync(dest).mode & 0o7777;
886
+ const want = stripCommitMode(/** @type {number} */ (c.mode));
887
+ modeSet.add(c.path);
888
+ if (oldMode === want) continue;
889
+ chmodSync(dest, want);
890
+ journal.push({ op: 'chmod', path: c.path, mode: oldMode });
891
+ } catch (e) {
892
+ swapFail(c.path, e, unownedParents);
893
+ }
894
+ }
895
+ // 5b. Temporary u+w back out: a step-0 parent the changeset does not set
896
+ // keeps its original mode. A parent the commit removed is gone: nothing
897
+ // to restore.
898
+ for (const [rel, orig] of tempChmods) {
899
+ if (modeSet.has(rel)) continue;
900
+ const dest = join(ov.proj, rel);
901
+ let cur;
902
+ try {
903
+ cur = statSync(dest).mode & 0o7777;
904
+ } catch (e) {
905
+ if (/** @type {NodeJS.ErrnoException} */ (e).code === 'ENOENT') continue;
906
+ swapFail(rel, e, unownedParents);
907
+ }
908
+ if (cur === orig) continue;
909
+ try {
910
+ chmodSync(dest, orig);
911
+ } catch (e) {
912
+ swapFail(rel, e, unownedParents);
913
+ }
914
+ }
915
+ }
916
+
917
+ // --- rollback ---------------------------------------------------------------
918
+
919
+ /** Raw fallback: relative upper paths, no added/modified/deleted inference. Same walker, statuses discarded; a missing upper is nothing to discard. */
920
+ function rawUpper(upper, ignore) {
921
+ /** @type {Map<string, unknown>} */
922
+ let entries;
923
+ try {
924
+ entries = walkLocal(upper, ignore);
925
+ } catch (e) {
926
+ if (/** @type {NodeJS.ErrnoException} */ (e).code === 'ENOENT') return [];
927
+ throw e;
928
+ }
929
+ return [...entries.keys()].sort().map((rel) => ({ path: rel, status: 'unknown', conflict: false, reason: null }));
930
+ }
931
+
932
+ /**
933
+ * Throw one run's tracing paper away: drop every sandboxed change and leave the project exactly as it was. Reports exactly what `diffOverlay` returns, taken before removal, so rollback and diff can never disagree; when the project is gone (or the view cannot be mounted) the report is the raw relative paths found in the upper, with no added/modified/deleted inference. Then the overlay dir is removed completely, so the next run starts fresh. Never touches the project.
934
+ *
935
+ * @param {object} opts
936
+ * @param {string} opts.runtime runtime dir holding the run's overlay (`<runtime>/overlay/<agent>`)
937
+ * @param {string} opts.agent agent name whose upper to discard
938
+ * @returns {{discarded: OverlayChange[], exact: boolean, why: string|null}} the changes that were dropped; `exact` is false for the raw fallback, and then `why` names the actual reason (diff's error, or `project <proj> is gone`, plus the raw-listing reason when that failed too). `why` is null when exact.
939
+ * @when Reach for this to throw one run's tracing paper away: it drops every sandboxed change and leaves the project exactly as it was.
940
+ * @fails Throws when no overlay exists for the agent or its record is corrupt, or when the overlay folder cannot be removed even after a permission repair (the error names the folder). Listing the changes never throws and never invents entries: an unlistable upper reports `discarded: []` with the reasons in `why`. Removal depends on neither listing nor the first permission pass: a partial failure retries removal once after a fresh permission pass. Dropping the upper never touches the project.
941
+ * @example
942
+ * import { rollbackOverlay } from "barebox";
943
+ * const { discarded } = rollbackOverlay({ runtime: "/tmp/sbx-abc", agent: "agent" });
944
+ * console.log(`discarded ${discarded.length} change(s)`);
945
+ */
946
+ export function rollbackOverlay({ runtime, agent }) {
947
+ assertAgentName(agent);
948
+ const { base: basedir, upper, work, manifest } = runtimePaths(runtime).overlay(agent);
949
+ const m = readRecord(manifest, runtime, agent);
950
+ const ignore = new Set(/** @type {string[]} */ (m.ignore ?? []));
951
+ // The escape hatch first: fix permissions before reading anything, so
952
+ // mode-000 debris the agent left can wedge neither the report nor the
953
+ // removal. Removal never depends on listing.
954
+ for (const d of [upper, work]) {
955
+ try {
956
+ chmodTree(d);
957
+ } catch {
958
+ // Missing already: the rm below still runs.
959
+ }
960
+ }
961
+ /** @type {OverlayChange[]} */
962
+ let discarded = [];
963
+ let exact = true;
964
+ /** @type {string|null} */
965
+ let why = null;
966
+ /** @type {string|null} */
967
+ let primary = null;
968
+ if (!existsSync(m.proj)) {
969
+ primary = `project ${m.proj} is gone`;
970
+ } else {
971
+ try {
972
+ discarded = diffOverlay({ runtime, agent });
973
+ } catch (e) {
974
+ primary = e instanceof Error ? e.message : String(e);
975
+ }
976
+ }
977
+ if (primary !== null) {
978
+ exact = false;
979
+ /** @type {string|null} */
980
+ let rawReason = null;
981
+ try {
982
+ discarded = rawUpper(upper, ignore);
983
+ } catch (e) {
984
+ rawReason = e instanceof Error ? e.message : String(e);
985
+ discarded = [];
986
+ }
987
+ why = rawReason === null || rawReason === primary
988
+ ? primary
989
+ : `${primary} (raw listing also failed: ${rawReason})`;
990
+ }
991
+ // Removal depends on neither listing nor the first permission pass: a
992
+ // partial chmodTree/rmSync failure retries removal once after a fresh
993
+ // permission pass over what is left; only that names the folder in a throw.
994
+ try {
995
+ rmSync(basedir, { recursive: true, force: true });
996
+ } catch (e) {
997
+ const first = e instanceof Error ? e.message : String(e);
998
+ for (const d of [upper, work]) {
999
+ try {
1000
+ chmodTree(d);
1001
+ } catch {
1002
+ // The remainder is chmodded as far as it goes; rmSync reports below.
1003
+ }
1004
+ }
1005
+ try {
1006
+ rmSync(basedir, { recursive: true, force: true });
1007
+ } catch {
1008
+ throw new Error(`sbx: cannot remove overlay for agent '${agent}' (${basedir}): ${first}`);
1009
+ }
1010
+ }
1011
+ return { discarded, exact, why };
1012
+ }