brl-subagent 2.8.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 (47) hide show
  1. package/AGENT.md +1 -1
  2. package/README.md +3 -3
  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 +3 -5
  9. package/src/delegate-handler.ts +2261 -0
  10. package/src/engineering-bar.ts +1 -1
  11. package/src/git.ts +220 -8
  12. package/src/headstate.ts +3 -3
  13. package/src/history.ts +21 -3
  14. package/src/index.ts +109 -4473
  15. package/src/loader.ts +1 -1
  16. package/src/logging.ts +1 -1
  17. package/src/mode-prologue.ts +4 -10
  18. package/src/mode-runners.ts +1575 -0
  19. package/src/notify-completion.ts +35 -8
  20. package/src/params.ts +14 -13
  21. package/src/preflight.ts +123 -16
  22. package/src/prelude.ts +14 -5
  23. package/src/presets.ts +3 -5
  24. package/src/proc.ts +2 -3
  25. package/src/recovery-engine.ts +1 -1
  26. package/src/recovery-surface.ts +1 -2
  27. package/src/recovery.ts +2 -3
  28. package/src/reports.ts +1 -7
  29. package/src/run-registry.ts +2 -3
  30. package/src/runner.ts +47 -18
  31. package/src/runtime.ts +50 -0
  32. package/src/sanitize.ts +20 -2
  33. package/src/scheduler.ts +1 -2
  34. package/src/scratch-root.ts +909 -0
  35. package/src/scratch-spawn.ts +256 -0
  36. package/src/session-manager.ts +75 -7
  37. package/src/state.ts +12 -14
  38. package/src/templates.ts +3 -5
  39. package/src/terminal-notifier.ts +405 -0
  40. package/src/transcript.ts +1 -1
  41. package/src/tui-format.ts +3 -1
  42. package/src/tui.ts +42 -32
  43. package/src/types.ts +29 -3
  44. package/src/unit-params.ts +113 -0
  45. package/src/unit-run.ts +35 -15
  46. package/src/validate.ts +2 -3
  47. package/src/worktree-report.ts +142 -0
@@ -0,0 +1,405 @@
1
+ // Purpose: The terminal notifier — the terminal event-bus subscriptions, their per-instance release latch, and the completion alert with its transport auto-retry.
2
+ /**
3
+ * brl-subagent — the terminal notifier (cycle S4, ADR 0027 D3/D5/D6)
4
+ *
5
+ * The `terminalTypes` table, the three event-bus subscriptions, their release
6
+ * latch (`terminalSubscriptions` / `terminalSubscriptionsReleased` /
7
+ * `releaseTerminalSubscriptions`), `scheduleTransportRetry`, its resume-preamble
8
+ * builder and `deliverCompletionAlert` used to be closures inside
9
+ * `src/index.ts`'s default export. They move here verbatim.
10
+ *
11
+ * D3: this module may import the `src/*.ts` modules it needs, and NOT the
12
+ * composition root. The three bindings the moved bodies read from their old
13
+ * closure (`pi`, `log`, `state`) arrive as the `RuntimeContext` argument, and the
14
+ * two capabilities the moved bodies cannot reach from here arrive as `deps`:
15
+ *
16
+ * - `getSession` is ADR 0027 D2. `sessionCtx` is written by `session_start` and
17
+ * stays a `let` in `index.ts`; the event-bus listener receives no ctx, so the
18
+ * composition root hands over a getter and every read site keeps its timing
19
+ * (the alert resolves the context AFTER the terminal claim, as before).
20
+ * - `spawnBackgroundRun` is the ONE backward edge (D6): the transport-retry path
21
+ * re-dispatches through the S3 background pipeline's spawn, which the
22
+ * composition root passes in. The field's signature mirrors
23
+ * `BackgroundPipeline["spawnBackgroundRun"]`; the wiring hands over that exact
24
+ * function, so a drift between the two is a compile error at the seam.
25
+ *
26
+ * D5: the subscription array and the released flag are factory-scoped, never
27
+ * module-private. A module-private latch would be shared by two `initExtension`
28
+ * instances, so one runtime's shutdown could unhook the other's listeners — or
29
+ * mark them released and never unhook them at all (the two-factory blocker:
30
+ * `a=1, b=0` where `b` should be 1).
31
+ *
32
+ * The move is verbatim. `createTerminalNotifier` destructures its context on its
33
+ * first lines and the bodies carry their original indentation, so a body line that
34
+ * differs from 91b286d is a bug in this commit, not a refactor. The three
35
+ * non-verbatim pieces are named in the PR: the factory wrapper (`rt`/`deps`
36
+ * destructure + the `return`), `getSession()` replacing the `sessionCtx` read, and
37
+ * `buildRetryResumePreamble` moving with its only caller.
38
+ *
39
+ * Issue #511 (U3) edits the one exception to that verbatim rule, and says so: the
40
+ * resume-preamble builder is no longer byte-identical to 91b286d (its bank path
41
+ * became the run's own `<scratchDir>/bank.md`), and it was hoisted to module
42
+ * scope — it reads no factory state — so the path logic could be unit-tested over
43
+ * a disposable run directory instead of through a spawned child.
44
+ */
45
+
46
+ import type { RuntimeContext } from "./runtime";
47
+ import type { DelegateTaskParams, SubagentEvent, SubagentEventListener, SubagentRun, ToolResult } from "./types";
48
+ import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
49
+ import * as fs from "node:fs";
50
+ import { isAbsolute, join } from "node:path";
51
+ import * as eventBus from "./event-bus";
52
+ import { resolveRetryParams } from "./history";
53
+ import {
54
+ buildCompletionMessage,
55
+ claimTerminalNotice,
56
+ resolveDelivery,
57
+ resolveRunEntry,
58
+ sendCompletionNotification,
59
+ withWorktreeState,
60
+ } from "./notify-completion";
61
+ import { bankPath, resolveRoot, RUNS_DIR, type RootOptions } from "./scratch-root";
62
+ import { isTransportRetryable, TRANSPORT_RETRY_TOAST } from "./transport-retry";
63
+ import { describeWorktreeState } from "./worktree-report";
64
+
65
+ /**
66
+ * The capabilities the moved bodies cannot reach from this module. Function fields
67
+ * only — no data crosses this seam (ADR 0027 D3/F2).
68
+ */
69
+ interface TerminalNotifierDeps {
70
+ /**
71
+ * ADR 0027 D2: `sessionCtx` stays a `let` in the composition root
72
+ * (`getSession: () => sessionCtx`). Read at the same spot the closure read the
73
+ * binding (`deliverCompletionAlert`), so the capture timing is unchanged.
74
+ */
75
+ getSession: () => ExtensionContext | undefined;
76
+ /**
77
+ * ADR 0027 D6: the ONE backward edge — the S3 pipeline's spawn, handed in by
78
+ * the composition root. Typed as that function so the wiring cannot pass a
79
+ * lookalike.
80
+ */
81
+ spawnBackgroundRun: (
82
+ pi: ExtensionAPI,
83
+ ctx: ExtensionContext,
84
+ params: (DelegateTaskParams & { noJev?: string }) | ReturnType<typeof resolveRetryParams>,
85
+ singleTask: string,
86
+ retrySourceRun?: SubagentRun,
87
+ attemptContext?: string,
88
+ ) => Promise<ToolResult<undefined>>;
89
+ }
90
+
91
+ /**
92
+ * What the composition root consumes: `release` is the shutdown hook (issue
93
+ * #437). Declared (not exported) for the same reason as the background
94
+ * pipeline's interface — the factory's return value IS the interface.
95
+ */
96
+ interface TerminalNotifier {
97
+ release: () => void;
98
+ }
99
+
100
+ /**
101
+ * Where the bank pointer's two filesystem questions are answered, injected by
102
+ * the tests: `exists` lets a unit test stand a run directory up somewhere
103
+ * disposable, and `root` moves the resolver's layout off the real home. Neither
104
+ * is needed in production, so both default to the real thing.
105
+ */
106
+ export interface RetryPreambleOptions {
107
+ /** Injectable existence probe; defaults to `fs.existsSync`. */
108
+ exists?: (path: string) => boolean;
109
+ /** Root-resolution inputs (`home` is the one that moves the layout); defaults to `resolveRoot()`. */
110
+ root?: RootOptions;
111
+ }
112
+
113
+ /** A run id is ONE path segment — the resolver's id rule, restated where the path is joined. */
114
+ function isPathSegment(id: string): boolean {
115
+ return id !== "" && id !== "." && id !== ".." && !id.includes("/") && !id.includes("\\");
116
+ }
117
+
118
+ /**
119
+ * The run's own directory — the durable record's `scratchDir` when it has one,
120
+ * otherwise `<root>/runs/<id>` recomputed. The crash-time in-flight registry
121
+ * carries no `scratchDir` (U2 of #511), and the path is deterministic from the
122
+ * run id, so a registry-only retry still names the right directory. The
123
+ * fallback is a recomputation, never a system-temp path: a bank in `/tmp` is
124
+ * the defect `scratch-root.ts` exists to remove.
125
+ */
126
+ function runDirectoryOf(run: SubagentRun, options: RetryPreambleOptions): string | undefined {
127
+ // A stored path is only usable if it is ABSOLUTE: the retry child can run in a
128
+ // different cwd (worktree/branch mode), so a relative bank path would resolve
129
+ // somewhere else — the same rule the recomputed half enforces on the id.
130
+ if (run.scratchDir !== undefined) return isAbsolute(run.scratchDir) ? run.scratchDir : undefined;
131
+ if (!isPathSegment(run.id)) return undefined;
132
+ try {
133
+ const resolved = resolveRoot(options.root);
134
+ return resolved.ok ? join(resolved.root, RUNS_DIR, run.id) : undefined;
135
+ } catch {
136
+ // `resolveRoot` reports rather than throws; a host whose home cannot be read
137
+ // at all (`os.homedir()` can raise) lands here. A prompt line is never worth a
138
+ // throw, so the sentence is simply dropped.
139
+ return undefined;
140
+ }
141
+ }
142
+
143
+ /**
144
+ * The bank's absolute path, or `undefined` when the run's directory is not
145
+ * really there. The gate is the same one the retained-session pointer uses, for
146
+ * the same reason: a legacy run (no `scratchDir`, no computed directory) and a
147
+ * pruned run must get no bank sentence at all rather than a dead path.
148
+ */
149
+ function bankPointer(run: SubagentRun, options: RetryPreambleOptions): string | undefined {
150
+ const exists = options.exists ?? fs.existsSync;
151
+ const runDir = runDirectoryOf(run, options);
152
+ return runDir !== undefined && exists(runDir) ? bankPath(runDir) : undefined;
153
+ }
154
+
155
+ /**
156
+ * Issue #401/#411: the resume preamble a transport auto-retry builds and delivers
157
+ * as a `<resume-context>` section on the child's system prompt — never inside
158
+ * the `<task>` fence. A dropped connection costs the child its context, not its
159
+ * files: the retry spawns into the same directory, so the work it already did
160
+ * (commits, written files, a bank) is still there. The preamble turns a blind
161
+ * replay into a resume by naming what to inspect first.
162
+ *
163
+ * Issue #511 (U3): the bank is the run's OWN file — `<runDir>/bank.md` under the
164
+ * shipped scratch root — named by its absolute path, and named only when the run
165
+ * directory exists. The pre-#511 `/tmp/brl-<label>-bank.md` convention (and the
166
+ * label sanitisation that existed only to build that filename) is gone: the path
167
+ * is id-based, so a label cannot reach it, and nothing in this builder points at
168
+ * a system temp directory.
169
+ *
170
+ * Kept bounded (5 lines max) and deliberately vetted for runtime vocabulary —
171
+ * it is prompt text a user can see in the child's system prompt.
172
+ *
173
+ * Issue #404: it also names the retained SDK session directory when one exists.
174
+ * That is the only artifact that holds attempt 1's CONVERSATION — the output log
175
+ * is a start/steering stub — and the settle path retains it for exactly this
176
+ * class of run. The pointer is absolute and computed conductor-side at build
177
+ * time: the retry's child can run in a different cwd (worktree/branch mode), so
178
+ * a relative path would point at the wrong tree. The exists gate is deliberate:
179
+ * an attempt whose session was not retained (size floor, marker failure, a
180
+ * legacy run) gets the bank-only preamble, never a dead path.
181
+ *
182
+ * A pure function at module scope on purpose: it reads no runtime context and no
183
+ * factory state, which is what lets it be unit-tested over a disposable run
184
+ * directory instead of through a spawned child.
185
+ */
186
+ export function buildRetryResumePreamble(
187
+ run: SubagentRun,
188
+ nextAttempt: number,
189
+ retainedSessionDir?: string,
190
+ options: RetryPreambleOptions = {},
191
+ ): string {
192
+ const bank = bankPointer(run, options);
193
+ const lines = [
194
+ `[attempt ${nextAttempt} — the previous attempt (${run.id}) died on a transport failure.`,
195
+ "This directory may already contain its uncommitted edits.",
196
+ bank === undefined
197
+ ? "Before acting, inspect: `git status --short` and `git log --oneline -8`."
198
+ : `Before acting, inspect: \`git status --short\`, \`git log --oneline -8\`, and the progress bank at ${bank} if it exists.`,
199
+ "Continue from what exists; do NOT redo committed, written, or banked work.]",
200
+ ];
201
+ if (retainedSessionDir) {
202
+ // Insert before the closing line so the block still reads as one unit.
203
+ lines.splice(
204
+ lines.length - 1,
205
+ 0,
206
+ `The previous attempt's session is retained at ${retainedSessionDir} — read the newest .jsonl inside (ISO-prefixed names sort lexicographically) to recover what it had worked out.`,
207
+ );
208
+ }
209
+ return lines.join("\n");
210
+ }
211
+
212
+ /**
213
+ * Build the terminal notifier over one runtime context (ADR 0027 D1/D3).
214
+ *
215
+ * Subscribing happens HERE, when the composition root calls this factory, which
216
+ * is the same point in `initExtension` the closure subscribed at — the bus sees
217
+ * the same registration order, and every subscription keeps its exact listener
218
+ * identity so `release` can remove precisely this instance's three.
219
+ */
220
+ export function createTerminalNotifier(rt: RuntimeContext, deps: TerminalNotifierDeps): TerminalNotifier {
221
+ const { pi, log, state } = rt;
222
+ const { getSession, spawnBackgroundRun } = deps;
223
+
224
+ // -------------------------------------------------------------------
225
+ // Issue #147: completion-push wake — subscribe to terminal event-bus events
226
+ // -------------------------------------------------------------------
227
+ // The event-bus is the complete terminal chokepoint (subagent:completed /
228
+ // subagent:failed / subagent:stopped), so the conductor is woken via
229
+ // pi.sendMessage + triggerTurn when a background run reaches a terminal state.
230
+ // Delivery is always-on (minimum nextTurn); the completionNotify knob controls
231
+ // the WAKE (D1+D2 — see notify-completion.ts). The shared terminal claim
232
+ // (issue #315) defends the pathological double-emit path (first terminal
233
+ // event or crash notice per id wins); it is capped simply (cleared when it
234
+ // exceeds 200 entries).
235
+ //
236
+ // Stopped-run degradation — ACCEPTED BY DESIGN (review #2, adjudicated
237
+ // 2026-09-01): subagent:stopped fires at stop time (updateAgentStatus) BEFORE
238
+ // finalizeRunEntry stamps cost/duration/errorCategory and before finalOutput
239
+ // is captured. So the stopped shape may lack those fields and the run entry
240
+ // resolveRunEntry returns may be the pre-finalize spawn entry. The wake is
241
+ // the point; details are best-effort — the notification must never throw or
242
+ // block on their absence.
243
+ const terminalTypes = ["subagent:completed", "subagent:failed", "subagent:stopped"] as const;
244
+
245
+ // Issue #437: keep the EXACT listener references this factory instance owns.
246
+ // Anonymous subscriptions could never be released, so a shut-down runtime's
247
+ // listeners stayed on the shared bus forever. Ownership is per factory
248
+ // invocation: the array and the released flag are this runtime's alone, so a
249
+ // replacement's listeners are never in the removal set.
250
+ const terminalSubscriptions: Array<{
251
+ type: (typeof terminalTypes)[number];
252
+ listener: SubagentEventListener;
253
+ }> = [];
254
+ let terminalSubscriptionsReleased = false;
255
+
256
+ /**
257
+ * Issue #437: unsubscribe exactly the listeners registered above.
258
+ *
259
+ * Idempotent — a repeated/double `session_shutdown` (or a late one after the
260
+ * replacement runtime is already live) is a no-op. Synchronous, so it can run
261
+ * as the first statement of `session_shutdown`, before any await or fallible
262
+ * cleanup. Never touches another subscriber or another runtime's listeners.
263
+ */
264
+ function releaseTerminalSubscriptions(): void {
265
+ if (terminalSubscriptionsReleased) return;
266
+ terminalSubscriptionsReleased = true;
267
+ for (const { type, listener } of terminalSubscriptions) {
268
+ eventBus.off(type, listener);
269
+ }
270
+ terminalSubscriptions.length = 0;
271
+ }
272
+
273
+ for (const type of terminalTypes) {
274
+ const listener: SubagentEventListener = (event) => {
275
+ void deliverCompletionAlert(event);
276
+ };
277
+ terminalSubscriptions.push({ type, listener });
278
+ eventBus.on(type, listener);
279
+ }
280
+
281
+ /**
282
+ * Issue #365: re-dispatch a background run that settled with a transport-class
283
+ * failure, using the `retryRunId` machinery. `resolveRetryParams({}, run)`
284
+ * restores the recorded params and `spawnBackgroundRun(..., run)` mints the
285
+ * lineage (`resumeOf` + `attempt: 2`), so the retry re-runs the normal gates
286
+ * (cost, approval, pre-task) and is visible in the record.
287
+ *
288
+ * Issue #401/#411: the retry carries a resume preamble (`attemptContext`) that
289
+ * is injected into the child's system prompt only (as a `<resume-context>`
290
+ * section), never inside the `<task>` fence. The task handed to
291
+ * `resolveSubagentParams` stays the recorded original, so auto-routing, H1
292
+ * keyword warnings and the capability checks behave exactly as they did on
293
+ * attempt 1.
294
+ *
295
+ * Returns TRUE when the retry was actually spawned — the caller then SUPPRESSES
296
+ * the source run's completion notice, because the retry's own terminal settle
297
+ * is the wake. A gate rejection or a throwing spawn returns FALSE and the
298
+ * caller reports the original failure exactly as before (no silent drop).
299
+ *
300
+ * Issue #439: this reads only `isError`, and a retry whose post-spawn tail
301
+ * faulted is still a SUCCESSFUL spawn (`isError: false`, degraded monitoring).
302
+ * It therefore returns TRUE for it: the source notice stays suppressed and the
303
+ * degraded advisory is the signal that the retry started with degraded
304
+ * monitoring. Reading a contained tail failure as "did not start" would
305
+ * surface the source failure for a run that is live.
306
+ */
307
+ async function scheduleTransportRetry(
308
+ ctx: ExtensionContext,
309
+ run: SubagentRun,
310
+ ): Promise<boolean> {
311
+ const sourceAttempt = run.attempt ?? 1;
312
+ try {
313
+ const retryParams = resolveRetryParams({}, run);
314
+ // Issue #404: point at the retained session ONLY when it is really
315
+ // there. Resolve this conductor-side: the child may run in another cwd.
316
+ // An invalid id cannot have a session dir (and `backgroundSessionDir`
317
+ // throws on one) — no pointer, no throw.
318
+ let retainedSessionDir: string | undefined;
319
+ try {
320
+ const { retainedSessionPointer } = await import('./session-manager');
321
+ const candidate = retainedSessionPointer(run.id);
322
+ if (fs.existsSync(candidate)) retainedSessionDir = candidate;
323
+ } catch {
324
+ retainedSessionDir = undefined;
325
+ }
326
+ const result = await spawnBackgroundRun(
327
+ pi,
328
+ ctx,
329
+ retryParams,
330
+ retryParams.task!,
331
+ run,
332
+ buildRetryResumePreamble(run, sourceAttempt + 1, retainedSessionDir),
333
+ );
334
+ if (result.isError) {
335
+ log.warn("Transport auto-retry spawn rejected — surfacing the original failure", {
336
+ sourceId: run.id,
337
+ attempt: sourceAttempt,
338
+ error: result.content[0]?.type === "text" ? result.content[0].text : undefined,
339
+ });
340
+ return false;
341
+ }
342
+ } catch (err) {
343
+ log.warn("Transport auto-retry spawn failed — surfacing the original failure", {
344
+ sourceId: run.id,
345
+ attempt: sourceAttempt,
346
+ error: (err as Error).message,
347
+ });
348
+ return false;
349
+ }
350
+ log.info("Background run settled — transport auto-retry scheduled", {
351
+ sourceId: run.id,
352
+ attempt: sourceAttempt + 1,
353
+ });
354
+ ctx.ui.notify(TRANSPORT_RETRY_TOAST, "warning");
355
+ return true;
356
+ }
357
+
358
+ async function deliverCompletionAlert(event: SubagentEvent): Promise<void> {
359
+ const id = event.agentId;
360
+ if (!claimTerminalNotice(id)) return;
361
+ const ctx = getSession();
362
+ if (!ctx) return;
363
+ try {
364
+ const { getAgent } = await import("./session-manager");
365
+ const agent = getAgent(id);
366
+ if (!agent) return; // pruned or foreign id — nothing to notify
367
+ const knob = state.config.completionNotify ?? "all";
368
+ const run = resolveRunEntry(state.getLogicalRunEntries(ctx), id);
369
+ // Issue #365: a transport-class background failure is re-dispatched once
370
+ // and the source notice is suppressed (the retry's settle is the wake).
371
+ // Every other terminal type — and every non-retryable failure — keeps the
372
+ // existing path unchanged.
373
+ if (event.type === "subagent:failed" && run && isTransportRetryable(run)) {
374
+ const retried = await scheduleTransportRetry(ctx, run);
375
+ if (retried) return;
376
+ }
377
+ const message = buildCompletionMessage(agent, run);
378
+ // Issue #474: a settle that is not a success reports the worktree it may
379
+ // have left. The CLASSIFIED status gates it (not `agent.status`), so the
380
+ // #179 completed→failed downgrade carries the block too, and a genuinely
381
+ // completed run stays noise-free. A record written before #474 has no
382
+ // `agent.cwd`; its retry snapshot's cwd is used only when it is absolute
383
+ // (describeWorktreeState refuses a relative one rather than resolving it
384
+ // against this process's cwd).
385
+ const settledMessage =
386
+ message.details.status === "completed"
387
+ ? message
388
+ : withWorktreeState(
389
+ message,
390
+ describeWorktreeState(agent.cwd ?? run?.originalParams?.cwd),
391
+ );
392
+ // Issue #179 (D2): resolve delivery from the CLASSIFIED notification
393
+ // status, not the raw agent status — otherwise a run whose completion
394
+ // the builder downgraded to failed would still be delivered as a success.
395
+ const delivery = resolveDelivery(settledMessage.details.status, knob);
396
+ sendCompletionNotification(pi, settledMessage, delivery);
397
+ } catch (err) {
398
+ log.warn(`completion-push handler failed for ${id}`, {
399
+ error: (err as Error).message,
400
+ });
401
+ }
402
+ }
403
+
404
+ return { release: releaseTerminalSubscriptions };
405
+ }
package/src/transcript.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  // Purpose: JSONL transcript recording for every agent run (`.pi/output/agent-<id>.jsonl`).
2
- import { appendFileSync, readFileSync, existsSync } from 'fs';
3
2
  import type { TranscriptEntry, TranscriptEntryType } from './types';
3
+ import { appendFileSync, readFileSync, existsSync } from 'fs';
4
4
  import { transcriptPath, TRANSCRIPT_DIR } from './transcript-path';
5
5
  import { createLogger } from './logging';
6
6
  import { ensureOwnerOnlyDir } from './store-permissions';
package/src/tui-format.ts CHANGED
@@ -12,8 +12,10 @@ import {
12
12
  TEMPLATE_PARAM_RE,
13
13
  formatTokens,
14
14
  isInterruptedRun,
15
+ type ModeContext,
16
+ type SubagentRun,
17
+ type TaskTemplate,
15
18
  } from "./types";
16
- import type { ModeContext, SubagentRun, TaskTemplate } from "./types";
17
19
 
18
20
  /** Frame duration of the braille spinners (10 frames → a 1.5 s cycle). */
19
21
  export const LIVE_SPINNER_FRAME_MS = 150;
package/src/tui.ts CHANGED
@@ -7,35 +7,17 @@
7
7
  * delegate_task result rendering.
8
8
  */
9
9
 
10
- import type {
11
- ExtensionContext,
12
- ExtensionAPI,
13
- Theme,
14
- ToolRenderResultOptions,
10
+ import type { AgentToolResult } from "@earendil-works/pi-agent-core";
11
+ import type { Api, Model } from "@earendil-works/pi-ai";
12
+ import {
13
+ DynamicBorder,
14
+ getMarkdownTheme,
15
+ type ExtensionContext,
16
+ type ExtensionAPI,
17
+ type Theme,
18
+ type ToolRenderResultOptions,
15
19
  } from "@earendil-works/pi-coding-agent";
16
- import { DynamicBorder, getMarkdownTheme } from "@earendil-works/pi-coding-agent";
17
20
  import { Container, type Component, type SelectItem, SelectList, Spacer, Text, Markdown, matchesKey } from "@earendil-works/pi-tui";
18
- import type { Api, Model } from "@earendil-works/pi-ai";
19
- import type { AgentToolResult } from "@earendil-works/pi-agent-core";
20
- import type {
21
- TaskTemplate,
22
- SubagentResult,
23
- SubagentRun,
24
- SubTaskResult,
25
- MultiSubagentDetails,
26
- ChainDetails,
27
- ParallelDetails,
28
- GraphDetails,
29
- DelegateTaskDetails,
30
- DelegateTaskParams,
31
- ThinkingLevel,
32
- UsageStats,
33
- FileDiff,
34
- CompletionNotifyMode,
35
- RecoveryMode,
36
- LiveSubagent,
37
- SLAMetrics,
38
- } from "./types";
39
21
  import {
40
22
  THINKING_LEVELS,
41
23
  NAV_FOOTER,
@@ -55,6 +37,23 @@ import {
55
37
  isGraphDetails,
56
38
  isUnsettledPartial,
57
39
  isInterruptedRun,
40
+ type TaskTemplate,
41
+ type SubagentResult,
42
+ type SubagentRun,
43
+ type SubTaskResult,
44
+ type MultiSubagentDetails,
45
+ type ChainDetails,
46
+ type ParallelDetails,
47
+ type GraphDetails,
48
+ type DelegateTaskDetails,
49
+ type DelegateTaskParams,
50
+ type ThinkingLevel,
51
+ type UsageStats,
52
+ type FileDiff,
53
+ type CompletionNotifyMode,
54
+ type RecoveryMode,
55
+ type LiveSubagent,
56
+ type SLAMetrics,
58
57
  } from "./types";
59
58
  import { buildFileAccessReport, buildSecretsExposureReport, generateComplianceSummary } from "./reports";
60
59
  import { extractParamNames } from "./templates";
@@ -67,12 +66,23 @@ import { collapseRunsForHistory, retryableRuns, sweepStaleLiveSubagents, type Se
67
66
  import { getAgent } from "./session-manager";
68
67
  import { visibleRunEntriesForSession } from "./recovery-surface";
69
68
  import { computeSLAMetrics, computeCostTrend, formatSparkline } from "./metrics";
70
- import { formatElapsed, formatOutcomeSymbol, liveRowName, liveSpinner, formatLiveRowDim, formatBudget, sortLiveSessions, runHistoryStatus, runHistoryStatusLabel, buildRetryOfferMessage, runDisplayName, formatMenuValue, formatTemplateSummary, menuSection } from "./tui-format";
71
69
  import {
72
- renderTranscriptMessages,
73
- type TranscriptLineStyle,
74
- type TranscriptMessage,
75
- } from "./transcript-tail";
70
+ formatElapsed,
71
+ formatOutcomeSymbol,
72
+ liveRowName,
73
+ liveSpinner,
74
+ formatLiveRowDim,
75
+ formatBudget,
76
+ sortLiveSessions,
77
+ runHistoryStatus,
78
+ runHistoryStatusLabel,
79
+ buildRetryOfferMessage,
80
+ runDisplayName,
81
+ formatMenuValue,
82
+ formatTemplateSummary,
83
+ menuSection,
84
+ } from "./tui-format";
85
+ import { renderTranscriptMessages, type TranscriptLineStyle, type TranscriptMessage } from "./transcript-tail";
76
86
 
77
87
  // ---------------------------------------------------------------------------
78
88
  // SelectList helper
package/src/types.ts CHANGED
@@ -5,11 +5,11 @@
5
5
  * All shared type definitions and constants for the brl-subagent extension.
6
6
  */
7
7
 
8
- import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
9
- import type { AgentToolResult } from "@earendil-works/pi-agent-core";
10
- import type { Static } from "typebox";
11
8
  import type { delegateTaskParamsSchema } from "./schema";
12
9
  import type { TranscriptMessage } from "./transcript-tail";
10
+ import type { AgentToolResult } from "@earendil-works/pi-agent-core";
11
+ import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
12
+ import type { Static } from "typebox";
13
13
 
14
14
  // ---------------------------------------------------------------------------
15
15
  // Core types
@@ -412,6 +412,19 @@ export interface SubagentRun {
412
412
  // Option B U3 (D4): the recovery posture in force when this run was
413
413
  // dispatched. Additive: a pre-U3 record lacks it and reads as "offer".
414
414
  recoveryPosture?: RecoveryMode;
415
+ /**
416
+ * Issue #511 (U2): the absolute path of this run's scratch directory
417
+ * (`<root>/runs/<id>`, owner-only 0700), written at spawn by the seam in
418
+ * `scratch-spawn.ts`. The progress bank lives at `<scratchDir>/bank.md`, and a
419
+ * terminal settle leaves a `.done` marker in the same directory.
420
+ *
421
+ * Additive and optional: a run whose scratch preparation was refused before
422
+ * anything was created never reaches the record, and a pre-U2 record simply
423
+ * lacks the key (readers must treat absence as "no known scratch dir", not as
424
+ * a path to derive). The retry preamble (U3) reads it, which is why it is
425
+ * persisted at spawn rather than reconstructed at settle.
426
+ */
427
+ scratchDir?: string;
415
428
  /**
416
429
  * Issue #447: the acceptance marker. `null` at creation — the dispatch is
417
430
  * TRACKED (agent record + run entry + registry entry written) but has not
@@ -548,6 +561,12 @@ export interface SubTaskResult {
548
561
  errorCategory?: ErrorCategory;
549
562
  gitBranch?: string;
550
563
  gitDiff?: string;
564
+ /**
565
+ * Issue #474: the worktree-state block for a FAILED unit, probed at that
566
+ * unit's OWN cwd (a step may declare one, distinct from the dispatch cwd).
567
+ * Absent on success — the block is failure-path reporting, not noise.
568
+ */
569
+ worktreeState?: string;
551
570
  }
552
571
 
553
572
  /** Aggregate result for chain and parallel modes. */
@@ -844,6 +863,13 @@ export interface BackgroundAgent {
844
863
  workBranch?: string;
845
864
  /** @internal — session reference for live monitor polling */
846
865
  _sessionRef?: import('@earendil-works/pi-coding-agent').AgentSession;
866
+ /**
867
+ * Issue #474: the directory this run was spawned in, stamped at spawn so a
868
+ * settled failure can report the worktree it may have left. Absolute by
869
+ * construction (the spawn's resolved cwd); additive, so a record written
870
+ * before the field existed reads as "no recorded cwd".
871
+ */
872
+ cwd?: string;
847
873
  /**
848
874
  * @internal — Option B U2: the on-disk session file for this run, captured
849
875
  * from `SessionManager.getSessionFile()` at spawn. Used by the settle path to