benignswarm 0.12.164 → 0.12.166

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.
@@ -2,13 +2,14 @@ import { spawn, spawnSync } from "node:child_process";
2
2
  import { Worker } from "node:worker_threads";
3
3
  import { FileFactsCache, scanLinesBackward, TAIL_CHUNK_BYTES, TAIL_MAX_BYTES } from "../tail-lines.js";
4
4
  import { rotateLogs } from "../log-rotation.js";
5
- import { createHash, createHmac, randomBytes } from "node:crypto";
5
+ import { createHash, createHmac, randomBytes, randomUUID } from "node:crypto";
6
6
  import { chmodSync, closeSync, cpSync, existsSync, lstatSync, mkdirSync, mkdtempSync, openSync, readdirSync, readFileSync, readSync, realpathSync, renameSync, rmSync, statSync, statfsSync, unlinkSync, writeFileSync } from "node:fs";
7
7
  import { arch, cpus, freemem, homedir, hostname, loadavg, platform, tmpdir, totalmem, userInfo } from "node:os";
8
8
  import { dirname, isAbsolute, join, relative, resolve } from "node:path";
9
9
  import { str } from "../args.js";
10
10
  import { interfaceFacts } from "../network.js";
11
11
  import { Client } from "../client.js";
12
+ import { machineNetworkOutages, recordMachineNetworkRequest } from "../machine-network-health.js";
12
13
  import { agentRef, configRoot, loadAgent, resolveAgentName, saveAgent } from "../config.js";
13
14
  import { CliError } from "../errors.js";
14
15
  import { AGY_APPARMOR_PATH, agyAppArmorProfile, BWRAP_APPARMOR_PATH, bwrapAppArmorProfile, CODEX_APPARMOR_PATH, CODEX_MANAGED_DIR, codexAppArmorProfile, codexManagedHooks, isCodexManagedRequirements } from "../harness.js";
@@ -41,12 +42,13 @@ import { collectModelChecksQueued, modelCheckRuntimeTuple, probeModelRunAsync }
41
42
  import { authorizeWorktreeScope, redactProcessCommand, scanWorktreeProcesses } from "../machine-processes.js";
42
43
  import { runMachineDaemonLoop } from "../machine-daemon.js";
43
44
  import { boundMachineReport } from "../machine-report.js";
45
+ import { cleanupStaleVitestScratchDirs, detectLocalDiskPressure } from "../scratch-cleanup.js";
44
46
  import { ECRClient } from "@aws-sdk/client-ecr";
45
47
  import { EcrHostedRegistry } from "../hosted-registry-ecr.js";
46
48
  import { publishHostedImage } from "../hosted-registry.js";
47
49
  import { assumeHostedBuilder } from "../hosted-registry-session.js";
48
50
  import { pushHostedImage } from "../hosted-registry-push.js";
49
- import { reconcilePendingUxJobs, retryPendingUxJobCompletions, sweepExpiredUxJobWorktrees, uxJobIdsForMachineReport } from "../ux-jobs.js";
51
+ import { reconcilePendingUxJobs, retryPendingPassedTrainGates, retryPendingUxJobClaims, retryPendingUxJobCompletions, sweepExpiredUxJobWorktrees, uxJobIdsForMachineReport } from "../ux-jobs.js";
50
52
  export const machineFile = () => join(configRoot(), "machine.json");
51
53
  export function loadMachine() {
52
54
  const f = machineFile();
@@ -59,6 +61,7 @@ const readMachineState = () => {
59
61
  const state = existsSync(stateFile()) ? JSON.parse(readFileSync(stateFile(), "utf8")) : { sessions: {} };
60
62
  state.starting_sessions ??= {};
61
63
  state.unsettled_turns ??= {};
64
+ state.resume_restart_handled_at ??= {};
62
65
  return state;
63
66
  };
64
67
  function writeMachineState(s) {
@@ -75,9 +78,10 @@ function writeMachineState(s) {
75
78
  * 3: turns get TMPDIR beside the checkout instead of the system's /tmp.
76
79
  * 11: Antigravity's linked-worktree Git permissions are narrowed to required data paths.
77
80
  * 12: Claude Code workspace-write roots name only the checkout, active unit worktree, narrowed Git metadata, config and caches.
81
+ * 13: subagent mode/model changes restart pool sessions with their new harness controls.
78
82
  */
79
- const START_REV = 12;
80
- export const sessionFingerprint = (s, writable = [], imageDigest = null) => JSON.stringify([s.id, s.harness, ...(s.provider && s.provider !== "anthropic" ? [s.provider] : []), s.dir, s.sandbox, s.model, s.effort, s.turn_timeout, s.turns_per_hour ?? DEFAULT_TURNS_PER_HOUR, s.unproductive_per_hour ?? DEFAULT_UNPRODUCTIVE_PER_HOUR, s.turn_coalesce_seconds ?? 180, ...(s.max_budget_usd != null ? [`budget:${s.max_budget_usd}`] : []), ...(s.harness_binary ? [`binary:${s.harness_binary}`] : []), s.thread, ...(writable.length ? [writable] : []), ...(imageDigest ? [`image:${imageDigest}`] : []), ...(s.secret_context_hash ? [`secrets:${s.secret_context_hash}`] : []), ...(START_REV > 1 ? [`rev${START_REV}`] : [])]);
83
+ const START_REV = 13;
84
+ export const sessionFingerprint = (s, writable = [], imageDigest = null) => JSON.stringify([s.id, s.harness, ...(s.provider && s.provider !== "anthropic" ? [s.provider] : []), s.dir, s.sandbox, s.model, s.effort, s.subagents ?? "default", s.subagent_model ?? null, s.turn_timeout, s.turns_per_hour ?? DEFAULT_TURNS_PER_HOUR, s.unproductive_per_hour ?? DEFAULT_UNPRODUCTIVE_PER_HOUR, s.turn_coalesce_seconds ?? 180, ...(s.max_budget_usd != null ? [`budget:${s.max_budget_usd}`] : []), ...(s.harness_binary ? [`binary:${s.harness_binary}`] : []), s.thread, ...(writable.length ? [writable] : []), ...(imageDigest ? [`image:${imageDigest}`] : []), ...(s.secret_context_hash ? [`secrets:${s.secret_context_hash}`] : []), ...(START_REV > 1 ? [`rev${START_REV}`] : [])]);
81
85
  /** A server thread update must restart the watcher even if a stored fingerprint is unexpectedly stale. */
82
86
  export function sessionConfigChanged(s, local, fingerprint) {
83
87
  const serverThreadChanged = s.thread !== null && s.thread !== (local?.thread ?? null);
@@ -90,6 +94,24 @@ export function reconcileThread(s, local) {
90
94
  return clearing ? null : s.thread ?? local?.thread ?? null;
91
95
  }
92
96
  export const watchLabelOf = (ref) => `${WATCH_LABEL_PREFIX}${ref.replace("/", ".")}`;
97
+ /**
98
+ * A resume timestamp is a one-shot restart request only when it is newer than the signal we
99
+ * handled locally and, for an errored server report, newer than that error itself. This keeps a
100
+ * failed resume from becoming a restart loop while still allowing a later operator resume.
101
+ */
102
+ export function resumeRestartDue(session, handledAt, watcherActive) {
103
+ if (session.desired !== "running" || !session.turn_resume_at)
104
+ return false;
105
+ if (session.reported?.state !== "error" && watcherActive)
106
+ return false;
107
+ const signalAt = Date.parse(session.turn_resume_at);
108
+ const handledAtMs = handledAt ? Date.parse(handledAt) : Number.NaN;
109
+ const errorAtMs = session.reported?.state === "error" && session.reported_at
110
+ ? Date.parse(session.reported_at)
111
+ : Number.NaN;
112
+ const priorAt = Math.max(Number.isFinite(handledAtMs) ? handledAtMs : 0, Number.isFinite(errorAtMs) ? errorAtMs : 0);
113
+ return Number.isFinite(signalAt) && signalAt > priorAt;
114
+ }
93
115
  /**
94
116
  * During a maintenance drain or window, a session that would be started fresh (no known thread, so
95
117
  * `b9s start` runs its first turn at once, past the watchers' check) waits; adopting a known
@@ -113,6 +135,8 @@ export function startArgs(s, thread, writable = [], startupJitterSeconds) {
113
135
  ...(s.harness_binary ? ["--harness-binary", s.harness_binary] : []),
114
136
  ...(s.model ? ["--model", s.model] : []),
115
137
  ...(s.effort ? ["--effort", s.effort] : []),
138
+ "--subagents", s.subagents ?? "default",
139
+ ...(s.subagent_model ? ["--subagent-model", s.subagent_model] : []),
116
140
  ...(thread ? ["--thread", thread] : []),
117
141
  ...(writable.length && s.sandbox === "workspace-write" ? writable.flatMap((path) => ["--writable-root", path]) : []),
118
142
  ...(startupJitterSeconds === undefined ? [] : ["--startup-jitter-seconds", String(startupJitterSeconds)]),
@@ -122,6 +146,7 @@ const KEY_CHECK_MS = 10 * 60_000;
122
146
  const CAPABILITY_PROBE_MS = 60 * 60_000;
123
147
  const lastCapabilityProbe = new Map();
124
148
  const WORKTREE_PRUNE_INTERVAL_MS = 60 * 60_000;
149
+ const WORKTREE_PRUNE_PRESSURE_INTERVAL_MS = 15 * 60_000;
125
150
  const WORKTREE_PRUNE_TIMEOUT_MS = 2 * 60_000;
126
151
  const lastWorktreePrune = new Map();
127
152
  export function resetWorktreePrune() {
@@ -130,6 +155,20 @@ export function resetWorktreePrune() {
130
155
  void state.worker.terminate();
131
156
  lastWorktreePrune.clear();
132
157
  }
158
+ function logPruneReclaimed(projectName, result, log) {
159
+ if (result.status === "error" || result.status === "skipped")
160
+ return;
161
+ const removed = typeof result.removed === "number" && Number.isFinite(result.removed) ? Math.max(0, result.removed) : 0;
162
+ const freedBytes = Array.isArray(result.free_space)
163
+ ? result.free_space.reduce((sum, entry) => {
164
+ const bytes = entry && typeof entry === "object" ? entry.freedBytes : undefined;
165
+ return sum + (typeof bytes === "number" && Number.isFinite(bytes) ? Math.max(0, bytes) : 0);
166
+ }, 0)
167
+ : 0;
168
+ if (removed > 0 || freedBytes > 0) {
169
+ log(`${projectName}: worktree prune removed ${removed} worktree(s), reclaimed ${freedBytes} bytes`);
170
+ }
171
+ }
133
172
  export function turnFaultSessionFields(fault, agent) {
134
173
  const binding = agent ? readState(agent).watch_turn_binding : undefined;
135
174
  return {
@@ -146,6 +185,18 @@ export function bareDigestOf(imageRef) {
146
185
  return /^sha256:[a-f0-9]{64}$/i.test(candidate.trim()) ? candidate.trim().toLowerCase() : null;
147
186
  }
148
187
  const MACHINE_REQUEST_TIMEOUT_MS = 45_000;
188
+ const MACHINE_NETWORK_RETRY_MS = 5 * 60_000;
189
+ const MACHINE_REPORT_UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
190
+ /** Keep malformed local UX job state from making the server reject an otherwise valid machine report. */
191
+ export function validatedUxJobIdsForMachineReport(ids, log) {
192
+ return ids.filter((id) => {
193
+ if (MACHINE_REPORT_UUID.test(id))
194
+ return true;
195
+ const printable = id.replace(/[\u0000-\u001f\u007f]/g, "?").slice(0, 100);
196
+ log(`ignoring non-UUID active UX job id in machine report: ${printable}`);
197
+ return false;
198
+ });
199
+ }
149
200
  const MACHINE_PASS_BUDGET_MS = 4 * 60_000;
150
201
  const MACHINE_WATCHDOG_MS = 5 * 60_000;
151
202
  export function resolvePinnedImageRef(image) {
@@ -1120,9 +1171,13 @@ export async function reconcile(m, log, reportIntervalSeconds = 30, deps) {
1120
1171
  requestTimeoutMs: MACHINE_REQUEST_TIMEOUT_MS,
1121
1172
  stagedPoolPreparation: true,
1122
1173
  signal: deps?.signal,
1123
- onRequest: (event) => log(event.phase === "start"
1124
- ? `request start ${event.method} ${event.path}`
1125
- : `request end ${event.method} ${event.path} in ${event.durationMs}ms${event.error ? ` (${event.error})` : ""}`),
1174
+ onRequest: (event) => {
1175
+ if (event.phase === "end")
1176
+ recordMachineNetworkRequest(event);
1177
+ log(event.phase === "start"
1178
+ ? `request start ${event.method} ${event.path} attempt ${event.attempt}`
1179
+ : `request end ${event.method} ${event.path} attempt ${event.attempt} in ${event.durationMs}ms${event.error ? " (failed)" : ""}`);
1180
+ },
1126
1181
  });
1127
1182
  if (Date.now() - lastLogRotationAt >= LOG_ROTATION_EVERY_MS) {
1128
1183
  lastLogRotationAt = Date.now();
@@ -1142,7 +1197,7 @@ export async function reconcile(m, log, reportIntervalSeconds = 30, deps) {
1142
1197
  const bundle = collectMachineDiagnosticBundle(m.name, workdir, (me.projects ?? []).map((project) => project.name ?? "").filter(Boolean));
1143
1198
  for (const query of diagnosticQueries) {
1144
1199
  try {
1145
- await client.call("POST", `/machines/me/diagnostics/${encodeURIComponent(query.id)}`, { bundle }, { retries: 2 });
1200
+ await client.call("POST", `/machines/me/diagnostics/${encodeURIComponent(query.id)}`, { bundle }, { retryForMs: MACHINE_NETWORK_RETRY_MS });
1146
1201
  log(`uploaded diagnostic evidence for ${query.requester_name}`);
1147
1202
  }
1148
1203
  catch (error) {
@@ -1206,6 +1261,12 @@ export async function reconcile(m, log, reportIntervalSeconds = 30, deps) {
1206
1261
  const service = localWatcherServices.find((entry) => entry.label === watchLabelOf(session.agent));
1207
1262
  if (!service || serviceActive(service))
1208
1263
  continue;
1264
+ if (resumeRestartDue(session, state.resume_restart_handled_at?.[session.id], false))
1265
+ continue;
1266
+ // An errored session only gets one recovery attempt per operator resume signal. Do not let
1267
+ // the general inactive-watcher recovery sweep retry a failed resume on every daemon poll.
1268
+ if (session.reported?.state === "error")
1269
+ continue;
1209
1270
  const sessionWritable = session.sandbox === "workspace-write"
1210
1271
  ? [...new Set([...defaultWorkspaceWritableRoots(), ...writable])]
1211
1272
  : writable;
@@ -1331,6 +1392,19 @@ export async function reconcile(m, log, reportIntervalSeconds = 30, deps) {
1331
1392
  const agentStateEnv = containerMode
1332
1393
  ? { ...process.env, B9S_HOME: join(agentHomeDirOf(s), ".b9s"), BSCHAT_HOME: join(agentHomeDirOf(s), ".b9s") }
1333
1394
  : process.env;
1395
+ let local = state.sessions[s.id];
1396
+ const hostSvc = svc();
1397
+ const resumeWatcherActive = containerMode && local?.container_name && local.container_runtime
1398
+ ? isContainerRunning(local.container_runtime, local.container_name, runner)
1399
+ : Boolean(hostSvc && serviceActive(hostSvc));
1400
+ const resumeRestart = resumeRestartDue(s, state.resume_restart_handled_at?.[s.id], resumeWatcherActive);
1401
+ if (resumeRestart) {
1402
+ state.resume_restart_handled_at[s.id] = s.turn_resume_at;
1403
+ // Persist before any checkout, credential, or launch work. A failure at any later stage
1404
+ // is still the one attempt authorized by this signal.
1405
+ writeMachineState(state);
1406
+ log(`${s.agent}: handling new turn resume signal; reconciling errored/inactive watcher once`);
1407
+ }
1334
1408
  if (!s.dir) {
1335
1409
  // A pool session: the daemon makes the checkout (clone once per machine, a worktree per agent).
1336
1410
  const c = ensureCheckout(s, log, workdir);
@@ -1342,7 +1416,6 @@ export async function reconcile(m, log, reportIntervalSeconds = 30, deps) {
1342
1416
  }
1343
1417
  if (!existsSync(s.dir))
1344
1418
  throw new Error(`checkout ${s.dir} does not exist on this machine`);
1345
- let local = state.sessions[s.id];
1346
1419
  if (s.desired === "prepared") {
1347
1420
  if (svc() || local?.container_name || state.starting_sessions?.[s.id] || state.unsettled_turns?.[s.dir])
1348
1421
  throw new Error("target already has a watcher or recorded container; preparation will not start another");
@@ -1506,7 +1579,6 @@ export async function reconcile(m, log, reportIntervalSeconds = 30, deps) {
1506
1579
  const thread = reconcileThread(s, local);
1507
1580
  const fp = sessionFingerprint({ ...s, thread }, s.sandbox === "workspace-write" ? sessionWritable : [], pinnedImageRef);
1508
1581
  const configChanged = sessionConfigChanged(s, local, fp);
1509
- const hostSvc = svc();
1510
1582
  if (containerMode && hostSvc) {
1511
1583
  removeService(hostSvc);
1512
1584
  log(`${s.agent}: removed host watcher service before container supervision`);
@@ -1520,12 +1592,27 @@ export async function reconcile(m, log, reportIntervalSeconds = 30, deps) {
1520
1592
  const containerActive = containerMode && activeContainerRuntime && activeContainerName
1521
1593
  ? isContainerRunning(activeContainerRuntime, activeContainerName, runner)
1522
1594
  : false;
1595
+ const watcherActive = containerMode ? containerActive : Boolean(hostSvc && serviceActive(hostSvc));
1596
+ if (s.reported?.state === "error" && !resumeRestart && !watcherActive && !state.starting_sessions?.[s.id] && !configChanged) {
1597
+ out.push({ id: s.id, state: "error", dir: s.dir, thread: local?.thread ?? s.thread, watcher: "inactive", error: s.reported.error ?? "session remains errored; a newer resume signal is required" });
1598
+ continue;
1599
+ }
1523
1600
  if (!s.secret_grant_required) {
1524
1601
  clearSessionSecrets(s.id);
1525
1602
  }
1603
+ if (resumeRestart) {
1604
+ if (!containerMode && hostSvc) {
1605
+ removeService(hostSvc);
1606
+ log(`${s.agent}: removed previous watcher before the one-shot resume restart`);
1607
+ }
1608
+ if (containerMode && local?.container_name && local.container_runtime) {
1609
+ removeAgentContainer(local.container_runtime, local.container_name, runner);
1610
+ log(`${s.agent}: removed previous container before the one-shot resume restart`);
1611
+ }
1612
+ }
1526
1613
  const needsLaunch = containerMode
1527
- ? (configChanged || !containerActive)
1528
- : (!hostSvc || configChanged);
1614
+ ? (configChanged || !containerActive || resumeRestart)
1615
+ : (!hostSvc || configChanged || resumeRestart);
1529
1616
  if (needsLaunch) {
1530
1617
  if (local?.has_project_secrets && configChanged) {
1531
1618
  if (!containerMode && hostSvc) {
@@ -1886,15 +1973,25 @@ export async function reconcile(m, log, reportIntervalSeconds = 30, deps) {
1886
1973
  log(`build cache fault on ${fault.volume} (${fault.free_pct}% < ${fault.floor_pct}% floor): ${fault.caches.join(", ")} in use by ${fault.processes.join(", ")}`);
1887
1974
  }
1888
1975
  const clones = refreshClones(workdir, [...new Set(desired.filter((s) => !s.dir && s.project && s.desired === "running").map((s) => s.project))], log);
1889
- const actualWorkdir = workdir ?? join(homedir(), "bschat");
1976
+ const readHomeDir = deps?.homeDir ?? homedir;
1977
+ const readVolumeSpace = deps?.volumeSpace ?? volumeSpace;
1978
+ const actualWorkdir = workdir ?? join(readHomeDir(), "bschat");
1979
+ const floorPct = me.machine?.cache_floor_pct ?? DEFAULT_CACHE_FLOOR_PCT;
1980
+ const homeSpaceBefore = readVolumeSpace(readHomeDir(), "home");
1981
+ const workSpaceBefore = readVolumeSpace(actualWorkdir, "workdir");
1982
+ const pressure = detectLocalDiskPressure([homeSpaceBefore, workSpaceBefore], floorPct);
1983
+ const pruneIntervalMs = pressure.underPressure ? WORKTREE_PRUNE_PRESSURE_INTERVAL_MS : WORKTREE_PRUNE_INTERVAL_MS;
1890
1984
  const worktreePrune = [];
1891
1985
  for (const project of projects) {
1892
1986
  const repo = join(actualWorkdir, project.name, "main");
1893
1987
  if (!existsSync(join(repo, ".git")))
1894
1988
  continue;
1895
1989
  let prior = lastWorktreePrune.get(project.id);
1896
- const due = !prior || Date.now() - prior.at >= WORKTREE_PRUNE_INTERVAL_MS;
1990
+ const due = !prior || Date.now() - prior.at >= pruneIntervalMs;
1897
1991
  if (due && !prior?.worker) {
1992
+ if (pressure.underPressure) {
1993
+ log(`${project.name}: disk pressure (${pressure.reasons.join(", ")}; floor ${floorPct}%): triggering clean closed-worktree prune`);
1994
+ }
1898
1995
  // Mark the attempt before starting the isolated worker, so overlapping reconcile passes
1899
1996
  // cannot start a second scan or removal for the same project.
1900
1997
  const attemptedAt = Date.now();
@@ -1912,8 +2009,10 @@ export async function reconcile(m, log, reportIntervalSeconds = 30, deps) {
1912
2009
  lastWorktreePrune.set(project.id, prior);
1913
2010
  if (deps?.pruneRunner) {
1914
2011
  void Promise.resolve().then(() => deps.pruneRunner(creds, project.name, repo, log)).then((result) => {
1915
- if (lastWorktreePrune.get(project.id) === prior)
1916
- prior.result = result;
2012
+ if (lastWorktreePrune.get(project.id) !== prior)
2013
+ return;
2014
+ prior.result = result;
2015
+ logPruneReclaimed(project.name, result, log);
1917
2016
  }).catch((error) => {
1918
2017
  if (lastWorktreePrune.get(project.id) !== prior)
1919
2018
  return;
@@ -1945,8 +2044,10 @@ export async function reconcile(m, log, reportIntervalSeconds = 30, deps) {
1945
2044
  return;
1946
2045
  settled = true;
1947
2046
  clearTimeout(timer);
1948
- if (lastWorktreePrune.get(project.id) === prior)
1949
- prior.result = result;
2047
+ if (lastWorktreePrune.get(project.id) !== prior)
2048
+ return;
2049
+ prior.result = result;
2050
+ logPruneReclaimed(project.name, result, log);
1950
2051
  };
1951
2052
  worker.on("message", (message) => {
1952
2053
  if (message.type === "log" && message.line)
@@ -1980,9 +2081,35 @@ export async function reconcile(m, log, reportIntervalSeconds = 30, deps) {
1980
2081
  }
1981
2082
  worktreePrune.push(prior?.result ?? { project: project.name, repo, status: "running" });
1982
2083
  }
1983
- const workSpace = volumeSpace(actualWorkdir, "workdir");
2084
+ let scratchCleanup = {
2085
+ disk_pressure: false, removed_dirs: 0, reclaimed_bytes: 0, skipped_active: 0, errors: 0, capped: false,
2086
+ };
2087
+ if (pressure.underPressure) {
2088
+ const scratchResult = cleanupStaleVitestScratchDirs({
2089
+ tempDir: (deps?.tmpdir ?? tmpdir)(),
2090
+ ...deps?.scratchCleanupOps,
2091
+ });
2092
+ scratchCleanup = {
2093
+ disk_pressure: true,
2094
+ removed_dirs: scratchResult.removed_dirs,
2095
+ reclaimed_bytes: scratchResult.reclaimed_bytes,
2096
+ skipped_active: scratchResult.skipped_active,
2097
+ errors: scratchResult.errors,
2098
+ capped: scratchResult.capped,
2099
+ ...(scratchResult.aborted_reason ? { aborted_reason: scratchResult.aborted_reason } : {}),
2100
+ };
2101
+ if (scratchResult.aborted_reason) {
2102
+ log(`disk pressure (${pressure.reasons.join(", ")}; floor ${floorPct}%): scratch cleanup skipped (${scratchResult.aborted_reason}; kept ${scratchResult.skipped_active} candidate(s))`);
2103
+ }
2104
+ else {
2105
+ log(`disk pressure (${pressure.reasons.join(", ")}; floor ${floorPct}%): scratch cleanup in ${scratchResult.tmpdir} removed ${scratchResult.removed_dirs} stale b9s-vitest-* dir(s), reclaimed ${scratchResult.reclaimed_bytes} bytes${scratchResult.skipped_active ? ` (kept ${scratchResult.skipped_active} active/unverified)` : ""}${scratchResult.capped ? " (per-pass limit reached)" : ""}`);
2106
+ }
2107
+ }
2108
+ const homeSpace = readVolumeSpace(readHomeDir(), "home");
2109
+ const workSpace = readVolumeSpace(actualWorkdir, "workdir");
1984
2110
  const facts = machineFacts([...providerChecks], {
1985
2111
  workdir: actualWorkdir,
2112
+ homeSpace,
1986
2113
  modelsToCheck: me.models_to_check ?? [],
1987
2114
  modelRunProbe: deps?.modelRunProbe,
1988
2115
  verifyClaudeEgress: true,
@@ -1990,7 +2117,7 @@ export async function reconcile(m, log, reportIntervalSeconds = 30, deps) {
1990
2117
  ec2Probe: () => onEc2,
1991
2118
  ...(imdsContainerProbe ? { containerImdsProbe: () => imdsContainerProbe } : {}),
1992
2119
  ...(hostContainerProbe ? { probes: { container: () => hostContainerProbe } } : {}),
1993
- }, desired, me.machine?.cache_floor_pct ?? DEFAULT_CACHE_FLOOR_PCT);
2120
+ }, desired, floorPct);
1994
2121
  const environmentChecks = machineEnvironmentChecks({ ...facts, workdir_free_bytes: workSpace?.freeBytes ?? null, workdir_total_bytes: workSpace?.totalBytes ?? null }, writable)
1995
2122
  .map(({ check, status, observation, remedy, recovery_verified }) => ({ check, status, diagnosis: observation, remedy, recovery_verified, observed_at: new Date().toISOString() }));
1996
2123
  const dirtyClosedWorktrees = worktreePrune.flatMap((result) => Array.isArray(result.dirty_closed) ? result.dirty_closed.filter((item) => typeof item === "string") : []);
@@ -2012,9 +2139,11 @@ export async function reconcile(m, log, reportIntervalSeconds = 30, deps) {
2012
2139
  workdir: actualWorkdir, workdir_free_bytes: workSpace?.freeBytes ?? null, workdir_total_bytes: workSpace?.totalBytes ?? null, clones,
2013
2140
  metric_availability: { ...facts.metric_availability, work_volume: workSpace ? "available" : "unavailable" },
2014
2141
  worktree_prune: worktreePrune,
2142
+ scratch_cleanup: scratchCleanup,
2015
2143
  build_caches: buildCaches,
2016
2144
  // The daemon's own confirmation that it is holding turns back, and how many are still running.
2017
2145
  maintenance: maintenanceReport(drainingUntil(), out),
2146
+ network_outages: machineNetworkOutages(),
2018
2147
  });
2019
2148
  const capabilities = {};
2020
2149
  const imageProbes = [];
@@ -2091,13 +2220,14 @@ export async function reconcile(m, log, reportIntervalSeconds = 30, deps) {
2091
2220
  }
2092
2221
  log(`machine report size: ${new TextEncoder().encode(JSON.stringify(report)).byteLength} UTF-8 bytes`);
2093
2222
  await client.call("POST", "/machines/me/report", {
2223
+ client_id: randomUUID(),
2094
2224
  report,
2095
2225
  report_interval_seconds: reportIntervalSeconds,
2096
2226
  sessions: out,
2097
2227
  capabilities,
2098
- active_ux_job_ids: uxJobIdsForMachineReport(deps?.uxJobsInFlight, deps?.uxJobDeps),
2228
+ active_ux_job_ids: validatedUxJobIdsForMachineReport(uxJobIdsForMachineReport(deps?.uxJobsInFlight, deps?.uxJobDeps), log),
2099
2229
  ...(imageProbes.length ? { image_probes: imageProbes } : {}),
2100
- });
2230
+ }, { retryForMs: MACHINE_NETWORK_RETRY_MS });
2101
2231
  const uxSessionHints = desired.map((session) => ({
2102
2232
  id: session.id,
2103
2233
  agent: session.agent,
@@ -2114,42 +2244,50 @@ export async function reconcile(m, log, reportIntervalSeconds = 30, deps) {
2114
2244
  for (const item of probedProjects) {
2115
2245
  lastCapabilityProbe.set(item.id, { at: Date.now(), signature: item.signature });
2116
2246
  }
2117
- const warning = diskSpaceNotice(volumeSpace(homedir(), "home"), volumeSpace(workdir ?? join(homedir(), "bschat"), "workdir"));
2247
+ const warning = diskSpaceNotice(homeSpace, workSpace);
2118
2248
  if (warning !== undefined)
2119
2249
  await client.call("PUT", "/machines/me/notices/disk", { text: warning });
2250
+ const uxJobContext = {
2251
+ accountId,
2252
+ machineName: m.name,
2253
+ workdir,
2254
+ diskFloorPct: me.machine?.cache_floor_pct ?? DEFAULT_CACHE_FLOOR_PCT,
2255
+ sessions: desired.map((s) => ({
2256
+ id: s.id,
2257
+ agent: s.agent,
2258
+ agent_name: s.agent_name,
2259
+ project: s.project,
2260
+ project_id: s.project_id ?? null,
2261
+ dir: s.dir,
2262
+ desired: s.desired,
2263
+ benched_at: s.benched_at ?? null,
2264
+ retired_at: null,
2265
+ })),
2266
+ log,
2267
+ };
2268
+ const uxJobDeps = {
2269
+ ensureSessionKey: async (hint) => {
2270
+ const match = desired.find((s) => s.id === hint.id);
2271
+ if (match)
2272
+ await ensureCredentials(client, m, match, state.sessions[match.id], log);
2273
+ },
2274
+ ...deps?.uxJobDeps,
2275
+ };
2276
+ const claimResumePromise = retryPendingUxJobClaims(client, uxJobContext, uxJobDeps, deps?.uxJobsInFlight);
2277
+ if (deps?.awaitUxJobs)
2278
+ await claimResumePromise;
2120
2279
  if (Array.isArray(me.ux_jobs) && me.ux_jobs.length) {
2121
- const uxPromise = reconcilePendingUxJobs(client, me.ux_jobs, {
2122
- accountId,
2123
- machineName: m.name,
2124
- workdir,
2125
- diskFloorPct: me.machine?.cache_floor_pct ?? DEFAULT_CACHE_FLOOR_PCT,
2126
- sessions: desired.map((s) => ({
2127
- id: s.id,
2128
- agent: s.agent,
2129
- agent_name: s.agent_name,
2130
- project: s.project,
2131
- project_id: s.project_id ?? null,
2132
- dir: s.dir,
2133
- desired: s.desired,
2134
- benched_at: s.benched_at ?? null,
2135
- retired_at: null,
2136
- })),
2137
- log,
2138
- }, {
2280
+ const uxPromise = reconcilePendingUxJobs(client, me.ux_jobs, uxJobContext, {
2139
2281
  inFlight: deps?.uxJobsInFlight,
2140
2282
  awaitCompletion: deps?.awaitUxJobs ?? false,
2141
- deps: {
2142
- ensureSessionKey: async (hint) => {
2143
- const match = desired.find((s) => s.id === hint.id);
2144
- if (match)
2145
- await ensureCredentials(client, m, match, state.sessions[match.id], log);
2146
- },
2147
- ...deps?.uxJobDeps,
2148
- },
2283
+ deps: uxJobDeps,
2149
2284
  });
2150
2285
  if (deps?.awaitUxJobs)
2151
2286
  await uxPromise;
2152
2287
  }
2288
+ const resumePromise = retryPendingPassedTrainGates(client, uxJobContext, uxJobDeps, deps?.uxJobsInFlight);
2289
+ if (deps?.awaitUxJobs)
2290
+ await resumePromise;
2153
2291
  return { sessions: out, report };
2154
2292
  }
2155
2293
  export async function answerWorktreeProcessQueries(client, desired, queries, log, scan = scanWorktreeProcesses) {
@@ -3057,7 +3195,7 @@ export function machineFacts(providersInUse = ["anthropic"], workdirOrOpts, sess
3057
3195
  const probeAgent = antigravityProbeAgent(sessions);
3058
3196
  const readAntigravityFacts = () => probes?.antigravity ? probes.antigravity(probeAgent) : antigravityFacts(path, readInstall()?.bin ?? null, probeAgent);
3059
3197
  const antigravity = readAntigravityFacts();
3060
- const homeSpace = volumeSpace(homedir(), "home");
3198
+ const homeSpace = opts.homeSpace !== undefined ? opts.homeSpace : volumeSpace(homedir(), "home");
3061
3199
  const readTelemetryFile = (path) => { try {
3062
3200
  return readFileSync(path, "utf8");
3063
3201
  }
@@ -0,0 +1,74 @@
1
+ import { readFileSync } from "node:fs";
2
+ import { need, repeated, str } from "../args.js";
3
+ import { consoleLink } from "../console-links.js";
4
+ import { CliError } from "../errors.js";
5
+ const usage = "mock create|list|iterate|approve <project> ... (see b9s-admin --help)";
6
+ function describeStudy(study, project) {
7
+ if (!study || typeof study.id !== "string" || !Array.isArray(study.rounds))
8
+ throw new CliError("bad_response", "design study response omitted study id or rounds; inspect the study before retrying a write");
9
+ const units = study.rounds.flatMap(round => round.variants.map(v => `${v.label}: ${v.work_unit_number == null ? "unavailable" : `WU #${v.work_unit_number}`}`));
10
+ return `Study ${study.id}${units.length ? `\nVariants: ${units.join(", ")}` : ""}\nViewer: ${consoleLink("mock", project, study.id)}`;
11
+ }
12
+ export async function mockAdmin(action, args, p, client, out) {
13
+ const [project, studyId, variantId] = args;
14
+ if (!action || !project || !["create", "list", "iterate", "approve"].includes(action))
15
+ throw new CliError("usage", usage);
16
+ if ((action === "create" || action === "list") && args.length !== 1 || action === "iterate" && args.length !== 2 || action === "approve" && args.length !== 3)
17
+ throw new CliError("usage", usage);
18
+ const base = `/projects/${encodeURIComponent(project)}/design-studies`;
19
+ if (action === "list") {
20
+ const status = str(p.flags, "status");
21
+ if (status !== undefined && !["active", "approved", "archived"].includes(status))
22
+ throw new CliError("usage", "--status must be active, approved, or archived");
23
+ const result = await client.call("GET", `${base}${status ? `?status=${encodeURIComponent(status)}` : ""}`);
24
+ if (!Array.isArray(result.studies))
25
+ throw new CliError("bad_response", "design study list response omitted studies");
26
+ out.print(result.studies.map((s) => `${s.id} [${s.status}] ${s.title}\n ${consoleLink("mock", project, s.id)}`).join("\n") || "No design studies.", result);
27
+ return;
28
+ }
29
+ if (action === "create") {
30
+ const title = need(p.flags, "title"), target = need(p.flags, "target");
31
+ const briefText = str(p.flags, "brief"), briefFile = str(p.flags, "brief-file");
32
+ if ((briefText === undefined) === (briefFile === undefined))
33
+ throw new CliError("usage", "choose exactly one of --brief or --brief-file");
34
+ const brief = briefFile !== undefined ? readFileSync(briefFile, "utf8") : briefText;
35
+ if (!brief.trim())
36
+ throw new CliError("usage", "brief must not be empty");
37
+ const intent = str(p.flags, "intent");
38
+ if (intent !== undefined && !["explore", "refine", "focus", "audit"].includes(intent))
39
+ throw new CliError("usage", "--intent must be explore, refine, focus, or audit");
40
+ const variants = repeated(p, "variant").map(v => v.trim());
41
+ if (variants.length < 1 || variants.length > 8 || variants.some(v => !v || /^(agent|model):\s*$/.test(v)))
42
+ throw new CliError("usage", "supply 1..8 nonempty --variant values");
43
+ let names = new Set();
44
+ if (variants.some(v => !v.startsWith("agent:") && !v.startsWith("model:"))) {
45
+ const agents = await client.call("GET", `/projects/${encodeURIComponent(project)}/agents`);
46
+ if (!Array.isArray(agents.agents) || agents.agents.some((a) => !a || typeof a !== "object" || typeof a.name !== "string"))
47
+ throw new CliError("bad_response", "project agent response omitted agent names");
48
+ names = new Set(agents.agents.map((a) => a.name));
49
+ }
50
+ const specs = variants.map(raw => {
51
+ const v = raw.trim();
52
+ if (v.startsWith("agent:"))
53
+ return { agent_name: v.slice(6).trim() };
54
+ if (v.startsWith("model:"))
55
+ return { model: v.slice(6).trim() };
56
+ return names.has(v) ? { agent_name: v } : { model: v };
57
+ });
58
+ const route = str(p.flags, "route");
59
+ const result = await client.call("POST", base, { title, target_area: target, brief, variants: specs, ...(route !== undefined ? { target_route: route } : {}), ...(intent !== undefined ? { intent_mode: intent } : {}) });
60
+ out.print(describeStudy(result.study, project), { ...result, viewer_url: consoleLink("mock", project, result.study.id) });
61
+ return;
62
+ }
63
+ if (action === "iterate") {
64
+ const variants = repeated(p, "variant");
65
+ if (variants.length > 1 || variants.some(v => !v.trim()))
66
+ throw new CliError("usage", "iterate accepts at most one nonempty --variant");
67
+ const note = str(p.flags, "note");
68
+ const result = await client.call("POST", `${base}/${encodeURIComponent(studyId)}/iterate`, { ...(variants.length ? { variant_id: variants[0] } : {}), ...(note !== undefined ? { note } : {}) });
69
+ out.print(describeStudy(result.study, project), { ...result, viewer_url: consoleLink("mock", project, result.study.id) });
70
+ return;
71
+ }
72
+ const result = await client.call("POST", `${base}/${encodeURIComponent(studyId)}/approve`, { variant_id: variantId });
73
+ out.print(describeStudy(result.study, project), { ...result, viewer_url: consoleLink("mock", project, result.study.id) });
74
+ }
@@ -0,0 +1,64 @@
1
+ import { str } from "../args.js";
2
+ import { Client } from "../client.js";
3
+ import { loadAgent, resolveAgentName, resolveModel } from "../config.js";
4
+ import { CliError, WrittenReceiptMismatchError } from "../errors.js";
5
+ import { projectOf } from "./agent.js";
6
+ import { evidence } from "./evidence.js";
7
+ export async function mock(p, out) {
8
+ const [, sub, study, variant, file] = p.positionals;
9
+ if (sub !== "upload" && sub !== "gaps")
10
+ throw new CliError("usage", "mock upload <studyId> <variantId> <file.html> [--summary text] | mock gaps <studyId> --json <gapsJson> | --clear");
11
+ if (!study)
12
+ throw new CliError("usage", "studyId is required");
13
+ if (sub === "upload" && (!variant || !file || p.positionals.length !== 5))
14
+ throw new CliError("usage", "mock upload <studyId> <variantId> <file.html> [--summary text]");
15
+ if (sub === "gaps" && p.positionals.length !== 3)
16
+ throw new CliError("usage", "mock gaps <studyId> --json <gapsJson> | --clear");
17
+ let gaps;
18
+ if (sub === "gaps") {
19
+ const raw = str(p.flags, "json");
20
+ if ((p.flags.clear === true) === (raw !== undefined))
21
+ throw new CliError("usage", "choose --json <gapsJson> or --clear");
22
+ if (raw !== undefined) {
23
+ let value;
24
+ try {
25
+ value = JSON.parse(raw);
26
+ }
27
+ catch {
28
+ throw new CliError("usage", "--json must be a JSON array of gaps");
29
+ }
30
+ if (!Array.isArray(value))
31
+ throw new CliError("usage", "--json must be a JSON array of gaps");
32
+ gaps = value;
33
+ }
34
+ else
35
+ gaps = [];
36
+ }
37
+ const name = resolveAgentName(str(p.flags, "as"));
38
+ const creds = loadAgent(name);
39
+ const client = Client.forAgent(creds, resolveModel(str(p.flags, "model"), process.env, process.cwd(), name));
40
+ const project = projectOf(p, creds);
41
+ const base = `/projects/${encodeURIComponent(project)}/design-studies/${encodeURIComponent(study)}`;
42
+ if (sub === "gaps") {
43
+ const result = await client.call("POST", `${base}/gaps`, { gaps });
44
+ out.print("Reality Check submitted.", result);
45
+ return;
46
+ }
47
+ let uploaded;
48
+ await evidence({ ...p, positionals: ["evidence", "post", file], flags: { ...p.flags, type: "text/html", kind: "other" } }, { json: true, print: (_human, data) => { uploaded = data; } });
49
+ const id = typeof uploaded?.evidence?.id === "string" ? uploaded.evidence.id : typeof uploaded?.ref === "string" ? uploaded.ref.replace(/^evidence:/, "") : null;
50
+ if (!id)
51
+ throw new CliError("bad_response", "evidence upload response omitted evidence id");
52
+ const summary = str(p.flags, "summary");
53
+ try {
54
+ const result = await client.call("POST", `${base}/variants/${encodeURIComponent(variant)}/artifact`, { evidence_id: id, ...(summary !== undefined ? { summary } : {}) });
55
+ out.print(`Mock uploaded and attached: evidence:${id}`, result);
56
+ }
57
+ catch (error) {
58
+ if (error instanceof WrittenReceiptMismatchError) {
59
+ error.actionResult = `Mock evidence:${id} attached`;
60
+ throw error;
61
+ }
62
+ throw new CliError("attach_failed", `Mock evidence:${id} was uploaded, but attachment failed: ${error.message}`);
63
+ }
64
+ }
@@ -121,6 +121,8 @@ export async function watch(p, out, dependencies = {}) {
121
121
  const value = JSON.parse(claudeRuntimeText);
122
122
  if (typeof value.sandbox !== "string" || !Array.isArray(value.writableRoots) || !value.writableRoots.every((root) => typeof root === "string")
123
123
  || (value.effort !== undefined && typeof value.effort !== "string")
124
+ || (value.subagents !== undefined && !["default", "encourage", "disabled"].includes(value.subagents))
125
+ || (value.subagentModel !== undefined && (typeof value.subagentModel !== "string" || !value.subagentModel.trim() || value.subagentModel.length > 100))
124
126
  || (value.maxBudgetUsd !== undefined && (typeof value.maxBudgetUsd !== "number" || !Number.isFinite(value.maxBudgetUsd) || value.maxBudgetUsd <= 0))) {
125
127
  throw new Error("invalid Claude turn runtime fields");
126
128
  }
@@ -151,7 +153,7 @@ export async function watch(p, out, dependencies = {}) {
151
153
  ...(value.secretEgress.sessionKey ? { sessionKey: value.secretEgress.sessionKey } : {}),
152
154
  };
153
155
  }
154
- claudeRuntime = { sandbox: value.sandbox, writableRoots: value.writableRoots, ...(value.effort ? { effort: value.effort } : {}), ...(value.maxBudgetUsd ? { maxBudgetUsd: value.maxBudgetUsd } : {}), ...(secretEgress ? { secretEgress } : {}) };
156
+ claudeRuntime = { sandbox: value.sandbox, writableRoots: value.writableRoots, ...(value.effort ? { effort: value.effort } : {}), ...(value.maxBudgetUsd ? { maxBudgetUsd: value.maxBudgetUsd } : {}), ...(value.subagents ? { subagents: value.subagents } : {}), ...(value.subagentModel ? { subagentModel: value.subagentModel } : {}), ...(secretEgress ? { secretEgress } : {}) };
155
157
  }
156
158
  catch (error) {
157
159
  throw new CliError("usage", `--turn-claude-runtime must be valid Claude runtime JSON: ${error.message}`);
@@ -1021,7 +1023,7 @@ export async function wakeOnce(name, exec, unackedAfter, followDelay, log, model
1021
1023
  const workUnitBinding = bindingResolution?.binding ?? null;
1022
1024
  let turnExec = exec;
1023
1025
  let turnCwd;
1024
- if (turnSink && (dependencies.claudeRuntime?.sandbox === "workspace-write" || (provider && dependencies.antigravityRuntime?.sandbox === "workspace-write"))) {
1026
+ if (turnSink && (dependencies.claudeRuntime?.sandbox === "workspace-write" || dependencies.antigravityRuntime?.sandbox === "workspace-write")) {
1025
1027
  if (bindingToPrepare && !preparedWorktree) {
1026
1028
  throw new CliError("unit_worktree_missing", `workspace-write ${dependencies.antigravityRuntime ? "Antigravity" : "Claude Code"} cannot start WU #${bindingToPrepare.work_unit_number}: the watcher did not prepare its unit worktree`);
1027
1029
  }
@@ -1055,7 +1057,7 @@ export async function wakeOnce(name, exec, unackedAfter, followDelay, log, model
1055
1057
  socksProxyPort: turnEgressRuntime.socksProxyPort,
1056
1058
  }
1057
1059
  : undefined;
1058
- const args = claudeSettings(runtime.sandbox, model, runtime.effort, process.cwd(), configRoot(), runtime.writableRoots, preparedWorktree ?? undefined, secretEgress);
1060
+ const args = claudeSettings(runtime.sandbox, model, runtime.effort, process.cwd(), configRoot(), runtime.writableRoots, preparedWorktree ?? undefined, secretEgress, runtime.subagents ?? "default");
1059
1061
  turnExec = turnExec.replace(CLAUDE_SETTINGS_PLACEHOLDER, args.map(shellQuote).join(" "));
1060
1062
  }
1061
1063
  if (turnSink && dependencies.antigravityRuntime && turnExec?.includes(ANTIGRAVITY_SETTINGS_PLACEHOLDER)) {