benignswarm 0.12.68 → 0.12.70

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.
@@ -57,7 +57,7 @@ export async function harnessStart(p, out, harness) {
57
57
  throw new CliError("usage", "--writable takes absolute or ~/ paths, comma separated");
58
58
  // Refuses a sandbox the harness cannot honour before anything is enrolled.
59
59
  const settings = harness === "codex"
60
- ? codexSettings(sandbox, model, effort, process.cwd(), configRoot(), writable)
60
+ ? codexSettings(sandbox, model, effort, process.cwd(), configRoot(), [...writable, ...ownWorktreeGitDir(process.cwd())])
61
61
  : claudeSettings(sandbox, model, effort, process.cwd(), configRoot(), writable);
62
62
  // 1. Who: enroll with the invite token, or use credentials already on this machine.
63
63
  const lines = [];
@@ -187,6 +187,22 @@ export function codexSettings(sandbox, model, effort, cwd, bschatHome, extraWrit
187
187
  : []),
188
188
  ];
189
189
  }
190
+ /**
191
+ * The agent's own linked-worktree git folder (<clone>/.git/worktrees/<name>), when it runs in one.
192
+ * Codex's sandbox makes the git folder of the directory it runs in read-only, and for a linked
193
+ * worktree that is this folder alone: the clone's common .git under the writable parent stays
194
+ * writable. So every reviewer on a machine failed `git fetch` from its home folder ("cannot open
195
+ * .../.git/worktrees/sol-reviewer/FETCH_HEAD: Read-only file system") while workers, committing in
196
+ * unit worktrees, did not. Listing it restores ordinary git there and opens nothing the agent could
197
+ * not already change through the common .git.
198
+ */
199
+ export function ownWorktreeGitDir(cwd) {
200
+ const r = spawnSync("git", ["rev-parse", "--absolute-git-dir", "--path-format=absolute", "--git-common-dir"], { cwd, encoding: "utf8" });
201
+ if (r.status !== 0)
202
+ return [];
203
+ const [gitDir, common] = r.stdout.trim().split("\n");
204
+ return gitDir && common && gitDir !== common ? [gitDir] : [];
205
+ }
190
206
  /** Starts a headless Codex session in its own process group and returns its thread id from the JSON event stream. */
191
207
  async function startThread(codexBin, args, logPath, agent) {
192
208
  const fd = openSync(logPath, "a");
@@ -1,5 +1,5 @@
1
1
  import { spawn, spawnSync } from "node:child_process";
2
- import { existsSync, mkdirSync, readFileSync, statfsSync, writeFileSync } from "node:fs";
2
+ import { closeSync, existsSync, mkdirSync, openSync, readFileSync, readSync, statSync, statfsSync, writeFileSync } from "node:fs";
3
3
  import { arch, cpus, freemem, homedir, hostname, loadavg, platform, totalmem, userInfo } from "node:os";
4
4
  import { dirname, join } from "node:path";
5
5
  import { str } from "../args.js";
@@ -26,7 +26,12 @@ function writeMachineState(s) {
26
26
  writeFileSync(stateFile(), JSON.stringify(s, null, 2) + "\n");
27
27
  }
28
28
  /** What a session's watcher is started with; a change means re-running codex start. The thread is compared separately. */
29
- export const sessionFingerprint = (s, writable = []) => JSON.stringify([s.harness, s.dir, s.sandbox, s.model, s.effort, s.turn_timeout, ...(writable.length ? [writable] : [])]);
29
+ /**
30
+ * Bumped when `bschat start` builds a session's settings differently, so every session is started
31
+ * again once with them. 2: the agent's own worktree git folder is writable under workspace-write.
32
+ */
33
+ const START_REV = 2;
34
+ export const sessionFingerprint = (s, writable = []) => JSON.stringify([s.harness, s.dir, s.sandbox, s.model, s.effort, s.turn_timeout, ...(writable.length ? [writable] : []), ...(START_REV > 1 ? [`rev${START_REV}`] : [])]);
30
35
  export const watchLabelOf = (ref) => `${WATCH_LABEL_PREFIX}${ref.replace("/", ".")}`;
31
36
  /** The `bschat start` arguments that bring a session up (adopting its thread or session when known). */
32
37
  export function startArgs(s, thread, writable = []) {
@@ -99,6 +104,13 @@ export async function reconcile(m, log) {
99
104
  }
100
105
  const w = svc();
101
106
  const th = state.sessions[s.id].thread;
107
+ // A watcher that exits at every start (a corrupt state file after the disk filled) is
108
+ // restarted by systemd forever and looked "running" here; report it as the error it is.
109
+ const fault = watcherFault(s.agent);
110
+ if (fault) {
111
+ out.push({ id: s.id, state: "error", dir: s.dir, thread: th, watcher: w && serviceActive(w) ? "active" : "inactive", error: `its watcher keeps exiting: ${fault}` });
112
+ continue;
113
+ }
102
114
  // The operator lifted a usage-limit pause: what bschat codex unpause does, here.
103
115
  if (s.unpause_at && state.sessions[s.id].unpause_applied !== s.unpause_at) {
104
116
  writeState(s.agent, { ...readState(s.agent), turn_unpaused_at: Date.parse(s.unpause_at) });
@@ -302,6 +314,47 @@ export function turnProcess(thread, harness = "codex", psOutput) {
302
314
  }
303
315
  return null;
304
316
  }
317
+ /**
318
+ * The error the watcher keeps exiting with, or null. A crash loop (systemd and launchd restart it
319
+ * every few seconds) leaves a fresh error line each time, while a watcher that failed once and
320
+ * recovered leaves an old one, so an error counts only when the line logged just before it is from
321
+ * the last two minutes. Error lines carry no time of their own.
322
+ */
323
+ export function watcherFault(ref, logText, nowMs = Date.now()) {
324
+ let text = logText;
325
+ if (text === undefined) {
326
+ const f = join(homedir(), ".bschat", "logs", `watch.${ref.replace("/", ".")}.err.log`);
327
+ if (!existsSync(f))
328
+ return null;
329
+ const size = statSync(f).size;
330
+ const fd = openSync(f, "r");
331
+ const buf = Buffer.alloc(Math.min(size, 16_384));
332
+ readSync(fd, buf, 0, buf.length, size - buf.length);
333
+ closeSync(fd);
334
+ text = buf.toString("utf8");
335
+ }
336
+ const lines = text.split("\n").filter((l) => l.trim());
337
+ let lastErr = -1;
338
+ for (let i = lines.length - 1; i >= 0; i--)
339
+ if (lines[i].startsWith('{"error"')) {
340
+ lastErr = i;
341
+ break;
342
+ }
343
+ if (lastErr < 0)
344
+ return null;
345
+ let at = NaN;
346
+ for (let i = lastErr - 1; i >= 0 && Number.isNaN(at); i--)
347
+ at = Date.parse(/^(\d{4}-\d\d-\d\dT[\d:.]+Z) /.exec(lines[i])?.[1] ?? "");
348
+ if (Number.isNaN(at) || nowMs - at > 120_000)
349
+ return null;
350
+ try {
351
+ const e = JSON.parse(lines[lastErr]);
352
+ return `${e.error ?? "error"}: ${(e.message ?? "").split("\n")[0].slice(0, 300)}`;
353
+ }
354
+ catch {
355
+ return lines[lastErr].slice(0, 300);
356
+ }
357
+ }
305
358
  /** The watcher's latest turn line (started, finished, FAILED, STOPPED, paused), for the report. */
306
359
  function lastTurnLine(ref) {
307
360
  const f = join(homedir(), ".bschat", "logs", `watch.${ref.replace("/", ".")}.err.log`);
@@ -243,7 +243,7 @@ export async function needsAdmin(p, out) {
243
243
  return out.print("Nothing is waiting on you.", r);
244
244
  const ind = (t) => t.replace(/\n/g, "\n ");
245
245
  out.print(r.needs.map((n, i) => [
246
- `${i + 1}. [${n.project}] ${n.kind === "unit_question" ? `WU #${n.unit} question` : n.kind === "wake_broken" ? "wake path" : n.kind === "notifier" ? "your alerts" : "decision"} · ${n.asked_by} · since ${n.since.slice(0, 16).replace("T", " ")} UTC`,
246
+ `${i + 1}. [${n.project}] ${n.kind === "unit_question" ? `WU #${n.unit} question` : n.kind === "wake_broken" ? "wake path" : n.kind === "notifier" ? "your alerts" : n.kind === "machine_session" ? "machine" : "decision"} · ${n.asked_by} · since ${n.since.slice(0, 16).replace("T", " ")} UTC`,
247
247
  n.plain ? ` In plain words: ${ind(n.plain)}` : n.unexplained ? ` In plain words: (${n.asked_by} did not explain this; bschat-admin explain ${n.key})` : null,
248
248
  n.blocks ? ` What's stuck: ${ind(n.blocks)}` : null,
249
249
  ` ${n.kind === "ask" ? "What I need from you: " : ""}${ind(n.text)}`,
package/dist/state.js CHANGED
@@ -1,4 +1,5 @@
1
- import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
1
+ import { existsSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs";
2
+ import { CliError } from "./errors.js";
2
3
  import { join } from "node:path";
3
4
  import { configRoot, isRef, splitRef } from "./config.js";
4
5
  /** State is keyed by agent ref (`<scope>/<name>`), like credentials. */
@@ -23,10 +24,30 @@ export function readState(ref, env = process.env) {
23
24
  adoptLegacyState(ref, env);
24
25
  if (!existsSync(p))
25
26
  return { inbox_after: "", last_check: 0 };
26
- return { inbox_after: "", last_check: 0, ...JSON.parse(readFileSync(p, "utf8")) };
27
+ const text = readFileSync(p, "utf8");
28
+ let saved;
29
+ try {
30
+ saved = JSON.parse(text);
31
+ }
32
+ catch {
33
+ // Never started over silently: cursors, wake numbers and follows live here.
34
+ throw new CliError("corrupt_state", `${p} is not valid JSON (${text.length} bytes): a write to it was cut short`, "Check free disk space on this machine, then repair the file or move it aside (the agent then starts from fresh cursors and its wake-up numbering restarts)");
35
+ }
36
+ return { inbox_after: "", last_check: 0, ...saved };
27
37
  }
28
38
  export function writeState(agent, state, env = process.env) {
29
39
  const p = statePath(agent, env);
30
40
  mkdirSync(join(p, ".."), { recursive: true });
31
- writeFileSync(p, JSON.stringify(state, null, 2) + "\n", { mode: 0o600 });
41
+ // Written beside it and renamed over it: a full disk once truncated three agents' files to 0
42
+ // bytes mid-write, and their watchers failed on every start for 17 hours. A failed write now
43
+ // throws and leaves the previous file whole.
44
+ const tmp = `${p}.${process.pid}.tmp`;
45
+ try {
46
+ writeFileSync(tmp, JSON.stringify(state, null, 2) + "\n", { mode: 0o600 });
47
+ renameSync(tmp, p);
48
+ }
49
+ catch (e) {
50
+ rmSync(tmp, { force: true });
51
+ throw e;
52
+ }
32
53
  }
package/dist/version.js CHANGED
@@ -1 +1 @@
1
- export const CLI_VERSION = "0.12.68";
1
+ export const CLI_VERSION = "0.12.70";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "benignswarm",
3
- "version": "0.12.68",
3
+ "version": "0.12.70",
4
4
  "description": "bschat: chat, status board and evidence store for coding agents (benignswarm.org)",
5
5
  "license": "UNLICENSED",
6
6
  "repository": {