Repository navigation
refactor(usage): share the Codex/OpenCode scan fold behind a provider contract - #12082
Conversation
The Codex and OpenCode scanners each carried their own byte-identical copy of the ~325-line aggregation pipeline (createEmptySession, the three breakdown folds, finalizeSessions, mergeSessions, mergeDailyAggregates). Two copies means a token-accounting fix — a bucket that double-counts, a merge that drops a breakdown row — lands in one provider and silently not the other. The copies had already started to drift in comments only; the next drift would have been in arithmetic. The providers differ in exactly one dimension: the extra metric folded alongside the token counters (Codex `hasInferredPricing`, OpenCode `estimatedCostUsd`). That is now injected as an empty/fromEvent/fold triple, so the shared code stays generic without collapsing the two record schemas into a nullable union. The clone strategy stays per-provider (`cloneSessionForMerge` vs `structuredClone`) rather than being unified on the assumption that the difference is accidental. `usage-provider-contract.ts` is the seam a plugin-contributed usage source will implement. It is deliberately generic over each provider's record types: Claude bills per turn while Codex/OpenCode bill per event, and `cachedInput` is a subset of `input` for the latter but a peer bucket for Claude, so a single normalized record would push nullable handling onto every consumer. No behavior change. Emitted objects are byte-identical, including key insertion order — verified by diffing JSON.stringify of the scan output before and after across mixed models, mixed locations, an inferred-pricing flip, and null vs non-null cost. Persisted field names and schemaVersion are untouched, so caches do not invalidate.
…orktree refs Follow-up to the aggregation extraction, addressing three review points. `UsageProvider`/`UsageScanResult` were declaration-only, which is the same speculative-interface problem stablyai#12077 just deleted 8,900 lines of. They are now implemented by both real providers via `satisfies`, so the seam is typechecked against actual scan functions rather than asserted. The blocker was that codex returns `processedFiles` and opencode returns `processedDatabases`; rather than rename persisted-adjacent fields, the source key is a type parameter, so each provider keeps its own on-disk name and the contract still binds. Verified the constraint bites: swapping the key to 'processedSources' fails typecheck. `schemaVersion` is part of provider identity in the contract, so each provider's SCHEMA_VERSION constant (with its cache-invalidation rationale) moves into the provider module and the store imports it. Values are unchanged (codex 5, opencode 2) and the stores compare them exactly as before, so no cache invalidates. This also keeps store -> provider -> scanner acyclic. `UsageWorktreeRef` collided with the existing export in usage-worktree-metadata (3 fields, no repoId). Two different exported types under one name in src/main is worse than the duplication being removed, so the scan-input type is now `UsageScanWorktreeRef`; usage-worktree-metadata is untouched. `createWorktreeRefs` was triplicated. Codex, OpenCode, and Claude copies are byte-identical apart from the return type name (verified by diff), and all three ref types have the same four fields, so one shared copy replaces all three. This is the only change to claude-usage/. No behavior change: same functions, same arguments, same call order. The store tests' `./scanner` mock still intercepts scanning because the provider captures the mocked binding; their now-inert `createWorktreeRefs` mock key is dropped so it does not read as still mocking something.
|
Warning Review limit reached
Next review available in: 8 minutes Enable usage-based reviews in Billing to review now. Otherwise, wait until the next included review is available. How can I continue?After more reviews become available, a review can be triggered using the To avoid repeated limits, reduce automatic review volume by pausing incremental auto-reviews earlier, using label-based review opt-in, excluding WIP or generated PR titles, or requesting reviews manually when the PR is ready. If your team needs uninterrupted high-volume reviews, an organization admin can enable usage-based reviews. How do review limits work?CodeRabbit enforces per-developer PR review limits for each organization. Most developers receive the normal plan review availability. For paid Pro and Pro+ PR reviews, CodeRabbit uses adaptive limits for sustained high-volume activity. When a developer's recent PR review activity reaches the 95th percentile or higher among CodeRabbit users, additional reviews become available more gradually as earlier reviews age out of the rolling window. Please refer docs for additional details. Review details⚙️ Run configurationConfiguration used: Repository UI Review profile: CHILL Plan: Pro Plus Run ID: 📒 Files selected for processing (17)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
Greptile SummaryThis PR eliminates a ~325-line verbatim duplication of the session/daily aggregation block that existed in both
Confidence Score: 5/5Safe to merge. The extracted fold is a pure structural refactoring of both scanners with no changes to persisted field names, schema versions, or the Claude scanner's aggregation path. All metric values (hasInferredPricing, estimatedCostUsd) are propagated through the new generic fold with exactly the same logic as the inline originals. The daily-aggregate key function is byte-identical to the inlined versions, cloneSessionForMerge strategies are unchanged per provider, finalizeSessions is called in the same order, and no persisted field names were renamed. Files Needing Attention: No files require special attention. The three new usage/ modules are the core of the change and read cleanly; the provider files and store changes are mechanical wiring.
|
| Filename | Overview |
|---|---|
| src/main/usage/usage-event-aggregation.ts | New shared fold engine — extracts the 325-line session/daily aggregation block duplicated between Codex and OpenCode, parameterized by a metric monoid and a clone strategy |
| src/main/usage/usage-rollup-merge.ts | Extracted cross-file merge logic for sessions and daily aggregates; correctly uses the metric fold for provider-specific fields |
| src/main/usage/usage-rollup-records.ts | Canonical generic record shapes with TMetric type parameter; UsageMetricFold interface and usageDailyAggregateKey helper |
| src/main/usage/usage-provider-contract.ts | New provider seam UsageProvider with TSourceKey type parameter preserving persisted field names on disk |
| src/main/codex-usage/scanner.ts | Codex aggregation wired through createUsageEventAggregation with hasInferredPricing metric; removes ~300 duplicated lines |
| src/main/opencode-usage/scanner.ts | OpenCode aggregation wired through createUsageEventAggregation with estimatedCostUsd metric using structuredClone |
| src/main/codex-usage/codex-usage-provider.ts | New provider registration object; CODEX_USAGE_SCHEMA_VERSION exported and re-used in store.ts |
| src/main/opencode-usage/opencode-usage-provider.ts | New OpenCode provider registration object; OPENCODE_USAGE_SCHEMA_VERSION exported and re-used in store.ts |
| src/main/usage/usage-worktree-refs.ts | Extracted createWorktreeRefs helper previously duplicated across all three scanner files |
| src/main/codex-usage/store.ts | Switched to codexUsageProvider.scan; CODEX_USAGE_SCHEMA_VERSION and createWorktreeRefs imported from new shared locations |
| src/main/opencode-usage/store.ts | Switched to openCodeUsageProvider.scan; OPENCODE_USAGE_SCHEMA_VERSION and createWorktreeRefs imported from new shared locations |
Flowchart
%%{init: {'theme': 'neutral'}}%%
flowchart TD
subgraph Shared
UAF[usage-event-aggregation.ts]
URM[usage-rollup-merge.ts]
URR[usage-rollup-records.ts]
UPC[usage-provider-contract.ts]
UWR[usage-worktree-refs.ts]
end
subgraph Codex
CUP[codex-usage-provider.ts]
CS[codex-usage/scanner.ts]
end
subgraph OpenCode
OUP[opencode-usage-provider.ts]
OS[opencode-usage/scanner.ts]
end
CS --> UAF
OS --> UAF
UAF --> URR
UAF --> URM
URM --> URR
CUP --> UPC
OUP --> UPC
Reviews (1): Last reviewed commit: "refactor(usage): make the provider contr..." | Re-trigger Greptile
… contract (stablyai#12082) * refactor(usage): share the session/daily fold between Codex and OpenCode The Codex and OpenCode scanners each carried their own byte-identical copy of the ~325-line aggregation pipeline (createEmptySession, the three breakdown folds, finalizeSessions, mergeSessions, mergeDailyAggregates). Two copies means a token-accounting fix — a bucket that double-counts, a merge that drops a breakdown row — lands in one provider and silently not the other. The copies had already started to drift in comments only; the next drift would have been in arithmetic. The providers differ in exactly one dimension: the extra metric folded alongside the token counters (Codex `hasInferredPricing`, OpenCode `estimatedCostUsd`). That is now injected as an empty/fromEvent/fold triple, so the shared code stays generic without collapsing the two record schemas into a nullable union. The clone strategy stays per-provider (`cloneSessionForMerge` vs `structuredClone`) rather than being unified on the assumption that the difference is accidental. `usage-provider-contract.ts` is the seam a plugin-contributed usage source will implement. It is deliberately generic over each provider's record types: Claude bills per turn while Codex/OpenCode bill per event, and `cachedInput` is a subset of `input` for the latter but a peer bucket for Claude, so a single normalized record would push nullable handling onto every consumer. No behavior change. Emitted objects are byte-identical, including key insertion order — verified by diffing JSON.stringify of the scan output before and after across mixed models, mixed locations, an inferred-pricing flip, and null vs non-null cost. Persisted field names and schemaVersion are untouched, so caches do not invalidate. * refactor(usage): make the provider contract load-bearing and dedupe worktree refs Follow-up to the aggregation extraction, addressing three review points. `UsageProvider`/`UsageScanResult` were declaration-only, which is the same speculative-interface problem stablyai#12077 just deleted 8,900 lines of. They are now implemented by both real providers via `satisfies`, so the seam is typechecked against actual scan functions rather than asserted. The blocker was that codex returns `processedFiles` and opencode returns `processedDatabases`; rather than rename persisted-adjacent fields, the source key is a type parameter, so each provider keeps its own on-disk name and the contract still binds. Verified the constraint bites: swapping the key to 'processedSources' fails typecheck. `schemaVersion` is part of provider identity in the contract, so each provider's SCHEMA_VERSION constant (with its cache-invalidation rationale) moves into the provider module and the store imports it. Values are unchanged (codex 5, opencode 2) and the stores compare them exactly as before, so no cache invalidates. This also keeps store -> provider -> scanner acyclic. `UsageWorktreeRef` collided with the existing export in usage-worktree-metadata (3 fields, no repoId). Two different exported types under one name in src/main is worse than the duplication being removed, so the scan-input type is now `UsageScanWorktreeRef`; usage-worktree-metadata is untouched. `createWorktreeRefs` was triplicated. Codex, OpenCode, and Claude copies are byte-identical apart from the return type name (verified by diff), and all three ref types have the same four fields, so one shared copy replaces all three. This is the only change to claude-usage/. No behavior change: same functions, same arguments, same call order. The store tests' `./scanner` mock still intercepts scanning because the provider captures the mocked binding; their now-inert `createWorktreeRefs` mock key is dropped so it does not read as still mocking something.
What
Collapses the ~325-line session/daily aggregation block that was duplicated verbatim between
codex-usage/scanner.tsandopencode-usage/scanner.tsinto one shared fold, and puts a typed provider seam in front of it.Net −108 lines (+696 / −804 across 17 files).
Why a contract, not just a dedupe
The shared fold is parameterized by an extra-metric monoid (
fold) and a clone strategy, because the two providers genuinely differ there — Codex carrieshasInferredPricingand clones viacloneSessionForMerge; OpenCode carriesestimatedCostUsdand clones viastructuredClone.UsageProviderwraps that so a future plugin-contributed usage source has a real registration point rather than a convention.The contract is deliberately generic over each provider's record types. Claude bills per turn while Codex/OpenCode bill per event, and
cachedInputis a subset ofinputfor the latter but a peer bucket for Claude. A single normalized record would push nullable handling onto every consumer, so only the scan envelope is shared.UsageScanResultkeeps the source-cache field name as a type parameter (processedFiles/processedDatabases) because those names are persisted on disk and must not be renamed.What is deliberately NOT touched
attributeCodexUsageEvent/attributeOpenCodeUsageEventare near-verbatim duplicates and are a good follow-up, but not here.schemaVersionvalues (Codex 5, OpenCode 2, both unchanged) — no cache invalidation.claude-usage/beyond removing one byte-identicalcreateWorktreeRefs(19 lines) and its import.Verification
src/main/{codex,opencode,claude}-usage+ai-vault: 49 files / 325 tests pass, identical to the pre-change baseline.pnpm typecheckclean;oxlintclean;oxfmton changed files only.parseCodexUsageFile/parseOpenCodeUsageDatabasewas dumped viaJSON.stringify, then the scanners were stashed and the same fixture re-run against the original code — byte-identical, which pins values and key order.structuredClone, existing entries are only assigned to pre-existing keys, and bothfoldimplementations write a property that already exists. The extracted merge was diffed line-for-line against the inline originals for both providers across all four breakdown levels.pnpm audit:dead-code(knip): zero findings in any new or changed file — the contract types are all load-bearing.Note on file layout
The extracted module was split into three files (
usage-rollup-records,usage-rollup-merge,usage-event-aggregation) along a real seam rather than adding amax-linesdisable, whichAGENTS.mdprohibits.Made with Orca 🐋