benignswarm 0.12.94 → 0.12.95

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.
@@ -1,7 +1,7 @@
1
1
  import { spawn, spawnSync } from "node:child_process";
2
2
  import { createHash } from "node:crypto";
3
- import { closeSync, existsSync, mkdirSync, openSync, readFileSync, readSync, statSync, statfsSync, writeFileSync } from "node:fs";
4
- import { arch, cpus, freemem, homedir, hostname, loadavg, platform, totalmem, uptime, userInfo } from "node:os";
3
+ import { closeSync, existsSync, mkdirSync, mkdtempSync, openSync, readFileSync, readSync, rmSync, statSync, statfsSync, writeFileSync } from "node:fs";
4
+ import { arch, cpus, freemem, homedir, hostname, loadavg, platform, tmpdir, totalmem, userInfo } from "node:os";
5
5
  import { dirname, join } from "node:path";
6
6
  import { str } from "../args.js";
7
7
  import { Client } from "../client.js";
@@ -17,8 +17,11 @@ import { CLI_VERSION } from "../version.js";
17
17
  import { probeCapabilities } from "../capabilities.js";
18
18
  import { diskSpaceNotice } from "../notices.js";
19
19
  import { verifyClaudeProvider } from "../providers.js";
20
- import { resumeTurnGuard } from "../turn-guard.js";
20
+ import { busyTurnPause, DEFAULT_TURNS_PER_HOUR, DEFAULT_UNPRODUCTIVE_PER_HOUR, resumeTurnGuard } from "../turn-guard.js";
21
21
  import { defaultWorkspaceWritableRoots } from "../start-options.js";
22
+ import { antigravityTurnArgs, parseAntigravityJson } from "../antigravity.js";
23
+ import { bootTimeMs } from "../boot-time.js";
24
+ import { manageBuildCaches } from "../build-caches.js";
22
25
  export const machineFile = () => join(configRoot(), "machine.json");
23
26
  export function loadMachine() {
24
27
  const f = machineFile();
@@ -38,8 +41,8 @@ function writeMachineState(s) {
38
41
  * again once with them. 2: the agent's own worktree git folder is writable under workspace-write.
39
42
  * 3: turns get TMPDIR beside the checkout instead of the system's /tmp.
40
43
  */
41
- const START_REV = 5;
42
- export const sessionFingerprint = (s, writable = []) => 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 ?? 20, s.thread, ...(writable.length ? [writable] : []), ...(START_REV > 1 ? [`rev${START_REV}`] : [])]);
44
+ const START_REV = 6;
45
+ export const sessionFingerprint = (s, writable = []) => 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.thread, ...(writable.length ? [writable] : []), ...(START_REV > 1 ? [`rev${START_REV}`] : [])]);
43
46
  /** A clear is distinct from a thread that the server has not received from the machine yet. */
44
47
  export function reconcileThread(s, local) {
45
48
  const clearing = s.thread === null && !!s.thread_override_at && s.thread_override_at !== local?.thread_override_at;
@@ -63,7 +66,7 @@ export function maintenanceReport(drain, sessions) {
63
66
  /** The `b9s start` arguments that bring a session up (adopting its thread or session when known). */
64
67
  export function startArgs(s, thread, writable = []) {
65
68
  return [
66
- "start", "--harness", s.harness, "--as", s.agent, "--sandbox", s.sandbox, "--turn-timeout", String(s.turn_timeout), "--turns-per-hour", String(s.turns_per_hour ?? 20), "--json",
69
+ "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), "--json",
67
70
  ...((s.provider ?? "anthropic") === "deepseek" ? ["--provider", "deepseek"] : []),
68
71
  ...(s.model ? ["--model", s.model] : []),
69
72
  ...(s.effort ? ["--effort", s.effort] : []),
@@ -78,7 +81,7 @@ export function turnFaultSessionFields(fault) {
78
81
  return { turn_fault_at: new Date(fault.at).toISOString() };
79
82
  }
80
83
  /** One pass: make what runs here match what the operator declared, then report. */
81
- export async function reconcile(m, log) {
84
+ export async function reconcile(m, log, reportIntervalSeconds = 30) {
82
85
  const client = Client.raw(m.url, m.key);
83
86
  const me = await client.call("GET", "/machines/me");
84
87
  const desired = me.sessions;
@@ -151,7 +154,7 @@ export async function reconcile(m, log) {
151
154
  const fault = agentState.turn_guard.fault;
152
155
  const detail = fault.reason === "unproductive"
153
156
  ? `${fault.consecutive_unproductive} consecutive turns made no BenignSwarm call; likely cause: ${fault.likely_cause}`
154
- : `the ${fault.turns_last_hour}-turn hourly ceiling was reached; likely cause: ${fault.likely_cause}`;
157
+ : `${fault.unproductive_last_hour} unproductive turns in the rolling hour; likely cause: ${fault.likely_cause}`;
155
158
  const error = `turn mode stopped after ${detail}; estimated tokens spent: ${fault.estimated_tokens}; last turn output: ${fault.output_tail || "(empty)"}`.slice(0, 1000);
156
159
  const w = svc();
157
160
  if (w) {
@@ -222,7 +225,7 @@ export async function reconcile(m, log) {
222
225
  state.sessions[s.id].unpause_applied = s.unpause_at;
223
226
  log(`${s.agent}: usage-limit pause lifted by the operator`);
224
227
  }
225
- out.push({ id: s.id, state: "running", dir: s.dir, thread: th, watcher: w && serviceActive(w) ? "active" : "inactive", last_turn: lastTurnLine(s.agent), ...turnFacts(s.agent, s.harness, th) });
228
+ out.push({ id: s.id, state: "running", dir: s.dir, thread: th, watcher: w && serviceActive(w) ? "active" : "inactive", last_turn: lastTurnLine(s.agent), ...turnFacts(s.agent, s.harness, th, s.turns_per_hour ?? DEFAULT_TURNS_PER_HOUR) });
226
229
  }
227
230
  catch (e) {
228
231
  const error = e.message.slice(0, 1000);
@@ -242,9 +245,38 @@ export async function reconcile(m, log) {
242
245
  delete state.sessions[id];
243
246
  }
244
247
  writeMachineState(state);
248
+ const protectedWorktrees = [...new Set(desired.map((s) => s.dir).filter((d) => Boolean(d)))];
249
+ const buildCaches = manageBuildCaches({
250
+ budgetGb: me.machine?.cache_budget_gb ?? null,
251
+ floorPct: me.machine?.cache_floor_pct ?? null,
252
+ machineCaches: me.machine?.build_caches ?? [],
253
+ projects,
254
+ workdir,
255
+ protectedWorktrees,
256
+ });
257
+ for (const cache of buildCaches.caches) {
258
+ const protectedNote = cache.skipped_protected?.length ? `; retained protected: ${cache.skipped_protected.join(", ")}` : "";
259
+ if (cache.status === "cleaned")
260
+ log(`build cache cleaned ${cache.path} (${cache.volume}): removed ${(cache.removed_bytes / 1e6).toFixed(1)} MB${protectedNote}`);
261
+ else if (cache.status === "skipped_in_use")
262
+ log(`build cache skipped ${cache.path} (in use by ${cache.active_processes.join(", ")})${protectedNote}`);
263
+ else if (cache.status === "skipped_protected")
264
+ log(`build cache skipped ${cache.path} (protected subtrees retained: ${(cache.skipped_protected ?? []).join(", ")})`);
265
+ else if (cache.status === "error")
266
+ log(`build cache error ${cache.path}: ${cache.error}`);
267
+ }
268
+ for (const fault of buildCaches.faults) {
269
+ if (fault.kind === "inspection_incomplete")
270
+ log(`build cache fault on ${fault.volume}: ${fault.reason} (${fault.caches.join(", ")}; uninspected: ${fault.processes.join(", ")})`);
271
+ else
272
+ log(`build cache fault on ${fault.volume} (${fault.free_pct}% < ${fault.floor_pct}% floor): ${fault.caches.join(", ")} in use by ${fault.processes.join(", ")}`);
273
+ }
245
274
  const clones = refreshClones(workdir, [...new Set(desired.filter((s) => !s.dir && s.project && s.desired === "running").map((s) => s.project))], log);
275
+ const actualWorkdir = workdir ?? join(homedir(), "bschat");
276
+ const workSpace = volumeSpace(actualWorkdir, "workdir");
246
277
  const report = {
247
- ...machineFacts([...providerChecks]), workdir: workdir ?? join(homedir(), "bschat"), workdir_free_bytes: freeBytes(workdir ?? homedir()), clones,
278
+ ...machineFacts([...providerChecks]), workdir: actualWorkdir, workdir_free_bytes: workSpace?.freeBytes ?? null, workdir_total_bytes: workSpace?.totalBytes ?? null, clones,
279
+ build_caches: buildCaches,
248
280
  // The daemon's own confirmation that it is holding turns back, and how many are still running.
249
281
  maintenance: maintenanceReport(drainingUntil(), out),
250
282
  };
@@ -262,7 +294,7 @@ export async function reconcile(m, log) {
262
294
  probedProjects.push(project.id);
263
295
  log(`${project.name}: probed ${capabilities[project.id].length} declared capabilities`);
264
296
  }
265
- await client.call("POST", "/machines/me/report", { report, sessions: out, capabilities });
297
+ await client.call("POST", "/machines/me/report", { report, report_interval_seconds: reportIntervalSeconds, sessions: out, capabilities });
266
298
  for (const projectId of probedProjects) {
267
299
  const declaration = projects.find((p) => p.id === projectId);
268
300
  lastCapabilityProbe.set(projectId, { at: Date.now(), signature: JSON.stringify(declaration.capabilities) });
@@ -425,14 +457,14 @@ export function errorText(s) {
425
457
  }
426
458
  }
427
459
  /** Whether the session has a turn running, its process, and a usage-limit pause still in force. */
428
- function turnFacts(agent, harness, thread) {
460
+ function turnFacts(agent, harness, thread, turnCap = DEFAULT_TURNS_PER_HOUR) {
429
461
  const ph = thread ? probeFor(harness, thread, agent).phase() : null;
430
462
  if (!thread || !ph || "missing" in ph)
431
- return { turn: { running: false, since: null }, process: null, paused_until: null, pause_started_at: null };
463
+ return { turn: { running: false, since: null }, process: null, paused_until: null, pause_started_at: null, turn_guard: null };
432
464
  const until = !ph.running ? probeFor(harness, thread, agent).limitUntil(ph.lastError) : null;
433
465
  const unpausedAt = readState(agent).turn_unpaused_at ?? 0;
434
466
  const paused = until && until > Date.now() && Date.parse(ph.lastErrorAt ?? "") > unpausedAt ? new Date(until).toISOString() : null;
435
- return { turn: { running: ph.running, since: ph.running ? ph.startedAt : ph.lastEventAt }, process: ph.running ? turnProcess(thread, harness, undefined, agent) : null, paused_until: paused, pause_started_at: paused ? ph.lastErrorAt : null };
467
+ return { turn: { running: ph.running, since: ph.running ? ph.startedAt : ph.lastEventAt }, process: ph.running ? turnProcess(thread, harness, undefined, agent) : null, paused_until: paused, pause_started_at: paused ? ph.lastErrorAt : null, turn_guard: busyTurnPause(readState(agent).turn_guard, turnCap, Date.now()) };
436
468
  }
437
469
  /** The harness process running a turn of this session (`codex exec resume <thread>`, `claude ... --resume <id>`), from ps. */
438
470
  export function turnProcess(thread, harness = "codex", psOutput, agent) {
@@ -545,10 +577,19 @@ function lastTurnLine(ref) {
545
577
  const lines = readFileSync(f, "utf8").split("\n").filter((l) => /b9s watch\[/.test(l) && /turn #|TURN #|usage limit|pause lifted/.test(l));
546
578
  return lines.length ? lines[lines.length - 1].slice(0, 300) : null;
547
579
  }
548
- function freeBytes(path) {
580
+ /** Linux pressure stall information is optional; unsupported hosts report it as unknown. */
581
+ function ioPressure() {
582
+ if (platform() !== "linux")
583
+ return null;
549
584
  try {
550
- const st = statfsSync(existsSync(path) ? path : dirname(path));
551
- return st.bavail * st.bsize;
585
+ const content = readFileSync("/proc/pressure/io", "utf8");
586
+ const avg10 = (kind) => {
587
+ const line = content.split("\n").find((entry) => entry.startsWith(`${kind} `));
588
+ const match = line && /(?:^|\s)avg10=([0-9]+(?:\.[0-9]+)?)(?:\s|$)/.exec(line);
589
+ return match ? Number(match[1]) : null;
590
+ };
591
+ const some = avg10("some"), full = avg10("full");
592
+ return some === null && full === null ? null : { some_avg10: some, full_avg10: full };
552
593
  }
553
594
  catch {
554
595
  return null;
@@ -573,6 +614,61 @@ export function codexSandbox(force = false, path = process.env.PATH ?? "") {
573
614
  sandboxCache = { at: Date.now(), result, path };
574
615
  return result;
575
616
  }
617
+ const AGY_SANDBOX_PROBE_MS = 10 * 60_000;
618
+ const AGY_SANDBOX_PROBE_MODEL = "gemini-4-hydrogen-low";
619
+ const AGY_SANDBOX_PROBE_RESPONSE = "B9S_SANDBOX_OK";
620
+ let agySandboxCache = null;
621
+ /** Runs one cached no-op turn through Antigravity's real workspace-write terminal sandbox. */
622
+ export function antigravitySandbox(force = false, path = process.env.PATH ?? "") {
623
+ if (!force && agySandboxCache && agySandboxCache.path === path && Date.now() - agySandboxCache.at < AGY_SANDBOX_PROBE_MS)
624
+ return agySandboxCache.result;
625
+ const work = mkdtempSync(join(tmpdir(), "b9s-agy-sandbox-probe-"));
626
+ let result;
627
+ try {
628
+ const marker = join(work, ".b9s-sandbox-probe");
629
+ const quotedMarker = `'${marker.replace(/'/g, `'\\''`)}'`;
630
+ const prompt = `Use your terminal tool once to run exactly: printf '${AGY_SANDBOX_PROBE_RESPONSE}' > ${quotedMarker}. Then reply with exactly ${AGY_SANDBOX_PROBE_RESPONSE}. Do not call any other tool.`;
631
+ const settings = ["--sandbox", "--settings", JSON.stringify({ enableTerminalSandbox: true, toolPermission: "proceed-in-sandbox", permissions: { allow: [] } })];
632
+ const r = spawnSync("agy", antigravityTurnArgs(prompt, AGY_SANDBOX_PROBE_MODEL, undefined, 45, settings), {
633
+ encoding: "utf8", timeout: 60_000, maxBuffer: 1024 * 1024, cwd: work, env: { ...process.env, PATH: path },
634
+ });
635
+ const parsed = parseAntigravityJson(r.stdout ?? "");
636
+ let wroteMarker = false;
637
+ try {
638
+ wroteMarker = readFileSync(marker, "utf8") === AGY_SANDBOX_PROBE_RESPONSE;
639
+ }
640
+ catch { /* a missing marker means the sandbox command did not run */ }
641
+ result = r.status === 0 && parsed?.status === "SUCCESS" && parsed.response?.trim() === AGY_SANDBOX_PROBE_RESPONSE && wroteMarker
642
+ ? { ok: true, error: null }
643
+ : { ok: false, error: r.status !== 0 ? `agy sandbox no-op failed (exit ${r.status ?? "unknown"})` : "agy sandbox no-op did not return the required successful result" };
644
+ }
645
+ finally {
646
+ rmSync(work, { recursive: true, force: true });
647
+ }
648
+ agySandboxCache = { at: Date.now(), result, path };
649
+ return result;
650
+ }
651
+ function antigravityLoginFacts(path) {
652
+ const env = { ...process.env, PATH: path };
653
+ const version = spawnSync("agy", ["--version"], { encoding: "utf8", timeout: 15_000, env });
654
+ if (version.status !== 0)
655
+ return { available: false, version: null, logged_in: false, error: "agy is not installed or --version failed" };
656
+ const models = spawnSync("agy", ["models"], { encoding: "utf8", timeout: 20_000, env, maxBuffer: 1024 * 1024 });
657
+ return {
658
+ available: true,
659
+ version: version.stdout.trim().slice(0, 100) || null,
660
+ logged_in: models.status === 0,
661
+ error: models.status === 0 ? null : "agy models did not succeed; log in interactively with agy on this machine",
662
+ };
663
+ }
664
+ /** Machine facts used by placement; the daemon probes login cheaply and caches the sandbox turn. */
665
+ export function antigravityFacts(path = process.env.PATH ?? "") {
666
+ const facts = antigravityLoginFacts(path);
667
+ return {
668
+ ...facts,
669
+ sandbox: facts.logged_in ? antigravitySandbox(false, path) : null,
670
+ };
671
+ }
576
672
  /** Memory a new process could use: Linux's MemAvailable (free alone undercounts the page cache), else free. */
577
673
  function memAvailable() {
578
674
  if (platform() === "linux") {
@@ -606,30 +702,28 @@ export function machineFacts(providersInUse = ["anthropic"]) {
606
702
  const codex = spawnSync("codex", ["--version"], { encoding: "utf8", env });
607
703
  const login = codex.status === 0 ? spawnSync("codex", ["login", "status"], { encoding: "utf8", env }) : null;
608
704
  const dsh = dshFacts(platform(), path);
609
- let diskFree = null;
610
- try {
611
- const st = statfsSync(homedir());
612
- diskFree = st.bavail * st.bsize;
613
- }
614
- catch {
615
- diskFree = null;
616
- }
705
+ const antigravity = antigravityFacts(path);
706
+ const homeSpace = volumeSpace(homedir(), "home");
617
707
  const req = "/etc/codex/requirements.toml";
618
708
  const claude = claudeReport(path, providersInUse);
709
+ const bootedAt = bootTimeMs();
619
710
  return {
620
711
  os: platform(), arch: arch(), hostname: hostname(), user: userInfo().username, cpus: cpus().length, mem_total_bytes: totalmem(),
621
712
  load: loadavg().map((x) => Math.round(x * 100) / 100), mem_available_bytes: memAvailable(),
622
713
  // When this machine last booted: the server ends a maintenance window once the machine is back.
623
- booted_at: new Date(Math.floor((Date.now() - uptime() * 1000) / 60_000) * 60_000).toISOString(),
714
+ booted_at: bootedAt === null ? null : new Date(Math.floor(bootedAt / 60_000) * 60_000).toISOString(),
624
715
  daemon_path: path,
625
716
  bschat: { version: CLI_VERSION, bin: requireInstall().bin },
626
717
  codex: codex.status === 0 ? { version: codex.stdout.trim(), logged_in: login?.status === 0 && /logged in/i.test(`${login.stdout}${login.stderr}`), login: `${login?.stdout ?? ""}${login?.stderr ?? ""}`.trim().slice(0, 200), account_fingerprint: codexAccountFingerprint(), sandbox: codexSandbox(false, path) } : null,
627
718
  "claude-code": claude,
628
719
  claude_code: claude,
629
720
  dsh,
721
+ antigravity,
630
722
  managed_hooks: existsSync(req) && isCodexManagedRequirements(readFileSync(req, "utf8")),
631
723
  linger: platform() === "linux" ? lingerEnabled() : null,
632
- disk_free_bytes: diskFree,
724
+ disk_free_bytes: homeSpace?.freeBytes ?? null,
725
+ disk_total_bytes: homeSpace?.totalBytes ?? null,
726
+ io_pressure: ioPressure(),
633
727
  at: new Date().toISOString(),
634
728
  };
635
729
  }
@@ -669,6 +763,12 @@ export function prepare(opts = {}) {
669
763
  steps.push(dsh.available
670
764
  ? { step: "dsh", result: "ok", detail: `${dsh.version}, ${dsh.path}` }
671
765
  : { step: "dsh", result: platform() === "linux" ? "skipped" : "failed", detail: dsh.error ?? "DeepSeek Harness dsh CLI is unavailable" });
766
+ const agy = antigravityLoginFacts(daemonPath);
767
+ steps.push(!agy.available
768
+ ? { step: "antigravity login", result: "skipped", detail: "agy is not available on the daemon PATH; install Antigravity and log in interactively before using Antigravity pools" }
769
+ : agy.logged_in
770
+ ? { step: "antigravity login", result: "ok", detail: `${agy.version ?? "agy"}; agy models succeeded` }
771
+ : { step: "antigravity login", result: "failed", detail: `${agy.version ?? "agy"}; agy models did not succeed; log in interactively with agy on this machine` });
672
772
  const codex = spawnSync("codex", ["--version"], { encoding: "utf8", env: daemonEnv });
673
773
  if (codex.status !== 0)
674
774
  steps.push({ step: "codex", result: "failed", detail: "codex is not on PATH; install the Codex CLI (npm i -g @openai/codex) and log in (codex login --device-auth)" });
@@ -794,10 +894,12 @@ export async function machine(p, out) {
794
894
  }
795
895
  if (sub === "run") {
796
896
  const interval = Number(str(p.flags, "interval") ?? "30");
897
+ if (!Number.isFinite(interval) || interval < 1 || interval > 3600)
898
+ throw new CliError("usage", "--interval must be from 1 to 3600 seconds");
797
899
  log(`running every ${interval}s against ${m.url}`);
798
900
  for (;;) {
799
901
  try {
800
- await reconcile(m, log);
902
+ await reconcile(m, log, interval);
801
903
  }
802
904
  catch (e) {
803
905
  log(`pass failed: ${e.message}`);
@@ -7,7 +7,7 @@ import { applyAck } from "./wake.js";
7
7
  import { lingerEnabled, loadSystemdUnit, reloadLaunchAgent, removeService, requireInstall, systemdUnit, systemdUserDir, WATCH_LABEL_PREFIX, watcherServices } from "../install.js";
8
8
  import { existsSync, mkdirSync, readdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
9
9
  import { createHash } from "node:crypto";
10
- import { homedir, uptime, userInfo } from "node:os";
10
+ import { homedir, 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";
@@ -22,9 +22,10 @@ import { formatUpdates, gatherUpdates, reportDelivery } from "./hook.js";
22
22
  import { readState, writeState } from "../state.js";
23
23
  import { probeCapabilities } from "../capabilities.js";
24
24
  import { fetchRecoveryBrief, formatRecoveryBrief, recoveryBriefUnavailableText, recoveryBriefWasDelivered } from "../brief.js";
25
- import { beginGuardedTurn, completeGuardedTurn, DEFAULT_TURNS_PER_HOUR, MAX_TURNS_PER_HOUR, MAX_UNPRODUCTIVE_TURNS } from "../turn-guard.js";
25
+ import { beginGuardedTurn, completeGuardedTurn, DEFAULT_TURNS_PER_HOUR, DEFAULT_UNPRODUCTIVE_PER_HOUR, MAX_TURNS_PER_HOUR, MAX_UNPRODUCTIVE_TURNS } from "../turn-guard.js";
26
26
  import { sessionUsage } from "../usage.js";
27
27
  import { collectPruneProtection } from "../prune-protection.js";
28
+ import { bootTimeMs } from "../boot-time.js";
28
29
  function omitMeasuresAlreadyIn(text, updates) {
29
30
  if (!text)
30
31
  return updates;
@@ -72,8 +73,13 @@ export async function watch(p, out) {
72
73
  const turnsPerHour = Number(str(p.flags, "turns-per-hour") ?? String(DEFAULT_TURNS_PER_HOUR));
73
74
  if (!Number.isInteger(turnsPerHour) || turnsPerHour < 1 || turnsPerHour > MAX_TURNS_PER_HOUR)
74
75
  throw new CliError("usage", `--turns-per-hour must be a whole number between 1 and ${MAX_TURNS_PER_HOUR}`);
76
+ const unproductivePerHour = Number(str(p.flags, "unproductive-per-hour") ?? String(DEFAULT_UNPRODUCTIVE_PER_HOUR));
77
+ if (!Number.isInteger(unproductivePerHour) || unproductivePerHour < 1 || unproductivePerHour > 60)
78
+ throw new CliError("usage", "--unproductive-per-hour must be a whole number between 1 and 60");
75
79
  if (!turnMode && p.flags["turns-per-hour"] !== undefined)
76
80
  throw new CliError("usage", "--turns-per-hour is only used with --turn");
81
+ if (!turnMode && p.flags["unproductive-per-hour"] !== undefined)
82
+ throw new CliError("usage", "--unproductive-per-hour is only used with --turn");
77
83
  const thread = exec ? threadOfExec(exec) : null;
78
84
  // Which harness runs the turns and the session they continue. Codex watchers installed before
79
85
  // 0.12.66 carry neither flag: their thread is in the exec command.
@@ -98,7 +104,7 @@ export async function watch(p, out) {
98
104
  if (providerName === "deepseek" && harness !== "claude-code")
99
105
  throw new CliError("usage", "--provider deepseek requires --harness claude-code");
100
106
  const model = str(p.flags, "model") ?? (providerName === "deepseek" ? "deepseek-flash" : undefined);
101
- turn = { harness, session, timeout: turnTimeout, turnsPerHour, provider: providerName, model };
107
+ turn = { harness, session, timeout: turnTimeout, turnsPerHour, unproductivePerHour, provider: providerName, model };
102
108
  }
103
109
  else if (p.flags.provider !== undefined) {
104
110
  throw new CliError("usage", "--provider is only used with --turn --harness claude-code");
@@ -250,7 +256,7 @@ export async function watch(p, out) {
250
256
  await turnStep(ctl, probe, turnTimeout, log, async (sink, beforeTurn) => {
251
257
  const result = await wakeOnce(name, exec, unackedAfter, followDelay, log, turn?.model ?? str(p.flags, "model"), once, sink, !resumeBriefDelivered, turn?.harness === "claude-code" ? turn.provider : undefined, turn?.harness === "dsh", () => probe.beginTurn?.(), beforeTurn, turn?.harness === "claude-code" ? turn.session : undefined);
252
258
  resumeBriefDelivered = resumeBriefDelivered || result.recoveryBriefDelivered;
253
- }, name, turn?.turnsPerHour ?? turnsPerHour);
259
+ }, name, turn?.turnsPerHour ?? turnsPerHour, process.env, turn?.unproductivePerHour ?? unproductivePerHour);
254
260
  else {
255
261
  const result = await wakeOnce(name, exec, unackedAfter, followDelay, log, str(p.flags, "model"), once, undefined, !resumeBriefDelivered);
256
262
  resumeBriefDelivered = resumeBriefDelivered || result.recoveryBriefDelivered;
@@ -533,7 +539,7 @@ const KEY_CHECK_MS = 5 * 60_000;
533
539
  * leaves the wake-up unacknowledged on the server, so a wake path that keeps failing shows as
534
540
  * broken; one that runs past --turn-timeout is stopped and logged.
535
541
  */
536
- export async function turnStep(ctl, probe, timeoutMin, log, wake, name, turnsPerHour = DEFAULT_TURNS_PER_HOUR, env = process.env) {
542
+ export async function turnStep(ctl, probe, timeoutMin, log, wake, name, turnsPerHour = DEFAULT_TURNS_PER_HOUR, env = process.env, unproductivePerHour = DEFAULT_UNPRODUCTIVE_PER_HOUR) {
537
543
  const turn = ctl.turn;
538
544
  if (turn) {
539
545
  if (!turn.confirmed && probe.startedSince(turn.startedMs)) {
@@ -646,8 +652,8 @@ export async function turnStep(ctl, probe, timeoutMin, log, wake, name, turnsPer
646
652
  }
647
653
  // A turn that started before this machine last booted died with it: no process survives a
648
654
  // reboot, and waiting out the quiet limit would idle the agent for up to --turn-timeout.
649
- const bootedAt = ph.running ? Date.now() - uptime() * 1000 : 0;
650
- if (ph.running && ph.startedAt && Date.parse(ph.startedAt) < bootedAt) {
655
+ const bootedAt = ph.running ? bootTimeMs() : null;
656
+ if (ph.running && ph.startedAt && bootedAt !== null && Date.parse(ph.startedAt) < bootedAt) {
651
657
  if (ctl.loggedRunning !== `boot:${ph.startedAt}`)
652
658
  log(`the turn started at ${ph.startedAt} was cut off when this machine restarted (booted ${new Date(bootedAt).toISOString()}); treating it as ended`);
653
659
  ctl.loggedRunning = `boot:${ph.startedAt}`;
@@ -687,7 +693,7 @@ export async function turnStep(ctl, probe, timeoutMin, log, wake, name, turnsPer
687
693
  writeState(name, { ...st, watch_pending: undefined, watch_dormant_logged_at: undefined }, env);
688
694
  }
689
695
  await wake((t) => { ctl.turn = t; }, async () => {
690
- return beginTurnGuardAttempt(name, turnsPerHour, log, env);
696
+ return beginTurnGuardAttempt(name, turnsPerHour, log, env, unproductivePerHour);
691
697
  });
692
698
  }
693
699
  async function turnActivity(name, env) {
@@ -697,17 +703,20 @@ async function turnActivity(name, env) {
697
703
  return snapshot;
698
704
  }
699
705
  /** Reserve every actual harness launch, including b9s start's onboarding turn. */
700
- export async function beginTurnGuardAttempt(name, turnsPerHour, log, env = process.env) {
706
+ export async function beginTurnGuardAttempt(name, turnsPerHour, log, env = process.env, unproductivePerHour = DEFAULT_UNPRODUCTIVE_PER_HOUR) {
701
707
  const before = await turnActivity(name, env);
702
708
  const current = readState(name, env);
703
709
  if (current.turn_guard?.fault) {
704
710
  log(`TURN MODE FAULT: ${turnFaultSummary(current.turn_guard.fault)}; no further turns until an operator or assigner resumes this session`);
705
711
  return false;
706
712
  }
707
- const begun = beginGuardedTurn(current.turn_guard, turnsPerHour, Date.now(), before.activity_seq);
713
+ const begun = beginGuardedTurn(current.turn_guard, turnsPerHour, Date.now(), before.activity_seq, unproductivePerHour);
708
714
  writeState(name, { ...current, turn_guard: begun.state }, env);
709
715
  if (!begun.start) {
710
- log(`TURN MODE FAULT: ${turnFaultSummary(begun.state.fault)}; no further turns until an operator or assigner resumes this session`);
716
+ if (begun.state.fault)
717
+ log(`TURN MODE FAULT: ${turnFaultSummary(begun.state.fault)}; no further turns until an operator or assigner resumes this session`);
718
+ else
719
+ log(`TURN MODE BUSY, NOT LOOPING: ${begun.state.turns.length}/${turnsPerHour} turns in the rolling hour; estimated tokens spent: ${begun.state.turns.reduce((sum, turn) => sum + turn.estimated_tokens, 0)}; resumes at ${new Date(begun.pause_until).toISOString()}`);
711
720
  return false;
712
721
  }
713
722
  return true;
@@ -766,7 +775,7 @@ export async function completePendingTurnGuard(name, probe, log, outputOverride,
766
775
  log("turn was productive: an agent-key call reached BenignSwarm");
767
776
  }
768
777
  function turnFaultSummary(fault) {
769
- return `${fault.reason === "unproductive" ? `${fault.consecutive_unproductive} consecutive turns made no BenignSwarm call` : `hourly ceiling reached (${fault.turns_last_hour} turns in the last hour)`}; likely cause: ${fault.likely_cause}; estimated tokens spent: ${fault.estimated_tokens}`;
778
+ return `${fault.reason === "unproductive" ? `${fault.consecutive_unproductive} consecutive turns made no BenignSwarm call` : `${fault.unproductive_last_hour} unproductive turns in the rolling hour`}; likely cause: ${fault.likely_cause}; estimated tokens spent: ${fault.estimated_tokens}`;
770
779
  }
771
780
  /** The watcher acknowledges a turn it started: the session shows the agent has the prompt. */
772
781
  async function ackTurn(name, seq, log, env = process.env) {
@@ -890,7 +899,7 @@ function installLaunchd(name, exec, interval, followDelay, extraEnv, activity, o
890
899
  bindSession(sess.kind, sess.id, name);
891
900
  out.print(`Wrote ${path} and (re)loaded it: the watcher is running ${program[0]}.${Object.keys(extraEnv).length ? `\nCaptured env: ${Object.keys(extraEnv).join(", ")} (re-run this command if the harness restarts and these change)` : ""}\nStop it: launchctl bootout gui/$(id -u)/${label}\nLogs: ${logDir}/watch.${slug}.*.log\nCheck it: b9s doctor\nThe watcher runs from ${process.cwd()} so the repo identity file applies.`, { plist: path, label, program: program[0] });
892
901
  }
893
- const turnArgs = (t) => (t ? ["--turn", "--turn-timeout", String(t.timeout), "--turns-per-hour", String(t.turnsPerHour), "--harness", t.harness, "--session", t.session, ...(t.provider === "deepseek" ? ["--provider", t.provider] : []), ...(t.model ? ["--model", t.model] : [])] : []);
902
+ const turnArgs = (t) => (t ? ["--turn", "--turn-timeout", String(t.timeout), "--turns-per-hour", String(t.turnsPerHour), "--unproductive-per-hour", String(t.unproductivePerHour ?? DEFAULT_UNPRODUCTIVE_PER_HOUR), "--harness", t.harness, "--session", t.session, ...(t.provider === "deepseek" ? ["--provider", t.provider] : []), ...(t.model ? ["--model", t.model] : [])] : []);
894
903
  function escapeXml(s) {
895
904
  return s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
896
905
  }
@@ -66,6 +66,11 @@ export function needsRetrospectiveInput(status, events = []) {
66
66
  const lastSubmission = events.reduce((last, event, index) => ["submitted", "resubmitted", "refreshed"].includes(event.type) ? index : last, -1);
67
67
  return events.slice(lastSubmission + 1).some((event) => event.type === "changes_requested");
68
68
  }
69
+ export function assignmentGuidanceOutput(warnings = []) {
70
+ return warnings.length
71
+ ? `\nScope checks and assignment suggestions (advisory; no changes applied):\n${warnings.map((warning) => `- ${warning}`).join("\n")}`
72
+ : "";
73
+ }
69
74
  function retrospectiveEventDetail(event) {
70
75
  const data = event.data ?? {};
71
76
  if (event.type === "changes_requested") {
@@ -221,6 +226,8 @@ export function waitPayload(on, clear, note, partial = "") {
221
226
  * b9s wu classify <n> --tags a,b [--note ...] classifier role only, when the process has that step
222
227
  * b9s wu tags <n> --add a,b --remove c [--note ...] owner before review, a reviewer during it
223
228
  * b9s wu done <n> --merged <sha> after approval; the sha is checked against the target branch
229
+ * b9s wu merge <n> [--note "..."] request the role-checked hosted merge; API only, no local Git state
230
+ * b9s wu merge status <n> read hosted merge operation and audit status
224
231
  * b9s wu abandon <n> [--note ...]
225
232
  * b9s wu note <n> --note "..." [--evidence id]
226
233
  * b9s wu evidence replace <n> <old> <new> [--note "why"]
@@ -446,7 +453,7 @@ export async function wu(p, out) {
446
453
  const scope = await scopeText();
447
454
  const replay = str(p.flags, "replay-of");
448
455
  const r = await client.call("POST", `${base}/assign`, { to, title, scope, tags: unitTags, requires: list("requires"), evidence: list("evidence"), after: afterUnits(), replay_of: replay ? Number(replay) : null, reworks: list("reworks").map(Number), branch: str(p.flags, "branch") ?? null, target: str(p.flags, "target") ?? null, milestone: str(p.flags, "milestone") ?? null, min_tier: str(p.flags, "tier"), hold: !!p.flags.hold, force: bool(p.flags, "force"), ...(reason === undefined ? {} : { reason }), ...(allowLowerTier ? { allow_lower_tier: true } : {}) });
449
- out.print(`${fmt(r.unit)}\n${assignmentDisposition(r.unit, to)}${allowLowerTier ? `\nLower-tier override reason supplied: ${reason.trim()}` : ""}${r.warnings?.length ? `\nScope warnings:\n${r.warnings.map((w) => `- ${w}`).join("\n")}` : ""}`, r);
456
+ out.print(`${fmt(r.unit)}\n${assignmentDisposition(r.unit, to)}${allowLowerTier ? `\nLower-tier override reason supplied: ${reason.trim()}` : ""}${assignmentGuidanceOutput(r.warnings ?? [])}`, r);
450
457
  return;
451
458
  }
452
459
  case "park": {
@@ -772,6 +779,24 @@ export async function wu(p, out) {
772
779
  out.print(fmt(r.unit) + (verifiedRemoteTarget ? `\nverified on ${verifiedRemoteTarget}` : "") + cleanupUnitWorktree(r.unit.worktree, def, !!p.flags["keep-worktree"]), r);
773
780
  return;
774
781
  }
782
+ case "merge": {
783
+ const statusOnly = p.positionals[2] === "status";
784
+ const rawNumber = statusOnly ? p.positionals[3] : p.positionals[2];
785
+ const unitNumber = Number(rawNumber);
786
+ if (!Number.isInteger(unitNumber) || unitNumber < 1)
787
+ throw new CliError("usage", `wu merge ${statusOnly ? "status " : ""}<number>`);
788
+ const path = `${base}/${unitNumber}/merge`;
789
+ const r = statusOnly
790
+ ? await client.call("GET", path)
791
+ : await client.call("POST", path, { ...(str(p.flags, "note") !== undefined ? { note: str(p.flags, "note") } : {}) });
792
+ const operation = r.operation;
793
+ const unit = r.unit;
794
+ const detail = operation
795
+ ? `Hosted merge #${unitNumber}: ${operation.state}${operation.merge_sha ? ` (${operation.merge_sha})` : ""}${operation.error_code ? `; ${operation.error_code}` : ""}`
796
+ : `Hosted merge #${unitNumber}: no merge operation recorded`;
797
+ out.print(`${detail}${unit ? `\nWU #${unitNumber} [${unit.status}]${unit.merged_sha ? ` · merged ${unit.merged_sha}` : ""}` : ""}`, r);
798
+ return;
799
+ }
775
800
  case "abandon": {
776
801
  const r = await client.call("POST", `${base}/${num()}/abandon`, { note: str(p.flags, "note") ?? "" });
777
802
  // Same as done: a clean worktree goes (its branch, and every commit on it, stays).
@@ -949,7 +974,7 @@ export async function wu(p, out) {
949
974
  return;
950
975
  }
951
976
  default:
952
- throw new CliError("usage", "wu open|assign|start [--branch b|--here]|decline|submit|approve|changes|classify|tags|done [--keep-worktree]|abandon|note|ask|rule|propose|show|list");
977
+ throw new CliError("usage", "wu open|assign|start [--branch b|--here]|decline|submit|approve|changes|classify|tags|merge <n>|merge status <n>|done [--keep-worktree]|abandon|note|ask|rule|propose|show|list");
953
978
  }
954
979
  }
955
980
  /** Queued units have no owner; ask the API to reject before any local worktree is made. */
package/dist/git.js CHANGED
@@ -58,19 +58,26 @@ export function scanWorktrees(cwd = process.cwd(), options = {}) {
58
58
  const list = git(["worktree", "list", "--porcelain"], cwd);
59
59
  if (list === null)
60
60
  return null;
61
- const paths = list.split("\n").filter((l) => l.startsWith("worktree ")).map((l) => l.slice(9));
62
- if (!paths.length)
61
+ const entries = list.split(/\n\n/).map((block) => {
62
+ const lines = block.split("\n");
63
+ const worktree = lines.find((line) => line.startsWith("worktree "));
64
+ if (!worktree)
65
+ return null;
66
+ const lock = lines.find((line) => line === "locked" || line.startsWith("locked "));
67
+ return { path: worktree.slice(9), locked: lock ? lock.slice("locked".length).trim() || "locked" : null };
68
+ }).filter((entry) => entry !== null);
69
+ if (!entries.length)
63
70
  return null;
64
- const repo = paths[0];
71
+ const repo = entries[0].path;
65
72
  options.onProgress?.(`Scanning repository ${repo}`);
66
- const worktrees = paths.map((p) => {
73
+ const worktrees = entries.map(({ path: p, locked }) => {
67
74
  options.onProgress?.(`Scanning worktree ${p}`);
68
75
  const branch = git(["symbolic-ref", "--short", "-q", "HEAD"], p) ?? git(["rev-parse", "--short", "HEAD"], p);
69
76
  const head = git(["rev-parse", "--short", "HEAD"], p);
70
77
  const worktreeStatus = status(p, options.statusTimeoutMs);
71
78
  const f = head ? mergeFacts(p, p) : { base: null, merged: null, ahead: null };
72
79
  const empty = existsSync(p) && readdirSync(p).every((e) => e === ".git");
73
- return { path: p, branch, head, dirty: worktreeStatus === null ? null : worktreeStatus.length > 0, base: f.base, merged: f.merged, ahead: f.ahead, empty };
80
+ return { path: p, branch, head, dirty: worktreeStatus === null ? null : worktreeStatus.length > 0, base: f.base, merged: f.merged, ahead: f.ahead, empty, locked };
74
81
  });
75
82
  return { repo, worktrees };
76
83
  }
@@ -366,6 +373,13 @@ export function pruneReport(cwd = process.cwd(), closedUnitPaths = new Map(), ac
366
373
  kept.push({ path: w.path, branch: w.branch, reason: "you are standing in it" });
367
374
  continue;
368
375
  }
376
+ // Git locks are an explicit operator/agent retention request. Preserve the reason in both
377
+ // report modes; an interrupted add's `locked: initializing` still follows the empty-checkout
378
+ // cleanup path below.
379
+ if (w.locked && !/^initializing\b/i.test(w.locked)) {
380
+ kept.push({ path: w.path, branch: w.branch, reason: `locked: ${w.locked}` });
381
+ continue;
382
+ }
369
383
  const worktreePath = realpathOrSelf(w.path);
370
384
  const use = options.inUse?.find((entry) => {
371
385
  if (!isAbsolute(entry.path))