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.
package/dist/harness.js CHANGED
@@ -1,4 +1,5 @@
1
1
  import { existsSync, mkdirSync, readFileSync, rmSync, statSync, writeFileSync } from "node:fs";
2
+ import { updateJsonFile, updateTextFile } from "./shared-file.js";
2
3
  import { shellPath } from "./install.js";
3
4
  import { homedir } from "node:os";
4
5
  import { basename, dirname, join } from "node:path";
@@ -58,30 +59,35 @@ export function findIdentityFile(start = process.cwd()) {
58
59
  dir = parent;
59
60
  }
60
61
  }
61
- export function readIdentityFile(path) {
62
- const raw = JSON.parse(readFileSync(path, "utf8"));
62
+ function asIdentityFile(path, raw) {
63
63
  if (!raw.agents || typeof raw.agents !== "object")
64
64
  throw new CliError("bad_identity_file", `${path} is not a b9s identity file`);
65
65
  return raw;
66
66
  }
67
+ export function readIdentityFile(path) {
68
+ return asIdentityFile(path, JSON.parse(readFileSync(path, "utf8")));
69
+ }
70
+ /** A settings file b9s shares with the harness and with other agents' joins: refused when it does not parse, never rewritten from empty. */
71
+ const badSettings = (path) => new CliError("bad_settings", `${path} is not valid JSON; fix it or remove it`);
67
72
  /**
68
73
  * Records which agent name a given vendor uses in this repo. Refuses to silently replace an
69
74
  * existing different name: two agents of one vendor in one worktree must use BSCHAT_AGENT.
70
75
  */
71
76
  export function writeIdentity(root, vendor, name, model, replace, project) {
72
77
  const p = join(repoDirectory(root), "identity.json");
73
- let file = { agents: {} };
74
- if (existsSync(p))
75
- file = readIdentityFile(p);
76
- const existing = file.agents[vendor];
77
- if (existing && existing.name !== name && !replace) {
78
- if (vendor === "claude-code")
79
- throw claudeCheckoutTaken(root, existing.project ? `${existing.project}/${existing.name}` : existing.name, name);
80
- throw new CliError("identity_exists", `${p} already maps ${vendor} to agent "${existing.name}"`, `Two ${vendor} agents share this checkout. Use --no-bind (join) and address yourself per call with --as ${name}, or --replace to make "${name}" the default here.`);
81
- }
82
- file.agents[vendor] = { name, project, ...(model ? { model } : {}) };
83
- mkdirSync(dirname(p), { recursive: true });
84
- writeFileSync(p, JSON.stringify(file, null, 2) + "\n");
78
+ // Read, checked and written under the file's lock: agents of different vendors join one checkout
79
+ // at the same moment, and each adds its own entry to this one file.
80
+ updateJsonFile(p, (raw) => {
81
+ const file = raw === undefined ? { agents: {} } : asIdentityFile(p, raw);
82
+ const existing = file.agents[vendor];
83
+ if (existing && existing.name !== name && !replace) {
84
+ if (vendor === "claude-code")
85
+ throw claudeCheckoutTaken(root, existing.project ? `${existing.project}/${existing.name}` : existing.name, name);
86
+ throw new CliError("identity_exists", `${p} already maps ${vendor} to agent "${existing.name}"`, `Two ${vendor} agents share this checkout. Use --no-bind (join) and address yourself per call with --as ${name}, or --replace to make "${name}" the default here.`);
87
+ }
88
+ file.agents[vendor] = { name, project, ...(model ? { model } : {}) };
89
+ return file;
90
+ }, { corrupt: (path) => new CliError("bad_identity_file", `${path} is not valid JSON`, "Fix it or remove it, then join again") });
85
91
  ensureGitignore(root, [".b9s/", ".bschat/", ".claude/settings.local.json"]);
86
92
  return p;
87
93
  }
@@ -89,30 +95,30 @@ export function ensureGitignore(root, entries) {
89
95
  if (!existsSync(join(root, ".git")))
90
96
  return;
91
97
  const p = join(root, ".gitignore");
92
- const current = existsSync(p) ? readFileSync(p, "utf8") : "";
93
- const lines = current.split("\n");
94
- const missing = entries.filter((e) => !lines.includes(e));
95
- if (!missing.length)
96
- return;
97
- writeFileSync(p, (current.endsWith("\n") || current === "" ? current : current + "\n") + "# b9s (per-machine agent identity)\n" + missing.join("\n") + "\n");
98
+ updateTextFile(p, (text) => {
99
+ const current = text ?? "";
100
+ const lines = current.split("\n");
101
+ const missing = entries.filter((e) => !lines.includes(e));
102
+ if (!missing.length)
103
+ return null;
104
+ return (current.endsWith("\n") || current === "" ? current : current + "\n") + "# b9s (per-machine agent identity)\n" + missing.join("\n") + "\n";
105
+ });
98
106
  }
99
107
  const START = "<!-- bschat:start -->";
100
108
  const END = "<!-- bschat:end -->";
101
109
  /** Replaces or appends a marked block in a markdown file. Idempotent. */
102
110
  export function upsertBlock(path, body) {
103
111
  const block = `${START}\n${body.trim()}\n${END}\n`;
104
- if (!existsSync(path)) {
105
- mkdirSync(dirname(path), { recursive: true });
106
- writeFileSync(path, block);
107
- return;
108
- }
109
- const cur = readFileSync(path, "utf8");
110
- const s = cur.indexOf(START);
111
- const e = cur.indexOf(END);
112
- if (s >= 0 && e > s)
113
- writeFileSync(path, cur.slice(0, s) + block + cur.slice(e + END.length).replace(/^\n/, ""));
114
- else
115
- writeFileSync(path, (cur.endsWith("\n") || cur === "" ? cur : cur + "\n") + "\n" + block);
112
+ // AGENTS.md and GEMINI.md are the project's own files, edited by every agent's join in the checkout.
113
+ updateTextFile(path, (cur) => {
114
+ if (cur === null)
115
+ return block;
116
+ const s = cur.indexOf(START);
117
+ const e = cur.indexOf(END);
118
+ if (s >= 0 && e > s)
119
+ return cur.slice(0, s) + block + cur.slice(e + END.length).replace(/^\n/, "");
120
+ return (cur.endsWith("\n") || cur === "" ? cur : cur + "\n") + "\n" + block;
121
+ });
116
122
  }
117
123
  /**
118
124
  * The section join writes into AGENTS.md / GEMINI.md. Those files are usually committed and read on
@@ -160,18 +166,11 @@ export function installForHarness(root, harness, files, agentName, apiUrl, bin)
160
166
  written.push(join(dir, "SKILL.md"));
161
167
  rmSync(join(root, ".claude", "skills", "bschat"), { recursive: true, force: true });
162
168
  const sp = join(root, ".claude", "settings.local.json");
163
- let settings = {};
164
- if (existsSync(sp)) {
165
- try {
166
- settings = JSON.parse(readFileSync(sp, "utf8"));
167
- }
168
- catch {
169
- throw new CliError("bad_settings", `${sp} is not valid JSON; fix it or remove it`);
170
- }
171
- }
172
- const env = { ...(settings.env ?? {}), BSCHAT_AGENT: agentName };
173
- const hooks = withBschatHooks(settings.hooks ?? {}, bin);
174
- writeFileSync(sp, JSON.stringify({ ...settings, env, hooks }, null, 2) + "\n");
169
+ updateJsonFile(sp, (settings = {}) => {
170
+ const env = { ...(settings.env ?? {}), BSCHAT_AGENT: agentName };
171
+ const hooks = withBschatHooks(settings.hooks ?? {}, bin);
172
+ return { ...settings, env, hooks };
173
+ }, { corrupt: badSettings });
175
174
  written.push(sp);
176
175
  break;
177
176
  }
@@ -191,16 +190,8 @@ export function installForHarness(root, harness, files, agentName, apiUrl, bin)
191
190
  writeFileSync(p, `---\ntrigger: always_on\ndescription: "How to use b9s, the agent chat for this project"\n---\n\n${pointer(agentName, apiUrl, bin)}\n`);
192
191
  written.push(p);
193
192
  const hp = join(root, ".agents", "hooks.json");
194
- let hooks = {};
195
- if (existsSync(hp)) {
196
- try {
197
- hooks = JSON.parse(readFileSync(hp, "utf8"));
198
- }
199
- catch {
200
- throw new CliError("bad_settings", `${hp} is not valid JSON; fix it or remove it`);
201
- }
202
- }
203
- writeFileSync(hp, JSON.stringify({ ...hooks, bschat: antigravityHooks(bin) }, null, 2) + "\n");
193
+ // Several Antigravity agents share a workspace and join it together.
194
+ updateJsonFile(hp, (hooks = {}) => ({ ...hooks, bschat: antigravityHooks(bin) }), { corrupt: badSettings });
204
195
  written.push(hp);
205
196
  break;
206
197
  }
@@ -220,49 +211,37 @@ export function refreshInstalledHooks(root, bin, requirementsPath = CODEX_REQUIR
220
211
  const written = [];
221
212
  const claude = join(root, ".claude", "settings.local.json");
222
213
  if (existsSync(claude)) {
223
- let settings;
224
- try {
225
- settings = JSON.parse(readFileSync(claude, "utf8"));
226
- }
227
- catch {
228
- throw new CliError("bad_settings", `${claude} is not valid JSON; fix it or remove it`);
229
- }
230
- const hooks = withBschatHooks(settings.hooks ?? {}, bin);
231
- writeFileSync(claude, JSON.stringify({ ...settings, hooks }, null, 2) + "\n");
232
- written.push(claude);
214
+ // A file removed since the look above stays removed (undefined leaves it alone).
215
+ const now = updateJsonFile(claude, (settings) => settings && { ...settings, hooks: withBschatHooks(settings.hooks ?? {}, bin) }, { corrupt: badSettings });
216
+ if (now)
217
+ written.push(claude);
233
218
  }
234
219
  const codex = join(process.env.CODEX_HOME ?? join(homedir(), ".codex"), "hooks.json");
235
220
  if (existsSync(codex)) {
236
- let settings;
237
- try {
238
- settings = JSON.parse(readFileSync(codex, "utf8"));
239
- }
240
- catch {
241
- throw new CliError("bad_settings", `${codex} is not valid JSON; fix it or remove it`);
242
- }
243
- if (codexManagedPolicyInstalled(requirementsPath)) {
244
- const cleaned = removeCodexHooks(settings);
245
- if (JSON.stringify(cleaned) !== JSON.stringify(settings)) {
246
- writeFileSync(codex, JSON.stringify(cleaned, null, 2) + "\n");
247
- written.push(codex);
221
+ // One hooks.json per machine: every Codex agent's start and refresh on the host edits it.
222
+ const managed = codexManagedPolicyInstalled(requirementsPath);
223
+ let changed = false;
224
+ updateJsonFile(codex, (settings) => {
225
+ if (!settings)
226
+ return undefined;
227
+ if (!managed) {
228
+ changed = true;
229
+ return withCodexHooks(settings, bin);
248
230
  }
249
- }
250
- else {
251
- writeFileSync(codex, JSON.stringify(withCodexHooks(settings, bin), null, 2) + "\n");
231
+ const cleaned = removeCodexHooks(settings);
232
+ if (JSON.stringify(cleaned) === JSON.stringify(settings))
233
+ return undefined;
234
+ changed = true;
235
+ return cleaned;
236
+ }, { corrupt: badSettings });
237
+ if (changed)
252
238
  written.push(codex);
253
- }
254
239
  }
255
240
  const antigravity = join(root, ".agents", "hooks.json");
256
241
  if (existsSync(antigravity)) {
257
- let settings;
258
- try {
259
- settings = JSON.parse(readFileSync(antigravity, "utf8"));
260
- }
261
- catch {
262
- throw new CliError("bad_settings", `${antigravity} is not valid JSON; fix it or remove it`);
263
- }
264
- writeFileSync(antigravity, JSON.stringify({ ...settings, bschat: antigravityHooks(bin) }, null, 2) + "\n");
265
- written.push(antigravity);
242
+ const now = updateJsonFile(antigravity, (settings) => settings && { ...settings, bschat: antigravityHooks(bin) }, { corrupt: badSettings });
243
+ if (now)
244
+ written.push(antigravity);
266
245
  }
267
246
  return written;
268
247
  }
@@ -383,25 +362,29 @@ export function reconcileCodexHooks(bin, registerIfUnmanaged, requirementsPath =
383
362
  const path = join(process.env.CODEX_HOME ?? join(homedir(), ".codex"), "hooks.json");
384
363
  if (!managed && !registerIfUnmanaged)
385
364
  return { managed, path: null, changed: false };
386
- let settings = {};
387
- if (existsSync(path)) {
388
- try {
389
- settings = JSON.parse(readFileSync(path, "utf8"));
365
+ // Managed and nothing of ours to remove: no file is made, and no folder for its lock.
366
+ if (managed && !existsSync(path))
367
+ return { managed, path, changed: false };
368
+ // Decided on the file as it is inside its lock: a fleet restart runs this once per Codex agent,
369
+ // all at the same moment, on the machine's one hooks.json.
370
+ let result = { managed, path, changed: false };
371
+ updateJsonFile(path, (onDisk) => {
372
+ const settings = onDisk ?? {};
373
+ const next = managed ? removeCodexHooks(settings) : withCodexHooks(settings, bin);
374
+ const before = JSON.stringify(settings);
375
+ const after = JSON.stringify(next);
376
+ if (managed && before === after) {
377
+ result = { managed, path, changed: false };
378
+ return undefined;
390
379
  }
391
- catch {
392
- throw new CliError("bad_settings", `${path} is not valid JSON; fix it or remove it`);
380
+ if (managed && onDisk === undefined) {
381
+ result = { managed, path: null, changed: false };
382
+ return undefined;
393
383
  }
394
- }
395
- const next = managed ? removeCodexHooks(settings) : withCodexHooks(settings, bin);
396
- const before = JSON.stringify(settings);
397
- const after = JSON.stringify(next);
398
- if (managed && before === after)
399
- return { managed, path, changed: false };
400
- if (managed && !existsSync(path))
401
- return { managed, path: null, changed: false };
402
- mkdirSync(dirname(path), { recursive: true });
403
- writeFileSync(path, JSON.stringify(next, null, 2) + "\n");
404
- return { managed, path, changed: before !== after };
384
+ result = { managed, path, changed: before !== after };
385
+ return next;
386
+ }, { corrupt: badSettings });
387
+ return result;
405
388
  }
406
389
  /**
407
390
  * Merges b9s's hooks into a Codex hooks.json document ({"hooks": {Event: [groups]}}): any
package/dist/harnesses.js CHANGED
@@ -4,7 +4,7 @@ import { homedir } from "node:os";
4
4
  import { dirname, join } from "node:path";
5
5
  import { CliError } from "./errors.js";
6
6
  import { configRoot } from "./config.js";
7
- import { readState, writeState } from "./state.js";
7
+ import { readState, updateState } from "./state.js";
8
8
  import { codexArchivedRollout, codexRollout } from "./sessions.js";
9
9
  import { readTurnPhase, usageLimitUntil } from "./turn.js";
10
10
  import { FileFactsCache, scanLinesBackward, TAIL_CHUNK_BYTES, TAIL_MAX_BYTES } from "./tail-lines.js";
@@ -314,10 +314,13 @@ export function dshProbe(session, ref, path = dshTurnLog(ref), processes) {
314
314
  },
315
315
  beginTurn() {
316
316
  invocationOffset = existsSync(path) ? statSync(path).size : 0;
317
- const state = readState(ref);
318
- if (state.harness_session?.initial_pid) {
319
- const { initial_pid: _initialPid, ...session } = state.harness_session;
320
- writeState(ref, { ...state, harness_session: session });
317
+ if (readState(ref).harness_session?.initial_pid) {
318
+ updateState(ref, (onDisk) => {
319
+ if (!onDisk.harness_session?.initial_pid)
320
+ return undefined;
321
+ const { initial_pid: _initialPid, ...session } = onDisk.harness_session;
322
+ return { ...onDisk, harness_session: session };
323
+ });
321
324
  }
322
325
  },
323
326
  startedSince() { return dshEvents(readInvocation(invocationOffset)).some((e) => e.type === "status" && e.phase === "turn_start"); },
package/dist/help.js CHANGED
@@ -84,6 +84,7 @@ Agent commands
84
84
  b9s wu assign <n> --to <agent> [--reason "why"] reassign an assigned or queued unit in place
85
85
  b9s wu lands-with <n> <base-unit|clear> set or clear the base WU whose landing gates this unit
86
86
  b9s wu priority <n> urgent|normal --note "why this priority changed" operator or assigner: change dispatch priority; urgent work is dispatched first
87
+ b9s wu expedite <n> operator or assigner: interrupt a qualified, wakeable worker for an urgent unit; their current unit resumes when this one is submitted
87
88
  b9s wu take <n> [--to <agent>] [--reason "why"] pull a unit or hand it to someone
88
89
  reason is required when an assigner uses its assign_outside_qualifications role capability
89
90
  b9s wu next take the oldest queued unit you qualify for
@@ -127,8 +128,10 @@ Agent commands
127
128
  acquisition queues through a machine maintenance drain/window and resumes after it
128
129
  machine identity is this host's hostname plus its registered label, shared by all agents here
129
130
  save the returned job token; reuse --token to check/retry the same job
130
- b9s lock run <name> [--unit n] [--note ..] [--shared] -- <command> wait for <name>, run the command, release when it ends (pass, fail or interrupt); exits with the command's code
131
- b9s unlock <name> [--job <id> | --token <job-token>] [--machine <label>|--shared] | b9s locks on the machine that took it the job's token is kept for you
131
+ b9s lock run <name> [--unit n] [--note ..] [--shared] -- <command> poll until granted, run the command, then release; exits with its code
132
+ polls every 15s; stale waiters are skipped after 60s with a process notice; later polls reap unreported holders idle 60s
133
+ b9s locks shows waiter poll age; reported-command holders do not expire
134
+ b9s unlock <name> [--job <id> | --token <job-token>] [--machine <label>|--shared] | b9s locks shows lock-run waiters' last-poll age; on this host the job token is kept for you
132
135
  b9s unlock <name> --remove-empty [--machine <label>|--shared]
133
136
  new agent jobs release by token; legacy jobs retain identity release; assigners/operators may release without a token
134
137
  closing a unit does not release a new job's lock
@@ -474,6 +477,7 @@ Pools (fixed or adaptive; the server names the agents and places them on machine
474
477
  [--quota-substitution | --no-quota-substitution] allows another eligible variant after authoritative quota exhaustion
475
478
  pool writes first show a server impact preview; confirm a fresh revision with --impact-revision <revision>
476
479
  b9s-admin pool list [project] | show <project>/<name> | events <project>/<name> [--limit 1..100]
480
+ Console → Pools shows account/project placement, slot work/session state, and machine headroom
477
481
  b9s-admin pool pause|resume <project>/<name> [--reason <text>] pause only automatic scaling; sessions keep running
478
482
  b9s-admin pool pin <project>/<name> <slot> --machine <name> [--until <ISO>] [--reason <text>] | unpin <project>/<name> <slot>
479
483
  b9s-admin pool suspend|restore <project>/<name> <slot> [--reason <text>] [--note <text>] suspend keeps the same slot and does not create a replacement
package/dist/install.js CHANGED
@@ -4,6 +4,7 @@ import { homedir, totalmem, userInfo } from "node:os";
4
4
  import { basename, delimiter, dirname, join, resolve } from "node:path";
5
5
  import { configRoot } from "./config.js";
6
6
  import { CliError } from "./errors.js";
7
+ import { writeFileAtomic } from "./shared-file.js";
7
8
  import { cmp } from "./update.js";
8
9
  import { CLI_VERSION } from "./version.js";
9
10
  import { watcherMemoryLimits } from "./watcher-memory.js";
@@ -72,9 +73,7 @@ export function provisionContainerInstallRecord(pathEnv = process.env.PATH ?? ""
72
73
  version: CLI_VERSION,
73
74
  installed_at: new Date().toISOString(),
74
75
  };
75
- const file = installFile();
76
- mkdirSync(dirname(file), { recursive: true });
77
- writeFileSync(file, JSON.stringify(record, null, 2) + "\n");
76
+ writeFileAtomic(installFile(), JSON.stringify(record, null, 2) + "\n");
78
77
  return requireInstall();
79
78
  }
80
79
  /** Build the environment installed for the machine daemon and used by its harness checks. */
@@ -183,8 +182,9 @@ export function ensureInstall(version, log, npmOverride) {
183
182
  // the resolved runtime path, which names a versioned folder that a Node upgrade removes.
184
183
  const stableNpm = join(pre.stdout.trim(), "bin", "npm");
185
184
  const rec = { bin, npm: existsSync(stableNpm) ? stableNpm : npm, version: binVersion(bin), installed_at: new Date().toISOString() };
186
- mkdirSync(configRoot(), { recursive: true });
187
- writeFileSync(installFile(), JSON.stringify(rec, null, 2) + "\n");
185
+ // Replaced in one step: every b9s command on the machine reads this record, and an upgrade runs
186
+ // this once per agent at the same moment. A reader never sees it half-written.
187
+ writeFileAtomic(installFile(), JSON.stringify(rec, null, 2) + "\n");
188
188
  return rec;
189
189
  }
190
190
  /**
@@ -355,8 +355,8 @@ export function launchdFacts() {
355
355
  export function launchdGuidance(session = launchdSessionNow()) {
356
356
  const uid = process.getuid();
357
357
  return session === "headless"
358
- ? `launchd: headless Mac, services are Background agents in user/${uid}. After a reboot they start once someone logs in over SSH (that also unlocks FileVault); a desktop sign-in is not needed. Harness sign-ins kept in the login keychain (Claude Code's by default) are unreadable without a desktop session; Codex and Antigravity keep theirs in files. External volumes may be refused to processes started while no one is signed in at the desktop: keep the workdir on the internal disk.`
359
- : `launchd: desktop session, services are LaunchAgents in gui/${uid}. They stop when that user signs out and start again at the next desktop sign-in; for a Mac meant to run unattended, use automatic sign-in, or install the services while no one is signed in so they run headless.`;
358
+ ? `launchd: headless Mac, services are Background agents in user/${uid}. Headless startup across reboot has not been validated; automatic desktop sign-in is the recommended unattended setup. A manual SSH login may load services for that session, but is not a verified boot-persistence method.`
359
+ : `launchd: desktop session, services are LaunchAgents in gui/${uid}. They stop when that user signs out and start again at the next desktop sign-in; automatic desktop sign-in is the recommended unattended setup.`;
360
360
  }
361
361
  /** One line for status output. */
362
362
  export function launchdFactsLine(f) {
@@ -476,7 +476,7 @@ export function rewriteServiceInstall(s, installBin) {
476
476
  updated = updated.replace(/^Slice=.*\n/gm, "").replace(/^MemoryMax=.*\n/gm, "");
477
477
  updated = updated.replace(/^\[Install\]$/m, `Slice=app.slice\nMemoryMax=${limits.unitMaxBytes}\n\n[Install]`);
478
478
  }
479
- writeFileSync(s.path, updated);
479
+ writeFileAtomic(s.path, updated);
480
480
  return original;
481
481
  }
482
482
  const read = spawnSync("plutil", ["-convert", "json", "-o", "-", s.path], { encoding: "utf8" });
@@ -547,7 +547,7 @@ export async function restartInstallServices(installBin, services = watcherServi
547
547
  const reload = spawnSync("systemctl", ["--user", "daemon-reload"], { encoding: "utf8" });
548
548
  if (reload.status !== 0) {
549
549
  for (const { service, original } of systemd) {
550
- writeFileSync(service.path, original);
550
+ writeFileAtomic(service.path, original);
551
551
  notRestarted.push(`${service.label} resolves to ${installReal}, but its rewritten unit could not be loaded`);
552
552
  }
553
553
  spawnSync("systemctl", ["--user", "daemon-reload"], { stdio: "ignore" });
@@ -646,7 +646,7 @@ export function installService(label, args, cwd, env, logName) {
646
646
  mkdirSync(systemdUserDir(), { recursive: true });
647
647
  const path = join(systemdUserDir(), `${label}.service`);
648
648
  const unit = systemdUnit(label, args, cwd, env, logDir, logName).replace(`watch.${logName}.out.log`, `${logName}.out.log`).replace(`watch.${logName}.err.log`, `${logName}.err.log`);
649
- writeFileSync(path, unit);
649
+ writeFileAtomic(path, unit);
650
650
  loadSystemdUnit(label);
651
651
  return path;
652
652
  }
@@ -655,7 +655,7 @@ export function installService(label, args, cwd, env, logName) {
655
655
  const esc = (s) => s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
656
656
  const path = join(launchAgentsDir(), `${label}.plist`);
657
657
  mkdirSync(launchAgentsDir(), { recursive: true });
658
- writeFileSync(path, `<?xml version="1.0" encoding="UTF-8"?>
658
+ writeFileAtomic(path, `<?xml version="1.0" encoding="UTF-8"?>
659
659
  <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
660
660
  <plist version="1.0"><dict>
661
661
  <key>Label</key><string>${label}</string>
@@ -1,6 +1,7 @@
1
1
  import { basename, join } from "node:path";
2
- import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
2
+ import { existsSync, readFileSync } from "node:fs";
3
3
  import { configRoot } from "./config.js";
4
+ import { writeFileAtomic } from "./shared-file.js";
4
5
  import { CLI_VERSION } from "./version.js";
5
6
  export function invokedProduct(argv1 = process.argv[1]) {
6
7
  return basename(argv1 ?? "") === "bschat" || basename(argv1 ?? "") === "bschat-admin" ? "bschat-cli" : "b9s-cli";
@@ -36,7 +37,7 @@ export function warnLegacyAlias(argv1 = process.argv[1], now = new Date(), root)
36
37
  const day = now.toISOString().slice(0, 10);
37
38
  if (seen[name] === day)
38
39
  return;
39
- mkdirSync(join(stateRoot, "state"), { recursive: true });
40
- writeFileSync(file, JSON.stringify({ ...seen, [name]: day }, null, 2) + "\n", { mode: 0o600 });
40
+ // In one step: this file is read by every alias call, which refuses one that does not parse.
41
+ writeFileAtomic(file, JSON.stringify({ ...seen, [name]: day }, null, 2) + "\n", { mode: 0o600 });
41
42
  process.stderr.write(`[b9s] ${name} is a compatibility alias; use ${replacement}.\n`);
42
43
  }
package/dist/lock-jobs.js CHANGED
@@ -1,54 +1,51 @@
1
- import { chmodSync, existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
2
1
  import { join } from "node:path";
3
2
  import { configDirectory } from "./directories.js";
4
3
  import { CliError } from "./errors.js";
4
+ import { readJsonFile, updateJsonFile } from "./shared-file.js";
5
5
  const KEEP_MS = 7 * 24 * 60 * 60 * 1000;
6
6
  export function lockJobsFile(agentRef, root = configDirectory()) {
7
7
  return join(root, "state", `lock-jobs.${agentRef.replace(/[^A-Za-z0-9._-]/g, ".")}.json`);
8
8
  }
9
9
  export const lockJobKey = (project, lock, machine) => JSON.stringify([project, lock, machine ?? ""]);
10
- function read(file) {
11
- if (!existsSync(file))
12
- return {};
13
- let parsed;
14
- try {
15
- parsed = JSON.parse(readFileSync(file, "utf8"));
16
- }
17
- catch {
18
- throw new CliError("corrupt_state", `${file} is not valid JSON; move it aside, then release held locks with their tokens or ask an assigner`);
19
- }
10
+ const corruptStore = (file) => new CliError("corrupt_state", `${file} is not valid JSON; move it aside, then release held locks with their tokens or ask an assigner`);
11
+ function asStore(file, parsed) {
20
12
  if (!parsed || typeof parsed !== "object" || Array.isArray(parsed))
21
13
  throw new CliError("corrupt_state", `${file} does not hold lock jobs; move it aside`);
22
14
  return parsed;
23
15
  }
24
- function write(file, store) {
25
- mkdirSync(join(file, ".."), { recursive: true });
26
- const temporary = `${file}.${process.pid}.tmp`;
27
- writeFileSync(temporary, JSON.stringify(store), { mode: 0o600 });
28
- chmodSync(temporary, 0o600);
29
- renameSync(temporary, file);
16
+ function read(file) {
17
+ const parsed = readJsonFile(file, corruptStore);
18
+ return parsed === undefined ? {} : asStore(file, parsed);
19
+ }
20
+ /** Read, changed and written under the file's lock: an agent may take and release locks from two commands at once. */
21
+ function update(file, change) {
22
+ updateJsonFile(file, (parsed) => change(parsed === undefined ? {} : asStore(file, parsed)), { mode: 0o600, corrupt: corruptStore, serialize: (store) => JSON.stringify(store) });
30
23
  }
31
24
  export function savedLockJobs(file, key) {
32
25
  return read(file)[key] ?? [];
33
26
  }
34
27
  export function rememberLockJob(file, key, entry, nowMs = Date.now()) {
35
- const store = read(file);
36
- for (const k of Object.keys(store)) {
37
- store[k] = store[k].filter((e) => nowMs - Date.parse(e.at) < KEEP_MS);
38
- if (!store[k].length)
39
- delete store[k];
40
- }
41
- store[key] = [...(store[key] ?? []).filter((e) => e.job !== entry.job), entry];
42
- write(file, store);
28
+ update(file, (store) => {
29
+ for (const k of Object.keys(store)) {
30
+ store[k] = store[k].filter((e) => nowMs - Date.parse(e.at) < KEEP_MS);
31
+ if (!store[k].length)
32
+ delete store[k];
33
+ }
34
+ store[key] = [...(store[key] ?? []).filter((e) => e.job !== entry.job), entry];
35
+ return store;
36
+ });
43
37
  }
44
38
  export function forgetLockJob(file, key, token) {
45
- const store = read(file);
46
- if (!store[key])
47
- return;
48
- store[key] = store[key].filter((e) => e.token !== token);
49
- if (!store[key].length)
50
- delete store[key];
51
- write(file, store);
39
+ if (!read(file)[key])
40
+ return; // nothing saved: no file is made
41
+ update(file, (store) => {
42
+ if (!store[key])
43
+ return undefined;
44
+ store[key] = store[key].filter((e) => e.token !== token);
45
+ if (!store[key].length)
46
+ delete store[key];
47
+ return store;
48
+ });
52
49
  }
53
50
  /**
54
51
  * The token to release with when none was typed: the one saved job, or the one named by --job.
package/dist/sessions.js CHANGED
@@ -1,20 +1,15 @@
1
- import { existsSync, mkdirSync, readFileSync, readdirSync, writeFileSync } from "node:fs";
1
+ import { existsSync, readdirSync } from "node:fs";
2
2
  import { homedir } from "node:os";
3
- import { dirname, join } from "node:path";
3
+ import { join } from "node:path";
4
4
  import { configRoot } from "./config.js";
5
5
  import { CliError } from "./errors.js";
6
6
  import { watcherServices } from "./install.js";
7
+ import { readJsonFile, updateJsonFile } from "./shared-file.js";
7
8
  const file = (kind) => join(configRoot(), `${kind}.json`);
8
9
  const UUID = /[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/i;
10
+ const badMap = (kind) => new CliError("bad_session_map", `${file(kind)} is not valid JSON`, `Remove it and run: b9s ${kind} sync`);
9
11
  function read(kind) {
10
- if (!existsSync(file(kind)))
11
- return { conversations: {} };
12
- try {
13
- return JSON.parse(readFileSync(file(kind), "utf8"));
14
- }
15
- catch {
16
- throw new CliError("bad_session_map", `${file(kind)} is not valid JSON`, `Remove it and run: b9s ${kind} sync`);
17
- }
12
+ return readJsonFile(file(kind), () => badMap(kind)) ?? { conversations: {} };
18
13
  }
19
14
  const KIND_NOUN = { codex: "a Codex thread", antigravity: "an Antigravity conversation", "claude-code": "a Claude Code session" };
20
15
  /**
@@ -25,7 +20,15 @@ const KIND_NOUN = { codex: "a Codex thread", antigravity: "an Antigravity conver
25
20
  export function bindSession(kind, id, ref, opts = {}) {
26
21
  if (!UUID.test(id))
27
22
  throw new CliError("usage", `"${id}" is not ${KIND_NOUN[kind]} id (a UUID)`);
28
- const m = read(kind);
23
+ updateJsonFile(file(kind), (m) => bindLocked(m ?? { conversations: {} }, kind, id, ref, opts), { busyCode: "session_map_busy", corrupt: () => badMap(kind) });
24
+ }
25
+ /**
26
+ * Applied to the map as it is on disk, under its lock (updateJsonFile), and the file is replaced by
27
+ * rename. An upgrade restarts every session on a machine at once (39 on one host), and each start
28
+ * binds its thread: a start that read the map while another was writing it failed with "not valid
29
+ * JSON" (four sessions, 2026-11-18), and two that read the same version would have lost one binding.
30
+ */
31
+ function bindLocked(m, kind, id, ref, opts) {
29
32
  const key = id.toLowerCase();
30
33
  if (kind === "claude-code") {
31
34
  for (const [other, owner] of Object.entries(m.conversations))
@@ -40,8 +43,7 @@ export function bindSession(kind, id, ref, opts = {}) {
40
43
  m.auto = { ...(m.auto ?? {}), [key]: true };
41
44
  else if (m.auto)
42
45
  delete m.auto[key];
43
- mkdirSync(dirname(file(kind)), { recursive: true });
44
- writeFileSync(file(kind), JSON.stringify(m, null, 2) + "\n");
46
+ return m;
45
47
  }
46
48
  export function sessionAgent(kind, id) {
47
49
  return read(kind).conversations[id.toLowerCase()] ?? null;