benignswarm 0.12.153 → 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.
@@ -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; });
@@ -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)
@@ -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
  }
@@ -70,6 +70,52 @@ function jsonFlag(p, key, expected) {
70
70
  throw new CliError("usage", `--${key} must be JSON ${expected}`);
71
71
  }
72
72
  }
73
+ /** Read the send-back review body's structured points before contacting the API. */
74
+ export function sendbackRuleFromFile(file) {
75
+ if (!file?.trim())
76
+ throw new CliError("usage", "wu sendback-rule <n> --file ruling.json");
77
+ let parsed;
78
+ try {
79
+ parsed = JSON.parse(readFileSync(resolve(file), "utf8"));
80
+ }
81
+ catch (error) {
82
+ throw new CliError("sendback_rule_file", `cannot read valid JSON from ${file}: ${error.message}`);
83
+ }
84
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed))
85
+ throw new CliError("usage", "send-back ruling JSON must be an object with a points array");
86
+ const points = parsed.points;
87
+ if (!Array.isArray(points) || !points.length)
88
+ throw new CliError("usage", "send-back ruling JSON must include a non-empty points array");
89
+ const dispositions = new Set(["in_scope_unmet", "out_of_scope", "already_met", "repeated"]);
90
+ const causes = new Set(["scope_gap", "missing_context", "worker_error", "reviewer_scope_growth", "environment", "stale_base"]);
91
+ if (points.some((point) => {
92
+ if (!point || typeof point !== "object" || Array.isArray(point))
93
+ return true;
94
+ const value = point;
95
+ if (typeof value.finding_event_id !== "string" || !value.finding_event_id.trim()
96
+ || typeof value.finding !== "string" || !value.finding.trim()
97
+ || typeof value.disposition !== "string" || !dispositions.has(value.disposition)
98
+ || typeof value.rationale !== "string" || !value.rationale.trim()
99
+ || typeof value.cause !== "string" || !causes.has(value.cause)
100
+ || typeof value.cause_evidence !== "string" || !value.cause_evidence.trim()
101
+ || (value.quote !== undefined && (typeof value.quote !== "string" || !value.quote.trim()))
102
+ || (value.commit !== undefined && (typeof value.commit !== "string" || !value.commit.trim())))
103
+ return true;
104
+ return (value.disposition === "out_of_scope" && (typeof value.quote !== "string" || !value.quote.trim()))
105
+ || (value.disposition === "already_met" && (typeof value.commit !== "string" || !value.commit.trim()));
106
+ })) {
107
+ throw new CliError("usage", "each send-back ruling point needs finding_event_id, finding, a permitted disposition, rationale, cause and cause_evidence; out_of_scope needs quote and already_met needs commit");
108
+ }
109
+ const value = parsed;
110
+ const needsDraft = value.points.some((point) => point.cause === "scope_gap" || point.cause === "missing_context");
111
+ if (value.scope_draft !== undefined && (typeof value.scope_draft !== "string" || !value.scope_draft.trim() || value.scope_draft.length > 2000)) {
112
+ throw new CliError("usage", "scope_draft must be a non-empty scope amendment up to 2000 characters");
113
+ }
114
+ if (needsDraft && typeof value.scope_draft !== "string") {
115
+ throw new CliError("usage", "scope_draft is required when a cause is scope_gap or missing_context; the assigner must confirm it with wu scope <n> --append");
116
+ }
117
+ return parsed;
118
+ }
73
119
  export function needsRetrospectiveInput(status, events = []) {
74
120
  if (status === "changes_requested")
75
121
  return true;
@@ -1037,6 +1083,19 @@ export async function wu(p, out) {
1037
1083
  out.print(withRuleText(fmt(r.unit), r, "submit"), r);
1038
1084
  return;
1039
1085
  }
1086
+ case "sendback-rule": {
1087
+ const body = sendbackRuleFromFile(str(p.flags, "file"));
1088
+ const r = await client.call("POST", `${base}/${num()}/sendback-rule`, body);
1089
+ const next = r.successor
1090
+ ? `\nBinding checklist assigned to stronger worker in successor WU #${r.successor.number}.`
1091
+ : r.reliability_unit
1092
+ ? `\nNo-blame reliability work queued as WU #${r.reliability_unit.number}.`
1093
+ : body.scope_draft
1094
+ ? `\nAssigner confirmation required: b9s wu scope ${num()} --append <exact scope_draft> --note "confirm send-back scope draft".`
1095
+ : "\nOriginal reviewer resumes the unit.";
1096
+ out.print(`${fmt(r.unit)}\nSend-back ruling recorded.${next}`, r);
1097
+ return;
1098
+ }
1040
1099
  case "approve":
1041
1100
  case "proceed":
1042
1101
  case "changes": {
@@ -1442,7 +1501,7 @@ export async function wu(p, out) {
1442
1501
  return;
1443
1502
  }
1444
1503
  default:
1445
- 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");
1504
+ 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");
1446
1505
  }
1447
1506
  }
1448
1507
  /** Queued units have no owner; ask the API to reject before any local worktree is made. */
@@ -1604,7 +1663,7 @@ function resolveRecordedBaseRef(recordedBase, target, n, branch) {
1604
1663
  }
1605
1664
  return fetched.ref;
1606
1665
  }
1607
- export function prepareWorktreeForWatcher(n, unit, def, exclude = []) {
1666
+ export function prepareWorktreeForWatcher(n, unit, def, exclude = [], inheritUrlRewrites = shouldInheritSandboxUrlRewrites()) {
1608
1667
  if (unit.branch && isShaBranchName(unit.branch))
1609
1668
  throw new CliError("no_branch", `recorded branch ${unit.branch} is a commit identifier, not a branch`, "Record and push the unit branch before retrying.");
1610
1669
  const target = unit.target ?? def.merge.target_branch;
@@ -1681,10 +1740,10 @@ export function prepareWorktreeForWatcher(n, unit, def, exclude = []) {
1681
1740
  // A branch checked out in the home checkout cannot also be attached to a linked worktree.
1682
1741
  if (!recoveryBase)
1683
1742
  throw new CliError("unit_worktree_prepare_failed", `cannot identify the committed work on WU #${n}'s home checkout; refusing to fork from the integration target`);
1684
- prepared = prepareWorktree(n, { ...unit, branch: null, worktree: null }, def, { positionals: [], flags: { branch: watcherBranch } }, exclude, recoveryBase);
1743
+ prepared = prepareWorktree(n, { ...unit, branch: null, worktree: null }, def, { positionals: [], flags: { branch: watcherBranch } }, exclude, recoveryBase, inheritUrlRewrites);
1685
1744
  }
1686
1745
  else {
1687
- prepared = prepareWorktree(n, unit, def, { positionals: [], flags: {} }, exclude);
1746
+ prepared = prepareWorktree(n, unit, def, { positionals: [], flags: {} }, exclude, undefined, inheritUrlRewrites);
1688
1747
  }
1689
1748
  if (prepared.mode === "here")
1690
1749
  throw new CliError("unit_worktree_prepare_failed", "watchers must prepare a linked unit worktree; --here is not available in watcher preparation");
@@ -1720,7 +1779,7 @@ export function prepareWorktreeForWatcher(n, unit, def, exclude = []) {
1720
1779
  needsRecord: !recorded || !existsSync(recorded) || !samePath(recorded, prepared.path) || unit.branch !== prepared.branch || (preparedHead !== null && unit.head !== preparedHead),
1721
1780
  recoveryRequired };
1722
1781
  }
1723
- function prepareWorktree(n, unit, def, p, exclude = [], baseRefOverride) {
1782
+ function prepareWorktree(n, unit, def, p, exclude = [], baseRefOverride, inheritUrlRewrites = shouldInheritSandboxUrlRewrites()) {
1724
1783
  // The unit's own target when it has one: a lane or release branch the work lands in.
1725
1784
  const target = unit.target ?? def.merge.target_branch;
1726
1785
  const log = (line) => process.stderr.write(`b9s: ${line}\n`);
@@ -1799,7 +1858,7 @@ function prepareWorktree(n, unit, def, p, exclude = [], baseRefOverride) {
1799
1858
  throw new UnitWorktreePrepareFailed(missingBranchFaultMessage(n, pinned, recordedBase, inspected.reason), { branch: pinned, recordedBase });
1800
1859
  }
1801
1860
  }
1802
- const result = !existing ? ensureUnitWorktree(path, pinned, baseRef, log, exclude) : { created: false, repaired: false };
1861
+ const result = !existing ? ensureUnitWorktree(path, pinned, baseRef, log, exclude, inheritUrlRewrites) : { created: false, repaired: false };
1803
1862
  if (shouldPushCreatedBranch) {
1804
1863
  const pushed = pushBranchToOrigin(pinned, path, "origin");
1805
1864
  if (!pushed.ok) {
@@ -1825,12 +1884,12 @@ function prepareWorktree(n, unit, def, p, exclude = [], baseRefOverride) {
1825
1884
  baseRef = at;
1826
1885
  }
1827
1886
  const branchCreated = fullSha(`refs/heads/${branch}`) === null;
1828
- const result = ensureUnitWorktree(path, branch, baseRef, log, exclude);
1887
+ const result = ensureUnitWorktree(path, branch, baseRef, log, exclude, inheritUrlRewrites);
1829
1888
  return { mode: "fresh", path, branch, created: result.created, branchCreated };
1830
1889
  }
1831
- function ensureUnitWorktree(path, branch, baseRef, log, exclude) {
1890
+ function ensureUnitWorktree(path, branch, baseRef, log, exclude, inheritUrlRewrites = shouldInheritSandboxUrlRewrites()) {
1832
1891
  try {
1833
- return ensureWorktree(path, branch, baseRef, process.cwd(), log, exclude, shouldInheritSandboxUrlRewrites());
1892
+ return ensureWorktree(path, branch, baseRef, process.cwd(), log, exclude, inheritUrlRewrites);
1834
1893
  }
1835
1894
  catch (error) {
1836
1895
  const cause = error.message;
package/dist/help.js CHANGED
@@ -170,6 +170,7 @@ Machine placement enforces configured session slots and reports machine pressure
170
170
  b9s wu supersede <n> --by <m> owner or assigner: this unit continues as #m; anyone blocked on #n now waits on #m
171
171
  b9s wu ask <n> "question" [--question <text>] owner, reviewer or assigner: a decision this unit cannot move without, including queued units (tag expert first, then the operator)
172
172
  b9s wu rule <n> "decision" [--ruling <text>|--note <text>] [--send-back-event <id> --cause <cause>] | --approve the tag's expert: answer an open question, or approve its proposal as written (operator questions are answered in the console); the event and cause record an explicit retrospective ruling
173
+ b9s wu sendback-rule <n> --file ruling.json send-back reviewer: record the binding point-by-point ruling; scope_gap/missing_context also need scope_draft, confirmed by the assigner with wu scope --append; environment/stale_base opens no-blame reliability work; out_of_scope needs quote and already_met needs commit
173
174
  b9s wu note <n> --note ".." [--annotation '<JSON object>'] add a note; assigner annotation links a cited scope finding to a cause and one-line reason
174
175
  b9s wu propose <n> "answer" owner, reviewer, assigner or expert: recommend an answer to the unit's open question, approvable as written
175
176
  b9s wu escalate <n> [--note ..] the tag's expert: pass the question to the operator
@@ -429,6 +430,8 @@ Use --admin <nickname> to select one of this machine's saved operator identities
429
430
  b9s-admin routing required-class <project> <n> (--class <p/h/m/e> | --clear) --reason "why"
430
431
  b9s-admin routing tag-required-class <project> <tag> (--class <p/h/m/e> | --clear) --reason "why"
431
432
  b9s-admin routing tier-migration <project> inspect cleared legacy min_tier units requiring operator required_class review
433
+ b9s-admin routing adjustments <project> inspect cause-backed per-tag model recommendations and assigner prompts
434
+ b9s-admin routing override <project> --tag <tag> --model <canonical-model> --reason "why" audit a project-local worker/reviewer model preference
432
435
  b9s-admin routing pool-suggestions <project> [--status pending|accepted|rejected|superseded|all]
433
436
  b9s-admin role delete <name> [--project p]
434
437
  b9s-admin channel create|delete <project> <name>
package/dist/version.js CHANGED
@@ -1 +1 @@
1
- export const CLI_VERSION = "0.12.153";
1
+ export const CLI_VERSION = "0.12.154";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "benignswarm",
3
- "version": "0.12.153",
3
+ "version": "0.12.154",
4
4
  "description": "b9s: chat, status board and evidence store for coding agents (benignswarm.org)",
5
5
  "license": "UNLICENSED",
6
6
  "repository": {