benignswarm 0.12.98 → 0.12.99

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -69,6 +69,33 @@ export async function unitWorktrees(creds, project, options = {}) {
69
69
  }
70
70
  return { closed, active };
71
71
  }
72
+ export async function pruneProjectWorktrees(creds, project, cwd, protection, log) {
73
+ const before = await scanProject(creds, project, { cwd });
74
+ const units = await unitWorktrees(creds, project);
75
+ const report = pruneReport(cwd, units.closed, units.active, undefined, protection);
76
+ const dirtyClosed = [...new Set(report.kept.flatMap((item) => {
77
+ const number = item.dirtyClosed ? /WU #(\d+)/.exec(item.dirtyClosed)?.[1] : undefined;
78
+ return number ? [`closed unit #${number} has uncommitted work in ${item.path}`] : [];
79
+ }))];
80
+ const probe = freeSpaceProbe(report.prunable.map((item) => item.path));
81
+ let removed = 0;
82
+ for (const candidate of report.prunable) {
83
+ const result = removePrunable(candidate, cwd, undefined, protection.inUse, true);
84
+ if (result.removed)
85
+ removed++;
86
+ log(result.removed ? `pruned ${candidate.path}${candidate.branch ? ` (${candidate.branch})` : ""}` : `kept ${candidate.path}: ${result.reason}`);
87
+ }
88
+ const freeSpace = probe.after();
89
+ if (removed) {
90
+ try {
91
+ await scanProject(creds, project, { cwd });
92
+ }
93
+ catch (error) {
94
+ log(`post-prune worktree scan failed: ${error.message}`);
95
+ }
96
+ }
97
+ return { project, repo: before.repo, removed, free_space: freeSpace, dirty_closed: dirtyClosed };
98
+ }
72
99
  /**
73
100
  * The project's worktree registry.
74
101
  * b9s worktrees every worktree the project knows about: machine, path, branch, dirty, merged, who, suggestion
@@ -132,7 +159,7 @@ export async function worktrees(p, out, timeouts = {}) {
132
159
  const kept = [];
133
160
  const probe = freeSpaceProbe(candidates.map((c) => c.path));
134
161
  for (const c of candidates) {
135
- const r = removePrunable(c, process.cwd(), statusTimeoutMs);
162
+ const r = removePrunable(c, process.cwd(), statusTimeoutMs, protection.inUse);
136
163
  if (r.removed)
137
164
  removed.push(c.path);
138
165
  else
@@ -165,7 +192,7 @@ export async function worktrees(p, out, timeouts = {}) {
165
192
  }
166
193
  /** Scan the repository at cwd and report it. Shared with the watcher, which runs it periodically. */
167
194
  export async function scanProject(creds, project, options = {}) {
168
- const scan = scanWorktrees(process.cwd(), options);
195
+ const scan = scanWorktrees(options.cwd ?? process.cwd(), options);
169
196
  if (!scan)
170
197
  throw new CliError("not_a_repo", "the current directory is not inside a git repository", "Run b9s worktrees scan from a checkout of the project's repository.");
171
198
  const machine = creds.machine || defaultMachine();
@@ -13,6 +13,8 @@ import { table } from "../output.js";
13
13
  import { restoreRecoveryArchive, sha256 as recoverySha256 } from "../recovery-archive.js";
14
14
  import { createRecoveryArchive } from "../recovery-archive.js";
15
15
  import { tmpdir } from "node:os";
16
+ import { chooseAgentContextAction, contextModeFromRuntime, explicitContextCompactSupport, hasCorrectionHistory } from "../context-policy.js";
17
+ import { formatConfidenceMatrix, formatExplorationSummary, formatUnitRoutingExplanation } from "./routing-admin.js";
16
18
  /** Only Claude's workspace-write sandbox needs SSH origins rewritten for its HTTP-only proxy. */
17
19
  export function shouldInheritClaudeSandboxUrlRewrites(env = process.env) {
18
20
  return env.CLAUDECODE === "1" && env.BSCHAT_CLAUDE_SANDBOX === "workspace-write";
@@ -71,6 +73,124 @@ export function assignmentGuidanceOutput(warnings = []) {
71
73
  ? `\nScope checks and assignment suggestions (advisory; no changes applied):\n${warnings.map((warning) => `- ${warning}`).join("\n")}`
72
74
  : "";
73
75
  }
76
+ /** Prepare and verify the action metadata required before a work unit starts. */
77
+ async function contextDecisionForStart(client, base, unit, name, p, events = []) {
78
+ const snapshot = unit.context_policy;
79
+ if (!snapshot || !["keep", "compact", "clear", "agent-decides"].includes(snapshot.resolved))
80
+ return undefined;
81
+ const creds = loadAgent(name);
82
+ const harness = ["codex", "claude-code", "dsh", "antigravity"].includes(creds.vendor) ? creds.vendor : null;
83
+ const state = readState(name);
84
+ const mode = contextModeFromRuntime({
85
+ harness,
86
+ turnMode: !!state.turn_guard,
87
+ activeSessionHarness: state.harness_session?.harness,
88
+ sessionObservedAt: state.harness_session?.last_seen_at,
89
+ interactiveTerminal: process.stdin.isTTY === true && process.stdout.isTTY === true,
90
+ headlessInvocation: process.env.BSCHAT_TEXT !== undefined || process.env.BSCHAT_SUMMARY !== undefined || process.env.BSCHAT_SESSION_ID !== undefined || process.env.BSCHAT_HARNESS !== undefined,
91
+ env: process.env,
92
+ });
93
+ let action = snapshot.resolved === "agent-decides" ? "keep" : snapshot.resolved;
94
+ let reason = `Resolved context policy: ${action}.`;
95
+ if (snapshot.resolved === "agent-decides") {
96
+ const sentBack = hasCorrectionHistory(unit, events);
97
+ let sameRecentArea = null;
98
+ if (!sentBack) {
99
+ const previous = await client.call("GET", `${base}?agent=${encodeURIComponent(creds.agent)}&all=1`);
100
+ const recent = (Array.isArray(previous.units) ? previous.units : [])
101
+ .filter((item) => item.number !== unit.number && item.owner_name === creds.agent)
102
+ .sort((a, b) => b.number - a.number)[0];
103
+ const tags = new Set(Array.isArray(unit.tags) ? unit.tags : []);
104
+ if (recent) {
105
+ sameRecentArea = (!!unit.milestone && unit.milestone === recent.milestone) ||
106
+ (Array.isArray(recent.tags) && recent.tags.some((tag) => tags.has(tag)));
107
+ }
108
+ }
109
+ const choice = chooseAgentContextAction({
110
+ contextPct: startTelemetry(name).context.pct,
111
+ thresholdPct: Number.isInteger(snapshot.agent_decides_threshold_pct) ? snapshot.agent_decides_threshold_pct : 70,
112
+ sentBack,
113
+ sameRecentArea,
114
+ });
115
+ action = choice.action;
116
+ reason = choice.reason;
117
+ const requested = str(p.flags, "context-action");
118
+ if (requested !== undefined && requested !== action) {
119
+ throw new CliError("context_policy", `agent-decides selected ${action}: ${reason}; --context-action ${requested} cannot override the rubric`);
120
+ }
121
+ }
122
+ else {
123
+ const requested = str(p.flags, "context-action");
124
+ if (requested !== undefined && requested !== action)
125
+ throw new CliError("context_policy", `unit policy resolves to ${action}; --context-action cannot substitute ${requested}`);
126
+ }
127
+ if (/[\r\n]/.test(reason) || reason.length > 300)
128
+ throw new CliError("context_policy", "generated context-policy reason exceeds the API limit");
129
+ const decision = { actual_action: action, outcome: "completed", reason, harness, mode };
130
+ if (action === "compact") {
131
+ if (!explicitContextCompactSupport(harness, mode)) {
132
+ const unsupportedReason = `Explicit compaction is unsupported for ${harness ?? "unknown harness"} in ${mode ?? "unknown mode"} mode; no fallback was applied.`;
133
+ await client.call("POST", `${base}/${unit.number}/context-policy/decision`, { ...decision, outcome: "unsupported", reason: unsupportedReason });
134
+ throw new CliError("unsupported", `WU #${unit.number}: ${unsupportedReason} Ask the assigner or operator to choose a supported policy.`);
135
+ }
136
+ if (!bool(p.flags, "context-confirmed")) {
137
+ throw new CliError("context_action_required", `WU #${unit.number} requires compact. Run /compact in this ${harness} interactive session, confirm it completed, then rerun b9s wu start ${unit.number} --context-confirmed.`);
138
+ }
139
+ const compactAt = state.harness_session?.compactions?.at(-1);
140
+ const resolvedAt = typeof snapshot.resolved_at === "string" ? Date.parse(snapshot.resolved_at) : Number.NaN;
141
+ if (compactAt === undefined || !Number.isFinite(resolvedAt) || compactAt < resolvedAt) {
142
+ const unsupportedReason = `The ${harness} session hook did not observe a compact boundary after this policy snapshot; completion cannot be verified.`;
143
+ await client.call("POST", `${base}/${unit.number}/context-policy/decision`, { ...decision, outcome: "unsupported", reason: unsupportedReason });
144
+ throw new CliError("unsupported", `WU #${unit.number}: ${unsupportedReason} Ask the assigner or operator to choose a supported policy.`);
145
+ }
146
+ }
147
+ if (action === "clear") {
148
+ const checkpointRef = str(p.flags, "context-checkpoint-ref");
149
+ const oldThreadId = str(p.flags, "context-old-thread");
150
+ const newThreadId = str(p.flags, "context-new-thread");
151
+ if (!bool(p.flags, "context-confirmed") || !checkpointRef || !oldThreadId || !newThreadId) {
152
+ throw new CliError("context_action_required", `WU #${unit.number} requires a checkpointed fresh thread. Save it with b9s checkpoint, open a new thread for this agent, then rerun b9s wu start ${unit.number} --context-confirmed --context-checkpoint-ref <handoff-id> --context-old-thread <old-thread-id> --context-new-thread <new-thread-id>.`);
153
+ }
154
+ const checkpoint = await client.call("GET", `/handoffs/${encodeURIComponent(checkpointRef)}`);
155
+ if (checkpoint.handoff?.agent_name !== creds.agent || checkpoint.handoff?.kind !== "resume") {
156
+ throw new CliError("context_action_required", "context checkpoint must be an existing resume note saved by this agent");
157
+ }
158
+ if (oldThreadId === newThreadId)
159
+ throw new CliError("context_action_required", "clear requires a different new thread id");
160
+ const currentThread = state.harness_session?.session_id;
161
+ const recentlyObserved = state.harness_session?.last_seen_at !== undefined && Date.now() - state.harness_session.last_seen_at < 60_000;
162
+ if (!currentThread || currentThread !== newThreadId || state.harness_session?.harness !== harness || !recentlyObserved) {
163
+ throw new CliError("context_action_required", `the new thread ${newThreadId} is not the current locally recorded ${harness ?? "harness"} session; start it and let its session hook record the thread before starting the unit`);
164
+ }
165
+ decision.checkpoint_ref = checkpointRef;
166
+ decision.old_thread_id = oldThreadId;
167
+ decision.new_thread_id = newThreadId;
168
+ let daemonManaged = null;
169
+ if (mode === "interactive") {
170
+ try {
171
+ const self = await client.call("GET", "/me");
172
+ // /me.runs_on intentionally reports only running sessions. It cannot prove that an
173
+ // agent is unmanaged: a stopped machine session can still own the remembered thread.
174
+ // Use the authoritative all-session inventory from API WU #359; absence is unknown.
175
+ if (Array.isArray(self.machine_sessions))
176
+ daemonManaged = self.machine_sessions.length > 0;
177
+ }
178
+ catch {
179
+ // An unreadable placement state is not proof that the agent is unmanaged.
180
+ }
181
+ }
182
+ if (mode !== "interactive" || daemonManaged === null) {
183
+ const unsupportedReason = mode !== "interactive"
184
+ ? `Fresh-thread clear is unsupported in ${mode ?? "unverified"} mode; an interactive fresh-thread session is required and no start was attempted.`
185
+ : `Fresh-thread clear is unsupported because the server could not confirm this agent's machine-session inventory; no start was attempted.`;
186
+ await client.call("POST", `${base}/${unit.number}/context-policy/decision`, { ...decision, outcome: "unsupported", reason: unsupportedReason });
187
+ throw new CliError("unsupported", `WU #${unit.number}: ${unsupportedReason} Ask the assigner or operator to choose a supported policy.`);
188
+ }
189
+ // For a managed session, the start endpoint persists the completed clear and CAS-updates
190
+ // the authoritative remembered thread in one D1 batch. A stale old_thread_id is refused.
191
+ }
192
+ return decision;
193
+ }
74
194
  function retrospectiveEventDetail(event) {
75
195
  const data = event.data ?? {};
76
196
  if (event.type === "changes_requested") {
@@ -418,9 +538,10 @@ export async function wu(p, out) {
418
538
  out.print(`${fmt(r.unit)}\nWait until ${r.unit.waits_on.map((on) => `WU #${on}`).join(", ")} closes, then start with: b9s wu start ${n}`, r);
419
539
  return;
420
540
  }
541
+ const contextDecision = await contextDecisionForStart(client, base, r.unit, name, p);
421
542
  const { path, branch, mode } = prepareWorktree(n, r.unit, await processDef(), p, await checkoutExclude());
422
543
  const where = symbolicBranchAndHead(path);
423
- const s = await client.call("POST", `${base}/${n}/start`, { branch: branch ?? where.branch, head: where.head, worktree: path, mode, ...startTelemetry(name) });
544
+ const s = await client.call("POST", `${base}/${n}/start`, { branch: branch ?? where.branch, head: where.head, worktree: path, mode, ...startTelemetry(name), ...(contextDecision ? { context_decision: contextDecision } : {}) });
424
545
  out.print(`${fmt(s.unit)}\n${mode === "here" ? "Working in this checkout." : `Your worktree: ${path} (branch ${branch})\n cd ${path}\nWork there.`}\nSubmit for review when ready: b9s wu submit ${n} --evidence <id>`, { ...s, worktree: path, branch, mode });
425
546
  return;
426
547
  }
@@ -512,18 +633,20 @@ export async function wu(p, out) {
512
633
  }
513
634
  case "start": {
514
635
  const n = num();
515
- const unit = (await client.call("GET", `${base}/${n}`)).unit;
636
+ const unitRecord = await client.call("GET", `${base}/${n}`);
637
+ const unit = unitRecord.unit;
516
638
  // Ask the server to refuse queued work before prepareWorktree can create a branch or checkout.
517
639
  // This also gives the refusal the canonical take instruction from the server.
518
640
  await preflightQueuedStart(client, base, n, unit);
519
641
  const def = await processDef();
520
642
  const target = unit.target ?? def.merge.target_branch;
643
+ const contextDecision = await contextDecisionForStart(client, base, unit, name, p, Array.isArray(unitRecord.events) ? unitRecord.events : []);
521
644
  const prepared = prepareWorktree(n, unit, def, p, await checkoutExclude());
522
645
  const { path, branch, mode } = prepared;
523
646
  const where = symbolicBranchAndHead(path);
524
647
  let r;
525
648
  try {
526
- r = await client.call("POST", `${base}/${n}/start`, { branch: branch ?? where.branch, head: where.head, worktree: path, mode, ...startTelemetry(name) });
649
+ r = await client.call("POST", `${base}/${n}/start`, { branch: branch ?? where.branch, head: where.head, worktree: path, mode, ...startTelemetry(name), ...(contextDecision ? { context_decision: contextDecision } : {}) });
527
650
  }
528
651
  catch (error) {
529
652
  if (prepared.created) {
@@ -977,7 +1100,9 @@ export async function wu(p, out) {
977
1100
  const context = measureContextOutput(r.measure_context, r.unit.expected_effect, r.unit.measured_effect);
978
1101
  const recovery = r.unit.recovery;
979
1102
  const recoveryText = recovery ? `\nRecovery: ${recovery.available ? `available (${recovery.size ?? "?"} bytes, sha256 ${recovery.sha256 ?? "?"})` : "not verified"}${recovery.expires_at ? `; expires ${recovery.expires_at}` : ""}${recovery.manifest?.skipped?.length ? `; skipped ${recovery.manifest.skipped.length} regenerable path(s)` : ""}${recovery.manifest?.omitted?.length ? `; ${recovery.manifest.omitted.length} uncaptured path(s), source volume remains protected` : ""}${recovery.available ? `; restore: b9s wu recovery restore ${r.unit.number}` : ""}` : "";
980
- out.print(`${fmt(r.unit)}${context ? `\n${context}` : ""}${lessons ? `\nWorker lessons (latest first):\n${lessons}` : ""}${recoveryText}\n${events}`, r);
1103
+ const routingLines = formatUnitRoutingExplanation(r.unit);
1104
+ const routingText = routingLines.length ? `\nRouting:\n${routingLines.join("\n")}` : "";
1105
+ out.print(`${fmt(r.unit)}${routingText}${context ? `\n${context}` : ""}${lessons ? `\nWorker lessons (latest first):\n${lessons}` : ""}${recoveryText}\n${events}`, r);
981
1106
  return;
982
1107
  }
983
1108
  case "list":
@@ -1298,9 +1423,27 @@ export async function record(p, out) {
1298
1423
  const project = creds.project ?? str(p.flags, "project") ?? process.env.BSCHAT_PROJECT;
1299
1424
  if (!project)
1300
1425
  throw new CliError("no_project", `${creds.agent} is an account-scoped agent; pass --project <name>`);
1426
+ const by = str(p.flags, "by");
1427
+ if (by === "matrix") {
1428
+ const mode = str(p.flags, "mode");
1429
+ if (mode && mode !== "build" && mode !== "review")
1430
+ throw new CliError("usage", "--mode must be build or review");
1431
+ const tag = str(p.flags, "tag");
1432
+ const routing = await client.call("GET", `/projects/${project}/routing`);
1433
+ const pol = routing.policy ?? {};
1434
+ const w = pol.weights ?? { quality: 65, time: 20, cost: 15 };
1435
+ const lines = [
1436
+ `Routing for ${routing.project} (weights ${w.quality}/${w.time}/${w.cost}, target ${pol.quality_target_percent ?? "none"}, min samples ${pol.minimum_sample_count ?? 8})`,
1437
+ formatExplorationSummary("build", routing.exploration?.build),
1438
+ formatExplorationSummary("review", routing.exploration?.review),
1439
+ formatConfidenceMatrix(routing.confidence ?? [], { mode, tag }),
1440
+ ];
1441
+ out.print(lines.join("\n"), routing);
1442
+ return;
1443
+ }
1301
1444
  const r = await client.call("GET", `/projects/${project}/record`);
1302
1445
  const counters = (x) => ({ done: x.units, "1st-round": x.approved_first_round, changes: x.changes_requested, "2nd-read send-backs": x.second_read_changes ?? 0, replays: x.replays, reviewed: x.reviewed, overturned: x.overturned, escalated: x.escalated });
1303
- if (str(p.flags, "by") === "model") {
1446
+ if (by === "model") {
1304
1447
  // The same counters keyed by what produced the work: model and effort setting at the time of the start or the verdict.
1305
1448
  const rows = (r.by_model ?? []).map((x) => ({ model: x.model, effort: x.effort, tag: `#${x.tag}`, ...counters(x), agents: x.agents.join(",") }));
1306
1449
  out.print(rows.length ? table(rows, ["model", "effort", "tag", "done", "1st-round", "changes", "2nd-read send-backs", "replays", "reviewed", "overturned", "escalated", "agents"]) : "(no reviewed units yet)", r);
@@ -0,0 +1,49 @@
1
+ export function hasCorrectionHistory(unit, events = []) {
2
+ return unit.status === "changes_requested" ||
3
+ events.some((event) => event.type === "changes_requested") ||
4
+ (unit.reworks ?? []).some((relation) => relation.unit === unit.number && relation.source === "send_back");
5
+ }
6
+ export function chooseAgentContextAction(input) {
7
+ if (input.sentBack)
8
+ return { action: "keep", reason: "This unit was sent back; keep the review and correction context." };
9
+ if (input.contextPct !== null && input.contextPct >= input.thresholdPct) {
10
+ return { action: "compact", reason: `Context fill is ${input.contextPct}% (threshold ${input.thresholdPct}%); compact before starting.` };
11
+ }
12
+ if (input.sameRecentArea === true) {
13
+ return {
14
+ action: "keep",
15
+ reason: input.contextPct === null
16
+ ? "Context measurement is unavailable; recent work is in the same milestone or code area, so keep context."
17
+ : "Recent work is in the same milestone or code area, so keep context.",
18
+ };
19
+ }
20
+ if (input.contextPct === null && input.sameRecentArea === null) {
21
+ return { action: "keep", reason: "Context measurement and recent work area are unavailable; keep context without claiming a threshold decision." };
22
+ }
23
+ return {
24
+ action: "clear",
25
+ reason: input.contextPct === null
26
+ ? "Context measurement is unavailable and recent work is in an unrelated area; save a checkpoint and clear."
27
+ : "Recent work is in an unrelated area; save a checkpoint and clear.",
28
+ };
29
+ }
30
+ /** Explicit pre-unit compaction is supported only for verified interactive adapters. */
31
+ export function explicitContextCompactSupport(harness, mode) {
32
+ return mode === "interactive" && (harness === "claude-code" || harness === "antigravity");
33
+ }
34
+ export function contextModeFromRuntime(input) {
35
+ if (input.turnMode)
36
+ return "turn";
37
+ if (input.headlessInvocation)
38
+ return "headless";
39
+ // Vendor/session hooks identify the harness, not how it was invoked. Headless
40
+ // print/watch turns can have both, so only a foreground terminal is affirmative
41
+ // evidence that interactive-only actions are available.
42
+ const now = input.now ?? Date.now();
43
+ const freshSession = input.sessionObservedAt !== undefined && now >= input.sessionObservedAt && now - input.sessionObservedAt < 60_000;
44
+ if (input.interactiveTerminal && input.harness === "claude-code" && input.activeSessionHarness === "claude-code" && freshSession && input.env.CLAUDECODE === "1")
45
+ return "interactive";
46
+ if (input.interactiveTerminal && input.harness === "antigravity" && input.activeSessionHarness === "antigravity" && freshSession)
47
+ return "interactive";
48
+ return null;
49
+ }
package/dist/git.js CHANGED
@@ -381,15 +381,18 @@ export function pruneReport(cwd = process.cwd(), closedUnitPaths = new Map(), ac
381
381
  for (const w of scan.worktrees) {
382
382
  if (realpathOrSelf(w.path) === realpathOrSelf(scan.repo))
383
383
  continue;
384
+ const closedNote = closedUnitPaths.get(realpathOrSelf(w.path));
385
+ const dirtyClosed = closedNote && w.dirty === true ? closedNote : undefined;
386
+ const keep = (reason, archivable) => kept.push({ path: w.path, branch: w.branch, reason, ...(archivable ? { archivable } : {}), ...(dirtyClosed ? { dirtyClosed } : {}) });
384
387
  if (here.startsWith(realpathOrSelf(w.path))) {
385
- kept.push({ path: w.path, branch: w.branch, reason: "you are standing in it" });
388
+ keep("you are standing in it");
386
389
  continue;
387
390
  }
388
391
  // Git locks are an explicit operator/agent retention request. Preserve the reason in both
389
392
  // report modes; an interrupted add's `locked: initializing` still follows the empty-checkout
390
393
  // cleanup path below.
391
394
  if (w.locked && !/^initializing\b/i.test(w.locked)) {
392
- kept.push({ path: w.path, branch: w.branch, reason: `locked: ${w.locked}` });
395
+ keep(`locked: ${w.locked}`);
393
396
  continue;
394
397
  }
395
398
  const worktreePath = realpathOrSelf(w.path);
@@ -401,13 +404,13 @@ export function pruneReport(cwd = process.cwd(), closedUnitPaths = new Map(), ac
401
404
  return rel === "" || (rel !== ".." && !rel.startsWith(`..${sep}`) && !isAbsolute(rel));
402
405
  });
403
406
  if (use) {
404
- kept.push({ path: w.path, branch: w.branch, reason: `in use by ${use.agent}` });
407
+ keep(`in use by ${use.agent}`);
405
408
  continue;
406
409
  }
407
410
  const homeAgent = w.branch?.startsWith("home/") ? w.branch.slice("home/".length) : null;
408
411
  const retiredHome = homeAgent !== null && options.retiredHomeAgents?.has(homeAgent);
409
412
  if (homeAgent && !retiredHome) {
410
- kept.push({ path: w.path, branch: w.branch, reason: `agent home for ${homeAgent} (not retired)` });
413
+ keep(`agent home for ${homeAgent} (not retired)`);
411
414
  continue;
412
415
  }
413
416
  // An agent's home checkout is never leftovers, whatever its branch: join/setup bind an identity
@@ -415,33 +418,46 @@ export function pruneReport(cwd = process.cwd(), closedUnitPaths = new Map(), ac
415
418
  // StickJoy's watcher removed a home checkout two minutes after it was created, before the agent
416
419
  // could bind it, because a fresh branch on main's head looks merged.
417
420
  if (!retiredHome && (existsSync(join(w.path, ".b9s", "identity.json")) || existsSync(join(w.path, ".bschat", "identity.json")))) {
418
- kept.push({ path: w.path, branch: w.branch, reason: "an agent's home checkout (it has a b9s identity file)" });
419
- continue;
420
- }
421
- const made = worktreeCreatedMs(w.path);
422
- if (made !== null && Date.now() - made < minAgeMs) {
423
- kept.push({ path: w.path, branch: w.branch, reason: "created less than a day ago" });
421
+ keep("an agent's home checkout (it has a b9s identity file)");
424
422
  continue;
425
423
  }
426
424
  // A unit still being worked keeps its worktree whatever git says: one just started has no
427
425
  // commits yet, so its head is on the base and it looks merged (ester WU 110 and 111).
428
426
  const active = activeUnits.paths.get(realpathOrSelf(w.path)) ?? (w.branch ? activeUnits.branches.get(w.branch) : undefined);
429
427
  if (active) {
430
- kept.push({ path: w.path, branch: w.branch, reason: `${active} is not closed` });
428
+ keep(`${active} is not closed`);
431
429
  continue;
432
430
  }
433
- const closedNote = closedUnitPaths.get(realpathOrSelf(w.path));
431
+ const made = worktreeCreatedMs(w.path);
432
+ if (!closedNote && made === null) {
433
+ keep("cannot determine worktree age");
434
+ continue;
435
+ }
436
+ if (!closedNote && Date.now() - made < minAgeMs) {
437
+ keep("created less than a day ago");
438
+ continue;
439
+ }
440
+ const onRemote = remoteBase && w.head ? spawnSync("git", ["merge-base", "--is-ancestor", w.head, remoteBase], { cwd: scan.repo, stdio: "ignore" }).status === 0 : false;
434
441
  // Nothing but .git: a checkout that never happened. There are no files to lose, and archiving
435
- // it would record "every file deleted". The branch is untouched.
442
+ // it would record "every file deleted". The branch is untouched. A closed unit still needs a
443
+ // remote push proof before this candidate can be nominated; its empty worktree is not proof
444
+ // that the local branch head was published.
436
445
  if (w.empty) {
446
+ if (closedNote && !onRemote && !pushedToOrigin(w.head, w.branch, scan.repo)) {
447
+ keep(`${closedNote} is not fully pushed to origin`);
448
+ continue;
449
+ }
437
450
  prunable.push({ path: w.path, branch: w.branch, empty: true, why: `empty checkout (an interrupted git worktree add)${closedNote ? `, ${closedNote}` : ""}` });
438
451
  continue;
439
452
  }
440
453
  if (w.dirty !== false) {
441
- kept.push({ path: w.path, branch: w.branch, reason: `${w.dirty === null ? "cannot read its status" : "uncommitted changes"}${closedNote ? ` (${closedNote}${w.dirty ? "; --archive saves them to a branch and removes it" : ""})` : ""}`, ...(closedNote && w.dirty === true ? { archivable: closedNote } : {}) });
454
+ keep(`${w.dirty === null ? "cannot read its status" : "uncommitted changes"}${closedNote ? ` (${closedNote}${w.dirty ? "; --archive saves them to a branch and removes it" : ""})` : ""}`, dirtyClosed);
455
+ continue;
456
+ }
457
+ if (closedNote && !onRemote && !pushedToOrigin(w.head, w.branch, scan.repo)) {
458
+ keep(`${closedNote} is not fully pushed to origin`);
442
459
  continue;
443
460
  }
444
- const onRemote = remoteBase && w.head ? spawnSync("git", ["merge-base", "--is-ancestor", w.head, remoteBase], { cwd: scan.repo, stdio: "ignore" }).status === 0 : false;
445
461
  if (w.merged === true || onRemote) {
446
462
  prunable.push({ path: w.path, branch: w.branch });
447
463
  continue;
@@ -456,7 +472,7 @@ export function pruneReport(cwd = process.cwd(), closedUnitPaths = new Map(), ac
456
472
  prunable.push({ path: w.path, branch: w.branch, why: closedNote });
457
473
  continue;
458
474
  }
459
- kept.push({ path: w.path, branch: w.branch, reason: `${w.ahead ?? "?"} commit${w.ahead === 1 ? "" : "s"} not on ${remoteBase ?? base ?? "the base branch"}` });
475
+ keep(`${w.ahead ?? "?"} commit${w.ahead === 1 ? "" : "s"} not on ${remoteBase ?? base ?? "the base branch"}`);
460
476
  }
461
477
  return { prunable, kept, base: remoteBase ?? base };
462
478
  }
@@ -620,7 +636,22 @@ export function formatBytes(n) {
620
636
  return n < 0 ? `-${s}` : s;
621
637
  }
622
638
  /** Removes a prune candidate: an empty checkout (re-checked here) by force, anything else only when clean. */
623
- export function removePrunable(c, cwd = process.cwd(), statusTimeoutMs = PRUNE_STATUS_TIMEOUT_MS) {
639
+ export function removePrunable(c, cwd = process.cwd(), statusTimeoutMs = PRUNE_STATUS_TIMEOUT_MS, inUse = [], protectAgentHomes = false) {
640
+ const candidate = realpathOrSelf(c.path);
641
+ if (protectAgentHomes && (c.branch?.startsWith("home/") || existsSync(join(c.path, ".b9s", "identity.json")) || existsSync(join(c.path, ".bschat", "identity.json")))) {
642
+ return { removed: false, reason: "agent home" };
643
+ }
644
+ const use = inUse.find((entry) => {
645
+ if (!isAbsolute(entry.path))
646
+ return false;
647
+ const rel = relative(candidate, realpathOrSelf(entry.path));
648
+ return rel === "" || (rel !== ".." && !rel.startsWith(`..${sep}`) && !isAbsolute(rel));
649
+ });
650
+ if (use)
651
+ return { removed: false, reason: `in use by ${use.agent}` };
652
+ const lock = worktreeLockReason(c.path, cwd);
653
+ if (lock)
654
+ return { removed: false, reason: lock };
624
655
  if (!c.empty)
625
656
  return removeWorktreeIfClean(c.path, cwd, statusTimeoutMs);
626
657
  if (!existsSync(c.path) || !readdirSync(c.path).every((e) => e === ".git"))
@@ -628,6 +659,26 @@ export function removePrunable(c, cwd = process.cwd(), statusTimeoutMs = PRUNE_S
628
659
  const r = spawnSync("git", ["worktree", "remove", "--force", c.path], { cwd, encoding: "utf8" });
629
660
  return r.status === 0 ? { removed: true } : { removed: false, reason: (r.stderr || r.stdout).trim() };
630
661
  }
662
+ function worktreeLockReason(path, cwd) {
663
+ const output = git(["worktree", "list", "--porcelain"], cwd) ?? "";
664
+ let current = null;
665
+ for (const line of `${output}\n`.split("\n")) {
666
+ if (line.startsWith("worktree "))
667
+ current = line.slice(9);
668
+ else if (line.startsWith("locked") && current && realpathOrSelf(current) === realpathOrSelf(path))
669
+ return `locked${line.slice(6).trim() ? `: ${line.slice(6).trim()}` : ""}`;
670
+ else if (line === "")
671
+ current = null;
672
+ }
673
+ return null;
674
+ }
675
+ function pushedToOrigin(head, branch, cwd) {
676
+ if (!head || !branch)
677
+ return false;
678
+ const remoteRef = `refs/remotes/origin/${branch}`;
679
+ const fetched = spawnSync("git", ["fetch", "--quiet", "origin", `+refs/heads/${branch}:${remoteRef}`], { cwd, encoding: "utf8", timeout: 120_000 });
680
+ return fetched.status === 0 && spawnSync("git", ["merge-base", "--is-ancestor", head, remoteRef], { cwd, stdio: "ignore" }).status === 0;
681
+ }
631
682
  export function removeWorktreeIfClean(path, cwd = process.cwd(), statusTimeoutMs = PRUNE_STATUS_TIMEOUT_MS) {
632
683
  const worktreeStatus = status(path, statusTimeoutMs);
633
684
  if (worktreeStatus === null)