benignswarm 0.12.157 → 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.
package/dist/args.js CHANGED
@@ -37,7 +37,7 @@ export const STRING_FLAGS = [
37
37
  "purpose", "storage-mode", "hosts", "arn", "version-id", "kms-key",
38
38
  "mode", "weights", "quality-target", "half-life", "min-samples", "build-explore", "review-explore", "pause-build", "pause-review", "class", "route",
39
39
  "expires-at", "conflicts-with", "source-channel-id", "source-message-id", "plain-summary",
40
- "metadata-file", "confirm-agent", "confirm-parked", "step", "compare", "merge-candidate",
40
+ "metadata-file", "confirm-agent", "confirm-parked", "step", "compare", "merge-candidate", "outcome",
41
41
  ];
42
42
  export const BOOL_FLAGS = [
43
43
  "latest", "no-restart", "json", "follow", "account", "help", "version", "broadcast", "create-channels",
@@ -47,7 +47,7 @@ export const BOOL_FLAGS = [
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
49
  "no-wait-verify", "preview", "remove-empty", "dry-run", "quota-substitution",
50
- "in-container", "retrieve-ec2", "stdin", "context-confirmed", "confirm-compatible", "move-provisioned", "provisioned", "no-commits-beyond-target",
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) {
53
53
  const options = {};
@@ -8,7 +8,7 @@ import { spawnSync } from "node:child_process";
8
8
  import { CliError } from "../errors.js";
9
9
  import { verifyUnitHeadOnOrigin } from "../git.js";
10
10
  import { table } from "../output.js";
11
- import { milestoneWith, milestonesWith } from "./wu.js";
11
+ import { milestoneWith, milestonesWith, resolveTrainClaimCommand } from "./wu.js";
12
12
  import { awayUntil } from "./agent.js";
13
13
  import { agentMove, machineAdmin, poolAdmin, projectCheckoutAdmin, projectRepoAdmin } from "./machine-admin.js";
14
14
  import { routingAdmin, runRequiredClassUpdate } from "./routing-admin.js";
@@ -588,6 +588,36 @@ async function role(action, rest, p, out) {
588
588
  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]");
589
589
  }
590
590
  async function workUnitAdmin(action, rest, p, out) {
591
+ if (action === "train") {
592
+ const [subcmd, project, runId] = rest;
593
+ if (subcmd === "resolve" && project && runId) {
594
+ return resolveTrainClaimCommand(adminClient(p), project, runId, p, out, 'b9s-admin wu train resolve <project> <run-id> --outcome pushed|not-pushed [--merged <sha>] --note "..."');
595
+ }
596
+ throw new CliError("usage", 'b9s-admin wu train resolve <project> <run-id> --outcome pushed|not-pushed [--merged <sha>] --note "..."');
597
+ }
598
+ if ((action === "abandon" || action === "supersede") && rest.length === 2 && /^\d+$/.test(rest[1])) {
599
+ const projectName = rest[0];
600
+ const numberText = rest[1];
601
+ const number = Number(numberText);
602
+ if (!Number.isSafeInteger(number) || number < 1)
603
+ throw new CliError("usage", `b9s-admin wu ${action} <project> <n>${action === "abandon" ? ' --note "why"' : " --by <m>"}`);
604
+ const base = `/projects/${encodeURIComponent(projectName)}/work-units/${number}`;
605
+ if (action === "abandon") {
606
+ const note = need(p.flags, "note").trim();
607
+ if (!note)
608
+ throw new CliError("usage", 'b9s-admin wu abandon <project> <n> --note "why"');
609
+ const result = await adminClient(p).call("POST", `${base}/abandon`, { note });
610
+ out.print(`Abandoned WU #${result.unit.number} [${result.unit.status}] in ${projectName}: ${result.unit.title}.`, result);
611
+ return;
612
+ }
613
+ const byText = need(p.flags, "by");
614
+ const by = Number(byText);
615
+ if (!/^\d+$/.test(byText) || !Number.isSafeInteger(by) || by < 1)
616
+ throw new CliError("usage", 'b9s-admin wu supersede <project> <n> --by <m>');
617
+ const result = await adminClient(p).call("POST", `${base}/supersede`, { by });
618
+ out.print(`Superseded WU #${result.unit.number} [${result.unit.status}] in ${projectName} by #${by}.`, result);
619
+ return;
620
+ }
591
621
  if ((action === "park" || action === "unpark") && rest.length === 2 && /^\d+$/.test(rest[1])) {
592
622
  const [projectName, numberText] = rest;
593
623
  const number = Number(numberText);
@@ -661,7 +691,7 @@ async function workUnitAdmin(action, rest, p, out) {
661
691
  return runRequiredClassUpdate(adminClient(p), rest[0], Number(rest[1]), p, out);
662
692
  }
663
693
  if (action !== "assign" || !rest[0] || !/^\d+$/.test(rest[1] ?? ""))
664
- throw new CliError("usage", 'b9s-admin wu assign <project> <n> --to <agent> [--reason "why"] | park|unpark <project> <n> --note "why" | b9s-admin wu done <project> <n> --merged <sha> [--gate-override-note "why"] | b9s-admin wu merged-sha <project> <n> --sha <full-sha> --reason "why" | b9s-admin wu required-class <project> <n> (--class p/h/m/e | --clear) --reason "why"');
694
+ throw new CliError("usage", 'b9s-admin wu abandon <project> <n> --note "why" | supersede <project> <n> --by <m> | assign <project> <n> --to <agent> [--reason "why"] | park|unpark <project> <n> --note "why" | done <project> <n> --merged <sha> [--gate-override-note "why"] | merged-sha <project> <n> --sha <full-sha> --reason "why" | required-class <project> <n> (--class p/h/m/e | --clear) --reason "why"');
665
695
  const to = str(p.flags, "to");
666
696
  if (!to)
667
697
  throw new CliError("usage", 'b9s-admin wu assign <project> <n> --to <agent> [--reason "why"]');
@@ -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)
@@ -327,7 +327,7 @@ export async function needsAdmin(p, out, project) {
327
327
  return out.print(project ? `Nothing waiting in ${r.project?.name ?? project}.` : "Nothing is waiting on you.", r);
328
328
  const ind = (t) => t.replace(/\n/g, "\n ");
329
329
  out.print(r.needs.map((n, i) => [
330
- `${i + 1}. [${n.project || "Account"}] ${n.display_id ?? (n.kind === "unit_question" ? `WU #${n.unit} question` : n.kind === "sendback_reviewer_gap" ? "send-back reviewer gap" : "decision id unavailable")} · ${n.kind === "unit_question" ? "unit question" : n.kind === "wake_broken" || n.kind === "wake_unresponsive" ? "wake path" : n.kind === "sendback_reviewer_gap" ? "send-back reviewer gap" : n.kind === "notifier" ? "your alerts" : n.kind === "machine_report_refused" ? "machine report refused" : n.kind === "machine_session" ? "machine" : n.kind === "lock_silent" ? "silent lock job" : "decision"} · ${n.asked_by} · since ${n.since.slice(0, 16).replace("T", " ")} UTC`,
330
+ `${i + 1}. [${n.project || "Account"}] ${n.display_id ?? (n.kind === "unit_question" ? `WU #${n.unit} question` : n.kind === "sendback_reviewer_gap" ? "send-back reviewer gap" : "decision id unavailable")} · ${n.kind === "unit_question" ? "unit question" : n.kind === "wake_broken" || n.kind === "wake_unresponsive" ? "wake path" : n.kind === "sendback_reviewer_gap" ? "send-back reviewer gap" : n.kind === "notifier" ? "your alerts" : n.kind === "machine_report_refused" ? "machine report refused" : n.kind === "machine_session" ? "machine" : n.kind === "lock_silent" ? "silent lock job" : n.kind === "platform_fault" ? (n.key.startsWith("remote-job-health:") ? "remote job health" : "platform fault") : "decision"} · ${n.asked_by} · since ${n.since.slice(0, 16).replace("T", " ")} UTC`,
331
331
  ` Console: ${consoleLink("decision", n.project, n.key)}`,
332
332
  n.plain ? ` In plain words: ${ind(n.plain)}` : n.unexplained ? ` In plain words: (${n.asked_by} did not explain this; b9s-admin explain ${n.key})` : null,
333
333
  n.blocks ? ` What's stuck: ${ind(n.blocks)}` : null,
@@ -38,7 +38,7 @@ async function printJob(job, res, p, out, creds, client, project) {
38
38
  function formatJob(job) {
39
39
  const isGate = job.job_kind === "gate";
40
40
  const what = isGate
41
- ? "complete-suite gate (scripts/gate.sh)"
41
+ ? (job.train_run_id ? "merge train gate" : "complete-suite gate (scripts/gate.sh)")
42
42
  : [job.task ? `ux:task ${job.task}` : null, job.compare_screen ? `ux:compare ${job.compare_screen}` : null].filter(Boolean).join(" + ");
43
43
  const headText = job.resolved_head ? job.resolved_head.slice(0, 9) : job.head ? job.head.slice(0, 9) : "branch tip";
44
44
  const evidenceLine = Array.isArray(job.evidence_ids) && job.evidence_ids.length
@@ -157,10 +157,27 @@ export async function gate(p, out) {
157
157
  const client = Client.forAgent(creds, resolveModel(str(p.flags, "model"), process.env, process.cwd(), name));
158
158
  const project = projectOf(p, creds);
159
159
  if (sub === "run") {
160
+ const train = bool(p.flags, "train");
161
+ if (train) {
162
+ if (p.positionals[2] !== undefined || str(p.flags, "merge-candidate") !== undefined) {
163
+ throw new CliError("usage", "b9s gate run --train [--target <branch>] [--on <machine>]");
164
+ }
165
+ const target = str(p.flags, "target")?.trim();
166
+ const machine = str(p.flags, "on")?.trim();
167
+ const res = await client.call("POST", `/projects/${project}/gate-jobs`, {
168
+ train: true,
169
+ ...(target ? { target } : {}),
170
+ ...(machine ? { machine } : {}),
171
+ });
172
+ const job = res.job;
173
+ const run = res.run;
174
+ out.print(`${formatJob(job)}\nTrain run: ${run?.id ?? "queued"} (target ${run?.target_branch ?? target ?? "default"}, ${run?.queued_units?.length ?? 0} queued unit(s))\nCheck status: b9s wu train status ${run?.id ?? ""}`.trimEnd(), res);
175
+ return;
176
+ }
160
177
  const unitText = p.positionals[2]?.trim();
161
178
  const unitNumber = unitText ? Number(unitText) : NaN;
162
179
  if (!Number.isSafeInteger(unitNumber) || unitNumber < 1) {
163
- throw new CliError("usage", "b9s gate run <n> [--merge-candidate <sha>] --on <machine>");
180
+ throw new CliError("usage", "b9s gate run <n> [--merge-candidate <sha>] --on <machine> | b9s gate run --train [--target <branch>] [--on <machine>]");
164
181
  }
165
182
  const machine = str(p.flags, "on")?.trim();
166
183
  if (!machine) {