Skip to content

feat(routing): add quota-aware policy scoring - #1014

Merged
Wibias merged 8 commits into
lidge-jun:devfrom
Wibias:feat/ri-07-quota-aware-routing
Aug 5, 2026
Merged

feat(routing): add quota-aware policy scoring#1014
Wibias merged 8 commits into
lidge-jun:devfrom
Wibias:feat/ri-07-quota-aware-routing

Conversation

@Wibias

@Wibias Wibias commented Aug 4, 2026

Copy link
Copy Markdown
Collaborator

Summary

RI-07 of the Router Intelligence / Routing Control Plane programme. Adds
quota-aware policy scoring: candidates are scored on known remaining
headroom, exhausted state, reset time, and (configurable) minimum-headroom
requirements - using the existing privacy-safe quota caches.

Unknown quota stays unknown (never zero); the profile's unknownEvidence.quota
policy decides how unknown evidence affects eligibility and score.

Scope

  • src/routing/quota.ts:
    • quotaEvidenceForCandidate() - Codex pool accounts
      (getAccountQuota, usage percents only) and Anthropic per-account quota
      cache; headroom as a 0..1 fraction, exhausted, nearest future
      resetAtMs, and a stable source code.
    • quotaScore() - deterministic: headroom fraction (larger is better),
      exhausted -> 0, unknown -> null.
  • src/routing/trace.ts - RouteQuotaEvidence gains headroom (fraction);
    bounded parse.
  • src/types.ts / src/routing/profile.ts - new hard requirement
    require.minQuotaHeadroom (0..1), validated and normalized like every
    other requirement.
  • src/routing/evaluator.ts - quota scoring folded into the composite:
    total = priority*priorityWeight + health*healthWeight + quota*quotaWeight
    where implemented weights come from profile.optimize. Unknown quota:
    exclude -> unknown-quota exclusion (ineligible), penalize ->
    deterministic 0.3 floor, allow -> priority-only. minQuotaHeadroom
    gates eligibility as a hard requirement.
  • src/router.ts - execution assembles quota evidence per candidate.
  • Docs: require.minQuotaHeadroom documented in the routing reference.
  • tests/quota-scoring.test.ts - 7 tests.

Where policy selection ends and account-pool selection begins

  • Policy profiles select provider/model targets. They never select Codex
    accounts: exact account selectors and existing pool strategies
    (quota/round-robin/fill-first, cooldown, affinity) remain authoritative in
    their existing scope.
  • Account-level quota evidence (codex openai accounts, Anthropic account
    refs) is consumed when a candidate carries an account reference
    (dry-run/evaluate with candidates[].accountRef/codexAccountId).
    Execution-time candidates without account refs get honest unknown quota.
  • Exact account selectors continue to fail closed; nothing in this PR can
    silently switch a pinned account.

Privacy / security

  • Quota evidence is usage-percent fractions and reset timestamps from
    existing caches - no raw quota responses, account emails, or tokens.
  • bun run privacy:scan passes.

Compatibility

  • Additive schema knob (minQuotaHeadroom); existing configs load unchanged.
  • Existing routing untouched; RI-05/06 behavior preserved when a profile sets
    optimize.quota: 0 and unknownEvidence.quota: allow.

Dependency

Non-goals

Local verification (exact)

  • bun x tsc --noEmit -> PASSED (0 errors)
  • bun run test tests/quota-scoring.test.ts -> 7/7 pass
  • Focused regression suites -> 203/203 pass across 9 files
  • bun run privacy:scan -> passed

Summary by CodeRabbit

  • New Features

    • Added quota-aware routing that considers remaining provider capacity when selecting candidates.
    • Added configurable minimum quota headroom requirements and handling for unavailable quota data.
    • Added quota evidence from local provider caches, including account-specific and pool-based routing.
    • Included quota details in routing evaluations, dry runs, and route traces.
  • Bug Fixes

    • Prevented selected provider aliases from triggering recursive policy lookup.
    • Improved request-history indexing when usage details are unavailable.
  • Documentation

    • Updated routing configuration guidance with quota evidence and account lookup details.

@coderabbitai

coderabbitai Bot commented Aug 4, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

Warning

Review limit reached

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

Next review available in: 18 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: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro Plus

Run ID: 452b5922-c308-486c-b1cc-647f0c6a43a4

📥 Commits

Reviewing files that changed from the base of the PR and between 3fd1a00 and f1ec2d6.

📒 Files selected for processing (1)
  • docs-site/src/content/docs/reference/configuration/routing.md
📝 Walkthrough

Walkthrough

Routing policies now use cached quota headroom for requirements, trace evidence, candidate scoring, and account-aware routing. The PR also updates tests, routing documentation, and stack records.

Changes

Quota-aware routing

Layer / File(s) Summary
Quota evidence and requirement contracts
src/routing/profile.ts, src/routing/trace.ts, src/types.ts
Adds minQuotaHeadroom to routing requirements and adds normalized fractional quota headroom to trace evidence.
Quota evidence generation
src/routing/quota.ts
Builds Codex and Anthropic quota evidence from cached account data and returns bounded quota scores.
Quota eligibility and scoring
src/routing/evaluator.ts
Checks minimum headroom, handles unknown quota, and combines priority, health, and quota scores.
Account-aware routing integration
src/router.ts, src/server/management/routing-profile-routes.ts
Adds quota evidence to candidates and uses effective Codex or active account references for quota lookup.
Quota verification and documentation
tests/*, docs-site/src/content/docs/reference/configuration/routing.md, devlog/_plan/260804_router_intelligence/001_pr_stack_status.md
Adds quota, request-evidence, history-index, API dry-run, configuration, and review-status coverage.

Estimated code review effort: 4 (Complex) | ~45 minutes

Sequence Diagram(s)

sequenceDiagram
  participant Router
  participant QuotaEvidence
  participant PolicyEvaluator
  participant RoutingProfile
  Router->>QuotaEvidence: Build account-aware quota evidence
  QuotaEvidence-->>Router: Return evidence or unknown
  Router->>PolicyEvaluator: Evaluate candidate
  PolicyEvaluator->>RoutingProfile: Check minQuotaHeadroom
  RoutingProfile-->>PolicyEvaluator: Return eligibility
  PolicyEvaluator-->>Router: Return weighted score
Loading

Possibly related PRs

Suggested reviewers: ingwannu, lidge-jun

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 57.14% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly and concisely describes the main change: adding quota-aware policy scoring to routing.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

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

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 9dbdce2ab2

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread src/router.ts Outdated
Comment thread src/routing/request-evidence.ts Outdated
Comment thread src/routing/history/indexer.ts Outdated
Comment thread src/router.ts
Comment thread src/routing/evaluator.ts Outdated
Comment thread src/routing/capability.ts Outdated
Comment thread src/routing/evaluator.ts Outdated
Comment thread src/routing/history/indexer.ts
@Wibias
Wibias force-pushed the feat/ri-07-quota-aware-routing branch from 9dbdce2 to dce85b7 Compare August 5, 2026 03:55
@Wibias

Wibias commented Aug 5, 2026

Copy link
Copy Markdown
Collaborator Author

[GD] Verdict: changes-requested

TLDR

  • PR: feat(routing): add quota-aware policy scoring #1014 — feat(routing): add quota-aware policy scoring
  • Head: dce85b74 on dev (mergeStateStatus: dirty)
  • Decision: useful; all review findings and all 8 bot threads are fixed (one declined with verified rationale); the only remaining blocker is the deliberately deferred base sync (waiting for feat(routing): execute capability-aware policy profiles #1012 to merge), which also prevents fresh CI on this head
  • Usefulness: delivers quota-aware scoring and minQuotaHeadroom gating from existing privacy-safe quota caches; real claimed value
  • Bugs: none remaining — minQuotaHeadroom unknown handling no longer leaks through the capability policy, execution-time quota now reflects the active codex account, dry-run populates quota evidence, and all shared RI-06 fixes carry in via the rebase
  • Security: no confirmed findings; quota evidence is usage-percent fractions and reset timestamps only
  • Spec / standards: clean; explicit non-goal boundaries (cost = RI-08) respected
  • Reviews: CodeRabbit rate-limited (no review); 8 chatgpt-codex-connector threads fact-checked — 7 fixed + 1 declined (cost limits/weights = RI-08, implemented in feat(routing): add cost-aware policy scoring and limits #1015), all replied in-thread and resolved
  • Base / CI: head conflicts with dev — merge ref unavailable, so pull_request CI cannot run until the sync — owner action: update from dev after RI-05 (feat(routing): execute capability-aware policy profiles #1012) merges; local tsc --noEmit 0 errors, 252/252 routing tests, privacy:scan green on dce85b74
  • Gate: none (not draft/WIP); ship-gate blocked only on base-state
  • Owner actions: sync from latest dev after feat(routing): execute capability-aware policy profiles #1012 merges, push, verify fresh CI on the mergeable head
  • Bottom line: review loop closed; code is merge-ready apart from the deferred base sync — sync after feat(routing): execute capability-aware policy profiles #1012 lands and re-verify CI.
Full verdict

Semantic propagation

  • Concepts audited: quota evidence (codex-pool / anthropic account refs), quota score + headroom semantics, minQuotaHeadroom hard requirement, optimize.quota + unknownEvidence.quota defaults, RouteQuotaEvidence.headroom wire field.
  • Authoritative sources: src/routing/quota.ts, src/routing/profile.ts (defaults/validation), src/types.ts (schema), src/routing/trace.ts (wire shape + normalizer).
  • Producers and consumers checked: router policy path, evaluator, dry-run management route, trace builder/normalizer, codex/providers quota caches, docs (routing.md).
  • Public/derived representations checked: RouteQuotaEvidence in traces, parseQuota (bounds headroom to 0..1), docs; no new persistence.
  • Material variant partitions checked: codex vs anthropic vs unknown, exhausted vs headroom, account-ref present vs absent, unknown policies (exclude/penalize/allow), quotaWeight 0 vs >0.
  • Positive and negative assertions checked: headroom derivation, exhausted = 0, unknown-stays-unknown, unknown-quota policy, minQuotaHeadroom known gating + unknown policy attribution, execution account wiring.
  • Unmapped surfaces: none.
  • Unproven equivalence assumptions: none — the execution wiring gap (quota always unknown) is fixed via the active codex account and the boundary stays honest when no account exists.
  • Representation mismatches: none.
  • Variant coverage gaps: none (new unknown-headroom policy + execution wiring tests added).
  • Axis verdict: pass.

Usefulness

Fixes a real gap: policy routing now scores candidates on remaining quota headroom and can hard-gate on minQuotaHeadroom, fed by existing privacy-safe caches (Codex pool usage percents, Anthropic account quota). Unknown stays unknown and never zero, with profile-controlled handling. Useful.

Bugs / correctness

  • Method: bug-review.md — Bugbot: n/a (Codex host); static: typecheck + focused suites; complementary lenses: done (silent_failures, resource_leaks, edge_cases, api_cli_wiring).
  • Findings fixed: minQuotaHeadroom unknown was gated by unknownEvidence.capability and labeled unknown-capability (now governed by the quota policy, labeled unknown-quota); quota evidence always unknown at execution (now passes the active codex account); dry-run omitted quota evidence (now config-populated); misindented validation check fixed; shared RI-06 fixes (index tail, nested images, request-side requirements, alias collision, policy fallthrough, adapter tool inference, partial-row validation) carried in via the rebase.
  • Fixed this session: 1bb0b629, dce85b74 (rebased onto 9f997f88).

Security

  • Scope reviewed: authn/authz (no change), injection (no new queries), secrets (usage percents + reset timestamps only), logging/privacy (no prompts/keys), business logic (fail-closed on quota exclude), data storage (in-memory caches), supply chain/CI (no change).
  • Findings: none confirmed.
  • Fixed this session: none (no security findings).

Spec / standards

  • Spec source: PR body + devlog master plan.
  • Gaps: none — the non-goal boundary (no cost scoring/limits, RI-08) is respected; the one bot thread on cost is declined because feat(routing): add cost-aware policy scoring and limits #1015 (open) implements it.
  • Standards: deterministic scoring, bounded trace, regression tests; no documented rule violations.

Reviews

  • Owners/maintainers: none open.
  • Bots: CodeRabbit rate-limited (no review). 8 chatgpt-codex-connector threads fact-checked: 7 fixed in dce85b74, 1 declined (cost limits/weights — RI-08, feat(routing): add cost-aware policy scoring and limits #1015 open), all replied in-thread and resolved. No unresolved threads.

Base / CI

  • Behind/conflicts: dirty — head conflicts with dev; merge ref refs/pull/1014/merge does not exist, so pull_request CI cannot start. Owner action: update from dev after RI-05 (feat(routing): execute capability-aware policy profiles #1012) merges.
  • Required checks: none configured (no branch protection); prior heads CI green.
  • Local tip compile/tests: bun x tsc --noEmit 0 errors; routing suites 252/252; privacy:scan passed on dce85b74.

Simplification

  • Approved candidates applied: misindented require.minContextWindow check fixed (profile.ts); shared RI-06 simplify carried in via the rebase. No behavior change; gates re-run after application.

Gate

none (not draft/WIP/do-not-merge); ship-gate blocked only on base-state (deferred sync).

Bottom line

The review loop is closed: every confirmed finding and bot thread is fixed with evidence and regression coverage, and local gates are green. The single remaining item is the base sync after #1012 merges (deliberately deferred per your instruction) — once synced and CI is green on the mergeable head, this PR is ready for merge.

@Wibias
Wibias marked this pull request as draft August 5, 2026 04:29
@Wibias
Wibias marked this pull request as ready for review August 5, 2026 05:16
@Wibias
Wibias force-pushed the feat/ri-07-quota-aware-routing branch from 0c51002 to b3a1a1e Compare August 5, 2026 05:26

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 0c51002715

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread src/router.ts Outdated
Comment thread src/server/management/routing-profile-routes.ts Outdated
Comment thread src/routing/quota.ts Outdated
Comment thread docs-site/src/content/docs/reference/configuration/routing.md Outdated
Comment thread src/routing/evaluator.ts Outdated
@Wibias
Wibias force-pushed the feat/ri-07-quota-aware-routing branch from b3a1a1e to 7aebbd3 Compare August 5, 2026 05:29

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

Actionable comments posted: 6

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@devlog/_plan/260804_router_intelligence/001_pr_stack_status.md`:
- Around line 226-235: Update the RI-07 acceptance metadata in the verification
record: replace the pending PR entry with PR `#1014` and correct the quota-scoring
test count from 7/7 to 9/9, preserving the remaining verification details.

In `@docs-site/src/content/docs/reference/configuration/routing.md`:
- Around line 155-162: The routing quota documentation incorrectly describes
runtime quota as always unknown and says quota scoring is planned. Update the
runtime candidate and quota-scoring sections to document that Pool mode
preserves its existing account selection, then reads quota for the selected
account, while Direct mode reads quota only from the current account; clarify
that quota evidence does not affect account selection, session affinity,
cooldowns, or switching behavior, and align the wording with the
Pool-versus-Direct CLI/API behavior.

In `@src/router.ts`:
- Around line 511-521: Update quotaEvidenceForCandidate calls in src/router.ts
lines 511-521 and src/server/management/routing-profile-routes.ts lines 129-139
to provide the resolved Anthropic accountRef, using the existing
account-reference resolution path alongside the pooled Codex account handling.
Apply the same resolution in both live routing and automatic dry-run paths so
Anthropic quota can be loaded.

In `@src/routing/evaluator.ts`:
- Around line 120-126: Update the minQuotaHeadroom requirement logic in the
evaluator to use quotaScore(quota) as the normalized actual value instead of
directly checking quota.headroom. Emit the requirement only when the normalized
score is non-null, so exhausted evidence without headroom evaluates as zero
while unknown or incomplete evidence is excluded. Add regressions covering
exhausted quota without headroom and unknown quota with malformed headroom.

In `@src/routing/quota.ts`:
- Around line 33-49: Update quotaEvidenceForCandidate() to obtain and use the
Codex account plan when processing codexAccountId. Select only the plan-specific
percentage and reset timestamp—monthly for go/free accounts and the existing
applicable value for other plans—then compute headroom and resetAtMs from those
values and pass plan to isCodexQuotaExhausted(quota, plan), preserving the
existing evidence shape.

In `@tests/quota-scoring.test.ts`:
- Around line 87-115: Extend the test around evaluatePolicyProfile to add an
unknownEvidence.quota: "allow" configuration and evaluation. Assert the
candidate remains eligible and its quota score is not
QUOTA_UNKNOWN_PENALTY_SCORE, completing coverage of the exclude, penalize, and
allow branches.
🪄 Autofix

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro Plus

Run ID: a201279c-2937-4fa0-9b88-6d84fc5273f3

📥 Commits

Reviewing files that changed from the base of the PR and between ebcfff4 and 480f157.

📒 Files selected for processing (14)
  • devlog/_plan/260804_router_intelligence/001_pr_stack_status.md
  • docs-site/src/content/docs/reference/configuration/routing.md
  • src/router.ts
  • src/routing/evaluator.ts
  • src/routing/profile.ts
  • src/routing/quota.ts
  • src/routing/trace.ts
  • src/server/management/routing-profile-routes.ts
  • src/types.ts
  • tests/policy-execution.test.ts
  • tests/quota-scoring.test.ts
  • tests/request-evidence.test.ts
  • tests/request-history-index.test.ts
  • tests/routing-profile.test.ts

Comment thread devlog/_plan/260804_router_intelligence/001_pr_stack_status.md Outdated
Comment thread docs-site/src/content/docs/reference/configuration/routing.md
Comment thread src/router.ts
Comment thread src/routing/evaluator.ts Outdated
Comment thread src/routing/quota.ts
Comment thread tests/quota-scoring.test.ts

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

Actionable comments posted: 1

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
docs-site/src/content/docs/reference/configuration/routing.md (1)

155-165: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Document missing quota as unknown.

If the cache has no usable reading, or the reading is incomplete, quota remains unknown. The evaluator then applies unknownEvidence.quota as exclude, penalize, or allow. Do not describe missing data as exhaustion or zero headroom.

Suggested wording
 Quota evidence ... is keyed by account.
+Missing or incomplete cached readings remain unknown. `unknownEvidence.quota`
+controls whether the candidate is excluded, penalized, or allowed.

As per path instructions, quota coverage must be described explicitly and missing readings must not be treated as usage.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@docs-site/src/content/docs/reference/configuration/routing.md` around lines
155 - 165, Update the quota evidence documentation around the local Codex and
Anthropic quota caches to state explicitly that absent, unusable, or incomplete
readings remain unknown and are evaluated through unknownEvidence.quota as
exclude, penalize, or allow. Clarify that missing data must not be interpreted
as quota exhaustion, zero headroom, or usage, while preserving the existing
account-selection and candidate-evidence behavior.

Source: Path instructions

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@docs-site/src/content/docs/reference/configuration/routing.md`:
- Around line 174-176: Remove the inactive cost scoring entry from the
scoring-weight table in the routing configuration documentation, or explicitly
mark it as reserved until RI-08; keep the documented scoring weights aligned
with the behavior implemented by the evaluator and retain cost only as the
limits.maxEstimatedCostUsd hard cap.

---

Outside diff comments:
In `@docs-site/src/content/docs/reference/configuration/routing.md`:
- Around line 155-165: Update the quota evidence documentation around the local
Codex and Anthropic quota caches to state explicitly that absent, unusable, or
incomplete readings remain unknown and are evaluated through
unknownEvidence.quota as exclude, penalize, or allow. Clarify that missing data
must not be interpreted as quota exhaustion, zero headroom, or usage, while
preserving the existing account-selection and candidate-evidence behavior.
🪄 Autofix

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro Plus

Run ID: 58275fd3-14f2-487f-9db7-da1d4eb9082d

📥 Commits

Reviewing files that changed from the base of the PR and between 480f157 and 850c625.

📒 Files selected for processing (7)
  • devlog/_plan/260804_router_intelligence/001_pr_stack_status.md
  • docs-site/src/content/docs/reference/configuration/routing.md
  • src/router.ts
  • src/routing/evaluator.ts
  • src/routing/quota.ts
  • src/server/management/routing-profile-routes.ts
  • tests/quota-scoring.test.ts

Comment thread docs-site/src/content/docs/reference/configuration/routing.md Outdated

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

Actionable comments posted: 1

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (2)
docs-site/src/content/docs/reference/configuration/routing.md (2)

160-161: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Do not describe quota as scoring-only.

require.minQuotaHeadroom is evaluated before scoring in src/routing/evaluator.ts Lines 98-176. A candidate with insufficient known headroom becomes ineligible. unknownEvidence.quota: "exclude" can also exclude a candidate.

Change the sentence to state that quota affects policy-profile eligibility and scoring. Keep the existing clarification that quota does not change Codex account selection, session affinity, cooldowns, or switching.

As per path instructions, quota must not be described as changing account selection or switching behavior, but its eligibility effect must remain documented.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@docs-site/src/content/docs/reference/configuration/routing.md` around lines
160 - 161, Update the quota behavior description near the dry-run/API
clarification to state that quota affects policy-profile eligibility and
scoring, while preserving that it does not change Codex account selection,
session affinity, cooldowns, or switching behavior.

Source: Path instructions


155-159: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Document that API-key routes never use Codex accounts.

Lines 155-159 distinguish Pool and Direct modes, but they do not state the API-key boundary. Add that API-key routes use their configured provider credentials and never resolve Codex pool or main accounts for quota evidence.

As per path instructions, Pool, Direct, and API-key account behavior must be documented separately.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@docs-site/src/content/docs/reference/configuration/routing.md` around lines
155 - 159, Update the quota evidence section in the routing documentation to
explicitly state that API-key routes use their configured provider credentials
and never resolve Codex pool or main accounts for quota evidence. Keep Pool,
Direct, and API-key account behavior described as separate cases.

Source: Path instructions

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@docs-site/src/content/docs/reference/configuration/routing.md`:
- Line 107: Update the optimize configuration documentation at the entries
corresponding to lines 107 and 138 to match the scoring behavior implemented by
evaluator.ts: only health, quota, and configuredPriority are scored directly,
while normalized latency and cost weights are folded into configuredPriority,
yielding a default configuredPriority share of 0.65. Remove the claim that cost
does not affect scoring, or instead change evaluator.ts to score latency and
cost independently.

---

Outside diff comments:
In `@docs-site/src/content/docs/reference/configuration/routing.md`:
- Around line 160-161: Update the quota behavior description near the
dry-run/API clarification to state that quota affects policy-profile eligibility
and scoring, while preserving that it does not change Codex account selection,
session affinity, cooldowns, or switching behavior.
- Around line 155-159: Update the quota evidence section in the routing
documentation to explicitly state that API-key routes use their configured
provider credentials and never resolve Codex pool or main accounts for quota
evidence. Keep Pool, Direct, and API-key account behavior described as separate
cases.
🪄 Autofix

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro Plus

Run ID: 221fa4e6-4c3b-429a-9d3a-e77faa4f1b12

📥 Commits

Reviewing files that changed from the base of the PR and between 850c625 and 3fd1a00.

📒 Files selected for processing (1)
  • docs-site/src/content/docs/reference/configuration/routing.md

Comment thread docs-site/src/content/docs/reference/configuration/routing.md Outdated
@Wibias

Wibias commented Aug 5, 2026

Copy link
Copy Markdown
Collaborator Author

Why this helps

PR #1014 (RI-07) adds quota-aware policy scoring to the routing-profile evaluator. It lets profiles weight quota and gate on require.minQuotaHeadroom, derives quota evidence from the Codex pool (plan-aware windows) and the active Anthropic account, and mirrors the same account-scoped evidence in the dry-run API/CLI so operators see the same eligibility as real routing. Docs and the devlog acceptance record were updated to match the shipped behavior.

@Wibias
Wibias merged commit 1f07c00 into lidge-jun:dev Aug 5, 2026
34 of 36 checks passed
@Wibias
Wibias deleted the feat/ri-07-quota-aware-routing branch August 5, 2026 07:21
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

enhancement New feature or request

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant