benignswarm 0.12.147 → 0.12.149

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
@@ -16,7 +16,7 @@ export const STRING_FLAGS = [
16
16
  "parent", "parent-item", "channel", "statuses", "assign", "if-status", "status", "exec", "interval",
17
17
  "requeue-after", "unacked-after", "category", "command", "command-pattern", "follow-delay", "startup-jitter-seconds", "env", "scope",
18
18
  "scope-file", "scope-from", "append", "pr", "note", "note-file", "add", "remove", "merged", "tag",
19
- "activity", "max-unanswered", "to", "replay-of", "branch", "effort", "max-budget-usd", "by", "target", "lands-with",
19
+ "activity", "max-unanswered", "to", "replay-of", "branch", "base", "effort", "max-budget-usd", "by", "target", "lands-with",
20
20
  "milestone", "file", "exit", "depends-on", "default-tags", "source", "on", "partial", "question", "ruling",
21
21
  "gaps", "unit", "units", "blocks", "sla", "takeover", "stall", "max-open", "max-in-progress", "require-scope",
22
22
  "require-evidence", "default-approver", "merged-by", "integrator-role", "require-rebased", "require-merge-commit",
@@ -45,7 +45,7 @@ export const BOOL_FLAGS = [
45
45
  "pending", "force", "no-hooks", "yes", "open", "bind-here", "peek", "once", "launchd", "full", "no-bind",
46
46
  "all", "here", "keep-worktree", "prune", "abandon", "defer", "hold", "clear", "met", "shared", "archive",
47
47
  "approve", "turn", "service", "print-hooks", "create", "rotate", "drain", "codex-userns", "bwrap-userns", "agy-userns", "print-apparmor",
48
- "cancel", "rerun", "confirmed", "refuted", "no-source", "confirm-bypass-signal", "assessment-only",
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
50
  "in-container", "retrieve-ec2", "stdin", "context-confirmed", "confirm-compatible", "move-provisioned", "provisioned", "no-commits-beyond-target",
51
51
  ];
@@ -25,7 +25,18 @@ function commandUsageLines(help) {
25
25
  }
26
26
  function commandAlternatives(line) {
27
27
  const text = line.trim().replace(/^b9s(?:-admin)?\s+/, "");
28
- const words = text.split(/\s+/);
28
+ // A placeholder may contain spaces (`<id or key>`, `"some text"`): it is one argument, so join
29
+ // its words first. Split apart, `or` read as a literal subcommand and `answer <id or key>
30
+ // --approve` matched no usage line, so --approve was refused (2026-11-21).
31
+ const words = [];
32
+ for (const word of text.split(/\s+/)) {
33
+ const open = words.at(-1);
34
+ if (open !== undefined && ((open.startsWith("<") && !open.endsWith(">")) || (open.startsWith("\"") && (open.length === 1 || !open.endsWith("\""))))) {
35
+ words[words.length - 1] = `${open} ${word}`;
36
+ }
37
+ else
38
+ words.push(word);
39
+ }
29
40
  const paths = [[]];
30
41
  for (const word of words) {
31
42
  if (word.startsWith("-") || word === "|" || word.startsWith("("))
@@ -57,13 +57,23 @@ function stopTree(signal = "SIGTERM") {
57
57
  return;
58
58
  stopping = true;
59
59
  signalTree(signal);
60
+ // Keep the supervisor alive until resistant descendants receive SIGKILL.
61
+ // An unreferenced timer can disappear when the shell exits, leaving them alive.
60
62
  killTimer = setTimeout(() => signalTree("SIGKILL"), 5_000);
61
- killTimer.unref?.();
63
+ }
64
+ for (const output of [process.stdout, process.stderr]) {
65
+ output.on("error", (error) => {
66
+ if (error.code !== "EPIPE")
67
+ throw error;
68
+ task?.stdout?.unpipe(output);
69
+ task?.stderr?.unpipe(output);
70
+ });
62
71
  }
63
72
  for (const signal of ["SIGINT", "SIGTERM", "SIGHUP"])
64
73
  process.on(signal, () => stopTree(signal));
65
74
  const control = createReadStream("", { fd: 3 });
66
75
  control.on("end", () => stopTree());
76
+ control.on("close", () => stopTree());
67
77
  control.resume();
68
78
  function finish(exitCode, startFailure) {
69
79
  if (killTimer)
@@ -36,7 +36,7 @@ export async function runUnderLock(o, deps) {
36
36
  throw new CliError('usage', 'B9S_LOCK_SILENCE_SECONDS must be an integer from 1 to 86400');
37
37
  const label = commandLabel(o.command);
38
38
  const base = `/projects/${o.project}/locks/${o.lock}`;
39
- const acquireBody = { unit: o.unit, note: o.note ?? label, shared: o.shared, machine: o.machine, job_token: o.token, lock_run: true };
39
+ const acquireBody = { unit: o.unit, note: o.note ?? label, shared: o.shared, machine: o.machine, job_token: o.token, lock_run: true, process_pid: process.pid };
40
40
  const release = async (completion) => {
41
41
  try {
42
42
  const result = await deps.call("POST", `${base}/release`, { shared: o.shared, machine: o.shared ? undefined : o.machine, job_token: o.token, ...completion });
@@ -74,7 +74,7 @@ export async function runUnderLock(o, deps) {
74
74
  }
75
75
  let code;
76
76
  try {
77
- await deps.call("POST", `${base}/running`, { shared: o.shared, machine: o.machine, job_token: o.token, command: label, silence_seconds: seconds });
77
+ await deps.call("POST", `${base}/running`, { shared: o.shared, machine: o.machine, job_token: o.token, command: label, process_pid: process.pid, silence_seconds: seconds });
78
78
  deps.log(`job ${o.jobId} holds ${o.lock}${slot === undefined ? "" : ` slot ${slot}`}; running: ${label}`);
79
79
  let latest;
80
80
  let pending;
@@ -88,7 +88,7 @@ export async function runUnderLock(o, deps) {
88
88
  const timer = setInterval(flush, Math.min(30000, Math.max(250, seconds * 1000 / 4)));
89
89
  let result;
90
90
  try {
91
- result = await deps.run(o.command, { lock: o.lock, jobId: o.jobId, ...(slot === undefined ? {} : { slot }), ...(o.lock === "ux-browser" ? { heartbeat: () => deps.call("POST", `${base}/running`, { shared: o.shared, machine: o.machine, job_token: o.token, command: label }) } : {}), 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); } });
91
+ 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 }), 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); } });
92
92
  }
93
93
  finally {
94
94
  clearInterval(timer);
@@ -96,7 +96,7 @@ export async function runUnderLock(o, deps) {
96
96
  await pending;
97
97
  }
98
98
  code = typeof result === "number" ? result : result.exit_code;
99
- const released = await release(typeof result === "number" ? { exit_code: code } : { exit_code: code, ...(result.gate_output ? { gate_output: true } : {}), ...(result.verified_baseline_sha ? { verified_baseline_sha: result.verified_baseline_sha } : {}), ...(result.tested_tree_sha ? { tested_tree_sha: result.tested_tree_sha } : {}), ...(result.timeout_reason ? { timeout_reason: result.timeout_reason } : {}) });
99
+ const released = await release(typeof result === "number" ? { exit_code: code } : { exit_code: code, ...(result.gate_output ? { gate_output: true } : {}), ...(result.verified_baseline_sha ? { verified_baseline_sha: result.verified_baseline_sha } : {}), ...(result.tested_tree_sha ? { tested_tree_sha: result.tested_tree_sha } : {}), ...(result.timeout_reason && code !== 0 ? { timeout_reason: result.timeout_reason } : {}) });
100
100
  if (released.gate_receipt?.recorded === false) {
101
101
  const configured = released.gate_receipt.configured_command;
102
102
  deps.log(`Gate receipt not recorded: ${released.gate_receipt.reason ?? "the reported gate result was refused"}.${configured ? ` Use the configured command: ${configured}` : " No complete gate command is configured."}`);
@@ -133,8 +133,8 @@ export function createGateMarkerScanner() {
133
133
  if (/^gate:/i.test(line))
134
134
  gateOutput = true;
135
135
  const timeoutMatch = line.match(/^gate: timed out in (.+)$/);
136
- if (timeoutMatch && !timeoutReason)
137
- timeoutReason = `timed out in ${timeoutMatch[1]}`;
136
+ if (timeoutMatch)
137
+ timeoutReason = `timed out in ${timeoutMatch[1]}`; // the last one is gate.sh's own; earlier ones can be test output
138
138
  const baselineMatch = line.match(/^gate: verified baseline ([0-9a-f]{40})\s*$/i);
139
139
  // The gate's header is authoritative. Tests run later in the same process
140
140
  // may print fixture marker lines; they must not replace the real SHAs.
@@ -227,8 +227,8 @@ export function processDeps(call, log, heartbeatIntervalMs = 15_000) {
227
227
  if (/^gate:/i.test(line))
228
228
  gateOutput = true;
229
229
  const timeoutMatch = line.match(/^gate: timed out in (.+)$/);
230
- if (timeoutMatch && !timeoutReason)
231
- timeoutReason = `timed out in ${timeoutMatch[1]}`;
230
+ if (timeoutMatch)
231
+ timeoutReason = `timed out in ${timeoutMatch[1]}`; // the last one is gate.sh's own; earlier ones can be test output
232
232
  const baselineMatch = line.match(/^gate: verified baseline ([0-9a-f]{40})\s*$/i);
233
233
  // The gate's header is authoritative. Tests run later in the same process
234
234
  // may print fixture marker lines; they must not replace the real SHAs.
@@ -1711,7 +1711,7 @@ export async function reconcile(m, log, reportIntervalSeconds = 30, deps) {
1711
1711
  // a session error while it retries; successful preparation clears it without a restart.
1712
1712
  const worktreeFault = readState(s.agent, agentStateEnv).worktree_fault;
1713
1713
  if (worktreeFault) {
1714
- out.push({ id: s.id, state: "error", dir: s.dir, thread: th, watcher: watcherState, error: worktreeFault.message });
1714
+ out.push({ id: s.id, state: "error", dir: s.dir, thread: th, watcher: watcherState, error: worktreeFault.message, worktree_fault_unit: worktreeFault.unit });
1715
1715
  continue;
1716
1716
  }
1717
1717
  // A watcher that exits at every start (a corrupt state file after the disk filled) is
@@ -404,7 +404,7 @@ export async function watch(p, out, dependencies = {}) {
404
404
  await (dependencies.wait ?? waitIntervalOrStop)(watchPollMs(interval), stopped);
405
405
  continue;
406
406
  }
407
- if (e.code === "unit_worktree_diverged" && !once)
407
+ if ((e.code === "unit_worktree_diverged" || e.code === "unit_worktree_prepare_failed") && !once)
408
408
  log(e.message);
409
409
  else
410
410
  throw e;
@@ -553,9 +553,12 @@ export async function prepareTurnWorktree(name, binding, allowSuperseded = false
553
553
  const { worktree_fault: _resolved, ...rest } = state;
554
554
  return rest;
555
555
  });
556
+ let preparedUnit = null;
557
+ let worktreePrepared = false;
556
558
  try {
557
559
  const record = await client.call("GET", base);
558
560
  const unit = record.unit;
561
+ preparedUnit = unit;
559
562
  if (!unit || unit.number !== binding.work_unit_number)
560
563
  throw new Error("the server did not return the requested work unit");
561
564
  if (unit.owner_name !== creds.agent) {
@@ -578,6 +581,16 @@ export async function prepareTurnWorktree(name, binding, allowSuperseded = false
578
581
  const process = await client.call("GET", `/projects/${encodeURIComponent(project)}/process`);
579
582
  const { contextDecisionForStart, prepareWorktreeForWatcher } = await import("./wu.js");
580
583
  const prepared = withAgentEnv(agentRef(creds), () => prepareWorktreeForWatcher(binding.work_unit_number, unit, process.process?.definition, process.checkout?.exclude ?? []));
584
+ worktreePrepared = true;
585
+ const hadFault = readState(name).worktree_fault?.project === project && readState(name).worktree_fault?.unit === binding.work_unit_number;
586
+ const clearServerWorktreeFault = async () => {
587
+ if (hadFault || unit.worktree_fault) {
588
+ try {
589
+ await client.call("POST", `${base}/worktree-fault`, { clear: true });
590
+ }
591
+ catch { }
592
+ }
593
+ };
581
594
  const restrictedWorkspaceWrite = dependencies.antigravityRuntime?.sandbox === "workspace-write" || dependencies.claudeRuntime?.sandbox === "workspace-write";
582
595
  const startedUnitRecovery = unit.status !== "assigned" && prepared.recoveryRequired;
583
596
  if (prepared.needsRecord && restrictedWorkspaceWrite && startedUnitRecovery) {
@@ -602,9 +615,11 @@ export async function prepareTurnWorktree(name, binding, allowSuperseded = false
602
615
  if (verified.unit?.status !== "open" || verified.unit?.branch !== location.branch || verified.unit?.head !== location.head || verified.unit?.worktree !== prepared.path) {
603
616
  throw new Error("server did not persist the prepared branch, commit and worktree exactly; refusing to launch the turn");
604
617
  }
618
+ await clearServerWorktreeFault();
605
619
  clearWorktreeFault();
606
620
  return { number: binding.work_unit_number, path: prepared.path, branch: location.branch, status: verified.unit.status, homeChanges: prepared.homeChanges, homeCommits: prepared.homeCommits, needsRecord: false };
607
621
  }
622
+ await clearServerWorktreeFault();
608
623
  clearWorktreeFault();
609
624
  return { number: binding.work_unit_number, path: prepared.path, branch: prepared.branch, status: unit.status, homeChanges: prepared.homeChanges, homeCommits: prepared.homeCommits, needsRecord: prepared.needsRecord };
610
625
  }
@@ -615,7 +630,7 @@ export async function prepareTurnWorktree(name, binding, allowSuperseded = false
615
630
  const prior = state.worktree_fault;
616
631
  if (prior?.project === project && prior.unit === binding.work_unit_number && prior.assignment === binding.assignment_event_id && prior.message === fault.message)
617
632
  return;
618
- return { ...state, worktree_fault: { project, unit: binding.work_unit_number, assignment: binding.assignment_event_id, message: fault.message, at: new Date().toISOString() } };
633
+ return { ...state, worktree_fault: { project, unit: binding.work_unit_number, assignment: binding.assignment_event_id, message: fault.message, branch: fault.branch, at: new Date().toISOString() } };
619
634
  });
620
635
  try {
621
636
  await client.call("POST", `${base}/head-divergence`, { recorded_head: fault.recordedHead, branch: fault.branch, branch_head: fault.branchHead, message: fault.message });
@@ -625,7 +640,34 @@ export async function prepareTurnWorktree(name, binding, allowSuperseded = false
625
640
  }
626
641
  throw fault;
627
642
  }
628
- throw new CliError("unit_worktree_prepare_failed", `watcher could not prepare the worktree for WU #${binding.work_unit_number}; no turn was started and the unit remains unchanged: ${error.message}`);
643
+ const prepareErr = error;
644
+ const rawMessage = error instanceof Error ? error.message : String(error);
645
+ const faultMessage = prepareErr.code === "unit_worktree_prepare_failed"
646
+ ? rawMessage
647
+ : `watcher could not prepare the worktree for WU #${binding.work_unit_number}; no turn was started and the unit remains unchanged: ${rawMessage}`;
648
+ const branch = prepareErr.details?.branch ?? preparedUnit?.branch ?? null;
649
+ const recordedBase = prepareErr.details?.recordedBase ?? preparedUnit?.branch_base ?? preparedUnit?.target ?? null;
650
+ if (!worktreePrepared) {
651
+ updateState(name, (state) => {
652
+ const prior = state.worktree_fault;
653
+ if (prior?.project === project && prior.unit === binding.work_unit_number && prior.assignment === binding.assignment_event_id && prior.message === faultMessage && (prior.branch ?? null) === branch)
654
+ return;
655
+ return { ...state, worktree_fault: { project, unit: binding.work_unit_number, assignment: binding.assignment_event_id, message: faultMessage, branch, at: new Date().toISOString() } };
656
+ });
657
+ try {
658
+ await client.call("POST", `${base}/worktree-fault`, {
659
+ code: "unit_worktree_prepare_failed",
660
+ message: faultMessage.slice(0, 2000),
661
+ ...(branch ? { branch } : {}),
662
+ ...(recordedBase ? { recorded_base: recordedBase } : {}),
663
+ assignment_event_id: binding.assignment_event_id,
664
+ });
665
+ }
666
+ catch {
667
+ // Local fault state and error propagation remain active; next poll retries reporting cleanly.
668
+ }
669
+ }
670
+ throw new CliError("unit_worktree_prepare_failed", faultMessage);
629
671
  }
630
672
  }
631
673
  /** Recheck the fault's own assignment even when the wake has no current unit binding. */
@@ -10,7 +10,7 @@ import { readState, updateState } from "../state.js";
10
10
  import { codexRollout, sessionsOf } from "../sessions.js";
11
11
  import { claudeSessionWithHookMetadata, sessionCompactions, sessionContext, sessionStart, sessionUsage } from "../usage.js";
12
12
  import { CliError, WrittenReceiptMismatchError } from "../errors.js";
13
- import { branchAndHead, commitAtTime, defaultMachine, ensureReviewWorktree, ensureWorktree, fetchRef, fetchRemoteBranch, findRemoteCommitBranch, formatRemoteCommitFailure, formatRemoteCommitSuccess, fullSha, isAncestor, isShaBranchName, removeWorktreeIfClean, repoName, repoParent, symbolicBranch, verifyMergedCommit, verifyNoCommitsBeyondTarget, verifyUnitHeadOnOrigin, worktreeForBranch, worktreeState } from "../git.js";
13
+ import { branchAndHead, commitAtTime, defaultMachine, ensureReviewWorktree, ensureWorktree, fetchRef, fetchRemoteBranch, findRemoteCommitBranch, formatRemoteCommitFailure, formatRemoteCommitSuccess, fullSha, hasRemote, inspectRemoteBranch, isAncestor, isShaBranchName, pushBranchToOrigin, removeWorktreeIfClean, repoName, repoParent, symbolicBranch, verifyMergedCommit, verifyNoCommitsBeyondTarget, verifyUnitHeadOnOrigin, worktreeForBranch, worktreeState } from "../git.js";
14
14
  import { join, resolve } from "node:path";
15
15
  import { formatStepRules, table } from "../output.js";
16
16
  import { restoreRecoveryArchive, sha256 as recoverySha256 } from "../recovery-archive.js";
@@ -591,7 +591,12 @@ export async function wu(p, out) {
591
591
  u.operator_hold ? ` ON HOLD by ${u.operator_hold.by}: ${u.operator_hold.note} (no verdict and no merge until the owner resubmits or it is released)` : null,
592
592
  u.question ? ` QUESTION for ${u.question.level === "expert" ? `a ${u.question.roles.join(" or ")}` : "the operator"} (asked by ${u.question.asked_by}${u.question.passed_by ? `, passed up by ${u.question.passed_by}` : ""}): ${u.question.text}` : null,
593
593
  u.evidence_claims?.total ? ` evidence claims: ${u.evidence_claims.confirmed} confirmed / ${u.evidence_claims.refuted} refuted / ${u.evidence_claims.unchecked} unchecked\n${u.evidence_claims.items.map((claim) => ` [${claim.state}] ${claim.filename}: ${claim.claim}${claim.verifier_name ? ` — ${claim.verifier_name}${claim.note ? `: ${claim.note}` : ""}` : ""}`).join("\n")}` : null,
594
- ` ${u.branch ? `${u.branch}${u.head ? ` @ ${u.head}` : ""}` : "no branch recorded"}${u.worktree ? ` in ${u.worktree.replace(/^\/(Users|home)\/[^/]+\//, "~/")}` : ""}${u.pr_url ? ` · ${u.pr_url}` : ""}${u.merged_sha ? ` · merged ${u.merged_sha}` : ""}${u.evidence.length ? ` · evidence ${u.evidence.map((e) => `evidence:${e}`).join(" ")}` : ""}`,
594
+ (() => {
595
+ const branchMeta = [u.branch_mode, u.branch_base ? `from ${u.branch_base}` : null].filter(Boolean).join(" ");
596
+ const branchText = u.branch ? `${u.branch}${branchMeta ? ` (${branchMeta})` : ""}${u.head ? ` @ ${u.head}` : ""}` : `no branch recorded${u.branch_base ? ` (base ${u.branch_base})` : ""}`;
597
+ return ` ${branchText}${u.worktree ? ` in ${u.worktree.replace(/^\/(Users|home)\/[^/]+\//, "~/")}` : ""}${u.pr_url ? ` · ${u.pr_url}` : ""}${u.merged_sha ? ` · merged ${u.merged_sha}` : ""}${u.evidence.length ? ` · evidence ${u.evidence.map((e) => `evidence:${e}`).join(" ")}` : ""}`;
598
+ })(),
599
+ u.worktree_fault ? ` WORKTREE FAULT (${u.worktree_fault.code}): ${u.worktree_fault.message}` : null,
595
600
  (u.base_scope ?? u.scope) ? ` scope: ${u.base_scope ?? u.scope}` : null,
596
601
  u.scope_amendments?.length ? ` scope amendments:\n${u.scope_amendments.map((amendment) => ` ${amendment.at} ${amendment.author}: ${amendment.text}`).join("\n")}` : null,
597
602
  ].filter(Boolean).join("\n");
@@ -695,11 +700,27 @@ export async function wu(p, out) {
695
700
  throw new CliError("usage", 'wu assign "<title>" --to <agent|auto|queue> --scope "<what it covers and does not>" [--scope-file <path> | --scope-from <n>] [--tags a,b] [--after <n>[,<m>]] [--evidence id] [--replay-of <n>]');
696
701
  const explicitBranch = str(p.flags, "branch") ?? null;
697
702
  assertNotShaBranch(explicitBranch);
703
+ const baseFlag = str(p.flags, "base");
704
+ const continueFlag = bool(p.flags, "continue");
705
+ if (continueFlag && !explicitBranch)
706
+ throw new CliError("usage", "--continue requires --branch <branch>");
698
707
  const scope = await scopeText();
699
708
  const replay = str(p.flags, "replay-of");
700
709
  const clientId = randomUUID();
701
- const r = await client.call("POST", `${base}/assign`, { client_id: clientId, to, title, scope, ...(str(p.flags, "summary") === undefined ? {} : { plain_summary: str(p.flags, "summary") }), tags: unitTags, requires: list("requires"), evidence: list("evidence"), after: afterUnits(), replay_of: replay ? Number(replay) : null, reworks: list("reworks").map(Number), branch: explicitBranch, target: str(p.flags, "target") ?? null, lands_with: parseLandsWith(str(p.flags, "lands-with")), milestone: str(p.flags, "milestone") ?? null, hold: !!p.flags.hold, force: bool(p.flags, "force"), ...(priority ? { priority } : {}), ...(reason === undefined ? {} : { reason }) }, { retries: 3 });
702
- out.print(withRuleText(`${createdReceiptLine(r.unit)}\n${fmt(r.unit)}\n${assignmentDisposition(r.unit, to)}${assignmentGuidanceOutput(r.warnings ?? [])}`, r, "cut"), createdReceipt(r.unit, r));
710
+ const r = await client.call("POST", `${base}/assign`, { client_id: clientId, to, title, scope, ...(str(p.flags, "summary") === undefined ? {} : { plain_summary: str(p.flags, "summary") }), tags: unitTags, requires: list("requires"), evidence: list("evidence"), after: afterUnits(), replay_of: replay ? Number(replay) : null, reworks: list("reworks").map(Number), branch: explicitBranch, ...(baseFlag !== undefined ? { base: baseFlag } : {}), ...(continueFlag ? { continue: true } : {}), target: str(p.flags, "target") ?? null, lands_with: parseLandsWith(str(p.flags, "lands-with")), milestone: str(p.flags, "milestone") ?? null, hold: !!p.flags.hold, force: bool(p.flags, "force"), ...(priority ? { priority } : {}), ...(reason === undefined ? {} : { reason }) }, { retries: 3 });
711
+ const clientWarnings = [];
712
+ if (explicitBranch && baseFlag === undefined && repoName() && hasRemote("origin")) {
713
+ const remoteState = inspectRemoteBranch(explicitBranch);
714
+ if (remoteState.state === "missing") {
715
+ const recordedBase = r.unit?.branch_base ?? r.unit?.target ?? "the project target";
716
+ const warningText = r.unit?.branch_mode === "continue"
717
+ ? `branch ${explicitBranch} does not exist on origin and no --base was given; start will fault until it is pushed from ${recordedBase} or cleared (b9s wu branch ${r.unit.number} --clear)`
718
+ : `branch ${explicitBranch} does not exist on origin and no --base was given; start will create and push it from ${recordedBase}`;
719
+ clientWarnings.push(warningText);
720
+ process.stderr.write(`b9s warning: ${warningText}\n`);
721
+ }
722
+ }
723
+ out.print(withRuleText(`${createdReceiptLine(r.unit)}\n${fmt(r.unit)}\n${assignmentDisposition(r.unit, to)}${assignmentGuidanceOutput([...(r.warnings ?? []), ...clientWarnings])}`, r, "cut"), createdReceipt(r.unit, r));
703
724
  return;
704
725
  }
705
726
  case "park": {
@@ -1201,6 +1222,32 @@ export async function wu(p, out) {
1201
1222
  out.print(fmt(r.unit), r);
1202
1223
  return;
1203
1224
  }
1225
+ case "branch": {
1226
+ const number = num();
1227
+ const clear = bool(p.flags, "clear");
1228
+ const branchArg = p.positionals[3];
1229
+ const reason = str(p.flags, "reason");
1230
+ const baseFlag = str(p.flags, "base");
1231
+ const continueFlag = bool(p.flags, "continue");
1232
+ if (clear && branchArg)
1233
+ throw new CliError("usage", 'pass either <branch> or --clear, not both: b9s wu branch <n> [<branch>] [--clear] [--reason "why"]');
1234
+ if (!clear && !branchArg)
1235
+ throw new CliError("usage", 'b9s wu branch <n> (<branch> --reason "why" | --clear [--reason "why"])');
1236
+ if (clear && continueFlag)
1237
+ throw new CliError("usage", "--continue cannot be combined with --clear");
1238
+ if (!clear)
1239
+ assertNotShaBranch(branchArg, "<branch>");
1240
+ if (!clear && !reason?.trim())
1241
+ throw new CliError("usage", 'wu branch <n> <branch> requires --reason "why"');
1242
+ const r = await client.call("POST", `${base}/${number}/branch`, {
1243
+ ...(clear ? { clear: true } : { branch: branchArg }),
1244
+ ...(reason !== undefined ? { reason } : {}),
1245
+ ...(baseFlag !== undefined ? { base: baseFlag } : {}),
1246
+ ...(continueFlag ? { continue: true } : {}),
1247
+ });
1248
+ out.print(`${fmt(r.unit)}\n${clear ? `Cleared recorded branch for WU #${number}; start creates its unit branch.` : `Recorded branch for WU #${number} set to ${r.unit.branch}.`}`, r);
1249
+ return;
1250
+ }
1204
1251
  case "review": {
1205
1252
  // The reviewer's checkout: the submitted commit, fetched from the remote, in its own worktree.
1206
1253
  const n = num();
@@ -1354,7 +1401,7 @@ export async function wu(p, out) {
1354
1401
  return;
1355
1402
  }
1356
1403
  default:
1357
- throw new CliError("usage", "wu open|assign|lands-with|start [--branch b|--here]|decline|submit|approve|changes|classify|tags|merge <n>|merge status <n>|done [--keep-worktree]|abandon|note|ask|rule|propose|show|list|stalled");
1404
+ 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|propose|show|list|stalled");
1358
1405
  }
1359
1406
  }
1360
1407
  /** Queued units have no owner; ask the API to reject before any local worktree is made. */
@@ -1481,15 +1528,64 @@ export class UnitWorktreeDiverged extends CliError {
1481
1528
  this.branchHead = branchHead;
1482
1529
  }
1483
1530
  }
1531
+ export class UnitWorktreePrepareFailed extends CliError {
1532
+ details;
1533
+ constructor(message, details) {
1534
+ super("unit_worktree_prepare_failed", message);
1535
+ this.details = details;
1536
+ }
1537
+ }
1538
+ function missingBranchFaultMessage(n, branch, recordedBase, reason) {
1539
+ return `WU #${n}: cannot fetch recorded branch ${branch} from origin (recorded base ${recordedBase}): ${reason}. Push the unit branch from ${recordedBase} (git push -u origin ${recordedBase}:refs/heads/${branch} or git push -u origin ${branch}), or clear the recorded branch with: b9s wu branch ${n} --clear`;
1540
+ }
1541
+ function canAutoCreateMissingBranch(unit, explicitBranch) {
1542
+ return !explicitBranch && unit.status === "assigned" && !unit.head && unit.branch_mode === "create";
1543
+ }
1544
+ function resolveRecordedBaseRef(recordedBase, target, n, branch) {
1545
+ if (isShaBranchName(recordedBase)) {
1546
+ let sha = fullSha(recordedBase);
1547
+ if (!sha) {
1548
+ fetchRemoteBranch(target);
1549
+ sha = fullSha(recordedBase);
1550
+ }
1551
+ if (!sha) {
1552
+ spawnSync("git", ["fetch", "--quiet", "origin"], { cwd: process.cwd(), encoding: "utf8", timeout: 120_000 });
1553
+ sha = fullSha(recordedBase);
1554
+ }
1555
+ if (!sha) {
1556
+ throw new UnitWorktreePrepareFailed(`WU #${n}: cannot prepare branch ${branch}: recorded base commit ${recordedBase} was not found locally or on origin. Push ${branch} from ${recordedBase} (git push -u origin ${branch}), or clear the recorded branch with: b9s wu branch ${n} --clear`, { branch, recordedBase });
1557
+ }
1558
+ return sha;
1559
+ }
1560
+ const fetched = fetchRemoteBranch(recordedBase);
1561
+ if (!fetched.ok) {
1562
+ throw new UnitWorktreePrepareFailed(`WU #${n}: cannot prepare branch ${branch} from recorded base ${recordedBase}: ${fetched.reason}. Push ${branch} from ${recordedBase} (git push -u origin ${branch}), or clear the recorded branch with: b9s wu branch ${n} --clear`, { branch, recordedBase });
1563
+ }
1564
+ return fetched.ref;
1565
+ }
1484
1566
  export function prepareWorktreeForWatcher(n, unit, def, exclude = []) {
1485
1567
  if (unit.branch && isShaBranchName(unit.branch))
1486
1568
  throw new CliError("no_branch", `recorded branch ${unit.branch} is a commit identifier, not a branch`, "Record and push the unit branch before retrying.");
1569
+ const target = unit.target ?? def.merge.target_branch;
1570
+ const recordedBase = unit.branch_base ?? target;
1487
1571
  if (unit.branch && !worktreeForBranch(unit.branch) && fullSha(`refs/heads/${unit.branch}`)) {
1488
- const remote = fetchRemoteBranch(unit.branch);
1489
- if (!remote.ok)
1490
- throw new CliError("no_branch", `cannot fetch recorded branch ${unit.branch} from origin: ${remote.reason}`, "Push the unit branch from the original checkout and retry.");
1491
- if (fullSha(`refs/heads/${unit.branch}`) !== fullSha(remote.ref))
1492
- throw new CliError("no_branch", `local ${unit.branch} differs from the pushed branch`, "Inspect the local branch and resolve the difference before retrying.");
1572
+ const inspected = inspectRemoteBranch(unit.branch);
1573
+ if (inspected.state === "exists") {
1574
+ const remote = fetchRemoteBranch(unit.branch);
1575
+ if (!remote.ok)
1576
+ throw new UnitWorktreePrepareFailed(missingBranchFaultMessage(n, unit.branch, recordedBase, remote.reason), { branch: unit.branch, recordedBase });
1577
+ if (fullSha(`refs/heads/${unit.branch}`) !== fullSha(remote.ref)) {
1578
+ throw new UnitWorktreePrepareFailed(`WU #${n}: local ${unit.branch} differs from the pushed branch (recorded base ${recordedBase}). Inspect the difference and push or resolve before retrying (git push -u origin ${unit.branch}, or clear with: b9s wu branch ${n} --clear).`, { branch: unit.branch, recordedBase });
1579
+ }
1580
+ }
1581
+ else if (inspected.state === "missing") {
1582
+ if (!canAutoCreateMissingBranch(unit, null)) {
1583
+ throw new UnitWorktreePrepareFailed(missingBranchFaultMessage(n, unit.branch, recordedBase, `couldn't find remote ref refs/heads/${unit.branch}`), { branch: unit.branch, recordedBase });
1584
+ }
1585
+ }
1586
+ else {
1587
+ throw new UnitWorktreePrepareFailed(missingBranchFaultMessage(n, unit.branch, recordedBase, inspected.reason), { branch: unit.branch, recordedBase });
1588
+ }
1493
1589
  }
1494
1590
  const home = resolve(process.cwd());
1495
1591
  const samePath = (a, b) => {
@@ -1608,26 +1704,73 @@ function prepareWorktree(n, unit, def, p, exclude = [], baseRefOverride) {
1608
1704
  const recordedBranch = unit.branch && !isShaBranchName(unit.branch) ? unit.branch : null;
1609
1705
  if (unit.branch && !recordedBranch)
1610
1706
  log(`ignoring recorded SHA-like branch ${unit.branch}; creating a wu/${n}-... branch from ${baseRef}`);
1707
+ const recordedBase = baseRefOverride ?? unit.branch_base ?? target;
1708
+ if (!baseRefOverride && !recordedBranch && unit.branch_base && !unit.replay?.created_at) {
1709
+ baseRef = resolveRecordedBaseRef(unit.branch_base, target, n, `wu/${n}-branch`);
1710
+ }
1611
1711
  const pinned = explicitBranch ?? recordedBranch;
1612
1712
  if (pinned) {
1613
1713
  const existing = worktreeForBranch(pinned);
1614
1714
  const path = existing ?? resolve(parent, `${name}-wu${n}`);
1615
1715
  // Check local branch refs explicitly: fullSha(pinned) would also resolve bare SHAs or tags.
1616
1716
  let branchCreated = !existing && fullSha(`refs/heads/${pinned}`) === null;
1617
- // Continuing someone else's branch from another machine: take origin's copy of it when we have none.
1618
- if (!existing && fullSha(`refs/heads/${pinned}`) === null) {
1619
- const remoteBranch = fetchRemoteBranch(pinned);
1620
- if (!remoteBranch.ok && !explicitBranch)
1621
- throw new CliError("no_branch", `cannot fetch recorded branch ${pinned} from origin: ${remoteBranch.reason}`, "Push the unit branch from the original checkout and retry.");
1622
- if (remoteBranch.ok) {
1623
- const r = spawnSync("git", ["branch", "--track", pinned, `origin/${pinned}`], { cwd: process.cwd(), encoding: "utf8" });
1624
- if (r.status !== 0)
1625
- throw new CliError("no_branch", `cannot create ${pinned} from origin: ${(r.stderr || r.stdout).trim()}`);
1626
- branchCreated = true;
1627
- log(`created ${pinned} from origin/${pinned}`);
1717
+ let shouldPushCreatedBranch = false;
1718
+ if (!existing) {
1719
+ const localSha = fullSha(`refs/heads/${pinned}`);
1720
+ const inspected = inspectRemoteBranch(pinned);
1721
+ if (inspected.state === "exists") {
1722
+ const remoteBranch = fetchRemoteBranch(pinned);
1723
+ if (!remoteBranch.ok)
1724
+ throw new UnitWorktreePrepareFailed(missingBranchFaultMessage(n, pinned, recordedBase, remoteBranch.reason), { branch: pinned, recordedBase });
1725
+ if (localSha === null) {
1726
+ const r = spawnSync("git", ["branch", "--track", pinned, `origin/${pinned}`], { cwd: process.cwd(), encoding: "utf8" });
1727
+ if (r.status !== 0)
1728
+ throw new UnitWorktreePrepareFailed(missingBranchFaultMessage(n, pinned, recordedBase, (r.stderr || r.stdout).trim()), { branch: pinned, recordedBase });
1729
+ branchCreated = true;
1730
+ log(`created ${pinned} from origin/${pinned}`);
1731
+ }
1732
+ else if (localSha !== fullSha(remoteBranch.ref)) {
1733
+ throw new UnitWorktreePrepareFailed(`WU #${n}: local ${pinned} differs from the pushed branch (recorded base ${recordedBase}). Inspect and push or resolve before retrying (git push -u origin ${pinned}, or clear with: b9s wu branch ${n} --clear).`, { branch: pinned, recordedBase });
1734
+ }
1735
+ }
1736
+ else if (inspected.state === "missing") {
1737
+ if (canAutoCreateMissingBranch(unit, explicitBranch && recordedBranch === null ? explicitBranch : null)) {
1738
+ const resolvedBase = baseRefOverride ?? resolveRecordedBaseRef(recordedBase, target, n, pinned);
1739
+ if (localSha !== null) {
1740
+ if (isAncestor(resolvedBase, localSha) !== true) {
1741
+ throw new UnitWorktreePrepareFailed(`WU #${n}: local ${pinned} is missing from origin and does not match recorded base ${recordedBase}. Push ${pinned} from ${recordedBase} (git push -u origin ${pinned}), or clear the recorded branch with: b9s wu branch ${n} --clear`, { branch: pinned, recordedBase });
1742
+ }
1743
+ }
1744
+ else {
1745
+ log(`creating missing branch ${pinned} from ${resolvedBase} (${fullSha(resolvedBase)?.slice(0, 9)})`);
1746
+ }
1747
+ baseRef = resolvedBase;
1748
+ shouldPushCreatedBranch = true;
1749
+ }
1750
+ else if (explicitBranch && recordedBranch === null) {
1751
+ // Local explicit --branch on a unit without a recorded branch keeps local-branch start behavior.
1752
+ }
1753
+ else {
1754
+ throw new UnitWorktreePrepareFailed(missingBranchFaultMessage(n, pinned, recordedBase, `couldn't find remote ref refs/heads/${pinned}`), { branch: pinned, recordedBase });
1755
+ }
1756
+ }
1757
+ else if (!explicitBranch || recordedBranch !== null) {
1758
+ throw new UnitWorktreePrepareFailed(missingBranchFaultMessage(n, pinned, recordedBase, inspected.reason), { branch: pinned, recordedBase });
1628
1759
  }
1629
1760
  }
1630
1761
  const result = !existing ? ensureUnitWorktree(path, pinned, baseRef, log, exclude) : { created: false, repaired: false };
1762
+ if (shouldPushCreatedBranch) {
1763
+ const pushed = pushBranchToOrigin(pinned, path, "origin");
1764
+ if (!pushed.ok) {
1765
+ if (result.created) {
1766
+ const removed = removeWorktreeIfClean(path);
1767
+ if (removed.removed && branchCreated)
1768
+ spawnSync("git", ["branch", "-D", pinned], { cwd: process.cwd(), encoding: "utf8" });
1769
+ }
1770
+ throw new UnitWorktreePrepareFailed(`WU #${n}: created ${pinned} from ${recordedBase} but failed to push to origin: ${pushed.reason}. Push ${pinned} from ${recordedBase} (git push -u origin ${pinned}), or clear the recorded branch with: b9s wu branch ${n} --clear`, { branch: pinned, recordedBase });
1771
+ }
1772
+ log(`pushed ${pinned} to origin/${pinned}`);
1773
+ }
1631
1774
  return { mode: "branch", path, branch: pinned, created: result.created, branchCreated };
1632
1775
  }
1633
1776
  const slug = String(unit.title).toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "").slice(0, 40);
@@ -1896,7 +2039,22 @@ export async function lock(p, out) {
1896
2039
  const lockName = p.positionals[1];
1897
2040
  if (cmd === "locks") {
1898
2041
  const r = await client.call("GET", `/projects/${project}/locks`);
1899
- out.print(r.locks.length ? r.locks.map((l) => `${l.name}${l.machine ? ` on ${l.machine}` : " (shared)"}: ${lockSlotsLabel(l, Date.now())}${l.waiting.length ? ` · waiting: ${l.waiting.map((w) => `${w.name}${w.unit ? ` (#${w.unit})` : ""}${w.legacy === 1 ? " (legacy, no token)" : w.job_id ? ` job ${w.job_id}` : ""}${w.note ? `: ${w.note}` : ""}${lockWaiterActivity(w, Date.now())}`).join(", ")}` : ""}`).join("\n") : "No locks in this project. Take one with: b9s lock <name> [--unit n]", r);
2042
+ const lockLines = r.locks.length ? r.locks.map((l) => {
2043
+ const holders = Array.isArray(l.holders) ? l.holders : null;
2044
+ const leaseAge = holders === null
2045
+ ? (l.holder_name ? "unknown (API does not report holder heartbeat)" : "no active lease")
2046
+ : holders.length === 0 ? "no active lease" : holders.map((h) => {
2047
+ const polled = typeof h.last_poll_at === "string" ? Date.parse(h.last_poll_at) : NaN;
2048
+ return `${h.name ?? "unknown"} ${Number.isFinite(polled) ? `${Math.floor(Math.max(0, Date.now() - polled) / 1000)}s` : "unknown (holder heartbeat timestamp not reported)"}`;
2049
+ }).join(", ");
2050
+ return `${l.name}${l.machine ? ` on ${l.machine}` : " (shared)"}: ${lockSlotsLabel(l, Date.now())}${l.waiting.length ? ` · waiting: ${l.waiting.map((w) => `${w.name}${w.unit ? ` (#${w.unit})` : ""}${w.legacy === 1 ? " (legacy, no token)" : w.job_id ? ` job ${w.job_id}` : ""}${w.note ? `: ${w.note}` : ""}${lockWaiterActivity(w, Date.now())}`).join(", ")}` : ""} · capacity ${Number.isInteger(l.capacity) ? l.capacity : "unknown (API does not report capacity)"} · lease age ${leaseAge}`;
2051
+ }) : ["No locks in this project. Take one with: b9s lock <name> [--unit n]"];
2052
+ const metricLines = (r.wait_metrics ?? []).map((m) => m.status === "unknown"
2053
+ ? `${m.resource_name}${m.machine ? ` on ${m.machine}` : " (shared)"} · ${m.hour}: unknown (${m.unknown_reason ?? "the API did not report why metrics are unknown"})`
2054
+ : `${m.resource_name}${m.machine ? ` on ${m.machine}` : " (shared)"} · ${m.hour}: median ${Math.round(m.median_wait_ms / 1000)}s, p90 ${Math.round(m.p90_wait_ms / 1000)}s, queue avg ${m.average_queue_length.toFixed(1)} / max ${m.max_queue_length} (${m.acquisitions} acquisitions)`);
2055
+ const coverage = typeof r.wait_metrics_since === "string" ? `; measurements available since ${r.wait_metrics_since}` : `; measurement coverage start unknown (${r.wait_metrics_coverage_unknown_reason ?? "API did not report it"})`;
2056
+ out.print([...lockLines, ...(r.wait_metrics_complete === false ? [`Wait metrics unknown${coverage}: ${r.wait_metrics_unknown_reason ?? "completeness was not reported"}`] : metricLines.length ? [`Wait metrics (hourly, last 24h${coverage}):`, ...metricLines] : [`Wait metrics: none recorded in the last 24h${coverage}.`]), ...(r.recent_waits?.length ? ["Recent waits:", ...r.recent_waits.map((w) => `${w.waiter_name}${w.unit ? ` (WU #${w.unit})` : ""} waited ${Math.round(w.wait_ms / 1000)}s for ${w.resource_name}${w.machine ? ` on ${w.machine}` : ""}; acquired ${w.acquired_at}; queue ${w.queue_length}`)] : [])].join("\n"), r);
2057
+ out.print([...lockLines, ...(r.wait_metrics_complete === false ? [`Wait metrics unknown${typeof r.wait_metrics_since === "string" ? `; measurements available since ${r.wait_metrics_since}` : `; measurement coverage start unknown (${r.wait_metrics_coverage_unknown_reason ?? "API did not report it"})`}: ${r.wait_metrics_unknown_reason ?? "completeness was not reported"}`] : metricLines.length ? [`Wait metrics (hourly, last 24h${typeof r.wait_metrics_since === "string" ? `; measurements available since ${r.wait_metrics_since}` : `; measurement coverage start unknown (${r.wait_metrics_coverage_unknown_reason ?? "API did not report it"})`}):`, ...metricLines] : [`Wait metrics: none recorded in the last 24h${typeof r.wait_metrics_since === "string" ? `; measurements available since ${r.wait_metrics_since}` : `; measurement coverage start unknown (${r.wait_metrics_coverage_unknown_reason ?? "API did not report it"})`}.`]), ...(r.recent_waits?.length ? ["Recent waits:", ...r.recent_waits.map((w) => `${w.waiter_name}${w.unit ? ` (WU #${w.unit})` : ""} waited ${Math.round(w.wait_ms / 1000)}s for ${w.resource_name}${w.machine ? ` on ${w.machine}` : ""}; acquired ${w.acquired_at}; queue ${w.queue_length}`)] : [])].join("\n"), r);
1900
2058
  return;
1901
2059
  }
1902
2060
  if (cmd === "lock" && lockName === "run" && (p.rest !== undefined || p.positionals.length > 2)) {
package/dist/git.js CHANGED
@@ -661,6 +661,31 @@ export function fullSha(ref, cwd = process.cwd()) {
661
661
  export function fetchRef(ref, remote = "origin", cwd = process.cwd()) {
662
662
  return spawnSync("git", ["fetch", "--quiet", remote, ref], { cwd, encoding: "utf8", timeout: 120_000 }).status === 0;
663
663
  }
664
+ export function hasRemote(remote = "origin", cwd = process.cwd()) {
665
+ return spawnSync("git", ["remote", "get-url", remote], { cwd, encoding: "utf8" }).status === 0;
666
+ }
667
+ export function inspectRemoteBranch(branch, remote = "origin", cwd = process.cwd()) {
668
+ const remoteRef = `refs/heads/${branch}`;
669
+ const r = spawnSync("git", ["ls-remote", "--exit-code", "--heads", remote, remoteRef], { cwd, encoding: "utf8", timeout: 120_000 });
670
+ if (r.status === 0) {
671
+ const line = (r.stdout ?? "").trim().split(/\r?\n/).map((entry) => entry.trim().split(/\s+/)).find((parts) => parts[1] === remoteRef && /^[0-9a-f]{40}$/i.test(parts[0] ?? ""));
672
+ if (!line)
673
+ return { state: "error", reason: `unexpected ls-remote output for ${remoteRef}` };
674
+ return { state: "exists", ref: remoteRef, sha: line[0].toLowerCase() };
675
+ }
676
+ if (r.status === 2 && !(r.stdout ?? "").trim() && !(r.stderr ?? "").trim()) {
677
+ return { state: "missing" };
678
+ }
679
+ const reason = (r.error ? r.error.message : (r.stderr || r.stdout).trim()) || `git ls-remote ${remote} ${branch} failed (exit ${r.status ?? "unknown"})`;
680
+ return { state: "error", reason };
681
+ }
682
+ export function pushBranchToOrigin(branch, cwd = process.cwd(), remote = "origin") {
683
+ const r = spawnSync("git", ["push", "-u", remote, `refs/heads/${branch}:refs/heads/${branch}`], { cwd, encoding: "utf8", timeout: 120_000 });
684
+ if (r.status === 0)
685
+ return { ok: true };
686
+ const reason = (r.error ? r.error.message : (r.stderr || r.stdout).trim()) || `git push ${remote} ${branch} failed (exit ${r.status ?? "unknown"})`;
687
+ return { ok: false, reason };
688
+ }
664
689
  /**
665
690
  * Fetch `branch` from `remote` explicitly into `refs/remotes/<remote>/<branch>`, returning either
666
691
  * the updated tracking ref or the git failure reason.
package/dist/help.js CHANGED
@@ -75,11 +75,12 @@ Agent commands
75
75
  b9s wu open "<title>" --scope "..." [--summary "plain work summary"] [--scope-file <path> | --scope-from <n>] [--tags a,b] [--lands-with <n>] [--reworks n,m] [--after <n>[,<m>]] [--requires cap,cap] [--priority urgent|normal] [--milestone <key>] [--force] [--evidence id[,id...]] [--target <branch>] [--here] [--json] open a work unit in its own
76
76
  worktree; tags come from the vocabulary; --target is the branch it lands in (default: the
77
77
  process target), e.g. a lane branch; wu target <n> <branch|default> changes it before review
78
- b9s wu assign "<title>" --to <agent|auto|queue> --scope ".." [--summary "plain work summary"] [--scope-file <path> | --scope-from <n>] [--tags a,b] [--lands-with <n>] [--reworks n,m] [--after <n>[,<m>]] [--requires cap,cap] [--priority urgent|normal] [--milestone <key>] [--branch <branch>] [--hold] [--evidence id[,id...]] [--force] [--replay-of n] [--template] [--reason "why"] [--json] hand out a unit (assigner roles);
78
+ b9s wu assign "<title>" --to <agent|auto|queue> --scope ".." [--summary "plain work summary"] [--scope-file <path> | --scope-from <n>] [--tags a,b] [--lands-with <n>] [--reworks n,m] [--after <n>[,<m>]] [--requires cap,cap] [--priority urgent|normal] [--milestone <key>] [--branch <branch>] [--base <branch-or-sha>] [--continue] [--hold] [--evidence id[,id...]] [--force] [--replay-of n] [--template] [--reason "why"] [--json] hand out a unit (assigner roles);
79
79
  --to auto picks the active qualified worker with the lightest load; it queues when nobody fits,
80
80
  reports why candidates were passed over, and the sweep chases it;
81
81
  --to queue waits deliberately; naming a busy worker reserves it for them (theirs when free,
82
82
  anyone's after the takeover window); --hold keeps it assigned to them however long it takes;
83
+ --branch pins a branch (--base records its starting commit or branch, else --after's head or target; --continue marks an existing pushed branch);
83
84
  --template --tags a,b prints the scope skeleton; --force records missing required sections, including for queue;
84
85
  assignment reports advisory scope suggestions from recorded causes, with counts and source dates; nothing is applied.
85
86
  Creation prints WU #<n> created first; --json returns {number,title,status,owner}.
@@ -131,11 +132,12 @@ Agent commands
131
132
  acquisition queues through a machine maintenance drain/window and resumes after it
132
133
  machine identity is this host's hostname plus its registered label, shared by all agents here
133
134
  save the returned job token; reuse --token to check/retry the same job
134
- b9s lock run <name> [--unit n] [--note ..] [--shared] [--token <job-token>] -- <command> poll until granted, run and release; gate receipt outcome is separate and does not change the command exit code
135
+ b9s lock run <name> [--unit n] [--note ..] [--shared] [--token <job-token>] -- <command> poll, heartbeat while running, stop its process tree before release; gate receipt outcome does not change the command exit code
135
136
  polls every 15s; stale waiters are skipped after 60s with a process notice; later polls reap unreported holders idle 60s
136
137
  output silence raises a Needs fault after B9S_LOCK_SILENCE_SECONDS (default 300); last output is redacted
137
- b9s locks shows waiter poll age; reported-command holders do not expire
138
- b9s unlock <name> [--job <id> | --token <job-token>] [--machine <label>|--shared] | b9s locks shows lock-run waiters' last-poll age; on this host the job token is kept for you
138
+ each holder reports a PID heartbeat; holders and waiters expire after 60s without one
139
+ output silence raises a Needs fault after B9S_LOCK_SILENCE_SECONDS (default 300); last output is redacted
140
+ b9s unlock <name> [--job <id> | --token <job-token>] [--machine <label>|--shared] | b9s locks shows holders, waiters, hourly wait metrics and recent waits
139
141
  b9s unlock <name> --remove-empty [--machine <label>|--shared]
140
142
  new agent jobs release by token; legacy jobs retain identity release; assigners/operators may release without a token
141
143
  closing a unit does not release a new job's lock
@@ -177,6 +179,7 @@ Machine placement enforces configured session slots and reports machine pressure
177
179
  b9s wu scope <n> --replace "<old>" "<new>" --note ".." replace one exact, unique substring of the scope
178
180
  b9s wu scope <n> --append ".." --note ".." add a dated scope amendment (up to 2000 chars); the base scope stays capped at 4000
179
181
  b9s wu target <n> <branch|default> [--summary "reviewed work summary"] owner, assigner or operator: change where this unit lands
182
+ b9s wu branch <n> [<branch>] [--clear] [--reason "why"] [--base <branch-or-sha>] [--continue] assigner or operator: set, correct, or clear a unit's recorded branch
180
183
  b9s wu head <n> <full-sha> --reason "why" assigner or operator: record a commit verified on the unit's branch
181
184
  b9s ask-operator "what you need from them" --plain ".." --blocks ".." --if-yes ".." --if-no ".." [--propose ".."] [--milestone <key> | --unit <n>] [--question <text>]
182
185
  b9s ask-operator --amend <id> ["new question"] [--plain ".."] [--blocks ".."] [--if-yes ".."] [--if-no ".."] [--propose ".."] [--question <text>] amend your own open ask
package/dist/ux-jobs.js CHANGED
@@ -569,6 +569,11 @@ export async function executeUxJob(machineClient, job, ctx, deps = {}) {
569
569
  throwIfHeartbeatFailed();
570
570
  return { res, combined };
571
571
  };
572
+ const stepFailure = (label, result) => {
573
+ const cause = (result.stderr || result.error?.message || result.stdout || "no stderr or stdout").trim().slice(0, 320);
574
+ const status = result.status === null ? "without an exit code" : `with exit code ${result.status}`;
575
+ return new Error(`${label} failed ${status}: ${cause}`);
576
+ };
572
577
  try {
573
578
  if (jobKind === "gate") {
574
579
  const scriptPath = join(jobWorktreeDir, "scripts", "gate.sh");
@@ -589,20 +594,6 @@ export async function executeUxJob(machineClient, job, ctx, deps = {}) {
589
594
  writeFileSync(gateLogFile, fullOutput || `${gateRes.stdout}\n${gateRes.stderr}` || `exit ${gateRes.status ?? 1}\n`);
590
595
  return { exit_code: gateRes.status ?? 1, ...scanner.result() };
591
596
  }
592
- if (job.task) {
593
- const { res: listed } = await runLockedStep("node", ["scripts/ux-console.mjs", "tasks"], {
594
- timeoutMs: 30_000,
595
- omitOutput: true,
596
- });
597
- if (listed.status !== 0) {
598
- appendLog(listed.stderr || listed.stdout);
599
- throw new Error(`could not enumerate registered ux:task names in ${jobWorktreeDir}`);
600
- }
601
- const registered = new Set(listed.stdout.split(/\r?\n/).map((line) => line.trim()).filter(Boolean));
602
- if (!registered.has(job.task)) {
603
- throw new Error(`ux:task ${job.task} is not registered in checkout ${shortHead}`);
604
- }
605
- }
606
597
  if (job.compare_screen) {
607
598
  const registryFile = join(jobWorktreeDir, "docs/ux/screens/mocks/compare.json");
608
599
  if (!existsSync(registryFile)) {
@@ -618,7 +609,29 @@ export async function executeUxJob(machineClient, job, ctx, deps = {}) {
618
609
  appendLog(installRes.stdout);
619
610
  appendLog(installRes.stderr);
620
611
  if (installRes.status !== 0)
621
- return installRes.status ?? 1;
612
+ throw stepFailure("npm ci", installRes);
613
+ if (jobKind === "ux") {
614
+ const { res: cliBuildRes } = await runLockedStep(npmBin, ["run", "build", "-w", "packages/cli"], { timeoutMs: 300_000 });
615
+ appendLog(cliBuildRes.stdout);
616
+ appendLog(cliBuildRes.stderr);
617
+ if (cliBuildRes.status !== 0)
618
+ throw stepFailure("npm run build -w packages/cli", cliBuildRes);
619
+ if (job.task) {
620
+ const { res: listed } = await runLockedStep("node", ["scripts/ux-console.mjs", "tasks"], {
621
+ timeoutMs: 30_000,
622
+ omitOutput: true,
623
+ });
624
+ appendLog(listed.stdout);
625
+ appendLog(listed.stderr);
626
+ if (listed.status !== 0) {
627
+ throw stepFailure(`could not enumerate registered ux:task names in ${jobWorktreeDir}`, listed);
628
+ }
629
+ const registered = new Set(listed.stdout.split(/\r?\n/).map((line) => line.trim()).filter(Boolean));
630
+ if (!registered.has(job.task)) {
631
+ throw new Error(`ux:task ${job.task} is not registered in checkout ${shortHead}`);
632
+ }
633
+ }
634
+ }
622
635
  const { res: seedRes } = await runLockedStep(npmBin, ["run", "ux:seed"], { timeoutMs: 300_000 });
623
636
  appendLog(seedRes.stdout);
624
637
  appendLog(seedRes.stderr);
package/dist/version.js CHANGED
@@ -1 +1 @@
1
- export const CLI_VERSION = "0.12.147";
1
+ export const CLI_VERSION = "0.12.149";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "benignswarm",
3
- "version": "0.12.147",
3
+ "version": "0.12.149",
4
4
  "description": "b9s: chat, status board and evidence store for coding agents (benignswarm.org)",
5
5
  "license": "UNLICENSED",
6
6
  "repository": {