benignswarm 0.12.158 → 0.12.159

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,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)
@@ -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) {
@@ -527,10 +537,10 @@ export function parseEvidenceReplacement(positionals) {
527
537
  }
528
538
  /** Changed paths are calculated from the fetched target's merge-base; a configured rule may not silently skip an unknown target. */
529
539
  export function changedPathsAgainstTarget(target, cwd = process.cwd()) {
530
- const fetched = spawnSync("git", ["fetch", "--quiet", "origin", target], { cwd, encoding: "utf8", timeout: 120_000 });
540
+ const fetched = retryGitFetchSync(["fetch", "--quiet", "origin", `+refs/heads/${target}:refs/remotes/origin/${target}`], cwd);
531
541
  if (fetched.status !== 0)
532
542
  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";
543
+ const targetRef = `refs/remotes/origin/${target}`;
534
544
  const verify = spawnSync("git", ["rev-parse", "--verify", "--quiet", `${targetRef}^{commit}`], { cwd, encoding: "utf8" });
535
545
  if (verify.status !== 0)
536
546
  throw new CliError("target_unavailable", `git fetch origin/${target} succeeded but FETCH_HEAD is not a commit`);
@@ -882,7 +892,7 @@ export async function wu(p, out) {
882
892
  }
883
893
  throw error;
884
894
  }
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 });
895
+ 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
896
  if (readState(name).pending_context_clear?.work_unit_number === n) {
887
897
  updateState(name, (onDisk) => {
888
898
  const clear = onDisk.pending_context_clear;
@@ -1786,7 +1796,7 @@ function resolveRecordedBaseRef(recordedBase, target, n, branch) {
1786
1796
  sha = fullSha(recordedBase);
1787
1797
  }
1788
1798
  if (!sha) {
1789
- spawnSync("git", ["fetch", "--quiet", "origin"], { cwd: process.cwd(), encoding: "utf8", timeout: 120_000 });
1799
+ retryGitFetchSync(["fetch", "--quiet", "--no-tags", "origin", recordedBase], process.cwd());
1790
1800
  sha = fullSha(recordedBase);
1791
1801
  }
1792
1802
  if (!sha) {
@@ -2306,7 +2316,9 @@ export async function lock(p, out) {
2306
2316
  const shared = bool(p.flags, "shared");
2307
2317
  const runToken = str(p.flags, "token") ?? `b9sjob_${randomBytes(24).toString("hex")}`;
2308
2318
  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`));
2319
+ const deps = processDeps((method, path, body) => client.call(method, path, body, path.endsWith('/running') ? { signal: AbortSignal.timeout(10_000) } :
2320
+ path.endsWith('/output') ? { signal: AbortSignal.timeout(5000) } :
2321
+ { retries: lockRunRetries(path) }), (line) => process.stderr.write(`[b9s] ${line}\n`));
2310
2322
  try {
2311
2323
  process.exitCode = await runUnderLock({
2312
2324
  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
+ }