Skip to content

refactor: normalize Claude usage responses at one boundary - #144707

Merged
jesse-merhi merged 2 commits into
mainfrom
refactor/claude-usage-schema
Sep 11, 2026
Merged

jesse-merhi merged 2 commits into
mainfrom
refactor/claude-usage-schema

Conversation

@jesse-merhi

@jesse-merhi jesse-merhi commented Sep 11, 2026 •

Copy link
Copy Markdown
Member

What Problem This Solves

Claude usage parsing currently normalizes billing but leaves windows and model scopes as raw records for projections to interpret. This maintainer-requested cleanup gives those consumed fields one typed boundary, reducing the places that must stay aligned when the provider response changes.

Why This Change Was Made

Use the existing Zod dependency with the existing finite-number, string and reset-time helpers. Infer the normalized type from the schema and remove downstream raw-record parsing. Normalize malformed fields independently so valid siblings survive.

User Impact

No intended behavior change. OAuth and web usage retain window ordering, Sonnet precedence, model-label deduplication, reset handling and their distinct billing projections. No dependency, configuration or authentication changes.

Evidence

Source-flow comparison:

Before After
Normalize billing, retain raw usage records, parse window/model fields while projecting. Normalize all consumed fields once, then project typed windows and billing.

Representative response through fetchClaudeUsage:

{"seven_day_sonnet":{"utilization":40},"limits":[{"percent":80,"scope":{"model":{"display_name":" sonnet "}}},{"percent":27,"scope":{"model":{"display_name":" ","id":" Fable "}}},{"percent":90,"scope":{"model":{"display_name":"FABLE"}}},{"percent":12,"is_active":"false","scope":{"model":{"id":"Other"}}}]}

The preserved snapshot contains Sonnet 40%, Fable 27%, and Other 12%, in that order. Labels trim and deduplicate case-insensitively. Only literal is_active: false disables a limit. This boundary fixture passed with the existing OAuth/web and billing cases.

Head 4a151324d172a24be66d33f0578bcb6d2c5bd85f passed all 27 Claude fetch tests on Blacksmith Testbox. Both callers invoke the schema directly; its preprocess step preserves the top-level nonobject fallback. Focused test run. Current-head CI and repository checks.

Two native passes and a fresh independent review, including separate test and TypeScript assessments, found no actionable issues on this head. No review repairs were needed. Authenticated live Claude usage was not exercised.

The focused run's later broad check stopped at an assertion-baseline comparison in three untouched files against its remote main. Those paths and the baseline are unchanged by this PR; the linked PR-scoped CI runs the base-aware ratchet and remaining checks.

AI-assisted implementation.

Change Breakdown

Part Files +LOC -LOC
Implementation 1 77 64
Tests and fixtures 1 22 0
Total 2 99 64

The 13-line production increase gives windows and nested model scopes typed ownership while removing the raw-record projection path and handwritten normalized types.

@clawsweeper

clawsweeper Bot commented Sep 11, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

Pull request received. I will update this pull request when review starts.

ClawSweeper review complete

ClawSweeper finished reviewing this revision. The review result is being finalized.

View the workflow run.

@openclaw-barnacle openclaw-barnacle Bot added size: S maintainer Maintainer-authored PR labels Sep 11, 2026
@jesse-merhi

Copy link
Copy Markdown
Member Author

/clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Sep 11, 2026

Copy link
Copy Markdown
Contributor

🦞🧹
ClawSweeper re-review requested.

I asked ClawSweeper to review this item again.
Action: item re-review queued (workflow sweep.yml, event exact_review_queue).
Result: when the review finishes, ClawSweeper will create the durable review comment if needed or update the existing comment in place.

@clawsweeper

clawsweeper Bot commented Sep 11, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@clawsweeper clawsweeper Bot added P3 Low-priority cleanup, docs, polish, ergonomics, or speculative work. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. labels Sep 11, 2026
@clawsweeper

clawsweeper Bot commented Sep 11, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge. Reviewed September 11, 2026, 8:43 AM ET / 12:43 UTC (Revision 5).

ClawSweeper review

What this changes

The PR normalizes Claude quota windows, model labels, and billing through one typed schema while preserving existing usage summaries.

Merge readiness

✅ Ready for maintainer review

Keep open as a useful, behavior-preserving cleanup with no actionable findings. Current main retains the older parsing structure, and the previous draft-status follow-up is resolved.

Priority: P3
Reviewed head: 4a151324d172a24be66d33f0578bcb6d2c5bd85f

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) A focused refactor with meaningful boundary coverage and no identified correctness or security defects.
Proof confidence 🌊 off-meta tidepool Not applicable: This MEMBER-authored parsing refactor is exempt from the external-contributor proof gate and does not materially change authority. The reported fetch-boundary tests are supplemental evidence; authenticated OAuth/web execution was explicitly not performed.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Not applicable Not applicable: This MEMBER-authored parsing refactor is exempt from the external-contributor proof gate and does not materially change authority. The reported fetch-boundary tests are supplemental evidence; authenticated OAuth/web execution was explicitly not performed.
Evidence reviewed 8 items Verified introduced change: The pinned base-to-head diff matches the supplied introduction evidence. Both usage callers use the same schema; downstream raw-record parsing is removed without changing request credentials, endpoints, fallback selection, or snapshot types.
Still distinct from current main: Fetched main still normalizes billing separately and interprets raw window and model records during projection; the proposed typed normalization boundary is not present.
Latest release comparison: The v2026.9.4 source also retains the older normalization structure, so the requested cleanup is not already shipped there.
Findings None None.
Security None None.

How this fits together

Claude usage collection converts OAuth or web API responses into provider-neutral quota and billing snapshots. These snapshots feed OpenClaw’s status commands and usage displays.

flowchart LR
  A[OAuth usage response] --> C[Normalize consumed fields]
  B[Web usage response] --> C
  C --> D[Order and deduplicate quota windows]
  C --> E[Project extra usage billing]
  D --> F[Provider usage snapshot]
  E --> F
  F --> G[Status and usage displays]
Loading

Before merge

None.

Agent review details

Security

None.

PR surface

Source +13, Tests +22. Total +35 across 2 files.

View PR surface stats
Area Files Added Removed Net
Source 1 77 64 +13
Tests 1 22 0 +22
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 2 99 64 +35

Review metrics

None.

Technical review

Best possible solution:

Keep one normalization boundary for both Claude usage paths while preserving tolerant field handling and the existing public snapshot contract.

Do we have a high-confidence way to reproduce the issue?

Not applicable: this is a behavior-preserving refactor, and source comparison found no concrete introduced failure.

Is this the best way to solve the issue?

Yes: the schema reuses existing coercion helpers, replaces the raw-record projection path, and serves both callers without adding a parallel implementation.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning medium; reviewed against 4407ed19ac63.

Labels

Label justifications:

  • P3: This is a bounded internal cleanup with no intended user-visible behavior change.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🌊 off-meta tidepool and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Not applicable: This MEMBER-authored parsing refactor is exempt from the external-contributor proof gate and does not materially change authority. The reported fetch-boundary tests are supplemental evidence; authenticated OAuth/web execution was explicitly not performed.

Evidence

What I checked:

  • Verified introduced change: The pinned base-to-head diff matches the supplied introduction evidence. Both usage callers use the same schema; downstream raw-record parsing is removed without changing request credentials, endpoints, fallback selection, or snapshot types. (src/infra/provider-usage.fetch.claude.ts:43, 4a151324d172)
  • Still distinct from current main: Fetched main still normalizes billing separately and interprets raw window and model records during projection; the proposed typed normalization boundary is not present. (src/infra/provider-usage.fetch.claude.ts:30, 4407ed19ac63)
  • Latest release comparison: The v2026.9.4 source also retains the older normalization structure, so the requested cleanup is not already shipped there. (src/infra/provider-usage.fetch.claude.ts:30, 3a9d69db306c)
  • Meaningful boundary coverage: Read the complete fetcher and test file. The added test exercises the public fetch boundary and protects trimming, case-insensitive deduplication, absent activity flags, and literal-false semantics. Existing tests cover malformed siblings, billing, resets, precedence, and web fallback. (src/infra/provider-usage.fetch.claude.test.ts:171, 4a151324d172)
  • Schema dependency contract: The new Zod import and optional/transform/catch composition establish a direct dependency signal. Inspected v4.4.3 implementations of those operators; the tag resolves to this dependency commit. OpenClaw already declares Zod 4.4.3. (packages/zod/src/v4/core/schemas.ts:3421, 1fb56a5c18c2)
  • Related merged work and routing history: Main history includes normalization-helper adoption by Peter Steinberger and malformed-response hardening by Leon-SK668. The supplied merged fix(infra): guard malformed Claude usage responses #111088 explicitly scoped itself to shape guards, so it does not supersede this cleanup. Deeper follow-history and blame inspection encountered unavailable historical blobs; exact introducing-line attribution remains unverified. (src/infra/provider-usage.fetch.claude.ts, 4407ed19ac63)

Likely related people:

  • Peter Steinberger: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)
  • Leon-SK668: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)

Rating scale

Score Internal tier Crab rank Meaning
6/6 S 🦀 challenger crab Exceptional readiness
5/6 A 🦞 diamond lobster Very strong readiness
4/6 B 🐚 platinum hermit Good normal PR; ordinary maintainer review
3/6 C 🦐 gold shrimp Useful, but confidence is limited
2/6 D 🦪 silver shellfish Proof or implementation needs work
1/6 F 🧂 unranked krab Not merge-ready
N/A NA 🌊 off-meta tidepool Rating does not apply

Overall follows the weaker of proof and patch quality.
Shiny media proof means a screenshot, video, or linked artifact directly shows the changed behavior. Runtime, network, CSP, and security claims still need visible diagnostics.

Workflow

  • ClawSweeper keeps one durable marker-backed review comment per issue or PR.
  • Re-runs edit this comment so the latest verdict, findings, and automation markers stay together instead of adding duplicate bot comments.
  • A fresh review can be triggered by eligible @clawsweeper re-review comments, exact-item GitHub events, scheduled/background review runs, or manual workflow dispatch.
  • PR/issue authors and users with repository write access can comment @clawsweeper re-review or @clawsweeper re-run on an open PR or issue to request a fresh review only.
  • Maintainers can also comment @clawsweeper review to request a fresh review only.
  • Fresh-review commands do not start repair, autofix, rebase, CI repair, or automerge.
  • Maintainer-only repair and merge flows require explicit commands such as @clawsweeper autofix, @clawsweeper automerge, @clawsweeper fix ci, or @clawsweeper address review.
  • Maintainers can comment @clawsweeper explain to ask for more context, or @clawsweeper stop to stop active automation.

History

Review history (4 earlier review cycles)
  • reviewed 2026-09-11T07:26:19.330Z sha 9422baf :: needs maintainer review before merge. :: none
  • reviewed 2026-09-11T11:50:26.424Z sha 4a15132 :: needs changes before merge. :: none
  • reviewed 2026-09-11T12:25:41.468Z sha 4a15132 :: needs changes before merge. :: none
  • reviewed 2026-09-11T12:36:11.741Z sha 4a15132 :: needs changes before merge. :: none

@jesse-merhi

Copy link
Copy Markdown
Member Author

/clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Sep 11, 2026 •

Copy link
Copy Markdown
Contributor

🦞🧹
ClawSweeper re-review requested.

I asked ClawSweeper to review this item again.
Action: item re-review queued (workflow sweep.yml, event exact_review_queue).
Result: when the review finishes, ClawSweeper will create the durable review comment if needed or update the existing comment in place.

Re-review progress:

@jesse-merhi

Copy link
Copy Markdown
Member Author

/clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Sep 11, 2026 •

Copy link
Copy Markdown
Contributor

🦞🧹
ClawSweeper re-review requested.

I asked ClawSweeper to review this item again.
Action: item re-review queued (workflow sweep.yml, event exact_review_queue).
Result: when the review finishes, ClawSweeper will create the durable review comment if needed or update the existing comment in place.

Re-review progress:

@jesse-merhi
jesse-merhi marked this pull request as ready for review September 11, 2026 12:39
Copilot AI lite review requested due to automatic review settings September 11, 2026 12:39

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot was unable to review this pull request because the user who requested the review has reached their quota limit.

@jesse-merhi
jesse-merhi merged commit 2852d63 into main Sep 11, 2026
364 of 365 checks passed
@jesse-merhi
jesse-merhi deleted the refactor/claude-usage-schema branch September 11, 2026 13:20
@jesse-merhi

Copy link
Copy Markdown
Member Author

Merged via squash.

vincentkoc added a commit that referenced this pull request Sep 11, 2026
* commit 'f2ce199238e974b1d4caff8f11112aa51eb00d9e': (310 commits)
  refactor(copilot): deduplicate transcript user text (#144888)
  refactor(sessions): await discovery and config readiness (#144854)
  refactor(e2e): deduplicate release file assertions (#144904)
  ci: keep growing hosted test plans within the job cap (#144965)
  fix(macos): avoid stale dashboard command assertions (#144710)
  refactor(memory): await standing intent operations (#144832)
  refactor(ui): derive native device settings types from schemas (#144705)
  refactor(memory): await journal operations and allocate sequences atomically (#144824)
  refactor(tests): share command field assertions (#144955)
  refactor(matrix): share bounded context cache insertion (#144939)
  refactor(i18n): share Apple catalog reader (#144848)
  fix(doctor): preserve legacy registry files when quarantine fails (#144787)
  refactor(tests): reuse PixVerse auth fixtures (#144926)
  fix(bonjour): silence transient ENODEV socket warnings (#144870)
  fix(matrix): preserve unrelated files when migration fails (#144883)
  feat(sqlite): run Team Reports storage in owned workers (#144871)
  fix(update): install explicit same-version artifacts (#144894)
  refactor(ui): share cached message extraction (#144244)
  refactor: normalize Claude usage responses at one boundary (#144707)
  refactor: simplify CLI child listener registration (#144929)
  ...
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Sep 12, 2026
…144707)

* refactor: normalize Claude usage responses at one boundary

* refactor: remove Claude usage normalization wrapper
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

maintainer Maintainer-authored PR P3 Low-priority cleanup, docs, polish, ergonomics, or speculative work. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. size: S status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants