benignswarm 0.12.158 → 0.12.160

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/args.js CHANGED
@@ -46,7 +46,7 @@ export const BOOL_FLAGS = [
46
46
  "all", "here", "keep-worktree", "prune", "abandon", "defer", "hold", "clear", "met", "shared", "archive",
47
47
  "approve", "turn", "service", "print-hooks", "create", "rotate", "drain", "codex-userns", "bwrap-userns", "agy-userns", "print-apparmor", "overdue",
48
48
  "cancel", "rerun", "confirmed", "refuted", "no-source", "confirm-bypass-signal", "assessment-only", "continue",
49
- "no-wait-verify", "preview", "remove-empty", "dry-run", "quota-substitution",
49
+ "no-wait-verify", "preview", "remove-empty", "dry-run", "quota-substitution", "auto-merge",
50
50
  "in-container", "retrieve-ec2", "stdin", "context-confirmed", "confirm-compatible", "move-provisioned", "provisioned", "no-commits-beyond-target", "train",
51
51
  ];
52
52
  export function parse(argv) {
@@ -1,3 +1,4 @@
1
+ import { evidenceTextHeaders } from "../evidence-text.js";
1
2
  import { createHash } from "node:crypto";
2
3
  import { readFileSync, writeFileSync } from "node:fs";
3
4
  import { basename, extname } from "node:path";
@@ -56,17 +57,13 @@ export async function evidence(p, out) {
56
57
  const filename = str(p.flags, "name") ?? basename(file);
57
58
  const contentType = str(p.flags, "type") ?? guessType(filename);
58
59
  const headers = { ...client.headers(), "content-type": contentType, "x-bschat-sha256": sha, "x-bschat-filename": filename };
59
- // Fetch normalizes leading/trailing whitespace in HTTP header values; model those exact
60
- // transmitted bytes here so the receipt verifies what the server actually received.
60
+ // Trim as before; encode UTF-8 metadata into ASCII-safe header values.
61
61
  const label = str(p.flags, "label")?.trim();
62
- if (label)
63
- headers["x-bschat-label"] = label;
64
62
  const kind = str(p.flags, "kind");
65
63
  if (kind)
66
64
  headers["x-bschat-kind"] = kind;
67
65
  const claim = str(p.flags, "claim")?.trim();
68
- if (claim)
69
- headers["x-bschat-claim"] = claim;
66
+ Object.assign(headers, await evidenceTextHeaders(client, project, { label, claim }));
70
67
  const res = await fetch(`${creds.url}/projects/${project}/evidence`, { method: "POST", headers, body: new Uint8Array(bytes) });
71
68
  const responseText = await res.text();
72
69
  let json;
@@ -35,8 +35,13 @@ function signalTree(signal) {
35
35
  return { state: "unknown", reason: result.error.message };
36
36
  return result.status === 0 ? { state: "running", descendants: [] } : { state: "gone" };
37
37
  }
38
+ const commandPid = task.pid;
39
+ if (!commandPid)
40
+ return { state: "gone" };
41
+ // The detached command is its own process-group leader. Registering this PID
42
+ // lets a later lock holder probe and signal the exact group if we die.
38
43
  try {
39
- process.kill(-task.pid, signal);
44
+ process.kill(-commandPid, signal);
40
45
  }
41
46
  catch (error) {
42
47
  if (error.code === "ESRCH")
@@ -68,6 +73,10 @@ function stopTree(signal = "SIGTERM") {
68
73
  if (stopping)
69
74
  return;
70
75
  stopping = true;
76
+ if (!task?.pid) {
77
+ finish(130);
78
+ return { state: "gone" };
79
+ }
71
80
  const result = signalTree(signal);
72
81
  if (result.state === "unknown") {
73
82
  reportUnknown(result.reason);
@@ -93,6 +102,7 @@ control.on("end", () => stopTree());
93
102
  control.on("close", () => stopTree());
94
103
  control.resume();
95
104
  function finish(exitCode, startFailure) {
105
+ stopping = true;
96
106
  if (killTimer)
97
107
  clearTimeout(killTimer);
98
108
  control.destroy();
@@ -103,12 +113,11 @@ function finish(exitCode, startFailure) {
103
113
  process.kill(process.pid, "SIGKILL");
104
114
  });
105
115
  }
106
- if (!Array.isArray(command) || typeof command[0] !== "string" || command.length === 0) {
107
- send({ type: "spawn_error", message: "missing command" });
108
- finish(127, "missing command");
109
- }
110
- else {
111
- task = spawn(command[0], command.slice(1), {
116
+ function startTask() {
117
+ if (task || stopping)
118
+ return;
119
+ const argv = command;
120
+ task = spawn(argv[0], argv.slice(1), {
112
121
  stdio: ["inherit", "pipe", "pipe"],
113
122
  detached: process.platform !== "win32",
114
123
  });
@@ -116,7 +125,7 @@ else {
116
125
  task.stderr?.pipe(process.stderr);
117
126
  task.once("error", (error) => { spawnError = error; taskExitCode = 127; });
118
127
  task.once("exit", (code, signal) => {
119
- // Stop any detached descendants that remain in the command's process group.
128
+ // Stop any descendants that remain in the shared command process group.
120
129
  const state = groupState(task?.pid);
121
130
  if (state.state === "running")
122
131
  stopTree();
@@ -127,24 +136,28 @@ else {
127
136
  send({ type: "spawn_error", message: spawnError.message });
128
137
  });
129
138
  task.once("close", async () => {
130
- const pid = task?.pid;
131
- let state = groupState(pid);
139
+ const commandPid = task?.pid;
140
+ if (!commandPid) {
141
+ finish(taskExitCode ?? 1, spawnError?.message);
142
+ return;
143
+ }
144
+ let state = groupState(commandPid);
132
145
  if (state.state === "unknown") {
133
146
  reportRetained(state);
134
147
  return;
135
148
  }
136
- if (pid && process.platform !== "win32" && state.state === "running") {
149
+ if (state.state === "running") {
137
150
  const stopped = stopTree();
138
151
  if (stopped?.state === "unknown")
139
152
  return;
140
- state = await waitForGroupGone(pid, 5_000);
153
+ state = await waitForGroupGone(commandPid, 5_000);
141
154
  if (state.state === "running") {
142
155
  const killed = signalTree("SIGKILL");
143
156
  if (killed.state === "unknown") {
144
157
  reportUnknown(killed.reason);
145
158
  return;
146
159
  }
147
- state = await waitForGroupGone(pid, 5_000);
160
+ state = await waitForGroupGone(commandPid, 5_000);
148
161
  }
149
162
  if (state.state !== "gone") {
150
163
  reportRetained(state);
@@ -154,3 +167,14 @@ else {
154
167
  finish(taskExitCode ?? (spawnError ? 127 : 1), spawnError?.message);
155
168
  });
156
169
  }
170
+ if (!Array.isArray(command) || typeof command[0] !== "string" || command.length === 0) {
171
+ send({ type: "spawn_error", message: "missing command" });
172
+ finish(127, "missing command");
173
+ }
174
+ else {
175
+ // Report the actual process-group leader; never report the supervising
176
+ // process, which is not part of the command's detached group.
177
+ startTask();
178
+ if (task?.pid)
179
+ send({ type: "ready", command_pid: task.pid });
180
+ }
@@ -2,8 +2,26 @@ import { spawn } from "node:child_process";
2
2
  import { constants } from "node:os";
3
3
  import { fileURLToPath } from "node:url";
4
4
  import { CliError } from "../errors.js";
5
+ import { createLockHeartbeatReporter } from "../lock-heartbeat.js";
5
6
  import { forgetLockJob, rememberLockJob } from "../lock-jobs.js";
6
7
  import { redactProcessCommand } from "../machine-processes.js";
8
+ function processIsRunning(pid) {
9
+ // command_pid identifies the leader of the command's private process group.
10
+ // Checking the group (rather than just the shell PID) also catches a gate whose
11
+ // shell exited while a child process is still running.
12
+ const target = process.platform === "win32" ? pid : -pid;
13
+ try {
14
+ process.kill(target, 0);
15
+ return true;
16
+ }
17
+ catch (error) {
18
+ if (error.code === "ESRCH")
19
+ return false;
20
+ if (error.code === "EPERM")
21
+ return true;
22
+ throw error;
23
+ }
24
+ }
7
25
  /**
8
26
  * How many times a lock-run call is repeated after a network failure or a 5xx. Every call carries
9
27
  * the job's token, so a repeat is the same request. A release that failed once during a database
@@ -94,16 +112,26 @@ export async function runUnderLock(o, deps) {
94
112
  throw new CliError("lock_release_failed", `job ${o.jobId} could not release ${o.lock} (${error instanceof Error ? error.message : String(error)})`, `Release it: ${unlockCommand(o)}`);
95
113
  }
96
114
  };
97
- let r = await deps.call("POST", `${base}/acquire`, acquireBody);
115
+ let r = await deps.call("POST", `${base}/acquire`, { ...acquireBody });
98
116
  if (r.job_token !== o.token)
99
117
  throw new CliError("lock_protocol_mismatch", "The server did not confirm job ownership; the command was not started. Inspect the lock state: b9s locks");
100
118
  rememberLockJob(o.jobsFile, o.jobsKey, { job: o.jobId, token: o.token, at: new Date(now()).toISOString() });
101
119
  let said = "";
102
120
  while (!r.acquired) {
121
+ let staleProcessAlive;
122
+ if (Number.isSafeInteger(r.stale_holder_process_pid) && r.stale_holder_process_pid > 0) {
123
+ const stalePid = r.stale_holder_process_pid;
124
+ staleProcessAlive = deps.isProcessRunning ? deps.isProcessRunning(stalePid) : processIsRunning(stalePid);
125
+ if (staleProcessAlive)
126
+ delete acquireBody.stopped_process_pid;
127
+ else
128
+ acquireBody.stopped_process_pid = stalePid;
129
+ }
103
130
  const state = r.maintenance ? `not handed out now: ${r.maintenance}` : `held by ${r.lock.holder_name ?? "nobody"}${r.lock.unit ? ` (WU #${r.lock.unit})` : ""}; job ${o.jobId} is #${r.position} in line`;
104
- if (state !== said) {
105
- deps.log(`${o.lock}: ${state}. Waiting.`);
106
- said = state;
131
+ const previousProcess = staleProcessAlive === undefined ? "" : `; previous command PID ${r.stale_holder_process_pid} ${staleProcessAlive ? "is still running" : "has exited"}`;
132
+ if (state + previousProcess !== said) {
133
+ deps.log(`${o.lock}: ${state}${previousProcess}. Waiting.`);
134
+ said = state + previousProcess;
107
135
  }
108
136
  await deps.sleep(o.pollMs ?? 15_000);
109
137
  if (deps.interrupted()) {
@@ -111,7 +139,7 @@ export async function runUnderLock(o, deps) {
111
139
  deps.log(`${o.lock}: interrupted while waiting; left the queue. The command was not run.`);
112
140
  return 130;
113
141
  }
114
- r = await deps.call("POST", `${base}/acquire`, acquireBody);
142
+ r = await deps.call("POST", `${base}/acquire`, { ...acquireBody });
115
143
  }
116
144
  const startedMs = now();
117
145
  const slot = Number.isInteger(r.slot) ? Number(r.slot) : undefined;
@@ -135,7 +163,7 @@ export async function runUnderLock(o, deps) {
135
163
  const timer = setInterval(flush, Math.min(30000, Math.max(250, seconds * 1000 / 4)));
136
164
  let result;
137
165
  try {
138
- result = await deps.run(o.command, { lock: o.lock, jobId: o.jobId, ...(slot === undefined ? {} : { slot }), heartbeat: () => deps.call("POST", `${base}/running`, { shared: o.shared, machine: o.machine, job_token: o.token, command: label, process_pid: process.pid, silence_seconds: seconds }), reportFault: (fault) => deps.call("POST", `${base}/running`, { shared: o.shared, machine: o.machine, job_token: o.token, command: label, process_pid: process.pid, silence_seconds: seconds, fault }), onOutput: line => { latest = redactProcessCommand(line).replace(/\bb9sjob_[A-Za-z0-9]{32,80}\b/g, '[redacted]').replace(/\b(Bearer\s+)[A-Za-z0-9._~+\/-]+=*/gi, '$1[redacted]').replace(/[\x00-\x1f\x7f]/g, ' ').slice(0, 200); } });
166
+ result = await deps.run(o.command, { lock: o.lock, jobId: o.jobId, ...(slot === undefined ? {} : { slot }), heartbeat: (commandPid) => deps.call("POST", `${base}/running`, { shared: o.shared, machine: o.machine, job_token: o.token, command: label, process_pid: process.pid, ...(commandPid === undefined ? {} : { command_pid: commandPid }), silence_seconds: seconds }), reportFault: (fault) => deps.call("POST", `${base}/running`, { shared: o.shared, machine: o.machine, job_token: o.token, command: label, process_pid: process.pid, silence_seconds: seconds, fault }), onOutput: line => { latest = redactProcessCommand(line).replace(/\bb9sjob_[A-Za-z0-9]{32,80}\b/g, '[redacted]').replace(/\b(Bearer\s+)[A-Za-z0-9._~+\/-]+=*/gi, '$1[redacted]').replace(/[\x00-\x1f\x7f]/g, ' ').slice(0, 200); } });
139
167
  }
140
168
  finally {
141
169
  clearInterval(timer);
@@ -150,8 +178,17 @@ export async function runUnderLock(o, deps) {
150
178
  }
151
179
  }
152
180
  catch (error) {
153
- if (!error || !(error instanceof CliError) || error.code !== "lock_release_failed")
154
- await release();
181
+ if (!error || !(error instanceof CliError) || error.code !== "lock_release_failed") {
182
+ try {
183
+ await release();
184
+ }
185
+ catch (releaseError) {
186
+ // Preserve the reason the command stopped when the lock already moved to
187
+ // another holder; reporting that as a release failure hides a lost lease.
188
+ if (!(error instanceof CliError && ["lock_heartbeat_failed", "lock_lease_lost"].includes(error.code)))
189
+ throw releaseError;
190
+ }
191
+ }
155
192
  throw error;
156
193
  }
157
194
  deps.log(`${o.lock}${slot === undefined ? "" : ` slot ${slot}`} released after ${Math.round((now() - startedMs) / 1000)} s; the command exited ${code}.`);
@@ -232,10 +269,10 @@ export function processDeps(call, log, heartbeatIntervalMs = 15_000) {
232
269
  // A lock-run process can be SIGKILLed, so it cannot rely on its own signal
233
270
  // handlers to stop the command. Keep the command under a small supervisor
234
271
  // and give it a private pipe whose EOF means its lock owner disappeared.
235
- // The command runs in a separate process group so the supervisor can stop
236
- // Wrangler/Vite/browser descendants before the lease expires and is reused.
272
+ // The command owns a detached process group distinct from the supervisor.
273
+ // Its group leader PID is registered with the lock while the task starts.
237
274
  const supervisor = fileURLToPath(new URL("../../dist/commands/lock-run-supervisor.js", import.meta.url));
238
- const child = spawn(process.execPath, [supervisor, JSON.stringify(command)], { stdio: ["inherit", "pipe", "pipe", "pipe", "pipe"], env });
275
+ const child = spawn(process.execPath, [supervisor, JSON.stringify(command)], { stdio: ["inherit", "pipe", "pipe", "pipe", "pipe"], env, detached: process.platform !== "win32" });
239
276
  const supervisorControl = child.stdio[3];
240
277
  child.once("exit", () => { supervisorControl?.end(); });
241
278
  child.once("error", () => { supervisorControl?.end(); });
@@ -308,6 +345,37 @@ export function processDeps(call, log, heartbeatIntervalMs = 15_000) {
308
345
  const statusReader = createSupervisorRecordReader((message) => {
309
346
  if (message.type === "spawn_error")
310
347
  commandStartFailure = message.message ?? "unknown spawn error";
348
+ if (message.type === "ready") {
349
+ if (!Number.isSafeInteger(message.command_pid) || message.command_pid < 1) {
350
+ commandStartFailure = "supervisor did not report a valid command process-group leader";
351
+ child.kill("SIGTERM");
352
+ }
353
+ else {
354
+ const commandPid = message.command_pid;
355
+ if (context?.heartbeat) {
356
+ const reportHeartbeat = createLockHeartbeatReporter(context.heartbeat, {
357
+ onRetry: (error, delayMs) => log(`job ${context.jobId} lock heartbeat failed transiently; retrying in ${delayMs}ms: ${error instanceof Error ? error.message : String(error)}`),
358
+ });
359
+ const refresh = () => {
360
+ if (heartbeatInFlight)
361
+ return;
362
+ heartbeatInFlight = reportHeartbeat(commandPid).then(() => {
363
+ if (!childClosed && commandExitCode === undefined && !heartbeatTimer) {
364
+ heartbeatTimer = setInterval(refresh, heartbeatIntervalMs);
365
+ heartbeatTimer.unref?.();
366
+ }
367
+ }, (error) => {
368
+ heartbeatFailure = error;
369
+ stopHeartbeat();
370
+ log(`job ${context.jobId} could not renew its lock lease; stopping the command: ${error instanceof Error ? error.message : String(error)}`);
371
+ if (!childClosed)
372
+ child.kill("SIGTERM");
373
+ }).finally(() => { heartbeatInFlight = undefined; });
374
+ };
375
+ refresh();
376
+ }
377
+ }
378
+ }
311
379
  if (message.type === "descendants_unknown" || message.type === "descendants_remain") {
312
380
  if (context?.reportFault)
313
381
  void reportSupervisorFault(message, context.jobId, context.reportFault, log);
@@ -323,20 +391,6 @@ export function processDeps(call, log, heartbeatIntervalMs = 15_000) {
323
391
  child.stdio[4]?.on("data", (chunk) => statusReader.push(chunk.toString("utf8")));
324
392
  child.stdio[4]?.on("end", () => statusReader.end());
325
393
  forward = (signal) => { child.kill(signal); };
326
- if (context?.heartbeat) {
327
- heartbeatTimer = setInterval(() => {
328
- if (heartbeatInFlight)
329
- return;
330
- heartbeatInFlight = context.heartbeat().then(() => undefined, (error) => {
331
- heartbeatFailure = error;
332
- stopHeartbeat();
333
- log(`job ${context.jobId} could not refresh its lock heartbeat; stopping the command to avoid running without the lock`);
334
- if (!childClosed)
335
- child.kill("SIGTERM");
336
- }).finally(() => { heartbeatInFlight = undefined; });
337
- }, heartbeatIntervalMs);
338
- heartbeatTimer.unref?.();
339
- }
340
394
  child.once("error", (error) => { childClosed = true; stopHeartbeat(); forward = undefined; reject(new CliError("command_not_started", `could not start ${command[0]}: ${error.message}`)); });
341
395
  // `close` follows stdout's `end`, so the final marker lines have been
342
396
  // consumed before we construct the receipt sent with the lock release.
@@ -346,7 +400,8 @@ export function processDeps(call, log, heartbeatIntervalMs = 15_000) {
346
400
  await heartbeatInFlight;
347
401
  forward = undefined;
348
402
  if (heartbeatFailure) {
349
- reject(new CliError("lock_heartbeat_failed", `job ${context?.jobId ?? "unknown"} stopped because its lock heartbeat failed: ${heartbeatFailure instanceof Error ? heartbeatFailure.message : String(heartbeatFailure)}`));
403
+ const code = heartbeatFailure instanceof CliError && heartbeatFailure.code === "lock_lease_lost" ? "lock_lease_lost" : "lock_heartbeat_failed";
404
+ reject(new CliError(code, `job ${context?.jobId ?? "unknown"} stopped because its lock lease could not be renewed: ${heartbeatFailure instanceof Error ? heartbeatFailure.message : String(heartbeatFailure)}`));
350
405
  return;
351
406
  }
352
407
  if (commandStartFailure) {
@@ -12,6 +12,7 @@ import { agentRef, configRoot, loadAgent, resolveAgentName, saveAgent } from "..
12
12
  import { CliError } from "../errors.js";
13
13
  import { AGY_APPARMOR_PATH, agyAppArmorProfile, BWRAP_APPARMOR_PATH, bwrapAppArmorProfile, CODEX_APPARMOR_PATH, CODEX_MANAGED_DIR, codexAppArmorProfile, codexManagedHooks, isCodexManagedRequirements } from "../harness.js";
14
14
  import { applySparse, sessionCheckoutFacts } from "../git.js";
15
+ import { retryGitFetch, retryGitFetchSync } from "../git-fetch.js";
15
16
  import { drainingUntil, writeMaintenance } from "../maintenance.js";
16
17
  import { TURN_HARNESSES, cachedClaudeEgressVerification, cachedClaudeLogin, claudeCodePath, claudeFacts, claudeHome, claudeSandbox, claudeSandboxCacheIdentity, claudeSecretEgressCapability, dshFacts, dshProcesses, inspectCurrentClaudeEgressCapability, probeFor, queueClaudeEgressProbe, sessionProcesses, shouldQueueClaudeEgressProbe, terminateClaudeSessionProcesses } from "../harnesses.js";
17
18
  import { clearSessionSecrets, SECRET_DECLARED_HOSTS_VAR, SECRET_EGRESS_ENV_KEYS_VAR, } from "../session-secrets.js";
@@ -324,7 +325,10 @@ export async function reconcilePendingImageBuilds(client, projects, opts) {
324
325
  }
325
326
  let hasCommit = runner("git", ["-C", baseDir, "cat-file", "-e", `${requestedCommit}^{commit}`], { env, timeout: 15_000 });
326
327
  if (hasCommit.status !== 0 && project.repo_url) {
327
- runner("git", ["-C", baseDir, "fetch", "--no-tags", "origin", requestedCommit], { env, timeout: 120_000 });
328
+ await retryGitFetch(async () => {
329
+ const fetched = runner("git", ["-C", baseDir, "fetch", "--no-tags", "origin", requestedCommit], { env, timeout: 120_000 });
330
+ return { ...fetched, stdout: fetched.stdout ?? "", stderr: fetched.stderr ?? "" };
331
+ }, `fetch commit ${requestedCommit}`);
328
332
  hasCommit = runner("git", ["-C", baseDir, "cat-file", "-e", `${requestedCommit}^{commit}`], { env, timeout: 15_000 });
329
333
  }
330
334
  if (hasCommit.status !== 0) {
@@ -2179,7 +2183,9 @@ export function ensureCheckout(s, log, workdir = null) {
2179
2183
  }
2180
2184
  const dir = join(root, s.agent_name);
2181
2185
  if (!existsSync(dir)) {
2182
- const f = git(["fetch", "origin"], base);
2186
+ const remoteHead = (git(["symbolic-ref", "--short", "refs/remotes/origin/HEAD"], base).stdout ?? "").trim();
2187
+ const defaultBranch = remoteHead.startsWith("origin/") ? remoteHead.slice("origin/".length) : "main";
2188
+ const f = retryGitFetchSync(["fetch", "--no-tags", "origin", `+refs/heads/${defaultBranch}:refs/remotes/origin/${defaultBranch}`], base);
2183
2189
  if (f.status !== 0)
2184
2190
  throw new Error(`git fetch in ${base} failed: ${(f.stderr ?? "").trim().slice(-300)}`);
2185
2191
  const head = (git(["symbolic-ref", "--short", "refs/remotes/origin/HEAD"], base).stdout ?? "").trim() || "origin/main";
@@ -2226,7 +2232,7 @@ export function refreshClones(workdir, projects, log) {
2226
2232
  if (!existsSync(join(base, ".git")))
2227
2233
  continue;
2228
2234
  const branch = (git(["rev-parse", "--abbrev-ref", "HEAD"], base).stdout ?? "").trim();
2229
- if (git(["fetch", "-q", "origin"], base).status !== 0) {
2235
+ if (!branch || branch === "HEAD" || retryGitFetchSync(["fetch", "-q", "--no-tags", "origin", `+refs/heads/${branch}:refs/remotes/origin/${branch}`], base).status !== 0) {
2230
2236
  out[p] = { branch, behind: -1, note: "fetch failed" };
2231
2237
  continue;
2232
2238
  }
@@ -1,3 +1,4 @@
1
+ import { evidenceTextHeaders } from "../evidence-text.js";
1
2
  import { createHash, randomUUID } from "node:crypto";
2
3
  import { existsSync, realpathSync } from "node:fs";
3
4
  import { spawnSync } from "node:child_process";
@@ -178,7 +179,7 @@ export function parseProducerOutput(stdout, kind) {
178
179
  }
179
180
  async function postBranchEvidence(client, url, project, name, text, version) {
180
181
  const bytes = Buffer.from(text, "utf8"), sha = createHash("sha256").update(bytes).digest("hex");
181
- const headers = { ...client.headers(), "content-type": "text/plain; charset=utf-8", "x-bschat-sha256": sha, "x-bschat-filename": `${name}-branch-check.txt`, "x-bschat-kind": "test", "x-bschat-label": `branch check ${name} producer ${version}` };
182
+ const headers = { ...client.headers(), "content-type": "text/plain; charset=utf-8", "x-bschat-sha256": sha, "x-bschat-filename": `${name}-branch-check.txt`, "x-bschat-kind": "test", ...await evidenceTextHeaders(client, project, { label: `branch check ${name} producer ${version}` }) };
182
183
  const response = await fetch(`${url}/projects/${project}/evidence`, { method: "POST", headers, body: new Uint8Array(bytes) });
183
184
  const json = await response.json();
184
185
  if (!response.ok)
@@ -177,16 +177,13 @@ export async function gate(p, out) {
177
177
  const unitText = p.positionals[2]?.trim();
178
178
  const unitNumber = unitText ? Number(unitText) : NaN;
179
179
  if (!Number.isSafeInteger(unitNumber) || unitNumber < 1) {
180
- throw new CliError("usage", "b9s gate run <n> [--merge-candidate <sha>] --on <machine> | b9s gate run --train [--target <branch>] [--on <machine>]");
180
+ throw new CliError("usage", "b9s gate run <n> [--merge-candidate <sha>] [--on <machine>] | b9s gate run --train [--target <branch>] [--on <machine>]");
181
181
  }
182
182
  const machine = str(p.flags, "on")?.trim();
183
- if (!machine) {
184
- throw new CliError("usage", "b9s gate run <n> [--merge-candidate <sha>] --on <machine> (--on is required)");
185
- }
186
183
  const candidate = str(p.flags, "merge-candidate")?.trim() || undefined;
187
184
  const res = await client.call("POST", `/projects/${project}/gate-jobs`, {
188
185
  unit: unitNumber,
189
- machine,
186
+ ...(machine ? { machine } : {}),
190
187
  ...(candidate ? { merge_candidate: candidate } : {}),
191
188
  });
192
189
  const job = res.job;
@@ -22,6 +22,16 @@ import { formatStandingRuleSet } from "../standing-rules.js";
22
22
  import { projectOf } from "./agent.js";
23
23
  import { consoleLink } from "../console-links.js";
24
24
  import { isAntigravityWorkspaceWrite } from "../antigravity.js";
25
+ import { retryGitFetchSync } from "../git-fetch.js";
26
+ import { detectVendor } from "../vendor.js";
27
+ /** WU #858: an Antigravity turn's sandbox is fixed when the turn starts. The watcher grants a unit's prepared
28
+ * worktree to every later turn (watch.ts), but a worktree created mid-turn by `wu start` is not writable until
29
+ * then, so the agent is told to end the turn instead of failing to commit or submit there. */
30
+ export function midTurnWorktreeNote(vendor, mode) {
31
+ if (vendor !== "antigravity" || mode === "here")
32
+ return "";
33
+ return "\nAntigravity: this turn's sandbox was set before this worktree existed, so you cannot write in it yet. End this turn now; your next turn starts with the worktree writable.";
34
+ }
25
35
  const waitAge = (minutes) => minutes < 60 ? `${minutes}m` : minutes < 24 * 60 ? `${Math.floor(minutes / 60)}h` : `${Math.floor(minutes / (24 * 60))}d`;
26
36
  /** Only Claude's workspace-write sandbox needs SSH origins rewritten for its HTTP-only proxy. */
27
37
  export function shouldInheritClaudeSandboxUrlRewrites(env = process.env) {
@@ -502,6 +512,7 @@ function waitActionResult(unit, on, clear) {
502
512
  * b9s wu classify <n> --tags a,b [--note ...] classifier role only, when the process has that step
503
513
  * b9s wu tags <n> --add a,b --remove c [--note ...] owner before review, a reviewer during it
504
514
  * b9s wu done <n> --merged <sha> after approval; the sha is checked against the target branch
515
+ * b9s wu pr <n> [--auto-merge] open or reuse a PR for the unit branch through the linked GitHub App
505
516
  * b9s wu merge <n> [--note "..."] request the role-checked hosted merge; API only, no local Git state
506
517
  * b9s wu merge status <n> read hosted merge operation and audit status
507
518
  * b9s wu abandon <n> [--note ...]
@@ -527,10 +538,10 @@ export function parseEvidenceReplacement(positionals) {
527
538
  }
528
539
  /** Changed paths are calculated from the fetched target's merge-base; a configured rule may not silently skip an unknown target. */
529
540
  export function changedPathsAgainstTarget(target, cwd = process.cwd()) {
530
- const fetched = spawnSync("git", ["fetch", "--quiet", "origin", target], { cwd, encoding: "utf8", timeout: 120_000 });
541
+ const fetched = retryGitFetchSync(["fetch", "--quiet", "origin", `+refs/heads/${target}:refs/remotes/origin/${target}`], cwd);
531
542
  if (fetched.status !== 0)
532
543
  throw new CliError("target_fetch_failed", `cannot fetch origin/${target} while finding changed paths for review rules: ${fetched.stderr?.trim() || "git fetch failed"}`, `check origin access and the target branch, then submit again`);
533
- const targetRef = "FETCH_HEAD";
544
+ const targetRef = `refs/remotes/origin/${target}`;
534
545
  const verify = spawnSync("git", ["rev-parse", "--verify", "--quiet", `${targetRef}^{commit}`], { cwd, encoding: "utf8" });
535
546
  if (verify.status !== 0)
536
547
  throw new CliError("target_unavailable", `git fetch origin/${target} succeeded but FETCH_HEAD is not a commit`);
@@ -882,7 +893,7 @@ export async function wu(p, out) {
882
893
  }
883
894
  throw error;
884
895
  }
885
- out.print(withRuleText(`${fmt(r.unit)}\nYour worktree: ${path}${mode === "fresh" ? ` (new branch ${branch} from origin/${target}${unit.replay ? " as of the original" : ""})` : mode === "branch" ? ` (branch ${branch})` : " (this checkout)"}\n cd ${path}\nWork there. Submit when ready: b9s wu submit ${n} --evidence <id>`, r, "start"), { ...r, worktree: path, branch, mode });
896
+ out.print(withRuleText(`${fmt(r.unit)}\nYour worktree: ${path}${mode === "fresh" ? ` (new branch ${branch} from origin/${target}${unit.replay ? " as of the original" : ""})` : mode === "branch" ? ` (branch ${branch})` : " (this checkout)"}\n cd ${path}\nWork there. Submit when ready: b9s wu submit ${n} --evidence <id>${midTurnWorktreeNote(detectVendor(), mode)}`, r, "start"), { ...r, worktree: path, branch, mode });
886
897
  if (readState(name).pending_context_clear?.work_unit_number === n) {
887
898
  updateState(name, (onDisk) => {
888
899
  const clear = onDisk.pending_context_clear;
@@ -1288,6 +1299,16 @@ export async function wu(p, out) {
1288
1299
  out.print(withRuleText(fmt(r.unit) + (verifiedRemoteTarget ? `\nverified on ${verifiedRemoteTarget}` : "") + cleanupUnitWorktree(r.unit.worktree, def, keepWorktree, antigravityWorkspaceWrite, "done", !deferredCleanupError && !keepWorktree, deferredCleanupError), r, "close"), r);
1289
1300
  return;
1290
1301
  }
1302
+ case "pr": {
1303
+ const unitNumber = Number(p.positionals[2]);
1304
+ if (!Number.isInteger(unitNumber) || unitNumber < 1)
1305
+ throw new CliError("usage", "wu pr <number> [--auto-merge]");
1306
+ const autoMerge = bool(p.flags, "auto-merge");
1307
+ const result = await client.call("POST", `${base}/${unitNumber}/pr`, { auto_merge: autoMerge });
1308
+ const pull = result.pull_request;
1309
+ out.print(`Pull request for WU #${unitNumber}: ${pull.url}${autoMerge ? " (auto-merge enabled)" : ""}`, result);
1310
+ return;
1311
+ }
1291
1312
  case "merge": {
1292
1313
  const statusOnly = p.positionals[2] === "status";
1293
1314
  const rawNumber = statusOnly ? p.positionals[3] : p.positionals[2];
@@ -1320,6 +1341,9 @@ export async function wu(p, out) {
1320
1341
  const failText = run.status === "failed"
1321
1342
  ? `\nFailed step: ${run.failed_step ?? "gate"}${run.attributed_unit_number ? `; culprit WU #${run.attributed_unit_number} (${run.attribution_method ?? "attributed"})` : ""}${run.error ? `\nError: ${run.error}` : ""}`
1322
1343
  : "";
1344
+ const retryText = Array.isArray(run.retry_reasons) && run.retry_reasons.length
1345
+ ? `\nRetry history: ${run.retry_reasons.map((reason) => `retried: ${reason}`).join("; ")}`
1346
+ : "";
1323
1347
  const entryLines = entries.map((e) => ({
1324
1348
  unit: `#${e.work_unit_number}`,
1325
1349
  status: e.status,
@@ -1327,7 +1351,7 @@ export async function wu(p, out) {
1327
1351
  owner: e.owner_name ?? "-",
1328
1352
  reason: e.reason ?? "-",
1329
1353
  }));
1330
- out.print(`Merge train run ${run.id} [${run.status}] on ${run.target_branch}${run.machine ? ` (${run.machine})` : ""}${run.merged_sha ? ` -> ${run.merged_sha.slice(0, 9)}` : ""}${run.closed_units?.length ? `\nClosed: ${run.closed_units.map((n) => `#${n}`).join(", ")}` : ""}${skippedText}${failText}${run.log_evidence_id ? `\nLog: evidence:${run.log_evidence_id}` : ""}${entryLines.length ? `\n${table(entryLines, ["unit", "status", "head", "owner", "reason"])}` : ""}`, detail);
1354
+ out.print(`Merge train run ${run.id} [${run.status}] on ${run.target_branch}${run.machine ? ` (${run.machine})` : ""}${run.merged_sha ? ` -> ${run.merged_sha.slice(0, 9)}` : ""}${run.closed_units?.length ? `\nClosed: ${run.closed_units.map((n) => `#${n}`).join(", ")}` : ""}${skippedText}${retryText}${failText}${run.log_evidence_id ? `\nLog: evidence:${run.log_evidence_id}` : ""}${entryLines.length ? `\n${table(entryLines, ["unit", "status", "head", "owner", "reason"])}` : ""}`, detail);
1331
1355
  return;
1332
1356
  }
1333
1357
  const qs = new URLSearchParams();
@@ -1351,7 +1375,7 @@ export async function wu(p, out) {
1351
1375
  const activeLine = res.active_run
1352
1376
  ? `Active run: ${res.active_run.id} [${res.active_run.status}] on ${res.active_run.target_branch}${res.active_run.machine ? ` (${res.active_run.machine})` : ""} · ${res.active_run.queued_units?.length ?? 0} queued`
1353
1377
  : "Active run: none";
1354
- const historyLines = res.history.slice(0, 10).map((r) => ` ${r.created_at.slice(0, 16).replace("T", " ")} ${r.id.slice(0, 8)} [${r.status}] ${r.target_branch}${r.merged_sha ? ` ${r.merged_sha.slice(0, 9)}` : ""}${r.closed_units?.length ? ` closed ${r.closed_units.map((n) => `#${n}`).join(",")}` : ""}${r.failed_step ? ` failed at ${r.failed_step}` : ""}${r.attributed_unit_number ? ` (send back WU #${r.attributed_unit_number})` : ""}`);
1378
+ const historyLines = res.history.slice(0, 10).map((r) => ` ${r.created_at.slice(0, 16).replace("T", " ")} ${r.id.slice(0, 8)} [${r.status}] ${r.target_branch}${r.merged_sha ? ` ${r.merged_sha.slice(0, 9)}` : ""}${r.closed_units?.length ? ` closed ${r.closed_units.map((n) => `#${n}`).join(",")}` : ""}${r.failed_step ? ` failed at ${r.failed_step}` : ""}${r.attributed_unit_number ? ` (send back WU #${r.attributed_unit_number})` : ""}${Array.isArray(r.retry_reasons) && r.retry_reasons.length ? ` · ${r.retry_reasons.map((reason) => `retried: ${reason}`).join("; ")}` : ""}`);
1355
1379
  out.print(`Merge train for ${res.project} (target ${res.target_branch}, merged_by ${res.policy?.merged_by ?? "owner"}, auto_enqueue ${res.policy?.auto_enqueue ? "yes" : "no"})\n${activeLine}\n${queueRows.length ? table(queueRows, ["unit", "status", "target", "head", "source", "owner", "title"]) : "(train queue is empty)"}${historyLines.length ? `\nRecent runs:\n${historyLines.join("\n")}` : ""}`, res);
1356
1380
  return;
1357
1381
  }
@@ -1638,7 +1662,7 @@ export async function wu(p, out) {
1638
1662
  return;
1639
1663
  }
1640
1664
  default:
1641
- throw new CliError("usage", "wu open|assign|lands-with|branch|start [--branch b|--here]|decline|submit|approve|changes|classify|tags|merge <n>|merge status <n>|train <list|status|enqueue|remove|run>|done [--keep-worktree]|abandon|note|ask|rule|sendback-rule|propose|show|list|stalled");
1665
+ throw new CliError("usage", "wu open|assign|lands-with|branch|start [--branch b|--here]|decline|submit|approve|changes|classify|tags|pr <n> [--auto-merge]|merge <n>|merge status <n>|train <list|status|enqueue|remove|run>|done [--keep-worktree]|abandon|note|ask|rule|sendback-rule|propose|show|list|stalled");
1642
1666
  }
1643
1667
  }
1644
1668
  /** Queued units have no owner; ask the API to reject before any local worktree is made. */
@@ -1786,7 +1810,7 @@ function resolveRecordedBaseRef(recordedBase, target, n, branch) {
1786
1810
  sha = fullSha(recordedBase);
1787
1811
  }
1788
1812
  if (!sha) {
1789
- spawnSync("git", ["fetch", "--quiet", "origin"], { cwd: process.cwd(), encoding: "utf8", timeout: 120_000 });
1813
+ retryGitFetchSync(["fetch", "--quiet", "--no-tags", "origin", recordedBase], process.cwd());
1790
1814
  sha = fullSha(recordedBase);
1791
1815
  }
1792
1816
  if (!sha) {
@@ -2306,7 +2330,9 @@ export async function lock(p, out) {
2306
2330
  const shared = bool(p.flags, "shared");
2307
2331
  const runToken = str(p.flags, "token") ?? `b9sjob_${randomBytes(24).toString("hex")}`;
2308
2332
  const machine = defaultMachine();
2309
- const deps = processDeps((method, path, body) => client.call(method, path, body, path.endsWith('/output') ? { signal: AbortSignal.timeout(5000) } : { retries: lockRunRetries(path) }), (line) => process.stderr.write(`[b9s] ${line}\n`));
2333
+ const deps = processDeps((method, path, body) => client.call(method, path, body, path.endsWith('/running') ? { signal: AbortSignal.timeout(10_000) } :
2334
+ path.endsWith('/output') ? { signal: AbortSignal.timeout(5000) } :
2335
+ { retries: lockRunRetries(path) }), (line) => process.stderr.write(`[b9s] ${line}\n`));
2310
2336
  try {
2311
2337
  process.exitCode = await runUnderLock({
2312
2338
  project, identity: agentRef(creds), projectSelection: creds.project ? undefined : project,
@@ -0,0 +1,18 @@
1
+ import { CliError } from "./errors.js";
2
+ /** Encode Unicode metadata safely, but refuse before writing if the API is too old. */
3
+ export async function evidenceTextHeaders(client, project, values) {
4
+ const fields = Object.entries(values).filter((entry) => typeof entry[1] === "string" && entry[1].length > 0);
5
+ if (fields.some(([, value]) => /[^\x20-\x7e]/.test(value))) {
6
+ const capabilities = await client.call("GET", `/projects/${encodeURIComponent(project)}/evidence?limit=1`);
7
+ if (capabilities.text_headers_utf8 !== true)
8
+ throw new CliError("unsupported_server", "server does not support Unicode evidence metadata; update the server before posting");
9
+ }
10
+ const headers = {};
11
+ for (const [name, value] of fields) {
12
+ if (/[^\x20-\x7e]/.test(value))
13
+ headers[`x-bschat-${name}-utf8`] = encodeURIComponent(value);
14
+ else
15
+ headers[`x-bschat-${name}`] = value;
16
+ }
17
+ return headers;
18
+ }
@@ -0,0 +1,38 @@
1
+ import { spawnSync } from "node:child_process";
2
+ export const GIT_FETCH_MAX_ATTEMPTS = 4;
3
+ const RETRY_DELAYS_MS = [100, 250, 500];
4
+ export function isGitRefLockRace(result) {
5
+ const detail = `${result.error?.message ?? ""}\n${result.stderr ?? ""}\n${result.stdout ?? ""}`;
6
+ return /cannot lock ref|unable to update local ref|unable to create .*\.lock|is at [0-9a-f]{7,40} but expected [0-9a-f]{7,40}|expected [0-9a-f]{7,40},? found [0-9a-f]{7,40}/i.test(detail);
7
+ }
8
+ function noteRetry(label, attempt, detail, onRetry) {
9
+ const line = `[b9s] ${label} hit a Git ref-lock race (attempt ${attempt}/${GIT_FETCH_MAX_ATTEMPTS}); retrying: ${detail.trim().slice(0, 240)}`;
10
+ if (onRetry)
11
+ onRetry(line);
12
+ else
13
+ process.stderr.write(`${line}\n`);
14
+ }
15
+ /** Run a fetch with bounded backoff for transient concurrent ref updates only. */
16
+ export async function retryGitFetch(run, label, options = {}) {
17
+ const sleep = options.sleep ?? ((ms) => new Promise((resolve) => setTimeout(resolve, ms)));
18
+ for (let attempt = 1;; attempt += 1) {
19
+ const result = await run();
20
+ if (result.status === 0 || !isGitRefLockRace(result) || attempt >= GIT_FETCH_MAX_ATTEMPTS)
21
+ return result;
22
+ const detail = result.stderr || result.stdout || result.error?.message || "ref changed during fetch";
23
+ noteRetry(label, attempt, detail, options.onRetry);
24
+ await sleep(RETRY_DELAYS_MS[attempt - 1]);
25
+ }
26
+ }
27
+ /** Synchronous counterpart for CLI and daemon paths that cannot be made async. */
28
+ export function retryGitFetchSync(args, cwd, options = {}) {
29
+ const run = options.run ?? ((command, commandArgs, runOptions) => spawnSync(command, commandArgs, runOptions));
30
+ for (let attempt = 1;; attempt += 1) {
31
+ const result = run("git", args, { cwd, encoding: "utf8", timeout: options.timeoutMs ?? 120_000, env: options.env });
32
+ if (result.status === 0 || !isGitRefLockRace(result) || attempt >= GIT_FETCH_MAX_ATTEMPTS)
33
+ return result;
34
+ const detail = result.stderr?.toString() || result.stdout?.toString() || result.error?.message || "ref changed during fetch";
35
+ noteRetry("git fetch", attempt, detail, options.onRetry);
36
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, RETRY_DELAYS_MS[attempt - 1]);
37
+ }
38
+ }