benignswarm 0.12.157 → 0.12.158

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"]');
@@ -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) {
@@ -583,6 +583,30 @@ export function measureContextOutput(context, expectedEffect, measuredEffects) {
583
583
  lines.push(` ${omitted} additional measures omitted`);
584
584
  return lines.join("\n");
585
585
  }
586
+ /** Resolve a stuck or timed-out merge-train push claim after checking the target branch. */
587
+ export async function resolveTrainClaimCommand(client, project, runId, p, out, usage) {
588
+ const outcomeRaw = str(p.flags, "outcome")?.trim();
589
+ if (!runId || (outcomeRaw !== "pushed" && outcomeRaw !== "not-pushed" && outcomeRaw !== "not_pushed")) {
590
+ throw new CliError("usage", usage);
591
+ }
592
+ const outcome = outcomeRaw === "not-pushed" ? "not_pushed" : outcomeRaw;
593
+ const merged = str(p.flags, "merged")?.trim();
594
+ const note = str(p.flags, "note")?.trim();
595
+ if (!note)
596
+ throw new CliError("usage", '--note "..." is required to record what the target branch check showed');
597
+ if (outcome === "pushed" && (!merged || !/^[0-9a-f]{40}$/i.test(merged))) {
598
+ throw new CliError("usage", "--merged <full-40-character-sha> is required when --outcome pushed");
599
+ }
600
+ if (outcome === "not_pushed" && merged) {
601
+ throw new CliError("usage", "--merged is only accepted with --outcome pushed");
602
+ }
603
+ const r = await client.call("POST", `/projects/${encodeURIComponent(project)}/merge-train/runs/${encodeURIComponent(runId)}/resolve`, {
604
+ outcome,
605
+ note,
606
+ ...(merged ? { merged_sha: merged.toLowerCase() } : {}),
607
+ });
608
+ 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);
609
+ }
586
610
  export async function wu(p, out) {
587
611
  const sub = p.positionals[1];
588
612
  const name = resolveAgentName(str(p.flags, "as"));
@@ -906,7 +930,8 @@ export async function wu(p, out) {
906
930
  if (check.remoteBranch) {
907
931
  remoteCommitBranch = check.remoteBranch;
908
932
  const containingBranch = check.remoteBranch.replace(/^origin\//, "");
909
- where.branch = containingBranch;
933
+ // Keep the branch collected from this checkout in the submission payload. A different
934
+ // remote branch may contain the same commit, but it does not change this checkout's branch.
910
935
  // Record the verified advertised tip, not the possibly older local submission SHA.
911
936
  // Repeated submissions of ancestors while origin is unchanged must not reset activity.
912
937
  if (submitUnit.owner_name === creds.agent && submitUnit.branch === localBranch && containingBranch === localBranch && where.head) {
@@ -1281,6 +1306,95 @@ export async function wu(p, out) {
1281
1306
  out.print(`${detail}${unit ? `\nWU #${unitNumber} [${unit.status}]${unit.merged_sha ? ` · merged ${unit.merged_sha}` : ""}` : ""}`, r);
1282
1307
  return;
1283
1308
  }
1309
+ case "train": {
1310
+ const action = p.positionals[2]?.trim() || "list";
1311
+ if (action === "list" || action === "status") {
1312
+ if (action === "status" && p.positionals[3]) {
1313
+ const runId = p.positionals[3].trim();
1314
+ const detail = await client.call("GET", `/projects/${project}/merge-train/runs/${encodeURIComponent(runId)}`);
1315
+ const run = detail.run;
1316
+ const entries = Array.isArray(detail.entries) ? detail.entries : [];
1317
+ const skippedText = Array.isArray(run.skipped_units) && run.skipped_units.length
1318
+ ? `\nSkipped: ${run.skipped_units.map((s) => `#${s.unit_number} (${s.outcome}: ${s.reason})`).join("; ")}`
1319
+ : "";
1320
+ const failText = run.status === "failed"
1321
+ ? `\nFailed step: ${run.failed_step ?? "gate"}${run.attributed_unit_number ? `; culprit WU #${run.attributed_unit_number} (${run.attribution_method ?? "attributed"})` : ""}${run.error ? `\nError: ${run.error}` : ""}`
1322
+ : "";
1323
+ const entryLines = entries.map((e) => ({
1324
+ unit: `#${e.work_unit_number}`,
1325
+ status: e.status,
1326
+ head: String(e.approved_head ?? "-").slice(0, 9),
1327
+ owner: e.owner_name ?? "-",
1328
+ reason: e.reason ?? "-",
1329
+ }));
1330
+ out.print(`Merge train run ${run.id} [${run.status}] on ${run.target_branch}${run.machine ? ` (${run.machine})` : ""}${run.merged_sha ? ` -> ${run.merged_sha.slice(0, 9)}` : ""}${run.closed_units?.length ? `\nClosed: ${run.closed_units.map((n) => `#${n}`).join(", ")}` : ""}${skippedText}${failText}${run.log_evidence_id ? `\nLog: evidence:${run.log_evidence_id}` : ""}${entryLines.length ? `\n${table(entryLines, ["unit", "status", "head", "owner", "reason"])}` : ""}`, detail);
1331
+ return;
1332
+ }
1333
+ const qs = new URLSearchParams();
1334
+ const target = str(p.flags, "target")?.trim();
1335
+ const limit = str(p.flags, "limit")?.trim();
1336
+ if (target)
1337
+ qs.set("target", target);
1338
+ if (limit)
1339
+ qs.set("limit", limit);
1340
+ const suffix = qs.toString() ? `?${qs}` : "";
1341
+ const res = await client.call("GET", `/projects/${project}/merge-train${suffix}`);
1342
+ const queueRows = res.queue.map((e) => ({
1343
+ unit: `#${e.work_unit_number}`,
1344
+ status: e.status,
1345
+ target: e.target_branch,
1346
+ head: String(e.approved_head ?? "-").slice(0, 9),
1347
+ source: e.enqueue_source,
1348
+ owner: e.owner_name ?? "-",
1349
+ title: String(e.title ?? "").slice(0, 48),
1350
+ }));
1351
+ const activeLine = res.active_run
1352
+ ? `Active run: ${res.active_run.id} [${res.active_run.status}] on ${res.active_run.target_branch}${res.active_run.machine ? ` (${res.active_run.machine})` : ""} · ${res.active_run.queued_units?.length ?? 0} queued`
1353
+ : "Active run: none";
1354
+ const historyLines = res.history.slice(0, 10).map((r) => ` ${r.created_at.slice(0, 16).replace("T", " ")} ${r.id.slice(0, 8)} [${r.status}] ${r.target_branch}${r.merged_sha ? ` ${r.merged_sha.slice(0, 9)}` : ""}${r.closed_units?.length ? ` closed ${r.closed_units.map((n) => `#${n}`).join(",")}` : ""}${r.failed_step ? ` failed at ${r.failed_step}` : ""}${r.attributed_unit_number ? ` (send back WU #${r.attributed_unit_number})` : ""}`);
1355
+ out.print(`Merge train for ${res.project} (target ${res.target_branch}, merged_by ${res.policy?.merged_by ?? "owner"}, auto_enqueue ${res.policy?.auto_enqueue ? "yes" : "no"})\n${activeLine}\n${queueRows.length ? table(queueRows, ["unit", "status", "target", "head", "source", "owner", "title"]) : "(train queue is empty)"}${historyLines.length ? `\nRecent runs:\n${historyLines.join("\n")}` : ""}`, res);
1356
+ return;
1357
+ }
1358
+ if (action === "enqueue") {
1359
+ const unitNumber = Number(p.positionals[3]);
1360
+ if (!Number.isInteger(unitNumber) || unitNumber < 1)
1361
+ throw new CliError("usage", "wu train enqueue <n> [--head <sha>]");
1362
+ const head = str(p.flags, "head")?.trim();
1363
+ const r = await client.call("POST", `/projects/${project}/merge-train/enqueue`, {
1364
+ unit: unitNumber,
1365
+ ...(head ? { head } : {}),
1366
+ });
1367
+ 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);
1368
+ return;
1369
+ }
1370
+ if (action === "remove") {
1371
+ const unitNumber = Number(p.positionals[3]);
1372
+ if (!Number.isInteger(unitNumber) || unitNumber < 1)
1373
+ throw new CliError("usage", 'wu train remove <n> [--reason "..."]');
1374
+ const reason = str(p.flags, "reason")?.trim();
1375
+ const r = await client.call("POST", `/projects/${project}/merge-train/remove`, {
1376
+ unit: unitNumber,
1377
+ ...(reason ? { reason } : {}),
1378
+ });
1379
+ out.print(r.removed ? `Removed WU #${unitNumber} from the merge train queue.` : `WU #${unitNumber} was not in the active merge train queue.`, r);
1380
+ return;
1381
+ }
1382
+ if (action === "run") {
1383
+ const target = str(p.flags, "target")?.trim();
1384
+ const machine = str(p.flags, "on")?.trim();
1385
+ const r = await client.call("POST", `/projects/${project}/merge-train/run`, {
1386
+ ...(target ? { target } : {}),
1387
+ ...(machine ? { machine } : {}),
1388
+ });
1389
+ 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);
1390
+ return;
1391
+ }
1392
+ if (action === "resolve") {
1393
+ await resolveTrainClaimCommand(client, project, p.positionals[3]?.trim() ?? "", p, out, 'wu train resolve <run-id> --outcome pushed|not-pushed [--merged <sha>] --note "..."');
1394
+ return;
1395
+ }
1396
+ throw new CliError("usage", "wu train <list|status [<run-id>]|enqueue <n>|remove <n>|run|resolve <run-id>>");
1397
+ }
1284
1398
  case "abandon": {
1285
1399
  const r = await client.call("POST", `${base}/${num()}/abandon`, { note: str(p.flags, "note") ?? "" });
1286
1400
  // Same as done: a clean worktree goes (its branch, and every commit on it, stays).
@@ -1524,7 +1638,7 @@ export async function wu(p, out) {
1524
1638
  return;
1525
1639
  }
1526
1640
  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");
1641
+ throw new CliError("usage", "wu open|assign|lands-with|branch|start [--branch b|--here]|decline|submit|approve|changes|classify|tags|merge <n>|merge status <n>|train <list|status|enqueue|remove|run>|done [--keep-worktree]|abandon|note|ask|rule|sendback-rule|propose|show|list|stalled");
1528
1642
  }
1529
1643
  }
1530
1644
  /** Queued units have no owner; ask the API to reject before any local worktree is made. */
package/dist/git.js CHANGED
@@ -6,7 +6,7 @@ import { CliError } from "./errors.js";
6
6
  import { configDirectory } from "./directories.js";
7
7
  export const PRUNE_STATUS_TIMEOUT_MS = 30_000;
8
8
  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 }) });
9
+ 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
10
  const errorCode = r.error?.code;
11
11
  if (errorCode === "ETIMEDOUT" || (r.error && /timed out/i.test(r.error.message))) {
12
12
  throw new CliError("timeout", `git status timed out after ${timeoutMs} ms in worktree ${cwd}`);
@@ -17,24 +17,25 @@ function status(cwd, timeoutMs) {
17
17
  }
18
18
  /** Local, bounded proof that a session checkout is clean and every commit is reachable from a remote. */
19
19
  export function sessionCheckoutFacts(cwd, options = {}) {
20
+ const gitDir = git(["rev-parse", "--absolute-git-dir"], cwd);
20
21
  const branchResult = spawnSync("git", ["rev-parse", "--abbrev-ref", "HEAD"], {
21
- cwd, encoding: "utf8", stdio: ["ignore", "pipe", "ignore"], maxBuffer: 1024 * 1024, timeout: 5_000,
22
+ cwd, env: gitMetadataEnv(cwd), encoding: "utf8", stdio: ["ignore", "pipe", "ignore"], maxBuffer: 1024 * 1024, timeout: 5_000,
22
23
  });
23
24
  const statusResult = spawnSync("git", ["status", "--porcelain"], {
24
- cwd, encoding: "utf8", stdio: ["ignore", "pipe", "ignore"], maxBuffer: 16 * 1024 * 1024, timeout: 5_000,
25
+ cwd, env: gitMetadataEnv(cwd), encoding: "utf8", stdio: ["ignore", "pipe", "ignore"], maxBuffer: 16 * 1024 * 1024, timeout: 5_000,
25
26
  });
26
- const fetched = options.verifyOrigin ? spawnSync("git", ["fetch", "--prune", "origin"], {
27
+ const fetched = options.verifyOrigin && gitDir ? spawnSync("git", ["--git-dir", gitDir, "--work-tree", cwd, "fetch", "--prune", "origin"], {
27
28
  cwd, encoding: "utf8", stdio: ["ignore", "ignore", "ignore"], timeout: 30_000,
28
- env: { ...process.env, GIT_TERMINAL_PROMPT: "0" },
29
+ env: gitTransportEnv(),
29
30
  }) : null;
30
31
  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,
32
+ cwd, env: gitMetadataEnv(cwd), encoding: "utf8", stdio: ["ignore", "pipe", "ignore"], maxBuffer: 1024 * 1024, timeout: 5_000,
32
33
  });
33
34
  const statusError = statusResult.error;
34
35
  const remoteError = remoteResult.error;
35
36
  const statusOk = statusResult.status === 0;
36
37
  const countText = remoteResult.stdout.trim();
37
- const count = (!fetched || fetched.status === 0) && remoteResult.status === 0 && /^\d+$/.test(countText) ? Number(countText) : null;
38
+ const count = (!options.verifyOrigin || fetched?.status === 0) && remoteResult.status === 0 && /^\d+$/.test(countText) ? Number(countText) : null;
38
39
  const entries = statusOk ? statusResult.stdout.split("\n").filter(Boolean) : [];
39
40
  const untracked = statusOk ? entries.some((line) => line.startsWith("??")) : null;
40
41
  const uncommitted = statusOk ? entries.some((line) => !line.startsWith("??")) : null;
@@ -42,7 +43,7 @@ export function sessionCheckoutFacts(cwd, options = {}) {
42
43
  const branch = branchResult.status === 0 && branchResult.stdout.trim() ? branchResult.stdout.trim() : null;
43
44
  const branchError = branchResult.error;
44
45
  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);
46
+ const errors = [statusError?.code ?? (statusOk ? null : `git status exited ${statusResult.status}`), options.verifyOrigin && !gitDir ? "git fetch origin failed: checkout could not be resolved" : 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);
46
47
  return {
47
48
  branch,
48
49
  clean,
@@ -56,11 +57,47 @@ export function sessionCheckoutFacts(cwd, options = {}) {
56
57
  function git(args, cwd) {
57
58
  // Large enough for `git status` on a big repo with every file changed (ester: 226k files, 25 MB);
58
59
  // 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 });
60
+ const r = spawnSync("git", args, { cwd, env: gitMetadataEnv(cwd), encoding: "utf8", stdio: ["ignore", "pipe", "ignore"], maxBuffer: 512 * 1024 * 1024 });
60
61
  if (r.status !== 0)
61
62
  return null;
62
63
  return r.stdout.trim();
63
64
  }
65
+ /**
66
+ * Repository facts describe the checkout at `cwd`, never a different repo selected by the
67
+ * session's Git environment. In particular, daemon-launched sessions may carry GIT_CONFIG_*
68
+ * entries for credential helpers and safe.directory. Keep that full environment for network Git
69
+ * operations (fetch/push), but isolate local inspection from all inherited Git overrides.
70
+ */
71
+ function gitMetadataEnv(cwd) {
72
+ const env = {};
73
+ for (const [key, value] of Object.entries(process.env)) {
74
+ if (!key.startsWith("GIT_"))
75
+ env[key] = value;
76
+ }
77
+ env.GIT_CONFIG_NOSYSTEM = "1";
78
+ env.GIT_CONFIG_GLOBAL = process.platform === "win32" ? "NUL" : "/dev/null";
79
+ env.GIT_CONFIG_COUNT = "1";
80
+ env.GIT_CONFIG_KEY_0 = "safe.directory";
81
+ env.GIT_CONFIG_VALUE_0 = cwd;
82
+ return env;
83
+ }
84
+ /** Keep credential config for transport, but pin repository discovery to the explicit cwd/git-dir. */
85
+ function gitTransportEnv() {
86
+ const env = { ...process.env, GIT_TERMINAL_PROMPT: "0" };
87
+ for (const key of [
88
+ "GIT_DIR", "GIT_WORK_TREE", "GIT_COMMON_DIR", "GIT_INDEX_FILE", "GIT_INDEX_VERSION",
89
+ "GIT_OBJECT_DIRECTORY", "GIT_ALTERNATE_OBJECT_DIRECTORIES", "GIT_CEILING_DIRECTORIES",
90
+ "GIT_DISCOVERY_ACROSS_FILESYSTEM", "GIT_NAMESPACE", "GIT_PREFIX", "GIT_SHALLOW_FILE",
91
+ "GIT_REPLACE_REF_BASE",
92
+ ])
93
+ delete env[key];
94
+ return env;
95
+ }
96
+ /** Pin remote Git commands to the checkout discovered under cwd-scoped metadata rules. */
97
+ function gitRepositoryArgs(cwd) {
98
+ const gitDir = git(["rev-parse", "--absolute-git-dir"], cwd);
99
+ return gitDir ? ["--git-dir", gitDir, "--work-tree", cwd] : [];
100
+ }
64
101
  /** Read from the real repo state every call. Never cached. */
65
102
  export function collectAuto(opts) {
66
103
  const cwd = opts.cwd ?? process.cwd();
@@ -88,7 +125,7 @@ export function mergeFacts(cwd, worktree) {
88
125
  const base = ["main", "master"].find((b) => git(["rev-parse", "--verify", "-q", `${b}^{commit}`], cwd) !== null) ?? null;
89
126
  if (!base)
90
127
  return { repo, base: null, merged: null, ahead: null };
91
- const merged = spawnSync("git", ["merge-base", "--is-ancestor", "HEAD", base], { cwd, stdio: "ignore" }).status === 0;
128
+ const merged = spawnSync("git", ["merge-base", "--is-ancestor", "HEAD", base], { cwd, env: gitMetadataEnv(cwd), stdio: "ignore" }).status === 0;
92
129
  const count = git(["rev-list", "--count", `${base}..HEAD`], cwd);
93
130
  return { repo, base, merged, ahead: count === null ? null : Number(count) };
94
131
  }
@@ -180,7 +217,7 @@ export function machineIdentityForAgent(savedMachine, env = process.env, host =
180
217
  export function isAncestor(ancestor, ref, cwd = process.cwd()) {
181
218
  if (git(["rev-parse", "--verify", "-q", `${ancestor}^{commit}`], cwd) === null || git(["rev-parse", "--verify", "-q", `${ref}^{commit}`], cwd) === null)
182
219
  return null;
183
- const r = spawnSync("git", ["merge-base", "--is-ancestor", ancestor, ref], { cwd, stdio: "ignore" });
220
+ const r = spawnSync("git", ["merge-base", "--is-ancestor", ancestor, ref], { cwd, env: gitMetadataEnv(cwd), stdio: "ignore" });
184
221
  return r.status === 0;
185
222
  }
186
223
  /** Confirm an evidence-only unit branch contains no commits missing from its configured target. */
@@ -621,14 +658,15 @@ export function remoteTrackingRefContainsCommit(branch, advertisedTip, sha, cwd
621
658
  /** Fetch origin, then report a remote branch containing the submitted commit. */
622
659
  export function findRemoteCommitBranch(sha, localBranch, cwd = process.cwd(), remote = "origin") {
623
660
  const checkedRef = `${remote}/${localBranch}`;
661
+ const repositoryArgs = gitRepositoryArgs(cwd);
624
662
  // Submission only needs current remote-tracking refs. Force pruning off even when user/repo
625
663
  // 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 });
664
+ const fetched = spawnSync("git", [...repositoryArgs, "-c", "fetch.prune=false", "-c", `remote.${remote}.prune=false`, "fetch", remote], { cwd, env: gitTransportEnv(), encoding: "utf8", timeout: 120_000 });
627
665
  if (fetched.status !== 0) {
628
666
  const detail = (fetched.stderr || fetched.stdout || `git fetch ${remote} exited with status ${fetched.status ?? "unknown"}`).trim();
629
667
  return { remoteBranch: null, advertisedTip: null, checkedRef, checked: false, reason: `git fetch ${remote} failed: ${detail}` };
630
668
  }
631
- const advertised = spawnSync("git", ["ls-remote", "--heads", remote], { cwd, encoding: "utf8", timeout: 30_000 });
669
+ const advertised = spawnSync("git", [...repositoryArgs, "ls-remote", "--heads", remote], { cwd, env: gitTransportEnv(), encoding: "utf8", timeout: 30_000 });
632
670
  if (advertised.status !== 0) {
633
671
  const detail = (advertised.stderr || advertised.stdout || `git ls-remote ${remote} exited with status ${advertised.status ?? "unknown"}`).trim();
634
672
  return { remoteBranch: null, advertisedTip: null, checkedRef, checked: false, reason: `git ls-remote ${remote} failed: ${detail}` };
@@ -650,7 +688,7 @@ export function findRemoteCommitBranch(sha, localBranch, cwd = process.cwd(), re
650
688
  // against their advertised tips. Checking every advertised branch one by one ran 1,542 git
651
689
  // processes for 771 branches (238 s on 2026-11-21), long enough for the API connection opened
652
690
  // 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 });
691
+ 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
692
  if (containing.status !== 0) {
655
693
  const detail = (containing.stderr || containing.stdout || `git for-each-ref exited with status ${containing.status ?? "unknown"}`).trim();
656
694
  return { remoteBranch: null, advertisedTip: null, checkedRef, checked: false, reason: `git for-each-ref --contains ${sha} failed: ${detail}` };
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