benignswarm 0.12.100 → 0.12.101

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/args.js CHANGED
@@ -14,7 +14,7 @@ export const STRING_FLAGS = [
14
14
  "name", "out", "token", "token-file", "prefix", "uses", "expires-hours", "skill-dir", "harness", "provider", "reply-to",
15
15
  "event", "project", "projects", "post", "title", "body", "body-file", "handoff-to", "evidence", "agent",
16
16
  "parent", "parent-item", "channel", "statuses", "assign", "if-status", "status", "exec", "interval",
17
- "requeue-after", "unacked-after", "category", "command", "command-pattern", "follow-delay", "env", "scope",
17
+ "requeue-after", "unacked-after", "category", "command", "command-pattern", "follow-delay", "startup-jitter-seconds", "env", "scope",
18
18
  "scope-file", "scope-from", "append", "pr", "note", "note-file", "add", "remove", "merged", "tag",
19
19
  "activity", "max-unanswered", "to", "replay-of", "branch", "effort", "max-budget-usd", "by", "target", "lands-with",
20
20
  "milestone", "file", "exit", "depends-on", "default-tags", "source", "on", "partial", "question", "ruling",
package/dist/client.js CHANGED
@@ -256,12 +256,14 @@ export class Client {
256
256
  auto;
257
257
  agentName;
258
258
  machineIdentity;
259
- constructor(url, key, auto, agentName, machineIdentity) {
259
+ requestOptions;
260
+ constructor(url, key, auto, agentName, machineIdentity, requestOptions = {}) {
260
261
  this.url = url;
261
262
  this.key = key;
262
263
  this.auto = auto;
263
264
  this.agentName = agentName;
264
265
  this.machineIdentity = machineIdentity;
266
+ this.requestOptions = requestOptions;
265
267
  }
266
268
  /**
267
269
  * presence: send the X-Bschat-Auto header, which refreshes the agent's automatic status and
@@ -275,8 +277,18 @@ export class Client {
275
277
  static forAdmin(c) {
276
278
  return new Client(c.url, c.key, null);
277
279
  }
278
- static raw(url, key) {
279
- return new Client(url, key, null);
280
+ static raw(url, key, requestOptions = {}) {
281
+ return new Client(url, key, null, undefined, null, requestOptions);
282
+ }
283
+ requestSignal(external) {
284
+ const signals = [this.requestOptions.signal, external].filter((signal) => Boolean(signal));
285
+ const timeout = this.requestOptions.requestTimeoutMs ? AbortSignal.timeout(this.requestOptions.requestTimeoutMs) : undefined;
286
+ if (timeout)
287
+ signals.push(timeout);
288
+ return { signal: signals.length > 1 ? AbortSignal.any(signals) : signals[0], timeout };
289
+ }
290
+ timeoutError(method, path) {
291
+ return new CliError("request_timeout", `${method} ${path} timed out after ${this.requestOptions.requestTimeoutMs}ms`);
280
292
  }
281
293
  headers() {
282
294
  const h = { authorization: `Bearer ${this.key}`, "user-agent": cliUserAgent() };
@@ -317,18 +329,28 @@ export class Client {
317
329
  const retries = opts.retries ?? 0;
318
330
  for (let attempt = 0;; attempt++) {
319
331
  let res;
332
+ let text;
333
+ const startedAt = Date.now();
334
+ const { signal, timeout } = this.requestSignal(opts.signal);
335
+ this.requestOptions.onRequest?.({ phase: "start", method, path });
320
336
  try {
321
- res = await fetch(this.url + path, { method, headers, body: body === undefined ? undefined : JSON.stringify(body), signal: opts.signal });
337
+ res = await fetch(this.url + path, { method, headers, body: body === undefined ? undefined : JSON.stringify(body), signal });
338
+ text = await res.text();
322
339
  }
323
340
  catch (e) {
341
+ this.requestOptions.onRequest?.({ phase: "end", method, path, durationMs: Date.now() - startedAt, error: timeout?.aborted ? "timeout" : e.message });
342
+ if (timeout?.aborted)
343
+ throw this.timeoutError(method, path);
344
+ if (this.requestOptions.signal?.aborted || opts.signal?.aborted)
345
+ throw new CliError("request_aborted", `${method} ${path} aborted before completion`);
324
346
  if (attempt < retries) {
325
347
  await backoff(attempt);
326
348
  continue;
327
349
  }
328
350
  throw new CliError("network", `could not reach ${this.url}: ${e.message}`);
329
351
  }
352
+ this.requestOptions.onRequest?.({ phase: "end", method, path, durationMs: Date.now() - startedAt });
330
353
  noteServerVersions(res.headers, this.agentName);
331
- const text = await res.text();
332
354
  let json;
333
355
  try {
334
356
  json = JSON.parse(text);
@@ -18,6 +18,7 @@ import { HARNESS_BIN, HARNESS_LABEL, assertClaudeSelfCheck, claudeCodePath, clau
18
18
  import { claudeTurnEnv } from "../providers.js";
19
19
  import { DEFAULT_TURNS_PER_HOUR, DEFAULT_UNPRODUCTIVE_PER_HOUR, MAX_TURNS_PER_HOUR } from "../turn-guard.js";
20
20
  import { DEFAULT_TURN_COALESCE_SECONDS, MAX_TURN_COALESCE_SECONDS } from "../turn.js";
21
+ import { DEFAULT_WATCH_STARTUP_JITTER_SECONDS, MAX_WATCH_STARTUP_JITTER_SECONDS } from "../startup-jitter.js";
21
22
  import { antigravityConversationDb, antigravityLog, antigravityResumeCommand, antigravitySettings, antigravityTotalTokens, antigravityTurnArgs, antigravityTurnEnv, runAntigravityTurn } from "../antigravity.js";
22
23
  import { configureGitCredentialForWorktree } from "./git-credential.js";
23
24
  const SANDBOXES = ["read-only", "workspace-write", "danger-full-access"];
@@ -31,7 +32,7 @@ export const DEFAULT_CLAUDE_MAX_BUDGET_USD = 1;
31
32
  * from the Codex app's queue silently not delivering wake-ups (fabricbios luna-worker, ten hours).
32
33
  *
33
34
  * b9s start --harness codex|claude-code|dsh|antigravity --as <name> --sandbox <mode> [--token bs_enroll_...]
34
- * [--thread <id>] [--model m] [--effort e] [--turn-timeout 180] [--interval 30] [--prune] [--dsh <path>] [--agy <path>]
35
+ * [--thread <id>] [--model m] [--effort e] [--turn-timeout 180] [--interval 30] [--startup-jitter-seconds 0..60] [--prune] [--dsh <path>] [--agy <path>]
35
36
  */
36
37
  export async function codexStart(p, out) {
37
38
  return harnessStart(p, out, "codex");
@@ -99,6 +100,10 @@ export async function harnessStart(p, out, harness) {
99
100
  const interval = Number(str(p.flags, "interval") ?? "30");
100
101
  if (!Number.isInteger(interval) || interval < 5)
101
102
  throw new CliError("usage", "--interval must be an integer number of seconds, at least 5");
103
+ const startupJitterSeconds = Number(str(p.flags, "startup-jitter-seconds") ?? String(DEFAULT_WATCH_STARTUP_JITTER_SECONDS));
104
+ if (!Number.isInteger(startupJitterSeconds) || startupJitterSeconds < 0 || startupJitterSeconds > MAX_WATCH_STARTUP_JITTER_SECONDS) {
105
+ throw new CliError("usage", `--startup-jitter-seconds must be a whole number from 0 to ${MAX_WATCH_STARTUP_JITTER_SECONDS}`);
106
+ }
102
107
  if (!inContainer && process.platform !== "darwin" && process.platform !== "linux")
103
108
  throw new CliError("unsupported", `${cmd} installs its watcher with launchd (macOS) or systemd (Linux)`);
104
109
  const dshOverride = str(p.flags, "dsh");
@@ -334,12 +339,13 @@ export async function harnessStart(p, out, harness) {
334
339
  "--exec", exec,
335
340
  "--interval", String(interval),
336
341
  "--follow-delay", String(followDelay),
342
+ "--startup-jitter-seconds", String(startupJitterSeconds),
337
343
  ...(prune ? ["--prune"] : []),
338
344
  ...turnArgs(turnSpec),
339
345
  ];
340
346
  }
341
347
  else {
342
- installWatcherService(ref, exec, interval, followDelay, watcherEnv, undefined, { json: false, print: (h) => watcherOut.push(h) }, prune, turnSpec);
348
+ installWatcherService(ref, exec, interval, followDelay, watcherEnv, undefined, { json: false, print: (h) => watcherOut.push(h) }, prune, turnSpec, startupJitterSeconds);
343
349
  const wl = watcherOut.join("\n").split("\n");
344
350
  lines.push(wl[0].replace(/^Wrote /, "Watcher: wrote "), ...wl.filter((l) => l.startsWith("Linger is off")));
345
351
  }
@@ -6,7 +6,7 @@ import { bool } from "../args.js";
6
6
  import { CliError } from "../errors.js";
7
7
  import { binVersion, ensureCommandLinks, ensureInstall, latestPublished, lingerEnabled, readInstall, restartInstallServices, watcherServices } from "../install.js";
8
8
  import { CLI_VERSION } from "../version.js";
9
- import { refreshInstalledHooks } from "../harness.js";
9
+ import { CODEX_REQUIREMENTS_PATH, codexHooksDuplicateWithManagedPolicy, reconcileCodexHooks, refreshInstalledHooks } from "../harness.js";
10
10
  import { configRoot } from "../config.js";
11
11
  import { defaultWorkspaceWritableRoots } from "../start-options.js";
12
12
  import { machineEnvironmentChecks } from "../environment-checks.js";
@@ -28,6 +28,9 @@ export async function install(p, out) {
28
28
  lines.push(`Updated PATH links: ${aliases.created.join(", ")}`);
29
29
  if (aliases.conflicts.length)
30
30
  lines.push(`Could not add PATH links: ${aliases.conflicts.join(", ")}`);
31
+ const managedCodex = reconcileCodexHooks(rec.bin, false);
32
+ if (managedCodex.managed && managedCodex.changed && managedCodex.path)
33
+ lines.push(`Removed duplicate Codex hook registration from ${managedCodex.path}; ${CODEX_REQUIREMENTS_PATH} already registers it.`);
31
34
  const refreshedHooks = bool(p.flags, "latest") ? refreshInstalledHooks(process.cwd(), rec.bin) : [];
32
35
  if (refreshedHooks.length)
33
36
  lines.push(`Updated harness hooks: ${refreshedHooks.join(", ")}`);
@@ -166,6 +169,20 @@ export async function doctor(_p, out) {
166
169
  checks.push({ ok: true, what: `npx caches hold ${npx.length} cop${npx.length === 1 ? "y" : "ies"} (${[...new Set(npx)].sort().join(", ")}); only commands that still say npx use them` });
167
170
  // This repo's hook and instructions.
168
171
  const root = spawnSync("git", ["rev-parse", "--show-toplevel"], { encoding: "utf8" }).stdout?.trim() || process.cwd();
172
+ if (existsSync(CODEX_REQUIREMENTS_PATH) && existsSync(join(process.env.CODEX_HOME ?? join(homedir(), ".codex"), "hooks.json"))) {
173
+ const requirements = readFileSync(CODEX_REQUIREMENTS_PATH, "utf8");
174
+ const codexPath = join(process.env.CODEX_HOME ?? join(homedir(), ".codex"), "hooks.json");
175
+ try {
176
+ const doc = JSON.parse(readFileSync(codexPath, "utf8"));
177
+ if (codexHooksDuplicateWithManagedPolicy(requirements, doc))
178
+ checks.push({ ok: false, what: `b9s Codex hook is registered by both ${CODEX_REQUIREMENTS_PATH} and ${codexPath}`, fix: "b9s setup --as <your agent> (removes only b9s's duplicate user hook entries)" });
179
+ }
180
+ catch (error) {
181
+ if (error instanceof CliError)
182
+ throw error;
183
+ throw new CliError("bad_settings", `${codexPath} is not valid JSON; fix it or remove it`);
184
+ }
185
+ }
169
186
  const sp = join(root, ".claude", "settings.local.json");
170
187
  if (existsSync(sp)) {
171
188
  const hooks = JSON.stringify(JSON.parse(readFileSync(sp, "utf8")).hooks ?? {});
@@ -2,13 +2,12 @@ import { cliUserAgent } from "../legacy-alias.js";
2
2
  import { need, str, bool } from "../args.js";
3
3
  import { agentRef, DEFAULT_URL, loadAgent, resolveModel, saveAgent } from "../config.js";
4
4
  import { spawnSync } from "node:child_process";
5
- import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
6
- import { dirname, join as pathJoin } from "node:path";
5
+ import { existsSync, readFileSync } from "node:fs";
6
+ import { join as pathJoin } from "node:path";
7
7
  import { CliError } from "../errors.js";
8
8
  import { defaultMachine } from "../git.js";
9
9
  import { ensureInstall, readInstall } from "../install.js";
10
- import { codexHooksPath } from "./codex.js";
11
- import { claudeCheckoutOwner, claudeCheckoutTaken, withCodexHooks, HARNESSES, findIdentityFile, installForHarness, normalizeVendor, readIdentityFile, writeIdentity } from "../harness.js";
10
+ import { claudeCheckoutOwner, claudeCheckoutTaken, reconcileCodexHooks, HARNESSES, findIdentityFile, installForHarness, normalizeVendor, readIdentityFile, writeIdentity } from "../harness.js";
12
11
  import { detectVendor } from "../vendor.js";
13
12
  import { CLI_VERSION } from "../version.js";
14
13
  import { assertEnrolledStartProject } from "../start-options.js";
@@ -61,6 +60,11 @@ export async function setup(p, out) {
61
60
  const written = [];
62
61
  for (const h of harnessList(p, vendor))
63
62
  written.push(...installForHarness(root, h, files, ref, creds.url, inst.bin));
63
+ if (harnessList(p, vendor).includes("codex")) {
64
+ const codex = reconcileCodexHooks(inst.bin, false);
65
+ if (codex.managed && codex.changed && codex.path)
66
+ written.push(codex.path);
67
+ }
64
68
  const uniq = [...new Set(written)];
65
69
  const selfTest = harnessList(p, vendor).includes("claude-code") ? verifyClaudeHook(root, ref) : null;
66
70
  out.print(`b9s ${inst.version} for this machine: ${inst.bin}\nRecorded ${vendor} -> ${ref} in ${idPath}\nWrote: ${uniq.join(", ")}${selfTest ? `\n${selfTest}` : ""}`, { install: inst, identity: idPath, written: uniq, hook_verified: !!selfTest });
@@ -122,8 +126,9 @@ export async function join(p, out, expectedProject) {
122
126
  written = [...new Set(written)];
123
127
  }
124
128
  const selfTest = !noBind && !bool(p.flags, "no-skill") && harnessList(p, vendor).includes("claude-code") ? verifyClaudeHook(root, ref) : null;
125
- const codexHookPath = vendor === "codex" ? installCodexHooks(inst.bin) : null;
126
- const hasLocalHook = !!selfTest || !!codexHookPath || written.some((file) => file.endsWith(".agents/hooks.json"));
129
+ const codexHook = vendor === "codex" ? reconcileCodexHooks(inst.bin, true) : null;
130
+ const codexHookPath = codexHook && !codexHook.managed ? codexHook.path : null;
131
+ const hasLocalHook = !!selfTest || !!codexHook || written.some((file) => file.endsWith(".agents/hooks.json"));
127
132
  const wakePathWarnings = hasLocalHook ? [] : (json.wake_path_warnings ?? []);
128
133
  const human = [
129
134
  json.project
@@ -144,7 +149,9 @@ export async function join(p, out, expectedProject) {
144
149
  json.revived && json.resume ? `--- ${json.resume.title} ---\n${json.resume.body}\n---${json.resume.evidence.length ? `\nevidence: ${json.resume.evidence.map((e) => `evidence:${e}`).join(" ")}` : ""}` : null,
145
150
  json.revived && json.resume ? `Read it before doing anything else.` : null,
146
151
  ``,
147
- vendor === "codex" ? `Codex: b9s's hooks are in ${codexHookPath} (approve them when Codex asks); they deliver your mentions and assignments inside your thread once b9s knows which thread is you: b9s codex bind <thread-id>, or a watcher (b9s watch --launchd), which is still what wakes you when you are idle.` : vendor === "antigravity" ? `Antigravity: .agents/hooks.json now delivers your mentions and assignments inside your conversation, once b9s knows which conversation is you: b9s antigravity bind <conversation-id> (the folder name under ~/.gemini/antigravity/brain/ holding your artifacts). A watcher (b9s watch --launchd) also binds it, and is still what wakes you when you are idle.` : vendor !== "claude-code" ? `No hook exists for ${vendor}: you will not be told about replies unless you run a watcher. See the skill's "Knowing when someone talks to you" section (b9s watch --launchd).` : null,
152
+ vendor === "codex" ? (codexHook?.managed
153
+ ? `Codex: b9s's hooks are managed once by /etc/codex/requirements.toml; duplicate user hook entries were removed. They deliver your mentions and assignments inside your thread once b9s knows which thread is you: b9s codex bind <thread-id>, or a watcher (b9s watch --launchd), which is still what wakes you when you are idle.`
154
+ : `Codex: b9s's hooks are in ${codexHookPath} (approve them when Codex asks); they deliver your mentions and assignments inside your thread once b9s knows which thread is you: b9s codex bind <thread-id>, or a watcher (b9s watch --launchd), which is still what wakes you when you are idle.`) : vendor === "antigravity" ? `Antigravity: .agents/hooks.json now delivers your mentions and assignments inside your conversation, once b9s knows which conversation is you: b9s antigravity bind <conversation-id> (the folder name under ~/.gemini/antigravity/brain/ holding your artifacts). A watcher (b9s watch --launchd) also binds it, and is still what wakes you when you are idle.` : vendor !== "claude-code" ? `No hook exists for ${vendor}: you will not be told about replies unless you run a watcher. See the skill's "Knowing when someone talks to you" section (b9s watch --launchd).` : null,
148
155
  `Next: b9s me && b9s who && b9s inbox && b9s handoffs --open`,
149
156
  ].filter((l) => l !== null).join("\n");
150
157
  out.print(human, { install: inst, agent: json.agent, project: json.project, saved: path, identity: idPath, bound: !noBind, written, wake_path_warnings: wakePathWarnings, revived: !!json.revived, resume: json.resume ?? null, export: { BSCHAT_AGENT: ref } });
@@ -202,19 +209,3 @@ function writeIdentityDryRun(root, vendor, name, replace) {
202
209
  throw new CliError("identity_exists", `${p} already maps ${vendor} to agent "${existing.name}"`, `Two ${vendor} agents share this checkout. Join with --no-bind and address yourself per call (b9s --as ${name} ...), or --replace to make "${name}" this checkout's default instead of "${existing.name}".`);
203
210
  }
204
211
  }
205
- /** Merges b9s's hooks into this machine's ~/.codex/hooks.json; returns its path. */
206
- function installCodexHooks(bin) {
207
- const path = codexHooksPath();
208
- let doc = {};
209
- if (existsSync(path)) {
210
- try {
211
- doc = JSON.parse(readFileSync(path, "utf8"));
212
- }
213
- catch {
214
- throw new CliError("bad_settings", `${path} is not valid JSON; fix it or remove it`);
215
- }
216
- }
217
- mkdirSync(dirname(path), { recursive: true });
218
- writeFileSync(path, JSON.stringify(withCodexHooks(doc, bin), null, 2) + "\n");
219
- return path;
220
- }
@@ -1,13 +1,16 @@
1
1
  import { spawnSync } from "node:child_process";
2
+ import { createHash } from "node:crypto";
3
+ import { existsSync, readFileSync } from "node:fs";
2
4
  import { createInterface } from "node:readline/promises";
3
5
  import { bool, need, str } from "../args.js";
4
6
  import { Client } from "../client.js";
5
- import { loadAdmin, resolveAdminName } from "../config.js";
7
+ import { loadAdmin, resolveAdminName, splitRef } from "../config.js";
6
8
  import { CliError } from "../errors.js";
7
9
  import { table } from "../output.js";
8
10
  import { CLI_VERSION } from "../version.js";
9
11
  import { runMachineResize } from "./machine-resize.js";
10
12
  import { poolSuggestionsAdmin } from "./routing-admin.js";
13
+ import { readState, stateFilePath, stateTransferContents } from "../state.js";
11
14
  /**
12
15
  * b9s-admin machine: provision machines over the operator's own ssh and declare the agent
13
16
  * sessions they run (docs/REMOTE-MACHINES.md). The server never sees an ssh credential: every ssh
@@ -730,14 +733,71 @@ function on(host, command, input) {
730
733
  }
731
734
  return ssh(host, command, input);
732
735
  }
733
- function machineMoveReadinessError(machine, harness, provider, sandbox, nowMs = Date.now()) {
734
- const report = machine?.report;
736
+ const STATE_ABSENT = "__B9S_AGENT_STATE_ABSENT__\n";
737
+ const STATE_PRESENT = "__B9S_AGENT_STATE_PRESENT__\n";
738
+ function statePathPrelude(ref) {
739
+ const { scope, name } = splitRef(ref);
740
+ return [
741
+ `new="$HOME/.b9s"; old="$HOME/.bschat";`,
742
+ `if [ -d "$new" ] && [ -d "$old" ] && [ ! -L "$old" ]; then printf '%s\\n' "both $new and $old are real directories; refusing to choose a state tree" >&2; exit 91; fi;`,
743
+ `if [ -L "$new" ]; then printf '%s\\n' "$new is a symlink; refusing to choose a state tree" >&2; exit 91; fi;`,
744
+ `if [ -e "$new" ] && [ ! -d "$new" ]; then printf '%s\\n' "$new is not a directory" >&2; exit 91; fi;`,
745
+ `if [ -e "$old" ] && [ ! -d "$old" ] && [ ! -L "$old" ]; then printf '%s\\n' "$old is not a directory" >&2; exit 91; fi;`,
746
+ `if [ -L "$old" ] && [ ! -d "$new" ]; then printf '%s\\n' "$old is a symlink but $new is not a directory" >&2; exit 91; fi;`,
747
+ `if [ -d "$new" ]; then root="$new"; elif [ -d "$old" ]; then root="$old"; else root="$new"; fi;`,
748
+ `path="$root/state/${scope}/${name}.json"; legacy="$root/state/${name}.json"; if [ ! -e "$path" ] && [ -f "$legacy" ]; then path="$legacy"; fi;`,
749
+ ].join(" ");
750
+ }
751
+ function readAgentStateSnapshot(host, ref) {
752
+ if (host === "local") {
753
+ readState(ref);
754
+ const path = stateFilePath(ref);
755
+ return existsSync(path) ? readFileSync(path, "utf8") : null;
756
+ }
757
+ const result = on(host, `${statePathPrelude(ref)} if [ -f "$path" ]; then printf '${STATE_PRESENT}'; cat "$path"; elif [ -e "$path" ]; then printf '%s\\n' "agent state path is not a regular file" >&2; exit 92; else printf '${STATE_ABSENT}'; fi`);
758
+ if (result.status !== 0)
759
+ throw new CliError("state_read_failed", `could not read ${ref}'s state on ${host}: ${result.stderr.trim() || `exit ${result.status}`}`);
760
+ if (result.stdout.startsWith(STATE_ABSENT))
761
+ return null;
762
+ if (result.stdout.startsWith(STATE_PRESENT))
763
+ return result.stdout.slice(STATE_PRESENT.length);
764
+ throw new CliError("state_read_failed", `could not identify ${ref}'s state response from ${host}`);
765
+ }
766
+ function writeAgentStateSnapshot(host, ref, text, previousText) {
767
+ const path = host === "local" ? stateFilePath(ref) : "";
768
+ const expected = previousText === null ? "missing" : createHash("sha256").update(previousText).digest("hex");
769
+ const code = `const fs=require('node:fs'),path=require('node:path'),crypto=require('node:crypto');const file=process.argv[1],expected=process.argv[2],data=fs.readFileSync(0);let current=null;try{current=fs.readFileSync(file)}catch(e){if(e.code!=='ENOENT')throw e}const actual=current===null?'missing':crypto.createHash('sha256').update(current).digest('hex');if(actual!==expected){console.error('destination agent state changed during transfer');process.exit(93)}JSON.parse(data.toString('utf8'));fs.mkdirSync(path.dirname(file),{recursive:true});const tmp=file+'.b9s-move-'+process.pid+'.tmp';try{fs.writeFileSync(tmp,data,{mode:0o600});fs.chmodSync(tmp,0o600);fs.renameSync(tmp,file)}catch(e){try{fs.rmSync(tmp,{force:true})}catch{}throw e}`;
770
+ const command = host === "local"
771
+ ? `node -e ${shellSingle(code)} ${shellSingle(path)} ${shellSingle(expected)}`
772
+ : `${statePathPrelude(ref)} node -e ${shellSingle(code)} "$path" ${shellSingle(expected)}`;
773
+ const result = on(host, command, text);
774
+ if (result.status !== 0)
775
+ throw new CliError("state_write_failed", `could not copy ${ref}'s state to ${host}: ${result.stderr.trim() || `exit ${result.status}`}`);
776
+ }
777
+ export function transferAgentState(ref, from, to, io = {
778
+ read: readAgentStateSnapshot,
779
+ write: writeAgentStateSnapshot,
780
+ }) {
781
+ if (from === to)
782
+ return false;
783
+ const source = io.read(from, ref);
784
+ if (source === null)
785
+ return false;
786
+ const destination = io.read(to, ref);
787
+ const contents = stateTransferContents(source, destination);
788
+ if (contents === null)
789
+ return false;
790
+ io.write(to, ref, contents, destination);
791
+ return true;
792
+ }
793
+ function machineMoveReadinessError(machine, harness, provider, sandbox, liveSample, nowMs = Date.now()) {
794
+ const report = liveSample ? liveSample.report : machine?.report;
735
795
  if (!report || typeof report !== "object")
736
796
  return `${machine?.name ?? "destination machine"} has not reported; no move was started there`;
737
- const intervalSeconds = Number(report.report_interval_seconds ?? 30);
738
- const reportedAt = Date.parse(machine.last_report_at ?? "");
797
+ const intervalSeconds = Number(liveSample?.report_interval_seconds ?? report.report_interval_seconds ?? 30);
798
+ const reportedAt = Date.parse(liveSample ? liveSample.at ?? "" : machine.last_report_at ?? "");
739
799
  if (!Number.isFinite(reportedAt) || !Number.isFinite(intervalSeconds) || intervalSeconds <= 0 || nowMs - reportedAt > intervalSeconds * 4_000) {
740
- return `${machine.name} has a missing or stale report; refresh the machine before moving an agent there`;
800
+ return `${machine.name} has a missing or stale ${liveSample ? "live sample" : "report"}; refresh the machine before moving an agent there`;
741
801
  }
742
802
  let facts = report[harness];
743
803
  if (harness === "claude-code") {
@@ -828,9 +888,11 @@ export async function agentMove(rest, p, out) {
828
888
  let model = str(p.flags, "model");
829
889
  let effort = str(p.flags, "effort");
830
890
  let problems = [];
891
+ const destinationHost = str(p.flags, "to-ssh") ?? to;
831
892
  try {
832
893
  const destination = await c.call("GET", `/machines/${to}`);
833
- const readinessError = machineMoveReadinessError(destination.machine, harness, provider, sandbox);
894
+ const live = await c.call("GET", `/machines/${to}/live`);
895
+ const readinessError = machineMoveReadinessError(destination.machine, harness, provider, sandbox, live.latest ?? null);
834
896
  if (readinessError)
835
897
  throw new CliError("destination_not_ready", readinessError);
836
898
  // 1. Work in progress must be on origin, or it stays behind on the old machine.
@@ -907,11 +969,10 @@ export async function agentMove(rest, p, out) {
907
969
  const last = lastTurnSettings(src.stdout.slice(nl + 1));
908
970
  model ??= last.model ?? undefined;
909
971
  effort ??= last.effort ?? undefined;
910
- const toHost = str(p.flags, "to-ssh") ?? to;
911
- const put = ssh(toHost, `mkdir -p ~/.codex/sessions/${JSON.stringify(rel.slice(0, rel.lastIndexOf("/")))} && cat > ~/.codex/sessions/${JSON.stringify(rel)}`, src.stdout.slice(nl + 1));
972
+ const put = ssh(destinationHost, `mkdir -p ~/.codex/sessions/${JSON.stringify(rel.slice(0, rel.lastIndexOf("/")))} && cat > ~/.codex/sessions/${JSON.stringify(rel)}`, src.stdout.slice(nl + 1));
912
973
  if (put.status !== 0)
913
- throw new CliError("copy_failed", `copying thread ${thread} to ${toHost}: ${put.stderr.trim()}`);
914
- say(` thread ${thread} copied to ${toHost} (${Math.round((src.stdout.length - nl) / 1024)} KB); the copy on ${from} is now a dead end: archive it in the Codex app there so nobody types into it`);
974
+ throw new CliError("copy_failed", `copying thread ${thread} to ${destinationHost}: ${put.stderr.trim()}`);
975
+ say(` thread ${thread} copied to ${destinationHost} (${Math.round((src.stdout.length - nl) / 1024)} KB); the copy on ${from} is now a dead end: archive it in the Codex app there so nobody types into it`);
915
976
  }
916
977
  else {
917
978
  const wait = Number(str(p.flags, "wait") ?? "10");
@@ -927,6 +988,8 @@ export async function agentMove(rest, p, out) {
927
988
  say(note ? ` resume note saved: ${note.title}` : ` no resume note within ${wait} min; it starts from its units, status and chat`);
928
989
  }
929
990
  }
991
+ if (transferAgentState(ref, from, destinationHost))
992
+ say(` read cursors, follows and watcher state copied to ${destinationHost}`);
930
993
  if (!model || !effort) {
931
994
  const st = ((await c.call("GET", `/projects/${project}/agents/status`)).statuses ?? []).find((s) => s.agent_name === agent);
932
995
  if (!model && st?.model && st.model !== "unknown")
@@ -28,6 +28,7 @@ import { machineResourceTelemetry, parsePageSize } from "../machine-telemetry.js
28
28
  import { macReadiness, macReadinessSteps } from "../macos-readiness.js";
29
29
  import { authorizeWorktreeScope, redactProcessCommand, scanWorktreeProcesses } from "../machine-processes.js";
30
30
  import { collectPruneProtection } from "../prune-protection.js";
31
+ import { runMachineDaemonLoop } from "../machine-daemon.js";
31
32
  import { pruneProjectWorktrees } from "./worktrees.js";
32
33
  export const machineFile = () => join(configRoot(), "machine.json");
33
34
  export function loadMachine() {
@@ -77,7 +78,7 @@ export function maintenanceReport(drain, sessions) {
77
78
  return drain ? { draining: true, until: drain.end, turns_running: sessions.filter((o) => o.turn?.running).length } : null;
78
79
  }
79
80
  /** The `b9s start` arguments that bring a session up (adopting its thread or session when known). */
80
- export function startArgs(s, thread, writable = []) {
81
+ export function startArgs(s, thread, writable = [], startupJitterSeconds) {
81
82
  return [
82
83
  "start", "--harness", s.harness, "--as", s.agent, "--sandbox", s.sandbox, "--turn-timeout", String(s.turn_timeout), "--turns-per-hour", String(s.turns_per_hour ?? DEFAULT_TURNS_PER_HOUR), "--unproductive-per-hour", String(s.unproductive_per_hour ?? DEFAULT_UNPRODUCTIVE_PER_HOUR), "--turn-coalesce-seconds", String(s.turn_coalesce_seconds ?? 180), "--machine-session-id", s.id, "--json",
83
84
  ...((s.provider ?? "anthropic") === "deepseek" ? ["--provider", "deepseek"] : []),
@@ -85,6 +86,7 @@ export function startArgs(s, thread, writable = []) {
85
86
  ...(s.effort ? ["--effort", s.effort] : []),
86
87
  ...(thread ? ["--thread", thread] : []),
87
88
  ...(writable.length && s.sandbox === "workspace-write" ? writable.flatMap((path) => ["--writable-root", path]) : []),
89
+ ...(startupJitterSeconds === undefined ? [] : ["--startup-jitter-seconds", String(startupJitterSeconds)]),
88
90
  ];
89
91
  }
90
92
  const KEY_CHECK_MS = 10 * 60_000;
@@ -97,6 +99,9 @@ export function turnFaultSessionFields(fault) {
97
99
  return { turn_fault_at: new Date(fault.at).toISOString() };
98
100
  }
99
101
  const syncRunner = (cmd, args, opts) => spawnSync(cmd, args, { encoding: "utf8", timeout: opts?.timeout ?? 180_000, cwd: opts?.cwd, env: opts?.env });
102
+ const MACHINE_REQUEST_TIMEOUT_MS = 45_000;
103
+ const MACHINE_PASS_BUDGET_MS = 4 * 60_000;
104
+ const MACHINE_WATCHDOG_MS = 5 * 60_000;
100
105
  export function resolvePinnedImageRef(image) {
101
106
  const raw = (image?.rollback_digest ?? image?.active_digest)?.trim() ?? "";
102
107
  if (!raw || /:latest\b/i.test(raw))
@@ -418,7 +423,7 @@ function readContainerStart(logsDir, agentRef) {
418
423
  export async function launchDesiredSession(opts) {
419
424
  const runner = opts.runner ?? syncRunner;
420
425
  if (!opts.containerMode) {
421
- return runner(opts.bin, startArgs(opts.s, opts.thread, opts.sessionWritable), {
426
+ return runner(opts.bin, startArgs(opts.s, opts.thread, opts.sessionWritable, opts.startupJitterSeconds), {
422
427
  cwd: opts.s.dir,
423
428
  timeout: 180_000,
424
429
  env: { ...process.env, ...opts.secretEnv },
@@ -467,7 +472,7 @@ export async function launchDesiredSession(opts) {
467
472
  B9S_AGENT: opts.s.agent,
468
473
  B9S_HOME: "/home/agent/.b9s",
469
474
  },
470
- command: ["b9s", ...startArgs(opts.s, opts.thread, opts.s.sandbox === "workspace-write" ? ["/workspace"] : []), "--in-container"],
475
+ command: ["b9s", ...startArgs(opts.s, opts.thread, opts.s.sandbox === "workspace-write" ? ["/workspace"] : [], opts.startupJitterSeconds), "--in-container"],
471
476
  });
472
477
  const launchRes = runner(runtime, runArgs, {
473
478
  cwd: opts.s.dir,
@@ -510,7 +515,13 @@ export async function launchDesiredSession(opts) {
510
515
  }
511
516
  /** One pass: make what runs here match what the operator declared, then report. */
512
517
  export async function reconcile(m, log, reportIntervalSeconds = 30, deps) {
513
- const client = Client.raw(m.url, m.key);
518
+ const client = Client.raw(m.url, m.key, {
519
+ requestTimeoutMs: MACHINE_REQUEST_TIMEOUT_MS,
520
+ signal: deps?.signal,
521
+ onRequest: (event) => log(event.phase === "start"
522
+ ? `request start ${event.method} ${event.path}`
523
+ : `request end ${event.method} ${event.path} in ${event.durationMs}ms${event.error ? ` (${event.error})` : ""}`),
524
+ });
514
525
  const me = await client.call("GET", "/machines/me");
515
526
  const desired = me.sessions;
516
527
  await answerWorktreeProcessQueries(client, desired, me.process_queries ?? [], log, deps?.worktreeProcessScanner ?? scanWorktreeProcesses);
@@ -679,6 +690,7 @@ export async function reconcile(m, log, reportIntervalSeconds = 30, deps) {
679
690
  workdir,
680
691
  runner,
681
692
  probeSandbox: deps?.probeSandbox,
693
+ startupJitterSeconds: deps?.startupJitterSeconds,
682
694
  });
683
695
  }
684
696
  finally {
@@ -1328,7 +1340,7 @@ export function machineFacts(providersInUse = ["anthropic"], workdirOrOpts, sess
1328
1340
  const volumeFloorPct = diskFloorPct;
1329
1341
  const req = "/etc/codex/requirements.toml";
1330
1342
  const claude = (probes?.claude ?? (() => claudeReport(path, providersInUse)))();
1331
- const bootedAt = bootTimeMs();
1343
+ const bootedAt = (opts.bootTime ?? bootTimeMs)();
1332
1344
  const gitIdentity = (probes?.gitIdentity ?? (() => readGitIdentity()))();
1333
1345
  const container = (probes?.container ?? (() => probeNestedSandbox()))();
1334
1346
  const imds = (opts.imdsProbe ?? probeImdsIsolation)();
@@ -1341,6 +1353,7 @@ export function machineFacts(providersInUse = ["anthropic"], workdirOrOpts, sess
1341
1353
  metric_availability: { ...telemetryAvailability, home_volume: homeSpace ? "available" : "unavailable" },
1342
1354
  // When this machine last booted: the server ends a maintenance window once the machine is back.
1343
1355
  booted_at: bootedAt === null ? null : new Date(Math.floor(bootedAt / 60_000) * 60_000).toISOString(),
1356
+ booted_at_exact: bootedAt === null ? null : new Date(bootedAt).toISOString(),
1344
1357
  daemon_path: path,
1345
1358
  bschat: { version: CLI_VERSION, bin: requireInstall().bin },
1346
1359
  git_identity: gitIdentity,
@@ -1935,15 +1948,14 @@ export async function machine(p, out) {
1935
1948
  if (!Number.isFinite(interval) || interval < 1 || interval > 3600)
1936
1949
  throw new CliError("usage", "--interval must be from 1 to 3600 seconds");
1937
1950
  log(`running every ${interval}s against ${m.url}`);
1938
- for (;;) {
1939
- try {
1940
- await reconcile(m, log, interval);
1941
- }
1942
- catch (e) {
1943
- log(`pass failed: ${e.message}`);
1944
- }
1945
- await new Promise((r) => setTimeout(r, interval * 1000));
1946
- }
1951
+ const intervalMs = interval * 1000;
1952
+ return runMachineDaemonLoop({
1953
+ intervalMs,
1954
+ passBudgetMs: Math.max(MACHINE_PASS_BUDGET_MS, intervalMs * 4),
1955
+ watchdogMs: Math.max(MACHINE_WATCHDOG_MS, intervalMs * 10),
1956
+ reconcile: (signal) => reconcile(m, log, interval, { signal }),
1957
+ log,
1958
+ });
1947
1959
  }
1948
1960
  throw new CliError("usage", "machine bootstrap | run | once | status | prepare | service | processes --worktree <path>");
1949
1961
  }
@@ -26,6 +26,7 @@ import { beginGuardedTurn, completeGuardedTurn, DEFAULT_TURNS_PER_HOUR, DEFAULT_
26
26
  import { sessionUsage } from "../usage.js";
27
27
  import { collectPruneProtection } from "../prune-protection.js";
28
28
  import { bootTimeMs } from "../boot-time.js";
29
+ import { DEFAULT_WATCH_STARTUP_JITTER_SECONDS, MAX_WATCH_STARTUP_JITTER_SECONDS, waitForWatcherStartup } from "../startup-jitter.js";
29
30
  function omitMeasuresAlreadyIn(text, updates) {
30
31
  if (!text)
31
32
  return updates;
@@ -66,6 +67,10 @@ export async function watch(p, out) {
66
67
  const followDelay = Number(str(p.flags, "follow-delay") ?? "300");
67
68
  if (!Number.isInteger(followDelay) || followDelay < 0)
68
69
  throw new CliError("usage", "--follow-delay must be a non-negative number of seconds");
70
+ const startupJitterSeconds = Number(str(p.flags, "startup-jitter-seconds") ?? String(DEFAULT_WATCH_STARTUP_JITTER_SECONDS));
71
+ if (!Number.isInteger(startupJitterSeconds) || startupJitterSeconds < 0 || startupJitterSeconds > MAX_WATCH_STARTUP_JITTER_SECONDS) {
72
+ throw new CliError("usage", `--startup-jitter-seconds must be a whole number from 0 to ${MAX_WATCH_STARTUP_JITTER_SECONDS}`);
73
+ }
69
74
  const turnMode = bool(p.flags, "turn");
70
75
  const turnTimeout = Number(str(p.flags, "turn-timeout") ?? "180");
71
76
  if (!Number.isInteger(turnTimeout) || turnTimeout < 5)
@@ -130,7 +135,7 @@ export async function watch(p, out) {
130
135
  throw new CliError("usage", `--env ${n}: not set in this shell; run this from a terminal inside the harness (Antigravity's terminal has ANTIGRAVITY_LS_ADDRESS and ANTIGRAVITY_CSRF_TOKEN)`);
131
136
  extraEnv[n] = v;
132
137
  }
133
- return installWatcherService(name, exec, interval, followDelay, extraEnv, str(p.flags, "activity"), out, bool(p.flags, "prune"), turn);
138
+ return installWatcherService(name, exec, interval, followDelay, extraEnv, str(p.flags, "activity"), out, bool(p.flags, "prune"), turn, startupJitterSeconds);
134
139
  }
135
140
  if (!exec && !once)
136
141
  throw new CliError("usage", 'watch --exec "<command>" [--interval 30] | watch --once (print and exit) | watch --exec ... --service (launchd on macOS, systemd on Linux)');
@@ -161,6 +166,11 @@ export async function watch(p, out) {
161
166
  process.once("SIGTERM", () => finish(143));
162
167
  }
163
168
  log(`watching${exec ? `, will run: ${exec}` : ""} every ${interval}s (${full ? "full text" : turnMode ? `turn mode, at most ${turnTimeout} min a turn` : "single wake-up"} mode)`);
169
+ if (!once) {
170
+ await waitForWatcherStartup(startupJitterSeconds, log, (milliseconds) => waitIntervalOrStop(milliseconds, stopped));
171
+ if (stopping)
172
+ return stoppingCode;
173
+ }
164
174
  // Harness liveness: the files the harness writes while it works, found from the wake command's
165
175
  // session id or given with --activity. Without one the server shows this agent as "unknown"
166
176
  // when it goes quiet, which is honest; say so once.
@@ -608,6 +618,68 @@ export function estimatedTurnCostMicros(reservation, tokens) {
608
618
  }
609
619
  const TURN_RETRY_MS = 5 * 60_000;
610
620
  const KEY_CHECK_MS = 5 * 60_000;
621
+ const MACHINE_PRESSURE_NOTICE_INTERVAL_MS = 30 * 60_000;
622
+ /** Respect critical pressure for turns; pressure alone never changes the agent's session or wake state. */
623
+ async function machinePressureAllowsTurn(name, env, log, sessionId = env.BSCHAT_MACHINE_SESSION_ID) {
624
+ if (!sessionId)
625
+ return true;
626
+ const prior = readState(name, env).machine_pressure_notice;
627
+ let pressure;
628
+ try {
629
+ const response = await Client.forAgent(loadAgent(name, env), undefined, { presence: false }).call("GET", `/agents/me/sessions/${sessionId}/turn-state`);
630
+ pressure = response.machine_pressure;
631
+ }
632
+ catch {
633
+ // Unavailability cannot clear an established critical hold. For an identity without such a
634
+ // hold, the managed turn-policy request below remains independently fail-closed.
635
+ return !(prior?.critical_hold || prior?.state === "critical");
636
+ }
637
+ const state = pressure?.state;
638
+ if (!pressure || !state || !["normal", "pressured", "critical", "unknown"].includes(state))
639
+ return !(prior?.critical_hold || prior?.state === "critical");
640
+ const held = Boolean(pressure?.critical_hold || pressure?.blocks_turns || prior?.critical_hold || prior?.state === "critical");
641
+ const freshNormal = state === "normal" && pressure?.freshness === "fresh";
642
+ const criticalHold = state === "critical" || (held && !freshNormal);
643
+ const recoveryPending = Boolean(prior?.recovery_hold || state === "pressured" || state === "critical");
644
+ let resumeAfter = prior?.state === "normal" && !prior.recovery_hold ? prior.resume_after : undefined;
645
+ if (freshNormal && recoveryPending) {
646
+ // Stable per-identity jitter spreads recovery across a 60-second window without sleeping or
647
+ // killing a watcher. Each poll reevaluates the recorded deadline.
648
+ let hash = 0;
649
+ for (const char of `${name}:${pressure.sample_at ?? ""}`)
650
+ hash = (hash * 31 + char.charCodeAt(0)) >>> 0;
651
+ resumeAfter = Date.now() + (hash % 60_000);
652
+ }
653
+ const observedChanged = prior?.state !== state;
654
+ let pendingNotice = prior?.pending_notice;
655
+ if (observedChanged && (state !== "normal" || (prior && prior.state !== "normal"))) {
656
+ pendingNotice = { state, ...(pressure.machine ? { machine: pressure.machine } : {}), ...(pressure.reasons?.length ? { reasons: pressure.reasons.slice(0, 3) } : {}), age_seconds: pressure.age_seconds, ...(prior?.state ? { from_state: prior.state } : {}) };
657
+ }
658
+ let lastNoticeAt = prior?.last_notice_at;
659
+ if (pendingNotice && (!lastNoticeAt || Date.now() - lastNoticeAt >= MACHINE_PRESSURE_NOTICE_INTERVAL_MS)) {
660
+ const machine = pendingNotice.machine ?? "this machine";
661
+ const reasons = pendingNotice.reasons?.length ? ` (${pendingNotice.reasons.join(", ")})` : "";
662
+ const age = pendingNotice.age_seconds === null || pendingNotice.age_seconds === undefined ? "unknown age" : `${Math.round(pendingNotice.age_seconds)}s old`;
663
+ if (pendingNotice.state === "critical")
664
+ log(`machine pressure critical on ${machine}${reasons}; last sample ${age}; no new turn starts, session and pending wake are preserved; reevaluating on the next watcher poll`);
665
+ else if (pendingNotice.state === "pressured" || pendingNotice.state === "unknown")
666
+ log(`machine pressure ${pendingNotice.state} on ${machine}${reasons}; light turns may continue, heavy permits remain paused; last sample ${age}; reevaluating on the next machine sample`);
667
+ else if (pendingNotice.from_state && pendingNotice.from_state !== "normal")
668
+ log(`machine pressure cleared on ${machine}; staggered turn recovery begins${resumeAfter && resumeAfter > Date.now() ? ` after ${new Date(resumeAfter).toISOString()}` : " now"}`);
669
+ lastNoticeAt = Date.now();
670
+ pendingNotice = undefined;
671
+ }
672
+ writeState(name, { ...readState(name, env), machine_pressure_notice: {
673
+ state, ...(pressure.machine ? { machine: pressure.machine } : {}), ...(resumeAfter ? { resume_after: resumeAfter } : {}),
674
+ ...(criticalHold ? { critical_hold: true } : {}), ...(recoveryPending && !freshNormal ? { recovery_hold: true } : {}),
675
+ ...(lastNoticeAt ? { last_notice_at: lastNoticeAt } : {}), ...(pendingNotice ? { pending_notice: pendingNotice } : {}),
676
+ } }, env);
677
+ if (criticalHold)
678
+ return false;
679
+ if (state === "normal" && resumeAfter && Date.now() < resumeAfter)
680
+ return false;
681
+ return true;
682
+ }
611
683
  /**
612
684
  * One poll in turn mode. While a turn runs nothing else starts: the turn's own hooks (Stop with new
613
685
  * direct items) keep it going. The wake-up is acknowledged by the watcher once the session file
@@ -782,6 +854,10 @@ export async function turnStep(ctl, probe, timeoutMin, log, wake, name, turnsPer
782
854
  debug(`no inbox poll: machine maintenance runs until ${maint.end}`);
783
855
  return;
784
856
  }
857
+ if (!(await machinePressureAllowsTurn(name, env, log))) {
858
+ debug("no inbox poll: critical machine pressure or staggered recovery is holding new turns; session and pending wake are preserved");
859
+ return;
860
+ }
785
861
  const st = readState(name, env);
786
862
  if (st.watch_pending) {
787
863
  debug(`no inbox poll: wake-up ${st.watch_pending.seq ?? "(legacy)"} is still pending`);
@@ -842,6 +918,8 @@ export async function beginTurnGuardAttempt(name, turnsPerHour, log, env = proce
842
918
  return false;
843
919
  }
844
920
  }
921
+ if (!(await machinePressureAllowsTurn(name, env, log, machineSessionId)))
922
+ return false;
845
923
  const before = await turnActivity(name, env);
846
924
  current = readState(name, env);
847
925
  if (current.turn_guard?.fault) {
@@ -1107,9 +1185,9 @@ function run(cmd, stdin, env) {
1107
1185
  * Installs the watcher as a service that keeps it running for this identity: a LaunchAgent on macOS,
1108
1186
  * a systemd user unit on Linux. Both run the machine's recorded install from this directory.
1109
1187
  */
1110
- export function installWatcherService(name, exec, interval, followDelay, extraEnv, activity, out, prune = false, turn = null) {
1188
+ export function installWatcherService(name, exec, interval, followDelay, extraEnv, activity, out, prune = false, turn = null, startupJitterSeconds = DEFAULT_WATCH_STARTUP_JITTER_SECONDS) {
1111
1189
  if (process.platform === "darwin")
1112
- return installLaunchd(name, exec, interval, followDelay, extraEnv, activity, out, prune, turn);
1190
+ return installLaunchd(name, exec, interval, followDelay, extraEnv, activity, out, prune, turn, startupJitterSeconds);
1113
1191
  if (process.platform !== "linux")
1114
1192
  throw new CliError("unsupported", "--service runs watchers under launchd (macOS) or systemd (Linux); on this system run b9s watch under your own supervisor");
1115
1193
  const slug = name.replace("/", ".");
@@ -1117,7 +1195,7 @@ export function installWatcherService(name, exec, interval, followDelay, extraEn
1117
1195
  const logDir = join(configRoot(), "logs");
1118
1196
  mkdirSync(systemdUserDir(), { recursive: true });
1119
1197
  mkdirSync(logDir, { recursive: true });
1120
- const args = [requireInstall().bin, "watch", "--as", name, "--exec", exec, "--interval", String(interval), "--follow-delay", String(followDelay), ...(activity ? ["--activity", activity] : []), ...(prune ? ["--prune"] : []), ...turnArgs(turn)];
1198
+ const args = [requireInstall().bin, "watch", "--as", name, "--exec", exec, "--interval", String(interval), "--follow-delay", String(followDelay), "--startup-jitter-seconds", String(startupJitterSeconds), ...(activity ? ["--activity", activity] : []), ...(prune ? ["--prune"] : []), ...turnArgs(turn)];
1121
1199
  const env = { PATH: process.env.PATH ?? "/usr/local/bin:/usr/bin:/bin", HOME: homedir(), ...extraEnv };
1122
1200
  const path = join(systemdUserDir(), `${label}.service`);
1123
1201
  writeFileSync(path, systemdUnit(label, args, process.cwd(), env, logDir));
@@ -1136,7 +1214,7 @@ export function installWatcherService(name, exec, interval, followDelay, extraEn
1136
1214
  ].filter(Boolean).join("\n"), { unit: path, label, program: args[0], linger });
1137
1215
  }
1138
1216
  /** Writes a launchd agent that keeps `b9s watch` running for this identity on macOS. */
1139
- function installLaunchd(name, exec, interval, followDelay, extraEnv, activity, out, prune = false, turn = null) {
1217
+ function installLaunchd(name, exec, interval, followDelay, extraEnv, activity, out, prune = false, turn = null, startupJitterSeconds = DEFAULT_WATCH_STARTUP_JITTER_SECONDS) {
1140
1218
  if (process.platform !== "darwin")
1141
1219
  throw new CliError("unsupported", "--launchd is macOS only; on Linux run `b9s watch` under a systemd user service");
1142
1220
  const slug = name.replace("/", ".");
@@ -1159,7 +1237,8 @@ function installLaunchd(name, exec, interval, followDelay, extraEnv, activity, o
1159
1237
  <string>--interval</string><string>${interval}</string>
1160
1238
  <string>--follow-delay</string><string>${followDelay}</string>${activity ? `
1161
1239
  <string>--activity</string><string>${escapeXml(activity)}</string>` : ""}${prune ? `
1162
- <string>--prune</string>` : ""}${turnArgs(turn).length ? `
1240
+ <string>--prune</string>` : ""}
1241
+ <string>--startup-jitter-seconds</string><string>${startupJitterSeconds}</string>${turnArgs(turn).length ? `
1163
1242
  ${turnArgs(turn).map((a) => `<string>${escapeXml(a)}</string>`).join("")}` : ""}
1164
1243
  </array>
1165
1244
  <key>EnvironmentVariables</key><dict><key>PATH</key><string>${escapeXml(process.env.PATH ?? "/usr/local/bin:/usr/bin:/bin")}</string><key>HOME</key><string>${homedir()}</string>${Object.entries(extraEnv).map(([k, v]) => `<key>${escapeXml(k)}</key><string>${escapeXml(v)}</string>`).join("")}</dict>
package/dist/harness.js CHANGED
@@ -188,7 +188,7 @@ export function installForHarness(root, harness, files, agentName, apiUrl, bin)
188
188
  return written;
189
189
  }
190
190
  /** Refresh existing machine hook settings to the current recorded install after `install --latest`. */
191
- export function refreshInstalledHooks(root, bin) {
191
+ export function refreshInstalledHooks(root, bin, requirementsPath = CODEX_REQUIREMENTS_PATH) {
192
192
  const written = [];
193
193
  const claude = join(root, ".claude", "settings.local.json");
194
194
  if (existsSync(claude)) {
@@ -212,8 +212,17 @@ export function refreshInstalledHooks(root, bin) {
212
212
  catch {
213
213
  throw new CliError("bad_settings", `${codex} is not valid JSON; fix it or remove it`);
214
214
  }
215
- writeFileSync(codex, JSON.stringify(withCodexHooks(settings, bin), null, 2) + "\n");
216
- written.push(codex);
215
+ if (codexManagedPolicyInstalled(requirementsPath)) {
216
+ const cleaned = removeCodexHooks(settings);
217
+ if (JSON.stringify(cleaned) !== JSON.stringify(settings)) {
218
+ writeFileSync(codex, JSON.stringify(cleaned, null, 2) + "\n");
219
+ written.push(codex);
220
+ }
221
+ }
222
+ else {
223
+ writeFileSync(codex, JSON.stringify(withCodexHooks(settings, bin), null, 2) + "\n");
224
+ written.push(codex);
225
+ }
217
226
  }
218
227
  const antigravity = join(root, ".agents", "hooks.json");
219
228
  if (existsSync(antigravity)) {
@@ -302,12 +311,76 @@ export function antigravityHooks(bin) {
302
311
  };
303
312
  }
304
313
  const CODEX_HOOK_MARK = "hook codex";
314
+ export const CODEX_REQUIREMENTS_PATH = "/etc/codex/requirements.toml";
315
+ /** True only for the policy file b9s writes; unrelated machine policies are not treated as ours. */
316
+ export function codexManagedPolicyInstalled(path = CODEX_REQUIREMENTS_PATH) {
317
+ if (!existsSync(path))
318
+ return false;
319
+ let text;
320
+ try {
321
+ text = readFileSync(path, "utf8");
322
+ }
323
+ catch (error) {
324
+ throw new CliError("codex_policy_unreadable", `cannot inspect ${path}: ${error.message}`);
325
+ }
326
+ return isCodexManagedRequirements(text);
327
+ }
328
+ /** Strip only b9s command entries, preserving user hooks even when they share a Codex group. */
329
+ export function removeCodexHooks(doc) {
330
+ const hooks = { ...(doc.hooks ?? {}) };
331
+ let changed = false;
332
+ for (const [event, rawGroups] of Object.entries(hooks)) {
333
+ if (!Array.isArray(rawGroups))
334
+ continue;
335
+ hooks[event] = rawGroups.flatMap((group) => {
336
+ const entries = (group.hooks ?? []).filter((entry) => !(typeof entry.command === "string" && entry.command.includes(CODEX_HOOK_MARK)));
337
+ if (entries.length !== (group.hooks ?? []).length)
338
+ changed = true;
339
+ return entries.length ? [{ ...group, hooks: entries }] : [];
340
+ });
341
+ }
342
+ return changed ? { ...doc, hooks } : doc;
343
+ }
344
+ export function codexHooksDuplicateWithManagedPolicy(requirements, doc) {
345
+ if (!isCodexManagedRequirements(requirements))
346
+ return false;
347
+ return Object.values(doc.hooks ?? {}).some((rawGroups) => Array.isArray(rawGroups) && rawGroups.some((raw) => {
348
+ const group = raw;
349
+ return (group.hooks ?? []).some((entry) => typeof entry.command === "string" && entry.command.includes(CODEX_HOOK_MARK));
350
+ }));
351
+ }
352
+ /** Reconcile Codex's user hook with the machine policy. Managed registration always wins. */
353
+ export function reconcileCodexHooks(bin, registerIfUnmanaged, requirementsPath = CODEX_REQUIREMENTS_PATH) {
354
+ const managed = codexManagedPolicyInstalled(requirementsPath);
355
+ const path = join(process.env.CODEX_HOME ?? join(homedir(), ".codex"), "hooks.json");
356
+ if (!managed && !registerIfUnmanaged)
357
+ return { managed, path: null, changed: false };
358
+ let settings = {};
359
+ if (existsSync(path)) {
360
+ try {
361
+ settings = JSON.parse(readFileSync(path, "utf8"));
362
+ }
363
+ catch {
364
+ throw new CliError("bad_settings", `${path} is not valid JSON; fix it or remove it`);
365
+ }
366
+ }
367
+ const next = managed ? removeCodexHooks(settings) : withCodexHooks(settings, bin);
368
+ const before = JSON.stringify(settings);
369
+ const after = JSON.stringify(next);
370
+ if (managed && before === after)
371
+ return { managed, path, changed: false };
372
+ if (managed && !existsSync(path))
373
+ return { managed, path: null, changed: false };
374
+ mkdirSync(dirname(path), { recursive: true });
375
+ writeFileSync(path, JSON.stringify(next, null, 2) + "\n");
376
+ return { managed, path, changed: before !== after };
377
+ }
305
378
  /**
306
379
  * Merges b9s's hooks into a Codex hooks.json document ({"hooks": {Event: [groups]}}): any
307
380
  * earlier b9s group is replaced, every other hook is kept. Commands carry no identity.
308
381
  */
309
382
  export function withCodexHooks(doc, bin) {
310
- const hooks = { ...(doc.hooks ?? {}) };
383
+ const hooks = { ...(removeCodexHooks(doc).hooks ?? {}) };
311
384
  const cmd = (event) => ({ type: "command", command: `${shellPath(bin)} ${CODEX_HOOK_MARK} --event ${event}`, timeout: 20 });
312
385
  const ours = {
313
386
  SessionStart: { matcher: "startup|resume|clear|compact", hooks: [cmd("SessionStart")] },
@@ -316,8 +389,7 @@ export function withCodexHooks(doc, bin) {
316
389
  Stop: { hooks: [cmd("Stop")] },
317
390
  };
318
391
  for (const [event, group] of Object.entries(ours)) {
319
- const kept = (hooks[event] ?? []).filter((g) => !(g.hooks ?? []).some((h) => typeof h.command === "string" && h.command.includes(CODEX_HOOK_MARK)));
320
- hooks[event] = [...kept, group];
392
+ hooks[event] = [...(hooks[event] ?? []), group];
321
393
  }
322
394
  return { ...doc, hooks };
323
395
  }
package/dist/help.js CHANGED
@@ -181,6 +181,7 @@ Agent commands
181
181
  unacknowledged wake-up is logged after --unacked-after 1800 s (once an hour), never re-queued.
182
182
  Tiers: direct (@you, replies, assignments, operator) wake now; @role wakes now;
183
183
  followed-channel chatter waits --follow-delay 300 s and collapses; digest never wakes.
184
+ Persistent watchers wait a logged random 0..60 s before startup calls/scans (--startup-jitter-seconds 0..60; 0 disables) to spread upgrades.
184
185
  --env A,B copies those variables from this shell into the LaunchAgent (Antigravity needs
185
186
  ANTIGRAVITY_LS_ADDRESS,ANTIGRAVITY_CSRF_TOKEN). --full queues the text itself. --once /
186
187
  Set BSCHAT_WATCH_DEBUG=1 for per-poll item counts, tier and wake decisions.
@@ -206,9 +207,12 @@ Agent commands
206
207
  b9s environment report --project <p> | --machine <m> --title <text> --category <name> --component <name> --description <what failed> [--normalized-key <key>] [--evidence <id,...>] [--units <id,...>]
207
208
  submit a bounded observation; evidence is account-scoped, and agents may link only their own units
208
209
  b9s codex hooks | bind <thread-id> | sync install b9s's Codex hooks (~/.codex/hooks.json) and say which thread is you
209
- b9s start --harness codex|claude-code|dsh|antigravity --as <project>/<name> --sandbox <mode> [--provider anthropic|deepseek] [--token t] [--thread id] [--model m] [--effort e] [--writable-root path]... [--max-budget-usd n] [--turns-per-hour 1..60] [--unproductive-per-hour 1..60] [--turn-coalesce-seconds 0..3600] [--machine-session-id uuid] [--dsh path] [--agy path]
210
+ b9s start --harness codex|claude-code|dsh|antigravity --as <project>/<name> --sandbox <mode> [--provider anthropic|deepseek] [--token t] [--thread id] [--model m] [--effort e] [--writable-root path]... [--max-budget-usd n] [--turns-per-hour 1..60] [--unproductive-per-hour 1..60] [--turn-coalesce-seconds 0..3600] [--startup-jitter-seconds 0..60] [--machine-session-id uuid] [--dsh path] [--agy path]
210
211
  run an agent headless: enroll, start or adopt its session, turn-mode watcher
211
212
  --machine-session-id is normally supplied by b9s-admin for a managed machine session
213
+ Persistent watcher startup waits a random logged 0..60 s by default; set --startup-jitter-seconds 0 to disable it for a deterministic start.
214
+ At critical machine pressure, the watcher waits before the next turn; running turns and sessions stay in place.
215
+ Pressured or unknown telemetry holds heavy permits; ordinary turns remain available.
212
216
  Claude Code workspace-write defaults to a $1 per-turn cap; configure it with --max-budget-usd
213
217
  Account turn-spend caps are set by the account operator separately; token caps support subscriptions,
214
218
  missing usage remains reserved. Judgment capture has a separate default-off activation in console WU #238.
@@ -385,7 +389,8 @@ Machines (provisioned over your own ssh; a daemon on each runs the agent session
385
389
  b9s-admin agent move <project>/<agent> --to <machine> --sandbox <mode> --from local|<ssh host> [--dir <path>|auto]
386
390
  [--harness codex|claude-code] [--provider anthropic|deepseek] [--carry note|thread]
387
391
  [--model m] [--effort e] [--wait min] [--force --confirm-force <project>/<agent>]
388
- opens a server move operation, checks the source worktrees and transfers context locally,
392
+ opens a server move operation, checks source worktrees, transfers thread/note plus local agent state over SSH,
393
+ refuses newer destination state and avoids duplicate Codex hooks under managed policy,
389
394
  then commits the session only after handoff succeeds; work left on the source requires both flags
390
395
  b9s-admin machine label <name> <label...> [--remove a,b] what cannot be measured (lab-lan, builds); pools' --needs match it
391
396
  b9s-admin machine slots <name> <n | auto> how many sessions it takes (auto: one per 4 GB of RAM)
@@ -0,0 +1,58 @@
1
+ const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
2
+ /** Run machine passes with a cancellable budget and exit if no pass completes successfully. */
3
+ export async function runMachineDaemonLoop(options) {
4
+ const now = options.now ?? Date.now;
5
+ const wait = options.sleep ?? sleep;
6
+ const exit = options.exit ?? ((code) => process.exit(code));
7
+ let lastCompleted = now();
8
+ let recovering = false;
9
+ let stopped = false;
10
+ const watchdog = setInterval(() => {
11
+ const stalledFor = now() - lastCompleted;
12
+ if (stalledFor < options.watchdogMs || stopped)
13
+ return;
14
+ stopped = true;
15
+ options.log(`watchdog: no completed reconcile pass for ${Math.round(stalledFor / 1000)}s; exiting non-zero`);
16
+ exit(1);
17
+ }, Math.max(10, Math.min(options.intervalMs, 1000)));
18
+ try {
19
+ while (!stopped && !options.shutdownSignal?.aborted) {
20
+ const startedAt = now();
21
+ const controller = new AbortController();
22
+ let timeout;
23
+ options.log("reconcile pass started");
24
+ try {
25
+ const deadline = new Promise((_resolve, reject) => {
26
+ timeout = setTimeout(() => {
27
+ const error = new Error(`reconcile pass exceeded ${options.passBudgetMs}ms budget`);
28
+ controller.abort(error);
29
+ reject(error);
30
+ }, options.passBudgetMs);
31
+ });
32
+ await Promise.race([options.reconcile(controller.signal), deadline]);
33
+ const elapsed = now() - startedAt;
34
+ lastCompleted = now();
35
+ if (recovering)
36
+ options.log(`recovered: reconcile pass completed after a stalled or failed pass (${Math.round(elapsed)}ms)`);
37
+ else
38
+ options.log(`reconcile pass completed in ${Math.round(elapsed)}ms`);
39
+ recovering = false;
40
+ }
41
+ catch (error) {
42
+ recovering = true;
43
+ // A timed-out/failed attempt still proves the loop is advancing. The request and pass
44
+ // budgets keep retrying; the watchdog is for a daemon that has stopped advancing at all.
45
+ lastCompleted = now();
46
+ options.log(`pass failed: ${error.message}`);
47
+ }
48
+ finally {
49
+ if (timeout)
50
+ clearTimeout(timeout);
51
+ }
52
+ await wait(options.intervalMs);
53
+ }
54
+ }
55
+ finally {
56
+ clearInterval(watchdog);
57
+ }
58
+ }
package/dist/output.js CHANGED
@@ -49,8 +49,9 @@ export function fmtMessage(m) {
49
49
  return `${m.created_at.slice(11, 19)} ${ch}${String(m.seq).padStart(5)} ${m.agent_name}${role}: ${m.body}`;
50
50
  }
51
51
  export function fmtStatus(s) {
52
+ const machineWaiting = s.machine_pressure?.waiting === true;
52
53
  const parts = [
53
- `${s.state === "benched" ? "BENCHED " : ""}${s.agent_name}${s.role_name ? `[${s.role_name}]` : ""}${s.away ? ` (away until ${s.away.until}: ${s.away.reason})` : s.usage_limit_until ? ` (usage limit until ${s.usage_limit_until})` : s.liveness === "quiet" ? " (quiet: harness went silent)" : s.liveness === "unknown" ? " (stale, harness unmonitored)" : s.liveness === "scheduled" ? ` (checks every ${s.checks_every} min, next ${(s.next_check_at ?? "").slice(11, 16)} UTC)` : s.liveness === "missed" ? ` (missed its ${s.checks_every}-min check)` : ""}`,
54
+ `${s.state === "benched" ? "BENCHED " : ""}${s.agent_name}${s.role_name ? `[${s.role_name}]` : ""}${s.away ? ` (away until ${s.away.until}: ${s.away.reason})` : s.usage_limit_until ? ` (usage limit until ${s.usage_limit_until})` : machineWaiting ? s.machine_pressure.blocks_turns ? " (next turn held: critical machine pressure)" : " (waiting: heavy machine permit)" : s.liveness === "quiet" ? " (quiet: harness went silent)" : s.liveness === "unknown" ? " (stale, harness unmonitored)" : s.liveness === "scheduled" ? ` (checks every ${s.checks_every} min, next ${(s.next_check_at ?? "").slice(11, 16)} UTC)` : s.liveness === "missed" ? ` (missed its ${s.checks_every}-min check)` : ""}`,
54
55
  `state=${s.state ?? "-"}`,
55
56
  s.goal ? `goal="${s.goal}"` : null,
56
57
  s.task ? `task="${s.task}"` : null,
@@ -58,6 +59,7 @@ export function fmtStatus(s) {
58
59
  `model=${s.model ?? "-"}`,
59
60
  s.machine ? `machine=${s.machine}` : null,
60
61
  s.machine_pressure ? `machine_health=${s.machine_pressure.state ?? "unknown"} (sample_age=${typeof s.machine_pressure.age_seconds === "number" ? `${Math.floor(s.machine_pressure.age_seconds)}s` : "unknown"}${s.machine_pressure.reasons?.length ? `; reasons=${s.machine_pressure.reasons.join(",")}` : ""})` : null,
62
+ machineWaiting ? `machine_wait=${s.machine_pressure.blocks_turns ? "next_turn_critical_pressure" : "heavy_permit"}` : null,
61
63
  s.capabilities?.length ? `capabilities=${s.capabilities.map((c) => `${c.name}:${c.ready ? c.version ?? "ok" : c.error ?? "stale/unknown"}`).join(",")}` : null,
62
64
  s.branch ? `branch=${s.branch}${s.dirty ? "*" : ""}@${s.head ?? "?"}` : null,
63
65
  s.worktree ? `worktree=${s.worktree}` : null,
@@ -0,0 +1,22 @@
1
+ export const DEFAULT_WATCH_STARTUP_JITTER_SECONDS = 60;
2
+ export const MAX_WATCH_STARTUP_JITTER_SECONDS = 60;
3
+ /** Select one delay for this watcher process; independently sampled starts spread their first calls. */
4
+ export function watcherStartupDelayMs(maxSeconds = DEFAULT_WATCH_STARTUP_JITTER_SECONDS, random = Math.random) {
5
+ if (!Number.isInteger(maxSeconds) || maxSeconds < 0 || maxSeconds > MAX_WATCH_STARTUP_JITTER_SECONDS) {
6
+ throw new RangeError(`watcher startup jitter must be a whole number from 0 to ${MAX_WATCH_STARTUP_JITTER_SECONDS} seconds`);
7
+ }
8
+ const sample = random();
9
+ if (!Number.isFinite(sample))
10
+ throw new RangeError("watcher startup jitter random sample must be finite");
11
+ return Math.floor(Math.max(0, Math.min(1, sample)) * maxSeconds * 1000);
12
+ }
13
+ /** Log and await the per-process delay before any startup scan or server call. */
14
+ export async function waitForWatcherStartup(maxSeconds, log, wait = (milliseconds) => new Promise((resolve) => setTimeout(resolve, milliseconds)), random = Math.random) {
15
+ const delayMs = watcherStartupDelayMs(maxSeconds, random);
16
+ log(delayMs > 0
17
+ ? `startup jitter: delaying initial server calls and scans by ${delayMs}ms (window 0..${maxSeconds}s)`
18
+ : `startup jitter: selected 0ms (window 0..${maxSeconds}s)`);
19
+ if (delayMs > 0)
20
+ await wait(delayMs);
21
+ return delayMs;
22
+ }
package/dist/state.js CHANGED
@@ -3,7 +3,7 @@ import { CliError } from "./errors.js";
3
3
  import { join } from "node:path";
4
4
  import { configRoot, isRef, splitRef } from "./config.js";
5
5
  /** State is keyed by agent ref (`<scope>/<name>`), like credentials. */
6
- function statePath(ref, env = process.env) {
6
+ export function stateFilePath(ref, env = process.env) {
7
7
  const { scope, name } = splitRef(ref);
8
8
  return join(configRoot(env), "state", scope, `${name}.json`);
9
9
  }
@@ -12,14 +12,14 @@ function adoptLegacyState(ref, env) {
12
12
  const legacy = join(configRoot(env), "state", `${splitRef(ref).name}.json`);
13
13
  if (!existsSync(legacy))
14
14
  return;
15
- const p = statePath(ref, env);
15
+ const p = stateFilePath(ref, env);
16
16
  mkdirSync(join(p, ".."), { recursive: true });
17
17
  renameSync(legacy, p);
18
18
  }
19
19
  export function readState(ref, env = process.env) {
20
20
  if (!isRef(ref))
21
21
  throw new Error(`readState needs an agent ref, got ${JSON.stringify(ref)}`);
22
- const p = statePath(ref, env);
22
+ const p = stateFilePath(ref, env);
23
23
  if (!existsSync(p))
24
24
  adoptLegacyState(ref, env);
25
25
  if (!existsSync(p))
@@ -36,7 +36,7 @@ export function readState(ref, env = process.env) {
36
36
  return { inbox_after: "", last_check: 0, ...saved };
37
37
  }
38
38
  export function writeState(agent, state, env = process.env) {
39
- const p = statePath(agent, env);
39
+ const p = stateFilePath(agent, env);
40
40
  mkdirSync(join(p, ".."), { recursive: true });
41
41
  // Written beside it and renamed over it: a full disk once truncated three agents' files to 0
42
42
  // bytes mid-write, and their watchers failed on every start for 17 hours. A failed write now
@@ -51,3 +51,79 @@ export function writeState(agent, state, env = process.env) {
51
51
  throw e;
52
52
  }
53
53
  }
54
+ /** Refuse a move when the destination has made newer monotonic progress than the source copy. */
55
+ export function destinationStateIsNewer(source, destination) {
56
+ const greater = (a, b) => (b ?? 0) > (a ?? 0);
57
+ const later = (a, b) => !!b && (!a || b > a);
58
+ if (greater(source.last_check, destination.last_check)
59
+ || later(source.inbox_after, destination.inbox_after)
60
+ || later(source.watch_inbox_after, destination.watch_inbox_after)
61
+ || greater(source.model_observed_at, destination.model_observed_at)
62
+ || greater(source.heartbeat_at, destination.heartbeat_at)
63
+ || greater(source.harness_session?.at, destination.harness_session?.at)
64
+ || greater(source.harness_session?.last_seen_at, destination.harness_session?.last_seen_at)
65
+ || greater(source.watch_seq, destination.watch_seq)
66
+ || greater(source.watch_acked, destination.watch_acked)
67
+ || greater(source.watch_process?.seen ?? undefined, destination.watch_process?.seen ?? undefined)
68
+ || greater(source.watch_process?.checked_at ?? undefined, destination.watch_process?.checked_at ?? undefined)
69
+ || later(source.watch_operator_at, destination.watch_operator_at)
70
+ || later(source.turn_resume_applied_at, destination.turn_resume_applied_at)
71
+ || greater(source.watch_followed_since, destination.watch_followed_since)
72
+ || greater(source.watch_turn_coalesce_since, destination.watch_turn_coalesce_since)
73
+ || greater(source.watch_dormant_logged_at, destination.watch_dormant_logged_at)
74
+ || greater(source.turn_unpaused_at, destination.turn_unpaused_at))
75
+ return true;
76
+ if (destination.turn_telemetry_start_pending && JSON.stringify(destination.turn_telemetry_start_pending) !== JSON.stringify(source.turn_telemetry_start_pending))
77
+ return true;
78
+ if (destination.turn_telemetry_completion_pending && JSON.stringify(destination.turn_telemetry_completion_pending) !== JSON.stringify(source.turn_telemetry_completion_pending))
79
+ return true;
80
+ if (destination.turn_guard && JSON.stringify(destination.turn_guard) !== JSON.stringify(source.turn_guard))
81
+ return true;
82
+ if (destination.machine_pressure_notice?.last_notice_at && greater(source.machine_pressure_notice?.last_notice_at, destination.machine_pressure_notice.last_notice_at))
83
+ return true;
84
+ for (const [channel, seq] of Object.entries(destination.channel_read ?? {})) {
85
+ if (seq > (source.channel_read?.[channel] ?? 0))
86
+ return true;
87
+ }
88
+ const sourcePending = JSON.stringify(source.pending_reads ?? []);
89
+ const destinationPending = JSON.stringify(destination.pending_reads ?? []);
90
+ if (destinationPending !== "[]" && destinationPending !== sourcePending)
91
+ return true;
92
+ const sourceWake = source.watch_pending?.seq ?? 0;
93
+ const destinationWake = destination.watch_pending?.seq ?? 0;
94
+ if (destinationWake > sourceWake)
95
+ return true;
96
+ if (destination.watch_pending) {
97
+ if (!source.watch_pending || destination.watch_pending.at > source.watch_pending.at
98
+ || later(source.watch_pending.inbox_after, destination.watch_pending.inbox_after))
99
+ return true;
100
+ for (const [channel, seq] of Object.entries(destination.watch_pending.channel_read ?? {})) {
101
+ if (seq > (source.watch_pending.channel_read?.[channel] ?? 0))
102
+ return true;
103
+ }
104
+ }
105
+ return false;
106
+ }
107
+ /** Keep the source file byte-for-byte; a malformed or newer destination is never overwritten. */
108
+ export function stateTransferContents(sourceText, destinationText) {
109
+ if (sourceText === null)
110
+ return null;
111
+ const parse = (text, side) => {
112
+ let value;
113
+ try {
114
+ value = JSON.parse(text);
115
+ }
116
+ catch {
117
+ throw new CliError("corrupt_state", `${side} agent state is not valid JSON; refusing to transfer it`);
118
+ }
119
+ if (!value || typeof value !== "object" || Array.isArray(value) || typeof value.inbox_after !== "string") {
120
+ throw new CliError("corrupt_state", `${side} agent state does not have a valid state shape; refusing to transfer it`);
121
+ }
122
+ return Object.assign({ inbox_after: "", last_check: 0 }, value);
123
+ };
124
+ const source = parse(sourceText, "source");
125
+ if (destinationText !== null && destinationStateIsNewer(source, parse(destinationText, "destination"))) {
126
+ throw new CliError("state_destination_newer", "the destination already has newer agent state; refusing to overwrite its cursors", "Inspect both state files and resolve them before retrying the move");
127
+ }
128
+ return sourceText;
129
+ }
package/dist/version.js CHANGED
@@ -1 +1 @@
1
- export const CLI_VERSION = "0.12.100";
1
+ export const CLI_VERSION = "0.12.101";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "benignswarm",
3
- "version": "0.12.100",
3
+ "version": "0.12.101",
4
4
  "description": "b9s: chat, status board and evidence store for coding agents (benignswarm.org)",
5
5
  "license": "UNLICENSED",
6
6
  "repository": {