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,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;
@@ -82,6 +84,73 @@ export interface ProgressStatusInput {
82
84
  modeContext?: ModeContext;
83
85
  /** Epoch ms at which the oldest active run started; absent → no elapsed suffix. */
84
86
  activeSinceMs?: number;
87
+ /**
88
+ * Issue #423: the live map's own clock, when the caller has one. Supersedes
89
+ * `activeSinceMs` for the age (it is the age of the OLDEST still-running
90
+ * agent, not the burst anchor) and adds the nearest deadline.
91
+ */
92
+ times?: ProgressTimes;
93
+ }
94
+
95
+ /** The one live-entry clock {@link computeProgressTimes} needs. */
96
+ export interface LiveBudgetInput {
97
+ startedAt: number;
98
+ deadlineAt?: number;
99
+ }
100
+
101
+ /** The footer's two derived clocks, both already filtered of settled runs. */
102
+ export interface ProgressTimes {
103
+ /** Age of the OLDEST still-running entry (ms), clamped at 0. */
104
+ ranMs?: number;
105
+ /** The soonest deadline: time left, and the fraction of its budget left. */
106
+ next?: { remainingMs: number; fraction: number };
107
+ }
108
+
109
+ /** Clamp a fraction into [0, 1]; a non-positive budget has nothing left. */
110
+ function clampFraction(value: number): number {
111
+ if (!Number.isFinite(value)) return 0;
112
+ return Math.min(1, Math.max(0, value));
113
+ }
114
+
115
+ /**
116
+ * Derive the footer's clocks from the live entries (issue #423). Pure.
117
+ *
118
+ * `ranMs` is the age of the OLDEST still-running agent — `now - min(startedAt)`
119
+ * — not the burst anchor: with a queue, the burst anchor predates the row the
120
+ * human is watching. An EMPTY list yields no `ranMs` so the caller can fall back
121
+ * to `activeSinceMs` (the pre-#423 line).
122
+ *
123
+ * `next` is the SOONEST deadline, and its `fraction` is measured against that
124
+ * entry's own budget, so a long-running agent with a long budget does not read
125
+ * as nearly-exhausted. Remaining time clamps at 0; a backwards clock jump makes
126
+ * the age 0 rather than negative.
127
+ */
128
+ export function computeProgressTimes(
129
+ live: ReadonlyArray<LiveBudgetInput>,
130
+ now: number,
131
+ ): ProgressTimes {
132
+ if (live.length === 0) return {};
133
+
134
+ let oldestStartedAt = Infinity;
135
+ let soonest: LiveBudgetInput | undefined;
136
+ for (const entry of live) {
137
+ oldestStartedAt = Math.min(oldestStartedAt, entry.startedAt);
138
+ if (entry.deadlineAt === undefined) continue;
139
+ if (soonest?.deadlineAt === undefined || entry.deadlineAt < soonest.deadlineAt) {
140
+ soonest = entry;
141
+ }
142
+ }
143
+
144
+ const times: ProgressTimes = { ranMs: Math.max(0, now - oldestStartedAt) };
145
+ if (soonest?.deadlineAt !== undefined) {
146
+ const remainingMs = Math.max(0, soonest.deadlineAt - now);
147
+ const budgetMs = soonest.deadlineAt - soonest.startedAt;
148
+ times.next = {
149
+ remainingMs,
150
+ fraction: budgetMs > 0 ? clampFraction(remainingMs / budgetMs) : 0,
151
+ };
152
+ }
153
+ return times;
85
154
  }
86
155
 
87
156
  /** One coloured run of text on the footer line. */
@@ -95,6 +164,24 @@ const DONE_SYMBOL = "\u2713";
95
164
  const FAILED_SYMBOL = "\u2717";
96
165
  /** Separator before the elapsed suffix — " · ", muted with the duration. */
97
166
  const ELAPSED_SEPARATOR = " \u00b7 ";
167
+ /** Issue #423 — the labels of the two clock segments, in one place. */
168
+ const RAN_LABEL = "ran: ";
169
+ const DEADLINE_LABEL = "deadline in ";
170
+ const DEADLINE_STOPPING = "deadline: stopping";
171
+ /**
172
+ * Issue #423 — the deadline segment's colour bands, by the fraction of budget
173
+ * left. The text always carries the value, so colour is redundant, never
174
+ * load-bearing.
175
+ */
176
+ const DEADLINE_ERROR_FRACTION = 0.05;
177
+ const DEADLINE_WARNING_FRACTION = 0.2;
178
+
179
+ /** The deadline clock's colour: exhausted/almost → error, tight → warning. */
180
+ function deadlineColor(next: { remainingMs: number; fraction: number }): ProgressStatusColor {
181
+ if (next.remainingMs <= 0 || next.fraction <= DEADLINE_ERROR_FRACTION) return "error";
182
+ if (next.fraction <= DEADLINE_WARNING_FRACTION) return "warning";
183
+ return "muted";
184
+ }
98
185
 
99
186
  /** The verdict a run or step settled on — the input to {@link formatOutcomeSymbol}. */
100
187
  export type OutcomeKind = "success" | "failure";
@@ -189,10 +276,29 @@ export function formatProgressSegments(
189
276
  });
190
277
  }
191
278
 
192
- if (active && state.activeSinceMs !== undefined) {
193
- // Clamp at zero: a clock jump backwards must never print a negative age.
194
- const elapsed = formatElapsed(Math.max(0, now - state.activeSinceMs));
195
- segments.push({ color: "muted", text: `${ELAPSED_SEPARATOR}${elapsed}` });
279
+ if (active) {
280
+ const times = state.times;
281
+ if (times?.ranMs !== undefined) {
282
+ // Clamp again here: the formatter is public and may be handed a raw age.
283
+ segments.push({
284
+ color: "muted",
285
+ text: `${ELAPSED_SEPARATOR}${RAN_LABEL}${formatElapsed(Math.max(0, times.ranMs))}`,
286
+ });
287
+ } else if (state.activeSinceMs !== undefined) {
288
+ // Pre-#423 fallback (no live clock known): the burst anchor, unchanged.
289
+ // Clamp at zero: a clock jump backwards must never print a negative age.
290
+ const elapsed = formatElapsed(Math.max(0, now - state.activeSinceMs));
291
+ segments.push({ color: "muted", text: `${ELAPSED_SEPARATOR}${elapsed}` });
292
+ }
293
+ if (times?.next !== undefined) {
294
+ segments.push({
295
+ color: deadlineColor(times.next),
296
+ text:
297
+ times.next.remainingMs <= 0
298
+ ? `${ELAPSED_SEPARATOR}${DEADLINE_STOPPING}`
299
+ : `${ELAPSED_SEPARATOR}${DEADLINE_LABEL}${formatElapsed(times.next.remainingMs)}`,
300
+ });
301
+ }
196
302
  }
197
303
 
198
304
  return segments;
@@ -213,13 +319,77 @@ export function formatProgressStatus(
213
319
  .join("");
214
320
  }
215
321
 
216
- /** Dim section of a live row: short id + token counts + elapsed. */
322
+ /** Dim section of a live row: short id + token counts + elapsed (+ budget). */
217
323
  export function formatLiveRowDim(
218
324
  id: string,
219
325
  usage: { input: number; output: number },
220
326
  elapsedStr: string,
327
+ // Issue #423: the budget segment, when the run has a known deadline.
328
+ budget?: string,
329
+ ): string {
330
+ return ` [${id.slice(0, 8)}] \u2191${formatTokens(usage.input)} \u2193${formatTokens(usage.output)} ${elapsedStr}${budget ? ` \u00b7 ${budget}` : ""}`;
331
+ }
332
+
333
+ // ---------------------------------------------------------------------------
334
+ // Issue #423 — budget display (footer, monitor rows, dashboard)
335
+ // ---------------------------------------------------------------------------
336
+
337
+ /**
338
+ * A budget/used/left duration: a whole number of minutes as `30m` (a budget is
339
+ * read as a round number), otherwise the compact `4m 12s` form. Pure.
340
+ */
341
+ export function formatBudgetDuration(ms: number): string {
342
+ const safe = Math.max(0, ms);
343
+ const minutes = safe / 60_000;
344
+ return Number.isInteger(minutes) && minutes > 0 ? `${minutes}m` : formatElapsed(safe);
345
+ }
346
+
347
+ /** The no-deadline token: the run has no timer, so there is nothing to state. */
348
+ const NO_BUDGET = "\u2014";
349
+
350
+ /**
351
+ * One live row's budget: `4m 12s / 30m (86% left)`. Pure.
352
+ *
353
+ * `startedAt` + `deadlineAt` are the entry's own clocks; a missing deadline
354
+ * renders {@link NO_BUDGET} (a foreground run with no timeout, or an old
355
+ * record) rather than inventing a 30m default the run does not have. An
356
+ * exhausted budget states `0% left` — the remaining time is clamped, never
357
+ * negative.
358
+ */
359
+ export function formatBudget(
360
+ startedAt: number,
361
+ deadlineAt: number | undefined,
362
+ now: number,
221
363
  ): string {
222
- return ` [${id.slice(0, 8)}] \u2191${formatTokens(usage.input)} \u2193${formatTokens(usage.output)} ${elapsedStr}`;
364
+ if (deadlineAt === undefined) return NO_BUDGET;
365
+ const budgetMs = deadlineAt - startedAt;
366
+ const usedMs = Math.max(0, now - startedAt);
367
+ const remainingMs = Math.max(0, deadlineAt - now);
368
+ const percentLeft =
369
+ budgetMs > 0 ? Math.max(0, Math.min(100, Math.floor((remainingMs / budgetMs) * 100))) : 0;
370
+ return `${formatBudgetDuration(usedMs)} / ${formatBudgetDuration(budgetMs)} (${percentLeft}% left)`;
371
+ }
372
+
373
+ /**
374
+ * Order live rows for display: soonest deadline first (undated last), then
375
+ * oldest first, then id for a stable total order. Pure; returns a copy.
376
+ *
377
+ * Ordering by `deadlineAt` IS ordering by remaining time (same `now`), so the
378
+ * list does not reorder between paints as the clock advances — only a
379
+ * registration or a deadline change moves a row.
380
+ */
381
+ export function sortLiveSessions<T extends LiveBudgetInput>(
382
+ entries: ReadonlyArray<readonly [string, T]>,
383
+ ): Array<[string, T]> {
384
+ return entries
385
+ .map(([id, entry]) => [id, entry] as [string, T])
386
+ .sort(([aId, a], [bId, b]) => {
387
+ const aDeadline = a.deadlineAt ?? Number.POSITIVE_INFINITY;
388
+ const bDeadline = b.deadlineAt ?? Number.POSITIVE_INFINITY;
389
+ if (aDeadline !== bDeadline) return aDeadline - bDeadline;
390
+ if (a.startedAt !== b.startedAt) return a.startedAt - b.startedAt;
391
+ return aId < bId ? -1 : aId > bId ? 1 : 0;
392
+ });
223
393
  }
224
394
 
225
395
  /**