← Back to Pull requests

fix(cli): take Claude round tokens from the round's own usage #2583

Merged
junmo-kim merged 5 files (812 lines) on Nov 28, 2026 11:17 UTC
View on GitHub
junmo-kim junmo-kim commented on Nov 24, 2026 03:42 UTC
Author

Problem

A Claude round footer took its token counts from modelUsage, which Claude Code reports as cumulative per-model counters that survive --resume. The CLI diffed those counters against the previous result to get per-round values. The diff has to cope with results that omit modelUsage, return an empty map, drop a counter, or list a model whose counters never include output tokens, and some of these still produced a wrong footer. For example, a model whose counters report input but no output tokens made the footer show 0 output tokens although usage.output_tokens was positive.

Separately, after /clear, a command result such as /help can arrive before its input echo and is held until the echo. When a background round of the same session finished in between, two things went wrong once the held result was forwarded:

  • Its older cumulative cost moved the usage baseline back, so the next reply counted the background round's cost and API time a second time (0.5 became 1.5 in the test).

  • Its round summary attached to the background reply shown before it and replaced that reply's footer.
  • Solution

  • Tokens: the round summary no longer carries modelUsage. Token counts come from the result's own usage, which is already per round, so the converter keeps no per-model token baselines. Web and Android already render a summary without per-model token counters as the message's model plus the usage tokens, so no client change is needed. usage covers the main model, so a round that ran a subagent on another model shows only the main model's tokens; its cost still includes the subagent's spend.

  • Cost and API time are unchanged: per-round differences of the cumulative total_cost_usd and duration_api_ms against a baseline tied to the native session id, omitted when there is no baseline or the value went backwards.

  • A held command result is counted for usage when it arrives, in order with the other results. When its echo arrives it ends the turn and is forwarded marked as held: the terminal still shows its output, while the log converter neither counts it again nor writes a summary for it, so it cannot move the baseline back or replace another reply's footer. Without an accounting callback the result is forwarded unmarked and counted as before.
  • Tests

    bun run typecheck && (cd shared && bun test) && (cd cli && bunx vitest run src/claude) && bun run test:parity && (cd web && bunx vitest run src/chat src/components/AssistantChat/messages)

  • sdkToLogConverter.test.ts: a round whose per-model counters lack output tokens now reports the result's usage and no modelUsage. This fails before the change. Tests that only covered the removed per-model diffing are deleted; the cost and API time cases are kept.

  • claudeRemote.test.ts: a /help result with its own cost, held until its echo while a background round completes. Before the change, the next reply's cost is 1.5 instead of 0.5 and the held result emits a summary. After the change, the background round reports only its share after the held result (0.75), the reply reports 0.5, the held result's text reaches the terminal, and it writes no transcript entry.

  • Parity goldens are unchanged.
  • Diff: 812 lines (+145 / -667) across 5 files Reviewer: github-actions[bot] Review duration: 6215m
    All Vouch review confidence checks passed
    Residual risk 0.20 = Change Risk (0.77) × (1 − Review Confidence (0.73)). Review depth and reviewer attention state are adequate.
    Model 1 · Change Risk (XGBoost)
    Score: 0.77 · 812 lines diff across 5 files
    0.77
    Model 2 · Review Depth (DistilBERT)
    Depth Score: 0.56 · 5 substantive comment(s)
    0.56
    Model 3 · Review Timing & Attention
    Session adequacy: 100% · Reviewer familiarity: 35%
    73%
    Bedrock Claude 3 · Risk Narration
    (disconnected)
    Groq
    Groq Risk Narration
    AWS Bedrock is currently disconnected. Generate high-confidence PR triage narration on-demand using Groq.
    Model 1 · Change Risk Attribution
    SHAP Weights
    Diff Size diff_size
    0.400
    Sensitive Paths sensitive_paths
    0.077
    Ai Authored ai_authored
    0.050
    Real PR Conversation Timeline
    48 items
    github-actions[bot] github-actions[bot] commented on code on Nov 24, 2026 03:48 UTC
    Code Review
    cli/src/claude/utils/sdkToLogConverter.ts:1
    @@ -170,11 +151,13 @@ export class SDKToLogConverter {
         // must not overwrite it.
         private contextUsageKeys = new Set<string>()
         private accountIdentity: string | null
    -    // Cumulative cost/modelUsage/duration_api_ms survive --resume, so emit only
    +    // Cumulative cost and duration_api_ms survive --resume, so emit only
         // deltas against a known baseline and omit fields when none is available.
         private previousCumulative: CumulativeUsageBaseline | null = null
         // Native session id that owns previousCumulative; null until learned.
         private usageSessionId: string | null = null
    +    // Models of the assistant messages since the previous result of that session.
    +    private answeredModels = new Set<string>()

    [Minor] A session rotation can carry models into the new session

    If an old-session background subagent emits an assistant message just before /clear binds a new native session, its model is already in answeredModels. Changing the session ID and consuming the suppressed /clear result leave the set populated. The first reply in the new session can then list the old subagent alongside its own model.

    Suggested fix

    Clear pending model names when the native session ID changes. Add a regression case that records an old-session assistant before the rotation and completes a reply after it.

    github-actions[bot] github-actions[bot] commented on code on Nov 24, 2026 03:48 UTC
    Code Review
    cli/src/claude/utils/sdkToLogConverter.ts:1
    @@ -710,19 +594,23 @@ export class SDKToLogConverter {
                             }
                         }
                     }
    -                // These fields are cumulative across resumes; emit only a
    +                // Cost and API time are cumulative across resumes; emit only a
                     // trustworthy per-round delta, never a lifetime total.
                     const perRound = resultMsg.hapi_skip_usage === true
    -                    ? { totalCostUsd: undefined, durationApiMs: undefined, modelUsage: undefined }
    +                    ? { totalCostUsd: undefined, durationApiMs: undefined }
                         : this.consumeCumulativeDeltas(resultMsg)
    +                // A result of the tracked session closes its round's model list.
    +                const ownRound = this.isUsageSession(resultMsg.session_id)
    +                const modelUsage = roundModels(ownRound ? this.answeredModels : new Set(), resultMsg.modelUsage)
    +                if (ownRound) this.answeredModels = new Set()

    [Minor] A held command result can consume a background round’s models

    After /clear, a command result can be held until its replay echo. If a same-session background round emits an assistant message between the held result and that echo, forwarding the held result consumes the background round’s model set. hapi_skip_usage protects the cost baseline, but this code still assigns and clears the models. The command gets the background model, and the background result can lose it.

    Suggested fix

    Capture the command’s model list when its result first arrives, or have replayed command results leave the live model set untouched. Cover an echo that arrives after the background assistant message and before its result.

    github-actions[bot] github-actions[bot] commented on code on Nov 24, 2026 03:48 UTC
    Code Review
    cli/src/claude/utils/sdkToLogConverter.ts:1
    @@ -710,19 +594,23 @@ export class SDKToLogConverter {
                             }
                         }
                     }
    -                // These fields are cumulative across resumes; emit only a
    +                // Cost and API time are cumulative across resumes; emit only a
                     // trustworthy per-round delta, never a lifetime total.
                     const perRound = resultMsg.hapi_skip_usage === true
    -                    ? { totalCostUsd: undefined, durationApiMs: undefined, modelUsage: undefined }
    +                    ? { totalCostUsd: undefined, durationApiMs: undefined }
                         : this.consumeCumulativeDeltas(resultMsg)
    +                // A result of the tracked session closes its round's model list.
    +                const ownRound = this.isUsageSession(resultMsg.session_id)
    +                const modelUsage = roundModels(ownRound ? this.answeredModels : new Set(), resultMsg.modelUsage)
    +                if (ownRound) this.answeredModels = new Set()
                     logMessage = {
                         ...baseFields,
                         type: 'system',
                         subtype: 'turn_duration',
                         durationMs: resultMsg.duration_ms,
                         resultSummary: {
                             usage: resultMsg.usage,
    -                        modelUsage: perRound.modelUsage,
    +                        modelUsage,

    [Minor] Android drops subagent models from the new summaries

    The CLI now emits every model entry with empty counters. Android’s RoundSummary.kt:89 discards the whole map when every entry lacks counters. In a reply whose Haiku messages are nested under an Agent tool call, Android falls back to the main response model and drops Haiku from the round details. The old summary could display both models when their counters were available.

    Suggested fix

    Keep empty model entries in Android’s round-summary decoder and retain its existing token fallback. Add a generated conformance case with a main model and a subagent model whose entries both lack counters.

    github-actions[bot] github-actions[bot] commented on code on Nov 24, 2026 03:48 UTC
    Code Review
    cli/src/claude/utils/sdkToLogConverter.ts:1
    @@ -124,6 +82,29 @@ function perRoundDelta(current: number, previous: number | undefined): number |
         return delta >= 0 ? delta : undefined
     }
     
    +/**
    + * The round's models without counters. Every `modelUsage` counter is
    + * cumulative, while the round's tokens come from its own `usage`, which
    + * covers the main model only. The web falls back to `usage` when no model
    + * carries token counters and still lists the models.
    + *
    + * The models are those whose assistant messages arrived in the round, main
    + * and subagent alike, so a round without one lists none. `modelUsage` keys
    + * also name models of earlier rounds and are not listed. An assistant model
    + * reported bare takes the result's "[1m]" id when present.
    + */
    +function roundModels(
    +    answeredModels: ReadonlySet<string>,
    +    modelUsage: SDKResultMessage['modelUsage']
    +): SDKResultMessage['modelUsage'] {
    +    const resultModels = Object.keys(modelUsage ?? {})
    +    if (answeredModels.size === 0) return modelUsage ? {} : undefined
    +    return Object.fromEntries(Array.from(answeredModels, (model) => [
    +        resultModels.includes(`${model}[1m]`) && !resultModels.includes(model) ? `${model}[1m]` : model,

    [Minor] A prior plain-model entry masks the current 1M variant

    After switching from plain Sonnet to Sonnet [1m] in a resumed session, the cumulative result map can contain both keys while the assistant message still reports bare Sonnet. This condition chooses the bare key whenever both exist, so the footer labels the current 1M reply as plain Sonnet. The converter already receives the suffixed model ID from system/init for this preset.

    Suggested fix

    Use the active init model to resolve the matching main assistant’s variant. Add a case where the current init model is suffixed and the result map contains both keys.

    github-actions[bot] github-actions[bot] commented on Nov 24, 2026 03:48 UTC
    Reviewer

    ✅ All stages passed (4 Minor)

    Review mode: initial

    Requirement — Pass

    Claude round footers should show the current round’s main-model token counts, the models that answered, and the round’s cost including subagent spend. The existing footer can show zero output despite positive round usage when the cumulative model entry contains input counters but omits output counters.

    Evidence

  • The PR description identifies missing and empty cumulative model counters as sources of incorrect totals.

  • Base cli/src/claude/utils/sdkToLogConverter.ts:375 can retain an input delta when output was never reported. Base web/src/components/AssistantChat/messages/MessageMetadata.tsx:42 then uses the model counters and treats missing output as zero.
  • Approach — Pass

    Using the SDK result’s per-round usage removes the need to reconstruct token totals from cumulative counters. Assistant messages provide model identities, while cost and API time still use cumulative deltas.

    Evidence

  • cli/src/claude/utils/sdkToLogConverter.ts:302 limits cumulative accounting to cost and API time, and line 612 forwards the SDK result’s usage.

  • web/src/chat/normalizeAgent.ts:80 keeps model names with empty counters. The existing footer uses round usage when no model has token counters.
  • Code — Reviewed

    Reviewed the full merge-base diff and relevant client consumers. The findings affect which models appear in the round footer.

  • [Minor] A session rotation can carry models into the new session — cli/src/claude/utils/sdkToLogConverter.ts:160

  • [Minor] A held command result can consume a background round’s models — cli/src/claude/utils/sdkToLogConverter.ts:605

  • [Minor] Android drops subagent models from the new summaries — cli/src/claude/utils/sdkToLogConverter.ts:613

  • [Minor] A prior plain-model entry masks the current 1M variant — cli/src/claude/utils/sdkToLogConverter.ts:103
  • Testing

    Not run (automation; PR code execution is prohibited).

  • GitHub checks for e2336356a18bff9a580f14659447cb332e7474c7 showed drift-gate, wrapper-parity, unit-cli, unit-web, integration, core, and windows-codex-mcp passing. Browser and pr-review were in progress.

  • The new tests cover per-round token fallback and delayed-result cost accounting. The review used read-only inspection without executing PR code or tests.
  • <!-- hapi-pr-review:v2:5363be15ecf684f4260e4439653ac7b0d2ea5b43d73d1023eb288c41218f3ae0 -->
    HAPI Bot

    github-actions[bot] github-actions[bot] commented on code on Nov 24, 2026 06:05 UTC
    Code Review
    android/core/protocol/src/main/kotlin/app/hapi/protocol/chat/RoundSummary.kt:1
    @@ -86,12 +87,19 @@ internal fun normalizeRoundSummary(value: JsonElement?): RoundSummary? {
                 )
             )
         }
    +    // A summary that names its round's models in round_models lists them
    +    // without counters, so the footer takes the round's tokens from usage.
    +    // Other summaries keep a model map only when some model carries tokens.
    +    val roundModels = (obj["round_models"] as? JsonArray)
    +        ?.mapNotNull { asString(it)?.takeIf { model -> model.isNotEmpty() } }
         val hasModelTokens = parsedModelUsage.any { (_, usage) ->
             usage.inputTokens != null || usage.outputTokens != null ||
                 usage.cacheReadInputTokens != null || usage.cacheCreationInputTokens != null
         }
         val modelUsage = LinkedHashMap<String, RoundModelUsage>()
    -    if (hasModelTokens) {
    +    if (roundModels != null) {
    +        roundModels.forEach { model -> modelUsage[model] = RoundModelUsage() }

    [Minor] Android drops round model names when it decodes the timeline event

    A Claude round with Sonnet and Haiku initially decodes both names from round_models into empty modelUsage entries. NormalizeAgent.kt:663 serializes those entries into the synthesized event without round_models. When the reducer reads TurnSummary.summary, the second decode applies the legacy rule and discards the empty entries. The footer falls back to the message’s model and omits Haiku.

    Suggested fix

    Preserve the explicit model list through event serialization and decoding while keeping the legacy wire fallback. Add a regression test that passes a two-model wire summary through the timeline reducer and verifies both names in the footer.

    github-actions[bot] github-actions[bot] commented on Nov 24, 2026 06:05 UTC
    Reviewer

    ✅ All stages passed (1 Minor)

    Review mode: follow-up after new commits

    Requirement — Pass

    Claude round footers should show the current round’s main-model tokens, identify the models that responded, and include subagent spend in the round cost. The existing footer can show zero output tokens when a cumulative model entry has input counters but lacks an output counter.

    Evidence

  • The PR description documents incorrect totals when Claude returns empty or partial cumulative model counters.

  • In the base code, cli/src/claude/utils/sdkToLogConverter.ts:375 can retain input counters without output counters. web/src/components/AssistantChat/messages/MessageMetadata.tsx:42 then prefers those counters and treats missing output as zero.
  • Approach — Pass

    Forwarding the SDK’s round usage removes the need to reconstruct token totals from cumulative counters. Assistant messages supply the model names, and cumulative deltas still supply round cost and API time.

    Evidence

  • cli/src/claude/utils/sdkToLogConverter.ts:498 collects models from assistant messages for the active session. Lines 617 and 637 handle cumulative accounting and round usage.

  • web/src/chat/normalizeAgent.ts:81 and android/core/protocol/src/main/kotlin/app/hapi/protocol/chat/RoundSummary.kt:93 recognize the explicit round model list while retaining the existing decoding rules for stored summaries.
  • Code — Reviewed

    Reviewed the full merge-base diff. Android still loses the new model list between wire decoding and footer rendering.

  • [Minor] Android drops round model names when it decodes the timeline event — android/core/protocol/src/main/kotlin/app/hapi/protocol/chat/RoundSummary.kt:101
  • Testing

    Not run (automation; PR code execution is prohibited).

  • No PR code or tests were run during this review. The merge-base diff passed git diff --check.

  • On head 0a27b7e6c24d4e7b514e48edd84aa9225f04227a, GitHub showed Android build, API 29 transcript layout, fixture drift, wrapper parity, CLI and web unit tests, core, integration, and windows-codex-mcp passing. Browser, API 36 transcript layout, and the current PR review were in progress.

  • The new Android label test calls the wire decoder directly and misses the synthesized event round trip used by the timeline.
  • <!-- hapi-pr-review:v2:cc18ac559f261f996c239408b501e2f9085f10cb6fd1a243e3a519666cc8e3b2 -->
    HAPI Bot

    github-actions[bot] github-actions[bot] commented on Nov 24, 2026 06:30 UTC
    Reviewer

    ✅ All stages passed (1 Minor)

    Review mode: follow-up after new commits

    Requirement — Pass

    Claude round footers should show the current round’s main-model token counts, identify the models that answered, and include subagent spend in the round cost.

    Evidence

  • The PR description documents incorrect totals when cumulative model counters are empty or incomplete.

  • The base converter can retain input counters without output counters at cli/src/claude/utils/sdkToLogConverter.ts:375. The web footer then treats the missing output count as zero at web/src/components/AssistantChat/messages/MessageMetadata.tsx:42.
  • Approach — Pass

    Using the SDK’s round usage removes the need to reconstruct token counts from cumulative counters. Assistant messages supply model names, and cumulative deltas still supply cost and API time.

    Evidence

  • cli/src/claude/utils/sdkToLogConverter.ts:617 handles cumulative accounting, and line 637 forwards round usage directly.

  • web/src/chat/normalizeAgent.ts:81 and android/core/protocol/src/main/kotlin/app/hapi/protocol/chat/RoundSummary.kt:100 decode the explicit model list and retain the existing fallback for stored summaries.
  • Code — Reviewed

    Reviewed the full merge-base diff. Android now preserves model names through event serialization and timeline reduction. One CLI issue remains when a main model and a subagent use different variants of the same model.

  • [Minor] A subagent’s model can collapse into the main model’s [1m] variant — cli/src/claude/utils/sdkToLogConverter.ts:500
  • Testing

    Not run (automation; PR code execution is prohibited).

  • The merge-base diff passed git diff --check. No PR code or tests were run locally.

  • On head cce4230e59789ff12a854217681a82806e2f7e21, fixture drift, CLI and web unit tests, wrapper parity, core, integration, Windows Codex MCP, and Android API 29 transcript layout passed. Browser and Android API 36 transcript layout were still running.

  • Android protocol tests passed in CI. The broader Android build failed in HubNavigationRestorationTest when Robolectric tried to fetch a Maven artifact.
  • <!-- hapi-pr-review:v2:953f32cc749ee732ae868507c7a2c999ef17721363cef25426e04676951b8e81 -->
    HAPI Bot

    github-actions[bot] github-actions[bot] commented on code on Nov 24, 2026 06:30 UTC
    Code Review
    cli/src/claude/utils/sdkToLogConverter.ts:1
    @@ -601,6 +494,11 @@ export class SDKToLogConverter {
                             usage.context_window = contextWindow
                         }
                     }
    +                // Synthetic messages (API errors, interruptions) name no real model.
    +                if (typeof message?.model === 'string' && message.model !== '<synthetic>'
    +                    && this.isUsageSession(assistantMsg.session_id)) {
    +                    this.answeredModels.add(message.model)

    [Minor] A subagent’s model can collapse into the main model’s [1m] variant

    When the main model uses claude-sonnet-5[1m] and a subagent uses plain claude-sonnet-5, both assistant messages report the same bare ID. The set deduplicates them before variant resolution, and line 104 resolves the remaining entry to the main model’s [1m] ID. The footer omits the plain model even when the SDK result contains both variants.

    Suggested fix

    Keep the main and subagent observations distinct using parent_tool_use_id. Apply the active init variant only to the main model, then deduplicate the resolved names. Add a regression test with both variants in one round.

    github-actions[bot] github-actions[bot] commented on code on Nov 24, 2026 06:45 UTC
    Code Review
    cli/src/claude/utils/sdkToLogConverter.ts:1
    @@ -124,6 +82,28 @@ function perRoundDelta(current: number, previous: number | undefined): number |
         return delta >= 0 ? delta : undefined
     }
     
    +/**
    + * The models that answered in the round, for the summary's `round_models`.
    + * The summary carries no `modelUsage`: every counter in it is cumulative,
    + * its keys also name models of earlier rounds, and the round's tokens come
    + * from its own `usage`, which covers the main model only.
    + *
    + * The models are those whose assistant messages arrived in the round, main
    + * and subagent alike, so a round without one lists none. Assistant messages
    + * report the model bare. A main-thread model already carries the variant of
    + * the session's active init model; any other model takes the result's "[1m]"
    + * id when only that variant is present.
    + */
    +function roundModels(
    +    answeredModels: ReadonlySet<string>,
    +    modelUsage: SDKResultMessage['modelUsage']
    +): string[] {
    +    const resultModels = Object.keys(modelUsage ?? {})
    +    const variant = (model: string): string =>
    +        resultModels.includes(`${model}[1m]`) && !resultModels.includes(model) ? `${model}[1m]` : model

    [Minor] A partial model snapshot can hide the plain subagent model

    When a claude-sonnet-5[1m] main model and a plain claude-sonnet-5 subagent both answer, the converter initially records both IDs. If modelUsage contains only the [1m] key, the fallback promotes the subagent’s bare ID to that same key, and deduplication leaves the footer showing only the main model. The regression test at line 679 of sdkToLogConverter.test.ts supplies both keys, so it misses this case.

    Suggested fix

    Keep the bare subagent ID when the suffixed key is already attributed to the main thread. Extend the mixed-variant test to cover a result that omits the plain key.

    github-actions[bot] github-actions[bot] commented on Nov 24, 2026 06:45 UTC
    Reviewer

    ✅ All stages passed (1 Minor)

    Review mode: follow-up after new commits

    Requirement — Pass

    Claude round footers should show the current round’s main-model tokens and participating models, with subagent spend included in the round cost. The current footer can undercount tokens when the SDK’s cumulative model counters are incomplete.

    Evidence

  • The PR description documents empty and incomplete modelUsage snapshots.

  • The base converter can retain input counts without output counts at cli/src/claude/utils/sdkToLogConverter.ts:375. The web footer treats missing output counts as zero at web/src/components/AssistantChat/messages/MessageMetadata.tsx:42.
  • Approach — Pass

    Using the SDK’s per-round usage removes the token dependency on cumulative snapshots. Assistant messages supply the model list, while cumulative deltas supply cost and API time.

    Evidence

  • cli/src/claude/utils/sdkToLogConverter.ts:619 handles cumulative accounting, and line 640 forwards the round’s usage.

  • web/src/chat/normalizeAgent.ts:81 and android/core/protocol/src/main/kotlin/app/hapi/protocol/chat/RoundSummary.kt:100 decode the explicit model list and preserve the fallback for stored summaries.
  • Code — Reviewed

    Reviewed the full merge-base diff. Android preserves the model list through timeline reduction. The CLI still drops a plain subagent model when the cumulative snapshot contains only the main model’s [1m] key.

  • [Minor] A partial model snapshot can hide the plain subagent model — cli/src/claude/utils/sdkToLogConverter.ts:103
  • Testing

    Not run (automation; PR code execution is prohibited).

  • The merge-base diff passed git diff --check. No PR code or tests were run locally.

  • On head 9248205649ccceab6d5f61145d96b1a7fe6ef6bb, fixture drift, CLI and web unit tests, wrapper parity, core, integration, and Windows Codex MCP passed. Browser tests, the Android build, and Android transcript layout on APIs 29 and 36 were still running.
  • <!-- hapi-pr-review:v2:2c4479a6e98462c7503f454d42f0aa095701101b77b08912a997e7ec81230ef4 -->
    HAPI Bot

    github-actions[bot] github-actions[bot] commented on code on Nov 24, 2026 07:37 UTC
    Code Review
    cli/src/claude/claudeRemote.ts:1
    @@ -856,7 +856,9 @@ export async function claudeRemote(opts: {
                             resolveSteer(true);
                         }
                         if (clearFollowUp?.uuid !== uuid || !clearFollowUp.earlyResult) continue;
    -                    message = clearFollowUp.earlyResult;
    +                    // A newer result of the same session may have arrived while this one
    +                    // was held, so its older counters must not become the usage baseline.
    +                    message = { ...clearFollowUp.earlyResult, hapi_skip_usage: true };

    [Minor] Held command results reach accounting too late

    If a native clear alias rotates the session but its result still carries the old ID, the new session has no baseline. A subsequent /help result can supply the first valid snapshot and be held for its input echo. If a background round finishes before that echo, its footer omits cost and the API-time-based token rate because accounting has yet to see the command snapshot. The integration test at cli/src/claude/claudeRemote.test.ts:811 seeds the baseline with the clear result and misses this case.

    Suggested fix

    Account for the first matching command result when it is captured, then skip accounting when it is replayed for display. Extend the integration test to cover a rotated session whose clear result carries the old ID.

    github-actions[bot] github-actions[bot] commented on code on Nov 24, 2026 07:37 UTC
    Code Review
    cli/src/claude/utils/sdkToLogConverter.ts:1
    @@ -710,19 +594,34 @@ export class SDKToLogConverter {
                             }
                         }
                     }
    -                // These fields are cumulative across resumes; emit only a
    +                // Cost and API time are cumulative across resumes; emit only a
                     // trustworthy per-round delta, never a lifetime total.
    -                const perRound = resultMsg.hapi_skip_usage === true
    -                    ? { totalCostUsd: undefined, durationApiMs: undefined, modelUsage: undefined }
    -                    : this.consumeCumulativeDeltas(resultMsg)
    +                // A result marked to skip usage reports no delta; it only seeds a
    +                // baseline of the tracked session when none exists yet, so it can
    +                // never move an existing baseline back.
    +                let perRound: { totalCostUsd: number | undefined; durationApiMs: number | undefined }
    +                if (resultMsg.hapi_skip_usage !== true) {
    +                    perRound = this.consumeCumulativeDeltas(resultMsg)
    +                } else {
    +                    if (this.previousCumulative === null && this.isUsageSession(resultMsg.session_id)) {
    +                        this.consumeCumulativeDeltas(resultMsg)
    +                    }
    +                    perRound = { totalCostUsd: undefined, durationApiMs: undefined }
    +                }
    +                // A result of the tracked session closes its round's model list. A
    +                // result marked to skip usage (a held command result) lists no models
    +                // and leaves the list to the round still in progress.
    +                const ownRound = resultMsg.hapi_skip_usage !== true && this.isUsageSession(resultMsg.session_id)

    [Minor] A command result can consume a background round’s model list

    When the SDK echoes /help before returning its result, the result is forwarded without hapi_skip_usage. If a same-session background assistant message arrives before that result, the converter puts its model on the command summary and clears it from the pending list. The background round’s eventual footer can then omit the subagent model that participated.

    Suggested fix

    Let local command receipts that close no assistant round update accounting without consuming pending model IDs. Test the echo-first ordering alongside the existing held-result case.

    github-actions[bot] github-actions[bot] commented on Nov 24, 2026 07:37 UTC
    Reviewer

    ✅ All stages passed (2 Minor)

    Review mode: follow-up after new commits

    Requirement — Pass

    Claude round footers should show the current round’s main-model tokens and participating models, with subagent spend included in the cost. The current footer can undercount output tokens when a cumulative model snapshot omits that counter.

    Evidence

  • The PR description distinguishes per-round usage from cumulative cost and API time.

  • The base converter can retain input counts when output counts are absent (cli/src/claude/utils/sdkToLogConverter.ts:375). The web footer then treats the missing output count as zero (web/src/components/AssistantChat/messages/MessageMetadata.tsx:42).
  • Approach — Pass

    Use the SDK result’s round usage for tokens, assistant messages for model IDs, and cumulative deltas for cost and API time. Web and Android can render the explicit model list through their existing footer logic while retaining the fallback for stored summaries.

    Evidence

  • cli/src/claude/utils/sdkToLogConverter.ts:481 collects assistant model IDs, and line 623 forwards per-round usage.

  • web/src/chat/normalizeAgent.ts:81 and android/core/protocol/src/main/kotlin/app/hapi/protocol/chat/RoundSummary.kt:100 decode the explicit model list.
  • Code — Reviewed

    Reviewed the full fixed-head merge-base diff. The prior mixed-variant finding is resolved. Two command-result ordering cases still affect round footers.

  • [Minor] Held command results reach accounting too late — cli/src/claude/claudeRemote.ts:861

  • [Minor] A command result can consume a background round’s model list — cli/src/claude/utils/sdkToLogConverter.ts:614
  • Testing

    Not run (automation; PR code execution is prohibited).

  • The merge-base diff passed git diff --check. No PR code or tests were run locally.

  • On head 836d3bd4a150af9a6d6673ea50536cfd3a228b5e, fixture drift, CLI and web unit tests, wrapper parity, core, integration, and Windows Codex MCP passed. Browser tests, the Android build, and Android transcript layout tests on APIs 29 and 36 were still running.
  • <!-- hapi-pr-review:v2:e1e0c96f4345406a3286e724201d704d2e40cc858e5887cf3d6126156aea89a0 -->
    HAPI Bot

    github-actions[bot] github-actions[bot] commented on code on Nov 24, 2026 07:59 UTC
    Code Review
    cli/src/claude/utils/sdkToLogConverter.ts:1
    @@ -710,19 +594,25 @@ export class SDKToLogConverter {
                             }
                         }
                     }
    -                // These fields are cumulative across resumes; emit only a
    +                // Cost and API time are cumulative across resumes; emit only a
                     // trustworthy per-round delta, never a lifetime total.
                     const perRound = resultMsg.hapi_skip_usage === true
    -                    ? { totalCostUsd: undefined, durationApiMs: undefined, modelUsage: undefined }
    +                    ? { totalCostUsd: undefined, durationApiMs: undefined }
                         : this.consumeCumulativeDeltas(resultMsg)
    +                // A result of the tracked session closes its round's model list. A
    +                // local command result answers no assistant round, so it lists no
    +                // models and leaves the list to the round still in progress.
    +                const ownRound = typeof resultMsg.local_command !== 'string' && this.isUsageSession(resultMsg.session_id)

    [Minor] A /compact receipt can consume a background round’s model list

    The wrapper recognizes a manual /compact result by its input UUID even when local_command is absent, and forwards it with hapi_compact_turn (cli/src/claude/claudeRemote.ts:914). If a same-session background subagent emits an assistant message before that receipt, the converter attaches its model to the compaction summary and clears the pending list. The background round’s eventual footer can then omit the subagent model.

    Suggested fix

    Exclude results marked hapi_compact_turn from model-list consumption while still advancing cost and API-time accounting. Add a regression case with a background assistant message, a UUID-only /compact receipt, and then the background result.

    github-actions[bot] github-actions[bot] commented on Nov 24, 2026 07:59 UTC
    Reviewer

    ✅ All stages passed (1 Minor)

    Review mode: follow-up after new commits

    Requirement — Pass

    Claude round footers should show the current round’s main-model token counts, the models that participated, and the round’s cost including subagent spend. The existing footer can show zero output tokens when a cumulative model entry omits that counter.

    Evidence

  • The PR description identifies SDK result usage as per-round and cost and API time as cumulative.

  • The base converter can retain input counts when output counts are absent (cli/src/claude/utils/sdkToLogConverter.ts:375). The web footer then sums the missing output count as zero (web/src/components/AssistantChat/messages/MessageMetadata.tsx:42).
  • Approach — Pass

    Taking tokens directly from result usage removes the unreliable per-model deltas. Collecting model IDs from assistant messages and accounting for held command results on arrival lets the CLI provide the footer data while Web and Android preserve the rendering of stored summaries.

    Evidence

  • The converter collects assistant model IDs and forwards round usage in cli/src/claude/utils/sdkToLogConverter.ts:481 and cli/src/claude/utils/sdkToLogConverter.ts:614.

  • The remote wrapper accounts for held results on arrival and marks them when forwarded for display in cli/src/claude/claudeRemote.ts:863 and cli/src/claude/claudeRemote.ts:877.

  • Web and Android decode the explicit model list in web/src/chat/normalizeAgent.ts:81 and android/core/protocol/src/main/kotlin/app/hapi/protocol/chat/RoundSummary.kt:100.
  • Code — Reviewed

    Reviewed the full fixed-head merge-base diff. The two prior findings are addressed. A manual compaction receipt can still take model IDs from a background round.

  • [Minor] A /compact receipt can consume a background round’s model list — cli/src/claude/utils/sdkToLogConverter.ts:605
  • Testing

    Not run (automation; PR code execution is prohibited).

  • git diff --check passed for the fixed merge-base diff. No PR code or tests were run locally.

  • On head 6e979f21ce20b6b2b05bc3082e62a8e1f2471f9b, fixture drift, CLI unit tests, wrapper parity, core, integration, and Windows Codex MCP passed. Web unit and browser tests, the Android build, and Android transcript layout tests on APIs 29 and 36 were still running when checked.
  • <!-- hapi-pr-review:v2:32fcc7093191760fb25b7da002e153882c4faf7abdda411351eec3812a67af07 -->
    HAPI Bot

    github-actions[bot] github-actions[bot] commented on code on Nov 24, 2026 08:26 UTC
    Code Review
    cli/src/claude/utils/sdkToLogConverter.ts:1
    @@ -710,19 +606,22 @@ export class SDKToLogConverter {
                             }
                         }
                     }
    -                // These fields are cumulative across resumes; emit only a
    +                // Cost and API time are cumulative across resumes; emit only a
                     // trustworthy per-round delta, never a lifetime total.
                     const perRound = resultMsg.hapi_skip_usage === true
    -                    ? { totalCostUsd: undefined, durationApiMs: undefined, modelUsage: undefined }
    +                    ? { totalCostUsd: undefined, durationApiMs: undefined }
                         : this.consumeCumulativeDeltas(resultMsg)
    +                const endsRound = this.endsAssistantRound(resultMsg)
    +                const models = endsRound ? [...this.answeredModels] : []
    +                if (endsRound) this.answeredModels = new Set()
                     logMessage = {
                         ...baseFields,
                         type: 'system',
                         subtype: 'turn_duration',
                         durationMs: resultMsg.duration_ms,
                         resultSummary: {
                             usage: resultMsg.usage,
    -                        modelUsage: perRound.modelUsage,
    +                        ...(models.length > 0 ? { round_models: models } : {}),

    [Minor] A late command receipt can overwrite the background round footer

    After /clear, a held /help result can be forwarded on its input echo after a same-session background reply has already published its summary. The wrapper consumes the echo at cli/src/claude/claudeRemote.ts:863, so it creates no transcript boundary. The converter still emits the receipt as a turn summary with no round_models or cost. The Web and Android reducers assign it to the same assistant group, replacing the background reply’s model list, usage, and cost. See web/src/chat/reducerTimeline.ts:607 and android/core/protocol/src/main/kotlin/app/hapi/protocol/chat/ReducerTimeline.kt:610.

    Suggested fix

    Keep command accounting on arrival and route receipt display through an event that leaves assistant round summaries intact. Add a reducer-level regression with a background reply and result followed by the held command’s echo.

    github-actions[bot] github-actions[bot] commented on Nov 24, 2026 08:26 UTC
    Reviewer

    ✅ All stages passed (1 Minor)

    Review mode: follow-up after new commits

    Requirement — Pass

    Claude round footers should show the round’s main-model token counts and participating models, with subagent spend included in the round cost. The current footer can show zero output tokens even when the SDK reports positive round usage.

    Evidence

  • The PR description identifies empty and incomplete cumulative model counters as sources of incorrect totals.

  • The base converter can retain input counters when output counters are absent at cli/src/claude/utils/sdkToLogConverter.ts:375. The web footer then treats missing output as zero at web/src/components/AssistantChat/messages/MessageMetadata.tsx:42.
  • Approach — Pass

    Using the SDK result’s round usage removes the dependency on cumulative token snapshots. Assistant messages supply model names, while cumulative deltas continue to supply cost and API time.

    Evidence

  • The converter collects model names from the tracked session at cli/src/claude/utils/sdkToLogConverter.ts:493 and forwards round usage at line 623.

  • Web and Android decode the explicit model list while retaining the fallback for stored summaries at web/src/chat/normalizeAgent.ts:81 and android/core/protocol/src/main/kotlin/app/hapi/protocol/chat/RoundSummary.kt:100.
  • Code — Reviewed

    Reviewed the full fixed-head merge-base diff. The UUID-only /compact receipt now preserves pending model names. A late command receipt can still replace an already-rendered background round footer.

  • [Minor] A late command receipt can overwrite the background round footer — cli/src/claude/utils/sdkToLogConverter.ts:624
  • Testing

    Not run (automation; PR code execution is prohibited).

  • The fixed merge-base diff passed git diff --check. No PR code or tests were executed locally.

  • On head 1654eae6c616eb7a6cbbce388920b497a0468873, GitHub showed fixture drift, CLI and Web unit tests, wrapper parity, core, integration, and Windows Codex MCP passing. Browser tests, the Android build, and Android transcript layout checks on APIs 29 and 36 were still in progress.
  • <!-- hapi-pr-review:v2:dcb0647820400e31ce5d9a1d0a4e80f65f68da1eb76794ad8023827de43b2a78 -->
    HAPI Bot

    github-actions[bot] github-actions[bot] commented on code on Nov 24, 2026 08:49 UTC
    Code Review
    cli/src/claude/utils/sdkToLogConverter.ts:1
    @@ -288,157 +254,74 @@ export class SDKToLogConverter {
             // The usage baseline is kept: updateSessionId clears it when the native session id changes.
         }
     
    +    /**
    +     * Start accounting for a newly spawned Claude process; a fresh one
    +     * (started without a prior transcript) starts its counters at zero.
    +     */
    +    beginProcess(fresh: boolean): void {
    +        // Models of a round whose process ended before its result do not
    +        // belong to the next round.
    +        this.answeredModels = new Set()
    +        if (fresh) this.startFreshProcessBaseline()
    +    }
    +
         /**
          * Seed a zero baseline for a process started without a prior transcript.
          */
         startFreshProcessBaseline(): void {
             // A fresh process owns whatever session id it reports next.
             this.usageSessionId = null
    -        this.previousCumulative = {
    -            totalCostUsd: 0,
    -            durationApiMs: 0,
    -            modelUsage: {},
    -            modelSnapshotKnown: true,
    -            staleModels: new Set(),
    -            modelGapSeen: false,
    -            missingTokenCounters: {}
    -        }
    +        this.previousCumulative = { totalCostUsd: 0, durationApiMs: 0 }
         }
     
         /**
          * Advance the cumulative baseline for a result that produces no transcript
    -     * entry, so the next round does not absorb its cost, tokens and API time.
    +     * entry, so the next round does not absorb its cost and API time.
          */
         consumeResultForAccounting(resultMsg: SDKResultMessage): void {
             this.consumeCumulativeDeltas(resultMsg)
         }
     
    +    /** False for a message of another native session than the one usage is tracked for. */
    +    private isUsageSession(sessionId: unknown): boolean {
    +        return this.usageSessionId === null || typeof sessionId !== 'string' || sessionId === this.usageSessionId
    +    }
    +
    +    /**
    +     * Whether a result ends an assistant round of the tracked session and so
    +     * takes the round's pending models. A command, compaction or clear receipt
    +     * ends none: it lists no models and leaves them to the round in progress,
    +     * while its cost and API time still count once.
    +     */
    +    private endsAssistantRound(resultMsg: SDKResultMessage): boolean {
    +        return !isCommandReceipt(resultMsg) && this.isUsageSession(resultMsg.session_id)

    [Minor] Sidechain results consume the enclosing round’s model list

    When a subagent emits a same-session result with parent_tool_use_id before the main result, the converter puts the accumulated main and subagent models on that sidechain result and clears the set. The web client routes the summary to the subagent card, which can show the main model, while the enclosing reply loses the subagent model. The existing sidechain result path is covered at cli/src/claude/utils/sdkToLogConverter.test.ts:446 and web/src/chat/reducer.test.ts:683.

    Suggested fix

    Reserve consumption of the enclosing round’s model list for a top-level result. If the sidechain footer needs model names, derive them from messages with the matching parent_tool_use_id. Cover a sidechain result followed by the enclosing result with distinct model names.

    github-actions[bot] github-actions[bot] commented on Nov 24, 2026 08:49 UTC
    Reviewer

    ✅ All stages passed (1 Minor)

    Review mode: follow-up after new commits

    Requirement — Pass

    Claude round footers should show the round’s main-model token counts, name the models that answered, and include subagent spend in the round cost. Incomplete cumulative counters can currently make a reply with positive output usage show zero output tokens.

    Evidence

  • The base converter can retain input counters when output counters are absent at cli/src/claude/utils/sdkToLogConverter.ts:375. The web footer treats the missing output count as zero at web/src/components/AssistantChat/messages/MessageMetadata.tsx:49.
  • Approach — Pass

    Using the SDK result’s own usage supplies per-round token counts directly. Assistant messages supply model names, while cumulative deltas still supply cost and API time. Accounting for held receipts on arrival preserves the baseline order.

    Evidence

  • cli/src/claude/utils/sdkToLogConverter.ts:491 collects model names, and line 626 forwards round usage.

  • cli/src/claude/claudeRemote.ts:873 accounts for a held receipt on arrival. The converter suppresses its footer at cli/src/claude/utils/sdkToLogConverter.ts:619.

  • web/src/chat/normalizeAgent.ts:81 and android/core/protocol/src/main/kotlin/app/hapi/protocol/chat/RoundSummary.kt:100 read the explicit model list and preserve the existing handling of stored summaries.
  • Code — Reviewed

    Reviewed the full fixed-head diff. The previous late-command footer overwrite is addressed. A sidechain result can still consume the enclosing round’s model list.

  • [Minor] Sidechain results consume the enclosing round’s model list — cli/src/claude/utils/sdkToLogConverter.ts:297
  • Testing

    Not run (automation; PR code execution is prohibited).

  • The fixed merge-base diff passed git diff --check. No PR code or tests were run locally.

  • On head b5e91626c918ec4fc65a2d3ccc092ec38b0df477, GitHub showed fixture drift, CLI and web unit tests, wrapper parity, core, integration, Windows Codex MCP, the Android build and tests, and Android transcript layout on API 29 passing. Browser tests and Android transcript layout on API 36 were in progress.
  • <!-- hapi-pr-review:v2:85b717a526f9470d49d0488a57ad100ddc5c3bee8cf4e71a1d2e8b7f4a3a1ac4 -->
    HAPI Bot

    github-actions[bot] github-actions[bot] commented on code on Nov 24, 2026 09:16 UTC
    Code Review
    cli/src/claude/utils/sdkToLogConverter.ts:1
    @@ -288,157 +256,90 @@ export class SDKToLogConverter {
             // The usage baseline is kept: updateSessionId clears it when the native session id changes.
         }
     
    +    /**
    +     * Start accounting for a newly spawned Claude process; a fresh one
    +     * (started without a prior transcript) starts its counters at zero.
    +     */
    +    beginProcess(fresh: boolean): void {
    +        // Models of a round whose process ended before its result do not
    +        // belong to the next round.
    +        this.dropPendingModels()
    +        if (fresh) this.startFreshProcessBaseline()
    +    }
    +
         /**
          * Seed a zero baseline for a process started without a prior transcript.
          */
         startFreshProcessBaseline(): void {
             // A fresh process owns whatever session id it reports next.
             this.usageSessionId = null
    -        this.previousCumulative = {
    -            totalCostUsd: 0,
    -            durationApiMs: 0,
    -            modelUsage: {},
    -            modelSnapshotKnown: true,
    -            staleModels: new Set(),
    -            modelGapSeen: false,
    -            missingTokenCounters: {}
    -        }
    +        this.previousCumulative = { totalCostUsd: 0, durationApiMs: 0 }
         }
     
         /**
          * Advance the cumulative baseline for a result that produces no transcript
    -     * entry, so the next round does not absorb its cost, tokens and API time.
    +     * entry, so the next round does not absorb its cost and API time.
          */
         consumeResultForAccounting(resultMsg: SDKResultMessage): void {
             this.consumeCumulativeDeltas(resultMsg)
         }
     
    +    /** False for a message of another native session than the one usage is tracked for. */
    +    private isUsageSession(sessionId: unknown): boolean {
    +        return this.usageSessionId === null || typeof sessionId !== 'string' || sessionId === this.usageSessionId
    +    }
    +
    +    private dropPendingModels(): void {
    +        this.answeredModels = new Set()
    +        this.subagentModels = new Map()
    +    }
    +
         /**
    -     * Diff a result's cumulative fields against the previous raw values, then
    -     * advance the baseline even for errored/compaction rounds and backwards
    -     * values. Fields without a trustworthy delta are omitted, not emitted raw.
    +     * The models a result lists, taken from the pending lists. A top-level
    +     * result of the tracked session ends the enclosing assistant round and
    +     * takes all its models. A subagent result (with parent_tool_use_id) takes
    +     * only the models of that subagent's messages and leaves the enclosing
    +     * round's list intact. A command, compaction or clear receipt, or a result
    +     * of another session, takes nothing. Cost and API time count either way.
    +     */
    +    private takeRoundModels(resultMsg: SDKResultMessage): string[] {
    +        if (isCommandReceipt(resultMsg) || !this.isUsageSession(resultMsg.session_id)) return []
    +        const parentToolUseId = resultMsg.parent_tool_use_id
    +        if (typeof parentToolUseId === 'string' && parentToolUseId.length > 0) {
    +            const models = this.subagentModels.get(parentToolUseId)
    +            this.subagentModels.delete(parentToolUseId)
    +            return models ? [...models] : []
    +        }
    +        const models = [...this.answeredModels]
    +        this.dropPendingModels()

    [Minor] Top-level results discard model names for unfinished subagents

    When a background subagent answers before the enclosing result and finishes afterward, the enclosing result clears its per-tool model set. If the subagent switches to a fallback model after that boundary, its own summary lists only the fallback model and omits the model that answered earlier in the same run. Mid-run fallback is documented at web/src/components/ToolCard/ToolCard.tsx:233.

    Suggested fix

    Clear the enclosing round’s model set at the top-level result. Keep each subagent’s model set until its own result, a native session rotation, or a new process. Cover a background subagent that reports distinct models on either side of the enclosing result.

    github-actions[bot] github-actions[bot] commented on Nov 24, 2026 09:16 UTC
    Reviewer

    ✅ All stages passed (1 Minor)

    Review mode: follow-up after new commits

    Requirement — Pass

    Claude round footers should show the current round’s main-model token counts, name the models that answered, and include subagent spend in the round cost. The existing calculation can show zero output tokens for a reply that generated output.

    Evidence

  • The base converter can retain input counters when output counters are absent at cli/src/claude/utils/sdkToLogConverter.ts:375. The web footer substitutes zero for the missing output counter at web/src/components/AssistantChat/messages/MessageMetadata.tsx:49.
  • Approach — Pass

    The SDK result supplies round usage directly. Assistant messages supply model names, and cumulative deltas supply cost and API time. Accounting for held receipts on arrival preserves the order of the cost and time snapshots.

    Evidence

  • cli/src/claude/utils/sdkToLogConverter.ts:509 collects model names and line 649 forwards round usage.

  • cli/src/claude/claudeRemote.ts:873 accounts for a held receipt before its input echo, and cli/src/claude/utils/sdkToLogConverter.ts:642 suppresses its summary.

  • web/src/chat/normalizeAgent.ts:81 and android/core/protocol/src/main/kotlin/app/hapi/protocol/chat/RoundSummary.kt:100 decode the explicit model list and preserve the handling of stored summaries.
  • Code — Reviewed

    Reviewed the full fixed-head diff. The prior sidechain finding is addressed. An enclosing result can still erase the model history of a background subagent that is running.

  • [Minor] Top-level results discard model names for unfinished subagents — cli/src/claude/utils/sdkToLogConverter.ts:314
  • Testing

    Not run (automation; PR code execution is prohibited).

  • The fixed merge-base diff passed git diff --check. Local verification was read-only.

  • GitHub reported success on 790b438a for the fixture drift gate, CLI and web unit tests, wrapper parity, core, integration, browser, Windows Codex MCP, and Android build, tests, and transcript layout on APIs 29 and 36.
  • <!-- hapi-pr-review:v2:a72e051cfa26c55078b8b092c70d976e8a129f07bf60924717ceb41ce5a1ba4c -->
    HAPI Bot

    github-actions[bot] github-actions[bot] commented on code on Nov 24, 2026 09:34 UTC
    Code Review
    cli/src/claude/claudeRemote.ts:1
    @@ -909,8 +918,12 @@ export async function claudeRemote(opts: {
                 const isCompactTurnResult = compact !== null
                     && isCommandResult(message, compact.uuid, 'compact', compact.initial && compact.sawCompactSignal);
                 if (!isClearResult && !isManualCompactBoundaryMessage(message) && !isCompactEchoMessage(message)) {
    -                opts.onMessage(isCompactTurnResult || staleUsageSession ? {
    +                // A command, compaction or clear result ends no assistant round.
    +                const isCommandReceipt = message.type === 'result' && (isCompactTurnResult || staleUsageSession

    [Minor] A first-input reset receipt can still replace a reply footer

    When /reset is the first input and the clear hook identifies the new session, an untagged result carrying the new session ID leaves staleUsageSession false. The existing first-input alias test exercises that result shape at cli/src/claude/claudeRemote.test.ts:1715. The new predicate forwards it as a normal result, so the converter emits a round summary and the web reducer can overwrite the latest eligible reply’s footer with the reset’s duration and turn count.

    Suggested fix

    Mark the result recognized by the first-input clear-hook path as a command receipt regardless of which session ID it carries. Keep the usage skip conditional on the stale ID, and extend the first-input alias test to check that the reset emits no round summary.

    github-actions[bot] github-actions[bot] commented on Nov 24, 2026 09:34 UTC
    Reviewer

    ✅ All stages passed (1 Minor)

    Review mode: follow-up after new commits

    Requirement — Pass

    Claude reply footers should show the current round’s main-model token usage, name the models that answered, and include subagent spend in the round cost. The existing calculation can show zero output tokens for a reply that generated output.

    Evidence

  • The base converter retains available model counters when output tokens are absent in cli/src/claude/utils/sdkToLogConverter.ts:375. The web footer substitutes zero for the missing output counter in web/src/components/AssistantChat/messages/MessageMetadata.tsx:49.
  • Approach — Pass

    Using the SDK result’s round usage removes the unreliable token subtraction. Assistant messages provide model names, and accounting for held receipts on arrival preserves the order of cumulative cost and API-time snapshots.

    Evidence

  • cli/src/claude/utils/sdkToLogConverter.ts:512 collects model names and line 652 forwards the result’s usage.

  • cli/src/claude/claudeRemote.ts:877 accounts for the held receipt before its input echo.

  • web/src/chat/normalizeAgent.ts:81 and android/core/protocol/src/main/kotlin/app/hapi/protocol/chat/RoundSummary.kt:100 decode the explicit model list and retain the existing handling of stored summaries.
  • Code — Reviewed

    Reviewed the full fixed-head diff. The follow-up preserves unfinished subagent model history across an enclosing result. One reset receipt still bypasses the new classification.

  • [Minor] A first-input reset receipt can still replace a reply footer — cli/src/claude/claudeRemote.ts:922
  • Testing

    Not run (automation; PR code execution is prohibited).

  • The fixed merge-base diff passed git diff --check. Review verification was read-only.

  • On 7dd945fc, GitHub reported success for CLI and web unit tests, wrapper parity, core, integration, browser, Windows Codex MCP, and fixture drift.

  • The Android build job failed in the unchanged ScratchlistStoreTest upload-progress test with UncompletedCoroutinesError. Android transcript layout checks on APIs 29 and 36 were still running. https://github.com/tiann/hapi/actions/runs/45365642012/job/138346537380
  • <!-- hapi-pr-review:v2:316f82a9f56ff03cb2f0ebba55bbeed99127b7eef3e79cccbe262083310fbb22 -->
    HAPI Bot

    github-actions[bot] github-actions[bot] commented on code on Nov 24, 2026 10:18 UTC
    Code Review
    cli/src/claude/utils/sdkToLogConverter.ts:1
    @@ -710,19 +630,27 @@ export class SDKToLogConverter {
                             }
                         }
                     }
    -                // These fields are cumulative across resumes; emit only a
    +                // Cost and API time are cumulative across resumes; emit only a
                     // trustworthy per-round delta, never a lifetime total.
                     const perRound = resultMsg.hapi_skip_usage === true
    -                    ? { totalCostUsd: undefined, durationApiMs: undefined, modelUsage: undefined }
    +                    ? { totalCostUsd: undefined, durationApiMs: undefined }
                         : this.consumeCumulativeDeltas(resultMsg)
    +                const models = this.takeRoundModels(resultMsg)
    +                // A command or clear receipt (local command, held command shown on its
    +                // echo, clear alias) or a result of another native session emits no
    +                // round summary: clients attach a summary to the latest assistant
    +                // reply, which may belong to another round. A compaction turn keeps
    +                // its summary for the compaction call's cost.
    +                if (!this.isUsageSession(resultMsg.session_id)) break
    +                if (isCommandReceipt(resultMsg) && !isCompactionResult(resultMsg)) break
                     logMessage = {
                         ...baseFields,
                         type: 'system',
                         subtype: 'turn_duration',
                         durationMs: resultMsg.duration_ms,
                         resultSummary: {
                             usage: resultMsg.usage,
    -                        modelUsage: perRound.modelUsage,
    +                        ...(models.length > 0 ? { round_models: models } : {}),

    [Minor] Late subagent results replace the Android reply’s model list

    When a background subagent finishes after the enclosing turn and before the next prompt, the CLI emits a summary containing only that subagent’s models, as covered at cli/src/claude/utils/sdkToLogConverter.test.ts:694. Android’s turn-summary normalizer drops the sidechain marker at android/core/protocol/src/main/kotlin/app/hapi/protocol/chat/NormalizeAgent.kt:658. The root reducer then replaces the enclosing reply’s footer at android/core/protocol/src/main/kotlin/app/hapi/protocol/chat/ReducerTimeline.kt:611, so the main model disappears from its own reply.

    Suggested fix

    Preserve the sidechain marker and parent tool-use ID when Android normalizes Claude turn summaries, then route them to the subagent’s group. Add a reduction test where a subagent result arrives after the enclosing result and verify that the enclosing footer keeps its original summary.

    github-actions[bot] github-actions[bot] commented on Nov 24, 2026 10:18 UTC
    Reviewer

    ✅ All stages passed (1 Minor)

    Review mode: follow-up after new commits

    Requirement — Pass

    Claude reply footers should show the current round’s main-model tokens and the models that answered, while retaining subagent spend in the round cost. The existing footer can show zero output tokens for a reply that generated output.

    Evidence

  • The base converter can retain available model counters when the output counter is absent at cli/src/claude/utils/sdkToLogConverter.ts:375. The web footer then substitutes zero at web/src/components/AssistantChat/messages/MessageMetadata.tsx:49.
  • Approach — Pass

    Using the SDK result’s per-round usage removes cumulative token subtraction. Assistant messages supply the model names, and accounting for held command results on arrival preserves the order of cost and API-time snapshots.

    Evidence

  • cli/src/claude/utils/sdkToLogConverter.ts:512 collects model names and line 652 forwards the result’s usage.

  • cli/src/claude/claudeRemote.ts:877 accounts for the held receipt before its input echo.

  • web/src/chat/normalizeAgent.ts:81 and android/core/protocol/src/main/kotlin/app/hapi/protocol/chat/RoundSummary.kt:100 decode the explicit model list and preserve handling of stored summaries.
  • Code — Reviewed

    Reviewed the full fixed-head diff. The previous first-input reset finding is resolved for both session IDs. Android can still attach a late subagent’s model list to the enclosing reply.

  • [Minor] Late subagent results replace the Android reply’s model list — cli/src/claude/utils/sdkToLogConverter.ts:653
  • Testing

    Not run (automation; PR code execution is prohibited).

  • The fixed merge-base diff passed git diff --check. PR tests were observed through GitHub Actions only.

  • On 74ff7255, GitHub reported success for CLI and web unit tests, wrapper parity, core, integration, Windows Codex MCP, fixture drift, Android build, and Android transcript layout on API 29. Browser and Android API 36 transcript layout checks were still running.
  • <!-- hapi-pr-review:v2:1ef328cc019caa4e14e4a76cc0913361e9182e18c00833808080c54443f78d75 -->
    HAPI Bot

    github-actions[bot] github-actions[bot] commented on code on Nov 24, 2026 10:34 UTC
    Code Review
    cli/src/claude/utils/sdkToLogConverter.ts:1
    @@ -601,6 +505,22 @@ export class SDKToLogConverter {
                             usage.context_window = contextWindow
                         }
                     }
    +                // Synthetic messages (API errors, interruptions) name no real model.
    +                // A main-thread message reports the active model bare, so it takes
    +                // the init model's variant; every other message keeps the id it
    +                // reported, so a subagent on a "[1m]" variant is listed bare.
    +                if (typeof message?.model === 'string' && message.model !== '<synthetic>'
    +                    && this.isUsageSession(assistantMsg.session_id)) {
    +                    const activeModel = this.resolvedModel
    +                    this.answeredModels.add(!isSidechain && activeModel?.replace(/\[1m\]$/, '') === message.model

    [Minor] A finished background subagent leaks into the next reply’s model list

    If a background subagent emits its final assistant message and result after the enclosing reply has finished, both events can arrive before the next prompt. The assistant message adds its model to answeredModels, but the subagent result clears only its private list. The next reply then lists the finished subagent’s model even when only the main model answered. The converter test at line 694 currently expects this carryover.

    Suggested fix

    Associate subagent model entries with their parent round. Keep late output available for the subagent’s own summary and exclude it from later replies once the parent round closes. Update the test to place the subagent completion before the next prompt and expect only the main model on that reply.

    github-actions[bot] github-actions[bot] commented on code on Nov 24, 2026 10:34 UTC
    Code Review
    android/core/protocol/src/main/kotlin/app/hapi/protocol/chat/Tracer.kt:1
    @@ -96,10 +99,12 @@ fun traceMessages(messages: List<NormalizedMessage>): List<TracedMessage> {
                 }
             }
     
    -        if (!sidechainId.isNullOrEmpty() && !uuid.isNullOrEmpty()) {
    -            state.uuidToSidechainId[uuid] = sidechainId
    +        // A message without a uuid (a subagent's turn summary event) still joins its
    +        // subagent; only a uuid can adopt orphans (web: tracer.ts).
    +        if (!sidechainId.isNullOrEmpty()) {

    [Minor] A subagent summary can overwrite the main footer when its parent call is outside the loaded page

    A paginated transcript can contain the main reply and a late subagent result while omitting the older Agent tool call. Android’s tracer then leaves the summary ungrouped at Tracer.kt:127, and the root reducer replaces the main reply’s footer at ReducerTimeline.kt:611 with the subagent’s model list and usage. The web tracer has the same ungrouped fallback at web/src/chat/tracer.ts:142.

    Suggested fix

    Exclude unresolved sidechain summary events from the root timeline in both clients. Add a reducer test with the main reply and late subagent summary in the loaded page and the parent call outside it.

    github-actions[bot] github-actions[bot] commented on Nov 24, 2026 10:34 UTC
    Reviewer

    ✅ All stages passed (2 Minor)

    Review mode: follow-up after new commits

    Requirement — Pass

    Claude reply footers should show the round’s main-model token counts and identify the models that answered in that round. The base footer can show zero output tokens for a reply that generated output.

    Evidence

  • The base converter can keep partial model counters at cli/src/claude/utils/sdkToLogConverter.ts:375. The web footer substitutes zero for a missing output counter at web/src/components/AssistantChat/messages/MessageMetadata.tsx:49.

  • The PR description specifies round-local tokens and model names while retaining cumulative cost and API-time deltas.
  • Approach — Pass

    Using the SDK result’s round-local usage removes token baseline errors. Assistant messages provide model names, and accounting for held command receipts on arrival preserves the order of cost and API-time snapshots.

    Evidence

  • cli/src/claude/utils/sdkToLogConverter.ts:512 collects assistant model names and line 652 forwards round usage.

  • cli/src/claude/claudeRemote.ts:877 accounts for a held command receipt on arrival.

  • web/src/chat/normalizeAgent.ts:81 and android/core/protocol/src/main/kotlin/app/hapi/protocol/chat/RoundSummary.kt:100 decode the explicit model list and preserve handling of stored summaries.
  • Code — Reviewed

    Reviewed the full merge-base diff. Android now routes a late subagent summary to its card when the parent call is loaded. Two attribution errors remain.

  • [Minor] A finished background subagent leaks into the next reply’s model list — cli/src/claude/utils/sdkToLogConverter.ts:515

  • [Minor] A subagent summary can overwrite the main footer when its parent call is outside the loaded page — android/core/protocol/src/main/kotlin/app/hapi/protocol/chat/Tracer.kt:104
  • Testing

    Not run (automation; PR code execution is prohibited).

  • The fixed merge-base diff passed git diff --check. PR code was inspected without local execution.

  • On c69bf208, GitHub reported success for CLI and web unit tests, wrapper parity, core, integration, Windows Codex MCP, and fixture drift. Browser, Android build, and Android transcript layout on API 29 and 36 were still running at the last check.
  • <!-- hapi-pr-review:v2:2ef353bade1fc5faf3b306b72a0cdeeaf245371e5641e0f38a7f6a180bdf6257 -->
    HAPI Bot

    github-actions[bot] github-actions[bot] commented on Nov 24, 2026 11:16 UTC
    Reviewer

    ✅ All stages passed (1 Minor)

    Review mode: follow-up after new commits

    Requirement — Pass

    Claude reply footers should show the current round’s main-model token counts and identify the models that answered in that round. The existing footer can show zero output tokens for a reply that generated output.

    Evidence

  • The base converter can retain partial per-model counters at cli/src/claude/utils/sdkToLogConverter.ts:375. The web footer treats a missing output counter as zero at web/src/components/AssistantChat/messages/MessageMetadata.tsx:49.

  • The PR description specifies round-local token counts and model names while preserving per-round cost and API-time deltas.
  • Approach — Pass

    Using the SDK result’s own usage removes the dependency on cumulative token counters. Assistant messages provide model names, and accounting for held command receipts on arrival preserves the order of cost and API-time snapshots.

    Evidence

  • cli/src/claude/utils/sdkToLogConverter.ts:525 collects model names and line 676 forwards round-local usage.

  • cli/src/claude/claudeRemote.ts:877 accounts for a held command receipt when it arrives.

  • web/src/chat/normalizeAgent.ts:81 and android/core/protocol/src/main/kotlin/app/hapi/protocol/chat/RoundSummary.kt:100 decode the explicit model list and preserve rendering for stored summaries.
  • Code — Reviewed

    The full merge-base diff addresses the previous findings for direct subagents and summaries whose parent card is outside the loaded page. Late output from a nested subagent can still be attributed to the next reply.

  • [Minor] A late nested subagent can appear in the next reply’s model list — cli/src/claude/utils/sdkToLogConverter.ts:540
  • Testing

    Not run (automation; PR code execution is prohibited).

  • The fixed merge-base diff passed git diff --check. No PR code or tests were run locally.

  • On c609e093, GitHub reported success for CLI unit tests, wrapper parity, core, integration, Windows Codex MCP, and fixture drift. Web unit tests, browser tests, Android build, and Android transcript layout checks on API 29 and 36 were still running at the last check.
  • <!-- hapi-pr-review:v2:efabddf8a15eb2f4e9e3a3ab3b8563aab426096640a21b1ba8b2cda30193268a -->
    HAPI Bot

    github-actions[bot] github-actions[bot] commented on code on Nov 24, 2026 11:16 UTC
    Code Review
    cli/src/claude/utils/sdkToLogConverter.ts:1
    @@ -601,6 +518,33 @@ export class SDKToLogConverter {
                             usage.context_window = contextWindow
                         }
                     }
    +                // Synthetic messages (API errors, interruptions) name no real model.
    +                // A main-thread message reports the active model bare, so it takes
    +                // the init model's variant; every other message keeps the id it
    +                // reported, so a subagent on a "[1m]" variant is listed bare.
    +                if (typeof message?.model === 'string' && message.model !== '<synthetic>'
    +                    && this.isUsageSession(assistantMsg.session_id)) {
    +                    const activeModel = this.resolvedModel
    +                    if (!parentToolUseId || !this.lateSubagents.has(parentToolUseId)) {
    +                        this.answeredModels.add(!isSidechain && activeModel?.replace(/\[1m\]$/, '') === message.model
    +                            ? activeModel
    +                            : message.model)
    +                    }
    +                    if (parentToolUseId) {
    +                        const models = this.subagentModels.get(parentToolUseId) ?? new Set<string>()
    +                        models.add(message.model)
    +                        this.subagentModels.set(parentToolUseId, models)
    +                    }
    +                }
    +                // Subagents the main thread starts belong to the round in progress.
    +                if (!isSidechain && this.isUsageSession(assistantMsg.session_id) && Array.isArray(message?.content)) {

    [Minor] A late nested subagent can appear in the next reply’s model list

    If a subagent starts another Agent tool call before the main reply finishes and the nested agent first answers afterward, the converter has no record that the nested call belongs to the closed round. The registration guard only records tool calls from the main thread. When the nested answer arrives, its model enters answeredModels and can appear in the next reply’s footer. The existing tracer test at web/src/chat/tracer.test.ts:215 covers Agent calls inside sidechains.

    Suggested fix

    Record nested Agent calls and give each child the same round as its parent. Add a converter test where the nested agent first answers after the enclosing result and verify its model stays on its own summary.

    github-actions[bot] github-actions[bot] commented on code on Nov 24, 2026 12:01 UTC
    Code Review
    cli/src/claude/utils/sdkToLogConverter.ts:1
    @@ -288,157 +262,100 @@ export class SDKToLogConverter {
             // The usage baseline is kept: updateSessionId clears it when the native session id changes.
         }
     
    +    /**
    +     * Start accounting for a newly spawned Claude process; a fresh one
    +     * (started without a prior transcript) starts its counters at zero.
    +     */
    +    beginProcess(fresh: boolean): void {
    +        // Models of a round whose process ended before its result do not
    +        // belong to the next round.
    +        this.dropPendingModels()
    +        if (fresh) this.startFreshProcessBaseline()
    +    }
    +
         /**
          * Seed a zero baseline for a process started without a prior transcript.
          */
         startFreshProcessBaseline(): void {
             // A fresh process owns whatever session id it reports next.
             this.usageSessionId = null
    -        this.previousCumulative = {
    -            totalCostUsd: 0,
    -            durationApiMs: 0,
    -            modelUsage: {},
    -            modelSnapshotKnown: true,
    -            staleModels: new Set(),
    -            modelGapSeen: false,
    -            missingTokenCounters: {}
    -        }
    +        this.previousCumulative = { totalCostUsd: 0, durationApiMs: 0 }
         }
     
         /**
          * Advance the cumulative baseline for a result that produces no transcript
    -     * entry, so the next round does not absorb its cost, tokens and API time.
    +     * entry, so the next round does not absorb its cost and API time.
          */
         consumeResultForAccounting(resultMsg: SDKResultMessage): void {
             this.consumeCumulativeDeltas(resultMsg)
         }
     
    +    /** False for a message of another native session than the one usage is tracked for. */
    +    private isUsageSession(sessionId: unknown): boolean {
    +        return this.usageSessionId === null || typeof sessionId !== 'string' || sessionId === this.usageSessionId
    +    }
    +
    +    private dropPendingModels(): void {
    +        this.answeredModels = new Set()
    +        this.subagentModels = new Map()
    +        this.roundSubagents = new Set()
    +        this.lateSubagents = new Set()
    +    }
    +
    +    /**
    +     * The models a result lists, taken from the pending lists. A top-level
    +     * result of the tracked session ends the enclosing assistant round and
    +     * takes all its models; each subagent keeps its own list, since a
    +     * background subagent can keep answering after that result. A subagent
    +     * result (with parent_tool_use_id) takes only the models of that
    +     * subagent's messages and leaves the enclosing round's list intact. A
    +     * command, compaction or clear receipt, or a result of another session,
    +     * takes nothing. Cost and API time count either way.
    +     */
    +    private takeRoundModels(resultMsg: SDKResultMessage): string[] {
    +        if (isCommandReceipt(resultMsg) || !this.isUsageSession(resultMsg.session_id)) return []
    +        const parentToolUseId = resultMsg.parent_tool_use_id
    +        if (typeof parentToolUseId === 'string' && parentToolUseId.length > 0) {
    +            const models = this.subagentModels.get(parentToolUseId)
    +            this.subagentModels.delete(parentToolUseId)
    +            this.roundSubagents.delete(parentToolUseId)
    +            this.lateSubagents.delete(parentToolUseId)
    +            return models ? [...models] : []
    +        }
    +        const models = [...this.answeredModels]
    +        this.answeredModels = new Set()
    +        // Subagents of this round that are still running answer late from now on.
    +        for (const id of this.roundSubagents) this.lateSubagents.add(id)
    +        for (const id of this.subagentModels.keys()) this.lateSubagents.add(id)

    [Minor] Completed subagents stay in the round tracker

    When a Task or Agent invocation finishes with a regular tool_result and no separate result carrying parent_tool_use_id, its model set and tool ID survive until the process or native session changes. The successful Task completion at shared/fixtures/chat/sidechain-task-nested-children.json:378 illustrates that tool-result shape. Each later reply scans the retained model sets, so repeated subagent use in a long-running session increases memory use and the work needed to process each footer.

    Suggested fix

    Release tracking state on definitive subagent completion, including a synchronous tool_result, and preserve it when the tool result only acknowledges a background launch. Move only the current round’s IDs into the late set and cover tool-result-only completion in a converter test.

    github-actions[bot] github-actions[bot] commented on Nov 24, 2026 12:01 UTC
    Reviewer

    ✅ All stages passed (1 Minor)

    Review mode: follow-up after new commits

    Requirement — Pass

    Claude reply footers should show the current round’s main-model token counts and identify the models that answered. The existing footer can report zero output tokens when a per-model counter is missing, even when the round reports positive output.

    Evidence

  • The PR description defines round-local token counts and model names while preserving per-round cost and API-time deltas.

  • The base converter can retain a partial token breakdown at cli/src/claude/utils/sdkToLogConverter.ts:375. The web footer treats a missing output counter as zero at web/src/components/AssistantChat/messages/MessageMetadata.tsx:49.
  • Approach — Pass

    Use the SDK result’s round-local usage for tokens, collect model names from assistant messages, and account for held command receipts when they arrive. Web and Android can render the explicit model list while preserving the existing fallback for stored summaries.

    Evidence

  • cli/src/claude/utils/sdkToLogConverter.ts:525 collects model names, and line 678 forwards the result’s usage.

  • cli/src/claude/claudeRemote.ts:877 accounts for a held command result on arrival, and line 863 marks it as already accounted when its echo arrives.

  • web/src/chat/normalizeAgent.ts:81 and android/core/protocol/src/main/kotlin/app/hapi/protocol/chat/RoundSummary.kt:100 decode the explicit model list.
  • Code — Reviewed

    The full merge-base diff addresses the previous nested-subagent attribution finding. The converter still retains state for subagents that complete through a tool result alone.

  • [Minor] Completed subagents stay in the round tracker — cli/src/claude/utils/sdkToLogConverter.ts:329
  • Testing

    Not run (automation; PR code execution is prohibited).

  • The fixed merge-base diff passed git diff --check. No PR code or tests were run locally.

  • GitHub reported success on c298d997 for the aggregate test check, CLI and web unit tests, wrapper parity, core, integration, browser, Windows Codex MCP, fixture drift, Android build, and Android transcript layout on API 29 and 36.
  • <!-- hapi-pr-review:v2:3be54ffe35261f0126c388ebcedf2909062fa005e68cbf87f9084cb90832d955 -->
    HAPI Bot

    github-actions[bot] github-actions[bot] commented on code on Nov 24, 2026 12:40 UTC
    Code Review
    cli/src/claude/utils/sdkToLogConverter.ts:1
    @@ -288,157 +262,104 @@ export class SDKToLogConverter {
             // The usage baseline is kept: updateSessionId clears it when the native session id changes.
         }
     
    +    /**
    +     * Start accounting for a newly spawned Claude process; a fresh one
    +     * (started without a prior transcript) starts its counters at zero.
    +     */
    +    beginProcess(fresh: boolean): void {
    +        // Models of a round whose process ended before its result do not
    +        // belong to the next round.
    +        this.dropPendingModels()
    +        if (fresh) this.startFreshProcessBaseline()
    +    }
    +
         /**
          * Seed a zero baseline for a process started without a prior transcript.
          */
         startFreshProcessBaseline(): void {
             // A fresh process owns whatever session id it reports next.
             this.usageSessionId = null
    -        this.previousCumulative = {
    -            totalCostUsd: 0,
    -            durationApiMs: 0,
    -            modelUsage: {},
    -            modelSnapshotKnown: true,
    -            staleModels: new Set(),
    -            modelGapSeen: false,
    -            missingTokenCounters: {}
    -        }
    +        this.previousCumulative = { totalCostUsd: 0, durationApiMs: 0 }
         }
     
         /**
          * Advance the cumulative baseline for a result that produces no transcript
    -     * entry, so the next round does not absorb its cost, tokens and API time.
    +     * entry, so the next round does not absorb its cost and API time.
          */
         consumeResultForAccounting(resultMsg: SDKResultMessage): void {
             this.consumeCumulativeDeltas(resultMsg)
         }
     
    +    /** False for a message of another native session than the one usage is tracked for. */
    +    private isUsageSession(sessionId: unknown): boolean {
    +        return this.usageSessionId === null || typeof sessionId !== 'string' || sessionId === this.usageSessionId
    +    }
    +
    +    private dropPendingModels(): void {
    +        this.answeredModels = new Set()
    +        this.subagentModels = new Map()
    +        this.roundSubagents = new Set()
    +        this.lateSubagents = new Set()
    +    }
    +
         /**
    -     * Diff a result's cumulative fields against the previous raw values, then
    -     * advance the baseline even for errored/compaction rounds and backwards
    -     * values. Fields without a trustworthy delta are omitted, not emitted raw.
    +     * The models a result lists, taken from the pending lists. A top-level
    +     * result of the tracked session ends the enclosing assistant round and
    +     * takes all its models; each subagent keeps its own list, since a
    +     * background subagent can keep answering after that result. A subagent
    +     * result (with parent_tool_use_id) takes only the models of that
    +     * subagent's messages and leaves the enclosing round's list intact. A
    +     * command, compaction or clear receipt, or a result of another session,
    +     * takes nothing. Cost and API time count either way.
    +     */
    +    private takeRoundModels(resultMsg: SDKResultMessage): string[] {
    +        if (isCommandReceipt(resultMsg) || !this.isUsageSession(resultMsg.session_id)) return []
    +        const parentToolUseId = resultMsg.parent_tool_use_id
    +        if (typeof parentToolUseId === 'string' && parentToolUseId.length > 0) {
    +            const models = this.subagentModels.get(parentToolUseId)
    +            this.releaseSubagent(parentToolUseId)
    +            return models ? [...models] : []
    +        }
    +        const models = [...this.answeredModels]
    +        this.answeredModels = new Set()
    +        // Subagents of this round that are still running answer late from now on.
    +        for (const id of this.roundSubagents) this.lateSubagents.add(id)

    [Minor] Background subagents can stay tracked after completion

    A background Agent launch keeps its tool-use ID in the tracker, and the enclosing result moves it into lateSubagents. If the task then finishes through a terminal system event without a separate result carrying parent_tool_use_id, the converter forwards the system event without releasing the ID or its model set. Repeated background tasks therefore grow the CLI’s retained state until the process or native session changes. HAPI has observed task_notification events for background completions in production. https://github.com/tiann/hapi/pull/2102

    Suggested fix

    Release the tracked tool-use ID on terminal SDK task events. Use the event’s tool_use_id when present, or correlate its task_id with the task-start event. Add a converter test for a background launch that completes through a task notification alone.

    github-actions[bot] github-actions[bot] commented on Nov 24, 2026 12:40 UTC
    Reviewer

    ✅ All stages passed (1 Minor)

    Review mode: follow-up after new commits

    Requirement — Pass

    Claude reply footers should show the round’s main-model token counts, identify the models that answered, and retain per-round cost and API time. The current footer can show zero output tokens when a per-model counter is missing despite positive round usage.

    Evidence

  • The PR description identifies failures with empty or incomplete cumulative model counters and with delayed command receipts after a session reset.

  • At the merge base, cli/src/claude/utils/sdkToLogConverter.ts:375 can retain a partial per-model token breakdown, and web/src/components/AssistantChat/messages/MessageMetadata.tsx:49 treats a missing output counter as zero.
  • Approach — Pass

    Use the SDK result’s round-local usage for tokens, collect model names from assistant messages, and account for held command results when they arrive. Web and Android can render the explicit model list while preserving the fallback for stored summaries.

    Evidence

  • cli/src/claude/utils/sdkToLogConverter.ts:537 collects assistant model names, and line 692 forwards round-local usage.

  • cli/src/claude/claudeRemote.ts:877 accounts for a held command on arrival, and line 863 prevents a second accounting pass when its echo arrives.

  • web/src/chat/normalizeAgent.ts:81 and android/core/protocol/src/main/kotlin/app/hapi/protocol/chat/RoundSummary.kt:100 decode the explicit model list.
  • Code — Reviewed

    The full merge-base diff now releases tracking after synchronous subagent tool results. Background subagents that complete through SDK task lifecycle events can still leave tracking state behind.

  • [Minor] Background subagents can stay tracked after completion — cli/src/claude/utils/sdkToLogConverter.ts:326
  • Testing

    Not run (automation; PR code execution is prohibited).

  • The fixed merge-base diff passed git diff --check. No PR code or tests were run locally.

  • On 45ff2e37, GitHub reported success for fixture drift, CLI and web unit tests, wrapper parity, core, integration, and Windows Codex MCP. Browser tests, Android build, and Android transcript-layout checks on API 29 and 36 were still running when checked.

  • The new cleanup tests cover synchronous tool results and a background launch followed by a separate subagent result. They do not cover completion through a task lifecycle event alone.
  • <!-- hapi-pr-review:v2:96eec3b36a18013585b0864deb7429f79a7d8afbb8f0a7e3fd59b66dc4f23716 -->
    HAPI Bot

    github-actions[bot] github-actions[bot] commented on Nov 24, 2026 13:28 UTC
    Reviewer

    ✅ All stages passed (2 Minor)

    Review mode: follow-up after new commits

    Requirement — Pass

    Claude reply footers should show the round’s main-model token counts, identify the models that answered, and retain per-round cost and API time. The current footer can report zero output tokens even when the round reports positive output.

    Evidence

  • At the merge base, cli/src/claude/utils/sdkToLogConverter.ts:375 can retain a per-model breakdown whose output counter has never been reported. web/src/components/AssistantChat/messages/MessageMetadata.tsx:49 treats that missing counter as zero.

  • The fixed PR description gives a second failure case in which a delayed command receipt after /clear causes the next reply to count a background round twice.
  • Approach — Pass

    Using the SDK result’s round-local usage removes the dependency on cumulative token snapshots. Collecting model names from assistant messages and accounting for held receipts on arrival addresses model attribution and preserves cost and API-time ordering.

    Evidence

  • cli/src/claude/utils/sdkToLogConverter.ts:541 collects assistant model names, and line 720 forwards the result’s own usage.

  • cli/src/claude/claudeRemote.ts:877 accounts for a held receipt when it arrives, and line 863 marks the replay so accounting happens once.

  • web/src/chat/normalizeAgent.ts:81 and android/core/protocol/src/main/kotlin/app/hapi/protocol/chat/RoundSummary.kt:100 decode explicit model names while preserving the fallback for stored summaries.
  • Code — Reviewed

    The latest commit handles terminal task notifications by task ID or tool-use ID. The static review found two remaining issues with subagent summary routing and cleanup.

  • [Minor] Sibling subagent summaries land on the first Android card — android/core/protocol/src/main/kotlin/app/hapi/protocol/chat/Tracer.kt:104

  • [Minor] Standalone tool results leave completed subagents tracked — cli/src/claude/utils/sdkToLogConverter.ts:498
  • Testing

    Not run (automation; PR code execution is prohibited).

  • The full merge-base diff passed git diff --check. No PR code or tests ran locally.

  • On f55e1bf5, GitHub reported success for fixture drift, CLI and web unit tests, wrapper parity, core, integration, Windows Codex MCP, Android build, and Android transcript layout on API 29 and 36. Browser tests were still running.
  • <!-- hapi-pr-review:v2:584de0f24f20b86d5be5380c52bfc1883182a35a891ee5b611aad9d5013d4283 -->
    HAPI Bot

    github-actions[bot] github-actions[bot] commented on code on Nov 24, 2026 13:28 UTC
    Code Review
    android/core/protocol/src/main/kotlin/app/hapi/protocol/chat/Tracer.kt:1
    @@ -96,10 +99,12 @@ fun traceMessages(messages: List<NormalizedMessage>): List<TracedMessage> {
                 }
             }
     
    -        if (!sidechainId.isNullOrEmpty() && !uuid.isNullOrEmpty()) {
    -            state.uuidToSidechainId[uuid] = sidechainId
    +        // A message without a uuid (a subagent's turn summary event) still joins its
    +        // subagent; only a uuid can adopt orphans (web: tracer.ts).
    +        if (!sidechainId.isNullOrEmpty()) {

    [Minor] Sibling subagent summaries land on the first Android card

    When one assistant record contains two Agent calls with different tool-use IDs, Tracer.kt:67 maps both IDs to the same message ID. The new summary routing puts both results in that shared group. ReducerTimeline.kt:1097 lets the first card consume the group, so the second agent’s model and usage can appear under the first card and the second card has no summary.

    Suggested fix

    Key explicitly identified sidechains by the spawning tool-use ID in the tracer and reducer. Cover two Agent calls in one assistant record and verify that each card receives its own summary. Apply the same keying in the web reference pipeline.

    github-actions[bot] github-actions[bot] commented on code on Nov 24, 2026 13:28 UTC
    Code Review
    cli/src/claude/utils/sdkToLogConverter.ts:1
    @@ -564,6 +489,14 @@ export class SDKToLogConverter {
     
                     // Check if this is a tool result and add mode if available
                     if (Array.isArray(userMsg.message.content)) {
    +                    // A subagent call's tool result reports its completion, unless it
    +                    // only acknowledges a background launch.
    +                    const toolResults = userMsg.message.content.filter((content) => content.type === 'tool_result')
    +                    for (const content of toolResults) {
    +                        if (!content.tool_use_id) continue
    +                        const structured = toolResults.length === 1 ? (userMsg as { tool_use_result?: unknown }).tool_use_result : undefined
    +                        if (!isBackgroundAgentLaunch(content.content, structured)) this.releaseSubagent(content.tool_use_id)

    [Minor] Standalone tool results leave completed subagents tracked

    A synchronous Agent completion delivered as a top-level tool_result bypasses this cleanup. The converter accepts that envelope in its standalone handler at line 732, and sdkToLogConverter.test.ts:2009 exercises the shape. When that is the only completion event, the next enclosing result moves the finished tool ID into lateSubagents and retains its model set until a session change or process restart.

    Suggested fix

    Share the completion check between the two supported tool-result envelopes. Add a converter case that completes an Agent through a standalone tool_result and verifies that its tracking entries are released.

    github-actions[bot] github-actions[bot] commented on code on Nov 24, 2026 14:43 UTC
    Code Review
    cli/src/claude/claudeRemote.ts:1
    @@ -891,8 +900,11 @@ export async function claudeRemote(opts: {
                 }
                 const initialClearSessionId = !clear && message.type === 'result' && resultSeq === 0
                     ? opts.getClearHookSessionId?.() : undefined;
    +            // The first result after a clear the hook identified is that clear's
    +            // result, whichever session id it carries.
    +            const isInitialClearResult = Boolean(initialClearSessionId && initialClearSessionId !== currentSessionId);

    [Minor] A first-prompt reset receipt can consume background round models

    When /reset is the first prompt, the clear hook can report the rotated session and an init for that session can arrive before the untagged receipt. The init sets currentSessionId at line 998, so the equality check here prevents receipt classification. The converter then treats the receipt as a reply and drains any models already collected for a background round in the rotated session. That round’s eventual footer can omit those models.

    Suggested fix

    Classify the first result identified by the clear hook as a receipt even when init has already bound the rotated session. Keep the ID comparison for deciding whether to rebind, and extend the first-prompt alias test to cover init arriving before the receipt.

    github-actions[bot] github-actions[bot] commented on Nov 24, 2026 14:43 UTC
    Reviewer

    ✅ All stages passed (1 Minor)

    Review mode: follow-up after new commits

    Requirement — Pass

    Claude reply footers should show the current round’s main-model token counts, identify the models that answered, and report round-local cost and API time.

    Evidence

  • At the merge base, cli/src/claude/utils/sdkToLogConverter.ts:375 retains per-model counters with missing output values. web/src/components/AssistantChat/messages/MessageMetadata.tsx:49 counts those missing values as zero even when the result reports positive output usage.

  • The PR description identifies a second accounting error when a command receipt held after /clear is replayed after a newer background result.
  • Approach — Pass

    Using the result’s own usage fixes token accounting. Collecting model names from assistant messages identifies which models answered, and accounting for held receipts on arrival preserves the order of cumulative cost and API-time snapshots.

    Evidence

  • cli/src/claude/utils/sdkToLogConverter.ts:546 collects assistant model names and line 725 forwards round-local usage.

  • cli/src/claude/claudeRemote.ts:877 accounts for a held receipt on arrival and line 863 marks its replay.

  • web/src/chat/normalizeAgent.ts:81 and android/core/protocol/src/main/kotlin/app/hapi/protocol/chat/RoundSummary.kt:100 decode explicit model names and preserve the fallback for stored summaries.
  • Code — Reviewed

    The current head fixes both earlier findings by grouping sibling subagents by tool-use ID and releasing completed subagents for standalone tool results. One first-prompt reset sequence can still consume a background round’s model list.

  • [Minor] A first-prompt reset receipt can consume background round models — cli/src/claude/claudeRemote.ts:905
  • Testing

    Not run (automation; PR code execution is prohibited).

  • The full merge-base diff passed git diff --check. No PR code or tests ran locally.

  • On 0d621ab9, GitHub reported success for fixture drift, CLI and web unit tests, wrapper parity, core, integration, browser, Windows Codex MCP, and Android transcript layout on API 29 and 36.

  • Android protocol tests completed successfully. The Android build job failed after five app unit tests hit a Robolectric Maven artifact download error. APK assembly and lint were skipped.
  • <!-- hapi-pr-review:v2:5a0745461077a769e3a086fe3752aeb0570a5d2cd97976d63eb50f9829f5be01 -->
    HAPI Bot

    github-actions[bot] github-actions[bot] commented on code on Nov 24, 2026 15:24 UTC
    Code Review
    cli/src/claude/claudeRemote.ts:1
    @@ -908,7 +915,10 @@ export async function claudeRemote(opts: {
                 const compact = compactState.active;
                 const isCompactTurnResult = compact !== null
                     && isCommandResult(message, compact.uuid, 'compact', compact.initial && compact.sawCompactSignal);
    -            if (!isClearResult && !isManualCompactBoundaryMessage(message) && !isCompactEchoMessage(message)) {
    +            // A held command result is not shown: its summary would land on a reply
    +            // that arrived while it was held.
    +            const isHeldResult = message === clearFollowUp?.earlyResult;
    +            if (!isClearResult && !isHeldResult && !isManualCompactBoundaryMessage(message) && !isCompactEchoMessage(message)) {

    [Minor] Held command results lose their terminal output

    When a post-/clear command result arrives before its echo and carries result text or an execution error, this guard drops the entire result. The launcher’s onMessage callback also feeds the terminal display, where cli/src/ui/messageFormatterInk.ts:93 renders result text and errors. The command can now finish without showing that output in the terminal.

    Suggested fix

    Keep arrival-time accounting and send the held result through terminal rendering on echo. Suppress transcript summary generation for that result.

    github-actions[bot] github-actions[bot] commented on code on Nov 24, 2026 15:24 UTC
    Code Review
    cli/src/claude/utils/sdkToLogConverter.ts:1
    @@ -722,7 +572,6 @@ export class SDKToLogConverter {
                         durationMs: resultMsg.duration_ms,
                         resultSummary: {
                             usage: resultMsg.usage,
    -                        modelUsage: perRound.modelUsage,

    [Minor] Replies lose token counts when SDK usage is absent

    The SDK result type allows usage to be omitted at cli/src/claude/sdk/types.ts:83. If a result omits it but has comparable per-model counters, such as a single-model reply on a fresh process with a zero baseline, the base converter supplied token counts. Removing modelUsage leaves the footer with its timing and cost but no token line. The existing web test at web/src/chat/conciseView.roundSummary.test.tsx:224 covers rendering a Claude summary with only per-model counts.

    Suggested fix

    Prefer result usage when present. For a result without it, use trustworthy same-round token counts when available and cover the missing-usage case with a regression test.

    github-actions[bot] github-actions[bot] commented on Nov 24, 2026 15:24 UTC
    Reviewer

    ✅ All stages passed (2 Minor)

    Review mode: follow-up after new commits

    Requirement — Pass

    Claude reply footers should show the main model’s token usage for the current round and report that round’s cost and API time. A command result held after /clear should leave a background reply’s footer intact.

    Evidence

  • At the merge base, cli/src/claude/utils/sdkToLogConverter.ts:375 can retain a model entry with input tokens and no output counter. web/src/components/AssistantChat/messages/MessageMetadata.tsx:49 then displays zero output tokens even when the result reports positive output usage.

  • The PR description identifies an ordering bug confirmed by the merge-base path at cli/src/claude/claudeRemote.ts:858, where an older command result is replayed after a newer background result has advanced the usage baseline.
  • Approach — Pass

    Using the result’s round-local usage removes dependence on incomplete cumulative token counters. Accounting for a held command result on arrival preserves the order of cost and API-time snapshots, and suppressing its footer preserves the background reply’s metadata.

    Evidence

  • cli/src/claude/utils/sdkToLogConverter.ts:271 keeps cost and API-time deltas tied to the native session. The summary reads the result’s usage at line 574.

  • cli/src/claude/claudeRemote.ts:875 accounts for the held result on arrival. Echo replay still reaches the turn-completion logic at line 1046.

  • web/src/components/AssistantChat/messages/MessageMetadata.tsx:42 and android/core/protocol/src/main/kotlin/app/hapi/protocol/chat/MessageMetadata.kt:120 already fall back to round-level usage.
  • Code — Reviewed

    The full merge-base diff fixes the reported accounting and footer overwrite bugs. Two display regressions remain for held command output and results with no round-level usage.

  • [Minor] Held command results lose their terminal output — cli/src/claude/claudeRemote.ts:921

  • [Minor] Replies lose token counts when SDK usage is absent — cli/src/claude/utils/sdkToLogConverter.ts:725
  • Testing

    Not run (automation; PR code execution is prohibited).

  • The full merge-base diff passed git diff --check. No PR code or tests ran locally.

  • For eaedb470, GitHub reported success for CLI and web unit tests, wrapper parity, core, integration, and Windows Codex MCP. The browser job was in progress when checked.

  • The new accounting test gives the held command the same cumulative cost and API time as /clear. Giving it nonzero deltas would verify that its accounting is applied before the background result.
  • <!-- hapi-pr-review:v2:5a5bd7f61e07529453985baf6ca7c7b726ff7a745c360f50b94cd6d26952ddaa -->
    HAPI Bot

    github-actions[bot] github-actions[bot] commented on code on Nov 24, 2026 16:09 UTC
    Code Review
    cli/src/claude/utils/sdkToLogConverter.ts:1
    @@ -722,7 +574,6 @@ export class SDKToLogConverter {
                         durationMs: resultMsg.duration_ms,
                         resultSummary: {
                             usage: resultMsg.usage,
    -                        modelUsage: perRound.modelUsage,

    [Minor] Round footers lose token counts when result usage is absent

    The result type permits omitted usage at cli/src/claude/sdk/types.ts:83. For a fresh session’s first single-model reply with complete modelUsage counters and no usage, the base converter could report those counters against its zero baseline. The new summary still carries duration and cost, but the web footer omits the token line because it has neither round-local usage nor per-model counts.

    Suggested fix

    Keep result usage as the primary source. For a result that omits it, populate round usage only where the counters are known to cover that round, such as a complete single-model snapshot against a known zero baseline. Cover that case with a regression test.

    github-actions[bot] github-actions[bot] commented on Nov 24, 2026 16:09 UTC
    Reviewer

    ✅ All stages passed (1 Minor)

    Review mode: follow-up after new commits

    Requirement — Pass

    Claude reply footers should show the main model’s token usage for the current round. A command result held after /clear should preserve the background reply’s footer and the next reply’s cost and API time.

    Evidence

  • At the merge base, cli/src/claude/utils/sdkToLogConverter.ts:375 can retain a model’s input counter when its output counter is absent. web/src/components/AssistantChat/messages/MessageMetadata.tsx:49 then displays zero output tokens even when the round reports positive output usage.

  • At the merge base, cli/src/claude/claudeRemote.ts:859 replays the older command result on echo. That result can replace the background reply’s footer and move the cumulative baseline backwards.
  • Approach — Pass

    The result’s round-local usage avoids incomplete cumulative token counters. Accounting for a held result on arrival preserves the order of cost and API-time snapshots. Forwarding it on echo preserves terminal output and turn completion while suppressing the misplaced footer.

    Evidence

  • cli/src/claude/utils/sdkToLogConverter.ts:271 keeps cumulative deltas scoped to the native session. The summary uses round-local usage at line 576.

  • cli/src/claude/claudeRemote.ts:879 accounts for the held result on arrival. Lines 864–866 mark it on echo, and cli/src/claude/utils/sdkToLogConverter.ts:563 skips its summary.

  • web/src/components/AssistantChat/messages/MessageMetadata.tsx:42 and android/core/protocol/src/main/kotlin/app/hapi/protocol/chat/MessageMetadata.kt:120 already support round-local usage.
  • Code — Reviewed

    The current head restores terminal output for held commands and adds coverage for their accounting order. One token display regression remains when a result omits usage.

  • [Minor] Round footers lose token counts when result usage is absent — cli/src/claude/utils/sdkToLogConverter.ts:725
  • Testing

    Not run (automation; PR code execution is prohibited).

  • The merge-base diff passed git diff --check. No PR code or tests ran locally.

  • GitHub reported success for core, wrapper-parity, windows-codex-mcp, unit-cli, and integration at c1681495ec831baa8ece661df750a61dda335ac5. Unit-web and browser were in progress when checked.
  • <!-- hapi-pr-review:v2:ce0328d5abb24a5b5fc8a179c95e51c16ad3356a1cbced7deea004c676cb1cdb -->
    HAPI Bot

    github-actions[bot] github-actions[bot] commented on code on Nov 25, 2026 00:44 UTC
    Code Review
    cli/src/claude/utils/sdkToLogConverter.ts:1
    @@ -722,7 +578,6 @@ export class SDKToLogConverter {
                         durationMs: resultMsg.duration_ms,
                         resultSummary: {
                             usage: resultMsg.usage,
    -                        modelUsage: perRound.modelUsage,

    [Minor] Fresh replies can lose available token counts

    The SDK result type permits omitted usage at cli/src/claude/sdk/types.ts:83. If the first reply in a fresh single-model session supplies complete modelUsage counters but omits usage, those counters cover that round and the base converter emits them from its known zero baseline. The new summary drops them, so the web and Android footers omit the token line.

    Suggested fix

    Keep result usage as the primary source. When it is absent, populate round usage from a complete single-model snapshot only when the converter can establish that it covers the round, such as the first result from a known fresh process. Add a regression test for that case.

    github-actions[bot] github-actions[bot] commented on Nov 25, 2026 00:44 UTC
    Reviewer

    ✅ All stages passed (1 Minor)

    Review mode: follow-up after new commits

    Requirement — Pass

    Claude reply footers should show the main model’s tokens for the current round. A command result held after /clear should preserve the background reply’s footer and the next reply’s cost and API time.

    Evidence

  • At the merge base, cli/src/claude/utils/sdkToLogConverter.ts:375 can retain a model’s input counter without an output counter. web/src/components/AssistantChat/messages/MessageMetadata.tsx:49 then displays zero output tokens even when the result reports positive round usage.

  • At the merge base, cli/src/claude/claudeRemote.ts:859 replays the older command result on echo. That can move the cumulative baseline backwards and replace the latest assistant group’s footer at web/src/chat/reducerTimeline.ts:609.
  • Approach — Pass

    Using the result’s round-local usage avoids incomplete cumulative token counters. Accounting for a held command on arrival preserves snapshot order, and forwarding it on echo preserves terminal output and turn completion while suppressing its misplaced footer.

    Evidence

  • cli/src/claude/utils/sdkToLogConverter.ts:271 keeps cost and API-time deltas scoped to the native session. The summary uses the result’s usage at line 580.

  • cli/src/claude/claudeRemote.ts:879 accounts for the held result on arrival. Line 865 marks it on echo, and cli/src/claude/utils/sdkToLogConverter.ts:563 skips its summary.

  • Web and Android already support summaries that carry round-level usage at web/src/components/AssistantChat/messages/MessageMetadata.tsx:42 and android/core/protocol/src/main/kotlin/app/hapi/protocol/chat/MessageMetadata.kt:120.
  • Code — Reviewed

    The full merge-base diff addresses the reported accounting and footer overwrite bugs. The latest commit documents the missing-usage behavior, and one token display regression remains.

  • [Minor] Fresh replies can lose available token counts — cli/src/claude/utils/sdkToLogConverter.ts:725
  • Testing

    Not run (automation; PR code execution is prohibited).

  • The fixed merge-base diff passed git diff --check. No PR code or tests ran locally.

  • GitHub reported success for core, integration, unit-cli, wrapper-parity, and windows-codex-mcp at 20924b7a. Unit-web and browser were still running when checked.

  • The new tests cover incomplete per-model counters when round usage is present and the held-command ordering case. They do not cover a first fresh result with complete per-model counters and omitted usage.
  • <!-- hapi-pr-review:v2:19eb4155866feaeb6353d3f9026c71cd95c1be48cf3d407511224f450d5f5c53 -->
    HAPI Bot

    Assignees
    junmo-kim junmo-kim
    Labels
    risk: low confidence: 73.5% reviewed sensitive_module
    Vouch Risk Breakdown
    AI-powered review risk analysis
    Change Risk
    Change Risk · Model 1 (XGBoost)
    Predicted defect probability (0.00–1.00) based on diff churn, modified sensitive files, and author risk history.
    Score: 77% (HIGH) · Higher = larger blast radius
    77%
    Review Confidence
    Review Confidence · Models 2 & 3
    Scrutiny score (0.00–1.00) combining DistilBERT semantic review depth with reviewer familiarity and session dwell time.
    Score: 73.5% · Lower = rushed or shallow review
    73.5%
    Residual Risk
    Residual Risk · Core Equation
    Residual = Change × (1 − Confidence)
    Unmitigated risk surviving review. ≥ 0.65 triggers an automated re-queue to protect production.
    Score: 20.4% · Safe to merge
    20.4%
    Repository