benignswarm 0.12.144 → 0.12.145

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.
@@ -1,7 +1,8 @@
1
1
  import { spawnSync } from "node:child_process";
2
- import { appendFileSync, existsSync, mkdirSync, readFileSync, realpathSync, statSync } from "node:fs";
2
+ import { createHash } from "node:crypto";
3
+ import { appendFileSync, existsSync, mkdirSync, readFileSync, realpathSync, rmSync, statSync } from "node:fs";
3
4
  import { homedir } from "node:os";
4
- import { basename, delimiter, dirname, join, resolve, sep } from "node:path";
5
+ import { basename, delimiter, dirname, isAbsolute, join, resolve, sep } from "node:path";
5
6
  import { configRoot } from "./config.js";
6
7
  import { repoDirectory } from "./directories.js";
7
8
  import { CliError } from "./errors.js";
@@ -56,7 +57,7 @@ export function antigravitySandboxPermissions(apiHost, b9sHome, b9sBin, nodeBin
56
57
  allow.push(`read_file(${nodeModules})`);
57
58
  if (skillRoot) {
58
59
  allow.push(`read_file(${join(skillRoot, "identity.json")})`);
59
- for (const file of ["SKILL.md", "references/api.md", "references/watchers.md", "references/process.md", "references/continuity.md"]) {
60
+ for (const file of ["SKILL.md", "references/api.md", "references/watchers.md", "references/process.md", "references/continuity.md", "references/agent-guide.md"]) {
60
61
  allow.push(`read_file(${join(skillRoot, file)})`);
61
62
  }
62
63
  allow.push(`read_file(${join(dirname(skillRoot), ".agents", "rules", "bschat.md")})`);
@@ -151,13 +152,48 @@ export function recordAntigravityTurn(path, record) {
151
152
  export function antigravityPath(b9sBin, path = process.env.PATH ?? "") {
152
153
  return [...new Set([dirname(b9sBin), dirname(process.execPath), ...path.split(delimiter).filter(Boolean)])].join(delimiter);
153
154
  }
154
- export function antigravityTurnEnv(sandbox, b9sBin) {
155
+ /** A private scratch directory inside the checkout Antigravity is explicitly allowed to write. */
156
+ export function antigravitySessionTmpDir(cwd, agent, sessionKey) {
157
+ if (!sessionKey.trim())
158
+ throw new CliError("usage", "Antigravity session scratch requires a session key");
159
+ const folder = createHash("sha256").update(`${agent}\0${sessionKey}`).digest("hex").slice(0, 20);
160
+ return join(resolve(cwd), ".b9s-tmp", folder);
161
+ }
162
+ /** Read current watcher settings and derive scratch for persisted configs written before scratch was added. */
163
+ export function parseAntigravityTurnRuntime(text, cwd, agent, session) {
164
+ const value = JSON.parse(text);
165
+ const tmpSessionKey = value.tmpSessionKey ?? session;
166
+ const tmpDir = value.tmpDir ?? antigravitySessionTmpDir(cwd, agent, tmpSessionKey);
167
+ if (value.sandbox !== "workspace-write" || typeof value.apiHost !== "string" || typeof value.b9sBin !== "string" || typeof value.nodeBin !== "string"
168
+ || typeof tmpSessionKey !== "string" || !tmpSessionKey.trim() || typeof tmpDir !== "string"
169
+ || tmpDir !== antigravitySessionTmpDir(cwd, agent, tmpSessionKey)
170
+ || !Array.isArray(value.writableRoots) || !value.writableRoots.every((root) => typeof root === "string")) {
171
+ throw new Error("invalid Antigravity turn runtime fields");
172
+ }
173
+ return { sandbox: value.sandbox, apiHost: value.apiHost, b9sBin: value.b9sBin, nodeBin: value.nodeBin, writableRoots: value.writableRoots, tmpSessionKey, tmpDir };
174
+ }
175
+ export function cleanupAntigravitySessionTmpDir(cwd, agent, sessionKey) {
176
+ rmSync(antigravitySessionTmpDir(cwd, agent, sessionKey), { recursive: true, force: true });
177
+ }
178
+ export function finishAntigravityScratchCleanup(cwd, agent, sessionKey, log, remove = cleanupAntigravitySessionTmpDir) {
179
+ try {
180
+ remove(cwd, agent, sessionKey);
181
+ log("removed Antigravity session scratch after the turn ended");
182
+ }
183
+ catch (e) {
184
+ log(`Antigravity session scratch cleanup failed; watcher turn finalization continues: ${e.message}`);
185
+ }
186
+ }
187
+ export function antigravityTurnEnv(sandbox, b9sBin, tmpDir, inheritedEnv = process.env) {
155
188
  if (sandbox !== "workspace-write")
156
189
  return { BSCHAT_HARNESS: "antigravity", BSCHAT_ANTIGRAVITY_SANDBOX: sandbox };
190
+ if (!tmpDir || !isAbsolute(tmpDir))
191
+ throw new CliError("usage", "Antigravity workspace-write needs an absolute per-session writable TMPDIR inside the checkout");
157
192
  const path = b9sBin ? antigravityPath(b9sBin) : [...new Set([dirname(process.execPath), ...(process.env.PATH ?? "").split(delimiter).filter(Boolean)])].join(delimiter);
158
193
  // Antigravity supplies its restricted outbound proxy to sandboxed commands. Node's fetch
159
194
  // ignores the proxy environment unless opted in; b9s uses fetch for authenticated API calls.
160
- return { BSCHAT_HARNESS: "antigravity", BSCHAT_ANTIGRAVITY_SANDBOX: sandbox, NODE_USE_ENV_PROXY: "1", PATH: path };
195
+ const noProxy = [...new Set([...(inheritedEnv.NO_PROXY ?? "").split(","), ...(inheritedEnv.no_proxy ?? "").split(",")].map((host) => host.trim()).filter(Boolean).concat(["127.0.0.1", "localhost", "::1"]))].join(",");
196
+ return { BSCHAT_HARNESS: "antigravity", BSCHAT_ANTIGRAVITY_SANDBOX: sandbox, NODE_USE_ENV_PROXY: "1", NO_PROXY: noProxy, no_proxy: noProxy, TMPDIR: tmpDir, TMP: tmpDir, TEMP: tmpDir, PATH: path };
161
197
  }
162
198
  export function runAntigravityTurn(bin, args, logPath, cwd, agent, expectedConversation, run = spawnSync, envOverride = {}) {
163
199
  const started = new Date().toISOString();
package/dist/client.js CHANGED
@@ -102,7 +102,7 @@ function expectedTextReceiptFields(method, path, body, response) {
102
102
  ? ["context_decision.reason"]
103
103
  : [];
104
104
  }
105
- if (action === "assign" || action === "kind" || action === "mandatory-reviewer" || action === "required-class")
105
+ if (action === "assign" || action === "kind" || action === "mandatory-reviewer" || action === "required-class" || action === "head")
106
106
  return strings("reason");
107
107
  if (action === "take")
108
108
  return strings("reason");
@@ -284,6 +284,8 @@ function expectedStoredText(method, path, body, response) {
284
284
  const route = path.split("?", 1)[0];
285
285
  const verb = method.toUpperCase();
286
286
  const stored = {};
287
+ if (verb === "POST" && /^\/projects\/[^/]+\/work-units\/\d+\/head$/.test(route) && typeof fields.reason === "string")
288
+ stored.reason = fields.reason.trim();
287
289
  if (verb === "POST" && /^\/projects\/[^/]+\/asks\/[^/]+\/answer$/.test(route) && typeof fields.answer === "string" && fields.answer.trim()) {
288
290
  const receipts = Array.isArray(response?.receipts) ? response.receipts : [];
289
291
  if (!receipts.some((receipt) => receipt?.field === "answer"))
@@ -6,6 +6,7 @@ import { DEFAULT_URL, forgetAdmin, loadAdmin, resolveAdminName, saveAdmin } from
6
6
  import { hostname } from "node:os";
7
7
  import { spawnSync } from "node:child_process";
8
8
  import { CliError } from "../errors.js";
9
+ import { verifyUnitHeadOnOrigin } from "../git.js";
9
10
  import { table } from "../output.js";
10
11
  import { milestoneWith, milestonesWith } from "./wu.js";
11
12
  import { awayUntil } from "./agent.js";
@@ -553,6 +554,23 @@ async function role(action, rest, p, out) {
553
554
  throw new CliError("usage", "admin role create|edit|list|delete <name> [--project p] [--projects a,b|*] [--post ch1,ch2] [--broadcast] [--create-channels] [--read-account-status] [--assign-outside-qualifications yes|no] [--judges yes|no] [--description d] [--cardinality one|many]");
554
555
  }
555
556
  async function workUnitAdmin(action, rest, p, out) {
557
+ if (action === "head" && rest[0] && /^\d+$/.test(rest[1] ?? "")) {
558
+ const project = rest[0];
559
+ const number = Number(rest[1]);
560
+ const sha = rest[2];
561
+ const reason = str(p.flags, "reason");
562
+ if (!sha || !/^[0-9a-f]{40}$/.test(sha) || !reason?.trim())
563
+ throw new CliError("usage", 'b9s-admin wu head <project> <n> <full-sha> --reason "why"');
564
+ const client = adminClient(p);
565
+ const base = `/projects/${encodeURIComponent(project)}/work-units/${number}`;
566
+ const detail = await client.call("GET", `${base}/head-verification`);
567
+ if (typeof detail.branch !== "string" || !detail.branch || typeof detail.repository_identity !== "string" || typeof detail.repository_url !== "string")
568
+ throw new CliError("origin_verification_failed", `WU #${number} did not provide its branch and project repository identity`);
569
+ const proof = verifyUnitHeadOnOrigin(detail.branch, sha, detail.repository_identity, detail.repository_url);
570
+ const result = await client.call("POST", `${base}/head`, { sha, reason, ...proof });
571
+ out.print(`WU #${number} recorded head corrected to ${sha}.`, result);
572
+ return;
573
+ }
556
574
  if (action === "merged-sha" && rest[0] && /^\d+$/.test(rest[1] ?? "")) {
557
575
  const project = rest[0];
558
576
  const number = Number(rest[1]);
@@ -429,12 +429,14 @@ export async function skill(p, out) {
429
429
  const watchers = await fetchText("/skill/references/watchers.md");
430
430
  const processGuide = await fetchText("/skill/references/process.md");
431
431
  const continuity = await fetchText("/skill/references/continuity.md");
432
+ const agentGuide = await fetchText("/skill/references/agent-guide.md");
432
433
  mkdirSync(join(dir, "references"), { recursive: true });
433
434
  writeFileSync(join(dir, "SKILL.md"), main);
434
435
  writeFileSync(join(dir, "references", "api.md"), api);
435
436
  writeFileSync(join(dir, "references", "watchers.md"), watchers);
436
437
  writeFileSync(join(dir, "references", "process.md"), processGuide);
437
438
  writeFileSync(join(dir, "references", "continuity.md"), continuity);
439
+ writeFileSync(join(dir, "references", "agent-guide.md"), agentGuide);
438
440
  if (resolve(dir) === resolve(process.cwd(), ".claude", "skills", "b9s"))
439
441
  rmSync(join(process.cwd(), ".claude", "skills", "bschat"), { recursive: true, force: true });
440
442
  out.print(`Installed skill to ${dir}`, { dir });
@@ -19,7 +19,7 @@ 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
21
  import { DEFAULT_WATCH_STARTUP_JITTER_SECONDS, MAX_WATCH_STARTUP_JITTER_SECONDS } from "../startup-jitter.js";
22
- import { ANTIGRAVITY_SETTINGS_PLACEHOLDER, antigravityConversationDb, antigravityLog, antigravityResumeCommand, antigravitySettings, antigravityTotalTokens, antigravityTurnArgs, antigravityTurnEnv, runAntigravityTurn } from "../antigravity.js";
22
+ import { ANTIGRAVITY_SETTINGS_PLACEHOLDER, antigravityConversationDb, antigravityLog, antigravityResumeCommand, antigravitySessionTmpDir, antigravitySettings, antigravityTotalTokens, antigravityTurnArgs, antigravityTurnEnv, runAntigravityTurn } from "../antigravity.js";
23
23
  import { configureGitCredentialForWorktree } from "./git-credential.js";
24
24
  import { checkAndRecordHarnessBinary } from "../machine-binary.js";
25
25
  const SANDBOXES = ["read-only", "workspace-write", "danger-full-access"];
@@ -203,6 +203,10 @@ export async function harnessStart(p, out, harness) {
203
203
  const initialTurnPending = priorState.turn_guard?.turns.some((attempt) => attempt.productive === null) ?? false;
204
204
  const rememberedSession = initialTurnPending && priorState.harness_session?.harness === harness ? priorState.harness_session.session_id : null;
205
205
  const adopt = requestedAdopt ?? rememberedSession ?? undefined;
206
+ const antigravityTmpSessionKey = harness === "antigravity" && sandbox === "workspace-write" ? adopt ?? randomUUID() : undefined;
207
+ const antigravityTmp = antigravityTmpSessionKey ? antigravitySessionTmpDir(process.cwd(), ref, antigravityTmpSessionKey) : undefined;
208
+ if (antigravityTmp)
209
+ mkdirSync(antigravityTmp, { recursive: true, mode: 0o700 });
206
210
  if (inContainer)
207
211
  provisionContainerInstallRecord();
208
212
  const install = requireInstall();
@@ -244,7 +248,7 @@ export async function harnessStart(p, out, harness) {
244
248
  lines.push(`Adopted Antigravity conversation ${session}. Do not resume it elsewhere while the watcher runs it: two clients on one conversation conflict.`);
245
249
  }
246
250
  if (harness === "antigravity" && sandbox === "workspace-write")
247
- await runAntigravitySandboxSelfCheck(ref, bin, settings, process.cwd(), session, model, effort, turnTimeout * 60, firstTurnLog, turnsPerHour, antigravityTurnEnv(sandbox, install.bin), unproductivePerHour);
251
+ await runAntigravitySandboxSelfCheck(ref, bin, settings, process.cwd(), session, model, effort, turnTimeout * 60, firstTurnLog, turnsPerHour, antigravityTurnEnv(sandbox, install.bin, antigravityTmp), unproductivePerHour);
248
252
  }
249
253
  }
250
254
  else {
@@ -280,12 +284,12 @@ export async function harnessStart(p, out, harness) {
280
284
  lines.push(`Started DeepSeek Harness session ${session}; its first turn (reading its role and inbox) is running, event log: ${firstTurnLog}`);
281
285
  }
282
286
  else if (harness === "antigravity") {
283
- const started = runAntigravityTurn(bin, antigravityTurnArgs(prompt, model, effort, turnTimeout * 60, settings), firstTurnLog, process.cwd(), ref, undefined, undefined, antigravityTurnEnv(sandbox, install.bin));
287
+ const started = runAntigravityTurn(bin, antigravityTurnArgs(prompt, model, effort, turnTimeout * 60, settings), firstTurnLog, process.cwd(), ref, undefined, undefined, antigravityTurnEnv(sandbox, install.bin, antigravityTmp));
284
288
  session = started.conversation;
285
289
  await completePendingTurnGuard(ref, probeFor(harness, session, ref), (message) => diagnostic.push(message), started.output, antigravityTokenTotal(started.record.result?.usage));
286
290
  lines.push(`Started Antigravity conversation ${session}; its first turn (reading its role and inbox) completed, JSON turn log: ${firstTurnLog}`);
287
291
  if (sandbox === "workspace-write")
288
- await runAntigravitySandboxSelfCheck(ref, bin, settings, process.cwd(), session, model, effort, turnTimeout * 60, firstTurnLog, turnsPerHour, antigravityTurnEnv(sandbox, install.bin), unproductivePerHour);
292
+ await runAntigravitySandboxSelfCheck(ref, bin, settings, process.cwd(), session, model, effort, turnTimeout * 60, firstTurnLog, turnsPerHour, antigravityTurnEnv(sandbox, install.bin, antigravityTmp), unproductivePerHour);
289
293
  }
290
294
  else {
291
295
  // Claude Code takes the session id from us, so nothing has to be read back from its output.
@@ -340,14 +344,14 @@ export async function harnessStart(p, out, harness) {
340
344
  // work volume, the folder is inside what the sandbox may write, and it survives a reboot. Learned
341
345
  // from ronald, whose root volume filled with agents' builds under /tmp (46 GB) while the work
342
346
  // volume had 750 GB free, and which empties /tmp at every boot.
343
- const tmp = sessionTmpDir(process.cwd(), creds.agent);
347
+ const tmp = antigravityTmp ?? sessionTmpDir(process.cwd(), creds.agent);
344
348
  mkdirSync(tmp, { recursive: true });
345
349
  const followDelay = Number(str(p.flags, "follow-delay") ?? "300");
346
350
  const prune = bool(p.flags, "prune");
347
- watcherEnv = { TMPDIR: tmp, ...(machineSessionId ? { BSCHAT_MACHINE_SESSION_ID: machineSessionId } : {}), ...(harness === "claude-code" ? claudeSandboxEnv(sandbox) : {}), ...(harness === "antigravity" ? { ...antigravityTurnEnv(sandbox, install.bin), BSCHAT_MODEL: model, ...(effort ? { BSCHAT_EFFORT: effort } : {}) } : {}) };
351
+ watcherEnv = { TMPDIR: tmp, ...(machineSessionId ? { BSCHAT_MACHINE_SESSION_ID: machineSessionId } : {}), ...(harness === "claude-code" ? claudeSandboxEnv(sandbox) : {}), ...(harness === "antigravity" ? { ...antigravityTurnEnv(sandbox, install.bin, antigravityTmp), ...(antigravityTmpSessionKey ? { BSCHAT_ANTIGRAVITY_TMP_SESSION_KEY: antigravityTmpSessionKey } : {}), BSCHAT_MODEL: model, ...(effort ? { BSCHAT_EFFORT: effort } : {}) } : {}) };
348
352
  const turnSpec = { harness, session, timeout: turnTimeout, turnsPerHour, unproductivePerHour, coalesceSeconds: turnCoalesceSeconds, provider, model,
349
353
  ...(harness === "claude-code" && sandbox === "workspace-write" ? { claudeRuntime: { sandbox, ...(effort ? { effort } : {}), writableRoots: writable, maxBudgetUsd } } : {}),
350
- ...(harness === "antigravity" && sandbox === "workspace-write" ? { antigravityRuntime: { sandbox, apiHost: new URL(creds.url).host, b9sBin: install.bin, nodeBin: process.execPath, writableRoots: writable } } : {}),
354
+ ...(harness === "antigravity" && sandbox === "workspace-write" ? { antigravityRuntime: { sandbox, apiHost: new URL(creds.url).host, b9sBin: install.bin, nodeBin: process.execPath, writableRoots: writable, tmpSessionKey: antigravityTmpSessionKey, tmpDir: antigravityTmp } } : {}),
351
355
  ...(machineSessionId ? { machineSessionId } : {}) };
352
356
  if (inContainer) {
353
357
  const sess = sessionOfExec(exec);
@@ -646,7 +650,7 @@ export function assertAntigravitySelfCheck(output) {
646
650
  }
647
651
  }
648
652
  /** Run the two connectivity checks through the real model tools inside the per-turn sandbox. */
649
- export async function runAntigravitySandboxSelfCheck(ref, bin, settings, cwd, session, model, effort, timeoutSeconds, logPath, turnsPerHour = DEFAULT_TURNS_PER_HOUR, env = antigravityTurnEnv("workspace-write"), unproductivePerHour = DEFAULT_UNPRODUCTIVE_PER_HOUR) {
653
+ export async function runAntigravitySandboxSelfCheck(ref, bin, settings, cwd, session, model, effort, timeoutSeconds, logPath, turnsPerHour = DEFAULT_TURNS_PER_HOUR, env = antigravityTurnEnv("workspace-write", undefined, antigravitySessionTmpDir(cwd, ref, session)), unproductivePerHour = DEFAULT_UNPRODUCTIVE_PER_HOUR) {
650
654
  const diagnostic = [];
651
655
  if (!(await beginTurnGuardAttempt(ref, turnsPerHour, (message) => diagnostic.push(message), process.env, unproductivePerHour, process.env.BSCHAT_MACHINE_SESSION_ID, "antigravity", probeFor("antigravity", session, ref)))) {
652
656
  throw new CliError("turn_mode_fault", refusalReason(diagnostic));
@@ -28,6 +28,7 @@ async function fetchSkill(url) {
28
28
  watchers: await get("/skill/references/watchers.md"),
29
29
  process: await get("/skill/references/process.md"),
30
30
  continuity: await get("/skill/references/continuity.md"),
31
+ agentGuide: await get("/skill/references/agent-guide.md"),
31
32
  };
32
33
  }
33
34
  function harnessList(p, vendor) {
@@ -808,7 +808,12 @@ export async function poolAdmin(action, rest, p, out, argv) {
808
808
  `${pool.project}/${pool.name}: ${pool.count} × role ${pool.role ?? "(none)"}, ${pool.sandbox}; busy cap ${pool.turns_per_hour ?? 60}/hour, unproductive fault ${pool.unproductive_per_hour ?? 6}/hour${pool.quota_substitution ? "; quota substitution enabled" : ""}; variants ${pool.variants.map((v) => `${v.tag}=${v.harness}:${v.model ?? "default"}${v.effort ? `:${v.effort}` : ""}${v.weight > 1 ? `*${v.weight}` : ""}${v.provider && v.provider !== "anthropic" ? `@${v.provider}` : ""}`).join(", ")}${pool.needs?.labels?.length ? `; needs ${pool.needs.labels.join(", ")}` : ""}${pool.needs?.min_ram_gb ? `; min ${pool.needs.min_ram_gb} GB` : ""}`,
809
809
  ...(pool.adaptive ? [` adaptive target ${pool.adaptive.target} (min ${pool.adaptive.min}, max ${pool.adaptive.max}); ${pool.adaptive.snapshot?.decision?.kind ?? "state unknown"}: ${pool.adaptive.snapshot?.decision?.reason ?? "no snapshot"}; queued ${pool.adaptive.snapshot?.queuedWork ?? "unknown"}, idle ${pool.adaptive.snapshot?.usableIdleSlots ?? "unknown"}, oldest ${pool.adaptive.snapshot?.oldestQueuedAgeSeconds == null ? "unknown" : `${Math.floor(pool.adaptive.snapshot.oldestQueuedAgeSeconds / 60)}m`}`] : []),
810
810
  ...(pool.adaptive?.paused ? [" scaling paused by operator"] : []),
811
- ...(pool.slots ?? []).map((slot) => ` ${slot.slot}: ${slot.suspended ? `SUSPENDED${slot.bench_note ? ` (${slot.bench_note})` : ""}` : slot.drain?.state && slot.drain.state !== "none" ? `DRAIN ${slot.drain.state}${slot.drain.reason ? ` (${slot.drain.reason})` : ""}` : slot.desired ?? "unplaced"}; ${slot.machine ? `on ${slot.machine}` : "NOT PLACED"}${slot.reported_state ? `; reported ${slot.reported_state}` : ""}${slot.stale_machine ? "; machine stale" : ""}${slot.pin ? `; pinned ${slot.pin.machine}${slot.pin.conflict ? ` (conflict: ${slot.pin.conflict})` : ""}` : ""}${slot.quota_pause ? `; quota paused: ${slot.quota_pause}` : ""}${slot.current_work ? `; work ${slot.current_work}` : ""}`),
811
+ ...(pool.slots ?? []).map((slot) => {
812
+ const state = slot.suspended ? `SUSPENDED${slot.bench_note ? ` (${slot.bench_note})` : ""}`
813
+ : slot.drain?.state && slot.drain.state !== "none" ? `DRAIN ${slot.drain.state}${slot.drain.reason ? ` (${slot.drain.reason})` : ""}`
814
+ : slot.placement_state ?? slot.desired ?? "unplaced";
815
+ return ` ${slot.slot}: ${state}; ${slot.machine ? `on ${slot.machine}` : "NOT PLACED"}${slot.recovery_source_machine ? `; recovery source on ${slot.recovery_source_machine}` : ""}${slot.reported_state ? `; reported ${slot.reported_state}` : ""}${slot.stale_machine ? "; machine stale" : ""}${slot.pin ? `; pinned ${slot.pin.machine}${slot.pin.conflict ? ` (conflict: ${slot.pin.conflict})` : ""}` : ""}${slot.quota_pause ? `; quota paused: ${slot.quota_pause}` : ""}${slot.current_work ? `; work ${slot.current_work}` : ""}`;
816
+ }),
812
817
  ...(pool.slots ? [] : (pool.status?.placed ?? []).map((x) => ` ${x.agent.padEnd(32)} on ${x.machine}`)),
813
818
  ...(pool.status?.unplaced ?? []).map((x) => /^moving to /i.test(x.reason ?? "")
814
819
  ? ` ${x.agent.padEnd(32)} ${x.reason}`
@@ -1647,6 +1647,13 @@ export async function reconcile(m, log, reportIntervalSeconds = 30, deps) {
1647
1647
  ? (isContainerRunning(runningContainerRuntime, runningContainerName, runner) ? "active" : "inactive")
1648
1648
  : (w && serviceActive(w) ? "active" : "inactive");
1649
1649
  const th = state.sessions[s.id].thread;
1650
+ // The watcher keeps polling through a worktree obstruction. Surface its durable fault as
1651
+ // a session error while it retries; successful preparation clears it without a restart.
1652
+ const worktreeFault = readState(s.agent, agentStateEnv).worktree_fault;
1653
+ if (worktreeFault) {
1654
+ out.push({ id: s.id, state: "error", dir: s.dir, thread: th, watcher: watcherState, error: worktreeFault.message });
1655
+ continue;
1656
+ }
1650
1657
  // A watcher that exits at every start (a corrupt state file after the disk filled) is
1651
1658
  // restarted by systemd forever and looked "running" here; report it as the error it is.
1652
1659
  const fault = containerMode ? null : watcherFault(s.agent);
@@ -2510,6 +2517,8 @@ export function antigravitySandbox(force = false, path = process.env.PATH ?? "",
2510
2517
  let work = null;
2511
2518
  try {
2512
2519
  work = mkdtempSync(join(tmpdir(), "b9s-agy-sandbox-probe-"));
2520
+ const sessionTmp = join(work, ".b9s-tmp", "machine-probe");
2521
+ mkdirSync(sessionTmp, { recursive: true, mode: 0o700 });
2513
2522
  const marker = join(work, ".b9s-sandbox-probe");
2514
2523
  const meOutputPath = join(work, ".b9s-sandbox-probe-me");
2515
2524
  const meErrorPath = join(work, ".b9s-sandbox-probe-me-error");
@@ -2523,7 +2532,7 @@ export function antigravitySandbox(force = false, path = process.env.PATH ?? "",
2523
2532
  const settings = ["--sandbox", "--settings", JSON.stringify({ enableTerminalSandbox: true, toolPermission: "proceed-in-sandbox", permissions: { allow: antigravitySandboxPermissions("api.benignswarm.org", configRoot(), b9sBin) } })];
2524
2533
  const r = spawnSync("agy", antigravityTurnArgs(prompt, AGY_SANDBOX_PROBE_MODEL, undefined, 45, settings), {
2525
2534
  encoding: "utf8", timeout: 60_000, maxBuffer: 1024 * 1024, cwd: work,
2526
- env: { ...process.env, ...antigravityTurnEnv("workspace-write", b9sBin), BSCHAT_AGENT: agent, PATH: antigravityPath(b9sBin, path) },
2535
+ env: { ...process.env, ...antigravityTurnEnv("workspace-write", b9sBin, sessionTmp), BSCHAT_AGENT: agent, PATH: antigravityPath(b9sBin, path) },
2527
2536
  });
2528
2537
  const parsed = parseAntigravityJson(r.stdout ?? "");
2529
2538
  let wroteMarker = false;
@@ -3,7 +3,7 @@ import { bindSession, sessionOfExec, threadOfExec } from "../sessions.js";
3
3
  import { DEFAULT_TURN_COALESCE_SECONDS, MAX_TURN_COALESCE_SECONDS, shouldDeferTurn, startTurn, stopTurn } from "../turn.js";
4
4
  import { drainingUntil } from "../maintenance.js";
5
5
  import { claudeSettings, probeFor, turnHarness } from "../harnesses.js";
6
- import { ANTIGRAVITY_SETTINGS_PLACEHOLDER, antigravitySettings } from "../antigravity.js";
6
+ import { ANTIGRAVITY_SETTINGS_PLACEHOLDER, antigravitySessionTmpDir, antigravitySettings, finishAntigravityScratchCleanup, parseAntigravityTurnRuntime } from "../antigravity.js";
7
7
  import { cleanupAntigravitySandboxProbeRefs } from "../sandbox-probe.js";
8
8
  import { applyAck } from "./wake.js";
9
9
  import { launchdSessionTypeXml, lingerEnabled, machineDaemonPath, plistLaunchdDomain, loadSystemdUnit, readInstall, reloadLaunchAgent, removeService, requireInstall, systemdUnit, systemdUserDir, WATCH_LABEL_PREFIX, watcherServices } from "../install.js";
@@ -134,12 +134,7 @@ export async function watch(p, out, dependencies = {}) {
134
134
  if (harness !== "antigravity")
135
135
  throw new CliError("usage", "--turn-antigravity-runtime is only valid with --harness antigravity");
136
136
  try {
137
- const value = JSON.parse(antigravityRuntimeText);
138
- if (value.sandbox !== "workspace-write" || typeof value.apiHost !== "string" || typeof value.b9sBin !== "string" || typeof value.nodeBin !== "string"
139
- || !Array.isArray(value.writableRoots) || !value.writableRoots.every((root) => typeof root === "string")) {
140
- throw new Error("invalid Antigravity turn runtime fields");
141
- }
142
- antigravityRuntime = { sandbox: value.sandbox, apiHost: value.apiHost, b9sBin: value.b9sBin, nodeBin: value.nodeBin, writableRoots: value.writableRoots };
137
+ antigravityRuntime = parseAntigravityTurnRuntime(antigravityRuntimeText, process.cwd(), name, session);
143
138
  }
144
139
  catch (error) {
145
140
  throw new CliError("usage", `--turn-antigravity-runtime must be valid Antigravity runtime JSON: ${error.message}`);
@@ -366,7 +361,10 @@ export async function watch(p, out, dependencies = {}) {
366
361
  finish(0);
367
362
  return stoppingCode;
368
363
  }
369
- throw e;
364
+ if (e.code === "unit_worktree_diverged" && !once)
365
+ log(e.message);
366
+ else
367
+ throw e;
370
368
  }
371
369
  if (stopping)
372
370
  return stoppingCode;
@@ -484,7 +482,7 @@ export function withAgentEnv(ref, work) {
484
482
  }
485
483
  }
486
484
  /** Prepare an owned unit before launching its next turn, outside the harness sandbox. */
487
- async function prepareTurnWorktree(name, binding, allowSuperseded = false, dependencies = {}) {
485
+ export async function prepareTurnWorktree(name, binding, allowSuperseded = false, dependencies = {}) {
488
486
  const creds = loadAgent(name);
489
487
  const project = binding.project ?? creds.project;
490
488
  if (!project)
@@ -493,20 +491,30 @@ async function prepareTurnWorktree(name, binding, allowSuperseded = false, depen
493
491
  throw new CliError("unit_worktree_prepare_failed", `cannot prepare WU #${binding.work_unit_number}: server project ${project} does not match ${name}'s project ${creds.project}`);
494
492
  const client = Client.forAgent(creds, undefined, { presence: false });
495
493
  const base = `/projects/${encodeURIComponent(project)}/work-units/${binding.work_unit_number}`;
494
+ const clearWorktreeFault = () => updateState(name, (state) => {
495
+ if (state.worktree_fault?.project !== project || state.worktree_fault.unit !== binding.work_unit_number || state.worktree_fault.assignment !== binding.assignment_event_id)
496
+ return;
497
+ const { worktree_fault: _resolved, ...rest } = state;
498
+ return rest;
499
+ });
496
500
  try {
497
501
  const record = await client.call("GET", base);
498
502
  const unit = record.unit;
499
503
  if (!unit || unit.number !== binding.work_unit_number)
500
504
  throw new Error("the server did not return the requested work unit");
501
505
  if (unit.owner_name !== creds.agent) {
506
+ clearWorktreeFault();
502
507
  if (allowSuperseded)
503
508
  return null;
504
509
  throw new Error(`WU #${binding.work_unit_number} is now owned by ${unit.owner_name ?? "no agent"}, not ${creds.agent}`);
505
510
  }
506
- if (!["assigned", "open", "changes_requested"].includes(unit.status))
511
+ if (!["assigned", "open", "changes_requested"].includes(unit.status)) {
512
+ clearWorktreeFault();
507
513
  return null;
514
+ }
508
515
  const activeAssignment = currentAssignmentEvent(record.events ?? [], unit.owner_agent_id, creds.agent);
509
516
  if (activeAssignment?.id !== binding.assignment_event_id) {
517
+ clearWorktreeFault();
510
518
  if (allowSuperseded)
511
519
  return null;
512
520
  throw new Error(`assignment event ${binding.assignment_event_id} is no longer current`);
@@ -538,14 +546,63 @@ async function prepareTurnWorktree(name, binding, allowSuperseded = false, depen
538
546
  if (verified.unit?.status !== "open" || verified.unit?.branch !== location.branch || verified.unit?.head !== location.head || verified.unit?.worktree !== prepared.path) {
539
547
  throw new Error("server did not persist the prepared branch, commit and worktree exactly; refusing to launch the turn");
540
548
  }
549
+ clearWorktreeFault();
541
550
  return { number: binding.work_unit_number, path: prepared.path, branch: location.branch, status: verified.unit.status, homeChanges: prepared.homeChanges, homeCommits: prepared.homeCommits, needsRecord: false };
542
551
  }
552
+ clearWorktreeFault();
543
553
  return { number: binding.work_unit_number, path: prepared.path, branch: prepared.branch, status: unit.status, homeChanges: prepared.homeChanges, homeCommits: prepared.homeCommits, needsRecord: prepared.needsRecord };
544
554
  }
545
555
  catch (error) {
556
+ if (error.code === "unit_worktree_diverged") {
557
+ const fault = error;
558
+ updateState(name, (state) => {
559
+ const prior = state.worktree_fault;
560
+ if (prior?.project === project && prior.unit === binding.work_unit_number && prior.assignment === binding.assignment_event_id && prior.message === fault.message)
561
+ return;
562
+ return { ...state, worktree_fault: { project, unit: binding.work_unit_number, assignment: binding.assignment_event_id, message: fault.message, at: new Date().toISOString() } };
563
+ });
564
+ try {
565
+ await client.call("POST", `${base}/head-divergence`, { recorded_head: fault.recordedHead, branch: fault.branch, branch_head: fault.branchHead, message: fault.message });
566
+ }
567
+ catch (reportError) {
568
+ throw new CliError("unit_worktree_prepare_failed", `${fault.message} Could not record the divergence fault: ${reportError.message}`);
569
+ }
570
+ throw fault;
571
+ }
546
572
  throw new CliError("unit_worktree_prepare_failed", `watcher could not prepare the worktree for WU #${binding.work_unit_number}; no turn was started and the unit remains unchanged: ${error.message}`);
547
573
  }
548
574
  }
575
+ /** Recheck the fault's own assignment even when the wake has no current unit binding. */
576
+ export async function reconcileWorktreeFault(name, log) {
577
+ const fault = readState(name).worktree_fault;
578
+ if (!fault)
579
+ return;
580
+ try {
581
+ const creds = loadAgent(name);
582
+ if (creds.project && creds.project !== fault.project)
583
+ throw new Error("fault project does not match the agent credential");
584
+ const record = await Client.forAgent(creds, undefined, { presence: false }).call("GET", `/projects/${encodeURIComponent(fault.project)}/work-units/${fault.unit}`);
585
+ const unit = record.unit;
586
+ if (!unit || unit.number !== fault.unit || typeof unit.status !== "string" || !(typeof unit.owner_name === "string" || unit.owner_name === null) || !Array.isArray(record.events))
587
+ throw new Error("unit or assignment history is incomplete");
588
+ const assignment = currentAssignmentEvent(record.events, unit.owner_agent_id, creds.agent);
589
+ if (unit.owner_name === creds.agent && ["assigned", "open", "changes_requested"].includes(unit.status)) {
590
+ if (!assignment)
591
+ throw new Error("current assignment event is unavailable");
592
+ if (assignment.id === fault.assignment)
593
+ return;
594
+ }
595
+ updateState(name, (state) => {
596
+ if (JSON.stringify(state.worktree_fault) !== JSON.stringify(fault))
597
+ return;
598
+ const { worktree_fault: _resolved, ...rest } = state;
599
+ return rest;
600
+ });
601
+ }
602
+ catch (error) {
603
+ log(`could not recheck WU #${fault.unit}'s worktree fault: ${error.message}; keeping the fault`);
604
+ }
605
+ }
549
606
  const CODEX_THREAD_ID = /[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/i;
550
607
  /** Follow a Codex exec that opens a new thread, as soon as the session hook records its id. */
551
608
  export function followCurrentCodexProbe(name, initialThread) {
@@ -633,6 +690,8 @@ async function pendingClearTurn(name, exec, clear, st, log, model, turnSink, bef
633
690
  export async function wakeOnce(name, exec, unackedAfter, followDelay, log, model, once, turnSink, includeResumeBrief = false, provider, turnStdin = false, beforeTurn, allowTurn, sessionId, turnCoalesceSeconds = 0, dependencies = {}) {
634
691
  const debug = (message) => { if (process.env.BSCHAT_WATCH_DEBUG === "1")
635
692
  log(`debug poll: ${message}`); };
693
+ if (turnSink)
694
+ await reconcileWorktreeFault(name, log);
636
695
  const state = readState(name);
637
696
  const pending = state.watch_pending;
638
697
  if (pending) {
@@ -828,6 +887,7 @@ export async function wakeOnce(name, exec, unackedAfter, followDelay, log, model
828
887
  }
829
888
  if (turnSink && dependencies.antigravityRuntime && turnExec?.includes(ANTIGRAVITY_SETTINGS_PLACEHOLDER)) {
830
889
  const runtime = dependencies.antigravityRuntime;
890
+ mkdirSync(runtime.tmpDir, { recursive: true, mode: 0o700 });
831
891
  const args = antigravitySettings(runtime.sandbox, process.cwd(), configRoot(), runtime.apiHost, [...runtime.writableRoots, ...(preparedWorktree ? [preparedWorktree.path] : [])], runtime.b9sBin, runtime.nodeBin, name, preparedWorktree ?? undefined);
832
892
  turnExec = turnExec.replace(ANTIGRAVITY_SETTINGS_PLACEHOLDER, args.map(shellQuote).join(" "));
833
893
  }
@@ -1152,6 +1212,10 @@ export async function turnStep(ctl, probe, timeoutMin, log, wake, name, turnsPer
1152
1212
  catch (e) {
1153
1213
  log(`Antigravity sandbox probe ref cleanup failed outside the session sandbox: ${e.message}`);
1154
1214
  }
1215
+ const tmpSessionKey = env.BSCHAT_ANTIGRAVITY_TMP_SESSION_KEY;
1216
+ if (tmpSessionKey && env.TMPDIR === antigravitySessionTmpDir(process.cwd(), name, tmpSessionKey)) {
1217
+ finishAntigravityScratchCleanup(process.cwd(), name, tmpSessionKey, log);
1218
+ }
1155
1219
  }
1156
1220
  ctl.turn = null;
1157
1221
  await completePendingTurnGuard(name, probe, log, undefined, undefined, env);
@@ -10,7 +10,7 @@ import { readState, updateState } from "../state.js";
10
10
  import { codexRollout, sessionsOf } from "../sessions.js";
11
11
  import { claudeSessionWithHookMetadata, sessionCompactions, sessionContext, sessionStart, sessionUsage } from "../usage.js";
12
12
  import { CliError, WrittenReceiptMismatchError } from "../errors.js";
13
- import { branchAndHead, commitAtTime, defaultMachine, ensureReviewWorktree, ensureWorktree, fetchRef, fetchRemoteBranch, findRemoteCommitBranch, formatRemoteCommitFailure, formatRemoteCommitSuccess, fullSha, isAncestor, isShaBranchName, removeWorktreeIfClean, repoName, repoParent, symbolicBranch, verifyMergedCommit, verifyNoCommitsBeyondTarget, worktreeForBranch, worktreeState } from "../git.js";
13
+ import { branchAndHead, commitAtTime, defaultMachine, ensureReviewWorktree, ensureWorktree, fetchRef, fetchRemoteBranch, findRemoteCommitBranch, formatRemoteCommitFailure, formatRemoteCommitSuccess, fullSha, isAncestor, isShaBranchName, removeWorktreeIfClean, repoName, repoParent, symbolicBranch, verifyMergedCommit, verifyNoCommitsBeyondTarget, verifyUnitHeadOnOrigin, worktreeForBranch, worktreeState } from "../git.js";
14
14
  import { join, resolve } from "node:path";
15
15
  import { formatStepRules, table } from "../output.js";
16
16
  import { restoreRecoveryArchive, sha256 as recoverySha256 } from "../recovery-archive.js";
@@ -1160,6 +1160,20 @@ export async function wu(p, out) {
1160
1160
  out.print(fmt(r.unit), r);
1161
1161
  return;
1162
1162
  }
1163
+ case "head": {
1164
+ const sha = p.positionals[3];
1165
+ const reason = str(p.flags, "reason");
1166
+ if (!sha || !/^[0-9a-f]{40}$/.test(sha) || !reason?.trim())
1167
+ throw new CliError("usage", 'wu head <n> <full-40-character-lowercase-sha> --reason "why"');
1168
+ const number = num();
1169
+ const detail = await client.call("GET", `${base}/${number}/head-verification`);
1170
+ if (typeof detail.branch !== "string" || !detail.branch || typeof detail.repository_identity !== "string" || typeof detail.repository_url !== "string")
1171
+ throw new CliError("origin_verification_failed", `WU #${number} did not provide its branch and project repository identity`);
1172
+ const proof = verifyUnitHeadOnOrigin(detail.branch, sha, detail.repository_identity, detail.repository_url);
1173
+ const result = await client.call("POST", `${base}/${number}/head`, { sha, reason, ...proof });
1174
+ out.print(fmt(result.unit), result);
1175
+ return;
1176
+ }
1163
1177
  case "target": {
1164
1178
  // Move where the unit lands, before review. "default" restores the process target.
1165
1179
  const t = p.positionals[3];
@@ -1416,6 +1430,29 @@ function assertNotShaBranch(branch, flag = "--branch") {
1416
1430
  throw new CliError("usage", `refusing ${flag} ${branch}: never name a branch after a commit SHA`, "Pass a descriptive branch name like wu/123-fix or omit --branch to create one from origin's target.");
1417
1431
  }
1418
1432
  }
1433
+ export function divergentUnitHeadMessage(n, recordedHead, branch, branchHead, cwd = process.cwd()) {
1434
+ const subject = spawnSync("git", ["show", "-s", "--format=%s", recordedHead], { cwd, encoding: "utf8" });
1435
+ const history = spawnSync("git", ["log", "-n", "2000", "--format=%H%x09%s", branchHead, "--"], { cwd, encoding: "utf8", maxBuffer: 4 * 1024 * 1024 });
1436
+ let match;
1437
+ if (subject.status !== 0 || history.status !== 0 || !subject.stdout.trim())
1438
+ match = "Matching commit subject could not be checked.";
1439
+ else {
1440
+ const found = history.stdout.split(/\r?\n/).map((line) => line.split("\t", 2)).find(([sha, title]) => sha !== recordedHead && title === subject.stdout.trim());
1441
+ match = found ? `A commit with the same subject appears on the branch: ${found[0]}; this is not proof of the same change.` : "No commit with the same subject appears in the first 2000 branch commits.";
1442
+ }
1443
+ return `WU #${n}: recorded head ${recordedHead} and local branch ${branch} at ${branchHead} diverge; refusing to guess which committed work belongs to the unit. ${match} After inspecting and pushing the intended branch, an operator or assigner can record its head with: b9s wu head ${n} ${branchHead} --reason "explain the verified head"`;
1444
+ }
1445
+ export class UnitWorktreeDiverged extends CliError {
1446
+ recordedHead;
1447
+ branch;
1448
+ branchHead;
1449
+ constructor(recordedHead, branch, branchHead, message) {
1450
+ super("unit_worktree_diverged", message);
1451
+ this.recordedHead = recordedHead;
1452
+ this.branch = branch;
1453
+ this.branchHead = branchHead;
1454
+ }
1455
+ }
1419
1456
  export function prepareWorktreeForWatcher(n, unit, def, exclude = []) {
1420
1457
  if (unit.branch && isShaBranchName(unit.branch))
1421
1458
  throw new CliError("no_branch", `recorded branch ${unit.branch} is a commit identifier, not a branch`, "Record and push the unit branch before retrying.");
@@ -1455,6 +1492,8 @@ export function prepareWorktreeForWatcher(n, unit, def, exclude = []) {
1455
1492
  const recoveryRequired = homeCheckoutRecorded || recordedWorktreeMissing || startedUnitWithoutRecordedWorktree || adoptedExistingWorktree;
1456
1493
  const recordedHead = recoveryRequired && typeof unit.head === "string" ? fullSha(unit.head) : null;
1457
1494
  const recordedBranchTip = recoveryRequired && typeof unit.branch === "string" && !isShaBranchName(unit.branch) ? fullSha(`refs/heads/${unit.branch}`) : null;
1495
+ if (recoveryRequired && unit.head && !recordedHead)
1496
+ throw new CliError("unit_worktree_prepare_failed", `recorded head ${unit.head} is unavailable in this checkout; fetch it before preparing WU #${n}`);
1458
1497
  let recoveryBase = recordedHead ?? recordedBranchTip;
1459
1498
  if (recordedHead && recordedBranchTip) {
1460
1499
  const headIsOnBranch = isAncestor(recordedHead, recordedBranchTip, home);
@@ -1462,7 +1501,7 @@ export function prepareWorktreeForWatcher(n, unit, def, exclude = []) {
1462
1501
  if (headIsOnBranch === true)
1463
1502
  recoveryBase = recordedBranchTip;
1464
1503
  else if (branchIsOnHead !== true) {
1465
- throw new CliError("unit_worktree_prepare_failed", `recorded head ${recordedHead} and local branch ${unit.branch} diverge; refusing to guess which committed work belongs to WU #${n}`);
1504
+ throw new UnitWorktreeDiverged(recordedHead, unit.branch, recordedBranchTip, divergentUnitHeadMessage(n, recordedHead, unit.branch, recordedBranchTip, home));
1466
1505
  }
1467
1506
  }
1468
1507
  if (adoptedExistingWorktree) {
package/dist/git.js CHANGED
@@ -677,6 +677,64 @@ export function fetchRemoteBranch(branch, remote = "origin", cwd = process.cwd()
677
677
  }
678
678
  return { ok: true, ref: trackingRef };
679
679
  }
680
+ /** Compare supported Git URL forms by host and repository path, without exposing user info. */
681
+ export function normalizedRepositoryUrl(value) {
682
+ const scp = /^([^@/:\s]+)@([^/:\s]+):(.+)$/.exec(value);
683
+ const candidate = scp ? `ssh://${scp[2]}/${scp[3]}` : value;
684
+ let parsed;
685
+ try {
686
+ parsed = new URL(candidate);
687
+ }
688
+ catch {
689
+ throw new CliError("origin_verification_failed", "repository URL cannot be normalized safely");
690
+ }
691
+ if (!["https:", "ssh:"].includes(parsed.protocol) || !parsed.hostname || parsed.search || parsed.hash)
692
+ throw new CliError("origin_verification_failed", "repository URL cannot be normalized safely");
693
+ const path = parsed.pathname.replace(/^\/+|\/+$/g, "").replace(/\.git$/, "");
694
+ if (!path)
695
+ throw new CliError("origin_verification_failed", "repository URL has no repository path");
696
+ const port = parsed.port && !(parsed.protocol === "ssh:" && parsed.port === "22") ? `${parsed.protocol.slice(0, -1)}:${parsed.port}@` : "";
697
+ return `${port}${parsed.hostname.toLowerCase()}/${path}`;
698
+ }
699
+ /** Verify the selected commit against a freshly fetched, consistently advertised origin branch. */
700
+ export function verifyUnitHeadOnOrigin(branch, sha, repositoryIdentity, repositoryUrl, cwd = process.cwd()) {
701
+ if (!/^[0-9a-f]{40}$/.test(sha))
702
+ throw new CliError("usage", "head must be a full 40-character lowercase commit SHA");
703
+ if (!/^[0-9a-f]{64}$/.test(repositoryIdentity))
704
+ throw new CliError("origin_verification_failed", "the project did not provide a valid repository identity");
705
+ const configured = spawnSync("git", ["config", "--get-all", "remote.origin.url"], { cwd, encoding: "utf8" });
706
+ const effective = spawnSync("git", ["remote", "get-url", "--all", "origin"], { cwd, encoding: "utf8" });
707
+ const urls = (text) => text.trim().split(/\r?\n/).filter(Boolean);
708
+ const configuredUrls = urls(configured.stdout ?? "");
709
+ const effectiveUrls = urls(effective.stdout ?? "");
710
+ if (configured.status !== 0 || effective.status !== 0 || configuredUrls.length !== 1 || effectiveUrls.length !== 1)
711
+ throw new CliError("origin_verification_failed", "origin must have exactly one configured URL");
712
+ const expected = normalizedRepositoryUrl(repositoryUrl);
713
+ const configuredOrigin = normalizedRepositoryUrl(configuredUrls[0]);
714
+ const effectiveOrigin = normalizedRepositoryUrl(effectiveUrls[0]);
715
+ if (configuredOrigin !== expected || effectiveOrigin !== expected)
716
+ throw new CliError("origin_verification_failed", `this checkout's origin ${configuredOrigin}${effectiveOrigin !== configuredOrigin ? ` (effective ${effectiveOrigin})` : ""} does not match the selected project's configured repository ${expected}`);
717
+ const remoteRef = `refs/heads/${branch}`;
718
+ if (spawnSync("git", ["check-ref-format", remoteRef], { cwd }).status !== 0)
719
+ throw new CliError("no_branch", "the recorded branch is not a valid Git branch");
720
+ const fetched = fetchRemoteBranch(branch, "origin", cwd);
721
+ if (!fetched.ok)
722
+ throw new CliError("origin_verification_failed", `cannot fetch the recorded branch from origin: ${fetched.reason}`);
723
+ const fetchedTip = fullSha(`refs/remotes/origin/${branch}`, cwd);
724
+ const listed = spawnSync("git", ["ls-remote", "--exit-code", "--heads", "origin", remoteRef], { cwd, encoding: "utf8", timeout: 120_000 });
725
+ if (listed.status !== 0)
726
+ throw new CliError("origin_verification_failed", `cannot read the recorded branch from origin: ${listed.error?.message || listed.stderr?.trim() || `git ls-remote exited ${listed.status ?? "without a status"}`}`);
727
+ const lines = listed.stdout.trim().split(/\r?\n/).map((line) => line.split(/\s+/));
728
+ if (lines.length !== 1 || lines[0]?.[1] !== remoteRef || !/^[0-9a-f]{40}$/.test(lines[0]?.[0] ?? ""))
729
+ throw new CliError("origin_verification_failed", "origin did not advertise exactly the recorded branch and a full SHA");
730
+ const remoteTip = lines[0][0];
731
+ if (!fetchedTip || fetchedTip !== remoteTip)
732
+ throw new CliError("origin_verification_failed", "the origin branch changed while it was being verified; fetch and try again");
733
+ const onBranch = isAncestor(sha, fetchedTip, cwd);
734
+ if (onBranch !== true)
735
+ throw new CliError("origin_verification_failed", onBranch === false ? `${sha} is not on origin/${branch}` : `cannot verify ${sha} against origin/${branch}`);
736
+ return { branch, remote_tip: remoteTip, repository_identity: repositoryIdentity };
737
+ }
680
738
  /** Check a merge against the local target, then the freshly fetched origin target when needed. */
681
739
  export function verifyMergedCommit(merged, target, cwd = process.cwd()) {
682
740
  const local = isAncestor(merged, target, cwd);
package/dist/harness.js CHANGED
@@ -153,6 +153,7 @@ export function installForHarness(root, harness, files, agentName, apiUrl, bin)
153
153
  writeFileSync(join(neutral, "references", "watchers.md"), files.watchers);
154
154
  writeFileSync(join(neutral, "references", "process.md"), files.process);
155
155
  writeFileSync(join(neutral, "references", "continuity.md"), files.continuity);
156
+ writeFileSync(join(neutral, "references", "agent-guide.md"), files.agentGuide);
156
157
  written.push(join(neutral, "SKILL.md"));
157
158
  switch (harness) {
158
159
  case "claude-code": {
@@ -163,6 +164,7 @@ export function installForHarness(root, harness, files, agentName, apiUrl, bin)
163
164
  writeFileSync(join(dir, "references", "watchers.md"), files.watchers);
164
165
  writeFileSync(join(dir, "references", "process.md"), files.process);
165
166
  writeFileSync(join(dir, "references", "continuity.md"), files.continuity);
167
+ writeFileSync(join(dir, "references", "agent-guide.md"), files.agentGuide);
166
168
  written.push(join(dir, "SKILL.md"));
167
169
  rmSync(join(root, ".claude", "skills", "bschat"), { recursive: true, force: true });
168
170
  const sp = join(root, ".claude", "settings.local.json");
package/dist/help.js CHANGED
@@ -175,6 +175,7 @@ Machine placement enforces configured session slots and reports machine pressure
175
175
  b9s wu scope <n> --replace "<old>" "<new>" --note ".." replace one exact, unique substring of the scope
176
176
  b9s wu scope <n> --append ".." --note ".." add a dated scope amendment (up to 2000 chars); the base scope stays capped at 4000
177
177
  b9s wu target <n> <branch|default> [--summary "reviewed work summary"] owner, assigner or operator: change where this unit lands
178
+ b9s wu head <n> <full-sha> --reason "why" assigner or operator: record a commit verified on the unit's branch
178
179
  b9s ask-operator "what you need from them" --plain ".." --blocks ".." --if-yes ".." --if-no ".." [--propose ".."] [--milestone <key> | --unit <n>] [--question <text>]
179
180
  b9s ask-operator --amend <id> ["new question"] [--plain ".."] [--blocks ".."] [--if-yes ".."] [--if-no ".."] [--propose ".."] [--question <text>] amend your own open ask
180
181
  b9s ask-operator withdraw <key> --note "why it no longer needs an operator answer" withdraw your own ask, a steward-raised declared-wait ask, or an ask if you are a project assigner
@@ -404,6 +405,7 @@ Use --admin <nickname> to select one of this machine's saved operator identities
404
405
  b9s-admin wu done <project> <n> --merged <sha> [--gate-override-note "why"] [--note "context"] operator: close approved work; missing receipt override requires a recorded reason
405
406
  b9s-admin wu done <project> <n> --no-source --evidence id[,id...] --no-commits-beyond-target [--gate-override-note "why"] operator: close evidence-only work after confirming no commits beyond target
406
407
  b9s-admin wu merged-sha <project> <n> --sha <full-40-character-lowercase-sha> --reason "why" operator: correct a legacy abbreviated merged SHA with an audited reason
408
+ b9s-admin wu head <project> <n> <full-sha> --reason "why" operator: record a commit verified on the unit's branch
407
409
  b9s-admin wu required-class <project> <n> (--class <p/h/m/e> | --clear) --reason "why" set or clear an operator hard routing-class lock
408
410
  b9s-admin routing show <project> [--mode build|review] [--tag <tag>] inspect confidence matrix, exploration spend, and recent decisions
409
411
  b9s-admin routing policy <project> [--weights q,t,c] [--quality-target <0..100|none>] [--half-life <days>] [--min-samples <n>] [--build-explore <0..20>] [--review-explore <0..20>] [--pause-build yes|no] [--pause-review yes|no] [--reason "why"]
@@ -1,4 +1,5 @@
1
1
  import { spawnSync } from "node:child_process";
2
+ import { createServer } from "node:http";
2
3
  import { createHash } from "node:crypto";
3
4
  import { closeSync, existsSync, mkdirSync, openSync, readFileSync, readdirSync, realpathSync, rmSync, unlinkSync, writeFileSync } from "node:fs";
4
5
  import { homedir } from "node:os";
@@ -11,7 +12,8 @@ export const PROBE_CHECKS = [
11
12
  "cwd_is_checkout", "origin_is_https",
12
13
  "tool_node", "tool_npm", "tool_npx", "tool_git", "tool_b9s",
13
14
  "git_branch", "git_branch_delete", "git_object", "git_worktree", "git_other_worktree", "git_remote_read",
14
- "net_api", "net_other_host",
15
+ "net_api", "net_other_host", "net_loopback",
16
+ "tmpdir_writable", "system_tmpdir_refused",
15
17
  "write_checkout", "write_checkout_parent", "write_unit_worktree", "write_sibling_checkout", "git_commit", "git_fetch", "write_b9s_home",
16
18
  "write_git_config", "write_git_hooks", "write_home", "write_node_install",
17
19
  ];
@@ -186,6 +188,30 @@ async function reach(url, timeoutMs = 10_000) {
186
188
  return { ok: false, detail: clip(cause ? `${e.message}: ${cause}` : e.message) };
187
189
  }
188
190
  }
191
+ async function reachLoopback() {
192
+ const server = createServer((_request, response) => { response.end("b9s-loopback-ok"); });
193
+ try {
194
+ await new Promise((resolve, reject) => {
195
+ server.once("error", reject);
196
+ server.listen(0, "127.0.0.1", resolve);
197
+ });
198
+ const address = server.address();
199
+ if (!address || typeof address === "string")
200
+ throw new Error("loopback server did not report its bound address");
201
+ const response = await fetch(`http://127.0.0.1:${address.port}/probe`, { signal: AbortSignal.timeout(5_000), redirect: "manual" });
202
+ const body = await response.text();
203
+ if (response.status !== 200 || body !== "b9s-loopback-ok")
204
+ throw new Error(`loopback response was HTTP ${response.status} with unexpected body`);
205
+ return { ok: true, value: `127.0.0.1:${address.port}`, detail: "local HTTP server reached directly" };
206
+ }
207
+ catch (error) {
208
+ return { ok: false, detail: clip(error.message) };
209
+ }
210
+ finally {
211
+ if (server.listening)
212
+ await new Promise((resolve) => server.close(() => resolve()));
213
+ }
214
+ }
189
215
  export async function runSandboxProbe(options) {
190
216
  const env = options.env ?? process.env;
191
217
  const cwd = options.cwd ?? process.cwd();
@@ -214,6 +240,9 @@ export async function runSandboxProbe(options) {
214
240
  checks.tool_npx = tool("npx", ["--version"], cwd, env);
215
241
  checks.tool_git = tool("git", ["--version"], cwd, env);
216
242
  checks.tool_b9s = tool("b9s", null, cwd, env);
243
+ checks.tmpdir_writable = env.TMPDIR ? createAndRemove(env.TMPDIR, nonce) : { ok: false, detail: "TMPDIR is not set" };
244
+ checks.system_tmpdir_refused = createAndRemove("/tmp", nonce);
245
+ checks.net_loopback = await reachLoopback();
217
246
  if (toplevel) {
218
247
  const agent = env.BSCHAT_AGENT;
219
248
  const watcherCleansRef = options.harness === "antigravity" && options.sandbox === "workspace-write";
@@ -387,7 +416,8 @@ export function expectedFor(harness, sandbox, result) {
387
416
  cwd_is_checkout: works, origin_is_https: { expected: "any", note: UNMEASURED },
388
417
  tool_node: works, tool_npm: works, tool_npx: works, tool_git: works, tool_b9s: works,
389
418
  git_branch: works, git_branch_delete: works, git_object: works, git_worktree: works, git_other_worktree: result?.checks.git_other_worktree?.not_applicable ? otherWorktree : { expected: "any", note: UNMEASURED }, git_remote_read: works,
390
- net_api: works, net_other_host: { expected: "any", note: UNMEASURED },
419
+ net_api: works, net_other_host: { expected: "any", note: UNMEASURED }, net_loopback: { expected: "any", note: UNMEASURED },
420
+ tmpdir_writable: { expected: "any", note: UNMEASURED }, system_tmpdir_refused: { expected: "any", note: UNMEASURED },
391
421
  write_checkout: works, write_checkout_parent: works, write_unit_worktree: { expected: "any", note: "requires --unit-worktree" }, write_sibling_checkout: { expected: "any", note: "requires --sibling-checkout" }, git_commit: { expected: "any", note: "requires --unit-worktree" }, git_fetch: { expected: "any", note: "requires --unit-worktree" }, write_b9s_home: works,
392
422
  write_git_config: { expected: "any", note: ACCEPTED_GIT }, write_git_hooks: { expected: "any", note: ACCEPTED_GIT },
393
423
  write_home: { expected: "any", note: UNMEASURED }, write_node_install: { expected: "any", note: UNMEASURED },
@@ -404,6 +434,9 @@ export function expectedFor(harness, sandbox, result) {
404
434
  return {
405
435
  ...base,
406
436
  origin_is_https: works,
437
+ net_loopback: { expected: "works", note: "Antigravity workspace-write must reach an explicitly bound local test server; loopback bypass is limited to localhost, 127.0.0.1 and ::1" },
438
+ tmpdir_writable: { expected: "works", note: "b9s start sets a checkout-local per-agent scratch directory for Antigravity workspace-write" },
439
+ system_tmpdir_refused: { expected: "refused", note: "Antigravity workspace-write remains scoped to checkout grants; system /tmp is not granted" },
407
440
  git_branch_delete: { expected: "refused", note: ANTIGRAVITY_REF_CLEANUP },
408
441
  git_worktree: { expected: "refused", note: ANTIGRAVITY_GIT_SCOPE },
409
442
  write_checkout_parent: { expected: "refused", note: ANTIGRAVITY_GIT_SCOPE },
@@ -476,7 +509,8 @@ const LABEL = {
476
509
  origin_is_https: "origin is reached over HTTPS",
477
510
  tool_node: "node runs", tool_npm: "npm runs", tool_npx: "npx runs", tool_git: "git runs", tool_b9s: "b9s is on PATH",
478
511
  git_branch: "git can create a probe branch", git_branch_delete: "git can delete a branch from inside the session", git_object: "git can write a commit object", git_worktree: "git can add its reserved sandbox probe worktree", git_other_worktree: "another agent's Git worktree metadata is writable", git_remote_read: "git can read origin",
479
- net_api: "the BenignSwarm API is reachable", net_other_host: "a host outside the allow-list is reachable",
512
+ net_api: "the BenignSwarm API is reachable", net_other_host: "a host outside the allow-list is reachable", net_loopback: "a local test server is reachable through loopback",
513
+ tmpdir_writable: "the configured TMPDIR accepts a temporary file", system_tmpdir_refused: "the system /tmp directory is refused",
480
514
  write_checkout: "the checkout is writable", write_checkout_parent: "the checkout's parent is writable", write_unit_worktree: "the active unit worktree is writable", write_sibling_checkout: "a sibling checkout is writable", git_commit: "git commit works in the active unit worktree", git_fetch: "git fetch works in the active unit worktree", write_b9s_home: "b9s's own folder is writable",
481
515
  write_git_config: "the clone's git config is writable", write_git_hooks: "the clone's git hooks are writable",
482
516
  write_home: "the home folder is writable", write_node_install: "the Node installation is writable",
package/dist/version.js CHANGED
@@ -1 +1 @@
1
- export const CLI_VERSION = "0.12.144";
1
+ export const CLI_VERSION = "0.12.145";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "benignswarm",
3
- "version": "0.12.144",
3
+ "version": "0.12.145",
4
4
  "description": "b9s: chat, status board and evidence store for coding agents (benignswarm.org)",
5
5
  "license": "UNLICENSED",
6
6
  "repository": {