Skip to content

Fix production retrieval correctness - #146

Merged
mohanagy merged 3 commits into
mainfrom
retrieval-correctness
May 12, 2026
Merged

mohanagy merged 3 commits into
mainfrom
retrieval-correctness

Conversation

@mohanagy

@mohanagy mohanagy commented May 11, 2026 •

Copy link
Copy Markdown
Owner

Summary

  • share default hard-ignore rules across legacy detect and SPI and add source-domain classification
  • make retrieval exclusions operational, fix negated test intent parsing, and prefer exact method anchors with truthful slice reasons
  • deepen slice-v1 runtime traversal, add bad-pack diagnostics, and lock behavior with production-correctness regressions

Verification

  • npm run typecheck
  • npm run build
  • npm run test:run

Summary by CodeRabbit

  • Changed
    • Default discovery now hard-ignores nested VCS/worktree copies, common build/cache outputs and saved memory artifacts while indexing tests/fixtures unless explicitly excluded
    • Retrieval honors exclusion phrases and emits structured exclusion signals (terms, path hints, domains); scoring uses source-domain penalties and literal-path anchoring
    • Anchoring/traversal improved for method-level and runtime/pipeline prompts; slicing adapts to anchors and intent
    • Diagnostics expanded to flag excluded/polluted domains, controller/pipeline shapes, missing anchors, and test-dominated packs
  • Documentation
    • README documents default discovery rules and .graphifyignore negation semantics
  • Tests
    • Added/updated tests for discovery, retrieval, diagnostics, scoring, and slice behavior

Review Change Stack

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
@coderabbitai

coderabbitai Bot commented May 11, 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: c87139ab-9f0a-420b-b179-bddfb57d24d7

📥 Commits

Reviewing files that changed from the base of the PR and between 3dd1ecf and b06d99b.

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

📝 Walkthrough

Walkthrough

Adds 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.

Changes

Source-domain filtering and discovery

Layer / File(s) Summary
Source Discovery Foundation
src/shared/source-discovery.ts
New module: path normalization, DEFAULT_HARD_IGNORE_GLOBS, hard-ignore regexes, .graphifyignore loader, isDiscoveryPathIgnored/isIgnoredByPatterns, classifySourceDomain, and isPollutedSourcePath.
Contract Updates
src/contracts/context-pack.ts, src/contracts/retrieval-gate.ts, src/contracts/context-pack-diagnostics.ts
ContextPackNode adds optional source_domain; new RetrievalExcludedDomain and exclusion signal fields; ContextPackDiagnosticKind and ContextPackQualitySignals extended with domain/pollution/structural diagnostics/signals.
Discovery Pipeline Refactoring
src/pipeline/detect.ts, src/pipeline/spi/build.ts
Detect and SPI build now load .graphifyignore patterns and call isDiscoveryPathIgnored/isIgnoredByPatterns; removed local glob helpers, reduced SKIP_DIRS, and removed special-case graphify-out/memory scan.
Retrieval Gate Exclusions
src/runtime/retrieval-gate.ts
Adds extractPromptExclusions() to detect exclusion spans, split/normalize phrases, map to excluded domains/path hints, produce a positivePrompt, and emit excluded_domains/excluded_terms/excluded_path_hints signals; expands symbol detection for non-backtick explicit references.
Symbol Reference Parsing
src/runtime/retrieve.ts
Introduces SymbolReference parsing, parseSymbolReference, and symbolReferenceMatchScore to drive precise symbol anchoring.
Retrieval Seed & Expansion Scoring
src/runtime/retrieve.ts
Seed and expansion candidates now carry sourceDomain, literalPathMatch; retrieval computes classificationRootPath; seeds are gated by excluded domains/terms/path hints and polluted-path checks unless strongly anchored; domain penalties/boosts applied; source_domain serialized in results.
Retrieval Slicing Policy
src/runtime/retrieve/slicing.ts
Adds effectivePolicy() to adjust traversal for method anchors and runtime prompts; adds SliceOptions; extends SliceScoredNode with nodeKind/frameworkRole/literalPathMatch; shouldSuppressNode now uses domain/pollution/exclusion signals; sliceCandidatesForRetrieve() accepts options.
Context Pack Candidate Scoring
src/runtime/context-pack.ts
Candidates resolved for source_domain via precedence; isTestEntry/isConfigurationEntry now use classifySourceDomain; added sourceDomainPenalty() and domain-aware boosts/penalties to scoring.
Context Pack Diagnostics
src/runtime/context-pack-diagnostics.ts
computeContextPackDiagnostics extended with polluted_source_path_selected, excluded_domain_selected, test_dominated_pack, controller_only_pipeline_pack, missing_method_anchor, missing_runtime_pipeline, missing_structural_evidence; computeSignals now returns domain_distribution, excluded_domains, and polluted_source_path_count; quality score uses fixed denominator.
Documentation
CHANGELOG.md, README.md
Document default discovery rules (hard-ignored build/VCS/cache paths; tests/benchmarks/fixtures indexed but soft-penalized), .graphifyignore override semantics, intent-aware exclusions, anchoring/traversal behavior, and diagnostics changes.

Test coverage

Layer / File(s) Summary
Discovery Tests
tests/unit/detect.test.ts, tests/unit/spi-build.test.ts
Verify nested worktrees/graphify-out/dist are hard-ignored; confirm tests/benchmarks/fixtures and config files are indexed; validate .graphifyignore matching semantics.
Retrieval Gate Tests
tests/unit/retrieval-gate.test.ts
Adds tests for explicit Class.method and module.function detection; verifies exclusions map to signals.excluded_domains/signals.excluded_terms and preserve explain intent when appropriate.
Context Pack Diagnostics Tests
tests/unit/context-pack-diagnostics.test.ts
New tests assert excluded-domain selection, polluted-source-path selection, controller-only pipeline pack, missing method anchor, missing runtime pipeline, test-dominated pack, and missing structural evidence warnings.
Production Retrieval Correctness
tests/unit/retrieve-production-correctness.test.ts
End-to-end tests build a production-like pipeline graph to validate domain/term suppression, Class.method anchor promotion, anchor-reason distinctions, and absence of incorrect diagnostic warnings.
Benchmark & Generate Tests
tests/unit/benchmark-quality.test.ts, tests/unit/generate.test.ts
Benchmark uses isolated OS temp directories; generate.test verifies saved memory notes under graphify-out/memory are not re-indexed.
Absolute Path Retrieval Tests
tests/unit/retrieve.test.ts
Ensure absolute tmp source paths are retained when graph.root_path is unset (cross-platform checks).

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Possibly related PRs

"I hopped through paths both clean and wild,
I nudged exclusions so prompts stay mild.
Domains wear tags and anchors find their mark,
The graph grows tidy, no more stray in the dark." 🐰

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 2.60% 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 The title accurately summarizes the main objective of the PR: fixing production retrieval correctness by introducing source-domain classification, operational retrieval exclusions, exact method anchoring, and diagnostic improvements.
Description check ✅ Passed The PR description covers the main changes (source-domain classification, retrieval exclusions, slice-v1 improvements, diagnostics) and verification steps, though it lacks explicit testing section formatting and checklist completion as specified in the template.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ 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 retrieval-correctness

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: 3

🧹 Nitpick comments (6)
src/runtime/context-pack-diagnostics.ts (2)

340-355: 💤 Low value

missingRuntimePipeline may produce false positives.

The function checks for both pipelineNodeCount === 0 and structuralRelations === 0. However, it already calls pipelinePrompt(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 value

Fixed 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 value

Regex may miss some valid symbol patterns.

The SYMBOL_EXPLICIT_RE pattern requires the class name to start with uppercase ([A-Z]), which won't match lowercase class names or module-style references like utils.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 value

Clarify the intent of domain boost for non-production sources.

The +0.25 boost for domains that are neither production nor unknown seems 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 value

Symbol matching score thresholds could benefit from documentation.

The symbolReferenceMatchScore function 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 >= 3 at line 1673, symbolMatch >= 3 at 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 value

Anchor reason cascade has a potential logic gap.

The reason assignment at lines 203-209 uses a cascade: exactLabelMatch → literalPathMatch → sourcePathMatch → default. However, sourcePathMatch could be true when both exact label AND source path match. The current order prioritizes exactLabelMatch which seems correct, but the intermediate literalPathMatch check (line 205) could mask cases where sourcePathMatch is 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

📥 Commits

Reviewing files that changed from the base of the PR and between 7d4e486 and 64b1ee2.

📒 Files selected for processing (20)
  • CHANGELOG.md
  • README.md
  • src/contracts/context-pack-diagnostics.ts
  • src/contracts/context-pack.ts
  • src/contracts/retrieval-gate.ts
  • src/pipeline/detect.ts
  • src/pipeline/spi/build.ts
  • src/runtime/context-pack-diagnostics.ts
  • src/runtime/context-pack.ts
  • src/runtime/retrieval-gate.ts
  • src/runtime/retrieve.ts
  • src/runtime/retrieve/slicing.ts
  • src/shared/source-discovery.ts
  • tests/unit/benchmark-quality.test.ts
  • tests/unit/context-pack-diagnostics.test.ts
  • tests/unit/detect.test.ts
  • tests/unit/generate.test.ts
  • tests/unit/retrieval-gate.test.ts
  • tests/unit/retrieve-production-correctness.test.ts
  • tests/unit/spi-build.test.ts

Comment thread src/runtime/retrieve.ts Resolved
Comment thread src/shared/source-discovery.ts Resolved
Comment thread src/shared/source-discovery.ts Resolved
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>

@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: 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 win

Re-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 candidatesById without rechecking any of those gates. With semantic: true or rerank: 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 win

Don't let negated .graphifyignore rules reopen hard-ignored paths.

This still lets a later !pattern flip ignored back to false after isHardIgnoredPath(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

📥 Commits

Reviewing files that changed from the base of the PR and between 64b1ee2 and 3dd1ecf.

📒 Files selected for processing (8)
  • src/runtime/context-pack-diagnostics.ts
  • src/runtime/context-pack.ts
  • src/runtime/retrieval-gate.ts
  • src/runtime/retrieve.ts
  • src/shared/source-discovery.ts
  • tests/unit/detect.test.ts
  • tests/unit/retrieval-gate.test.ts
  • tests/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

Comment thread src/runtime/retrieve.ts Resolved
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
@mohanagy
mohanagy merged commit 76074e6 into main May 12, 2026
7 checks passed
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.

1 participant