benignswarm 0.12.137 → 0.12.139

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
@@ -22,7 +22,7 @@ export const STRING_FLAGS = [
22
22
  "require-evidence", "default-approver", "merged-by", "integrator-role", "require-rebased", "require-merge-commit",
23
23
  "require-pushed", "require-gate-receipt", "quiet", "summary", "meaning", "expert-role", "reviews", "works", "trials", "email",
24
24
  "repeat", "summary-minutes", "churn", "unmet", "require-cited-changes", "checks-every", "propose", "waits-on",
25
- "flow-summary", "flow-min-age", "flow-min-impact", "checkout", "api", "nonce",
25
+ "flow-summary", "flow-min-age", "flow-min-impact", "checkout", "unit-worktree", "sibling-checkout", "api", "nonce",
26
26
  "sandbox", "thread", "turn-timeout", "turns-per-hour", "unproductive-per-hour", "turn-coalesce-seconds", "session", "operation",
27
27
  "plain", "if-yes", "if-no", "ssh", "variant", "count", "min", "max", "needs", "min-ram", "exclude", "carry", "from",
28
28
  "to-ssh", "ssh-from", "wait", "writable", "writable-root", "dsh", "agy", "for", "until", "reason", "at", "requires",
@@ -34,7 +34,7 @@ export const STRING_FLAGS = [
34
34
  "drain-timeout", "on-running-turn", "extend", "ssh-config", "poll-ms",
35
35
  "stage", "machines", "resolved-retention-days", "wont-fix-retention-days", "alert-cooldown-minutes", "alerts", "confirm-force",
36
36
  "machine-session-id", "harness-binary", "pool-sessions", "registry", "detail", "worktree", "turn-claude-runtime", "turn-antigravity-runtime",
37
- "purpose", "storage-mode", "hosts", "arn", "version-id",
37
+ "purpose", "storage-mode", "hosts", "arn", "version-id", "kms-key",
38
38
  "mode", "weights", "quality-target", "half-life", "min-samples", "build-explore", "review-explore", "pause-build", "pause-review", "class",
39
39
  "expires-at", "conflicts-with", "source-channel-id", "source-message-id", "plain-summary",
40
40
  "metadata-file", "confirm-agent", "confirm-parked", "step",
@@ -44,7 +44,7 @@ export const BOOL_FLAGS = [
44
44
  "read-account-status", "replace-key", "mentions-me", "no-skill", "replace", "template", "scope-only", "unread",
45
45
  "pending", "force", "no-hooks", "yes", "open", "bind-here", "peek", "once", "launchd", "full", "no-bind",
46
46
  "all", "here", "keep-worktree", "prune", "abandon", "defer", "hold", "clear", "met", "shared", "archive",
47
- "approve", "turn", "service", "print-hooks", "create", "rotate", "codex-userns", "bwrap-userns", "agy-userns", "print-apparmor",
47
+ "approve", "turn", "service", "print-hooks", "create", "rotate", "drain", "codex-userns", "bwrap-userns", "agy-userns", "print-apparmor",
48
48
  "cancel", "rerun", "confirmed", "refuted", "no-source", "confirm-bypass-signal", "assessment-only",
49
49
  "no-wait-verify", "preview", "remove-empty", "dry-run", "quota-substitution",
50
50
  "in-container", "retrieve-ec2", "stdin", "context-confirmed", "confirm-compatible", "no-commits-beyond-target",
@@ -127,7 +127,7 @@ export async function admin(p, out) {
127
127
  case "notifier":
128
128
  return notifierAdmin(p, out);
129
129
  case "account":
130
- return accountAdmin(p, out);
130
+ return accountAdmin(p, out, action, rest);
131
131
  case "account-stores":
132
132
  return accountStoresAdmin(action, rest, p, out);
133
133
  case "turn-judgment":
@@ -370,7 +370,7 @@ export async function machineAdmin(action, rest, p, out) {
370
370
  if (action === "label" || action === "slots") {
371
371
  const name = rest[0];
372
372
  if (!name)
373
- throw new CliError("usage", "machine label <name> <label...> [--remove a,b] | machine slots <name> <n | auto>");
373
+ throw new CliError("usage", "machine label <name> <label...> [--remove a,b] [--preview | --impact-revision <revision>] | machine slots <name> <n | auto> [--preview | --impact-revision <revision>]");
374
374
  const cur = (await c.call("GET", `/machines/${name}`)).machine;
375
375
  let body;
376
376
  if (action === "label") {
@@ -382,9 +382,26 @@ export async function machineAdmin(action, rest, p, out) {
382
382
  throw new CliError("usage", "machine slots <name> <n | auto> (auto: one per 4 GB of RAM)");
383
383
  body = { slots: rest[1] === "auto" ? null : Number(rest[1]) };
384
384
  }
385
+ const suppliedRevision = str(p.flags, "impact-revision");
386
+ if (bool(p.flags, "preview") && suppliedRevision !== undefined)
387
+ throw new CliError("usage", "use either --preview or --impact-revision, not both");
388
+ const { impact } = await c.call("POST", `/machines/${encodeURIComponent(name)}/settings-impact`, body);
389
+ if (!impact || typeof impact.source_revision !== "string")
390
+ throw new CliError("invalid_response", "machine settings preview did not include a source revision");
391
+ const impactText = [
392
+ `${name}: ${action} placement preview (${impact.source_revision})`,
393
+ ` labels: ${impact.after.labels.join(", ") || "(none)"}; slots: ${impact.after.slots ?? "automatic"}`,
394
+ ...impact.placements.map((move) => ` ${move.project}/${move.pool}/${move.slot}: ${move.from ?? "unplaced"} → ${move.to ?? `unplaced (${move.reason ?? "no eligible machine"})`}`),
395
+ `Review this impact, then repeat the command with --impact-revision ${impact.source_revision}.`,
396
+ ].join("\n");
397
+ if (bool(p.flags, "preview") || suppliedRevision === undefined)
398
+ return out.print(impactText, { impact });
399
+ if (suppliedRevision !== impact.source_revision)
400
+ throw new CliError("stale_preview", `machine settings impact changed since revision ${suppliedRevision}; nothing was changed; review the new preview with --preview`);
401
+ body.source_revision = impact.source_revision;
385
402
  const r = await c.call("PATCH", `/machines/${name}`, body);
386
403
  const kept = keptInPlace(((await c.call("GET", "/pools")).pools ?? []));
387
- 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 });
404
+ 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, impact, kept_in_place: kept });
388
405
  }
389
406
  if (action === "readiness") {
390
407
  const name = rest[0];
@@ -69,9 +69,10 @@ function writeMachineState(s) {
69
69
  * again once with them. 2: the agent's own worktree git folder is writable under workspace-write.
70
70
  * 3: turns get TMPDIR beside the checkout instead of the system's /tmp.
71
71
  * 11: Antigravity's linked-worktree Git permissions are narrowed to required data paths.
72
+ * 12: Claude Code workspace-write roots name only the checkout, active unit worktree, narrowed Git metadata, config and caches.
72
73
  */
73
- const START_REV = 11;
74
- export const sessionFingerprint = (s, writable = [], imageDigest = null) => JSON.stringify([s.id, s.harness, ...(s.provider && s.provider !== "anthropic" ? [s.provider] : []), s.dir, s.sandbox, s.model, s.effort, s.turn_timeout, s.turns_per_hour ?? DEFAULT_TURNS_PER_HOUR, s.unproductive_per_hour ?? DEFAULT_UNPRODUCTIVE_PER_HOUR, s.turn_coalesce_seconds ?? 180, ...(s.max_budget_usd != null ? [`budget:${s.max_budget_usd}`] : []), ...(s.harness_binary ? [`binary:${s.harness_binary}`] : []), s.thread, ...(writable.length ? [writable] : []), ...(imageDigest ? [imageDigest] : []), ...(START_REV > 1 ? [`rev${START_REV}`] : [])]);
74
+ const START_REV = 12;
75
+ export const sessionFingerprint = (s, writable = [], imageDigest = null) => JSON.stringify([s.id, s.harness, ...(s.provider && s.provider !== "anthropic" ? [s.provider] : []), s.dir, s.sandbox, s.model, s.effort, s.turn_timeout, s.turns_per_hour ?? DEFAULT_TURNS_PER_HOUR, s.unproductive_per_hour ?? DEFAULT_UNPRODUCTIVE_PER_HOUR, s.turn_coalesce_seconds ?? 180, ...(s.max_budget_usd != null ? [`budget:${s.max_budget_usd}`] : []), ...(s.harness_binary ? [`binary:${s.harness_binary}`] : []), s.thread, ...(writable.length ? [writable] : []), ...(imageDigest ? [`image:${imageDigest}`] : []), ...(s.secret_context_hash ? [`secrets:${s.secret_context_hash}`] : []), ...(START_REV > 1 ? [`rev${START_REV}`] : [])]);
75
76
  /** A server thread update must restart the watcher even if a stored fingerprint is unexpectedly stale. */
76
77
  export function sessionConfigChanged(s, local, fingerprint) {
77
78
  const serverThreadChanged = s.thread !== null && s.thread !== (local?.thread ?? null);
@@ -967,7 +968,12 @@ export async function launchDesiredSession(opts) {
967
968
  return runner(opts.bin, startArgs(opts.s, opts.thread, opts.sessionWritable, opts.startupJitterSeconds), {
968
969
  cwd: opts.s.dir,
969
970
  timeout: startWaitMs(opts.s),
970
- env: { ...process.env, ...opts.secretEnv, ...(opts.progressFile ? { BSCHAT_MACHINE_START_PROGRESS_FILE: opts.progressFile } : {}) },
971
+ env: {
972
+ ...process.env,
973
+ ...opts.secretEnv,
974
+ ...(opts.secretDeclaredHosts?.length ? { B9S_SECRET_DECLARED_HOSTS: JSON.stringify(opts.secretDeclaredHosts) } : {}),
975
+ ...(opts.progressFile ? { BSCHAT_MACHINE_START_PROGRESS_FILE: opts.progressFile } : {}),
976
+ },
971
977
  });
972
978
  }
973
979
  const { runtime, imageDigest } = resolveContainerLaunchPrereqs({
@@ -1033,14 +1039,16 @@ export async function launchDesiredSession(opts) {
1033
1039
  B9S_URL: opts.m.url,
1034
1040
  B9S_AGENT: opts.s.agent,
1035
1041
  B9S_HOME: "/home/agent/.b9s",
1042
+ ...(opts.secretDeclaredHosts?.length ? { B9S_SECRET_DECLARED_HOSTS: JSON.stringify(opts.secretDeclaredHosts) } : {}),
1036
1043
  ...(opts.containerProgressFile ? { BSCHAT_MACHINE_START_PROGRESS_FILE: opts.containerProgressFile } : {}),
1037
1044
  },
1045
+ secretEnvKeys: opts.projectSecretEnvKeys,
1038
1046
  command: ["b9s", ...startArgs({ ...opts.s, harness_binary: null }, opts.thread, opts.s.sandbox === "workspace-write" ? containerWritablePaths : [], opts.startupJitterSeconds), "--in-container"],
1039
1047
  });
1040
1048
  const launchRes = runner(runtime, runArgs, {
1041
1049
  cwd: opts.s.dir,
1042
1050
  timeout: 60_000,
1043
- env: isolatedSubprocessEnv(process.env),
1051
+ env: isolatedSubprocessEnv(process.env, opts.secretEnv, opts.projectSecretEnvKeys),
1044
1052
  });
1045
1053
  if (launchRes.status !== 0)
1046
1054
  return launchRes;
@@ -1480,68 +1488,112 @@ export async function reconcile(m, log, reportIntervalSeconds = 30, deps) {
1480
1488
  }
1481
1489
  delete state.unsettled_turns[s.dir];
1482
1490
  }
1483
- const secretDelivery = resolveSessionSecretDelivery({
1484
- session: s,
1485
- secrets: me.harness_secrets ?? [],
1486
- targetDir: join(configRoot(), "providers", "ephemeral"),
1487
- runner: deps?.runner,
1488
- });
1489
- const startId = createHash("sha256").update(s.id).digest("hex").slice(0, 24);
1490
- const progressDir = containerMode ? join(agentHomeDirOf(s), ".b9s", "logs") : join(configRoot(), "state", "machine-start");
1491
- mkdirSync(progressDir, { recursive: true, mode: 0o700 });
1492
- const progressFile = join(progressDir, `start-${startId}.json`);
1493
- // What the daemon trusts (the child's identity, the outcome) stays in host-private state:
1494
- // a containerised session can write its own home, and only the progress note lives there.
1495
- // The name is per attempt, so nothing an earlier child wrote is read as this one's.
1496
- const privateDir = join(configRoot(), "state", "machine-start");
1497
- mkdirSync(privateDir, { recursive: true, mode: 0o700 });
1498
- const resultFile = join(privateDir, `result-${startId}-${randomBytes(6).toString("hex")}.json`);
1499
- writeJsonAtomically(progressFile, { state: "starting", at: new Date().toISOString() });
1500
- const launchOptions = {
1501
- m, accountId, s, project: projectEntry, thread, sessionWritable, machineWritable: writable,
1502
- bin, secretEnv: secretDelivery.env, containerMode, pullImage: isPoolImageOptIn, workdir,
1503
- sandboxReport: hostContainerProbe ?? undefined, onEc2, containerImdsBlocked: containerImdsOk,
1504
- startupJitterSeconds: deps?.startupJitterSeconds,
1505
- progressFile: containerMode ? undefined : progressFile,
1506
- containerProgressFile: containerMode ? `/home/agent/.b9s/logs/start-${startId}.json` : undefined,
1507
- };
1508
- rmSync(startChildFile(resultFile), { force: true });
1509
- // The intent is on disk before anything is launched, so a daemon that stops at any point
1510
- // from here finds either this record, the child's own file, or the result: never nothing.
1511
- const pending = {
1512
- pid: 0, pid_started: null, started_at: new Date().toISOString(), progress_file: progressFile, result_file: resultFile,
1513
- child_file: startChildFile(resultFile),
1514
- secret_files: secretDelivery.files, fingerprint: fp, thread, desired: s,
1515
- writable: sessionWritable, image_digest: pinnedImageRef,
1516
- ...(containerMode && containerPrereqs && containerName
1517
- ? {
1518
- container_name: containerName,
1519
- container_runtime: containerPrereqs.runtime,
1520
- container_runtime_version: containerPrereqs.version,
1521
- image_digest: extractPinnedImageDigest(pinnedImageRef),
1522
- image_reference: pinnedImageRef,
1523
- }
1524
- : {}),
1525
- };
1526
- state.starting_sessions[s.id] = pending;
1491
+ let secretDelivery = null;
1492
+ let pending = null;
1493
+ let childLaunched = false;
1494
+ const projectSecretEnv = {};
1495
+ const mergedSecretEnv = {};
1496
+ let secretDeclaredHosts = [];
1527
1497
  try {
1498
+ secretDelivery = resolveSessionSecretDelivery({
1499
+ session: s,
1500
+ secrets: me.harness_secrets ?? [],
1501
+ targetDir: join(configRoot(), "providers", "ephemeral"),
1502
+ runner: deps?.runner,
1503
+ });
1504
+ if (s.secret_grant_required) {
1505
+ const grant = await client.call("POST", `/machines/me/sessions/${encodeURIComponent(s.id)}/secret-grant`, {});
1506
+ const redeemed = await Client.raw(m.url, grant.grant_token).call("POST", "/secret-broker/redeem", {});
1507
+ if (!redeemed.secrets || typeof redeemed.secrets !== "object" || Array.isArray(redeemed.secrets)) {
1508
+ throw new Error("secret broker returned no authorized secret values");
1509
+ }
1510
+ if (!Array.isArray(redeemed.declared_hosts) || redeemed.declared_hosts.some((host) => typeof host !== "string")) {
1511
+ throw new Error("secret broker returned an invalid declared host list");
1512
+ }
1513
+ secretDeclaredHosts = redeemed.declared_hosts;
1514
+ for (const [key, value] of Object.entries(redeemed.secrets)) {
1515
+ if (typeof value !== "string")
1516
+ throw new Error("secret broker returned a non-text secret value");
1517
+ if (Object.prototype.hasOwnProperty.call(secretDelivery.env, key)) {
1518
+ throw new Error(`secret name ${key} collides with a machine credential`);
1519
+ }
1520
+ projectSecretEnv[key] = value;
1521
+ }
1522
+ }
1523
+ Object.assign(mergedSecretEnv, secretDelivery.env, projectSecretEnv);
1524
+ const startId = createHash("sha256").update(s.id).digest("hex").slice(0, 24);
1525
+ const progressDir = containerMode ? join(agentHomeDirOf(s), ".b9s", "logs") : join(configRoot(), "state", "machine-start");
1526
+ mkdirSync(progressDir, { recursive: true, mode: 0o700 });
1527
+ const progressFile = join(progressDir, `start-${startId}.json`);
1528
+ // The child identity and result are private machine state; neither contains secret values.
1529
+ const privateDir = join(configRoot(), "state", "machine-start");
1530
+ mkdirSync(privateDir, { recursive: true, mode: 0o700 });
1531
+ const resultFile = join(privateDir, `result-${startId}-${randomBytes(6).toString("hex")}.json`);
1532
+ pending = {
1533
+ pid: 0, pid_started: null, started_at: new Date().toISOString(), progress_file: progressFile, result_file: resultFile,
1534
+ child_file: startChildFile(resultFile),
1535
+ secret_files: secretDelivery.files, fingerprint: fp, thread, desired: s,
1536
+ writable: sessionWritable, image_digest: pinnedImageRef,
1537
+ ...(containerMode && containerPrereqs && containerName
1538
+ ? {
1539
+ container_name: containerName,
1540
+ container_runtime: containerPrereqs.runtime,
1541
+ container_runtime_version: containerPrereqs.version,
1542
+ image_digest: extractPinnedImageDigest(pinnedImageRef),
1543
+ image_reference: pinnedImageRef,
1544
+ }
1545
+ : {}),
1546
+ };
1547
+ writeJsonAtomically(progressFile, { state: "starting", at: new Date().toISOString() });
1548
+ const launchOptions = {
1549
+ m, accountId, s, project: projectEntry, thread, sessionWritable, machineWritable: writable,
1550
+ bin, secretEnv: mergedSecretEnv, projectSecretEnvKeys: Object.keys(projectSecretEnv), secretDeclaredHosts,
1551
+ containerMode, pullImage: isPoolImageOptIn, workdir,
1552
+ sandboxReport: hostContainerProbe ?? undefined, onEc2, containerImdsBlocked: containerImdsOk,
1553
+ startupJitterSeconds: deps?.startupJitterSeconds,
1554
+ progressFile: containerMode ? undefined : progressFile,
1555
+ containerProgressFile: containerMode ? `/home/agent/.b9s/logs/start-${startId}.json` : undefined,
1556
+ };
1557
+ rmSync(startChildFile(resultFile), { force: true });
1558
+ // Persist the start intent before launch so a daemon restart can find the child/result.
1559
+ state.starting_sessions[s.id] = pending;
1528
1560
  writeMachineState(state);
1529
- }
1530
- catch (error) {
1531
- delete state.starting_sessions[s.id];
1532
- secretDelivery.cleanup();
1533
- throw error;
1534
- }
1535
- try {
1536
1561
  await scheduleRestartWork("session start/relaunch", s.agent);
1537
1562
  pending.pid = (deps?.startTrackedSession ?? ((childBin, options, result) => startSessionChild(childBin, s.dir, options, result)))(bin, launchOptions, resultFile);
1563
+ childLaunched = true;
1538
1564
  }
1539
1565
  catch (error) {
1540
- delete state.starting_sessions[s.id];
1541
- writeMachineState(state);
1542
- cleanupMachineStart(pending);
1566
+ if (pending) {
1567
+ delete state.starting_sessions[s.id];
1568
+ try {
1569
+ writeMachineState(state);
1570
+ }
1571
+ finally {
1572
+ cleanupMachineStart(pending);
1573
+ }
1574
+ }
1543
1575
  throw error;
1544
1576
  }
1577
+ finally {
1578
+ for (const k of Object.keys(projectSecretEnv)) {
1579
+ projectSecretEnv[k] = "";
1580
+ delete projectSecretEnv[k];
1581
+ }
1582
+ for (const k of Object.keys(mergedSecretEnv)) {
1583
+ mergedSecretEnv[k] = "";
1584
+ delete mergedSecretEnv[k];
1585
+ }
1586
+ if (secretDelivery) {
1587
+ for (const k of Object.keys(secretDelivery.env)) {
1588
+ secretDelivery.env[k] = "";
1589
+ delete secretDelivery.env[k];
1590
+ }
1591
+ if (!childLaunched)
1592
+ secretDelivery.cleanup();
1593
+ }
1594
+ }
1595
+ if (!pending)
1596
+ throw new Error("tracked machine start did not persist its intent");
1545
1597
  pending.pid_started = readStartStamp(pending.pid);
1546
1598
  try {
1547
1599
  writeMachineState(state);
@@ -2,7 +2,7 @@ import { mkdirSync, readFileSync, writeFileSync } from "node:fs";
2
2
  import { homedir } from "node:os";
3
3
  import { join } from "node:path";
4
4
  import { DEFAULT_URL, listSaved } from "../config.js";
5
- import { bool, str } from "../args.js";
5
+ import { bool, need, str } from "../args.js";
6
6
  import { Client } from "../client.js";
7
7
  import { loadAdmin, resolveAdminName } from "../config.js";
8
8
  import { CliError } from "../errors.js";
@@ -395,8 +395,29 @@ export async function notifierAdmin(p, out) {
395
395
  l ? `last report ${l.at.slice(0, 16).replace("T", " ")} UTC (${l.project}, ${l.items} item${l.items === 1 ? "" : "s"})${l.agent ? `\n ${l.agent.ok ? "ok " : "FAIL"} ${l.agent.name}: ${l.agent.detail}` : ""}${l.email ? `\n ${l.email.ok ? "ok " : "FAIL"} email ${l.email.to}: ${l.email.detail}` : ""}` : "nothing reported yet",
396
396
  ].join("\n"), r);
397
397
  }
398
- export async function accountAdmin(p, out) {
398
+ export async function accountAdmin(p, out, action, rest = []) {
399
399
  const c = adminClient(p);
400
+ if (action === "secrets-kms") {
401
+ const sub = rest[0] ?? "status";
402
+ if (sub === "status" && rest.length <= 1) {
403
+ const k = await c.call("GET", "/account/secrets-kms");
404
+ out.print(`Project secret envelope mode: ${k.mode} (available: ${k.value_storage_available ? "yes" : "no"}${k.value_storage_unavailable_reason ? `, reason: ${k.value_storage_unavailable_reason}` : ""})${k.kms_key_id ? `\nKMS key: ${k.kms_key_id} (${k.kms_region ?? "?"})` : ""}${k.deletion_scheduled_at ? `\nDeletion scheduled: ${k.deletion_scheduled_at}` : ""}\n${k.value_storage_unavailable_message ? `${k.value_storage_unavailable_message}\n` : ""}${k.disclosure ?? ""}`.trim(), k);
405
+ return;
406
+ }
407
+ if (sub === "enable" && rest.length === 1) {
408
+ const region = need(p.flags, "region");
409
+ const kmsKeyId = str(p.flags, "kms-key");
410
+ const k = await c.call("PUT", "/account/secrets-kms", {
411
+ region,
412
+ ...(kmsKeyId ? { kms_key_id: kmsKeyId } : {}),
413
+ });
414
+ out.print(`Enabled per-account AWS KMS wrapping in ${k.kms_region}: ${k.kms_key_id}.\n${k.disclosure ?? ""}`.trim(), k);
415
+ return;
416
+ }
417
+ throw new CliError("usage", "b9s-admin account secrets-kms [status | enable --region <aws-region> [--kms-key <arn-or-id>]]");
418
+ }
419
+ if (action)
420
+ throw new CliError("usage", "b9s-admin account [--summary-minutes <n>] | secrets-kms [status | enable --region <r> [--kms-key <id>]]");
400
421
  const m = intFlag(str(p.flags, "summary-minutes"), "summary-minutes");
401
422
  if (m !== undefined)
402
423
  await c.call("PATCH", "/account", { summary_minutes: m });
@@ -1,5 +1,15 @@
1
1
  import { bool, need, str } from "../args.js";
2
2
  import { CliError } from "../errors.js";
3
+ import { table } from "../output.js";
4
+ function limitFlag(p) {
5
+ const raw = str(p.flags, "limit");
6
+ if (raw === undefined)
7
+ return undefined;
8
+ const n = Number(raw);
9
+ if (!Number.isInteger(n) || n < 1)
10
+ throw new CliError("usage", "--limit must be a positive integer");
11
+ return n;
12
+ }
3
13
  function csv(value) {
4
14
  return value?.split(",").map((part) => part.trim()).filter(Boolean) ?? [];
5
15
  }
@@ -12,7 +22,7 @@ function purposeFlag(p) {
12
22
  export async function projectSecrets(rest, p, c, out) {
13
23
  const [project, action, secret, ...extra] = rest;
14
24
  if (!project || !action)
15
- throw new CliError("usage", "project secrets <project> list|show|create|rotate|revoke|delete|set ...");
25
+ throw new CliError("usage", "project secrets <project> list|show|create|update|rotate|revoke|delete|set|audit ...");
16
26
  const base = `/projects/${encodeURIComponent(project)}/secrets`;
17
27
  const resolve = async (name) => {
18
28
  const listed = await c.call("GET", base);
@@ -40,7 +50,12 @@ export async function projectSecrets(rest, p, c, out) {
40
50
  if (mode === "aws_secrets_manager")
41
51
  body.reference = { arn: need(p.flags, "arn"), version_id: need(p.flags, "version-id") };
42
52
  const result = await c.call("POST", base, body);
43
- out.print(`Created ${secret} for ${project}; values are unavailable until encrypted storage lands in WU #231. Console control: WU #230.`, result);
53
+ const nextHint = mode === "aws_secrets_manager"
54
+ ? "External AWS reference recorded."
55
+ : result.value_storage_available
56
+ ? `Set its encrypted value with: b9s-admin project secrets ${project} set ${secret} --stdin`
57
+ : `Encrypted storage is unavailable (${result.value_storage_unavailable_reason ?? "aws_kms_unconfigured"}); configure per-account AWS KMS before calling set.`;
58
+ out.print(`Created ${secret} for ${project}. ${nextHint} (Console control: WU #230.)`, result);
44
59
  return;
45
60
  }
46
61
  if (action === "show" && secret && !extra.length) {
@@ -49,9 +64,33 @@ export async function projectSecrets(rest, p, c, out) {
49
64
  return;
50
65
  }
51
66
  if (action === "rotate" && secret && !extra.length) {
52
- const result = await c.call("POST", `${base}/${encodeURIComponent(await resolve(secret))}/versions`, { reference: { arn: need(p.flags, "arn"), version_id: need(p.flags, "version-id") } });
53
- out.print(`Recorded a new external reference version for ${secret}.`, result);
54
- return;
67
+ const id = await resolve(secret);
68
+ const drain = bool(p.flags, "drain");
69
+ const arn = str(p.flags, "arn");
70
+ const versionId = str(p.flags, "version-id");
71
+ if (arn !== undefined || versionId !== undefined) {
72
+ const result = await c.call("POST", `${base}/${encodeURIComponent(id)}/versions`, {
73
+ reference: { arn: need(p.flags, "arn"), version_id: need(p.flags, "version-id") },
74
+ ...(drain ? { drain_sessions: true } : {}),
75
+ });
76
+ out.print(`Recorded a new external reference version v${result.secret?.current_version ?? "?"} for ${secret}.${drain ? ` Drained ${result.drained_sessions?.length ?? 0} running session(s).` : ""}`, result);
77
+ return;
78
+ }
79
+ if (bool(p.flags, "stdin") || process.stdin.isTTY) {
80
+ const meta = await c.call("GET", `${base}/${encodeURIComponent(id)}`);
81
+ if (!meta.value_storage_available) {
82
+ throw new CliError("secret_storage_unavailable", "Secret value rotation is unavailable because encrypted storage is not configured on this server; no value was read or sent.");
83
+ }
84
+ let value = await readSecretValue(bool(p.flags, "stdin"));
85
+ const result = await c.call("PUT", `${base}/${encodeURIComponent(id)}/value`, {
86
+ value,
87
+ ...(drain ? { drain_sessions: true } : {}),
88
+ });
89
+ value = "";
90
+ out.print(`Rotated ${secret} to encrypted v${result.version ?? "?"} (${result.storage?.backend ?? "encrypted"}). Notice: BenignSwarm decrypts hosted secrets in memory during broker delivery to authorized sessions.`, result);
91
+ return;
92
+ }
93
+ throw new CliError("usage", "project secrets <p> rotate <name> (--arn <exact ARN> --version-id <id> | --stdin) [--drain]");
55
94
  }
56
95
  if (action === "update" && secret && !extra.length) {
57
96
  const body = {};
@@ -77,27 +116,54 @@ export async function projectSecrets(rest, p, c, out) {
77
116
  }
78
117
  if (action === "revoke" && secret && !extra.length) {
79
118
  const result = await c.call("POST", `${base}/${encodeURIComponent(await resolve(secret))}/revoke`, {});
80
- out.print(`Revoked future access to ${secret}.`, result);
119
+ out.print(`Revoked access to ${secret}; stopped ${result.stopped_sessions?.length ?? 0} active session(s).`, result);
81
120
  return;
82
121
  }
83
122
  if (action === "delete" && secret && !extra.length) {
84
123
  const result = await c.call("DELETE", `${base}/${encodeURIComponent(await resolve(secret))}`);
85
- out.print(`Deleted definition ${secret}; customer-owned AWS resources are unchanged.`, result);
124
+ out.print(`Deleted ${secret} (${result.stopped_sessions?.length ?? 0} session(s) stopped); customer-owned AWS Secrets Manager secrets and IAM roles remain in your AWS account.`, result);
86
125
  return;
87
126
  }
88
127
  if (action === "set" && secret && !extra.length && (bool(p.flags, "stdin") || process.stdin.isTTY)) {
89
128
  const id = await resolve(secret);
90
129
  const result = await c.call("GET", `${base}/${encodeURIComponent(id)}`);
91
130
  if (!result.value_storage_available) {
92
- throw new CliError("secret_storage_unavailable", "Secret value entry is unavailable until encrypted storage lands in WU #231; no value was read or sent.");
131
+ throw new CliError("secret_storage_unavailable", "Secret value entry is unavailable because encrypted storage is not configured on this server; no value was read or sent.");
93
132
  }
94
- // The metadata capability gate above must precede any read/prompt. WU #231 enables this path.
95
- const value = await readSecretValue(bool(p.flags, "stdin"));
96
- await c.call("PUT", `${base}/${encodeURIComponent(id)}/value`, { value });
97
- out.print(`Saved a new value version for ${secret}.`, { ok: true });
133
+ // The metadata capability gate above must precede any read/prompt.
134
+ let value = await readSecretValue(bool(p.flags, "stdin"));
135
+ const drain = bool(p.flags, "drain");
136
+ const saved = await c.call("PUT", `${base}/${encodeURIComponent(id)}/value`, {
137
+ value,
138
+ ...(drain ? { drain_sessions: true } : {}),
139
+ });
140
+ value = "";
141
+ const kmsNote = saved.storage?.kms_key_id
142
+ ? `encrypted with per-account AWS KMS key (${saved.storage.kms_key_id})`
143
+ : "encrypted with per-account AWS KMS key";
144
+ out.print(`Saved encrypted v${saved.version ?? "?"} for ${secret} (${kmsNote}).${drain ? ` Drained ${saved.drained_sessions?.length ?? 0} running session(s).` : ""} Notice: BenignSwarm decrypts hosted secrets in memory during broker delivery to authorized sessions.`, saved);
145
+ return;
146
+ }
147
+ if (action === "audit" && !extra.length) {
148
+ const limit = limitFlag(p);
149
+ const qs = limit !== undefined ? `?limit=${limit}` : "";
150
+ const path = secret
151
+ ? `${base}/${encodeURIComponent(await resolve(secret))}/audit${qs}`
152
+ : `${base}/audit${qs}`;
153
+ const result = await c.call("GET", path);
154
+ const events = result.events ?? [];
155
+ out.print(events.length
156
+ ? table(events.map((e) => ({
157
+ at: e.created_at,
158
+ action: e.action,
159
+ actor: e.actor_id,
160
+ version: e.version ?? "—",
161
+ detail: typeof e.detail === "string" ? e.detail : JSON.stringify(e.detail ?? {}),
162
+ })), ["at", "action", "actor", "version", "detail"])
163
+ : "No secret audit events.", result);
98
164
  return;
99
165
  }
100
- throw new CliError("usage", "project secrets <project> list | show <name> | create <name> --purpose <text> --storage-mode hosted|aws_secrets_manager --units 1,2 --tags api --hosts db.example.com [--arn <exact ARN> --version-id <id>] | update <name> [--purpose <text>] [--units 1,2] [--tags api] [--hosts host[,host]] | rotate <name> --arn <exact ARN> --version-id <id> | revoke <name> | delete <name> | set <name> [--stdin]");
166
+ throw new CliError("usage", "project secrets <project> list | show <name> | audit [<name>] [--limit N] | create <name> --purpose <text> --storage-mode hosted|aws_secrets_manager --units 1,2 --tags api --hosts db.example.com [--arn <exact ARN> --version-id <id>] | update <name> [--purpose <text>] [--units 1,2] [--tags api] [--hosts host[,host]] | rotate <name> (--arn <exact ARN> --version-id <id> | --stdin) [--drain] | revoke <name> | delete <name> | set <name> [--stdin] [--drain]");
101
167
  }
102
168
  function decodeSecretValue(bytes) {
103
169
  try {
@@ -6,9 +6,10 @@ import { describeFinding, describeProbe, evaluateProbe, expectedFor, runSandboxP
6
6
  /**
7
7
  * What the sandbox this command runs in really allows.
8
8
  *
9
- * b9s sandbox probe [--checkout <dir>] [--api <host>] [--out <file>] [--nonce <id>] [--harness <h> --sandbox <mode>]
9
+ * b9s sandbox probe [--checkout <dir>] [--unit-worktree <dir>] [--sibling-checkout <dir>] [--api <host>] [--out <file>] [--nonce <id>] [--harness <h> --sandbox <mode>]
10
10
  * measure, from inside the sandbox: where commands run, which tools are there, what git can
11
- * do, which hosts answer, and what is writable. Records facts and judges nothing.
11
+ * do, which hosts answer, and what is writable. Records facts and judges nothing. By default
12
+ * it prints to stdout; --out must name a writable file (for example inside the checkout).
12
13
  * b9s sandbox check <file> --harness <h> --sandbox <mode>
13
14
  * compare a probe's result with what is expected of that harness and mode; exits 1 on a
14
15
  * difference, naming each one.
@@ -24,7 +25,7 @@ export async function sandbox(p, out) {
24
25
  const mode = str(p.flags, "sandbox");
25
26
  if ((harness === undefined) !== (mode === undefined) || harness === "" || mode === "")
26
27
  throw new CliError("usage", "sandbox probe --harness and --sandbox must be provided together");
27
- const result = await runSandboxProbe({ nonce, checkout: str(p.flags, "checkout"), apiHost: str(p.flags, "api"), ...(harness !== undefined && mode !== undefined ? { harness, sandbox: mode } : {}) });
28
+ const result = await runSandboxProbe({ nonce, checkout: str(p.flags, "checkout"), unitWorktree: str(p.flags, "unit-worktree"), siblingCheckout: str(p.flags, "sibling-checkout"), apiHost: str(p.flags, "api"), ...(harness !== undefined && mode !== undefined ? { harness, sandbox: mode } : {}) });
28
29
  const file = str(p.flags, "out");
29
30
  if (file)
30
31
  writeProbeResult(file, result);
@@ -46,7 +47,7 @@ export async function sandbox(p, out) {
46
47
  }
47
48
  if (result?.schema !== 1 || !result.checks)
48
49
  throw new CliError("probe_unreadable", `${file} is not a sandbox probe result`);
49
- const verdict = evaluateProbe(result, expectedFor(harness, mode));
50
+ const verdict = evaluateProbe(result, expectedFor(harness, mode, result));
50
51
  const lines = verdict.ok
51
52
  ? [`sandbox as expected for ${harness} ${mode} (${verdict.unjudged.length} recorded without a verdict)`]
52
53
  : [`sandbox differs from what is expected for ${harness} ${mode}:`, ...verdict.failures.map((f) => ` - ${describeFinding(f)}`)];
@@ -55,5 +56,5 @@ export async function sandbox(p, out) {
55
56
  throw new CliError("sandbox_differs", `${verdict.failures.length} sandbox check${verdict.failures.length === 1 ? "" : "s"} differ from what is expected`);
56
57
  return;
57
58
  }
58
- throw new CliError("usage", "sandbox probe [--checkout <dir>] [--api <host>] [--out <file>] [--nonce <id>] [--harness <h> --sandbox <mode>] | sandbox check <file> --harness <h> --sandbox <mode>");
59
+ throw new CliError("usage", "sandbox probe [--checkout <dir>] [--unit-worktree <dir>] [--sibling-checkout <dir>] [--api <host>] [--out <file>] [--nonce <id>] [--harness <h> --sandbox <mode>] | sandbox check <file> --harness <h> --sandbox <mode>");
59
60
  }
@@ -759,6 +759,9 @@ export async function wakeOnce(name, exec, unackedAfter, followDelay, log, model
759
759
  let preparedWorktree = null;
760
760
  if (turnSink && bindingToPrepare) {
761
761
  preparedWorktree = await (dependencies.prepareWorktree ?? prepareTurnWorktree)(name, bindingToPrepare);
762
+ if (!preparedWorktree && dependencies.claudeRuntime?.sandbox === "workspace-write") {
763
+ throw new CliError("unit_worktree_missing", `Claude Code workspace-write cannot start WU #${bindingToPrepare.work_unit_number}: the watcher did not prepare its unit worktree`);
764
+ }
762
765
  if (preparedWorktree) {
763
766
  wakePrefix.push(preparedWorktree.status === "assigned"
764
767
  ? `The watcher prepared WU #${preparedWorktree.number}'s worktree at ${preparedWorktree.path}. Run b9s wu start ${preparedWorktree.number} from this checkout to record the start, then work in that path.`
@@ -780,8 +783,7 @@ export async function wakeOnce(name, exec, unackedAfter, followDelay, log, model
780
783
  turnCwd = preparedWorktree?.path ?? process.cwd();
781
784
  if (turnSink && dependencies.claudeRuntime && turnExec?.includes(CLAUDE_SETTINGS_PLACEHOLDER)) {
782
785
  const runtime = dependencies.claudeRuntime;
783
- const cwd = turnCwd ?? process.cwd();
784
- const args = claudeSettings(runtime.sandbox, model, runtime.effort, cwd, configRoot(), runtime.writableRoots);
786
+ const args = claudeSettings(runtime.sandbox, model, runtime.effort, process.cwd(), configRoot(), runtime.writableRoots, preparedWorktree ?? undefined);
785
787
  turnExec = turnExec.replace(CLAUDE_SETTINGS_PLACEHOLDER, args.map(shellQuote).join(" "));
786
788
  }
787
789
  if (turnSink && dependencies.antigravityRuntime && turnExec?.includes(ANTIGRAVITY_SETTINGS_PLACEHOLDER)) {
package/dist/container.js CHANGED
@@ -975,12 +975,13 @@ export function agentContainerRunArgs(opts) {
975
975
  const hostCache = assertSafeMountPath(join(opts.cacheRootDir, cacheName), "cache", boundaryOpts);
976
976
  args.push("-v", `${hostCache}:/caches/${cacheName}:rw`);
977
977
  }
978
+ const secretEnvKeys = new Set(opts.secretEnvKeys ?? []);
978
979
  for (const [k, v] of Object.entries(opts.extraEnv ?? {})) {
979
980
  if (/^(AWS_|B9S_MACHINE|BSCHAT_MACHINE)/i.test(k))
980
981
  continue;
981
982
  if (SECRET_KEY_RE.test(k) && v.includes("machine.json"))
982
983
  continue;
983
- args.push("-e", `${k}=${v}`);
984
+ args.push("-e", secretEnvKeys.has(k) ? k : `${k}=${v}`);
984
985
  }
985
986
  args.push(opts.imageDigest, ...opts.command);
986
987
  return args;
@@ -989,7 +990,7 @@ export function agentContainerRunArgs(opts) {
989
990
  * Constructs a secret-free host subprocess environment for disposable image builds and
990
991
  * container-runtime client invocations, stripping AWS, harness, GitHub, and machine credentials.
991
992
  */
992
- export function isolatedSubprocessEnv(baseEnv = process.env, extraEnv = {}) {
993
+ export function isolatedSubprocessEnv(baseEnv = process.env, extraEnv = {}, passSecretKeys = []) {
993
994
  const out = {};
994
995
  const allowKeys = ["PATH", "LANG", "LC_ALL", "TERM", "TMPDIR", "XDG_RUNTIME_DIR", "CONTAINER_HOST", "DOCKER_HOST"];
995
996
  for (const key of allowKeys) {
@@ -998,7 +999,7 @@ export function isolatedSubprocessEnv(baseEnv = process.env, extraEnv = {}) {
998
999
  out[key] = v;
999
1000
  }
1000
1001
  for (const [k, v] of Object.entries(extraEnv)) {
1001
- if (!SECRET_KEY_RE.test(k))
1002
+ if (!SECRET_KEY_RE.test(k) || passSecretKeys.includes(k))
1002
1003
  out[k] = v;
1003
1004
  }
1004
1005
  return out;
package/dist/harnesses.js CHANGED
@@ -1,9 +1,10 @@
1
1
  import { spawnSync } from "node:child_process";
2
- import { accessSync, constants, existsSync, readFileSync, readdirSync, statSync } from "node:fs";
2
+ import { accessSync, constants, existsSync, readFileSync, readdirSync, realpathSync, statSync } from "node:fs";
3
3
  import { homedir } from "node:os";
4
- import { dirname, join } from "node:path";
4
+ import { basename, dirname, join, resolve } from "node:path";
5
5
  import { CliError } from "./errors.js";
6
6
  import { configRoot } from "./config.js";
7
+ import { gitSandboxWritablePaths } from "./git-sandbox-paths.js";
7
8
  import { readState, updateState } from "./state.js";
8
9
  import { codexArchivedRollout, codexRollout } from "./sessions.js";
9
10
  import { readTurnPhase, usageLimitUntil } from "./turn.js";
@@ -579,19 +580,54 @@ function claudeProbe(session, ref) {
579
580
  * The Claude Code flags a headless turn runs with. Claude Code's sandbox always lets the agent write
580
581
  * its working folder, so read-only cannot be honoured and is refused. workspace-write is its sandbox
581
582
  * (refusing to start when the sandbox is unavailable, never running a command outside it), every
582
- * domain reachable as with Codex, edits allowed in the checkout and the folders `wu start` and bschat
583
- * write (the checkout's parent, ~/.b9s) plus the machine's writable folders; anything that would
584
- * need a prompt is denied, since nobody can answer one. danger-full-access skips permissions.
583
+ * domain reachable as with Codex, edits allowed in the agent's checkout, its active unit worktree,
584
+ * the Git metadata those checkouts need, b9s's config root, and the machine's writable folders;
585
+ * anything that would need a prompt is denied, since nobody can answer one. danger-full-access skips
586
+ * permissions.
585
587
  */
586
- export function claudeSettings(sandbox, model, effort, cwd, bschatHome, extraWritable = []) {
588
+ export function claudeSettings(sandbox, model, effort, checkoutRoot, bschatHome, extraWritable = [], unitWorktree) {
587
589
  const common = [...(model ? ["--model", model] : []), ...(effort ? ["--effort", effort] : [])];
588
590
  if (sandbox === "danger-full-access")
589
591
  return [...common, "--permission-mode", "bypassPermissions"];
590
592
  if (sandbox === "read-only")
591
- throw new CliError("unsupported", "Claude Code has no read-only sandbox: its sandbox always lets the agent write its working folder. Use workspace-write (sandboxed; writes limited to the checkout, its unit worktrees, ~/.b9s and the machine's writable folders) or danger-full-access");
593
+ throw new CliError("unsupported", "Claude Code has no read-only sandbox: its sandbox always lets the agent write its working folder. Use workspace-write (sandboxed; writes limited to the checkout, the active unit worktree, required Git metadata, b9s config and machine writable folders) or danger-full-access");
592
594
  if (sandbox !== "workspace-write")
593
595
  throw new CliError("usage", `unknown sandbox ${sandbox}`);
594
- const dirs = [dirname(cwd), bschatHome, ...extraWritable];
596
+ const requiredDirectory = (label, value) => {
597
+ let resolved;
598
+ try {
599
+ resolved = realpathSync(resolve(value));
600
+ if (!statSync(resolved).isDirectory())
601
+ throw new Error("not a directory");
602
+ }
603
+ catch {
604
+ throw new CliError("sandbox_path_missing", `Claude Code workspace-write cannot start: ${label} directory ${value} is missing or is not a directory`);
605
+ }
606
+ return resolved;
607
+ };
608
+ const checkout = requiredDirectory("agent checkout", checkoutRoot);
609
+ const directories = [checkout];
610
+ const files = [];
611
+ if (unitWorktree)
612
+ directories.push(requiredDirectory(`WU #${unitWorktree.number} worktree`, unitWorktree.path));
613
+ // Shared Git path discovery is also used by Antigravity. Add directories as roots and files
614
+ // only to allowWrite; the common .git root, hooks/config and unassigned worktree metadata stay out.
615
+ const exactGitFiles = new Set(["FETCH_HEAD", "FETCH_HEAD.lock", "packed-refs", "packed-refs.lock", "HEAD", "HEAD.lock", "index", "index.lock", "COMMIT_EDITMSG"]);
616
+ // The checkout and prepared worktree can be separate clones on a machine. Compute each Git
617
+ // metadata allowlist independently, then deduplicate; neither is allowed to widen the other.
618
+ const gitPaths = [
619
+ ...gitSandboxWritablePaths(checkout),
620
+ ...(unitWorktree ? gitSandboxWritablePaths(unitWorktree.path) : []),
621
+ ];
622
+ const gitFiles = gitPaths.filter((path) => exactGitFiles.has(basename(path)));
623
+ directories.push(...gitPaths.filter((path) => !exactGitFiles.has(basename(path))));
624
+ files.push(...gitFiles);
625
+ // A first-time `b9s start --token` computes settings before enrollment creates this exact folder.
626
+ // It is safe to allow the path before creation; never replace it with its parent.
627
+ directories.push(existsSync(bschatHome) ? requiredDirectory("b9s config", bschatHome) : resolve(bschatHome));
628
+ directories.push(...extraWritable.map((path) => resolve(path)));
629
+ const dirs = [...new Set(directories)];
630
+ const writable = [...new Set([...dirs, ...files])];
595
631
  const settings = {
596
632
  env: claudeSandboxEnv(sandbox),
597
633
  sandbox: {
@@ -599,7 +635,7 @@ export function claudeSettings(sandbox, model, effort, cwd, bschatHome, extraWri
599
635
  failIfUnavailable: true,
600
636
  autoAllowBashIfSandboxed: true,
601
637
  allowUnsandboxedCommands: false,
602
- filesystem: { allowWrite: dirs },
638
+ filesystem: { allowWrite: writable },
603
639
  network: { allowedDomains: ["*", "api.benignswarm.org"] },
604
640
  },
605
641
  };
package/dist/help.js CHANGED
@@ -231,9 +231,11 @@ Machine placement enforces configured session slots and reports machine pressure
231
231
  restart the machine daemon first, then watchers in batches of 5 with 5 s between batches
232
232
  b9s install [<version> | --latest] [--no-restart] make or upgrade this machine's one b9s (join does it once), repair PATH aliases,
233
233
  restart the machine daemon first, then watchers in batches of 5 with 5 s between batches
234
- b9s sandbox probe [--checkout <dir>] [--api <host>] [--out <file>] [--nonce <id>] [--harness <h> --sandbox <mode>]
234
+ b9s sandbox probe [--checkout <dir>] [--unit-worktree <dir>] [--sibling-checkout <dir>] [--api <host>] [--out <file>] [--nonce <id>] [--harness <h> --sandbox <mode>]
235
235
  what the sandbox this runs in really allows: where commands run, which tools
236
236
  are there, what git can do, which hosts answer, what is writable; facts only.
237
+ Prints to stdout by default; --out must name a writable file, such as one inside
238
+ the checkout.
237
239
  The harness/mode pair is needed for watcher cleanup on Antigravity workspace-write
238
240
  b9s sandbox check <file> --harness <h> --sandbox <mode>
239
241
  compare a probe result with what is expected of that harness; exits 1 on a difference
@@ -352,13 +354,15 @@ Use --admin <nickname> to select one of this machine's saved operator identities
352
354
  enable only after exact ruleset verification in console and live bypass-change signal check; controls are also in console WU #196
353
355
  b9s-admin project secrets <project> list
354
356
  b9s-admin project secrets <project> show <name>
357
+ b9s-admin project secrets <project> audit [<name>] [--limit n]
355
358
  b9s-admin project secrets <project> create <name> --purpose <text> --storage-mode hosted|aws_secrets_manager --units 1,2 --tags api --hosts host[,host] [--arn <exact ARN> --version-id <id>]
356
359
  b9s-admin project secrets <project> update <name> [--purpose <text>] [--units 1,2] [--tags api] [--hosts host[,host]]
357
- b9s-admin project secrets <project> rotate <name> --arn <exact ARN> --version-id <id>
360
+ b9s-admin project secrets <project> rotate <name> (--arn <exact ARN> --version-id <id> | --stdin) [--drain]
358
361
  b9s-admin project secrets <project> revoke <name>
359
362
  b9s-admin project secrets <project> delete <name>
360
- b9s-admin project secrets <project> set <name> [--stdin]
361
- purpose is trimmed before send (1–200 characters); values remain unavailable until encrypted storage lands in WU #231; set checks before reading input; console control is WU #230
363
+ b9s-admin project secrets <project> set <name> [--stdin] [--drain]
364
+ --hosts stores declared hostnames only; all current machine adapters refuse secret grants until outer egress enforcement exists
365
+ purpose is trimmed before send (1–200 characters); set/rotate check AWS KMS availability before reading a value; no plaintext fallback; console control is WU #230
362
366
  b9s-admin project environment show <project>
363
367
  b9s-admin project environment setup <project> [--catalog family@version] [--assessment-only] [--context text]
364
368
  b9s-admin project environment set <project> --file declaration.json --source-commit <merged-sha>
@@ -446,6 +450,8 @@ Use --admin <nickname> to select one of this machine's saved operator identities
446
450
  b9s-admin explain <key> ask the agent to explain a decision in plain words (the console's Explain)
447
451
  b9s-admin notifier [--agent name|none] [--email yes|no] [--repeat m] [--flow-summary yes|no] [--flow-min-age m] [--flow-min-impact n] how you are reached away from the console, and the last report
448
452
  b9s-admin account [--summary-minutes m] plan, usage and the account summary period
453
+ b9s-admin account secrets-kms status | enable --region <aws-region> [--kms-key <arn-or-id>]
454
+ dedicated per-account KMS key; foreign, shared, or untagged keys are refused
449
455
  assistant stays opt-in: PATCH /account {"assistant_enabled":true|false}; GET /account/usage shows used, allowance, uncertain calls and reset date
450
456
  b9s-admin account-stores migrations show|run [--json] inspect or resume the per-account SQLite schema migration runner (platform admin only)
451
457
  session/admin clients use GET /assistant/conversations/:id/messages for paged history and GET/POST/DELETE /assistant/conversations; POST messages streams data and saves tool notices with assistant messages; old assistant messages have notices_available=false; operator must explicitly apply or discard (see operator skill)
@@ -491,9 +497,9 @@ Machines (provisioned over your own ssh; a daemon on each runs the agent session
491
497
  transfers thread/note plus local agent state over SSH,
492
498
  refuses newer destination state and avoids duplicate Codex hooks under managed policy,
493
499
  then commits the session only after handoff succeeds; work left on the source requires both flags
494
- b9s-admin machine label <name> <label...> [--remove a,b] what cannot be measured (lab-lan, builds); pools' --needs match it
500
+ b9s-admin machine label <name> <label...> [--remove a,b] [--preview | --impact-revision <revision>] preview affected pool placement, then confirm with its revision
495
501
  b9s-admin machine headroom [name] latest resource headroom, freshness, session ceiling and reservations (console WU #118)
496
- b9s-admin machine slots <name> <n | auto> how many sessions it takes (auto: one per 4 GB of RAM)
502
+ b9s-admin machine slots <name> <n | auto> [--preview | --impact-revision <revision>] preview affected pool placement, then confirm with its revision
497
503
  b9s-admin machine writable <name> <path...> | none folders workspace-write agents there may also write (~/.cargo, ~/.ester)
498
504
  b9s-admin machine workdir <name> <path | default> where its daemon clones projects for pool sessions (default ~/bschat)
499
505
  b9s-admin machine cache-budget <name> [<GB> | default] [--floor <pct | default>] per-cache budget (default 40 GB) and volume free-space floor (default 15%)
@@ -1,8 +1,8 @@
1
1
  import { spawnSync } from "node:child_process";
2
2
  import { createHash } from "node:crypto";
3
- import { closeSync, existsSync, mkdirSync, openSync, readdirSync, realpathSync, rmSync, unlinkSync, writeFileSync } from "node:fs";
3
+ import { closeSync, existsSync, mkdirSync, openSync, readFileSync, readdirSync, realpathSync, rmSync, unlinkSync, writeFileSync } from "node:fs";
4
4
  import { homedir } from "node:os";
5
- import { basename, delimiter, dirname, join } from "node:path";
5
+ import { basename, delimiter, dirname, isAbsolute, join, resolve } from "node:path";
6
6
  import { configRoot } from "./config.js";
7
7
  import { CliError } from "./errors.js";
8
8
  import { CLI_VERSION } from "./version.js";
@@ -12,7 +12,7 @@ export const PROBE_CHECKS = [
12
12
  "tool_node", "tool_npm", "tool_npx", "tool_git", "tool_b9s",
13
13
  "git_branch", "git_branch_delete", "git_object", "git_worktree", "git_other_worktree", "git_remote_read",
14
14
  "net_api", "net_other_host",
15
- "write_checkout", "write_checkout_parent", "write_b9s_home",
15
+ "write_checkout", "write_checkout_parent", "write_unit_worktree", "write_sibling_checkout", "git_commit", "git_fetch", "write_b9s_home",
16
16
  "write_git_config", "write_git_hooks", "write_home", "write_node_install",
17
17
  ];
18
18
  const clip = (text) => text.trim().replace(/\s+/g, " ").slice(0, 300);
@@ -86,6 +86,96 @@ function createAndRemove(dir, nonce) {
86
86
  unlinkSync(path);
87
87
  });
88
88
  }
89
+ function canonicalIfPresent(path) {
90
+ if (!path)
91
+ return null;
92
+ try {
93
+ return realpathSync(path);
94
+ }
95
+ catch (error) {
96
+ if (error.code === "ENOENT")
97
+ return null;
98
+ throw error;
99
+ }
100
+ }
101
+ /** Identity names written into agent home checkouts and unit worktrees. */
102
+ function identityIdsAt(checkout) {
103
+ for (const path of [join(checkout, ".b9s", "identity.json"), join(checkout, ".bschat", "identity.json")]) {
104
+ let raw;
105
+ try {
106
+ raw = readFileSync(path, "utf8");
107
+ }
108
+ catch (error) {
109
+ if (error.code === "ENOENT")
110
+ continue;
111
+ throw error;
112
+ }
113
+ const identity = JSON.parse(raw);
114
+ if (typeof identity.agent === "string" && identity.agent.trim())
115
+ return [identity.agent.trim()];
116
+ if (!identity.agents || typeof identity.agents !== "object" || Array.isArray(identity.agents))
117
+ return [];
118
+ return Object.values(identity.agents).flatMap((value) => {
119
+ if (!value || typeof value !== "object" || Array.isArray(value))
120
+ return [];
121
+ const entry = value;
122
+ if (typeof entry.name !== "string" || !entry.name.trim())
123
+ return [];
124
+ return [typeof entry.project === "string" && entry.project.trim() ? `${entry.project.trim()}/${entry.name.trim()}` : entry.name.trim()];
125
+ });
126
+ }
127
+ return [];
128
+ }
129
+ /** Resolve a linked-worktree admin entry back to the checkout whose metadata it represents. */
130
+ function linkedCheckout(adminDir) {
131
+ const record = readFileSync(join(adminDir, "gitdir"), "utf8").trim();
132
+ const match = /^(?:gitdir:\s*)?(.+)$/i.exec(record);
133
+ if (!match?.[1])
134
+ throw new Error(`invalid linked-worktree gitdir record at ${adminDir}`);
135
+ const gitFile = realpathSync(isAbsolute(match[1]) ? match[1] : resolve(adminDir, match[1]));
136
+ return realpathSync(dirname(gitFile));
137
+ }
138
+ function otherAgentWorktree(commonDir, currentGitDir, currentCheckout, options, env) {
139
+ const selfPaths = new Set([options.checkout, options.unitWorktree, currentCheckout]
140
+ .map((path) => canonicalIfPresent(path)).filter((path) => path !== null));
141
+ const currentIds = new Set([env.BSCHAT_AGENT, env.B9S_AGENT, ...identityIdsAt(options.checkout ?? currentCheckout)]
142
+ .filter((id) => typeof id === "string" && id.trim().length > 0).map((id) => id.trim()));
143
+ let entries;
144
+ try {
145
+ entries = readdirSync(join(commonDir, "worktrees"), { withFileTypes: true });
146
+ }
147
+ catch (error) {
148
+ if (error.code === "ENOENT")
149
+ return null;
150
+ throw error;
151
+ }
152
+ for (const entry of entries) {
153
+ if (!entry.isDirectory())
154
+ continue;
155
+ const adminDir = join(commonDir, "worktrees", entry.name);
156
+ let checkout;
157
+ try {
158
+ if (realpathSync(adminDir) === currentGitDir)
159
+ continue;
160
+ checkout = linkedCheckout(adminDir);
161
+ }
162
+ catch (error) {
163
+ if (error.code === "ENOENT")
164
+ continue;
165
+ throw error;
166
+ }
167
+ if (selfPaths.has(checkout))
168
+ continue;
169
+ const candidateIds = identityIdsAt(checkout);
170
+ const identityMayBeSame = (currentId, candidateId) => currentId === candidateId
171
+ || (!currentId.includes("/") && candidateId.endsWith(`/${currentId}`))
172
+ || (!candidateId.includes("/") && currentId.endsWith(`/${candidateId}`));
173
+ const isDifferentAgent = (id) => ![...currentIds].some((currentId) => identityMayBeSame(currentId, id));
174
+ if (candidateIds.length > 0 && currentIds.size > 0 && candidateIds.every(isDifferentAgent))
175
+ return { checkout, adminDir };
176
+ }
177
+ return null;
178
+ }
89
179
  async function reach(url, timeoutMs = 10_000) {
90
180
  try {
91
181
  const res = await fetch(url, { method: "GET", signal: AbortSignal.timeout(timeoutMs), redirect: "manual" });
@@ -110,10 +200,11 @@ export async function runSandboxProbe(options) {
110
200
  const originConfigured = read(["config", "--get", "remote.origin.url"]);
111
201
  const originEffective = read(["remote", "get-url", "origin"]);
112
202
  const checks = Object.fromEntries(PROBE_CHECKS.map((id) => [id, null]));
113
- checks.cwd_is_checkout = options.checkout
114
- ? cwd === options.checkout && toplevel === options.checkout
203
+ const expectedWorkingTree = options.unitWorktree ?? options.checkout;
204
+ checks.cwd_is_checkout = expectedWorkingTree
205
+ ? cwd === expectedWorkingTree && toplevel === expectedWorkingTree
115
206
  ? { ok: true, value: cwd }
116
- : { ok: false, value: cwd, detail: clip(`expected ${options.checkout}; the repository here is ${toplevel ?? "none"}`) }
207
+ : { ok: false, value: cwd, detail: clip(`expected ${expectedWorkingTree}; the repository here is ${toplevel ?? "none"}`) }
117
208
  : null;
118
209
  checks.origin_is_https = originEffective === null
119
210
  ? { ok: false, detail: "no origin remote is readable here" }
@@ -181,25 +272,76 @@ export async function runSandboxProbe(options) {
181
272
  throw new Error(`added a worktree but could not remove it: ${gone.err}`);
182
273
  }
183
274
  });
184
- checks.git_other_worktree = observe(() => {
185
- const currentGitDir = realpathSync(gitDir);
186
- const entries = readdirSync(join(commonDir, "worktrees"), { withFileTypes: true })
187
- .filter((entry) => entry.isDirectory() && realpathSync(join(commonDir, "worktrees", entry.name)) !== currentGitDir);
188
- const other = entries[0];
189
- if (!other)
190
- throw new Error("no other linked-worktree entry is available to check");
191
- const result = createAndRemove(join(commonDir, "worktrees", other.name), nonce);
192
- if (!result.ok)
193
- throw new Error(result.detail ?? `another worktree entry was refused: ${other.name}`);
194
- });
275
+ let other;
276
+ try {
277
+ other = otherAgentWorktree(commonDir, realpathSync(gitDir), toplevel, options, env);
278
+ }
279
+ catch (error) {
280
+ checks.git_other_worktree = { ok: false, error: true, detail: clip(error.message) };
281
+ other = null;
282
+ }
283
+ if (checks.git_other_worktree === null) {
284
+ if (!other) {
285
+ checks.git_other_worktree = { ok: false, not_applicable: true, detail: "no linked worktree belonging to another agent was found" };
286
+ }
287
+ else {
288
+ const result = createAndRemove(other.adminDir, nonce);
289
+ checks.git_other_worktree = result.ok
290
+ ? { ...result, value: other.checkout }
291
+ : { ...result, detail: clip(`another agent's linked-worktree metadata at ${other.checkout}: ${result.detail ?? "write refused"}`) };
292
+ }
293
+ }
195
294
  const remote = git(["ls-remote", "origin", "HEAD"], 30_000);
196
295
  // Exit 0 is the remote answering; a remote whose HEAD names no branch yet answers with nothing.
197
296
  checks.git_remote_read = remote.status === 0
198
297
  ? { ok: true }
199
298
  : { ok: false, detail: clip(remote.err || `git ls-remote origin exited ${remote.status ?? "without a status"}`) };
200
- checks.write_checkout = createAndRemove(toplevel, nonce);
201
- checks.write_checkout_parent = createAndRemove(dirname(toplevel), nonce);
299
+ checks.write_checkout = createAndRemove(options.checkout ?? toplevel, nonce);
300
+ checks.write_checkout_parent = createAndRemove(dirname(options.checkout ?? toplevel), nonce);
202
301
  }
302
+ if (options.unitWorktree) {
303
+ const unitWorktree = options.unitWorktree;
304
+ checks.write_unit_worktree = createAndRemove(unitWorktree, nonce);
305
+ const commitFile = join(unitWorktree, `.b9s-probe-commit-${nonce}`);
306
+ const indexFile = join(unitWorktree, `.b9s-probe-index-${nonce}`);
307
+ checks.git_commit = observe(() => {
308
+ const original = run("git", ["rev-parse", "HEAD"], unitWorktree, env);
309
+ if (original.status !== 0 || !original.out)
310
+ throw new Error(original.err || "cannot read unit worktree HEAD");
311
+ const oldHead = original.out;
312
+ writeFileSync(commitFile, `b9s sandbox probe ${nonce}\n`, { flag: "wx" });
313
+ const gitEnv = { ...env, GIT_INDEX_FILE: indexFile };
314
+ const readTree = run("git", ["read-tree", "HEAD"], unitWorktree, gitEnv);
315
+ if (readTree.status !== 0)
316
+ throw new Error(readTree.err || "git read-tree failed");
317
+ const add = run("git", ["add", "--", `.b9s-probe-commit-${nonce}`], unitWorktree, gitEnv);
318
+ if (add.status !== 0)
319
+ throw new Error(add.err || "git add failed");
320
+ const commit = run("git", ["-c", "user.name=b9s sandbox probe", "-c", "user.email=probe@invalid", "commit", "--no-verify", "-m", `b9s sandbox probe ${nonce}`], unitWorktree, gitEnv);
321
+ if (commit.status !== 0)
322
+ throw new Error(commit.err || "git commit failed");
323
+ const committedHead = run("git", ["rev-parse", "HEAD"], unitWorktree, env);
324
+ if (committedHead.status !== 0 || !committedHead.out || committedHead.out === oldHead)
325
+ throw new Error("git commit returned without advancing HEAD");
326
+ const restore = run("git", ["update-ref", "HEAD", oldHead, committedHead.out], unitWorktree, env);
327
+ if (restore.status !== 0)
328
+ throw new Error(`probe commit ${committedHead.out} was created but HEAD could not be restored: ${restore.err}`);
329
+ return `created and removed probe commit ${committedHead.out.slice(0, 12)}`;
330
+ });
331
+ // The alternate index leaves the agent's staged and unstaged work untouched; HEAD is
332
+ // compare-and-swap restored after the successful temporary commit.
333
+ rmSync(commitFile, { force: true });
334
+ rmSync(indexFile, { force: true });
335
+ rmSync(`${indexFile}.lock`, { force: true });
336
+ const fetched = run("git", ["fetch", "--no-tags", "origin", "HEAD"], unitWorktree, env, 60_000);
337
+ checks.git_fetch = fetched.status === 0 ? { ok: true } : { ok: false, detail: clip(fetched.err || `git fetch exited ${fetched.status ?? "without a status"}`) };
338
+ }
339
+ else {
340
+ checks.write_unit_worktree = null;
341
+ checks.git_commit = null;
342
+ checks.git_fetch = null;
343
+ }
344
+ checks.write_sibling_checkout = options.siblingCheckout ? createAndRemove(options.siblingCheckout, nonce) : null;
203
345
  if (commonDir) {
204
346
  // Opened for appending and closed: shows whether it could be changed without changing it.
205
347
  checks.write_git_config = observe(() => { closeSync(openSync(join(commonDir, "config"), "a")); });
@@ -214,30 +356,39 @@ export async function runSandboxProbe(options) {
214
356
  checks.net_other_host = await reach(`https://${options.otherHost ?? "example.com"}/`);
215
357
  return {
216
358
  schema: 1, nonce, at: new Date().toISOString(), cli_version: CLI_VERSION, platform: process.platform,
217
- cwd, checkout: options.checkout ?? null,
359
+ cwd, checkout: options.checkout ?? null, unit_worktree: options.unitWorktree ?? null, sibling_checkout: options.siblingCheckout ?? null,
218
360
  git: { toplevel, git_dir: gitDir, common_dir: commonDir, origin_configured: originConfigured?.replace(/\/\/[^@/]*@/, "//") ?? null, origin_effective: originEffective?.replace(/\/\/[^@/]*@/, "//") ?? null },
219
361
  checks,
220
362
  };
221
363
  }
222
364
  export function writeProbeResult(path, result) {
223
- mkdirSync(dirname(path), { recursive: true });
224
- writeFileSync(path, `${JSON.stringify(result, null, 2)}\n`, { mode: 0o600 });
365
+ try {
366
+ mkdirSync(dirname(path), { recursive: true });
367
+ writeFileSync(path, `${JSON.stringify(result, null, 2)}\n`, { mode: 0o600 });
368
+ }
369
+ catch (error) {
370
+ throw new CliError("sandbox_probe_output_failed", `cannot write sandbox probe result to ${path}: ${error.message}`, "Choose a writable path inside the checkout, or omit --out to print the result to stdout.");
371
+ }
225
372
  }
226
- const ACCEPTED_GIT = "accepted limit (2026-11-19): the clone's shared git folder is writable under the checkout's parent; see docs/REMOTE-MACHINES.md";
373
+ const ACCEPTED_GIT = "not measured for this harness yet";
227
374
  const UNMEASURED = "not measured for this harness yet";
228
375
  const CODEX_WORKSPACE_WRITE = "measured 2026-11-19 in Codex workspace-write: writes to the user's home and the Node installation are refused";
229
376
  const CLAUDE_WORKTREE = "measured 2026-11-19 in Claude Code workspace-write: git worktree add is refused because the clone's shared .git/worktrees folder is read-only; the watcher must prepare unit worktrees outside the sandbox";
230
- const CLAUDE_WORKSPACE_WRITE = "measured 2026-11-19 in Claude Code workspace-write: writes to the user's home, Node installation, shared git config and hooks are refused";
377
+ const CLAUDE_WORKSPACE_WRITE = "measured 2026-11-19 in Claude Code workspace-write: writes to the user's home, Node installation, checkout parent, shared git config and hooks are refused";
378
+ const CLAUDE_ORIGIN = "origin transport is machine-specific; git remote read and active-worktree fetch are measured independently";
231
379
  const ANTIGRAVITY_GIT_SCOPE = "Antigravity workspace-write policy: Git objects, refs and logs plus exact active/prepared worktree metadata are writable; arbitrary git worktree add is refused because only exact paths or recursive directories are supported, and recursive registry access would expose siblings. The watcher prepares the unit worktree before the turn; config, hooks, sibling worktrees and the checkout parent stay refused";
232
380
  const ANTIGRAVITY_REF_CLEANUP = "measured 2026-11-20 on Linux Antigravity 1.5.13: branch creation and commit-object writes work, but deleting a ref requires .git/packed-refs.lock under the read-only common Git directory. The watcher removes refs in this probe namespace outside the sandbox after the check; the session does not delete branches";
233
- export function expectedFor(harness, sandbox) {
381
+ export function expectedFor(harness, sandbox, result) {
234
382
  const works = { expected: "works" };
383
+ const otherWorktree = result?.checks.git_other_worktree?.not_applicable
384
+ ? { expected: "not_applicable", note: result.checks.git_other_worktree.detail }
385
+ : { expected: "refused", note: ANTIGRAVITY_GIT_SCOPE };
235
386
  const base = {
236
387
  cwd_is_checkout: works, origin_is_https: { expected: "any", note: UNMEASURED },
237
388
  tool_node: works, tool_npm: works, tool_npx: works, tool_git: works, tool_b9s: works,
238
- git_branch: works, git_branch_delete: works, git_object: works, git_worktree: works, git_other_worktree: { expected: "any", note: UNMEASURED }, git_remote_read: works,
389
+ git_branch: works, git_branch_delete: works, git_object: works, git_worktree: works, git_other_worktree: result?.checks.git_other_worktree?.not_applicable ? otherWorktree : { expected: "any", note: UNMEASURED }, git_remote_read: works,
239
390
  net_api: works, net_other_host: { expected: "any", note: UNMEASURED },
240
- write_checkout: works, write_checkout_parent: works, write_b9s_home: works,
391
+ write_checkout: works, write_checkout_parent: works, write_unit_worktree: { expected: "any", note: "requires --unit-worktree" }, write_sibling_checkout: { expected: "any", note: "requires --sibling-checkout" }, git_commit: { expected: "any", note: "requires --unit-worktree" }, git_fetch: { expected: "any", note: "requires --unit-worktree" }, write_b9s_home: works,
241
392
  write_git_config: { expected: "any", note: ACCEPTED_GIT }, write_git_hooks: { expected: "any", note: ACCEPTED_GIT },
242
393
  write_home: { expected: "any", note: UNMEASURED }, write_node_install: { expected: "any", note: UNMEASURED },
243
394
  };
@@ -256,25 +407,33 @@ export function expectedFor(harness, sandbox) {
256
407
  git_branch_delete: { expected: "refused", note: ANTIGRAVITY_REF_CLEANUP },
257
408
  git_worktree: { expected: "refused", note: ANTIGRAVITY_GIT_SCOPE },
258
409
  write_checkout_parent: { expected: "refused", note: ANTIGRAVITY_GIT_SCOPE },
259
- git_other_worktree: { expected: "refused", note: ANTIGRAVITY_GIT_SCOPE },
410
+ git_other_worktree: otherWorktree,
260
411
  write_git_config: { expected: "refused", note: ANTIGRAVITY_GIT_SCOPE },
261
412
  write_git_hooks: { expected: "refused", note: ANTIGRAVITY_GIT_SCOPE },
262
413
  write_node_install: { expected: "refused" },
263
414
  };
264
415
  }
265
416
  if (harness === "claude-code") {
266
- // Its sandbox proxies HTTP(S) only, so an SSH origin cannot be reached (the reason b9s start
267
- // rewrites it per worktree). On 2026-11-19 workspace-write also refused writes to home, the
417
+ // Origin transport is machine-specific; require the actual remote read below rather than
418
+ // requiring HTTPS. On 2026-11-20, ronald's real SSH origin was readable and fetchable in the
419
+ // live Claude Code workspace-write turn. Workspace-write also refuses writes to home, the
268
420
  // Node installation, shared git config/hooks, and git worktree registration.
269
421
  return {
270
422
  ...base,
271
- origin_is_https: works,
423
+ origin_is_https: { expected: "any", note: CLAUDE_ORIGIN },
424
+ write_checkout_parent: { expected: "refused", note: CLAUDE_WORKSPACE_WRITE },
272
425
  git_worktree: { expected: "refused", note: CLAUDE_WORKTREE },
273
- git_other_worktree: { expected: "any", note: CLAUDE_WORKTREE },
426
+ git_other_worktree: result?.checks.git_other_worktree?.not_applicable ? otherWorktree : { expected: "refused", note: "another agent's linked-worktree Git metadata is outside the active turn's allow-list" },
274
427
  write_git_config: { expected: "refused", note: CLAUDE_WORKSPACE_WRITE },
275
428
  write_git_hooks: { expected: "refused", note: CLAUDE_WORKSPACE_WRITE },
276
429
  write_home: { expected: "refused", note: CLAUDE_WORKSPACE_WRITE },
277
430
  write_node_install: { expected: "refused", note: CLAUDE_WORKSPACE_WRITE },
431
+ ...(result?.unit_worktree ? {
432
+ write_unit_worktree: { expected: "works", note: "the prepared active unit worktree is explicitly allow-listed" },
433
+ git_commit: { expected: "works", note: "the probe creates a temporary commit and restores HEAD" },
434
+ git_fetch: { expected: "works", note: "fetch writes shared Git objects, refs/logs, and FETCH_HEAD" },
435
+ } : {}),
436
+ ...(result?.sibling_checkout ? { write_sibling_checkout: { expected: "refused", note: "sibling checkouts are outside the active turn's allow-list" } } : {}),
278
437
  };
279
438
  }
280
439
  if (harness === "codex")
@@ -295,39 +454,43 @@ export function evaluateProbe(result, expected) {
295
454
  const seen = result.checks[check];
296
455
  const want = expected[check];
297
456
  const observed = seen === null || seen === undefined ? "not run"
298
- : seen.ok ? "works"
299
- : check === "git_branch_delete" ? seen.refusal === "packed-refs-lock-read-only" ? "refused" : "error"
300
- : "refused";
457
+ : seen.not_applicable ? "not applicable"
458
+ : seen.error ? "error"
459
+ : seen.ok ? "works"
460
+ : check === "git_branch_delete" ? seen.refusal === "packed-refs-lock-read-only" ? "refused" : "error"
461
+ : "refused";
301
462
  const detail = seen?.detail ?? seen?.value;
302
463
  if (want.expected === "any") {
303
464
  unjudged.push({ check, expected: "any", observed, ...(detail ? { detail } : {}), ...(want.note ? { note: want.note } : {}) });
304
465
  continue;
305
466
  }
467
+ if (want.expected === "not_applicable" && observed === "not applicable")
468
+ continue;
306
469
  if (observed !== want.expected)
307
470
  failures.push({ check, expected: want.expected, observed, ...(detail ? { detail } : {}) });
308
471
  }
309
472
  return { ok: failures.length === 0, failures, unjudged };
310
473
  }
311
474
  const LABEL = {
312
- cwd_is_checkout: "commands run in the agent's checkout",
475
+ cwd_is_checkout: "commands run in the checkout or active unit worktree",
313
476
  origin_is_https: "origin is reached over HTTPS",
314
477
  tool_node: "node runs", tool_npm: "npm runs", tool_npx: "npx runs", tool_git: "git runs", tool_b9s: "b9s is on PATH",
315
478
  git_branch: "git can create a probe branch", git_branch_delete: "git can delete a branch from inside the session", git_object: "git can write a commit object", git_worktree: "git can add its reserved sandbox probe worktree", git_other_worktree: "another agent's Git worktree metadata is writable", git_remote_read: "git can read origin",
316
479
  net_api: "the BenignSwarm API is reachable", net_other_host: "a host outside the allow-list is reachable",
317
- write_checkout: "the checkout is writable", write_checkout_parent: "the checkout's parent is writable", write_b9s_home: "b9s's own folder is writable",
480
+ write_checkout: "the checkout is writable", write_checkout_parent: "the checkout's parent is writable", write_unit_worktree: "the active unit worktree is writable", write_sibling_checkout: "a sibling checkout is writable", git_commit: "git commit works in the active unit worktree", git_fetch: "git fetch works in the active unit worktree", write_b9s_home: "b9s's own folder is writable",
318
481
  write_git_config: "the clone's git config is writable", write_git_hooks: "the clone's git hooks are writable",
319
482
  write_home: "the home folder is writable", write_node_install: "the Node installation is writable",
320
483
  };
321
484
  export function describeFinding(f) {
322
- const want = f.expected === "works" ? "should work" : "should be refused";
323
- const got = f.observed === "works" ? "it works" : f.observed === "refused" ? "it is refused" : f.observed === "error" ? "the check failed" : "the check could not run";
485
+ const want = f.expected === "works" ? "should work" : f.expected === "refused" ? "should be refused" : f.expected === "not_applicable" ? "should not apply" : "has no expected outcome";
486
+ const got = f.observed === "works" ? "it works" : f.observed === "refused" ? "it is refused" : f.observed === "error" ? "the check failed" : f.observed === "not applicable" ? "it is not applicable" : "the check could not run";
324
487
  return `${LABEL[f.check]}: ${want}, but ${got}${f.detail ? ` (${f.detail})` : ""}`;
325
488
  }
326
489
  export function describeProbe(result) {
327
490
  const lines = [`sandbox probe ${result.nonce} at ${result.at} (b9s ${result.cli_version}, ${result.platform})`, ` ran in ${result.cwd}${result.checkout ? `; expected ${result.checkout}` : ""}`];
328
491
  for (const check of PROBE_CHECKS) {
329
492
  const seen = result.checks[check];
330
- const state = seen === null ? "not run" : seen.ok ? "yes" : seen.refusal ? "refused" : "no";
493
+ const state = seen === null ? "not run" : seen.not_applicable ? "not applicable" : seen.error ? "error" : seen.ok ? "yes" : seen.refusal ? "refused" : "no";
331
494
  lines.push(` ${state.padEnd(7)} ${LABEL[check]}${seen?.detail ? ` (${seen.detail})` : seen?.value ? ` (${seen.value})` : ""}`);
332
495
  }
333
496
  return lines.join("\n");
package/dist/version.js CHANGED
@@ -1 +1 @@
1
- export const CLI_VERSION = "0.12.137";
1
+ export const CLI_VERSION = "0.12.139";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "benignswarm",
3
- "version": "0.12.137",
3
+ "version": "0.12.139",
4
4
  "description": "b9s: chat, status board and evidence store for coding agents (benignswarm.org)",
5
5
  "license": "UNLICENSED",
6
6
  "repository": {