benignswarm 0.12.103 → 0.12.105

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.
@@ -20,7 +20,7 @@ export async function projectImageAdmin(rest, p, out) {
20
20
  }
21
21
  const c = Client.forAdmin(loadAdmin(resolveAdminName(str(p.flags, "admin"))));
22
22
  if (!sub || !project) {
23
- throw new CliError("usage", "project image <validate --file f | config <p> [--path f] [--arch linux/amd64|linux/arm64] [--cache name...] | show <p> | build <p> --commit <sha> --file <devcontainer.json> [--dockerfile f] [--arch a] | rollback <p> (<sha256:...> | clear)>");
23
+ throw new CliError("usage", "project image <validate --file f | config <p> [--path f] [--arch linux/amd64|linux/arm64] [--cache name...] | show <p> | build <p> --commit <sha> --file <devcontainer.json> [--dockerfile f] [--arch a] | activate <p> <sha256:...> | rollback <p> (<sha256:...> | clear)>");
24
24
  }
25
25
  switch (sub) {
26
26
  case "config": {
@@ -71,6 +71,14 @@ export async function projectImageAdmin(rest, p, out) {
71
71
  out.print(`Project ${project} active digest is now ${r.image.active_digest ?? "(none)"}`, r);
72
72
  return;
73
73
  }
74
+ case "activate": {
75
+ const digest = rest[2];
76
+ if (!digest)
77
+ throw new CliError("usage", "project image activate <project> <sha256:...>");
78
+ const r = await c.call("POST", `/projects/${encodeURIComponent(project)}/image/select`, { image_digest: digest });
79
+ out.print(`Project ${project} active digest is now ${r.image.active_digest ?? "(none)"}`, r);
80
+ return;
81
+ }
74
82
  default:
75
83
  throw new CliError("usage", "project image validate|config|show|build|rollback ...");
76
84
  }
@@ -954,6 +954,7 @@ export async function agentMove(rest, p, out) {
954
954
  say(` move ${move.id}: ${move.from ?? "source"} → ${to}; other agent keys will be revoked only after completion`);
955
955
  await c.call("PATCH", progressRoute, { status: "checking", expected_status: "requested", detail: "trusted CLI is checking local readiness and preparing the handoff" });
956
956
  let problems = [];
957
+ const skippedWorktrees = [];
957
958
  const destinationHost = str(p.flags, "to-ssh") ?? to;
958
959
  try {
959
960
  const destination = await c.call("GET", `/machines/${to}`);
@@ -963,34 +964,108 @@ export async function agentMove(rest, p, out) {
963
964
  throw new CliError("destination_not_ready", readinessError);
964
965
  // 1. Work in progress must be on origin, or it stays behind on the old machine.
965
966
  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));
967
+ if (units.length && !move.from)
968
+ throw new CliError("source_machine_unknown", `the move operation has active units but no recorded source machine; cannot scope their worktrees on ${from}`);
969
+ const sourceMachine = move.from ?? from;
970
+ const observedWorktrees = units.length ? (await c.call("GET", `/projects/${project}/worktrees`)).worktrees : [];
971
+ if (!Array.isArray(observedWorktrees))
972
+ throw new CliError("worktrees_unavailable", `cannot determine which worktrees are recorded on source machine ${sourceMachine}`);
973
+ const worktrees = observedWorktrees.filter((w) => w.missing_at == null);
974
+ const attributedToAgent = (worktree) => {
975
+ // Older/scan-only registry rows may have no attribution yet. In that case,
976
+ // an owner's matching unit path/branch is the bounded legacy fallback.
977
+ if (!Array.isArray(worktree.agents) || worktree.agents.length === 0)
978
+ return true;
979
+ return worktree.agents.some((a) => a?.name === agent);
980
+ };
981
+ const inspections = [];
982
+ const inspectedPaths = new Set();
983
+ const addInspection = (unit, path, label) => {
984
+ if (inspectedPaths.has(path))
985
+ return;
986
+ inspectedPaths.add(path);
987
+ inspections.push({ unit, path, label });
988
+ };
966
989
  for (const u of units) {
967
- if (!u.worktree) {
968
- problems.push(`#${u.number} (${u.branch ?? "no branch recorded"}): no worktree is recorded, so its Git state cannot be verified`);
969
- continue;
990
+ const pathRecords = worktrees.filter((w) => w.path === u.worktree);
991
+ const branchRecords = u.branch ? worktrees.filter((w) => w.branch === u.branch) : [];
992
+ const related = [...new Map([...pathRecords, ...branchRecords].map((w) => [`${w.machine}\0${w.path}`, w])).values()];
993
+ const owner = u.owner_name === agent;
994
+ const reviewer = Array.isArray(u.reviewers) && u.reviewers.some((r) => r?.name === agent);
995
+ if (owner) {
996
+ const attributable = related.filter(attributedToAgent);
997
+ const sourceRecords = attributable.filter((w) => w.machine === sourceMachine);
998
+ const elsewhere = [...new Set(attributable.filter((w) => w.machine !== sourceMachine).map((w) => String(w.machine)))];
999
+ if (sourceRecords.length) {
1000
+ for (const record of sourceRecords)
1001
+ addInspection(u, record.path, `#${u.number} (${u.branch ?? "no branch recorded"})`);
1002
+ }
1003
+ else if (elsewhere.length) {
1004
+ skippedWorktrees.push(`#${u.number}: owned worktree ${u.worktree ?? u.branch ?? "(unknown)"} is recorded on ${elsewhere.join(", ")}, not ${sourceMachine}`);
1005
+ }
1006
+ else if (u.worktree) {
1007
+ // Preserve the existing owned-unit check when no machine observation has been recorded yet.
1008
+ addInspection(u, u.worktree, `#${u.number} (${u.branch ?? "no branch recorded"})`);
1009
+ }
1010
+ else if (!u.branch) {
1011
+ skippedWorktrees.push(`#${u.number}: no branch or worktree is recorded, so no source worktree can be left behind`);
1012
+ }
1013
+ else {
1014
+ problems.push(`#${u.number} (${u.branch ?? "no branch recorded"}): no worktree is recorded, so its Git state cannot be verified`);
1015
+ }
1016
+ }
1017
+ else if (reviewer) {
1018
+ const attributed = related.filter((w) => Array.isArray(w.agents) && w.agents.some((a) => a?.name === agent));
1019
+ const sourceRecords = attributed.filter((w) => w.machine === sourceMachine);
1020
+ const elsewhere = [...new Set(related.filter((w) => w.machine !== sourceMachine).map((w) => String(w.machine)))];
1021
+ if (sourceRecords.length) {
1022
+ for (const record of sourceRecords)
1023
+ addInspection(u, record.path, `#${u.number} (${u.branch ?? "no branch recorded"})`);
1024
+ }
1025
+ else if (!worktrees.some((w) => w.machine === sourceMachine && Array.isArray(w.agents) && w.agents.some((a) => a?.name === agent))) {
1026
+ skippedWorktrees.push(`#${u.number}: review assignment is not this agent's source-machine worktree${elsewhere.length ? `; related worktree record(s) are on ${elsewhere.join(", ")}, not ${sourceMachine}` : " (no source-machine worktree is recorded)"}`);
1027
+ }
1028
+ }
1029
+ else {
1030
+ skippedWorktrees.push(`#${u.number}: API work-unit result is neither owned nor reviewed by ${agent}; skipped as unassigned work`);
970
1031
  }
1032
+ }
1033
+ // The registry's agent attribution is authoritative for a review worktree. It
1034
+ // covers detached heads and review branches that differ from the owner's unit
1035
+ // branch/path, which cannot be discovered by matching those fields alone.
1036
+ for (const record of worktrees.filter((w) => w.machine === sourceMachine && Array.isArray(w.agents) && w.agents.some((a) => a?.name === agent))) {
1037
+ const unit = units.find((u) => u.owner_name === agent && (u.worktree === record.path || (u.branch && u.branch === record.branch)))
1038
+ ?? units.find((u) => Array.isArray(u.reviewers) && u.reviewers.some((r) => r?.name === agent));
1039
+ addInspection(unit ?? null, record.path, unit ? `#${unit.number} (${unit.branch ?? "no branch recorded"})` : `agent worktree ${record.path}`);
1040
+ }
1041
+ for (const record of worktrees.filter((w) => w.machine !== sourceMachine && Array.isArray(w.agents) && w.agents.some((a) => a?.name === agent))) {
1042
+ skippedWorktrees.push(`agent worktree ${record.path} is recorded on ${record.machine}, not ${sourceMachine}`);
1043
+ }
1044
+ for (const { unit: u, path: worktree, label } of inspections) {
1045
+ const workLabel = u ? `#${u.number} (${u.branch ?? "no branch recorded"})` : label;
971
1046
  const unavailableMarker = "BSCHAT_MOVE_WORKTREE_UNAVAILABLE";
972
- const cd = `cd ${shellSingle(u.worktree)} 2>/dev/null || { printf '%s\\n' '${unavailableMarker}' >&2; exit 97; }; `;
1047
+ const cd = `cd ${shellSingle(worktree)} 2>/dev/null || { printf '%s\\n' '${unavailableMarker}' >&2; exit 97; }; `;
973
1048
  const unavailable = (result) => result.status === 97 && result.stderr.trim() === unavailableMarker;
974
1049
  const status = on(from, `${cd}git status --porcelain`);
975
1050
  if (unavailable(status)) {
976
- problems.push(`#${u.number} (${u.branch ?? "no branch recorded"}): ${u.worktree} is not available on ${from}`);
1051
+ problems.push(`${workLabel}: ${worktree} is not available on ${from}`);
977
1052
  continue;
978
1053
  }
979
1054
  if (status.status !== 0)
980
- throw new CliError("git_preflight_failed", `cannot inspect Git status for #${u.number} (${u.branch ?? "no branch recorded"}) on ${from}: ${status.stderr.trim().slice(0, 200) || `git status exited ${status.status}`}`);
1055
+ throw new CliError("git_preflight_failed", `cannot inspect Git status for ${workLabel} on ${from}: ${status.stderr.trim().slice(0, 200) || `git status exited ${status.status}`}`);
981
1056
  const unpushed = on(from, `${cd}git rev-list --count HEAD --not --remotes`);
982
1057
  if (unavailable(unpushed)) {
983
- problems.push(`#${u.number} (${u.branch ?? "no branch recorded"}): ${u.worktree} is not available on ${from}`);
1058
+ problems.push(`${workLabel}: ${worktree} is not available on ${from}`);
984
1059
  continue;
985
1060
  }
986
1061
  if (unpushed.status !== 0 || !/^\d+$/.test(unpushed.stdout.trim()))
987
- throw new CliError("git_preflight_failed", `cannot inspect unpushed commits for #${u.number} (${u.branch ?? "no branch recorded"}) on ${from}: ${unpushed.stderr.trim().slice(0, 200) || `git rev-list exited ${unpushed.status}`}`);
1062
+ throw new CliError("git_preflight_failed", `cannot inspect unpushed commits for ${workLabel} on ${from}: ${unpushed.stderr.trim().slice(0, 200) || `git rev-list exited ${unpushed.status}`}`);
988
1063
  const dirtyCount = status.stdout.trim() ? status.stdout.trimEnd().split("\n").length : 0;
989
1064
  const unpushedCount = Number(unpushed.stdout.trim());
990
1065
  if (dirtyCount || unpushedCount)
991
- problems.push(`#${u.number} (${u.branch}): ${unpushedCount} unpushed commit(s), ${dirtyCount} uncommitted file(s) in ${u.worktree}`);
1066
+ problems.push(`${workLabel}: ${unpushedCount} unpushed commit(s), ${dirtyCount} uncommitted file(s) in ${worktree}`);
992
1067
  else
993
- say(` #${u.number} [${u.status}] ${u.branch}: pushed and clean`);
1068
+ say(` ${u ? `#${u.number} [${u.status}] ${u.branch}` : label}: pushed and clean`);
994
1069
  }
995
1070
  if (problems.length && !bool(p.flags, "force"))
996
1071
  throw new CliError("unpushed_work", `${ref} has work only on ${from}:\n ${problems.join("\n ")}`, `Have the agent push it (or commit and push), then move it; to leave it on ${from}, rerun with --force --confirm-force ${ref}`);
@@ -1116,9 +1191,10 @@ export async function agentMove(rest, p, out) {
1116
1191
  `Move ${move.id} completed: ${ref} now runs on ${to} (${r.session.harness}/${r.session.provider}, ${r.session.sandbox}, ${r.session.dir || "automatic checkout"}${thread ? `, thread ${thread}` : ", a fresh session"}); its daemon starts it within 30 s.`,
1117
1192
  r.moved_from.length ? `Its session on ${r.moved_from.join(", ")} was removed.` : null,
1118
1193
  `${r.revoked_keys} key(s) elsewhere revoked: a watcher left running there stops and removes itself. Archive its old thread in the Codex app so nobody types into that copy.`,
1194
+ ...skippedWorktrees.map((skipped) => `Skipped ${skipped}`),
1119
1195
  problems.length ? `Left behind on ${from} (--force confirmed): ${problems.join("; ")}` : null,
1120
1196
  `Follow it: b9s-admin machine show ${to}`,
1121
- ].filter(Boolean).join("\n"), r);
1197
+ ].filter(Boolean).join("\n"), { ...r, skipped_worktrees: skippedWorktrees });
1122
1198
  }
1123
1199
  /** --at: an ISO timestamp, or HH:MM in this machine's local time (today, or tomorrow when past). */
1124
1200
  export function maintenanceStart(at, nowMs = Date.now()) {
@@ -1,6 +1,6 @@
1
1
  import { spawn, spawnSync } from "node:child_process";
2
2
  import { createHash, createHmac } from "node:crypto";
3
- import { chmodSync, closeSync, existsSync, mkdirSync, mkdtempSync, openSync, readdirSync, readFileSync, readSync, realpathSync, rmSync, statSync, statfsSync, unlinkSync, writeFileSync } from "node:fs";
3
+ import { chmodSync, closeSync, cpSync, existsSync, lstatSync, mkdirSync, mkdtempSync, openSync, readdirSync, readFileSync, readSync, realpathSync, rmSync, statSync, statfsSync, unlinkSync, writeFileSync } from "node:fs";
4
4
  import { arch, cpus, freemem, homedir, hostname, loadavg, platform, tmpdir, totalmem, userInfo } from "node:os";
5
5
  import { dirname, isAbsolute, join, relative, resolve } from "node:path";
6
6
  import { str } from "../args.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, isolatedBuildCommand, isolatedDevcontainerBuildCommand, isolatedImagePullCommands, isolatedSubprocessEnv, probeImdsIsolation, probeNestedSandbox, readGitIdentity, resolveSessionSecretDelivery, validateDevcontainerSpec, } from "../container.js";
25
+ import { agentContainerName, agentContainerRunArgs, isolatedBuildCommand, isolatedDevcontainerBuildCommand, isolatedImagePullCommands, isolatedSubprocessEnv, networklessRuntimeWrapper, probeImdsIsolation, probeNestedSandbox, readGitIdentity, resolveSessionSecretDelivery, 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";
@@ -30,6 +30,11 @@ import { authorizeWorktreeScope, redactProcessCommand, scanWorktreeProcesses } f
30
30
  import { collectPruneProtection } from "../prune-protection.js";
31
31
  import { runMachineDaemonLoop } from "../machine-daemon.js";
32
32
  import { pruneProjectWorktrees } from "./worktrees.js";
33
+ import { ECRClient } from "@aws-sdk/client-ecr";
34
+ import { EcrHostedRegistry } from "../hosted-registry-ecr.js";
35
+ import { publishHostedImage } from "../hosted-registry.js";
36
+ import { assumeHostedBuilder } from "../hosted-registry-session.js";
37
+ import { pushHostedImage } from "../hosted-registry-push.js";
33
38
  export const machineFile = () => join(configRoot(), "machine.json");
34
39
  export function loadMachine() {
35
40
  const f = machineFile();
@@ -103,7 +108,7 @@ const MACHINE_REQUEST_TIMEOUT_MS = 45_000;
103
108
  const MACHINE_PASS_BUDGET_MS = 4 * 60_000;
104
109
  const MACHINE_WATCHDOG_MS = 5 * 60_000;
105
110
  export function resolvePinnedImageRef(image) {
106
- const raw = (image?.rollback_digest ?? image?.active_digest)?.trim() ?? "";
111
+ const raw = image?.active_digest?.trim() ?? "";
107
112
  if (!raw || /:latest\b/i.test(raw))
108
113
  return null;
109
114
  const normalized = raw.includes("@sha256:") ? raw : `${image?.registry_namespace ?? ""}@${raw}`;
@@ -120,6 +125,110 @@ function assertConfinedSnapshotPath(snapshotRealRoot, rawPath, label) {
120
125
  return targetReal;
121
126
  }
122
127
  const LOCKFILE_CANDIDATES = ["package-lock.json", "pnpm-lock.yaml", "yarn.lock", "Cargo.lock", "poetry.lock", "uv.lock"];
128
+ function runImageValidationCommand(runtime, imageRef, command, sourceDir) {
129
+ const args = ["run", "--rm", "--network", "none", "--read-only", "--cap-drop", "ALL", "--security-opt", "no-new-privileges", "--pids-limit", "256", "--memory", "4g", "--cpus", "2", "--tmpfs", "/tmp:rw,nosuid,nodev,noexec,size=512m"];
130
+ if (sourceDir)
131
+ args.push("--mount", `type=bind,source=${sourceDir},target=/workspace`, "--workdir", "/workspace");
132
+ args.push(imageRef, "/bin/sh", "-lc", command);
133
+ return { cmd: runtime, args };
134
+ }
135
+ const MAX_BUILD_CONTEXT_FILES = 20_000;
136
+ const MAX_BUILD_CONTEXT_BYTES = 512 * 1024 * 1024;
137
+ export function assertBuildContextHasNoSecrets(root) {
138
+ let files = 0;
139
+ let bytes = 0;
140
+ const visit = (dir) => {
141
+ for (const name of readdirSync(dir)) {
142
+ const path = join(dir, name);
143
+ const stat = lstatSync(path);
144
+ if (stat.isDirectory()) {
145
+ visit(path);
146
+ continue;
147
+ }
148
+ if (stat.isSymbolicLink())
149
+ throw new Error("build context contains a symlink; refusing an unbounded secret scan");
150
+ if (!stat.isFile())
151
+ continue;
152
+ files += 1;
153
+ bytes += stat.size;
154
+ if (files > MAX_BUILD_CONTEXT_FILES || bytes > MAX_BUILD_CONTEXT_BYTES) {
155
+ throw new Error("build context exceeds bounded secret scan limits; refusing build");
156
+ }
157
+ if (containsBuildSecretMaterial(readFileSync(path))) {
158
+ throw new Error("build context contains credential material; refusing to place secrets in image layers");
159
+ }
160
+ }
161
+ };
162
+ visit(root);
163
+ }
164
+ function scanImageArchiveEntry(archivePath, entryPath, runner, env) {
165
+ const quote = (value) => `'${value.replace(/'/g, "'\\''")}'`;
166
+ // Stream archive members through a bounded scanner. It never prints matched bytes or secret values.
167
+ const scanner = `let tail='';let total=0;const re=new RegExp(${JSON.stringify(BUILD_SECRET_CONTENT_RE.source)},'im');process.stdin.on('data',b=>{total+=b.length;if(total>536870912){process.exitCode=43;process.stdin.destroy();return}const s=tail+b.toString('latin1');if(re.test(s)){process.exitCode=42;process.stdin.destroy();return}tail=s.slice(-1024)});`;
168
+ const script = `tar -xOf ${quote(archivePath)} ${quote(entryPath)} | ${quote(process.execPath)} -e ${quote(scanner)}`;
169
+ const result = runner("bash", ["-o", "pipefail", "-c", script], { env, timeout: 900_000 });
170
+ if (result.status === 42)
171
+ throw new Error("exported image contains credential material in config or layer history");
172
+ if (result.status !== 0)
173
+ throw new Error(`could not complete bounded secret scan of exported image (status ${result.status}); refusing ready status`);
174
+ }
175
+ function scanImageArchiveConfig(archivePath, entryPath, runner, env) {
176
+ const quote = (value) => `'${value.replace(/'/g, "'\\''")}'`;
177
+ // Image config is JSON and may contain nested JSON in labels or environment values. Parse
178
+ // those strings recursively so escaped quotes cannot hide a credential assignment.
179
+ const scanner = `const chunks=[];let total=0;const re=new RegExp(${JSON.stringify(BUILD_SECRET_CONTENT_RE.source)},'im');const keyRe=new RegExp(${JSON.stringify(BUILD_SECRET_KEY_NAME_RE.source)},'i');process.stdin.on('data',b=>{total+=b.length;if(total>16777216){process.exitCode=43;process.stdin.destroy();return}chunks.push(b)});process.stdin.on('end',()=>{let root;try{root=JSON.parse(Buffer.concat(chunks).toString('utf8'))}catch{process.exitCode=44;return}let nodes=0;function secret(value,depth){if(++nodes>100000||depth>32)throw Error('scan limit');if(typeof value==='string'){if(re.test(value))return true;let nested;try{nested=JSON.parse(value)}catch{return false}return nested&&typeof nested==='object'?secret(nested,depth+1):false}if(Array.isArray(value))return value.some(v=>secret(v,depth+1));if(value&&typeof value==='object')return Object.entries(value).some(([k,v])=>keyRe.test(k)||re.test(k)||secret(v,depth+1));return false}try{process.exitCode=secret(root,0)?42:0}catch{process.exitCode=43}});`;
180
+ const script = `tar -xOf ${quote(archivePath)} ${quote(entryPath)} | ${quote(process.execPath)} -e ${quote(scanner)}`;
181
+ const result = runner("bash", ["-o", "pipefail", "-c", script], { env, timeout: 30_000 });
182
+ if (result.status === 42)
183
+ throw new Error("exported image contains credential material in config or layer history");
184
+ if (result.status !== 0)
185
+ throw new Error(`could not complete bounded secret scan of exported image config (status ${result.status}); refusing ready status`);
186
+ }
187
+ function measureCompressedImageBytes(runtime, imageRef, archivePath, runner, env) {
188
+ const imageSize = runner(runtime, ["image", "inspect", imageRef, "--format", "{{.Size}}"], { env, timeout: 30_000 });
189
+ const uncompressedBytes = Number((imageSize.stdout ?? "").trim());
190
+ if (imageSize.status !== 0 || !Number.isSafeInteger(uncompressedBytes) || uncompressedBytes < 1)
191
+ throw new Error("could not inspect uncompressed image size before archive measurement");
192
+ const disk = statfsSync(dirname(archivePath));
193
+ const freeBytes = Number(disk.bavail) * Number(disk.bsize);
194
+ if (!Number.isSafeInteger(freeBytes) || freeBytes < Math.ceil(uncompressedBytes * 1.2))
195
+ throw new Error("insufficient free space to safely measure compressed image layers");
196
+ const saved = runner(runtime, ["image", "save", "--output", archivePath, imageRef], { env, timeout: 900_000 });
197
+ if (saved.status !== 0)
198
+ throw new Error(`could not export image for size measurement: ${errorText(saved.stderr || saved.stdout)}`);
199
+ const quote = (value) => `'${value.replace(/'/g, "'\\''")}'`;
200
+ const manifestResult = runner("tar", ["-xOf", archivePath, "manifest.json"], { env, timeout: 30_000 });
201
+ if (manifestResult.status !== 0)
202
+ throw new Error("image archive has no Docker manifest for size measurement");
203
+ let manifest;
204
+ try {
205
+ manifest = JSON.parse(manifestResult.stdout ?? "");
206
+ }
207
+ catch {
208
+ throw new Error("image archive Docker manifest is invalid");
209
+ }
210
+ const layers = manifest[0]?.Layers;
211
+ const config = manifest[0]?.Config;
212
+ if (!Array.isArray(layers) || !layers.length || layers.some((layer) => typeof layer !== "string" || layer.startsWith("/") || layer.split("/").includes("..")) || typeof config !== "string" || config.startsWith("/") || config.split("/").includes("..")) {
213
+ throw new Error("image archive manifest has invalid layer paths");
214
+ }
215
+ let bytes = Buffer.byteLength(manifestResult.stdout ?? "");
216
+ const configResult = runner("bash", ["-o", "pipefail", "-c", `tar -xOf ${quote(archivePath)} ${quote(config)} | wc -c`], { env, timeout: 30_000 });
217
+ const configBytes = Number((configResult.stdout ?? "").trim());
218
+ if (configResult.status !== 0 || !Number.isSafeInteger(configBytes) || configBytes < 0)
219
+ throw new Error("could not measure image config metadata");
220
+ scanImageArchiveConfig(archivePath, config, runner, env);
221
+ bytes += configBytes;
222
+ for (const layer of layers) {
223
+ scanImageArchiveEntry(archivePath, layer, runner, env);
224
+ const result = runner("bash", ["-o", "pipefail", "-c", `tar -xOf ${quote(archivePath)} ${quote(layer)} | gzip -c | wc -c`], { env, timeout: 900_000 });
225
+ const layerBytes = Number((result.stdout ?? "").trim());
226
+ if (result.status !== 0 || !Number.isSafeInteger(layerBytes) || layerBytes < 1)
227
+ throw new Error(`could not measure compressed image layer ${layer}`);
228
+ bytes += layerBytes;
229
+ }
230
+ return bytes;
231
+ }
123
232
  /**
124
233
  * Materializes an isolated read-only-intent git worktree at `build.source_commit` (never reading
125
234
  * mutable `<workdir>/<project>/main`), verifies `HEAD`, clean tree, `target_arch`, `recipe_hash`,
@@ -133,6 +242,13 @@ export async function reconcilePendingImageBuilds(client, projects, opts) {
133
242
  const build = img?.latest_build;
134
243
  if (!img || !build || build.status !== "pending")
135
244
  continue;
245
+ if (img.hosted_build_blocked_reason) {
246
+ const error = `hosted image build refused: ${img.hosted_build_blocked_reason}`;
247
+ await client.call("POST", `/machines/me/image-builds/${build.id}`, { status: "failed", error }).catch(() => { });
248
+ opts.log(`${project.name}: ${error}`);
249
+ results.push({ project_id: project.id, build_id: build.id, status: "failed", error });
250
+ continue;
251
+ }
136
252
  const nested = (opts.probeSandbox ?? probeNestedSandbox)({ runner });
137
253
  if (!nested.runtime) {
138
254
  if (process.env.B9S_CONTAINER_AGENTS === "1") {
@@ -252,6 +368,7 @@ export async function reconcilePendingImageBuilds(client, projects, opts) {
252
368
  const declaredFeatures = matchedSpec.features ?? [];
253
369
  let imageRef;
254
370
  if (declaredFeatures.length > 0) {
371
+ assertBuildContextHasNoSecrets(snapshotRealRoot);
255
372
  const dcCheck = runner("devcontainer", ["--version"], { env, timeout: 10_000 });
256
373
  if (dcCheck.status !== 0) {
257
374
  throw new Error(`devcontainer CLI is required to build devcontainer with features (${declaredFeatures.join(", ")}); refusing bare ${nested.runtime} build that would omit declared features`);
@@ -260,6 +377,7 @@ export async function reconcilePendingImageBuilds(client, projects, opts) {
260
377
  ...refPrefix,
261
378
  workspaceFolder: snapshotRealRoot,
262
379
  configPath: devcontainerReal,
380
+ dockerPath: networklessRuntimeWrapper(nested.runtime, buildTmpRoot),
263
381
  });
264
382
  imageRef = dcBuildSpec.imageRef;
265
383
  const b = runner(dcBuildSpec.cmd, dcBuildSpec.args, { cwd: snapshotRealRoot, env, timeout: 600_000 });
@@ -272,6 +390,7 @@ export async function reconcilePendingImageBuilds(client, projects, opts) {
272
390
  ? resolve(dcDir, buildSection.context)
273
391
  : snapshotRealRoot;
274
392
  const contextReal = assertConfinedSnapshotPath(snapshotRealRoot, rawCtx, "build.context");
393
+ assertBuildContextHasNoSecrets(contextReal);
275
394
  const buildSpec = isolatedBuildCommand({
276
395
  ...refPrefix,
277
396
  dockerfilePath: dockerfileReal,
@@ -313,10 +432,85 @@ export async function reconcilePendingImageBuilds(client, projects, opts) {
313
432
  if (insp.status !== 0 || !digestMatch) {
314
433
  throw new Error(`built image ${imageRef} did not yield an immutable @sha256 digest`);
315
434
  }
316
- const imageDigest = digestMatch[1].toLowerCase();
435
+ let imageDigest = digestMatch[1].toLowerCase();
436
+ const validationResults = [];
437
+ for (const probe of build.declared_probes ?? []) {
438
+ if (probe.scope !== "image")
439
+ continue;
440
+ const probeSpec = runImageValidationCommand(nested.runtime, imageRef, probe.probe);
441
+ const result = runner(probeSpec.cmd, probeSpec.args, { env, timeout: 60_000 });
442
+ const output = (result.stdout ?? "").trim();
443
+ validationResults.push(result.status === 0
444
+ ? { name: probe.name, scope: "image", ok: true, ...(output ? { version: sanitizeBuildDiagnosticText(output).slice(0, 120) } : {}) }
445
+ : { name: probe.name, scope: "image", ok: false, error: errorText(result.stderr || result.stdout || `${probe.name} probe exited ${result.status}`).slice(0, 300) });
446
+ }
447
+ const testCommand = typeof build.test_command === "string" ? build.test_command.trim() : "";
448
+ const projectTestDir = join(buildTmpRoot, "project-test");
449
+ let projectTest;
450
+ if (!testCommand) {
451
+ projectTest = { ok: false, error: "approved environment declaration is missing its project test command" };
452
+ }
453
+ else {
454
+ cpSync(snapshotRealRoot, projectTestDir, { recursive: true, dereference: false });
455
+ rmSync(join(projectTestDir, ".git"), { recursive: true, force: true });
456
+ const testSpec = runImageValidationCommand(nested.runtime, imageRef, testCommand, projectTestDir);
457
+ const testRun = runner(testSpec.cmd, testSpec.args, { env, cwd: buildTmpRoot, timeout: 1_800_000 });
458
+ projectTest = testRun.status === 0
459
+ ? { ok: true }
460
+ : { ok: false, error: errorText(testRun.stderr || testRun.stdout || `project test exited ${testRun.status}`).slice(0, 300) };
461
+ }
462
+ const compressedSizeBytes = measureCompressedImageBytes(nested.runtime, imageRef, join(buildTmpRoot, "image-size.tar"), runner, env);
463
+ const provenance = {
464
+ source_commit: resolvedCommit,
465
+ recipe_hash: matchedSpec.recipe_hash,
466
+ target_arch: build.target_arch,
467
+ base_image_digest: matchedSpec.base_image_digest ?? null,
468
+ builder_runtime: nested.runtime,
469
+ };
470
+ const validationError = [
471
+ ...validationResults.filter((r) => !r.ok).map((r) => `${r.name} probe failed: ${r.error}`),
472
+ ...(!projectTest.ok ? [`project test failed: ${projectTest.error}`] : []),
473
+ ...(compressedSizeBytes > 8 * 1024 * 1024 * 1024 ? ["compressed image exceeds the 8 GiB limit"] : []),
474
+ ].join("; ");
475
+ let hostedImageReference;
476
+ if (!validationError && img.hosted_registry) {
477
+ const registry = img.hosted_registry;
478
+ let ecr;
479
+ try {
480
+ let port;
481
+ if (opts.hostedPort) {
482
+ port = await opts.hostedPort(registry, imageRef, nested.runtime, buildTmpRoot, env);
483
+ }
484
+ else {
485
+ const session = await assumeHostedBuilder(opts.accountId, project.id, registry);
486
+ ecr = new ECRClient(session);
487
+ const ecrClient = ecr;
488
+ const registryId = registry.registry_endpoint.split(".")[0];
489
+ port = new EcrHostedRegistry(ecrClient, registryId, async (source, target) => {
490
+ const prefix = `${registry.registry_endpoint}/`;
491
+ if (!target.startsWith(prefix))
492
+ throw new Error("hosted registry target mismatch");
493
+ const lastColon = target.lastIndexOf(":");
494
+ return pushHostedImage({ ecr: ecrClient, registryId, endpoint: registry.registry_endpoint, repository: target.slice(prefix.length, lastColon), tag: target.slice(lastColon + 1), source, runtime: nested.runtime, directory: buildTmpRoot, runner, env });
495
+ });
496
+ }
497
+ const pushed = await publishHostedImage({ accountId: opts.accountId, projectId: project.id, registry, sourceImage: imageRef, tag: build.id }, port);
498
+ imageDigest = pushed.digest;
499
+ hostedImageReference = pushed.imageReference;
500
+ }
501
+ finally {
502
+ ecr?.destroy();
503
+ }
504
+ }
317
505
  await client.call("POST", `/machines/me/image-builds/${build.id}`, {
318
- status: "ready",
506
+ status: validationError ? "failed" : "ready",
319
507
  image_digest: imageDigest,
508
+ ...(hostedImageReference ? { image_reference: hostedImageReference } : {}),
509
+ probe_results: validationResults,
510
+ project_test: projectTest,
511
+ compressed_size_bytes: compressedSizeBytes,
512
+ provenance,
513
+ ...(validationError ? { error: validationError } : {}),
320
514
  tool_versions: {
321
515
  source_commit: resolvedCommit,
322
516
  recipe_hash: matchedSpec.recipe_hash,
@@ -325,11 +519,24 @@ export async function reconcilePendingImageBuilds(client, projects, opts) {
325
519
  ...(declaredFeatures.length ? { features: declaredFeatures.join(",") } : {}),
326
520
  },
327
521
  });
328
- opts.log(`${project.name}: built project image ${imageRef}@${imageDigest}`);
329
- results.push({ project_id: project.id, build_id: build.id, status: "ready", image_digest: imageDigest });
522
+ if (!validationError && validationResults.length) {
523
+ await client.call("POST", "/machines/me/image-probes", {
524
+ project_id: project.id,
525
+ image_digest: imageDigest,
526
+ probes: validationResults,
527
+ });
528
+ }
529
+ if (validationError) {
530
+ opts.log(`${project.name}: image candidate validation failed: ${validationError}`);
531
+ results.push({ project_id: project.id, build_id: build.id, status: "failed", error: validationError });
532
+ }
533
+ else {
534
+ opts.log(`${project.name}: built and validated project image ${imageRef}@${imageDigest}`);
535
+ results.push({ project_id: project.id, build_id: build.id, status: "ready", image_digest: imageDigest });
536
+ }
330
537
  }
331
538
  catch (e) {
332
- const error = e.message.slice(0, 500);
539
+ const error = sanitizeBuildDiagnosticText(e.message).slice(0, 500);
333
540
  await client.call("POST", `/machines/me/image-builds/${build.id}`, { status: "failed", error }).catch(() => { });
334
541
  opts.log(`${project.name}: image build failed: ${error}`);
335
542
  results.push({ project_id: project.id, build_id: build.id, status: "failed", error });
@@ -1047,14 +1254,15 @@ async function ensureCredentials(client, m, s, local, log) {
1047
1254
  }
1048
1255
  export function errorText(s) {
1049
1256
  const last = s.trim().split("\n").pop() ?? "";
1257
+ const redact = sanitizeBuildDiagnosticText;
1050
1258
  try {
1051
1259
  const parsed = JSON.parse(last);
1052
1260
  if (parsed.error === "directory_conflict")
1053
- return "directory_conflict: " + (parsed.message ?? last) + (parsed.hint ? "; " + parsed.hint : "");
1054
- return parsed.message ?? last;
1261
+ return redact("directory_conflict: " + (parsed.message ?? last) + (parsed.hint ? "; " + parsed.hint : ""));
1262
+ return redact(parsed.message ?? last).slice(0, 500);
1055
1263
  }
1056
1264
  catch {
1057
- return last.slice(0, 500);
1265
+ return redact(last).slice(0, 500);
1058
1266
  }
1059
1267
  }
1060
1268
  /** Whether the session has a turn running, its process, and a usage-limit pause still in force. */