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
package/src/state.ts CHANGED
@@ -9,20 +9,9 @@
9
9
  * F9: State schema validation — validates on load, migrates legacy formats.
10
10
  */
11
11
 
12
- import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
13
- import type {
14
- SubagentState,
15
- SubagentRun,
16
- LiveSubagent,
17
- ThinkingLevel,
18
- ApprovalMode,
19
- CompletionNotifyMode,
20
- RecoveryMode,
21
- CircuitBreakerState,
22
- Priority,
23
- ModeContext,
24
- } from "./types";
12
+ import type { Logger } from "./logging";
25
13
  import type { TranscriptMessage } from "./transcript-tail";
14
+ import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
26
15
  import {
27
16
  isSubagentStateShape,
28
17
  isSubagentRunShape,
@@ -38,10 +27,19 @@ import {
38
27
  MAX_CONSECUTIVE_FAILURES,
39
28
  CIRCUIT_BREAKER_RESET_MS,
40
29
  CIRCUIT_DEGRADED_THINKING,
30
+ type SubagentState,
31
+ type SubagentRun,
32
+ type LiveSubagent,
33
+ type ThinkingLevel,
34
+ type ApprovalMode,
35
+ type CompletionNotifyMode,
36
+ type RecoveryMode,
37
+ type CircuitBreakerState,
38
+ type Priority,
39
+ type ModeContext,
41
40
  } from "./types";
42
41
  import { cleanupRuns } from "./history";
43
42
  import { persistRunRecord, type InflightRunKind } from "./run-registry";
44
- import type { Logger } from "./logging";
45
43
 
46
44
  // ---------------------------------------------------------------------------
47
45
  // Live-monitor staleness sweep (issue #52 part 2)
@@ -78,17 +76,24 @@ export const STALE_FINALIZE_GRACE_MS = POLLER_TICK_MS + 1000;
78
76
  * preference rule. Recovery's `dedupeRunEntriesById` delegates here, so the
79
77
  * boot scan and every display/retry lookup agree by construction.
80
78
  *
81
- * Each run writes TWO custom entries sharing its id, in append order: a spawn
82
- * entry (status "running", carrying `originalParams`) FIRST, then the final
83
- * entry (status "done"/"failed", stamped with fullOutput/cost/duration) at
84
- * settle. Preference, in order:
79
+ * Each run writes a spawn entry (status "running", carrying `originalParams`)
80
+ * FIRST, then its terminal entry (status "done"/"failed", stamped with
81
+ * fullOutput/cost/duration) at settle. A run stopped by the deadline writes ONE
82
+ * MORE terminal entry at the late settle — a payload AMENDMENT of the deadline's
83
+ * classification snapshot (issue #453, ADR 0023 decision 4). Preference, in order:
85
84
  *
86
- * 1. a TERMINAL entry (status !== "running") — the run is resolved;
85
+ * 1. the LAST terminal entry (status !== "running") — with an amendment that
86
+ * is the amended payload; without one it is the only terminal entry, so
87
+ * this is unchanged for every pre-#453 run (mutant M5 is `find` here);
87
88
  * 2. among non-terminal entries, one carrying the D3 `interruptedAt` mark —
88
89
  * append-only stores keep the original spawn entry forever, so the marked
89
90
  * clone is the authoritative RECOVERED state U3's shared lookup reads;
90
91
  * 3. otherwise the first match (the pre-finalize spawn shape).
91
92
  *
93
+ * Ordering contract: callers pass a store-ordered list (`getRunEntries` is
94
+ * newest-first with a STABLE sort, so a run's entries stay in append order —
95
+ * spawn, snapshot, amendment). "Last" therefore means "appended last".
96
+ *
92
97
  * Returns undefined when no entry matches.
93
98
  */
94
99
  export function resolveTerminalRunEntry(
@@ -98,12 +103,39 @@ export function resolveTerminalRunEntry(
98
103
  const matching = entries.filter((r) => r.id === id);
99
104
  if (matching.length === 0) return undefined;
100
105
  return (
101
- matching.find((r) => r.status !== "running") ??
106
+ matching.findLast((r) => r.status !== "running") ??
102
107
  matching.find((r) => r.interruptedAt) ??
103
108
  matching[0]
104
109
  );
105
110
  }
106
111
 
112
+ /**
113
+ * Issue #453 (ADR 0023 decision 4): ONE logical run per id — the projection every
114
+ * raw-entry consumer reads.
115
+ *
116
+ * A run that hits its deadline and settles late has three entries sharing its id
117
+ * (spawn, `failed/timeout` snapshot, payload amendment). Aggregates that take the
118
+ * raw list count it two or three times and sum two full payloads (measured: 3
119
+ * runs / $5 for a $2 snapshot + $3 amendment pair). This yields, per id, the LAST
120
+ * entry in the input's order: the amendment when there is one (so the amended
121
+ * payload — the real cost/tokens/output — is what readers see), the terminal entry
122
+ * for an ordinary run, the spawn entry for a run still in flight.
123
+ *
124
+ * ORDER: the output keeps each id's FIRST-seen position and drops repeats, so a
125
+ * caller's window (`slice(0, n)`) applied AFTER this projects runs, not entries.
126
+ * That is the contract — apply the projection BEFORE any window or cap, or a
127
+ * window can split one run's entries across its edge.
128
+ */
129
+ export function projectLogicalRuns(entries: SubagentRun[]): SubagentRun[] {
130
+ const lastById = new Map<string, SubagentRun>();
131
+ const order: string[] = [];
132
+ for (const entry of entries) {
133
+ if (!lastById.has(entry.id)) order.push(entry.id);
134
+ lastById.set(entry.id, entry);
135
+ }
136
+ return order.map((id) => lastById.get(id)!);
137
+ }
138
+
107
139
  /**
108
140
  * Run-history display projection (issue #259): ONE record per SETTLED run.
109
141
  *
@@ -111,7 +143,8 @@ export function resolveTerminalRunEntry(
111
143
  * "running") first, then the terminal entry at settle — so a raw entry list
112
144
  * renders every run twice and the spawn row shows a stale "running" forever.
113
145
  * This collapses each id to its terminal-preferred entry via the ONE shared
114
- * rule (`resolveTerminalRunEntry`). Runs still in flight (spawn entry, no
146
+ * rule (`resolveTerminalRunEntry`). Callers pass the LOGICAL list
147
+ * (`getLogicalRunEntries`) since #453, so an amended run is already one entry. Runs still in flight (spawn entry, no
115
148
  * terminal entry yet) are omitted: live state belongs to the monitor. U3 (D1)
116
149
  * carves ONE exception — an INTERRUPTED run (running + `interruptedAt`, per
117
150
  * `isInterruptedRun`) is surfaced, because the human must see it to recover or
@@ -217,6 +250,14 @@ export class SessionState {
217
250
  */
218
251
  private _finalizedLiveIds = new Set<string>();
219
252
 
253
+ /**
254
+ * The pending deferred-delete handle per finalized id (issue #423). Kept so
255
+ * a RE-registration can cancel it: a retry inside the 3 s window re-claims
256
+ * the id, and a stale delete would otherwise evict the fresh live row that
257
+ * the display surfaces just started rendering again.
258
+ */
259
+ private _finalizeTimers = new Map<string, ReturnType<typeof setTimeout>>();
260
+
220
261
  /** Loaded built-in presets */
221
262
  builtinPresets = new Array<import("./types").SubagentPreset>();
222
263
 
@@ -389,8 +430,13 @@ export class SessionState {
389
430
  // Run entry access
390
431
  // -------------------------------------------------------------------
391
432
 
392
- getRunEntries(ctx: ExtensionContext): SubagentRun[] {
393
- const runs = ctx.sessionManager
433
+ /**
434
+ * The RAW run-entry store, session order (oldest append first), uncapped.
435
+ * Two callers only: {@link getRunEntries} (the raw view) and
436
+ * {@link getLogicalRunEntries} (the one every aggregate reads).
437
+ */
438
+ private readRunEntries(ctx: ExtensionContext): SubagentRun[] {
439
+ return ctx.sessionManager
394
440
  .getEntries()
395
441
  .filter((e: { type: string; customType?: string }) =>
396
442
  e.type === "custom" && e.customType === CUSTOM_ENTRY_TYPES.run,
@@ -402,7 +448,32 @@ export class SessionState {
402
448
  return undefined;
403
449
  })
404
450
  .filter((r): r is SubagentRun => r !== undefined);
405
- return cleanupRuns(runs, this.config.maxHistoryEntries);
451
+ }
452
+
453
+ /**
454
+ * The RAW run-entry view, newest-first and capped at `maxHistoryEntries`
455
+ * ENTRIES. Not the display/aggregate view — a run has two entries (spawn +
456
+ * terminal) and a deadline-stopped one has three, so a consumer that counts,
457
+ * sums or windows these sees one run several times. It remains the right view
458
+ * for `findSpawnRunById` (which deliberately wants the SPAWN entry) and for
459
+ * raw-store bookkeeping.
460
+ */
461
+ getRunEntries(ctx: ExtensionContext): SubagentRun[] {
462
+ return cleanupRuns(this.readRunEntries(ctx), this.config.maxHistoryEntries);
463
+ }
464
+
465
+ /**
466
+ * Issue #453: the LOGICAL run-entry view — one entry per run id, carrying the
467
+ * amended payload when the deadline and a late settle both wrote (see
468
+ * {@link projectLogicalRuns}). Every aggregate/display consumer uses THIS:
469
+ * metrics, cost accounting, history, the reports and the dashboard.
470
+ *
471
+ * The projection runs BEFORE the cap, so `maxHistoryEntries` counts RUNS: an
472
+ * amended run cannot be half-kept, and its amendment can never be windowed
473
+ * away from the snapshot it amends.
474
+ */
475
+ getLogicalRunEntries(ctx: ExtensionContext): SubagentRun[] {
476
+ return cleanupRuns(projectLogicalRuns(this.readRunEntries(ctx)), this.config.maxHistoryEntries);
406
477
  }
407
478
 
408
479
  /**
@@ -422,7 +493,10 @@ export class SessionState {
422
493
  * `fullOutput`, `cost`, `durationMs`, `errorCategory`.
423
494
  */
424
495
  findTerminalRunById(ctx: ExtensionContext, id: string): SubagentRun | undefined {
425
- return resolveTerminalRunEntry(this.getRunEntries(ctx), id);
496
+ // #453 review: the LOGICAL view, not the raw capped list — at the
497
+ // `maxHistoryEntries` edge a raw read can return the deadline snapshot while
498
+ // every other surface shows the later amendment (the run's real payload).
499
+ return resolveTerminalRunEntry(this.getLogicalRunEntries(ctx), id);
426
500
  }
427
501
 
428
502
  // -------------------------------------------------------------------
@@ -430,6 +504,11 @@ export class SessionState {
430
504
  // -------------------------------------------------------------------
431
505
 
432
506
  registerLiveSubagent(id: string, data: Omit<LiveSubagent, "liveOutput" | "usage">): void {
507
+ // Issue #423: a registration means the id is live AGAIN — a retry
508
+ // re-registers inside the 3 s linger window, and every display surface
509
+ // filters finalized ids, so the claim (and its pending delete) must not
510
+ // survive the re-registration.
511
+ this.clearLiveFinalize(id);
433
512
  this.subagentSessions.set(id, { ...data, liveOutput: "", usage: { input: 0, output: 0 } });
434
513
  }
435
514
 
@@ -459,13 +538,30 @@ export class SessionState {
459
538
  // review: the poller must not decrement when the sweep already did).
460
539
  if (this._finalizedLiveIds.has(id)) return false;
461
540
  this._finalizedLiveIds.add(id);
462
- setTimeout(() => {
463
- this.subagentSessions.delete(id);
464
- this._finalizedLiveIds.delete(id);
465
- }, FINALIZE_RESET_WINDOW_MS);
541
+ this._finalizeTimers.set(
542
+ id,
543
+ setTimeout(() => {
544
+ this._finalizeTimers.delete(id);
545
+ this.subagentSessions.delete(id);
546
+ this._finalizedLiveIds.delete(id);
547
+ }, FINALIZE_RESET_WINDOW_MS),
548
+ );
466
549
  return true;
467
550
  }
468
551
 
552
+ /**
553
+ * Drop a pending finalize claim AND its deferred delete (issue #423). Called
554
+ * by {@link registerLiveSubagent} when an id is registered again.
555
+ */
556
+ private clearLiveFinalize(id: string): void {
557
+ const handle = this._finalizeTimers.get(id);
558
+ if (handle !== undefined) {
559
+ clearTimeout(handle);
560
+ this._finalizeTimers.delete(id);
561
+ }
562
+ this._finalizedLiveIds.delete(id);
563
+ }
564
+
469
565
  /** True when the live entry has been finalized (deferred delete pending). */
470
566
  isLiveEntryFinalized(id: string): boolean {
471
567
  return this._finalizedLiveIds.has(id);
@@ -509,6 +605,8 @@ export class SessionState {
509
605
  * would no-op on an id a stale claim still remembers (PR #71 review).
510
606
  */
511
607
  resetLiveFinalizeClaims(): void {
608
+ for (const handle of this._finalizeTimers.values()) clearTimeout(handle);
609
+ this._finalizeTimers.clear();
512
610
  this._finalizedLiveIds.clear();
513
611
  }
514
612
 
@@ -604,7 +702,9 @@ export class SessionState {
604
702
  * Sum the cost of all completed runs in the current session.
605
703
  */
606
704
  getSessionTotalCost(ctx: ExtensionContext): number {
607
- const runs = this.getRunEntries(ctx);
705
+ // Issue #453: one row per run — a deadline snapshot and its amendment both
706
+ // carry a full cost, so summing raw entries would charge the run twice.
707
+ const runs = this.getLogicalRunEntries(ctx);
608
708
  return runs.reduce((acc, r) => acc + (r.cost ?? 0), 0);
609
709
  }
610
710
 
package/src/templates.ts CHANGED
@@ -22,12 +22,11 @@
22
22
  * // resolved.value.task now has placeholders filled
23
23
  */
24
24
 
25
+ import type { Logger } from "./logging";
25
26
  import * as fs from "node:fs";
26
27
  import * as path from "node:path";
27
- import type { TaskTemplate, ThinkingLevel, SubagentPreset } from "./types";
28
- import { TEMPLATE_PARAM_RE, THINKING_LEVELS } from "./types";
29
- import type { Logger } from "./logging";
30
- import { loadMarkdownRecords } from "./loader";
28
+ import { TEMPLATE_PARAM_RE, THINKING_LEVELS, type TaskTemplate, type ThinkingLevel, type SubagentPreset } from "./types";
29
+ import { applyFrontmatterMappers, loadMarkdownRecords, type FrontmatterFieldMapper, type FrontmatterMapContext } from "./loader";
31
30
  import { sanitizeFileName } from "./presets";
32
31
  import { pkgPath } from "./paths";
33
32
 
@@ -174,6 +173,43 @@ export function validateTemplate(meta: Record<string, unknown>, fileName: string
174
173
  return errors;
175
174
  }
176
175
 
176
+ // ---------------------------------------------------------------------------
177
+ // Frontmatter → TaskTemplate mapping
178
+ // ---------------------------------------------------------------------------
179
+
180
+ /**
181
+ * Per-key return types: same shape as `PresetFieldMappers` (src/presets.ts), so
182
+ * a mapper that returns the wrong type — `timeout: () => "soon"` — fails at the
183
+ * row instead of at the assembly cast.
184
+ */
185
+ type TemplateFieldMappers = {
186
+ [K in keyof TaskTemplate]: FrontmatterFieldMapper<TaskTemplate[K]>;
187
+ };
188
+
189
+ /**
190
+ * THE declaration of which frontmatter keys reach a `TaskTemplate` — every
191
+ * field (no omission allowlist), so a new declared field is a missing-key
192
+ * compile error and a stale key is an excess-property error.
193
+ *
194
+ * `task` comes from the markdown body (multiline by construction), and
195
+ * `timeout` is the one numeric coercion: frontmatter values are strings.
196
+ */
197
+ const TEMPLATE_FIELD_MAPPERS = {
198
+ name: (_meta, ctx) => ctx.name,
199
+ description: (meta) => (meta.description as string) || undefined,
200
+ task: (_meta, ctx) => ctx.body,
201
+ preset: (meta) => (meta.preset as string) || undefined,
202
+ thinkingLevel: (meta) => (meta.thinkingLevel as string) || undefined,
203
+ outputFile: (meta) => (meta.outputFile as string) || undefined,
204
+ timeout: (meta) => (meta.timeout !== undefined ? Number(meta.timeout) : undefined),
205
+ tools: (meta) => (Array.isArray(meta.tools) ? (meta.tools as string[]) : undefined),
206
+ excludeTools: (meta) =>
207
+ Array.isArray(meta.excludeTools) ? (meta.excludeTools as string[]) : undefined,
208
+ noBuiltinTools: (meta) => (meta.noBuiltinTools === "true" ? true : undefined),
209
+ inheritSystemPrompt: (meta) =>
210
+ (meta.inheritSystemPrompt === "false" ? false : undefined),
211
+ } satisfies TemplateFieldMappers;
212
+
177
213
  // ---------------------------------------------------------------------------
178
214
  // Loading
179
215
  // ---------------------------------------------------------------------------
@@ -187,19 +223,8 @@ function templateFromFrontmatter(
187
223
  body: string,
188
224
  name: string,
189
225
  ): TaskTemplate {
190
- return {
191
- name,
192
- description: (meta.description as string) || undefined,
193
- task: body,
194
- preset: (meta.preset as string) || undefined,
195
- thinkingLevel: (meta.thinkingLevel as string) || undefined,
196
- outputFile: (meta.outputFile as string) || undefined,
197
- timeout: meta.timeout !== undefined ? Number(meta.timeout) : undefined,
198
- tools: Array.isArray(meta.tools) ? (meta.tools as string[]) : undefined,
199
- excludeTools: Array.isArray(meta.excludeTools) ? (meta.excludeTools as string[]) : undefined,
200
- noBuiltinTools: meta.noBuiltinTools === "true" ? true : undefined,
201
- inheritSystemPrompt: meta.inheritSystemPrompt === "false" ? false : undefined,
202
- };
226
+ const ctx: FrontmatterMapContext = { name, body };
227
+ return applyFrontmatterMappers<TaskTemplate>(TEMPLATE_FIELD_MAPPERS, meta, ctx);
203
228
  }
204
229
 
205
230
  /**