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.
@@ -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`);
@@ -583,6 +593,30 @@ export function measureContextOutput(context, expectedEffect, measuredEffects) {
583
593
  lines.push(` ${omitted} additional measures omitted`);
584
594
  return lines.join("\n");
585
595
  }
596
+ /** Resolve a stuck or timed-out merge-train push claim after checking the target branch. */
597
+ export async function resolveTrainClaimCommand(client, project, runId, p, out, usage) {
598
+ const outcomeRaw = str(p.flags, "outcome")?.trim();
599
+ if (!runId || (outcomeRaw !== "pushed" && outcomeRaw !== "not-pushed" && outcomeRaw !== "not_pushed")) {
600
+ throw new CliError("usage", usage);
601
+ }
602
+ const outcome = outcomeRaw === "not-pushed" ? "not_pushed" : outcomeRaw;
603
+ const merged = str(p.flags, "merged")?.trim();
604
+ const note = str(p.flags, "note")?.trim();
605
+ if (!note)
606
+ throw new CliError("usage", '--note "..." is required to record what the target branch check showed');
607
+ if (outcome === "pushed" && (!merged || !/^[0-9a-f]{40}$/i.test(merged))) {
608
+ throw new CliError("usage", "--merged <full-40-character-sha> is required when --outcome pushed");
609
+ }
610
+ if (outcome === "not_pushed" && merged) {
611
+ throw new CliError("usage", "--merged is only accepted with --outcome pushed");
612
+ }
613
+ const r = await client.call("POST", `/projects/${encodeURIComponent(project)}/merge-train/runs/${encodeURIComponent(runId)}/resolve`, {
614
+ outcome,
615
+ note,
616
+ ...(merged ? { merged_sha: merged.toLowerCase() } : {}),
617
+ });
618
+ out.print(`Resolved merge train run ${runId} (${outcome === "pushed" ? `pushed -> ${merged.slice(0, 9)}` : "not pushed"})${Array.isArray(r.closed_units) && r.closed_units.length ? `; closed ${r.closed_units.map((n) => `WU #${n}`).join(", ")}` : ""}.`, r);
619
+ }
586
620
  export async function wu(p, out) {
587
621
  const sub = p.positionals[1];
588
622
  const name = resolveAgentName(str(p.flags, "as"));
@@ -858,7 +892,7 @@ export async function wu(p, out) {
858
892
  }
859
893
  throw error;
860
894
  }
861
- 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 });
862
896
  if (readState(name).pending_context_clear?.work_unit_number === n) {
863
897
  updateState(name, (onDisk) => {
864
898
  const clear = onDisk.pending_context_clear;
@@ -906,7 +940,8 @@ export async function wu(p, out) {
906
940
  if (check.remoteBranch) {
907
941
  remoteCommitBranch = check.remoteBranch;
908
942
  const containingBranch = check.remoteBranch.replace(/^origin\//, "");
909
- where.branch = containingBranch;
943
+ // Keep the branch collected from this checkout in the submission payload. A different
944
+ // remote branch may contain the same commit, but it does not change this checkout's branch.
910
945
  // Record the verified advertised tip, not the possibly older local submission SHA.
911
946
  // Repeated submissions of ancestors while origin is unchanged must not reset activity.
912
947
  if (submitUnit.owner_name === creds.agent && submitUnit.branch === localBranch && containingBranch === localBranch && where.head) {
@@ -1281,6 +1316,95 @@ export async function wu(p, out) {
1281
1316
  out.print(`${detail}${unit ? `\nWU #${unitNumber} [${unit.status}]${unit.merged_sha ? ` · merged ${unit.merged_sha}` : ""}` : ""}`, r);
1282
1317
  return;
1283
1318
  }
1319
+ case "train": {
1320
+ const action = p.positionals[2]?.trim() || "list";
1321
+ if (action === "list" || action === "status") {
1322
+ if (action === "status" && p.positionals[3]) {
1323
+ const runId = p.positionals[3].trim();
1324
+ const detail = await client.call("GET", `/projects/${project}/merge-train/runs/${encodeURIComponent(runId)}`);
1325
+ const run = detail.run;
1326
+ const entries = Array.isArray(detail.entries) ? detail.entries : [];
1327
+ const skippedText = Array.isArray(run.skipped_units) && run.skipped_units.length
1328
+ ? `\nSkipped: ${run.skipped_units.map((s) => `#${s.unit_number} (${s.outcome}: ${s.reason})`).join("; ")}`
1329
+ : "";
1330
+ const failText = run.status === "failed"
1331
+ ? `\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}` : ""}`
1332
+ : "";
1333
+ const entryLines = entries.map((e) => ({
1334
+ unit: `#${e.work_unit_number}`,
1335
+ status: e.status,
1336
+ head: String(e.approved_head ?? "-").slice(0, 9),
1337
+ owner: e.owner_name ?? "-",
1338
+ reason: e.reason ?? "-",
1339
+ }));
1340
+ 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);
1341
+ return;
1342
+ }
1343
+ const qs = new URLSearchParams();
1344
+ const target = str(p.flags, "target")?.trim();
1345
+ const limit = str(p.flags, "limit")?.trim();
1346
+ if (target)
1347
+ qs.set("target", target);
1348
+ if (limit)
1349
+ qs.set("limit", limit);
1350
+ const suffix = qs.toString() ? `?${qs}` : "";
1351
+ const res = await client.call("GET", `/projects/${project}/merge-train${suffix}`);
1352
+ const queueRows = res.queue.map((e) => ({
1353
+ unit: `#${e.work_unit_number}`,
1354
+ status: e.status,
1355
+ target: e.target_branch,
1356
+ head: String(e.approved_head ?? "-").slice(0, 9),
1357
+ source: e.enqueue_source,
1358
+ owner: e.owner_name ?? "-",
1359
+ title: String(e.title ?? "").slice(0, 48),
1360
+ }));
1361
+ const activeLine = res.active_run
1362
+ ? `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`
1363
+ : "Active run: none";
1364
+ 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})` : ""}`);
1365
+ 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);
1366
+ return;
1367
+ }
1368
+ if (action === "enqueue") {
1369
+ const unitNumber = Number(p.positionals[3]);
1370
+ if (!Number.isInteger(unitNumber) || unitNumber < 1)
1371
+ throw new CliError("usage", "wu train enqueue <n> [--head <sha>]");
1372
+ const head = str(p.flags, "head")?.trim();
1373
+ const r = await client.call("POST", `/projects/${project}/merge-train/enqueue`, {
1374
+ unit: unitNumber,
1375
+ ...(head ? { head } : {}),
1376
+ });
1377
+ out.print(`WU #${unitNumber} ${r.already_queued ? "already queued" : "queued"} on merge train for ${r.entry.target_branch} at ${String(r.entry.approved_head).slice(0, 9)}${r.scheduled_run ? ` (scheduled run ${r.scheduled_run.id})` : ""}.`, r);
1378
+ return;
1379
+ }
1380
+ if (action === "remove") {
1381
+ const unitNumber = Number(p.positionals[3]);
1382
+ if (!Number.isInteger(unitNumber) || unitNumber < 1)
1383
+ throw new CliError("usage", 'wu train remove <n> [--reason "..."]');
1384
+ const reason = str(p.flags, "reason")?.trim();
1385
+ const r = await client.call("POST", `/projects/${project}/merge-train/remove`, {
1386
+ unit: unitNumber,
1387
+ ...(reason ? { reason } : {}),
1388
+ });
1389
+ out.print(r.removed ? `Removed WU #${unitNumber} from the merge train queue.` : `WU #${unitNumber} was not in the active merge train queue.`, r);
1390
+ return;
1391
+ }
1392
+ if (action === "run") {
1393
+ const target = str(p.flags, "target")?.trim();
1394
+ const machine = str(p.flags, "on")?.trim();
1395
+ const r = await client.call("POST", `/projects/${project}/merge-train/run`, {
1396
+ ...(target ? { target } : {}),
1397
+ ...(machine ? { machine } : {}),
1398
+ });
1399
+ out.print(`Queued merge train run ${r.run.id} (gate job ${r.job.id}) on ${r.run.machine ?? "eligible machine"} for ${r.run.target_branch}.`, r);
1400
+ return;
1401
+ }
1402
+ if (action === "resolve") {
1403
+ await resolveTrainClaimCommand(client, project, p.positionals[3]?.trim() ?? "", p, out, 'wu train resolve <run-id> --outcome pushed|not-pushed [--merged <sha>] --note "..."');
1404
+ return;
1405
+ }
1406
+ throw new CliError("usage", "wu train <list|status [<run-id>]|enqueue <n>|remove <n>|run|resolve <run-id>>");
1407
+ }
1284
1408
  case "abandon": {
1285
1409
  const r = await client.call("POST", `${base}/${num()}/abandon`, { note: str(p.flags, "note") ?? "" });
1286
1410
  // Same as done: a clean worktree goes (its branch, and every commit on it, stays).
@@ -1524,7 +1648,7 @@ export async function wu(p, out) {
1524
1648
  return;
1525
1649
  }
1526
1650
  default:
1527
- 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>|done [--keep-worktree]|abandon|note|ask|rule|sendback-rule|propose|show|list|stalled");
1651
+ 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");
1528
1652
  }
1529
1653
  }
1530
1654
  /** Queued units have no owner; ask the API to reject before any local worktree is made. */
@@ -1672,7 +1796,7 @@ function resolveRecordedBaseRef(recordedBase, target, n, branch) {
1672
1796
  sha = fullSha(recordedBase);
1673
1797
  }
1674
1798
  if (!sha) {
1675
- spawnSync("git", ["fetch", "--quiet", "origin"], { cwd: process.cwd(), encoding: "utf8", timeout: 120_000 });
1799
+ retryGitFetchSync(["fetch", "--quiet", "--no-tags", "origin", recordedBase], process.cwd());
1676
1800
  sha = fullSha(recordedBase);
1677
1801
  }
1678
1802
  if (!sha) {
@@ -2192,7 +2316,9 @@ export async function lock(p, out) {
2192
2316
  const shared = bool(p.flags, "shared");
2193
2317
  const runToken = str(p.flags, "token") ?? `b9sjob_${randomBytes(24).toString("hex")}`;
2194
2318
  const machine = defaultMachine();
2195
- 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`));
2196
2322
  try {
2197
2323
  process.exitCode = await runUnderLock({
2198
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
+ }
package/dist/git.js CHANGED
@@ -4,9 +4,10 @@ import { hostname } from "node:os";
4
4
  import { dirname, isAbsolute, join, relative, sep } from "node:path";
5
5
  import { CliError } from "./errors.js";
6
6
  import { configDirectory } from "./directories.js";
7
+ import { retryGitFetchSync } from "./git-fetch.js";
7
8
  export const PRUNE_STATUS_TIMEOUT_MS = 30_000;
8
9
  function status(cwd, timeoutMs) {
9
- const r = spawnSync("git", ["status", "--porcelain"], { cwd, encoding: "utf8", stdio: ["ignore", "pipe", "ignore"], maxBuffer: 512 * 1024 * 1024, ...(timeoutMs === undefined ? {} : { timeout: timeoutMs }) });
10
+ const r = spawnSync("git", ["status", "--porcelain"], { cwd, env: gitMetadataEnv(cwd), encoding: "utf8", stdio: ["ignore", "pipe", "ignore"], maxBuffer: 512 * 1024 * 1024, ...(timeoutMs === undefined ? {} : { timeout: timeoutMs }) });
10
11
  const errorCode = r.error?.code;
11
12
  if (errorCode === "ETIMEDOUT" || (r.error && /timed out/i.test(r.error.message))) {
12
13
  throw new CliError("timeout", `git status timed out after ${timeoutMs} ms in worktree ${cwd}`);
@@ -17,32 +18,62 @@ function status(cwd, timeoutMs) {
17
18
  }
18
19
  /** Local, bounded proof that a session checkout is clean and every commit is reachable from a remote. */
19
20
  export function sessionCheckoutFacts(cwd, options = {}) {
21
+ const gitDir = git(["rev-parse", "--absolute-git-dir"], cwd);
20
22
  const branchResult = spawnSync("git", ["rev-parse", "--abbrev-ref", "HEAD"], {
21
- cwd, encoding: "utf8", stdio: ["ignore", "pipe", "ignore"], maxBuffer: 1024 * 1024, timeout: 5_000,
23
+ cwd, env: gitMetadataEnv(cwd), encoding: "utf8", stdio: ["ignore", "pipe", "ignore"], maxBuffer: 1024 * 1024, timeout: 5_000,
22
24
  });
25
+ const branch = branchResult.status === 0 && branchResult.stdout.trim() ? branchResult.stdout.trim() : null;
23
26
  const statusResult = spawnSync("git", ["status", "--porcelain"], {
24
- cwd, encoding: "utf8", stdio: ["ignore", "pipe", "ignore"], maxBuffer: 16 * 1024 * 1024, timeout: 5_000,
27
+ cwd, env: gitMetadataEnv(cwd), encoding: "utf8", stdio: ["ignore", "pipe", "ignore"], maxBuffer: 16 * 1024 * 1024, timeout: 5_000,
25
28
  });
26
- const fetched = options.verifyOrigin ? spawnSync("git", ["fetch", "--prune", "origin"], {
27
- cwd, encoding: "utf8", stdio: ["ignore", "ignore", "ignore"], timeout: 30_000,
28
- env: { ...process.env, GIT_TERMINAL_PROMPT: "0" },
29
- }) : null;
30
- const remoteResult = spawnSync("git", ["rev-list", "--count", "HEAD", "--not", options.verifyOrigin ? "--remotes=origin" : "--remotes"], {
31
- cwd, encoding: "utf8", stdio: ["ignore", "pipe", "ignore"], maxBuffer: 1024 * 1024, timeout: 5_000,
29
+ let fetchFailure = null;
30
+ const liveRemoteRefs = [];
31
+ if (options.verifyOrigin && gitDir) {
32
+ // Reachability has historically meant any advertised origin branch. Enumerate that live set,
33
+ // update each changed tracking ref explicitly, and keep deleted cached refs out of the proof.
34
+ // Fetching all origin refs in one operation let an unrelated branch update abort this check.
35
+ const advertised = spawnSync("git", ["ls-remote", "--heads", "origin"], { cwd, encoding: "utf8", timeout: 30_000, env: gitTransportEnv(), maxBuffer: 16 * 1024 * 1024 });
36
+ if (advertised.status !== 0) {
37
+ fetchFailure = { status: advertised.status, stdout: advertised.stdout, stderr: advertised.stderr, error: advertised.error };
38
+ }
39
+ else {
40
+ for (const line of advertised.stdout.split("\n")) {
41
+ const [remoteSha, remoteBranchRef] = line.trim().split(/\s+/);
42
+ if (!/^[0-9a-f]{40,64}$/i.test(remoteSha ?? "") || !remoteBranchRef?.startsWith("refs/heads/"))
43
+ continue;
44
+ const branchName = remoteBranchRef.slice("refs/heads/".length);
45
+ const trackingRef = `refs/remotes/origin/${branchName}`;
46
+ if (fullSha(trackingRef, cwd) !== remoteSha.toLowerCase()) {
47
+ const fetched = retryGitFetchSync(["--git-dir", gitDir, "--work-tree", cwd, "fetch", "--no-tags", "origin", `+${remoteBranchRef}:${trackingRef}`], cwd, { timeoutMs: 30_000, env: gitTransportEnv() });
48
+ if (fetched.status !== 0 || fullSha(trackingRef, cwd) === null) {
49
+ fetchFailure = fetched.status === 0
50
+ ? { ...fetched, status: 1, stderr: `${trackingRef} was unavailable after fetch` }
51
+ : fetched;
52
+ break;
53
+ }
54
+ }
55
+ liveRemoteRefs.push(trackingRef);
56
+ }
57
+ }
58
+ }
59
+ const reachabilityArgs = options.verifyOrigin
60
+ ? ["rev-list", "--count", "HEAD", ...(liveRemoteRefs.length ? ["--not", ...liveRemoteRefs] : [])]
61
+ : ["rev-list", "--count", "HEAD", "--not", "--remotes"];
62
+ const remoteResult = spawnSync("git", reachabilityArgs, {
63
+ cwd, env: gitMetadataEnv(cwd), encoding: "utf8", stdio: ["ignore", "pipe", "ignore"], maxBuffer: 1024 * 1024, timeout: 5_000,
32
64
  });
33
65
  const statusError = statusResult.error;
34
66
  const remoteError = remoteResult.error;
35
67
  const statusOk = statusResult.status === 0;
36
68
  const countText = remoteResult.stdout.trim();
37
- const count = (!fetched || fetched.status === 0) && remoteResult.status === 0 && /^\d+$/.test(countText) ? Number(countText) : null;
69
+ const count = (!options.verifyOrigin || (gitDir !== null && fetchFailure === null)) && remoteResult.status === 0 && /^\d+$/.test(countText) ? Number(countText) : null;
38
70
  const entries = statusOk ? statusResult.stdout.split("\n").filter(Boolean) : [];
39
71
  const untracked = statusOk ? entries.some((line) => line.startsWith("??")) : null;
40
72
  const uncommitted = statusOk ? entries.some((line) => !line.startsWith("??")) : null;
41
73
  const clean = statusOk ? entries.length === 0 : null;
42
- const branch = branchResult.status === 0 && branchResult.stdout.trim() ? branchResult.stdout.trim() : null;
43
74
  const branchError = branchResult.error;
44
- const fetchError = fetched?.error;
45
- const errors = [statusError?.code ?? (statusOk ? null : `git status exited ${statusResult.status}`), fetched && fetched.status !== 0 ? `git fetch origin failed: ${fetchError?.code ?? `exit ${fetched.status}`}` : null, remoteError?.code ?? (remoteResult.status !== 0 || !/^\d+$/.test(countText) ? `git remote reachability exited ${remoteResult.status}` : null), branchError?.code ?? (branch === null ? `git branch inspection exited ${branchResult.status}` : null)].filter(Boolean);
75
+ const fetchError = fetchFailure?.error;
76
+ const errors = [statusError?.code ?? (statusOk ? null : `git status exited ${statusResult.status}`), options.verifyOrigin && !gitDir ? "git fetch origin failed: checkout could not be resolved" : fetchFailure ? `git fetch origin failed: ${fetchError?.code ?? fetchFailure.stderr?.trim() ?? `exit ${fetchFailure.status}`}` : null, remoteError?.code ?? (remoteResult.status !== 0 || !/^\d+$/.test(countText) ? `git remote reachability exited ${remoteResult.status}` : null), branchError?.code ?? (branch === null ? `git branch inspection exited ${branchResult.status}` : null)].filter(Boolean);
46
77
  return {
47
78
  branch,
48
79
  clean,
@@ -56,11 +87,47 @@ export function sessionCheckoutFacts(cwd, options = {}) {
56
87
  function git(args, cwd) {
57
88
  // Large enough for `git status` on a big repo with every file changed (ester: 226k files, 25 MB);
58
89
  // the 1 MB default made such a worktree unreadable rather than dirty.
59
- const r = spawnSync("git", args, { cwd, encoding: "utf8", stdio: ["ignore", "pipe", "ignore"], maxBuffer: 512 * 1024 * 1024 });
90
+ const r = spawnSync("git", args, { cwd, env: gitMetadataEnv(cwd), encoding: "utf8", stdio: ["ignore", "pipe", "ignore"], maxBuffer: 512 * 1024 * 1024 });
60
91
  if (r.status !== 0)
61
92
  return null;
62
93
  return r.stdout.trim();
63
94
  }
95
+ /**
96
+ * Repository facts describe the checkout at `cwd`, never a different repo selected by the
97
+ * session's Git environment. In particular, daemon-launched sessions may carry GIT_CONFIG_*
98
+ * entries for credential helpers and safe.directory. Keep that full environment for network Git
99
+ * operations (fetch/push), but isolate local inspection from all inherited Git overrides.
100
+ */
101
+ function gitMetadataEnv(cwd) {
102
+ const env = {};
103
+ for (const [key, value] of Object.entries(process.env)) {
104
+ if (!key.startsWith("GIT_"))
105
+ env[key] = value;
106
+ }
107
+ env.GIT_CONFIG_NOSYSTEM = "1";
108
+ env.GIT_CONFIG_GLOBAL = process.platform === "win32" ? "NUL" : "/dev/null";
109
+ env.GIT_CONFIG_COUNT = "1";
110
+ env.GIT_CONFIG_KEY_0 = "safe.directory";
111
+ env.GIT_CONFIG_VALUE_0 = cwd;
112
+ return env;
113
+ }
114
+ /** Keep credential config for transport, but pin repository discovery to the explicit cwd/git-dir. */
115
+ function gitTransportEnv() {
116
+ const env = { ...process.env, GIT_TERMINAL_PROMPT: "0" };
117
+ for (const key of [
118
+ "GIT_DIR", "GIT_WORK_TREE", "GIT_COMMON_DIR", "GIT_INDEX_FILE", "GIT_INDEX_VERSION",
119
+ "GIT_OBJECT_DIRECTORY", "GIT_ALTERNATE_OBJECT_DIRECTORIES", "GIT_CEILING_DIRECTORIES",
120
+ "GIT_DISCOVERY_ACROSS_FILESYSTEM", "GIT_NAMESPACE", "GIT_PREFIX", "GIT_SHALLOW_FILE",
121
+ "GIT_REPLACE_REF_BASE",
122
+ ])
123
+ delete env[key];
124
+ return env;
125
+ }
126
+ /** Pin remote Git commands to the checkout discovered under cwd-scoped metadata rules. */
127
+ function gitRepositoryArgs(cwd) {
128
+ const gitDir = git(["rev-parse", "--absolute-git-dir"], cwd);
129
+ return gitDir ? ["--git-dir", gitDir, "--work-tree", cwd] : [];
130
+ }
64
131
  /** Read from the real repo state every call. Never cached. */
65
132
  export function collectAuto(opts) {
66
133
  const cwd = opts.cwd ?? process.cwd();
@@ -88,7 +155,7 @@ export function mergeFacts(cwd, worktree) {
88
155
  const base = ["main", "master"].find((b) => git(["rev-parse", "--verify", "-q", `${b}^{commit}`], cwd) !== null) ?? null;
89
156
  if (!base)
90
157
  return { repo, base: null, merged: null, ahead: null };
91
- const merged = spawnSync("git", ["merge-base", "--is-ancestor", "HEAD", base], { cwd, stdio: "ignore" }).status === 0;
158
+ const merged = spawnSync("git", ["merge-base", "--is-ancestor", "HEAD", base], { cwd, env: gitMetadataEnv(cwd), stdio: "ignore" }).status === 0;
92
159
  const count = git(["rev-list", "--count", `${base}..HEAD`], cwd);
93
160
  return { repo, base, merged, ahead: count === null ? null : Number(count) };
94
161
  }
@@ -180,14 +247,14 @@ export function machineIdentityForAgent(savedMachine, env = process.env, host =
180
247
  export function isAncestor(ancestor, ref, cwd = process.cwd()) {
181
248
  if (git(["rev-parse", "--verify", "-q", `${ancestor}^{commit}`], cwd) === null || git(["rev-parse", "--verify", "-q", `${ref}^{commit}`], cwd) === null)
182
249
  return null;
183
- const r = spawnSync("git", ["merge-base", "--is-ancestor", ancestor, ref], { cwd, stdio: "ignore" });
250
+ const r = spawnSync("git", ["merge-base", "--is-ancestor", ancestor, ref], { cwd, env: gitMetadataEnv(cwd), stdio: "ignore" });
184
251
  return r.status === 0;
185
252
  }
186
253
  /** Confirm an evidence-only unit branch contains no commits missing from its configured target. */
187
254
  export function verifyNoCommitsBeyondTarget(branch, target, cwd = process.cwd(), requirePushed = false) {
188
255
  const localBranch = `refs/heads/${branch}`;
189
256
  const ref = `origin/${target}`;
190
- const fetchTarget = spawnSync("git", ["fetch", "--quiet", "origin", `+refs/heads/${target}:refs/remotes/origin/${target}`], { cwd, encoding: "utf8", timeout: 120_000 });
257
+ const fetchTarget = retryGitFetchSync(["fetch", "--quiet", "origin", `+refs/heads/${target}:refs/remotes/origin/${target}`], cwd);
191
258
  if (fetchTarget.status !== 0) {
192
259
  const detail = fetchTarget.error?.message || fetchTarget.stderr?.trim() || fetchTarget.stdout?.trim() || `git fetch exited ${fetchTarget.status ?? "without a status"}`;
193
260
  return { on: null, ref, reason: `git fetch origin ${target} failed: ${detail}` };
@@ -205,7 +272,7 @@ export function verifyNoCommitsBeyondTarget(branch, target, cwd = process.cwd(),
205
272
  const listed = spawnSync("git", ["ls-remote", "--exit-code", "--heads", "origin", remoteBranchRef], { cwd, encoding: "utf8", timeout: 120_000 });
206
273
  if (listed.status === 0 && listed.stdout?.trim()) {
207
274
  const remoteTracking = `refs/remotes/origin/${branch}`;
208
- const fetchBranch = spawnSync("git", ["fetch", "--quiet", "origin", `+${remoteBranchRef}:${remoteTracking}`], { cwd, encoding: "utf8", timeout: 120_000 });
275
+ const fetchBranch = retryGitFetchSync(["fetch", "--quiet", "origin", `+${remoteBranchRef}:${remoteTracking}`], cwd);
209
276
  if (fetchBranch.status !== 0) {
210
277
  const detail = fetchBranch.error?.message || fetchBranch.stderr?.trim() || fetchBranch.stdout?.trim() || `git fetch exited ${fetchBranch.status ?? "without a status"}`;
211
278
  return { on: null, ref, reason: `git fetch origin ${branch} failed: ${detail}` };
@@ -621,14 +688,15 @@ export function remoteTrackingRefContainsCommit(branch, advertisedTip, sha, cwd
621
688
  /** Fetch origin, then report a remote branch containing the submitted commit. */
622
689
  export function findRemoteCommitBranch(sha, localBranch, cwd = process.cwd(), remote = "origin") {
623
690
  const checkedRef = `${remote}/${localBranch}`;
691
+ const repositoryArgs = gitRepositoryArgs(cwd);
624
692
  // Submission only needs current remote-tracking refs. Force pruning off even when user/repo
625
693
  // config enables it: pruning stale refs takes .git/packed-refs.lock in the shared Git dir.
626
- const fetched = spawnSync("git", ["-c", "fetch.prune=false", "-c", `remote.${remote}.prune=false`, "fetch", remote], { cwd, encoding: "utf8", timeout: 120_000 });
694
+ const fetched = retryGitFetchSync([...repositoryArgs, "-c", "fetch.prune=false", "-c", `remote.${remote}.prune=false`, "fetch", remote], cwd, { env: gitTransportEnv() });
627
695
  if (fetched.status !== 0) {
628
696
  const detail = (fetched.stderr || fetched.stdout || `git fetch ${remote} exited with status ${fetched.status ?? "unknown"}`).trim();
629
697
  return { remoteBranch: null, advertisedTip: null, checkedRef, checked: false, reason: `git fetch ${remote} failed: ${detail}` };
630
698
  }
631
- const advertised = spawnSync("git", ["ls-remote", "--heads", remote], { cwd, encoding: "utf8", timeout: 30_000 });
699
+ const advertised = spawnSync("git", [...repositoryArgs, "ls-remote", "--heads", remote], { cwd, env: gitTransportEnv(), encoding: "utf8", timeout: 30_000 });
632
700
  if (advertised.status !== 0) {
633
701
  const detail = (advertised.stderr || advertised.stdout || `git ls-remote ${remote} exited with status ${advertised.status ?? "unknown"}`).trim();
634
702
  return { remoteBranch: null, advertisedTip: null, checkedRef, checked: false, reason: `git ls-remote ${remote} failed: ${detail}` };
@@ -650,7 +718,7 @@ export function findRemoteCommitBranch(sha, localBranch, cwd = process.cwd(), re
650
718
  // against their advertised tips. Checking every advertised branch one by one ran 1,542 git
651
719
  // processes for 771 branches (238 s on 2026-11-21), long enough for the API connection opened
652
720
  // before it to go stale, so wu submit failed with "fetch failed".
653
- const containing = spawnSync("git", ["for-each-ref", "--contains", sha, "--format=%(refname:short)", `refs/remotes/${remote}/`], { cwd, encoding: "utf8", timeout: 60_000 });
721
+ const containing = spawnSync("git", [...repositoryArgs, "for-each-ref", "--contains", sha, "--format=%(refname:short)", `refs/remotes/${remote}/`], { cwd, env: gitMetadataEnv(cwd), encoding: "utf8", timeout: 60_000 });
654
722
  if (containing.status !== 0) {
655
723
  const detail = (containing.stderr || containing.stdout || `git for-each-ref exited with status ${containing.status ?? "unknown"}`).trim();
656
724
  return { remoteBranch: null, advertisedTip: null, checkedRef, checked: false, reason: `git for-each-ref --contains ${sha} failed: ${detail}` };
@@ -674,7 +742,7 @@ export function fullSha(ref, cwd = process.cwd()) {
674
742
  }
675
743
  /** `git fetch <remote> <ref>`; false when the fetch fails (no remote, unreachable, no such ref). */
676
744
  export function fetchRef(ref, remote = "origin", cwd = process.cwd()) {
677
- return spawnSync("git", ["fetch", "--quiet", remote, ref], { cwd, encoding: "utf8", timeout: 120_000 }).status === 0;
745
+ return retryGitFetchSync(["fetch", "--quiet", remote, ref], cwd).status === 0;
678
746
  }
679
747
  export function hasRemote(remote = "origin", cwd = process.cwd()) {
680
748
  return spawnSync("git", ["remote", "get-url", remote], { cwd, encoding: "utf8" }).status === 0;
@@ -706,10 +774,10 @@ export function pushBranchToOrigin(branch, cwd = process.cwd(), remote = "origin
706
774
  * the updated tracking ref or the git failure reason.
707
775
  */
708
776
  export function fetchRemoteBranch(branch, remote = "origin", cwd = process.cwd()) {
709
- const r = spawnSync("git", ["fetch", "--quiet", remote, `+refs/heads/${branch}:refs/remotes/${remote}/${branch}`], { cwd, encoding: "utf8", timeout: 120_000 });
777
+ const r = retryGitFetchSync(["fetch", "--quiet", remote, `+refs/heads/${branch}:refs/remotes/${remote}/${branch}`], cwd);
710
778
  const trackingRef = `${remote}/${branch}`;
711
779
  if (r.status !== 0) {
712
- const reason = (r.error ? r.error.message : (r.stderr || r.stdout).trim()) || `git fetch ${remote} ${branch} failed (exit ${r.status ?? "unknown"})`;
780
+ const reason = r.error?.message || r.stderr?.trim() || r.stdout?.trim() || `git fetch ${remote} ${branch} failed (exit ${r.status ?? "unknown"})`;
713
781
  return { ok: false, reason };
714
782
  }
715
783
  if (fullSha(trackingRef, cwd) === null) {
@@ -783,7 +851,7 @@ export function verifyMergedCommit(merged, target, cwd = process.cwd()) {
783
851
  // Fetch into the remote-tracking ref explicitly. Fetching a bare branch name updates
784
852
  // FETCH_HEAD only and leaves origin/<target> stale, which cannot verify this condition.
785
853
  const ref = `origin/${target}`;
786
- const fetched = spawnSync("git", ["fetch", "--quiet", "origin", `+refs/heads/${target}:refs/remotes/origin/${target}`], { cwd, encoding: "utf8", timeout: 120_000 }).status === 0;
854
+ const fetched = retryGitFetchSync(["fetch", "--quiet", "origin", `+refs/heads/${target}:refs/remotes/origin/${target}`], cwd).status === 0;
787
855
  if (!fetched)
788
856
  return { on: local, ref: target };
789
857
  const remote = isAncestor(merged, ref, cwd);
@@ -918,7 +986,7 @@ function pushedToOrigin(head, branch, cwd) {
918
986
  if (!head || !branch)
919
987
  return false;
920
988
  const remoteRef = `refs/remotes/origin/${branch}`;
921
- const fetched = spawnSync("git", ["fetch", "--quiet", "origin", `+refs/heads/${branch}:${remoteRef}`], { cwd, encoding: "utf8", timeout: 120_000 });
989
+ const fetched = retryGitFetchSync(["fetch", "--quiet", "origin", `+refs/heads/${branch}:${remoteRef}`], cwd);
922
990
  return fetched.status === 0 && spawnSync("git", ["merge-base", "--is-ancestor", head, remoteRef], { cwd, stdio: "ignore" }).status === 0;
923
991
  }
924
992
  export function removeWorktreeIfClean(path, cwd = process.cwd(), statusTimeoutMs = PRUNE_STATUS_TIMEOUT_MS) {
package/dist/help.js CHANGED
@@ -203,6 +203,12 @@ Machine placement enforces configured session slots and reports machine pressure
203
203
  Antigravity workspace-write queues the exact closed worktree for cleanup outside the sandbox at turn finalization; branches are kept
204
204
  b9s wu merge <n> [--note "..."] role-checked hosted merge through the API; never inspects local Git credentials or state
205
205
  b9s wu merge status <n> operation status and non-secret audit trail for a hosted merge
206
+ b9s wu train list [--target <branch>] [--limit <n>] list active merge train queue and recent train runs
207
+ b9s wu train status [<run-id>] [--target <branch>] [--limit <n>] inspect merge train state or a specific run's details
208
+ b9s wu train enqueue <n> [--head <sha>] queue an approved unit onto the project merge train at its approved head
209
+ b9s wu train remove <n> [--reason "..."] remove a queued unit from the merge train
210
+ b9s wu train run [--target <branch>] [--on <machine>] start a remote gate job for the project merge train
211
+ b9s wu train resolve <run-id> --outcome pushed|not-pushed [--merged <sha>] --note "..." operator: resolve a stuck merge-train push claim after checking the target
206
212
  b9s wu show <n> [--scope-only] show the full unit and its Console link (or only its scope for scripts)
207
213
  b9s wu recovery save <n> --reason "..." save a WIP branch commit and encrypted cutoff bundle; keep the source volume until safe_to_delete
208
214
  b9s wu recovery restore <n> next owner: verify and restore the restricted recovery bundle into the unit worktree
@@ -322,7 +328,8 @@ Machine placement enforces configured session slots and reports machine pressure
322
328
  b9s ux job <id> [--log] inspect remote browser job diagnostics; --log prints its full log
323
329
  b9s ux jobs [--unit <n>] [--limit n] list remote browser jobs in this project
324
330
  b9s gate run <n> [--merge-candidate <sha>] --on <machine>
325
- queue a complete-suite gate run on a machine; records the receipt and posts the log as evidence
331
+ b9s gate run --train [--target <branch>] [--on <machine>]
332
+ queue a complete-suite gate run (or merge-train run) on a machine; records the receipt and posts the log as evidence
326
333
  b9s gate job <id> [--log] inspect remote gate diagnostics; --log prints its full log
327
334
  b9s gate jobs [--unit <n>] [--limit n] list remote gate jobs in this project
328
335
  b9s retire --title t (--body b | --body-file f) [--handoff-to @x|@role:y] [--evidence id,id] --yes
@@ -423,12 +430,15 @@ Project agents inspect work waits with b9s wu stalled [--all]; its default inclu
423
430
  b9s-admin role edit <name> [--project p] [--projects a,b|*] [--post c1,c2] [--broadcast] [--create-channels] [--read-account-status] [--assign-outside-qualifications yes|no] [--description d] [--cardinality one|many]
424
431
  b9s-admin role list [--project p]
425
432
  b9s-admin wu assign <project> <n> --to <agent> [--reason "why"] operator: reassign a unit in place
433
+ b9s-admin wu abandon <project> <n> --note "why" operator: close work that is no longer needed
434
+ b9s-admin wu supersede <project> <n> --by <m> operator: close this unit as continued by #m
426
435
  b9s-admin wu park|unpark <project> <n> --note "why" operator: park open or sent-back work, or return parked work to open
427
436
  b9s-admin wu done <project> <n> --merged <sha> [--gate-override-note "why"] [--note "context"] operator: close approved work; missing receipt override requires a recorded reason
428
437
  b9s-admin wu done <project> <n> --no-source --evidence id[,id...] --no-commits-beyond-target [--gate-override-note "why"] operator: close evidence-only work after confirming no commits beyond target
429
438
  b9s-admin wu merged-sha <project> <n> --sha <full-40-character-lowercase-sha> --reason "why" operator: correct a legacy abbreviated merged SHA with an audited reason
430
439
  b9s-admin wu head <project> <n> <full-sha> --reason "why" operator: record a commit verified on the unit's branch
431
440
  b9s-admin wu required-class <project> <n> (--class <p/h/m/e> | --clear) --reason "why" set or clear an operator hard routing-class lock
441
+ b9s-admin wu train resolve <project> <run-id> --outcome pushed|not-pushed [--merged <sha>] --note "..." operator: resolve a stuck merge-train push claim after checking the target
432
442
  b9s-admin routing show <project> [--mode build|review] [--tag <tag>] inspect confidence matrix, exploration spend, and recent decisions
433
443
  b9s-admin routing policy <project> [--weights q,t,c] [--quality-target <0..100|none>] [--half-life <days>] [--min-samples <n>] [--build-explore <0..20>] [--review-explore <0..20>] [--pause-build yes|no] [--pause-review yes|no] [--reason "why"]
434
444
  b9s-admin routing explain <project> <n> explain a unit's required_class, build route_decision, review_route, and dispatch candidates
@@ -0,0 +1,33 @@
1
+ import { performance } from "node:perf_hooks";
2
+ import { CliError } from "./errors.js";
3
+ export const LOCK_RUN_LEASE_MS = 60_000;
4
+ /** Retry an uncertain renewal while the last confirmed lock lease is still valid. */
5
+ export function createLockHeartbeatReporter(heartbeat, options = {}) {
6
+ const leaseMs = options.leaseMs ?? LOCK_RUN_LEASE_MS;
7
+ const now = options.now ?? (() => performance.now());
8
+ const sleep = options.sleep ?? ((ms) => new Promise((resolve) => setTimeout(resolve, ms)));
9
+ let lastConfirmedAt = now();
10
+ return async (commandPid) => {
11
+ let attempt = 0;
12
+ for (;;) {
13
+ try {
14
+ await heartbeat(commandPid);
15
+ lastConfirmedAt = now();
16
+ return;
17
+ }
18
+ catch (error) {
19
+ if (error instanceof CliError && (error.code === "lock_lease_lost" || error.code === "not_found")) {
20
+ throw new CliError("lock_lease_lost", `the server says this job no longer holds its lock: ${error.message}`, undefined, error.httpStatus);
21
+ }
22
+ const remainingMs = leaseMs - (now() - lastConfirmedAt);
23
+ if (remainingMs <= 0) {
24
+ throw new CliError("lock_heartbeat_failed", `lock renewal did not succeed for ${leaseMs}ms; the lease may have expired: ${error instanceof Error ? error.message : String(error)}`);
25
+ }
26
+ const delayMs = Math.min(remainingMs, Math.min(5_000, 500 * 2 ** Math.min(attempt, 4)));
27
+ options.onRetry?.(error, delayMs);
28
+ attempt++;
29
+ await sleep(delayMs);
30
+ }
31
+ }
32
+ };
33
+ }