refactor(rag): extract second-stage ranking - #1472
Conversation
Warning Review limit reachedYou’ve reached a temporary PR review limit under our Fair Usage Limits Policy. Next review available in:51 minutes Your organization has reached its usage spending cap. Adjust your spending cap in the billing tab. 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: Path: .coderabbit.yaml Review profile: CHILL Plan: Pro Run ID: 📒 Files selected for processing (3)
📝 WalkthroughWalkthroughSecond-stage RAG reranking and telemetry helpers move from ChangesRAG reranking extraction
Estimated code review effort: 3 (Moderate) | ~20 minutes Possibly related PRs
Suggested reviewers: 🚥 Pre-merge checks | ✅ 5✅ Passed checks (5 passed)
✨ Finishing Touches📝 Generate docstrings
Comment |
BigSimmo
commented
Jul 30, 2026
@CodeRabbit review PR |
BigSimmo
commented
Jul 30, 2026
@codex review PR |
✅ Action performedReview finished.
|
Codex Review: Didn't find any major issues. Chef's kiss. Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
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". |
# Conflicts: # docs/codebase-index.md # scripts/check-maintainability-budgets.mjs # src/lib/rag/rag.ts
There was a problem hiding this comment.
Pull request overview
This PR refactors the RAG pipeline by extracting the second-stage reranking logic out of src/lib/rag/rag.ts into a dedicated module, aiming to reduce the rag.ts monolith while preserving existing ranking behavior and the public @/lib/rag/rag export surface.
Changes:
- Extracted second-stage rerank logic (engagement predicate, scoring adjustments, document diversity penalty, subject-match protection, and related telemetry helpers) into
src/lib/rag/rag-second-stage.ts. - Updated
rag.tsto import and re-exportapplySecondStageRerankIfNeededfrom the new module and to use the extracted telemetry helpers. - Tightened the maintainability budget for
rag.tsand updated RAG module documentation/workorder notes.
Reviewed changes
Copilot reviewed 5 out of 5 changed files in this pull request and generated 1 comment.
Show a summary per file
| File | Description |
|---|---|
| src/lib/rag/rag.ts | Removes in-file second-stage rerank implementation and switches to importing/re-exporting the extracted module while keeping orchestration in rag.ts. |
| src/lib/rag/rag-second-stage.ts | New module containing the extracted second-stage rerank implementation and retrieval-layer telemetry helpers. |
| scripts/check-maintainability-budgets.mjs | Ratchets the rag.ts line-count budget downward to reflect the extraction. |
| docs/maturity-backlog-workorders.md | Records the extraction as X3 maturity progress (but currently contains stale post-extraction budget numbers). |
| docs/codebase-index.md | Adds rag-second-stage.ts to the documented RAG module cluster. |
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
Uh oh!
There was an error while loading. Please reload this page.
BigSimmo
commented
Jul 30, 2026
@copilot Fix the code for all comments in this review thread. When a review comment includes a suggested change, apply the suggestion exactly. Do not make changes beyond what is described in the linked review thread. |
Fixed in the latest commit — updated |
There was a problem hiding this comment.
Actionable comments posted: 1
🤖 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/maturity-backlog-workorders.md`:
- Around line 95-99: Correct the `#086` second-stage extraction entry in the
ratchet ledger to use the established 4,543-line baseline from the hydration
entry, update the resulting post-extraction count and ratcheted budget
consistently, and verify or correct the duplicated `#086` PR reference so it does
not repeat the coverage-gate bullet.
🪄 Autofix (Beta)
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: CHILL
Plan: Pro
Run ID: 30c8ce83-8689-4dac-9ee4-9e0d51a5e9a0
📒 Files selected for processing (5)
docs/codebase-index.mddocs/maturity-backlog-workorders.mdscripts/check-maintainability-budgets.mjssrc/lib/rag/rag-second-stage.tssrc/lib/rag/rag.ts
Uh oh!
There was an error while loading. Please reload this page.
BigSimmo
commented
Jul 30, 2026
Temporarily paused during the owner-authorized ordered merge sweep so |
BigSimmo
commented
Jul 31, 2026
@cursoragent this PR will be re-opened soon. Please resolve any failing CI, run bugbot and resolve any bugbot comments against current repo and fix any merge conflicts and also fix any errors and address and fix all comments or suggestions that are likely to improve the PR and Codebase. Please implement smallest required fix according to best code practices. Check your work. Leave this PR closed for now but still make all these changes and run the review. I want it ready to go for when I re-open it. |
PR #1472 is ready to reopen and left CLOSED. Done
Branch tip
GitHub still shows the frozen closed head |
Sync closed PR #1472 with current main ahead of reopen. Co-authored-by: BigSimmo <BigSimmo@users.noreply.github.com>
Read remote.origin.url via git config so tokenized url.*.insteadOf rewrites in Cursor Cloud do not falsely treat a clean origin as credential-bearing and break Codex Cloud setup tests. Co-authored-by: BigSimmo <BigSimmo@users.noreply.github.com>
Append the closed-PR readiness review at tip cb07a6c after main sync, CodeRabbit baseline fix, and Codex Cloud origin inspect fix. Co-authored-by: BigSimmo <BigSimmo@users.noreply.github.com>
Record the ledger-only tip after the approved reopen-prep review so lookup matches the current branch HEAD. Co-authored-by: BigSimmo <BigSimmo@users.noreply.github.com>
Sync closed PR #1472 with current main ahead of reopen. Co-authored-by: BigSimmo <BigSimmo@users.noreply.github.com>
BigSimmo
commented
Jul 31, 2026
@coderabbitai please run a new review of this closed PR for me |
✅ Action performedFull review finished. Your included review limit is currently reached under our Fair Usage Limits Policy. Your recent PR review activity is in the 95th percentile or higher among CodeRabbit users, so adaptive limits apply. This review may still proceed through usage-based billing if eligible. Your next included review will be available in 37 minutes. |
This pull request has been ignored for the connected project Preview Branches by Supabase. |
Resolve insteadOf-origin conflicts by keeping main's clearer comments and configuredOriginUrl test helper; behavior is identical on both sides. Co-authored-by: BigSimmo <BigSimmo@users.noreply.github.com>
BigSimmo
commented
Jul 31, 2026
@cursoragent resolve merge conflict |
Resolved. GitHub’s
Complicated conflicts: none. |
Sync closed PR #1472 after main advanced past the previous tip. Co-authored-by: BigSimmo <BigSimmo@users.noreply.github.com>
Uh oh!
There was an error while loading. Please reload this page.


Motivation
rag.tsmonolith and complete the X3 maturity work by moving a cohesive second-stage rerank unit into its own module while preserving existing behaviour and public exports.src/lib/ragcodebase easier to reason about, enforce the maintainability budget, and unblock further domain-directory extractions.RAG impact: no retrieval behaviour changebecause this is a verbatim extraction with the same public API and comparator precedence.Description
src/lib/rag/rag-second-stage.tscontaining the second-stage engagement predicate, scoring adjustments, document-diversity penalties, subject-match protection, and retrieval-layer telemetry extracted unchanged fromrag.ts.src/lib/rag/rag.tsto import and re-exportapplySecondStageRerankIfNeededand to call the extracted unit at the same pipeline points so the public orchestration and behaviour remain identical.rag.tsmaintainability budget inscripts/check-maintainability-budgets.mjs(budget reduced to reflect the extraction) and updated documentation indocs/codebase-index.mdanddocs/maturity-backlog-workorders.mdto record the change.Testing
npm run test -- tests/rag-second-stage-ranking.test.ts tests/rag-fast-path-ordering.test.ts tests/rag-document-lookup-escalation-rescue.test.tsand they all passed.npm run verify:pr-local -- --files src/lib/rag/rag.ts,src/lib/rag/rag-second-stage.ts,scripts/check-maintainability-budgets.mjs,docs/codebase-index.md,docs/maturity-backlog-workorders.md,npm run typecheck,npm run lint,npm run test(full Vitest),npm run build,npm run check:rag:fixtures, andnpm run eval:rag:offline; these completed and passed the offline/CI-local checks.npm run format/npm run format:checkand the tree is formatted.npm run eval:retrieval:quality,npm run check:production-readiness, andnpm run verify:uibecause they are live/provider-backed or UI gates and require separate approval.Codex Task
RAG impact: no retrieval behaviour change — verbatim second-stage ranking extraction; orchestration, comparator precedence, and call sites are preserved.
Verification after current-main reconciliation
pm run typecheck passed.
pm run check:maintainability-budgets passed with
ag.ts at 4351/4351 lines.
pm run eval:rag:offline passed: 36 golden cases, 23 suites, 574 tests.
pm run check:production-readiness:ci returned READY with expected missing-local-secret warnings.
Risk and rollout
This is a structural extraction only. Revert the squash commit if module resolution, public re-exports, or retrieval telemetry differs; no provider configuration or production data is changed.
Clinical Governance Preflight
Summary by CodeRabbit
Improvements
Documentation