benignswarm 0.12.145 → 0.12.147

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.
@@ -2,8 +2,10 @@ import { spawn, spawnSync } from "node:child_process";
2
2
  import { bindSession, sessionOfExec, threadOfExec } from "../sessions.js";
3
3
  import { DEFAULT_TURN_COALESCE_SECONDS, MAX_TURN_COALESCE_SECONDS, shouldDeferTurn, startTurn, stopTurn } from "../turn.js";
4
4
  import { drainingUntil } from "../maintenance.js";
5
- import { claudeSettings, probeFor, turnHarness } from "../harnesses.js";
5
+ import { claudeSettings, probeFor, terminateClaudeSessionProcesses, turnHarness } from "../harnesses.js";
6
+ import { allocateClaudeEgressPortPair, buildClaudeEgressSupervisedShellCommand, resolveTrustedControlPlaneOrigin } from "../claude-egress-proxy.js";
6
7
  import { ANTIGRAVITY_SETTINGS_PLACEHOLDER, antigravitySessionTmpDir, antigravitySettings, finishAntigravityScratchCleanup, parseAntigravityTurnRuntime } from "../antigravity.js";
8
+ import { clearSessionSecrets, normalizeAndValidateSecretHosts, readSessionSecrets, wipeSecretMap } from "../session-secrets.js";
7
9
  import { cleanupAntigravitySandboxProbeRefs } from "../sandbox-probe.js";
8
10
  import { applyAck } from "./wake.js";
9
11
  import { launchdSessionTypeXml, lingerEnabled, machineDaemonPath, plistLaunchdDomain, loadSystemdUnit, readInstall, reloadLaunchAgent, removeService, requireInstall, systemdUnit, systemdUserDir, WATCH_LABEL_PREFIX, watcherServices } from "../install.js";
@@ -122,7 +124,34 @@ export async function watch(p, out, dependencies = {}) {
122
124
  || (value.maxBudgetUsd !== undefined && (typeof value.maxBudgetUsd !== "number" || !Number.isFinite(value.maxBudgetUsd) || value.maxBudgetUsd <= 0))) {
123
125
  throw new Error("invalid Claude turn runtime fields");
124
126
  }
125
- claudeRuntime = { sandbox: value.sandbox, writableRoots: value.writableRoots, ...(value.effort ? { effort: value.effort } : {}), ...(value.maxBudgetUsd ? { maxBudgetUsd: value.maxBudgetUsd } : {}) };
127
+ let secretEgress;
128
+ if (value.secretEgress !== undefined) {
129
+ if (value.sandbox !== "workspace-write")
130
+ throw new Error("secretEgress requires workspace-write sandbox");
131
+ if (!value.secretEgress || typeof value.secretEgress !== "object" || Array.isArray(value.secretEgress)) {
132
+ throw new Error("invalid secretEgress configuration");
133
+ }
134
+ const declaredHosts = normalizeAndValidateSecretHosts(value.secretEgress.declaredHosts, false);
135
+ if (!Array.isArray(value.secretEgress.envKeys) || value.secretEgress.envKeys.length < 1
136
+ || value.secretEgress.envKeys.some((k) => typeof k !== "string" || !/^[A-Z_][A-Z0-9_]{0,63}$/.test(k))) {
137
+ throw new Error("secretEgress.envKeys must list uppercase environment variable names");
138
+ }
139
+ if (value.secretEgress.apiUrl !== undefined) {
140
+ if (typeof value.secretEgress.apiUrl !== "string")
141
+ throw new Error("secretEgress.apiUrl must be a URL string");
142
+ new URL(value.secretEgress.apiUrl);
143
+ }
144
+ if (value.secretEgress.sessionKey !== undefined && (typeof value.secretEgress.sessionKey !== "string" || !value.secretEgress.sessionKey)) {
145
+ throw new Error("secretEgress.sessionKey must be a non-empty string");
146
+ }
147
+ secretEgress = {
148
+ declaredHosts,
149
+ envKeys: [...new Set(value.secretEgress.envKeys)],
150
+ ...(value.secretEgress.apiUrl ? { apiUrl: value.secretEgress.apiUrl } : {}),
151
+ ...(value.secretEgress.sessionKey ? { sessionKey: value.secretEgress.sessionKey } : {}),
152
+ };
153
+ }
154
+ claudeRuntime = { sandbox: value.sandbox, writableRoots: value.writableRoots, ...(value.effort ? { effort: value.effort } : {}), ...(value.maxBudgetUsd ? { maxBudgetUsd: value.maxBudgetUsd } : {}), ...(secretEgress ? { secretEgress } : {}) };
126
155
  }
127
156
  catch (error) {
128
157
  throw new CliError("usage", `--turn-claude-runtime must be valid Claude runtime JSON: ${error.message}`);
@@ -178,6 +207,9 @@ export async function watch(p, out, dependencies = {}) {
178
207
  return;
179
208
  stopping = true;
180
209
  stoppingCode = code;
210
+ if (dependencies.wakeOnceDependencies?.inMemorySecrets) {
211
+ wipeSecretMap(dependencies.wakeOnceDependencies.inMemorySecrets);
212
+ }
181
213
  releaseWatchLock?.();
182
214
  signalStop();
183
215
  // The harness command may be awaiting I/O that never settles. The lock is released first,
@@ -315,6 +347,12 @@ export async function watch(p, out, dependencies = {}) {
315
347
  log(`capability probe/report failed: ${e.message}`);
316
348
  }
317
349
  }
350
+ const secretCleanup = {
351
+ sessionKey: turn?.claudeRuntime?.secretEgress?.sessionKey ?? envSessionKey(turn?.machineSessionId),
352
+ claudeSession: turn?.harness === "claude-code" ? turn.session : undefined,
353
+ hasSecrets: Boolean(turn?.claudeRuntime?.secretEgress),
354
+ inMemorySecrets: dependencies.wakeOnceDependencies?.inMemorySecrets,
355
+ };
318
356
  if (!once && Date.now() - lastKeyCheck > KEY_CHECK_MS) {
319
357
  lastKeyCheck = Date.now();
320
358
  try {
@@ -322,12 +360,12 @@ export async function watch(p, out, dependencies = {}) {
322
360
  }
323
361
  catch (e) {
324
362
  if (e.code === "agent_benched") {
325
- stopBenchedWatcher(name, e.message, log);
363
+ stopBenchedWatcher(name, e.message, log, secretCleanup);
326
364
  finish(0);
327
365
  return stoppingCode;
328
366
  }
329
367
  if (e.code === "unauthorized") {
330
- stopRevokedWatcher(name, log);
368
+ stopRevokedWatcher(name, log, secretCleanup);
331
369
  finish(0);
332
370
  return stoppingCode;
333
371
  }
@@ -352,15 +390,20 @@ export async function watch(p, out, dependencies = {}) {
352
390
  }
353
391
  catch (e) {
354
392
  if (e.code === "agent_benched") {
355
- stopBenchedWatcher(name, e.message, log);
393
+ stopBenchedWatcher(name, e.message, log, secretCleanup);
356
394
  finish(0);
357
395
  return stoppingCode;
358
396
  }
359
397
  if (e.code === "unauthorized" && !once) {
360
- stopRevokedWatcher(name, log);
398
+ stopRevokedWatcher(name, log, secretCleanup);
361
399
  finish(0);
362
400
  return stoppingCode;
363
401
  }
402
+ if (e.code === "session_secrets_unavailable" && !once) {
403
+ log(`not starting turn: ${e.message}`);
404
+ await (dependencies.wait ?? waitIntervalOrStop)(watchPollMs(interval), stopped);
405
+ continue;
406
+ }
364
407
  if (e.code === "unit_worktree_diverged" && !once)
365
408
  log(e.message);
366
409
  else
@@ -379,12 +422,12 @@ export async function watch(p, out, dependencies = {}) {
379
422
  }
380
423
  catch (e) {
381
424
  if (e.code === "agent_benched") {
382
- stopBenchedWatcher(name, e.message, log);
425
+ stopBenchedWatcher(name, e.message, log, secretCleanup);
383
426
  finish(0);
384
427
  return stoppingCode;
385
428
  }
386
429
  if (e.code === "unauthorized") {
387
- stopRevokedWatcher(name, log);
430
+ stopRevokedWatcher(name, log, secretCleanup);
388
431
  finish(0);
389
432
  return stoppingCode;
390
433
  }
@@ -415,7 +458,7 @@ export async function watch(p, out, dependencies = {}) {
415
458
  // record the same actual payload bytes and kinds through the hook's existing metric call.
416
459
  await reportDelivery(name, update.text, update.delivery.by_kind, "watch");
417
460
  if (delivered)
418
- updateState(name, (onDisk) => ({ ...onDisk, ...(update.noticeNext ? { notice_state: update.noticeNext } : {}), ...(update.measureSnapshot ? { measure_state: update.measureSnapshot } : {}) }));
461
+ updateState(name, (onDisk) => ({ ...onDisk, ...(update.stalledNext ? { stalled_work_delivered: update.stalledNext } : {}), ...(update.noticeNext ? { notice_state: update.noticeNext } : {}), ...(update.measureSnapshot ? { measure_state: update.measureSnapshot } : {}) }));
419
462
  resumeBriefDelivered = resumeBriefDelivered || recoveryBriefWasDelivered(recovery, delivered);
420
463
  if (stopping)
421
464
  return stoppingCode;
@@ -439,6 +482,19 @@ async function waitIntervalOrStop(ms, stopped) {
439
482
  if (timer)
440
483
  clearTimeout(timer);
441
484
  }
485
+ /**
486
+ * One numbered wake-up at a time. Each wake-up carries a sequence number and asks the agent to
487
+ * acknowledge it first (b9s wake ack <n>); until it does, nothing else is queued for it, for
488
+ * any reason. Learned from Codex: a harness delivers queued prompts only after its current turn,
489
+ * so the old rule (pending clears when the agent's read cursors move, an operator message or a
490
+ * timeout queues another) let six or seven wake-ups pile up behind a busy turn. Delivered back to
491
+ * back, they pulled sol-architect off its task and it stopped with the task unfinished. The
492
+ * cursors moved because the agent was reading while it worked, not because it saw the wake-up.
493
+ */
494
+ function envSessionKey(explicitSessionId) {
495
+ const id = explicitSessionId ?? process.env.BSCHAT_MACHINE_SESSION_ID;
496
+ return id && id.trim() ? id.trim() : undefined;
497
+ }
442
498
  /** Bind only when the server says this identity has exactly one active owner assignment. */
443
499
  export async function resolveWatcherWorkUnitBinding(name) {
444
500
  const creds = loadAgent(name);
@@ -880,9 +936,35 @@ export async function wakeOnce(name, exec, unackedAfter, followDelay, log, model
880
936
  }
881
937
  turnCwd = preparedWorktree?.path ?? process.cwd();
882
938
  }
939
+ let turnEgressRuntime;
940
+ if (turnSink && dependencies.claudeRuntime?.secretEgress) {
941
+ if (dependencies.claudeRuntime.sandbox !== "workspace-write" || !turnExec?.includes(CLAUDE_SETTINGS_PLACEHOLDER)) {
942
+ throw new CliError("secret_egress_unenforced_claude-code", "Claude Code secret-bearing turns require workspace-write settings expansion");
943
+ }
944
+ const enrolledUrl = loadAgent(name).url;
945
+ const requestedApiUrl = dependencies.claudeRuntime.secretEgress.apiUrl ?? enrolledUrl;
946
+ try {
947
+ resolveTrustedControlPlaneOrigin({ apiUrl: requestedApiUrl, trustedControlPlaneUrl: enrolledUrl });
948
+ }
949
+ catch (error) {
950
+ throw new CliError("secret_egress_invalid_hosts", error.message);
951
+ }
952
+ const { httpProxyPort, socksProxyPort } = await allocateClaudeEgressPortPair();
953
+ turnEgressRuntime = { httpProxyPort, socksProxyPort, apiUrl: requestedApiUrl, trustedControlPlaneUrl: enrolledUrl };
954
+ }
883
955
  if (turnSink && dependencies.claudeRuntime && turnExec?.includes(CLAUDE_SETTINGS_PLACEHOLDER)) {
884
956
  const runtime = dependencies.claudeRuntime;
885
- const args = claudeSettings(runtime.sandbox, model, runtime.effort, process.cwd(), configRoot(), runtime.writableRoots, preparedWorktree ?? undefined);
957
+ const secretEgress = runtime.secretEgress
958
+ ? {
959
+ declaredHosts: runtime.secretEgress.declaredHosts,
960
+ apiUrl: turnEgressRuntime.apiUrl,
961
+ trustedControlPlaneUrl: turnEgressRuntime.trustedControlPlaneUrl,
962
+ provider,
963
+ httpProxyPort: turnEgressRuntime.httpProxyPort,
964
+ socksProxyPort: turnEgressRuntime.socksProxyPort,
965
+ }
966
+ : undefined;
967
+ const args = claudeSettings(runtime.sandbox, model, runtime.effort, process.cwd(), configRoot(), runtime.writableRoots, preparedWorktree ?? undefined, secretEgress);
886
968
  turnExec = turnExec.replace(CLAUDE_SETTINGS_PLACEHOLDER, args.map(shellQuote).join(" "));
887
969
  }
888
970
  if (turnSink && dependencies.antigravityRuntime && turnExec?.includes(ANTIGRAVITY_SETTINGS_PLACEHOLDER)) {
@@ -891,7 +973,7 @@ export async function wakeOnce(name, exec, unackedAfter, followDelay, log, model
891
973
  const args = antigravitySettings(runtime.sandbox, process.cwd(), configRoot(), runtime.apiHost, [...runtime.writableRoots, ...(preparedWorktree ? [preparedWorktree.path] : [])], runtime.b9sBin, runtime.nodeBin, name, preparedWorktree ?? undefined);
892
974
  turnExec = turnExec.replace(ANTIGRAVITY_SETTINGS_PLACEHOLDER, args.map(shellQuote).join(" "));
893
975
  }
894
- if (!(await deliver(name, turnExec, wake, line, u ? u.tier : "process", total, log, operatorNew ? "operator message; " : "", seq, turnSink, payload?.delivery.by_kind ?? u?.delivery.by_kind, provider, model, turnStdin, beforeTurn, { ...(dependencies.startTurn ? { startTurn: dependencies.startTurn } : {}), sessionId, workUnitBinding, workUnitBindingReason: bindingResolution?.reason ?? null, ...(turnCwd ? { cwd: turnCwd } : {}) }, allowTurn))) {
976
+ if (!(await deliver(name, turnExec, wake, line, u ? u.tier : "process", total, log, operatorNew ? "operator message; " : "", seq, turnSink, payload?.delivery.by_kind ?? u?.delivery.by_kind, provider, model, turnStdin, beforeTurn, { ...(dependencies.startTurn ? { startTurn: dependencies.startTurn } : {}), sessionId, workUnitBinding, workUnitBindingReason: bindingResolution?.reason ?? null, ...(turnCwd ? { cwd: turnCwd } : {}), ...(dependencies.claudeRuntime?.secretEgress ? { secretEgress: dependencies.claudeRuntime.secretEgress, egressRuntime: turnEgressRuntime } : {}), ...(dependencies.inMemorySecrets ? { inMemorySecrets: dependencies.inMemorySecrets } : {}) }, allowTurn))) {
895
977
  debug("no wake: delivery failed or turn guard denied the launch");
896
978
  return { sent: false, recoveryBriefDelivered: false };
897
979
  }
@@ -903,6 +985,7 @@ export async function wakeOnce(name, exec, unackedAfter, followDelay, log, model
903
985
  ...(processNews ? { watch_process_woken: lag.version } : {}),
904
986
  watch_pending: { seq, at: queuedAt, inbox_after: st.inbox_after, channel_read: st.channel_read ?? {} },
905
987
  watch_operator_at: u?.latestOperatorAt ?? st.watch_operator_at,
988
+ ...(u?.stalledNext ? { stalled_work_delivered: u.stalledNext } : {}),
906
989
  ...(u ? { notice_state: u.noticeNext } : {}),
907
990
  ...(u?.measureSnapshot ? { measure_state: u.measureSnapshot } : {}),
908
991
  watch_followed_since: undefined,
@@ -924,6 +1007,9 @@ async function recoveryBriefText(name, log) {
924
1007
  const CLAUDE_SETTINGS_PLACEHOLDER = "__B9S_CLAUDE_TURN_SETTINGS__";
925
1008
  export async function deliver(name, exec, wake, summary, tier, total, log, prefix, seq, turnSink, kinds = {}, provider, model, turnStdin = false, beforeTurn, dependencies = {}, allowTurn) {
926
1009
  if (!exec) {
1010
+ if (dependencies.secretEgress) {
1011
+ throw new CliError("secret_egress_unenforced_claude-code", "Claude Code secret-bearing delivery cannot run without an outer egress proxy turn command");
1012
+ }
927
1013
  process.stdout.write(wake + "\n");
928
1014
  return true;
929
1015
  }
@@ -940,18 +1026,69 @@ export async function deliver(name, exec, wake, summary, tier, total, log, prefi
940
1026
  const providerEnv = claudeTurnEnv(provider, turnModel, dependencies.providerRoot);
941
1027
  if (allowTurn && !(await allowTurn()))
942
1028
  return false;
1029
+ const turnSecretEnv = {};
1030
+ let launchCmd = cmd;
1031
+ const egressRunnerEnv = {};
1032
+ if (dependencies.secretEgress) {
1033
+ if (!dependencies.egressRuntime) {
1034
+ throw new CliError("secret_egress_unenforced_claude-code", "Claude Code secret-bearing turns require an active outer egress proxy boundary");
1035
+ }
1036
+ if (dependencies.inMemorySecrets) {
1037
+ for (const key of dependencies.secretEgress.envKeys) {
1038
+ const val = dependencies.inMemorySecrets[key];
1039
+ if (typeof val !== "string") {
1040
+ throw new CliError("session_secrets_unavailable", `required project secret ${key} is no longer in session memory`);
1041
+ }
1042
+ turnSecretEnv[key] = val;
1043
+ }
1044
+ }
1045
+ else {
1046
+ const keyId = dependencies.secretEgress.sessionKey ?? envSessionKey();
1047
+ if (!keyId) {
1048
+ throw new CliError("session_secrets_unavailable", `missing session secret reference for ${name}`);
1049
+ }
1050
+ Object.assign(turnSecretEnv, readSessionSecrets({
1051
+ sessionKey: keyId,
1052
+ expectedAgent: name,
1053
+ expectedHarness: "claude-code",
1054
+ expectedKeys: dependencies.secretEgress.envKeys,
1055
+ expectedDeclaredHosts: dependencies.secretEgress.declaredHosts,
1056
+ }));
1057
+ }
1058
+ const runnerConfig = {
1059
+ provider: provider ?? "anthropic",
1060
+ apiUrl: dependencies.egressRuntime.apiUrl,
1061
+ trustedControlPlaneUrl: dependencies.egressRuntime.trustedControlPlaneUrl,
1062
+ declaredHosts: dependencies.secretEgress.declaredHosts,
1063
+ httpProxyPort: dependencies.egressRuntime.httpProxyPort,
1064
+ socksProxyPort: dependencies.egressRuntime.socksProxyPort,
1065
+ mode: "shell",
1066
+ shellCommand: cmd,
1067
+ };
1068
+ egressRunnerEnv.B9S_CLAUDE_EGRESS_RUNNER_CONFIG = JSON.stringify(runnerConfig);
1069
+ launchCmd = buildClaudeEgressSupervisedShellCommand();
1070
+ }
943
1071
  beforeTurn?.();
944
1072
  const launchedAt = new Date().toISOString();
945
1073
  const binding = dependencies.workUnitBinding ?? null;
946
1074
  updateState(name, (onDisk) => ({ ...onDisk, watch_turn_binding: { launched_at: launchedAt, started_at: null, work_unit_number: binding?.work_unit_number ?? null, assignment_event_id: binding?.assignment_event_id ?? null, reason: binding ? null : dependencies.workUnitBindingReason ?? "agent has no in-progress work unit" } }));
947
- const startedTurn = (dependencies.startTurn ?? startTurn)(cmd, {
948
- ...env,
949
- BSCHAT_AGENT: name,
950
- ...(turnModel ? { BSCHAT_MODEL: turnModel } : {}),
951
- ...(dependencies.sessionId ? { BSCHAT_SESSION_ID: dependencies.sessionId } : {}),
952
- ...(provider ? { BSCHAT_PROVIDER: provider } : {}),
953
- ...providerEnv,
954
- }, seq, turnStdin ? wake : undefined, binding, dependencies.cwd);
1075
+ let startedTurn;
1076
+ try {
1077
+ startedTurn = (dependencies.startTurn ?? startTurn)(launchCmd, {
1078
+ ...env,
1079
+ BSCHAT_AGENT: name,
1080
+ ...(turnModel ? { BSCHAT_MODEL: turnModel } : {}),
1081
+ ...(dependencies.sessionId ? { BSCHAT_SESSION_ID: dependencies.sessionId } : {}),
1082
+ ...(provider ? { BSCHAT_PROVIDER: provider } : {}),
1083
+ ...providerEnv,
1084
+ ...egressRunnerEnv,
1085
+ ...turnSecretEnv,
1086
+ }, seq, turnStdin ? wake : undefined, binding, dependencies.cwd);
1087
+ }
1088
+ finally {
1089
+ wipeSecretMap(turnSecretEnv);
1090
+ wipeSecretMap(egressRunnerEnv);
1091
+ }
955
1092
  const startedAt = Number.isFinite(startedTurn.startedMs) ? new Date(startedTurn.startedMs).toISOString() : launchedAt;
956
1093
  updateState(name, (onDisk) => {
957
1094
  const pending = onDisk.watch_turn_binding;
@@ -982,13 +1119,24 @@ export async function deliver(name, exec, wake, summary, tier, total, log, prefi
982
1119
  }
983
1120
  return true;
984
1121
  }
1122
+ function cleanupWatcherSecrets(cleanup) {
1123
+ if (!cleanup)
1124
+ return;
1125
+ if (cleanup.inMemorySecrets)
1126
+ wipeSecretMap(cleanup.inMemorySecrets);
1127
+ if (cleanup.sessionKey)
1128
+ clearSessionSecrets(cleanup.sessionKey);
1129
+ if (cleanup.hasSecrets && cleanup.claudeSession)
1130
+ terminateClaudeSessionProcesses(cleanup.claudeSession);
1131
+ }
985
1132
  /**
986
1133
  * The agent's key no longer works here: it was moved to another machine (b9s-admin agent move
987
1134
  * revokes every key not minted for the new one) or retired. Keys are only ever revoked on purpose,
988
1135
  * so this watcher stops for good and removes its own service; otherwise launchd or systemd would
989
1136
  * restart it into the same 401 forever. A daemon that still runs the agent here reinstalls it.
990
1137
  */
991
- function stopRevokedWatcher(name, log) {
1138
+ function stopRevokedWatcher(name, log, cleanup) {
1139
+ cleanupWatcherSecrets(cleanup);
992
1140
  const label = `${WATCH_LABEL_PREFIX}${name.replace("/", ".")}`;
993
1141
  // By label, else by the --as it runs with: watchers installed before 0.9 carry labels without the
994
1142
  // project (org.benignswarm.watch.visualizer-creator), and missing them left a restart loop.
@@ -999,7 +1147,8 @@ function stopRevokedWatcher(name, log) {
999
1147
  if (svc)
1000
1148
  removeService(svc);
1001
1149
  }
1002
- function stopBenchedWatcher(name, reason, log) {
1150
+ function stopBenchedWatcher(name, reason, log, cleanup) {
1151
+ cleanupWatcherSecrets(cleanup);
1003
1152
  const label = `${WATCH_LABEL_PREFIX}${name.replace("/", ".")}`;
1004
1153
  const bare = name.split("/").pop();
1005
1154
  const svc = watcherServices().find((s) => s.label === label)
@@ -122,10 +122,17 @@ export async function pruneProjectWorktrees(creds, project, cwd, protection, log
122
122
  }))];
123
123
  const probe = freeSpaceProbe(report.prunable.map((item) => item.path));
124
124
  let removed = 0;
125
+ let removedPathCount = 0;
126
+ const removedPaths = [];
125
127
  for (const candidate of report.prunable) {
126
128
  const result = removePrunable(candidate, cwd, undefined, protection.inUse, true);
127
- if (result.removed)
129
+ if (result.removed) {
128
130
  removed++;
131
+ removedPathCount++;
132
+ removedPaths.push(candidate.path);
133
+ if (removedPaths.length > 5)
134
+ removedPaths.shift();
135
+ }
129
136
  log(result.removed ? `pruned ${candidate.path}${candidate.branch ? ` (${candidate.branch})` : ""}` : `kept ${candidate.path}: ${result.reason}`);
130
137
  }
131
138
  const freeSpace = probe.after();
@@ -137,7 +144,7 @@ export async function pruneProjectWorktrees(creds, project, cwd, protection, log
137
144
  log(`post-prune worktree scan failed: ${error.message}`);
138
145
  }
139
146
  }
140
- return { project, repo: before.repo, removed, free_space: freeSpace, dirty_closed: dirtyClosed };
147
+ return { project, repo: before.repo, removed, paths: removedPaths, paths_count: removedPathCount, free_space: freeSpace, dirty_closed: dirtyClosed };
141
148
  }
142
149
  /**
143
150
  * The project's worktree registry.
@@ -20,6 +20,7 @@ import { chooseAgentContextAction, contextModeFromRuntime, explicitContextCompac
20
20
  import { formatConfidenceMatrix, formatExplorationSummary, formatUnitRoutingExplanation } from "./routing-admin.js";
21
21
  import { formatStandingRuleSet } from "../standing-rules.js";
22
22
  import { projectOf } from "./agent.js";
23
+ import { consoleLink } from "../console-links.js";
23
24
  import { isAntigravityWorkspaceWrite } from "../antigravity.js";
24
25
  /** Only Claude's workspace-write sandbox needs SSH origins rewritten for its HTTP-only proxy. */
25
26
  export function shouldInheritClaudeSandboxUrlRewrites(env = process.env) {
@@ -583,7 +584,7 @@ export async function wu(p, out) {
583
584
  const reviewers = u.reviewers.map((r) => `${r.name}${r.tags.length ? ` for ${r.tags.map((t) => `#${t}`).join(" ")}` : ""}`).join(", ");
584
585
  const approvals = u.approvals.map((a) => a.name).join(", ");
585
586
  return [
586
- `WU #${u.number} [${u.status}] ${tags(u)} ${u.title}${flags ? ` (${flags})` : ""}${u.requires?.length ? `\n requires: ${u.requires.join(", ")}` : ""}`,
587
+ `WU #${u.number} [${u.status}]${u.stalled ? ` STALLED ${u.stalled.age_minutes}m · ${u.stalled.reason}` : ""} ${tags(u)} ${u.title}${flags ? ` (${flags})` : ""}${u.requires?.length ? `\n requires: ${u.requires.join(", ")}` : ""}`,
587
588
  u.candidate_record?.tags?.length ? ` ${u.candidate_record.agent} first-round approval: ${u.candidate_record.tags.map((x) => `#${x.tag} ${x.approved_first_round}/${x.units} (${Math.round(x.rate * 100)}%)`).join(", ")}` : null,
588
589
  ` owner ${u.owner_name || "unassigned (queued)"}${reviewers ? ` · reviewers ${reviewers}` : ""}${approvals ? ` · approved by ${approvals}` : ""}${u.uncovered?.length ? ` · awaiting ${u.uncovered.map((t) => `#${t}`).join(" ")}` : ""}`,
589
590
  Object.keys(u.tag_focus ?? {}).length ? ` review focus:\n${Object.entries(u.tag_focus).map(([tag, focus]) => ` #${tag}: ${focus}`).join("\n")}` : null,
@@ -826,7 +827,11 @@ export async function wu(p, out) {
826
827
  pushed = check.remoteBranch ? true : check.checked ? false : null;
827
828
  if (check.remoteBranch) {
828
829
  remoteCommitBranch = check.remoteBranch;
829
- where.branch = check.remoteBranch.replace(/^origin\//, "");
830
+ const containingBranch = check.remoteBranch.replace(/^origin\//, "");
831
+ where.branch = containingBranch;
832
+ if (submitUnit.owner_name === creds.agent && submitUnit.branch === localBranch && containingBranch === localBranch && where.head) {
833
+ await client.call("POST", `${base}/${num()}/activity`, { source: "branch_push", branch: localBranch, head: where.head });
834
+ }
830
835
  }
831
836
  else if (def.merge.require_pushed) {
832
837
  const message = formatRemoteCommitFailure(localBranch, check.checkedRef, check.reason ?? "no containing origin branch was found");
@@ -993,6 +998,19 @@ export async function wu(p, out) {
993
998
  out.print(`${fmt(r.unit)}\n${actionResult}`, r);
994
999
  return;
995
1000
  }
1001
+ case "reviewer": {
1002
+ const replace = str(p.flags, "replace");
1003
+ const withName = str(p.flags, "with");
1004
+ const note = str(p.flags, "note");
1005
+ if (!replace?.trim() || !note?.trim()) {
1006
+ throw new CliError("usage", 'wu reviewer <n> --replace <agent> [--with <agent>] --note "why this reviewer is being replaced"');
1007
+ }
1008
+ const r = await client.call("POST", `${base}/${num()}/reviewer`, {
1009
+ replace: replace.trim(), ...(withName?.trim() ? { with: withName.trim() } : {}), note: note.trim(),
1010
+ });
1011
+ out.print(withRuleText(fmt(r.unit), r, "submit"), r);
1012
+ return;
1013
+ }
996
1014
  case "approve":
997
1015
  case "proceed":
998
1016
  case "changes": {
@@ -1296,7 +1314,8 @@ export async function wu(p, out) {
1296
1314
  return;
1297
1315
  }
1298
1316
  case "show": {
1299
- const r = await client.call("GET", `${base}/${num()}`);
1317
+ const number = num();
1318
+ const r = await client.call("GET", `${base}/${number}`);
1300
1319
  const onlyScope = scopeOnlyOutput(r.unit, bool(p.flags, "scope-only"));
1301
1320
  if (onlyScope !== null) {
1302
1321
  out.print(onlyScope, { scope: onlyScope });
@@ -1309,7 +1328,7 @@ export async function wu(p, out) {
1309
1328
  const recoveryText = recovery ? `\nRecovery: ${recovery.available ? `available (${recovery.size ?? "?"} bytes, sha256 ${recovery.sha256 ?? "?"})` : "not verified"}${recovery.expires_at ? `; expires ${recovery.expires_at}` : ""}${recovery.manifest?.skipped?.length ? `; skipped ${recovery.manifest.skipped.length} regenerable path(s)` : ""}${recovery.manifest?.omitted?.length ? `; ${recovery.manifest.omitted.length} uncaptured path(s), source volume remains protected` : ""}${recovery.available ? `; restore: b9s wu recovery restore ${r.unit.number}` : ""}` : "";
1310
1329
  const routingLines = formatUnitRoutingExplanation(r.unit);
1311
1330
  const routingText = routingLines.length ? `\nRouting:\n${routingLines.join("\n")}` : "";
1312
- out.print(`${fmt(r.unit)}${routingText}${context ? `\n${context}` : ""}${lessons ? `\nWorker lessons (latest first):\n${lessons}` : ""}${recoveryText}\n${events}`, r);
1331
+ out.print(`${fmt(r.unit)}\nConsole: ${consoleLink("work", project, r.unit.number)}${routingText}${context ? `\n${context}` : ""}${lessons ? `\nWorker lessons (latest first):\n${lessons}` : ""}${recoveryText}\n${events}`, r);
1313
1332
  return;
1314
1333
  }
1315
1334
  case "list":
@@ -1321,12 +1340,21 @@ export async function wu(p, out) {
1321
1340
  if (str(p.flags, k))
1322
1341
  qs.set(k, str(p.flags, k));
1323
1342
  const r = await client.call("GET", `${base}${qs.size ? `?${qs}` : ""}`);
1324
- const rows = r.units.map((u) => ({ n: `#${u.number}`, status: u.status, tags: u.tags.map((t) => `#${t}`).join(" "), owner: u.owner_name, reviewers: u.reviewers.map((x) => x.name).join(",") || "-", awaiting: (u.uncovered ?? []).map((t) => `#${t}`).join(" ") || "-", base: u.lands_with ? `#${u.lands_with}` : "-", title: u.title.slice(0, 50) }));
1343
+ const rows = r.units.map((u) => ({ n: `#${u.number}`, status: u.stalled ? `STALLED ${u.stalled.age_minutes}m · ${u.stalled.reason} · ${u.status}` : u.status, tags: u.tags.map((t) => `#${t}`).join(" "), owner: u.owner_name, reviewers: u.reviewers.map((x) => x.name).join(",") || "-", awaiting: (u.uncovered ?? []).map((t) => `#${t}`).join(" ") || "-", base: u.lands_with ? `#${u.lands_with}` : "-", title: u.title.slice(0, 50) }));
1325
1344
  out.print(rows.length ? table(rows, ["n", "status", "tags", "owner", "reviewers", "awaiting", "base", "title"]) : "(no open work units; b9s wu list --all for closed ones)", r);
1326
1345
  return;
1327
1346
  }
1347
+ case "stalled": {
1348
+ const response = await client.call("GET", `${base}?all=1`);
1349
+ const units = response.units.filter((unit) => unit.stalled);
1350
+ const rows = units.map((unit) => ({ n: `#${unit.number}`, age: `${unit.stalled.age_minutes} min`, status: unit.status, owner: unit.owner_name || "unassigned", reason: unit.stalled.reason, title: unit.title }));
1351
+ out.print(rows.length ? table(rows, ["n", "age", "status", "owner", "reason", "title"]) : "(no stalled work units)", { project, units });
1352
+ if (rows.length)
1353
+ process.exitCode = 1;
1354
+ return;
1355
+ }
1328
1356
  default:
1329
- throw new CliError("usage", "wu open|assign|lands-with|start [--branch b|--here]|decline|submit|approve|changes|classify|tags|merge <n>|merge status <n>|done [--keep-worktree]|abandon|note|ask|rule|propose|show|list");
1357
+ throw new CliError("usage", "wu open|assign|lands-with|start [--branch b|--here]|decline|submit|approve|changes|classify|tags|merge <n>|merge status <n>|done [--keep-worktree]|abandon|note|ask|rule|propose|show|list|stalled");
1330
1358
  }
1331
1359
  }
1332
1360
  /** Queued units have no owner; ask the API to reject before any local worktree is made. */
@@ -1843,6 +1871,22 @@ export function lockWaiterActivity(waiter, nowMs) {
1843
1871
  const seconds = Math.floor(Math.max(0, nowMs - polledAt) / 1000);
1844
1872
  return ` · last poll ${seconds < 60 ? `${seconds}s` : `${Math.floor(seconds / 60)}m`} ago`;
1845
1873
  }
1874
+ function lockHolderLabel(holder, nowMs) {
1875
+ return `slot ${holder.slot}: ${holder.name}${holder.unit ? ` (WU #${holder.unit})` : ""}${holder.legacy === 1 ? " (legacy, no token)" : holder.job_id ? ` job ${holder.job_id}` : ""}${holder.note ? `: ${holder.note}` : ""}${holder.acquired_at ? ` since ${holder.acquired_at.slice(11, 16)} UTC` : ""}${lockActivity({ running: holder.running, acquired_at: holder.acquired_at, holder_legacy: holder.legacy }, nowMs)}`;
1876
+ }
1877
+ export function lockSlotsLabel(lock, nowMs) {
1878
+ if (!Number.isInteger(lock.capacity) || lock.capacity < 2)
1879
+ return lock.holder_name
1880
+ ? `held by ${lock.holder_name}${lock.unit ? ` (WU #${lock.unit})` : ""}${lock.holder_legacy === 1 ? " (legacy, no token)" : lock.holder_job_id ? ` job ${lock.holder_job_id}` : ""}${lock.note ? `: ${lock.note}` : ""} since ${lock.acquired_at.slice(11, 16)} UTC${lockActivity(lock, nowMs)}`
1881
+ : "free";
1882
+ const holders = Array.isArray(lock.holders) ? lock.holders : [];
1883
+ const slots = Array.from({ length: lock.capacity }, (_, index) => {
1884
+ const slot = index + 1;
1885
+ const holder = holders.find((item) => item.slot === slot);
1886
+ return holder ? lockHolderLabel(holder, nowMs) : `slot ${slot}: free`;
1887
+ });
1888
+ return `${lock.capacity} slots [${slots.join("; ")}]`;
1889
+ }
1846
1890
  export async function lock(p, out) {
1847
1891
  const name = resolveAgentName(str(p.flags, "as"));
1848
1892
  const creds = loadAgent(name);
@@ -1852,7 +1896,7 @@ export async function lock(p, out) {
1852
1896
  const lockName = p.positionals[1];
1853
1897
  if (cmd === "locks") {
1854
1898
  const r = await client.call("GET", `/projects/${project}/locks`);
1855
- out.print(r.locks.length ? r.locks.map((l) => `${l.name}${l.machine ? ` on ${l.machine}` : " (shared)"}: ${l.holder_name ? `held by ${l.holder_name}${l.unit ? ` (WU #${l.unit})` : ""}${l.holder_legacy === 1 ? " (legacy, no token)" : l.holder_job_id ? ` job ${l.holder_job_id}` : ""}${l.note ? `: ${l.note}` : ""} since ${l.acquired_at.slice(11, 16)} UTC${lockActivity(l, Date.now())}` : "free"}${l.waiting.length ? ` · waiting: ${l.waiting.map((w) => `${w.name}${w.unit ? ` (#${w.unit})` : ""}${w.legacy === 1 ? " (legacy, no token)" : w.job_id ? ` job ${w.job_id}` : ""}${w.note ? `: ${w.note}` : ""}${lockWaiterActivity(w, Date.now())}`).join(", ")}` : ""}`).join("\n") : "No locks in this project. Take one with: b9s lock <name> [--unit n]", r);
1899
+ out.print(r.locks.length ? r.locks.map((l) => `${l.name}${l.machine ? ` on ${l.machine}` : " (shared)"}: ${lockSlotsLabel(l, Date.now())}${l.waiting.length ? ` · waiting: ${l.waiting.map((w) => `${w.name}${w.unit ? ` (#${w.unit})` : ""}${w.legacy === 1 ? " (legacy, no token)" : w.job_id ? ` job ${w.job_id}` : ""}${w.note ? `: ${w.note}` : ""}${lockWaiterActivity(w, Date.now())}`).join(", ")}` : ""}`).join("\n") : "No locks in this project. Take one with: b9s lock <name> [--unit n]", r);
1856
1900
  return;
1857
1901
  }
1858
1902
  if (cmd === "lock" && lockName === "run" && (p.rest !== undefined || p.positionals.length > 2)) {
@@ -1867,7 +1911,7 @@ export async function lock(p, out) {
1867
1911
  const shared = bool(p.flags, "shared");
1868
1912
  const runToken = str(p.flags, "token") ?? `b9sjob_${randomBytes(24).toString("hex")}`;
1869
1913
  const machine = defaultMachine();
1870
- const deps = processDeps((method, path, body) => client.call(method, path, body, { retries: lockRunRetries(path) }), (line) => process.stderr.write(`[b9s] ${line}\n`));
1914
+ const deps = processDeps((method, path, body) => client.call(method, path, body, path.endsWith('/output') ? { signal: AbortSignal.timeout(5000) } : { retries: lockRunRetries(path) }), (line) => process.stderr.write(`[b9s] ${line}\n`));
1871
1915
  try {
1872
1916
  process.exitCode = await runUnderLock({
1873
1917
  project, identity: agentRef(creds), projectSelection: creds.project ? undefined : project,
@@ -0,0 +1,17 @@
1
+ const CONSOLE_URL = "https://benignswarm.org";
2
+ /** Build the canonical console destination used when CLI output names a record. */
3
+ export function consoleLink(kind, project, id) {
4
+ const base = CONSOLE_URL;
5
+ if (kind === "work") {
6
+ if (!project)
7
+ throw new Error("A work-unit console link requires its project");
8
+ return `${base}/projects/${encodeURIComponent(project)}/work?unit=${encodeURIComponent(String(id))}`;
9
+ }
10
+ if (kind === "evidence") {
11
+ if (!project)
12
+ throw new Error("An evidence console link requires its project");
13
+ return `${base}/projects/${encodeURIComponent(project)}/evidence/${encodeURIComponent(String(id))}`;
14
+ }
15
+ const query = new URLSearchParams({ need: String(id) });
16
+ return `${base}${project ? `/projects/${encodeURIComponent(project)}` : ""}/needs?${query}`;
17
+ }