benignswarm 0.12.142 → 0.12.144

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.
@@ -7,6 +7,9 @@ import { repoDirectory } from "./directories.js";
7
7
  import { CliError } from "./errors.js";
8
8
  import { gitSandboxDeniedPaths, gitSandboxWritablePaths, sandboxProbeWorktreeAdminPath } from "./git-sandbox-paths.js";
9
9
  export const ANTIGRAVITY_SETTINGS_PLACEHOLDER = "__B9S_ANTIGRAVITY_TURN_SETTINGS__";
10
+ export function isAntigravityWorkspaceWrite(env = process.env) {
11
+ return env.BSCHAT_HARNESS === "antigravity" && env.BSCHAT_ANTIGRAVITY_SANDBOX === "workspace-write";
12
+ }
10
13
  export function antigravityTotalTokens(usage) {
11
14
  if (!usage)
12
15
  return null;
@@ -15,7 +15,7 @@ import { bool, str } from "../args.js";
15
15
  import { agentRef, configRoot, loadAgent, resolveAgentName } from "../config.js";
16
16
  import { Client } from "../client.js";
17
17
  import { heartbeatIfActive, reportWatcherHeartbeat, resolveActivitySource } from "../heartbeat.js";
18
- import { scanProject, unitWorktrees } from "./worktrees.js";
18
+ import { cleanupDeferredUnitWorktree, scanProject, unitWorktrees } from "./worktrees.js";
19
19
  import { branchAndHead, formatBytes, freeSpaceProbe, pruneReport, removePrunable } from "../git.js";
20
20
  import { CliError } from "../errors.js";
21
21
  import { claudeTurnEnv } from "../providers.js";
@@ -349,7 +349,7 @@ export async function watch(p, out, dependencies = {}) {
349
349
  const wakeDependencies = { ...dependencies.wakeOnceDependencies, ...(turn?.claudeRuntime ? { claudeRuntime: turn.claudeRuntime } : {}), ...(turn?.antigravityRuntime ? { antigravityRuntime: turn.antigravityRuntime } : {}) };
350
350
  const result = await (dependencies.wakeOnce ?? wakeOnce)(name, exec, unackedAfter, followDelay, log, turn?.model ?? str(p.flags, "model"), once, sink, !resumeBriefDelivered, turn?.harness === "claude-code" ? turn.provider : undefined, turn?.harness === "dsh", () => activeProbe.beginTurn?.(), beforeTurn, turn?.harness === "claude-code" ? turn.session : undefined, turn?.coalesceSeconds ?? 0, wakeDependencies);
351
351
  resumeBriefDelivered = resumeBriefDelivered || result.recoveryBriefDelivered;
352
- }, name, turn?.turnsPerHour ?? turnsPerHour, process.env, turn?.unproductivePerHour ?? unproductivePerHour, turn?.harness);
352
+ }, name, turn?.turnsPerHour ?? turnsPerHour, process.env, turn?.unproductivePerHour ?? unproductivePerHour, turn?.harness, currentWatcherOomKillCount, turn?.antigravityRuntime?.sandbox);
353
353
  else {
354
354
  const result = await (dependencies.wakeOnce ?? wakeOnce)(name, exec, unackedAfter, followDelay, log, str(p.flags, "model"), once, undefined, !resumeBriefDelivered, undefined, false, undefined, undefined, undefined, 0, dependencies.wakeOnceDependencies);
355
355
  resumeBriefDelivered = resumeBriefDelivered || result.recoveryBriefDelivered;
@@ -1043,7 +1043,7 @@ function diskFloorAllowsTurn(log, env) {
1043
1043
  * leaves the wake-up unacknowledged on the server, so a wake path that keeps failing shows as
1044
1044
  * broken; one that runs past --turn-timeout is stopped and logged.
1045
1045
  */
1046
- 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) {
1046
+ 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, antigravitySandbox) {
1047
1047
  const debug = (message) => { if (env.BSCHAT_WATCH_DEBUG === "1")
1048
1048
  log(`debug poll: ${message}`); };
1049
1049
  const turn = ctl.turn;
@@ -1106,6 +1106,44 @@ export async function turnStep(ctl, probe, timeoutMin, log, wake, name, turnsPer
1106
1106
  ctl.failedAt = Date.now();
1107
1107
  }
1108
1108
  if (harness === "antigravity") {
1109
+ if (antigravitySandbox === "workspace-write") {
1110
+ try {
1111
+ const pending = readState(name, env).watcher_worktree_cleanups ?? [];
1112
+ const completed = [];
1113
+ for (const closure of pending) {
1114
+ try {
1115
+ const cleanup = await cleanupDeferredUnitWorktree(loadAgent(name), closure, process.cwd());
1116
+ if (cleanup.retry) {
1117
+ log(`Antigravity turn cleanup kept WU #${closure.work_unit_number} for retry: ${cleanup.reason}`);
1118
+ }
1119
+ else {
1120
+ log(cleanup.removed
1121
+ ? `Antigravity turn cleanup WU #${closure.work_unit_number}: ${cleanup.reason}`
1122
+ : `Antigravity turn cleanup did not remove WU #${closure.work_unit_number}: ${cleanup.reason}`);
1123
+ completed.push(closure.id);
1124
+ }
1125
+ }
1126
+ catch (e) {
1127
+ log(`Antigravity turn worktree cleanup failed outside the session sandbox for WU #${closure.work_unit_number}: ${e.message}`);
1128
+ }
1129
+ }
1130
+ if (completed.length) {
1131
+ const finished = new Set(completed);
1132
+ try {
1133
+ updateState(name, (state) => ({
1134
+ ...state,
1135
+ watcher_worktree_cleanups: (state.watcher_worktree_cleanups ?? []).filter((closure) => !finished.has(closure.id)),
1136
+ }), env);
1137
+ }
1138
+ catch (e) {
1139
+ log(`Antigravity turn cleanup receipts could not be cleared from watcher state: ${e.message}`);
1140
+ }
1141
+ }
1142
+ }
1143
+ catch (e) {
1144
+ log(`Antigravity turn cleanup queue could not be read outside the session sandbox: ${e.message}`);
1145
+ }
1146
+ }
1109
1147
  try {
1110
1148
  const removed = cleanupAntigravitySandboxProbeRefs(process.cwd(), agentRef(loadAgent(name)), env);
1111
1149
  if (removed.length)
@@ -4,13 +4,47 @@ import { Client } from "../client.js";
4
4
  import { loadAgent, resolveAgentName } from "../config.js";
5
5
  import { CliError } from "../errors.js";
6
6
  import { spawnSync } from "node:child_process";
7
- import { archiveWorktreeChanges, defaultMachine, formatBytes, freeSpaceProbe, scanWorktrees, pruneReport, removePrunable, PRUNE_STATUS_TIMEOUT_MS } from "../git.js";
7
+ import { archiveWorktreeChanges, defaultMachine, formatBytes, freeSpaceProbe, scanWorktrees, pruneReport, removePrunable, removeWorktreeIfClean, worktreeState, PRUNE_STATUS_TIMEOUT_MS } from "../git.js";
8
8
  import { table } from "../output.js";
9
9
  import { collectPruneProtection } from "../prune-protection.js";
10
10
  import { sweepClosedHarnessServers } from "../harness-server-sweep.js";
11
+ import { isAntigravityWorkspaceWrite } from "../antigravity.js";
11
12
  const CLOSED = ["done", "abandoned", "superseded"];
12
13
  const PRUNE_UNIT_STATES_TIMEOUT_MS = 30_000;
13
14
  const WORKTREE_SCAN_TIMEOUT_MS = 30_000;
15
+ /** Remove only the exact clean worktree recorded for a successful close, outside the Antigravity sandbox. */
16
+ export async function cleanupDeferredUnitWorktree(creds, closure, cwd = process.cwd()) {
17
+ const number = closure.work_unit_number;
18
+ if (closure.keep_worktree)
19
+ return { removed: false, retry: false, reason: "--keep-worktree was requested" };
20
+ const record = await Client.forAgent(creds, undefined, { presence: false }).call("GET", `/projects/${encodeURIComponent(closure.project)}/work-units/${number}`);
21
+ const unit = record.unit;
22
+ if (unit?.number !== number)
23
+ return { removed: false, retry: false, reason: "the server returned a different work unit" };
24
+ if (unit.status !== "done")
25
+ return { removed: false, retry: false, reason: `WU #${number} is ${unit.status}, not done` };
26
+ if (typeof unit.worktree !== "string" || !unit.worktree)
27
+ return { removed: false, retry: false, reason: "the unit has no recorded worktree" };
28
+ if (!existsSync(unit.worktree))
29
+ return { removed: false, retry: false, reason: "the recorded worktree path no longer exists" };
30
+ const path = realpathSync(unit.worktree);
31
+ const expectedPath = existsSync(closure.worktree) ? realpathSync(closure.worktree) : null;
32
+ if (path !== expectedPath)
33
+ return { removed: false, retry: false, reason: "the unit worktree no longer matches the exact deferred closure" };
34
+ if ((unit.branch ?? null) !== closure.branch)
35
+ return { removed: false, retry: false, reason: "the unit branch no longer matches the exact deferred closure" };
36
+ if (path === realpathSync(cwd))
37
+ return { removed: false, retry: false, reason: "the worktree is the watcher checkout" };
38
+ const state = worktreeState(path, cwd);
39
+ if (state.state !== "ready")
40
+ return { removed: false, retry: false, reason: state.state === "partial" ? state.reason : "the recorded path is not a linked worktree" };
41
+ if (state.branch !== closure.branch)
42
+ return { removed: false, retry: false, reason: `the linked worktree is on ${state.branch ?? "a detached head"}, not ${closure.branch ?? "the recorded detached head"}` };
43
+ const result = removeWorktreeIfClean(path, cwd);
44
+ return result.removed
45
+ ? { removed: true, retry: false, reason: "removed the clean closed unit worktree; its branch was kept" }
46
+ : { removed: false, retry: true, reason: result.reason ?? "Git refused removal" };
47
+ }
14
48
  async function timedClientCall(client, method, path, body, timeoutMs, operation) {
15
49
  const controller = new AbortController();
16
50
  let timedOut = false;
@@ -112,6 +146,9 @@ export async function pruneProjectWorktrees(creds, project, cwd, protection, log
112
146
  */
113
147
  export async function worktrees(p, out, timeouts = {}) {
114
148
  const sub = p.positionals[1];
149
+ if (sub === "prune" && isAntigravityWorkspaceWrite()) {
150
+ throw new CliError("antigravity_cleanup_owner", "b9s worktrees prune is refused in Antigravity workspace-write because the shared Git worktree registry is read-only; the watcher processes queued wu done worktrees at turn finalization, and retained or abandoned worktrees must be pruned from an unrestricted checkout");
151
+ }
115
152
  const name = resolveAgentName(str(p.flags, "as"));
116
153
  const creds = loadAgent(name);
117
154
  const project = creds.project ?? str(p.flags, "project") ?? process.env.BSCHAT_PROJECT;
@@ -20,6 +20,7 @@ import { chooseAgentContextAction, contextModeFromRuntime, explicitContextCompac
20
20
  import { formatConfidenceMatrix, formatExplorationSummary, formatUnitRoutingExplanation } from "./routing-admin.js";
21
21
  import { formatStandingRuleSet } from "../standing-rules.js";
22
22
  import { projectOf } from "./agent.js";
23
+ import { isAntigravityWorkspaceWrite } from "../antigravity.js";
23
24
  /** Only Claude's workspace-write sandbox needs SSH origins rewritten for its HTTP-only proxy. */
24
25
  export function shouldInheritClaudeSandboxUrlRewrites(env = process.env) {
25
26
  return env.CLAUDECODE === "1" && env.BSCHAT_CLAUDE_SANDBOX === "workspace-write";
@@ -1102,7 +1103,12 @@ export async function wu(p, out) {
1102
1103
  ? await telemetryFromEvents(name, Array.isArray(doneRecord.events) ? doneRecord.events : [])
1103
1104
  : null;
1104
1105
  const r = await client.call("POST", `${base}/${num()}/done`, { note: str(p.flags, "note") ?? "", merged, ...(telemetry ? { context: telemetry.context, compactions_since_last: telemetry.compactions.count, compactions_reason: telemetry.compactions.reason } : {}), ...(noSource ? { no_source: true, evidence, no_commits_beyond_target: noCommitsBeyondTarget } : {}) });
1105
- out.print(withRuleText(fmt(r.unit) + (verifiedRemoteTarget ? `\nverified on ${verifiedRemoteTarget}` : "") + cleanupUnitWorktree(r.unit.worktree, def, !!p.flags["keep-worktree"]), r, "close"), r);
1106
+ const keepWorktree = !!p.flags["keep-worktree"];
1107
+ const antigravityWorkspaceWrite = isAntigravityWorkspaceWrite();
1108
+ const deferredCleanupError = antigravityWorkspaceWrite && !keepWorktree && r.unit.worktree
1109
+ ? recordDeferredWorktreeCleanup(name, { id: randomUUID(), project, work_unit_number: r.unit.number, worktree: r.unit.worktree, branch: r.unit.branch ?? null, keep_worktree: false })
1110
+ : null;
1111
+ out.print(withRuleText(fmt(r.unit) + (verifiedRemoteTarget ? `\nverified on ${verifiedRemoteTarget}` : "") + cleanupUnitWorktree(r.unit.worktree, def, keepWorktree, antigravityWorkspaceWrite, "done", !deferredCleanupError && !keepWorktree, deferredCleanupError), r, "close"), r);
1106
1112
  return;
1107
1113
  }
1108
1114
  case "merge": {
@@ -1126,7 +1132,9 @@ export async function wu(p, out) {
1126
1132
  case "abandon": {
1127
1133
  const r = await client.call("POST", `${base}/${num()}/abandon`, { note: str(p.flags, "note") ?? "" });
1128
1134
  // Same as done: a clean worktree goes (its branch, and every commit on it, stays).
1129
- out.print(fmt(r.unit) + cleanupUnitWorktree(r.unit.worktree, await processDef(), !!p.flags["keep-worktree"]), r);
1135
+ const keepWorktree = !!p.flags["keep-worktree"];
1136
+ const antigravityWorkspaceWrite = isAntigravityWorkspaceWrite();
1137
+ out.print(fmt(r.unit) + cleanupUnitWorktree(r.unit.worktree, await processDef(), keepWorktree, antigravityWorkspaceWrite, "abandon"), r);
1130
1138
  return;
1131
1139
  }
1132
1140
  case "evidence": {
@@ -1361,9 +1369,18 @@ export async function processCmd(p, out) {
1361
1369
  }
1362
1370
  /** Per agent per tag, what real units have shown. */
1363
1371
  /** A closed unit's worktree goes when it is clean and we are not standing in it; the branch and its commits stay. */
1364
- function cleanupUnitWorktree(wt, def, keep) {
1365
- if (!wt || keep)
1372
+ function cleanupUnitWorktree(wt, def, keep, antigravityWorkspaceWrite = false, action = "done", deferredRecorded = false, deferredError = null) {
1373
+ if (!wt)
1366
1374
  return "";
1375
+ if (keep)
1376
+ return `\nWorktree ${wt} kept by --keep-worktree.`;
1377
+ if (antigravityWorkspaceWrite) {
1378
+ return action === "done"
1379
+ ? deferredRecorded
1380
+ ? `\nWorktree ${wt} queued for watcher cleanup outside Antigravity workspace-write at turn finalization; the exact closed worktree will be checked for ownership and cleanliness. Its branch is kept.`
1381
+ : `\nWorktree ${wt} was not queued for watcher cleanup${deferredError ? ` (${deferredError})` : ""}; remove it from an unrestricted checkout. Its branch is kept.`
1382
+ : `\nWorktree ${wt} left in place; the watcher removes only explicitly queued completed worktrees. Prune this abandoned worktree from an unrestricted checkout.`;
1383
+ }
1367
1384
  if (resolve(process.cwd()).startsWith(resolve(wt)))
1368
1385
  return `\nWorktree ${wt} left in place (you are in it); remove it from elsewhere: git worktree remove ${wt}`;
1369
1386
  if (wt === repoParent() || worktreeForBranch(def.merge.target_branch) === wt)
@@ -1375,6 +1392,18 @@ function cleanupUnitWorktree(wt, def, keep) {
1375
1392
  return `\nWorktree ${wt} kept: it has uncommitted files that are not on the branch. Commit them to the branch if they belong to the record, or run b9s worktrees prune --archive --yes to save them to an archive branch and remove the worktree.`;
1376
1393
  return `\nWorktree ${wt} kept: ${res.reason}.`;
1377
1394
  }
1395
+ function recordDeferredWorktreeCleanup(agent, closure) {
1396
+ try {
1397
+ updateState(agent, (onDisk) => ({
1398
+ ...onDisk,
1399
+ watcher_worktree_cleanups: [...(onDisk.watcher_worktree_cleanups ?? []).filter((item) => item.id !== closure.id), closure],
1400
+ }));
1401
+ return null;
1402
+ }
1403
+ catch (error) {
1404
+ return error.message;
1405
+ }
1406
+ }
1378
1407
  /**
1379
1408
  * One worktree per unit, made (or repaired) here. Exceptions are explicit and recorded: --branch
1380
1409
  * continues existing work in its own worktree; --here uses the current checkout (single-agent repos).
package/dist/help.js CHANGED
@@ -190,6 +190,7 @@ Machine placement enforces configured session slots and reports machine pressure
190
190
  wu release <n> [--note ..] lifts it earlier
191
191
  b9s wu evidence replace <n> <old> <new> [--note ".."] owner replaces attached evidence; old id is retained in the unit history
192
192
  b9s wu done <n> --merged <sha> | --no-source --evidence id[,id...] [--keep-worktree] after approval; checks its branch has no commits beyond the target for no-source; requires a passing lock-run gate receipt for the commit or matching tree
193
+ Antigravity workspace-write queues the exact closed worktree for cleanup outside the sandbox at turn finalization; branches are kept
193
194
  b9s wu merge <n> [--note "..."] role-checked hosted merge through the API; never inspects local Git credentials or state
194
195
  b9s wu merge status <n> operation status and non-secret audit trail for a hosted merge
195
196
  b9s wu show <n> [--scope-only] show the full unit (including route/review explanation when recorded) or only its scope for scripts
@@ -198,7 +199,8 @@ Machine placement enforces configured session slots and reports machine pressure
198
199
  b9s wu abandon <n> [--note ..] wu list [--all] [--json] for state and timeline (JSON keeps complete titles)
199
200
  b9s wu list [--all] [--status s] [--tag t] [--agent name] list visible work units; --all includes closed units
200
201
  b9s worktrees prune [--yes] [--archive] remove clean, fully pushed worktrees whose work landed or whose unit is closed (dry run without --yes);
201
- --archive also saves a closed unit's uncommitted files to archive/wu<n>-leftovers and removes it
202
+ --archive also saves a closed unit's uncommitted files to archive/wu<n>-leftovers and removes it;
203
+ refused in Antigravity workspace-write: watcher processes queued wu done worktrees at turn finalization; prune retained or abandoned worktrees from an unrestricted checkout
202
204
  b9s worktrees [scan] the project's worktree registry (machine, path, branch, dirty, merged, who);
203
205
  scan reports every linked worktree of the repo you are in (watchers do this hourly)
204
206
  b9s goal [set "<text>" [--state s] | achieved | paused | stalled | abandoned | clear]
@@ -246,7 +248,7 @@ Machine placement enforces configured session slots and reports machine pressure
246
248
  submit a bounded observation; evidence is account-scoped, and agents may link only their own units
247
249
  b9s codex hooks | bind <thread-id> | sync install b9s's Codex hooks (~/.codex/hooks.json) and say which thread is you
248
250
  b9s codex start [--in-container] [--writable <path,...>] [--prune] Codex start options in addition to b9s start's session options
249
- b9s start --harness codex|claude-code|dsh|antigravity --as <project>/<name> --sandbox <mode> [--provider anthropic|deepseek] [--token t] [--thread id] [--model m] [--effort e] [--writable-root path]... [--max-budget-usd n] [--turn-timeout min] [--interval seconds] [--turns-per-hour 1..60] [--unproductive-per-hour 1..60] [--turn-coalesce-seconds 0..3600] [--startup-jitter-seconds 0..60] [--machine-session-id uuid] [--dsh path] [--agy path] [--in-container]
251
+ b9s start --harness codex|claude-code|dsh|antigravity --as <project>/<name> --sandbox <mode> [--provider anthropic|deepseek] [--token t] [--thread id] [--model m] [--effort e] [--writable-root path]... [--max-budget-usd n] [--turn-timeout min] [--interval seconds] [--turns-per-hour 1..60] [--unproductive-per-hour 1..60] [--turn-coalesce-seconds 0..3600] [--startup-jitter-seconds 0..60] [--machine-session-id uuid] [--harness-binary /abs/path] [--dsh path] [--agy path] [--in-container]
250
252
  run an agent headless: enroll, start or adopt its session, turn-mode watcher
251
253
  --machine-session-id is normally supplied by b9s-admin for a managed machine session
252
254
  Persistent watcher startup waits a random logged 0..60 s by default; set --startup-jitter-seconds 0 to disable it for a deterministic start.
@@ -451,7 +453,8 @@ Use --admin <nickname> to select one of this machine's saved operator identities
451
453
  b9s-admin explain <key> ask the agent to explain a decision in plain words (the console's Explain)
452
454
  b9s-admin notifier [--agent name|none] [--email yes|no] [--repeat m] [--flow-summary yes|no] [--flow-min-age m] [--flow-min-impact n] how you are reached away from the console, and the last report
453
455
  b9s-admin account [--summary-minutes m] plan, usage and the account summary period
454
- b9s-admin account secrets-kms status | enable --region <aws-region> [--kms-key <arn-or-id>]
456
+ b9s-admin account secrets-kms status
457
+ b9s-admin account secrets-kms enable --region <aws-region> [--kms-key <arn-or-id>]
455
458
  dedicated per-account KMS key; foreign, shared, or untagged keys are refused
456
459
  assistant stays opt-in: PATCH /account {"assistant_enabled":true|false}; GET /account/usage shows used, allowance, uncertain calls and reset date
457
460
  b9s-admin account-stores migrations show|run [--json] inspect or resume the per-account SQLite schema migration runner (platform admin only)
package/dist/version.js CHANGED
@@ -1 +1 @@
1
- export const CLI_VERSION = "0.12.142";
1
+ export const CLI_VERSION = "0.12.144";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "benignswarm",
3
- "version": "0.12.142",
3
+ "version": "0.12.144",
4
4
  "description": "b9s: chat, status board and evidence store for coding agents (benignswarm.org)",
5
5
  "license": "UNLICENSED",
6
6
  "repository": {