benignswarm 0.12.144 → 0.12.146

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]);
@@ -97,15 +97,28 @@ export async function me(p, out) {
97
97
  }
98
98
  export async function who(p, out) {
99
99
  const { client, creds } = agentClient(p);
100
+ const projectStalls = async (project) => {
101
+ const response = await client.call("GET", `/projects/${encodeURIComponent(project)}/work-units?all=1`);
102
+ return (response.units ?? []).filter((unit) => unit.stalled).map((unit) => ({ number: unit.number, owner_name: unit.owner_name, age_minutes: unit.stalled.age_minutes, reason: unit.stalled.reason }));
103
+ };
104
+ const statusLines = (statuses, stalled) => statuses.map((status) => {
105
+ const owned = stalled.filter((unit) => unit.owner_name === status.agent_name);
106
+ return `${fmtStatus(status)}${owned.length ? `\n stalled work: ${owned.map((unit) => `WU #${unit.number} · ${unit.age_minutes} min · ${unit.reason}`).join("; ")}` : ""}`;
107
+ });
100
108
  if (bool(p.flags, "account") || (!creds.project && !str(p.flags, "project") && !process.env.BSCHAT_PROJECT)) {
101
109
  const r = await client.call("GET", "/account/agents/status");
102
110
  const acct = r.account.statuses.length ? `## account-wide agents\n${r.account.statuses.map(fmtStatus).join("\n")}\n\n` : "";
103
- const text = acct + r.projects.map((pr) => `## ${pr.project}\n${pr.statuses.length ? pr.statuses.map(fmtStatus).join("\n") : "(no agents have reported)"}`).join("\n\n");
104
- out.print(text, r);
111
+ const projects = await Promise.all(r.projects.map(async (pr) => {
112
+ const stalled = await projectStalls(pr.project);
113
+ return { ...pr, stalled_units: stalled, text: `## ${pr.project}\n${pr.statuses.length ? statusLines(pr.statuses, stalled).join("\n") : "(no agents have reported)"}` };
114
+ }));
115
+ const text = acct + projects.map((pr) => pr.text).join("\n\n");
116
+ out.print(text, { ...r, projects });
105
117
  return;
106
118
  }
107
119
  const r = await client.call("GET", `/projects/${projectOf(p, creds)}/agents/status`);
108
- out.print(r.statuses.length ? r.statuses.map(fmtStatus).join("\n") : "(no agents have reported status yet)", r);
120
+ const stalled = await projectStalls(projectOf(p, creds));
121
+ out.print(r.statuses.length ? statusLines(r.statuses, stalled).join("\n") : "(no agents have reported status yet)", { ...r, stalled_units: stalled });
109
122
  }
110
123
  export async function status(p, out) {
111
124
  const sub = p.positionals[1];
@@ -429,12 +442,14 @@ export async function skill(p, out) {
429
442
  const watchers = await fetchText("/skill/references/watchers.md");
430
443
  const processGuide = await fetchText("/skill/references/process.md");
431
444
  const continuity = await fetchText("/skill/references/continuity.md");
445
+ const agentGuide = await fetchText("/skill/references/agent-guide.md");
432
446
  mkdirSync(join(dir, "references"), { recursive: true });
433
447
  writeFileSync(join(dir, "SKILL.md"), main);
434
448
  writeFileSync(join(dir, "references", "api.md"), api);
435
449
  writeFileSync(join(dir, "references", "watchers.md"), watchers);
436
450
  writeFileSync(join(dir, "references", "process.md"), processGuide);
437
451
  writeFileSync(join(dir, "references", "continuity.md"), continuity);
452
+ writeFileSync(join(dir, "references", "agent-guide.md"), agentGuide);
438
453
  if (resolve(dir) === resolve(process.cwd(), ".claude", "skills", "b9s"))
439
454
  rmSync(join(process.cwd(), ".claude", "skills", "bschat"), { recursive: true, force: true });
440
455
  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));
@@ -225,9 +225,38 @@ export async function gatherUpdates(name, opts) {
225
225
  const followed = [];
226
226
  const readCommands = [];
227
227
  const pendingReads = new Map();
228
+ const stalledLines = [];
229
+ const stalledNext = { ...(state.stalled_work_delivered ?? {}) };
230
+ const stalledRemoved = new Set();
228
231
  try {
229
232
  const projects = creds.project ? [creds.project] : ((await client.call("GET", "/me")).projects ?? []).map((x) => x.name);
230
233
  for (const project of projects) {
234
+ try {
235
+ const work = await client.call("GET", `/projects/${encodeURIComponent(project)}/work-units?agent=${encodeURIComponent(creds.agent)}`);
236
+ const activeStalls = new Set();
237
+ for (const unit of (work.units ?? []).filter((item) => item.owner_name === creds.agent && item.stalled)) {
238
+ const key = `${project}/${unit.number}`;
239
+ activeStalls.add(key);
240
+ const episode = unit.stalled.since;
241
+ if (typeof episode !== "string" || !episode) {
242
+ process.stderr.write(`b9s: stalled work status for ${project} WU #${unit.number} has no episode timestamp\n`);
243
+ continue;
244
+ }
245
+ if (stalledNext[key] !== episode) {
246
+ stalledLines.push(` ${creds.project ? "" : `[${project}] `}WU #${unit.number}: stalled ${unit.stalled.age_minutes} min · ${unit.stalled.reason} — b9s wu show ${creds.project ? "" : `--project ${project} `}${unit.number}`);
247
+ stalledNext[key] = episode;
248
+ }
249
+ }
250
+ for (const key of Object.keys(stalledNext)) {
251
+ if (key.startsWith(`${project}/`) && !activeStalls.has(key)) {
252
+ delete stalledNext[key];
253
+ stalledRemoved.add(key);
254
+ }
255
+ }
256
+ }
257
+ catch (error) {
258
+ process.stderr.write(`b9s: stalled work status for ${project}: ${error.message}\n`);
259
+ }
231
260
  const since = Object.fromEntries(Object.entries(channelRead).filter(([k]) => k.startsWith(`${project}/`)).map(([k, v]) => [k.slice(project.length + 1), v]));
232
261
  const sinceQuery = Object.keys(since).length ? `?since=${encodeURIComponent(JSON.stringify(since))}` : "";
233
262
  const { cursors } = await client.call("GET", `/projects/${project}/channels/cursors${sinceQuery}`);
@@ -311,13 +340,21 @@ export async function gatherUpdates(name, opts) {
311
340
  // Never backwards: another reader may have surfaced later messages meanwhile.
312
341
  ...(newest && (!onDisk[cursorField] || onDisk[cursorField] < newest) ? { [cursorField]: newest } : {}),
313
342
  ...(nextMeasureState !== null ? { measure_state: nextMeasureState } : {}),
343
+ ...(!opts.dryRun ? { stalled_work_delivered: stalledNext } : {}),
314
344
  channel_read: { ...(onDisk.channel_read ?? {}), ...Object.fromEntries(moved) },
315
345
  ...(pending ? { pending_reads: pending } : {}),
316
346
  ...(noticeChanges ? { notice_state: noticeChanges.next } : {}),
317
347
  };
318
348
  });
319
349
  }
320
- if (!messages.length && !questions.length && !items.length && !digest.length && !followed.length && !noticeLines.length && !measureLines.length)
350
+ if (opts.dryRun && stalledRemoved.size)
351
+ updateState(name, (onDisk) => {
352
+ const delivered = { ...(onDisk.stalled_work_delivered ?? {}) };
353
+ for (const key of stalledRemoved)
354
+ delete delivered[key];
355
+ return { ...onDisk, stalled_work_delivered: delivered };
356
+ });
357
+ if (!messages.length && !questions.length && !items.length && !digest.length && !followed.length && !noticeLines.length && !measureLines.length && !stalledLines.length)
321
358
  return null;
322
359
  const lines = messages.map((m) => `${creds.project ? "" : `[${m.project}] `}${fmtMessage(m)}${m.reply_to_seq ? ` (reply to #${m.reply_to_seq})` : ""}`);
323
360
  const questionLines = questions.slice(0, 4).map((q) => ` ${q.project} #${q.channel} seq ${q.seq} from ${q.from} (${q.age_minutes} min ago): ${q.question} — ${q.next}`);
@@ -335,6 +372,7 @@ export async function gatherUpdates(name, opts) {
335
372
  followed.length ? `new messages in followed channels` : null,
336
373
  digest.length ? `unread channels` : null,
337
374
  noticeLines.length ? `${noticeLines.length} notice change${noticeLines.length === 1 ? "" : "s"}` : null,
375
+ stalledLines.length ? `${stalledLines.length} stalled work unit${stalledLines.length === 1 ? "" : "s"}` : null,
338
376
  measureLines.length ? `${measureLines.length} outcome measure change${measureLines.length === 1 ? "" : "s"}` : null,
339
377
  ].filter(Boolean).join(", ");
340
378
  const proj = creds.project ? "" : "--project <project> ";
@@ -359,7 +397,8 @@ export async function gatherUpdates(name, opts) {
359
397
  const directPointer = firstDeferred ? inboxPointer : "b9s inbox --unread";
360
398
  const itemPointer = firstItemDeferred ? inboxPointer : "b9s inbox --unread";
361
399
  const followedPointer = pendingReads.size ? "b9s read --pending" : readCommands.join("; ") || "b9s read --pending";
362
- const parts = { header, protectedDirect: [...(questionBlock ? [questionBlock] : []), ...protectedDirect, ...(noticeBlock ? [noticeBlock] : []), ...measureLines], direct: directLines, direct_ids: messages.flatMap((message) => message.role_name === "human" ? [] : [String(message.id)]), directPointer, itemPointer, followedPointer, digestPointer: digestCommands.length ? "b9s read --pending" : "b9s inbox --unread", items: itemLines, followed, digest, footer, readCommand: `b9s read <channel> --since <seq>`, budget };
400
+ const stalledBlock = stalledLines.length ? [`Your stalled work units; see their wait and next actor:`, ...stalledLines] : [];
401
+ const parts = { header, protectedDirect: [...(questionBlock ? [questionBlock] : []), ...protectedDirect, ...stalledBlock, ...(noticeBlock ? [noticeBlock] : []), ...measureLines], direct: directLines, direct_ids: messages.flatMap((message) => message.role_name === "human" ? [] : [String(message.id)]), directPointer, itemPointer, followedPointer, digestPointer: digestCommands.length ? "b9s read --pending" : "b9s inbox --unread", items: itemLines, followed, digest, footer, readCommand: `b9s read <channel> --since <seq>`, budget };
363
402
  const delivery = budgetDelivery(parts);
364
403
  const operator = messages.filter((m) => m.role_name === "human").map((m) => m.created_at).sort().pop() ?? null;
365
404
  const visibleReadCommands = readCommands.slice(0, 8);
@@ -368,7 +407,7 @@ export async function gatherUpdates(name, opts) {
368
407
  const cmds = [...(messages.length || questions.length || items.length ? ["b9s inbox --unread"] : []), ...visibleReadCommands];
369
408
  const escapedAgent = creds.agent.replace(/[-_]/g, "\\$&");
370
409
  const isDirectMessage = (message) => message.role_name === "human" || !!message.reply_to_seq || message.mentions?.includes(creds.agent) || new RegExp(`(^|[^\\w@])@${escapedAgent}(?![\\w-])`).test(message.body);
371
- const direct = questions.length > 0 || items.length > 0 || noticeLines.length > 0 || measureLines.length > 0 || messages.some(isDirectMessage);
410
+ const direct = questions.length > 0 || items.length > 0 || noticeLines.length > 0 || measureLines.length > 0 || stalledLines.length > 0 || messages.some(isDirectMessage);
372
411
  const tier = direct ? "direct" : messages.length ? "role" : followed.length ? "followed" : "digest";
373
412
  const turnBindingCandidates = tier === "direct" ? messages.map((message, index) => ({
374
413
  id: String(message.id),
@@ -386,7 +425,7 @@ export async function gatherUpdates(name, opts) {
386
425
  const firstDirectAt = directTimes.sort()[0] ?? null;
387
426
  const urgent = messages.some((message) => message.urgent === true || message.priority === "urgent")
388
427
  || items.some((item) => item.urgent === true || item.priority === "urgent");
389
- return { text: delivery.text, counts: { messages: messages.length, questions: questions.length, items: items.length, followed: followed.length, digest: digest.length, notices: noticeLines.length }, noticeLines, noticeNext, measureSnapshot: nextMeasureState ?? undefined, latestOperatorAt: operator, readCommands: cmds, tier, firstDirectAt, urgent, turn_binding_candidates: turnBindingCandidates, ...(opts.watchCursor && messages.length ? { watchCursorAfter: messages[messages.length - 1].created_at } : {}), delivery: { bytes: delivery.bytes, by_kind: delivery.by_kind }, parts };
428
+ return { text: delivery.text, counts: { messages: messages.length, questions: questions.length, items: items.length, followed: followed.length, digest: digest.length, notices: noticeLines.length }, noticeLines, noticeNext, stalledNext, measureSnapshot: nextMeasureState ?? undefined, latestOperatorAt: operator, readCommands: cmds, tier, firstDirectAt, urgent, turn_binding_candidates: turnBindingCandidates, ...(opts.watchCursor && messages.length ? { watchCursorAfter: messages[messages.length - 1].created_at } : {}), delivery: { bytes: delivery.bytes, by_kind: delivery.by_kind }, parts };
390
429
  }
391
430
  /** Command patterns warn without blocking; errors remain visible to the caller. */
392
431
  export async function commandWarnings(name, command) {
@@ -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;
@@ -417,7 +415,7 @@ export async function watch(p, out, dependencies = {}) {
417
415
  // record the same actual payload bytes and kinds through the hook's existing metric call.
418
416
  await reportDelivery(name, update.text, update.delivery.by_kind, "watch");
419
417
  if (delivered)
420
- updateState(name, (onDisk) => ({ ...onDisk, ...(update.noticeNext ? { notice_state: update.noticeNext } : {}), ...(update.measureSnapshot ? { measure_state: update.measureSnapshot } : {}) }));
418
+ updateState(name, (onDisk) => ({ ...onDisk, ...(update.stalledNext ? { stalled_work_delivered: update.stalledNext } : {}), ...(update.noticeNext ? { notice_state: update.noticeNext } : {}), ...(update.measureSnapshot ? { measure_state: update.measureSnapshot } : {}) }));
421
419
  resumeBriefDelivered = resumeBriefDelivered || recoveryBriefWasDelivered(recovery, delivered);
422
420
  if (stopping)
423
421
  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
  }
@@ -843,6 +903,7 @@ export async function wakeOnce(name, exec, unackedAfter, followDelay, log, model
843
903
  ...(processNews ? { watch_process_woken: lag.version } : {}),
844
904
  watch_pending: { seq, at: queuedAt, inbox_after: st.inbox_after, channel_read: st.channel_read ?? {} },
845
905
  watch_operator_at: u?.latestOperatorAt ?? st.watch_operator_at,
906
+ ...(u?.stalledNext ? { stalled_work_delivered: u.stalledNext } : {}),
846
907
  ...(u ? { notice_state: u.noticeNext } : {}),
847
908
  ...(u?.measureSnapshot ? { measure_state: u.measureSnapshot } : {}),
848
909
  watch_followed_since: undefined,
@@ -1152,6 +1213,10 @@ export async function turnStep(ctl, probe, timeoutMin, log, wake, name, turnsPer
1152
1213
  catch (e) {
1153
1214
  log(`Antigravity sandbox probe ref cleanup failed outside the session sandbox: ${e.message}`);
1154
1215
  }
1216
+ const tmpSessionKey = env.BSCHAT_ANTIGRAVITY_TMP_SESSION_KEY;
1217
+ if (tmpSessionKey && env.TMPDIR === antigravitySessionTmpDir(process.cwd(), name, tmpSessionKey)) {
1218
+ finishAntigravityScratchCleanup(process.cwd(), name, tmpSessionKey, log);
1219
+ }
1155
1220
  }
1156
1221
  ctl.turn = null;
1157
1222
  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";
@@ -583,7 +583,7 @@ export async function wu(p, out) {
583
583
  const reviewers = u.reviewers.map((r) => `${r.name}${r.tags.length ? ` for ${r.tags.map((t) => `#${t}`).join(" ")}` : ""}`).join(", ");
584
584
  const approvals = u.approvals.map((a) => a.name).join(", ");
585
585
  return [
586
- `WU #${u.number} [${u.status}] ${tags(u)} ${u.title}${flags ? ` (${flags})` : ""}${u.requires?.length ? `\n requires: ${u.requires.join(", ")}` : ""}`,
586
+ `WU #${u.number} [${u.status}]${u.stalled ? ` STALLED ${u.stalled.age_minutes}m · ${u.stalled.reason}` : ""} ${tags(u)} ${u.title}${flags ? ` (${flags})` : ""}${u.requires?.length ? `\n requires: ${u.requires.join(", ")}` : ""}`,
587
587
  u.candidate_record?.tags?.length ? ` ${u.candidate_record.agent} first-round approval: ${u.candidate_record.tags.map((x) => `#${x.tag} ${x.approved_first_round}/${x.units} (${Math.round(x.rate * 100)}%)`).join(", ")}` : null,
588
588
  ` owner ${u.owner_name || "unassigned (queued)"}${reviewers ? ` · reviewers ${reviewers}` : ""}${approvals ? ` · approved by ${approvals}` : ""}${u.uncovered?.length ? ` · awaiting ${u.uncovered.map((t) => `#${t}`).join(" ")}` : ""}`,
589
589
  Object.keys(u.tag_focus ?? {}).length ? ` review focus:\n${Object.entries(u.tag_focus).map(([tag, focus]) => ` #${tag}: ${focus}`).join("\n")}` : null,
@@ -826,7 +826,11 @@ export async function wu(p, out) {
826
826
  pushed = check.remoteBranch ? true : check.checked ? false : null;
827
827
  if (check.remoteBranch) {
828
828
  remoteCommitBranch = check.remoteBranch;
829
- where.branch = check.remoteBranch.replace(/^origin\//, "");
829
+ const containingBranch = check.remoteBranch.replace(/^origin\//, "");
830
+ where.branch = containingBranch;
831
+ if (submitUnit.owner_name === creds.agent && submitUnit.branch === localBranch && containingBranch === localBranch && where.head) {
832
+ await client.call("POST", `${base}/${num()}/activity`, { source: "branch_push", branch: localBranch, head: where.head });
833
+ }
830
834
  }
831
835
  else if (def.merge.require_pushed) {
832
836
  const message = formatRemoteCommitFailure(localBranch, check.checkedRef, check.reason ?? "no containing origin branch was found");
@@ -1160,6 +1164,20 @@ export async function wu(p, out) {
1160
1164
  out.print(fmt(r.unit), r);
1161
1165
  return;
1162
1166
  }
1167
+ case "head": {
1168
+ const sha = p.positionals[3];
1169
+ const reason = str(p.flags, "reason");
1170
+ if (!sha || !/^[0-9a-f]{40}$/.test(sha) || !reason?.trim())
1171
+ throw new CliError("usage", 'wu head <n> <full-40-character-lowercase-sha> --reason "why"');
1172
+ const number = num();
1173
+ const detail = await client.call("GET", `${base}/${number}/head-verification`);
1174
+ if (typeof detail.branch !== "string" || !detail.branch || typeof detail.repository_identity !== "string" || typeof detail.repository_url !== "string")
1175
+ throw new CliError("origin_verification_failed", `WU #${number} did not provide its branch and project repository identity`);
1176
+ const proof = verifyUnitHeadOnOrigin(detail.branch, sha, detail.repository_identity, detail.repository_url);
1177
+ const result = await client.call("POST", `${base}/${number}/head`, { sha, reason, ...proof });
1178
+ out.print(fmt(result.unit), result);
1179
+ return;
1180
+ }
1163
1181
  case "target": {
1164
1182
  // Move where the unit lands, before review. "default" restores the process target.
1165
1183
  const t = p.positionals[3];
@@ -1282,7 +1300,8 @@ export async function wu(p, out) {
1282
1300
  return;
1283
1301
  }
1284
1302
  case "show": {
1285
- const r = await client.call("GET", `${base}/${num()}`);
1303
+ const number = num();
1304
+ const r = await client.call("GET", `${base}/${number}`);
1286
1305
  const onlyScope = scopeOnlyOutput(r.unit, bool(p.flags, "scope-only"));
1287
1306
  if (onlyScope !== null) {
1288
1307
  out.print(onlyScope, { scope: onlyScope });
@@ -1307,12 +1326,21 @@ export async function wu(p, out) {
1307
1326
  if (str(p.flags, k))
1308
1327
  qs.set(k, str(p.flags, k));
1309
1328
  const r = await client.call("GET", `${base}${qs.size ? `?${qs}` : ""}`);
1310
- const rows = r.units.map((u) => ({ n: `#${u.number}`, status: u.status, tags: u.tags.map((t) => `#${t}`).join(" "), owner: u.owner_name, reviewers: u.reviewers.map((x) => x.name).join(",") || "-", awaiting: (u.uncovered ?? []).map((t) => `#${t}`).join(" ") || "-", base: u.lands_with ? `#${u.lands_with}` : "-", title: u.title.slice(0, 50) }));
1329
+ const rows = r.units.map((u) => ({ n: `#${u.number}`, status: u.stalled ? `STALLED ${u.stalled.age_minutes}m · ${u.stalled.reason} · ${u.status}` : u.status, tags: u.tags.map((t) => `#${t}`).join(" "), owner: u.owner_name, reviewers: u.reviewers.map((x) => x.name).join(",") || "-", awaiting: (u.uncovered ?? []).map((t) => `#${t}`).join(" ") || "-", base: u.lands_with ? `#${u.lands_with}` : "-", title: u.title.slice(0, 50) }));
1311
1330
  out.print(rows.length ? table(rows, ["n", "status", "tags", "owner", "reviewers", "awaiting", "base", "title"]) : "(no open work units; b9s wu list --all for closed ones)", r);
1312
1331
  return;
1313
1332
  }
1333
+ case "stalled": {
1334
+ const response = await client.call("GET", `${base}?all=1`);
1335
+ const units = response.units.filter((unit) => unit.stalled);
1336
+ const rows = units.map((unit) => ({ n: `#${unit.number}`, age: `${unit.stalled.age_minutes} min`, status: unit.status, owner: unit.owner_name || "unassigned", reason: unit.stalled.reason, title: unit.title }));
1337
+ out.print(rows.length ? table(rows, ["n", "age", "status", "owner", "reason", "title"]) : "(no stalled work units)", { project, units });
1338
+ if (rows.length)
1339
+ process.exitCode = 1;
1340
+ return;
1341
+ }
1314
1342
  default:
1315
- throw new CliError("usage", "wu open|assign|lands-with|start [--branch b|--here]|decline|submit|approve|changes|classify|tags|merge <n>|merge status <n>|done [--keep-worktree]|abandon|note|ask|rule|propose|show|list");
1343
+ throw new CliError("usage", "wu open|assign|lands-with|start [--branch b|--here]|decline|submit|approve|changes|classify|tags|merge <n>|merge status <n>|done [--keep-worktree]|abandon|note|ask|rule|propose|show|list|stalled");
1316
1344
  }
1317
1345
  }
1318
1346
  /** Queued units have no owner; ask the API to reject before any local worktree is made. */
@@ -1416,6 +1444,29 @@ function assertNotShaBranch(branch, flag = "--branch") {
1416
1444
  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
1445
  }
1418
1446
  }
1447
+ export function divergentUnitHeadMessage(n, recordedHead, branch, branchHead, cwd = process.cwd()) {
1448
+ const subject = spawnSync("git", ["show", "-s", "--format=%s", recordedHead], { cwd, encoding: "utf8" });
1449
+ const history = spawnSync("git", ["log", "-n", "2000", "--format=%H%x09%s", branchHead, "--"], { cwd, encoding: "utf8", maxBuffer: 4 * 1024 * 1024 });
1450
+ let match;
1451
+ if (subject.status !== 0 || history.status !== 0 || !subject.stdout.trim())
1452
+ match = "Matching commit subject could not be checked.";
1453
+ else {
1454
+ const found = history.stdout.split(/\r?\n/).map((line) => line.split("\t", 2)).find(([sha, title]) => sha !== recordedHead && title === subject.stdout.trim());
1455
+ 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.";
1456
+ }
1457
+ 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"`;
1458
+ }
1459
+ export class UnitWorktreeDiverged extends CliError {
1460
+ recordedHead;
1461
+ branch;
1462
+ branchHead;
1463
+ constructor(recordedHead, branch, branchHead, message) {
1464
+ super("unit_worktree_diverged", message);
1465
+ this.recordedHead = recordedHead;
1466
+ this.branch = branch;
1467
+ this.branchHead = branchHead;
1468
+ }
1469
+ }
1419
1470
  export function prepareWorktreeForWatcher(n, unit, def, exclude = []) {
1420
1471
  if (unit.branch && isShaBranchName(unit.branch))
1421
1472
  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 +1506,8 @@ export function prepareWorktreeForWatcher(n, unit, def, exclude = []) {
1455
1506
  const recoveryRequired = homeCheckoutRecorded || recordedWorktreeMissing || startedUnitWithoutRecordedWorktree || adoptedExistingWorktree;
1456
1507
  const recordedHead = recoveryRequired && typeof unit.head === "string" ? fullSha(unit.head) : null;
1457
1508
  const recordedBranchTip = recoveryRequired && typeof unit.branch === "string" && !isShaBranchName(unit.branch) ? fullSha(`refs/heads/${unit.branch}`) : null;
1509
+ if (recoveryRequired && unit.head && !recordedHead)
1510
+ throw new CliError("unit_worktree_prepare_failed", `recorded head ${unit.head} is unavailable in this checkout; fetch it before preparing WU #${n}`);
1458
1511
  let recoveryBase = recordedHead ?? recordedBranchTip;
1459
1512
  if (recordedHead && recordedBranchTip) {
1460
1513
  const headIsOnBranch = isAncestor(recordedHead, recordedBranchTip, home);
@@ -1462,7 +1515,7 @@ export function prepareWorktreeForWatcher(n, unit, def, exclude = []) {
1462
1515
  if (headIsOnBranch === true)
1463
1516
  recoveryBase = recordedBranchTip;
1464
1517
  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}`);
1518
+ throw new UnitWorktreeDiverged(recordedHead, unit.branch, recordedBranchTip, divergentUnitHeadMessage(n, recordedHead, unit.branch, recordedBranchTip, home));
1466
1519
  }
1467
1520
  }
1468
1521
  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
@@ -198,6 +199,7 @@ Machine placement enforces configured session slots and reports machine pressure
198
199
  b9s wu recovery restore <n> next owner: verify and restore the restricted recovery bundle into the unit worktree
199
200
  b9s wu abandon <n> [--note ..] wu list [--all] [--json] for state and timeline (JSON keeps complete titles)
200
201
  b9s wu list [--all] [--status s] [--tag t] [--agent name] list visible work units; --all includes closed units
202
+ b9s wu stalled list stalled units with age and reason; exits 1 when any are stalled
201
203
  b9s worktrees prune [--yes] [--archive] remove clean, fully pushed worktrees whose work landed or whose unit is closed (dry run without --yes);
202
204
  --archive also saves a closed unit's uncommitted files to archive/wu<n>-leftovers and removes it;
203
205
  refused in Antigravity workspace-write: watcher processes queued wu done worktrees at turn finalization; prune retained or abandoned worktrees from an unrestricted checkout
@@ -404,6 +406,7 @@ Use --admin <nickname> to select one of this machine's saved operator identities
404
406
  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
407
  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
408
  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
409
+ b9s-admin wu head <project> <n> <full-sha> --reason "why" operator: record a commit verified on the unit's branch
407
410
  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
411
  b9s-admin routing show <project> [--mode build|review] [--tag <tag>] inspect confidence matrix, exploration spend, and recent decisions
409
412
  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.146";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "benignswarm",
3
- "version": "0.12.144",
3
+ "version": "0.12.146",
4
4
  "description": "b9s: chat, status board and evidence store for coding agents (benignswarm.org)",
5
5
  "license": "UNLICENSED",
6
6
  "repository": {