benignswarm 0.12.122 → 0.12.124

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,236 @@
1
+ import { chmodSync, closeSync, existsSync, fstatSync, linkSync, lstatSync, mkdirSync, openSync, readFileSync, readlinkSync, realpathSync, renameSync, rmSync, statSync, writeFileSync, writeSync } from "node:fs";
2
+ import { randomBytes } from "node:crypto";
3
+ import { dirname, resolve } from "node:path";
4
+ import { CliError } from "./errors.js";
5
+ /**
6
+ * Files that several b9s processes on one machine read and write at the same moment: watchers,
7
+ * harness hooks, the machine daemon and the agents' own commands (about forty agents on one host).
8
+ * Two things go wrong with a plain read, change, `writeFileSync`:
9
+ *
10
+ * - a torn read: `writeFileSync` truncates first, so a reader in that instant sees an empty or
11
+ * half-written file (four sessions failed with "not valid JSON" when 39 starts bound their
12
+ * threads at once, 2026-11-18);
13
+ * - a lost update: two processes read the same version, each adds its own change, and the second
14
+ * write discards the first.
15
+ *
16
+ * `writeFileAtomic` ends the first (written beside the file, then renamed over it). `updateJsonFile`
17
+ * and `updateTextFile` end the second: one writer at a time, and the file is read again inside the
18
+ * lock, so a change is always applied to what is on disk now. The locked section is synchronous by
19
+ * construction; a lock is never held across a network call or a child process.
20
+ */
21
+ /** A lock older than this belongs to a process that died inside its (millisecond) locked section. */
22
+ const STALE_MS = 30_000;
23
+ /** How long a writer waits for the lock before it fails. It never writes without it. */
24
+ const WAIT_MS = 10_000;
25
+ const POLL_MS = 25;
26
+ /** The file a write must land in: the path itself, or what it links to (a hooks.json kept in a dotfiles repo stays a link). */
27
+ function writeTarget(path) {
28
+ let link = false;
29
+ try {
30
+ link = lstatSync(path).isSymbolicLink();
31
+ }
32
+ catch (error) {
33
+ if (error.code !== "ENOENT")
34
+ throw error;
35
+ }
36
+ if (!link)
37
+ return path;
38
+ try {
39
+ return realpathSync(path);
40
+ }
41
+ catch (error) {
42
+ if (error.code !== "ENOENT")
43
+ throw error;
44
+ return resolve(dirname(path), readlinkSync(path)); // a link to a file that does not exist yet
45
+ }
46
+ }
47
+ /**
48
+ * Replaces `path` with `data` in one step: readers see the old file or the new one, never a part.
49
+ * A failed write throws, removes its temporary file and leaves the previous file whole. Without
50
+ * `mode` an existing file keeps its permissions.
51
+ */
52
+ export function writeFileAtomic(path, data, opts = {}) {
53
+ const target = writeTarget(path);
54
+ mkdirSync(dirname(target), { recursive: true });
55
+ let mode = opts.mode;
56
+ if (mode === undefined) {
57
+ try {
58
+ mode = statSync(target).mode & 0o777;
59
+ }
60
+ catch (error) {
61
+ if (error.code !== "ENOENT")
62
+ throw error;
63
+ }
64
+ }
65
+ // The pid alone is not unique: containers sharing one mounted config folder each have their own pid 7.
66
+ const tmp = `${target}.${process.pid}.${randomBytes(4).toString("hex")}.tmp`;
67
+ try {
68
+ writeFileSync(tmp, data, mode === undefined ? {} : { mode });
69
+ if (mode !== undefined)
70
+ chmodSync(tmp, mode); // the mode given to open is cut by the umask
71
+ renameSync(tmp, target);
72
+ }
73
+ catch (error) {
74
+ rmSync(tmp, { force: true });
75
+ throw error;
76
+ }
77
+ }
78
+ function sleep(ms) {
79
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
80
+ }
81
+ /**
82
+ * Takes a stale lock out of the way. The rename has one winner among the waiters that saw the same
83
+ * dead lock. A waiter that judged the old lock stale and then renamed a live one that replaced it
84
+ * in between puts that one back.
85
+ */
86
+ function removeStaleLock(lock) {
87
+ const stolen = `${lock}.${process.pid}.${randomBytes(4).toString("hex")}.stale`;
88
+ try {
89
+ renameSync(lock, stolen);
90
+ }
91
+ catch (error) {
92
+ if (error.code === "ENOENT")
93
+ return;
94
+ throw error;
95
+ }
96
+ try {
97
+ if (Date.now() - statSync(stolen).mtimeMs <= STALE_MS) {
98
+ try {
99
+ linkSync(stolen, lock);
100
+ }
101
+ catch (error) {
102
+ if (error.code !== "EEXIST")
103
+ throw error;
104
+ }
105
+ }
106
+ }
107
+ finally {
108
+ rmSync(stolen, { force: true });
109
+ }
110
+ }
111
+ /**
112
+ * Runs `run` while holding `<path>.lock` (an exclusive create). `run` must be synchronous. Not
113
+ * getting the lock within ten seconds is an error naming the file: the caller never proceeds
114
+ * unlocked. A lock left by a dead process is taken over after 30 s.
115
+ */
116
+ export function withFileLock(path, run, opts = {}) {
117
+ const lock = `${path}.lock`;
118
+ mkdirSync(dirname(lock), { recursive: true });
119
+ const deadline = Date.now() + (opts.waitMs ?? WAIT_MS);
120
+ let mine;
121
+ for (let attempt = 0;; attempt++) {
122
+ let fd;
123
+ try {
124
+ fd = openSync(lock, "wx");
125
+ }
126
+ catch (error) {
127
+ if (error.code !== "EEXIST")
128
+ throw error;
129
+ let age;
130
+ try {
131
+ age = Date.now() - statSync(lock).mtimeMs;
132
+ }
133
+ catch (statError) {
134
+ if (statError.code === "ENOENT")
135
+ continue; // released just now
136
+ throw statError;
137
+ }
138
+ if (age > STALE_MS) {
139
+ removeStaleLock(lock);
140
+ continue;
141
+ }
142
+ if (Date.now() > deadline) {
143
+ let holder = "";
144
+ try {
145
+ holder = readFileSync(lock, "utf8").trim();
146
+ }
147
+ catch { /* released between the two looks; the wait still ran out */ }
148
+ throw new CliError(opts.busyCode ?? "file_busy", `${path} is locked by another b9s process${/^\d+$/.test(holder) ? ` (pid ${holder})` : ""}; nothing was written`, "Retry in a moment");
149
+ }
150
+ // Short waits first: the holder is inside a read and a rename, which take well under a millisecond.
151
+ sleep(Math.min(POLL_MS, 1 + attempt * 2));
152
+ continue;
153
+ }
154
+ try {
155
+ writeSync(fd, String(process.pid)); // who holds it, for the error another process reports
156
+ const st = fstatSync(fd);
157
+ mine = { ino: st.ino, mtimeMs: st.mtimeMs };
158
+ }
159
+ catch (error) {
160
+ rmSync(lock, { force: true }); // a lock we could not finish making is not left behind
161
+ throw error;
162
+ }
163
+ finally {
164
+ closeSync(fd);
165
+ }
166
+ break;
167
+ }
168
+ try {
169
+ const result = run();
170
+ if (result instanceof Promise)
171
+ throw new Error(`withFileLock(${path}): the locked section must be synchronous`);
172
+ return result;
173
+ }
174
+ finally {
175
+ // Only our own lock: one taken over as stale (this process was suspended) now belongs to someone else.
176
+ try {
177
+ const st = statSync(lock);
178
+ if (st.ino === mine.ino && st.mtimeMs === mine.mtimeMs)
179
+ rmSync(lock, { force: true });
180
+ }
181
+ catch (error) {
182
+ if (error.code !== "ENOENT")
183
+ throw error;
184
+ }
185
+ }
186
+ }
187
+ /**
188
+ * Changes a text file under its lock: `change` gets the text on disk now (null when there is no
189
+ * file) and returns the new text, or null to leave the file alone. Returns what the file holds.
190
+ */
191
+ export function updateTextFile(path, change, opts = {}) {
192
+ const target = writeTarget(path);
193
+ return withFileLock(target, () => {
194
+ const current = existsSync(target) ? readFileSync(target, "utf8") : null;
195
+ const next = change(current);
196
+ if (next === null || next === current)
197
+ return current;
198
+ writeFileAtomic(target, next, opts.mode === undefined ? {} : { mode: opts.mode });
199
+ return next;
200
+ }, opts);
201
+ }
202
+ const prettyJson = (value) => JSON.stringify(value, null, 2) + "\n";
203
+ /** The JSON a file holds, or undefined when there is no file. A file that does not parse is refused by name. */
204
+ export function readJsonFile(path, corrupt) {
205
+ let text;
206
+ try {
207
+ text = readFileSync(path, "utf8");
208
+ }
209
+ catch (error) {
210
+ if (error.code === "ENOENT")
211
+ return undefined;
212
+ throw error;
213
+ }
214
+ try {
215
+ return JSON.parse(text);
216
+ }
217
+ catch {
218
+ throw corrupt ? corrupt(path, text) : new CliError("corrupt_file", `${path} is not valid JSON (${text.length} bytes)`, "Repair it or move it aside");
219
+ }
220
+ }
221
+ /**
222
+ * Changes a JSON file under its lock. `change` gets the value on disk now (undefined when there is
223
+ * no file), read inside the lock, and returns the value to write, or undefined to leave the file
224
+ * alone. Returns what the file holds afterwards.
225
+ */
226
+ export function updateJsonFile(path, change, opts = {}) {
227
+ const target = writeTarget(path);
228
+ return withFileLock(target, () => {
229
+ const current = readJsonFile(target, opts.corrupt);
230
+ const next = change(current);
231
+ if (next === undefined)
232
+ return current;
233
+ writeFileAtomic(target, (opts.serialize ?? prettyJson)(next), opts.mode === undefined ? {} : { mode: opts.mode });
234
+ return next;
235
+ }, opts);
236
+ }
package/dist/state.js CHANGED
@@ -1,7 +1,8 @@
1
- import { existsSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs";
1
+ import { existsSync, mkdirSync, readFileSync, renameSync } from "node:fs";
2
2
  import { CliError } from "./errors.js";
3
3
  import { join } from "node:path";
4
4
  import { configRoot, isRef, splitRef } from "./config.js";
5
+ import { withFileLock, writeFileAtomic } from "./shared-file.js";
5
6
  /** State is keyed by agent ref (`<scope>/<name>`), like credentials. */
6
7
  export function stateFilePath(ref, env = process.env) {
7
8
  const { scope, name } = splitRef(ref);
@@ -37,21 +38,39 @@ export function readState(ref, env = process.env) {
37
38
  delete current.machine_pressure_notice;
38
39
  return { inbox_after: "", last_check: 0, ...current };
39
40
  }
40
- export function writeState(agent, state, env = process.env) {
41
+ /**
42
+ * Changes this agent's state: `change` gets the state on disk now, read inside the file's lock, and
43
+ * returns the state to write (or nothing, to leave the file alone). Returns the state afterwards.
44
+ *
45
+ * The watcher, the harness hook, the machine daemon and the agent's own commands all write this
46
+ * one file, usually around a network call. Reading it, waiting, then writing the copy back
47
+ * discarded whatever another of them wrote meanwhile: a read cursor, an acknowledgement, the turn
48
+ * guard. So `change` must be the small change itself, applied to what it is given, never a copy
49
+ * read earlier; and it is synchronous, so the lock is never held across a server call or a turn.
50
+ * Failing to get the lock is `state_busy`, never an unlocked write.
51
+ */
52
+ export function updateState(agent, change, env = process.env) {
41
53
  const p = stateFilePath(agent, env);
42
54
  mkdirSync(join(p, ".."), { recursive: true });
43
- // Written beside it and renamed over it: a full disk once truncated three agents' files to 0
44
- // bytes mid-write, and their watchers failed on every start for 17 hours. A failed write now
45
- // throws and leaves the previous file whole.
46
- const tmp = `${p}.${process.pid}.tmp`;
47
- try {
48
- writeFileSync(tmp, JSON.stringify(state, null, 2) + "\n", { mode: 0o600 });
49
- renameSync(tmp, p);
50
- }
51
- catch (e) {
52
- rmSync(tmp, { force: true });
53
- throw e;
54
- }
55
+ return withFileLock(p, () => {
56
+ const current = readState(agent, env);
57
+ const next = change(current);
58
+ if (!next)
59
+ return current;
60
+ // Written beside it and renamed over it: a full disk once truncated three agents' files to 0
61
+ // bytes mid-write, and their watchers failed on every start for 17 hours. A failed write now
62
+ // throws and leaves the previous file whole.
63
+ writeFileAtomic(p, JSON.stringify(next, null, 2) + "\n", { mode: 0o600 });
64
+ return next;
65
+ }, { busyCode: "state_busy" });
66
+ }
67
+ /**
68
+ * Replaces the whole state file (first set-up, tests). Anything that changes a field of a state
69
+ * another process may also be writing uses updateState instead: a copy read earlier and written
70
+ * back here discards what was written in between.
71
+ */
72
+ export function writeState(agent, state, env = process.env) {
73
+ updateState(agent, () => state, env);
55
74
  }
56
75
  /** Refuse a move when the destination has made newer monotonic progress than the source copy. */
57
76
  export function destinationStateIsNewer(source, destination) {
package/dist/version.js CHANGED
@@ -1 +1 @@
1
- export const CLI_VERSION = "0.12.122";
1
+ export const CLI_VERSION = "0.12.124";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "benignswarm",
3
- "version": "0.12.122",
3
+ "version": "0.12.124",
4
4
  "description": "b9s: chat, status board and evidence store for coding agents (benignswarm.org)",
5
5
  "license": "UNLICENSED",
6
6
  "repository": {