benignswarm 0.12.104 → 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.
@@ -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()) {
@@ -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();
@@ -427,7 +432,7 @@ export async function reconcilePendingImageBuilds(client, projects, opts) {
427
432
  if (insp.status !== 0 || !digestMatch) {
428
433
  throw new Error(`built image ${imageRef} did not yield an immutable @sha256 digest`);
429
434
  }
430
- const imageDigest = digestMatch[1].toLowerCase();
435
+ let imageDigest = digestMatch[1].toLowerCase();
431
436
  const validationResults = [];
432
437
  for (const probe of build.declared_probes ?? []) {
433
438
  if (probe.scope !== "image")
@@ -467,10 +472,40 @@ export async function reconcilePendingImageBuilds(client, projects, opts) {
467
472
  ...(!projectTest.ok ? [`project test failed: ${projectTest.error}`] : []),
468
473
  ...(compressedSizeBytes > 8 * 1024 * 1024 * 1024 ? ["compressed image exceeds the 8 GiB limit"] : []),
469
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
+ }
470
505
  await client.call("POST", `/machines/me/image-builds/${build.id}`, {
471
506
  status: validationError ? "failed" : "ready",
472
507
  image_digest: imageDigest,
473
- ...(img.hosted_registry_repository ? { image_reference: `${imageRef}@${imageDigest}` } : {}),
508
+ ...(hostedImageReference ? { image_reference: hostedImageReference } : {}),
474
509
  probe_results: validationResults,
475
510
  project_test: projectTest,
476
511
  compressed_size_bytes: compressedSizeBytes,
@@ -40,19 +40,9 @@ export async function reportWatcherCapabilities(creds, project, definitions, cwd
40
40
  const results = await probeCapabilities(definitions, cwd);
41
41
  await Client.forAgent(creds, undefined, { presence: false, machineIdentity: true }).call("POST", `/projects/${project}/agents/me/capabilities`, { results });
42
42
  }
43
- /**
44
- * Event bridge for harnesses that can be woken from outside (Codex: `codex queue --thread <id>`).
45
- *
46
- * Default mode queues ONE short wake-up and nothing else until the agent has read (its own
47
- * `b9s inbox --unread` / `b9s read` advance the shared cursors). Content is never put in
48
- * the queue, so the agent always reads it fresh and superseded messages collapse naturally.
49
- * A direct message from a human operator re-wakes immediately even while a wake-up is pending.
50
- * `--full` restores the old behaviour of queueing the text itself (for harnesses that cannot run
51
- * b9s themselves when woken).
52
- */
53
- export async function watch(p, out) {
43
+ export async function watch(p, out, dependencies = {}) {
54
44
  const name = resolveAgentName(str(p.flags, "as"));
55
- const exec = str(p.flags, "exec");
45
+ let exec = str(p.flags, "exec");
56
46
  const interval = Number(str(p.flags, "interval") ?? "30");
57
47
  if (!Number.isInteger(interval) || interval < 5)
58
48
  throw new CliError("usage", "--interval must be an integer number of seconds, at least 5");
@@ -167,7 +157,7 @@ export async function watch(p, out) {
167
157
  }
168
158
  log(`watching${exec ? `, will run: ${exec}` : ""} every ${interval}s (${full ? "full text" : turnMode ? `turn mode, at most ${turnTimeout} min a turn` : "single wake-up"} mode)`);
169
159
  if (!once) {
170
- await waitForWatcherStartup(startupJitterSeconds, log, (milliseconds) => waitIntervalOrStop(milliseconds, stopped));
160
+ await (dependencies.waitForStartup ?? waitForWatcherStartup)(startupJitterSeconds, log, (milliseconds) => (dependencies.wait ?? waitIntervalOrStop)(milliseconds, stopped));
171
161
  if (stopping)
172
162
  return stoppingCode;
173
163
  }
@@ -191,9 +181,31 @@ export async function watch(p, out) {
191
181
  // the key on its own clock.
192
182
  let lastKeyCheck = 0;
193
183
  const ctl = { turn: null, failedAt: 0, loggedRunning: null, loggedFailureAt: null, pausedUntil: 0, pausedAt: 0 };
194
- const probe = turn ? probeFor(turn.harness, turn.session, name) : null;
184
+ let probe = turn ? turn.harness === "codex" ? followCurrentCodexProbe(name, turn.session) : probeFor(turn.harness, turn.session, name) : null;
195
185
  let resumeBriefDelivered = false;
196
186
  while (!stopping) {
187
+ if (turn?.harness === "codex") {
188
+ const current = readState(name);
189
+ const clear = current.pending_context_clear;
190
+ const observedThread = current.harness_session?.session_id;
191
+ const freshThread = clear?.status === "completed" ? clear.new_thread_id
192
+ : clear?.status === "pending" && observedThread && observedThread !== clear.old_thread_id ? observedThread
193
+ : null;
194
+ if (freshThread && freshThread !== turn.session) {
195
+ exec = resumeFreshCodexExecTemplate(exec, freshThread);
196
+ turn.session = freshThread;
197
+ probe = followCurrentCodexProbe(name, freshThread);
198
+ bindSession("codex", freshThread, name);
199
+ }
200
+ if (freshThread && clear?.status === "pending") {
201
+ writeState(name, { ...readState(name), pending_context_clear: { ...clear, new_thread_id: freshThread } });
202
+ log(`context clear opened fresh Codex thread ${freshThread}; the pending unit start will complete its recorded decision`);
203
+ }
204
+ else if (freshThread && clear?.status === "completed") {
205
+ writeState(name, { ...readState(name), pending_context_clear: undefined });
206
+ log(`context clear completed; watcher now follows fresh Codex thread ${freshThread}`);
207
+ }
208
+ }
197
209
  if (activity && heartbeatClient)
198
210
  lastSample = await heartbeatIfActive(heartbeatClient, activity, lastSample, interval, log);
199
211
  if (stopping)
@@ -209,7 +221,7 @@ export async function watch(p, out) {
209
221
  if (taken)
210
222
  log(`worktree scan: skipped, ${taken}`);
211
223
  else {
212
- const r = await scanProject(scanCreds, scanCreds.project);
224
+ const r = await (dependencies.scanProject ?? scanProject)(scanCreds, scanCreds.project);
213
225
  log(`worktree scan: ${r.recorded} in ${r.repo}${r.missing ? `, ${r.missing} gone` : ""}`);
214
226
  }
215
227
  if (bool(p.flags, "prune")) {
@@ -241,7 +253,7 @@ export async function watch(p, out) {
241
253
  const processInfo = await client.call("GET", `/projects/${scanCreds.project}/process`);
242
254
  const definitions = (processInfo.process?.definition?.capabilities ?? []);
243
255
  if (definitions.length) {
244
- await reportWatcherCapabilities(scanCreds, scanCreds.project, definitions, process.cwd());
256
+ await (dependencies.reportCapabilities ?? reportWatcherCapabilities)(scanCreds, scanCreds.project, definitions, process.cwd());
245
257
  log(`capabilities: probed ${definitions.length} project requirements`);
246
258
  }
247
259
  lastCapabilities = Date.now();
@@ -274,13 +286,14 @@ export async function watch(p, out) {
274
286
  }
275
287
  if (!full) {
276
288
  try {
277
- if (probe)
278
- await turnStep(ctl, probe, turnTimeout, log, async (sink, beforeTurn) => {
279
- const result = await wakeOnce(name, exec, unackedAfter, followDelay, log, turn?.model ?? str(p.flags, "model"), once, sink, !resumeBriefDelivered, turn?.harness === "claude-code" ? turn.provider : undefined, turn?.harness === "dsh", () => probe.beginTurn?.(), beforeTurn, turn?.harness === "claude-code" ? turn.session : undefined, turn?.coalesceSeconds ?? 0);
289
+ const activeProbe = probe;
290
+ if (activeProbe)
291
+ await (dependencies.turnStep ?? turnStep)(ctl, activeProbe, turnTimeout, log, async (sink, beforeTurn) => {
292
+ const result = await (dependencies.wakeOnce ?? wakeOnce)(name, exec, unackedAfter, followDelay, log, turn?.model ?? str(p.flags, "model"), once, sink, !resumeBriefDelivered, turn?.harness === "claude-code" ? turn.provider : undefined, turn?.harness === "dsh", () => activeProbe.beginTurn?.(), beforeTurn, turn?.harness === "claude-code" ? turn.session : undefined, turn?.coalesceSeconds ?? 0, dependencies.wakeOnceDependencies);
280
293
  resumeBriefDelivered = resumeBriefDelivered || result.recoveryBriefDelivered;
281
294
  }, name, turn?.turnsPerHour ?? turnsPerHour, process.env, turn?.unproductivePerHour ?? unproductivePerHour, turn?.harness);
282
295
  else {
283
- const result = await wakeOnce(name, exec, unackedAfter, followDelay, log, str(p.flags, "model"), once, undefined, !resumeBriefDelivered);
296
+ const result = await (dependencies.wakeOnce ?? wakeOnce)(name, exec, unackedAfter, followDelay, log, str(p.flags, "model"), once, undefined, !resumeBriefDelivered, undefined, false, undefined, undefined, undefined, 0, dependencies.wakeOnceDependencies);
284
297
  resumeBriefDelivered = resumeBriefDelivered || result.recoveryBriefDelivered;
285
298
  }
286
299
  }
@@ -301,7 +314,7 @@ export async function watch(p, out) {
301
314
  return stoppingCode;
302
315
  if (once)
303
316
  return;
304
- await waitIntervalOrStop(watchPollMs(interval), stopped);
317
+ await (dependencies.wait ?? waitIntervalOrStop)(watchPollMs(interval), stopped);
305
318
  continue;
306
319
  }
307
320
  let u;
@@ -356,7 +369,7 @@ export async function watch(p, out) {
356
369
  }
357
370
  if (once)
358
371
  return;
359
- await waitIntervalOrStop(watchPollMs(interval), stopped);
372
+ await (dependencies.wait ?? waitIntervalOrStop)(watchPollMs(interval), stopped);
360
373
  }
361
374
  return stoppingCode;
362
375
  }
@@ -370,6 +383,87 @@ async function waitIntervalOrStop(ms, stopped) {
370
383
  if (timer)
371
384
  clearTimeout(timer);
372
385
  }
386
+ const CODEX_THREAD_ID = /[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/i;
387
+ /** Follow a Codex exec that opens a new thread, as soon as the session hook records its id. */
388
+ export function followCurrentCodexProbe(name, initialThread) {
389
+ const active = () => {
390
+ const session = readState(name).harness_session;
391
+ return session?.harness === "codex" && session.session_id && session.session_id !== initialThread
392
+ ? probeFor("codex", session.session_id, name)
393
+ : probeFor("codex", initialThread, name);
394
+ };
395
+ return {
396
+ get label() { return active().label; },
397
+ get what() { return active().what; },
398
+ phase: () => active().phase(),
399
+ startedSince: (ms) => active().startedSince(ms),
400
+ turnError: () => active().turnError(),
401
+ turnOutput: () => active().turnOutput?.() ?? "",
402
+ turnTokens: () => active().turnTokens?.() ?? null,
403
+ limitUntil: (error) => active().limitUntil(error),
404
+ isLimit: (error) => active().isLimit(error),
405
+ beginTurn: () => active().beginTurn?.(),
406
+ };
407
+ }
408
+ /** Convert a Codex resume template into its one-shot new-thread equivalent. */
409
+ export function freshCodexExecTemplate(exec) {
410
+ const thread = threadOfExec(exec);
411
+ if (!thread)
412
+ throw new CliError("context_clear_unsupported", "turn-mode clear requires a Codex exec resume command with a known thread id");
413
+ return exec.replace(/\bcodex\s+exec\s+resume\s+[0-9a-f-]{36}\b/i, "codex exec");
414
+ }
415
+ /** The watcher follows the verified fresh thread for subsequent turns. */
416
+ export function resumeFreshCodexExecTemplate(exec, thread) {
417
+ if (!CODEX_THREAD_ID.test(thread))
418
+ throw new CliError("context_clear_failed", "the fresh Codex thread id is invalid; watcher remains on its previous thread");
419
+ const replacedResume = exec.replace(/\bcodex\s+exec\s+resume\s+[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\b/i, `codex exec resume ${thread}`);
420
+ if (replacedResume !== exec)
421
+ return replacedResume;
422
+ const resumed = exec.replace(/\bcodex\s+exec\s+(?!resume\b)/i, `codex exec resume ${thread} `);
423
+ if (resumed === exec)
424
+ throw new CliError("context_clear_failed", "could not update the Codex turn command to follow the fresh thread");
425
+ return resumed;
426
+ }
427
+ async function pendingClearTurn(name, exec, clear, st, log, model, turnSink, beforeTurn, allowTurn, dependencies = {}) {
428
+ if (clear.harness !== "codex")
429
+ throw new CliError("context_clear_unsupported", `fresh-thread turn-mode clear is not implemented for ${clear.harness}`);
430
+ const alreadyFresh = !!clear.new_thread_id && st.harness_session?.session_id === clear.new_thread_id;
431
+ const command = alreadyFresh ? exec : freshCodexExecTemplate(exec);
432
+ const creds = loadAgent(name);
433
+ const client = Client.forAgent(creds, undefined, { presence: false });
434
+ const [handoffResponse, unitResponse] = await Promise.all([
435
+ client.call("GET", `/handoffs/${encodeURIComponent(clear.checkpoint_ref)}`),
436
+ client.call("GET", `/projects/${encodeURIComponent(clear.project)}/work-units/${clear.work_unit_number}`),
437
+ ]);
438
+ const handoff = handoffResponse.handoff;
439
+ const unit = unitResponse.unit;
440
+ if (handoff?.kind !== "resume" || handoff.agent_name !== creds.agent)
441
+ throw new Error("pending checkpoint is no longer an owner-authored resume note");
442
+ if (!unit || unit.owner_name !== creds.agent || !["assigned", "open", "changes_requested"].includes(unit.status) || unit.context_policy_decision?.outcome !== "pending"
443
+ || unit.context_policy_decision.checkpoint_ref !== clear.checkpoint_ref
444
+ || unit.context_policy_decision.old_thread_id !== clear.old_thread_id) {
445
+ throw new Error(`WU #${clear.work_unit_number} no longer has this owner's pending clear decision`);
446
+ }
447
+ const seq = (st.watch_seq ?? 0) + 1;
448
+ const prompt = [
449
+ `[b9s] Turn #${seq}, started by your BenignSwarm watcher for a pending context clear. This is a fresh thread; do not refer to the old conversation.`,
450
+ `First read these durable rules and the resume note, then start WU #${unit.number} before other work.`,
451
+ `Resume note (${clear.checkpoint_ref}):\n${handoff.body ?? "(empty resume note)"}`,
452
+ `Assigned work unit #${unit.number}: ${unit.title}\n\nComplete scope:\n${unit.scope}`,
453
+ `Start it now with: b9s wu start ${unit.number} --context-checkpoint-ref ${clear.checkpoint_ref}`,
454
+ `That command completes the pending clear only after this new thread is locally recorded. If any step fails, report the named failure and leave the unit unstarted.`,
455
+ ].join("\n\n");
456
+ const delivered = await deliver(name, command, prompt, `fresh-thread clear for WU #${unit.number}`, "direct", new TextEncoder().encode(prompt).byteLength, log, "context clear; ", seq, turnSink, {}, undefined, model, false, beforeTurn, { ...(dependencies.startTurn ? { startTurn: dependencies.startTurn } : {}) }, allowTurn);
457
+ if (!delivered)
458
+ return { sent: false, recoveryBriefDelivered: false };
459
+ writeState(name, {
460
+ ...readState(name),
461
+ watch_seq: seq,
462
+ watch_pending: { seq, at: Date.now(), inbox_after: st.inbox_after, channel_read: st.channel_read ?? {} },
463
+ watch_dormant_logged_at: undefined,
464
+ });
465
+ return { sent: true, recoveryBriefDelivered: false };
466
+ }
373
467
  export async function wakeOnce(name, exec, unackedAfter, followDelay, log, model, once, turnSink, includeResumeBrief = false, provider, turnStdin = false, beforeTurn, allowTurn, sessionId, turnCoalesceSeconds = 0, dependencies = {}) {
374
468
  const debug = (message) => { if (process.env.BSCHAT_WATCH_DEBUG === "1")
375
469
  log(`debug poll: ${message}`); };
@@ -402,6 +496,18 @@ export async function wakeOnce(name, exec, unackedAfter, followDelay, log, model
402
496
  log(`wake-up ${st.watch_pending.seq !== undefined ? `#${st.watch_pending.seq} ` : ""}queued ${Math.round(waited / 1000)}s ago and not acknowledged; not queueing another`);
403
497
  return { sent: false, recoveryBriefDelivered: false };
404
498
  }
499
+ const clear = st.pending_context_clear;
500
+ if (clear?.status === "pending" && turnSink) {
501
+ try {
502
+ if (!exec || turnStdin)
503
+ throw new CliError("context_clear_unsupported", "the turn watcher has no Codex command template to start a fresh thread");
504
+ return await pendingClearTurn(name, exec, clear, st, log, model, turnSink, beforeTurn, allowTurn, dependencies);
505
+ }
506
+ catch (error) {
507
+ log(`context clear for WU #${clear.work_unit_number} failed before a new turn was started: ${error.message}; the unit remains unstarted`);
508
+ return { sent: false, recoveryBriefDelivered: false };
509
+ }
510
+ }
405
511
  const u = await (dependencies.gatherUpdates ?? gatherUpdates)(name, { force: true, model, delivery: "watch", dryRun: true, watchCursor: true });
406
512
  const commitWatchCursor = () => {
407
513
  if (!u?.watchCursorAfter)
@@ -500,7 +606,7 @@ export async function wakeOnce(name, exec, unackedAfter, followDelay, log, model
500
606
  // the acknowledgement, operator note, process pointer, read commands, and delivery body.
501
607
  const line = wake;
502
608
  debug(`wake: delivering ${u?.tier ?? "process"} activity as wake-up #${seq}`);
503
- if (!(await deliver(name, exec, wake, line, u ? u.tier : "process", total, log, operatorNew ? "operator message; " : "", seq, turnSink, payload?.delivery.by_kind ?? u?.delivery.by_kind, provider, model, turnStdin, beforeTurn, { sessionId }, allowTurn))) {
609
+ if (!(await deliver(name, exec, wake, line, u ? u.tier : "process", total, log, operatorNew ? "operator message; " : "", seq, turnSink, payload?.delivery.by_kind ?? u?.delivery.by_kind, provider, model, turnStdin, beforeTurn, { ...(dependencies.startTurn ? { startTurn: dependencies.startTurn } : {}), sessionId }, allowTurn))) {
504
610
  debug("no wake: delivery failed or turn guard denied the launch");
505
611
  return { sent: false, recoveryBriefDelivered: false };
506
612
  }
@@ -3,7 +3,7 @@ import { lstatSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "nod
3
3
  import { bool, str } from "../args.js";
4
4
  import { Client } from "../client.js";
5
5
  import { agentRef, loadAgent, resolveAgentName, resolveModel } from "../config.js";
6
- import { readState } from "../state.js";
6
+ import { readState, writeState } from "../state.js";
7
7
  import { codexRollout, sessionsOf } from "../sessions.js";
8
8
  import { claudeSessionWithHookMetadata, sessionCompactions, sessionContext, sessionStart, sessionUsage } from "../usage.js";
9
9
  import { CliError } from "../errors.js";
@@ -81,6 +81,10 @@ async function contextDecisionForStart(client, base, unit, name, p, events = [])
81
81
  const creds = loadAgent(name);
82
82
  const harness = ["codex", "claude-code", "dsh", "antigravity"].includes(creds.vendor) ? creds.vendor : null;
83
83
  const state = readState(name);
84
+ const pendingClear = state.pending_context_clear;
85
+ if (pendingClear && (pendingClear.project !== creds.project || pendingClear.work_unit_number !== unit.number)) {
86
+ throw new CliError("context_policy", `a fresh-thread clear is pending for WU #${pendingClear.work_unit_number}; finish that start before starting WU #${unit.number}`);
87
+ }
84
88
  const mode = contextModeFromRuntime({
85
89
  harness,
86
90
  turnMode: !!state.turn_guard,
@@ -148,6 +152,73 @@ async function contextDecisionForStart(client, base, unit, name, p, events = [])
148
152
  const checkpointRef = str(p.flags, "context-checkpoint-ref");
149
153
  const oldThreadId = str(p.flags, "context-old-thread");
150
154
  const newThreadId = str(p.flags, "context-new-thread");
155
+ if (mode === "turn") {
156
+ if (!harness)
157
+ throw new CliError("context_policy", "a verified harness is required to schedule a fresh turn-mode thread");
158
+ if (harness !== "codex") {
159
+ const unsupportedReason = `Fresh-thread clear in turn mode is not implemented for ${harness}; no start was attempted.`;
160
+ await client.call("POST", `${base}/${unit.number}/context-policy/decision`, { ...decision, outcome: "unsupported", reason: unsupportedReason });
161
+ throw new CliError("unsupported", `WU #${unit.number}: ${unsupportedReason} Ask the assigner or operator to choose a supported policy.`);
162
+ }
163
+ if (!creds.project)
164
+ throw new CliError("context_policy", "a project-scoped agent is required for a turn-mode clear");
165
+ const pending = pendingClear;
166
+ if (!pending) {
167
+ const currentThread = state.harness_session?.session_id;
168
+ if (!currentThread || state.harness_session?.harness !== harness || state.harness_session?.last_seen_at === undefined || Date.now() - state.harness_session.last_seen_at >= 60_000) {
169
+ throw new CliError("context_action_required", `the current ${harness ?? "harness"} thread is not locally verified; no clear was scheduled`);
170
+ }
171
+ let ref = checkpointRef;
172
+ if (ref) {
173
+ const checkpoint = await client.call("GET", `/handoffs/${encodeURIComponent(ref)}`);
174
+ if (checkpoint.handoff?.agent_name !== creds.agent || checkpoint.handoff?.kind !== "resume") {
175
+ throw new CliError("context_action_required", "context checkpoint must be an existing resume note saved by this agent");
176
+ }
177
+ }
178
+ else {
179
+ const title = `WU #${unit.number}: ${String(unit.title ?? "work unit")}`.slice(0, 200);
180
+ const body = [
181
+ `Work unit #${unit.number}: ${unit.title ?? "work unit"}`,
182
+ `Scope: ${String(unit.scope ?? "(scope unavailable)").slice(0, 50_000)}`,
183
+ `Current Codex thread: ${currentThread}`,
184
+ `Branch: ${unit.branch ?? "not set"}; head: ${unit.head ?? "not set"}.`,
185
+ `Next: read the current process and this note, then run b9s wu start ${unit.number} --context-checkpoint-ref <this-note-id> in the fresh thread. The watcher will include the unit brief and start that turn on a new Codex thread.`,
186
+ ].join("\n\n");
187
+ const saved = await client.call("POST", "/agents/me/checkpoint", { title, body, evidence: [] });
188
+ ref = saved.handoff?.id;
189
+ if (typeof ref !== "string" || !ref)
190
+ throw new CliError("context_action_required", "the resume checkpoint was not saved; no clear was scheduled");
191
+ }
192
+ const pendingDecision = { ...decision, outcome: "pending", reason: "checkpoint saved; the watcher will start the next turn on a fresh thread", checkpoint_ref: ref, old_thread_id: currentThread };
193
+ await client.call("POST", `${base}/${unit.number}/context-policy/decision`, pendingDecision);
194
+ writeState(name, {
195
+ ...state,
196
+ pending_context_clear: { project: creds.project, work_unit_number: unit.number, checkpoint_ref: ref, old_thread_id: currentThread, harness, requested_at: new Date().toISOString(), status: "pending" },
197
+ });
198
+ return { pending_clear: true, checkpoint_ref: ref };
199
+ }
200
+ if (!pending.checkpoint_ref || !pending.old_thread_id || pending.harness !== harness) {
201
+ throw new CliError("context_policy", "the pending clear record is incomplete or belongs to a different harness; no start was attempted");
202
+ }
203
+ const currentThread = state.harness_session?.session_id;
204
+ if (pending.status === "completed")
205
+ throw new CliError("context_policy", `WU #${unit.number} clear has completed; the watcher is switching to thread ${pending.new_thread_id ?? "(unknown)"}`);
206
+ const recentlyObserved = state.harness_session?.last_seen_at !== undefined && Date.now() - state.harness_session.last_seen_at < 60_000;
207
+ if (!currentThread || currentThread === pending.old_thread_id || state.harness_session?.harness !== harness || !recentlyObserved) {
208
+ throw new CliError("context_action_required", `WU #${unit.number} is waiting for its watcher to start a new ${harness ?? "harness"} thread; no start was attempted`);
209
+ }
210
+ if (pending.new_thread_id && currentThread !== pending.new_thread_id) {
211
+ throw new CliError("context_action_required", `WU #${unit.number} is waiting for the watcher to bind fresh thread ${pending.new_thread_id}; current thread ${currentThread} does not match`);
212
+ }
213
+ const checkpoint = await client.call("GET", `/handoffs/${encodeURIComponent(pending.checkpoint_ref)}`);
214
+ if (checkpoint.handoff?.agent_name !== creds.agent || checkpoint.handoff?.kind !== "resume") {
215
+ throw new CliError("context_action_required", "pending context checkpoint is not an existing resume note saved by this agent");
216
+ }
217
+ decision.checkpoint_ref = pending.checkpoint_ref;
218
+ decision.old_thread_id = pending.old_thread_id;
219
+ decision.new_thread_id = currentThread;
220
+ return decision;
221
+ }
151
222
  if (!bool(p.flags, "context-confirmed") || !checkpointRef || !oldThreadId || !newThreadId) {
152
223
  throw new CliError("context_action_required", `WU #${unit.number} requires a checkpointed fresh thread. Save it with b9s checkpoint, open a new thread for this agent, then rerun b9s wu start ${unit.number} --context-confirmed --context-checkpoint-ref <handoff-id> --context-old-thread <old-thread-id> --context-new-thread <new-thread-id>.`);
153
224
  }
@@ -641,6 +712,10 @@ export async function wu(p, out) {
641
712
  const def = await processDef();
642
713
  const target = unit.target ?? def.merge.target_branch;
643
714
  const contextDecision = await contextDecisionForStart(client, base, unit, name, p, Array.isArray(unitRecord.events) ? unitRecord.events : []);
715
+ if (contextDecision && "pending_clear" in contextDecision) {
716
+ out.print(`WU #${n}: checkpoint recorded; the watcher will start the next turn on a fresh thread, then start the unit.`, { unit, pending_context_clear: true, checkpoint_ref: contextDecision.checkpoint_ref });
717
+ return;
718
+ }
644
719
  const prepared = prepareWorktree(n, unit, def, p, await checkoutExclude());
645
720
  const { path, branch, mode } = prepared;
646
721
  const where = symbolicBranchAndHead(path);
@@ -657,6 +732,11 @@ export async function wu(p, out) {
657
732
  throw error;
658
733
  }
659
734
  out.print(`${fmt(r.unit)}\nYour worktree: ${path}${mode === "fresh" ? ` (new branch ${branch} from origin/${target}${unit.replay ? " as of the original" : ""})` : mode === "branch" ? ` (branch ${branch})` : " (this checkout)"}\n cd ${path}\nWork there. Submit when ready: b9s wu submit ${n} --evidence <id>`, { ...r, worktree: path, branch, mode });
735
+ if (readState(name).pending_context_clear?.work_unit_number === n) {
736
+ const current = readState(name);
737
+ const clear = current.pending_context_clear;
738
+ writeState(name, { ...current, pending_context_clear: { ...clear, status: "completed", new_thread_id: clear.new_thread_id ?? current.harness_session?.session_id ?? undefined } });
739
+ }
660
740
  return;
661
741
  }
662
742
  case "decline": {
package/dist/help.js CHANGED
@@ -87,11 +87,12 @@ Agent commands
87
87
  checkout is removed and made again; wu open does the same for your own units;
88
88
  --branch continues existing work (never a SHA); always fetches and branches from origin/<target>; --here uses this checkout
89
89
  context policy is resolved before worktree creation: keep is recorded automatically;
90
- compact requires a completed interactive /compact confirmation; clear requires a saved checkpoint,
91
- a different thread, and a matching locally recorded current-thread id; /me.machine_sessions identifies placement:
90
+ compact requires a completed interactive /compact confirmation; Codex turn-mode clear saves a resume checkpoint
91
+ automatically (or accepts --context-checkpoint-ref), then the watcher starts a fresh thread with the note and unit scope;
92
+ interactive clear requires a saved checkpoint, a different thread, and a matching locally recorded current-thread id;
93
+ /me.machine_sessions identifies placement:
92
94
  managed sessions update their remembered thread atomically on start; an empty list confirms unmanaged; unknown is refused;
93
- Codex clear also remains unsupported until an affirmative foreground-mode marker is verified;
94
- clear also needs --context-checkpoint-ref, --context-old-thread, and --context-new-thread; unsupported work never starts
95
+ unsupported or failed clear handoffs never start the unit;
95
96
  lifecycle events include context-fill metadata and compaction deltas: Claude Code reads assistant usage
96
97
  and compact markers, Codex reads token_count and compaction events; Antigravity needs a confirmed window;
97
98
  unsupported or unavailable measurements include a reason; compaction intervals include the start and exclude the end
@@ -352,7 +353,7 @@ the returned object and warning, then exits 3. Inspect the object and do not ret
352
353
  b9s-admin milestone <project> add|edit <key> --title .. [--exit ..] [--source ..] [--depends-on a,b] [--informs c,d] [--default-tags a,b] one slice in, the rest untouched
353
354
  b9s-admin milestone <project> show|review|reopen <key> | decide <key> "ruling" --unit n | close <key> --note .. [--abandon|--defer] | verdict <key> --met|--gaps .. | gap-units <key> --units n,m
354
355
  b9s-admin flow [--project <p>] [--from <UTC date/time>] [--to <UTC date/time>] [--json]
355
- read-only state counts, waits, capacity, critical paths, attention, trends, freshness and coverage
356
+ read-only state counts, waits, qualified worker/reviewer capacity, critical paths, attention, trends, freshness and coverage
356
357
  b9s-admin role edit <name> [--project p] --reviews a,b --works c --trials d which tags a role reviews, works and trials ("*" all, "" none)
357
358
  --assign-outside-qualifications yes|no allow assigners in this role to make reasoned ownership exceptions; dispatch stays qualified
358
359
  b9s-admin needs decisions waiting on you (asks, unit questions, broken wake paths, alert failures)
@@ -395,7 +396,8 @@ Machines (provisioned over your own ssh; a daemon on each runs the agent session
395
396
  [--harness codex|claude-code] [--provider anthropic|deepseek] [--carry note|thread]
396
397
  [--model m] [--effort e] [--wait min] [--force --confirm-force <project>/<agent>]
397
398
  creates a move or continues the requested operation from the console; stored options are loaded and explicit options must match
398
- checks source worktrees, transfers thread/note plus local agent state over SSH,
399
+ checks owned and agent-attributed review worktrees on the source, reports unrelated, remote, and unrecorded work as skipped,
400
+ transfers thread/note plus local agent state over SSH,
399
401
  refuses newer destination state and avoids duplicate Codex hooks under managed policy,
400
402
  then commits the session only after handoff succeeds; work left on the source requires both flags
401
403
  b9s-admin machine label <name> <label...> [--remove a,b] what cannot be measured (lab-lan, builds); pools' --needs match it
@@ -0,0 +1,55 @@
1
+ import { BatchGetRepositoryScanningConfigurationCommand, CreateRepositoryCommand, DescribeRepositoriesCommand, GetLifecyclePolicyCommand, PutLifecyclePolicyCommand, } from "@aws-sdk/client-ecr";
2
+ // Expire only old untagged layers; tagged images remain protected by immutable tags.
3
+ export const HOSTED_IMAGE_LIFECYCLE = JSON.stringify({ rules: [{ rulePriority: 1, description: "Expire untagged images after 14 days", selection: { tagStatus: "untagged", countType: "sinceImagePushed", countUnit: "days", countNumber: 14 }, action: { type: "expire" } }] });
4
+ export class EcrHostedRegistry {
5
+ ecr;
6
+ registryId;
7
+ pushImage;
8
+ constructor(ecr, registryId, pushImage) {
9
+ this.ecr = ecr;
10
+ this.registryId = registryId;
11
+ this.pushImage = pushImage;
12
+ }
13
+ async describe(name) {
14
+ try {
15
+ const response = await this.ecr.send(new DescribeRepositoriesCommand({ registryId: this.registryId, repositoryNames: [name] }));
16
+ if (response.repositories?.length !== 1)
17
+ throw new Error("unexpected repository count");
18
+ const row = response.repositories[0];
19
+ if (row.registryId !== this.registryId)
20
+ throw new Error("registry mismatch");
21
+ return { repositoryName: row.repositoryName, imageTagMutability: row.imageTagMutability, encryptionConfiguration: row.encryptionConfiguration };
22
+ }
23
+ catch (error) {
24
+ if (error.name === "RepositoryNotFoundException")
25
+ return null;
26
+ throw error;
27
+ }
28
+ }
29
+ async create(name, kmsKey) {
30
+ await this.ecr.send(new CreateRepositoryCommand({ registryId: this.registryId, repositoryName: name, imageTagMutability: "IMMUTABLE", imageScanningConfiguration: { scanOnPush: true }, encryptionConfiguration: { encryptionType: "KMS", kmsKey } }));
31
+ }
32
+ async putLifecycle(name) {
33
+ await this.ecr.send(new PutLifecyclePolicyCommand({ registryId: this.registryId, repositoryName: name, lifecyclePolicyText: HOSTED_IMAGE_LIFECYCLE }));
34
+ }
35
+ async hasLifecycle(name) {
36
+ try {
37
+ const response = await this.ecr.send(new GetLifecyclePolicyCommand({ registryId: this.registryId, repositoryName: name }));
38
+ if (response.registryId !== this.registryId || response.repositoryName !== name || !response.lifecyclePolicyText)
39
+ return false;
40
+ const policy = JSON.parse(response.lifecyclePolicyText);
41
+ return !!policy && typeof policy === "object" && Array.isArray(policy.rules) && policy.rules.length > 0;
42
+ }
43
+ catch (error) {
44
+ if (error.name === "LifecyclePolicyNotFoundException")
45
+ return false;
46
+ throw error;
47
+ }
48
+ }
49
+ async scanOnPush(name) {
50
+ const response = await this.ecr.send(new BatchGetRepositoryScanningConfigurationCommand({ repositoryNames: [name] }));
51
+ const rows = response.scanningConfigurations ?? [];
52
+ return !(response.failures?.length) && rows.length === 1 && rows[0].repositoryName === name && rows[0].scanOnPush === true;
53
+ }
54
+ async push(source, target) { return this.pushImage(source, target); }
55
+ }
@@ -0,0 +1,40 @@
1
+ import { DescribeImagesCommand, GetAuthorizationTokenCommand } from "@aws-sdk/client-ecr";
2
+ import { mkdirSync, writeFileSync } from "node:fs";
3
+ import { join } from "node:path";
4
+ /** Push using a process-local credential helper; no password is written to an auth file. */
5
+ export async function pushHostedImage(input) {
6
+ if (!new RegExp(`^${input.registryId}\\.dkr\\.ecr\\.[a-z0-9-]+\\.amazonaws\\.com$`).test(input.endpoint) || !/^\d{12}$/.test(input.registryId))
7
+ throw new Error("registry endpoint mismatch");
8
+ if (!/^benignswarm\/[a-z0-9][a-z0-9._-]*\/[a-z0-9][a-z0-9._-]*$/.test(input.repository) || !/^[A-Za-z0-9_][A-Za-z0-9_.-]{0,127}$/.test(input.tag))
9
+ throw new Error("invalid registry target");
10
+ const response = await input.ecr.send(new GetAuthorizationTokenCommand({ registryIds: [input.registryId] }));
11
+ const auth = response.authorizationData;
12
+ if (!auth || auth.length !== 1 || auth[0].proxyEndpoint !== `https://${input.endpoint}` || !auth[0].authorizationToken)
13
+ throw new Error("registry authorization response mismatch");
14
+ const raw = Buffer.from(auth[0].authorizationToken, "base64").toString("utf8");
15
+ if (!raw.startsWith("AWS:") || raw.length <= 4 || /[\r\n\0]/.test(raw))
16
+ throw new Error("registry authorization response invalid");
17
+ const password = raw.slice(4);
18
+ const authDir = join(input.directory, "registry-auth");
19
+ mkdirSync(authDir, { mode: 0o700 });
20
+ const config = join(authDir, "config.json");
21
+ writeFileSync(config, JSON.stringify({ auths: {}, credHelpers: { [input.endpoint]: "b9secr" } }), { mode: 0o600 });
22
+ // The helper contains no credential. Its only secret arrives through the short-lived child's
23
+ // environment and is written to the runtime's credential-helper pipe, never to disk or logs.
24
+ const helper = join(authDir, "docker-credential-b9secr");
25
+ const helperSource = `#!${process.execPath}\nconst fs=require('node:fs');if(process.argv[2]!=='get'||fs.readFileSync(0,'utf8').trim()!==process.env.B9S_ECR_ENDPOINT||!process.env.B9S_ECR_PASSWORD)process.exit(1);process.stdout.write(JSON.stringify({Username:'AWS',Secret:process.env.B9S_ECR_PASSWORD}));\n`;
26
+ writeFileSync(helper, helperSource, { mode: 0o700 });
27
+ const target = `${input.endpoint}/${input.repository}:${input.tag}`;
28
+ const cleanEnv = { ...input.env, DOCKER_CONFIG: authDir, REGISTRY_AUTH_FILE: config, PATH: `${authDir}:${input.env.PATH ?? ""}` };
29
+ const tagged = input.runner(input.runtime, ["tag", input.source, target], { env: cleanEnv, timeout: 30_000 });
30
+ if (tagged.status !== 0)
31
+ throw new Error("could not tag hosted image");
32
+ const pushed = input.runner(input.runtime, ["push", target], { env: { ...cleanEnv, B9S_ECR_ENDPOINT: input.endpoint, B9S_ECR_PASSWORD: password }, timeout: 900_000 });
33
+ if (pushed.status !== 0)
34
+ throw new Error("could not push hosted image");
35
+ const images = await input.ecr.send(new DescribeImagesCommand({ registryId: input.registryId, repositoryName: input.repository, imageIds: [{ imageTag: input.tag }] }));
36
+ const digest = images.imageDetails?.length === 1 ? images.imageDetails[0].imageDigest : undefined;
37
+ if (typeof digest !== "string" || !/^sha256:[a-f0-9]{64}$/.test(digest))
38
+ throw new Error("registry did not return an immutable pushed digest");
39
+ return digest;
40
+ }
@@ -0,0 +1,26 @@
1
+ import { AssumeRoleCommand, STSClient } from "@aws-sdk/client-sts";
2
+ import { fromInstanceMetadata } from "@aws-sdk/credential-provider-imds";
3
+ import { validateHostedRegistry } from "./hosted-registry.js";
4
+ async function assumeInstanceRole(role, region, externalId) {
5
+ const sts = new STSClient({ region, credentials: fromInstanceMetadata({ timeout: 1000, maxRetries: 2 }) });
6
+ try {
7
+ return (await sts.send(new AssumeRoleCommand({ RoleArn: role, RoleSessionName: "benignswarm-image-builder", DurationSeconds: 900, ExternalId: externalId }))).Credentials;
8
+ }
9
+ finally {
10
+ sts.destroy();
11
+ }
12
+ }
13
+ export async function assumeHostedBuilder(accountId, projectId, registry, assume = assumeInstanceRole) {
14
+ const { region } = validateHostedRegistry(accountId, projectId, registry);
15
+ let result;
16
+ try {
17
+ result = await assume(registry.builder_role_arn, region, `benignswarm/${accountId.toLowerCase()}`);
18
+ }
19
+ catch {
20
+ throw new Error("hosted builder role not assumable; verify machine trust and sts:AssumeRole permission");
21
+ }
22
+ if (!result?.AccessKeyId || !result.SecretAccessKey || !result.SessionToken || !result.Expiration || !Number.isFinite(result.Expiration.getTime()) || result.Expiration.getTime() <= Date.now()) {
23
+ throw new Error("hosted builder returned invalid temporary credentials");
24
+ }
25
+ return { region, credentials: { accessKeyId: result.AccessKeyId, secretAccessKey: result.SecretAccessKey, sessionToken: result.SessionToken, expiration: result.Expiration } };
26
+ }
@@ -0,0 +1,73 @@
1
+ export function validateHostedRegistry(accountId, projectId, registry) {
2
+ const segment = /^[a-z0-9][a-z0-9-]{0,127}$/i;
3
+ if (!segment.test(accountId) || !segment.test(projectId) || registry.repository_prefix !== `benignswarm/${accountId.toLowerCase()}`)
4
+ throw new Error("hosted registry account prefix or project id is invalid");
5
+ const endpoint = /^(\d{12})\.dkr\.ecr\.([a-z0-9-]+)\.amazonaws\.com$/.exec(registry.registry_endpoint);
6
+ const role = /^arn:aws:iam::(\d{12}):role\/[A-Za-z0-9+=,.@_\/-]+$/.exec(registry.builder_role_arn);
7
+ const key = /^arn:aws:kms:([a-z0-9-]+):(\d{12}):key\/[A-Za-z0-9-]{1,128}$/.exec(registry.kms_key_arn);
8
+ if (!endpoint || !role || !key || role[1] !== endpoint[1] || key[1] !== endpoint[2] || key[2] !== endpoint[1])
9
+ throw new Error("hosted registry endpoint, builder role or KMS key is invalid");
10
+ return { repository: `${registry.repository_prefix}/${projectId.toLowerCase()}`, region: endpoint[2] };
11
+ }
12
+ export async function publishHostedImage(input, port) {
13
+ const { accountId, projectId, registry } = input;
14
+ const { repository: name } = validateHostedRegistry(accountId, projectId, registry);
15
+ if (!/^[A-Za-z0-9_][A-Za-z0-9_.-]{0,127}$/.test(input.tag))
16
+ throw new Error("hosted image tag is invalid");
17
+ let row;
18
+ try {
19
+ row = await port.describe(name);
20
+ }
21
+ catch {
22
+ throw new Error("hosted registry repository inspection failed; verify ecr:DescribeRepositories permission");
23
+ }
24
+ if (!row) {
25
+ try {
26
+ await port.create(name, registry.kms_key_arn);
27
+ await port.putLifecycle(name);
28
+ }
29
+ catch {
30
+ throw new Error("hosted registry repository creation failed");
31
+ }
32
+ try {
33
+ row = await port.describe(name);
34
+ }
35
+ catch {
36
+ throw new Error("hosted registry repository inspection failed; verify ecr:DescribeRepositories permission");
37
+ }
38
+ }
39
+ if (!row || row.repositoryName !== name)
40
+ throw new Error("hosted registry repository name mismatch");
41
+ if (row.imageTagMutability !== "IMMUTABLE")
42
+ throw new Error("hosted registry tags are not immutable");
43
+ if (row.encryptionConfiguration?.encryptionType !== "KMS" || row.encryptionConfiguration.kmsKey !== registry.kms_key_arn)
44
+ throw new Error("hosted registry KMS encryption mismatch");
45
+ let scanning;
46
+ try {
47
+ scanning = await port.scanOnPush(name);
48
+ }
49
+ catch {
50
+ throw new Error("hosted registry scanning inspection failed; verify ecr:BatchGetRepositoryScanningConfiguration permission");
51
+ }
52
+ if (!scanning)
53
+ throw new Error("hosted registry scan on push is disabled");
54
+ let lifecycle;
55
+ try {
56
+ lifecycle = await port.hasLifecycle(name);
57
+ }
58
+ catch {
59
+ throw new Error("hosted registry lifecycle inspection failed; verify ecr:GetLifecyclePolicy permission");
60
+ }
61
+ if (!lifecycle)
62
+ throw new Error("hosted registry lifecycle policy is missing");
63
+ let digest;
64
+ try {
65
+ digest = await port.push(input.sourceImage, `${registry.registry_endpoint}/${name}:${input.tag}`);
66
+ }
67
+ catch {
68
+ throw new Error("hosted registry push or digest lookup failed; verify ecr:GetAuthorizationToken and ecr:DescribeImages permissions");
69
+ }
70
+ if (!/^sha256:[a-f0-9]{64}$/.test(digest))
71
+ throw new Error("hosted registry returned an invalid pushed digest");
72
+ return { digest, imageReference: `${registry.registry_endpoint}/${name}@${digest}` };
73
+ }
package/dist/version.js CHANGED
@@ -1 +1 @@
1
- export const CLI_VERSION = "0.12.104";
1
+ export const CLI_VERSION = "0.12.105";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "benignswarm",
3
- "version": "0.12.104",
3
+ "version": "0.12.105",
4
4
  "description": "b9s: chat, status board and evidence store for coding agents (benignswarm.org)",
5
5
  "license": "UNLICENSED",
6
6
  "repository": {
@@ -40,5 +40,10 @@
40
40
  "@types/node": "^24.0.0",
41
41
  "typescript": "^5.9.3",
42
42
  "vitest": "^4.1.0"
43
+ },
44
+ "dependencies": {
45
+ "@aws-sdk/client-ecr": "^3.1170.0",
46
+ "@aws-sdk/client-sts": "^3.1170.0",
47
+ "@aws-sdk/credential-provider-imds": "^3.370.0"
43
48
  }
44
49
  }