Skip to content

fix: preserve OpenCode provider-reported costs in metrics - #3780

Merged
integry merged 8 commits into
integry:mainfrom
czehentner:fix/opencode-cost-reporting
Dec 1, 2026
Merged

integry merged 8 commits into
integry:mainfrom
czehentner:fix/opencode-cost-reporting

Conversation

@czehentner

@czehentner czehentner commented Nov 24, 2026 •

Copy link
Copy Markdown
Contributor

Summary

refs #3781

OpenCode reports the provider's actual cost in step_finish events (part.cost). That value was dropped at parse time, so metrics fell back to model-catalog pricing. Custom LiteLLM model ids have no catalog entry, so llm_executions.cost_usd became 0 and llm_logs.cost_usd became NULL, even though token counts were recorded correctly.

Root cause (verified against current code)

  1. parseOpenCodeJsonl() aggregated tokens only and never read cost.
  2. OpenCodeAgent therefore had no cost to put on AgentExecutionResult, and never passed one to createLlmLogFromAgentExecution().
  3. toClaudeResult() (and the other AgentExecutionResult/ClaudeCodeResponse → ClaudeResult adapters) did not forward a cost.
  4. calculateCost() in llmMetrics.ts only used the catalog, falling back to finalResult.*cost* (never set for OpenCode); persistLlmLog() then computed a catalog estimate that returns undefined for unknown models → NULL.

Changes

  • openCodeParsing.ts: extract cost.
    • step_finish parts add their own cost; a repeated part id is counted once.
    • result events carry a running total, which replaces the step sum (max over snapshots) so nothing is double-counted.
    • Missing, malformed, negative, non-finite or non-numeric values are ignored; an explicit 0 is a real cost; no cost → undefined.
  • OpenCodeAgent.ts: sets cost/providerCostUsd on the result and costUsd on both log paths (execution and analysis).
  • New optional providerCostUsd on AgentExecutionResult, ClaudeCodeResponse and ClaudeResult, forwarded by the issue, PR-comment, error-handler, goal-metrics and failed-execution adapters.
  • llmMetrics.ts: a valid provider cost is preferred over the catalog estimate; otherwise the existing logic is unchanged.
  • llmLogger.ts: createLlmLogFromAnalysis accepts costUsd (the existing persistLlmLog already keeps a provided cost, including 0).

Token accounting (including cache-read handling) is untouched. Other agents never set providerCostUsd, so their behaviour is unchanged.

Tests

  • test/opencodeCostReporting.test.ts: multiple step_finish sums, duplicate parts, cumulative totals without double counting, explicit zero vs missing, invalid values, non-cost events, unchanged token usage, toClaudeResult() / failure adapters / log-entry propagation.
  • test/llmMetricsProviderCost.test.ts: custom model unknown to the catalog, provider cost beats catalog, reported zero, invalid costs fall back, catalog fallback preserved.
  • Existing OpenCode, llmLogger, llmMetrics* suites still pass (llmMetrics.test.ts needs a live Redis and was not run). npx tsc --noEmit (core) and eslint src/ are clean.

Before / after

before after
llm_executions.cost_usd 0.00 provider total (e.g. 0.8750 for three steps of 0.25 + 0.5 + 0.125)
llm_logs.cost_usd NULL same total

Limitations

  • If only some step_finish events carry a cost, the known costs are summed (an undercount, but better than 0).
  • Cost is taken from step_finish parts and result summary events only.

…tence

OpenCode step_finish events carry the provider's actual cost in part.cost,
but the parser dropped it and the metrics pipeline fell back to catalog
pricing, which custom LiteLLM model ids do not have. The result was a zero
llm_executions cost and a NULL llm_logs cost.

Parse per-step costs (counted once per part id) and cumulative result
totals (replace, never add), carry the value as providerCostUsd through
AgentExecutionResult, ClaudeCodeResponse and ClaudeResult, and prefer a
valid reported cost over the catalog estimate. Missing and invalid costs
fall back to the existing behaviour; a reported zero is kept.

Co-authored-by: Copilot <[email protected]>
@czehentner
czehentner marked this pull request as draft November 24, 2026 09:27
@integry integry added the AI label Nov 24, 2026
@integry
integry marked this pull request as ready for review November 24, 2026 10:26
@integry

integry commented Nov 24, 2026

Copy link
Copy Markdown
Owner

/review astra fable

@propr-dev

propr-dev Bot commented Nov 24, 2026 •

Copy link
Copy Markdown
Contributor

✅ AI Code Review Complete requested by @integry

Posted 2 reviews:

View Task Details

@propr-dev

propr-dev Bot commented Nov 24, 2026

Copy link
Copy Markdown
Contributor

🔍 AI Code Review — astra

Overall Evaluation

This PR needs changes before merge. It carries OpenCode’s reported cost through task execution and several job adapters, but PR reviews still lose that cost. The parser can also promote a partial step subtotal to the authoritative price for a whole run. The visible objective identifies missing detail records on large executions, and the PR leaves that part unresolved. The supplied issue description ends mid-section, so its remaining acceptance criteria could not be assessed.

✅ Reported zero survives — The task adapters preserve an explicit 0, and calculateCost() returns it before looking up catalog pricing.

✅ Repeated steps are counted once — The parser deduplicates reported step costs by part ID. A focused test covers a repeated part followed by a distinct billable step.

Merge blockers

Every finding below was introduced by this PR and must be resolved before merging.

F1: 🔴 PR review executions still lose provider cost

  • Category: correctness

  • Required behavior: A review execution using a custom OpenCode model must retain its reported cost when the review job records execution metrics.

  • Evidence: packages/core/src/agents/impl/OpenCodeAgent.ts:184, OpenCodeAgent.analyze

    static trace:

    1. An OpenCode review emits a valid step_finish cost of $1.25. analyze() passes it to its internal logger when logging is enabled, then returns analysis.result.
    2. evaluateOpenCodeAnalysis() constructs both its success and failure results with token usage but no cost. src/jobs/reviewResultMetrics.ts:29 builds the execution metrics from that returned result.
    3. recordLLMMetrics() therefore receives no providerCostUsd. For an unlisted model, the review execution still records $0. When suppressLlmLog is enabled, the caller responsible for the authoritative log also receives no cost.

    The new log-builder tests pass costUsd directly. They bypass the analyze() return boundary where the value disappears.

  • Minimum fix: Add optional providerCostUsd to AnalysisResult, populate it from parsedOutput.cost on success and failure, and forward it wherever the returned analysis supplies review execution metrics or the authoritative log. Cover a review using an unlisted model.

F2: 🔴 A partial step subtotal overrides whole-run pricing

  • Category: correctness

  • Required behavior: Only a cost covering the execution may override the catalog estimate for all of its tokens.

  • Evidence: packages/core/src/agents/impl/openCodeParsing.ts:64, applyOpenCodeCost, and packages/core/src/utils/llmMetrics.ts:103

    static trace:

    1. One step_finish reports an explicit cost of 0. A second, distinct step reports billable tokens and omits part.cost. The run emits no cumulative cost. Both step shapes appear in the new parser tests.
    2. The parser accumulates tokens for both steps. It skips the missing cost and returns the first step’s 0 as the execution cost.
    3. OpenCodeAgent forwards that 0 to logging and metrics. Even for a priced model, calculateCost() returns zero before consulting the catalog. The second step’s usage disappears from the execution price.

    The finite-number check validates individual values. It cannot establish that every billable step contributed one. The tests cover all-zero and all-missing runs separately.

  • Minimum fix: Track whether each distinct step with billable usage has a valid cost, accounting for repeat events with the same ID. Prefer a reported cumulative total. Otherwise expose the step sum as authoritative only when coverage is complete, preserving the existing fallback for incomplete runs.

F3: 🔴 Large-execution detail persistence remains unresolved

  • Category: requirement

  • Required behavior: Issue Bug: OpenCode provider-reported costs are lost, and large executions may have missing detail records #3781 explicitly includes a long execution whose summary persisted without associated llm_execution_details.

  • Evidence: packages/core/src/utils/llmMetrics.ts:92 and test/llmMetricsProviderCost.test.ts:32

    static trace:

    1. The production metrics change selects the execution cost. It leaves the detail-writing path unchanged.
    2. Every new persistence test supplies conversationLog: [] and inspects only llm_executions.cost_usd. The existing detail persistence test exercises a single event.
    3. The existing claim-recovery test permits a summary to survive a failed detail insert. The PR provides neither a large-log reproduction nor evidence that the reported case already persists its details. Merging as a fix for Bug: OpenCode provider-reported costs are lost, and large executions may have missing detail records #3781 would leave this visible objective unresolved.

    The supplied evidence establishes the delivery gap. It does not establish what caused the original detail insert to fail.

  • Minimum fix: Exercise the detail writer with a representative large OpenCode conversation and assert that the expected sequence of rows is linked to the persisted execution. Use that result to fix the demonstrated failure or establish that the current writer already handles the reported case.

Suggestions

These are optional follow-ups and are not sent to /fix.

S1: 🟢 Test the stored log cost

The log tests stop at the object returned by createLlmLogFromAgentExecution() or createLlmLogFromAnalysis(). A persistence-level assertion for $1.25 and an explicit $0 on an unlisted model would cover the llm_logs.cost_usd column named in the issue. This is additional coverage for a separate boundary where the supplied diff establishes no write defect.

Score

The task path handles reported zero and duplicate steps correctly, but review executions and mixed-cost runs can still record the wrong price. Large-run detail persistence remains unverified, and all three current head checks were skipped.

Score: 5/10


🤖 Review Details

  • Model: GPT-6.2 Astra
  • Time: 43s
  • Tokens: 52,791 (51,426 in / 1,365 out)
  • Cost: $0.36

View Task


💡 Next step: Comment /fix to address every F# merge blocker, /fix all for every pending blocker and suggestion, or name records explicitly, as in /fix F3 S5.
F# and S# IDs increment across review comments and remain permanent, so selectors such as /fix F3 F5 stay unambiguous across cycles. S# suggestions stay optional: they are implemented only when you name them or request /fix all, and they never relax a merge blocker.

Copy and edit to choose records from this review:

/fix F1 F2 F3 S1

🤖 Review by ProPR

@propr-dev

propr-dev Bot commented Nov 24, 2026

Copy link
Copy Markdown
Contributor

🔍 AI Code Review — fable

Overall Evaluation

The PR reads the cost OpenCode emits on step_finish parts, carries it as a new providerCostUsd field through every AgentExecutionResult/ClaudeCodeResponse → ClaudeResult adapter in the diff, and makes calculateCost() prefer it over the pricing catalog. It also passes the cost to the llm_logs entry builders. For the reported scenario (implementation run, custom LiteLLM model id, non-zero part.cost), the static trace reaches llm_executions.cost_usd correctly.

I found no verified blocker in the changed code. I would not call it merge-ready yet, for three reasons:

  • No CI ran on this head. All three checks are skipped, so tests, typecheck and lint are unconfirmed, and I ran nothing in this review.
  • The llm_logs half is unverified. persistLlmLog() and createLlmLogFromAgentExecution() are not in the supplied context. I could not confirm that a supplied costUsd (including 0) skips the catalog estimate, or that createLlmLogFromAgentExecution forwards costUsd — the diff adds the field only to createLlmLogFromAnalysis.
  • The "reported zero beats the catalog" rule may erase existing estimates (S1). This needs a maintainer decision before merge.

The issue and PR descriptions are truncated in the supplied context, so I could not check the full acceptance criteria.

✅ Separate field for "reported" versus "estimated" — providerCostUsd is absent when nothing was reported, forwarded with !== undefined spreads so 0 survives, and re-validated (finite, non-negative) in reportedProviderCost() before it overrides anything.

✅ Additive step costs with repeat protection — applyOpenCodeCost() sums per-step costs, counts a repeated part id once, and ignores negative, non-finite and non-numeric values; opencodeCostReporting.test.ts covers each of these and confirms token accounting is unchanged.

✅ Failure paths keep the spend — failedExecutionResult(), persistFailedExecutionLog() and agentResultToMetricsResult() all carry the cost, and executeTask sets it on non-zero-exit and timeout results too.

Merge blockers

No merge blockers.

Suggestions

These are optional follow-ups and are not sent to /fix.

S2: 🟢 Confirm a reported zero is really a cost

calculateCost() now returns a provider cost of 0 ahead of the catalog, and parseOpenCodeJsonl() yields 0 whenever every step reports cost: 0. As far as I know (not verifiable from the supplied code), OpenCode computes part.cost locally from the model's configured pricing and emits 0 when it has none. That would cover a custom provider without a cost block and subscription/OAuth-backed models. If so, OpenCode runs on models ProPR's catalog can price would drop from a catalog estimate to $0.00 after this PR. Please check this against real OpenCode output before merging. If it holds, the safer rule is to prefer the provider cost only when it is positive and fall back to the catalog when it is 0.

S3: 🟢 Analysis runs still record $0 executions

OpenCodeAgent.analyze() passes parsedOutput.cost to its llm_logs row, but evaluateOpenCodeAnalysis() (unchanged) does not put it on AnalysisResult. Consumers such as src/jobs/reviewResultMetrics.ts therefore call recordLLMMetrics without providerCostUsd. OpenCode PR reviews on an unlisted model will still show llm_executions.cost_usd = 0. Adding an optional providerCostUsd to AnalysisResult and forwarding it would close this; I left it as optional because the visible objective centres on task executions.

S4: 🟢 Issue's missing-detail-records half is untouched

Issue #3781 also reports an execution with a summary row but no llm_execution_details. Nothing in this diff addresses that, yet "fixes #3781" will close the issue on merge. Consider "refs #3781" or a separate issue for the details problem, unless the truncated description already scopes it out.

S5: 🟢 result-event cost branch looks speculative

applyOpenCodeCost() handles a result event with six key aliases across three locations (event, stats, usage). The issue only describes part.cost on step_finish. The branch mirrors the existing token handling, so it is defensible, but a result carrying cost: 0 would override a positive step sum via cumulativeCost ?? stepCost. Either drop the branch until such an event is observed, or take the larger of the two values.

S6: 🟢 Add an agent-level wiring test

The new tests cover the parser, the adapters and recordLLMMetrics, but not the wiring in OpenCodeAgent.executeTask/analyze. test/opencodeExecutionLog.test.ts already mocks executeDockerCommand and persistLlmLog; one case feeding step_finish stdout and asserting entry.costUsd and response.providerCostUsd would cover it. It would also settle the open question about createLlmLogFromAgentExecution.

S7: 🟢 Reuse firstNumber for cost parsing

parseOpenCodeCost/firstOpenCodeCost largely repeat the number-or-numeric-string logic of the existing firstNumber in the same file, adding only a non-negative check. Sharing one coercion helper would keep the two paths from drifting; this is cosmetic.

Score

No verified code blocker, and the main execution-cost path is correct with good tests. But no checks ran on this head, the llm_logs persistence is unverifiable from the supplied context, and the zero-cost precedence (S1) should be confirmed before merge.

Score: 7/10


🤖 Review Details

  • Model: Claude Fable 5.2
  • Time: 1m 33s
  • Tokens: 82,154 (73,433 in / 8,721 out)
  • Cost: $1.08

View Task


💡 Next step: Comment /fix to address every F# merge blocker, /fix all for every pending blocker and suggestion, or name records explicitly, as in /fix F3 S5.
F# and S# IDs increment across review comments and remain permanent, so selectors such as /fix F3 F5 stay unambiguous across cycles. S# suggestions stay optional: they are implemented only when you name them or request /fix all, and they never relax a merge blocker.

Copy and edit to choose records from this review:

/fix S2 S3 S4 S5 S6 S7

🤖 Review by ProPR

czehentner and others added 2 commits November 24, 2026 13:21
- Propagate providerCostUsd through AnalysisResult, review metrics, and suppressLlmLog analysis callers
- Avoid overriding catalog pricing with partial step-cost subtotals or letting a zero cumulative summary erase positive step costs
- Refactor OpenCodeAgent.executeTask, applyOpenCodeCost, and calculateCost to satisfy ESLint complexity and max-lines rules
- Add regression tests for partial/cumulative cost edge cases, review metrics, and OpenCodeAgent executeTask/analyze wiring

Co-authored-by: Copilot <[email protected]>
Summary miners suppress the agent's own log and write one llm_logs row per
batch, so the provider cost returned on AnalysisResult was dropped. Sum it
across every retry and fallback call; when any call returns no cost, leave
it unset so the catalog estimate still applies instead of a partial sum.

Adds real-SQLite tests asserting llm_logs.cost_usd for summed retries,
partial coverage, an explicit zero, and a failed keyword extraction call.

Co-authored-by: Copilot <[email protected]>
@integry

integry commented Nov 24, 2026

Copy link
Copy Markdown
Owner

/review astra fable

@propr-dev

propr-dev Bot commented Nov 24, 2026 •

Copy link
Copy Markdown
Contributor

✅ AI Code Review Complete requested by @integry

Posted 2 reviews:

View Task Details

@propr-dev

propr-dev Bot commented Nov 24, 2026

Copy link
Copy Markdown
Contributor

🔍 AI Code Review — astra

Overall Evaluation

The PR carries OpenCode costs through execution and analysis results into both metrics tables. It needs changes before merge. Two parser branches contradict the stated cost rules, and the new batch accounting can persist a partial retry cost as the full charge. The current head has 20 passed checks and no failed or pending checks.

✅ Provider pricing takes precedence — calculateCost() returns a valid provider cost before looking up catalog pricing. The persistence tests cover an unlisted model, an explicit zero, and fallback when the value is invalid.

✅ Execution and analysis both propagate cost — The agent-level test follows two priced steps through executeTask() and analyze() and checks that each result and its log entry receive the same $1.25 total.

Merge blockers

Every finding below was introduced by this PR and must be resolved before merging.

F4: 🔴 An unpriced step discards known spend

  • Category: requirement

  • Required behavior: The objective explicitly says to sum the known costs when only some step_finish events report a cost.

  • Evidence: packages/core/src/agents/impl/openCodeParsing.ts, recordUnpricedOpenCodeStep and resolveOpenCodeCost. static trace:

    1. An unlisted model emits a step costing $0.25, followed by a step with token usage and no cost. There is no cumulative result.
    2. The parser retains 0.25 in stepCost, but the second step's ID makes completeStepCost undefined.
    3. Neither persistence path receives the known $0.25. Without catalog pricing, the execution falls back to zero and the log to NULL.

    The new partial-subtotal test in test/opencodeCostReporting.test.ts explicitly expects this loss, so passing it confirms the discrepancy.

  • Minimum fix: When no valid cumulative total exists, return the deduplicated sum of valid step costs. Remove the unnecessary unpriced-step bookkeeping and update the mixed-coverage test to expect the known subtotal.

F5: 🔴 A reported zero total loses precedence

  • Category: correctness

  • Required behavior: A valid cumulative result replaces the step sum, and an explicit zero is a valid reported cost.

  • Evidence: packages/core/src/agents/impl/openCodeParsing.ts, resolveOpenCodeCost. static trace:

    1. Two steps report $0.25 and $0.50. The sole result event reports a cumulative cost of $0.
    2. The parser accepts zero into cumulativeCost, then takes a special branch that returns the $0.75 step subtotal.
    3. Both metrics paths receive $0.75 as the provider total. Their downstream zero handling cannot recover the discarded summary value.

    test/opencodeCostReporting.test.ts contains this exact input and asserts $0.75, contrary to the stated precedence.

  • Minimum fix: Return cumulativeCost whenever it is defined, retaining the maximum over valid snapshots. Update the zero-summary test to expect zero.

F6: 🔴 Synthetic failover hides charged attempts

  • Category: correctness

  • Required behavior: A provider total on a caller-owned analysis log must cover the physical attempts represented by that log.

  • Evidence: packages/core/src/services/relevance/summaryMinerBatch.ts:416, packages/core/src/services/relevance/summaryMinerDirectoryBatch.ts:411, packages/core/src/services/relevance/keywordExtractor.ts:271, and packages/core/src/services/relevance/semanticScorer.ts:214. static trace:

    1. A synthetic route selects an OpenCode agent. Its analysis returns a retryable failure with a $0.25 provider cost. evaluateOpenCodeAnalysis preserves cost on failed results.
    2. SyntheticRoutingSession.analyze() handles that failure internally, selects another agent, and returns its successful $0.50 result. The first result never reaches the caller.
    3. The file and directory trackers see one priced result and consider coverage complete. Keyword extraction and semantic scoring likewise copy only the returned cost. The caller-owned log records $0.50 for $0.75 of reported spend.

    The batch fallback test exercises retries visible to the caller. It does not exercise the internal failover loop in syntheticRoutingService.ts:152–174.

  • Minimum fix: Aggregate physical-attempt costs within each routed analyze() invocation and expose that aggregate to all four callers. Preserve zero and leave the aggregate undefined when an attempt's cost is unknown. Add a routed failure-then-success test.

F7: 🔴 Rejected attempts bypass batch tracking

  • Category: correctness

  • Required behavior: The new batch tracker promises to leave the provider total unknown when it lacks cost coverage across retries and fallback.

  • Evidence: packages/core/src/services/relevance/summaryMinerBatch.ts:416, packages/core/src/services/relevance/summaryMinerDirectoryBatch.ts:411, and packages/core/src/services/relevance/summaryMinerMetrics.ts, trackedProviderCost. static trace:

    1. An awaited agent.analyze() or routingSession.analyze() rejects with a retryable error before returning cost information.
    2. withRetry() invokes the callback again. The successful retry reports $0.50. Since trackProviderCost() runs only after the await resolves, the tracker has one call and complete === true.
    3. The batch log persists $0.50 as a fully reported total even though the first attempt's charge is unknown. The same omission survives a switch to fallback because both agents share the tracker.

    The missing-cost test covers a resolved result with an absent field. A rejection skips that check entirely.

  • Minimum fix: In both batch paths, mark cost coverage incomplete when the analysis invocation rejects, then rethrow so existing retry handling continues. Keep this handling scoped to the invocation so a later parsing error still preserves an already reported charge.

Suggestions

These are optional follow-ups and are not sent to /fix.

S8: 🟢 Exercise non-finite JSON input directly

The non-finite parser fixture passes Infinity through JSON.stringify, which serializes it as null. A raw JSONL line containing 1e309 would exercise the finite-number guard directly. This is optional because the guard is already present and the suite separately covers null.

Score

The direct execution and analysis paths have good coverage, and all current checks are green. The parser discrepancies and incomplete retry accounting still affect the persisted costs this PR is intended to correct.

Score: 5/10


🤖 Review Details

  • Model: GPT-6.2 Astra
  • Time: 46s
  • Tokens: 61,282 (59,741 in / 1,541 out)
  • Cost: $0.43

View Task


💡 Next step: Comment /fix to address every F# merge blocker, /fix all for every pending blocker and suggestion, or name records explicitly, as in /fix F3 S5.
F# and S# IDs increment across review comments and remain permanent, so selectors such as /fix F3 F5 stay unambiguous across cycles. S# suggestions stay optional: they are implemented only when you name them or request /fix all, and they never relax a merge blocker.

Copy and edit to choose records from this review:

/fix F4 F5 F6 F7 S8

🤖 Review by ProPR

@propr-dev

propr-dev Bot commented Nov 24, 2026

Copy link
Copy Markdown
Contributor

🔍 AI Code Review — fable

Overall Evaluation

This PR carries OpenCode's reported cost from step_finish parsing through AgentExecutionResult/AnalysisResult, the ClaudeResult adapters, calculateCost() and both llm_logs paths. I traced each path statically from the supplied diff (nothing was executed) and found no reachable failure in the changed behaviour. All current-head checks pass. The PR is ready to merge within scope; the items below are optional.

✅ Cost is never double-counted or silently partial — applyOpenCodeCost in packages/core/src/agents/impl/openCodeParsing.ts dedupes repeated part ids. resolveOpenCodeCost withholds a step sum when a token-bearing step has no valid cost, and a later priced repeat of the same id completes coverage. Each branch has a test in test/opencodeCostReporting.test.ts.

✅ Zero versus absent is preserved end to end — every adapter forwards with !== undefined rather than truthiness, and reportedProviderCost in llmMetrics.ts rejects negative, NaN and infinite values before falling back. test/llmMetricsProviderCost.test.ts proves this with a catalog stub returning 99.

✅ Other agents are unaffected — only OpenCode sets providerCostUsd. In the summarization tracker, any call without a cost marks the batch incomplete, so non-OpenCode and mixed-agent batches keep the existing catalog estimate.

Merge blockers

No merge blockers.

Suggestions

These are optional follow-ups and are not sent to /fix.

S9: 🟢 Reported zero may mean "price unknown"

The PR treats an explicit 0 as a real cost that beats the catalog estimate, exactly as the objective specifies. As far as I know (not verifiable from the supplied code), OpenCode computes part.cost from its own model price table and emits 0 when it has no price for a model. If so, an OpenCode model that OpenCode cannot price but ProPR's catalog can (for example via toOpenCodeGoOpenRouterId) would now record 0 instead of the previous estimate. It is worth checking against a real run of such a model. If confirmed, prefer the catalog estimate when the reported cost is 0, tokens are non-zero and catalog pricing exists. This is optional because the behaviour matches the stated objective.

S10: 🟢 PR description contradicts the partial-cost behaviour

The Limitations section says that when only some step_finish events carry a cost, "the known costs are summed (an undercount, but better than 0)". The code does the opposite: resolveOpenCodeCost returns undefined, and the test "does not promote a partial step subtotal" pins that. The code's behaviour is the safer one; update the description so operators are not misled. The description also omits the relevance-service changes (keyword extractor, semantic scorer, summary miner batches) and the new AnalysisResult.providerCostUsd field.

S11: 🟢 Tracker misses attempts that never return

trackProviderCost in summaryMinerBatch.ts and summaryMinerDirectoryBatch.ts runs only after analyze returns. An attempt that throws is not counted, and neither are failed attempts consumed inside SyntheticRoutingSession.analyze's failover loop. The tracker therefore stays complete and the logged total can omit those attempts, despite its doc comment saying it sums every call. The practical effect is small because such attempts rarely report a cost. Either mark the tracker incomplete in a catch around the analyze call, or soften the comment.

S12: 🟢 Cost validity predicate is written three times

"Finite, non-negative number" is implemented separately in parseOpenCodeCost (openCodeParsing.ts), reportedProviderCost (llmMetrics.ts) and trackProviderCost (summaryMinerMetrics.ts). A single shared helper would keep them from drifting. This is cosmetic.

S13: 🟢 Speculative result-event cost handling

applyOpenCodeCost reads six key spellings across event, event.stats and event.usage for result events, plus a special case for a zero cumulative total. The objective lists result totals, so this is in scope. If real opencode run --format json output never emits such an event, the branch could be reduced to shapes actually observed. A cumulative total lower than a complete step sum also currently wins; taking the larger of the two would be more defensive.

S14: 🟢 Unrelated compaction in calculateCost

llmMetrics.ts now passes { ...tokens, totalTokens } to calculateCostWithCachePricing instead of listing fields, and joins a logger call onto one line. The result is equivalent, but the spread now forwards any extra fields on CumulativeTokenUsage. This is harmless today; keep it in mind if that type grows.

Score

The change delivers the objective with correct propagation on every adapter and log path, careful handling of zero, absent and partial costs, and focused tests, with all current-head checks green. Remaining items are a description mismatch and optional hardening.

Score: 8/10


🤖 Review Details

  • Model: Claude Fable 5.2
  • Time: 1m 3s
  • Tokens: 94,264 (88,188 in / 6,076 out)
  • Cost: $1.12

View Task


💡 Next step: Comment /fix to address every F# merge blocker, /fix all for every pending blocker and suggestion, or name records explicitly, as in /fix F3 S5.
F# and S# IDs increment across review comments and remain permanent, so selectors such as /fix F3 F5 stay unambiguous across cycles. S# suggestions stay optional: they are implemented only when you name them or request /fix all, and they never relax a merge blocker.

Copy and edit to choose records from this review:

/fix S9 S10 S11 S12 S13 S14

🤖 Review by ProPR

@integry

integry commented Nov 24, 2026

Copy link
Copy Markdown
Owner

/fix F4 F5 F6 F7

@propr-dev

propr-dev Bot commented Nov 24, 2026 •

Copy link
Copy Markdown
Contributor

✅ Applied the requested follow-up changes in commit e82d9c6

Addressed 1 AI review comment (IDs: 7136692400)

Addressed findings F4, F5, F6, F7

Summary of Changes

Applied F4–F7 for PR #3780.

  • OpenCode sums deduplicated, valid step costs when no cumulative total is available. A valid cumulative total takes precedence, including $0.
  • Synthetic routing returns the combined cost of all physical analysis attempts to all four callers. If any attempt’s cost is unknown, the combined total is unknown.
  • File and directory batches mark cost coverage incomplete when analysis rejects. A later parsing failure preserves any cost the analysis already reported.

All six targeted test suites passed. Core type checking and linting for the changed source files passed. The LLM Log preview shows the verified $0.750 failover total.

Separate observations outside the selected fixes: the LLM Logs API maps stored zero costs to null, the routing details display raw model IDs, and PR review comments still calculate cost from catalog pricing.

Review digest

Risk-tiered paths

  • High risk: none
  • Normal risk (5 files)
    • packages/core/src/agents/impl/openCodeParsing.ts (+3/−41)
    • packages/core/src/services/relevance/summaryMinerBatch.ts (+4/−5)
    • packages/core/src/services/relevance/summaryMinerDirectoryBatch.ts (+4/−5)
    • packages/core/src/services/relevance/summaryMinerMetrics.ts (+18/−7)
    • packages/core/src/services/syntheticRoutingService.ts (+8/−4)
  • Low risk (2 files)
    • test/opencodeCostReporting.test.ts (+7/−7)
    • test/summaryMinerBatchFallback.test.ts (+126/−0)

Diff size: 7 files changed, +170/−69 lines

Visual preview

Routed summarization cost in the LLM Log

Routed summarization cost in the LLM Log

The Usage column shows $0.750 for a summarization call whose two physical attempts reported $0.25 and $0.50.

Full-size original


🤖 Implementation Details

  • Model: GPT-6.2 Sol (medium)
  • Requested By: @integry
  • Time: 9m 41s
  • Tokens: 2,414,871 (2,402,233 in / 12,638 out)
  • Cost: $0.54
  • Subscription usage: Weekly +1%

Undo Changes • View Task Execution


💡 ProPR Slash Commands
Command Description Example
/merge Merge target branch into this PR and resolve conflicts /merge
/review Request an AI code review /review or /review claude-sonnet
/fix Address review blockers, or blockers and suggestions with /fix all /fix, /fix all, or /fix F3 S5
/switch Change the AI model for this PR /switch claude-opus
/use Override the model for a single follow-up run /use claude-sonnet
/ultrafix Loop review→fix cycles until score goal is met /ultrafix or /ultrafix goal=8 max=10

🤖 Generated by ProPR
Processing comment ID: 7138343005✓

Applied F4–F7 for PR integry#3780.

- OpenCode sums deduplicated, valid step costs when no cumulative total is available. A valid cumulative total takes precedence, including `$0`.
- Synthetic routing returns the combined cost of all physical analysis attempts to all four callers. If any attempt’s cost is unknown, the combined total is unknown.
- File and directory batches mark cost coverage incomplete when analysis rejects. A later parsing failure preserves any cost the analysis already reported.

All six targeted test suites passed. Core type checking and linting for the changed source files passed. The LLM Log preview shows the verified `$0.750` failover total.

Separate observations outside the selected fixes: the LLM Logs API maps stored zero costs to `null`, the routing details display raw model IDs, and PR review comments still calculate cost from catalog pricing.

PR: integry#3780
Comment by: @integry (ID: 7138343005)
Model: GPT-6.2 Sol

ProPR-Agent: codex/gpt-6.2-sol
@integry

integry commented Nov 24, 2026

Copy link
Copy Markdown
Owner

/review astra

@propr-dev

propr-dev Bot commented Nov 24, 2026 •

Copy link
Copy Markdown
Contributor

✅ AI Code Review Complete requested by @integry

Posted 1 review:

View Task Details

@propr-dev

propr-dev Bot commented Nov 24, 2026

Copy link
Copy Markdown
Contributor

🔍 AI Code Review — astra

Overall Evaluation

The PR needs a localized correction before merge. It carries OpenCode’s reported cost through execution and analysis, but synthetic routing still loses known spend when every member returns a retryable failure.

✅ Zero survives propagation — The parser, result adapters, and metrics calculation preserve an explicit 0. An unlisted model can therefore record a free execution without a catalog lookup.

✅ Repeated events are handled correctly — Replayed step IDs count once, and a cumulative result total supersedes the step sum. The tests cover both behaviors, including a zero total that overrides positive step costs.

Merge blockers

Every finding below was introduced by this PR and must be resolved before merging.

F8: 🔴 Preserve known spend on route exhaustion

  • Category: correctness

  • Required behavior: A caller that owns the analysis log must retain the total provider cost when every physical attempt reported its cost, including when the overall analysis fails.

  • Evidence: packages/core/src/services/syntheticRoutingService.ts:151, SyntheticRoutingSession.analyze; packages/core/src/services/relevance/keywordExtractor.ts:271; packages/core/src/services/relevance/summaryMinerMetrics.ts, analyzeWithProviderCost.

    static trace:

    1. Keyword extraction uses a synthetic route with two unlisted OpenCode members and suppresses their individual logs. Both members return retryable failures with reported costs, first $0.25, then $0.50.
    2. analyze adds each cost and calls failCurrent after each failure. With both members spent, the next select() throws for pool exhaustion. The $0.75 total exists only in a local variable, and the method exposes it only when returning a result.
    3. Keyword extraction reaches its failure logger without executing providerCostUsd = analysisResult.providerCostUsd. Its authoritative log therefore has no provider total, and the unlisted model has no catalog price to fill it. Semantic scoring has the same assignment-after-return pattern in packages/core/src/services/relevance/semanticScorer.ts:214.
    4. File and directory summarization also lose the cost on this path. analyzeWithProviderCost sees the rejected routing promise and marks the tracker incomplete. Even if a subsequent fallback reports its cost, the batch log omits the known total.

    The failover tests cover a priced failure followed by success, which reaches the return statement. The exhaustion test starts with a member that throws without reporting any cost, for which an unknown total is correct. Neither covers exhaustion after fully priced failures.

  • Minimum fix: Carry the accumulated cost on the exhaustion error when at least one attempt ran and every attempt reported a valid cost. Consume it in the keyword and semantic failure logs and in the batch tracker, preserving existing retry and fallback behavior. Cover fully priced exhaustion and exhaustion followed by a priced fallback.

Suggestions

These are optional follow-ups and are not sent to /fix.

S15: 🟢 Test a decreasing snapshot

The largest-snapshot test supplies 0.5, 1.5, and 1.5, so it would also pass if the parser simply kept the last value. Ending with 0.75 and asserting 1.5 would distinguish the two behaviors. This is optional because the current Math.max implementation already preserves the larger total.

Score

The direct OpenCode paths and successful failover have substantial coverage. Fully priced route exhaustion still leaves incorrect cost records. No check runs were reported for the current head.

Score: 6/10


🤖 Review Details

  • Model: GPT-6.2 Astra
  • Time: 42s
  • Tokens: 61,609 (60,625 in / 984 out)
  • Cost: $0.42

View Task


💡 Next step: Comment /fix to address every F# merge blocker, /fix all for every pending blocker and suggestion, or name records explicitly, as in /fix F3 S5.
F# and S# IDs increment across review comments and remain permanent, so selectors such as /fix F3 F5 stay unambiguous across cycles. S# suggestions stay optional: they are implemented only when you name them or request /fix all, and they never relax a merge blocker.

Copy and edit to choose records from this review:

/fix F8 S15

🤖 Review by ProPR

@integry

integry commented Nov 24, 2026

Copy link
Copy Markdown
Owner

/fix F8

@propr-dev

propr-dev Bot commented Nov 24, 2026 •

Copy link
Copy Markdown
Contributor

✅ Applied the requested follow-up changes in commit 1064f3b

Addressed 1 AI review comment (IDs: 7141486069)

Addressed finding F8

Summary of Changes

F8 is fixed: when a synthetic route runs out of members after every attempt reported a cost, the summed cost now reaches the caller's log instead of being dropped.

What changed

  • Routing (syntheticRoutingService.ts, syntheticRoutingTypes.ts): SyntheticRoutingSession.analyze records the accumulated cost on the SyntheticPoolExhaustedError. It does so only when at least one attempt ran in that call and every attempt reported a valid cost; a missing cost or a thrown attempt still leaves it unknown.
  • Keyword extraction and semantic scoring: their failure logs now read the cost from the exhaustion error.
  • File and directory batches (analyzeWithProviderCost in summaryMinerMetrics.ts): the tracker adds the exhaustion error's cost instead of marking the total unknown, so a priced fallback afterwards yields the full sum.

One addition beyond the literal finding

When a member's failure reason contains a retryable-looking word such as "timeout", the batch retry re-enters the already exhausted route. That re-entry runs no attempt, but the tracker treated it as an unknown-cost call and discarded the total again. The error now also carries the number of attempts that ran, and the tracker skips a zero-attempt exhaustion. Retry and fallback behaviour is unchanged.

Verification

  • test/summaryMinerBatchFallback.test.ts passes 44/44; the 9 new regressions fail with the source change reverted.
  • New regressions cover:
    • fully priced exhaustion for all four callers ($0.25 + $0.50 logged as $0.75).
    • exhaustion followed by a priced fallback for file and directory batches ($0.875).
    • exhaustion with a missing or thrown attempt cost (stays unknown).
    • an all-zero total.
  • Core tsc --noEmit and eslint src/ --max-warnings 0 are clean. To stay under the 400-line lint limit in syntheticRoutingService.ts, I merged its two imports from syntheticRoutingTypes.js into one.
  • planFileGeneration, opencodeCostReporting, llmMetricsProviderCost and reviewResultMetricsReasoningLevel pass.
  • opencodeExecutionLog has one failing test, with or without this change: it cannot create a temp directory under the read-only /tmp/git-processor in this container.

No visual preview: the change only affects stored cost values on a failure path.

Separate observation (not changed)

withRetry treats a pool-exhaustion error as retryable whenever a member's failure reason matches its message patterns ("timeout", "connection", …), so an exhausted route gets pointlessly re-entered up to three times before fallback.

Review digest

Risk-tiered paths

  • High risk: none
  • Normal risk (5 files)
    • packages/core/src/services/relevance/keywordExtractor.ts (+2/−0)
    • packages/core/src/services/relevance/semanticScorer.ts (+2/−0)
    • packages/core/src/services/relevance/summaryMinerMetrics.ts (+15/−6)
    • packages/core/src/services/syntheticRoutingService.ts (+4/−3)
    • packages/core/src/services/syntheticRoutingTypes.ts (+25/−0)
  • Low risk (1 file)
    • test/summaryMinerBatchFallback.test.ts (+103/−0)

Diff size: 6 files changed, +151/−9 lines


🤖 Implementation Details

  • Model: Claude Fable 5.2 (medium)
  • Requested By: @integry
  • Time: 7m 27s
  • Tokens: 1,688,967 (1,673,785 in / 15,182 out)
  • Cost: $1.87
  • Subscription usage: Weekly +1%, Fable +1%

Undo Changes • View Task Execution


💡 ProPR Slash Commands
Command Description Example
/merge Merge target branch into this PR and resolve conflicts /merge
/review Request an AI code review /review or /review claude-sonnet
/fix Address review blockers, or blockers and suggestions with /fix all /fix, /fix all, or /fix F3 S5
/switch Change the AI model for this PR /switch claude-opus
/use Override the model for a single follow-up run /use claude-sonnet
/ultrafix Loop review→fix cycles until score goal is met /ultrafix or /ultrafix goal=8 max=10

🤖 Generated by ProPR
Processing comment ID: 7141747175✓

F8 is fixed: when a synthetic route runs out of members after every attempt reported a cost, the summed cost now reaches the caller's log instead of being dropped.

## What changed

- **Routing** (`syntheticRoutingService.ts`, `syntheticRoutingTypes.ts`): `SyntheticRoutingSession.analyze` records the accumulated cost on the `SyntheticPoolExhaustedError`. It does so only when at least one attempt ran in that call and every attempt reported a valid cost; a missing cost or a thrown attempt still leaves it unknown.
- **Keyword extraction and semantic scoring**: their failure logs now read the cost from the exhaustion error.
- **File and directory batches** (`analyzeWithProviderCost` in `summaryMinerMetrics.ts`): the tracker adds the exhaustion error's cost instead of marking the total unknown, so a priced fallback afterwards yields the full sum.

## One addition beyond the literal finding

When a member's failure reason contains a retryable-looking word such as "timeout", the batch retry re-enters the already exhausted route. That re-entry runs no attempt, but the tracker treated it as an unknown-cost call and discarded the total again. The error now also carries the number of attempts that ran, and the tracker skips a zero-attempt exhaustion. Retry and fallback behaviour is unchanged.

## Verification

- `test/summaryMinerBatchFallback.test.ts` passes 44/44; the 9 new regressions fail with the source change reverted.
- New regressions cover:
  - fully priced exhaustion for all four callers ($0.25 + $0.50 logged as $0.75).
  - exhaustion followed by a priced fallback for file and directory batches ($0.875).
  - exhaustion with a missing or thrown attempt cost (stays unknown).
  - an all-zero total.
- Core `tsc --noEmit` and `eslint src/ --max-warnings 0` are clean. To stay under the 400-line lint limit in `syntheticRoutingService.ts`, I merged its two imports from `syntheticRoutingTypes.js` into one.
- `planFileGeneration`, `opencodeCostReporting`, `llmMetricsProviderCost` and `reviewResultMetricsReasoningLevel` pass.
- `opencodeExecutionLog` has one failing test, with or without this change: it cannot create a temp directory under the read-only `/tmp/git-processor` in this container.

No visual preview: the change only affects stored cost values on a failure path.

## Separate observation (not changed)

`withRetry` treats a pool-exhaustion error as retryable whenever a member's failure reason matches its message patterns ("timeout", "connection", …), so an exhausted route gets pointlessly re-entered up to three times before fallback.

PR: integry#3780
Comment by: @integry (ID: 7141747175)
Model: Claude Fable 5.2

ProPR-Agent: claude/claude-fable-5-2
@integry

integry commented Nov 24, 2026

Copy link
Copy Markdown
Owner

/review astra

@propr-dev

propr-dev Bot commented Nov 24, 2026 •

Copy link
Copy Markdown
Contributor

✅ AI Code Review Complete requested by @integry

Posted 1 review:

View Task Details

@propr-dev

propr-dev Bot commented Nov 24, 2026

Copy link
Copy Markdown
Contributor

🔍 AI Code Review — astra

Overall Evaluation

The PR carries OpenCode’s reported cost from JSONL events into execution metrics and analysis logs. It needs minor changes before merge. A capacity wait can still erase a fully known batch cost, and a post-execution verification failure can leave the execution metric inconsistent with its log. No check runs were reported for the current head. This was a read-only static review.

✅ Zero survives the full path — The parser, result adapters, and metrics calculation preserve an explicit 0. The metrics tests cover a zero-cost run even when catalog pricing is available.

✅ Repeated events are handled correctly — The parser counts each priced step ID once and gives a cumulative result total precedence over the step sum. Tests cover both a repeated step and a zero cumulative total following positive steps.

Merge blockers

Every finding below was introduced by this PR and must be resolved before merging.

F9: 🔴 Preserve known spend across capacity waits

  • Category: correctness

  • Required behavior: A batch whose physical attempts all reported costs must retain their total. Waiting for capacity adds no provider spend.

  • Evidence: packages/core/src/services/syntheticRoutingService.ts:155, packages/core/src/services/syntheticRoutingTypes.ts (withAnalysisSpend), and packages/core/src/services/relevance/summaryMinerMetrics.ts (analyzeWithProviderCost).

    static trace:

    1. A physical member returns a retryable failure with a reported cost of $0.25. SyntheticRoutingSession.analyze adds it to the running total and tries to select the next member.
    2. Selection raises a capacity error before another physical attempt starts. withAnalysisSpend annotates only SyntheticPoolExhaustedError, so the capacity error leaves the routing session without the known $0.25.
    3. The batch tracker treats that rejection as an attempt with unknown spend and sets complete = false. Both file and directory batch logging then receive undefined from trackedProviderCost, even if a later retry succeeds and reports its cost. For an unlisted model, the log loses the known spend and can persist NULL.

    The same tracker also marks a capacity wait before the first physical attempt as unknown spend. The zero-attempt exemption and the added tests cover pool exhaustion specifically.

  • Minimum fix: Carry the invocation’s attempt count and accumulated cost through selection-time capacity errors while preserving their capacity-error identity. Have the tracker ignore a zero-attempt wait and retain the total from any priced attempts preceding the wait.

F10: 🔴 Keep cost through post-execution verification

  • Category: correctness

  • Required behavior: A completed OpenCode run must retain its reported cost when a later local step fails, so its execution metric and log agree.

  • Evidence: packages/core/src/agents/impl/OpenCodeAgent.ts:106, executeTask and reportExecutionOutcome.

    static trace:

    1. OpenCode exits successfully and reports $0.75 for an unlisted model. buildExecutionResponse sets providerCostUsd, and persistExecutionLogSafely writes a successful log with that cost.
    2. reportExecutionOutcome invokes verifyWorktreePostExecution. If verification throws, control reaches the outer catch after the priced log has already been written.
    3. The catch constructs a fresh failed response from the exception, writes a second log, and returns the response without the parsed cost or tokens. The caller’s execution metric consequently falls back to 0 for the unlisted model, while the first log still records $0.75.

    The safe-persistence wrapper covers log writes only. The new test exercises a successful return from verification.

  • Minimum fix: Retain the completed response through verification, apply any verification failure to that response, and persist the final outcome once. Add a regression asserting one failed log and a returned failure with the same reported cost.

Suggestions

These are optional follow-ups and are not sent to /fix.

S16: 🟢 Exercise a decreasing cumulative snapshot

The test named “keeps the largest cumulative total” uses 0.5, 1.5, 1.5. A final snapshot of 0.75 would distinguish retaining the maximum from overwriting it with the latest value. This is optional because the implementation already uses Math.max.

Score

The primary reporting path handles zero, duplicates, and catalog fallback well. Two localized failure paths still lose known spend or produce conflicting accounting records.

Score: 6/10


🤖 Review Details

  • Model: GPT-6.2 Astra
  • Time: 38s
  • Tokens: 64,758 (63,578 in / 1,180 out)
  • Cost: $0.45

View Task


💡 Next step: Comment /fix to address every F# merge blocker, /fix all for every pending blocker and suggestion, or name records explicitly, as in /fix F3 S5.
F# and S# IDs increment across review comments and remain permanent, so selectors such as /fix F3 F5 stay unambiguous across cycles. S# suggestions stay optional: they are implemented only when you name them or request /fix all, and they never relax a merge blocker.

Copy and edit to choose records from this review:

/fix F9 F10 S16

🤖 Review by ProPR

@integry

integry commented Nov 24, 2026

Copy link
Copy Markdown
Owner

/fix F9 F10

@propr-dev

propr-dev Bot commented Nov 24, 2026 •

Copy link
Copy Markdown
Contributor

✅ Applied the requested follow-up changes in commit 759226d

Addressed 1 AI review comment (IDs: 7142810678)

Addressed findings F9, F10

Summary of Changes

F9 and F10 are both fixed, with regressions that fail on the previous code and pass now. Core tsc --noEmit and eslint src/ --max-warnings 0 are clean, and the summary-miner, OpenCode, capacity and synthetic-routing suites I ran all pass.

F9: known spend across capacity waits

  • Selection-time wait: a capacity error raised while selecting the next member now carries the call's attempt count and accumulated cost. It is the same error object, so its capacity-error identity is unchanged.
  • Tracker: a wait with no attempt behind it is ignored, and a wait after priced attempts adds their total. Both file and directory batch logging now keep the full sum when a later retry succeeds.
  • Same defect in sibling paths, also corrected:
    • A capacity error thrown by the physical member itself (admission wait) was passed through unannotated; it now carries the prior spend too.
    • OpenCodeAgent.analyze returns a capacity wait as a failed result rather than throwing. The routing session now treats that as zero spend, not unknown spend.
    • Keyword extraction and semantic scoring read the same carried cost, so they pick this up without their own change.

The cost-summing logic moved into two small helpers in syntheticRoutingTypes.ts to keep syntheticRoutingService.ts under the 400-line and complexity lint gates.

Regressions in test/summaryMinerBatchFallback.test.ts (9 new cases):

  • wait at selection and at admission after a $0.25 attempt.
  • wait before the first attempt.
  • wait returned as a failed result.
  • file and directory batches where a retry succeeds after the wait (0.75 after a priced attempt, 0.5 after none).
  • a direct agent with no routing session.

F10: cost through post-execution verification

In OpenCodeAgent.executeTask, verification now runs on the completed response before the log is written. If it throws, that same response is marked failed with the verification message, keeping its cost, tokens and session id, and the log is persisted once.

The regression in test/opencodeExecutionLog.test.ts asserts one failed log with costUsd 0.75 and a returned failure with the same providerCostUsd.

Separate observations (not changed)

  • The session only arms selection-time capacity deferral for the first selection, so the F9 trace (a selection-time wait after a priced attempt) is not reachable through the built-in selector today. The regression simulates it by overriding select; the admission-wait and failed-result paths are the ones that occur in practice.
  • In this container, the existing analyze test in opencodeExecutionLog.test.ts only passes with OPENCODE_ANALYSIS_ROOT pointed at a writable directory, because /tmp/git-processor is read-only here. That is environmental, not caused by this change.

No visual preview: the change is not user-visible.

Review digest

Risk-tiered paths

  • High risk: none
  • Normal risk (4 files)
    • packages/core/src/agents/impl/OpenCodeAgent.ts (+17/−8)
    • packages/core/src/services/relevance/summaryMinerMetrics.ts (+5/−4)
    • packages/core/src/services/syntheticRoutingService.ts (+12/−11)
    • packages/core/src/services/syntheticRoutingTypes.ts (+62/−13)
  • Low risk (2 files)
    • test/opencodeExecutionLog.test.ts (+36/−1)
    • test/summaryMinerBatchFallback.test.ts (+94/−0)

Diff size: 6 files changed, +226/−37 lines


🤖 Implementation Details

  • Model: Claude Fable 5.2 (medium)
  • Requested By: @integry
  • Time: 8m 10s
  • Tokens: 1,810,624 (1,791,777 in / 18,847 out)
  • Cost: $2.09

Undo Changes • View Task Execution


💡 ProPR Slash Commands
Command Description Example
/merge Merge target branch into this PR and resolve conflicts /merge
/review Request an AI code review /review or /review claude-sonnet
/fix Address review blockers, or blockers and suggestions with /fix all /fix, /fix all, or /fix F3 S5
/switch Change the AI model for this PR /switch claude-opus
/use Override the model for a single follow-up run /use claude-sonnet
/ultrafix Loop review→fix cycles until score goal is met /ultrafix or /ultrafix goal=8 max=10

🤖 Generated by ProPR
Processing comment ID: 7144025768✓

F9 and F10 are both fixed, with regressions that fail on the previous code and pass now. Core `tsc --noEmit` and `eslint src/ --max-warnings 0` are clean, and the summary-miner, OpenCode, capacity and synthetic-routing suites I ran all pass.

## F9: known spend across capacity waits

- **Selection-time wait:** a capacity error raised while selecting the next member now carries the call's attempt count and accumulated cost. It is the same error object, so its capacity-error identity is unchanged.
- **Tracker:** a wait with no attempt behind it is ignored, and a wait after priced attempts adds their total. Both file and directory batch logging now keep the full sum when a later retry succeeds.
- **Same defect in sibling paths, also corrected:**
  - A capacity error thrown by the physical member itself (admission wait) was passed through unannotated; it now carries the prior spend too.
  - `OpenCodeAgent.analyze` returns a capacity wait as a failed result rather than throwing. The routing session now treats that as zero spend, not unknown spend.
  - Keyword extraction and semantic scoring read the same carried cost, so they pick this up without their own change.

The cost-summing logic moved into two small helpers in `syntheticRoutingTypes.ts` to keep `syntheticRoutingService.ts` under the 400-line and complexity lint gates.

Regressions in `test/summaryMinerBatchFallback.test.ts` (9 new cases):
- wait at selection and at admission after a `$0.25` attempt.
- wait before the first attempt.
- wait returned as a failed result.
- file and directory batches where a retry succeeds after the wait (`0.75` after a priced attempt, `0.5` after none).
- a direct agent with no routing session.

## F10: cost through post-execution verification

In `OpenCodeAgent.executeTask`, verification now runs on the completed response before the log is written. If it throws, that same response is marked failed with the verification message, keeping its cost, tokens and session id, and the log is persisted once.

The regression in `test/opencodeExecutionLog.test.ts` asserts one failed log with `costUsd` 0.75 and a returned failure with the same `providerCostUsd`.

## Separate observations (not changed)

- The session only arms selection-time capacity deferral for the first selection, so the F9 trace (a selection-time wait after a priced attempt) is not reachable through the built-in selector today. The regression simulates it by overriding `select`; the admission-wait and failed-result paths are the ones that occur in practice.
- In this container, the existing analyze test in `opencodeExecutionLog.test.ts` only passes with `OPENCODE_ANALYSIS_ROOT` pointed at a writable directory, because `/tmp/git-processor` is read-only here. That is environmental, not caused by this change.

No visual preview: the change is not user-visible.

PR: integry#3780
Comment by: @integry (ID: 7144025768)
Model: Claude Fable 5.2

ProPR-Agent: claude/claude-fable-5-2
@integry

integry commented Nov 24, 2026

Copy link
Copy Markdown
Owner

/review

@propr-dev

propr-dev Bot commented Nov 24, 2026 •

Copy link
Copy Markdown
Contributor

✅ AI Code Review Complete requested by @integry

Posted 1 review:

View Task Details

@propr-dev

propr-dev Bot commented Nov 24, 2026

Copy link
Copy Markdown
Contributor

🔍 AI Code Review — codex:gpt-6-astra

Overall Evaluation

The PR carries OpenCode’s reported cost through parsing, result adapters, execution metrics, and logs. The retry and failover accounting is consistent with preserving known totals without presenting incomplete totals as authoritative. Ready to merge within the reviewed scope.

✅ Zero remains meaningful — Parsing and metrics distinguish an explicit zero from missing cost, and valid provider costs take precedence over catalog estimates.

✅ Failure costs are retained — Failed-result adapters and OpenCode logging preserve reported spend, including the post-execution verification path.

✅ Coverage follows propagation — Added tests cover parsing, adapter forwarding, persistence, retries, failover, and capacity waits.

This was a static review of the supplied code. No commands or tests were run, as requested. No current-head check runs were reported.

Merge blockers

No merge blockers.

Suggestions

These are optional follow-ups and are not sent to /fix.

S17: 🟢 Isolate parser tests

Consider separating the pure parsing tests in test/opencodeCostReporting.test.ts from adapter tests that import @propr/core and require connection cleanup. This would make parser regressions easier to run independently. It is optional because the current tests still exercise the intended parsing behavior.

Score

The implementation addresses the stated objective with substantial coverage and no verified merge blockers. Runtime validation remains unconfirmed in this review.
Score: 8/10


🤖 Review Details

  • Model: GPT-6 Astra
  • Time: 39s
  • Tokens: 67,079 (66,321 in / 758 out)
  • Cost: $0.59

View Task


💡 Next step: Comment /fix to address every F# merge blocker, /fix all for every pending blocker and suggestion, or name records explicitly, as in /fix F3 S5.
F# and S# IDs increment across review comments and remain permanent, so selectors such as /fix F3 F5 stay unambiguous across cycles. S# suggestions stay optional: they are implemented only when you name them or request /fix all, and they never relax a merge blocker.

Copy and edit to choose records from this review:

/fix S17

🤖 Review by ProPR

@integry integry removed the AI label Nov 25, 2026
@integry

integry commented Nov 25, 2026

Copy link
Copy Markdown
Owner

@czehentner please check if the PRs still look good and work as intended after the fix loops

@czehentner

czehentner commented Nov 26, 2026 •

Copy link
Copy Markdown
Contributor Author

@czehentner please check if the PRs still look good and work as intended after the fix loops

@integry from a visual check they look good, I will be able to deploy to my staging not before tomorrow to confirm with my live setup.

@propr-dev

propr-dev Bot commented Nov 28, 2026 •

Copy link
Copy Markdown
Contributor

🔀 Resolved merge conflicts from main into fix/opencode-cost-reporting in commit 4817014

Conflicting Files

  • packages/core/src/agents/types.ts
  • packages/core/src/utils/llmMetrics.ts
  • src/jobs/prCommentJobUtils.ts

Resolution Summary

The merge is resolved. Both branches had added the same feature: an optional providerCostUsd that carries the provider's own reported cost and is recorded instead of a pricing-catalog estimate. On main it came in for the Pi agent; this PR adds it for OpenCode. In each conflict I kept the PR's version, and I took nothing from main because its side duplicated what the PR already does.

The three flagged conflicts:

  1. packages/core/src/agents/types.ts: both sides added providerCostUsd?: number to AgentExecutionResult. Only the comment differed. I kept the PR's comment, because it covers more: the field is absent when no cost was reported, a reported 0 is kept, and it takes priority over the estimate. That also covers the Pi case from main.

  2. packages/core/src/utils/llmMetrics.ts (calculateCost): both sides return the reported cost early if it is a finite, non-negative number. I kept the PR's version. It does the same check through the PR's reportedProviderCost() helper, logs "Using provider-reported cost", and keeps the PR's formatting of the pricing lookup. The behaviour for Pi is unchanged.

  3. src/jobs/prCommentJobUtils.ts (toClaudeResult): the same providerCostUsd spread appeared on both sides, placed before or after usageMetrics. The two are equivalent, so I kept the PR's ordering.

Two problems git merged without flagging: the typecheck showed that git had kept both sides' declarations of the field. That caused TS2300 Duplicate identifier 'providerCostUsd' in:

  • packages/core/src/claude/claudeService.ts (ClaudeCodeResponse)
  • packages/core/src/utils/llmMetrics.types.ts

In both I removed main's duplicate line and kept the PR's, which documents the reported-0 behaviour. The type is the same either way.

Checks on the merged tree:

  • No conflict markers remain anywhere in the repo.
  • tsc --noEmit passes for packages/core and for the root project. The root check first needed core and packages/local-setup built, because it reads their build output.
  • ESLint with zero warnings allowed passes on all five edited files.
  • The seven test files that cover providerCostUsd pass: 117 tests. The first runs failed for container reasons, not code. The tests need Node's --experimental-test-module-mocks flag. One OpenCode test also needed a writable OPENCODE_ANALYSIS_ROOT, because /tmp/git-processor is read-only here. With both set, they all pass.

🤖 Resolution Details

  • Model: Claude Opus 5.5
  • Time: 5m 43s

View Task Execution


System-triggered merge conflict resolution

Automatically resolved merge conflicts after merging target branch into PR branch.
Resolved conflicts in:
- packages/core/src/agents/types.ts
- packages/core/src/utils/llmMetrics.ts
- src/jobs/prCommentJobUtils.ts

PR: integry#3780
Model: Claude Opus 5.5
@czehentner

Copy link
Copy Markdown
Contributor Author

@integry confirmed in local staging. cost reports come through via opencode 👍

Bildschirmfoto 2026-11-30 um 14 47 23

integry commented Dec 1, 2026

Copy link
Copy Markdown
Owner

/review

@integry integry added the AI label Dec 1, 2026

integry commented Dec 1, 2026

Copy link
Copy Markdown
Owner

/review

@propr-dev

propr-dev Bot commented Dec 1, 2026 •

Copy link
Copy Markdown
Contributor

✅ AI Code Review Complete requested by @integry

Posted 1 review:

View Task Details

@propr-dev

propr-dev Bot commented Dec 1, 2026

Copy link
Copy Markdown
Contributor

🔍 AI Code Review — codex:gpt-6-astra

Overall Evaluation

The PR carries OpenCode’s reported cost through execution, analysis, logging, and metrics, with substantial coverage for retries and failover. It needs one localized correction before merge: direct-agent capacity waits returned as failed results incorrectly invalidate subsequent known costs.

✅ Zero remains meaningful — Parsing and metrics distinguish an explicit zero from an absent cost, preserving provider precedence over catalog estimates.

✅ Failover accounting — Routed analysis totals include priced failed attempts, and tests cover exhaustion, fallback, and unknown spend.

The supplied current-head status reports 20 passed checks and no failed or pending checks. This review uses static analysis of the supplied code; no commands were run.

Merge blockers

Every finding below was introduced by this PR and must be resolved before merging.

F11: 🔴 Returned capacity waits invalidate known costs

  • Category: correctness

  • Required behavior: Analysis cost aggregation must preserve known provider spend across retries when an earlier capacity wait reached no provider.

  • Evidence: packages/core/src/services/relevance/summaryMinerMetrics.ts, analyzeWithProviderCost; packages/core/src/agents/impl/OpenCodeAgent.ts, analyze

    1. A file or directory batch calls a direct OpenCode agent through analyzeWithProviderCost, without a routing session.
    2. Container admission raises AgentCapacityWaitTimeoutError. OpenCodeAgent.analyze catches it and returns { success: false, error: err.message }, with no provider cost.
    3. The tracker handles this as a returned result, leaves spent = true, and permanently sets complete = false.
    4. The batch converts that failed result into an error. When its capacity-timeout retry succeeds with a reported cost, the tracker adds that cost but remains incomplete.
    5. trackedProviderCost returns undefined; for an unlisted model, the batch log retains NULL instead of the known successful attempt’s cost.

    static trace: Both summaryMinerBatch.ts and summaryMinerDirectoryBatch.ts use this helper. Its no-spend detection runs only in the rejection branch. The routing layer already recognizes returned capacity failures through analysisAttemptCost, but direct calls bypass that protection. The added direct-agent capacity test throws the error from the mock; it does not reproduce OpenCode’s conversion into a failed result.

  • Minimum fix: Apply analysisAttemptCost or equivalent returned-result classification in the tracker’s success branch, excluding capacity-only failures without a reported cost. Add a regression covering a direct agent returning a capacity timeout before a successful priced retry; the shared correction should cover both batch callers.

Suggestions

These are optional follow-ups and are not sent to /fix.

S18: 🟢 Remove duplicate cost assignments

failedAgentExecution.ts assigns providerCostUsd twice in both failedExecutionResult and agentResultToMetricsResult. Retain one assignment per result, preferably the conditional spread used elsewhere. The duplicate values currently agree, so this is optional cleanup rather than a merge blocker.

Score

The implementation has strong coverage and passing current-head checks, but one reachable retry path still loses the provider cost this PR intends to preserve. The required correction is localized.

Score: 6/10


🤖 Review Details

  • Model: GPT-6 Astra
  • Time: 33s
  • Tokens: 69,126 (68,236 in / 890 out)
  • Cost: $0.62

View Task


💡 Next step: Comment /fix to address every F# merge blocker, /fix all for every pending blocker and suggestion, or name records explicitly, as in /fix F3 S5.
F# and S# IDs increment across review comments and remain permanent, so selectors such as /fix F3 F5 stay unambiguous across cycles. S# suggestions stay optional: they are implemented only when you name them or request /fix all, and they never relax a merge blocker.

Copy and edit to choose records from this review:

/fix F11 S18

🤖 Review by ProPR

integry commented Dec 1, 2026

Copy link
Copy Markdown
Owner

/fix F11

@propr-dev

propr-dev Bot commented Dec 1, 2026 •

Copy link
Copy Markdown
Contributor

✅ Applied the requested follow-up changes in commit 82838d6

Addressed 1 AI review comment (IDs: 7296888073)

Addressed finding F11

Summary of Changes

F11 is fixed: a capacity wait that a direct agent returns as a failed result no longer marks the batch's known cost as incomplete.

What changed

  • summaryMinerMetrics.ts: analyzeWithProviderCost now runs returned results from direct agents through analysisAttemptCost. A failed result that only waited for capacity and reports no cost is treated as "no provider reached", the same as the thrown form.
  • summaryMinerBatch.ts / summaryMinerDirectoryBatch.ts: both callers pass a new routed flag (!!routingSession). Routed results are taken as reported, because the routing session has already classified its attempts. Reclassifying them would let a capacity result hide an earlier unpriced attempt.

Regressions added (test/summaryMinerBatchFallback.test.ts)

  • File and directory batch: a priced attempt followed by a direct agent returning a capacity wait logs the priced attempt's cost (0.25) instead of NULL.
  • Tracker level: returned capacity wait, then a priced retry, gives 0.5.
  • The existing thrown capacity wait test now also covers the directory batch.
  • Guards: a non-capacity failed result still leaves the total unknown, and a routed capacity result without a total stays unknown.

The suite passes 59/59. With the fix reverted, the three new returned-result tests fail. Core tsc --noEmit and eslint on the touched source files are clean, and opencodeCostReporting.test.ts passes 14/14.

Independent discovery (not changed)

The finding's step 4 is not reachable through the batches as written. Once the batch turns the returned failure into a plain Error, its message ("Timed out waiting for agent capacity…") matches no retry pattern, so the batch fails instead of retrying; only the thrown form is retried, via the error name. That is why the batch-level regression uses the reachable order (priced attempt first, capacity wait second) and the wait-then-priced-retry order is covered at tracker level. Whether a returned capacity wait should be retried like the thrown one is a separate behaviour question, left alone here.

No visual preview: the change is not visible in the UI.

Review digest

Risk-tiered paths

  • High risk: none
  • Normal risk (3 files)
    • packages/core/src/services/relevance/summaryMinerBatch.ts (+1/−1)
    • packages/core/src/services/relevance/summaryMinerDirectoryBatch.ts (+1/−1)
    • packages/core/src/services/relevance/summaryMinerMetrics.ts (+7/−3)
  • Low risk (1 file)
    • test/summaryMinerBatchFallback.test.ts (+64/−11)

Diff size: 4 files changed, +73/−16 lines


🤖 Implementation Details

  • Model: Claude Fable 5.2 (medium)
  • Requested By: @integry
  • Time: 6m 0s
  • Tokens: 1,055,238 (1,045,907 in / 9,331 out)
  • Cost: $1.27

Undo Changes • View Task Execution


💡 ProPR Slash Commands
Command Description Example
/merge Merge target branch into this PR and resolve conflicts /merge
/review Request an AI code review /review or /review claude-sonnet
/fix Address review blockers, or blockers and suggestions with /fix all /fix, /fix all, or /fix F3 S5
/switch Change the AI model for this PR /switch claude-opus
/use Override the model for a single follow-up run /use claude-sonnet
/ultrafix Loop review→fix cycles until score goal is met /ultrafix or /ultrafix goal=8 max=10

🤖 Generated by ProPR
Processing comment ID: 7296908608✓

F11 is fixed: a capacity wait that a direct agent returns as a failed result no longer marks the batch's known cost as incomplete.

## What changed
- **`summaryMinerMetrics.ts`**: `analyzeWithProviderCost` now runs returned results from direct agents through `analysisAttemptCost`. A failed result that only waited for capacity and reports no cost is treated as "no provider reached", the same as the thrown form.
- **`summaryMinerBatch.ts` / `summaryMinerDirectoryBatch.ts`**: both callers pass a new `routed` flag (`!!routingSession`). Routed results are taken as reported, because the routing session has already classified its attempts. Reclassifying them would let a capacity result hide an earlier unpriced attempt.

## Regressions added (`test/summaryMinerBatchFallback.test.ts`)
- File and directory batch: a priced attempt followed by a direct agent returning a capacity wait logs the priced attempt's cost (0.25) instead of `NULL`.
- Tracker level: returned capacity wait, then a priced retry, gives 0.5.
- The existing thrown capacity wait test now also covers the directory batch.
- Guards: a non-capacity failed result still leaves the total unknown, and a routed capacity result without a total stays unknown.

The suite passes 59/59. With the fix reverted, the three new returned-result tests fail. Core `tsc --noEmit` and eslint on the touched source files are clean, and `opencodeCostReporting.test.ts` passes 14/14.

## Independent discovery (not changed)
The finding's step 4 is not reachable through the batches as written. Once the batch turns the returned failure into a plain `Error`, its message ("Timed out waiting for agent capacity…") matches no retry pattern, so the batch fails instead of retrying; only the thrown form is retried, via the error name. That is why the batch-level regression uses the reachable order (priced attempt first, capacity wait second) and the wait-then-priced-retry order is covered at tracker level. Whether a returned capacity wait should be retried like the thrown one is a separate behaviour question, left alone here.

No visual preview: the change is not visible in the UI.

PR: integry#3780
Comment by: @integry (ID: 7296908608)
Model: Claude Fable 5.2

ProPR-Agent: claude/claude-fable-5-2

integry commented Dec 1, 2026

Copy link
Copy Markdown
Owner

/review

@propr-dev

propr-dev Bot commented Dec 1, 2026 •

Copy link
Copy Markdown
Contributor

✅ AI Code Review Complete requested by @integry

Posted 1 review:

View Task Details

@propr-dev

propr-dev Bot commented Dec 1, 2026

Copy link
Copy Markdown
Contributor

🔍 AI Code Review — codex:gpt-6-astra

Overall Evaluation

The PR carries OpenCode’s reported cost through execution results, analysis results, metrics, and logs, while accounting for retries and synthetic failover. It is merge-ready within the reviewed scope, conditional on pending checks completing successfully.

✅ Zero remains meaningful — Parsing and propagation distinguish an explicit zero from missing cost, and metrics prefer valid provider totals over catalog estimates.

✅ Retry costs remain complete — Batch tracking accumulates priced attempts and leaves totals unknown when an actual attempt lacks pricing, preventing a partial total from being reported as authoritative.

✅ Relevant regression coverage — Added tests cover duplicate step IDs, cumulative totals, failed calls, fallback attempts, capacity waits, and downstream persistence.

This assessment is based on static review of the supplied diff and context. No commands or tests were run. The supplied current-head status reports no failed checks, with ten pending.

Merge blockers

No merge blockers.

Suggestions

These are optional follow-ups and are not sent to /fix.

S19: 🟢 Remove duplicate cost assignments

In packages/core/src/agents/impl/utils/failedAgentExecution.ts, failedExecutionResult() assigns providerCostUsd directly and again through a conditional spread; agentResultToMetricsResult() repeats the same conditional spread twice. Keep one conditional assignment in each adapter. The duplicates currently produce the same value, so this is optional cleanup, but removing them would make the intended handling of absent costs clearer.

S20: 🟢 Clarify verification test boundaries

The new post-execution verification test mocks verifyWorktreePostExecution() to throw, whereas the supplied real implementation catches its own errors. The test verifies that OpenCode preserves cost if this dependency throws, but it does not demonstrate how actual worktree verification failures propagate today. Clarifying that distinction in the test description or comment would improve its documentation value; changing the existing verifier’s behavior is outside this PR’s required scope.

Score

The implementation addresses the cost-reporting objective with substantial coverage of propagation and recovery paths. Static review found no merge blockers; pending checks still need to complete.

Score: 8/10


🤖 Review Details

  • Model: GPT-6 Astra
  • Time: 25s
  • Tokens: 70,769 (70,161 in / 608 out)
  • Cost: $0.62

View Task


💡 Next step: Comment /fix to address every F# merge blocker, /fix all for every pending blocker and suggestion, or name records explicitly, as in /fix F3 S5.
F# and S# IDs increment across review comments and remain permanent, so selectors such as /fix F3 F5 stay unambiguous across cycles. S# suggestions stay optional: they are implemented only when you name them or request /fix all, and they never relax a merge blocker.

Copy and edit to choose records from this review:

/fix S19 S20

🤖 Review by ProPR

@integry
integry merged commit dcde04d into integry:main Dec 1, 2026
42 checks passed
@integry

integry commented Dec 1, 2026

Copy link
Copy Markdown
Owner

Merged, thank you! The follow-up keeps a capacity wait that returns as a failed result from voiding the known cost, with a regression test, and CI was fully green on the final head.

integry added a commit to czehentner/propr that referenced this pull request Dec 1, 2026
Brings czehentner's OpenCode cost reporting (integry#3780) and execution-detail
persistence (integry#3782) into the epic. Conflicts resolved by keeping both sides:
reported provider cost and detail persistence from main, compute usage and
the runtime abstraction from the epic. Main's OpenCode response builder now
types its result from runAgent and wraps it with attachComputeUsage.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants