benignswarm 0.12.113 → 0.12.115

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,9 +5,9 @@ import { drainingUntil } from "../maintenance.js";
5
5
  import { probeFor, turnHarness } from "../harnesses.js";
6
6
  import { applyAck } from "./wake.js";
7
7
  import { launchdSessionTypeXml, lingerEnabled, plistLaunchdDomain, loadSystemdUnit, reloadLaunchAgent, removeService, requireInstall, systemdUnit, systemdUserDir, WATCH_LABEL_PREFIX, watcherServices } from "../install.js";
8
- import { existsSync, mkdirSync, readdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
8
+ import { existsSync, mkdirSync, readdirSync, readFileSync, rmSync, statfsSync, writeFileSync } from "node:fs";
9
9
  import { createHash } from "node:crypto";
10
- import { homedir, userInfo } from "node:os";
10
+ import { homedir, totalmem, userInfo } from "node:os";
11
11
  import { basename, dirname, join } from "node:path";
12
12
  import { bool, str } from "../args.js";
13
13
  import { configRoot, loadAgent, resolveAgentName } from "../config.js";
@@ -27,6 +27,8 @@ import { sessionUsage } from "../usage.js";
27
27
  import { collectPruneProtection } from "../prune-protection.js";
28
28
  import { bootTimeMs } from "../boot-time.js";
29
29
  import { DEFAULT_WATCH_STARTUP_JITTER_SECONDS, MAX_WATCH_STARTUP_JITTER_SECONDS, waitForWatcherStartup } from "../startup-jitter.js";
30
+ import { macMemoryFloorRefusal, parseMemoryEvents } from "../watcher-memory.js";
31
+ import { parseMacVmStat, parsePageSize } from "../machine-telemetry.js";
30
32
  function omitMeasuresAlreadyIn(text, updates) {
31
33
  if (!text)
32
34
  return updates;
@@ -725,66 +727,79 @@ export function estimatedTurnCostMicros(reservation, tokens) {
725
727
  const TURN_RETRY_MS = 5 * 60_000;
726
728
  const KEY_CHECK_MS = 5 * 60_000;
727
729
  const MACHINE_PRESSURE_NOTICE_INTERVAL_MS = 30 * 60_000;
728
- /** Respect critical pressure for turns; pressure alone never changes the agent's session or wake state. */
729
- async function machinePressureAllowsTurn(name, env, log, sessionId = env.BSCHAT_MACHINE_SESSION_ID) {
730
- if (!sessionId)
731
- return true;
732
- const prior = readState(name, env).machine_pressure_notice;
733
- let pressure;
730
+ const GiB = 1024 ** 3;
731
+ let lastDiskRefusal = null;
732
+ /**
733
+ * The one machine check before a turn starts (WU #517): the checkout's volume and b9s's own state volume
734
+ * must keep at least 1 GiB and 2% free. Stateless: it reads the volumes each time, holds nothing between
735
+ * polls, and logs only when its answer changes. A full disk truncated three agents' state files on ronald
736
+ * (2026-11-11), which is why this guard stays when machine pressure became advisory.
737
+ */
738
+ export function diskFloorRefusal(paths, statfs = (p) => statfsSync(p)) {
739
+ for (const path of [...new Set(paths)]) {
740
+ let st;
741
+ try {
742
+ st = statfs(path);
743
+ }
744
+ catch (e) {
745
+ // Only a path that no longer exists has no volume to protect; any other failure (EACCES, EIO) means
746
+ // the floor can't be read, which refuses the turn rather than assuming the disk is fine.
747
+ if (e.code === "ENOENT")
748
+ continue;
749
+ return `cannot read free space for ${path}: ${e.code ?? e.message}`;
750
+ }
751
+ const free = Number(st.bavail) * Number(st.bsize);
752
+ const total = Number(st.blocks) * Number(st.bsize);
753
+ const floor = Math.max(GiB, total * 0.02);
754
+ if (free < floor)
755
+ return `the volume holding ${path} has ${(free / GiB).toFixed(1)} GiB free, below its floor of ${(floor / GiB).toFixed(1)} GiB (1 GiB or 2%)`;
756
+ }
757
+ return null;
758
+ }
759
+ /** cgroup-v2 OOM counter for this watcher service, if systemd placed it in a unified hierarchy. */
760
+ export function currentWatcherOomKillCount(readText = (path) => {
734
761
  try {
735
- const response = await Client.forAgent(loadAgent(name, env), undefined, { presence: false }).call("GET", `/agents/me/sessions/${sessionId}/turn-state`);
736
- pressure = response.machine_pressure;
762
+ return readFileSync(path, "utf8");
737
763
  }
738
764
  catch {
739
- // Unavailability cannot clear an established critical hold. For an identity without such a
740
- // hold, the managed turn-policy request below remains independently fail-closed.
741
- return !(prior?.critical_hold || prior?.state === "critical");
742
- }
743
- const state = pressure?.state;
744
- if (!pressure || !state || !["normal", "pressured", "critical", "unknown"].includes(state))
745
- return !(prior?.critical_hold || prior?.state === "critical");
746
- const held = Boolean(pressure?.critical_hold || pressure?.blocks_turns || prior?.critical_hold || prior?.state === "critical");
747
- const freshNormal = state === "normal" && pressure?.freshness === "fresh";
748
- const criticalHold = state === "critical" || (held && !freshNormal);
749
- const recoveryPending = Boolean(prior?.recovery_hold || state === "pressured" || state === "critical");
750
- let resumeAfter = prior?.state === "normal" && !prior.recovery_hold ? prior.resume_after : undefined;
751
- if (freshNormal && recoveryPending) {
752
- // Stable per-identity jitter spreads recovery across a 60-second window without sleeping or
753
- // killing a watcher. Each poll reevaluates the recorded deadline.
754
- let hash = 0;
755
- for (const char of `${name}:${pressure.sample_at ?? ""}`)
756
- hash = (hash * 31 + char.charCodeAt(0)) >>> 0;
757
- resumeAfter = Date.now() + (hash % 60_000);
758
- }
759
- const observedChanged = prior?.state !== state;
760
- let pendingNotice = prior?.pending_notice;
761
- if (observedChanged && (state !== "normal" || (prior && prior.state !== "normal"))) {
762
- pendingNotice = { state, ...(pressure.machine ? { machine: pressure.machine } : {}), ...(pressure.reasons?.length ? { reasons: pressure.reasons.slice(0, 3) } : {}), age_seconds: pressure.age_seconds, ...(prior?.state ? { from_state: prior.state } : {}) };
765
+ return null;
763
766
  }
764
- let lastNoticeAt = prior?.last_notice_at;
765
- if (pendingNotice && (!lastNoticeAt || Date.now() - lastNoticeAt >= MACHINE_PRESSURE_NOTICE_INTERVAL_MS)) {
766
- const machine = pendingNotice.machine ?? "this machine";
767
- const reasons = pendingNotice.reasons?.length ? ` (${pendingNotice.reasons.join(", ")})` : "";
768
- const age = pendingNotice.age_seconds === null || pendingNotice.age_seconds === undefined ? "unknown age" : `${Math.round(pendingNotice.age_seconds)}s old`;
769
- if (pendingNotice.state === "critical")
770
- log(`machine pressure critical on ${machine}${reasons}; last sample ${age}; no new turn starts, session and pending wake are preserved; reevaluating on the next watcher poll`);
771
- else if (pendingNotice.state === "pressured" || pendingNotice.state === "unknown")
772
- log(`machine pressure ${pendingNotice.state} on ${machine}${reasons}; light turns may continue, heavy permits remain paused; last sample ${age}; reevaluating on the next machine sample`);
773
- else if (pendingNotice.from_state && pendingNotice.from_state !== "normal")
774
- log(`machine pressure cleared on ${machine}; staggered turn recovery begins${resumeAfter && resumeAfter > Date.now() ? ` after ${new Date(resumeAfter).toISOString()}` : " now"}`);
775
- lastNoticeAt = Date.now();
776
- pendingNotice = undefined;
767
+ }) {
768
+ const cgroup = readText("/proc/self/cgroup");
769
+ const path = /^0::(\/[\w./@:-]+)$/m.exec(cgroup ?? "")?.[1];
770
+ if (!path || path.split("/").includes(".."))
771
+ return null;
772
+ const events = readText(`/sys/fs/cgroup${path}/memory.events`);
773
+ return events === null ? null : parseMemoryEvents(events)?.oomKill ?? null;
774
+ }
775
+ export function cgroupOomFailureReason(exit, before, after) {
776
+ const failed = exit.signal !== null || exit.code !== 0;
777
+ return failed && before !== undefined && after !== null && after > before
778
+ ? `systemd watcher cgroup OOM-killed the turn (memory.events oom_kill increased from ${before} to ${after})`
779
+ : null;
780
+ }
781
+ function macTurnMemoryFloorRefusal() {
782
+ const pageSizeResult = spawnSync("sysctl", ["-n", "hw.pagesize"], { encoding: "utf8", timeout: 2_000 });
783
+ const vmStatResult = spawnSync("vm_stat", [], { encoding: "utf8", timeout: 2_000 });
784
+ const pageSize = pageSizeResult.status === 0 ? parsePageSize(pageSizeResult.stdout ?? "") : null;
785
+ const memory = vmStatResult.status === 0 ? parseMacVmStat(vmStatResult.stdout ?? "", pageSize) : null;
786
+ return macMemoryFloorRefusal(totalmem(), memory?.available_bytes ?? null);
787
+ }
788
+ function turnMemoryFloorAllows(log) {
789
+ if (process.platform !== "darwin")
790
+ return true;
791
+ const refusal = macTurnMemoryFloorRefusal();
792
+ if (refusal)
793
+ log(`no new turn starts: ${refusal}; turns are checked again on the next poll`);
794
+ return refusal === null;
795
+ }
796
+ function diskFloorAllowsTurn(log, env) {
797
+ const refusal = diskFloorRefusal([process.cwd(), configRoot(env)]);
798
+ if (refusal !== lastDiskRefusal) {
799
+ log(refusal ? `no new turn starts: ${refusal}; free space there to continue` : "disk space is back above its floor; turns may start");
800
+ lastDiskRefusal = refusal;
777
801
  }
778
- writeState(name, { ...readState(name, env), machine_pressure_notice: {
779
- state, ...(pressure.machine ? { machine: pressure.machine } : {}), ...(resumeAfter ? { resume_after: resumeAfter } : {}),
780
- ...(criticalHold ? { critical_hold: true } : {}), ...(recoveryPending && !freshNormal ? { recovery_hold: true } : {}),
781
- ...(lastNoticeAt ? { last_notice_at: lastNoticeAt } : {}), ...(pendingNotice ? { pending_notice: pendingNotice } : {}),
782
- } }, env);
783
- if (criticalHold)
784
- return false;
785
- if (state === "normal" && resumeAfter && Date.now() < resumeAfter)
786
- return false;
787
- return true;
802
+ return refusal === null;
788
803
  }
789
804
  /**
790
805
  * One poll in turn mode. While a turn runs nothing else starts: the turn's own hooks (Stop with new
@@ -793,7 +808,7 @@ async function machinePressureAllowsTurn(name, env, log, sessionId = env.BSCHAT_
793
808
  * leaves the wake-up unacknowledged on the server, so a wake path that keeps failing shows as
794
809
  * broken; one that runs past --turn-timeout is stopped and logged.
795
810
  */
796
- export async function turnStep(ctl, probe, timeoutMin, log, wake, name, turnsPerHour = DEFAULT_TURNS_PER_HOUR, env = process.env, unproductivePerHour = DEFAULT_UNPRODUCTIVE_PER_HOUR, harness) {
811
+ export async function turnStep(ctl, probe, timeoutMin, log, wake, name, turnsPerHour = DEFAULT_TURNS_PER_HOUR, env = process.env, unproductivePerHour = DEFAULT_UNPRODUCTIVE_PER_HOUR, harness, oomKillCounter = currentWatcherOomKillCount) {
797
812
  const debug = (message) => { if (env.BSCHAT_WATCH_DEBUG === "1")
798
813
  log(`debug poll: ${message}`); };
799
814
  const turn = ctl.turn;
@@ -818,6 +833,9 @@ export async function turnStep(ctl, probe, timeoutMin, log, wake, name, turnsPer
818
833
  error = `could not read the harness result: ${e.message}`;
819
834
  }
820
835
  }
836
+ const oomReason = cgroupOomFailureReason(turn.exit, turn.oomKillCountBefore, turn.exit.code !== 0 || turn.exit.signal !== null ? oomKillCounter() : null);
837
+ if (oomReason)
838
+ error = oomReason;
821
839
  if (turn.exit.code === 0 && !error) {
822
840
  if (!turn.confirmed)
823
841
  await ackTurn(name, turn.seq, log, env);
@@ -970,8 +988,12 @@ export async function turnStep(ctl, probe, timeoutMin, log, wake, name, turnsPer
970
988
  debug(`no inbox poll: machine maintenance runs until ${maint.end}`);
971
989
  return;
972
990
  }
973
- if (!(await machinePressureAllowsTurn(name, env, log))) {
974
- debug("no inbox poll: critical machine pressure or staggered recovery is holding new turns; session and pending wake are preserved");
991
+ if (!diskFloorAllowsTurn(log, env)) {
992
+ debug("no inbox poll: a volume is below its disk floor; session and pending wake are preserved");
993
+ return;
994
+ }
995
+ if (!turnMemoryFloorAllows(log)) {
996
+ debug("no inbox poll: the macOS available-memory floor is not met; session and pending wake are preserved");
975
997
  return;
976
998
  }
977
999
  const st = readState(name, env);
@@ -981,8 +1003,18 @@ export async function turnStep(ctl, probe, timeoutMin, log, wake, name, turnsPer
981
1003
  log(`wake-up ${st.watch_pending.seq !== undefined ? `#${st.watch_pending.seq} ` : ""}was never answered and no turn is running; a turn replaces it`);
982
1004
  writeState(name, { ...st, watch_pending: undefined, watch_dormant_logged_at: undefined }, env);
983
1005
  }
984
- await wake((t) => { ctl.turn = t; }, async () => {
985
- return beginTurnGuardAttempt(name, turnsPerHour, log, env, unproductivePerHour, env.BSCHAT_MACHINE_SESSION_ID, harness);
1006
+ let oomKillCountBefore = null;
1007
+ await wake((t) => {
1008
+ if (oomKillCountBefore !== null)
1009
+ t.oomKillCountBefore = oomKillCountBefore;
1010
+ ctl.turn = t;
1011
+ }, async () => {
1012
+ if (!turnMemoryFloorAllows(log))
1013
+ return false;
1014
+ const allowed = await beginTurnGuardAttempt(name, turnsPerHour, log, env, unproductivePerHour, env.BSCHAT_MACHINE_SESSION_ID, harness);
1015
+ if (allowed)
1016
+ oomKillCountBefore = oomKillCounter();
1017
+ return allowed;
986
1018
  });
987
1019
  }
988
1020
  async function turnActivity(name, env) {
@@ -1034,7 +1066,9 @@ export async function beginTurnGuardAttempt(name, turnsPerHour, log, env = proce
1034
1066
  return false;
1035
1067
  }
1036
1068
  }
1037
- if (!(await machinePressureAllowsTurn(name, env, log, machineSessionId)))
1069
+ if (!diskFloorAllowsTurn(log, env))
1070
+ return false;
1071
+ if (!turnMemoryFloorAllows(log))
1038
1072
  return false;
1039
1073
  const before = await turnActivity(name, env);
1040
1074
  current = readState(name, env);
package/dist/container.js CHANGED
@@ -1039,8 +1039,8 @@ export function fetchAwsSecretToEphemeralFile(opts) {
1039
1039
  }
1040
1040
  /**
1041
1041
  * Resolves the most specific Secrets Manager reference (project-scoped before account-wide,
1042
- * matching provider before 'default') and materializes it into an ephemeral 0600 key file
1043
- * only for the duration of process startup, returning cleanup + env bindings without logging values.
1042
+ * matching provider before 'default') and materializes it into an ephemeral 0600 key file.
1043
+ * Callers launching a tracked child retain that file until the child exits, then clean it up.
1044
1044
  */
1045
1045
  export function resolveSessionSecretDelivery(opts) {
1046
1046
  const provider = opts.session.provider ?? "anthropic";
@@ -1048,7 +1048,7 @@ export function resolveSessionSecretDelivery(opts) {
1048
1048
  .filter((x) => x.harness === opts.session.harness && (x.provider === provider || x.provider === "default") && (!x.project_id || x.project_id === opts.session.project_id))
1049
1049
  .sort((a, b) => (b.project_id ? 1 : 0) - (a.project_id ? 1 : 0) || (b.provider === provider ? 1 : 0) - (a.provider === provider ? 1 : 0))[0];
1050
1050
  if (!match)
1051
- return { env: {}, cleanup: () => { } };
1051
+ return { env: {}, files: [], cleanup: () => { } };
1052
1052
  const fetched = fetchAwsSecretToEphemeralFile({
1053
1053
  secretArn: match.secret_arn,
1054
1054
  region: match.region,
@@ -1066,5 +1066,5 @@ export function resolveSessionSecretDelivery(opts) {
1066
1066
  env.ANTHROPIC_API_KEY = value;
1067
1067
  else
1068
1068
  env.B9S_HARNESS_CREDENTIAL_FILE = fetched.path;
1069
- return { env, cleanup: fetched.cleanup };
1069
+ return { env, files: [fetched.path], cleanup: fetched.cleanup };
1070
1070
  }
package/dist/help.js CHANGED
@@ -224,8 +224,9 @@ Machine placement shares capacity across the account's projects: session seats a
224
224
  run an agent headless: enroll, start or adopt its session, turn-mode watcher
225
225
  --machine-session-id is normally supplied by b9s-admin for a managed machine session
226
226
  Persistent watcher startup waits a random logged 0..60 s by default; set --startup-jitter-seconds 0 to disable it for a deterministic start.
227
- At critical machine pressure, the watcher waits before the next turn; running turns and sessions stay in place.
228
- Pressured or unknown telemetry holds heavy permits; ordinary turns remain available.
227
+ Machine pressure is advisory: it is reported, never a reason to hold a turn. A turn is refused only while
228
+ the checkout's or state volume has under 1 GiB or 2% free (checked fresh each time, nothing latched).
229
+ Heavy machine-job permits still wait for normal, fresh telemetry.
229
230
  Claude Code workspace-write defaults to a $1 per-turn cap; configure it with --max-budget-usd
230
231
  Account turn-spend caps are set by the account operator separately; token caps support subscriptions,
231
232
  missing usage remains reserved. Hard caps alone do not enable judgment capture; the account owner explicitly
@@ -270,7 +271,7 @@ Machine placement shares capacity across the account's projects: session seats a
270
271
  JUnit requires context JSON (source, invocation, runner, run); JSON reports include those fields
271
272
  b9s test-results show <run-id> show the stored run, outcome counts, and original report evidence
272
273
  b9s retire --title t (--body b | --body-file f) [--handoff-to @x|@role:y] [--evidence id,id] --yes
273
- save a RESUME or HANDOFF note, announce it, revoke this key; history stays
274
+ save a RESUME or HANDOFF note, revoke keys and remove machine sessions; revival does not restore sessions
274
275
  b9s handoffs [--open] [--agent a] notes left by retired agents (open = not yet picked up)
275
276
  b9s handoffs show <id> | pickup <id>
276
277
  b9s lists [--account] shared lists (open/total, your unread count)
@@ -327,7 +328,7 @@ the returned object and warning, then exits 3. Inspect the object and do not ret
327
328
  b9s-admin agent list <project>
328
329
  b9s-admin agent bench <project>/<agent> [--note <text>] suspend keys and free an active seat
329
330
  b9s-admin agent unbench <project>/<agent> restore keys if a seat is available
330
- b9s-admin agent retire <project>/<agent> [--note <text> | --note-file <file>] --yes revoke keys, release its units, optionally save a resume handoff
331
+ b9s-admin agent retire <project>/<agent> [--note <text> | --note-file <file>] --yes revoke keys, remove machine sessions, release units, optionally save a resume handoff
331
332
  b9s-admin agent away <project>/<agent> (--for <minutes|hours> | --until <ISO timestamp>) --reason "why"
332
333
  b9s-admin agent back <project>/<agent>
333
334
  b9s-admin enroll create <project> [--name n | --prefix p] [--role r] [--uses n] [--expires-hours h] prints the invite text
@@ -401,7 +402,7 @@ Machines (provisioned over your own ssh; a daemon on each runs the agent session
401
402
  b9s-admin machine list | show <name> | remove <name> [--preview] [--confirm <name> --impact-revision <revision>]
402
403
  show includes host readiness, configured disk floors and named readiness refusals; removal previews sessions, work, keys, recovery blockers and replanned slots
403
404
  the API requires a fresh revision for removal
404
- b9s-admin machine companion run <handoff-code> [--confirm <name>] accept a 15-minute, single-use console operation; confirms locally and reports progress
405
+ b9s-admin machine companion run <handoff-code> [--confirm <name>] accept a 15-minute, single-use handoff from Account > Machines; confirms locally and reports progress
405
406
  b9s-admin machine maintenance <name> --at <ISO | HH:MM> --for <30m | 2h> | --cancel a window: no new turns from
406
407
  15 min before, its agents away until the machine reports back after booting
407
408
  b9s-admin machine resize <name> --type <t> [--instance-id <id>] [--drain-timeout 5m] [--yes] [--on-running-turn wait|proceed|abort] [--extend 5m] [--ssh <host>]
@@ -444,7 +445,7 @@ BYO AWS cloud machines (the connection is account-scoped; AWS bills the account
444
445
 
445
446
  Project devcontainer images & immutable registry builds (console controls in WU #377)
446
447
  b9s-admin project image validate --file <.devcontainer/devcontainer.json> [--dockerfile Dockerfile] [--arch linux/amd64|linux/arm64] validate @sha256 pins and reject secrets/host mounts/--privileged
447
- b9s-admin project image config <project> [--path <path>] [--arch linux/amd64|linux/arm64] [--cache name,...] [--pool-sessions on|off] [--registry <ns>] configure immutable per-account image registry, build cache allowlist, and SSH-machine container pool opt-in
448
+ b9s-admin project image config <project> [--path <path>] [--arch linux/amd64|linux/arm64] [--cache name,...] [--pool-sessions on|off] [--registry <ns>] configure immutable per-account image registry, project-scoped writable cache mounts, and SSH-machine container pool opt-in
448
449
  b9s-admin project image show <project> active digest, rollback target, latest build, and image capability probes
449
450
  b9s-admin project image build <project> --commit <sha> --file <.devcontainer/devcontainer.json> [--dockerfile Dockerfile] [--arch <arch>] build only the reviewed declaration commit; machine validation runs its image probes and project test before ready
450
451
  b9s-admin project image activate <project> <sha256:...> explicitly select a ready candidate for future or restarted sessions
@@ -0,0 +1,37 @@
1
+ import { createHash } from "node:crypto";
2
+ import { homedir } from "node:os";
3
+ import { join } from "node:path";
4
+ const CACHE_NAME_RE = /^[a-z0-9][a-z0-9._-]{0,63}$/;
5
+ export function imageCacheBaseDir() {
6
+ return join(homedir(), ".cache", "bschat", "project-image-caches");
7
+ }
8
+ function scopedSegment(kind, id) {
9
+ if (!id.trim())
10
+ throw new Error(`refusing image cache without a ${kind} id`);
11
+ return createHash("sha256").update(`${kind}\0${id}`).digest("hex");
12
+ }
13
+ /** A stable host directory shared only by sessions in the same account and project. */
14
+ export function imageCacheProjectRoot(accountId, projectId, baseDir = imageCacheBaseDir()) {
15
+ return join(baseDir, scopedSegment("account", accountId), scopedSegment("project", projectId));
16
+ }
17
+ export function imageCacheBuildSpecs(accountId, projectId, names, baseDir = imageCacheBaseDir()) {
18
+ return [...new Set(names)].sort().map((name) => {
19
+ if (!CACHE_NAME_RE.test(name))
20
+ throw new Error(`invalid allowed cache name ${JSON.stringify(name)}`);
21
+ return {
22
+ path: join(imageCacheProjectRoot(accountId, projectId, baseDir), name),
23
+ tool: "generic",
24
+ processes: [],
25
+ };
26
+ });
27
+ }
28
+ /** Adds writable image caches to the same declared-cache budget/cleanup path as build caches. */
29
+ export function projectsWithImageCaches(accountId, projects, baseDir = imageCacheBaseDir()) {
30
+ return projects.map((project) => ({
31
+ name: project.name,
32
+ build_caches: [
33
+ ...(project.build_caches ?? []),
34
+ ...imageCacheBuildSpecs(accountId, project.id, project.image?.allowed_caches ?? [], baseDir),
35
+ ],
36
+ }));
37
+ }
package/dist/install.js CHANGED
@@ -1,11 +1,12 @@
1
1
  import { spawnSync } from "node:child_process";
2
2
  import { accessSync, constants, existsSync, lstatSync, mkdirSync, readFileSync, readdirSync, realpathSync, rmSync, statSync, symlinkSync, writeFileSync } from "node:fs";
3
- import { homedir, userInfo } from "node:os";
3
+ import { homedir, totalmem, userInfo } from "node:os";
4
4
  import { basename, delimiter, dirname, join, resolve } from "node:path";
5
5
  import { configRoot } from "./config.js";
6
6
  import { CliError } from "./errors.js";
7
7
  import { cmp } from "./update.js";
8
8
  import { CLI_VERSION } from "./version.js";
9
+ import { watcherMemoryLimits } from "./watcher-memory.js";
9
10
  export const installFile = () => join(configRoot(), "install.json");
10
11
  export function readInstall() {
11
12
  const p = installFile();
@@ -465,9 +466,16 @@ export function rewriteServiceInstall(s, installBin) {
465
466
  if (!/^# bschat-args: .*$/m.test(original) || !/^ExecStart=.*$/m.test(original)) {
466
467
  throw new CliError("service_unreadable", `${s.label} has no recognized service command metadata`);
467
468
  }
468
- const updated = original
469
+ let updated = original
469
470
  .replace(/^# bschat-args: .*$/m, `# bschat-args: ${JSON.stringify(nextArgs)}`)
470
471
  .replace(/^ExecStart=.*$/m, `ExecStart=${nextArgs.map(systemdQuote).join(" ")}`);
472
+ if (s.label.startsWith(WATCH_LABEL_PREFIX)) {
473
+ const limits = watcherMemoryLimits(totalmem());
474
+ if (!limits)
475
+ throw new CliError("memory_limits_unavailable", "cannot determine physical RAM; refusing to leave an uncapped Linux watcher");
476
+ updated = updated.replace(/^Slice=.*\n/gm, "").replace(/^MemoryMax=.*\n/gm, "");
477
+ updated = updated.replace(/^\[Install\]$/m, `Slice=app.slice\nMemoryMax=${limits.unitMaxBytes}\n\n[Install]`);
478
+ }
471
479
  writeFileSync(s.path, updated);
472
480
  return original;
473
481
  }
@@ -516,6 +524,15 @@ export async function restartInstallServices(installBin, services = watcherServi
516
524
  else
517
525
  matching.push(service);
518
526
  }
527
+ if (matching.some((service) => service.kind === "systemd" && service.label.startsWith(WATCH_LABEL_PREFIX))) {
528
+ try {
529
+ ensureWatcherSliceMemoryLimits();
530
+ }
531
+ catch (error) {
532
+ notRestarted.push(`Linux watcher memory limits were not applied; services were not restarted: ${error.message}`);
533
+ return { restarted, not_restarted: notRestarted };
534
+ }
535
+ }
519
536
  const rewritten = [];
520
537
  for (const service of matching) {
521
538
  try {
@@ -560,6 +577,7 @@ export async function restartInstallServices(installBin, services = watcherServi
560
577
  * watcher only, never a Codex turn it started (turns run in their own process group, like on macOS).
561
578
  */
562
579
  export function systemdUnit(label, args, cwd, env, logDir, slug = label.slice(WATCH_LABEL_PREFIX.length)) {
580
+ const memoryLimits = label.startsWith(WATCH_LABEL_PREFIX) ? watcherMemoryLimits(totalmem()) : null;
563
581
  return [
564
582
  `# Written by b9s; re-run its b9s watch ... --service (or b9s codex start) to change it.`,
565
583
  `# bschat-args: ${JSON.stringify(args)}`,
@@ -576,6 +594,7 @@ export function systemdUnit(label, args, cwd, env, logDir, slug = label.slice(WA
576
594
  `RestartPreventExitStatus=78`,
577
595
  `RestartSec=5`,
578
596
  `KillMode=process`,
597
+ ...(memoryLimits ? [`Slice=app.slice`, `MemoryMax=${memoryLimits.unitMaxBytes}`] : []),
579
598
  `StandardOutput=append:${join(logDir, `watch.${slug}.out.log`)}`,
580
599
  `StandardError=append:${join(logDir, `watch.${slug}.err.log`)}`,
581
600
  ``,
@@ -589,6 +608,8 @@ export function loadSystemdUnit(label) {
589
608
  // systemd's own checker first, where it exists: it names the bad line (a quoted WorkingDirectory
590
609
  // once failed only at restart, as "bad unit file setting").
591
610
  const path = join(systemdUserDir(), `${label}.service`);
611
+ if (label.startsWith(WATCH_LABEL_PREFIX))
612
+ ensureWatcherSliceMemoryLimits();
592
613
  const v = spawnSync("systemd-analyze", ["--user", "verify", path], { encoding: "utf8" });
593
614
  if (!v.error && v.status !== 0)
594
615
  throw new CliError("bad_unit", `systemd rejects ${path}`, (v.stderr ?? "").trim().slice(0, 500));
@@ -598,6 +619,22 @@ export function loadSystemdUnit(label) {
598
619
  throw new CliError("systemctl_failed", `systemctl --user ${args.join(" ")} failed`, (r.stderr ?? "").trim());
599
620
  }
600
621
  }
622
+ /** Apply a shared RAM-derived ceiling to all managed agent watcher services on this host. */
623
+ export function ensureWatcherSliceMemoryLimits(ramBytes = totalmem()) {
624
+ const limits = watcherMemoryLimits(ramBytes);
625
+ if (!limits)
626
+ throw new CliError("memory_limits_unavailable", "cannot determine physical RAM; refusing to install an uncapped Linux watcher");
627
+ const sliceDir = join(systemdUserDir(), "app.slice.d");
628
+ mkdirSync(sliceDir, { recursive: true });
629
+ const dropIn = join(sliceDir, "50-b9s-memory.conf");
630
+ writeFileSync(dropIn, `[Slice]\nMemoryHigh=${limits.sliceHighBytes}\nMemoryMax=${limits.sliceMaxBytes}\nMemorySwapMax=0\n`);
631
+ const reload = spawnSync("systemctl", ["--user", "daemon-reload"], { encoding: "utf8" });
632
+ if (reload.status !== 0)
633
+ throw new CliError("systemctl_failed", "systemctl --user daemon-reload failed while applying watcher memory limits", (reload.stderr ?? "").trim());
634
+ const apply = spawnSync("systemctl", ["--user", "set-property", "--runtime", "app.slice", `MemoryHigh=${limits.sliceHighBytes}`, `MemoryMax=${limits.sliceMaxBytes}`, "MemorySwapMax=0"], { encoding: "utf8" });
635
+ if (apply.status !== 0)
636
+ throw new CliError("systemctl_failed", "systemd could not apply MemoryHigh, MemoryMax, and MemorySwapMax to app.slice; Linux watcher installation is refused", (apply.stderr ?? "").trim());
637
+ }
601
638
  /**
602
639
  * Installs and (re)starts a service running `args` from `cwd`: a LaunchAgent on macOS, a systemd user
603
640
  * unit on Linux. Logs go to ~/.b9s/logs/<logName>.{out,err}.log. Returns the definition's path.
@@ -1,3 +1,51 @@
1
+ /** Pair systemd's loaded unit state with the cgroup's measured memory cap and current use. */
2
+ export function measuredWatcherServiceMemoryLimits(units, systemdShow, readText) {
3
+ if (systemdShow === null)
4
+ return { status: "unavailable", services: units.map((unit) => ({ unit, status: "unavailable", control_group: null, configured_memory_max_bytes: null, effective_memory_max_bytes: null, memory_current_bytes: null })) };
5
+ const records = new Map();
6
+ for (const block of systemdShow.trim().split(/\r?\n\s*\r?\n/)) {
7
+ const values = {};
8
+ for (const line of block.split(/\r?\n/)) {
9
+ const at = line.indexOf("=");
10
+ if (at > 0)
11
+ values[line.slice(0, at)] = line.slice(at + 1);
12
+ }
13
+ if (values.Id)
14
+ records.set(values.Id, values);
15
+ }
16
+ const bytes = (raw) => {
17
+ if (raw === "max" || raw === "infinity")
18
+ return "max";
19
+ const parsed = Number(raw);
20
+ return raw && Number.isSafeInteger(parsed) && parsed >= 0 ? parsed : null;
21
+ };
22
+ const services = units.map((unit) => {
23
+ const values = records.get(unit);
24
+ if (!values)
25
+ return { unit, status: "unavailable", control_group: null, configured_memory_max_bytes: null, effective_memory_max_bytes: null, memory_current_bytes: null };
26
+ const configured = bytes(values.MemoryMax);
27
+ const group = values.ControlGroup || null;
28
+ if (!group)
29
+ return { unit, status: "inactive", control_group: null, configured_memory_max_bytes: configured, effective_memory_max_bytes: null, memory_current_bytes: null };
30
+ const components = group.split("/").filter(Boolean);
31
+ if (!group.startsWith("/user.slice/") || !group.includes("/app.slice/") || components.includes("..") || components.at(-1) !== unit) {
32
+ return { unit, status: "unavailable", control_group: null, configured_memory_max_bytes: configured, effective_memory_max_bytes: null, memory_current_bytes: null };
33
+ }
34
+ const prefix = `/sys/fs/cgroup${group}`;
35
+ const effective = bytes(readText(`${prefix}/memory.max`)?.trim());
36
+ const current = bytes(readText(`${prefix}/memory.current`)?.trim());
37
+ return {
38
+ unit,
39
+ status: effective === null ? "unavailable" : "available",
40
+ control_group: group,
41
+ configured_memory_max_bytes: configured,
42
+ effective_memory_max_bytes: effective,
43
+ memory_current_bytes: typeof current === "number" ? current : null,
44
+ };
45
+ });
46
+ const status = services.some((service) => service.status === "unavailable") ? "partial" : "available";
47
+ return { status, services };
48
+ }
1
49
  /** Parse one Linux PSI file without turning a missing some/full line into zero. */
2
50
  export function parsePressureStall(content) {
3
51
  const parseWindow = (kind) => {
@@ -126,6 +174,16 @@ export function machineResourceTelemetry(hostPlatform, readText, pageSizeBytes,
126
174
  ? "/" + components.slice(0, appSlice + 1).join("/") : null;
127
175
  const groupPressure = (kind) => safePath ? parsePressureStall(readText(`/sys/fs/cgroup${safePath}/${kind}.pressure`) ?? "") : null;
128
176
  const groupMemory = groupPressure("memory"), groupCpu = groupPressure("cpu"), groupIo = groupPressure("io");
177
+ const groupLimit = (name) => {
178
+ if (!safePath)
179
+ return null;
180
+ const raw = readText(`/sys/fs/cgroup${safePath}/${name}`)?.trim();
181
+ if (raw === "max")
182
+ return "max";
183
+ const value = Number(raw);
184
+ return raw && Number.isSafeInteger(value) && value >= 0 ? value : null;
185
+ };
186
+ const sliceMemoryLimits = { memory_high_bytes: groupLimit("memory.high"), memory_max_bytes: groupLimit("memory.max"), memory_swap_max_bytes: groupLimit("memory.swap.max") };
129
187
  const groupAvailable = [groupMemory, groupCpu, groupIo].every((value) => value?.some?.avg10 != null) && groupIo?.full?.avg10 != null && groupMemory?.full?.avg10 != null;
130
188
  const swapTotal = linuxMemory?.swap_total_bytes ?? macSwap?.total_bytes ?? null;
131
189
  const swapUsed = linuxMemory?.swap_used_bytes ?? macSwap?.used_bytes ?? null;
@@ -157,6 +215,11 @@ export function machineResourceTelemetry(hostPlatform, readText, pageSizeBytes,
157
215
  memory_pressure: flattenPressure(groupMemory),
158
216
  cpu_pressure: flattenPressure(groupCpu),
159
217
  io_pressure: flattenPressure(groupIo),
218
+ memory_limits: {
219
+ source: safePath,
220
+ status: !linux || legacyCgroup ? "unsupported" : Object.values(sliceMemoryLimits).every((value) => value !== null) ? "available" : "unavailable",
221
+ ...sliceMemoryLimits,
222
+ },
160
223
  },
161
224
  metric_availability: {
162
225
  memory: linux ? (typeof linuxMemory?.total_bytes === "number" && typeof linuxMemory?.available_bytes === "number" ? "available" : "unavailable") : darwin ? (typeof macMemory?.available_bytes === "number" ? "available" : "unavailable") : "unsupported",
package/dist/output.js CHANGED
@@ -53,7 +53,7 @@ export function fmtMessage(m) {
53
53
  export function fmtStatus(s) {
54
54
  const machineWaiting = s.machine_pressure?.waiting === true;
55
55
  const parts = [
56
- `${s.state === "benched" ? "BENCHED " : ""}${s.agent_name}${s.role_name ? `[${s.role_name}]` : ""}${s.away ? ` (away until ${s.away.until}: ${s.away.reason})` : s.usage_limit_until ? ` (usage limit until ${s.usage_limit_until})` : machineWaiting ? s.machine_pressure.blocks_turns ? " (next turn held: critical machine pressure)" : " (waiting: heavy machine permit)" : s.liveness === "quiet" ? " (quiet: harness went silent)" : s.liveness === "unknown" ? " (stale, harness unmonitored)" : s.liveness === "scheduled" ? ` (checks every ${s.checks_every} min, next ${(s.next_check_at ?? "").slice(11, 16)} UTC)` : s.liveness === "missed" ? ` (missed its ${s.checks_every}-min check)` : ""}`,
56
+ `${s.state === "benched" ? "BENCHED " : ""}${s.agent_name}${s.role_name ? `[${s.role_name}]` : ""}${s.away ? ` (away until ${s.away.until}: ${s.away.reason})` : s.usage_limit_until ? ` (usage limit until ${s.usage_limit_until})` : machineWaiting && !s.machine_pressure.blocks_turns ? " (waiting: heavy machine permit)" : s.liveness === "quiet" ? " (quiet: harness went silent)" : s.liveness === "unknown" ? " (stale, harness unmonitored)" : s.liveness === "scheduled" ? ` (checks every ${s.checks_every} min, next ${(s.next_check_at ?? "").slice(11, 16)} UTC)` : s.liveness === "missed" ? ` (missed its ${s.checks_every}-min check)` : ""}`,
57
57
  `state=${s.state ?? "-"}`,
58
58
  s.goal ? `goal="${s.goal}"` : null,
59
59
  s.task ? `task="${s.task}"` : null,
@@ -61,7 +61,8 @@ export function fmtStatus(s) {
61
61
  `model=${s.model ?? "-"}`,
62
62
  s.machine ? `machine=${s.machine}` : null,
63
63
  s.machine_pressure ? `machine_health=${s.machine_pressure.state ?? "unknown"} (sample_age=${typeof s.machine_pressure.age_seconds === "number" ? `${Math.floor(s.machine_pressure.age_seconds)}s` : "unknown"}${s.machine_pressure.reasons?.length ? `; reasons=${s.machine_pressure.reasons.join(",")}` : ""})` : null,
64
- machineWaiting ? `machine_wait=${s.machine_pressure.blocks_turns ? "next_turn_critical_pressure" : "heavy_permit"}` : null,
64
+ // WU #517: pressure is advisory, so an older API's blocks_turns is not rendered as a held turn.
65
+ machineWaiting && !s.machine_pressure.blocks_turns ? "machine_wait=heavy_permit" : null,
65
66
  s.capabilities?.length ? `capabilities=${s.capabilities.map((c) => `${c.name}:${c.ready ? c.version ?? "ok" : c.error ?? "stale/unknown"}`).join(",")}` : null,
66
67
  s.branch ? `branch=${s.branch}${s.dirty ? "*" : ""}@${s.head ?? "?"}` : null,
67
68
  s.worktree ? `worktree=${s.worktree}` : null,
package/dist/version.js CHANGED
@@ -1 +1 @@
1
- export const CLI_VERSION = "0.12.113";
1
+ export const CLI_VERSION = "0.12.115";
@@ -0,0 +1,32 @@
1
+ export const GIB = 1024 ** 3;
2
+ /** Keep a machine-wide reserve while allowing one normal build-heavy turn. */
3
+ export function watcherMemoryLimits(totalBytes) {
4
+ if (!Number.isSafeInteger(totalBytes) || totalBytes <= 0)
5
+ return null;
6
+ return {
7
+ totalBytes,
8
+ sliceHighBytes: Math.floor(totalBytes * 0.75),
9
+ sliceMaxBytes: Math.floor(totalBytes * 0.85),
10
+ unitMaxBytes: Math.floor(totalBytes * 0.30),
11
+ swapMaxBytes: 0,
12
+ };
13
+ }
14
+ export function parseMemoryEvents(content) {
15
+ const values = new Map();
16
+ for (const line of content.split(/\r?\n/)) {
17
+ const match = /^(oom|oom_kill) (\d+)$/.exec(line.trim());
18
+ if (match)
19
+ values.set(match[1], Number(match[2]));
20
+ }
21
+ const oom = values.get("oom"), oomKill = values.get("oom_kill");
22
+ return Number.isSafeInteger(oom) && Number.isSafeInteger(oomKill) ? { oom: oom, oomKill: oomKill } : null;
23
+ }
24
+ export function macMemoryFloorRefusal(totalBytes, availableBytes) {
25
+ if (totalBytes === null || availableBytes === null || !Number.isFinite(totalBytes) || !Number.isFinite(availableBytes) || totalBytes <= 0 || availableBytes < 0) {
26
+ return "cannot read available memory on this Mac";
27
+ }
28
+ const floor = Math.max(2 * GIB, totalBytes * 0.10);
29
+ return availableBytes < floor
30
+ ? `available memory is ${(availableBytes / GIB).toFixed(1)} GiB, below the turn-start floor of ${(floor / GIB).toFixed(1)} GiB (2 GiB or 10% of RAM)`
31
+ : null;
32
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "benignswarm",
3
- "version": "0.12.113",
3
+ "version": "0.12.115",
4
4
  "description": "b9s: chat, status board and evidence store for coding agents (benignswarm.org)",
5
5
  "license": "UNLICENSED",
6
6
  "repository": {