brl-subagent 2.9.2 → 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.
@@ -40,10 +40,15 @@ import {
40
40
  type RecoveryMode,
41
41
  type RetryCause,
42
42
  type SubagentRun,
43
+ type SubagentUsageGroup,
43
44
  } from "./types";
45
+ import { createLogger } from "./logging";
44
46
  import { assertSafeAgentId } from "./sanitize";
45
47
  import { ensureOwnerOnlyDir } from "./store-permissions";
46
48
 
49
+ /** Module logger — issue #648 needs one place to say the host cannot append usage. */
50
+ const log = createLogger("run-registry");
51
+
47
52
  /** Which execution path owns an in-flight run (drives the boot scan's mark). */
48
53
  export type InflightRunKind = "foreground" | "unit" | "background";
49
54
 
@@ -484,6 +489,75 @@ export interface PersistRunRecordOptions {
484
489
  * passes this flag. Every other writer keeps the historical order.
485
490
  */
486
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
+ }
487
561
  }
488
562
 
489
563
  export function persistRunRecord(
@@ -498,4 +572,25 @@ export function persistRunRecord(
498
572
  registerInflightRun(toRegistryInput(run, kind));
499
573
  }
500
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 });
501
596
  }
package/src/runner.ts CHANGED
@@ -12,6 +12,7 @@
12
12
 
13
13
  import type { TranscriptMessage, TranscriptContentBlock, TranscriptToolCallBlock } from "./transcript-tail";
14
14
  import type { AgentToolResult } from "@earendil-works/pi-agent-core";
15
+ import type { Usage } from "@earendil-works/pi-ai";
15
16
  import { spawn, type ChildProcess } from "node:child_process";
16
17
  import * as fs from "node:fs";
17
18
  import * as path from "node:path";
@@ -29,6 +30,7 @@ import {
29
30
  SUBAGENT_SIGNAL_KILLED_MESSAGE,
30
31
  type SubagentResult,
31
32
  type SubagentToolOptions,
33
+ type SubagentUsageGroup,
32
34
  type UsageStats,
33
35
  type ThinkingLevel,
34
36
  } from "./types";
@@ -161,6 +163,59 @@ export function __registerActiveChildForTest(proc: ChildProcess, marker?: string
161
163
  };
162
164
  }
163
165
 
166
+ /**
167
+ * #244: the escalations this module started and nobody awaited. The abort handler
168
+ * and the timeout handler both `trackEscalation(...)` their `escalateKill(...)`
169
+ * — `launchForeground` settles on the child's `close`, which the escalation does
170
+ * NOT gate, so "the run returned" does not imply "the escalation finished". A
171
+ * test that resets its `/proc` fixtures on return would then be reading the
172
+ * kernel mid-escalation; `__awaitEscalationsForTest` is how it waits instead.
173
+ *
174
+ * Inert in production (an entry per escalation that removes itself on settle),
175
+ * and the AWAIT is gated, so no production caller can wait here.
176
+ */
177
+ const inFlightEscalations = new Set<Promise<unknown>>();
178
+
179
+ /**
180
+ * Register an escalation for test draining. Settles the entry on BOTH outcomes
181
+ * via `then` (not `.finally`, whose chained promise would carry a rejection
182
+ * nobody handles): `escalateKill` is documented as never rejecting over a target
183
+ * that vanished, but a throwing `sleep` still must not leave a stale entry that
184
+ * would hang `__awaitEscalationsForTest` forever.
185
+ */
186
+ function trackEscalation(escalation: Promise<unknown>): void {
187
+ inFlightEscalations.add(escalation);
188
+ const settle = () => {
189
+ inFlightEscalations.delete(escalation);
190
+ };
191
+ void escalation.then(settle, settle);
192
+ }
193
+
194
+ /**
195
+ * #244: TEST-ONLY drain of the in-flight abort/timeout escalations. Throws
196
+ * outside the test environment (same runtime gate as
197
+ * `__setEscalationTimingForTest`): production has no caller that should wait on
198
+ * a queue it never observes, and a stray import must not turn a kill into a
199
+ * join.
200
+ *
201
+ * Loops: `await`ing the CURRENT set can settle an escalation that spun off no
202
+ * new one, but a settled promise is removed by its own `then` BEFORE the await
203
+ * resumes only if it settled first — re-checking `size` after every await is
204
+ * what makes "empty" mean empty rather than "empty at the last sample". Never
205
+ * rejects on a failed escalation (`allSettled`): a test drains, it does not
206
+ * assert a kill's success.
207
+ */
208
+ export async function __awaitEscalationsForTest(): Promise<void> {
209
+ if (!isTestEnvironment()) {
210
+ throw new Error(
211
+ "__awaitEscalationsForTest() is test-only and cannot run in production.",
212
+ );
213
+ }
214
+ while (inFlightEscalations.size > 0) {
215
+ await Promise.allSettled([...inFlightEscalations]);
216
+ }
217
+ }
218
+
164
219
  /**
165
220
  * Escalation target for one spawned child. `verifyDeath` defaults to the
166
221
  * REAL-exit check (`childExited`) AND — on a group target — group emptiness, and
@@ -532,6 +587,242 @@ export function accumulateUsage(
532
587
  }
533
588
  }
534
589
 
590
+ // ---------------------------------------------------------------------------
591
+ // Issue #648: per-model usage groups (the footer's subagent spend)
592
+ // ---------------------------------------------------------------------------
593
+
594
+ /**
595
+ * Is this value a JSON object (a message, an entry, a usage record)?
596
+ * Kept local: the grouping helpers read untyped stream/session records.
597
+ */
598
+ function isRecord(value: unknown): value is Record<string, unknown> {
599
+ return typeof value === "object" && value !== null;
600
+ }
601
+
602
+ /** The model half of a usage record may be `model` or the responses-API `responseModel`. */
603
+ function nonEmptyString(value: unknown): string | undefined {
604
+ return typeof value === "string" && value.length > 0 ? value : undefined;
605
+ }
606
+
607
+ function emptyHostUsage(): Usage {
608
+ return {
609
+ input: 0,
610
+ output: 0,
611
+ cacheRead: 0,
612
+ cacheWrite: 0,
613
+ totalTokens: 0,
614
+ cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },
615
+ };
616
+ }
617
+
618
+ /** Add one host `Usage` onto an accumulated group. Absent fields contribute 0. */
619
+ function addHostUsage(target: Usage, src: Record<string, unknown>): void {
620
+ const cost = isRecord(src.cost) ? src.cost : {};
621
+ target.input += typeof src.input === "number" ? src.input : 0;
622
+ target.output += typeof src.output === "number" ? src.output : 0;
623
+ target.cacheRead += typeof src.cacheRead === "number" ? src.cacheRead : 0;
624
+ target.cacheWrite += typeof src.cacheWrite === "number" ? src.cacheWrite : 0;
625
+ target.totalTokens += typeof src.totalTokens === "number" ? src.totalTokens : 0;
626
+ target.cost.input += typeof cost.input === "number" ? cost.input : 0;
627
+ target.cost.output += typeof cost.output === "number" ? cost.output : 0;
628
+ target.cost.cacheRead += typeof cost.cacheRead === "number" ? cost.cacheRead : 0;
629
+ target.cost.cacheWrite += typeof cost.cacheWrite === "number" ? cost.cacheWrite : 0;
630
+ target.cost.total += typeof cost.total === "number" ? cost.total : 0;
631
+ }
632
+
633
+ /** "entirely zero" = every token bucket AND every cost component is 0 (the drop rule). */
634
+ function isZeroHostUsage(usage: Usage): boolean {
635
+ return (
636
+ usage.input === 0 &&
637
+ usage.output === 0 &&
638
+ usage.cacheRead === 0 &&
639
+ usage.cacheWrite === 0 &&
640
+ usage.totalTokens === 0 &&
641
+ usage.cost.input === 0 &&
642
+ usage.cost.output === 0 &&
643
+ usage.cost.cacheRead === 0 &&
644
+ usage.cost.cacheWrite === 0 &&
645
+ usage.cost.total === 0
646
+ );
647
+ }
648
+
649
+ /** A group addressable by the host's own `${provider}/${model}` breakdown key. */
650
+ interface GroupSlot {
651
+ provider: string;
652
+ model: string;
653
+ usage: Usage;
654
+ }
655
+
656
+ function groupKey(provider: string, model: string): string {
657
+ return `${provider}\u0000${model}`;
658
+ }
659
+
660
+ /** Fold one usage record into the group map. A record without usage is skipped. */
661
+ function foldUsage(
662
+ groups: Map<string, GroupSlot>,
663
+ provider: string,
664
+ model: string,
665
+ usage: unknown,
666
+ ): void {
667
+ if (!isRecord(usage)) return;
668
+ const key = groupKey(provider, model);
669
+ let group = groups.get(key);
670
+ if (!group) {
671
+ group = { provider, model, usage: emptyHostUsage() };
672
+ groups.set(key, group);
673
+ }
674
+ addHostUsage(group.usage, usage);
675
+ }
676
+
677
+ /** pi's breakdown key uses `responseModel ?? model`; absent names degrade honestly. */
678
+ function messageModel(msg: Record<string, unknown>): { provider: string; model: string } {
679
+ return {
680
+ provider: nonEmptyString(msg.provider) ?? "unknown",
681
+ model: nonEmptyString(msg.responseModel) ?? nonEmptyString(msg.model) ?? "unknown",
682
+ };
683
+ }
684
+
685
+ /** The model a compaction/branch-summary call is attributed to (it carries no model). */
686
+ function lastAssistantModel(
687
+ messages: ReadonlyArray<unknown> | undefined,
688
+ ): { provider: string; model: string } | undefined {
689
+ const list = messages ?? [];
690
+ for (let index = list.length - 1; index >= 0; index--) {
691
+ const msg = list[index];
692
+ if (isRecord(msg) && msg.role === "assistant") return messageModel(msg);
693
+ }
694
+ return undefined;
695
+ }
696
+
697
+ /** `provider/model-id` (the run record's folded model string) → its two halves. */
698
+ function parseModelString(model: string | undefined): { provider: string; model: string } | undefined {
699
+ if (!model) return undefined;
700
+ const slash = model.indexOf("/");
701
+ if (slash <= 0 || slash === model.length - 1) return undefined;
702
+ return { provider: model.slice(0, slash), model: model.slice(slash + 1) };
703
+ }
704
+
705
+ function finalizeGroups(groups: Map<string, GroupSlot>): SubagentUsageGroup[] {
706
+ return [...groups.values()].filter((group) => !isZeroHostUsage(group.usage));
707
+ }
708
+
709
+ /** The model a usage record that names no model is attributed to (it carries none). */
710
+ function provenanceAttribution(
711
+ messages: ReadonlyArray<unknown> | undefined,
712
+ fallbackModel?: string,
713
+ ): { provider: string; model: string } {
714
+ return (
715
+ lastAssistantModel(messages) ??
716
+ parseModelString(fallbackModel) ??
717
+ { provider: "unknown", model: "unknown" }
718
+ );
719
+ }
720
+
721
+ /**
722
+ * Fold one message list into the group map (one rule, two callers).
723
+ *
724
+ * Assistant turns key their OWN `provider` + `responseModel ?? model`. A
725
+ * `toolResult` message carries `Usage` (the tool's side spend) but NO model, so
726
+ * it joins the group of the run's last assistant message — the attribution rule
727
+ * the spec already accepts for compaction, and the same `Tools/summaries` bucket
728
+ * the host's own breakdown files it under (issue #648 review r2). Dropping it
729
+ * under-counts the money the footer exists to report.
730
+ */
731
+ function foldMessageUsage(
732
+ groups: Map<string, GroupSlot>,
733
+ messages: ReadonlyArray<unknown> | undefined,
734
+ attribution: { provider: string; model: string },
735
+ ): void {
736
+ for (const msg of messages ?? []) {
737
+ if (!isRecord(msg)) continue;
738
+ if (msg.role === "assistant") {
739
+ const { provider, model } = messageModel(msg);
740
+ foldUsage(groups, provider, model, msg.usage);
741
+ } else if (msg.role === "toolResult" && msg.usage) {
742
+ foldUsage(groups, attribution.provider, attribution.model, msg.usage);
743
+ }
744
+ }
745
+ }
746
+
747
+ /**
748
+ * Issue #648 (Q3): group a run's messages into the host footer's per-model key
749
+ * — `provider` + `responseModel ?? model` — and sum each group's usage in the
750
+ * host's `Usage` shape. Groups whose usage is entirely zero are DROPPED: a run
751
+ * that measured nothing contributes no footer entry.
752
+ *
753
+ * Two sources come from `messages`: assistant turns, and `toolResult` usage (a
754
+ * tool's own spend, attributed like compaction — see {@link foldMessageUsage}).
755
+ * Pure: no I/O, no clock. The foreground path passes `result.messages`.
756
+ */
757
+ export function usageGroupsFrom(messages: ReadonlyArray<unknown> | undefined): SubagentUsageGroup[] {
758
+ const groups = new Map<string, GroupSlot>();
759
+ foldMessageUsage(groups, messages, provenanceAttribution(messages));
760
+ return finalizeGroups(groups);
761
+ }
762
+
763
+ /**
764
+ * Issue #648 (Q4/C): the BACKGROUND path's grouping. The child's own footer sums
765
+ * FOUR sources — assistant messages, `toolResult` usage, `type: "usage"` entries
766
+ * and `compaction`/`branch_summary` usage — so a run's recorded spend must
767
+ * include all four or it cannot equal what the child would have reported.
768
+ *
769
+ * A `usage` entry names its own provider/model. A compaction/branch-summary
770
+ * entry does NOT, so it is attributed to the model of the run's last assistant
771
+ * message (falling back to `fallbackModel`, the run record's folded
772
+ * `provider/model-id`); the spec states this so the number stays explainable.
773
+ * `toolResult` messages take the same attribution — {@link foldMessageUsage}.
774
+ * Pure, like {@link usageGroupsFrom}.
775
+ */
776
+ export function usageGroupsFromSession(
777
+ messages: ReadonlyArray<unknown> | undefined,
778
+ entries: ReadonlyArray<unknown> | undefined,
779
+ fallbackModel?: string,
780
+ ): SubagentUsageGroup[] {
781
+ const groups = new Map<string, GroupSlot>();
782
+ const attribution = provenanceAttribution(messages, fallbackModel);
783
+ foldMessageUsage(groups, messages, attribution);
784
+ for (const entry of entries ?? []) {
785
+ if (!isRecord(entry)) continue;
786
+ if (entry.type === "usage") {
787
+ foldUsage(
788
+ groups,
789
+ nonEmptyString(entry.provider) ?? attribution.provider,
790
+ nonEmptyString(entry.model) ?? attribution.model,
791
+ entry.usage,
792
+ );
793
+ } else if ((entry.type === "compaction" || entry.type === "branch_summary") && entry.usage) {
794
+ foldUsage(groups, attribution.provider, attribution.model, entry.usage);
795
+ }
796
+ }
797
+ return finalizeGroups(groups);
798
+ }
799
+
800
+ /** Token/cost totals for a group list — the run record's `cost`/`tokensIn`/… derive from this. */
801
+ export interface UsageGroupTotals {
802
+ input: number;
803
+ output: number;
804
+ cacheRead: number;
805
+ cacheWrite: number;
806
+ cost: number;
807
+ }
808
+
809
+ /**
810
+ * Sum the groups into the flattened totals our run record stores. Deriving the
811
+ * record's numbers from the SAME groups the footer receives is what makes the
812
+ * two agree by construction (issue #648).
813
+ */
814
+ export function sumUsageGroups(groups: ReadonlyArray<SubagentUsageGroup>): UsageGroupTotals {
815
+ const totals: UsageGroupTotals = { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, cost: 0 };
816
+ for (const group of groups) {
817
+ totals.input += group.usage.input;
818
+ totals.output += group.usage.output;
819
+ totals.cacheRead += group.usage.cacheRead;
820
+ totals.cacheWrite += group.usage.cacheWrite;
821
+ totals.cost += group.usage.cost.total;
822
+ }
823
+ return totals;
824
+ }
825
+
535
826
  // ---------------------------------------------------------------------------
536
827
  // Abort handler
537
828
  // ---------------------------------------------------------------------------
@@ -556,11 +847,15 @@ function attachAbortHandler(
556
847
  // a SIGTERM-ignoring child dead and skipped the force-kill. The same
557
848
  // poll/early-exit wait `reapActiveChildren` uses means a cooperative child
558
849
  // completes in ms while a stubborn one gets SIGKILL at the grace boundary.
559
- void escalateKill([childTarget(proc)], {
560
- graceMs: escalationTiming.graceMs,
561
- pollMs: escalationTiming.pollMs,
562
- sleep: realSleep,
563
- });
850
+ // #244: tracked (not bare `void`), so a test can drain the escalation
851
+ // before its `/proc` fixtures go away.
852
+ trackEscalation(
853
+ escalateKill([childTarget(proc)], {
854
+ graceMs: escalationTiming.graceMs,
855
+ pollMs: escalationTiming.pollMs,
856
+ sleep: realSleep,
857
+ }),
858
+ );
564
859
  };
565
860
  if (signal.aborted) killProc();
566
861
  else signal.addEventListener("abort", killProc, { once: true });
@@ -1293,11 +1588,14 @@ ${msgBlock}`;
1293
1588
  // Same REAL-exit check as the abort path (issue #303 — see there):
1294
1589
  // `child.killed` flips on signal-sent, not process-death, so it would
1295
1590
  // skip the SIGKILL for a SIGTERM-ignoring child.
1296
- void escalateKill([childTarget(proc)], {
1297
- graceMs: escalationTiming.graceMs,
1298
- pollMs: escalationTiming.pollMs,
1299
- sleep: realSleep,
1300
- });
1591
+ // #244: tracked, same as the abort handler above.
1592
+ trackEscalation(
1593
+ escalateKill([childTarget(proc)], {
1594
+ graceMs: escalationTiming.graceMs,
1595
+ pollMs: escalationTiming.pollMs,
1596
+ sleep: realSleep,
1597
+ }),
1598
+ );
1301
1599
  }, timeout);
1302
1600
  proc.on("close", () => clearTimeout(timer));
1303
1601
  }
package/src/schema.ts CHANGED
@@ -237,17 +237,6 @@ export const delegateTaskParamsSchema = Type.Object({
237
237
  "Warnings are surfaced either way. force never suppresses outputFile-without-write conflicts.",
238
238
  }),
239
239
  ),
240
- noJev: Type.Optional(
241
- Type.String({
242
- minLength: 1,
243
- description:
244
- "Stated bypass for the Jev dispatch-line pre-flight, which is active ONLY in a project whose package.json sets the `brl-subagent.processChecks` field (this repository). " +
245
- "A reason string that states WHY the line is missing: the dispatch proceeds and the reason is surfaced as a warning in the result, so the bypass is never silent. " +
246
- "The reason is validated when the dispatch is handled, not by this schema: the argument validator coerces loosely typed input, so a boolean or a number arrives as its text (`true` becomes \"true\") and is REFUSED exactly like an absent bypass. " +
247
- "It bypasses ONLY the line check — capability conflicts still reject (unlike force). " +
248
- "Append `jev: unavailable` to the task instead when the classifier did not run.",
249
- }),
250
- ),
251
240
  background: Type.Optional(
252
241
  Type.Boolean({
253
242
  description:
@@ -20,13 +20,14 @@ import {
20
20
  type RetryCause,
21
21
  type SubagentResult,
22
22
  type SubagentRun,
23
+ type SubagentUsageGroup,
23
24
  type ThinkingLevel,
24
25
  type SubagentToolOptions,
25
26
  type UsageStats,
26
27
  type ErrorCategory,
27
28
  type AssistantEvidence,
28
29
  } from './types';
29
- import { accumulateUsage } from './runner';
30
+ import { sumUsageGroups, usageGroupsFromSession } from './runner';
30
31
  import * as eventBus from './event-bus';
31
32
  import * as transcript from './transcript';
32
33
  import { createEvent } from './event-bus';
@@ -52,6 +53,7 @@ import { effectiveBackgroundBudget } from './validate';
52
53
  import { currentProcessOwner, classifyOwner, defaultRecoveryDeps, type AgentRecordFailureReason } from './recovery';
53
54
  import {
54
55
  persistRunRecord,
56
+ persistSettledRunRecord,
55
57
  listInflightRuns,
56
58
  clearInflightRun,
57
59
  markRecordFlipPending,
@@ -2107,9 +2109,32 @@ export async function spawnBackgroundSession(
2107
2109
  * deadline ever sets it (see the arm site). A settle→settle re-entry (the
2108
2110
  * catch-all after a throwing handler) therefore still writes nothing, which is
2109
2111
  * the single-terminal-entry contract the old `runFinalized` guard enforced.
2112
+ * CONSUMED by the amendment (issue #648 review r2): one snapshot, one amendment,
2113
+ * so a second terminal call cannot append the run's spend twice.
2110
2114
  */
2111
2115
  let snapshot: SubagentRun | undefined;
2112
2116
 
2117
+ /**
2118
+ * Issue #648 (Q4/C): the child session's own entries. The child's footer sums
2119
+ * assistant messages AND `toolResult` usage (the messages half, taken from
2120
+ * `session.messages`) plus `type: "usage"` entries and compaction/branch-summary
2121
+ * calls, so a run's recorded spend must fold the same sources to agree with what
2122
+ * the child would have reported. Defensive by contract: a session fixture without
2123
+ * a manager (most tests) is an empty source, never a throw.
2124
+ */
2125
+ const childEntries = (): ReadonlyArray<unknown> => {
2126
+ try {
2127
+ const entries = session.sessionManager?.getEntries?.();
2128
+ return Array.isArray(entries) ? entries : [];
2129
+ } catch {
2130
+ return [];
2131
+ }
2132
+ };
2133
+
2134
+ /** The groups the TERMINAL write (and its amendment) appends. Never the snapshot. */
2135
+ const terminalUsageGroups = (): SubagentUsageGroup[] =>
2136
+ usageGroupsFromSession(session.messages ?? [], childEntries(), run.model);
2137
+
2113
2138
  /**
2114
2139
  * This call's OWN classification. The retention/prune gate reads THIS — never
2115
2140
  * the snapshot's — because at the deadline a run looks like `timeout` (not
@@ -2147,6 +2172,14 @@ export async function spawnBackgroundSession(
2147
2172
  stopReason?: string;
2148
2173
  errorCategory?: ErrorCategory;
2149
2174
  prune?: boolean;
2175
+ /**
2176
+ * Issue #648 (Q2): this write is the DEADLINE's classification snapshot, not
2177
+ * a measurement. A still-running agent's usage is zero/partial, so the
2178
+ * snapshot appends NO footer entry — the payload lands on the amendment the
2179
+ * late settle writes. Set by the one call site that IS the deadline; every
2180
+ * other terminal write leaves it unset and appends its groups.
2181
+ */
2182
+ snapshot?: boolean;
2150
2183
  /**
2151
2184
  * Issue #546: do NOT retire the registry entry here — the caller owns the
2152
2185
  * retirement and performs it only once the record flip is durable. Only the
@@ -2208,7 +2241,8 @@ export async function spawnBackgroundSession(
2208
2241
  // second classification claim — mutant M7).
2209
2242
  if (entryWritten) {
2210
2243
  // No snapshot => this is a settle RE-ENTRY (the settle already wrote the
2211
- // record); nothing new to say. Only a deadline snapshot is amendable.
2244
+ // record, and any deadline snapshot has already been amended); nothing new
2245
+ // to say. Only an UNCONSUMED deadline snapshot is amendable.
2212
2246
  if (!snapshot) return undefined;
2213
2247
  const amended: SubagentRun = {
2214
2248
  ...snapshot,
@@ -2221,7 +2255,15 @@ export async function spawnBackgroundSession(
2221
2255
  outputSummary: finalOutput.slice(0, 200),
2222
2256
  fullOutput: finalOutput || undefined,
2223
2257
  };
2224
- persistRunRecord(pi, amended);
2258
+ persistSettledRunRecord(pi, amended, terminalUsageGroups());
2259
+ // Issue #648 review r2: the latch is CONSUMED by the write that used it.
2260
+ // Leaving the snapshot set let a LATER terminal call (the catch-all after a
2261
+ // settle-handler step threw — a read-only transcript, a throwing emit) amend
2262
+ // the same snapshot a SECOND time. Before #648 that duplicated a record;
2263
+ // with the run's spend riding on the write it duplicated MONEY — the footer
2264
+ // over-counted that run by its whole cost. Cleared only AFTER the append
2265
+ // resolved, so a throwing write still leaves the amendment retryable.
2266
+ snapshot = undefined;
2225
2267
  log.info("Background run amended after a late settle", {
2226
2268
  agentId: id,
2227
2269
  status: amended.status,
@@ -2268,7 +2310,9 @@ export async function spawnBackgroundSession(
2268
2310
  ? { ...(run.originalParams ?? {}), errorCategory }
2269
2311
  : run.originalParams,
2270
2312
  };
2271
- persistRunRecord(pi, entry, undefined, { deferRetire: terminal?.deferRetire });
2313
+ persistSettledRunRecord(pi, entry, terminal?.snapshot ? [] : terminalUsageGroups(), {
2314
+ deferRetire: terminal?.deferRetire,
2315
+ });
2272
2316
  // Issue #453: set only AFTER the append resolved. A throwing write therefore
2273
2317
  // leaves `entryWritten === false`, so a later settle still classifies the run
2274
2318
  // instead of amending a record that was never written (mutant M3).
@@ -2633,22 +2677,41 @@ export async function spawnBackgroundSession(
2633
2677
 
2634
2678
  // Issue #122: the session's REAL usage lives on the assistant messages in
2635
2679
  // session.messages — each turn carries the same usage shape accumulateUsage
2636
- // folds (the runner's single source of truth for usage semantics: turns++,
2637
- // sum input/output/cache, cost.total, contextTokens from totalTokens). Fold
2638
- // the session's assistant turns into a fresh stats object and MERGE it onto
2639
- // the agent's result record — never replace: the git-diff branches may have
2640
- // already set exitCode/messages/stderr/gitBranch/gitDiff, and the aborted/
2641
- // failed branches previously OVERWROTE usage with the empty fallback. Runs
2642
- // on every terminal path right before the finalize; must never throw
2643
- // (best-effort, same discipline as markTerminalBestEffort).
2680
+ // folds (turns++, sum input/output/cache, cost.total, contextTokens from
2681
+ // totalTokens). Fold the session's assistant turns into a fresh stats object
2682
+ // and MERGE it onto the agent's result record — never replace: the git-diff
2683
+ // branches may have already set exitCode/messages/stderr/gitBranch/gitDiff,
2684
+ // and the aborted/failed branches previously OVERWROTE usage with the empty
2685
+ // fallback. Runs on every terminal path right before the finalize; must never
2686
+ // throw (best-effort, same discipline as markTerminalBestEffort).
2687
+ //
2688
+ // Issue #648 (Q4/C): the fold is the SAME four-source fold the footer receives
2689
+ // — assistant messages, `toolResult` usage, `usage` entries, compaction/branch-
2690
+ // summary usage — and the record's cost/tokens are DERIVED from those groups, so
2691
+ // the run record and the appended footer entries agree by construction rather
2692
+ // than by two copies of the arithmetic. `turns` and `contextTokens` stay MESSAGE
2693
+ // semantics and stay assistant-only: a usage entry is not a turn, a toolResult's
2694
+ // tool-side spend is not a turn either, and context size is the LAST turn's
2695
+ // total. Money is per-source; work volume is per-turn.
2644
2696
  const recordSessionUsage = (): void => {
2645
2697
  try {
2698
+ const messages = session.messages ?? [];
2699
+ const groups = usageGroupsFromSession(messages, childEntries(), run.model);
2700
+ const totals = sumUsageGroups(groups);
2646
2701
  const usage: UsageStats = { ...EMPTY_USAGE };
2647
- for (const msg of session.messages ?? []) {
2648
- if (msg.role === 'assistant') {
2649
- accumulateUsage(usage, msg.usage as Parameters<typeof accumulateUsage>[1]);
2650
- }
2702
+ for (const msg of messages) {
2703
+ if (msg.role !== 'assistant' || !msg.usage) continue;
2704
+ // Issue #179 (D3): a turn is an assistant message that CARRIES usage —
2705
+ // the same rule `accumulateUsage` applies, so "did nothing" stays 0.
2706
+ usage.turns++;
2707
+ const totalTokens = (msg.usage as { totalTokens?: number } | undefined)?.totalTokens;
2708
+ if (totalTokens) usage.contextTokens = totalTokens;
2651
2709
  }
2710
+ usage.input = totals.input;
2711
+ usage.output = totals.output;
2712
+ usage.cacheRead = totals.cacheRead;
2713
+ usage.cacheWrite = totals.cacheWrite;
2714
+ usage.cost = totals.cost;
2652
2715
  agent.result = {
2653
2716
  // Issue #122: seed the FULL required SubagentResult shape (messages /
2654
2717
  // exitCode / stderr) BEFORE the existing record is spread — the seed
@@ -3064,6 +3127,7 @@ export async function spawnBackgroundSession(
3064
3127
  stopReason: 'aborted',
3065
3128
  errorCategory: 'timeout',
3066
3129
  prune: false,
3130
+ snapshot: true,
3067
3131
  });
3068
3132
  } catch (err) {
3069
3133
  log.warn(`spawnBackgroundSession: deadline record write failed for ${id}`, {