benignswarm 0.12.97 → 0.12.99

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.
@@ -5,7 +5,7 @@ import { arch, cpus, freemem, homedir, hostname, loadavg, platform, tmpdir, tota
5
5
  import { dirname, isAbsolute, join, relative, resolve } from "node:path";
6
6
  import { str } from "../args.js";
7
7
  import { Client } from "../client.js";
8
- import { configRoot, loadAgent, saveAgent } from "../config.js";
8
+ import { configRoot, loadAgent, resolveAgentName, saveAgent } from "../config.js";
9
9
  import { CliError } from "../errors.js";
10
10
  import { BWRAP_APPARMOR_PATH, bwrapAppArmorProfile, CODEX_APPARMOR_PATH, CODEX_MANAGED_DIR, codexAppArmorProfile, codexManagedHooks, isCodexManagedRequirements } from "../harness.js";
11
11
  import { applySparse } from "../git.js";
@@ -24,7 +24,11 @@ import { bootTimeMs } from "../boot-time.js";
24
24
  import { DEFAULT_CACHE_FLOOR_PCT, manageBuildCaches } from "../build-caches.js";
25
25
  import { agentContainerName, agentContainerRunArgs, isolatedBuildCommand, isolatedDevcontainerBuildCommand, isolatedImagePullCommands, isolatedSubprocessEnv, probeImdsIsolation, probeNestedSandbox, readGitIdentity, resolveSessionSecretDelivery, validateDevcontainerSpec, } from "../container.js";
26
26
  import { machineEnvironmentChecks } from "../environment-checks.js";
27
+ import { machineResourceTelemetry, parsePageSize } from "../machine-telemetry.js";
27
28
  import { macReadiness, macReadinessSteps } from "../macos-readiness.js";
29
+ import { authorizeWorktreeScope, redactProcessCommand, scanWorktreeProcesses } from "../machine-processes.js";
30
+ import { collectPruneProtection } from "../prune-protection.js";
31
+ import { pruneProjectWorktrees } from "./worktrees.js";
28
32
  export const machineFile = () => join(configRoot(), "machine.json");
29
33
  export function loadMachine() {
30
34
  const f = machineFile();
@@ -44,8 +48,14 @@ function writeMachineState(s) {
44
48
  * again once with them. 2: the agent's own worktree git folder is writable under workspace-write.
45
49
  * 3: turns get TMPDIR beside the checkout instead of the system's /tmp.
46
50
  */
47
- const START_REV = 6;
48
- export const sessionFingerprint = (s, writable = [], imageDigest = null) => JSON.stringify([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.thread, ...(writable.length ? [writable] : []), ...(imageDigest ? [imageDigest] : []), ...(START_REV > 1 ? [`rev${START_REV}`] : [])]);
51
+ const START_REV = 7;
52
+ 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.thread, ...(writable.length ? [writable] : []), ...(imageDigest ? [imageDigest] : []), ...(START_REV > 1 ? [`rev${START_REV}`] : [])]);
53
+ /** A server thread update must restart the watcher even if a stored fingerprint is unexpectedly stale. */
54
+ export function sessionConfigChanged(s, local, fingerprint) {
55
+ const serverThreadChanged = s.thread !== null && s.thread !== (local?.thread ?? null);
56
+ const serverClearChanged = s.thread === null && !!s.thread_override_at && s.thread_override_at !== local?.thread_override_at;
57
+ return !local || local.fingerprint !== fingerprint || serverThreadChanged || serverClearChanged;
58
+ }
49
59
  /** A clear is distinct from a thread that the server has not received from the machine yet. */
50
60
  export function reconcileThread(s, local) {
51
61
  const clearing = s.thread === null && !!s.thread_override_at && s.thread_override_at !== local?.thread_override_at;
@@ -69,7 +79,7 @@ export function maintenanceReport(drain, sessions) {
69
79
  /** The `b9s start` arguments that bring a session up (adopting its thread or session when known). */
70
80
  export function startArgs(s, thread, writable = []) {
71
81
  return [
72
- "start", "--harness", s.harness, "--as", s.agent, "--sandbox", s.sandbox, "--turn-timeout", String(s.turn_timeout), "--turns-per-hour", String(s.turns_per_hour ?? DEFAULT_TURNS_PER_HOUR), "--unproductive-per-hour", String(s.unproductive_per_hour ?? DEFAULT_UNPRODUCTIVE_PER_HOUR), "--turn-coalesce-seconds", String(s.turn_coalesce_seconds ?? 180), "--json",
82
+ "start", "--harness", s.harness, "--as", s.agent, "--sandbox", s.sandbox, "--turn-timeout", String(s.turn_timeout), "--turns-per-hour", String(s.turns_per_hour ?? DEFAULT_TURNS_PER_HOUR), "--unproductive-per-hour", String(s.unproductive_per_hour ?? DEFAULT_UNPRODUCTIVE_PER_HOUR), "--turn-coalesce-seconds", String(s.turn_coalesce_seconds ?? 180), "--machine-session-id", s.id, "--json",
73
83
  ...((s.provider ?? "anthropic") === "deepseek" ? ["--provider", "deepseek"] : []),
74
84
  ...(s.model ? ["--model", s.model] : []),
75
85
  ...(s.effort ? ["--effort", s.effort] : []),
@@ -80,6 +90,9 @@ export function startArgs(s, thread, writable = []) {
80
90
  const KEY_CHECK_MS = 10 * 60_000;
81
91
  const CAPABILITY_PROBE_MS = 60 * 60_000;
82
92
  const lastCapabilityProbe = new Map();
93
+ const WORKTREE_PRUNE_INTERVAL_MS = 60 * 60_000;
94
+ const lastWorktreePrune = new Map();
95
+ export function resetWorktreePrune() { lastWorktreePrune.clear(); }
83
96
  export function turnFaultSessionFields(fault) {
84
97
  return { turn_fault_at: new Date(fault.at).toISOString() };
85
98
  }
@@ -500,6 +513,7 @@ export async function reconcile(m, log, reportIntervalSeconds = 30, deps) {
500
513
  const client = Client.raw(m.url, m.key);
501
514
  const me = await client.call("GET", "/machines/me");
502
515
  const desired = me.sessions;
516
+ await answerWorktreeProcessQueries(client, desired, me.process_queries ?? [], log, deps?.worktreeProcessScanner ?? scanWorktreeProcesses);
503
517
  if (Array.isArray(me.device_logins)) {
504
518
  handleDeviceLoginRequests(client, me.device_logins, log, deps?.deviceLoginInFlight ?? defaultDeviceLoginInFlight);
505
519
  }
@@ -623,7 +637,7 @@ export async function reconcile(m, log, reportIntervalSeconds = 30, deps) {
623
637
  : writable;
624
638
  const thread = reconcileThread(s, local);
625
639
  const fp = sessionFingerprint({ ...s, thread }, s.sandbox === "workspace-write" ? sessionWritable : [], pinnedImageRef);
626
- const threadChanged = !!local?.thread && !!s.thread && s.thread !== local.thread;
640
+ const configChanged = sessionConfigChanged(s, local, fp);
627
641
  const hostSvc = svc();
628
642
  if (containerMode && hostSvc) {
629
643
  removeService(hostSvc);
@@ -633,8 +647,8 @@ export async function reconcile(m, log, reportIntervalSeconds = 30, deps) {
633
647
  ? isContainerRunning(containerPrereqs.runtime, containerName, runner)
634
648
  : false;
635
649
  const needsLaunch = containerMode
636
- ? (!local || local.fingerprint !== fp || threadChanged || !containerActive)
637
- : (!hostSvc || !local || local.fingerprint !== fp || threadChanged);
650
+ ? (configChanged || !containerActive)
651
+ : (!hostSvc || configChanged);
638
652
  if (needsLaunch) {
639
653
  // A new session's start runs its first turn at once, past the watchers' check: during a
640
654
  // maintenance window it waits. (Adopting a known thread starts no turn, so that proceeds.)
@@ -708,7 +722,7 @@ export async function reconcile(m, log, reportIntervalSeconds = 30, deps) {
708
722
  state.sessions[s.id].unpause_applied = s.unpause_at;
709
723
  log(`${s.agent}: usage-limit pause lifted by the operator`);
710
724
  }
711
- out.push({ id: s.id, state: "running", dir: s.dir, thread: th, watcher: watcherState, last_turn: lastTurnLine(s.agent), ...turnFacts(s.agent, s.harness, th, s.turns_per_hour ?? DEFAULT_TURNS_PER_HOUR) });
725
+ out.push({ id: s.id, state: "running", dir: s.dir, thread: th, watcher: watcherState, last_turn: lastTurnLine(s.agent), turn_judgment: s.turn_judgment ?? null, ...turnFacts(s.agent, s.harness, th, s.turns_per_hour ?? DEFAULT_TURNS_PER_HOUR) });
712
726
  }
713
727
  catch (e) {
714
728
  const error = e.message.slice(0, 1000);
@@ -760,13 +774,63 @@ export async function reconcile(m, log, reportIntervalSeconds = 30, deps) {
760
774
  }
761
775
  const clones = refreshClones(workdir, [...new Set(desired.filter((s) => !s.dir && s.project && s.desired === "running").map((s) => s.project))], log);
762
776
  const actualWorkdir = workdir ?? join(homedir(), "bschat");
777
+ const worktreePrune = [];
778
+ for (const project of projects) {
779
+ const repo = join(actualWorkdir, project.name, "main");
780
+ if (!existsSync(join(repo, ".git")))
781
+ continue;
782
+ const prior = lastWorktreePrune.get(project.id);
783
+ if (prior && Date.now() - prior.at < WORKTREE_PRUNE_INTERVAL_MS) {
784
+ worktreePrune.push(prior.result);
785
+ continue;
786
+ }
787
+ // Record the attempt before network or filesystem work so a failing API cannot cause
788
+ // the daemon's 30-second report loop to repeat a destructive scan.
789
+ const attemptedAt = Date.now();
790
+ const session = desired.find((s) => s.project_id === project.id && s.agent);
791
+ if (!session) {
792
+ const skipped = { project: project.name, repo, status: "skipped", reason: "no project session is available to read pruning protections" };
793
+ lastWorktreePrune.set(project.id, { at: attemptedAt, result: skipped });
794
+ worktreePrune.push(skipped);
795
+ log(`${project.name}: worktree prune skipped: no project session is available`);
796
+ continue;
797
+ }
798
+ try {
799
+ const creds = loadAgent(session.agent);
800
+ const protection = await collectPruneProtection(creds, project.name);
801
+ const result = await pruneProjectWorktrees(creds, project.name, repo, protection, log);
802
+ lastWorktreePrune.set(project.id, { at: attemptedAt, result });
803
+ worktreePrune.push(result);
804
+ }
805
+ catch (error) {
806
+ const skipped = { project: project.name, repo, status: "error", reason: error.message };
807
+ lastWorktreePrune.set(project.id, { at: attemptedAt, result: skipped });
808
+ worktreePrune.push(skipped);
809
+ log(`${project.name}: worktree prune failed safely: ${error.message}`);
810
+ }
811
+ }
763
812
  const workSpace = volumeSpace(actualWorkdir, "workdir");
764
813
  const facts = machineFacts([...providerChecks], actualWorkdir, desired, me.machine?.cache_floor_pct ?? DEFAULT_CACHE_FLOOR_PCT);
765
814
  const environmentChecks = machineEnvironmentChecks({ ...facts, workdir_free_bytes: workSpace?.freeBytes ?? null, workdir_total_bytes: workSpace?.totalBytes ?? null }, writable)
766
815
  .map(({ check, status, observation, remedy, recovery_verified }) => ({ check, status, diagnosis: observation, remedy, recovery_verified, observed_at: new Date().toISOString() }));
816
+ const dirtyClosedWorktrees = worktreePrune.flatMap((result) => Array.isArray(result.dirty_closed) ? result.dirty_closed.filter((item) => typeof item === "string") : []);
817
+ const pruneUnavailable = worktreePrune.some((result) => result.status === "error" || result.status === "skipped");
818
+ const pruneStatus = dirtyClosedWorktrees.length ? "failed" : pruneUnavailable ? "unknown" : "healthy";
819
+ const pruneDiagnosis = [
820
+ ...dirtyClosedWorktrees,
821
+ ...(pruneUnavailable ? ["Closed-unit worktree pruning could not inspect every project clone on this machine."] : []),
822
+ ...(!dirtyClosedWorktrees.length && !pruneUnavailable ? ["No dirty closed-unit worktrees were found."] : []),
823
+ ].join("; ");
824
+ environmentChecks.push({
825
+ check: "closed_unit_dirty_worktree", status: pruneStatus, diagnosis: pruneDiagnosis,
826
+ remedy: pruneStatus === "failed" ? "Review the listed worktrees and preserve or remove their uncommitted changes before pruning." : null,
827
+ recovery_verified: pruneStatus === "healthy", observed_at: new Date().toISOString(),
828
+ });
767
829
  const report = {
768
830
  ...facts, environment_checks: environmentChecks,
769
831
  workdir: actualWorkdir, workdir_free_bytes: workSpace?.freeBytes ?? null, workdir_total_bytes: workSpace?.totalBytes ?? null, clones,
832
+ metric_availability: { ...facts.metric_availability, work_volume: workSpace ? "available" : "unavailable" },
833
+ worktree_prune: worktreePrune,
770
834
  build_caches: buildCaches,
771
835
  // The daemon's own confirmation that it is holding turns back, and how many are still running.
772
836
  maintenance: maintenanceReport(drainingUntil(), out),
@@ -795,6 +859,36 @@ export async function reconcile(m, log, reportIntervalSeconds = 30, deps) {
795
859
  await client.call("PUT", "/machines/me/notices/disk", { text: warning });
796
860
  return { sessions: out, report };
797
861
  }
862
+ export async function answerWorktreeProcessQueries(client, desired, queries, log, scan = scanWorktreeProcesses) {
863
+ for (const query of queries) {
864
+ try {
865
+ const projectPresent = desired.some((session) => session.project_id === query.project_id);
866
+ if (!projectPresent)
867
+ throw new Error("requested worktree is not a session of this project on this machine");
868
+ const authorized = authorizeWorktreeScope(query.worktree, query.project_roots, query.foreign_roots);
869
+ const processes = scan(authorized.worktree, authorized).map((process) => ({
870
+ pid: process.pid,
871
+ parent_pid: process.parent_pid,
872
+ started_at: process.started_at,
873
+ elapsed_seconds: process.elapsed_seconds,
874
+ command: redactProcessCommand(process.command).slice(0, 120),
875
+ cwd: process.cwd,
876
+ listeners: process.listeners.slice(0, 100),
877
+ }));
878
+ await client.call("POST", `/machines/me/process-queries/${encodeURIComponent(query.id)}`, { sampled_at: new Date().toISOString(), processes });
879
+ log(`reported process sample for ${query.worktree} (${processes.length} processes)`);
880
+ }
881
+ catch (error) {
882
+ const message = error.message.slice(0, 500);
883
+ try {
884
+ await client.call("POST", `/machines/me/process-queries/${encodeURIComponent(query.id)}`, { sampled_at: new Date().toISOString(), error: message });
885
+ }
886
+ catch (reportError) {
887
+ log(`could not complete process query ${query.id}: ${reportError.message}`);
888
+ }
889
+ }
890
+ }
891
+ }
798
892
  const git = (args, cwd) => spawnSync("git", args, { cwd, encoding: "utf8", timeout: 600_000 });
799
893
  /**
800
894
  * The checkout of a pool session: the project's repository cloned once per machine under
@@ -1069,24 +1163,6 @@ function lastTurnLine(ref) {
1069
1163
  const lines = readFileSync(f, "utf8").split("\n").filter((l) => /b9s watch\[/.test(l) && /turn #|TURN #|usage limit|pause lifted/.test(l));
1070
1164
  return lines.length ? lines[lines.length - 1].slice(0, 300) : null;
1071
1165
  }
1072
- /** Linux pressure stall information is optional; unsupported hosts report it as unknown. */
1073
- function ioPressure() {
1074
- if (platform() !== "linux")
1075
- return null;
1076
- try {
1077
- const content = readFileSync("/proc/pressure/io", "utf8");
1078
- const avg10 = (kind) => {
1079
- const line = content.split("\n").find((entry) => entry.startsWith(`${kind} `));
1080
- const match = line && /(?:^|\s)avg10=([0-9]+(?:\.[0-9]+)?)(?:\s|$)/.exec(line);
1081
- return match ? Number(match[1]) : null;
1082
- };
1083
- const some = avg10("some"), full = avg10("full");
1084
- return some === null && full === null ? null : { some_avg10: some, full_avg10: full };
1085
- }
1086
- catch {
1087
- return null;
1088
- }
1089
- }
1090
1166
  function volumeSpace(path, label) {
1091
1167
  try {
1092
1168
  const st = statfsSync(existsSync(path) ? path : dirname(path));
@@ -1239,6 +1315,17 @@ export function machineFacts(providersInUse = ["anthropic"], workdirOrOpts, sess
1239
1315
  const dsh = (probes?.dsh ?? (() => dshFacts(platform(), path)))();
1240
1316
  const antigravity = (probes?.antigravity ?? (() => antigravityFacts(path)))();
1241
1317
  const homeSpace = volumeSpace(homedir(), "home");
1318
+ const readTelemetryFile = (path) => { try {
1319
+ return readFileSync(path, "utf8");
1320
+ }
1321
+ catch {
1322
+ return null;
1323
+ } };
1324
+ const pageSize = platform() === "linux" ? parsePageSize(spawnSync("getconf", ["PAGESIZE"], { encoding: "utf8", timeout: 2_000 }).stdout ?? "") : null;
1325
+ const macSwap = platform() === "darwin" ? spawnSync("sysctl", ["-n", "vm.swapusage"], { encoding: "utf8", timeout: 2_000 }).stdout ?? null : null;
1326
+ const telemetry = machineResourceTelemetry(platform(), readTelemetryFile, pageSize, macSwap);
1327
+ const telemetryAvailability = telemetry.metric_availability;
1328
+ const volumeFloorPct = diskFloorPct;
1242
1329
  const req = "/etc/codex/requirements.toml";
1243
1330
  const claude = (probes?.claude ?? (() => claudeReport(path, providersInUse)))();
1244
1331
  const bootedAt = bootTimeMs();
@@ -1249,6 +1336,9 @@ export function machineFacts(providersInUse = ["anthropic"], workdirOrOpts, sess
1249
1336
  const facts = {
1250
1337
  os: platform(), arch: arch(), hostname: hostname(), user: userInfo().username, cpus: cpus().length, mem_total_bytes: totalmem(),
1251
1338
  load: loadavg().map((x) => Math.round(x * 100) / 100), mem_available_bytes: memAvailable(),
1339
+ ...telemetry,
1340
+ volume_floor_pct: volumeFloorPct,
1341
+ metric_availability: { ...telemetryAvailability, home_volume: homeSpace ? "available" : "unavailable" },
1252
1342
  // When this machine last booted: the server ends a maintenance window once the machine is back.
1253
1343
  booted_at: bootedAt === null ? null : new Date(Math.floor(bootedAt / 60_000) * 60_000).toISOString(),
1254
1344
  daemon_path: path,
@@ -1266,7 +1356,6 @@ export function machineFacts(providersInUse = ["anthropic"], workdirOrOpts, sess
1266
1356
  linger: platform() === "linux" ? lingerEnabled() : null,
1267
1357
  disk_free_bytes: homeSpace?.freeBytes ?? null,
1268
1358
  disk_total_bytes: homeSpace?.totalBytes ?? null,
1269
- io_pressure: ioPressure(),
1270
1359
  host_checks: platform() === "linux" ? collectLinuxHostChecks() : null,
1271
1360
  at: new Date().toISOString(),
1272
1361
  };
@@ -1757,6 +1846,36 @@ export function handleDeviceLoginRequests(client, requests, log, inFlight = defa
1757
1846
  }
1758
1847
  export async function machine(p, out) {
1759
1848
  const sub = p.positionals[1];
1849
+ if (sub === "processes") {
1850
+ const creds = loadAgent(resolveAgentName(str(p.flags, "as")));
1851
+ if (!creds.project)
1852
+ throw new CliError("usage", "machine processes requires a project agent session");
1853
+ const worktree = str(p.flags, "worktree");
1854
+ if (!worktree || !isAbsolute(worktree))
1855
+ throw new CliError("usage", "machine processes --worktree <absolute-path> [--as <project>/<agent>] [--json]");
1856
+ const client = Client.forAgent(creds, undefined, { presence: false });
1857
+ const base = `/projects/${encodeURIComponent(creds.project)}/machine-processes`;
1858
+ const request = await client.call("POST", base, { worktree });
1859
+ const deadline = Date.now() + 90_000;
1860
+ let response = null;
1861
+ while (Date.now() < deadline) {
1862
+ response = await client.call("GET", `${base}/${encodeURIComponent(request.machine)}/${encodeURIComponent(request.id)}`);
1863
+ if (response && ["complete", "failed", "expired"].includes(response.status))
1864
+ break;
1865
+ await new Promise((resolve) => setTimeout(resolve, 1_000));
1866
+ }
1867
+ if (!response || response.status === "pending") {
1868
+ const stale = response?.stale ? " The machine's last report is stale." : "";
1869
+ throw new CliError("machine_process_timeout", `machine ${request.machine} did not answer the process query within 90 seconds.${stale}`, "Check the machine daemon and run this query again.");
1870
+ }
1871
+ if (response.status === "expired")
1872
+ throw new CliError("machine_process_expired", `the process query expired before the daemon answered.${response.stale ? " The machine's last sample is stale." : ""}`);
1873
+ if (response.status === "failed" || !response.result || response.result.error)
1874
+ throw new CliError("machine_process_failed", response.result?.error ?? "the machine could not inspect this worktree");
1875
+ const result = { machine: request.machine, worktree, sampled_at: response.result.sampled_at, stale: response.stale, processes: response.result.processes ?? [] };
1876
+ const rows = result.processes.map((proc) => `${String(proc.pid).padEnd(8)} parent ${String(proc.parent_pid).padEnd(8)} started ${proc.started_at} elapsed ${proc.elapsed_seconds}s ${proc.command}\n cwd ${proc.cwd}${proc.listeners.length ? `\n TCP listeners ${proc.listeners.join(", ")}` : ""}`);
1877
+ return out.print(`machine ${request.machine} process sample for ${worktree} at ${result.sampled_at}${result.stale ? " (stale)" : ""}\n${rows.join("\n") || "no processes found"}`, result);
1878
+ }
1760
1879
  if (sub === "bootstrap") {
1761
1880
  const url = str(p.flags, "url") ?? process.env.B9S_URL ?? process.env.BSCHAT_URL;
1762
1881
  if (!url)
@@ -1794,7 +1913,8 @@ export async function machine(p, out) {
1794
1913
  const state = readMachineState();
1795
1914
  const rows = desired.map((s) => {
1796
1915
  const w = watcherServices().find((x) => x.label === watchLabelOf(s.agent));
1797
- return `${s.agent.padEnd(32)} desired ${s.desired.padEnd(8)} watcher ${w ? (serviceActive(w) ? "active" : "inactive") : "none"} ${s.harness}/${s.provider ?? "anthropic"} thread ${state.sessions[s.id]?.thread ?? s.thread ?? "-"} ${s.dir}`;
1916
+ const judgment = s.turn_judgment ? ` judgment ${s.turn_judgment.state}: ${s.turn_judgment.trigger_reasons.join(", ")}` : "";
1917
+ return `${s.agent.padEnd(32)} desired ${s.desired.padEnd(8)} watcher ${w ? (serviceActive(w) ? "active" : "inactive") : "none"} ${s.harness}/${s.provider ?? "anthropic"} thread ${state.sessions[s.id]?.thread ?? s.thread ?? "-"}${judgment} ${s.dir}`;
1798
1918
  });
1799
1919
  return out.print([`machine ${m.name} (${m.url})`, ...rows, rows.length ? "" : "no sessions declared"].join("\n"), { machine: m.name, sessions: desired, local: state });
1800
1920
  }
@@ -1825,6 +1945,6 @@ export async function machine(p, out) {
1825
1945
  await new Promise((r) => setTimeout(r, interval * 1000));
1826
1946
  }
1827
1947
  }
1828
- throw new CliError("usage", "machine bootstrap | run | once | status | prepare | service");
1948
+ throw new CliError("usage", "machine bootstrap | run | once | status | prepare | service | processes --worktree <path>");
1829
1949
  }
1830
1950
  const desiredName = (id) => readMachineState().sessions[id]?.label.replace(WATCH_LABEL_PREFIX, "") ?? id;
@@ -131,6 +131,7 @@ function describeProcess(r) {
131
131
  ` heavy jobs: ${Object.entries(d.heavy_jobs ?? {}).map(([name, job]) => `${name} (${job.memory_gib} GiB; ${job.purpose}; workflows ${job.workflows.join(", ")})`).join("; ") || "none"}`,
132
132
  ` steward: ${d.steward.enabled ? "on" : "off"}, quiet ${d.steward.quiet_minutes} min, summary every ${d.steward.summary_minutes} min, ask the operator after ${d.steward.churn_rounds ? `${d.steward.churn_rounds} rounds on one goal` : "(never)"}`,
133
133
  ` agreements: ${r.process.agreements.length} of 8000 characters; charter: ${(r.process.charter ?? "").length ? `${r.process.charter.length} of 4000 characters` : "none (b9s-admin process charter <project> --file charter.md)"}; send-backs ${d.require_cited_changes === false ? "free-form" : "must cite the clause they fail"}`,
134
+ ...(d.routing_policy ? [` routing: weights ${d.routing_policy.weights?.quality ?? 65}/${d.routing_policy.weights?.time ?? 20}/${d.routing_policy.weights?.cost ?? 15}, target ${d.routing_policy.quality_target_percent ?? "none"}, half-life ${d.routing_policy.recency_half_life_days ?? 30}d, min samples ${d.routing_policy.minimum_sample_count ?? 8}, build explore ${d.routing_policy.build_exploration_budget_percent ?? 10}%${d.routing_policy.build_exploration_paused ? " (paused)" : ""}, review explore ${d.routing_policy.review_exploration_budget_percent ?? 10}%${d.routing_policy.review_exploration_paused ? " (paused)" : ""}`] : []),
134
135
  v.length ? `Tags:` : `No tag vocabulary: every unit goes to the default approver.`,
135
136
  ...v.map((t) => ` #${t.name}: ${t.meaning || "(NO MEANING: workers cannot decide by it)"}${t.require_evidence ? " · evidence" : ""}${t.require_rebased ? " · rebased" : ""}${t.expert_role ? ` · expert ${t.expert_role}` : ""}${t.requires?.length ? ` · requires ${t.requires.join(", ")}` : ""}`),
136
137
  ].join("\n");
@@ -0,0 +1,177 @@
1
+ import { bool, need, str } from "../args.js";
2
+ import { CliError } from "../errors.js";
3
+ function csv(value) {
4
+ return value?.split(",").map((part) => part.trim()).filter(Boolean) ?? [];
5
+ }
6
+ function purposeFlag(p) {
7
+ const purpose = need(p.flags, "purpose").trim();
8
+ if (!purpose)
9
+ throw new CliError("usage", "--purpose must contain non-whitespace text");
10
+ return purpose;
11
+ }
12
+ export async function projectSecrets(rest, p, c, out) {
13
+ const [project, action, secret, ...extra] = rest;
14
+ if (!project || !action)
15
+ throw new CliError("usage", "project secrets <project> list|show|create|rotate|revoke|delete|set ...");
16
+ const base = `/projects/${encodeURIComponent(project)}/secrets`;
17
+ const resolve = async (name) => {
18
+ const listed = await c.call("GET", base);
19
+ const row = (listed.secrets ?? []).find((item) => item.name === name || item.id === name);
20
+ if (!row)
21
+ throw new CliError("not_found", "project secret not found");
22
+ return row.id;
23
+ };
24
+ if (action === "list" && !secret && !extra.length) {
25
+ const result = await c.call("GET", base);
26
+ out.print((result.secrets ?? []).map((item) => `${item.name} ${item.storage_mode} v${item.current_version ?? "—"}${item.revoked_at ? " revoked" : ""}`).join("\n") || "No project secrets.", result);
27
+ return;
28
+ }
29
+ if (action === "create" && secret && !extra.length) {
30
+ const mode = need(p.flags, "storage-mode");
31
+ if (mode !== "hosted" && mode !== "aws_secrets_manager")
32
+ throw new CliError("usage", "--storage-mode must be hosted or aws_secrets_manager");
33
+ const body = {
34
+ name: secret,
35
+ purpose: purposeFlag(p),
36
+ storage_mode: mode,
37
+ selectors: { units: csv(str(p.flags, "units")).map((n) => Number(n)), tags: csv(str(p.flags, "tags")) },
38
+ allowed_hosts: csv(str(p.flags, "hosts")),
39
+ };
40
+ if (mode === "aws_secrets_manager")
41
+ body.reference = { arn: need(p.flags, "arn"), version_id: need(p.flags, "version-id") };
42
+ 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);
44
+ return;
45
+ }
46
+ if (action === "show" && secret && !extra.length) {
47
+ const result = await c.call("GET", `${base}/${encodeURIComponent(await resolve(secret))}`);
48
+ out.print(JSON.stringify(result.secret, null, 2), result);
49
+ return;
50
+ }
51
+ 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;
55
+ }
56
+ if (action === "update" && secret && !extra.length) {
57
+ const body = {};
58
+ const purpose = str(p.flags, "purpose");
59
+ const units = str(p.flags, "units");
60
+ const tags = str(p.flags, "tags");
61
+ const hosts = str(p.flags, "hosts");
62
+ if (purpose !== undefined) {
63
+ const normalizedPurpose = purpose.trim();
64
+ if (!normalizedPurpose)
65
+ throw new CliError("usage", "--purpose must contain non-whitespace text");
66
+ body.purpose = normalizedPurpose;
67
+ }
68
+ if (units !== undefined || tags !== undefined)
69
+ body.selectors = { units: csv(units).map((n) => Number(n)), tags: csv(tags) };
70
+ if (hosts !== undefined)
71
+ body.allowed_hosts = csv(hosts);
72
+ if (!Object.keys(body).length)
73
+ throw new CliError("usage", "project secrets update <name> [--purpose <text>] [--units 1,2] [--tags api] [--hosts host[,host]]");
74
+ const result = await c.call("PATCH", `${base}/${encodeURIComponent(await resolve(secret))}`, body);
75
+ out.print(`Updated definition ${secret}.`, result);
76
+ return;
77
+ }
78
+ if (action === "revoke" && secret && !extra.length) {
79
+ const result = await c.call("POST", `${base}/${encodeURIComponent(await resolve(secret))}/revoke`, {});
80
+ out.print(`Revoked future access to ${secret}.`, result);
81
+ return;
82
+ }
83
+ if (action === "delete" && secret && !extra.length) {
84
+ const result = await c.call("DELETE", `${base}/${encodeURIComponent(await resolve(secret))}`);
85
+ out.print(`Deleted definition ${secret}; customer-owned AWS resources are unchanged.`, result);
86
+ return;
87
+ }
88
+ if (action === "set" && secret && !extra.length && (bool(p.flags, "stdin") || process.stdin.isTTY)) {
89
+ const id = await resolve(secret);
90
+ const result = await c.call("GET", `${base}/${encodeURIComponent(id)}`);
91
+ 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.");
93
+ }
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 });
98
+ return;
99
+ }
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]");
101
+ }
102
+ function decodeSecretValue(bytes) {
103
+ try {
104
+ // Secret bytes are opaque text input: a leading UTF-8 BOM is data, not a signature to strip.
105
+ return new TextDecoder("utf-8", { fatal: true, ignoreBOM: true }).decode(bytes);
106
+ }
107
+ catch {
108
+ throw new CliError("secret_input_invalid_utf8", "Secret input is not valid UTF-8.");
109
+ }
110
+ }
111
+ function removeLastUtf8Character(bytes) {
112
+ if (!bytes.length)
113
+ return;
114
+ let start = bytes.length - 1;
115
+ while (start > 0 && (bytes[start] & 0xc0) === 0x80)
116
+ start--;
117
+ const lead = bytes[start];
118
+ const length = lead >= 0xf0 ? 4 : lead >= 0xe0 ? 3 : lead >= 0xc0 ? 2 : 1;
119
+ bytes.splice(Math.max(start, bytes.length - length), length);
120
+ }
121
+ export async function readSecretValue(fromStdin, input = process.stdin) {
122
+ if (fromStdin) {
123
+ const chunks = [];
124
+ for await (const chunk of input)
125
+ chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
126
+ const value = Buffer.concat(chunks);
127
+ let end = value.length;
128
+ if (value[end - 1] === 0x0a) {
129
+ end--;
130
+ if (end > 0 && value[end - 1] === 0x0d)
131
+ end--;
132
+ }
133
+ return decodeSecretValue(value.subarray(0, end));
134
+ }
135
+ if (!input.isTTY || typeof input.setRawMode !== "function")
136
+ throw new CliError("secret_input_unavailable", "Use --stdin to provide the value without echo.");
137
+ process.stderr.write("Secret value (hidden): ");
138
+ input.setRawMode(true);
139
+ input.resume();
140
+ return new Promise((resolve, reject) => {
141
+ const bytes = [];
142
+ let finished = false;
143
+ const cleanup = () => {
144
+ if (finished)
145
+ return;
146
+ finished = true;
147
+ input.setRawMode(false);
148
+ input.pause();
149
+ input.off("data", onData);
150
+ process.stderr.write("\n");
151
+ };
152
+ const onData = (chunk) => {
153
+ for (const byte of chunk) {
154
+ if (byte === 3) {
155
+ cleanup();
156
+ reject(new CliError("cancelled", "Secret entry cancelled."));
157
+ return;
158
+ }
159
+ if (byte === 13 || byte === 10) {
160
+ cleanup();
161
+ try {
162
+ resolve(decodeSecretValue(Uint8Array.from(bytes)));
163
+ }
164
+ catch (error) {
165
+ reject(error);
166
+ }
167
+ return;
168
+ }
169
+ if (byte === 127 || byte === 8)
170
+ removeLastUtf8Character(bytes);
171
+ else if (byte >= 32)
172
+ bytes.push(byte);
173
+ }
174
+ };
175
+ input.on("data", onData);
176
+ });
177
+ }