Repository navigation
feat(#75): selective retrieval gate - #101
Conversation
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.
|
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: defaults Review profile: CHILL Plan: Pro Plus Run ID: 📒 Files selected for processing (2)
✅ Files skipped from review due to trivial changes (1)
🚧 Files skipped from review as they are similar to previous changes (1)
📝 WalkthroughWalkthroughAdds 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. ChangesRetrieval Gate Implementation
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~25 minutes Poem
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches📝 Generate docstrings
🧪 Generate unit tests (beta)
Comment |
There was a problem hiding this comment.
Actionable comments posted: 2
🧹 Nitpick comments (1)
tests/unit/retrieval-gate.test.ts (1)
149-171: ⚡ Quick winAdd a regression test for
refactorwithout 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
📒 Files selected for processing (2)
src/runtime/retrieval-gate.tstests/unit/retrieval-gate.test.ts
| if (input.manualOverride !== undefined) { | ||
| return { | ||
| level: input.manualOverride, | ||
| skipped_retrieval: input.manualOverride === 0, |
There was a problem hiding this comment.
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,
}
}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.
…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.
Closes #75 (in part — wiring into retrieve runtime + context-pack metadata follows in a tiny follow-up).
Summary
Decision logic (short version)
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
Refs #74 (budgeted selector), #76 (multi-resolution context) — both consume the gate's level signal.
Summary by CodeRabbit
New Features
Tests