brl-subagent 2.8.0 → 2.9.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/AGENT.md +17 -2
- package/README.md +3 -3
- package/package.json +6 -5
- package/src/agent-tools.ts +332 -0
- package/src/background-pipeline.ts +1025 -0
- package/src/boot-recovery.ts +360 -0
- package/src/commands.ts +137 -0
- package/src/concurrency.ts +3 -5
- package/src/delegate-handler.ts +2261 -0
- package/src/engineering-bar.ts +1 -1
- package/src/git.ts +220 -8
- package/src/headstate.ts +3 -3
- package/src/history.ts +21 -3
- package/src/index.ts +109 -4473
- package/src/loader.ts +1 -1
- package/src/logging.ts +67 -4
- package/src/mode-prologue.ts +4 -10
- package/src/mode-runners.ts +1575 -0
- package/src/notify-completion.ts +35 -8
- package/src/params.ts +14 -13
- package/src/preflight.ts +123 -16
- package/src/prelude.ts +14 -5
- package/src/presets.ts +3 -5
- package/src/proc.ts +2 -3
- package/src/recovery-engine.ts +1 -1
- package/src/recovery-surface.ts +1 -2
- package/src/recovery.ts +238 -10
- package/src/reports.ts +1 -7
- package/src/run-registry.ts +133 -10
- package/src/runner.ts +47 -18
- package/src/runtime.ts +50 -0
- package/src/sanitize.ts +20 -2
- package/src/scheduler.ts +1 -2
- package/src/schema.ts +4 -2
- package/src/scratch-root.ts +909 -0
- package/src/scratch-spawn.ts +256 -0
- package/src/session-manager.ts +587 -81
- package/src/state.ts +12 -14
- package/src/templates.ts +3 -5
- package/src/terminal-notifier.ts +405 -0
- package/src/transcript.ts +1 -1
- package/src/tui-format.ts +3 -1
- package/src/tui.ts +46 -36
- package/src/types.ts +29 -3
- package/src/unit-params.ts +113 -0
- package/src/unit-run.ts +35 -15
- package/src/validate.ts +28 -9
- package/src/worktree-report.ts +142 -0
|
@@ -0,0 +1,360 @@
|
|
|
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
|
+
// Issue #546 (major 6): the whole session-manager wiring — the record-flip
|
|
113
|
+
// applier included — is built at the EXISTING lazy import site and in its own
|
|
114
|
+
// containment. A failure there leaves `wiring` undefined: the scan still runs
|
|
115
|
+
// over the run registry, and `applyRecordFlip`/`readFreshAgentRecord` are not
|
|
116
|
+
// passed at all, so the scan takes its no-applier branch (the pre-#546
|
|
117
|
+
// behaviour: markers untouched). No half-wired repair is possible.
|
|
118
|
+
//
|
|
119
|
+
// The import must stay DYNAMIC: a static named import of a lifecycle mutator
|
|
120
|
+
// violates the reader-API rule in architecture-rules.test.ts (the allow-list
|
|
121
|
+
// is `getAgent`/`listAgents`; a dynamic `import()` edge carries no names
|
|
122
|
+
// there), and it would load session-manager on every extension start.
|
|
123
|
+
let sm: typeof import("./session-manager") | undefined;
|
|
124
|
+
try {
|
|
125
|
+
sm = await import("./session-manager");
|
|
126
|
+
} catch (err) {
|
|
127
|
+
log.warn("Boot recovery: session-manager unavailable — running the registry-only scan", {
|
|
128
|
+
error: (err as Error).message,
|
|
129
|
+
});
|
|
130
|
+
}
|
|
131
|
+
const wiring = sm;
|
|
132
|
+
try {
|
|
133
|
+
// `recoverProduction` owns the /proc platform guard (nothing is marked or
|
|
134
|
+
// killed without start-token verification) — see src/recovery.ts.
|
|
135
|
+
const summary = await recoverProduction({
|
|
136
|
+
log,
|
|
137
|
+
// Read THAT ONE agent record by id — never the whole store.
|
|
138
|
+
readAgentRecord: wiring ? (id) => wiring.getAgent(id) : undefined,
|
|
139
|
+
mark(record, interruptedAt) {
|
|
140
|
+
// Registry entry = the durable mark for every kind. Issue #304: its
|
|
141
|
+
// boolean is the durable-write result — do NOT drop it, or the boot
|
|
142
|
+
// summary would claim a mark that never landed. The scan counts a
|
|
143
|
+
// `false` as `markFailures` and warns with the id.
|
|
144
|
+
const durable = markInterrupted(record.id, interruptedAt);
|
|
145
|
+
if (record.kind === "agent") wiring?.markAgentInterrupted(record.id, interruptedAt);
|
|
146
|
+
return durable;
|
|
147
|
+
},
|
|
148
|
+
// Issue #447: a dispatch whose acceptance marker is still `null` never
|
|
149
|
+
// reached `session.prompt()`. It is finalized `failed` here — a
|
|
150
|
+
// terminal write, so `persistRunRecord` retires the registry entry in
|
|
151
|
+
// the same call and no interrupted/retry surface can pick it up.
|
|
152
|
+
finalizeNeverStarted: (run) => {
|
|
153
|
+
state.persistRun(pi, run);
|
|
154
|
+
},
|
|
155
|
+
...(wiring
|
|
156
|
+
? {
|
|
157
|
+
// Issue #546 (major 3): the pre-flip read is DISK-ONLY — `getAgent`
|
|
158
|
+
// is memory-first and a stale map would re-stamp a settled record.
|
|
159
|
+
readFreshAgentRecord: (id: string) => wiring.readAgentRecordFromDisk(id),
|
|
160
|
+
// Issue #546: the terminal write whose process died before the
|
|
161
|
+
// agent record was flipped. The two writes belong together — the
|
|
162
|
+
// registry entry IS the marker, so it may be retired only once
|
|
163
|
+
// the flip is durable. The outcome is passed through, and a
|
|
164
|
+
// settlement that did not land (record write OR unlink, major 4)
|
|
165
|
+
// keeps the entry for the next boot.
|
|
166
|
+
applyRecordFlip: (verdict) => {
|
|
167
|
+
const outcome = wiring.flipAgentRecord(verdict.id, verdict.status, verdict.error);
|
|
168
|
+
if (outcome === false) return false;
|
|
169
|
+
return clearInflightRun(verdict.id) ? outcome : false;
|
|
170
|
+
},
|
|
171
|
+
}
|
|
172
|
+
: {}),
|
|
173
|
+
});
|
|
174
|
+
// Report the scan whenever it did anything durable OR attempted a mark
|
|
175
|
+
// that failed — a failure-only boot must not be silent (issue #304).
|
|
176
|
+
if (summary.marked > 0 || summary.markFailures > 0) {
|
|
177
|
+
log.warn("Boot recovery marked interrupted runs", { ...summary });
|
|
178
|
+
}
|
|
179
|
+
// Issue #447: never-started dispatches are finalized, not marked — a
|
|
180
|
+
// separate line so the two outcomes cannot be read as one another.
|
|
181
|
+
// Issue #546: record flips a dead process left pending. A separate line
|
|
182
|
+
// from both the interrupted marks and the never-started finalizes — this
|
|
183
|
+
// outcome rewrites the AGENT RECORD, which neither of those does.
|
|
184
|
+
if (summary.flipRepaired > 0 || summary.flipRetired > 0 || summary.flipFailures > 0) {
|
|
185
|
+
log.warn("Boot recovery settled pending record flips", {
|
|
186
|
+
repaired: summary.flipRepaired,
|
|
187
|
+
retired: summary.flipRetired,
|
|
188
|
+
failures: summary.flipFailures,
|
|
189
|
+
});
|
|
190
|
+
}
|
|
191
|
+
if (summary.neverStarted > 0) {
|
|
192
|
+
log.info("Boot recovery finalized never-started dispatches", {
|
|
193
|
+
count: summary.neverStarted,
|
|
194
|
+
});
|
|
195
|
+
}
|
|
196
|
+
} catch (err) {
|
|
197
|
+
// Recovery is best-effort hygiene — it must never break session start.
|
|
198
|
+
log.warn("Boot recovery scan failed", { error: (err as Error).message });
|
|
199
|
+
}
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
/**
|
|
203
|
+
* Issue #466 (ADR 0026 D2): the git/process surface the head-state table
|
|
204
|
+
* reads, wired once so the boot step and its tests cannot drift apart.
|
|
205
|
+
*/
|
|
206
|
+
function headStateDeps(): HeadStateDeps {
|
|
207
|
+
const procDeps = defaultRecoveryDeps();
|
|
208
|
+
return {
|
|
209
|
+
getRepoRoot,
|
|
210
|
+
classifyOwner: (owner) => classifyOwner(owner, procDeps),
|
|
211
|
+
getHeadBranch,
|
|
212
|
+
restoreHead,
|
|
213
|
+
hasUncommittedChanges,
|
|
214
|
+
listWorkBranches,
|
|
215
|
+
};
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
/**
|
|
219
|
+
* Issue #466: the boot's ONE git-mutating step, between the scan (which only
|
|
220
|
+
* marks records) and the notices. Best-effort like the scan — a failing store
|
|
221
|
+
* must never break session start — but every record still ends in exactly one
|
|
222
|
+
* LOGGED verdict (D5: silence is not a verdict).
|
|
223
|
+
*
|
|
224
|
+
* The repair itself is NEVER gated by `config.recovery`: a tree left on a dead
|
|
225
|
+
* run's branch is a correctness problem, not a recovery offer. Only the notice
|
|
226
|
+
* below is gated.
|
|
227
|
+
*/
|
|
228
|
+
function reconcileHeadStatesAtBoot(): HeadStateOutcome[] {
|
|
229
|
+
try {
|
|
230
|
+
const outcomes = reconcileHeadStates(headStateDeps());
|
|
231
|
+
for (const outcome of outcomes) {
|
|
232
|
+
log.info("Boot head-state verdict", { ...outcome });
|
|
233
|
+
}
|
|
234
|
+
// Housekeeping, never part of the repair contract: only a record whose
|
|
235
|
+
// repository no longer resolves (or that cannot be parsed) is swept, so
|
|
236
|
+
// a live orphan's base is never deleted by age.
|
|
237
|
+
const swept = sweepHeadStates({
|
|
238
|
+
repoGone: (record) => getRepoRoot(record.repoRoot) === undefined,
|
|
239
|
+
});
|
|
240
|
+
if (swept > 0) log.info("Swept stale head-state records", { count: swept });
|
|
241
|
+
return outcomes;
|
|
242
|
+
} catch (err) {
|
|
243
|
+
log.warn("Boot head-state reconciliation failed", { error: (err as Error).message });
|
|
244
|
+
return [];
|
|
245
|
+
}
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
/**
|
|
249
|
+
* Issue #466 (D5): the repair and the needs-manual verdict reach the user
|
|
250
|
+
* once, on the same `nextTurn` channel as the recovery notice, and are gated
|
|
251
|
+
* by `config.recovery !== "off"` like every other boot surface.
|
|
252
|
+
*/
|
|
253
|
+
function maybeSendHeadStateNotice(outcomes: HeadStateOutcome[]): void {
|
|
254
|
+
if (state.config.recovery === "off") return;
|
|
255
|
+
const notice = buildHeadStateNotice(outcomes);
|
|
256
|
+
if (!notice) return;
|
|
257
|
+
try {
|
|
258
|
+
pi.sendMessage(notice, resolveRecoveryNoticeDelivery());
|
|
259
|
+
log.info("Head-state notice delivered", { count: notice.details.count });
|
|
260
|
+
} catch (err) {
|
|
261
|
+
// The notice is best-effort — it must never break session start.
|
|
262
|
+
log.warn("Head-state notice failed", { error: (err as Error).message });
|
|
263
|
+
}
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
/**
|
|
267
|
+
* Option B U3 Fix A: the recovery visibility bridge, wired for the two
|
|
268
|
+
* extension consumers that resolve a run id (the retryRunId branch and the
|
|
269
|
+
* abandon action). Session run entries UNIONED with synthetic durable
|
|
270
|
+
* interrupted records the session has never seen (a genuine fresh boot), so
|
|
271
|
+
* an id named by the boot notice resolves here instead of being rejected as
|
|
272
|
+
* not found. `getAgent` is injected because the callers already load it
|
|
273
|
+
* dynamically — this keeps the registry/agent reads in ONE place.
|
|
274
|
+
*/
|
|
275
|
+
function visibleRunsFor(
|
|
276
|
+
ctx: ExtensionContext,
|
|
277
|
+
getAgent: RecoveryAgentLookup,
|
|
278
|
+
): SubagentRun[] {
|
|
279
|
+
return visibleRunEntriesForSession(state.getLogicalRunEntries(ctx), getAgent);
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
/**
|
|
283
|
+
* Option B U3 (D2): after the boot scan, send ONE notice at the next turn
|
|
284
|
+
* boundary listing every unresolved interrupted run whose dispatch snapshot
|
|
285
|
+
* (and the session posture) says "offer". Delivery is `nextTurn` — the notice
|
|
286
|
+
* can never steer or arrive mid-turn (see `resolveRecoveryNoticeDelivery`).
|
|
287
|
+
* Silent when there is nothing to offer; at most once per session start.
|
|
288
|
+
*/
|
|
289
|
+
async function maybeSendRecoveryNotice(ctx: ExtensionContext): Promise<void> {
|
|
290
|
+
if (recoveryNoticeDelivered) return;
|
|
291
|
+
recoveryNoticeDelivered = true;
|
|
292
|
+
// Session posture off silences the whole surface, regardless of per-run
|
|
293
|
+
// snapshots (a user opting out expects quiet).
|
|
294
|
+
if (state.config.recovery === "off") return;
|
|
295
|
+
try {
|
|
296
|
+
const { getAgent } = await import("./session-manager");
|
|
297
|
+
const offered = offeredInterruptedRuns(
|
|
298
|
+
collectInterruptedRuns({
|
|
299
|
+
listInflight: () => listInflightRuns(),
|
|
300
|
+
getAgent: (id) => getAgent(id),
|
|
301
|
+
findRun: (id) => state.findTerminalRunById(ctx, id),
|
|
302
|
+
}),
|
|
303
|
+
);
|
|
304
|
+
if (offered.length === 0) return;
|
|
305
|
+
pi.sendMessage(buildRecoveryNotice(offered), resolveRecoveryNoticeDelivery());
|
|
306
|
+
log.info("Recovery notice delivered", { count: offered.length });
|
|
307
|
+
} catch (err) {
|
|
308
|
+
// The notice is best-effort — it must never break session start.
|
|
309
|
+
log.warn("Recovery notice failed", { error: (err as Error).message });
|
|
310
|
+
}
|
|
311
|
+
}
|
|
312
|
+
|
|
313
|
+
/**
|
|
314
|
+
* Option B U3 (D5): finalize ONE interrupted run as the existing terminal
|
|
315
|
+
* `stopped` outcome and prune its U2 session dir. Wired through injected deps
|
|
316
|
+
* so the pure core (`recovery-surface.ts`) stays testable; the run record is
|
|
317
|
+
* written terminal (the run store's `status` union has no `stopped` — a
|
|
318
|
+
* stopped outcome is represented as `failed` + `errorCategory: "aborted"`,
|
|
319
|
+
* exactly as every other stop path does) and the background agent record is
|
|
320
|
+
* flipped to `stopped`.
|
|
321
|
+
*/
|
|
322
|
+
async function abandonProductionRun(ctx: ExtensionContext, id: string): Promise<void> {
|
|
323
|
+
const { updateAgentStatus, pruneBackgroundSession, getAgent } = await import("./session-manager");
|
|
324
|
+
// Fix A: the abandon lookup routes through the visibility bridge, so a run
|
|
325
|
+
// that exists ONLY in the durable registry after a fresh boot is
|
|
326
|
+
// abandonable instead of resolving to undefined (the silent `false`).
|
|
327
|
+
const visible = visibleRunsFor(ctx, getAgent);
|
|
328
|
+
abandonInterruptedRun(id, {
|
|
329
|
+
getRun: (runId) => resolveTerminalRunEntry(visible, runId),
|
|
330
|
+
writeRun: (run) => {
|
|
331
|
+
state.persistRun(pi, run);
|
|
332
|
+
pruneHistoryIfNeeded(state, ctx, log);
|
|
333
|
+
},
|
|
334
|
+
markAgentStopped: (agentId) => {
|
|
335
|
+
const agent = updateAgentStatus(agentId, "stopped");
|
|
336
|
+
if (agent) log.info("Abandoned background agent record", { agentId });
|
|
337
|
+
},
|
|
338
|
+
retireRegistry: (runId) => clearInflightRun(runId),
|
|
339
|
+
pruneSession: (runId) => pruneBackgroundSession(runId),
|
|
340
|
+
});
|
|
341
|
+
}
|
|
342
|
+
/**
|
|
343
|
+
* Issue #437-adjacent (ADR 0027 D5): the shutdown re-arm the closure performed
|
|
344
|
+
* inline. `session_shutdown` still runs it at the same position in the handler
|
|
345
|
+
* sequence, so a later boot in the same runtime notifies again.
|
|
346
|
+
*/
|
|
347
|
+
function resetRecoveryNotice(): void {
|
|
348
|
+
recoveryNoticeDelivered = false;
|
|
349
|
+
}
|
|
350
|
+
|
|
351
|
+
return {
|
|
352
|
+
performBootRecovery,
|
|
353
|
+
reconcileHeadStatesAtBoot,
|
|
354
|
+
maybeSendHeadStateNotice,
|
|
355
|
+
maybeSendRecoveryNotice,
|
|
356
|
+
abandonProductionRun,
|
|
357
|
+
visibleRunsFor,
|
|
358
|
+
resetRecoveryNotice,
|
|
359
|
+
};
|
|
360
|
+
}
|
package/src/commands.ts
ADDED
|
@@ -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
|
+
}
|
package/src/concurrency.ts
CHANGED
|
@@ -9,12 +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 {
|
|
17
|
-
import type
|
|
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";
|
|
18
16
|
|
|
19
17
|
// ---------------------------------------------------------------------------
|
|
20
18
|
// Slot management
|