brl-subagent 2.9.1 → 2.9.3

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 (46) hide show
  1. package/AGENT.md +3 -0
  2. package/CHANGELOG.md +366 -0
  3. package/README.md +11 -5
  4. package/package.json +14 -11
  5. package/src/agent-tools.ts +178 -19
  6. package/src/atomic-write.ts +101 -0
  7. package/src/background-guard.ts +295 -0
  8. package/src/background-pipeline.ts +21 -5
  9. package/src/boot-recovery.ts +16 -0
  10. package/src/brief.ts +228 -0
  11. package/src/delegate-handler.ts +51 -12
  12. package/src/dispatch-header.ts +226 -0
  13. package/src/history.ts +0 -6
  14. package/src/index.ts +27 -5
  15. package/src/kill-escalation.ts +32 -9
  16. package/src/mode-prologue.ts +3 -11
  17. package/src/mode-runners.ts +0 -3
  18. package/src/notify-completion.ts +81 -12
  19. package/src/params.ts +10 -2
  20. package/src/prelude.ts +1 -9
  21. package/src/proc.ts +73 -15
  22. package/src/project-flags.ts +42 -6
  23. package/src/recovery-engine.ts +16 -2
  24. package/src/recovery.ts +29 -0
  25. package/src/retry-armed.ts +383 -0
  26. package/src/run-registry.ts +121 -1
  27. package/src/runner.ts +308 -10
  28. package/src/schema.ts +0 -11
  29. package/src/session-manager.ts +490 -54
  30. package/src/state.ts +16 -1
  31. package/src/stop-lineage.ts +280 -0
  32. package/src/templates.ts +97 -1
  33. package/src/terminal-notifier.ts +70 -4
  34. package/src/types.ts +110 -0
  35. package/src/unit-run.ts +7 -2
  36. package/src/validate.ts +47 -86
  37. package/templates/analyze-data.md +1 -0
  38. package/templates/code-review.md +1 -0
  39. package/templates/debug-issue.md +1 -0
  40. package/templates/implement-feature.md +1 -0
  41. package/templates/prototype.md +1 -0
  42. package/templates/refactor.md +1 -0
  43. package/templates/security-audit.md +1 -0
  44. package/templates/write-docs.md +1 -0
  45. package/templates/write-tests.md +1 -0
  46. package/src/dispatch-line.ts +0 -144
@@ -0,0 +1,383 @@
1
+ // Purpose: The durable "retry armed" marker for the background transport auto-retry (issue #616).
2
+ /**
3
+ * Issue #616 (Q3) — the ARMED-RETRY marker.
4
+ *
5
+ * The background transport auto-retry has an unaddressable window: the retry
6
+ * attempt's id is minted inside `spawnBackgroundSession` and its agent record +
7
+ * registry entry only land several statements later. Between the two, nothing
8
+ * durable says the retry exists, so a `stop_subagent` aimed at the dispatch
9
+ * finds a dead attempt 1 and truthfully-but-uselessly reports "stopped" while
10
+ * the retry is being started.
11
+ *
12
+ * This module closes that window with a marker that is an **intent, not a run**:
13
+ *
14
+ * - it is written by `scheduleTransportRetry` BEFORE the spawn
15
+ * (`armRetry`), naming the SOURCE run it replaces and the attempt it will
16
+ * become;
17
+ * - a stop of that dispatch sets `cancelRequested` (`cancelArmedRetry`);
18
+ * - the spawn honours it at its pre-prompt gate
19
+ * (`isRetryCancelRequested` → settle `stopped`, never prompt) and clears it
20
+ * once the retry is durable (`clearArmedRetry`).
21
+ *
22
+ * WHY NOT A FIELD ON THE EXISTING REGISTRY ENTRY: the retry's entry does not
23
+ * exist yet inside the window — that IS the window. The marker therefore hangs
24
+ * off the one id that does exist, the source run.
25
+ *
26
+ * WHY A SUBDIRECTORY (`.pi/run-registry/armed/`): every run-shaped reader —
27
+ * `listInflightRuns` (and therefore the boot scan), run history, the monitor —
28
+ * enumerates `*.json` files directly in the registry directory. A nested
29
+ * directory is invisible to all of them by construction, which is what keeps an
30
+ * INTENT from rendering as a RUN ROW. (`src/__tests__/stop-subagent-lineage.test.ts`
31
+ * pins that: arming produces no registry entry and no run record.)
32
+ *
33
+ * Writes are atomic (temp + rename) and owner-only (0o600), mirroring the
34
+ * registry's own discipline. Every reader is total: a missing, unreadable or
35
+ * malformed marker reads as "nothing armed" and never throws — the failure mode
36
+ * is the pre-#616 window, not a broken stop.
37
+ *
38
+ * THE AGE RULE (review 624 r2, B1): **age may reclaim an INTENT, never a
39
+ * CANCEL.** An UNCLAIMED marker past `ARMED_RETRY_STALE_MS` is crash residue and
40
+ * is reclaimed on read (and by the boot sweep); a marker whose
41
+ * `cancelRequested === true` is NEVER stale and is never unlinked by age, in any
42
+ * reader. The stretch between the arm and the pre-prompt gate is NOT bounded —
43
+ * the spawn waits in the process-wide spawn queue, and a `gitMode: 'branch'`
44
+ * retry waits on another run's repository lock, bound only by that run's
45
+ * lifetime — so a cancel can still have its gate coming arbitrarily far away.
46
+ * Reclaiming it on age would silently lose a live stop, which is the failure this
47
+ * issue exists to prevent.
48
+ *
49
+ * THE ACCEPTED RESIDUAL (stated, not papered over): a cancel whose spawn never
50
+ * materialises — the process died after the cancel write, before the gate — stays
51
+ * on disk forever, and every later stop of that dispatch keeps the "not claimed
52
+ * quiescent" disclosure. A permanent false NOT-QUIESCENT is acceptable; a false
53
+ * QUIESCENT is the bug this issue exists for.
54
+ */
55
+
56
+ import * as fs from 'node:fs';
57
+ import * as path from 'node:path';
58
+
59
+ import { writeFileAtomicSync } from './atomic-write';
60
+ import { registryDir } from './run-registry';
61
+ import { assertSafeAgentId } from './sanitize';
62
+ import { ensureOwnerOnlyDir } from './store-permissions';
63
+
64
+ /** The armed retry's cause. Only the automatic transport retry is ever armed. */
65
+ export type ArmedRetryCause = 'transport';
66
+
67
+ /**
68
+ * Issue #616 / review 624 (B1) — the RE-ARM BOUND.
69
+ *
70
+ * The ONE thing this bound decides is whether a SECOND arm for the same source
71
+ * may inherit a cancel from the previous one. Inside it, a re-arm PRESERVES the
72
+ * cancel (a second `scheduleTransportRetry` must not un-cancel a stop that
73
+ * already reached the dispatch). Beyond it the previous arm describes a spawn
74
+ * that never made it (the process died between arm and gate), so a cancel on it
75
+ * belongs to a spawn that is gone — preserving it would let a phantom kill the
76
+ * retry this arm is about to start.
77
+ *
78
+ * It is NOT a staleness bound: no reader reclaims a marker on this age, and age
79
+ * never reclaims a cancel at all (see `ARMED_RETRY_STALE_MS`).
80
+ */
81
+ export const ARMED_RETRY_SPAWN_BOUND_MS = 120_000;
82
+
83
+ /**
84
+ * Issue #616 / review 624 (B1) — the UNCLAIMED-MARKER STALE BOUND.
85
+ *
86
+ * Nothing clears a marker when the process dies between the arm write and the
87
+ * spawn, and no run-shaped reader enumerates `armed/` (that is what keeps an
88
+ * intent from rendering as a run row), so without an age rule a phantom marker
89
+ * makes every later stop of that dispatch print "Cancelled transport retry …"
90
+ * for a retry that will never exist, and suppress the universal claim forever.
91
+ *
92
+ * AGE RECLAIMS AN INTENT, NEVER A CANCEL. This bound applies ONLY to a marker
93
+ * with no `cancelRequested` (see the module header). A CANCELLED marker is never
94
+ * stale at any age — in the gate, in the stop's cancel, and in the boot sweep —
95
+ * because its gate can still be an unbounded wait away.
96
+ *
97
+ * THE ACCEPTED RESIDUAL: a cancel whose spawn never materialises stays on disk
98
+ * indefinitely and keeps its dispatch's "not claimed quiescent" disclosure. The
99
+ * safe direction is deliberate: a false not-quiescent is survivable, a false
100
+ * quiescent is not.
101
+ */
102
+ export const ARMED_RETRY_STALE_MS = 600_000;
103
+
104
+ /** One durable "a transport retry is being started for this run" intent. */
105
+ export interface ArmedRetry {
106
+ /** The SOURCE run id — the attempt a stop of the dispatch resolves to. */
107
+ parentId: string;
108
+ /** The attempt number the retry will carry (`sourceAttempt + 1`). */
109
+ attempt: number;
110
+ cause: ArmedRetryCause;
111
+ /** ISO stamp of the arm write (diagnostics and ordering). */
112
+ armedAt: string;
113
+ /** Set by a stop that reached the dispatch while the retry was unspawned. */
114
+ cancelRequested?: boolean;
115
+ /** ISO stamp of that cancel. */
116
+ cancelRequestedAt?: string;
117
+ }
118
+
119
+ /** The marker subdirectory, resolved against the CURRENT registry dir per call. */
120
+ function armedDir(): string {
121
+ return path.join(registryDir(), 'armed');
122
+ }
123
+
124
+ /** `<registry>/armed/<parentId>.json`, or `null` for an unusable id. */
125
+ function armedPath(parentId: string): string | null {
126
+ try {
127
+ assertSafeAgentId(parentId);
128
+ } catch {
129
+ return null;
130
+ }
131
+ return path.join(armedDir(), `${parentId}.json`);
132
+ }
133
+
134
+ function isArmedRetry(value: unknown): value is ArmedRetry {
135
+ if (!value || typeof value !== 'object') return false;
136
+ const v = value as Record<string, unknown>;
137
+ if (typeof v.parentId !== 'string' || v.parentId === '') return false;
138
+ if (typeof v.attempt !== 'number' || !Number.isFinite(v.attempt) || v.attempt < 1) return false;
139
+ if (v.cause !== 'transport') return false;
140
+ if (typeof v.armedAt !== 'string' || v.armedAt === '') return false;
141
+ if (v.cancelRequested !== undefined && typeof v.cancelRequested !== 'boolean') return false;
142
+ if (v.cancelRequestedAt !== undefined && typeof v.cancelRequestedAt !== 'string') return false;
143
+ return true;
144
+ }
145
+
146
+ function writeArmed(retry: ArmedRetry): boolean {
147
+ const file = armedPath(retry.parentId);
148
+ if (!file) return false;
149
+ try {
150
+ ensureOwnerOnlyDir(armedDir());
151
+ writeFileAtomicSync(file, JSON.stringify(retry, null, 2));
152
+ return true;
153
+ } catch {
154
+ // Best-effort by contract: a marker that cannot be written leaves the
155
+ // pre-#616 window, which is strictly better than refusing the retry.
156
+ return false;
157
+ }
158
+ }
159
+
160
+ /** The marker's age in ms, or `null` when its stamp cannot be read. */
161
+ function armedAgeMs(retry: ArmedRetry): number | null {
162
+ const armedAt = Date.parse(retry.armedAt);
163
+ if (!Number.isFinite(armedAt)) return null;
164
+ return Date.now() - armedAt;
165
+ }
166
+
167
+ /**
168
+ * Is this marker an unclaimed intent old enough to be crash residue?
169
+ *
170
+ * RULE (1), review 624 r2: a CANCEL is never stale — its spawn's gate can still
171
+ * be waiting behind the spawn queue or another run's repository lock, so an age
172
+ * bound would silently drop a live stop. Only an UNCLAIMED marker is judged, and
173
+ * only by age.
174
+ *
175
+ * TOTAL and CHEAP: one parse of a stamp already in memory. An unjudgeable stamp
176
+ * (a rolled-back clock, a corrupt `armedAt`) is NOT stale — the conservative
177
+ * side is to honour an intent we cannot date (review 624, N-r2-4).
178
+ */
179
+ function isStaleArmedRetry(retry: ArmedRetry): boolean {
180
+ if (retry.cancelRequested === true) return false;
181
+ const age = armedAgeMs(retry);
182
+ if (age === null) return false;
183
+ return age > ARMED_RETRY_STALE_MS;
184
+ }
185
+
186
+ /** Unlink a marker file. Best-effort: a failed unlink leaves it readable. */
187
+ function reclaimArmed(file: string): boolean {
188
+ try {
189
+ fs.unlinkSync(file);
190
+ return true;
191
+ } catch {
192
+ // ENOENT (already gone) and EACCES (cannot reclaim) both leave a marker that
193
+ // the next read judges stale again — no state is corrupted by failing here.
194
+ return false;
195
+ }
196
+ }
197
+
198
+ /** Read one marker. Total: absent/unreadable/malformed all read as `null`. */
199
+ export function readArmedRetry(parentId: string): ArmedRetry | null {
200
+ const file = armedPath(parentId);
201
+ if (!file) return null;
202
+ let parsed: unknown;
203
+ try {
204
+ parsed = JSON.parse(fs.readFileSync(file, 'utf-8'));
205
+ } catch {
206
+ return null;
207
+ }
208
+ if (!isArmedRetry(parsed)) return null;
209
+ // The id in the FILE must be the id we asked about: a mismatched marker is
210
+ // not this run's intent.
211
+ if (parsed.parentId !== parentId) return null;
212
+ // Review 624 (B1): reclaim on read. A stale marker must not be honoured by
213
+ // ANY reader — the gate, the cancel and the stop report all come through here.
214
+ // A cancel is never stale (rule 1), so this can only drop an unclaimed intent.
215
+ if (isStaleArmedRetry(parsed)) {
216
+ reclaimArmed(file);
217
+ return null;
218
+ }
219
+ return parsed;
220
+ }
221
+
222
+ /**
223
+ * Arm `attempt` for `parentId`. Idempotent WITHIN THE RE-ARM BOUND: re-arming an
224
+ * already-armed retry refreshes the stamp but PRESERVES a cancel that is already
225
+ * requested (a second arming must not un-cancel a stop that already reached it).
226
+ *
227
+ * BEYOND the re-arm bound the previous marker cannot be about this spawn: it
228
+ * outlived an arm whose spawn never reached the gate (the process died), so a
229
+ * cancel on it describes a spawn that is gone. Preserving it would let a phantom
230
+ * kill THIS retry at the gate, so the arm starts fresh instead (review 624, B1).
231
+ *
232
+ * An age that CANNOT be judged is IN-WINDOW (review 624, N-r2-4): honour the
233
+ * cancel rather than discard one that every other reader would still honour.
234
+ */
235
+ export function armRetry(input: {
236
+ parentId: string;
237
+ attempt: number;
238
+ armedAt: string;
239
+ }): boolean {
240
+ const existing = readArmedRetry(input.parentId);
241
+ const age = existing ? armedAgeMs(existing) : null;
242
+ const inSpawnWindow = age === null || age <= ARMED_RETRY_SPAWN_BOUND_MS;
243
+ if (existing && existing.attempt === input.attempt && inSpawnWindow) {
244
+ return writeArmed({ ...existing, armedAt: input.armedAt });
245
+ }
246
+ return writeArmed({
247
+ parentId: input.parentId,
248
+ attempt: input.attempt,
249
+ cause: 'transport',
250
+ armedAt: input.armedAt,
251
+ });
252
+ }
253
+
254
+ /**
255
+ * What a stop's cancel attempt did. Three outcomes, not two, because the caller
256
+ * must distinguish "the retry has not spawned yet" (`cancelled`) from "the
257
+ * marker was already gone because the retry became durable" (`gone` — worth ONE
258
+ * lineage re-read, since the retry is now a normal record) from "the marker is
259
+ * there and could not be written" (`failed` — the retry may still prompt, which
260
+ * is an error the caller must report).
261
+ */
262
+ export type CancelOutcome = 'cancelled' | 'gone' | 'failed';
263
+
264
+ /** Request the cancel on an armed retry. Never throws. */
265
+ export function cancelArmedRetry(parentId: string, attempt: number): CancelOutcome {
266
+ // Reclaim-on-read applies here too (B1): an unclaimed marker past the stale
267
+ // bound is `gone` for every attempt, and is unlinked rather than left to
268
+ // mislead the next reader. A CANCEL is never stale (rule 1).
269
+ const existing = readArmedRetry(parentId);
270
+ // A marker for a DIFFERENT attempt is not this retry's intent: treat it as
271
+ // gone for this attempt (the gate compares attempts too, so no cancel leaks).
272
+ if (!existing || existing.attempt !== attempt) return 'gone';
273
+ const cancelled: ArmedRetry = {
274
+ ...existing,
275
+ cancelRequested: true,
276
+ cancelRequestedAt: new Date().toISOString(),
277
+ };
278
+ return writeArmed(cancelled) ? 'cancelled' : 'failed';
279
+ }
280
+
281
+ /**
282
+ * The PRE-PROMPT gate (issue #616's Q3 seam): has a stop cancelled the retry
283
+ * that is about to prompt? Total — an unreadable marker answers `false`, which
284
+ * degrades to the pre-#616 behaviour rather than blocking a legitimate retry.
285
+ */
286
+ export function isRetryCancelRequested(parentId: string, attempt: number): boolean {
287
+ const armed = readArmedRetry(parentId);
288
+ return !!armed && armed.attempt === attempt && armed.cancelRequested === true;
289
+ }
290
+
291
+ /** Drop the marker for `parentId` when it names `attempt`. True when none is left. */
292
+ export function clearArmedRetry(parentId: string, attempt?: number): boolean {
293
+ const file = armedPath(parentId);
294
+ if (!file) return true;
295
+ const existing = readArmedRetry(parentId);
296
+ if (existing && attempt !== undefined && existing.attempt !== attempt) return false;
297
+ try {
298
+ fs.unlinkSync(file);
299
+ return true;
300
+ } catch (err) {
301
+ // Only ENOENT proves the desired end state (the same rule
302
+ // `clearInflightRun` follows).
303
+ return (err as NodeJS.ErrnoException).code === 'ENOENT';
304
+ }
305
+ }
306
+
307
+ /**
308
+ * Is this file NOT a marker for the name it sits under? Total, and never throws.
309
+ *
310
+ * A file that cannot be parsed, does not have the marker shape, or names a
311
+ * different `parentId` can never be returned by `readArmedRetry(fileParentId)`:
312
+ * the path is derived from the id and the read additionally requires the parsed
313
+ * id to match. An UNREADABLE file (EACCES, a race with the unlink) is NOT orphan
314
+ * evidence — the sweep leaves what it cannot judge to the next boot.
315
+ */
316
+ function isOrphanMarkerFile(fileParentId: string, file: string): boolean {
317
+ let text: string;
318
+ try {
319
+ text = fs.readFileSync(file, 'utf-8');
320
+ } catch {
321
+ return false;
322
+ }
323
+ let parsed: unknown;
324
+ try {
325
+ parsed = JSON.parse(text);
326
+ } catch {
327
+ return true;
328
+ }
329
+ return !isArmedRetry(parsed) || parsed.parentId !== fileParentId;
330
+ }
331
+
332
+ /**
333
+ * Issue #616 / review 624 (B1) — the BOOT SWEEP.
334
+ *
335
+ * Nothing outside a marker's own lifecycle clears it, so a process death between
336
+ * the arm write and the spawn leaves a file that every later stop of that
337
+ * dispatch would read as an armed retry. The readers already reclaim what they
338
+ * touch; this reclaims what no reader will touch for a while, so a stale intent
339
+ * does not sit on disk until the dispatch is stopped again.
340
+ *
341
+ * Cheap by construction: one `readdir` of a directory that holds at most one
342
+ * marker per in-flight retry, and the same total read every other caller uses.
343
+ *
344
+ * TWO KINDS OF RESIDUE (review 624 r2, N-r2-2):
345
+ *
346
+ * - a MARKER whose own read judges it stale — reclaimed by the read itself;
347
+ * - a FILE that is not a marker for the name it sits under (its `parentId`
348
+ * names another run, or it does not parse into a marker at all). Every
349
+ * reader is keyed by `parentId` and rejects the mismatch, so nothing can
350
+ * ever consume it — it is rubbish that would otherwise be re-scanned on
351
+ * every boot. Unlinking it drops no cancel any reader could honour.
352
+ *
353
+ * RULE (1) IS OBEYED: a well-formed, correctly-named marker with
354
+ * `cancelRequested === true` is never reclaimed here at any age — its gate may
355
+ * still be an unbounded wait away (see the module header).
356
+ */
357
+ export function sweepStaleArmedRetries(): {
358
+ scanned: number;
359
+ reclaimed: number;
360
+ } {
361
+ let files: string[];
362
+ try {
363
+ files = fs.readdirSync(armedDir());
364
+ } catch {
365
+ return { scanned: 0, reclaimed: 0 };
366
+ }
367
+ let scanned = 0;
368
+ let reclaimed = 0;
369
+ for (const file of files) {
370
+ if (!file.endsWith('.json')) continue;
371
+ const parentId = file.slice(0, -'.json'.length);
372
+ const full = path.join(armedDir(), file);
373
+ scanned += 1;
374
+ if (isOrphanMarkerFile(parentId, full)) {
375
+ if (reclaimArmed(full)) reclaimed += 1;
376
+ continue;
377
+ }
378
+ if (readArmedRetry(parentId) === null && !fs.existsSync(full)) {
379
+ reclaimed += 1;
380
+ }
381
+ }
382
+ return { scanned, reclaimed };
383
+ }
@@ -32,10 +32,23 @@
32
32
  import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
33
33
  import * as fs from "node:fs";
34
34
  import * as path from "node:path";
35
- import { CUSTOM_ENTRY_TYPES, RECOVERY_MODES, type ProcessOwner, type RecoveryMode, type SubagentRun } from "./types";
35
+ import {
36
+ CUSTOM_ENTRY_TYPES,
37
+ RECOVERY_MODES,
38
+ RETRY_CAUSES,
39
+ type ProcessOwner,
40
+ type RecoveryMode,
41
+ type RetryCause,
42
+ type SubagentRun,
43
+ type SubagentUsageGroup,
44
+ } from "./types";
45
+ import { createLogger } from "./logging";
36
46
  import { assertSafeAgentId } from "./sanitize";
37
47
  import { ensureOwnerOnlyDir } from "./store-permissions";
38
48
 
49
+ /** Module logger — issue #648 needs one place to say the host cannot append usage. */
50
+ const log = createLogger("run-registry");
51
+
39
52
  /** Which execution path owns an in-flight run (drives the boot scan's mark). */
40
53
  export type InflightRunKind = "foreground" | "unit" | "background";
41
54
 
@@ -72,6 +85,13 @@ export interface InflightRun {
72
85
  id: string;
73
86
  dispatchId?: string;
74
87
  attempt?: number;
88
+ /**
89
+ * Issue #616: why this attempt exists (`transport` auto-retry vs a manual
90
+ * `retryRunId` retry). Mirrored from the run record so a stop that must
91
+ * resolve a retry from the registry alone (no agent record yet) can still
92
+ * scope itself. Absent = unknown, never `transport`.
93
+ */
94
+ retryCause?: RetryCause;
75
95
  kind: InflightRunKind;
76
96
  owner?: ProcessOwner;
77
97
  childMarker?: string;
@@ -114,6 +134,7 @@ export interface InflightRunInput {
114
134
  id: string;
115
135
  dispatchId?: string;
116
136
  attempt?: number;
137
+ retryCause?: RetryCause;
117
138
  kind: InflightRunKind;
118
139
  owner?: ProcessOwner;
119
140
  childMarker?: string;
@@ -218,6 +239,13 @@ function normalizeEnrichment(value: InflightRun, raw: Record<string, unknown>):
218
239
  } else {
219
240
  delete entry.originalParams;
220
241
  }
242
+ // Issue #616: same lenient rule — a cause we cannot trust is DROPPED (absent ⇒
243
+ // unknown ⇒ never auto-stopped), never coerced to the stop-scoped value.
244
+ if (typeof raw.retryCause === "string" && (RETRY_CAUSES as readonly string[]).includes(raw.retryCause)) {
245
+ entry.retryCause = raw.retryCause as RetryCause;
246
+ } else {
247
+ delete entry.retryCause;
248
+ }
221
249
  // Issue #447: keep the tri-state intact and treat anything else as LEGACY
222
250
  // (absent) rather than inventing a fourth state. A mistyped marker must
223
251
  // never downgrade a real run into the never-started class.
@@ -267,6 +295,7 @@ function mergeInput(base: InflightRun, input: InflightRunInput): InflightRun {
267
295
  const next: InflightRun = { ...base, id: input.id, kind: input.kind };
268
296
  if (input.dispatchId !== undefined) next.dispatchId = input.dispatchId;
269
297
  if (input.attempt !== undefined) next.attempt = input.attempt;
298
+ if (input.retryCause !== undefined) next.retryCause = input.retryCause;
270
299
  if (input.recoveryPosture !== undefined) next.recoveryPosture = input.recoveryPosture;
271
300
  if (input.owner !== undefined) next.owner = input.owner;
272
301
  if (input.childMarker !== undefined) next.childMarker = input.childMarker;
@@ -425,6 +454,7 @@ function toRegistryInput(run: SubagentRun, kind: InflightRunKind): InflightRunIn
425
454
  id: run.id,
426
455
  dispatchId: run.dispatchId,
427
456
  attempt: run.attempt,
457
+ retryCause: run.retryCause,
428
458
  kind,
429
459
  recoveryPosture: run.recoveryPosture,
430
460
  owner: run.owner,
@@ -459,6 +489,75 @@ export interface PersistRunRecordOptions {
459
489
  * passes this flag. Every other writer keeps the historical order.
460
490
  */
461
491
  deferRetire?: boolean;
492
+ /**
493
+ * Issue #648: the run's spend, one entry per model group, appended AFTER the
494
+ * record. ABSENT means "this write claims no usage" — the correct value for a
495
+ * dispatch/refresh write, a mode aggregate (it sums its units' records) and
496
+ * the boot scan's interrupted mark. A SUBAGENT TERMINAL site does not use this
497
+ * field: it calls {@link persistSettledRunRecord}, which requires the groups.
498
+ */
499
+ usageGroups?: readonly SubagentUsageGroup[];
500
+ }
501
+
502
+ /**
503
+ * Issue #648: one host warning per process (= one pi process per session). The
504
+ * settle path must survive a host pi < 1.8.0 that has no `appendUsage`, and it
505
+ * must not say so on every run.
506
+ */
507
+ let appendUsageWarningLogged = false;
508
+
509
+ /** Test-only: restore the one-time warning so a spec can observe both states. */
510
+ export function __resetAppendUsageWarning(): void {
511
+ appendUsageWarningLogged = false;
512
+ }
513
+
514
+ /**
515
+ * Q8: `<label|description|run> (<run id, 8>)` — survives record pruning, and the
516
+ * 8-character prefix is a DISPLAY POINTER a human can see and type, not a value
517
+ * `retryRunId` accepts: retry resolution is an exact full-id match
518
+ * (`findSpawnRunById` → `r.id === id`, no prefix match in the retryRunId path), the
519
+ * same way the retry surface renders `run.id.slice(0, 8)` beside the full id.
520
+ */
521
+ function usageNote(run: SubagentRun): string {
522
+ const name = run.label?.trim() || run.description?.trim() || "run";
523
+ return `${name} (${run.id.slice(0, 8)})`;
524
+ }
525
+
526
+ /**
527
+ * Issue #648: append the run's spend to the CONDUCTOR's session, one entry per
528
+ * model group, so the footer totals the money the subagent actually burned.
529
+ *
530
+ * Contract: NEVER throws (this runs on a settle path, and a footer nicety must
531
+ * not change a run's outcome), and appends NOTHING for an empty group list or a
532
+ * host without `appendUsage` — the run record is already written either way.
533
+ */
534
+ function appendRunUsage(
535
+ pi: ExtensionAPI,
536
+ run: SubagentRun,
537
+ groups: readonly SubagentUsageGroup[] | undefined,
538
+ ): void {
539
+ if (!groups || groups.length === 0) return;
540
+ if (typeof pi.appendUsage !== "function") {
541
+ if (!appendUsageWarningLogged) {
542
+ appendUsageWarningLogged = true;
543
+ log.warn("footer subagent usage unavailable: host pi lacks appendUsage", {
544
+ runId: run.id,
545
+ });
546
+ }
547
+ return;
548
+ }
549
+ const note = usageNote(run);
550
+ for (const group of groups) {
551
+ try {
552
+ pi.appendUsage({ kind: "subagent", provider: group.provider, model: group.model, usage: group.usage, note });
553
+ } catch (err) {
554
+ // A footer entry is best-effort: the run record is the durable claim.
555
+ log.warn("footer subagent usage append failed", {
556
+ runId: run.id,
557
+ error: err instanceof Error ? err.message : String(err),
558
+ });
559
+ }
560
+ }
462
561
  }
463
562
 
464
563
  export function persistRunRecord(
@@ -473,4 +572,25 @@ export function persistRunRecord(
473
572
  registerInflightRun(toRegistryInput(run, kind));
474
573
  }
475
574
  pi.appendEntry(CUSTOM_ENTRY_TYPES.run, run);
575
+ // Issue #648 (Q6): the usage rides on the SAME write, after it. A record that
576
+ // failed to append must not leave money attributed to a run nobody can see.
577
+ appendRunUsage(pi, run, options?.usageGroups);
578
+ }
579
+
580
+ /**
581
+ * Issue #648 (Q6): THE terminal subagent write. `usageGroups` is REQUIRED, so a
582
+ * subagent terminal site cannot silently omit the run's spend — omitting the
583
+ * argument is a type error, and the honest "measured nothing" is `[]` (a
584
+ * `turns: 0` run, a crash before the first assistant turn, the deadline
585
+ * snapshot). Structural writers (dispatch/refresh, mode aggregates, boot
586
+ * recovery) keep {@link persistRunRecord}: they are not a subagent terminal site
587
+ * and have no usage to claim.
588
+ */
589
+ export function persistSettledRunRecord(
590
+ pi: ExtensionAPI,
591
+ run: SubagentRun,
592
+ usageGroups: readonly SubagentUsageGroup[],
593
+ options?: PersistRunRecordOptions,
594
+ ): void {
595
+ persistRunRecord(pi, run, undefined, { ...options, usageGroups });
476
596
  }