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/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, 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
@@ -495,7 +505,7 @@ export async function showSLAStats(
495
505
  ctx: ExtensionContext,
496
506
  state: SessionState,
497
507
  ): Promise<void> {
498
- const runs = state.getRunEntries(ctx).slice(0, state.config.slaWindowSize);
508
+ const runs = state.getLogicalRunEntries(ctx).slice(0, state.config.slaWindowSize);
499
509
  if (runs.length === 0) {
500
510
  ctx.ui.notify("No runs to analyze. Delegate a task first.", "info");
501
511
  return;
@@ -542,7 +552,7 @@ export async function showFileAccessReport(
542
552
  ctx: ExtensionContext,
543
553
  state: SessionState,
544
554
  ): Promise<void> {
545
- const runs = state.getRunEntries(ctx);
555
+ const runs = state.getLogicalRunEntries(ctx);
546
556
  if (runs.length === 0) {
547
557
  ctx.ui.notify("No runs to analyze. Delegate a task first.", "info");
548
558
  return;
@@ -577,7 +587,7 @@ export async function showSecretsExposureReport(
577
587
  ctx: ExtensionContext,
578
588
  state: SessionState,
579
589
  ): Promise<void> {
580
- const runs = state.getRunEntries(ctx);
590
+ const runs = state.getLogicalRunEntries(ctx);
581
591
  if (runs.length === 0) {
582
592
  ctx.ui.notify("No runs to analyze. Delegate a task first.", "info");
583
593
  return;
@@ -634,7 +644,7 @@ export async function showFullComplianceSummary(
634
644
  ctx: ExtensionContext,
635
645
  state: SessionState,
636
646
  ): Promise<void> {
637
- const runs = state.getRunEntries(ctx);
647
+ const runs = state.getLogicalRunEntries(ctx);
638
648
  if (runs.length === 0) {
639
649
  ctx.ui.notify("No runs to analyze. Delegate a task first.", "info");
640
650
  return;
@@ -1269,7 +1279,7 @@ export async function showConfigMenu(
1269
1279
  * run that exists only in the durable registry.
1270
1280
  */
1271
1281
  function recoverableRunEntries(ctx: ExtensionContext, state: SessionState): SubagentRun[] {
1272
- return visibleRunEntriesForSession(state.getRunEntries(ctx), getAgent);
1282
+ return visibleRunEntriesForSession(state.getLogicalRunEntries(ctx), getAgent);
1273
1283
  }
1274
1284
 
1275
1285
  export async function showRunHistory(
@@ -1558,6 +1568,11 @@ export async function showMonitor(
1558
1568
  // Selected row index (0-based). Clamped to the map size on every
1559
1569
  // render — entries can be swept while the monitor is open.
1560
1570
  let selectedIndex = 0;
1571
+ // Issue #423: the id list from the LAST paint. Selection identity is an
1572
+ // index over what was RENDERED, not over the live map: a spawn or a
1573
+ // finalize between paint and Enter would otherwise shift the id list and
1574
+ // open an agent other than the highlighted row.
1575
+ let lastRenderedIds: string[] = [];
1561
1576
  // Guards against stacking drill-in overlays on repeated Enter.
1562
1577
  let detailOpen = false;
1563
1578
 
@@ -1567,13 +1582,17 @@ export async function showMonitor(
1567
1582
  // render pass. Idempotent, so racing the poller is safe.
1568
1583
  sweepStaleLiveSubagents(state, getAgent);
1569
1584
 
1585
+ // Issue #423: the shared display projection (settled ids out, deadline order).
1586
+ const entries = liveDisplayEntries(state);
1587
+ lastRenderedIds = entries.map(([id]) => id);
1588
+
1570
1589
  const container = new Container();
1571
1590
  container.addChild(new DynamicBorder((s: string) => theme.fg("accent", s)));
1572
1591
  container.addChild(
1573
1592
  new Text(
1574
1593
  theme.fg(
1575
1594
  "accent",
1576
- theme.bold(`Subagent Monitor (${state.subagentSessions.size} active)`),
1595
+ theme.bold(`Subagent Monitor (${entries.length} active)`),
1577
1596
  ),
1578
1597
  1,
1579
1598
  0,
@@ -1584,14 +1603,14 @@ export async function showMonitor(
1584
1603
  );
1585
1604
  container.addChild(new Text("", 0, 0));
1586
1605
 
1587
- const entries = Array.from(state.subagentSessions.entries());
1588
1606
  const selIdx = Math.min(selectedIndex, Math.max(0, entries.length - 1));
1607
+ const now = Date.now();
1589
1608
 
1590
1609
  let idx = 0;
1591
1610
  for (const [id, session] of entries) {
1592
- const elapsedStr = formatElapsed(Date.now() - session.startedAt);
1611
+ const elapsedStr = formatElapsed(now - session.startedAt);
1593
1612
  const name = liveRowName(session.label, session.task);
1594
- const spinner = liveSpinner(Date.now());
1613
+ const spinner = liveSpinner(now);
1595
1614
  // Selection marker: a "›" prefix on the selected row only. The
1596
1615
  // rest of the row (spinner/name/dim/muted lines) is unchanged.
1597
1616
  const marker = idx === selIdx ? "› " : "";
@@ -1601,7 +1620,14 @@ export async function showMonitor(
1601
1620
  theme.fg("accent", `${marker}${spinner} ${name}`) +
1602
1621
  theme.fg(
1603
1622
  "dim",
1604
- formatLiveRowDim(id, session.usage, elapsedStr),
1623
+ formatLiveRowDim(
1624
+ id,
1625
+ session.usage,
1626
+ elapsedStr,
1627
+ // Issue #423: used / budget (percent left); `—` when the run has
1628
+ // no timer at all (a foreground run with no timeout).
1629
+ formatBudget(session.startedAt, session.deadlineAt, now),
1630
+ ),
1605
1631
  ),
1606
1632
  1,
1607
1633
  0,
@@ -1652,15 +1678,17 @@ export async function showMonitor(
1652
1678
  done();
1653
1679
  return;
1654
1680
  }
1655
- // up / down: move the selection, wrapping like SelectList.
1681
+ // up / down: move the selection, wrapping like SelectList. The bound is
1682
+ // the list the LAST paint rendered (issue #423), so the highlight can
1683
+ // never run past a row the human cannot see.
1656
1684
  if (_kb.matches(data, "tui.select.up")) {
1657
- const count = state.subagentSessions.size;
1685
+ const count = lastRenderedIds.length;
1658
1686
  selectedIndex = count > 0 ? (selectedIndex - 1 + count) % count : 0;
1659
1687
  tui.requestRender();
1660
1688
  return;
1661
1689
  }
1662
1690
  if (_kb.matches(data, "tui.select.down")) {
1663
- const count = state.subagentSessions.size;
1691
+ const count = lastRenderedIds.length;
1664
1692
  selectedIndex = count > 0 ? (selectedIndex + 1) % count : 0;
1665
1693
  tui.requestRender();
1666
1694
  return;
@@ -1668,9 +1696,11 @@ export async function showMonitor(
1668
1696
  // enter: open the full-screen drill-in overlay for the selected agent.
1669
1697
  // The overlay's done() returns to the list — the monitor stays open
1670
1698
  // beneath it (fire-and-forget; handleInput is synchronous).
1699
+ // Issue #423: the id resolves against the RENDERED list, so a spawn or
1700
+ // a finalize between paint and Enter cannot open a different agent than
1701
+ // the highlighted row (a stale id falls through to the not-found path).
1671
1702
  if (_kb.matches(data, "tui.select.confirm")) {
1672
- const ids = Array.from(state.subagentSessions.keys());
1673
- const id = ids[Math.min(selectedIndex, ids.length - 1)];
1703
+ const id = lastRenderedIds[selectedIndex];
1674
1704
  if (id && !detailOpen) {
1675
1705
  detailOpen = true;
1676
1706
  showAgentDetail(ctx, state, id).finally(() => {
@@ -1982,7 +2012,7 @@ function compactDuration(ms: number): string {
1982
2012
  /** The per-row live-session slice the Active Subagents panel renders. */
1983
2013
  export type ActiveSubagentSlice = Pick<
1984
2014
  LiveSubagent,
1985
- "label" | "task" | "startedAt" | "usage"
2015
+ "label" | "task" | "startedAt" | "deadlineAt" | "usage"
1986
2016
  >;
1987
2017
 
1988
2018
  /** Panel 1 — header: the dashboard title plus the refresh stamp. */
@@ -2001,15 +2031,35 @@ export function renderDashboardHeader(theme: Theme, refreshStr: string): Compone
2001
2031
  /**
2002
2032
  * Panel 2 — active subagents: the live count in the title, one row per entry.
2003
2033
  *
2004
- * `now` is injected (the composer passes the wall clock) so the spinner frame
2005
- * and the elapsed suffix stay testable; it is sampled per row, as before.
2034
+ * Issue #423: the rows arrive as an ORDERED array (the call site filters
2035
+ * finalized ids and sorts by the soonest deadline) rather than the raw map, so
2036
+ * the panel cannot render a settled row or an order the monitor disagrees with,
2037
+ * and `activeCount` is the rendered length instead of `map.size` (which counted
2038
+ * finalized-but-lingering entries).
2039
+ *
2040
+ * `now` is injected (the composer passes the wall clock) so the spinner frame,
2041
+ * the elapsed suffix and the budget stay testable; it is sampled per render.
2006
2042
  */
2043
+ /**
2044
+ * Issue #423: the monitor and the dashboard render the same projection — settled
2045
+ * ids removed (a 3 s lingering row must not show a live deadline) and rows
2046
+ * ordered by the soonest deadline. One definition, so the surfaces cannot
2047
+ * disagree (review 425, DRY).
2048
+ */
2049
+ export function liveDisplayEntries(state: SessionState): Array<[string, LiveSubagent]> {
2050
+ return sortLiveSessions(
2051
+ Array.from(state.subagentSessions.entries()).filter(
2052
+ ([id]) => !state.isLiveEntryFinalized(id),
2053
+ ),
2054
+ );
2055
+ }
2056
+
2007
2057
  export function renderDashboardActivePanel(
2008
2058
  theme: Theme,
2009
- sessions: ReadonlyMap<string, ActiveSubagentSlice>,
2059
+ sessions: ReadonlyArray<readonly [string, ActiveSubagentSlice]>,
2010
2060
  now: () => number = Date.now,
2011
2061
  ): Component[] {
2012
- const activeCount = sessions.size;
2062
+ const activeCount = sessions.length;
2013
2063
  const components: Component[] = [
2014
2064
  new Text(
2015
2065
  theme.fg("accent", theme.bold(`Active Subagents (${activeCount})`)),
@@ -2022,15 +2072,22 @@ export function renderDashboardActivePanel(
2022
2072
  } else {
2023
2073
  let idx = 0;
2024
2074
  for (const [id, session] of sessions) {
2025
- const elapsedStr = formatElapsed(now() - session.startedAt);
2075
+ const nowMs = now();
2076
+ const elapsedStr = formatElapsed(nowMs - session.startedAt);
2026
2077
  const name = liveRowName(session.label, session.task);
2027
- const spinner = liveSpinner(now());
2078
+ const spinner = liveSpinner(nowMs);
2028
2079
  components.push(
2029
2080
  new Text(
2030
2081
  theme.fg("accent", ` ${spinner} ${name}`) +
2031
2082
  theme.fg(
2032
2083
  "dim",
2033
- formatLiveRowDim(id, session.usage, elapsedStr),
2084
+ formatLiveRowDim(
2085
+ id,
2086
+ session.usage,
2087
+ elapsedStr,
2088
+ // Issue #423: used / budget (percent left); `—` when no timer.
2089
+ formatBudget(session.startedAt, session.deadlineAt, nowMs),
2090
+ ),
2034
2091
  ),
2035
2092
  1,
2036
2093
  0,
@@ -2234,10 +2291,11 @@ export async function showDashboard(
2234
2291
  append(renderDashboardHeader(theme, refreshStr));
2235
2292
 
2236
2293
  // ---- Panel 2: Active subagents ----
2237
- append(renderDashboardActivePanel(theme, state.subagentSessions, Date.now));
2294
+ // Issue #423: the panel takes the same ordered projection as the monitor.
2295
+ append(renderDashboardActivePanel(theme, liveDisplayEntries(state), Date.now));
2238
2296
 
2239
2297
  // ---- Panel 3: SLA Summary ----
2240
- const allRuns = state.getRunEntries(ctx);
2298
+ const allRuns = state.getLogicalRunEntries(ctx);
2241
2299
  const recentRuns = allRuns.slice(0, state.config.slaWindowSize || 50);
2242
2300
  const metrics = recentRuns.length > 0 ? computeSLAMetrics(recentRuns) : null;
2243
2301
  append(renderDashboardSlaPanel(theme, metrics, recentRuns.length));
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
@@ -35,6 +35,28 @@ export type ThinkingLevel = "off" | "minimal" | "low" | "medium" | "high" | "xhi
35
35
 
36
36
  export const THINKING_LEVELS: ThinkingLevel[] = ["off", "minimal", "low", "medium", "high", "xhigh"];
37
37
 
38
+ /**
39
+ * Issue #443: the ONE membership test for a thinking level — the guard every
40
+ * seam that can launch a subagent calls before a DECLARED level is resolved.
41
+ *
42
+ * Why it is not `resolveThinkingLevel`: that function CLAMPS, and it cannot
43
+ * report failure. An unknown value (`"bogus"`, `"MAX"`, `" high"`) has index
44
+ * -1, so `THINKING_LEVELS[Math.min(-1, maxIdx)]` is `undefined` — the level is
45
+ * then erased into argv as `--thinking undefined`, pi warns and runs at ITS OWN
46
+ * default, and the configured cap is bypassed rather than a launch refused.
47
+ * Callers therefore check membership first and keep `resolveThinkingLevel`
48
+ * exactly as it is for valid input.
49
+ *
50
+ * Case- and whitespace-exact by construction (`THINKING_LEVELS.includes`), so
51
+ * `"High"` and `" high"` are rejected too. `""` is NOT a level: the dispatch
52
+ * seams preserve its existing meaning (top level → the configured maximum,
53
+ * per unit → the global level), so the empty string is handled by them, not
54
+ * here. pi's own `max` is not a delegated level.
55
+ */
56
+ export function isThinkingLevel(value: unknown): value is ThinkingLevel {
57
+ return typeof value === "string" && (THINKING_LEVELS as readonly string[]).includes(value);
58
+ }
59
+
38
60
  export type Priority = "critical" | "high" | "normal" | "low";
39
61
 
40
62
  export const PRIORITY_ORDER: Record<Priority, number> = {
@@ -80,6 +102,14 @@ export const SUBAGENT_ABORTED_MESSAGE = "Subagent aborted by user";
80
102
  // SUBAGENT_ABORTED_MESSAGE match) — keep the literal in sync with classifyError.
81
103
  export const SUBAGENT_SIGNAL_KILLED_MESSAGE = "Subagent killed by external signal";
82
104
 
105
+ // Issue #447: the honest stamp for a dispatch that never reached
106
+ // `session.prompt()`. Shared by the in-process pre-start cleanup
107
+ // (session-manager) and the boot scan's never-started finalize (recovery) so
108
+ // the two surfaces cannot describe the same non-event differently. It carries
109
+ // no classifyError keyword on purpose — a pre-start failure is `unknown`, not a
110
+ // timeout, an abort, or an exit error.
111
+ export const PROMPT_NEVER_ISSUED_MESSAGE = "Subagent prompt was never issued";
112
+
83
113
  /**
84
114
  * Classify a subagent result into an error category based on its errorMessage,
85
115
  * stopReason, exitCode, and stderr content. Inspects patterns in priority order.
@@ -382,6 +412,33 @@ export interface SubagentRun {
382
412
  // Option B U3 (D4): the recovery posture in force when this run was
383
413
  // dispatched. Additive: a pre-U3 record lacks it and reads as "offer".
384
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;
428
+ /**
429
+ * Issue #447: the acceptance marker. `null` at creation — the dispatch is
430
+ * TRACKED (agent record + run entry + registry entry written) but has not
431
+ * reached `session.prompt()`; an ISO timestamp written immediately before
432
+ * the prompt; absent on records written before the field existed.
433
+ *
434
+ * The tri-state IS the compatibility contract: `null` cannot be produced by
435
+ * a pre-upgrade record (JSON keeps `null`, where `undefined` would vanish),
436
+ * so the boot scan reads `null` as never-started without taking the retry
437
+ * offer away from a legacy record. It is NOT a display status — the
438
+ * vocabulary stays running | completed | failed | stopped, and "started,
439
+ * outcome unknown" remains #439's business (see `isInterruptedRun`).
440
+ */
441
+ acceptedAt?: string | null;
385
442
  startedAt: string;
386
443
  finishedAt?: string;
387
444
  durationMs?: number;
@@ -406,6 +463,13 @@ export interface LiveSubagent {
406
463
  // Issue #114: per-unit priority for the drill-in header (`p:critical` etc.).
407
464
  priority?: string;
408
465
  startedAt: number;
466
+ /**
467
+ * Issue #423: absolute deadline (epoch ms) for this run, when it has a timer.
468
+ * Absent for a foreground run with no explicit timeout (foreground has no
469
+ * default deadline) and for a background run with no persisted budget (an
470
+ * old record). Display only — the kill remains the timer owner's business.
471
+ */
472
+ deadlineAt?: number;
409
473
  liveOutput: string;
410
474
  usage: { input: number; output: number };
411
475
  ctx: ExtensionContext;
@@ -497,6 +561,12 @@ export interface SubTaskResult {
497
561
  errorCategory?: ErrorCategory;
498
562
  gitBranch?: string;
499
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;
500
570
  }
501
571
 
502
572
  /** Aggregate result for chain and parallel modes. */
@@ -769,6 +839,13 @@ export interface BackgroundAgent {
769
839
  status: AgentStatus;
770
840
  startedAt: number;
771
841
  completedAt?: number;
842
+ /**
843
+ * Issue #423: the EFFECTIVE budget of this background run (explicit timeout,
844
+ * else the 30 m default), persisted at spawn so the result and wake can
845
+ * state it after the closure that armed the timer is gone. Absent on records
846
+ * written before the field existed — read as "no budget known".
847
+ */
848
+ timeoutMs?: number;
772
849
  task: string;
773
850
  model: string;
774
851
  thinkingLevel: ThinkingLevel;
@@ -777,8 +854,22 @@ export interface BackgroundAgent {
777
854
  error?: string;
778
855
  result?: SubagentResult;
779
856
  finalOutput?: string;
857
+ /**
858
+ * Issue #465: the work branch this run's `gitMode=branch` isolation created,
859
+ * stamped when the branch is created so a DURABLE record names it even if the
860
+ * run never settles (a stuck owner never writes `result.gitBranch`, which is
861
+ * settle-only). Serializable on purpose — a refusal's message is built from it.
862
+ */
863
+ workBranch?: string;
780
864
  /** @internal — session reference for live monitor polling */
781
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;
782
873
  /**
783
874
  * @internal — Option B U2: the on-disk session file for this run, captured
784
875
  * from `SessionManager.getSessionFile()` at spawn. Used by the settle path to
@@ -802,10 +893,59 @@ export interface BackgroundAgent {
802
893
  recoveryPosture?: RecoveryMode;
803
894
  }
804
895
 
896
+ /**
897
+ * Issue #439: the part of a spawned background run that is needed to REPORT it,
898
+ * captured as a plain record the instant the spawn returns.
899
+ *
900
+ * Why a separate record rather than the agent itself: everything after the
901
+ * spawn is contained (a fault there must classify the run as STARTED, never as
902
+ * a failed spawn), and a containment whose degraded path still formats from the
903
+ * live agent re-opens the window it exists to close. Callers format from these
904
+ * fields only; `label` is `description` under the name `delegate_task` takes it
905
+ * from the caller, so a fan-out can render its unit label from the same record.
906
+ */
907
+ export interface BackgroundAgentIdentity {
908
+ id: string;
909
+ label?: string;
910
+ description: string;
911
+ task: string;
912
+ status: AgentStatus;
913
+ model: string;
914
+ }
915
+
916
+ /**
917
+ * Issue #439: what the background-spawn tail returns. `agent` is the live
918
+ * record the tail's own poller/deadline close over; `identity` is the plain
919
+ * reporting record (all callers format from it); `tailFailures` is the
920
+ * containments' ledger — empty when the whole tail attached.
921
+ *
922
+ * A non-empty `tailFailures` means exactly one thing: **the run started and its
923
+ * monitoring is degraded**. It is never a spawn failure, so no caller may
924
+ * classify it as an error (the transport retry reads `isError` as "did not
925
+ * start" and would surface a false source failure).
926
+ */
927
+ export interface BackgroundAgentSpawnResult {
928
+ agent: BackgroundAgent;
929
+ identity: BackgroundAgentIdentity;
930
+ tailFailures: string[];
931
+ }
932
+
805
933
  // ---------------------------------------------------------------------------
806
934
  // Helper functions
807
935
  // ---------------------------------------------------------------------------
808
936
 
937
+ /**
938
+ * The approval modes that make a background spawn impossible (W5, issue #28).
939
+ *
940
+ * ONE definition, two consumers — `rejectApprovalAlwaysInBackground`
941
+ * (prelude.ts, the background gates) and `resolveThinkingDispatchSwitch`
942
+ * (params.ts, the dispatch pre-flight that must not switch a dispatch into a
943
+ * rejection — issue #433). A re-spelled `=== "always"` at either site is the
944
+ * drift this helper exists to prevent: widening or narrowing what background
945
+ * can accept must change the pre-flight's verdict in the same edit.
946
+ */
947
+ export const approvalBlocksBackground = (m: ApprovalMode): boolean => m === "always";
948
+
809
949
  export function resolveThinkingLevel(
810
950
  requested: ThinkingLevel | undefined,
811
951
  maxAllowed: ThinkingLevel,
@@ -816,6 +956,26 @@ export function resolveThinkingLevel(
816
956
  return THINKING_LEVELS[Math.min(requestedIdx, maxIdx)];
817
957
  }
818
958
 
959
+ /**
960
+ * Issue #443: the value that actually REACHES resolution — the per-call
961
+ * declaration, else the selected preset's — before any clamping.
962
+ *
963
+ * ONE spelling, three readers: `resolveSubagentParams` merges it, and both
964
+ * dispatch seams guard it (`execute` and `spawnBackgroundRun`, the latter for
965
+ * the transport auto-retry). A guard that computed this differently would
966
+ * judge a value the merge never uses, which is the silent-drift class this
967
+ * helper removes; `resolveThinkingLevel` then clamps what it returns.
968
+ *
969
+ * `undefined` (omitted) and `""` are returned unchanged on purpose — they are
970
+ * existing declarations, not values to judge (see `isThinkingLevel`).
971
+ */
972
+ export function declaredThinkingLevel(
973
+ callLevel: string | undefined,
974
+ presetLevel: string | undefined,
975
+ ): string | undefined {
976
+ return callLevel ?? presetLevel;
977
+ }
978
+
819
979
  export function formatTokens(count: number): string {
820
980
  if (count < 1000) return count.toString();
821
981
  if (count < 10_000) return `${(count / 1000).toFixed(1)}k`;
@@ -948,6 +1108,30 @@ export interface TerminalOutcome {
948
1108
  errorCategory?: ErrorCategory;
949
1109
  }
950
1110
 
1111
+ /**
1112
+ * Issue #449: what the settle site saw in the session's PROJECTED message array.
1113
+ *
1114
+ * `"absent"` means exactly ONE thing: the array was READ and contained no
1115
+ * assistant message. It is supplied only by the background settle site, which
1116
+ * reads the projection the SDK rewrote before settling; a missing or throwing
1117
+ * `messages` getter is `"unknown"` (it never reaches the classifier — the settle
1118
+ * handler's catch-all owns it), and a projection holding an assistant message is
1119
+ * `"present"` whatever that message contains.
1120
+ */
1121
+ export type AssistantEvidence = "present" | "absent" | "unknown";
1122
+
1123
+ /**
1124
+ * Issue #449: the fixed failure headline for a run that settled with no
1125
+ * assistant output. The omitted message cannot be recovered, so this asserts the
1126
+ * OBSERVATION (no output) and only offers truncation as a possibility — it never
1127
+ * claims truncation as fact. Deliberately free of every TRANSPORT_SIGNATURES
1128
+ * substring (transport-retry.ts), so an automatic transport retry cannot fire on
1129
+ * this class; its `incomplete` category is independently excluded by that
1130
+ * predicate's class gate.
1131
+ */
1132
+ export const NO_ASSISTANT_OUTPUT_REASON =
1133
+ "Run settled with no assistant output — the provider's response may have been truncated and omitted by the SDK (see #449)";
1134
+
951
1135
  /**
952
1136
  * Issue #179 (D1): classify a run's terminal outcome from its final assistant
953
1137
  * stopReason. This is the settle-time counterpart to classifyError/isSubagentError
@@ -955,16 +1139,25 @@ export interface TerminalOutcome {
955
1139
  *
956
1140
  * | stopReason | status | errorCategory |
957
1141
  * |--------------------------|-----------|----------------------------|
958
- * | stop / undefined | completed | — |
1142
+ * | stop | completed | — |
1143
+ * | undefined | completed | — |
1144
+ * | undefined + absent (449) | failed | incomplete |
959
1145
  * | aborted | stopped | aborted |
960
1146
  * | error | failed | from classifyError |
961
1147
  * | length | failed | truncated |
962
1148
  * | toolUse/deferred/pending | failed | incomplete |
1149
+ *
1150
+ * Issue #449: `extra.assistantEvidence` defaults to `"unknown"`, so every caller
1151
+ * that does not pass it keeps the pre-#449 result byte for byte. Only an already-
1152
+ * KNOWN terminal outcome (the switch arms above) beats the evidence; the evidence
1153
+ * decides the formerly-default case alone. The omitted message is unrecoverable,
1154
+ * so this is a structural guard: it cannot tell a truncation omission from any
1155
+ * other resolve-with-no-assistant-message.
963
1156
  */
964
1157
  export function classifyTerminalOutcome(
965
1158
  stopReason: string | undefined,
966
1159
  errorMessage?: string,
967
- extra?: { stderr?: string; exitCode?: number },
1160
+ extra?: { stderr?: string; exitCode?: number; assistantEvidence?: AssistantEvidence },
968
1161
  ): TerminalOutcome {
969
1162
  switch (stopReason) {
970
1163
  case "aborted":
@@ -986,6 +1179,14 @@ export function classifyTerminalOutcome(
986
1179
  }),
987
1180
  };
988
1181
  default:
1182
+ // Issue #449: no terminal stopReason at all. A projection READ as an
1183
+ // array holding no assistant message is not a success — the still-open
1184
+ // turn has no answer to show for itself. Only the MISSING reason can be
1185
+ // decided by the evidence: any stopReason the caller observed (including
1186
+ // "stop") is an already-known outcome and keeps its existing result.
1187
+ if (stopReason === undefined && extra?.assistantEvidence === "absent") {
1188
+ return { status: "failed", errorCategory: "incomplete" };
1189
+ }
989
1190
  return { status: "completed" };
990
1191
  }
991
1192
  }