benignswarm 0.12.123 → 0.12.125

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.
@@ -7,7 +7,7 @@ import { agentRef, DEFAULT_URL, listSaved, loadAgent, removeAgent, resolveAgentN
7
7
  import { CliError } from "../errors.js";
8
8
  import { defaultMachine } from "../git.js";
9
9
  import { fmtMessage, fmtStatus, table } from "../output.js";
10
- import { readState, writeState } from "../state.js";
10
+ import { readState, updateState } from "../state.js";
11
11
  import { formatStandingRuleSummary } from "../standing-rules.js";
12
12
  function agentClient(p) {
13
13
  const name = resolveAgentName(str(p.flags, "as"));
@@ -210,11 +210,11 @@ export async function send(p, out) {
210
210
  const r = await client.call("POST", `/projects/${project}/channels/${channel}/messages`, { body, reply_to: replyTo === undefined ? null : Number(replyTo), client_id: clientId }, { retries: 3 });
211
211
  {
212
212
  // Our own post must not count as unread for us; advance the cursor if we were caught up.
213
- const st = readState(agentRef(creds));
214
213
  const key = `${project}/${channel}`;
215
- const last = st.channel_read?.[key];
216
- if (last !== undefined && last >= r.message.seq - 1)
217
- writeState(agentRef(creds), { ...st, channel_read: { ...(st.channel_read ?? {}), [key]: r.message.seq } });
214
+ updateState(agentRef(creds), (onDisk) => {
215
+ const last = onDisk.channel_read?.[key];
216
+ return last !== undefined && last >= r.message.seq - 1 ? { ...onDisk, channel_read: { ...(onDisk.channel_read ?? {}), [key]: r.message.seq } } : undefined;
217
+ });
218
218
  }
219
219
  let hint = "";
220
220
  if (body.trimEnd().endsWith("?")) {
@@ -252,7 +252,7 @@ export async function read(p, out) {
252
252
  out.print("(no deferred channel reads)", { messages: [], pending: 0 });
253
253
  return;
254
254
  }
255
- const channelRead = { ...(state.channel_read ?? {}) };
255
+ const channelRead = {};
256
256
  const messages = [];
257
257
  for (const item of pending) {
258
258
  let cursor = item.since;
@@ -269,7 +269,13 @@ export async function read(p, out) {
269
269
  }
270
270
  channelRead[`${item.project}/${item.channel}`] = finalCursor;
271
271
  }
272
- writeState(ref, { ...state, pending_reads: undefined, channel_read: channelRead });
272
+ // Only the channels read here move, and only the deferred reads served here are dropped: the
273
+ // watcher may have added others while these were being fetched.
274
+ const served = new Set(pending.map((item) => JSON.stringify([item.project, item.channel, item.since])));
275
+ updateState(ref, (onDisk) => {
276
+ const left = (onDisk.pending_reads ?? []).filter((item) => !served.has(JSON.stringify([item.project, item.channel, item.since])));
277
+ return { ...onDisk, pending_reads: left.length ? left : undefined, channel_read: { ...(onDisk.channel_read ?? {}), ...channelRead } };
278
+ });
273
279
  out.print(`${messages.length ? messages.map(fmtMessage).join("\n") : "(no messages)"}\nRead ${pending.length} deferred channel${pending.length === 1 ? "" : "s"}.`, { messages, pending: pending.length });
274
280
  return;
275
281
  }
@@ -288,18 +294,19 @@ export async function read(p, out) {
288
294
  qs.set("limit", str(p.flags, "limit") ?? "100");
289
295
  const r = await client.call("GET", `/projects/${project}/channels/${channel}/messages?${qs}`);
290
296
  const text = r.messages.length ? r.messages.map(fmtMessage).join("\n") : "(no messages)";
291
- const st = readState(agentRef(creds));
292
- const pendingReads = (st.pending_reads ?? []).flatMap((item) => {
293
- if (item.project !== project || item.channel !== channel || since === undefined || Number(since) > item.since)
294
- return [item];
295
- const lastShown = r.messages.length ? Number(r.messages[r.messages.length - 1].seq) : undefined;
296
- if (lastShown === undefined)
297
- return r.cursor <= item.since ? [] : [item];
298
- if (lastShown >= r.cursor)
299
- return [];
300
- return lastShown > item.since ? [{ ...item, since: lastShown }] : [item];
297
+ updateState(agentRef(creds), (onDisk) => {
298
+ const pendingReads = (onDisk.pending_reads ?? []).flatMap((item) => {
299
+ if (item.project !== project || item.channel !== channel || since === undefined || Number(since) > item.since)
300
+ return [item];
301
+ const lastShown = r.messages.length ? Number(r.messages[r.messages.length - 1].seq) : undefined;
302
+ if (lastShown === undefined)
303
+ return r.cursor <= item.since ? [] : [item];
304
+ if (lastShown >= r.cursor)
305
+ return [];
306
+ return lastShown > item.since ? [{ ...item, since: lastShown }] : [item];
307
+ });
308
+ return { ...onDisk, channel_read: { ...(onDisk.channel_read ?? {}), [`${project}/${channel}`]: r.cursor }, pending_reads: pendingReads.length ? pendingReads : undefined };
301
309
  });
302
- writeState(agentRef(creds), { ...st, channel_read: { ...(st.channel_read ?? {}), [`${project}/${channel}`]: r.cursor }, pending_reads: pendingReads.length ? pendingReads : undefined });
303
310
  out.print(`${text}\ncursor: ${r.cursor}`, r);
304
311
  }
305
312
  function follow(client, path, out) {
@@ -350,8 +357,11 @@ export async function inbox(p, out) {
350
357
  qs.set("after", after);
351
358
  qs.set("limit", str(p.flags, "limit") ?? "50");
352
359
  const r = await client.call("GET", `/inbox?${qs}`);
353
- if (unread && r.messages.length)
354
- writeState(agentRef(creds), { ...state, inbox_after: r.messages[r.messages.length - 1].created_at, last_check: Date.now() });
360
+ if (unread && r.messages.length) {
361
+ const newest = r.messages[r.messages.length - 1].created_at;
362
+ // Never backwards: the hook may have surfaced later messages while this call was in flight.
363
+ updateState(agentRef(creds), (onDisk) => ({ ...onDisk, ...(!onDisk.inbox_after || onDisk.inbox_after < newest ? { inbox_after: newest } : {}), last_check: Date.now() }));
364
+ }
355
365
  const fmt = (m) => `${creds.project ? "" : `[${m.project}] `}${fmtMessage(m)}${m.reply_to_seq ? ` (reply to #${m.reply_to_seq})` : ""}`;
356
366
  const questions = (r.questions ?? []).map((q) => ` ${q.project} #${q.channel} seq ${q.seq} from ${q.from} (${q.age_minutes} min ago): ${q.question} — ${q.next}`);
357
367
  const items = (r.items ?? []).map((i) => `list "${i.list}": [${i.status}] ${i.title} (item ${i.id})`);
@@ -506,6 +516,13 @@ export async function followCmd(p, out) {
506
516
  await client.call("GET", `/projects/${project}/channels/${channel}/messages?limit=1`); // validates access
507
517
  follows.add(key);
508
518
  }
509
- writeState(agentRef(creds), { ...st, follows: [...follows] });
510
- out.print(`${unfollow ? "unfollowed" : "following"} #${channel} in ${project}`, { follows: [...follows] });
519
+ const saved = updateState(agentRef(creds), (onDisk) => {
520
+ const current = new Set(onDisk.follows ?? []);
521
+ if (unfollow)
522
+ current.delete(key);
523
+ else
524
+ current.add(key);
525
+ return { ...onDisk, follows: [...current] };
526
+ });
527
+ out.print(`${unfollow ? "unfollowed" : "following"} #${channel} in ${project}`, { follows: saved.follows ?? [] });
511
528
  }
@@ -10,7 +10,7 @@ import { provisionContainerInstallRecord, requireInstall } from "../install.js";
10
10
  import { bindSession, codexArchivedRollout, codexRollout, sessionOfExec } from "../sessions.js";
11
11
  import { codexHooksPath } from "./codex.js";
12
12
  import { isCodexManagedRequirements } from "../harness.js";
13
- import { readState, writeState } from "../state.js";
13
+ import { readState, updateState } from "../state.js";
14
14
  import { join } from "./join.js";
15
15
  import { beginTurnGuardAttempt, completePendingTurnGuard, installWatcherService, turnArgs, watch } from "./watch.js";
16
16
  import { randomUUID } from "node:crypto";
@@ -166,8 +166,6 @@ export async function harnessStart(p, out, harness) {
166
166
  ? dshSettings(sandbox, process.cwd(), configRoot(), [...writable, ...ownWorktreeGitDir(process.cwd())])
167
167
  : harness === "claude-code" ? claudeSettings(sandbox, model, effort, process.cwd(), configRoot(), writable) : [];
168
168
  const providerEnv = { ...claudeTurnEnv(harness === "claude-code" ? provider : undefined, model), ...(harness === "claude-code" ? claudeSandboxEnv(sandbox) : {}) };
169
- if ((harness === "claude-code" || harness === "antigravity") && sandbox === "workspace-write")
170
- configureHttpsOriginForWorktree(process.cwd());
171
169
  // 1. Who: enroll with the invite token, or use credentials already on this machine.
172
170
  const lines = [];
173
171
  const token = str(p.flags, "token");
@@ -308,12 +306,12 @@ export async function harnessStart(p, out, harness) {
308
306
  if (harness === "claude-code")
309
307
  bindSession("claude-code", session, ref);
310
308
  const transcript = harness === "dsh" ? dshTurnLog(ref) : harness === "antigravity" ? antigravityLog(ref) : harness === "claude-code" ? claudeTranscript(session) ?? firstTurnLog ?? "" : codexRollout(session) ?? firstTurnLog ?? "";
311
- writeState(ref, { ...readState(ref), harness_session: { harness, transcript, session_id: session, at: Date.now(), ...(model ? { model } : {}), ...(harness === "claude-code" ? { provider } : {}), ...(initialPid ? { initial_pid: initialPid } : {}) } });
309
+ updateState(ref, (onDisk) => ({ ...onDisk, harness_session: { harness, transcript, session_id: session, at: Date.now(), ...(model ? { model } : {}), ...(harness === "claude-code" ? { provider } : {}), ...(initialPid ? { initial_pid: initialPid } : {}) } }));
312
310
  // A session adopted here may end in a usage-limit error from the machine it came from, written in
313
311
  // that machine's local time ("3:32 PM" Central read as UTC on ronald: six hours off). Only errors
314
312
  // from turns on this machine pause it; if the account is still limited, the next turn says so here.
315
313
  if (adopt)
316
- writeState(ref, { ...readState(ref), turn_unpaused_at: Date.now() });
314
+ updateState(ref, (onDisk) => ({ ...onDisk, turn_unpaused_at: Date.now() }));
317
315
  // 4. The watcher, in turn mode: it runs each later turn itself.
318
316
  const exec = harness === "codex"
319
317
  ? [bin, "exec", "resume", session, ...settings].map(shq).join(" ") + " {text}"
@@ -1,14 +1,14 @@
1
- import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
2
1
  import { homedir } from "node:os";
3
- import { dirname, join } from "node:path";
2
+ import { join } from "node:path";
4
3
  import { str } from "../args.js";
5
4
  import { agentRef, loadAgent, resolveAgentName } from "../config.js";
6
5
  import { CliError } from "../errors.js";
7
6
  import { withCodexHooks } from "../harness.js";
8
7
  import { requireInstall } from "../install.js";
9
8
  import { bindSession, syncFromWatchers } from "../sessions.js";
9
+ import { updateJsonFile } from "../shared-file.js";
10
10
  import { codexStart } from "./codex-start.js";
11
- import { readState, writeState } from "../state.js";
11
+ import { updateState } from "../state.js";
12
12
  /**
13
13
  * b9s codex hooks install b9s's hooks in ~/.codex/hooks.json (this machine's Codex)
14
14
  * b9s codex bind <thread-id> [--as a] this Codex thread is you: its hooks deliver to you
@@ -20,17 +20,8 @@ export async function codex(p, out) {
20
20
  const sub = p.positionals[1];
21
21
  if (sub === "hooks") {
22
22
  const path = codexHooksPath();
23
- let doc = {};
24
- if (existsSync(path)) {
25
- try {
26
- doc = JSON.parse(readFileSync(path, "utf8"));
27
- }
28
- catch {
29
- throw new CliError("bad_settings", `${path} is not valid JSON; fix it or remove it`);
30
- }
31
- }
32
- mkdirSync(dirname(path), { recursive: true });
33
- writeFileSync(path, JSON.stringify(withCodexHooks(doc, requireInstall().bin), null, 2) + "\n");
23
+ const bin = requireInstall().bin;
24
+ updateJsonFile(path, (doc = {}) => withCodexHooks(doc, bin), { corrupt: (file) => new CliError("bad_settings", `${file} is not valid JSON; fix it or remove it`) });
34
25
  const bound = syncFromWatchers().filter((b) => b.kind === "codex");
35
26
  out.print(`Wrote b9s's hooks to ${path} (SessionStart, UserPromptSubmit, PostToolUse, Stop).\nCodex asks you to trust new hooks the next time a session starts: approve them there.\nThreads bound from watchers: ${bound.length ? bound.map((b) => `${b.conversation} -> ${b.agent}`).join(", ") : "none"}. Any other Codex session gets nothing from them.`, { path, bound });
36
27
  return;
@@ -61,7 +52,7 @@ export async function codex(p, out) {
61
52
  */
62
53
  export async function unpause(p, out) {
63
54
  const name = resolveAgentName(str(p.flags, "as"));
64
- writeState(name, { ...readState(name), turn_unpaused_at: Date.now() });
55
+ updateState(name, (onDisk) => ({ ...onDisk, turn_unpaused_at: Date.now() }));
65
56
  out.print(`Turns for ${name} may start again: its watcher lifts the usage-limit pause on its next poll (within its --interval).`, { agent: name, unpaused: true });
66
57
  }
67
58
  export const codexHooksPath = () => join(process.env.CODEX_HOME ?? join(homedir(), ".codex"), "hooks.json");
@@ -1,8 +1,11 @@
1
1
  import { spawnSync } from "node:child_process";
2
+ import { accessSync, constants, existsSync, realpathSync, statSync } from "node:fs";
3
+ import { isAbsolute } from "node:path";
2
4
  import { Client } from "../client.js";
3
5
  import { loadAgent, resolveAgentName } from "../config.js";
4
6
  import { CliError } from "../errors.js";
5
- import { requireInstall } from "../install.js";
7
+ import { isLiveExecutable, requireInstall } from "../install.js";
8
+ import { str } from "../args.js";
6
9
  function credentialInput(input) {
7
10
  const result = {};
8
11
  for (const line of input.split(/\r?\n/)) {
@@ -40,6 +43,12 @@ export async function credentialResponse(input, api) {
40
43
  const credential = await api("POST", "", {});
41
44
  return `username=${credential.username}\npassword=${credential.password}\n\n`;
42
45
  }
46
+ function missingRepositoryPathHint(input) {
47
+ const request = credentialInput(input);
48
+ if (request.protocol !== "https" || request.host?.toLowerCase() !== "github.com" || request.path)
49
+ return null;
50
+ return "GitHub credential lookup has no repository path; set credential.https://github.com.useHttpPath true to send it";
51
+ }
43
52
  export async function gitCredentialOperation(operation, input, api) {
44
53
  if (operation === "store" || operation === "erase")
45
54
  return "";
@@ -47,17 +56,22 @@ export async function gitCredentialOperation(operation, input, api) {
47
56
  throw new CliError("usage", "git-credential get|store|erase");
48
57
  return credentialResponse(input, api);
49
58
  }
50
- export async function gitCredential(p) {
59
+ export async function gitCredential(p, stdin = process.stdin) {
51
60
  const operation = p.positionals[1];
52
61
  const chunks = [];
53
- for await (const chunk of process.stdin)
62
+ for await (const chunk of stdin)
54
63
  chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
55
64
  const input = Buffer.concat(chunks).toString("utf8");
56
65
  if (operation === "store" || operation === "erase")
57
66
  return;
58
67
  if (operation !== "get")
59
68
  throw new CliError("usage", "git-credential get|store|erase");
60
- const agent = loadAgent(resolveAgentName(undefined));
69
+ const pathHint = missingRepositoryPathHint(input);
70
+ if (pathHint) {
71
+ process.stderr.write(`${pathHint}\n`);
72
+ return;
73
+ }
74
+ const agent = loadAgent(resolveAgentName(str(p.flags, "as")));
61
75
  if (!agent.project)
62
76
  throw new CliError("github_not_connected", "GitHub credential helper requires a project-scoped agent identity.");
63
77
  const client = Client.forAgent(agent, undefined, { presence: false });
@@ -85,8 +99,26 @@ function gitConfig(cwd, args) {
85
99
  throw new CliError("git_credential_config", (result.stderr ?? "").trim() || "could not configure the worktree Git credential helper");
86
100
  }
87
101
  function shellQuote(value) { return `'${value.replace(/'/g, `'\\''`)}'`; }
102
+ function credentialHelperInstall(install) {
103
+ if (!isLiveExecutable(install.node)) {
104
+ throw new CliError("recorded_node_missing", "the recorded b9s install has no live absolute Node runtime for its Git credential helper", "Run: b9s install --latest to refresh the recorded runtime before starting a linked GitHub worktree");
105
+ }
106
+ if (!isAbsolute(install.bin) || !existsSync(install.bin) || !statSync(install.bin).isFile()) {
107
+ throw new CliError("install_missing", `the recorded b9s script ${install.bin} is not an absolute live path`);
108
+ }
109
+ const script = realpathSync(install.bin);
110
+ try {
111
+ accessSync(script, constants.R_OK);
112
+ }
113
+ catch {
114
+ throw new CliError("install_missing", `the recorded b9s script ${script} is not readable`);
115
+ }
116
+ if (!isAbsolute(script) || !statSync(script).isFile())
117
+ throw new CliError("install_missing", `the recorded b9s script ${install.bin} did not resolve to an absolute file`);
118
+ return { node: realpathSync(install.node), script };
119
+ }
88
120
  /** Adds the exact repo helper only when origin is the repository linked to this project. */
89
- export async function configureGitCredentialForWorktree(cwd, creds, lookup, installBin) {
121
+ export async function configureGitCredentialForWorktree(cwd, creds, lookup, installRecord) {
90
122
  if (!creds.project)
91
123
  return;
92
124
  const client = Client.forAgent(creds, undefined, { presence: false });
@@ -105,6 +137,9 @@ export async function configureGitCredentialForWorktree(cwd, creds, lookup, inst
105
137
  return;
106
138
  if (`${metadata.repository.owner}/${metadata.repository.name}`.toLowerCase() !== parsed.path)
107
139
  return;
140
+ // Validate every executable before changing worktree config. A stale install must leave the
141
+ // SSH origin and extensions untouched so a failed start cannot strand Git mid-rewrite.
142
+ const helper = credentialHelperInstall(installRecord ?? requireInstall());
108
143
  const enabled = spawnSync("git", ["config", "extensions.worktreeConfig", "true"], { cwd, encoding: "utf8" });
109
144
  if (enabled.status !== 0)
110
145
  throw new CliError("git_credential_config", (enabled.stderr ?? "").trim() || "could not enable per-worktree Git configuration");
@@ -120,7 +155,7 @@ export async function configureGitCredentialForWorktree(cwd, creds, lookup, inst
120
155
  const repoUrl = `https://github.com/${parsed.credentialPath}`;
121
156
  const helperKey = `credential.${repoUrl}.helper`;
122
157
  gitConfig(cwd, ["--worktree", "--replace-all", helperKey, ""]);
123
- gitConfig(cwd, ["--worktree", "--add", helperKey, `!${shellQuote(installBin ?? requireInstall().bin)} git-credential`]);
158
+ gitConfig(cwd, ["--worktree", "--add", helperKey, `!${shellQuote(helper.node)} ${shellQuote(helper.script)} git-credential`]);
124
159
  gitConfig(cwd, ["--worktree", "credential.https://github.com.useHttpPath", "true"]);
125
160
  }
126
161
  export async function gitCredentialMain(p) {
@@ -3,7 +3,7 @@ import { Client } from "../client.js";
3
3
  import { agentRef, loadAgent, resolveAgentName } from "../config.js";
4
4
  import { CliError } from "../errors.js";
5
5
  import { heartbeatNow, HARNESS_GOAL_STATES } from "../heartbeat.js";
6
- import { readState, writeState } from "../state.js";
6
+ import { readState, updateState } from "../state.js";
7
7
  /**
8
8
  * Harness goal self-report, for harnesses whose /goal state lives where no file on this machine
9
9
  * shows it (Codex app threads keep it in the cloud; DeepSeek exposes it through get_goal). Claude
@@ -50,6 +50,6 @@ export async function goal(p, out) {
50
50
  throw new CliError("usage", `goal [set <text> [--state s] | ${HARNESS_GOAL_STATES.join(" | ")} | clear]`);
51
51
  }
52
52
  const r = await heartbeatNow(client, "agent-report", next);
53
- writeState(ref, { ...readState(ref), harness_goal: next ?? undefined });
53
+ updateState(ref, (onDisk) => ({ ...onDisk, harness_goal: next ?? undefined }));
54
54
  out.print(next ? `reported harness goal (${next.state}): ${next.text}` : "reported: no harness goal", { status: r });
55
55
  }
@@ -5,7 +5,7 @@ import { ACCOUNT_SCOPE, loadAgent, resolveAgentName, resolveModel } from "../con
5
5
  import { findIdentityFile, readIdentityFile } from "../harness.js";
6
6
  import { heartbeatNow } from "../heartbeat.js";
7
7
  import { fmtMessage } from "../output.js";
8
- import { readState, writeState } from "../state.js";
8
+ import { readState, updateState } from "../state.js";
9
9
  import { goalFromClaudeTranscript, modelFromClaudeTranscript } from "../model.js";
10
10
  import { bindSession, conversationAgent, sessionAgent, sessionsOf, syncFromWatchers } from "../sessions.js";
11
11
  import { fetchRecoveryBrief, formatOutcomeMeasures, formatRecoveryBrief, outcomeMeasureSnapshot, recoveryBriefUnavailableText } from "../brief.js";
@@ -210,15 +210,6 @@ export async function gatherUpdates(name, opts) {
210
210
  process.stderr.write(`b9s: outcome measures: ${e.message}\n`);
211
211
  }
212
212
  }
213
- const next = { ...state, last_check: Date.now() };
214
- if (messages.length) {
215
- if (opts.watchCursor)
216
- next.watch_inbox_after = messages[messages.length - 1].created_at;
217
- else
218
- next.inbox_after = messages[messages.length - 1].created_at;
219
- }
220
- if (nextMeasureState !== null)
221
- next.measure_state = nextMeasureState;
222
213
  const initialWatchCursor = opts.watchCursor && state.watch_inbox_after === undefined
223
214
  ? state.inbox_after ?? (messages.length
224
215
  ? new Date(Date.parse(messages[0].created_at) - 1).toISOString()
@@ -276,30 +267,53 @@ export async function gatherUpdates(name, opts) {
276
267
  catch (e) {
277
268
  process.stderr.write(`b9s: channels: ${e.message}\n`);
278
269
  }
279
- next.channel_read = channelRead;
280
270
  const deferredReads = readCommands.length > 8 ? [...pendingReads.values()].slice(8) : [];
281
271
  const pendingBacklog = [...pendingReads.values(), ...digestReads.values()];
282
- if (pendingBacklog.length) {
283
- const combined = new Map((state.pending_reads ?? []).map((item) => [`${item.project}/${item.channel}`, item]));
272
+ // This poll spent several server calls since it read the state, and the watcher, the hook and the
273
+ // agent's own `read`/`inbox` all move these cursors. So what is saved is this poll's own changes,
274
+ // applied to the state as it is on disk now, never the copy read at the top.
275
+ const withBacklog = (saved) => {
276
+ if (!pendingBacklog.length)
277
+ return saved;
278
+ const combined = new Map((saved ?? []).map((item) => [`${item.project}/${item.channel}`, item]));
284
279
  for (const item of pendingBacklog) {
285
280
  const key = `${item.project}/${item.channel}`;
286
281
  const previous = combined.get(key);
287
282
  combined.set(key, previous ? { ...item, since: Math.min(previous.since, item.since) } : item);
288
283
  }
289
- next.pending_reads = [...combined.values()];
290
- }
284
+ return [...combined.values()];
285
+ };
291
286
  if (opts.dryRun) {
292
287
  // Persist only the baselines of channels never seen before; everything else stays unread.
293
- const merged = { ...(state.channel_read ?? {}) };
294
- for (const [k, v] of Object.entries(channelRead))
295
- if (merged[k] === undefined)
296
- merged[k] = v;
297
288
  // Keep fetched messages visible to wakeOnce until it knows whether direct work was delivered.
298
289
  // Empty polls still persist the independent watcher baseline.
299
- writeState(name, { ...state, channel_read: merged, ...(next.pending_reads ? { pending_reads: next.pending_reads } : {}), ...(initialWatchCursor !== undefined ? { watch_inbox_after: initialWatchCursor } : {}) });
290
+ updateState(name, (onDisk) => {
291
+ const merged = { ...(onDisk.channel_read ?? {}) };
292
+ for (const [k, v] of Object.entries(channelRead))
293
+ if (merged[k] === undefined)
294
+ merged[k] = v;
295
+ const pending = withBacklog(onDisk.pending_reads);
296
+ return { ...onDisk, channel_read: merged, ...(pending ? { pending_reads: pending } : {}), ...(initialWatchCursor !== undefined && onDisk.watch_inbox_after === undefined ? { watch_inbox_after: initialWatchCursor } : {}) };
297
+ });
300
298
  }
301
299
  else {
302
- writeState(name, { ...next, ...(noticeChanges ? { notice_state: noticeChanges.next } : {}) });
300
+ const newest = messages.length ? messages[messages.length - 1].created_at : undefined;
301
+ const cursorField = opts.watchCursor ? "watch_inbox_after" : "inbox_after";
302
+ // The channels whose cursor this poll moved; the others keep whatever is on disk.
303
+ const moved = Object.entries(channelRead).filter(([k, v]) => state.channel_read?.[k] !== v);
304
+ updateState(name, (onDisk) => {
305
+ const pending = withBacklog(onDisk.pending_reads);
306
+ return {
307
+ ...onDisk,
308
+ last_check: Date.now(),
309
+ // Never backwards: another reader may have surfaced later messages meanwhile.
310
+ ...(newest && (!onDisk[cursorField] || onDisk[cursorField] < newest) ? { [cursorField]: newest } : {}),
311
+ ...(nextMeasureState !== null ? { measure_state: nextMeasureState } : {}),
312
+ channel_read: { ...(onDisk.channel_read ?? {}), ...Object.fromEntries(moved) },
313
+ ...(pending ? { pending_reads: pending } : {}),
314
+ ...(noticeChanges ? { notice_state: noticeChanges.next } : {}),
315
+ };
316
+ });
303
317
  }
304
318
  if (!messages.length && !questions.length && !items.length && !digest.length && !followed.length && !noticeLines.length && !measureLines.length)
305
319
  return null;
@@ -457,7 +471,7 @@ export async function hook(p, payload) {
457
471
  const state = readState(name);
458
472
  const observed = (typeof input.to_model === "string" && input.to_model) || (typeof input.model === "string" && input.model) || (typeof input.transcript_path === "string" ? modelFromClaudeTranscript(input.transcript_path) : null);
459
473
  if (observed && observed !== state.model)
460
- writeState(name, { ...state, model: observed, model_observed_at: Date.now() });
474
+ updateState(name, (onDisk) => ({ ...onDisk, model: observed, model_observed_at: Date.now() }));
461
475
  }
462
476
  if (harness === "claude-code" && typeof input?.transcript_path === "string")
463
477
  noteSession(name, "claude-code", input.transcript_path, typeof input.session_id === "string" ? input.session_id : null, event === "SessionStart" && input?.source === "compact");
@@ -495,7 +509,7 @@ export async function hook(p, payload) {
495
509
  try {
496
510
  await heartbeatNow(Client.forAgent(loadAgent(name), undefined, { presence: false }), "claude-code-hook", goalChanged ? observedGoal : undefined);
497
511
  const cur = readState(name);
498
- writeState(name, { ...cur, heartbeat_at: Date.now(), ...(goalChanged ? { harness_goal: observedGoal ?? undefined, harness_goal_reported: true } : {}) });
512
+ updateState(name, (onDisk) => ({ ...onDisk, heartbeat_at: Date.now(), ...(goalChanged ? { harness_goal: observedGoal ?? undefined, harness_goal_reported: true } : {}) }));
499
513
  }
500
514
  catch (e) {
501
515
  process.stderr.write(`b9s: heartbeat failed: ${e.message}\n`);
@@ -654,15 +668,15 @@ async function antigravityHook(p, payload) {
654
668
  if (typeof input?.transcriptPath === "string" && input.transcriptPath)
655
669
  noteSession(name, "antigravity", input.transcriptPath, conv, event === "SessionStart" && input?.source === "compact");
656
670
  if (typeof input?.modelName === "string" && input.modelName) {
657
- const st = readState(name);
658
- if (st.model !== input.modelName)
659
- writeState(name, { ...st, model: input.modelName, model_observed_at: Date.now() });
671
+ const observed = input.modelName;
672
+ if (readState(name).model !== observed)
673
+ updateState(name, (onDisk) => ({ ...onDisk, model: observed, model_observed_at: Date.now() }));
660
674
  }
661
675
  const st = readState(name);
662
676
  if (Date.now() - (st.heartbeat_at ?? 0) > HEARTBEAT_MS) {
663
677
  try {
664
678
  await heartbeatNow(Client.forAgent(loadAgent(name), undefined, { presence: false }), "antigravity-hook");
665
- writeState(name, { ...readState(name), heartbeat_at: Date.now() });
679
+ updateState(name, (onDisk) => ({ ...onDisk, heartbeat_at: Date.now() }));
666
680
  }
667
681
  catch (e) {
668
682
  process.stderr.write(`b9s: heartbeat failed: ${e.message}\n`);
@@ -730,14 +744,14 @@ async function codexHook(p, payload) {
730
744
  if (typeof input?.transcript_path === "string" && input.transcript_path)
731
745
  noteSession(name, "codex", input.transcript_path, sid);
732
746
  if (typeof input?.model === "string" && input.model) {
733
- const st = readState(name);
734
- if (st.model !== input.model)
735
- writeState(name, { ...st, model: input.model, model_observed_at: Date.now() });
747
+ const observed = input.model;
748
+ if (readState(name).model !== observed)
749
+ updateState(name, (onDisk) => ({ ...onDisk, model: observed, model_observed_at: Date.now() }));
736
750
  }
737
751
  if (Date.now() - (readState(name).heartbeat_at ?? 0) > HEARTBEAT_MS) {
738
752
  try {
739
753
  await heartbeatNow(Client.forAgent(loadAgent(name), undefined, { presence: false }), "codex-hook");
740
- writeState(name, { ...readState(name), heartbeat_at: Date.now() });
754
+ updateState(name, (onDisk) => ({ ...onDisk, heartbeat_at: Date.now() }));
741
755
  }
742
756
  catch (e) {
743
757
  process.stderr.write(`b9s: heartbeat failed: ${e.message}\n`);
@@ -773,12 +787,13 @@ async function codexHook(p, payload) {
773
787
  }
774
788
  /** Records where this agent's harness session writes, so `wu submit` can read its token counts. */
775
789
  function noteSession(name, harness, transcript, sessionId, compacted = false) {
776
- const st = readState(name);
777
- const cur = st.harness_session;
778
- const same = !!cur && cur.transcript === transcript && cur.harness === harness;
779
- const compactions = same ? [...(cur.compactions ?? [])] : [];
780
- if (compacted)
781
- compactions.push(Date.now());
782
790
  const observedAt = Date.now();
783
- writeState(name, { ...st, harness_session: { harness, transcript, session_id: sessionId, at: same ? cur.at : observedAt, last_seen_at: observedAt, ...(compactions.length ? { compactions: compactions.slice(-1000) } : {}), ...(same && cur.provider ? { provider: cur.provider } : {}) } });
791
+ updateState(name, (onDisk) => {
792
+ const cur = onDisk.harness_session;
793
+ const same = !!cur && cur.transcript === transcript && cur.harness === harness;
794
+ const compactions = same ? [...(cur.compactions ?? [])] : [];
795
+ if (compacted)
796
+ compactions.push(observedAt);
797
+ return { ...onDisk, harness_session: { harness, transcript, session_id: sessionId, at: same ? cur.at : observedAt, last_seen_at: observedAt, ...(compactions.length ? { compactions: compactions.slice(-1000) } : {}), ...(same && cur.provider ? { provider: cur.provider } : {}) } };
798
+ });
784
799
  }
@@ -2,6 +2,18 @@ import { spawn } from "node:child_process";
2
2
  import { constants } from "node:os";
3
3
  import { CliError } from "../errors.js";
4
4
  import { forgetLockJob, rememberLockJob } from "../lock-jobs.js";
5
+ /**
6
+ * How many times a lock-run call is repeated after a network failure or a 5xx. Every call carries
7
+ * the job's token, so a repeat is the same request. A release that failed once during a database
8
+ * overload left the lock held with no process behind it (two build hosts' suite locks sat held for
9
+ * 45 minutes), and a failed poll ended a job that was only waiting its turn. The release keeps
10
+ * trying for about two minutes, the others for about 40 seconds; after that the failure is
11
+ * reported as before, naming the job. If a release was applied and only its answer was lost, the
12
+ * repeat is refused (the job no longer holds the lock) and reported: the lock is free then.
13
+ */
14
+ export function lockRunRetries(path) {
15
+ return path.endsWith("/release") ? 20 : 8;
16
+ }
5
17
  /** What a listing shows for the command: one line, at most 200 characters. */
6
18
  export function commandLabel(command) {
7
19
  const line = command.join(" ").replace(/\s+/g, " ").trim();
@@ -756,7 +756,10 @@ export async function poolAdmin(action, rest, p, out, argv) {
756
756
  const [project, name, slot] = parts.map(encodeURIComponent);
757
757
  const reason = str(p.flags, "reason");
758
758
  const r = await c.call("POST", `/projects/${project}/pools/${name}/slots/${slot}/stop`, reason === undefined ? {} : { reason });
759
- return out.print(`Suspended ${target}; its machine will stop the session.`, r);
759
+ const followUp = r.reconciliation?.complete === false
760
+ ? ` Follow-up needed for: ${(r.reconciliation.failed_steps ?? []).join(", ")}.`
761
+ : "";
762
+ return out.print(`Suspended ${target}; its session stop was requested and the agent remains benched until restored.${followUp}`, r);
760
763
  }
761
764
  const KEPT_IN_PLACE = KEPT_IN_PLACE_RE;
762
765
  const statusLines = (pool) => [
@@ -849,7 +852,7 @@ export async function poolAdmin(action, rest, p, out, argv) {
849
852
  const endpoint = `${path(project, name)}/slots/${encodeURIComponent(slot)}/${action === "pin" || action === "unpin" ? "pin" : action === "suspend" ? "suspend" : "restore"}`;
850
853
  return previewOrConfirm(project, name, action, { ...body, slot }, async (revision) => {
851
854
  const r = await c.call(action === "pin" ? "PUT" : action === "unpin" ? "DELETE" : "POST", endpoint, { ...body, impact_revision: revision });
852
- return out.print(`${project}/${name}/${slot}: ${action === "unpin" ? "pin cleared" : action === "restore" ? "slot restored" : action === "suspend" ? "slot suspended" : `pinned to ${machine}${until ? ` until ${until}` : ""}`}.`, r);
855
+ return out.print(`${project}/${name}/${slot}: ${action === "unpin" ? "pin cleared" : action === "restore" ? "slot restored" : action === "suspend" ? "slot suspended; the agent remains benched until restored" : `pinned to ${machine}${until ? ` until ${until}` : ""}`}.`, r);
853
856
  });
854
857
  }
855
858
  if (action === "remove") {
@@ -14,7 +14,8 @@ import { AGY_APPARMOR_PATH, agyAppArmorProfile, BWRAP_APPARMOR_PATH, bwrapAppArm
14
14
  import { applySparse, sessionCheckoutFacts } from "../git.js";
15
15
  import { drainingUntil, writeMaintenance } from "../maintenance.js";
16
16
  import { TURN_HARNESSES, cachedClaudeLogin, claudeFacts, claudeHome, claudeSandbox, dshFacts, dshProcesses, probeFor, sessionProcesses } from "../harnesses.js";
17
- import { readState, writeState } from "../state.js";
17
+ import { writeFileAtomic } from "../shared-file.js";
18
+ import { readState, updateState } from "../state.js";
18
19
  import { installService, launchdFacts, launchdFactsLine, launchdGuidance, launchdSessionNow, lingerEnabled, MACHINE_LABEL, machineDaemonPath, readInstall, removeService, requireInstall, restartWatcher, serviceActive, WATCH_LABEL_PREFIX, watcherServices } from "../install.js";
19
20
  import { CLI_VERSION } from "../version.js";
20
21
  import { probeCapabilities } from "../capabilities.js";
@@ -1338,8 +1339,9 @@ export async function reconcile(m, log, reportIntervalSeconds = 30, deps) {
1338
1339
  }
1339
1340
  let agentState = readState(s.agent, agentStateEnv);
1340
1341
  if (s.turn_resume_at && agentState.turn_resume_applied_at !== s.turn_resume_at) {
1341
- agentState = { ...agentState, turn_guard: resumeTurnGuard(agentState.turn_guard), turn_resume_applied_at: s.turn_resume_at };
1342
- writeState(s.agent, agentState, agentStateEnv);
1342
+ const resumeAt = s.turn_resume_at;
1343
+ // On the state as it is on disk now: the session's watcher writes its turn guard there too.
1344
+ agentState = updateState(s.agent, (onDisk) => ({ ...onDisk, turn_guard: resumeTurnGuard(onDisk.turn_guard), turn_resume_applied_at: resumeAt }), agentStateEnv);
1343
1345
  log(`${s.agent}: operator/assigner resumed turn mode`);
1344
1346
  }
1345
1347
  if (agentState.turn_guard?.fault) {
@@ -1534,7 +1536,8 @@ export async function reconcile(m, log, reportIntervalSeconds = 30, deps) {
1534
1536
  }
1535
1537
  // The operator lifted a usage-limit pause: what b9s codex unpause does, here.
1536
1538
  if (s.unpause_at && state.sessions[s.id].unpause_applied !== s.unpause_at) {
1537
- writeState(s.agent, { ...readState(s.agent, agentStateEnv), turn_unpaused_at: Date.parse(s.unpause_at) }, agentStateEnv);
1539
+ const unpausedAt = Date.parse(s.unpause_at);
1540
+ updateState(s.agent, (onDisk) => ({ ...onDisk, turn_unpaused_at: unpausedAt }), agentStateEnv);
1538
1541
  state.sessions[s.id].unpause_applied = s.unpause_at;
1539
1542
  log(`${s.agent}: usage-limit pause lifted by the operator`);
1540
1543
  }
@@ -1927,8 +1930,8 @@ export function ensureCheckout(s, log, workdir = null) {
1927
1930
  writeFileSync(exclude, `${ex}${ex && !ex.endsWith("\n") ? "\n" : ""}${addExclude.join("\n")}\n`);
1928
1931
  }
1929
1932
  const id = join(dir, ".b9s", "identity.json");
1930
- mkdirSync(dirname(id), { recursive: true });
1931
- writeFileSync(id, JSON.stringify({ agents: { [s.harness]: { name: s.agent_name, project: s.project, ...(s.model ? { model: s.model } : {}) } } }, null, 2) + "\n");
1933
+ // In one step: the agent's hooks and commands read this file while the daemon rewrites it.
1934
+ writeFileAtomic(id, JSON.stringify({ agents: { [s.harness]: { name: s.agent_name, project: s.project, ...(s.model ? { model: s.model } : {}) } } }, null, 2) + "\n");
1932
1935
  return { dir };
1933
1936
  }
1934
1937
  const shq = (x) => `'${x.replace(/'/g, `'\\''`)}'`;
@@ -1,7 +1,7 @@
1
1
  import { str } from "../args.js";
2
2
  import { loadAgent, resolveAgentName } from "../config.js";
3
3
  import { Client } from "../client.js";
4
- import { readState, writeState } from "../state.js";
4
+ import { readState, updateState } from "../state.js";
5
5
  import { CliError } from "../errors.js";
6
6
  /** Explicit, local turn-end note; the watcher sends it only as a bounded unverified excerpt. */
7
7
  export async function turn(p, out) {
@@ -19,7 +19,7 @@ export async function turn(p, out) {
19
19
  const note = p.positionals.slice(2).join(" ").trim();
20
20
  if (!note || [...note].length > 300)
21
21
  throw new CliError("usage", "turn note needs 1 to 300 characters");
22
- writeState(name, { ...state, turn_note: note });
22
+ updateState(name, (onDisk) => ({ ...onDisk, turn_note: note }));
23
23
  out.print("saved a turn-end note; it will be shown as unverified context in the account-scoped judgment packet", { saved: true });
24
24
  }
25
25
  /**
@@ -2,7 +2,7 @@ import { str } from "../args.js";
2
2
  import { Client } from "../client.js";
3
3
  import { loadAgent, resolveAgentName, resolveModel } from "../config.js";
4
4
  import { CliError } from "../errors.js";
5
- import { readState, writeState } from "../state.js";
5
+ import { readState, updateState } from "../state.js";
6
6
  /**
7
7
  * The agent's side of the watcher's numbered wake-ups. Each wake-up asks for this first; the
8
8
  * watcher queues nothing else until it runs, and the server records it so the console can tell
@@ -28,9 +28,15 @@ export async function wake(p, out) {
28
28
  if (!Number.isInteger(seq) || seq < 1)
29
29
  throw new CliError("usage", "wake ack <n>: n is the wake-up's number, e.g. b9s wake ack 17");
30
30
  }
31
- const { next, clears } = applyAck(st, seq);
32
- const pending = st.watch_pending;
33
- writeState(name, next);
31
+ // Applied to the state on disk now: the watcher writes this file every poll.
32
+ let pending;
33
+ let clears = false;
34
+ const next = updateState(name, (onDisk) => {
35
+ pending = onDisk.watch_pending;
36
+ const acked = applyAck(onDisk, seq);
37
+ clears = acked.clears;
38
+ return acked.next;
39
+ });
34
40
  // The ack is the agent's own call, so it also counts as seen.
35
41
  const r = await Client.forAgent(loadAgent(name), resolveModel(str(p.flags, "model"), process.env, process.cwd(), name), { effort: str(p.flags, "effort") }).call("POST", "/agents/me/wake/ack", { seq });
36
42
  const ahead = pending?.seq !== undefined && pending.seq > next.watch_acked ? ` Wake-up #${pending.seq} is still pending: acknowledge that one when you read it.` : "";