pi-cowboy 0.14.1 → 0.15.1

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.
package/README.md CHANGED
@@ -124,6 +124,8 @@ Once the work is merged, the orchestrator cleans up the agent's resources (or yo
124
124
 
125
125
  Cleanup is safe by default: it refuses to touch an agent that is still running, keeps any worktree that still has uncommitted changes, and deletes the branch only if it has already been merged. If one step cannot be completed, `pi-cowboy` reports the reason and finishes the rest.
126
126
 
127
+ When the `/cowboy status` menu refuses to remove a worktree because of uncommitted changes or an unreadable state, it offers to `Force` the removal. Force deletes the worktree and discards anything uncommitted in it, so it asks for a confirmation that names the checkout and what will be lost. Forced removals are reported as `forced — <reason>`. This override lives in the menu only — the `cleanup_cowboy_agent` tool never forces, and the menu only offers it for a settled agent, never one it still lists as running.
128
+
127
129
  ## Customizing your workflow
128
130
 
129
131
  ### Agent templates
@@ -11,7 +11,7 @@
11
11
  import { hasOutcome } from "../types.js";
12
12
  import { createLogger } from "../logger.js";
13
13
  import { errorMessage } from "../utils.js";
14
- import { ambiguousReport, assembleReport, assessRemovability, keptReport, paneDispositionFor, planRecovered, recordedSettlement, recoveryGate, recoveryRefusalReason, removalMechanismOf, shouldDropSpawn, } from "./cleanup-policy.js";
14
+ import { ambiguousReport, assembleReport, assessRemovability, forcedFields, keptReport, paneDispositionFor, planRecovered, recordedSettlement, recoveryGate, recoveryRefusalReason, removalMechanismOf, shouldDropSpawn, } from "./cleanup-policy.js";
15
15
  const log = createLogger("cleanup");
16
16
  /* ── Addresses ─────────────────────────────────────────────────────────── */
17
17
  /** Actuator address: memory's ref refreshed from herdr's live report; recovered runs rebuild it with `paneCreated` false; no pane address means no ref (git plane removes the checkout). */
@@ -189,10 +189,12 @@ export function createCleanup(assets) {
189
189
  kind: "refused",
190
190
  settlement,
191
191
  reason: { kind: "agent-active", phase: hint.lifecycle.phase },
192
+ // Force never stops a run — see stop_cowboy_agent.
193
+ forceable: false,
192
194
  };
193
195
  }
194
196
  // No recorded end: force overrides without reading; otherwise herdr's live read decides (unreadable refuses — never evidence the run is over).
195
- if (opts?.force === true) {
197
+ if (opts?.force !== undefined) {
196
198
  return {
197
199
  kind: "torn-down",
198
200
  settlement: recovered(agentId, { kind: "forced" }),
@@ -212,6 +214,8 @@ export function createCleanup(assets) {
212
214
  kind: "refused",
213
215
  settlement: recovered(agentId, basis),
214
216
  reason: recoveryRefusalReason(basis),
217
+ // Force overrides the read it could not make; the refusal is bypassable.
218
+ forceable: true,
215
219
  };
216
220
  }
217
221
  }
@@ -222,6 +226,8 @@ export function createCleanup(assets) {
222
226
  kind: "refused",
223
227
  settlement: recovered(agentId, gate.basis),
224
228
  reason: recoveryRefusalReason(gate.basis),
229
+ // A pane still reporting `working` is exactly what force exists to override.
230
+ forceable: true,
225
231
  };
226
232
  }
227
233
  /** Clean up one ended run end-to-end (best effort); a refusal removes nothing — no tree, branch, pane, or stop. */
@@ -240,7 +246,10 @@ export function createCleanup(assets) {
240
246
  const plan = planRecovered(located);
241
247
  const verdict = await verdictFor(agentId, located, hint, opts);
242
248
  if (verdict.kind === "refused") {
243
- return keptReport(agentId, located.source, plan, verdict.settlement, verdict.reason, "open");
249
+ return keptReport(agentId, located.source, plan, verdict.settlement, {
250
+ reason: verdict.reason,
251
+ forceable: verdict.forceable,
252
+ });
244
253
  }
245
254
  // Ordered before the dirty probe — see Harness.teardown.
246
255
  const harness = hint?.execution.harness;
@@ -270,7 +279,9 @@ export function createCleanup(assets) {
270
279
  const report = {
271
280
  agentId,
272
281
  source: located.source,
273
- outcome: { kind: "torn-down" },
282
+ // Even this hand-built report carries the marker: a forced pass that
283
+ // lands here must not read as a routine "already gone".
284
+ outcome: { kind: "torn-down", ...forcedFields(opts) },
274
285
  branchName: plan.branchName,
275
286
  settlement: verdict.settlement,
276
287
  pane: await paneOutcomeForAbsentTree(assets, located.pane),
@@ -283,18 +294,26 @@ export function createCleanup(assets) {
283
294
  return report;
284
295
  }
285
296
  return keptReport(agentId, located.source, plan, verdict.settlement, {
286
- kind: "unverifiable",
287
- detail: "missing worktree path or repo cwd",
288
- }, "open");
297
+ reason: {
298
+ kind: "unverifiable",
299
+ detail: "missing worktree path or repo cwd",
300
+ },
301
+ // Force cannot address a removal with no repo cwd — not bypassable.
302
+ forceable: false,
303
+ });
289
304
  }
290
305
  if (plan.kind === "worktree") {
291
306
  const gate = await assessRemovability(assets.isWorktreeDirty, opts, plan.worktree);
292
307
  if (gate.kind === "kept") {
293
- return keptReport(agentId, located.source, plan, verdict.settlement, gate.reason, "open");
308
+ return keptReport(agentId, located.source, plan, verdict.settlement, {
309
+ reason: gate.reason,
310
+ // The dirty/unverifiable probe is exactly what force skips.
311
+ forceable: true,
312
+ });
294
313
  }
295
314
  }
296
315
  const removal = await removeResources(assets, plan, hostRefFor(located));
297
- const report = assembleReport(agentId, located.source, plan, verdict.settlement, removal);
316
+ const report = assembleReport(agentId, located.source, plan, verdict.settlement, removal, opts);
298
317
  // A recovered run has no record to forget; drop only tracked spawns.
299
318
  if (shouldDropSpawn(report) && hint !== undefined)
300
319
  registry.dropSpawn(hint);
@@ -3,7 +3,7 @@
3
3
  * Located artifacts: LocatedWorktree/LocatedPane/LocatedArtifacts.
4
4
  * Plan: CleanupPlan/planRecovered. Gate: GateOutcome/assessRemovability.
5
5
  * Settlement: SettlementVerdict/recordedSettlement/recoveryGate/recoveryRefusalReason.
6
- * Report: CleanupReport/keptReport/ambiguousReport/assembleReport/shouldDropSpawn.
6
+ * Report: CleanupReport/keptReport/ambiguousReport/assembleReport/forcedFields/isForceableRefusal/shouldDropSpawn.
7
7
  * Removal: RemovalOutcomes/RemovablePlan/WorktreeRemovalMechanism/PaneDisposition/removalMechanismOf/paneDispositionFor.
8
8
  * Probes: WorktreeDirtyProbe. Options: CleanupOptions. Source: CleanupSource. Basis: DiscoveryBasis.
9
9
  */
@@ -44,7 +44,7 @@ export function planRecovered(artifacts) {
44
44
  }
45
45
  /** Removability gate: dirty/unverifiable blocks (the only way removal loses work); unmerged does not (the branch survives in the repo); force skips the probe. */
46
46
  export async function assessRemovability(isDirty, opts, worktree) {
47
- if (opts?.force === true)
47
+ if (opts?.force !== undefined)
48
48
  return { kind: "removable" };
49
49
  const dirty = await isDirty(worktree.worktreePath);
50
50
  if (dirty === undefined) {
@@ -98,8 +98,8 @@ export function recoveryRefusalReason(basis) {
98
98
  }
99
99
  }
100
100
  /* ── Stage 5: report + record-keeping (pure) ───────────────────────────── */
101
- /** Refusal report shared by all early returns; the reason rides the verdict, so it survives even with no worktree to name. */
102
- export function keptReport(agentId, source, plan, settlement, reason, paneStatus) {
101
+ /** Refusal report shared by all early returns; the reason rides the verdict, so it survives even with no worktree to name. `refusal.forceable` marks a refusal the operator override can change (see CleanupVerdictOutcome). A refusal closes nothing, so its pane is always reported open. */
102
+ export function keptReport(agentId, source, plan, settlement, refusal) {
103
103
  const worktree = plan.kind === "worktree"
104
104
  ? { kind: "kept", path: plan.worktree.worktreePath }
105
105
  : plan.kind === "worktree-unlocatable"
@@ -108,7 +108,11 @@ export function keptReport(agentId, source, plan, settlement, reason, paneStatus
108
108
  return {
109
109
  agentId,
110
110
  source,
111
- outcome: { kind: "refused", reason },
111
+ outcome: {
112
+ kind: "refused",
113
+ reason: refusal.reason,
114
+ forceable: refusal.forceable,
115
+ },
112
116
  branchName: plan.kind === "worktree"
113
117
  ? plan.worktree.branchName
114
118
  : plan.kind === "worktree-unlocatable"
@@ -116,7 +120,7 @@ export function keptReport(agentId, source, plan, settlement, reason, paneStatus
116
120
  : undefined,
117
121
  settlement,
118
122
  pane: plan.pane
119
- ? { kind: paneStatus, paneId: plan.pane.paneId }
123
+ ? { kind: "open", paneId: plan.pane.paneId }
120
124
  : { kind: "none" },
121
125
  worktree,
122
126
  branch: { kind: "not-applicable" },
@@ -130,6 +134,7 @@ export function ambiguousReport(agentId, source, settlement, candidates) {
130
134
  outcome: {
131
135
  kind: "refused",
132
136
  reason: { kind: "ambiguous-artifacts", candidates },
137
+ forceable: false,
133
138
  },
134
139
  settlement,
135
140
  pane: { kind: "none" },
@@ -137,11 +142,22 @@ export function ambiguousReport(agentId, source, settlement, candidates) {
137
142
  branch: { kind: "not-applicable" },
138
143
  };
139
144
  }
140
- export function assembleReport(agentId, source, plan, settlement, removal) {
145
+ /**
146
+ * The `forced` marker a teardown earned by overriding a removability gate, as a
147
+ * fragment for its `torn-down` outcome (`{}` for a routine teardown). The tool
148
+ * never forces, so only the menu sets it — and every teardown path spreads this,
149
+ * so the marker is invariant.
150
+ */
151
+ export function forcedFields(opts) {
152
+ return opts?.force !== undefined ? { forced: opts.force } : {};
153
+ }
154
+ export function assembleReport(agentId, source, plan, settlement, removal, opts) {
141
155
  return {
142
156
  agentId,
143
157
  source,
144
- outcome: { kind: "torn-down" },
158
+ // A forced teardown states it overrode a gate, so its report line cannot be
159
+ // mistaken for a routine one (see forcedFields).
160
+ outcome: { kind: "torn-down", ...forcedFields(opts) },
145
161
  branchName: plan.kind === "worktree" ? plan.worktree.branchName : undefined,
146
162
  settlement,
147
163
  pane: removal.pane,
@@ -149,6 +165,14 @@ export function assembleReport(agentId, source, plan, settlement, removal) {
149
165
  branch: removal.branch,
150
166
  };
151
167
  }
168
+ /**
169
+ * Whether the operator override can change a refusal's answer. The menu offers
170
+ * Force only for these: a live run, a contested id, and a tree with no address
171
+ * force can reach are final refusals, not candidates for a second attempt.
172
+ */
173
+ export function isForceableRefusal(report) {
174
+ return report.outcome.kind === "refused" && report.outcome.forceable;
175
+ }
152
176
  /**
153
177
  * Drop a spawn once its tracked resources are gone; a kept/failed tree
154
178
  * keeps its spawn so status still shows why. An absent tree drops too: a
@@ -25,7 +25,8 @@ function formatSettlement(settlement) {
25
25
  ? settlement.phase
26
26
  : `unrecorded (basis: ${formatBasis(settlement.basis)})`;
27
27
  }
28
- function formatKeptReason(reason) {
28
+ /** The refusal wording, shared by the report and the menu's force dialog. */
29
+ export function formatKeptReason(reason) {
29
30
  switch (reason.kind) {
30
31
  case "dirty":
31
32
  return "has uncommitted changes";
@@ -78,11 +79,17 @@ function branchText(report) {
78
79
  : "not applicable";
79
80
  return `${text}${report.branchName ? ` (${report.branchName})` : ""}`;
80
81
  }
81
- /** The report's opening line: a refusal says it refused and why; a teardown says it finished. */
82
+ /** The forced clause a teardown earned by overriding a gate; empty otherwise. */
83
+ function forcedClause(forced) {
84
+ if (!forced)
85
+ return "";
86
+ return ` forced${forced.reason ? ` — ${formatKeptReason(forced.reason)}` : ""}`;
87
+ }
88
+ /** The report's opening line: a refusal says it refused and why; a teardown says it finished, and whether an operator override was in play. */
82
89
  function headline(report) {
83
90
  return report.outcome.kind === "refused"
84
91
  ? `Did not clean up agent ${report.agentId}: ${formatKeptReason(report.outcome.reason)}`
85
- : `Cleaned up agent ${report.agentId}:`;
92
+ : `Cleaned up agent ${report.agentId}${forcedClause(report.outcome.forced)}:`;
86
93
  }
87
94
  /** The tool's report: what happened to the run, its pane, worktree and branch. */
88
95
  export function renderCleanupReport(report) {
@@ -28,13 +28,19 @@ export class GitCommandRunner {
28
28
  constructor(pi) {
29
29
  this.pi = pi;
30
30
  }
31
- /** Run git; `undefined` when `pi.exec` itself fails (transport/timeout). */
31
+ /** Run git; `undefined` when the run produced no answer — `pi.exec` failed, or the child was killed (timeout/abort). */
32
32
  async run(args, cwd, timeoutMs = GIT_EXEC_TIMEOUT_MS) {
33
33
  try {
34
34
  const result = await this.pi.exec("git", [...args], {
35
35
  cwd,
36
36
  timeout: timeoutMs,
37
37
  });
38
+ // `pi.exec` reports a child it killed as exit 0 (see cow-clone.ts's hard
39
+ // requirement). A killed run answered nothing — reading it as a
40
+ // successful empty result is how a timed-out `git status` becomes
41
+ // "clean" and how a dirty worktree gets destroyed.
42
+ if (result.killed)
43
+ return undefined;
38
44
  return {
39
45
  code: result.code,
40
46
  stdout: result.stdout.trim(),
@@ -6,7 +6,6 @@
6
6
  * worktrees are interpreted in git-retention.ts, branch deletion policy in
7
7
  * git-merger.ts.
8
8
  */
9
- import { GIT_EXEC_TIMEOUT_MS } from "../../utils.js";
10
9
  import { GitError, GitCommandRunner, GIT_WORKTREE_TIMEOUT_MS, } from "./git-runner.js";
11
10
  /** Budget (ms) for the read-only questions a picker asks: a scan must stay snappy. */
12
11
  const WORKTREE_SCAN_TIMEOUT_MS = 5_000;
@@ -33,7 +32,10 @@ export class GitWorktree {
33
32
  }
34
33
  /** Whether the checkout has uncommitted changes; `undefined` is not clean. */
35
34
  async isDirty() {
36
- const status = await this.status({ timeoutMs: GIT_EXEC_TIMEOUT_MS });
35
+ // The probe budget (not the 5s exec budget): `git status` on a big, cold
36
+ // checkout routinely outlives the latter, and a shorter kill would only
37
+ // surface as a spurious "unverifiable".
38
+ const status = await this.status();
37
39
  if (status === undefined)
38
40
  return undefined;
39
41
  return status !== "";
@@ -239,3 +239,7 @@ export function createSearchableSelect(items, callbacks, theme) {
239
239
  view = new SwappableView(selector);
240
240
  return view;
241
241
  }
242
+ /** How the status menu's off-menu actions name the ids they were handed. */
243
+ export function agentSubject(ids) {
244
+ return ids.length === 1 ? `agent ${ids[0]}` : `${ids.length} agent(s)`;
245
+ }
@@ -0,0 +1,203 @@
1
+ /**
2
+ * menu-agent-status-cleanup.ts — the status menu's two-phase cleanup workflow.
3
+ *
4
+ * A non-force pass runs first, in-menu, so a refusal the operator can override
5
+ * can be surfaced where the decision belongs. When (and only when) a run refuses
6
+ * for a *forceable* reason, the workflow offers `Force`, then a destructive
7
+ * confirmation that names the checkout and what force would discard. Everything
8
+ * else — the successful teardowns, the refusals force cannot touch — is reported
9
+ * as it lands, and a clean sweep closes the menu.
10
+ *
11
+ * The force override lives here so it can never leak into `cleanup_cowboy_agent`:
12
+ * the tool takes no options, and this is the only caller that passes `force`.
13
+ */
14
+ import { SelectList, } from "@earendil-works/pi-tui";
15
+ import { cleanupNeedsAttention, formatKeptReason, summarizeCleanupReport, } from "../../agents/cleanup-report.js";
16
+ import { isForceableRefusal, } from "../../agents/cleanup-policy.js";
17
+ import { getManagerOrNull } from "../../shell.js";
18
+ import { errorMessage } from "../../utils.js";
19
+ import { createKeyConfirm } from "./submenus/confirm.js";
20
+ import { actionReport, agentSubject, buildSelectListTheme, withVimKeys, } from "./helpers.js";
21
+ /**
22
+ * Run a cleanup pass over `ids` sequentially — teardowns share herdr/git state,
23
+ * so items never run in parallel — building each id's options from `optsFor`.
24
+ * Never throws: a per-id failure rides as `error`, so one id's outcome never
25
+ * blocks the rest.
26
+ */
27
+ async function runCleanupPass(ids, optsFor) {
28
+ const manager = getManagerOrNull();
29
+ if (!manager) {
30
+ return ids.map((id) => ({
31
+ id,
32
+ kind: "error",
33
+ error: "manager unavailable",
34
+ }));
35
+ }
36
+ const outcomes = [];
37
+ for (const id of ids) {
38
+ try {
39
+ outcomes.push({
40
+ id,
41
+ kind: "report",
42
+ report: await manager.cleanup(id, optsFor(id)),
43
+ });
44
+ }
45
+ catch (err) {
46
+ outcomes.push({ id, kind: "error", error: errorMessage(err) });
47
+ }
48
+ }
49
+ return outcomes;
50
+ }
51
+ /** Emit one terminal notification per outcome, with the wording the tool reports. */
52
+ function reportCleanupOutcomes(ctx, outcomes) {
53
+ const action = actionReport(ctx.ui);
54
+ for (const outcome of outcomes) {
55
+ if (outcome.kind === "report") {
56
+ action.succeeded(summarizeCleanupReport(outcome.report), cleanupNeedsAttention(outcome.report) ? "warning" : "info");
57
+ }
58
+ else {
59
+ action.failed(`Failed to clean up agent ${outcome.id}`, outcome.error);
60
+ }
61
+ }
62
+ }
63
+ /** The refusal a report carries, or undefined when the run was not refused. */
64
+ function refusalReason(report) {
65
+ return report.outcome.kind === "refused" ? report.outcome.reason : undefined;
66
+ }
67
+ /** The worktree a refusal kept, when it named one. */
68
+ function refusalWorktreePath(report) {
69
+ return report.worktree.kind === "kept"
70
+ ? (report.worktree.path ?? undefined)
71
+ : undefined;
72
+ }
73
+ /** The offer's phrasing of why force applies; the headline's wording reads after a colon, not after "anyway?". */
74
+ function offerReason(reason) {
75
+ switch (reason.kind) {
76
+ case "dirty":
77
+ return "It has uncommitted changes";
78
+ case "unverifiable":
79
+ return `Its state could not be verified (${reason.detail})`;
80
+ case "recovered-refusal":
81
+ return "Herdr still reports it at work";
82
+ default:
83
+ return formatKeptReason(reason);
84
+ }
85
+ }
86
+ /** A minimal in-menu status body shown while a slow cleanup pass runs. */
87
+ function progressBody(theme, message) {
88
+ return {
89
+ invalidate() { },
90
+ render: () => [` ${theme.fg("dim", message)}`],
91
+ };
92
+ }
93
+ /** The first force dialog: Force first, Cancel second, Esc cancels. */
94
+ function forceOfferList(theme, message, onForce, onCancel) {
95
+ const items = [
96
+ { value: "force", label: "Force", description: message },
97
+ {
98
+ value: "cancel",
99
+ label: "Cancel",
100
+ description: "Keep the worktree and its changes",
101
+ },
102
+ ];
103
+ const list = withVimKeys(new SelectList(items, 6, buildSelectListTheme(theme)));
104
+ list.onSelect = (item) => (item.value === "force" ? onForce() : onCancel());
105
+ list.onCancel = onCancel;
106
+ return list;
107
+ }
108
+ /**
109
+ * Build the cleanup entry point for the status menu. The returned callback runs
110
+ * the two-phase flow for `ids`; the menu stays open through the force decision
111
+ * and only a clean sweep (or a confirmed force) closes it.
112
+ */
113
+ export function createStatusCleanup(deps) {
114
+ const { ctx, theme, view, refresh, close, requestRender } = deps;
115
+ /** Swap the body and repaint (a swap with no keypress behind it gets no repaint). */
116
+ const show = (body) => {
117
+ view.activate(body);
118
+ requestRender();
119
+ };
120
+ /** The second force step: spell out the consequence and require a Y. */
121
+ const askForceConfirm = (idsToForce, reasons, detailLines, onNo) => {
122
+ const single = idsToForce.length === 1;
123
+ show(createKeyConfirm({
124
+ theme,
125
+ message: single
126
+ ? `Force cleanup of agent ${idsToForce[0]}?`
127
+ : `Force cleanup of ${idsToForce.length} agents?`,
128
+ detail: [
129
+ ...detailLines,
130
+ "",
131
+ single
132
+ ? "This DELETES its worktree and anything uncommitted in it."
133
+ : "This DELETES their worktrees and anything uncommitted in them.",
134
+ ].join("\n"),
135
+ onNo,
136
+ onYes: () => {
137
+ // The decision is made: hand the teardown back to run off-menu.
138
+ close();
139
+ actionReport(ctx.ui).pending(`Forcing cleanup of ${agentSubject(idsToForce)}`);
140
+ void (async () => {
141
+ const forced = await runCleanupPass(idsToForce, (id) => {
142
+ const reason = reasons.get(id);
143
+ return { force: reason ? { reason } : {} };
144
+ });
145
+ reportCleanupOutcomes(ctx, forced);
146
+ })();
147
+ },
148
+ }));
149
+ };
150
+ /** The first force step: offer Force beside Cancel; Esc backs out. */
151
+ const offerForce = (refusals) => {
152
+ const reasons = new Map();
153
+ for (const { id, report } of refusals) {
154
+ const reason = refusalReason(report);
155
+ if (reason)
156
+ reasons.set(id, reason);
157
+ }
158
+ const idsToForce = [...reasons.keys()];
159
+ const single = idsToForce.length === 1;
160
+ const detailLines = refusals.map(({ id, report }) => {
161
+ const reason = refusalReason(report);
162
+ const named = reason
163
+ ? single
164
+ ? formatKeptReason(reason)
165
+ : `${id}: ${formatKeptReason(reason)}`
166
+ : `${id}: kept`;
167
+ const path = refusalWorktreePath(report);
168
+ return path ? `${named} (${path})` : named;
169
+ });
170
+ const only = reasons.get(idsToForce[0] ?? "");
171
+ const message = single
172
+ ? `Clean up agent ${idsToForce[0]} anyway? ${only ? offerReason(only) : "kept"}.`
173
+ : `Clean up ${idsToForce.length} agents anyway?`;
174
+ // Backing out reports the reasons the dialog would have shown, then refreshes.
175
+ const backOut = () => {
176
+ reportCleanupOutcomes(ctx, refusals);
177
+ refresh();
178
+ };
179
+ show(forceOfferList(theme, message, () => askForceConfirm(idsToForce, reasons, detailLines, backOut), backOut));
180
+ };
181
+ /** Run one id set through both phases; see the module header for the shape. */
182
+ return (ids) => {
183
+ show(progressBody(theme, `Cleaning up ${agentSubject(ids)}\u2026`));
184
+ void (async () => {
185
+ const first = await runCleanupPass(ids, () => undefined);
186
+ const refusals = first.filter((o) => o.kind === "report" && isForceableRefusal(o.report));
187
+ const refusalIds = new Set(refusals.map((o) => o.id));
188
+ // Report everything that is settled now; forceable refusals wait for the dialog.
189
+ reportCleanupOutcomes(ctx, first.filter((o) => !refusalIds.has(o.id)));
190
+ if (refusals.length > 0) {
191
+ offerForce(refusals);
192
+ return;
193
+ }
194
+ const needsAttention = first.some((o) => o.kind === "error" || cleanupNeedsAttention(o.report));
195
+ // A refusal or failure leaves the agent listed with its reason; only a
196
+ // clean sweep closes the menu.
197
+ if (needsAttention)
198
+ refresh();
199
+ else
200
+ close();
201
+ })();
202
+ };
203
+ }
@@ -1,7 +1,9 @@
1
1
  /**
2
2
  * menu-agent-status.ts — the agent list (active and settled) and per-agent
3
3
  * actions. Snapshot at construction; re-entry refreshes. Actions focus the
4
- * subagent's herdr pane instead of an in-extension viewer.
4
+ * subagent's herdr pane instead of an in-extension viewer. The two-phase
5
+ * cleanup flow — including the menu-only force override — lives in
6
+ * menu-agent-status-cleanup.ts.
5
7
  * Exports: showAgentStatusMenu, buildAgentActionsList.
6
8
  */
7
9
  import { matchesKey, SelectList, truncateToWidth, visibleWidth, } from "@earendil-works/pi-tui";
@@ -9,9 +11,9 @@ import { ALL_AGENT_PHASES, hasOutcome, isActivePhase, lifecycleResult, lifecycle
9
11
  import { errorMessage } from "../../utils.js";
10
12
  import { getDisplayName, agentBulletPrefix, formatMs, statusIcon, } from "../format.js";
11
13
  import { getManagerOrNull, getRuntime } from "../../shell.js";
12
- import { cleanupNeedsAttention, summarizeCleanupReport, } from "../../agents/cleanup-report.js";
13
14
  import { ScreenHost, SwappableView, asListFields } from "./screen-host.js";
14
- import { SEPARATOR_ID, actionReport, buildSelectListTheme, installSeparatorSkip, withVimKeys, } from "./helpers.js";
15
+ import { createStatusCleanup } from "./menu-agent-status-cleanup.js";
16
+ import { SEPARATOR_ID, actionReport, agentSubject, buildSelectListTheme, installSeparatorSkip, withVimKeys, } from "./helpers.js";
15
17
  import { SettingsListWrapper } from "./wrappers/settings-list.js";
16
18
  /** Focus the subagent's herdr tab. */
17
19
  async function focusHerdrPane(ctx, spawn) {
@@ -120,10 +122,6 @@ async function showTextViewer(ctx, spawn, kind, text) {
120
122
  };
121
123
  });
122
124
  }
123
- /** How the off-menu helpers name the ids they were handed. */
124
- function agentSubject(ids) {
125
- return ids.length === 1 ? `agent ${ids[0]}` : `${ids.length} agent(s)`;
126
- }
127
125
  /**
128
126
  * Stop agents without holding the menu open, and report the outcome once each
129
127
  * stop settles. A stop waits on herdr's registry and the run's settle pass, so
@@ -169,38 +167,13 @@ function stopAgentsOffMenu(ctx, ids) {
169
167
  }
170
168
  })();
171
169
  }
172
- /**
173
- * Clean agents up without holding the menu open, and report each teardown as
174
- * it lands. Cleanup closes panes, removes worktrees and deletes merged
175
- * branches, so callers hand the UI back first.
176
- */
177
- function cleanupAgentsOffMenu(ctx, ids) {
178
- const manager = getManagerOrNull();
179
- const idSubject = agentSubject(ids);
180
- const action = actionReport(ctx.ui);
181
- if (!manager) {
182
- action.failed(`Failed to clean up ${idSubject}`, "manager unavailable");
183
- return;
184
- }
185
- void (async () => {
186
- for (const id of ids) {
187
- try {
188
- const report = await manager.cleanup(id);
189
- action.succeeded(summarizeCleanupReport(report), cleanupNeedsAttention(report) ? "warning" : "info");
190
- }
191
- catch (err) {
192
- action.failed(`Failed to clean up agent ${id}`, err);
193
- }
194
- }
195
- })();
196
- }
197
170
  /**
198
171
  * Per-agent actions submenu for a delegating component.
199
172
  * @param done — return to the parent agent list.
200
- * @param setActive — swap the delegating component's active child.
201
173
  * @param onClose — close the entire menu.
174
+ * @param beginCleanup — start the two-phase cleanup flow over these ids.
202
175
  */
203
- export function buildAgentActionsList(ctx, spawn, theme, done, setActive, onClose) {
176
+ export function buildAgentActionsList(ctx, spawn, theme, done, onClose, beginCleanup) {
204
177
  const items = [];
205
178
  // Spawn id is the full handle — printed whole, never sliced.
206
179
  const id = spawn.id;
@@ -258,11 +231,9 @@ export function buildAgentActionsList(ctx, spawn, theme, done, setActive, onClos
258
231
  stopAgentsOffMenu(ctx, [spawn.id]);
259
232
  }
260
233
  else if (item.value === "cleanup") {
261
- // The spawn record goes with the artifacts, so the list it came from is
262
- // stale either way: close, and report the teardown when it lands.
263
- actionReport(ctx.ui).pending(`Cleaning up agent ${id}`);
264
- onClose();
265
- cleanupAgentsOffMenu(ctx, [spawn.id]);
234
+ // The flow keeps the menu open for the force decision, then hands the
235
+ // teardown back to run off-menu; it reports every outcome itself.
236
+ beginCleanup([spawn.id]);
266
237
  }
267
238
  };
268
239
  list.onCancel = () => done();
@@ -270,16 +241,16 @@ export function buildAgentActionsList(ctx, spawn, theme, done, setActive, onClos
270
241
  }
271
242
  export async function showAgentStatusMenu(ctx) {
272
243
  // Settled spawns outlive their session, so list them here.
273
- const agents = getManagerOrNull()?.listAgents(ALL_AGENT_PHASES) ?? [];
274
- if (agents.length === 0) {
244
+ if ((getManagerOrNull()?.listAgents(ALL_AGENT_PHASES) ?? []).length === 0) {
275
245
  ctx.ui.notify("No agents have been spawned this session", "info");
276
246
  return;
277
247
  }
278
- // Active work is never cleaned up
279
- const activeAgents = agents.filter((r) => isActivePhase(r.lifecycle.phase));
280
- const finished = agents.filter((r) => !isActivePhase(r.lifecycle.phase));
281
- const completed = agents.filter((r) => hasOutcome(r.lifecycle) && r.lifecycle.status === "completed");
282
- await new ScreenHost(ctx).open(({ theme, close }) => {
248
+ await new ScreenHost(ctx).open(({ tui, theme, close }) => {
249
+ // Re-read on refresh: a cleanup drops the spawns whose artifacts it removed.
250
+ let agents = getManagerOrNull()?.listAgents(ALL_AGENT_PHASES) ?? [];
251
+ const activeAgents = () => agents.filter((r) => isActivePhase(r.lifecycle.phase));
252
+ const finishedAgents = () => agents.filter((r) => !isActivePhase(r.lifecycle.phase));
253
+ const completedAgents = () => agents.filter((r) => hasOutcome(r.lifecycle) && r.lifecycle.status === "completed");
283
254
  const buildAgentItems = () => {
284
255
  // One timestamp for every row keeps durations mutually consistent.
285
256
  const now = Date.now();
@@ -306,11 +277,14 @@ export async function showAgentStatusMenu(ctx) {
306
277
  label: `${icon} ${spawn.id} ${bullet}${spawn.display.type} ${status} ${duration}${wtInfo}${suffix}${ago}`,
307
278
  };
308
279
  });
309
- if (activeAgents.length > 0) {
280
+ const active = activeAgents();
281
+ const finished = finishedAgents();
282
+ const completed = completedAgents();
283
+ if (active.length > 0) {
310
284
  items.push({ value: SEPARATOR_ID, label: " " });
311
285
  items.push({
312
286
  value: "__stop-all",
313
- label: `Stop ${activeAgents.length} active agent(s)`,
287
+ label: `Stop ${active.length} active agent(s)`,
314
288
  });
315
289
  }
316
290
  if (finished.length > 0) {
@@ -333,31 +307,51 @@ export async function showAgentStatusMenu(ctx) {
333
307
  // SelectList never lands on separators itself.
334
308
  installSeparatorSkip(asListFields(agentList));
335
309
  const view = new SwappableView(agentList);
310
+ /** Repaint: pi-tui redraws on input, but a swap driven by an async pass has none. */
311
+ const requestRender = () => tui.requestRender();
312
+ /** Re-read the fleet and rebuild the rows in place (removed agents drop out), keeping the cursor on `focusId` when it survives. */
313
+ const refresh = (focusId) => {
314
+ agents = getManagerOrNull()?.listAgents(ALL_AGENT_PHASES) ?? [];
315
+ const fields = asListFields(agentList);
316
+ const items = buildAgentItems();
317
+ fields.items = items;
318
+ fields.filteredItems = items;
319
+ const at = focusId
320
+ ? items.findIndex((item) => item.value === focusId)
321
+ : -1;
322
+ agentList.setSelectedIndex(at >= 0 ? at : 0);
323
+ view.activate(agentList);
324
+ requestRender();
325
+ };
326
+ // The two-phase cleanup flow owns the force dialogs; the menu stays open
327
+ // through the decision and only a clean sweep (or a confirmed force) closes.
328
+ const beginCleanup = createStatusCleanup({
329
+ ctx,
330
+ theme,
331
+ view,
332
+ refresh,
333
+ close,
334
+ requestRender,
335
+ });
336
336
  agentList.onSelect = async (item) => {
337
337
  if (item.value === "__stop-all") {
338
- actionReport(ctx.ui).pending(`Stopping ${activeAgents.length} agent(s)`);
338
+ const active = activeAgents();
339
+ actionReport(ctx.ui).pending(`Stopping ${active.length} agent(s)`);
339
340
  close();
340
- stopAgentsOffMenu(ctx, activeAgents.map((r) => r.id));
341
+ stopAgentsOffMenu(ctx, active.map((r) => r.id));
341
342
  return;
342
343
  }
343
344
  if (item.value === "__cleanup-finished") {
344
- actionReport(ctx.ui).pending(`Cleaning up ${finished.length} settled agent(s)`);
345
- close();
346
- cleanupAgentsOffMenu(ctx, finished.map((r) => r.id));
345
+ beginCleanup(finishedAgents().map((r) => r.id));
347
346
  return;
348
347
  }
349
348
  if (item.value === "__cleanup-completed") {
350
- actionReport(ctx.ui).pending(`Cleaning up ${completed.length} completed agent(s)`);
351
- close();
352
- cleanupAgentsOffMenu(ctx, completed.map((r) => r.id));
349
+ beginCleanup(completedAgents().map((r) => r.id));
353
350
  return;
354
351
  }
355
352
  const spawn = agents.find((r) => r.id === item.value);
356
353
  if (spawn) {
357
- const actionsList = buildAgentActionsList(ctx, spawn, theme, () => {
358
- view.activate(agentList);
359
- }, view.activate.bind(view), () => close());
360
- view.activate(actionsList);
354
+ view.activate(buildAgentActionsList(ctx, spawn, theme, () => refresh(spawn.id), () => close(), beginCleanup));
361
355
  }
362
356
  };
363
357
  agentList.onCancel = () => close();
@@ -1,5 +1,6 @@
1
- /** confirm-submenu.ts — yes/no confirm dialog for destructive SettingsList rows. */
2
- import { SelectList } from "@earendil-works/pi-tui";
1
+ /** confirm-submenu.ts — yes/no confirm dialogs for destructive menu actions. */
2
+ import { matchesKey, SelectList, truncateToWidth, } from "@earendil-works/pi-tui";
3
+ import { asSubmenuComponent } from "../screen-host.js";
3
4
  import { buildSelectListTheme, withVimKeys } from "../helpers.js";
4
5
  export function createConfirmSubmenu(options) {
5
6
  return (_currentValue, done) => {
@@ -21,3 +22,39 @@ export function createConfirmSubmenu(options) {
21
22
  return list;
22
23
  };
23
24
  }
25
+ /**
26
+ * Key-driven yes/no dialog: Y confirms, N or Escape cancels. Its message and
27
+ * detail are free text, so a destructive action's consequence can be spelled
28
+ * out in full — unlike the single-line row descriptions a SelectList shows.
29
+ */
30
+ export function createKeyConfirm(options) {
31
+ const body = {
32
+ invalidate() { },
33
+ render(width) {
34
+ const innerW = Math.max(0, width - 4);
35
+ const line = (text) => ` ${truncateToWidth(text, innerW, "...", true)}`;
36
+ const lines = [line(options.theme.bold(options.message))];
37
+ if (options.detail) {
38
+ for (const part of options.detail.split("\n"))
39
+ lines.push(line(part));
40
+ }
41
+ lines.push(line(options.theme.fg("dim", "Y yes \u00b7 N no")));
42
+ return lines;
43
+ },
44
+ handleInput(data) {
45
+ // Y accepts shift+y (a capital Y arrives as the legacy uppercase form).
46
+ if (matchesKey(data, "y") || matchesKey(data, "shift+y")) {
47
+ options.onYes();
48
+ return;
49
+ }
50
+ // Escape and N both mean no; every other key is ignored.
51
+ if (matchesKey(data, "n") ||
52
+ matchesKey(data, "shift+n") ||
53
+ matchesKey(data, "escape")) {
54
+ options.onNo();
55
+ }
56
+ },
57
+ };
58
+ // Focusable, so the hosting frame routes every key straight here.
59
+ return asSubmenuComponent(body);
60
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-cowboy",
3
- "version": "0.14.1",
3
+ "version": "0.15.1",
4
4
  "type": "module",
5
5
  "packageManager": "pnpm@12.9.1",
6
6
  "description": "Agent orchestrator for pi: can manage Codex, Claude Code, OpenCode, pi, pig and pi-bolt as subagents. Runs subagents in background Herdr panes, isolated in copy-on-write Git worktrees.",
@@ -96,7 +96,7 @@
96
96
  "eslint": "^10.12.0",
97
97
  "eslint-plugin-import-x": "^4.17.1",
98
98
  "husky": "^9.1.7",
99
- "oxlint": "1.87.0",
99
+ "oxlint": "1.88.0",
100
100
  "oxlint-tsgolint": "7.0.2004",
101
101
  "prettier": "^3.9.9",
102
102
  "semantic-release": "^25.0.9",