feat(medications): smarter catalog search for typos and brand names - #1785
Conversation
Wire /api/medications and the medications typeahead domain through a catalog-local query normalizer so common typos and brand/generic names rank correctly without changing RAG retrieval analysis. Co-authored-by: BigSimmo <BigSimmo@users.noreply.github.com>
Co-authored-by: BigSimmo <BigSimmo@users.noreply.github.com>
Warning Review limit reachedYou’ve reached a temporary PR review limit under our Fair Usage Limits Policy. Next review available in:33 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 (2)
📝 WalkthroughWalkthroughThe medication catalog now supports brand-aware ranking, typo correction, brand–generic expansion, and query interpretation. Medication API and universal search responses use catalog analysis and preserve brand names in indexed projections. Tests cover parsing, ranking, corrections, expansions, and response shapes. ChangesMedication catalog search
Estimated code review effort: 4 (Complex) | ~45 minutes Sequence Diagram(s)sequenceDiagram
participant Client
participant MedicationsAPI
participant searchMedicationCatalog
participant analyzeMedicationCatalogQuery
participant MedicationRanker
Client->>MedicationsAPI: Search medication query
MedicationsAPI->>searchMedicationCatalog: Full medication records and query
searchMedicationCatalog->>analyzeMedicationCatalogQuery: Analyze corrections and expansions
analyzeMedicationCatalogQuery-->>searchMedicationCatalog: Query analysis
searchMedicationCatalog->>MedicationRanker: Rank corrected query and expansions
MedicationRanker-->>searchMedicationCatalog: Ranked medication matches
searchMedicationCatalog-->>MedicationsAPI: Matches and interpretation
MedicationsAPI-->>Client: Medication records and query interpretation
Possibly related PRs
Suggested reviewers: 🚥 Pre-merge checks | ✅ 3 | ❌ 2❌ Failed checks (2 warnings)
✅ Passed checks (3 passed)
✨ Finishing Touches 💡 1📝 Generate docstrings 💡
🧪 Generate unit tests (beta)
Comment |
This pull request has been ignored for the connected project Preview Branches by Supabase. |
Co-authored-by: BigSimmo <BigSimmo@users.noreply.github.com>
Co-authored-by: BigSimmo <BigSimmo@users.noreply.github.com>
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit:adb437563f
ℹ️ 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".
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
BigSimmo
commented
Aug 9, 2026
@codex resolve actionable Codex review findings for this pull request and current head using the repository instructions. This is the pull request's single automatic repair pass: do not perform a fresh review, create new standalone findings, or request another review. Work only the existing unresolved Codex threads on the current head. The only repository destination is BigSimmo/Database, and the only branch destination is the pull request head branch cursor/smarter-meds-search-9c1b at starting commit cfb5dc8; never publish fixes to a detached or synthetic work branch and never create a stacked pull request. Use the authenticated GitHub connector to commit each approved fix to BigSimmo/Database:cursor/smarter-meds-search-9c1b, then verify that the pull request head contains the published commit before reporting success. Always fix P0 and P1 findings. For P2 and lower findings, fix only clear, scoped, low-risk issues; otherwise disposition them with a concise reason. For a fixed thread, reply with as the first line and as the second line. For a no-code disposition, use followed by . These result markers authorize the workflow to close that exact thread only after it verifies a fixed commit is the pull request head; a local-only commit is not a fix. If publication or verification fails, do not use either result marker, do not claim success, and leave the thread open with the blocker. If human input or new authorization is required, do the same. Finish only after every actionable thread is fixed or dispositioned and closed, or explicitly left open for a human decision. Do not update the branch from main, address unrelated reviews, broaden scope, or create more than one scoped fix commit. Do not use external APIs, paid services, credentials, dependency changes, or broad refactors unless explicitly authorized. Add targeted tests where behavior changes and run the narrowest relevant validation. |
There was a problem hiding this comment.
Pull request overview
Adds catalog-local medication search normalization for typos, brand names, and conservative near-matches.
Changes:
- Adds medication query analysis and brand-aware ranking.
- Applies normalized search to the API and universal search.
- Adds route, catalog, and Playwright mock coverage.
Reviewed changes
Copilot reviewed 9 out of 9 changed files in this pull request and generated 2 comments.
Show a summary per file
| File | Description |
|---|---|
src/lib/medication-query.ts | Implements catalog query normalization. |
src/lib/medications.ts | Extracts and ranks brand names. |
src/app/api/medications/route.ts | Returns normalized matches and interpretation. |
src/lib/universal-search.ts | Applies normalization to medication typeahead. |
src/lib/medication-entities.ts | Clarifies alias usage. |
tests/medications.test.ts | Tests normalization and brand ranking. |
tests/medications-route.test.ts | Tests API behavior. |
tests/ui-smoke.spec.ts | Aligns the demo API mock. |
docs/branch-review-ledger.md | Records review and verification history. |
💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit:cfb5dc84e4
ℹ️ 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".
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
Keep shared clinical-search typo corrections for the medications domain, stop sibling-brand expansions from substring-matching unrelated content, project fields=index matches to the slim identity payload, and parse brand lists without annotation/prose tokens. Add focused regression coverage. Co-authored-by: BigSimmo <BigSimmo@users.noreply.github.com>
Babysit / unblock summary (PR #1785)Tip: What blockedRequired CI on the prior tip ( What I fixed ( |
Sync behind-but-clean tip so PR mergeability clears; keep PR catalog-search fixes and prefer main shared queues on hot docs. Co-authored-by: BigSimmo <BigSimmo@users.noreply.github.com>
Babysit / unblock update (PR #1785)Tip: What blocked
What I fixed
Required CI (this tip)Re-running on Residual
|
Clear behind-but-clean DIRTY mergeability after main advanced; no product delta beyond the sync. Co-authored-by: BigSimmo <BigSimmo@users.noreply.github.com>
Babysit / unblock update (PR #1785)Tip: What blocked
What I fixed
Required CIRe-running on Residual
|
BigSimmo
commented
Aug 10, 2026
@cursoragent Unblock the current open PR. Confirm the PR number and GitHub head first from context. If more than one open PR could apply, stop and say which one you would use and why. Fetch and start from the remote tip that matches that GitHub head. If the named branch ref is missing or stale, use the PR head ref. Preserve unrelated local WIP; do not discard dirty work; do not treat a local-ahead commit as the reviewed tip. Do not merge the PR, force-push, rebase, or arm auto-merge. No provider-backed gates without approval. If you cannot push or resolve threads, diagnose and comment only; if inline replies fail, resolve when possible and put blocker dispositions in the summary comment. If auto-merge is already armed, push only for a real blocker and avoid cancelling in-flight required CI unless the push clears that blocker. If the PR is already merged or closed: confirm outcome, post one summary, and stop. Primary job: clear mergeability and required-CI blockers on this tip. Do a full product review only if needed to explain or fix a blocker. Stay light otherwise—no broad verification suites or Playwright unless needed to prove one concrete unblock fix. Snapshot the GitHub head: tip, behind/ahead, mergeable state, merge-tree versus origin/main (real conflict versus behind-but-clean), required checks on that tip including Production UI when selected, and unresolved threads that block merge or required CI. Missing checks while dirty are not green. Tip moved → re-snapshot. Ledger-lookup against that GitHub head under an unblock/fix scope for this PR. If already handled at this head for unblock work, merge-tree clean, required checks green, and no blocking threads: summarize, comment, stop. Unblock once: real conflict → merge origin/main with the smallest correct resolution (prefer main’s shared queues; keep this PR’s notes); behind-but-clean → one sync, late if required CI is in flight; clean → leave. skip-branch-sync and similar labels do not block a manual sync needed to clear a real blocker. No sync thrash. After any sync or push, re-snapshot tip, merge-tree, and required checks before declaring done. Dedupe the ledger if a merge touched it. Fix only what blocks required checks or mergeability on this tip. Ignore advisory red unless it reveals a real required failure. Prefer the smallest safe fix; if a bot/autofix commit caused the break, prefer revert. Prove with the smallest targeted check only. Format and commit before push. Push only blocker-fix commits. Append ledger for the final GitHub head under the unblock scope. Never push a ledger-only tip. One PR comment: tip, sync/merge-tree, what blocked and what you fixed or dispositioned, required CI status, residual risks; merge left to me. Stop when merge-tree is clean on the current GitHub tip, no blocking threads remain for merge/required CI, and required checks are green or clearly in progress. |
❌ Unable to add follow-up after multiple attempts. The agent may be experiencing issues. Please try again later or Open in Web to view the status. Learn more about Cursor Agents |
Clear behind-but-clean DIRTY mergeability after main advanced; no product delta beyond the sync.
There was a problem hiding this comment.
Actionable comments posted: 4
🤖 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/branch-review-ledger.md`:
- Around line 853-862: Preserve the append-only ordering of
docs/branch-review-ledger.md: do not move or manually edit existing ledger rows
around the PR `#1785` entries. Add any new records only through the established
ledger command, retaining its existing merge-driver behavior.
In `@src/lib/universal-search.ts`:
- Around line 265-272: Update the medication-ranking flow around
analyzeMedicationCatalogQuery so it analyzes args.baseQuery, preserving the
shared correction before applying catalog corrections and composing both into
the ranking query. In tests/universal-search.test.ts lines 439-451, add a
regression for a combined typo such as “sertaline monitring” and assert
medication ranking uses both corrections.
In `@tests/medications-route.test.ts`:
- Around line 243-254: Remove the duplicate members from the response payload
type declarations in the brand and typo test cases. Keep one matches definition
per payload and one interpretation definition in typoPayload, preserving the
existing fields and assertions.
In `@tests/ui-smoke.spec.ts`:
- Around line 305-325: Update medicationIndexRecords and the mock’s fields=index
response path: derive the brand row from medicationBrandNames(record) so
annotation and prose cleanup match production, then project every matched
medication through medicationIndexRecords() instead of returning full
match.medication records. Preserve the existing full-record response for other
fields values.
🪄 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: CHILL
Plan: Pro
Run ID: 57fff2b5-937b-4c71-a604-f83abb400369
📒 Files selected for processing (10)
docs/branch-review-ledger.mdsrc/app/api/medications/route.tssrc/lib/medication-entities.tssrc/lib/medication-query.tssrc/lib/medications.tssrc/lib/universal-search.tstests/medications-route.test.tstests/medications.test.tstests/ui-smoke.spec.tstests/universal-search.test.ts
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
CI triageCI failed on this PR. Automated classification of the 2 failed job(s):
Compared with main CI run #9583 (cancelled). Classification is evidence routing, not permission to ignore a failure. Exact quarantined Playwright identities remain governed by the flake ledger. |
Sync past #1791 so GitHub mergeability is current; merge-tree was already clean.
Production UI (3) failed when a single scrollPrimarySurface("end") left
~67px remaining after reserve/layout settled. Match the differentials
pattern: re-issue endpoint scroll inside expect().toPass().
Records the PR #1785 unblock/fix ledger row for this sweep.Uh oh!
There was an error while loading. Please reload this page.
Babysit summary (merged)
|


Summary
GET /api/medications?q=) now runs a catalog-local query normalizer for common typos, brand↔generic expansion, and conservative edit-distance-1 near-misses.rankMedicationRecords, so queries likecampral/zolofthit like generics rather than weak content matches.clinical-search/ RAG analysis tables are untouched.interpretation(correctedQuery/corrections/appliedExpansions) for a future “Did you mean” chip.Verification
npm run test— 547 files / 5899 passed | 4 skipped (on feature commit)tests/medications.test.ts+tests/medications-route.test.ts— 49 passed afterorigin/mainsyncgit merge-tree --write-tree origin/main HEAD— clean; GitHubmergeable: trueafter syncnpm run verify:pr-local— not run; unit suite covers the changed catalog/query/route contractsragRanking: false)Risk and rollout
/api/medicationsreturns to raw-query ranking.Clinical Governance Preflight
Clinical KB Database(sjrfecxgysukkwxsowpy)Notes
MedicationPrescribingWorkspace, brand subtitle on result rows, growing the local typo map from real misses.Summary by CodeRabbit
New Features
Bug Fixes
Tests