brl-subagent 2.7.0 → 2.9.0

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.
Files changed (51) hide show
  1. package/AGENT.md +3 -3
  2. package/README.md +18 -10
  3. package/package.json +6 -5
  4. package/src/agent-tools.ts +332 -0
  5. package/src/background-pipeline.ts +1025 -0
  6. package/src/boot-recovery.ts +313 -0
  7. package/src/commands.ts +137 -0
  8. package/src/concurrency.ts +26 -5
  9. package/src/delegate-handler.ts +2261 -0
  10. package/src/engineering-bar.ts +69 -0
  11. package/src/event-bus.ts +10 -0
  12. package/src/git.ts +274 -5
  13. package/src/headstate.ts +471 -0
  14. package/src/history.ts +21 -3
  15. package/src/index.ts +127 -3943
  16. package/src/kill-escalation.ts +87 -7
  17. package/src/loader.ts +47 -1
  18. package/src/logging.ts +1 -1
  19. package/src/mode-prologue.ts +4 -10
  20. package/src/mode-runners.ts +1575 -0
  21. package/src/notify-completion.ts +180 -12
  22. package/src/params.ts +211 -37
  23. package/src/preflight.ts +123 -16
  24. package/src/prelude.ts +92 -7
  25. package/src/presets.ts +85 -18
  26. package/src/proc.ts +2 -3
  27. package/src/project-flags.ts +3 -3
  28. package/src/recovery-engine.ts +11 -1
  29. package/src/recovery-surface.ts +1 -2
  30. package/src/recovery.ts +155 -20
  31. package/src/reports.ts +1 -7
  32. package/src/run-registry.ts +22 -3
  33. package/src/runner.ts +80 -21
  34. package/src/runtime.ts +50 -0
  35. package/src/sanitize.ts +20 -2
  36. package/src/scheduler.ts +1 -2
  37. package/src/schema.ts +37 -7
  38. package/src/scratch-root.ts +909 -0
  39. package/src/scratch-spawn.ts +256 -0
  40. package/src/session-manager.ts +854 -200
  41. package/src/state.ts +130 -30
  42. package/src/templates.ts +42 -17
  43. package/src/terminal-notifier.ts +405 -0
  44. package/src/transcript.ts +1 -1
  45. package/src/tui-format.ts +177 -7
  46. package/src/tui.ts +115 -57
  47. package/src/types.ts +206 -5
  48. package/src/unit-params.ts +113 -0
  49. package/src/unit-run.ts +45 -16
  50. package/src/validate.ts +89 -11
  51. package/src/worktree-report.ts +142 -0
@@ -0,0 +1,313 @@
1
+ // Purpose: Boot recovery — the interrupted-run scan, the boot head-state reconcile and the recovery notices, built over one runtime context.
2
+ /**
3
+ * brl-subagent — the boot recovery cluster (cycle S4, ADR 0027 D3/D5/D6)
4
+ *
5
+ * `performBootRecovery`, `reconcileHeadStatesAtBoot` and the two notice surfaces
6
+ * used to be closures inside `src/index.ts`'s default export, alongside the
7
+ * head-state deps wiring and the visibility bridge they share (`headStateDeps`,
8
+ * `visibleRunsFor`) and the abandon action the recovery notice offers
9
+ * (`abandonProductionRun`). They move here verbatim.
10
+ *
11
+ * D3: this module may import the `src/*.ts` modules it needs, and NOT the
12
+ * composition root — `architecture-rules` forbids a non-entry module importing
13
+ * `index.ts`. The three bindings the moved bodies read from their old closure
14
+ * (`pi`, `log`, `state`) arrive as the `RuntimeContext` argument; everything else
15
+ * they touch was already a module import, so this factory takes no `deps`. The
16
+ * session-manager reads inside the bodies stay `await import("./session-manager")`
17
+ * at their original statement position: those are the lifecycle mutators
18
+ * (`markAgentInterrupted`, `updateAgentStatus`, `pruneBackgroundSession`) the
19
+ * reader-API rule keeps off non-entry modules' STATIC imports, and ADR 0027's
20
+ * recorded limit is that the rule cannot see dynamic destructuring — so the lazy
21
+ * load and its await position are preserved rather than converted to a static
22
+ * import (which would hoist a load the boot path must not perform early).
23
+ *
24
+ * D5: `recoveryNoticeDelivered` is a `let` INSIDE this factory, never
25
+ * module-private. Two `initExtension` instances must not share the once-per-boot
26
+ * latch: one runtime's shutdown reset would otherwise re-arm (or silence) the
27
+ * other's notice. `resetRecoveryNotice` is how the owning runtime re-arms it.
28
+ *
29
+ * The move is verbatim. `createBootRecovery` destructures its context on its
30
+ * first lines and the bodies carry their original indentation, so a body line
31
+ * that differs from 91b286d is a bug in this commit, not a refactor. The two
32
+ * non-verbatim pieces are named in the PR: the factory wrapper itself
33
+ * (`rt` destructure + the latch declaration) and `resetRecoveryNotice`.
34
+ */
35
+
36
+ import type { RuntimeContext } from "./runtime";
37
+ import type { SubagentRun } from "./types";
38
+ import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
39
+ import { getHeadBranch, getRepoRoot, hasUncommittedChanges, listWorkBranches, restoreHead } from "./git";
40
+ import { buildHeadStateNotice, reconcileHeadStates, sweepHeadStates, type HeadStateDeps, type HeadStateOutcome } from "./headstate";
41
+ import { classifyOwner, defaultRecoveryDeps, recoverProduction } from "./recovery";
42
+ import {
43
+ abandonInterruptedRun,
44
+ buildRecoveryNotice,
45
+ collectInterruptedRuns,
46
+ offeredInterruptedRuns,
47
+ resolveRecoveryNoticeDelivery,
48
+ visibleRunEntriesForSession,
49
+ type RecoveryAgentLookup,
50
+ } from "./recovery-surface";
51
+ import { clearInflightRun, listInflightRuns, markInterrupted } from "./run-registry";
52
+ import { resolveTerminalRunEntry } from "./state";
53
+ import { pruneHistoryIfNeeded } from "./unit-run";
54
+
55
+ /**
56
+ * The boot cluster's returned capabilities. Declared (not exported) for the same
57
+ * reason as the background pipeline's interface: the factory's return value IS
58
+ * the interface the composition root consumes, so the returned object and this
59
+ * declaration cannot drift.
60
+ */
61
+ interface BootRecovery {
62
+ performBootRecovery: () => Promise<void>;
63
+ reconcileHeadStatesAtBoot: () => HeadStateOutcome[];
64
+ maybeSendHeadStateNotice: (outcomes: HeadStateOutcome[]) => void;
65
+ maybeSendRecoveryNotice: (ctx: ExtensionContext) => Promise<void>;
66
+ abandonProductionRun: (ctx: ExtensionContext, id: string) => Promise<void>;
67
+ /**
68
+ * Fix A's visibility bridge, shared with the composition root's `retryRunId`
69
+ * branch — the second consumer that resolves a run id (see `visibleRunsFor`).
70
+ */
71
+ visibleRunsFor: (ctx: ExtensionContext, getAgent: RecoveryAgentLookup) => SubagentRun[];
72
+ /**
73
+ * D5: re-arm the once-per-boot latch. The shutdown handler calls this where
74
+ * the closure used to assign `recoveryNoticeDelivered = false` inline — the
75
+ * latch belongs to this instance, so only its owner can reset it.
76
+ */
77
+ resetRecoveryNotice: () => void;
78
+ }
79
+
80
+ /**
81
+ * Build the boot recovery cluster over one runtime context (ADR 0027 D1/D3).
82
+ *
83
+ * The destructure re-creates, as locals, the names the bodies read from their old
84
+ * closure, so every moved statement stays byte-identical.
85
+ */
86
+ export function createBootRecovery(rt: RuntimeContext): BootRecovery {
87
+ const { pi, log, state } = rt;
88
+
89
+ // Option B U3 (D2): "one recovery notice per boot". The boot scan may be
90
+ // followed by more session_starts in the same process (reload); without this
91
+ // guard every one would re-list the same interrupted runs. Reset on shutdown
92
+ // so a genuinely new session notifies again. ADR 0027 D5: per factory
93
+ // instance — a module-private latch would be shared by two runtimes.
94
+ let recoveryNoticeDelivered = false;
95
+
96
+ // -------------------------------------------------------------------
97
+ // Option B U1: boot recovery — identity/liveness detection + child reap
98
+ // -------------------------------------------------------------------
99
+ // Runs AFTER restoreFromSession so config is ready. Candidate runs come from
100
+ // the DURABLE registry (`.pi/run-registry/`), NOT from this session's run
101
+ // entries: a crashed session's foreground/unit records are invisible to a
102
+ // default fresh startup, and the full `.pi/subagents/` store is too costly to
103
+ // parse (only the one agent record a background entry names is read). For
104
+ // each in-flight run whose owner is dead, its orphaned marker-verified child
105
+ // is reaped and the record is marked: the registry entry always, plus the
106
+ // agent record for background runs. The scan itself is SILENT in the UI —
107
+ // U3's `maybeSendRecoveryNotice` (below) is the one notice surface.
108
+ // Platforms without /proc skip the whole scan (one log line):
109
+ // pid-only liveness cannot rule out pid reuse, so nothing is killed or
110
+ // marked unverified.
111
+ async function performBootRecovery(): Promise<void> {
112
+ try {
113
+ const { getAgent, markAgentInterrupted } = await import("./session-manager");
114
+ // `recoverProduction` owns the /proc platform guard (nothing is marked or
115
+ // killed without start-token verification) — see src/recovery.ts.
116
+ const summary = await recoverProduction({
117
+ log,
118
+ // Read THAT ONE agent record by id — never the whole store.
119
+ readAgentRecord: (id) => getAgent(id),
120
+ mark(record, interruptedAt) {
121
+ // Registry entry = the durable mark for every kind. Issue #304: its
122
+ // boolean is the durable-write result — do NOT drop it, or the boot
123
+ // summary would claim a mark that never landed. The scan counts a
124
+ // `false` as `markFailures` and warns with the id.
125
+ const durable = markInterrupted(record.id, interruptedAt);
126
+ if (record.kind === "agent") markAgentInterrupted(record.id, interruptedAt);
127
+ return durable;
128
+ },
129
+ // Issue #447: a dispatch whose acceptance marker is still `null` never
130
+ // reached `session.prompt()`. It is finalized `failed` here — a
131
+ // terminal write, so `persistRunRecord` retires the registry entry in
132
+ // the same call and no interrupted/retry surface can pick it up.
133
+ finalizeNeverStarted: (run) => {
134
+ state.persistRun(pi, run);
135
+ },
136
+ });
137
+ // Report the scan whenever it did anything durable OR attempted a mark
138
+ // that failed — a failure-only boot must not be silent (issue #304).
139
+ if (summary.marked > 0 || summary.markFailures > 0) {
140
+ log.warn("Boot recovery marked interrupted runs", { ...summary });
141
+ }
142
+ // Issue #447: never-started dispatches are finalized, not marked — a
143
+ // separate line so the two outcomes cannot be read as one another.
144
+ if (summary.neverStarted > 0) {
145
+ log.info("Boot recovery finalized never-started dispatches", {
146
+ count: summary.neverStarted,
147
+ });
148
+ }
149
+ } catch (err) {
150
+ // Recovery is best-effort hygiene — it must never break session start.
151
+ log.warn("Boot recovery scan failed", { error: (err as Error).message });
152
+ }
153
+ }
154
+
155
+ /**
156
+ * Issue #466 (ADR 0026 D2): the git/process surface the head-state table
157
+ * reads, wired once so the boot step and its tests cannot drift apart.
158
+ */
159
+ function headStateDeps(): HeadStateDeps {
160
+ const procDeps = defaultRecoveryDeps();
161
+ return {
162
+ getRepoRoot,
163
+ classifyOwner: (owner) => classifyOwner(owner, procDeps),
164
+ getHeadBranch,
165
+ restoreHead,
166
+ hasUncommittedChanges,
167
+ listWorkBranches,
168
+ };
169
+ }
170
+
171
+ /**
172
+ * Issue #466: the boot's ONE git-mutating step, between the scan (which only
173
+ * marks records) and the notices. Best-effort like the scan — a failing store
174
+ * must never break session start — but every record still ends in exactly one
175
+ * LOGGED verdict (D5: silence is not a verdict).
176
+ *
177
+ * The repair itself is NEVER gated by `config.recovery`: a tree left on a dead
178
+ * run's branch is a correctness problem, not a recovery offer. Only the notice
179
+ * below is gated.
180
+ */
181
+ function reconcileHeadStatesAtBoot(): HeadStateOutcome[] {
182
+ try {
183
+ const outcomes = reconcileHeadStates(headStateDeps());
184
+ for (const outcome of outcomes) {
185
+ log.info("Boot head-state verdict", { ...outcome });
186
+ }
187
+ // Housekeeping, never part of the repair contract: only a record whose
188
+ // repository no longer resolves (or that cannot be parsed) is swept, so
189
+ // a live orphan's base is never deleted by age.
190
+ const swept = sweepHeadStates({
191
+ repoGone: (record) => getRepoRoot(record.repoRoot) === undefined,
192
+ });
193
+ if (swept > 0) log.info("Swept stale head-state records", { count: swept });
194
+ return outcomes;
195
+ } catch (err) {
196
+ log.warn("Boot head-state reconciliation failed", { error: (err as Error).message });
197
+ return [];
198
+ }
199
+ }
200
+
201
+ /**
202
+ * Issue #466 (D5): the repair and the needs-manual verdict reach the user
203
+ * once, on the same `nextTurn` channel as the recovery notice, and are gated
204
+ * by `config.recovery !== "off"` like every other boot surface.
205
+ */
206
+ function maybeSendHeadStateNotice(outcomes: HeadStateOutcome[]): void {
207
+ if (state.config.recovery === "off") return;
208
+ const notice = buildHeadStateNotice(outcomes);
209
+ if (!notice) return;
210
+ try {
211
+ pi.sendMessage(notice, resolveRecoveryNoticeDelivery());
212
+ log.info("Head-state notice delivered", { count: notice.details.count });
213
+ } catch (err) {
214
+ // The notice is best-effort — it must never break session start.
215
+ log.warn("Head-state notice failed", { error: (err as Error).message });
216
+ }
217
+ }
218
+
219
+ /**
220
+ * Option B U3 Fix A: the recovery visibility bridge, wired for the two
221
+ * extension consumers that resolve a run id (the retryRunId branch and the
222
+ * abandon action). Session run entries UNIONED with synthetic durable
223
+ * interrupted records the session has never seen (a genuine fresh boot), so
224
+ * an id named by the boot notice resolves here instead of being rejected as
225
+ * not found. `getAgent` is injected because the callers already load it
226
+ * dynamically — this keeps the registry/agent reads in ONE place.
227
+ */
228
+ function visibleRunsFor(
229
+ ctx: ExtensionContext,
230
+ getAgent: RecoveryAgentLookup,
231
+ ): SubagentRun[] {
232
+ return visibleRunEntriesForSession(state.getLogicalRunEntries(ctx), getAgent);
233
+ }
234
+
235
+ /**
236
+ * Option B U3 (D2): after the boot scan, send ONE notice at the next turn
237
+ * boundary listing every unresolved interrupted run whose dispatch snapshot
238
+ * (and the session posture) says "offer". Delivery is `nextTurn` — the notice
239
+ * can never steer or arrive mid-turn (see `resolveRecoveryNoticeDelivery`).
240
+ * Silent when there is nothing to offer; at most once per session start.
241
+ */
242
+ async function maybeSendRecoveryNotice(ctx: ExtensionContext): Promise<void> {
243
+ if (recoveryNoticeDelivered) return;
244
+ recoveryNoticeDelivered = true;
245
+ // Session posture off silences the whole surface, regardless of per-run
246
+ // snapshots (a user opting out expects quiet).
247
+ if (state.config.recovery === "off") return;
248
+ try {
249
+ const { getAgent } = await import("./session-manager");
250
+ const offered = offeredInterruptedRuns(
251
+ collectInterruptedRuns({
252
+ listInflight: () => listInflightRuns(),
253
+ getAgent: (id) => getAgent(id),
254
+ findRun: (id) => state.findTerminalRunById(ctx, id),
255
+ }),
256
+ );
257
+ if (offered.length === 0) return;
258
+ pi.sendMessage(buildRecoveryNotice(offered), resolveRecoveryNoticeDelivery());
259
+ log.info("Recovery notice delivered", { count: offered.length });
260
+ } catch (err) {
261
+ // The notice is best-effort — it must never break session start.
262
+ log.warn("Recovery notice failed", { error: (err as Error).message });
263
+ }
264
+ }
265
+
266
+ /**
267
+ * Option B U3 (D5): finalize ONE interrupted run as the existing terminal
268
+ * `stopped` outcome and prune its U2 session dir. Wired through injected deps
269
+ * so the pure core (`recovery-surface.ts`) stays testable; the run record is
270
+ * written terminal (the run store's `status` union has no `stopped` — a
271
+ * stopped outcome is represented as `failed` + `errorCategory: "aborted"`,
272
+ * exactly as every other stop path does) and the background agent record is
273
+ * flipped to `stopped`.
274
+ */
275
+ async function abandonProductionRun(ctx: ExtensionContext, id: string): Promise<void> {
276
+ const { updateAgentStatus, pruneBackgroundSession, getAgent } = await import("./session-manager");
277
+ // Fix A: the abandon lookup routes through the visibility bridge, so a run
278
+ // that exists ONLY in the durable registry after a fresh boot is
279
+ // abandonable instead of resolving to undefined (the silent `false`).
280
+ const visible = visibleRunsFor(ctx, getAgent);
281
+ abandonInterruptedRun(id, {
282
+ getRun: (runId) => resolveTerminalRunEntry(visible, runId),
283
+ writeRun: (run) => {
284
+ state.persistRun(pi, run);
285
+ pruneHistoryIfNeeded(state, ctx, log);
286
+ },
287
+ markAgentStopped: (agentId) => {
288
+ const agent = updateAgentStatus(agentId, "stopped");
289
+ if (agent) log.info("Abandoned background agent record", { agentId });
290
+ },
291
+ retireRegistry: (runId) => clearInflightRun(runId),
292
+ pruneSession: (runId) => pruneBackgroundSession(runId),
293
+ });
294
+ }
295
+ /**
296
+ * Issue #437-adjacent (ADR 0027 D5): the shutdown re-arm the closure performed
297
+ * inline. `session_shutdown` still runs it at the same position in the handler
298
+ * sequence, so a later boot in the same runtime notifies again.
299
+ */
300
+ function resetRecoveryNotice(): void {
301
+ recoveryNoticeDelivered = false;
302
+ }
303
+
304
+ return {
305
+ performBootRecovery,
306
+ reconcileHeadStatesAtBoot,
307
+ maybeSendHeadStateNotice,
308
+ maybeSendRecoveryNotice,
309
+ abandonProductionRun,
310
+ visibleRunsFor,
311
+ resetRecoveryNotice,
312
+ };
313
+ }
@@ -0,0 +1,137 @@
1
+ // Purpose: The /brl-subagent command definition — its argument completions and the handler table — returned to the composition root to register.
2
+ /**
3
+ * brl-subagent — the command surface (ADR 0027 S5, issue #483)
4
+ *
5
+ * `pi.registerCommand("brl-subagent", { … })` used to be a ~50-line object
6
+ * literal inside `src/index.ts`'s default export. The definition moves here; the
7
+ * REGISTRATION does not (D7): `index.ts` still calls `pi.registerCommand` with
8
+ * what this factory returns, so the surface is composed in exactly one place.
9
+ *
10
+ * Two rules this module must keep, because the table is stateful per invocation:
11
+ *
12
+ * - **No stale `ctx`.** Every handler reads `state` from the runtime and takes
13
+ * `ctx` from the per-call `handler(args, ctx)` signature. A `ctx` captured at
14
+ * factory time would be the previous session's context — the whole reason the
15
+ * table is built inside the handler rather than beside it.
16
+ * - **No `create*` factory here.** `applyConfig`/`resetState` (config writes
17
+ * owned by the composition root) and `abandonProductionRun` (the S4 boot
18
+ * factory's, whose notice latch is per-instance — D5) arrive through `deps`.
19
+ * Building a second one would give this module a second instance of state the
20
+ * runtime owns exactly once.
21
+ */
22
+
23
+ import type { RuntimeContext } from "./runtime";
24
+ import type { ExtensionContext, RegisteredCommand } from "@earendil-works/pi-coding-agent";
25
+ import {
26
+ showApprovalModeSelector,
27
+ showCompletionNotifySelector,
28
+ showComplianceMenu,
29
+ showConcurrencyInput,
30
+ showConfigMenu,
31
+ showCostLimitInput,
32
+ showDashboard,
33
+ showDepthInput,
34
+ showHistoryEntriesInput,
35
+ showModelSelector,
36
+ showMonitor,
37
+ showPresetManager,
38
+ showRecoverySelector,
39
+ showRetryMenu,
40
+ showRunHistory,
41
+ showSLAConfig,
42
+ showSLAStats,
43
+ showTemplateManager,
44
+ showThinkingSelector,
45
+ } from "./tui";
46
+
47
+ /**
48
+ * What the command table needs from the composition root — injected, never
49
+ * rebuilt here (see the header: a second config writer or a second boot factory
50
+ * would be a second owner of state the runtime holds once).
51
+ *
52
+ * Deliberately narrow (interface segregation): each entry is the exact call the
53
+ * table makes, not the factory that produced it.
54
+ */
55
+ export interface CommandDeps {
56
+ /** Persist a config change, repaint the footer and notify the user. */
57
+ applyConfig: (ctx: ExtensionContext, message: string) => void;
58
+ /** Factory-reset the configuration (and reload the file-backed templates). */
59
+ resetState: (ctx: ExtensionContext) => void;
60
+ /** The S4 boot cluster's abandon action, behind the retry menu. */
61
+ abandonProductionRun: (ctx: ExtensionContext, id: string) => Promise<void>;
62
+ }
63
+
64
+ /**
65
+ * The command definition `pi.registerCommand` consumes. `name` and `sourceInfo`
66
+ * are the registrar's (it is called with the name), so they are excluded rather
67
+ * than invented here — the definition is exactly the object literal the call
68
+ * site used to inline.
69
+ */
70
+ export type BrlCommandDefinition = Omit<RegisteredCommand, "name" | "sourceInfo">;
71
+
72
+ /**
73
+ * Build the `/brl-subagent` definition over one runtime context (ADR 0027 D1/D3).
74
+ *
75
+ * The destructure re-creates the two names the moved table read from its old
76
+ * closure (`pi` for `persistState`, `state` for every menu). The table itself is
77
+ * built inside `handler`, so each invocation gets the live `ctx`.
78
+ */
79
+ export function createCommands(
80
+ rt: RuntimeContext,
81
+ deps: CommandDeps,
82
+ ): BrlCommandDefinition {
83
+ const { pi, state } = rt;
84
+ const { applyConfig, resetState, abandonProductionRun } = deps;
85
+
86
+ return {
87
+ description: "Configure subagent model and thinking level",
88
+ getArgumentCompletions: (prefix: string) => {
89
+ const options = [
90
+ "history", "historyentries", "monitor", "dashboard", "preset", "templates", "retry", "completionnotify", "recovery",
91
+ ];
92
+ const filtered = options.filter((o) => o.startsWith(prefix));
93
+ return filtered.length > 0
94
+ ? filtered.map((o) => ({ value: o, label: o }))
95
+ : null;
96
+ },
97
+ handler: async (args, ctx) => {
98
+ const trimmed = args?.trim();
99
+
100
+ const handlers: Record<string, () => Promise<void> | void> = {
101
+ model: () => showModelSelector(ctx, state, applyConfig),
102
+ thinking: () => showThinkingSelector(ctx, state, applyConfig),
103
+ concurrency: () => showConcurrencyInput(ctx, state, applyConfig),
104
+ depth: () => showDepthInput(ctx, state, applyConfig),
105
+ approval: () => showApprovalModeSelector(ctx, state, applyConfig),
106
+ completionnotify: () => showCompletionNotifySelector(ctx, state, applyConfig),
107
+ recovery: () => showRecoverySelector(ctx, state, applyConfig),
108
+ costlimit: () => showCostLimitInput(ctx, state, applyConfig),
109
+ reset: () => resetState(ctx),
110
+ history: () => showRunHistory(ctx, state, () => state.persistState(pi)),
111
+ historyentries: () => showHistoryEntriesInput(ctx, state, applyConfig),
112
+ monitor: () => showMonitor(ctx, state),
113
+ dashboard: () => showDashboard(ctx, state),
114
+ preset: () => showPresetManager(ctx, state),
115
+ templates: () => showTemplateManager(ctx, state),
116
+ retry: () => showRetryMenu(ctx, state, (id) => abandonProductionRun(ctx, id)),
117
+ sla: () => showSLAConfig(ctx, state, applyConfig),
118
+ "sla-stats": () => showSLAStats(ctx, state),
119
+ // E5: the compliance report menu (file access / secrets exposure /
120
+ // full summary) shipped in tui.ts but had no handler key, so
121
+ // `/brl-subagent compliance` fell through to the config menu and the
122
+ // feature was unreachable (broken wiring, not dead code).
123
+ compliance: () => showComplianceMenu(ctx, state),
124
+ };
125
+
126
+ if (trimmed && trimmed in handlers) {
127
+ await handlers[trimmed]();
128
+ } else if (trimmed?.startsWith("templates")) {
129
+ await handlers.templates();
130
+ } else if (trimmed?.startsWith("preset")) {
131
+ await handlers.preset();
132
+ } else {
133
+ await showConfigMenu(ctx, state, handlers);
134
+ }
135
+ },
136
+ };
137
+ }
@@ -9,11 +9,10 @@
9
9
  * acquireSlot/releaseSlot, eliminating races between parallel completions.
10
10
  */
11
11
 
12
- import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
13
- import type { Priority } from "./types";
14
- import { PRIORITY_ORDER } from "./types";
15
12
  import type { SessionState } from "./state";
16
- import { LIVE_SPINNER_FRAME_MS, formatProgressStatus } from "./tui-format";
13
+ import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
14
+ import { PRIORITY_ORDER, type Priority } from "./types";
15
+ import { LIVE_SPINNER_FRAME_MS, computeProgressTimes, formatProgressStatus, type LiveBudgetInput } from "./tui-format";
17
16
 
18
17
  // ---------------------------------------------------------------------------
19
18
  // Slot management
@@ -121,9 +120,31 @@ const STATUS_RESET_DELAY_MS = 3000;
121
120
 
122
121
  /** Repaint the footer from the current counters (issue #354). */
123
122
  function renderProgressStatus(state: SessionState, ctx: ExtensionContext): void {
123
+ const now = Date.now();
124
+ // Issue #423: the footer's clocks come from the LIVE map, with settled ids
125
+ // excluded — a finalized row must not keep a deadline on screen. The input
126
+ // is built explicitly (the formatter no longer reads the whole state) so the
127
+ // counter slice and the clock slice stay separable.
128
+ const live: LiveBudgetInput[] = [];
129
+ for (const [id, session] of state.subagentSessions) {
130
+ if (state.isLiveEntryFinalized(id)) continue;
131
+ live.push(session);
132
+ }
124
133
  ctx.ui.setStatus(
125
134
  "brl-subagent",
126
- formatProgressStatus(state, Date.now(), ctx.ui.theme),
135
+ formatProgressStatus(
136
+ {
137
+ activeSubagents: state.activeSubagents,
138
+ completedSubagents: state.completedSubagents,
139
+ failedSubagents: state.failedSubagents,
140
+ unseenSubagents: state.unseenSubagents,
141
+ modeContext: state.modeContext,
142
+ activeSinceMs: state.activeSinceMs,
143
+ times: computeProgressTimes(live, now),
144
+ },
145
+ now,
146
+ ctx.ui.theme,
147
+ ),
127
148
  );
128
149
  }
129
150