@tpsdev-ai/flair 0.55.1 → 0.55.2

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.
@@ -0,0 +1,557 @@
1
+ /**
2
+ * config-critical-section.ts — the ONE exclusive, identity-checked
3
+ * observe → decide → write primitive for Flair's read-modify-write config
4
+ * sinks (flair#1778 slice 2c-i-b, invariant I3b).
5
+ *
6
+ * A config sink that reads a file, decides what it should become, and writes
7
+ * it back is a race when two Flair writers run at once: both read the same
8
+ * bytes, both compute from that stale snapshot, and the second write silently
9
+ * discards the first. Before this module every sink did exactly that with an
10
+ * in-place `writeFileSync` — no lock, no re-check, no atomic replace.
11
+ *
12
+ * This primitive makes observe → decide → write ONE critical section:
13
+ *
14
+ * 1. OBSERVE (before the lock) records THREE things, never one: the
15
+ * configured ENTRY's identity ({dev, ino}) and type; the RESOLVED
16
+ * target's realpath + stat; and the RESOLVED PARENT directory's realpath
17
+ * + {dev, ino}. ABSENCE is explicit — the target is "absent" only when
18
+ * the configured entry does not exist AND the parent resolves. A dangling
19
+ * symlink is not absence; EACCES / ELOOP / ENOTDIR are resolution ERRORS
20
+ * and HOLD, never "absent".
21
+ * 2. LOCK: an `O_EXCL` create of `<resolvedTarget>.lock`, beside the
22
+ * RESOLVED target so stable symlink aliases share one lock, computed once
23
+ * per attempt. Content is diagnostic only (`<pid> <iso> <hostname>`),
24
+ * never an authorization input. Bounded retry then a NAMED refusal. No
25
+ * reclaim, no age-out, no pid-liveness shortcut.
26
+ * 3. RE-OBSERVE INSIDE the lock and compare. Any change of entry type,
27
+ * entry identity, resolved path, target identity, parent identity or
28
+ * absence state HELDS the write (fixture 11/12), naming which
29
+ * observation changed.
30
+ * 4. READ inside the lock, then call `decide(bytes, identity)`. The callback
31
+ * returns a DECISION and cannot write. (This does not make it pure — it
32
+ * can still import fs or close over stale state — so sinks are covered by
33
+ * an import-boundary fixture as well; TypeScript does not enforce it.)
34
+ * 5. WRITE (on `{ write }`): a temp `<resolvedTarget>.tmp-<pid>-<rand>`
35
+ * created `wx` mode 0600 BEFORE any bytes, written, chmod'd to the
36
+ * ORIGINAL's permission bits (new file 0600; setuid/setgid/sticky
37
+ * stripped; special file types rejected), owner/group preserved with
38
+ * `fchown` or REFUSED before rename, `fsync` → rename → best-effort
39
+ * parent `fsync`. Rename lands on the RESOLVED target, never the
40
+ * configured symlink. A failure BEFORE the rename leaves the original
41
+ * intact ("nothing written"); a failure AFTER it is a COMMITTED write
42
+ * with a cleanup warning, never reported as "nothing written".
43
+ *
44
+ * BACKUP SEMANTICS. `opts.backup` runs on the IN-LOCK bytes BEFORE `decide` on
45
+ * every call that reaches the read — INCLUDING calls whose decision ends up
46
+ * noop or held. A backup of the current bytes is never wrong; the churn is the
47
+ * price of backing up before parsing. It is skipped only where the read is
48
+ * skipped: an absent destination, or a non-regular one (refused above).
49
+ * 6. FRESH-ATTEMPT PROTOCOL: another cooperative writer's committed
50
+ * replacement changes the target inode, so a waiting writer's in-lock
51
+ * comparison FAILS and it is HELD — by design, never waived. The
52
+ * primitive runs up to K=3 complete fresh attempts, retrying ONLY when
53
+ * the change is "target identity changed AND entry type unchanged AND new
54
+ * target is a regular file" (a committed replacement). A type change,
55
+ * retarget, parent change or absence change is a FINAL hold. Every
56
+ * attempt decides on ITS OWN in-lock bytes; nothing precomputed crosses
57
+ * attempts; exhausting the bound is a HOLD-with-reason, never a throw.
58
+ *
59
+ * THREAT BOUNDARY (flair#1778 2c-i-b design review, convergent). This
60
+ * primitive serializes cooperative Flair writers and detects identity changes
61
+ * made before its final check; it does not defend against an ancestor
62
+ * directory replaced between that check and the rename — a pathname is not a
63
+ * pinned directory handle, and Node exposes no openat-relative rename.
64
+ *
65
+ * FILESYSTEM GUARANTEES. The exclusive create/rename guarantees hold on macOS
66
+ * APFS (probed: O_EXCL→EEXIST, same-directory rename atomic, directory fsync
67
+ * honoured) and on Linux ext4/xfs. On NFS/SMB homes O_EXCL is not reliable:
68
+ * there the lock may not serialize at all, and safety DEGRADES to the in-lock
69
+ * re-observe plus the fresh-attempt protocol — this module never claims
70
+ * serialization on those filesystems. A stale lock left by another host on a
71
+ * shared home is a NAMED availability residual: the refusal names the recorded
72
+ * host and the operator may not have it. This primitive REFUSES on a held
73
+ * lock; it never reclaims one (two reclaimers can rename a LIVE lock away, pid
74
+ * reuse lies, and a blank/partially written lock is refused too).
75
+ *
76
+ * METADATA / BEHAVIOUR CHANGE. Every config sink this replaces writes IN PLACE
77
+ * and preserves the inode. Temp+rename REPLACES the inode, so: (a) an
78
+ * owner/group change the process cannot preserve is a REFUSE, never a silent
79
+ * success — UNTESTED (needs a privilege drop): exercising the refusal needs the
80
+ * ORIGINAL to be owned by a uid the process cannot `fchown` the replacement to,
81
+ * which a same-user fixture cannot arrange, so this branch is covered by review,
82
+ * not by a test; (b) a client holding an open fd keeps the OLD inode until it reopens
83
+ * (every wired client re-reads at startup). ACL, xattr and hard-link
84
+ * preservation are NOT handled and are documented, not silently dropped.
85
+ *
86
+ * Leaf module: imports only node:fs, node:crypto, node:os and node:path.
87
+ * NEVER import src/cli.ts here — its `writeFileAtomic` lacks exclusive temp
88
+ * creation, fsync, locking and identity checks (flair#1778 2c-i-b ruling).
89
+ */
90
+ import { closeSync, existsSync, fchmodSync, fchownSync, fstatSync, fsyncSync, lstatSync, openSync, readFileSync, realpathSync, renameSync, statSync, unlinkSync, writeFileSync, writeSync, } from "node:fs";
91
+ import { randomBytes } from "node:crypto";
92
+ import { hostname } from "node:os";
93
+ import { basename, dirname, join } from "node:path";
94
+ // ── helpers ─────────────────────────────────────────────────────────────────
95
+ function msg(err) {
96
+ return err instanceof Error ? err.message : String(err);
97
+ }
98
+ /** Synchronous backoff without blocking the process on a sleep primitive that
99
+ * differs between bun and node. */
100
+ function sleepSync(ms) {
101
+ if (ms <= 0)
102
+ return;
103
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
104
+ }
105
+ /** ENV-GATED barrier for child-process fixtures: after marking its own stage
106
+ * file it waits (bounded) for a `go` file the schedule controller drops.
107
+ * Inert unless `FLAIR_TEST_CRITICAL_BARRIER` names a directory.
108
+ *
109
+ * TRUSTED-ENV ASSUMPTION: this path is only as privileged as the environment
110
+ * it is set in. Anyone who can set a flair process's `FLAIR_TEST_CRITICAL_BARRIER`
111
+ * can already set `HOME` / `FLAIR_*`, so the barrier grants no capability that
112
+ * was not already available to them; and it self-releases — a stale barrier
113
+ * waits at most 15 s, then proceeds. */
114
+ function envBarrier(stage) {
115
+ const dir = process.env.FLAIR_TEST_CRITICAL_BARRIER;
116
+ if (!dir)
117
+ return;
118
+ try {
119
+ writeFileSync(join(dir, `${process.pid}.${stage}`), "1");
120
+ }
121
+ catch { /* */ }
122
+ const go = join(dir, "go");
123
+ // A STAGE-SPECIFIC release (`go.<stage>`) lets a fixture advance the earlier
124
+ // stages while HOLDING this one — the shared `go` releases every stage at
125
+ // once (flair#1778 2c-i-d2 needs the writer to pause at the fsync stage).
126
+ const goStage = join(dir, `go.${stage}`);
127
+ const deadline = Date.now() + 15_000;
128
+ while (!existsSync(go) && !existsSync(goStage) && Date.now() < deadline)
129
+ sleepSync(5);
130
+ }
131
+ function barrier(hook, stage, attempt) {
132
+ envBarrier(stage);
133
+ hook?.(attempt);
134
+ }
135
+ function isRegularMode(mode) {
136
+ return (mode & 0o170000) === 0o100000;
137
+ }
138
+ function entryTypeOf(st) {
139
+ if (st.isSymbolicLink())
140
+ return "symlink";
141
+ if (st.isFile())
142
+ return "regular";
143
+ return "other";
144
+ }
145
+ function targetTypeOf(st) {
146
+ if (st.isFile())
147
+ return "regular";
148
+ return "other";
149
+ }
150
+ /**
151
+ * The one observation: configured entry (`lstat`), resolved target (realpath +
152
+ * `stat`), resolved parent (realpath + `stat`). Total: every failure to resolve
153
+ * is reported as a reason, never coerced to "absent".
154
+ */
155
+ export function observeConfig(configPath) {
156
+ const parentDir = dirname(configPath);
157
+ let parentPath;
158
+ let parentStat;
159
+ try {
160
+ parentPath = realpathSync(parentDir);
161
+ parentStat = statSync(parentPath);
162
+ }
163
+ catch (err) {
164
+ return { ok: false, reason: `cannot resolve the parent directory ${parentDir}: ${msg(err)}` };
165
+ }
166
+ const parent = { path: parentPath, dev: parentStat.dev, ino: parentStat.ino };
167
+ let entryStat;
168
+ try {
169
+ entryStat = lstatSync(configPath);
170
+ }
171
+ catch (err) {
172
+ if (err.code === "ENOENT")
173
+ entryStat = null;
174
+ else
175
+ return { ok: false, reason: `cannot stat ${configPath}: ${msg(err)}` };
176
+ }
177
+ if (entryStat === null) {
178
+ // Absent entry, parent resolves → explicit ABSENCE.
179
+ const targetPath = join(parentPath, basename(configPath));
180
+ return {
181
+ ok: true,
182
+ value: {
183
+ entry: { type: "absent", dev: null, ino: null },
184
+ target: { path: targetPath, type: "absent", dev: null, ino: null, mode: null, uid: null, gid: null },
185
+ parent,
186
+ },
187
+ };
188
+ }
189
+ const entry = { type: entryTypeOf(entryStat), dev: entryStat.dev, ino: entryStat.ino };
190
+ // Resolve the target: a read follows the entry (realpath). A dangling
191
+ // symlink / EACCES / ELOOP / ENOTDIR here is a resolution ERROR → hold.
192
+ let targetPath;
193
+ try {
194
+ targetPath = realpathSync(configPath);
195
+ }
196
+ catch (err) {
197
+ return { ok: false, reason: `cannot resolve ${configPath} to a target: ${msg(err)}` };
198
+ }
199
+ let targetStat;
200
+ try {
201
+ targetStat = statSync(targetPath);
202
+ }
203
+ catch (err) {
204
+ return { ok: false, reason: `cannot stat the resolved target ${targetPath}: ${msg(err)}` };
205
+ }
206
+ return {
207
+ ok: true,
208
+ value: {
209
+ entry,
210
+ target: {
211
+ path: targetPath,
212
+ type: targetTypeOf(targetStat),
213
+ dev: targetStat.dev,
214
+ ino: targetStat.ino,
215
+ mode: targetStat.mode,
216
+ uid: targetStat.uid,
217
+ gid: targetStat.gid,
218
+ },
219
+ parent,
220
+ },
221
+ };
222
+ }
223
+ function resolvedTargetPath(obs, configPath) {
224
+ if (obs.target.type === "absent")
225
+ return join(obs.parent.path, basename(configPath));
226
+ return obs.target.path;
227
+ }
228
+ /** First changed field, in a fixed order. Entry TYPE first (a regular entry
229
+ * replaced by a symlink), then absence, then PARENT identity (an ancestor
230
+ * swapped), then a SYMLINK entry's own link identity (replaced link), then
231
+ * the resolved path (a retarget), then the target identity (a committed
232
+ * replacement of the file). For a plain regular entry the entry's and the
233
+ * target's identity are the same inode, so the committed-replacement case is
234
+ * reported as `target-identity` and stays retryable. Null when identical. */
235
+ export function compareObservation(a, b) {
236
+ if (a.entry.type !== b.entry.type)
237
+ return "entry-type";
238
+ const aAbsent = a.target.type === "absent";
239
+ const bAbsent = b.target.type === "absent";
240
+ if (aAbsent !== bAbsent)
241
+ return "absence";
242
+ if (a.parent.dev !== b.parent.dev || a.parent.ino !== b.parent.ino)
243
+ return "parent-identity";
244
+ if (a.entry.type === "symlink" && (a.entry.dev !== b.entry.dev || a.entry.ino !== b.entry.ino)) {
245
+ return "entry-identity";
246
+ }
247
+ if (!aAbsent && a.target.path !== b.target.path)
248
+ return "resolved-path";
249
+ if (!aAbsent && (a.target.dev !== b.target.dev || a.target.ino !== b.target.ino))
250
+ return "target-identity";
251
+ return null;
252
+ }
253
+ const FIELD_LABEL = {
254
+ "entry-type": "the configured entry's type",
255
+ "entry-identity": "the configured entry's identity",
256
+ absence: "the destination's presence",
257
+ "resolved-path": "the resolved target path",
258
+ "target-identity": "the target's identity",
259
+ "parent-identity": "the resolved parent directory's identity",
260
+ };
261
+ function heldLine(field) {
262
+ return `held: ${FIELD_LABEL[field]} changed between the pre-lock observation and the in-lock re-observe — nothing written (another Flair writer touched the destination).`;
263
+ }
264
+ function parseLockHolder(raw) {
265
+ if (!raw)
266
+ return null;
267
+ const m = raw.trim().match(/^(\d+)\s+(\S+)\s+(\S+)$/);
268
+ if (!m)
269
+ return null;
270
+ return { pid: m[1], timestamp: m[2], host: m[3] };
271
+ }
272
+ function lockRefusalLine(lockPath, holder) {
273
+ const parsed = parseLockHolder(holder);
274
+ if (parsed) {
275
+ return (`lock exists at ${lockPath}; recorded holder pid ${parsed.pid} since ${parsed.timestamp} on host ${parsed.host}. ` +
276
+ `Quiesce Flair writers and check the recorded holder ON THAT HOST before removing the file.`);
277
+ }
278
+ return (`lock exists at ${lockPath} and its contents are not a readable holder record (blank or partially written); refusing to write. ` +
279
+ `Quiesce Flair writers and check the recorded holder ON THAT HOST before removing the file.`);
280
+ }
281
+ function acquireLock(lockPath, retry) {
282
+ for (let i = 0; i < retry.attempts; i++) {
283
+ try {
284
+ const fd = openSync(lockPath, "wx", 0o600);
285
+ try {
286
+ writeSync(fd, `${process.pid} ${new Date().toISOString()} ${hostname()}\n`);
287
+ }
288
+ catch {
289
+ // The lock exists (that is what protects us); a failed diagnostic
290
+ // write is not fatal, and the content is never an authorization input.
291
+ }
292
+ finally {
293
+ try {
294
+ closeSync(fd);
295
+ }
296
+ catch { /* already closed */ }
297
+ }
298
+ return { ok: true };
299
+ }
300
+ catch (err) {
301
+ if (err.code !== "EEXIST")
302
+ return { ok: false, holder: null };
303
+ if (i < retry.attempts - 1)
304
+ sleepSync(retry.delayMs);
305
+ }
306
+ }
307
+ let holder = null;
308
+ try {
309
+ holder = readFileSync(lockPath, "utf-8");
310
+ }
311
+ catch {
312
+ holder = null;
313
+ }
314
+ return { ok: false, holder };
315
+ }
316
+ function releaseLock(lockPath) {
317
+ try {
318
+ unlinkSync(lockPath);
319
+ }
320
+ catch { /* best effort; a leaked lock refuses, never corrupts */ }
321
+ }
322
+ /**
323
+ * Write the whole buffer, looping until every byte is out. A single `writeSync`
324
+ * may write FEWER bytes than asked (a short write), so the returned count must
325
+ * be added to the offset and the loop resumed — a truncated staging file
326
+ * renamed into place is a false recovery copy. Exported so the hook-backup
327
+ * helper reuses THIS loop rather than a second copy (flair#1778).
328
+ *
329
+ * `write` is injectable for the backup helper's test seam; production callers
330
+ * leave it as node's writeSync.
331
+ */
332
+ export function writeAllSync(fd, buf, write = writeSync) {
333
+ let off = 0;
334
+ while (off < buf.length)
335
+ off += write(fd, buf, off, buf.length - off);
336
+ }
337
+ /**
338
+ * Temp (wx, 0600) → write → fchmod to the original bits → fchown owner/group
339
+ * or refuse → fsync → rename onto the RESOLVED target → best-effort parent
340
+ * fsync. A failure before the rename leaves the original untouched.
341
+ */
342
+ export function atomicReplace(targetPath, bytes, original, onTempCreate,
343
+ // TEST-ONLY: fires AFTER the staging file is fsynced and BEFORE the rename
344
+ // (flair#1778 2c-i-d2 crash window, T1c). A SIGKILL here leaves the target
345
+ // byte-identical and orphans the temp + lock (cleanup bypassed).
346
+ onAfterFsync) {
347
+ if (original && !isRegularMode(original.mode)) {
348
+ return { ok: false, reason: `the destination ${targetPath} is not a regular file (mode ${original.mode.toString(8)}); refusing to replace it` };
349
+ }
350
+ const dir = dirname(targetPath);
351
+ const tempPath = `${targetPath}.tmp-${process.pid}-${randomBytes(6).toString("hex")}`;
352
+ let fd = -1;
353
+ const cleanupTemp = () => { try {
354
+ unlinkSync(tempPath);
355
+ }
356
+ catch { /* nothing to remove */ } };
357
+ const fail = (reason) => {
358
+ if (fd >= 0) {
359
+ try {
360
+ closeSync(fd);
361
+ }
362
+ catch { /* */ }
363
+ fd = -1;
364
+ }
365
+ cleanupTemp();
366
+ return { ok: false, reason };
367
+ };
368
+ const buf = Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength);
369
+ try {
370
+ fd = openSync(tempPath, "wx", 0o600);
371
+ onTempCreate?.(tempPath);
372
+ writeAllSync(fd, buf);
373
+ const perm = original ? (original.mode & 0o777) : 0o600;
374
+ try {
375
+ fchmodSync(fd, perm);
376
+ }
377
+ catch (err) {
378
+ return fail(`could not set mode ${perm.toString(8)} on the staging file: ${msg(err)}`);
379
+ }
380
+ if (original) {
381
+ let fchownError = null;
382
+ try {
383
+ fchownSync(fd, original.uid, original.gid);
384
+ }
385
+ catch (err) {
386
+ fchownError = err;
387
+ }
388
+ if (fchownError !== null) {
389
+ let cur = null;
390
+ try {
391
+ cur = fstatSync(fd);
392
+ }
393
+ catch {
394
+ cur = null;
395
+ }
396
+ if (!cur || cur.uid !== original.uid || cur.gid !== original.gid) {
397
+ return fail(`cannot preserve owner/group ${original.uid}:${original.gid} on the replacement (${msg(fchownError)}); ` +
398
+ `refusing to change ownership silently`);
399
+ }
400
+ }
401
+ }
402
+ try {
403
+ fsyncSync(fd);
404
+ }
405
+ catch (err) {
406
+ return fail(`could not fsync the staging file: ${msg(err)}`);
407
+ }
408
+ }
409
+ catch (err) {
410
+ return fail(`staging the replacement failed: ${msg(err)}`);
411
+ }
412
+ finally {
413
+ if (fd >= 0) {
414
+ try {
415
+ closeSync(fd);
416
+ }
417
+ catch { /* */ }
418
+ }
419
+ }
420
+ // TEST-ONLY barrier AFTER the fsync (and the fd close) and BEFORE the rename
421
+ // (flair#1778 2c-i-d2, T1c). Inert in production: envBarrier returns unless
422
+ // FLAIR_TEST_CRITICAL_BARRIER is set. A SIGKILL here leaves the target
423
+ // byte-identical and orphans the staging temp + the lock (the crash window).
424
+ envBarrier("fsync");
425
+ onAfterFsync?.(tempPath);
426
+ try {
427
+ renameSync(tempPath, targetPath);
428
+ }
429
+ catch (err) {
430
+ cleanupTemp();
431
+ return { ok: false, reason: `could not rename the staging file into place: ${msg(err)}` };
432
+ }
433
+ let cleanupWarning = null;
434
+ try {
435
+ const dfd = openSync(dir, "r");
436
+ try {
437
+ fsyncSync(dfd);
438
+ }
439
+ finally {
440
+ try {
441
+ closeSync(dfd);
442
+ }
443
+ catch { /* */ }
444
+ }
445
+ }
446
+ catch (err) {
447
+ cleanupWarning = `the replacement is committed but the directory fsync failed: ${msg(err)}`;
448
+ }
449
+ return { ok: true, cleanupWarning };
450
+ }
451
+ // ── the primitive ───────────────────────────────────────────────────────────
452
+ /**
453
+ * Observe → lock → re-observe → read → decide → write, as ONE critical
454
+ * section. See the module docblock for the full contract.
455
+ */
456
+ export function withConfigCriticalSection(configPath, decide, opts = {}) {
457
+ const maxAttempts = Math.max(1, opts.maxAttempts ?? 3);
458
+ const lockRetry = { attempts: opts.lockRetry?.attempts ?? 40, delayMs: opts.lockRetry?.delayMs ?? 50 };
459
+ let attempts = 0;
460
+ let lastHold = null;
461
+ for (let attempt = 1; attempt <= maxAttempts; attempt++) {
462
+ attempts = attempt;
463
+ // 1. OBSERVE (before the lock).
464
+ const pre = observeConfig(configPath);
465
+ if (!pre.ok) {
466
+ return { status: "held", path: configPath, attempts, message: pre.reason };
467
+ }
468
+ const preObs = pre.value;
469
+ const targetPath = resolvedTargetPath(preObs, configPath);
470
+ barrier(opts.testHooks?.afterPreObserve, "preObserve", attempt);
471
+ // 2. LOCK (computed once per attempt).
472
+ const lockPath = `${targetPath}.lock`;
473
+ const lock = acquireLock(lockPath, lockRetry);
474
+ if (!lock.ok) {
475
+ return { status: "refused", path: targetPath, attempts, message: lockRefusalLine(lockPath, lock.holder) };
476
+ }
477
+ try {
478
+ // 3. RE-OBSERVE inside the lock.
479
+ const inLock = observeConfig(configPath);
480
+ if (!inLock.ok) {
481
+ return { status: "held", path: targetPath, attempts, message: `held: ${inLock.reason} — nothing written.` };
482
+ }
483
+ const obs = inLock.value;
484
+ const changed = compareObservation(preObs, obs);
485
+ if (changed) {
486
+ const retryable = changed === "target-identity" &&
487
+ obs.entry.type === preObs.entry.type &&
488
+ obs.target.type === "regular";
489
+ const line = heldLine(changed);
490
+ if (retryable && attempt < maxAttempts) {
491
+ lastHold = { status: "held", path: targetPath, attempts, message: line, changed };
492
+ continue; // fresh attempt: re-observe from scratch
493
+ }
494
+ return { status: "held", path: targetPath, attempts, message: line, changed };
495
+ }
496
+ if (obs.target.type === "other") {
497
+ return { status: "refused", path: targetPath, attempts, message: `the destination ${targetPath} is not a regular file; refusing to write it.` };
498
+ }
499
+ // 4. READ inside the lock.
500
+ let bytes = null;
501
+ if (obs.target.type === "regular") {
502
+ try {
503
+ bytes = readFileSync(obs.target.path);
504
+ }
505
+ catch (err) {
506
+ return { status: "held", path: targetPath, attempts, message: `held: could not read ${obs.target.path}: ${msg(err)} — nothing written.` };
507
+ }
508
+ }
509
+ // Backup on the IN-LOCK bytes, before decide. A failure short-circuits.
510
+ let backupPath = null;
511
+ if (opts.backup && bytes !== null) {
512
+ try {
513
+ const r = opts.backup(bytes);
514
+ backupPath = typeof r === "string" ? r : null;
515
+ }
516
+ catch (err) {
517
+ return { status: "refused", path: targetPath, attempts, message: `backup failed before deciding: ${msg(err)} — nothing written.` };
518
+ }
519
+ }
520
+ barrier(opts.testHooks?.afterRead, "read", attempt);
521
+ const decision = decide(bytes, obs);
522
+ if ("hold" in decision) {
523
+ return { status: "held", path: targetPath, attempts, message: decision.hold, backupPath };
524
+ }
525
+ if ("noop" in decision) {
526
+ return { status: "noop", path: targetPath, attempts, message: decision.noop, backupPath };
527
+ }
528
+ // 5. WRITE.
529
+ const original = obs.target.type === "regular"
530
+ ? { mode: obs.target.mode, uid: obs.target.uid, gid: obs.target.gid }
531
+ : null;
532
+ const wr = atomicReplace(targetPath, decision.write, original, opts.testHooks?.afterTempCreate, opts.testHooks?.afterFsync);
533
+ if (!wr.ok) {
534
+ return { status: "refused", path: targetPath, attempts, message: `nothing written: ${wr.reason}`, backupPath };
535
+ }
536
+ return {
537
+ status: "written",
538
+ path: targetPath,
539
+ attempts,
540
+ message: "",
541
+ backupPath,
542
+ committed: true,
543
+ cleanupWarning: wr.cleanupWarning,
544
+ };
545
+ }
546
+ finally {
547
+ // 6. RELEASE in finally, including when decide() throws.
548
+ releaseLock(lockPath);
549
+ }
550
+ }
551
+ return lastHold ?? {
552
+ status: "held",
553
+ path: configPath,
554
+ attempts,
555
+ message: `held: the destination changed on every one of ${maxAttempts} attempts — nothing written.`,
556
+ };
557
+ }