Skip to content

feat(#75): selective retrieval gate - #101

Merged
mohanagy merged 2 commits into
mainfrom
feat/issue-75-retrieval-gate
May 10, 2026
Merged

mohanagy merged 2 commits into
mainfrom
feat/issue-75-retrieval-gate

Conversation

@mohanagy

@mohanagy mohanagy commented May 10, 2026 •

Copy link
Copy Markdown
Owner

Closes #75 (in part — wiring into retrieve runtime + context-pack metadata follows in a tiny follow-up).

Summary

  • Adds a deterministic, dependency-free heuristic gate that classifies a prompt into one of six retrieval levels per issue Implement selective retrieval gate before building context packs #75 so upstream callers can skip retrieval entirely (level 0) or scope it from local symbol context (level 1) up to a full PR impact pack (level 5).
  • Pure function: `classifyRetrievalLevel({ prompt, intent?, hasPrDiff?, mentionedPaths?, mentionedSymbols?, hasStackTrace?, manualOverride? }) → { level, skipped_retrieval, reason, intent, signals }`. No I/O, no model calls, no graph lookups — just regex + structured signals so the decision is logged transparently.
  • Manual override (`manualOverride: 0-5`) satisfies the issue's acceptance criterion that the gate be overridable via CLI/MCP options.

Decision logic (short version)

Signal Level Reason
`manualOverride` set as supplied `'manual override'`
Stack trace detected 3 behavior slice — even if intent looks lexical
PR diff + review/impact/test intent 5 full PR impact pack
Chitchat (`hi`, `thanks`) 0 no retrieval needed
Impact intent without PR diff 4 cross-module impact
Debug (`why`, `error`, `slow`) 3 behavior slice
Review intent without PR diff 3 behavior slice
Test intent + mention 3 behavior slice
Test intent without mention 4 cross-module impact
Explain + mention 2 direct dependencies
Explain without mention 1 local context
Refactor + mention 2 direct dependencies
Refactor without mention 3 behavior slice
Rename + mention 1 local symbol/file
Rename without mention 0 no retrieval needed
Otherwise unclassified 1 default to local

Heuristic ordering matters where intents overlap: debug (`explain why`) beats explain (`walk me through`).

Why a separate slice from wiring

The issue's deliverables include both the gate module and emitting `retrieval_level` / `reason` / `skipped_retrieval` in context-pack output. `src/runtime/retrieve.ts` is 1,646 lines, so wiring lives in a small follow-up PR rather than crowding this slice. The gate is shipped standalone here so callers (including future #74 selector and #76 multi-resolution layers) can import it immediately.

Test plan

  • `npm run typecheck` — clean
  • `npm run build` — clean
  • `npm run test:run` — 86 files / 1552 tests pass (26 new for the gate + 1526 pre-existing)
  • Tests cover: every example decision from issue Implement selective retrieval gate before building context packs #75 (rename → 0/1, explain → 1/2, why → 3, "can this PR break onboarding?" → 5, "what tests should I add?" → 3/4); escalation signals (stack trace forces 3, PR diff escalates review/impact/test to 5, PR diff alone does not escalate explain); chitchat ("hi" / "thanks" → 0); manual override behavior (0 and 5); signal extraction (file paths, backtick symbols); caller-supplied intent and mentions; output-shape invariants.
  • CI must pass on Ubuntu/macOS/Windows matrix before merge.

Refs #74 (budgeted selector), #76 (multi-resolution context) — both consume the gate's level signal.

Summary by CodeRabbit

  • New Features

    • Added an intelligent context retrieval gate that classifies prompts into retrieval levels (0–5), detects intents, stack traces, mentioned paths/symbols, and supports manual overrides to determine how much repository context to fetch.
  • Tests

    • Added comprehensive unit tests covering intent classification, signal detection, escalation rules, override behavior, and output shape/consistency.

Review Change Stack

Adds a deterministic heuristic gate that classifies a prompt into one of
six retrieval levels (0 = no retrieval, 5 = full PR impact pack) so
upstream callers can skip or scope context retrieval before pulling
graph data:

  0 = no retrieval needed       (chitchat, bare rename without target)
  1 = local symbol/file only    (default for unclassified prompts)
  2 = direct dependencies       (explain/refactor with explicit reference)
  3 = behavior slice            (debug/why, stack trace, review w/o PR)
  4 = cross-module impact       (impact intent, vague test prompts)
  5 = full PR impact pack       (PR diff present + review/impact/test)

The gate is pure: takes `{ prompt, intent?, hasPrDiff?, mentionedPaths?,
mentionedSymbols?, hasStackTrace?, manualOverride? }` and returns
`{ level, skipped_retrieval, reason, intent, signals }`. Heuristics
order matters where intents overlap — debug ("explain why") beats
explain ("walk me through"). Stack-trace detection forces level 3
regardless of intent. PR diff escalates review/impact/test intents to
level 5. The `manualOverride` parameter satisfies the issue's
acceptance criterion that the gate be overridable via CLI/MCP options.

This slice ships the gate as a standalone module so it can be imported
anywhere a retrieval decision is needed. Wiring into the existing
retrieve runtime + emitting `retrieval_level` / `reason` /
`skipped_retrieval` in context-pack output lands in a follow-up slice.
The tests cover every example decision from issue #75 plus override
behavior, signal extraction, escalation rules, and output-shape
invariants.
@coderabbitai

coderabbitai Bot commented May 10, 2026 •

Copy link
Copy Markdown

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: 04669a8d-8d41-40cd-8dfa-7fd63033dcfd

📥 Commits

Reviewing files that changed from the base of the PR and between ce6c52a and 36d8bde.

📒 Files selected for processing (2)
  • src/runtime/retrieval-gate.ts
  • tests/unit/retrieval-gate.test.ts
✅ Files skipped from review due to trivial changes (1)
  • tests/unit/retrieval-gate.test.ts
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/runtime/retrieval-gate.ts

📝 Walkthrough

Walkthrough

Adds a deterministic retrieval gate that classifies prompts into retrieval levels (0–5) with exported I/O types, regex-based intent and signal extraction, decision heuristics (stack-trace escalation, PR-diff dominance, intent+mention branching), manual override support, and comprehensive Vitest coverage.

Changes

Retrieval Gate Implementation

Layer / File(s) Summary
Type Contracts and Input/Output Shapes
src/runtime/retrieval-gate.ts
Defines RetrievalLevel (0–5), RetrievalIntent, RetrievalGateInput, RetrievalGateSignals, and RetrievalGateDecision.
Signal Detection Patterns
src/runtime/retrieval-gate.ts
Adds ordered intent regexes and helpers detectIntent(), detectPaths(), detectSymbols(), plus path/symbol/stack-trace regexes.
Retrieval Classification Logic
src/runtime/retrieval-gate.ts
Adds classifyRetrievalLevel() and decideLevel() implementing manual override, stack-trace escalation (level 3), PR-diff dominance for review/impact/test (level 5), and intent+mention-count mapping to levels 0–4 with reason strings.
Unit Tests
tests/unit/retrieval-gate.test.ts
Vitest suite validating example mappings (issue #75), escalation behaviors, chitchat/unknown handling, manual override transparency, signal extraction and overrides, refactor banding, caller-supplied intent, and output-shape assertions.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Poem

A rabbit hops through prompts with care,
Counting mentions floating there—
Stack traces lift the gate up high,
PR diffs call for fuller sky.
He nudges levels, then winks goodbye. 🐰✨

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% 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
Title check ✅ Passed Title clearly and specifically summarizes the main change: adding a selective retrieval gate feature that addresses issue #75.
Description check ✅ Passed PR description is well-structured, comprehensive, covers summary, decision logic, rationale, and test plan. All template sections are addressed appropriately.
Linked Issues check ✅ Passed The pull request fully implements the retrieval-gate module specified in #75 with correct decision logic, input/output types, manual override support, and comprehensive tests covering all example decisions and acceptance criteria.
Out of Scope Changes check ✅ Passed All changes are directly scoped to implementing the retrieval gate module and tests as specified in #75; no unrelated modifications detected.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feat/issue-75-retrieval-gate

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

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

Actionable comments posted: 2

🧹 Nitpick comments (1)
tests/unit/retrieval-gate.test.ts (1)

149-171: ⚡ Quick win

Add a regression test for refactor without explicit mentions.

This branch is not asserted today; adding a dedicated case will lock the intended retrieval scope and prevent future drift.

Suggested test case
 describe('classifyRetrievalLevel — signal extraction', () => {
@@
 })
+
+describe('classifyRetrievalLevel — refactor intent scope', () => {
+  it('refactor without mention stays in scoped retrieval band', () => {
+    const decision = classify({ prompt: 'Refactor this module' })
+    expect(decision.intent).toBe('refactor')
+    expect(decision.level).toBe(2)
+  })
+})
🤖 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 `@tests/unit/retrieval-gate.test.ts` around lines 149 - 171, Add a regression
test that ensures a prompt implying a refactor without any explicit
backtick-quoted symbols or caller-supplied mentions still yields intent
'refactor' and the expected retrieval scope: call classify with a refactor-style
prompt (e.g. "Refactor the auth module"), assert decision.intent === 'refactor',
assert decision.signals.mentioned_symbols is empty, and assert decision.level
equals the intended default level (use decision.level === 1 if your retrieval
policy treats no-mentions as minimal scope); reference the classify function and
the decision.signals.mentioned_symbols / decision.intent / decision.level fields
when adding the new it(...) case in the existing
describe('classifyRetrievalLevel — signal extraction', ...) block.
🤖 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 `@src/runtime/retrieval-gate.ts`:
- Around line 164-167: The 'refactor' switch branch currently returns level 3
when mentions === 0 which over-escalates; change the no-mentions branch to
return level 2 (matching the v1 heuristic 0–2) and update the reason string
accordingly. Locate the case 'refactor' branch that uses the mentions variable
and replace the { level: 3, reason: 'refactor intent without explicit reference
— behavior slice' } object with { level: 2, reason: 'refactor intent without
explicit reference — general refactor intent' } (or similar concise reason) so
both mentions and no-mentions refactor paths stay within the 0–2 range.

---

Nitpick comments:
In `@tests/unit/retrieval-gate.test.ts`:
- Around line 149-171: Add a regression test that ensures a prompt implying a
refactor without any explicit backtick-quoted symbols or caller-supplied
mentions still yields intent 'refactor' and the expected retrieval scope: call
classify with a refactor-style prompt (e.g. "Refactor the auth module"), assert
decision.intent === 'refactor', assert decision.signals.mentioned_symbols is
empty, and assert decision.level equals the intended default level (use
decision.level === 1 if your retrieval policy treats no-mentions as minimal
scope); reference the classify function and the
decision.signals.mentioned_symbols / decision.intent / decision.level fields
when adding the new it(...) case in the existing
describe('classifyRetrievalLevel — signal extraction', ...) block.
🪄 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: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: c9dd9d59-828e-46a9-8a95-b60559bfd62a

📥 Commits

Reviewing files that changed from the base of the PR and between 0a151f6 and ce6c52a.

📒 Files selected for processing (2)
  • src/runtime/retrieval-gate.ts
  • tests/unit/retrieval-gate.test.ts

Comment on lines +108 to +111
if (input.manualOverride !== undefined) {
return {
level: input.manualOverride,
skipped_retrieval: input.manualOverride === 0,

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Validate manualOverride at runtime before returning it as level.

Line 110 trusts unvalidated input. If CLI/MCP passes -1, 6, or a non-integer, this function can return an invalid level despite the declared contract.

Suggested fix
+function isRetrievalLevel(value: unknown): value is RetrievalLevel {
+  return Number.isInteger(value) && (value as number) >= 0 && (value as number) <= 5
+}
+
 export function classifyRetrievalLevel(input: RetrievalGateInput): RetrievalGateDecision {
@@
-  if (input.manualOverride !== undefined) {
+  if (isRetrievalLevel(input.manualOverride)) {
     return {
       level: input.manualOverride,
       skipped_retrieval: input.manualOverride === 0,
       reason: 'manual override',
       intent,
       signals,
     }
   }

Comment thread src/runtime/retrieval-gate.ts Resolved
CodeRabbit flagged that the no-mentions branch of `case 'refactor'`
returned level 3 (behavior slice), which over-escalates a code-
modification intent into the debugging band. Both branches of
`refactor` now resolve to level 2 (direct dependencies): the with-
mention case keeps its existing scope, and the no-mention case drops
from 3 to 2 so the band is consistent.

Adds two regression tests pinning both branches: refactor + symbol
mention → level 2 with the symbol surfaced in `signals.mentioned_
symbols`; refactor without any reference → level 2 with empty mention
arrays. The reason string for the no-mention branch updates to
"direct dependencies" to match the level.
@mohanagy
mohanagy merged commit 734bed6 into main May 10, 2026
7 checks passed
mohanagy added a commit that referenced this pull request May 10, 2026
…tput (#103)

Now that the gate module (#101) and the context-pack metadata wiring
(#102) are in place, plumb the gate into the actual prompt-receiving
entry points so it runs on real client traffic and the decision is
visible in tool/CLI responses.

Changes:

  * src/runtime/retrieve.ts — retrieveContext() classifies each
    incoming question and attaches the decision to compileContextPack.
    Both the matched and empty-question paths now emit the gate's
    output. Adds retrieval_gate?: RetrievalGateDecision to
    RetrieveResult so MCP clients can read level/reason/intent.
  * src/runtime/stdio/tools.ts — both compileContextPack call sites
    (PR-impact-style and stored-context-pack) classify their incoming
    prompt. ContextPlaneMetadata grows a retrieval_gate field;
    contextMetadata() picks it up from the supplied pack so any tool
    that already merges metadata into its response inherits the gate
    decision automatically.
  * src/infrastructure/context-pack-command.ts — same pattern for the
    CLI's impact context-pack path.

The gate's classifyRetrievalLevel() is pure: every entry point passes
the user prompt verbatim and the gate handles empty-string / chitchat
inputs. Tokens-stripped questions like "how does the" still receive a
sensible decision (`unknown` intent → level 1 default), and chitchat
("hi" / "thanks") classifies as level 0 with skipped_retrieval=true.

Tests pin: matched questions get a debug/explain decision attached;
the empty-question branch still attaches the field; chitchat → level
0; both paths consistently expose retrieval_gate so callers can
unconditionally read it.
@coderabbitai coderabbitai Bot mentioned this pull request May 12, 2026
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.

Implement selective retrieval gate before building context packs

1 participant