Skip to content

refactor(usage): share the Codex/OpenCode scan fold behind a provider contract - #12082

Merged
nwparker merged 2 commits into
stablyai:mainfrom
nwparker:nwparker/slim-usage-aggregation
Aug 2, 2026
Merged

nwparker merged 2 commits into
stablyai:mainfrom
nwparker:nwparker/slim-usage-aggregation

Conversation

@nwparker

@nwparker nwparker commented Aug 2, 2026 •

Copy link
Copy Markdown
Contributor

What

Collapses the ~325-line session/daily aggregation block that was duplicated verbatim between codex-usage/scanner.ts and opencode-usage/scanner.ts into 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 carries hasInferredPricing and clones via cloneSessionForMerge; OpenCode carries estimatedCostUsd and clones via structuredClone. UsageProvider wraps 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 cachedInput is a subset of input for 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.

UsageScanResult keeps 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

  • Attribution and worktree matching. Claude uses a different matching algorithm that yields different answers; unifying it would change results. attributeCodexUsageEvent / attributeOpenCodeUsageEvent are near-verbatim duplicates and are a good follow-up, but not here.
  • Codex cumulative-delta resolution, pricing/model normalization, store query semantics.
  • Persisted field names and schemaVersion values (Codex 5, OpenCode 2, both unchanged) — no cache invalidation.
  • claude-usage/ beyond removing one byte-identical createWorktreeRefs (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 typecheck clean; oxlint clean; oxfmt on changed files only.
  • Output equivalence probed, not assumed: a fixture driving parseCodexUsageFile / parseOpenCodeUsageDatabase was dumped via JSON.stringify, then the scanners were stashed and the same fixture re-run against the original code — byte-identical, which pins values and key order.
  • Cross-source merge key order is preserved by construction: new entries enter via spread / structuredClone, existing entries are only assigned to pre-existing keys, and both fold implementations 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 a max-lines disable, which AGENTS.md prohibits.

Made with Orca 🐋

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.
@coderabbitai

coderabbitai Bot commented Aug 2, 2026

Copy link
Copy Markdown
Contributor

Warning

Review limit reached

@nwparker, you've reached your PR review limit, so we couldn't start this review.

Next review available in: 8 minutes

Enable usage-based reviews in Billing to review now. Otherwise, wait until the next included review is available.
You're only billed for reviews past your plan's rate limits ($0.25/file).

How can I continue?

After more reviews become available, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

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 configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 46175838-358e-4f74-8995-171e5d7b3f51

📥 Commits

Reviewing files that changed from the base of the PR and between 4a76565 and 7299b06.

📒 Files selected for processing (17)
  • src/main/claude-usage/scanner.ts
  • src/main/claude-usage/store.ts
  • src/main/codex-usage/codex-usage-provider.ts
  • src/main/codex-usage/scanner.ts
  • src/main/codex-usage/store.test.ts
  • src/main/codex-usage/store.ts
  • src/main/opencode-usage/opencode-usage-provider.ts
  • src/main/opencode-usage/scanner.ts
  • src/main/opencode-usage/store.test.ts
  • src/main/opencode-usage/store.ts
  • src/main/usage/usage-event-aggregation.ts
  • src/main/usage/usage-path-comparison.ts
  • src/main/usage/usage-provider-contract.ts
  • src/main/usage/usage-record-coercion.ts
  • src/main/usage/usage-rollup-merge.ts
  • src/main/usage/usage-rollup-records.ts
  • src/main/usage/usage-worktree-refs.ts

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.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@greptile-apps

greptile-apps Bot commented Aug 2, 2026

Copy link
Copy Markdown

Greptile Summary

This PR eliminates a ~325-line verbatim duplication of the session/daily aggregation block that existed in both codex-usage/scanner.ts and opencode-usage/scanner.ts, replacing it with a single generic fold engine (createUsageEventAggregation) parameterized by a provider-specific metric monoid. A UsageProvider contract type is introduced as a formal registration seam for future plugin-contributed usage sources.

  • New shared modules (usage-event-aggregation.ts, usage-rollup-merge.ts, usage-rollup-records.ts) house the extracted fold logic, keeping each file under the project's max-lines limit by splitting along genuine seams.
  • Provider objects (codexUsageProvider, openCodeUsageProvider) satisfy the UsageProvider contract and serve as the single source of truth for each provider's schemaVersion.
  • Persisted field names (processedFiles, processedDatabases) and both schemaVersion values are unchanged, so no cache invalidation occurs for existing users.

Confidence Score: 5/5

Safe 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.

Important Files Changed

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
Loading

Reviews (1): Last reviewed commit: "refactor(usage): make the provider contr..." | Re-trigger Greptile

@nwparker
nwparker merged commit 07bd574 into stablyai:main Aug 2, 2026
44 checks passed
enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
… 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.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant