benignswarm 0.12.153 → 0.12.155

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; });
@@ -329,6 +329,7 @@ export function processDeps(call, log, heartbeatIntervalMs = 15_000) {
329
329
  return;
330
330
  heartbeatInFlight = context.heartbeat().then(() => undefined, (error) => {
331
331
  heartbeatFailure = error;
332
+ stopHeartbeat();
332
333
  log(`job ${context.jobId} could not refresh its lock heartbeat; stopping the command to avoid running without the lock`);
333
334
  if (!childClosed)
334
335
  child.kill("SIGTERM");
@@ -8,6 +8,7 @@ import { loadAdmin, resolveAdminName, splitRef } from "../config.js";
8
8
  import { CliError } from "../errors.js";
9
9
  import { table } from "../output.js";
10
10
  import { CLI_VERSION } from "../version.js";
11
+ import { consoleLink } from "../console-links.js";
11
12
  import { runMachineResize } from "./machine-resize.js";
12
13
  import { poolSuggestionsAdmin } from "./routing-admin.js";
13
14
  import { readState, stateFilePath, stateTransferContents } from "../state.js";
@@ -128,6 +129,23 @@ export function machinePrepareCommand(options) {
128
129
  }
129
130
  export async function machineAdmin(action, rest, p, out) {
130
131
  const c = adminClient(p);
132
+ if (action === "diag") {
133
+ if (!rest[0])
134
+ throw new CliError("usage", "machine diag <name>");
135
+ const machine = rest[0];
136
+ const request = await c.call("POST", `/machines/${encodeURIComponent(machine)}/diagnostics`, {});
137
+ const deadline = Date.now() + 120_000;
138
+ while (Date.now() < deadline) {
139
+ const current = await c.call("GET", `/machines/${encodeURIComponent(machine)}/diagnostics/${encodeURIComponent(request.id)}`);
140
+ if (current.status === "complete" && current.evidence_id) {
141
+ return out.print(`Diagnostic evidence: evidence:${current.evidence_id}\nConsole: ${consoleLink("evidence", current.project, current.evidence_id)}`, current);
142
+ }
143
+ if (current.status === "expired")
144
+ throw new CliError("diagnostic_expired", "machine did not return the diagnostic bundle within two minutes");
145
+ await new Promise((resolve) => setTimeout(resolve, 1_000));
146
+ }
147
+ throw new CliError("diagnostic_timeout", `machine diagnostic request timed out; request ${request.id} may still complete`);
148
+ }
131
149
  if (action === "companion") {
132
150
  if (rest[0] !== "run" || !rest[1] || !/^bs_handoff_[A-Za-z0-9_-]{20,}$/.test(rest[1])) {
133
151
  throw new CliError("usage", "machine companion run <handoff-code> [--confirm <machine-name>] (paste the short-lived code from the signed-in console)");
@@ -21,6 +21,8 @@ import { installService, launchdFacts, launchdFactsLine, launchdGuidance, launch
21
21
  import { CLI_VERSION } from "../version.js";
22
22
  import { probeCapabilities } from "../capabilities.js";
23
23
  import { diskSpaceNotice } from "../notices.js";
24
+ import { collectMachineDiagnosticBundle } from "../machine-diagnostics.js";
25
+ import { consoleLink } from "../console-links.js";
24
26
  import { cachedClaudeProviderCheck, deepSeekKeyPath, verifyClaudeProvider } from "../providers.js";
25
27
  import { busyTurnPause, DEFAULT_TURNS_PER_HOUR, DEFAULT_UNPRODUCTIVE_PER_HOUR, resumeTurnGuard, verificationUnavailable } from "../turn-guard.js";
26
28
  import { defaultWorkspaceWritableRoots } from "../start-options.js";
@@ -1122,6 +1124,23 @@ export async function reconcile(m, log, reportIntervalSeconds = 30, deps) {
1122
1124
  const desired = me.sessions;
1123
1125
  const processScanner = deps?.worktreeProcessScanner ?? scanWorktreeProcesses;
1124
1126
  await answerWorktreeProcessQueries(client, desired, me.process_queries ?? [], log, processScanner);
1127
+ const diagnosticQueries = me.diagnostic_queries ?? [];
1128
+ if (diagnosticQueries.length) {
1129
+ const configuredWorkdir = me.machine?.workdir;
1130
+ const workdir = !configuredWorkdir ? join(homedir(), "bschat")
1131
+ : configuredWorkdir === "~" ? homedir()
1132
+ : configuredWorkdir.startsWith("~/") ? join(homedir(), configuredWorkdir.slice(2)) : configuredWorkdir;
1133
+ const bundle = collectMachineDiagnosticBundle(m.name, workdir, (me.projects ?? []).map((project) => project.name ?? "").filter(Boolean));
1134
+ for (const query of diagnosticQueries) {
1135
+ try {
1136
+ await client.call("POST", `/machines/me/diagnostics/${encodeURIComponent(query.id)}`, { bundle }, { retries: 2 });
1137
+ log(`uploaded diagnostic evidence for ${query.requester_name}`);
1138
+ }
1139
+ catch (error) {
1140
+ log(`diagnostic request ${query.id} failed: ${error.message}`);
1141
+ }
1142
+ }
1143
+ }
1125
1144
  if (Array.isArray(me.device_logins)) {
1126
1145
  handleDeviceLoginRequests(client, me.device_logins, log, deps?.deviceLoginInFlight ?? defaultDeviceLoginInFlight);
1127
1146
  }
@@ -3690,6 +3709,26 @@ export async function machine(p, out) {
3690
3709
  }
3691
3710
  const m = loadMachine();
3692
3711
  const log = (s) => process.stderr.write(`${new Date().toISOString()} b9s machine[${m.name}]: ${s}\n`);
3712
+ if (sub === "diag") {
3713
+ const target = p.positionals[2];
3714
+ if (!target || target !== m.name)
3715
+ throw new CliError("machine_scope", `this daemon is ${m.name}; agents may request diagnostics only from a machine they run on`);
3716
+ const agent = loadAgent(resolveAgentName(str(p.flags, "as"), process.env));
3717
+ const client = Client.forAgent(agent, undefined);
3718
+ const request = await client.call("POST", `/machines/${encodeURIComponent(target)}/diagnostics`, {});
3719
+ const deadline = Date.now() + 120_000;
3720
+ while (Date.now() < deadline) {
3721
+ const current = await client.call("GET", `/machines/${encodeURIComponent(target)}/diagnostics/${encodeURIComponent(request.id)}`);
3722
+ if (current.status === "complete" && current.evidence_id) {
3723
+ const result = { ...current, ref: `evidence:${current.evidence_id}` };
3724
+ return out.print(`Diagnostic evidence: evidence:${current.evidence_id}\nConsole: ${consoleLink("evidence", current.project, current.evidence_id)}`, result);
3725
+ }
3726
+ if (current.status === "expired")
3727
+ throw new CliError("diagnostic_expired", "machine did not return the diagnostic bundle within two minutes");
3728
+ await new Promise((resolve) => setTimeout(resolve, 1_000));
3729
+ }
3730
+ throw new CliError("diagnostic_timeout", `machine diagnostic request timed out; request ${request.id} may still complete`);
3731
+ }
3693
3732
  if (sub === "status") {
3694
3733
  const desired = (await Client.raw(m.url, m.key).call("GET", "/machines/me")).sessions;
3695
3734
  const state = readMachineState();
@@ -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
@@ -280,6 +281,7 @@ Machine placement enforces configured session slots and reports machine pressure
280
281
  b9s machine once run one daemon cycle
281
282
  b9s machine build-images run pending image builds
282
283
  b9s machine status show daemon state
284
+ b9s machine diag <machine> [--as <project>/<agent>] request and wait for a safe machine diagnostic evidence bundle
283
285
  b9s machine prepare [--codex-userns] [--bwrap-userns] [--agy-userns] [--print-hooks] [--print-apparmor] check machine readiness and required sandbox profiles
284
286
  --agy-userns opts into an AppArmor
285
287
  profile for the resolved agy binary if Ubuntu blocks its workspace-write terminal sandbox (passwordless sudo)
@@ -429,6 +431,8 @@ Use --admin <nickname> to select one of this machine's saved operator identities
429
431
  b9s-admin routing required-class <project> <n> (--class <p/h/m/e> | --clear) --reason "why"
430
432
  b9s-admin routing tag-required-class <project> <tag> (--class <p/h/m/e> | --clear) --reason "why"
431
433
  b9s-admin routing tier-migration <project> inspect cleared legacy min_tier units requiring operator required_class review
434
+ b9s-admin routing adjustments <project> inspect cause-backed per-tag model recommendations and assigner prompts
435
+ b9s-admin routing override <project> --tag <tag> --model <canonical-model> --reason "why" audit a project-local worker/reviewer model preference
432
436
  b9s-admin routing pool-suggestions <project> [--status pending|accepted|rejected|superseded|all]
433
437
  b9s-admin role delete <name> [--project p]
434
438
  b9s-admin channel create|delete <project> <name>
@@ -498,6 +502,7 @@ Machines (provisioned over your own ssh; a daemon on each runs the agent session
498
502
  install a profile only for the resolved ~/.local/bin/agy (Antigravity terminal sandbox)
499
503
  b9s-admin machine list
500
504
  b9s-admin machine show <name>
505
+ b9s-admin machine diag <name> request and wait for the daemon's redacted diagnostic evidence bundle
501
506
  b9s-admin machine remove <name> [--preview] [--confirm <name> --impact-revision <revision>]
502
507
  show includes host readiness, configured disk floors and named readiness refusals; removal previews sessions, work, keys, recovery blockers and replanned slots
503
508
  the API requires a fresh revision for removal
@@ -0,0 +1,200 @@
1
+ import { spawnSync } from "node:child_process";
2
+ import { readdirSync, readFileSync, statSync, statfsSync } from "node:fs";
3
+ import { homedir } from "node:os";
4
+ import { delimiter, join, parse } from "node:path";
5
+ import { configRoot } from "./config.js";
6
+ import { MACHINE_LABEL, watcherServices } from "./install.js";
7
+ import { scanLinesBackward, TAIL_MAX_BYTES } from "./tail-lines.js";
8
+ const SECRET_PATTERNS = [
9
+ /\bBearer\s+[A-Za-z0-9._~+/=-]+/gi,
10
+ /\bbs_(?:admin|agent|machine|boot)_[A-Za-z0-9_-]+\b/g,
11
+ /((?:[A-Za-z_][A-Za-z0-9_]*(?:TOKEN|SECRET|PASSWORD|CREDENTIAL|API_KEY|PRIVATE_KEY|ACCESS_KEY|AUTHORIZATION|_KEY)|--?[\w-]*(?:token|secret|password|credential|api[_-]?key|private[_-]?key|access[_-]?key|auth(?:orization)?|key))\s*(?:[=:]|\s)\s*)("?)[^",}\s]+/gi,
12
+ /\b(?:gh[pousr]_[A-Za-z0-9_]{20,}|xox[baprs]-[A-Za-z0-9-]{10,}|glpat-[A-Za-z0-9_-]{20,})\b/g,
13
+ /([a-z][a-z0-9+.-]*:\/\/)[^/@\s]+:[^/@\s]+@/gi,
14
+ ];
15
+ export function redactDiagnosticText(input) {
16
+ let text = input.replace(/[\x00-\x08\x0b\x0c\x0e-\x1f\x7f]/g, "");
17
+ for (const pattern of SECRET_PATTERNS)
18
+ text = text.replace(pattern, (match, prefix, quote) => typeof prefix === "string" ? `${prefix}${typeof quote === "string" ? quote : ""}[REDACTED]` : "[REDACTED]");
19
+ return text.slice(0, 4_000);
20
+ }
21
+ /** Keep only the known service entrypoint; arbitrary argv may contain credentials or private data. */
22
+ export function safeServiceArguments(args) {
23
+ const command = args.slice(1);
24
+ if (command[0] === "machine" && command[1] === "run")
25
+ return ["machine", "run"];
26
+ if (command[0] === "watch")
27
+ return ["watch"];
28
+ return [];
29
+ }
30
+ /** Return only a fixed process role; never upload the daemon's arbitrary argv text. */
31
+ export function diagnosticProcessLabel(command) {
32
+ if (/lock-run-supervisor/i.test(command))
33
+ return "b9s lock supervisor";
34
+ const cliCommand = /(?:^|\s)(?:\S*\/)?(?:b9s|bschat)(?:\s|$)/i.test(command)
35
+ || /\/(?:benignswarm|bschat)\/(?:packages\/cli\/)?dist\/index\.js(?:\s|$)/i.test(command);
36
+ if (!cliCommand)
37
+ return null;
38
+ if (/\bmachine\s+run\b/i.test(command))
39
+ return "b9s machine daemon";
40
+ if (/\bwatch\b/i.test(command))
41
+ return "b9s agent watcher";
42
+ return null;
43
+ }
44
+ function executable(pathValue, name) {
45
+ for (const dir of pathValue.split(delimiter)) {
46
+ const candidate = join(dir || ".", name);
47
+ try {
48
+ if (statSync(candidate).isFile())
49
+ return candidate;
50
+ }
51
+ catch { /* continue */ }
52
+ }
53
+ return null;
54
+ }
55
+ function treeSize(path, maxEntries = 500) {
56
+ let size = 0;
57
+ let visited = 0;
58
+ const walk = (dir, depth) => {
59
+ if (depth > 4 || visited >= maxEntries)
60
+ return;
61
+ let entries;
62
+ try {
63
+ entries = readdirSync(dir);
64
+ }
65
+ catch {
66
+ return;
67
+ }
68
+ for (const entry of entries) {
69
+ if (++visited > maxEntries)
70
+ break;
71
+ const child = join(dir, entry);
72
+ try {
73
+ const st = statSync(child);
74
+ if (st.isDirectory())
75
+ walk(child, depth + 1);
76
+ else if (st.isFile())
77
+ size += st.size;
78
+ }
79
+ catch { /* racing removal */ }
80
+ }
81
+ };
82
+ walk(path, 0);
83
+ return size;
84
+ }
85
+ /** Collect deliberately narrow host facts; never read arbitrary service environment variables. */
86
+ export function collectMachineDiagnosticBundle(machine, workdir, projectNames, env = process.env) {
87
+ const safePath = env.PATH ?? "/usr/local/bin:/usr/bin:/bin";
88
+ const home = homedir();
89
+ const service = watcherServices().find((entry) => entry.label === MACHINE_LABEL);
90
+ let serviceEnv = { PATH: safePath, HOME: home };
91
+ let workingDirectory = null;
92
+ let stdoutPath = null;
93
+ let stderrPath = null;
94
+ if (service?.kind === "launchd") {
95
+ const parsed = spawnSync("plutil", ["-convert", "json", "-o", "-", service.path], { encoding: "utf8", timeout: 2_000 });
96
+ if (parsed.status === 0)
97
+ try {
98
+ const plist = JSON.parse(parsed.stdout);
99
+ const allowed = plist.EnvironmentVariables ?? {};
100
+ serviceEnv = { PATH: typeof allowed.PATH === "string" ? allowed.PATH : safePath, HOME: typeof allowed.HOME === "string" ? allowed.HOME : home };
101
+ workingDirectory = typeof plist.WorkingDirectory === "string" ? plist.WorkingDirectory : null;
102
+ stdoutPath = typeof plist.StandardOutPath === "string" ? plist.StandardOutPath : null;
103
+ stderrPath = typeof plist.StandardErrorPath === "string" ? plist.StandardErrorPath : null;
104
+ }
105
+ catch { /* keep only the current process's safe defaults */ }
106
+ }
107
+ else if (service?.kind === "systemd") {
108
+ try {
109
+ const text = readFileSync(service.path, "utf8");
110
+ const envText = [...text.matchAll(/^Environment=(.*)$/gm)].map((match) => match[1]).join(" ");
111
+ const pathMatch = /(?:^|\s)"?PATH=([^"\s]*)"?/.exec(envText);
112
+ const homeMatch = /(?:^|\s)"?HOME=([^"\s]*)"?/.exec(envText);
113
+ serviceEnv = { PATH: pathMatch?.[1] ?? safePath, HOME: homeMatch?.[1] ?? home };
114
+ workingDirectory = /^WorkingDirectory=(.*)$/m.exec(text)?.[1]?.trim() ?? null;
115
+ stdoutPath = /^StandardOutput=append:(.*)$/m.exec(text)?.[1]?.trim() ?? null;
116
+ stderrPath = /^StandardError=append:(.*)$/m.exec(text)?.[1]?.trim() ?? null;
117
+ }
118
+ catch { /* keep only the current process's safe defaults */ }
119
+ }
120
+ const runtimes = {};
121
+ for (const [key, binary, args] of [["b9s", "b9s", ["--version"]], ["node", "node", ["--version"]], ["npm", "npm", ["--version"]]]) {
122
+ const path = executable(serviceEnv.PATH, binary);
123
+ const result = path ? spawnSync(path, [...args], { encoding: "utf8", timeout: 2_000, env: serviceEnv }) : null;
124
+ runtimes[key] = { path, version: result?.status === 0 ? redactDiagnosticText(result.stdout.trim()) : null };
125
+ }
126
+ const serviceInfo = service ? {
127
+ kind: service.kind, label: service.label, definition_path: service.path,
128
+ program: service.args?.[0] ? redactDiagnosticText(service.args[0]) : null,
129
+ args: safeServiceArguments(service.args ?? []),
130
+ working_directory: workingDirectory ? redactDiagnosticText(workingDirectory) : null,
131
+ stdout_path: stdoutPath ? redactDiagnosticText(stdoutPath) : null,
132
+ stderr_path: stderrPath ? redactDiagnosticText(stderrPath) : null,
133
+ environment: { PATH: redactDiagnosticText(serviceEnv.PATH), HOME: redactDiagnosticText(serviceEnv.HOME) }, runtimes,
134
+ } : null;
135
+ const logs = [];
136
+ for (const file of [join(configRoot(), "logs", "machine.out.log"), join(configRoot(), "logs", "machine.err.log")]) {
137
+ let lines = [];
138
+ try {
139
+ const newest = [];
140
+ scanLinesBackward(file, (line) => { if (line)
141
+ newest.push(line); return newest.length >= 250; }, undefined, TAIL_MAX_BYTES);
142
+ lines = newest.reverse().map(redactDiagnosticText);
143
+ }
144
+ catch { /* no log yet */ }
145
+ logs.push({ file: file.replace(home, "~"), lines });
146
+ }
147
+ const jobs = [];
148
+ for (const project of projectNames.slice(0, 30)) {
149
+ const root = join(workdir, project, ".ux-jobs");
150
+ let names;
151
+ try {
152
+ names = readdirSync(root).slice(-100);
153
+ }
154
+ catch {
155
+ continue;
156
+ }
157
+ for (const name of names) {
158
+ const path = join(root, name);
159
+ try {
160
+ const st = statSync(path);
161
+ if (st.isDirectory())
162
+ jobs.push({ name: `${project}/${name}`.slice(0, 200), age_seconds: Math.max(0, Math.floor((Date.now() - st.mtimeMs) / 1000)), size_bytes: treeSize(path) });
163
+ }
164
+ catch { /* job cleaned up concurrently */ }
165
+ }
166
+ }
167
+ jobs.sort((a, b) => a.age_seconds - b.age_seconds);
168
+ const disks = [];
169
+ const seen = new Set();
170
+ for (const path of [parse(home).root, home, workdir, ...projectNames.slice(0, 30).map((p) => join(workdir, p))]) {
171
+ try {
172
+ const st = statSync(path);
173
+ const key = String(st.dev);
174
+ if (seen.has(key))
175
+ continue;
176
+ seen.add(key);
177
+ const fs = statfsSync(path);
178
+ disks.push({ volume: path.replace(home, "~"), free_bytes: fs.bavail * fs.bsize, total_bytes: fs.blocks * fs.bsize });
179
+ }
180
+ catch { /* absent mount */ }
181
+ }
182
+ const ps = spawnSync("ps", process.platform === "darwin" ? ["-axo", "pid=,etime=,command="] : ["-eo", "pid=,etime=,args="], { encoding: "utf8", timeout: 2_000, env: { PATH: safePath, HOME: home } });
183
+ const processes = [];
184
+ if (ps.status === 0)
185
+ for (const line of ps.stdout.split(/\r?\n/)) {
186
+ const match = /^\s*(\d+)\s+(\S+)\s+(.+)$/.exec(line);
187
+ if (!match)
188
+ continue;
189
+ const command = diagnosticProcessLabel(match[3]);
190
+ if (!command)
191
+ continue;
192
+ const elapsed = match[2].split("-");
193
+ const parts = elapsed.pop().split(":").map(Number);
194
+ const seconds = parts.reduce((total, part) => total * 60 + part, 0) + (elapsed.length ? Number(elapsed[0]) * 86_400 : 0);
195
+ processes.push({ pid: Number(match[1]), command, age_seconds: seconds });
196
+ if (processes.length >= 100)
197
+ break;
198
+ }
199
+ return { collected_at: new Date().toISOString(), machine: redactDiagnosticText(machine), service: serviceInfo, logs, jobs: jobs.slice(0, 100), disks, processes };
200
+ }
package/dist/ux-jobs.js CHANGED
@@ -344,6 +344,7 @@ export const spawnAsyncCommand = (cmd, args, opts) => new Promise((resolve) => {
344
344
  env: opts.env,
345
345
  stdio: ["ignore", "pipe", "pipe"],
346
346
  shell: false,
347
+ detached: process.platform !== "win32",
347
348
  });
348
349
  let stdout = "";
349
350
  let stderr = "";
@@ -363,13 +364,36 @@ export const spawnAsyncCommand = (cmd, args, opts) => new Promise((resolve) => {
363
364
  });
364
365
  let timedOut = false;
365
366
  let aborted = false;
366
- const stopChild = () => {
367
- child.kill("SIGTERM");
368
- setTimeout(() => child.kill("SIGKILL"), 5_000).unref();
367
+ let stopping = false;
368
+ const signalTree = (signal) => {
369
+ if (!child.pid)
370
+ return;
371
+ if (process.platform === "win32") {
372
+ child.kill(signal);
373
+ return;
374
+ }
375
+ try {
376
+ process.kill(-child.pid, signal);
377
+ }
378
+ catch (error) {
379
+ if (error.code !== "ESRCH")
380
+ opts.onStderrChunk?.(`Could not signal command process group: ${error.message}\n`);
381
+ }
382
+ };
383
+ const stopChild = (immediate = false) => {
384
+ if (stopping)
385
+ return;
386
+ stopping = true;
387
+ if (immediate) {
388
+ signalTree("SIGKILL");
389
+ return;
390
+ }
391
+ signalTree("SIGTERM");
392
+ setTimeout(() => signalTree("SIGKILL"), 5_000).unref();
369
393
  };
370
394
  const onAbort = () => {
371
395
  aborted = true;
372
- stopChild();
396
+ stopChild(true);
373
397
  };
374
398
  opts.signal?.addEventListener("abort", onAbort, { once: true });
375
399
  const timer = setTimeout(() => {
@@ -1038,6 +1062,8 @@ export async function executeUxJob(machineClient, job, ctx, deps = {}) {
1038
1062
  return;
1039
1063
  heartbeatInFlight = lockContext.heartbeat().then(() => undefined, (error) => {
1040
1064
  heartbeatFailure = error;
1065
+ if (heartbeatTimer)
1066
+ clearInterval(heartbeatTimer);
1041
1067
  ctx.log(`${jobKind} job ${job.id} (${lockContext.jobId}) could not refresh its lock heartbeat; stopping the command to avoid running without the lock`);
1042
1068
  heartbeatController.abort();
1043
1069
  }).finally(() => {
package/dist/version.js CHANGED
@@ -1 +1 @@
1
- export const CLI_VERSION = "0.12.153";
1
+ export const CLI_VERSION = "0.12.155";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "benignswarm",
3
- "version": "0.12.153",
3
+ "version": "0.12.155",
4
4
  "description": "b9s: chat, status board and evidence store for coding agents (benignswarm.org)",
5
5
  "license": "UNLICENSED",
6
6
  "repository": {