Repository navigation
Fix production retrieval correctness - #146
Conversation
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
|
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)
📝 WalkthroughWalkthroughAdds shared source-discovery and hard-ignore rules, extends contracts for domain/exclusion signals, delegates discovery to shared helpers, implements prompt-exclusion extraction, adds symbol-aware anchoring and domain-aware retrieval scoring/suppression, updates slicing to respect exclusions/polluted paths, extends diagnostics, and updates tests/docs. ChangesSource-domain filtering and discovery
Test coverage
Estimated code review effort🎯 4 (Complex) | ⏱️ ~60 minutes Possibly related PRs
🚥 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: 3
🧹 Nitpick comments (6)
src/runtime/context-pack-diagnostics.ts (2)
340-355: 💤 Low value
missingRuntimePipelinemay produce false positives.The function checks for both
pipelineNodeCount === 0andstructuralRelations === 0. However, it already callspipelinePrompt(pack)at line 354, which means it's checking a pipeline prompt. If the pack has pipeline nodes but no structural relations (or vice versa), it will still trigger. Consider whether this OR condition is intentional or if it should be AND.🤖 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 `@src/runtime/context-pack-diagnostics.ts` around lines 340 - 355, The missingRuntimePipeline function currently uses an OR between pipelineNodeCount === 0 and structuralRelations === 0 which causes false positives when only one of those is missing; update the return to require both to be missing by changing the condition to pipelinePrompt(pack) && (pipelineNodeCount === 0 && structuralRelations === 0) so that missingRuntimePipeline only reports when there are no pipeline nodes AND no structural relations; ensure you modify the expression that references pipelineNodeCount and structuralRelations in missingRuntimePipeline accordingly.
371-382: 💤 Low valueFixed denominator may allow negative scores before clamping.
The fixed denominator of 10 means that if many new warnings trigger (total weight > 10), the raw score would go negative before the
Math.max(0, ...)clamp. This is handled correctly, but consider adding a comment explaining the design choice and the expected behavior when total triggered weight exceeds the denominator.🤖 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 `@src/runtime/context-pack-diagnostics.ts` around lines 371 - 382, The computeQualityScore function uses a fixed denominator totalWeight = 10 which allows the raw score to go negative when triggeredWeight (accumulated from RULE_WEIGHTS via the warnings loop) exceeds that denominator before the clamp; add a concise comment above totalWeight (or at the top of computeQualityScore) explaining that the denominator is intentionally fixed to preserve historical comparability, that excess triggeredWeight will produce negative raw scores which are then clamped to 0 by Math.max, and document the expected semantics (new warnings reduce the numerator but don’t change the historical baseline), referencing totalWeight, triggeredWeight, and RULE_WEIGHTS so future readers understand the design choice.src/runtime/retrieval-gate.ts (1)
75-76: 💤 Low valueRegex may miss some valid symbol patterns.
The
SYMBOL_EXPLICIT_REpattern requires the class name to start with uppercase ([A-Z]), which won't match lowercase class names or module-style references likeutils.parseDate. Consider whether this is intentional or if the pattern should be more permissive.🤖 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 `@src/runtime/retrieval-gate.ts` around lines 75 - 76, The SYMBOL_EXPLICIT_RE currently enforces an uppercase first character for the left-hand identifier which will miss valid symbols like lowercase class names or module.function references; update the regex used in SYMBOL_EXPLICIT_RE to allow an initial lowercase letter and to accept dot-separated module paths (e.g., allow [A-Za-z_$][A-Za-z0-9_$]* at the front and permit repeated (?:\.[A-Za-z_$][A-Za-z0-9_$]*)? segments), while preserving existing support for separators (., #, ::) and trailing parentheses; locate and update the SYMBOL_EXPLICIT_RE declaration to be more permissive (no change needed to STACK_TRACE_RE).src/runtime/context-pack.ts (1)
863-866: 💤 Low valueClarify the intent of domain boost for non-production sources.
The +0.25 boost for domains that are neither
productionnorunknownseems intentional—it rewards explicitly-tagged domains (test, benchmark, config, etc.) when they pass the penalty gate (i.e., when the task contract requests them). However, this logic is subtle and could benefit from a brief inline comment explaining the rationale.🤖 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 `@src/runtime/context-pack.ts` around lines 863 - 866, Add a brief inline comment above the block that adjusts score based on view.source_domain (the if checking view.source_domain !== 'production' && view.source_domain !== 'unknown') explaining the intent: that non-production explicit domains (e.g., test, benchmark, config) receive a +0.25 boost to reward explicitly-tagged non-prod sources when the task contract permits them (after any penalty gate), so future readers understand this subtle scoring choice; reference the variables score, reasons, and the pushUnique call in the comment for clarity.src/runtime/retrieve.ts (1)
741-781: 💤 Low valueSymbol matching score thresholds could benefit from documentation.
The
symbolReferenceMatchScorefunction returns scores in the range 0-4 with specific thresholds (4, 3.5, 3, 2.5) for different match qualities. Consider adding a brief comment or JSDoc explaining the score semantics, as these values are used as gates elsewhere (e.g.,symbolMatch >= 3at line 1673,symbolMatch >= 3at line 1982).🤖 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 `@src/runtime/retrieve.ts` around lines 741 - 781, The function symbolReferenceMatchScore uses numeric thresholds (0, 2.5, 3, 3.5, 4) to represent match quality but has no documentation; add a concise JSDoc above symbolReferenceMatchScore that documents the meaning of each score (e.g., 4 = exact match, 3.5 = method match with class in source, 3 = method match on reference with class context, 2.5 = bare name match, 0 = no match) and note where callers gate on values (e.g., consumers that compare symbolMatch >= 3 expect strong matches). Ensure the comment mentions the score range (0–4) and intended semantic thresholds so future readers and maintainers understand why callers check for >=3.src/runtime/retrieve/slicing.ts (1)
203-209: 💤 Low valueAnchor reason cascade has a potential logic gap.
The reason assignment at lines 203-209 uses a cascade:
exactLabelMatch→literalPathMatch→sourcePathMatch→ default. However,sourcePathMatchcould be true when both exact label AND source path match. The current order prioritizesexactLabelMatchwhich seems correct, but the intermediateliteralPathMatchcheck (line 205) could mask cases wheresourcePathMatchis more descriptive. Consider whether this is the intended precedence.🤖 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 `@src/runtime/retrieve/slicing.ts` around lines 203 - 209, The cascade assigning reason can mis-prioritize source path matches because node.literalPathMatch is checked before node.sourcePathMatch; decide the intended precedence and update the ternary chain accordingly (e.g., exactLabelMatch → sourcePathMatch → literalPathMatch → default if source path should be more descriptive), or explicitly document the chosen precedence with a comment next to the reason assignment; update the expression that computes reason (referencing the variable reason and properties node.exactLabelMatch, node.literalPathMatch, node.sourcePathMatch) and add/adjust unit tests to cover combinations where multiple flags are true to prevent regressions.
🤖 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/retrieve.ts`:
- Line 1563: The code sets rootPath using graph.graph.root_path with
process.cwd() as a silent fallback (const rootPath = typeof
graph.graph.root_path === 'string' ? graph.graph.root_path : process.cwd()),
which can cause surprising behavior in non-standard working directories; update
the logic to detect when graph.graph.root_path is missing and emit a clear
warning log (e.g., via the existing logger used in this module) that indicates
the fallback to process.cwd() and recommends configuring root_path, and apply
the same change to the other occurrence noted (the line around 2118) so both
places log the fallback rather than silently using process.cwd().
In `@src/shared/source-discovery.ts`:
- Around line 157-174: The isDiscoveryPathIgnored function currently lets a
negated pattern flip a hard-ignore; change the loop logic so hard ignores from
isHardIgnoredPath(relativePath) cannot be overridden by negated patterns:
compute ignored = isHardIgnoredPath(relativePath) as now, but inside the
for-loop (over patterns) if matchesWorkspacePattern(relativePath, path, pattern)
and the matched pattern is a negation (pattern.startsWith('!')), skip applying
the negation when ignored is true due to isHardIgnoredPath; only allow
non-negated patterns to set ignored = true and allow negated patterns to clear
ignored when and only when the current ignored state was set by a non-hard
ignore. Ensure references to isDiscoveryPathIgnored, isHardIgnoredPath,
matchesWorkspacePattern and the pattern/negated logic are updated accordingly.
---
Nitpick comments:
In `@src/runtime/context-pack-diagnostics.ts`:
- Around line 340-355: The missingRuntimePipeline function currently uses an OR
between pipelineNodeCount === 0 and structuralRelations === 0 which causes false
positives when only one of those is missing; update the return to require both
to be missing by changing the condition to pipelinePrompt(pack) &&
(pipelineNodeCount === 0 && structuralRelations === 0) so that
missingRuntimePipeline only reports when there are no pipeline nodes AND no
structural relations; ensure you modify the expression that references
pipelineNodeCount and structuralRelations in missingRuntimePipeline accordingly.
- Around line 371-382: The computeQualityScore function uses a fixed denominator
totalWeight = 10 which allows the raw score to go negative when triggeredWeight
(accumulated from RULE_WEIGHTS via the warnings loop) exceeds that denominator
before the clamp; add a concise comment above totalWeight (or at the top of
computeQualityScore) explaining that the denominator is intentionally fixed to
preserve historical comparability, that excess triggeredWeight will produce
negative raw scores which are then clamped to 0 by Math.max, and document the
expected semantics (new warnings reduce the numerator but don’t change the
historical baseline), referencing totalWeight, triggeredWeight, and RULE_WEIGHTS
so future readers understand the design choice.
In `@src/runtime/context-pack.ts`:
- Around line 863-866: Add a brief inline comment above the block that adjusts
score based on view.source_domain (the if checking view.source_domain !==
'production' && view.source_domain !== 'unknown') explaining the intent: that
non-production explicit domains (e.g., test, benchmark, config) receive a +0.25
boost to reward explicitly-tagged non-prod sources when the task contract
permits them (after any penalty gate), so future readers understand this subtle
scoring choice; reference the variables score, reasons, and the pushUnique call
in the comment for clarity.
In `@src/runtime/retrieval-gate.ts`:
- Around line 75-76: The SYMBOL_EXPLICIT_RE currently enforces an uppercase
first character for the left-hand identifier which will miss valid symbols like
lowercase class names or module.function references; update the regex used in
SYMBOL_EXPLICIT_RE to allow an initial lowercase letter and to accept
dot-separated module paths (e.g., allow [A-Za-z_$][A-Za-z0-9_$]* at the front
and permit repeated (?:\.[A-Za-z_$][A-Za-z0-9_$]*)? segments), while preserving
existing support for separators (., #, ::) and trailing parentheses; locate and
update the SYMBOL_EXPLICIT_RE declaration to be more permissive (no change
needed to STACK_TRACE_RE).
In `@src/runtime/retrieve.ts`:
- Around line 741-781: The function symbolReferenceMatchScore uses numeric
thresholds (0, 2.5, 3, 3.5, 4) to represent match quality but has no
documentation; add a concise JSDoc above symbolReferenceMatchScore that
documents the meaning of each score (e.g., 4 = exact match, 3.5 = method match
with class in source, 3 = method match on reference with class context, 2.5 =
bare name match, 0 = no match) and note where callers gate on values (e.g.,
consumers that compare symbolMatch >= 3 expect strong matches). Ensure the
comment mentions the score range (0–4) and intended semantic thresholds so
future readers and maintainers understand why callers check for >=3.
In `@src/runtime/retrieve/slicing.ts`:
- Around line 203-209: The cascade assigning reason can mis-prioritize source
path matches because node.literalPathMatch is checked before
node.sourcePathMatch; decide the intended precedence and update the ternary
chain accordingly (e.g., exactLabelMatch → sourcePathMatch → literalPathMatch →
default if source path should be more descriptive), or explicitly document the
chosen precedence with a comment next to the reason assignment; update the
expression that computes reason (referencing the variable reason and properties
node.exactLabelMatch, node.literalPathMatch, node.sourcePathMatch) and
add/adjust unit tests to cover combinations where multiple flags are true to
prevent regressions.
🪄 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: 6683a487-0d60-4861-9a0f-ffbf42ec8331
📒 Files selected for processing (20)
CHANGELOG.mdREADME.mdsrc/contracts/context-pack-diagnostics.tssrc/contracts/context-pack.tssrc/contracts/retrieval-gate.tssrc/pipeline/detect.tssrc/pipeline/spi/build.tssrc/runtime/context-pack-diagnostics.tssrc/runtime/context-pack.tssrc/runtime/retrieval-gate.tssrc/runtime/retrieve.tssrc/runtime/retrieve/slicing.tssrc/shared/source-discovery.tstests/unit/benchmark-quality.test.tstests/unit/context-pack-diagnostics.test.tstests/unit/detect.test.tstests/unit/generate.test.tstests/unit/retrieval-gate.test.tstests/unit/retrieve-production-correctness.test.tstests/unit/spi-build.test.ts
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
There was a problem hiding this comment.
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)
src/runtime/retrieve.ts (1)
2227-2245:⚠️ Potential issue | 🟠 Major | ⚡ Quick winRe-apply polluted/excluded-source gating before admitting semantic-only candidates.
The lexical pass now filters hard-ignored / excluded-domain / excluded-term matches, but this async path adds top semantic hits from
candidatesByIdwithout rechecking any of those gates. Withsemantic: trueorrerank: true, test/generated/build-artifact nodes can slip back into the final result even when the lexical retrieval gate rejected them.Fix direction
+ const gate = lexicalResult.retrieval_gate ?? classifyRetrievalLevel({ + prompt: options.question, + ...(options.retrievalLevel !== undefined ? { manualOverride: options.retrievalLevel } : {}), + }) + const mentionedSymbolRefs = gate.signals.mentioned_symbols.map(parseSymbolReference) + const mentionedPaths = gate.signals.mentioned_paths + const excludedDomains = gate.signals.excluded_domains ?? [] + const excludedTerms = gate.signals.excluded_terms ?? [] + const excludedPathHints = gate.signals.excluded_path_hints ?? [] + + const isAsyncCandidateAllowed = (node: ScoredNode): boolean => { + const exclusionMatches = + excludedDomains.includes(node.sourceDomain as never) || + excludedTermMatches(node.label, excludedTerms, excludedPathHints) || + excludedTermMatches(node.sourceFile, excludedTerms, excludedPathHints) + const symbolMatch = symbolReferenceMatchScore(node.label, node.sourceFile, mentionedSymbolRefs) + const pathMatch = sourceFileMatchesMentionedPath(node.sourceFile, mentionedPaths) + return (!isPollutedSourcePath(node.sourceFile, classificationRootPath) && !exclusionMatches) || symbolMatch > 0 || pathMatch + } + if (semanticScores.size > 0) { for (const [candidateId] of [...semanticScores.entries()] .sort((left, right) => right[1] - left[1]) .slice(0, 8)) { if (lexicalSliceIds !== null && !lexicalSliceIds.has(candidateId)) { continue } - candidateIds.add(candidateId) + const candidate = candidatesById.get(candidateId) + if (candidate && isAsyncCandidateAllowed(candidate)) { + candidateIds.add(candidateId) + } } }🤖 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 `@src/runtime/retrieve.ts` around lines 2227 - 2245, The semantic-only admission path is bypassing the lexical gating (hard-ignored / excluded-domain / excluded-term) and can reintroduce blocked nodes; when iterating semanticScores or when mapping candidateIds -> candidatesById (symbols: candidateIds, semanticScores, lexicalSliceIds, candidatesById, ScoredNode, lexicalResult) reapply the same gating predicate used by the lexical pass: skip any candidateId not in lexicalSliceIds (when lexicalSliceIds !== null) and also run the candidate through the same exclusion checks (the hard-ignore / excluded-domain / excluded-term predicate used earlier) before adding to candidateIds or including in candidatePool so semantic-only hits cannot bypass the filters.
♻️ Duplicate comments (1)
src/shared/source-discovery.ts (1)
188-197:⚠️ Potential issue | 🟠 Major | ⚡ Quick winDon't let negated
.graphifyignorerules reopen hard-ignored paths.This still lets a later
!patternflipignoredback tofalseafterisHardIgnoredPath(relativePath)already matched. A rule like!graphify-out/**or!node_modules/**would re-index artifacts that this PR explicitly treats as non-overridable hard ignores.Possible fix
export function isDiscoveryPathIgnored(path: string, root: string, patterns: readonly string[]): boolean { const relativePath = relativeWorkspacePath(path, root) if (!relativePath) { return false } - let ignored = isHardIgnoredPath(relativePath) + if (isHardIgnoredPath(relativePath)) { + return true + } + + let ignored = false for (const rawPattern of patterns) { const pattern = rawPattern.trim() if (!pattern) { continue }🤖 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 `@src/shared/source-discovery.ts` around lines 188 - 197, The current loop lets a negated pattern reopen paths that were marked by isHardIgnoredPath(relativePath); preserve hard ignores by capturing that value (e.g., const hardIgnored = isHardIgnoredPath(relativePath)) and then, inside the patterns loop where matchesWorkspacePattern(relativePath, path, pattern) is checked, do not allow negated rules to flip ignored back to false when hardIgnored is true — either skip applying negations or always keep ignored true for hardIgnored paths; update references to ignored (and the matchesWorkspacePattern handling) accordingly so hardIgnored paths remain non-overridable.
🤖 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/retrieve.ts`:
- Around line 846-849: The current excludedTermMatches function uses substring
matching (includes) which flags terms inside unrelated identifiers; change it to
token-aware matching: in excludedTermMatches, normalize value (lowercase), split
it into tokens by splitting on non-alphanumeric characters and also split
camelCase/PascalCase/identifier boundaries (e.g., insert splits before capital
letters) to produce atomic tokens, then check if any excludedTerms or
excludedPathHints (lowercased) exactly equal any of those tokens (rather than
using includes). Update the function to build tokens from value and perform
equality checks against excludedTerms/excludedPathHints to avoid false positives
for identifiers like "ContestService" or filenames like "latest.ts".
---
Outside diff comments:
In `@src/runtime/retrieve.ts`:
- Around line 2227-2245: The semantic-only admission path is bypassing the
lexical gating (hard-ignored / excluded-domain / excluded-term) and can
reintroduce blocked nodes; when iterating semanticScores or when mapping
candidateIds -> candidatesById (symbols: candidateIds, semanticScores,
lexicalSliceIds, candidatesById, ScoredNode, lexicalResult) reapply the same
gating predicate used by the lexical pass: skip any candidateId not in
lexicalSliceIds (when lexicalSliceIds !== null) and also run the candidate
through the same exclusion checks (the hard-ignore / excluded-domain /
excluded-term predicate used earlier) before adding to candidateIds or including
in candidatePool so semantic-only hits cannot bypass the filters.
---
Duplicate comments:
In `@src/shared/source-discovery.ts`:
- Around line 188-197: The current loop lets a negated pattern reopen paths that
were marked by isHardIgnoredPath(relativePath); preserve hard ignores by
capturing that value (e.g., const hardIgnored = isHardIgnoredPath(relativePath))
and then, inside the patterns loop where matchesWorkspacePattern(relativePath,
path, pattern) is checked, do not allow negated rules to flip ignored back to
false when hardIgnored is true — either skip applying negations or always keep
ignored true for hardIgnored paths; update references to ignored (and the
matchesWorkspacePattern handling) accordingly so hardIgnored paths remain
non-overridable.
🪄 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: a4b8b7b4-d44c-489d-a531-bef1d7d05774
📒 Files selected for processing (8)
src/runtime/context-pack-diagnostics.tssrc/runtime/context-pack.tssrc/runtime/retrieval-gate.tssrc/runtime/retrieve.tssrc/shared/source-discovery.tstests/unit/detect.test.tstests/unit/retrieval-gate.test.tstests/unit/retrieve.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 (3)
- src/runtime/retrieval-gate.ts
- src/runtime/context-pack-diagnostics.ts
- src/runtime/context-pack.ts
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Summary
Verification
Summary by CodeRabbit