benignswarm 0.12.108 → 0.12.110

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,8 +200,12 @@ 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 ?? {};
205
+ const pressureText = (pressure) => `some ${pressure?.some_avg10 ?? "unknown"}% / full ${pressure?.full_avg10 ?? "unknown"}% (10s avg)`;
206
+ const agentPressure = rep.agent_cgroup_pressure;
193
207
  const head = [
208
+ ...[['I/O', 'io_pressure'], ['Memory', 'memory_pressure'], ['CPU', 'cpu_pressure']].map(([label, key]) => ` ${label} PSI host: ${pressureText(rep[key])}; agents: ${agentPressure?.status === "available" ? `${pressureText(agentPressure[key])} (${agentPressure.source})` : `${agentPressure?.status ?? "unknown"}; host PSI used when available`}${liveReport ? "" : "; live sample unavailable"}`),
194
209
  `${m.name}: last report ${m.last_report_at ?? "never"}; labels ${(m.labels ?? []).join(", ") || "(none)"}; slots ${m.slots ?? "auto"}; writable ${(m.writable ?? []).join(", ") || "-"}; workdir ${rep.workdir ?? m.workdir ?? "~/bschat"}${rep.workdir_free_bytes ? ` (${Math.round(rep.workdir_free_bytes / 1e9)} GB free)` : ""}; cache budget ${m.cache_budget_gb ?? 40} GB (floor ${m.cache_floor_pct ?? 15}%)`,
195
210
  rep.os ? ` ${rep.os}/${rep.arch} ${rep.hostname} as ${rep.user}; ${rep.cpus ?? "?"} CPUs, ${rep.mem_total_bytes ? `${Math.round(rep.mem_total_bytes / 1024 ** 3)} GB RAM` : "? RAM"}; b9s ${rep.bschat?.version}; codex ${rep.codex ? `${rep.codex.version}, ${rep.codex.logged_in ? "logged in" : "NOT logged in"}, sandbox ${rep.codex.sandbox ? (rep.codex.sandbox.ok ? "ok" : `FAILS (${rep.codex.sandbox.error})`) : "?"}` : "missing"}; hooks ${rep.managed_hooks ? "managed by policy" : "user-level"}; linger ${rep.linger ?? "n/a"}; disk free ${rep.disk_free_bytes ? `${Math.round(rep.disk_free_bytes / 1e9)} GB` : "?"}` : " (no report yet: is its daemon running?)",
196
211
  rep.os ? ` Antigravity: ${rep.antigravity ? `${rep.antigravity.version ?? "agy"}, ${rep.antigravity.available ? "available" : "unavailable"}, ${rep.antigravity.logged_in ? "logged in" : "not logged in"}, sandbox ${rep.antigravity.sandbox ? (rep.antigravity.sandbox.ok ? "ok" : `FAILS (${rep.antigravity.sandbox.error})`) : "not checked"}` : "not installed"}` : null,
@@ -230,7 +245,7 @@ export async function machineAdmin(action, rest, p, out) {
230
245
  const providers = rep.claude_code?.providers ?? {};
231
246
  const providerLines = Object.entries(providers).map(([provider, check]) => ` Claude Code ${provider}: ${check.logged_in ? "verified" : `NOT verified (${check.reason ?? "unknown reason"})`}`);
232
247
  const output = liveReport ? { ...r, machine: { ...m, report: rep } } : r;
233
- 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);
234
249
  }
235
250
  if (action === "maintenance") {
236
251
  // A window on the machine: no new turns from 15 min before, its agents away until it ends.
@@ -328,7 +343,8 @@ export async function machineAdmin(action, rest, p, out) {
328
343
  body = { slots: rest[1] === "auto" ? null : Number(rest[1]) };
329
344
  }
330
345
  const r = await c.call("PATCH", `/machines/${name}`, body);
331
- 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 });
332
348
  }
333
349
  if (action === "readiness") {
334
350
  const name = rest[0];
@@ -632,6 +648,39 @@ export async function poolAdmin(action, rest, p, out, argv) {
632
648
  throw new CliError("usage", "--turn-coalesce-seconds is only supported for individual machine sessions; pool settings do not support turn coalescing");
633
649
  }
634
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
+ }
635
684
  if (action === "slot") {
636
685
  const [operation, target, ...extra] = rest;
637
686
  const parts = (target ?? "").split("/");
@@ -643,11 +692,19 @@ export async function poolAdmin(action, rest, p, out, argv) {
643
692
  const r = await c.call("POST", `/projects/${project}/pools/${name}/slots/${slot}/stop`, reason === undefined ? {} : { reason });
644
693
  return out.print(`Suspended ${target}; its machine will stop the session.`, r);
645
694
  }
695
+ const KEPT_IN_PLACE = KEPT_IN_PLACE_RE;
646
696
  const statusLines = (pool) => [
647
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` : ""}`,
648
698
  ...(pool.status?.placed ?? []).map((x) => ` ${x.agent.padEnd(32)} on ${x.machine}`),
649
- ...(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}`),
650
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
+ };
651
708
  if (action === "set") {
652
709
  const [project, name] = (rest[0] ?? "").split("/");
653
710
  const variants = repeated(argv, "variant").map(parseVariant);
@@ -663,7 +720,7 @@ export async function poolAdmin(action, rest, p, out, argv) {
663
720
  if (uph !== undefined && (!/^\d+$/.test(uph) || Number(uph) < 1 || Number(uph) > 60))
664
721
  throw new CliError("usage", "--unproductive-per-hour must be a whole number from 1 to 60");
665
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) } : {}) });
666
- 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);
667
724
  }
668
725
  if (action === "list" || action === undefined) {
669
726
  const r = await c.call("GET", rest[0] ? `/projects/${rest[0]}/pools` : "/pools");
@@ -851,10 +908,32 @@ function machineMoveReadinessError(machine, harness, provider, sandbox, liveSamp
851
908
  * change. The API does not receive source paths or SSH material and is not told the move completed
852
909
  * until the local handoff succeeded.
853
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
+ }
854
932
  export async function agentMove(rest, p, out) {
855
933
  const ref = rest[0] ?? "";
856
934
  const [project, agent] = ref.split("/");
857
935
  const operationId = str(p.flags, "operation");
936
+ const poolMoveOperation = str(p.flags, "__pool-move-operation");
858
937
  const requestedTo = str(p.flags, "to");
859
938
  const requestedSandbox = str(p.flags, "sandbox");
860
939
  const requestedHarness = str(p.flags, "harness");
@@ -866,7 +945,7 @@ export async function agentMove(rest, p, out) {
866
945
  const requestedThread = str(p.flags, "thread");
867
946
  const from = str(p.flags, "from");
868
947
  const forceConfirmation = str(p.flags, "confirm-force");
869
- if (!project || !agent || (!operationId && (!requestedTo || !requestedSandbox)))
948
+ if (!project || !agent || (!operationId && !poolMoveOperation && (!requestedTo || !requestedSandbox)))
870
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>]");
871
950
  if (forceConfirmation && !bool(p.flags, "force"))
872
951
  throw new CliError("usage", "--confirm-force is valid only with --force");
@@ -888,12 +967,15 @@ export async function agentMove(rest, p, out) {
888
967
  let model = requestedModel;
889
968
  let effort = requestedEffort;
890
969
  let thread = requestedThread ?? null;
891
- if (operationId) {
892
- 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)}`);
893
973
  move = loaded.move;
894
974
  if (move.status !== "requested")
895
- 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`);
896
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`);
897
979
  const expected = [
898
980
  ["--to", requestedTo, move.to], ["--sandbox", requestedSandbox, target.sandbox], ["--harness", requestedHarness, target.harness],
899
981
  ["--provider", requestedProvider, target.provider], ["--carry", requestedCarry, move.carry], ["--dir", requestedDir, target.dir],
@@ -901,11 +983,11 @@ export async function agentMove(rest, p, out) {
901
983
  ];
902
984
  for (const [flag, supplied, stored] of expected) {
903
985
  if (supplied !== undefined && supplied !== (stored == null ? undefined : String(stored))) {
904
- 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})`}`);
905
987
  }
906
988
  }
907
989
  if (str(p.flags, "turn-timeout") !== undefined && Number(str(p.flags, "turn-timeout")) !== target.turn_timeout) {
908
- 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})`);
909
991
  }
910
992
  to = String(move.to);
911
993
  sandbox = String(target.sandbox);
@@ -965,6 +1047,26 @@ export async function agentMove(rest, p, out) {
965
1047
  if (!out.json)
966
1048
  say(` move ${move.id}: ${move.from ?? "source"} → ${to}; other agent keys will be revoked only after completion`);
967
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
+ };
968
1070
  let problems = [];
969
1071
  const skippedWorktrees = [];
970
1072
  const destinationHost = str(p.flags, "to-ssh") ?? to;
@@ -974,8 +1076,9 @@ export async function agentMove(rest, p, out) {
974
1076
  const readinessError = machineMoveReadinessError(destination.machine, harness, provider, sandbox, live.latest ?? null);
975
1077
  if (readinessError)
976
1078
  throw new CliError("destination_not_ready", readinessError);
1079
+ await confirmPoolMoveSource();
977
1080
  // 1. Work in progress must be on origin, or it stays behind on the old machine.
978
- 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));
979
1082
  if (units.length && !move.from)
980
1083
  throw new CliError("source_machine_unknown", `the move operation has active units but no recorded source machine; cannot scope their worktrees on ${from}`);
981
1084
  const sourceMachine = move.from ?? from;
@@ -1048,9 +1151,13 @@ export async function agentMove(rest, p, out) {
1048
1151
  for (const record of worktrees.filter((w) => w.machine === sourceMachine && Array.isArray(w.agents) && w.agents.some((a) => a?.name === agent))) {
1049
1152
  const unit = units.find((u) => u.owner_name === agent && (u.worktree === record.path || (u.branch && u.branch === record.branch)))
1050
1153
  ?? units.find((u) => Array.isArray(u.reviewers) && u.reviewers.some((r) => r?.name === agent));
1154
+ if (poolMoveOperation && !unit)
1155
+ continue;
1051
1156
  addInspection(unit ?? null, record.path, unit ? `#${unit.number} (${unit.branch ?? "no branch recorded"})` : `agent worktree ${record.path}`);
1052
1157
  }
1053
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;
1054
1161
  skippedWorktrees.push(`agent worktree ${record.path} is recorded on ${record.machine}, not ${sourceMachine}`);
1055
1162
  }
1056
1163
  for (const { unit: u, path: worktree, label } of inspections) {
@@ -1141,6 +1248,8 @@ export async function agentMove(rest, p, out) {
1141
1248
  say(note ? ` resume note saved: ${note.title}` : ` no resume note within ${wait} min; it starts from its units, status and chat`);
1142
1249
  }
1143
1250
  }
1251
+ if (poolMoveOperation)
1252
+ await confirmPoolMoveSource();
1144
1253
  if (transferAgentState(ref, from, destinationHost))
1145
1254
  say(` read cursors, follows and watcher state copied to ${destinationHost}`);
1146
1255
  if (!model || !effort) {
@@ -1155,15 +1264,17 @@ export async function agentMove(rest, p, out) {
1155
1264
  }
1156
1265
  catch (error) {
1157
1266
  const detail = error instanceof Error ? error.message : String(error);
1158
- const recordedDetail = error instanceof CliError && error.code === "destination_not_ready"
1159
- ? "destination harness, login, or sandbox readiness check failed"
1160
- : error instanceof CliError && error.code === "unpushed_work"
1161
- ? "source Git preflight found dirty, unpushed, or unavailable worktrees"
1162
- : error instanceof CliError && error.code === "git_preflight_failed"
1163
- ? "source Git inspection could not confirm worktree state"
1164
- : error instanceof CliError && error.code === "force_confirmation_required"
1165
- ? "source-only work was not explicitly confirmed"
1166
- : "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";
1167
1278
  try {
1168
1279
  const refusalReason = error instanceof CliError ? `${error.code}: ${recordedDetail}` : recordedDetail;
1169
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) {
@@ -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
+ }
package/dist/container.js CHANGED
@@ -179,6 +179,10 @@ export function readGitIdentity(cwd, runner = defaultRunner) {
179
179
  const userEmail = emailRes.status === 0 && emailRes.stdout.trim() ? emailRes.stdout.trim() : null;
180
180
  return { ok: Boolean(userName && userEmail), user_name: userName, user_email: userEmail };
181
181
  }
182
+ export function parseContainerRuntimeVersion(stdout) {
183
+ const line = (stdout ?? "").split(/\r?\n/).find((item) => item.trim())?.trim() ?? "";
184
+ return line && !line.startsWith("{") ? line.slice(0, 120) : null;
185
+ }
182
186
  function normalizeContainerArch(raw) {
183
187
  if (!raw)
184
188
  return null;
@@ -198,18 +202,26 @@ export function probeNestedSandbox(opts = {}) {
198
202
  const readSysctl = opts.readSysctl ?? ((p) => (existsSync(p) ? readFileSync(p, "utf8").trim() : null));
199
203
  const listDir = opts.listDir ?? ((p) => (existsSync(p) ? readdirSync(p) : []));
200
204
  let runtime = opts.runtime ?? null;
205
+ let version = null;
201
206
  if (!runtime) {
202
207
  for (const candidate of ["podman", "docker"]) {
203
208
  const r = runner(candidate, ["--version"]);
204
209
  if (r.status === 0) {
205
210
  runtime = candidate;
211
+ version = parseContainerRuntimeVersion(r.stdout);
206
212
  break;
207
213
  }
208
214
  }
209
215
  }
216
+ else {
217
+ const r = runner(runtime, ["--version"]);
218
+ if (r.status === 0)
219
+ version = parseContainerRuntimeVersion(r.stdout);
220
+ }
210
221
  if (!runtime) {
211
222
  return {
212
223
  runtime: null,
224
+ version: null,
213
225
  ok: false,
214
226
  nested_sandbox_ok: false,
215
227
  usable_without_root: false,
@@ -297,6 +309,7 @@ export function probeNestedSandbox(opts = {}) {
297
309
  const ok = missing.length === 0 && usableWithoutRoot;
298
310
  return {
299
311
  runtime,
312
+ version,
300
313
  ok,
301
314
  nested_sandbox_ok: ok,
302
315
  usable_without_root: usableWithoutRoot,
package/dist/git.js CHANGED
@@ -14,6 +14,33 @@ function status(cwd, timeoutMs) {
14
14
  return null;
15
15
  return r.stdout.trim();
16
16
  }
17
+ /** Local, bounded proof that a session checkout is clean and every commit is reachable from a remote. */
18
+ export function sessionCheckoutFacts(cwd) {
19
+ const statusResult = spawnSync("git", ["status", "--porcelain"], {
20
+ cwd, encoding: "utf8", stdio: ["ignore", "pipe", "ignore"], maxBuffer: 16 * 1024 * 1024, timeout: 5_000,
21
+ });
22
+ const remoteResult = spawnSync("git", ["rev-list", "--count", "HEAD", "--not", "--remotes"], {
23
+ cwd, encoding: "utf8", stdio: ["ignore", "pipe", "ignore"], maxBuffer: 1024 * 1024, timeout: 5_000,
24
+ });
25
+ const statusError = statusResult.error;
26
+ const remoteError = remoteResult.error;
27
+ const statusOk = statusResult.status === 0;
28
+ const countText = remoteResult.stdout.trim();
29
+ const count = remoteResult.status === 0 && /^\d+$/.test(countText) ? Number(countText) : null;
30
+ const entries = statusOk ? statusResult.stdout.split("\n").filter(Boolean) : [];
31
+ const untracked = statusOk ? entries.some((line) => line.startsWith("??")) : null;
32
+ const uncommitted = statusOk ? entries.some((line) => !line.startsWith("??")) : null;
33
+ const clean = statusOk ? entries.length === 0 : null;
34
+ const errors = [statusError?.code ?? (statusOk ? null : `git status exited ${statusResult.status}`), remoteError?.code ?? (count === null ? `git remote reachability exited ${remoteResult.status}` : null)].filter(Boolean);
35
+ return {
36
+ clean,
37
+ uncommitted,
38
+ untracked,
39
+ pushed: count === null ? null : count === 0,
40
+ unpushed_commits: count,
41
+ ...(errors.length ? { error: errors.join("; ") } : {}),
42
+ };
43
+ }
17
44
  function git(args, cwd) {
18
45
  // Large enough for `git status` on a big repo with every file changed (ester: 226k files, 25 MB);
19
46
  // the 1 MB default made such a worktree unreadable rather than dirty.
package/dist/help.js CHANGED
@@ -258,6 +258,10 @@ Machine placement shares capacity across the account's projects: session seats a
258
258
  b9s evidence info <id|sha256>
259
259
  b9s evidence get <id|sha256> [--out path] verifies sha256 on download
260
260
  b9s evidence verify <id> --confirmed|--refuted --note "..." named agent checks a claim; evidence authors cannot verify their own
261
+ b9s test-results import <junit.xml|run.json> [--metadata-file context.json] [--unit n]
262
+ preserve the report as test evidence, validate/import schema v1, optionally attach to a unit
263
+ JUnit requires context JSON (source, invocation, runner, run); JSON reports include those fields
264
+ b9s test-results show <run-id> show the stored run, outcome counts, and original report evidence
261
265
  b9s retire --title t (--body b | --body-file f) [--handoff-to @x|@role:y] [--evidence id,id] --yes
262
266
  save a RESUME or HANDOFF note, announce it, revoke this key; history stays
263
267
  b9s handoffs [--open] [--agent a] notes left by retired agents (open = not yet picked up)
@@ -442,6 +446,8 @@ Pools (a role, variants and a count; the server names the agents and places them
442
446
  slots are agents named <name>-<tag>-<n>; fewer retires the extra ones
443
447
  b9s-admin pool list [project] | show <project>/<name> | remove <project>/<name>
444
448
  b9s-admin pool slot stop <project>/<pool>/<slot> [--reason text] suspend one slot and stop its session
449
+ b9s-admin pool move <project>/<name> --from <source-machine> --to <destination-machine> [--carry note|thread] [--ssh-from local|<host>] [--to-ssh <host>]
450
+ verifies each source slot independently; unsafe slots stay placed with a reason
445
451
  b9s-admin pool suggestions <project> [--status pending|accepted|rejected|superseded|all] inspect explicit non-mutating pool-weight suggestions
446
452
  b9s-admin pool suggestion accept <project> <id> [--note "..."] apply a pending pool-weight suggestion and audit it
447
453
  b9s-admin pool suggestion reject <project> <id> [--reason "..."] reject a pool-weight suggestion with an audit note
package/dist/index.js CHANGED
@@ -35,6 +35,7 @@ import { agentNotice } from "./commands/notices.js";
35
35
  import { versionLine, warnLegacyAlias } from "./legacy-alias.js";
36
36
  import { gitCredentialMain } from "./commands/git-credential.js";
37
37
  import { templates } from "./commands/templates.js";
38
+ import { testResults } from "./commands/test-results.js";
38
39
  import { environment } from "./commands/environment.js";
39
40
  import { runCommandSafely } from "./command-runner.js";
40
41
  const COMMANDS = {
@@ -47,6 +48,7 @@ const COMMANDS = {
47
48
  resume,
48
49
  "git-credential": async (p) => gitCredentialMain(p),
49
50
  templates,
51
+ "test-results": testResults,
50
52
  environment,
51
53
  notice: agentNotice,
52
54
  who: a.who,
@@ -115,6 +115,18 @@ export function machineResourceTelemetry(hostPlatform, readText, pageSizeBytes,
115
115
  const memoryPressure = pressure("memory");
116
116
  const cpuPressure = pressure("cpu");
117
117
  const ioPressure = pressure("io");
118
+ const cgroupText = linux ? readText("/proc/self/cgroup") : null;
119
+ const unifiedPath = /^0::(\/[^\n\r]*)$/m.exec(cgroupText ?? "")?.[1];
120
+ const legacyCgroup = !!cgroupText && !unifiedPath && /^\d+:[^:\n]+:/m.test(cgroupText);
121
+ const components = unifiedPath?.split("/").filter(Boolean) ?? [];
122
+ const appSlice = components.indexOf("app.slice");
123
+ const userSlice = /^user-(\d+)\.slice$/.exec(components[1] ?? "");
124
+ const userService = /^user@(\d+)\.service$/.exec(components[2] ?? "");
125
+ const safePath = appSlice === 3 && components[0] === "user.slice" && !!userSlice && !!userService && userSlice[1] === userService[1]
126
+ ? "/" + components.slice(0, appSlice + 1).join("/") : null;
127
+ const groupPressure = (kind) => safePath ? parsePressureStall(readText(`/sys/fs/cgroup${safePath}/${kind}.pressure`) ?? "") : null;
128
+ const groupMemory = groupPressure("memory"), groupCpu = groupPressure("cpu"), groupIo = groupPressure("io");
129
+ const groupAvailable = [groupMemory, groupCpu, groupIo].every((value) => value?.some?.avg10 != null) && groupIo?.full?.avg10 != null && groupMemory?.full?.avg10 != null;
118
130
  const swapTotal = linuxMemory?.swap_total_bytes ?? macSwap?.total_bytes ?? null;
119
131
  const swapUsed = linuxMemory?.swap_used_bytes ?? macSwap?.used_bytes ?? null;
120
132
  const swapAvailable = swapTotal !== null && swapUsed !== null;
@@ -139,6 +151,13 @@ export function machineResourceTelemetry(hostPlatform, readText, pageSizeBytes,
139
151
  memory_pressure: flattenPressure(memoryPressure),
140
152
  cpu_pressure: flattenPressure(cpuPressure),
141
153
  io_pressure: flattenPressure(ioPressure),
154
+ agent_cgroup_pressure: {
155
+ source: safePath,
156
+ status: !linux || legacyCgroup ? "unsupported" : groupAvailable ? "available" : "unavailable",
157
+ memory_pressure: flattenPressure(groupMemory),
158
+ cpu_pressure: flattenPressure(groupCpu),
159
+ io_pressure: flattenPressure(groupIo),
160
+ },
142
161
  metric_availability: {
143
162
  memory: linux ? (typeof linuxMemory?.total_bytes === "number" && typeof linuxMemory?.available_bytes === "number" ? "available" : "unavailable") : darwin ? (typeof macMemory?.available_bytes === "number" ? "available" : "unavailable") : "unsupported",
144
163
  ...(darwin ? { memory_source: "vm_stat_reclaimable_pages" } : {}),
@@ -0,0 +1,418 @@
1
+ import { SaxesParser } from "saxes";
2
+ import { CliError } from "./errors.js";
3
+ import { CLI_VERSION } from "./version.js";
4
+ const RUNNER_KEYS = ["machine", "os", "arch", "runtime", "toolchain", "sandbox", "container", "test_configuration", "importer_version"];
5
+ const SOURCE_KEYS = ["commit", "binary_hash", "target_branch", "target_commit", "package", "workspace", "target_config"];
6
+ const ISO_UTC = /^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(?:\.\d{1,3})?Z$/;
7
+ const SHA = /^(?:[0-9a-f]{40}|[0-9a-f]{64})$/i;
8
+ const PRIVATE_PATH = /(?:^|[\s=:"'])~\/|(?:^|[\s=:"'])\/(?:Users|home|root|private|tmp|var)\/|(?:^|[\\/])(?:Users|home|root|private|\.ssh|\.aws)[\\/][^\\/\s]+/i;
9
+ const ASSIGNMENT = /(?:^|[\s;&|()]+)(?:export\s+)?[A-Za-z_][A-Za-z0-9_]*=[^\s;&|()]*/;
10
+ const SECRET = /(?:^|\s)(?:[A-Z][A-Z0-9_]*(?:TOKEN|SECRET|PASSWORD|API_KEY|ACCESS_KEY)|(?:--)?(?:token|secret|password|api[-_]key|access[-_]key|authorization))\s*[=:]\s*\S+/i;
11
+ const SECRET_OPTION = /^--?(?:token|secret|password|api[-_]key|access[-_]key|authorization)$/i;
12
+ const ABSOLUTE_PATH = /(?:^|[\s=:"'])(?:\/(?!\/)[^\s]+|[A-Za-z]:[\\/][^\s]+|\\\\[^\\]+\\[^\s]+)/;
13
+ const PRIVATE_PARTS = new Set(["users", "home", "root", "private", "tmp", ".ssh", ".aws"]);
14
+ const OUTCOMES = new Set(["passed", "failed", "skipped", "did_not_run", "still_running_at_stop", "unknown"]);
15
+ const RUN_STATES = new Set(["completed", "timed_out", "killed", "interrupted"]);
16
+ function invalid(message) { throw new CliError("invalid_test_run", message); }
17
+ function record(value, field) {
18
+ if (!value || typeof value !== "object" || Array.isArray(value))
19
+ invalid(`${field} must be an object`);
20
+ return value;
21
+ }
22
+ function onlyKeys(value, allowed, field) {
23
+ const extra = Object.keys(value).find((key) => !allowed.includes(key));
24
+ if (extra)
25
+ invalid(`${field}.${extra} is not supported by test-run schema v1`);
26
+ }
27
+ function string(value, field, max, required = true) {
28
+ if (value === undefined && !required)
29
+ return undefined;
30
+ if (typeof value !== "string" || !value.trim())
31
+ invalid(`${field} must be a non-empty string`);
32
+ const v = value;
33
+ if (v.length > max)
34
+ invalid(`${field} exceeds ${max} characters`);
35
+ if (/[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f]/.test(v))
36
+ invalid(`${field} contains control characters`);
37
+ return v;
38
+ }
39
+ function safeDescription(value, field, max, required = false) {
40
+ const v = string(value, field, max, required);
41
+ if (v !== undefined && (PRIVATE_PATH.test(v) || ABSOLUTE_PATH.test(v) || ASSIGNMENT.test(v) || SECRET.test(v))) {
42
+ invalid(`${field} must not contain credentials, environment values, or filesystem paths`);
43
+ }
44
+ return v;
45
+ }
46
+ function safeLabel(value, field, max, required = false) {
47
+ const v = string(value, field, max, required);
48
+ if (v !== undefined && (!/^[A-Za-z0-9][A-Za-z0-9._+-]{0,127}$/.test(v) || v.includes("..")))
49
+ invalid(`${field} must be a safe path-free label`);
50
+ return v;
51
+ }
52
+ function relativePath(value, field, max, required = false) {
53
+ const v = string(value, field, max, required);
54
+ if (v === undefined)
55
+ return undefined;
56
+ const parts = v.split("/");
57
+ if (v.length > max || v.startsWith("/") || v.includes("\\") || ABSOLUTE_PATH.test(v) || parts.some((part) => !part || part === "." || part === ".." || PRIVATE_PARTS.has(part.toLowerCase())) || !/^(?:\.|[A-Za-z0-9][A-Za-z0-9._@+-]*(?:\/[A-Za-z0-9][A-Za-z0-9._@+-]*)*)$/.test(v)) {
58
+ invalid(`${field} must be a repository-relative path without private filesystem paths`);
59
+ }
60
+ return v;
61
+ }
62
+ function number(value, field, integer = false) {
63
+ if (typeof value !== "number" || !Number.isFinite(value) || value < 0 || (integer && !Number.isSafeInteger(value)))
64
+ invalid(`${field} must be a finite non-negative ${integer ? "integer" : "number"}`);
65
+ return value;
66
+ }
67
+ function timestamp(value, field) {
68
+ const v = string(value, field, 40);
69
+ const date = new Date(v);
70
+ const [month, day, hour, minute, second] = v.match(/^\d{4}-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})/)?.slice(1).map(Number) ?? [];
71
+ if (!ISO_UTC.test(v) || !Number.isFinite(date.getTime()) || date.getUTCMonth() + 1 !== month || date.getUTCDate() !== day || date.getUTCHours() !== hour || date.getUTCMinutes() !== minute || date.getUTCSeconds() !== second || date.getUTCFullYear() !== Number(v.slice(0, 4)) || month < 1 || month > 12 || day < 1 || day > 31 || hour > 23 || minute > 59 || second > 59)
72
+ invalid(`${field} must be a valid ISO-8601 UTC timestamp`);
73
+ return v;
74
+ }
75
+ /** Parse and locally validate the API v1 draft. Artifact identity is always generated from these source bytes. */
76
+ function validateDraft(input) {
77
+ const body = record(input, "body");
78
+ const allowedTop = ["schema_version", "source", "invocation", "runner", "run", "tests", "build_targets", "load", "artifact"];
79
+ onlyKeys(body, allowedTop, "body");
80
+ if (body.schema_version !== 1)
81
+ invalid("schema_version must be 1");
82
+ const source = record(body.source, "source");
83
+ onlyKeys(source, SOURCE_KEYS, "source");
84
+ const commit = string(source.commit, "source.commit", 64);
85
+ if (!SHA.test(commit))
86
+ invalid("source.commit must be a 40- or 64-character hexadecimal SHA");
87
+ for (const key of ["binary_hash", "target_commit"]) {
88
+ const v = string(source[key], `source.${key}`, 64, false);
89
+ if (v !== undefined && !SHA.test(v))
90
+ invalid(`source.${key} must be a 40- or 64-character hexadecimal SHA`);
91
+ }
92
+ for (const key of ["package", "workspace"])
93
+ relativePath(source[key], `source.${key}`, 256, false);
94
+ safeLabel(source.target_config, "source.target_config", 512, false);
95
+ const branch = string(source.target_branch, "source.target_branch", 256, false);
96
+ if (branch !== undefined && (!/^[A-Za-z0-9][A-Za-z0-9._/-]*$/.test(branch) || branch.includes("..") || branch.endsWith("/")))
97
+ invalid("source.target_branch must be a safe branch label");
98
+ const invocation = record(body.invocation, "invocation");
99
+ onlyKeys(invocation, ["argv", "cwd"], "invocation");
100
+ if (!Array.isArray(invocation.argv) || invocation.argv.length < 1 || invocation.argv.length > 100)
101
+ invalid("invocation.argv must contain 1..100 arguments");
102
+ invocation.argv.forEach((arg, i, argv) => {
103
+ const v = string(arg, `invocation.argv[${i}]`, 4096);
104
+ if (ASSIGNMENT.test(v) || PRIVATE_PATH.test(v) || ABSOLUTE_PATH.test(v) || SECRET.test(v) || (SECRET_OPTION.test(v) && i + 1 < argv.length && !String(argv[i + 1]).startsWith("--"))) {
105
+ invalid("invocation.argv contains an environment assignment, credential, or filesystem path; remove or redact it before submitting");
106
+ }
107
+ });
108
+ const cwd = string(invocation.cwd, "invocation.cwd", 1024);
109
+ if (cwd !== ".")
110
+ relativePath(cwd, "invocation.cwd", 1024, true);
111
+ const runner = record(body.runner, "runner");
112
+ onlyKeys(runner, RUNNER_KEYS, "runner");
113
+ const machine = string(runner.machine, "runner.machine", 64);
114
+ if (!/^[a-z0-9][a-z0-9_-]{0,63}$/.test(machine))
115
+ invalid("runner.machine must be an opaque machine alias");
116
+ const os = safeLabel(runner.os, "runner.os", 32, true).toLowerCase();
117
+ if (!["linux", "macos", "windows"].includes(os))
118
+ invalid("runner.os must be linux, macOS, or windows");
119
+ const arch = safeLabel(runner.arch, "runner.arch", 32, true).toLowerCase();
120
+ if (!["x64", "x86_64", "amd64", "x86", "arm64", "aarch64"].includes(arch))
121
+ invalid("runner.arch must be a supported architecture label");
122
+ for (const key of ["runtime", "toolchain", "sandbox", "container", "test_configuration"])
123
+ safeLabel(runner[key], `runner.${key}`, 128, key === "sandbox");
124
+ safeLabel(runner.importer_version, "runner.importer_version", 64, false);
125
+ const run = record(body.run, "run");
126
+ onlyKeys(run, ["started_at", "ended_at", "exit_status", "state"], "run");
127
+ const startedAt = timestamp(run.started_at, "run.started_at");
128
+ const endedAt = timestamp(run.ended_at, "run.ended_at");
129
+ if (Date.parse(endedAt) < Date.parse(startedAt))
130
+ invalid("run.ended_at cannot precede run.started_at");
131
+ if (run.exit_status !== null && (!Number.isInteger(run.exit_status) || typeof run.exit_status !== "number"))
132
+ invalid("run.exit_status must be an integer or null");
133
+ if (typeof run.state !== "string" || !RUN_STATES.has(run.state))
134
+ invalid("run.state must be completed, timed_out, killed, or interrupted");
135
+ if (!Array.isArray(body.tests) || body.tests.length > 10_000)
136
+ invalid("tests must contain at most 10,000 test cases");
137
+ const identities = new Set();
138
+ const tests = body.tests.map((value, i) => {
139
+ const t = record(value, `tests[${i}]`);
140
+ onlyKeys(t, ["id", "suite", "package", "outcome", "duration_ms", "identity_comparable", "failure"], `tests[${i}]`);
141
+ const id = safeDescription(t.id, `tests[${i}].id`, 512, true);
142
+ if (identities.has(id))
143
+ invalid(`tests contains duplicate test identity ${JSON.stringify(id)}`);
144
+ identities.add(id);
145
+ const suite = relativePath(t.suite, `tests[${i}].suite`, 512, false);
146
+ const pkg = relativePath(t.package, `tests[${i}].package`, 256, false);
147
+ if (typeof t.outcome !== "string" || !OUTCOMES.has(t.outcome))
148
+ invalid(`tests[${i}].outcome is not supported`);
149
+ const duration = t.duration_ms === undefined ? undefined : number(t.duration_ms, `tests[${i}].duration_ms`);
150
+ if (t.identity_comparable !== undefined && typeof t.identity_comparable !== "boolean")
151
+ invalid(`tests[${i}].identity_comparable must be boolean`);
152
+ let failure;
153
+ if (t.failure !== undefined) {
154
+ const f = record(t.failure, `tests[${i}].failure`);
155
+ onlyKeys(f, ["classification", "message_ref"], `tests[${i}].failure`);
156
+ const classification = safeLabel(f.classification, `tests[${i}].failure.classification`, 128, false);
157
+ const messageRef = safeDescription(f.message_ref, `tests[${i}].failure.message_ref`, 256, false);
158
+ failure = { ...(classification ? { classification } : {}), ...(messageRef ? { message_ref: messageRef } : {}) };
159
+ }
160
+ return { id, ...(suite ? { suite } : {}), ...(pkg ? { package: pkg } : {}), outcome: t.outcome, ...(duration !== undefined ? { duration_ms: duration } : {}), ...(t.identity_comparable === undefined ? {} : { identity_comparable: t.identity_comparable }), ...(failure ? { failure } : {}) };
161
+ });
162
+ if (body.build_targets !== undefined) {
163
+ if (!Array.isArray(body.build_targets) || body.build_targets.length > 100)
164
+ invalid("build_targets must contain at most 100 targets");
165
+ body.build_targets.forEach((value, i) => {
166
+ const target = record(value, `build_targets[${i}]`);
167
+ onlyKeys(target, ["name", "status", "duration_ms"], `build_targets[${i}]`);
168
+ safeDescription(target.name, `build_targets[${i}].name`, 256, true);
169
+ if (!new Set(["compiled", "not_compiled", "failed", "unknown"]).has(String(target.status)))
170
+ invalid(`build_targets[${i}].status is not supported`);
171
+ if (target.duration_ms !== undefined)
172
+ number(target.duration_ms, `build_targets[${i}].duration_ms`);
173
+ });
174
+ }
175
+ if (body.load !== undefined) {
176
+ const load = record(body.load, "load");
177
+ onlyKeys(load, ["load_average", "available_cpu", "available_memory_bytes", "concurrent_jobs", "sandbox_contention", "unavailable_reason"], "load");
178
+ for (const key of ["load_average", "available_cpu", "available_memory_bytes", "concurrent_jobs"]) {
179
+ if (load[key] !== undefined && load[key] !== null)
180
+ number(load[key], `load.${key}`, key !== "load_average" && key !== "available_cpu");
181
+ if (load[key] === null && load.unavailable_reason === undefined)
182
+ invalid(`load.unavailable_reason is required when load.${key} is null`);
183
+ }
184
+ if (load.sandbox_contention !== undefined && load.sandbox_contention !== null && typeof load.sandbox_contention !== "boolean")
185
+ invalid("load.sandbox_contention must be boolean or null");
186
+ safeDescription(load.unavailable_reason, "load.unavailable_reason", 256, false);
187
+ }
188
+ if (body.artifact !== undefined) {
189
+ const artifact = record(body.artifact, "artifact");
190
+ onlyKeys(artifact, ["evidence_id", "sha256"], "artifact");
191
+ string(artifact.evidence_id, "artifact.evidence_id", 128);
192
+ if (typeof artifact.sha256 !== "string" || !/^[0-9a-f]{64}$/i.test(artifact.sha256))
193
+ invalid("artifact.sha256 must be a SHA-256 string");
194
+ }
195
+ const draft = {
196
+ schema_version: 1,
197
+ source: { ...source },
198
+ invocation: { argv: [...invocation.argv], cwd },
199
+ runner: { ...runner, importer_version: CLI_VERSION, os, arch },
200
+ run: { ...run, started_at: startedAt, ended_at: endedAt },
201
+ tests,
202
+ ...(body.build_targets === undefined ? {} : { build_targets: body.build_targets }),
203
+ ...(body.load === undefined ? {} : { load: body.load }),
204
+ };
205
+ if (new TextEncoder().encode(JSON.stringify(draft)).byteLength > 4 * 1024 * 1024)
206
+ invalid("canonical test-run JSON exceeds 4 MiB; split the target or reduce metadata");
207
+ return draft;
208
+ }
209
+ function parseJUnit(bytes) {
210
+ let xml;
211
+ try {
212
+ xml = new TextDecoder("utf-8", { fatal: true }).decode(bytes);
213
+ }
214
+ catch {
215
+ invalid("JUnit report must be UTF-8 XML");
216
+ }
217
+ if (/<!\s*DOCTYPE/i.test(xml))
218
+ invalid("JUnit XML DOCTYPE is not supported; external or declared entities are refused");
219
+ const tests = [];
220
+ const suites = [];
221
+ let rootDeclaredTests;
222
+ let rootSeen = false;
223
+ let gapIndex = 0;
224
+ const seenIds = new Map();
225
+ let activeCase;
226
+ let caseIndex = 0;
227
+ let parseError;
228
+ const parser = new SaxesParser({ xmlns: false });
229
+ parser.on("error", (error) => { parseError ??= error; });
230
+ parser.on("doctype", () => { parseError ??= new Error("DOCTYPE is not supported"); });
231
+ parser.on("opentag", (tag) => {
232
+ const a = tag.attributes;
233
+ if (!rootSeen) {
234
+ rootSeen = true;
235
+ if (tag.name !== "testsuite" && tag.name !== "testsuites")
236
+ parseError ??= new Error("root must be testsuite or testsuites");
237
+ }
238
+ if (tag.name === "testsuites") {
239
+ const declared = a.tests === undefined ? undefined : Number(a.tests);
240
+ if (declared !== undefined && (!Number.isSafeInteger(declared) || declared < 0)) {
241
+ parseError ??= new Error("testsuites tests count is invalid");
242
+ return;
243
+ }
244
+ rootDeclaredTests = declared;
245
+ }
246
+ if (tag.name === "testsuite") {
247
+ if (suites.length > 8) {
248
+ parseError ??= new Error("JUnit suite nesting exceeds 8 levels");
249
+ return;
250
+ }
251
+ const declared = a.tests === undefined ? undefined : Number(a.tests);
252
+ if (declared !== undefined && (!Number.isSafeInteger(declared) || declared < 0)) {
253
+ parseError ??= new Error("testsuite tests count is invalid");
254
+ return;
255
+ }
256
+ if (suites.length)
257
+ suites[suites.length - 1].nested = true;
258
+ suites.push({ name: a.file ?? a.name, tests: declared, descendantCases: 0, childGaps: 0, nested: false });
259
+ }
260
+ else if (tag.name === "testcase") {
261
+ if (activeCase) {
262
+ parseError ??= new Error("nested testcase elements are not supported");
263
+ return;
264
+ }
265
+ for (const suite of suites)
266
+ suite.descendantCases++;
267
+ caseIndex++;
268
+ const suiteName = suites.at(-1)?.name;
269
+ const duration = a.time === undefined ? undefined : Number(a.time) * 1000;
270
+ if (duration !== undefined && (!Number.isFinite(duration) || duration < 0)) {
271
+ parseError ??= new Error("testcase time must be finite and non-negative");
272
+ return;
273
+ }
274
+ activeCase = { suite: suiteName, classname: a.classname, name: a.name, durationMs: duration, state: "passed" };
275
+ }
276
+ else if (activeCase && (tag.name === "failure" || tag.name === "error")) {
277
+ activeCase.state = "failed";
278
+ const classification = a.type;
279
+ activeCase.failureClass = classification && classification.length <= 128 && /^[A-Za-z0-9][A-Za-z0-9._+-]*$/.test(classification) && !classification.includes("..")
280
+ ? classification
281
+ : tag.name;
282
+ }
283
+ else if (activeCase && tag.name === "skipped" && activeCase.state !== "failed") {
284
+ activeCase.state = "skipped";
285
+ }
286
+ });
287
+ parser.on("closetag", (tag) => {
288
+ if (tag.name === "testcase" && activeCase) {
289
+ const suite = safeSuite(activeCase.suite);
290
+ const classname = safeIdentityPart(activeCase.classname);
291
+ const name = safeIdentityPart(activeCase.name);
292
+ const comparable = !!suite && !!classname && !!name;
293
+ const stableId = comparable ? `${suite}/${classname} :: ${name}` : undefined;
294
+ let id = stableId ?? `unknown/testcase-${caseIndex}`;
295
+ let row = {
296
+ id,
297
+ ...(suite ? { suite } : {}),
298
+ outcome: activeCase.state,
299
+ ...(activeCase.durationMs === undefined ? {} : { duration_ms: Math.round(activeCase.durationMs * 1000) / 1000 }),
300
+ ...(!comparable ? { identity_comparable: false } : {}),
301
+ ...(activeCase.state === "failed" ? { failure: { classification: activeCase.failureClass ?? "failure" } } : {}),
302
+ };
303
+ if (stableId && seenIds.has(stableId)) {
304
+ for (const priorIndex of seenIds.get(stableId)) {
305
+ const prior = tests[priorIndex];
306
+ prior.id = `unknown/duplicate-testcase-${priorIndex + 1}`;
307
+ prior.identity_comparable = false;
308
+ }
309
+ id = `unknown/duplicate-testcase-${caseIndex}`;
310
+ row = { ...row, id, identity_comparable: false };
311
+ seenIds.get(stableId).push(tests.length);
312
+ }
313
+ else if (stableId) {
314
+ seenIds.set(stableId, [tests.length]);
315
+ }
316
+ tests.push(row);
317
+ activeCase = undefined;
318
+ if (tests.length > 10_000)
319
+ parseError ??= new Error("JUnit report exceeds 10,000 testcase entries");
320
+ }
321
+ if (tag.name === "testsuite") {
322
+ const suite = suites.pop();
323
+ if (!suite) {
324
+ parseError ??= new Error("JUnit testsuite nesting is invalid");
325
+ return;
326
+ }
327
+ if (suite.tests !== undefined && suite.tests < suite.descendantCases + suite.childGaps) {
328
+ parseError ??= new Error("testsuite declares fewer tests than its child entries");
329
+ return;
330
+ }
331
+ const missing = suite.tests === undefined ? 0 : suite.tests - suite.descendantCases - suite.childGaps;
332
+ if (missing > 0) {
333
+ const suiteName = safeSuite(suite.name);
334
+ const id = `unknown/suite-${++gapIndex} :: report coverage gap (${missing} unreported)`;
335
+ tests.push({ id, ...(suiteName ? { suite: suiteName } : {}), outcome: "unknown", identity_comparable: false });
336
+ if (suites.length)
337
+ suites[suites.length - 1].childGaps += missing;
338
+ }
339
+ }
340
+ });
341
+ try {
342
+ parser.write(xml).close();
343
+ }
344
+ catch (error) {
345
+ parseError ??= error;
346
+ }
347
+ if (parseError)
348
+ invalid(`invalid JUnit XML: ${parseError.message}`);
349
+ if (activeCase || suites.length)
350
+ invalid("invalid JUnit XML: report ended before all test cases and suites closed");
351
+ if (!rootSeen)
352
+ invalid("JUnit XML must contain a testsuite or testsuites root");
353
+ if (rootDeclaredTests !== undefined) {
354
+ const gaps = tests.filter((test) => test.identity_comparable === false && test.id.includes("report coverage gap")).reduce((n, t) => n + Number(/\((\d+) unreported\)/.exec(t.id)?.[1] ?? 0), 0);
355
+ const actualCases = caseIndex;
356
+ if (rootDeclaredTests < actualCases + gaps)
357
+ invalid("testsuites declares fewer tests than its child entries");
358
+ if (rootDeclaredTests > actualCases + gaps)
359
+ tests.push({ id: `unknown/report :: report coverage gap ${++gapIndex} (${rootDeclaredTests - actualCases - gaps} unreported)`, outcome: "unknown", identity_comparable: false });
360
+ }
361
+ return tests;
362
+ }
363
+ function safeSuite(value) {
364
+ if (!value || value.length > 512)
365
+ return undefined;
366
+ const normalized = value.replace(/\\/g, "/").replace(/^\.\//, "");
367
+ if (normalized.startsWith("/") || normalized.split("/").some((part) => !part || part === "." || part === ".." || PRIVATE_PARTS.has(part.toLowerCase())) || !/^[A-Za-z0-9][A-Za-z0-9._@+-]*(?:\/[A-Za-z0-9][A-Za-z0-9._@+-]*)*$/.test(normalized))
368
+ return undefined;
369
+ return normalized;
370
+ }
371
+ function safeIdentityPart(value) {
372
+ if (!value || value.length > 256 || PRIVATE_PATH.test(value) || ABSOLUTE_PATH.test(value) || SECRET.test(value) || ASSIGNMENT.test(value))
373
+ return undefined;
374
+ return value.trim() || undefined;
375
+ }
376
+ function parseJson(bytes, field) {
377
+ let textValue;
378
+ try {
379
+ textValue = new TextDecoder("utf-8", { fatal: true }).decode(bytes);
380
+ }
381
+ catch {
382
+ invalid(`${field} must be UTF-8 JSON`);
383
+ }
384
+ try {
385
+ return record(JSON.parse(textValue), field);
386
+ }
387
+ catch (error) {
388
+ if (error instanceof CliError)
389
+ throw error;
390
+ invalid(`${field} must be valid JSON`);
391
+ }
392
+ }
393
+ /** Accept a v1 JSON draft or JUnit XML plus a JSON run-context file. */
394
+ export function parseTestRunReport(filename, bytes, metadataBytes) {
395
+ if (!bytes.byteLength)
396
+ invalid("report file is empty");
397
+ if (filename.toLowerCase().endsWith(".json")) {
398
+ if (metadataBytes)
399
+ invalid("--metadata-file is only used with JUnit XML");
400
+ return validateDraft(parseJson(bytes, "report"));
401
+ }
402
+ if (!filename.toLowerCase().endsWith(".xml"))
403
+ invalid("report must end in .json or .xml");
404
+ if (!metadataBytes)
405
+ invalid("JUnit import requires --metadata-file with schema_version, source, invocation, runner, and run fields");
406
+ const metadata = parseJson(metadataBytes, "metadata");
407
+ if (Object.hasOwn(metadata, "tests") || Object.hasOwn(metadata, "artifact"))
408
+ invalid("JUnit metadata-file must not contain tests or artifact; tests are parsed from the XML and artifact is generated from it");
409
+ const tests = parseJUnit(bytes);
410
+ return validateDraft({ ...metadata, tests });
411
+ }
412
+ export function summarizeTestRun(run) {
413
+ const counts = { passed: 0, failed: 0, skipped: 0, did_not_run: 0, still_running_at_stop: 0, unknown: 0 };
414
+ for (const test of run.tests ?? [])
415
+ if (test.outcome && test.outcome in counts)
416
+ counts[test.outcome]++;
417
+ return `commit ${run.source?.commit ?? "unknown"}; ${run.run?.state ?? "unknown"}; ${counts.passed} passed, ${counts.failed} failed, ${counts.skipped} skipped, ${counts.did_not_run} did not run, ${counts.still_running_at_stop} active at stop, ${counts.unknown} unknown`;
418
+ }
package/dist/version.js CHANGED
@@ -1 +1 @@
1
- export const CLI_VERSION = "0.12.108";
1
+ export const CLI_VERSION = "0.12.110";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "benignswarm",
3
- "version": "0.12.108",
3
+ "version": "0.12.110",
4
4
  "description": "b9s: chat, status board and evidence store for coding agents (benignswarm.org)",
5
5
  "license": "UNLICENSED",
6
6
  "repository": {
@@ -44,6 +44,7 @@
44
44
  "dependencies": {
45
45
  "@aws-sdk/client-ecr": "^3.1170.0",
46
46
  "@aws-sdk/client-sts": "^3.1170.0",
47
- "@aws-sdk/credential-provider-imds": "^3.370.0"
47
+ "@aws-sdk/credential-provider-imds": "^3.370.0",
48
+ "saxes": "^6.0.0"
48
49
  }
49
50
  }