benignswarm 0.12.152 → 0.12.154

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
@@ -42,7 +42,7 @@ export const STRING_FLAGS = [
42
42
  export const BOOL_FLAGS = [
43
43
  "latest", "no-restart", "json", "follow", "account", "help", "version", "broadcast", "create-channels",
44
44
  "read-account-status", "replace-key", "mentions-me", "no-skill", "replace", "template", "scope-only", "unread",
45
- "pending", "force", "no-hooks", "yes", "open", "bind-here", "peek", "once", "launchd", "full", "no-bind",
45
+ "pending", "force", "no-hooks", "yes", "open", "bind-here", "peek", "once", "launchd", "full", "no-bind", "log",
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", "overdue",
48
48
  "cancel", "rerun", "confirmed", "refuted", "no-source", "confirm-bypass-signal", "assessment-only", "continue",
@@ -12,7 +12,7 @@ import { codexHooksPath } from "./codex.js";
12
12
  import { isCodexManagedRequirements } from "../harness.js";
13
13
  import { readState, updateState } from "../state.js";
14
14
  import { join } from "./join.js";
15
- import { beginTurnGuardAttempt, completePendingTurnGuard, installWatcherService, turnArgs, watch } from "./watch.js";
15
+ import { beginTurnGuardAttempt, completePendingTurnGuard, installWatcherService, parseWorkUnitBindingResponse, prepareTurnWorktree, preparedWorktreePromptLines, resolveWatcherWorkUnitBinding, turnArgs, watch } from "./watch.js";
16
16
  import { randomUUID } from "node:crypto";
17
17
  import { HARNESS_BIN, HARNESS_LABEL, assertClaudeSelfCheck, claudeCodePath, claudeResultError, claudeResultFile, claudeSandboxEnv, claudeSettings, claudeTranscript, claudeTurnArgs, dshPath, dshResultError, dshSessionFromEvents, dshSettings, dshTurnLog, inspectCurrentClaudeEgressCapability, probeFor } from "../harnesses.js";
18
18
  import { allocateClaudeEgressPortPair, resolveTrustedControlPlaneOrigin, spawnClaudeEgressSupervised } from "../claude-egress-proxy.js";
@@ -79,7 +79,45 @@ function writeContainerStatusFile(file, payload) {
79
79
  writeFileSync(tmp, JSON.stringify(payload, null, 2) + "\n");
80
80
  renameSync(tmp, file);
81
81
  }
82
- export async function harnessStart(p, out, harness) {
82
+ /**
83
+ * Prepare a unique active assigned/started unit worktree outside the sandbox before launching a
84
+ * fresh workspace-write onboarding turn for harnesses whose checkout parent stays read-only.
85
+ * Continue unbound in process.cwd() only when the server confirms no in-progress work unit.
86
+ */
87
+ async function prepareOnboardingWorktree(ref, harness, sandbox, writable, antigravityRuntime, dependencies = {}) {
88
+ if (sandbox !== "workspace-write" || (harness !== "claude-code" && harness !== "antigravity"))
89
+ return null;
90
+ let resolution;
91
+ try {
92
+ resolution = dependencies.resolveWorkUnitBinding
93
+ ? await dependencies.resolveWorkUnitBinding(ref)
94
+ : await resolveWatcherWorkUnitBinding(ref, { strict: true });
95
+ }
96
+ catch (error) {
97
+ if (error instanceof CliError)
98
+ throw error;
99
+ const detail = error instanceof Error ? error.message : String(error);
100
+ throw new CliError("unit_worktree_prepare_failed", `cannot resolve active work-unit binding for ${ref} before launch: ${detail}`);
101
+ }
102
+ const verified = parseWorkUnitBindingResponse(resolution);
103
+ if (!verified) {
104
+ throw new CliError("unit_worktree_prepare_failed", `cannot resolve active work-unit binding for ${ref} before launch: server returned an invalid work-unit binding response`);
105
+ }
106
+ if (!verified.binding) {
107
+ if (verified.reason === "agent has no in-progress work unit")
108
+ return null;
109
+ throw new CliError("unit_worktree_prepare_failed", `cannot prepare a unit worktree before launching ${ref}: ${verified.reason}`, "Verify or disambiguate the agent's active work-unit assignment before starting this workspace-write session.");
110
+ }
111
+ const runtimeDeps = harness === "claude-code"
112
+ ? { claudeRuntime: { sandbox, writableRoots: writable } }
113
+ : { antigravityRuntime };
114
+ const prepared = await (dependencies.prepareWorktree ?? prepareTurnWorktree)(ref, verified.binding, true, runtimeDeps);
115
+ if (!prepared) {
116
+ throw new CliError("unit_worktree_missing", `cannot prepare WU #${verified.binding.work_unit_number} worktree before launching ${ref} in ${sandbox} mode`);
117
+ }
118
+ return prepared;
119
+ }
120
+ export async function harnessStart(p, out, harness, dependencies = {}) {
83
121
  const label = HARNESS_LABEL[harness];
84
122
  const cmd = harness === "codex" ? "codex start" : "start";
85
123
  const name = str(p.flags, "as");
@@ -329,11 +367,35 @@ export async function harnessStart(p, out, harness) {
329
367
  }
330
368
  }
331
369
  else {
370
+ const onboardingWorktree = await prepareOnboardingWorktree(ref, harness, sandbox, writable, harness === "antigravity" && sandbox === "workspace-write"
371
+ ? {
372
+ sandbox: "workspace-write",
373
+ apiHost: new URL(creds.url).host,
374
+ b9sBin: install.bin,
375
+ nodeBin: process.execPath,
376
+ writableRoots: writable,
377
+ tmpSessionKey: antigravityTmpSessionKey,
378
+ tmpDir: antigravityTmp,
379
+ }
380
+ : undefined, dependencies);
381
+ const onboardingUnit = onboardingWorktree ? { number: onboardingWorktree.number, path: onboardingWorktree.path } : undefined;
382
+ const onboardingCwd = onboardingWorktree?.path ?? process.cwd();
383
+ const onboardingPreflightSettings = harness === "claude-code" && sandbox === "workspace-write" && onboardingUnit
384
+ ? claudeSettings(sandbox, model, effort, process.cwd(), configRoot(), writable, onboardingUnit)
385
+ : preflightSettings;
386
+ if (onboardingUnit) {
387
+ if (harness === "claude-code") {
388
+ settings = claudeSettings(sandbox, model, effort, process.cwd(), configRoot(), writable, onboardingUnit, claudeSecretEgress);
389
+ }
390
+ else if (harness === "antigravity") {
391
+ settings = antigravitySettings(sandbox, process.cwd(), configRoot(), new URL(creds.url).host, [...writable, onboardingUnit.path], install.bin, process.execPath, ref, onboardingUnit);
392
+ }
393
+ }
332
394
  // The proxy/Git preflight spends model tokens, so it is its own guarded harness launch. The
333
395
  // first real turn resumes this same checked session and receives a separate reservation below.
334
396
  if (harness === "claude-code" && sandbox === "workspace-write") {
335
397
  session = randomUUID();
336
- await runGuardedClaudeSandboxSelfCheck(ref, turnsPerHour, bin, preflightSettings, maxBudgetUsd, providerEnv, process.cwd(), session, undefined, unproductivePerHour);
398
+ await runGuardedClaudeSandboxSelfCheck(ref, turnsPerHour, bin, onboardingPreflightSettings, maxBudgetUsd, providerEnv, onboardingCwd, session, undefined, unproductivePerHour);
337
399
  }
338
400
  const logDir = joinPath(configRoot(), "logs");
339
401
  mkdirSync(logDir, { recursive: true });
@@ -343,6 +405,7 @@ export async function harnessStart(p, out, harness) {
343
405
  `Your watcher starts a turn for you whenever something needs you, so end your turn when nothing is left to do.`,
344
406
  `Now: run \`b9s me\`, \`b9s process\` and \`b9s inbox --unread\`, then do what your role and inbox ask.`,
345
407
  `If you ran on another machine before, read your latest note first: \`b9s handoffs --agent ${creds.agent}\` (your units, branches and chat are on the server as before).`,
408
+ ...(onboardingWorktree ? preparedWorktreePromptLines(onboardingWorktree, "b9s start") : []),
346
409
  ].join("\n");
347
410
  const diagnostic = [];
348
411
  if (!(await beginTurnGuardAttempt(ref, turnsPerHour, (m) => diagnostic.push(m), process.env, unproductivePerHour, process.env.BSCHAT_MACHINE_SESSION_ID, harness, session ? probeFor(harness, session, ref) : undefined))) {
@@ -361,18 +424,18 @@ export async function harnessStart(p, out, harness) {
361
424
  lines.push(`Started DeepSeek Harness session ${session}; its first turn (reading its role and inbox) is running, event log: ${firstTurnLog}`);
362
425
  }
363
426
  else if (harness === "antigravity") {
364
- const started = runAntigravityTurn(bin, antigravityTurnArgs(prompt, model, effort, turnTimeout * 60, settings), firstTurnLog, process.cwd(), ref, undefined, undefined, antigravityTurnEnv(sandbox, install.bin, antigravityTmp));
427
+ const started = runAntigravityTurn(bin, antigravityTurnArgs(prompt, model, effort, turnTimeout * 60, settings), firstTurnLog, onboardingCwd, ref, undefined, undefined, antigravityTurnEnv(sandbox, install.bin, antigravityTmp));
365
428
  session = started.conversation;
366
429
  await completePendingTurnGuard(ref, probeFor(harness, session, ref), (message) => diagnostic.push(message), started.output, antigravityTokenTotal(started.record.result?.usage));
367
430
  lines.push(`Started Antigravity conversation ${session}; its first turn (reading its role and inbox) completed, JSON turn log: ${firstTurnLog}`);
368
431
  if (sandbox === "workspace-write")
369
- await runAntigravitySandboxSelfCheck(ref, bin, settings, process.cwd(), session, model, effort, turnTimeout * 60, firstTurnLog, turnsPerHour, antigravityTurnEnv(sandbox, install.bin, antigravityTmp), unproductivePerHour);
432
+ await runAntigravitySandboxSelfCheck(ref, bin, settings, onboardingCwd, session, model, effort, turnTimeout * 60, firstTurnLog, turnsPerHour, antigravityTurnEnv(sandbox, install.bin, antigravityTmp), unproductivePerHour);
370
433
  }
371
434
  else {
372
435
  // Claude Code takes the session id from us, so nothing has to be read back from its output.
373
436
  session ??= randomUUID();
374
437
  secretSessionKey = activateClaudeSecretSession(session);
375
- await startClaudeSession(bin, ["-p", prompt, ...settings, ...(sandbox === "workspace-write" ? claudeTurnArgs(maxBudgetUsd) : []), ...claudeSessionStartArgs(sandbox, session), "--output-format", "json"], firstTurnLog, ref, session, providerEnv, model, provider, claudeSecretEgress ? projectSecretEnv : {}, claudeSecretEgress);
438
+ await startClaudeSession(bin, ["-p", prompt, ...settings, ...(sandbox === "workspace-write" ? claudeTurnArgs(maxBudgetUsd) : []), ...claudeSessionStartArgs(sandbox, session), "--output-format", "json"], firstTurnLog, ref, session, providerEnv, model, provider, claudeSecretEgress ? projectSecretEnv : {}, claudeSecretEgress, onboardingCwd);
376
439
  lines.push(`Started Claude Code session ${session}; its first turn (reading its role and inbox) is running, result: ${firstTurnLog}`);
377
440
  }
378
441
  }
@@ -587,7 +650,7 @@ export async function startDshSession(bin, args, logPath, agent, prompt) {
587
650
  * minutes; this command does not wait for it) and returns once its transcript exists, or fails
588
651
  * with Claude Code's own error when it exits first.
589
652
  */
590
- async function startClaudeSession(bin, args, logPath, agent, session, providerEnv, model, provider, secretEnv = {}, secretEgress) {
653
+ async function startClaudeSession(bin, args, logPath, agent, session, providerEnv, model, provider, secretEnv = {}, secretEgress, cwd = process.cwd()) {
591
654
  if (secretEgress && (!secretEgress.httpProxyPort || !secretEgress.socksProxyPort)) {
592
655
  throw new CliError("secret_egress_unenforced_claude-code", "Claude Code secret delivery requires an active outer egress proxy boundary");
593
656
  }
@@ -615,12 +678,12 @@ async function startClaudeSession(bin, args, logPath, agent, session, providerEn
615
678
  bin,
616
679
  args,
617
680
  },
618
- cwd: process.cwd(),
681
+ cwd,
619
682
  env: childEnv,
620
683
  stdio: ["ignore", fd, fd],
621
684
  detached: true,
622
685
  })
623
- : spawn(bin, args, { stdio: ["ignore", fd, fd], detached: true, cwd: process.cwd(), env: childEnv });
686
+ : spawn(bin, args, { stdio: ["ignore", fd, fd], detached: true, cwd, env: childEnv });
624
687
  closeSync(fd);
625
688
  let exited = null;
626
689
  child.on("exit", (code) => { exited = code ?? 1; });
@@ -44,7 +44,7 @@ import { EcrHostedRegistry } from "../hosted-registry-ecr.js";
44
44
  import { publishHostedImage } from "../hosted-registry.js";
45
45
  import { assumeHostedBuilder } from "../hosted-registry-session.js";
46
46
  import { pushHostedImage } from "../hosted-registry-push.js";
47
- import { reconcilePendingUxJobs, retryPendingUxJobCompletions, uxJobIdsForMachineReport } from "../ux-jobs.js";
47
+ import { reconcilePendingUxJobs, retryPendingUxJobCompletions, sweepExpiredUxJobWorktrees, uxJobIdsForMachineReport } from "../ux-jobs.js";
48
48
  export const machineFile = () => join(configRoot(), "machine.json");
49
49
  export function loadMachine() {
50
50
  const f = machineFile();
@@ -2003,7 +2003,19 @@ export async function reconcile(m, log, reportIntervalSeconds = 30, deps) {
2003
2003
  active_ux_job_ids: uxJobIdsForMachineReport(deps?.uxJobsInFlight, deps?.uxJobDeps),
2004
2004
  ...(imageProbes.length ? { image_probes: imageProbes } : {}),
2005
2005
  });
2006
- await retryPendingUxJobCompletions(client, log, deps?.uxJobDeps);
2006
+ const uxSessionHints = desired.map((session) => ({
2007
+ id: session.id,
2008
+ agent: session.agent,
2009
+ agent_name: session.agent_name,
2010
+ project: session.project,
2011
+ project_id: session.project_id ?? null,
2012
+ dir: session.dir,
2013
+ desired: session.desired,
2014
+ benched_at: session.benched_at ?? null,
2015
+ retired_at: null,
2016
+ }));
2017
+ await retryPendingUxJobCompletions(client, log, deps?.uxJobDeps, uxSessionHints);
2018
+ await sweepExpiredUxJobWorktrees(workdir ?? join(homedir(), "bschat"), projects, undefined, process.env, log, Date.now(), (jobId) => client.call("POST", `/machines/me/ux-jobs/${encodeURIComponent(jobId)}/checkout-removed`, {}));
2007
2019
  for (const item of probedProjects) {
2008
2020
  lastCapabilityProbe.set(item.id, { at: Date.now(), signature: item.signature });
2009
2021
  }
@@ -2015,6 +2027,7 @@ export async function reconcile(m, log, reportIntervalSeconds = 30, deps) {
2015
2027
  accountId,
2016
2028
  machineName: m.name,
2017
2029
  workdir,
2030
+ diskFloorPct: me.machine?.cache_floor_pct ?? DEFAULT_CACHE_FLOOR_PCT,
2018
2031
  sessions: desired.map((s) => ({
2019
2032
  id: s.id,
2020
2033
  agent: s.agent,
@@ -146,11 +146,47 @@ export async function runRequiredClassUpdate(c, project, unitNumber, p, out) {
146
146
  * b9s-admin routing required-class <project> <unit> (--class p/h/m/e | --clear) --reason "why"
147
147
  * b9s-admin routing tag-required-class <project> <tag> (--class p/h/m/e | --clear) --reason "why"
148
148
  * b9s-admin routing tier-migration <project>
149
+ * b9s-admin routing adjustments <project>
150
+ * b9s-admin routing override <project> --tag <tag> --model <canonical-model> --reason "why"
149
151
  * b9s-admin routing pool-suggestions <project> [--status pending|accepted|rejected|superseded|all]
150
152
  */
151
153
  export async function routingAdmin(action, rest, p, out) {
152
154
  const c = adminClient(p);
153
155
  switch (action) {
156
+ case "adjustments": {
157
+ const project = rest[0];
158
+ if (!project)
159
+ throw new CliError("usage", "routing adjustments <project>");
160
+ const r = await c.call("GET", `/projects/${project}/routing/adjustments`);
161
+ const lines = [`Cause-backed routing adjustments for ${r.project} (minimum model sample ${r.minimum_sample_count ?? "unknown"}):`];
162
+ for (const item of r.adjustments ?? []) {
163
+ const worker = item.recommended_worker_model?.model
164
+ ? `${item.recommended_worker_model.model}@${item.recommended_worker_model.effort} (${item.recommended_worker_model.cause_rate} worker-error, n=${item.recommended_worker_model.denominator})`
165
+ : `unknown (${item.recommended_worker_model?.reason ?? "no evidence"})`;
166
+ const reviewer = item.recommended_reviewer_model?.model
167
+ ? `${item.recommended_reviewer_model.model}@${item.recommended_reviewer_model.effort} (${item.recommended_reviewer_model.cause_rate} reviewer-scope-growth, n=${item.recommended_reviewer_model.denominator})`
168
+ : `unknown (${item.recommended_reviewer_model?.reason ?? "no evidence"})`;
169
+ lines.push(` #${item.tag}: worker ${worker}; reviewer ${reviewer}`);
170
+ lines.push(` scope prompt: ${item.assigner_scope_prompt?.text ?? `unknown (${item.assigner_scope_prompt?.reason ?? "no evidence"})`}`);
171
+ lines.push(` override: ${item.operator_override ? `${item.operator_override.model} (${item.operator_override.reason}; by ${item.operator_override.actor})` : "none"}`);
172
+ }
173
+ if (!r.adjustments?.length)
174
+ lines.push(" (no project vocabulary tags)");
175
+ out.print(lines.join("\n"), r);
176
+ return;
177
+ }
178
+ case "override": {
179
+ const project = rest[0];
180
+ const tag = str(p.flags, "tag");
181
+ const model = str(p.flags, "model")?.trim();
182
+ const reason = str(p.flags, "reason")?.trim();
183
+ if (!project || !tag || !model || !reason) {
184
+ throw new CliError("usage", 'routing override <project> --tag <tag> --model <canonical-model> --reason "why"');
185
+ }
186
+ const r = await c.call("POST", `/projects/${project}/routing/adjustments/override`, { tag: normalizeTag(tag), model, reason });
187
+ out.print(`Set ${project} #${normalizeTag(tag)} worker/reviewer model preference to ${model} (${reason}).`, r);
188
+ return;
189
+ }
154
190
  case "show": {
155
191
  const project = rest[0];
156
192
  if (!project)
@@ -1,3 +1,4 @@
1
+ import { createHash } from "node:crypto";
1
2
  import { bool, str } from "../args.js";
2
3
  import { Client } from "../client.js";
3
4
  import { loadAgent, resolveAgentName, resolveModel } from "../config.js";
@@ -5,6 +6,35 @@ import { CliError } from "../errors.js";
5
6
  import { collectAuto } from "../git.js";
6
7
  import { table } from "../output.js";
7
8
  import { projectOf } from "./agent.js";
9
+ async function printJob(job, res, p, out, creds, client, project) {
10
+ if (!bool(p.flags, "log")) {
11
+ out.print(formatJob(job), res);
12
+ return;
13
+ }
14
+ const evidenceId = job.full_log_evidence_id;
15
+ if (typeof evidenceId !== "string" || !evidenceId) {
16
+ throw new CliError("log_unavailable", "this job has no uploaded full-log evidence");
17
+ }
18
+ const response = await fetch(`${creds.url}/projects/${encodeURIComponent(project)}/evidence/${encodeURIComponent(evidenceId)}/content`, {
19
+ headers: client.headers(),
20
+ });
21
+ if (!response.ok) {
22
+ let message = `full-log download failed (HTTP ${response.status})`;
23
+ try {
24
+ const body = await response.json();
25
+ if (typeof body.message === "string")
26
+ message = body.message;
27
+ }
28
+ catch { }
29
+ throw new CliError(`http_${response.status}`, message);
30
+ }
31
+ const bytes = Buffer.from(await response.arrayBuffer());
32
+ const expected = response.headers.get("x-bschat-sha256") ?? "";
33
+ const actual = createHash("sha256").update(bytes).digest("hex");
34
+ if (!expected || actual !== expected)
35
+ throw new CliError("checksum_mismatch", `full-log bytes hash to ${actual} but server says ${expected || "no checksum"}`);
36
+ process.stdout.write(bytes);
37
+ }
8
38
  function formatJob(job) {
9
39
  const isGate = job.job_kind === "gate";
10
40
  const what = isGate
@@ -16,7 +46,32 @@ function formatJob(job) {
16
46
  : "";
17
47
  const errorLine = job.error ? `\nError: ${job.error}` : "";
18
48
  const kindLabel = isGate ? "Gate" : "UX";
19
- return `${kindLabel} job ${job.id} [${job.status}] on ${job.machine} for WU #${job.work_unit_number}\nTask: ${what}\nBranch: ${job.branch} @ ${headText}${evidenceLine}${errorLine}`;
49
+ const fullLogLine = job.full_log_evidence_id ? `\nFull log: evidence:${job.full_log_evidence_id} (use --log to print)` : "\nFull log: unavailable";
50
+ const steps = Array.isArray(job.step_timeline) && job.step_timeline.length
51
+ ? `\nSteps:\n${table(job.step_timeline.map((step) => ({
52
+ step: step.name,
53
+ started: step.started_at,
54
+ duration_ms: step.duration_ms,
55
+ exit: step.exit_code ?? "unknown",
56
+ })), ["step", "started", "duration_ms", "exit"])}`
57
+ : "";
58
+ const failedStep = Array.isArray(job.step_timeline) ? [...job.step_timeline].reverse().find((step) => step.exit_code !== null && step.exit_code !== undefined && step.exit_code !== 0) : undefined;
59
+ const failedTail = failedStep?.output_tail ? `\nFailed step (${failedStep.name}) output tail:\n${failedStep.output_tail}` : "";
60
+ const fingerprint = job.environment_fingerprint && typeof job.environment_fingerprint === "object"
61
+ ? `\nEnvironment: node ${job.environment_fingerprint.node?.version ?? "unknown"} (${job.environment_fingerprint.node?.path ?? "path unknown"}); npm ${job.environment_fingerprint.npm?.version ?? "unknown"} (${job.environment_fingerprint.npm?.path ?? "path unknown"}); b9s ${job.environment_fingerprint.b9s?.version ?? "unknown"} (${job.environment_fingerprint.b9s?.path ?? "path unknown"}); slot ${job.environment_fingerprint.slot ?? "unknown"}; lock ${job.environment_fingerprint.lock_job_id ?? "unknown"}; ports ${JSON.stringify(job.environment_fingerprint.ports ?? {})}; PATH ${job.environment_fingerprint.PATH ?? "unknown"}`
62
+ : "";
63
+ let checkoutLine = "";
64
+ if (job.checkout_path) {
65
+ if (job.checkout_removed_at)
66
+ checkoutLine = `\nCheckout: removed at ${job.checkout_removed_at} (${job.checkout_path})`;
67
+ else if (job.checkout_expires_at && Date.parse(job.checkout_expires_at) <= Date.now())
68
+ checkoutLine = `\nCheckout: retention expired at ${job.checkout_expires_at}; daemon cleanup not yet reported (${job.checkout_path})`;
69
+ else
70
+ checkoutLine = `\nCheckout: retained at ${job.checkout_path}${job.checkout_expires_at ? ` until ${job.checkout_expires_at}` : ""}`;
71
+ }
72
+ else if (job.checkout_retention_note)
73
+ checkoutLine = `\nCheckout: ${job.checkout_retention_note}`;
74
+ return `${kindLabel} job ${job.id} [${job.status}] on ${job.machine} for WU #${job.work_unit_number}\nTask: ${what}\nBranch: ${job.branch} @ ${headText}${steps}${failedTail}${fingerprint}${checkoutLine}${evidenceLine}${fullLogLine}${errorLine}`;
20
75
  }
21
76
  export async function ux(p, out) {
22
77
  const sub = p.positionals[1];
@@ -65,9 +120,9 @@ export async function ux(p, out) {
65
120
  if (sub === "job") {
66
121
  const id = p.positionals[2]?.trim();
67
122
  if (!id)
68
- throw new CliError("usage", "b9s ux job <id>");
123
+ throw new CliError("usage", "b9s ux job <id> [--log]");
69
124
  const res = await client.call("GET", `/projects/${project}/ux-jobs/${encodeURIComponent(id)}`);
70
- out.print(formatJob(res.job), res);
125
+ await printJob(res.job, res, p, out, creds, client, project);
71
126
  return;
72
127
  }
73
128
  if (sub === "jobs") {
@@ -124,9 +179,9 @@ export async function gate(p, out) {
124
179
  if (sub === "job") {
125
180
  const id = p.positionals[2]?.trim();
126
181
  if (!id)
127
- throw new CliError("usage", "b9s gate job <id>");
182
+ throw new CliError("usage", "b9s gate job <id> [--log]");
128
183
  const res = await client.call("GET", `/projects/${project}/gate-jobs/${encodeURIComponent(id)}`);
129
- out.print(formatJob(res.job), res);
184
+ await printJob(res.job, res, p, out, creds, client, project);
130
185
  return;
131
186
  }
132
187
  if (sub === "jobs") {
@@ -495,26 +495,85 @@ function envSessionKey(explicitSessionId) {
495
495
  const id = explicitSessionId ?? process.env.BSCHAT_MACHINE_SESSION_ID;
496
496
  return id && id.trim() ? id.trim() : undefined;
497
497
  }
498
+ /** Prompt instructions telling an agent where its outside-sandbox prepared worktree sits and how to start/use it. */
499
+ export function preparedWorktreePromptLines(preparedWorktree, preparer = "The watcher") {
500
+ const lines = [
501
+ preparedWorktree.needsRecord
502
+ ? `${preparer} prepared WU #${preparedWorktree.number}'s worktree at ${preparedWorktree.path}. Run b9s wu start ${preparedWorktree.number}${preparedWorktree.branch ? ` --branch ${preparedWorktree.branch}` : ""} from this checkout to record this worktree on the unit, then work in that path.`
503
+ : preparedWorktree.status === "assigned"
504
+ ? `${preparer} prepared WU #${preparedWorktree.number}'s worktree at ${preparedWorktree.path}. Run b9s wu start ${preparedWorktree.number} from this checkout to record the start, then work in that path.`
505
+ : `${preparer} prepared WU #${preparedWorktree.number}'s worktree at ${preparedWorktree.path}; continue working there.`,
506
+ ];
507
+ if (preparedWorktree.homeChanges?.length) {
508
+ lines.push(`The home checkout was left untouched with uncommitted changes: ${preparedWorktree.homeChanges.join(", ")}. Review and carry over only the changes that belong in this unit; they were not copied automatically.`);
509
+ }
510
+ if (preparedWorktree.homeCommits?.length) {
511
+ lines.push(`The home checkout was left untouched with committed changes beyond its recorded head: ${preparedWorktree.homeCommits.join("; ")}. Those commits are present in the prepared unit worktree.`);
512
+ }
513
+ return lines;
514
+ }
515
+ function parseValidWorkUnitBinding(raw) {
516
+ if (!raw || typeof raw !== "object" || Array.isArray(raw))
517
+ return null;
518
+ const candidate = raw;
519
+ if (Number.isSafeInteger(candidate.work_unit_number)
520
+ && Number(candidate.work_unit_number) > 0
521
+ && typeof candidate.assignment_event_id === "string"
522
+ && candidate.assignment_event_id.length > 0
523
+ && typeof candidate.project === "string"
524
+ && candidate.project.length > 0) {
525
+ return {
526
+ work_unit_number: Number(candidate.work_unit_number),
527
+ assignment_event_id: candidate.assignment_event_id,
528
+ project: candidate.project,
529
+ };
530
+ }
531
+ return null;
532
+ }
533
+ /** Validate a /agents/me/work-unit-binding response payload, returning null if malformed. */
534
+ export function parseWorkUnitBindingResponse(raw) {
535
+ if (!raw || typeof raw !== "object" || Array.isArray(raw))
536
+ return null;
537
+ const result = raw;
538
+ if (result.binding !== undefined && result.binding !== null) {
539
+ const validBinding = parseValidWorkUnitBinding(result.binding);
540
+ if (!validBinding)
541
+ return null;
542
+ if (result.reason !== undefined && result.reason !== null)
543
+ return null;
544
+ return { binding: validBinding, reason: null };
545
+ }
546
+ if (result.binding !== null)
547
+ return null;
548
+ if (result.reason === "agent has no in-progress work unit"
549
+ || result.reason === "agent has multiple in-progress work units"
550
+ || result.reason === "current work-unit assignment event is unavailable") {
551
+ return { binding: null, reason: result.reason };
552
+ }
553
+ return null;
554
+ }
498
555
  /** Bind only when the server says this identity has exactly one active owner assignment. */
499
- export async function resolveWatcherWorkUnitBinding(name) {
556
+ export async function resolveWatcherWorkUnitBinding(name, options = {}) {
500
557
  const creds = loadAgent(name);
501
558
  const client = Client.forAgent(creds, undefined, { presence: false });
559
+ let raw;
502
560
  try {
503
- const result = await client.call("GET", "/agents/me/work-unit-binding");
504
- if (result.binding && Number.isSafeInteger(result.binding.work_unit_number) && Number(result.binding.work_unit_number) > 0
505
- && typeof result.binding.assignment_event_id === "string" && result.binding.assignment_event_id
506
- && typeof result.binding.project === "string" && result.binding.project) {
507
- return { binding: { work_unit_number: Number(result.binding.work_unit_number), assignment_event_id: result.binding.assignment_event_id, project: result.binding.project }, reason: null };
508
- }
509
- if (result.reason === "agent has no in-progress work unit" || result.reason === "agent has multiple in-progress work units"
510
- || result.reason === "current work-unit assignment event is unavailable") {
511
- return { binding: null, reason: result.reason };
561
+ raw = await client.call("GET", "/agents/me/work-unit-binding");
562
+ }
563
+ catch (error) {
564
+ if (options.strict) {
565
+ const detail = error instanceof Error ? error.message : String(error);
566
+ throw new CliError("unit_worktree_prepare_failed", `cannot resolve active work-unit binding for ${name} before launch: ${detail}`, undefined, error instanceof CliError ? error.httpStatus : undefined);
512
567
  }
513
568
  return { binding: null, reason: "current work-unit assignment event is unavailable" };
514
569
  }
515
- catch {
516
- return { binding: null, reason: "current work-unit assignment event is unavailable" };
570
+ const parsed = parseWorkUnitBindingResponse(raw);
571
+ if (parsed)
572
+ return parsed;
573
+ if (options.strict) {
574
+ throw new CliError("unit_worktree_prepare_failed", `cannot resolve active work-unit binding for ${name} before launch: server returned an invalid /agents/me/work-unit-binding response`);
517
575
  }
576
+ return { binding: null, reason: "current work-unit assignment event is unavailable" };
518
577
  }
519
578
  /**
520
579
  * Runs `work` with BSCHAT_AGENT naming this watcher's agent, then puts the environment back.
@@ -580,7 +639,8 @@ export async function prepareTurnWorktree(name, binding, allowSuperseded = false
580
639
  }
581
640
  const process = await client.call("GET", `/projects/${encodeURIComponent(project)}/process`);
582
641
  const { contextDecisionForStart, prepareWorktreeForWatcher } = await import("./wu.js");
583
- const prepared = withAgentEnv(agentRef(creds), () => prepareWorktreeForWatcher(binding.work_unit_number, unit, process.process?.definition, process.checkout?.exclude ?? []));
642
+ const restrictedWorkspaceWrite = dependencies.antigravityRuntime?.sandbox === "workspace-write" || dependencies.claudeRuntime?.sandbox === "workspace-write";
643
+ const prepared = withAgentEnv(agentRef(creds), () => prepareWorktreeForWatcher(binding.work_unit_number, unit, process.process?.definition, process.checkout?.exclude ?? [], restrictedWorkspaceWrite));
584
644
  worktreePrepared = true;
585
645
  const hadFault = readState(name).worktree_fault?.project === project && readState(name).worktree_fault?.unit === binding.work_unit_number;
586
646
  const clearServerWorktreeFault = async () => {
@@ -591,7 +651,6 @@ export async function prepareTurnWorktree(name, binding, allowSuperseded = false
591
651
  catch { }
592
652
  }
593
653
  };
594
- const restrictedWorkspaceWrite = dependencies.antigravityRuntime?.sandbox === "workspace-write" || dependencies.claudeRuntime?.sandbox === "workspace-write";
595
654
  const startedUnitRecovery = unit.status !== "assigned" && prepared.recoveryRequired;
596
655
  if (prepared.needsRecord && restrictedWorkspaceWrite && startedUnitRecovery) {
597
656
  const location = branchAndHead(prepared.path);
@@ -948,17 +1007,7 @@ export async function wakeOnce(name, exec, unackedAfter, followDelay, log, model
948
1007
  throw new CliError("unit_worktree_missing", `Claude Code workspace-write cannot start WU #${bindingToPrepare.work_unit_number}: the watcher did not prepare its unit worktree`);
949
1008
  }
950
1009
  if (preparedWorktree) {
951
- wakePrefix.push(preparedWorktree.needsRecord
952
- ? `The watcher prepared WU #${preparedWorktree.number}'s worktree at ${preparedWorktree.path}. Run b9s wu start ${preparedWorktree.number}${preparedWorktree.branch ? ` --branch ${preparedWorktree.branch}` : ""} from this checkout to record this worktree on the unit, then work in that path.`
953
- : preparedWorktree.status === "assigned"
954
- ? `The watcher prepared WU #${preparedWorktree.number}'s worktree at ${preparedWorktree.path}. Run b9s wu start ${preparedWorktree.number} from this checkout to record the start, then work in that path.`
955
- : `The watcher prepared WU #${preparedWorktree.number}'s worktree at ${preparedWorktree.path}; continue working there.`);
956
- if (preparedWorktree.homeChanges?.length) {
957
- wakePrefix.push(`The home checkout was left untouched with uncommitted changes: ${preparedWorktree.homeChanges.join(", ")}. Review and carry over only the changes that belong in this unit; they were not copied automatically.`);
958
- }
959
- if (preparedWorktree.homeCommits?.length) {
960
- wakePrefix.push(`The home checkout was left untouched with committed changes beyond its recorded head: ${preparedWorktree.homeCommits.join("; ")}. Those commits are present in the prepared unit worktree.`);
961
- }
1010
+ wakePrefix.push(...preparedWorktreePromptLines(preparedWorktree));
962
1011
  }
963
1012
  }
964
1013
  const payload = u ? formatUpdates(omitMeasuresAlreadyIn(recoveryPrompt, u), wakePrefix, wakeSuffix) : null;
@@ -972,7 +1021,7 @@ export async function wakeOnce(name, exec, unackedAfter, followDelay, log, model
972
1021
  const workUnitBinding = bindingResolution?.binding ?? null;
973
1022
  let turnExec = exec;
974
1023
  let turnCwd;
975
- if (turnSink && provider && (dependencies.claudeRuntime?.sandbox === "workspace-write" || dependencies.antigravityRuntime?.sandbox === "workspace-write")) {
1024
+ if (turnSink && (dependencies.claudeRuntime?.sandbox === "workspace-write" || (provider && dependencies.antigravityRuntime?.sandbox === "workspace-write"))) {
976
1025
  if (bindingToPrepare && !preparedWorktree) {
977
1026
  throw new CliError("unit_worktree_missing", `workspace-write ${dependencies.antigravityRuntime ? "Antigravity" : "Claude Code"} cannot start WU #${bindingToPrepare.work_unit_number}: the watcher did not prepare its unit worktree`);
978
1027
  }