benignswarm 0.12.109 → 0.12.111

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/args.js CHANGED
@@ -24,7 +24,7 @@ export const STRING_FLAGS = [
24
24
  "repeat", "summary-minutes", "churn", "unmet", "require-cited-changes", "checks-every", "propose", "waits-on",
25
25
  "sandbox", "thread", "turn-timeout", "turns-per-hour", "unproductive-per-hour", "turn-coalesce-seconds", "session", "operation",
26
26
  "plain", "if-yes", "if-no", "ssh", "variant", "count", "needs", "min-ram", "exclude", "carry", "from",
27
- "to-ssh", "wait", "writable", "writable-root", "dsh", "agy", "for", "until", "reason", "at", "requires",
27
+ "to-ssh", "ssh-from", "wait", "writable", "writable-root", "dsh", "agy", "for", "until", "reason", "at", "requires",
28
28
  "priority", "informs", "amend", "waive-informs", "text", "kind", "claim", "decision", "sha", "value", "expect",
29
29
  "expectations", "reworks", "cause", "lesson", "disputes", "annotation", "send-back-event", "confirm-causes", "floor",
30
30
  "tool", "processes", "arch", "arn", "base-image", "b9s-version", "cache", "caches", "commit", "dockerfile",
@@ -35,6 +35,7 @@ export const STRING_FLAGS = [
35
35
  "machine-session-id", "pool-sessions", "registry", "detail", "worktree",
36
36
  "purpose", "storage-mode", "hosts", "arn", "version-id",
37
37
  "mode", "weights", "quality-target", "half-life", "min-samples", "build-explore", "review-explore", "pause-build", "pause-review", "class",
38
+ "metadata-file",
38
39
  ];
39
40
  export const BOOL_FLAGS = [
40
41
  "latest", "no-restart", "json", "follow", "account", "help", "version", "broadcast", "create-channels",
@@ -11,6 +11,17 @@ import { CLI_VERSION } from "../version.js";
11
11
  import { runMachineResize } from "./machine-resize.js";
12
12
  import { poolSuggestionsAdmin } from "./routing-admin.js";
13
13
  import { readState, stateFilePath, stateTransferContents } from "../state.js";
14
+ /** WU #470: pool slots whose machine no longer fits and that nothing can take keep running; the server says "still running on <machines>; ...". */
15
+ const KEPT_IN_PLACE_RE = /^still running on ([^;]+);/;
16
+ export function keptInPlace(pools) {
17
+ return pools.flatMap((pool) => (pool.status?.unplaced ?? []).flatMap((x) => {
18
+ const m = KEPT_IN_PLACE_RE.exec(x.reason ?? "");
19
+ return m ? [{ pool: `${pool.project}/${pool.name}`, agent: x.agent, machines: m[1].split(",").map((n) => n.trim()), reason: x.reason }] : [];
20
+ }));
21
+ }
22
+ export function keptWarningLines(kept) {
23
+ return kept.length ? [`Warning: ${kept.length} slot(s) no longer fit their machine and nothing can take them, so they keep running where they are: ${kept.map((k) => `${k.agent} (${k.pool}, on ${k.machines.join(", ")})`).join("; ")}`] : [];
24
+ }
14
25
  /**
15
26
  * b9s-admin machine: provision machines over the operator's own ssh and declare the agent
16
27
  * sessions they run (docs/REMOTE-MACHINES.md). The server never sees an ssh credential: every ssh
@@ -189,6 +200,7 @@ export async function machineAdmin(action, rest, p, out) {
189
200
  liveReport = live.latest?.report ?? null;
190
201
  }
191
202
  catch { /* A machine without a live sample still uses its last stable report. */ }
203
+ const keptHere = keptInPlace(((await c.call("GET", "/pools")).pools ?? [])).filter((k) => k.machines.includes(m.name));
192
204
  const rep = liveReport ?? m.report ?? {};
193
205
  const pressureText = (pressure) => `some ${pressure?.some_avg10 ?? "unknown"}% / full ${pressure?.full_avg10 ?? "unknown"}% (10s avg)`;
194
206
  const agentPressure = rep.agent_cgroup_pressure;
@@ -233,7 +245,7 @@ export async function machineAdmin(action, rest, p, out) {
233
245
  const providers = rep.claude_code?.providers ?? {};
234
246
  const providerLines = Object.entries(providers).map(([provider, check]) => ` Claude Code ${provider}: ${check.logged_in ? "verified" : `NOT verified (${check.reason ?? "unknown reason"})`}`);
235
247
  const output = liveReport ? { ...r, machine: { ...m, report: rep } } : r;
236
- return out.print([...head, ...machineMacLines(rep.macos), ...machineGitLines(rep.git), ...cacheLines, ...capabilityLines, ...providerLines, rows.length ? table(rows, ["agent", "pool", "desired", "state", "turns_per_hour", "coalesce_s", "thread", "harness", "provider", "sandbox", "image", "model", "dir", "error", "last_turn"]) : " no sessions"].filter((line) => line !== null).join("\n"), output);
248
+ return out.print([...head, ...machineMacLines(rep.macos), ...machineGitLines(rep.git), ...cacheLines, ...capabilityLines, ...providerLines, rows.length ? table(rows, ["agent", "pool", "desired", "state", "turns_per_hour", "coalesce_s", "thread", "harness", "provider", "sandbox", "image", "model", "dir", "error", "last_turn"]) : " no sessions", ...keptHere.map((k) => ` kept in place (cannot move): ${k.agent} (${k.pool}): ${k.reason}`)].filter((line) => line !== null).join("\n"), output);
237
249
  }
238
250
  if (action === "maintenance") {
239
251
  // A window on the machine: no new turns from 15 min before, its agents away until it ends.
@@ -331,7 +343,8 @@ export async function machineAdmin(action, rest, p, out) {
331
343
  body = { slots: rest[1] === "auto" ? null : Number(rest[1]) };
332
344
  }
333
345
  const r = await c.call("PATCH", `/machines/${name}`, body);
334
- return out.print(`${name}: labels ${r.machine.labels.join(", ") || "(none)"}; slots ${r.machine.slots ?? "auto"}. Pools were re-placed: b9s-admin pool list`, r);
346
+ const kept = keptInPlace(((await c.call("GET", "/pools")).pools ?? []));
347
+ return out.print([`${name}: labels ${r.machine.labels.join(", ") || "(none)"}; slots ${r.machine.slots ?? "auto"}. Pools were re-placed: b9s-admin pool list`, ...keptWarningLines(kept)].join("\n"), { ...r, kept_in_place: kept });
335
348
  }
336
349
  if (action === "readiness") {
337
350
  const name = rest[0];
@@ -635,6 +648,39 @@ export async function poolAdmin(action, rest, p, out, argv) {
635
648
  throw new CliError("usage", "--turn-coalesce-seconds is only supported for individual machine sessions; pool settings do not support turn coalescing");
636
649
  }
637
650
  const c = adminClient(p);
651
+ if (action === "move") {
652
+ const [project, name] = (rest[0] ?? "").split("/");
653
+ const from = str(p.flags, "from");
654
+ const to = str(p.flags, "to");
655
+ const carry = str(p.flags, "carry") ?? "note";
656
+ if (!project || !name || !from || !to)
657
+ throw new CliError("usage", "pool move <project>/<name> --from <source-machine> --to <destination-machine> [--carry note|thread] [--ssh-from local|<host>] [--to-ssh <host>] [--thread <uuid>] [--wait min]");
658
+ if (carry !== "note" && carry !== "thread")
659
+ throw new CliError("usage", "--carry must be note or thread");
660
+ const requested = await c.call("POST", `/projects/${project}/pools/${name}/moves`, { from, to, carry });
661
+ const results = [];
662
+ for (const move of requested.moves) {
663
+ if (move.status !== "requested" || typeof move.id !== "string" || typeof move.agent !== "string") {
664
+ results.push(move);
665
+ continue;
666
+ }
667
+ const moveOut = { json: true, print: (_human, data) => {
668
+ const result = data;
669
+ results.push({ ...move, status: result.move?.status ?? "completed", result });
670
+ } };
671
+ const operationParsed = { ...p, flags: { ...p.flags, from: str(p.flags, "ssh-from") ?? from, "__pool-move-operation": move.id } };
672
+ delete operationParsed.flags.source;
673
+ delete operationParsed.flags["ssh-from"];
674
+ try {
675
+ await agentMove([`${project}/${move.agent}`], operationParsed, moveOut);
676
+ }
677
+ catch (error) {
678
+ results.push({ ...move, status: "blocked", reason: error instanceof Error ? error.message : String(error) });
679
+ }
680
+ }
681
+ const done = results.filter((result) => result.status === "completed").length;
682
+ return out.print(`Pool move ${project}/${name} ${from} → ${to}: ${done} moved, ${results.length - done} stayed with a reason.`, { project, pool: name, from, to, moves: results });
683
+ }
638
684
  if (action === "slot") {
639
685
  const [operation, target, ...extra] = rest;
640
686
  const parts = (target ?? "").split("/");
@@ -646,11 +692,19 @@ export async function poolAdmin(action, rest, p, out, argv) {
646
692
  const r = await c.call("POST", `/projects/${project}/pools/${name}/slots/${slot}/stop`, reason === undefined ? {} : { reason });
647
693
  return out.print(`Suspended ${target}; its machine will stop the session.`, r);
648
694
  }
695
+ const KEPT_IN_PLACE = KEPT_IN_PLACE_RE;
649
696
  const statusLines = (pool) => [
650
697
  `${pool.project}/${pool.name}: ${pool.count} × role ${pool.role ?? "(none)"}, ${pool.sandbox}; busy cap ${pool.turns_per_hour ?? 60}/hour, unproductive fault ${pool.unproductive_per_hour ?? 6}/hour; variants ${pool.variants.map((v) => `${v.tag}=${v.harness}:${v.model ?? "default"}${v.effort ? `:${v.effort}` : ""}${v.weight > 1 ? `*${v.weight}` : ""}${v.provider && v.provider !== "anthropic" ? `@${v.provider}` : ""}`).join(", ")}${pool.needs?.labels?.length ? `; needs ${pool.needs.labels.join(", ")}` : ""}${pool.needs?.min_ram_gb ? `; min ${pool.needs.min_ram_gb} GB` : ""}`,
651
698
  ...(pool.status?.placed ?? []).map((x) => ` ${x.agent.padEnd(32)} on ${x.machine}`),
652
- ...(pool.status?.unplaced ?? []).map((x) => ` ${x.agent.padEnd(32)} NOT PLACED: ${x.reason}`),
699
+ ...(pool.status?.unplaced ?? []).map((x) => KEPT_IN_PLACE.test(x.reason)
700
+ ? ` ${x.agent.padEnd(32)} KEPT IN PLACE (cannot move): ${x.reason}`
701
+ : ` ${x.agent.padEnd(32)} NOT PLACED: ${x.reason}`),
653
702
  ];
703
+ // WU #470: a slot whose machine no longer fits, with nowhere to go, keeps running; say so loudly after a change.
704
+ const keptWarning = (pool) => {
705
+ const kept = (pool.status?.unplaced ?? []).filter((x) => KEPT_IN_PLACE.test(x.reason)).map((x) => x.agent);
706
+ return kept.length ? [`Warning: ${kept.length} slot(s) no longer fit their machine and nothing can take them, so they keep running where they are: ${kept.join(", ")}`] : [];
707
+ };
654
708
  if (action === "set") {
655
709
  const [project, name] = (rest[0] ?? "").split("/");
656
710
  const variants = repeated(argv, "variant").map(parseVariant);
@@ -666,7 +720,7 @@ export async function poolAdmin(action, rest, p, out, argv) {
666
720
  if (uph !== undefined && (!/^\d+$/.test(uph) || Number(uph) < 1 || Number(uph) > 60))
667
721
  throw new CliError("usage", "--unproductive-per-hour must be a whole number from 1 to 60");
668
722
  const r = await c.call("PUT", `/projects/${project}/pools/${name}`, { role: str(p.flags, "role") ?? null, variants, count, sandbox: str(p.flags, "sandbox"), needs, ...(tt ? { turn_timeout: Number(tt) } : {}), ...(tph ? { turns_per_hour: Number(tph) } : {}), ...(uph ? { unproductive_per_hour: Number(uph) } : {}) });
669
- return out.print([...statusLines(r.pool), "Their machines' daemons start them within 30 s: b9s-admin machine show <machine>"].join("\n"), r);
723
+ return out.print([...statusLines(r.pool), ...keptWarning(r.pool), "Their machines' daemons start them within 30 s: b9s-admin machine show <machine>"].join("\n"), r);
670
724
  }
671
725
  if (action === "list" || action === undefined) {
672
726
  const r = await c.call("GET", rest[0] ? `/projects/${rest[0]}/pools` : "/pools");
@@ -854,10 +908,32 @@ function machineMoveReadinessError(machine, harness, provider, sandbox, liveSamp
854
908
  * change. The API does not receive source paths or SSH material and is not told the move completed
855
909
  * until the local handoff succeeded.
856
910
  */
911
+ export function poolMoveSourceBlockReason(sample, sessionId, nowMs = Date.now(), requestedAt) {
912
+ const interval = Number(sample?.report_interval_seconds ?? 30);
913
+ if (!sample?.at || !Number.isFinite(Date.parse(sample.at)) || nowMs - Date.parse(sample.at) > Math.max(30, interval) * 4_000)
914
+ return "source daemon has no fresh sample to confirm the turn ended";
915
+ if (requestedAt && Date.parse(sample.at) < Date.parse(requestedAt))
916
+ return "source daemon has not reported since this move was requested";
917
+ const observed = sample.sessions?.find((session) => session.id === sessionId);
918
+ const turnRunning = observed?.turn?.running ?? observed?.turn_running;
919
+ if (turnRunning !== false)
920
+ return "source daemon has not confirmed the harness turn ended";
921
+ const checkout = observed?.checkout;
922
+ if (checkout?.clean !== true || checkout?.uncommitted === true || checkout?.untracked === true)
923
+ return "source daemon has not confirmed a clean session checkout";
924
+ if (checkout?.pushed !== true || typeof checkout?.unpushed_commits !== "number") {
925
+ const unpushed = checkout?.unpushed_commits;
926
+ if (checkout?.pushed === false && typeof unpushed === "number")
927
+ return `session checkout has ${unpushed} unpushed ${unpushed === 1 ? "commit" : "commits"}`;
928
+ return "source daemon has not confirmed the session checkout is pushed";
929
+ }
930
+ return null;
931
+ }
857
932
  export async function agentMove(rest, p, out) {
858
933
  const ref = rest[0] ?? "";
859
934
  const [project, agent] = ref.split("/");
860
935
  const operationId = str(p.flags, "operation");
936
+ const poolMoveOperation = str(p.flags, "__pool-move-operation");
861
937
  const requestedTo = str(p.flags, "to");
862
938
  const requestedSandbox = str(p.flags, "sandbox");
863
939
  const requestedHarness = str(p.flags, "harness");
@@ -869,7 +945,7 @@ export async function agentMove(rest, p, out) {
869
945
  const requestedThread = str(p.flags, "thread");
870
946
  const from = str(p.flags, "from");
871
947
  const forceConfirmation = str(p.flags, "confirm-force");
872
- if (!project || !agent || (!operationId && (!requestedTo || !requestedSandbox)))
948
+ if (!project || !agent || (!operationId && !poolMoveOperation && (!requestedTo || !requestedSandbox)))
873
949
  throw new CliError("usage", "agent move <project>/<agent> (--to <machine> --sandbox <mode> | --operation <id>) [--dir <path>|auto] [--harness codex|claude-code] [--provider anthropic|deepseek] [--carry note|thread] [--from local|<ssh host>] [--model m] [--effort e] [--wait min] [--force --confirm-force <project>/<agent>]");
874
950
  if (forceConfirmation && !bool(p.flags, "force"))
875
951
  throw new CliError("usage", "--confirm-force is valid only with --force");
@@ -891,12 +967,15 @@ export async function agentMove(rest, p, out) {
891
967
  let model = requestedModel;
892
968
  let effort = requestedEffort;
893
969
  let thread = requestedThread ?? null;
894
- if (operationId) {
895
- const loaded = await c.call("GET", `${moveRoute}/${encodeURIComponent(operationId)}`);
970
+ if (operationId || poolMoveOperation) {
971
+ const continuationId = operationId ?? poolMoveOperation;
972
+ const loaded = await c.call("GET", `${moveRoute}/${encodeURIComponent(continuationId)}`);
896
973
  move = loaded.move;
897
974
  if (move.status !== "requested")
898
- throw new CliError("move_not_awaiting_execution", `move operation ${operationId} is ${move.status}; only a requested operation can be continued`);
975
+ throw new CliError("move_not_awaiting_execution", `move operation ${continuationId} is ${move.status}; only a requested operation can be continued`);
899
976
  const target = move.target;
977
+ if (poolMoveOperation && !target.pool_move)
978
+ throw new CliError("move_not_pool_operation", `move operation ${continuationId} is not an authorized pool slot move`);
900
979
  const expected = [
901
980
  ["--to", requestedTo, move.to], ["--sandbox", requestedSandbox, target.sandbox], ["--harness", requestedHarness, target.harness],
902
981
  ["--provider", requestedProvider, target.provider], ["--carry", requestedCarry, move.carry], ["--dir", requestedDir, target.dir],
@@ -904,11 +983,11 @@ export async function agentMove(rest, p, out) {
904
983
  ];
905
984
  for (const [flag, supplied, stored] of expected) {
906
985
  if (supplied !== undefined && supplied !== (stored == null ? undefined : String(stored))) {
907
- throw new CliError("move_option_mismatch", `${flag}=${supplied} does not match move operation ${operationId}${stored == null ? " (not set on the operation)" : ` (${stored})`}`);
986
+ throw new CliError("move_option_mismatch", `${flag}=${supplied} does not match move operation ${continuationId}${stored == null ? " (not set on the operation)" : ` (${stored})`}`);
908
987
  }
909
988
  }
910
989
  if (str(p.flags, "turn-timeout") !== undefined && Number(str(p.flags, "turn-timeout")) !== target.turn_timeout) {
911
- throw new CliError("move_option_mismatch", `--turn-timeout=${str(p.flags, "turn-timeout")} does not match move operation ${operationId} (${target.turn_timeout})`);
990
+ throw new CliError("move_option_mismatch", `--turn-timeout=${str(p.flags, "turn-timeout")} does not match move operation ${continuationId} (${target.turn_timeout})`);
912
991
  }
913
992
  to = String(move.to);
914
993
  sandbox = String(target.sandbox);
@@ -968,6 +1047,26 @@ export async function agentMove(rest, p, out) {
968
1047
  if (!out.json)
969
1048
  say(` move ${move.id}: ${move.from ?? "source"} → ${to}; other agent keys will be revoked only after completion`);
970
1049
  await c.call("PATCH", progressRoute, { status: "checking", expected_status: "requested", detail: "trusted CLI is checking local readiness and preparing the handoff" });
1050
+ const confirmPoolMoveSource = async () => {
1051
+ if (!poolMoveOperation)
1052
+ return;
1053
+ const createdAt = move.created_at;
1054
+ const sourceSessionId = move.source_session_id;
1055
+ const waitMinutes = Number(str(p.flags, "wait") ?? "10");
1056
+ const deadline = Date.now() + Math.max(0, waitMinutes) * 60_000;
1057
+ let reason = null;
1058
+ do {
1059
+ const sample = await c.call("GET", `/machines/${encodeURIComponent(move.from ?? "")}/live`);
1060
+ reason = poolMoveSourceBlockReason(sample.latest, sourceSessionId ?? "", Date.now(), createdAt);
1061
+ if (!reason || !["has not confirmed the harness turn ended", "has not reported since this move was requested", "has no fresh sample", "has not confirmed a clean session checkout", "has not confirmed the session checkout is pushed"].some((fragment) => reason.includes(fragment)))
1062
+ break;
1063
+ if (Date.now() >= deadline)
1064
+ break;
1065
+ await new Promise((resolve) => setTimeout(resolve, Math.min(5_000, deadline - Date.now())));
1066
+ } while (Date.now() < deadline);
1067
+ if (reason)
1068
+ throw new CliError("source_not_ready", reason);
1069
+ };
971
1070
  let problems = [];
972
1071
  const skippedWorktrees = [];
973
1072
  const destinationHost = str(p.flags, "to-ssh") ?? to;
@@ -977,8 +1076,9 @@ export async function agentMove(rest, p, out) {
977
1076
  const readinessError = machineMoveReadinessError(destination.machine, harness, provider, sandbox, live.latest ?? null);
978
1077
  if (readinessError)
979
1078
  throw new CliError("destination_not_ready", readinessError);
1079
+ await confirmPoolMoveSource();
980
1080
  // 1. Work in progress must be on origin, or it stays behind on the old machine.
981
- const units = (await c.call("GET", `/projects/${project}/work-units?agent=${encodeURIComponent(agent)}`)).units.filter((u) => ["assigned", "open", "changes_requested", "in_review", "approved"].includes(u.status));
1081
+ const units = (await c.call("GET", `/projects/${project}/work-units?agent=${encodeURIComponent(agent)}`)).units.filter((u) => (!poolMoveOperation || u.owner_name === agent) && ["assigned", "open", "changes_requested", "in_review", "approved"].includes(u.status));
982
1082
  if (units.length && !move.from)
983
1083
  throw new CliError("source_machine_unknown", `the move operation has active units but no recorded source machine; cannot scope their worktrees on ${from}`);
984
1084
  const sourceMachine = move.from ?? from;
@@ -1051,9 +1151,13 @@ export async function agentMove(rest, p, out) {
1051
1151
  for (const record of worktrees.filter((w) => w.machine === sourceMachine && Array.isArray(w.agents) && w.agents.some((a) => a?.name === agent))) {
1052
1152
  const unit = units.find((u) => u.owner_name === agent && (u.worktree === record.path || (u.branch && u.branch === record.branch)))
1053
1153
  ?? units.find((u) => Array.isArray(u.reviewers) && u.reviewers.some((r) => r?.name === agent));
1154
+ if (poolMoveOperation && !unit)
1155
+ continue;
1054
1156
  addInspection(unit ?? null, record.path, unit ? `#${unit.number} (${unit.branch ?? "no branch recorded"})` : `agent worktree ${record.path}`);
1055
1157
  }
1056
1158
  for (const record of worktrees.filter((w) => w.machine !== sourceMachine && Array.isArray(w.agents) && w.agents.some((a) => a?.name === agent))) {
1159
+ if (poolMoveOperation && !units.some((u) => u.owner_name === agent && (u.worktree === record.path || (u.branch && u.branch === record.branch))))
1160
+ continue;
1057
1161
  skippedWorktrees.push(`agent worktree ${record.path} is recorded on ${record.machine}, not ${sourceMachine}`);
1058
1162
  }
1059
1163
  for (const { unit: u, path: worktree, label } of inspections) {
@@ -1144,6 +1248,8 @@ export async function agentMove(rest, p, out) {
1144
1248
  say(note ? ` resume note saved: ${note.title}` : ` no resume note within ${wait} min; it starts from its units, status and chat`);
1145
1249
  }
1146
1250
  }
1251
+ if (poolMoveOperation)
1252
+ await confirmPoolMoveSource();
1147
1253
  if (transferAgentState(ref, from, destinationHost))
1148
1254
  say(` read cursors, follows and watcher state copied to ${destinationHost}`);
1149
1255
  if (!model || !effort) {
@@ -1158,15 +1264,17 @@ export async function agentMove(rest, p, out) {
1158
1264
  }
1159
1265
  catch (error) {
1160
1266
  const detail = error instanceof Error ? error.message : String(error);
1161
- const recordedDetail = error instanceof CliError && error.code === "destination_not_ready"
1162
- ? "destination harness, login, or sandbox readiness check failed"
1163
- : error instanceof CliError && error.code === "unpushed_work"
1164
- ? "source Git preflight found dirty, unpushed, or unavailable worktrees"
1165
- : error instanceof CliError && error.code === "git_preflight_failed"
1166
- ? "source Git inspection could not confirm worktree state"
1167
- : error instanceof CliError && error.code === "force_confirmation_required"
1168
- ? "source-only work was not explicitly confirmed"
1169
- : "local source check or context handoff failed";
1267
+ const recordedDetail = error instanceof CliError && error.code === "source_not_ready"
1268
+ ? detail
1269
+ : error instanceof CliError && error.code === "destination_not_ready"
1270
+ ? "destination harness, login, or sandbox readiness check failed"
1271
+ : error instanceof CliError && error.code === "unpushed_work"
1272
+ ? "source Git preflight found dirty, unpushed, or unavailable worktrees"
1273
+ : error instanceof CliError && error.code === "git_preflight_failed"
1274
+ ? "source Git inspection could not confirm worktree state"
1275
+ : error instanceof CliError && error.code === "force_confirmation_required"
1276
+ ? "source-only work was not explicitly confirmed"
1277
+ : "local source check or context handoff failed";
1170
1278
  try {
1171
1279
  const refusalReason = error instanceof CliError ? `${error.code}: ${recordedDetail}` : recordedDetail;
1172
1280
  await c.call("PATCH", progressRoute, { status: "blocked", detail: recordedDetail, refusal_reason: refusalReason.slice(0, 1000) });
@@ -8,7 +8,7 @@ import { Client } from "../client.js";
8
8
  import { configRoot, loadAgent, resolveAgentName, saveAgent } from "../config.js";
9
9
  import { CliError } from "../errors.js";
10
10
  import { AGY_APPARMOR_PATH, agyAppArmorProfile, BWRAP_APPARMOR_PATH, bwrapAppArmorProfile, CODEX_APPARMOR_PATH, CODEX_MANAGED_DIR, codexAppArmorProfile, codexManagedHooks, isCodexManagedRequirements } from "../harness.js";
11
- import { applySparse } from "../git.js";
11
+ import { applySparse, sessionCheckoutFacts } from "../git.js";
12
12
  import { drainingUntil, writeMaintenance } from "../maintenance.js";
13
13
  import { TURN_HARNESSES, claudeFacts, claudeSandbox, dshFacts, dshProcesses, probeFor, sessionProcesses } from "../harnesses.js";
14
14
  import { readState, writeState } from "../state.js";
@@ -22,7 +22,7 @@ import { defaultWorkspaceWritableRoots } from "../start-options.js";
22
22
  import { antigravityPath, antigravitySandboxPermissions, antigravityTurnArgs, parseAntigravityJson } from "../antigravity.js";
23
23
  import { bootTimeMs } from "../boot-time.js";
24
24
  import { DEFAULT_CACHE_FLOOR_PCT, manageBuildCaches } from "../build-caches.js";
25
- import { agentContainerName, agentContainerRunArgs, detectEc2Host, ensurePinnedImagePulled, isolatedBuildCommand, isolatedDevcontainerBuildCommand, isolatedImagePullCommands, isolatedSubprocessEnv, probeContainerImdsIsolation, networklessRuntimeWrapper, probeImdsIsolation, probeNestedSandbox, readGitIdentity, resolveSessionSecretDelivery, resolveWritableMounts, validateDevcontainerSpec, BUILD_SECRET_KEY_NAME_RE, BUILD_SECRET_CONTENT_RE, containsBuildSecretMaterial, sanitizeBuildDiagnosticText, } from "../container.js";
25
+ import { agentContainerName, agentContainerRunArgs, detectEc2Host, ensurePinnedImagePulled, isolatedBuildCommand, isolatedDevcontainerBuildCommand, isolatedImagePullCommands, isolatedSubprocessEnv, probeContainerImdsIsolation, networklessRuntimeWrapper, parseContainerRuntimeVersion, probeImdsIsolation, probeNestedSandbox, readGitIdentity, resolveSessionSecretDelivery, resolveWritableMounts, validateDevcontainerSpec, BUILD_SECRET_KEY_NAME_RE, BUILD_SECRET_CONTENT_RE, containsBuildSecretMaterial, sanitizeBuildDiagnosticText, } from "../container.js";
26
26
  import { machineEnvironmentChecks } from "../environment-checks.js";
27
27
  import { machineResourceTelemetry, parsePageSize } from "../machine-telemetry.js";
28
28
  import { macReadiness, macReadinessSteps } from "../macos-readiness.js";
@@ -558,8 +558,36 @@ export async function reconcilePendingImageBuilds(client, projects, opts) {
558
558
  }
559
559
  return results;
560
560
  }
561
+ const PINNED_IMAGE_REF_RE = /^[a-z0-9][a-z0-9._:/-]*@sha256:[a-f0-9]{64}$/i;
562
+ export function extractPinnedImageDigest(imageRef) {
563
+ if (!imageRef)
564
+ return null;
565
+ const match = /@(sha256:[a-f0-9]{64})$/i.exec(imageRef.trim());
566
+ return match ? match[1].toLowerCase() : null;
567
+ }
568
+ /** Inspect the actual running container's pinned image reference instead of trusting desired config. */
569
+ export function inspectContainerImage(runtime, containerName, runner = syncRunner) {
570
+ const res = runner(runtime, ["inspect", "-f", "{{.Config.Image}}", containerName], {
571
+ timeout: 10_000,
572
+ env: isolatedSubprocessEnv(process.env),
573
+ });
574
+ if (res.status !== 0)
575
+ return null;
576
+ const firstLine = (res.stdout ?? "").split(/\r?\n/)[0]?.trim() ?? "";
577
+ const imageDigest = extractPinnedImageDigest(firstLine);
578
+ if (!firstLine || !imageDigest || !PINNED_IMAGE_REF_RE.test(firstLine))
579
+ return null;
580
+ return { imageReference: firstLine, imageDigest };
581
+ }
582
+ function readContainerRuntimeVersion(runtime, runner) {
583
+ const res = runner(runtime, ["--version"], { timeout: 10_000, env: isolatedSubprocessEnv(process.env) });
584
+ if (res.status !== 0)
585
+ return null;
586
+ return parseContainerRuntimeVersion(res.stdout);
587
+ }
561
588
  export function resolveContainerLaunchPrereqs(opts) {
562
- const nested = opts.sandboxReport ?? (opts.probeSandbox ?? probeNestedSandbox)({ runner: opts.runner });
589
+ const runner = opts.runner ?? syncRunner;
590
+ const nested = opts.sandboxReport ?? (opts.probeSandbox ?? probeNestedSandbox)({ runner });
563
591
  if (!nested.runtime) {
564
592
  throw new Error("container isolation required but neither podman nor docker is available; refusing unisolated host fallback");
565
593
  }
@@ -585,7 +613,8 @@ export function resolveContainerLaunchPrereqs(opts) {
585
613
  if (!imageDigest || !bareDigest) {
586
614
  throw new Error(`container session for ${opts.s.agent} has no ready pinned @sha256 project image digest; refusing unisolated host fallback`);
587
615
  }
588
- return { runtime: nested.runtime, imageDigest, bareDigest };
616
+ const version = nested.version ?? readContainerRuntimeVersion(nested.runtime, runner);
617
+ return { runtime: nested.runtime, version, imageDigest, bareDigest };
589
618
  }
590
619
  export function resolveContainerImageProbePrereqs(opts) {
591
620
  const pinnedRef = resolvePinnedImageRef(opts.project.image);
@@ -833,7 +862,8 @@ export async function reconcile(m, log, reportIntervalSeconds = 30, deps) {
833
862
  });
834
863
  const me = await client.call("GET", "/machines/me");
835
864
  const desired = me.sessions;
836
- await answerWorktreeProcessQueries(client, desired, me.process_queries ?? [], log, deps?.worktreeProcessScanner ?? scanWorktreeProcesses);
865
+ const processScanner = deps?.worktreeProcessScanner ?? scanWorktreeProcesses;
866
+ await answerWorktreeProcessQueries(client, desired, me.process_queries ?? [], log, processScanner);
837
867
  if (Array.isArray(me.device_logins)) {
838
868
  handleDeviceLoginRequests(client, me.device_logins, log, deps?.deviceLoginInFlight ?? defaultDeviceLoginInFlight);
839
869
  }
@@ -907,13 +937,13 @@ export async function reconcile(m, log, reportIntervalSeconds = 30, deps) {
907
937
  const persisted = readState(s.agent).harness_session;
908
938
  const thread = local?.thread ?? s.thread ?? (persisted?.harness === s.harness ? persisted.session_id : null);
909
939
  const dir = s.dir || (s.project ? join(workdir ?? join(homedir(), "bschat"), s.project, s.agent_name) : "");
910
- const facts = stoppedSessionFacts(dir, thread, undefined, undefined, () => {
940
+ const facts = stoppedSessionFacts(dir, thread, undefined, (path) => processScanner(path, { project_roots: [path], foreign_roots: [] }), () => {
911
941
  if (!thread || !TURN_HARNESSES.includes(s.harness))
912
942
  return null;
913
943
  const phase = probeFor(s.harness, thread, s.agent).phase();
914
944
  return "missing" in phase ? null : phase.running;
915
945
  });
916
- out.push({ id: s.id, state: "stopped", ...facts });
946
+ out.push({ id: s.id, state: "stopped", ...facts, ...(s.pool_move_pending ? { checkout: sessionCheckoutFacts(dir) } : {}) });
917
947
  continue;
918
948
  }
919
949
  if (!TURN_HARNESSES.includes(s.harness))
@@ -1001,8 +1031,10 @@ export async function reconcile(m, log, reportIntervalSeconds = 30, deps) {
1001
1031
  removeAgentContainer(local.container_runtime, local.container_name, runner);
1002
1032
  log(`${s.agent}: removed stale container ${local.container_name} before host run`);
1003
1033
  }
1004
- const containerActive = containerMode && containerPrereqs && containerName
1005
- ? isContainerRunning(containerPrereqs.runtime, containerName, runner)
1034
+ const activeContainerRuntime = local?.container_runtime ?? containerPrereqs?.runtime;
1035
+ const activeContainerName = local?.container_name ?? containerName;
1036
+ const containerActive = containerMode && activeContainerRuntime && activeContainerName
1037
+ ? isContainerRunning(activeContainerRuntime, activeContainerName, runner)
1006
1038
  : false;
1007
1039
  const needsLaunch = containerMode
1008
1040
  ? (configChanged || !containerActive)
@@ -1058,11 +1090,34 @@ export async function reconcile(m, log, reportIntervalSeconds = 30, deps) {
1058
1090
  thread_override_at: s.thread_override_at ?? null,
1059
1091
  key_checked_at: state.sessions[s.id]?.key_checked_at ?? Date.now(),
1060
1092
  ...(containerMode && containerPrereqs && containerName
1061
- ? { container_name: containerName, container_runtime: containerPrereqs.runtime, image_digest: containerPrereqs.bareDigest }
1093
+ ? {
1094
+ container_name: containerName,
1095
+ container_runtime: containerPrereqs.runtime,
1096
+ container_runtime_version: containerPrereqs.version,
1097
+ image_digest: extractPinnedImageDigest(pinnedImageRef),
1098
+ image_reference: pinnedImageRef,
1099
+ }
1062
1100
  : {}),
1063
1101
  };
1064
1102
  log(`${s.agent}: ${thread ? "adopted" : "started"} ${s.harness === "codex" ? "thread" : "session"} ${started.thread} in ${s.dir}`);
1065
1103
  }
1104
+ else if (containerMode && state.sessions[s.id] && state.sessions[s.id].image_reference === undefined) {
1105
+ const localSession = state.sessions[s.id];
1106
+ const inspectRuntime = localSession.container_runtime ?? containerPrereqs?.runtime ?? null;
1107
+ const targetContainerName = localSession.container_name ?? containerName;
1108
+ const inspected = inspectRuntime && targetContainerName
1109
+ ? inspectContainerImage(inspectRuntime, targetContainerName, runner)
1110
+ : null;
1111
+ // Recover only facts verified from the running container or recorded at launch; never copy
1112
+ // desired project image pins or current host runtime versions onto an older container.
1113
+ state.sessions[s.id] = {
1114
+ ...localSession,
1115
+ ...(targetContainerName && !localSession.container_name && inspected ? { container_name: targetContainerName } : {}),
1116
+ ...(inspected && !localSession.container_runtime && inspectRuntime ? { container_runtime: inspectRuntime } : {}),
1117
+ container_runtime_version: localSession.container_runtime_version ?? null,
1118
+ ...(inspected ? { image_digest: inspected.imageDigest, image_reference: inspected.imageReference } : {}),
1119
+ };
1120
+ }
1066
1121
  else if (!containerMode && hostSvc) {
1067
1122
  if (!serviceActive(hostSvc)) {
1068
1123
  if (!restartWatcher(hostSvc))
@@ -1071,8 +1126,10 @@ export async function reconcile(m, log, reportIntervalSeconds = 30, deps) {
1071
1126
  }
1072
1127
  }
1073
1128
  const w = containerMode ? undefined : svc();
1074
- const watcherState = containerMode && containerPrereqs && containerName
1075
- ? (isContainerRunning(containerPrereqs.runtime, containerName, runner) ? "active" : "inactive")
1129
+ const runningContainerRuntime = state.sessions[s.id]?.container_runtime ?? containerPrereqs?.runtime;
1130
+ const runningContainerName = state.sessions[s.id]?.container_name ?? containerName;
1131
+ const watcherState = containerMode && runningContainerRuntime && runningContainerName
1132
+ ? (isContainerRunning(runningContainerRuntime, runningContainerName, runner) ? "active" : "inactive")
1076
1133
  : (w && serviceActive(w) ? "active" : "inactive");
1077
1134
  const th = state.sessions[s.id].thread;
1078
1135
  // A watcher that exits at every start (a corrupt state file after the disk filled) is
@@ -1096,6 +1153,29 @@ export async function reconcile(m, log, reportIntervalSeconds = 30, deps) {
1096
1153
  out.push({ id: s.id, state: "error", dir: s.dir, thread: th, watcher: w && serviceActive(w) ? "active" : "inactive", error: `turn verification unavailable: ${unverified.last_error} (unverified since ${new Date(unverified.since).toISOString()}, ${unverified.attempts} failed samples); no new turns start until it is verified`.slice(0, 1000) });
1097
1154
  continue;
1098
1155
  }
1156
+ const currentLocal = state.sessions[s.id];
1157
+ const sessionImageFacts = containerMode
1158
+ ? {
1159
+ ...(currentLocal.container_runtime
1160
+ ? {
1161
+ container_runtime: {
1162
+ runtime: currentLocal.container_runtime,
1163
+ version: currentLocal.container_runtime_version ?? null,
1164
+ },
1165
+ }
1166
+ : {}),
1167
+ ...(currentLocal.image_digest && currentLocal.image_reference
1168
+ ? {
1169
+ image_digest: currentLocal.image_digest,
1170
+ image_reference: currentLocal.image_reference,
1171
+ }
1172
+ : {}),
1173
+ }
1174
+ : {
1175
+ container_runtime: null,
1176
+ image_digest: null,
1177
+ image_reference: null,
1178
+ };
1099
1179
  out.push({
1100
1180
  id: s.id,
1101
1181
  state: "running",
@@ -1104,9 +1184,9 @@ export async function reconcile(m, log, reportIntervalSeconds = 30, deps) {
1104
1184
  watcher: watcherState,
1105
1185
  last_turn: lastTurnLine(s.agent),
1106
1186
  turn_judgment: s.turn_judgment ?? null,
1107
- image_digest: containerMode && containerPrereqs ? containerPrereqs.bareDigest : null,
1108
- container_runtime: containerMode && containerPrereqs ? containerPrereqs.runtime : null,
1187
+ ...(s.pool_move_pending ? { checkout: sessionCheckoutFacts(s.dir) } : {}),
1109
1188
  ...turnFacts(s.agent, s.harness, th, s.turns_per_hour ?? DEFAULT_TURNS_PER_HOUR),
1189
+ ...sessionImageFacts,
1110
1190
  });
1111
1191
  }
1112
1192
  catch (e) {
@@ -1546,7 +1626,7 @@ function turnFacts(agent, harness, thread, turnCap = DEFAULT_TURNS_PER_HOUR) {
1546
1626
  const ph = thread ? probeFor(harness, thread, agent).phase() : null;
1547
1627
  const accountFingerprint = harness === "codex" ? codexAccountFingerprint() : null;
1548
1628
  if (!thread || !ph || "missing" in ph)
1549
- return { turn: { running: false, since: null }, process: null, paused_until: null, pause_started_at: null, turn_guard: null, ...(harness === "codex" ? { usage_account_fingerprint: accountFingerprint } : {}) };
1629
+ return { turn: { running: "missing" in (ph ?? {}) && ph.unknown ? null : false, since: null }, process: null, paused_until: null, pause_started_at: null, turn_guard: null, ...(harness === "codex" ? { usage_account_fingerprint: accountFingerprint } : {}) };
1550
1630
  const until = !ph.running ? probeFor(harness, thread, agent).limitUntil(ph.lastError) : null;
1551
1631
  const unpausedAt = readState(agent).turn_unpaused_at ?? 0;
1552
1632
  const paused = until && until > Date.now() && Date.parse(ph.lastErrorAt ?? "") > unpausedAt ? new Date(until).toISOString() : null;
@@ -0,0 +1,125 @@
1
+ import { createHash } from "node:crypto";
2
+ import { readFileSync } from "node:fs";
3
+ import { basename, extname } from "node:path";
4
+ import { str } from "../args.js";
5
+ import { Client } from "../client.js";
6
+ import { loadAgent, resolveAgentName, resolveModel } from "../config.js";
7
+ import { CliError, WrittenReceiptMismatchError } from "../errors.js";
8
+ import { parseTestRunReport, summarizeTestRun } from "../test-results.js";
9
+ import { projectOf } from "./agent.js";
10
+ function readFile(path, label) {
11
+ try {
12
+ const bytes = readFileSync(path);
13
+ if (!bytes.length)
14
+ throw new CliError("empty_report", `${label} is empty`);
15
+ return bytes;
16
+ }
17
+ catch (error) {
18
+ if (error instanceof CliError)
19
+ throw error;
20
+ throw new CliError("read_failed", `cannot read ${label}: ${error.message}`);
21
+ }
22
+ }
23
+ function parseUnit(value) {
24
+ if (value === undefined)
25
+ return undefined;
26
+ if (!/^\d+$/.test(value) || !Number.isSafeInteger(Number(value)) || Number(value) < 1)
27
+ throw new CliError("usage", "--unit must be a positive work unit number");
28
+ return Number(value);
29
+ }
30
+ function contentType(path) {
31
+ return extname(path).toLowerCase() === ".xml" ? "application/xml" : "application/json";
32
+ }
33
+ async function uploadOriginal(client, apiUrl, project, path, bytes) {
34
+ const sha256 = createHash("sha256").update(bytes).digest("hex");
35
+ const filename = basename(path);
36
+ if (!filename || filename.length > 255 || /[\\/\0]/.test(filename))
37
+ throw new CliError("usage", "report filename must be 1..255 characters without path separators");
38
+ const headers = {
39
+ ...client.headers(),
40
+ "content-type": contentType(path),
41
+ "x-bschat-sha256": sha256,
42
+ "x-bschat-filename": filename,
43
+ "x-bschat-kind": "test",
44
+ };
45
+ const response = await fetch(`${apiUrl.replace(/\/$/, "")}/projects/${encodeURIComponent(project)}/evidence`, { method: "POST", headers, body: new Uint8Array(bytes) });
46
+ const responseText = await response.text();
47
+ let json;
48
+ try {
49
+ json = JSON.parse(responseText);
50
+ }
51
+ catch {
52
+ if (!response.ok)
53
+ throw new CliError(`http_${response.status}`, responseText || `test artifact upload failed with HTTP ${response.status}`);
54
+ throw new CliError("bad_response", `test artifact upload returned non-JSON (${response.status})`);
55
+ }
56
+ if (!response.ok)
57
+ throw new CliError(typeof json?.error === "string" ? json.error : `http_${response.status}`, typeof json?.message === "string" ? json.message : "test artifact upload failed");
58
+ const id = json?.evidence?.id;
59
+ const returnedSha = json?.evidence?.sha256;
60
+ if (typeof id !== "string" || !id || typeof returnedSha !== "string")
61
+ throw new CliError("bad_response", "test artifact upload omitted its evidence ID or checksum");
62
+ if (returnedSha.toLowerCase() !== sha256)
63
+ throw new CliError("checksum_mismatch", `uploaded test artifact checksum ${returnedSha} does not match local bytes ${sha256}`);
64
+ return { id, sha256, ref: typeof json.ref === "string" ? json.ref : `evidence:${id}` };
65
+ }
66
+ export async function testResults(p, out) {
67
+ const sub = p.positionals[1];
68
+ const agent = resolveAgentName(str(p.flags, "as"));
69
+ const creds = loadAgent(agent);
70
+ const client = Client.forAgent(creds, resolveModel(str(p.flags, "model"), process.env, process.cwd(), agent));
71
+ const project = projectOf(p, creds);
72
+ if (sub === "show") {
73
+ const runId = p.positionals[2];
74
+ if (!runId)
75
+ throw new CliError("usage", "test-results show <run-id>");
76
+ const result = await client.call("GET", `/projects/${encodeURIComponent(project)}/test-runs/${encodeURIComponent(runId)}`);
77
+ const run = result?.run;
78
+ if (!run || typeof run !== "object")
79
+ throw new CliError("bad_response", "test-run response omitted run");
80
+ const summary = summarizeTestRun(run);
81
+ out.print(`${run.run_id ?? runId}: ${summary}${run.artifact?.evidence_id ? `\nartifact evidence:${run.artifact.evidence_id} sha256 ${run.artifact.sha256}` : ""}`, result);
82
+ return;
83
+ }
84
+ if (sub !== "import")
85
+ throw new CliError("usage", "test-results <import|show>");
86
+ const path = p.positionals[2];
87
+ if (!path)
88
+ throw new CliError("usage", "test-results import <junit.xml|run.json> [--metadata-file run-context.json] [--unit n]");
89
+ const unit = parseUnit(str(p.flags, "unit"));
90
+ const bytes = readFile(path, "test report");
91
+ const metadataPath = str(p.flags, "metadata-file");
92
+ const metadataBytes = metadataPath ? readFile(metadataPath, "run metadata") : undefined;
93
+ const draft = parseTestRunReport(path, bytes, metadataBytes);
94
+ // Check attachment authorization before uploading an artifact or creating a run.
95
+ if (unit !== undefined)
96
+ await client.call("GET", `/projects/${encodeURIComponent(project)}/work-units/${unit}`);
97
+ process.stderr.write("[b9s] The original report is uploaded verbatim as test evidence. Inspect it for credentials first; use a redacted copy if needed.\n");
98
+ const artifact = await uploadOriginal(client, creds.url, project, path, bytes);
99
+ let result;
100
+ try {
101
+ result = await client.call("POST", `/projects/${encodeURIComponent(project)}/test-runs`, {
102
+ ...draft,
103
+ artifact: { evidence_id: artifact.id, sha256: artifact.sha256 },
104
+ });
105
+ }
106
+ catch (error) {
107
+ throw new CliError("test_run_create_failed", `canonical run creation failed; original report remains at ${artifact.ref}. Check the run list before retrying to avoid a duplicate. ${error instanceof Error ? error.message : String(error)}`);
108
+ }
109
+ const run = result?.run;
110
+ if (!run || typeof run !== "object" || typeof run.run_id !== "string")
111
+ throw new CliError("bad_response", `test run was submitted but the response omitted run_id; source artifact is ${artifact.ref}`);
112
+ if (unit !== undefined) {
113
+ const note = `Imported test run ${run.run_id}: ${summarizeTestRun(run)}`;
114
+ try {
115
+ await client.call("POST", `/projects/${encodeURIComponent(project)}/work-units/${unit}/note`, { note, evidence: [artifact.id] });
116
+ }
117
+ catch (error) {
118
+ if (error instanceof WrittenReceiptMismatchError)
119
+ throw error;
120
+ throw new CliError("unit_attachment_failed", `test run ${run.run_id} was imported, but could not be attached to work unit #${unit}; artifact is ${artifact.ref}. ${error instanceof Error ? error.message : String(error)}`);
121
+ }
122
+ }
123
+ const summary = summarizeTestRun(run);
124
+ out.print(`Imported test run ${run.run_id}: ${summary}\nsource artifact ${artifact.ref} (sha256 ${artifact.sha256})${unit !== undefined ? `\nattached to work unit #${unit}` : ""}`, { ...result, source_artifact: artifact, attached_unit: unit ?? null });
125
+ }