Skip to content

Add bounded snippets to retrieve responses - #345

Merged
mohanagy merged 1 commit into
nextfrom
issue-338-retrieve-snippets
May 27, 2026
Merged

mohanagy merged 1 commit into
nextfrom
issue-338-retrieve-snippets

Conversation

@mohanagy

@mohanagy mohanagy commented May 27, 2026 •

Copy link
Copy Markdown
Owner

Summary

  • add bounded snippet shaping to retrieve compact and verbose responses
  • expose snippet_budget and top_n_with_snippet on the retrieve MCP tool
  • cover review-driven token-count and focus-line regressions in unit tests

Testing

  • npm run typecheck
  • npm run build
  • CI=1 npm run test:run

Closes #338

Summary by CodeRabbit

Release Notes

  • New Features

    • Added snippet token budgeting to retrieval operations with configurable limits.
    • New retrieval parameters: snippet_budget (default 3000 tokens) and top_n_with_snippet (default 8 nodes) to control snippet text size and coverage.
  • Updates

    • Retrieval results now include snippet truncation tracking and token usage accounting fields.

Review Change Stack

Closes #338

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

coderabbitai Bot commented May 27, 2026 •

Copy link
Copy Markdown
📝 Walkthrough

Walkthrough

This PR adds token-budgeted code snippets to the retrieve tool response, eliminating follow-up Read calls for accessing matched node source code. The feature introduces snippet budget accounting with tokenizer-based truncation, tool schema parameters, compact result integration, and comprehensive test coverage for snippet bounds and retrieve/context_pack alignment.

Changes

Snippet Token Budgeting for Retrieve

Layer / File(s) Summary
Snippet budget types, defaults, and token accounting
src/runtime/retrieve.ts
Tokenizer import, default constants (3000 tokens, 8 nodes), and snippetTokenCount helper enable token-aware budget accounting. RetrieveOptions, RetrieveMatchedNode, and result schemas updated with snippetBudget, topNWithSnippet, snippet_truncated, and budget tracking fields.
Snippet truncation and budget application logic
src/runtime/retrieve.ts
Core withRetrieveSnippetBudget function normalizes budget options, truncates snippet text using GPT tokenizer encode/decode, applies budget across nodes, zeroes snippets for nodes outside top-N window, and returns shaped result with snippet_budget_tokens_used and snippet_budget_tokens_remaining.
Compact result integration and stdio output
src/runtime/retrieve.ts
compactRetrieveResult and compactRetrieveResultForStdio now accept snippet options, apply budget during compaction, recompute token_count from truncated snippets, preserve snippet_truncated metadata in node reconstruction, and include budget accounting fields in final result.
Tool schema, parameter validation, and option threading
src/runtime/stdio/definitions.ts, src/runtime/stdio/tools.ts
retrieve tool schema adds snippet_budget and top_n_with_snippet optional parameters. Tool handler validates numeric ranges, constructs retrieveSnippetOptions, and threads options through both verbose (withRetrieveSnippetBudget) and compact (compactRetrieveResult) retrieval paths.
Test fixtures, unit tests, and integration validation
tests/unit/benchmark-artifact.test.ts, tests/unit/retrieve.test.ts, tests/unit/stdio-slice-surface.test.ts, tests/unit/mcp-schema-budget.test.ts
Fixture helper estimateSnippetTokens and updated buildPackFixture compute budget fields. Unit tests validate compact budget bounds, snippet truncation on small budgets, and withRetrieveSnippetBudget token count recomputation. Integration test verifies retrieve vs context_pack snippet alignment for overlapping nodes. Schema regression test ceiling raised for new parameter payload.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Poem

🐰 With snippets now flowing from retrieval's deep well,
The agent reads code straight, no more chasing shells.
Eight nodes, three thousand tokens to spend,
No follow-up Reads—the scaling won't bend!

🚥 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 The title 'Add bounded snippets to retrieve responses' clearly and concisely summarizes the main change: introducing snippet token budgeting to the retrieve tool.
Description check ✅ Passed The PR description covers the summary of changes, testing commands, and links the related issue, meeting the template requirements adequately.
Linked Issues check ✅ Passed The PR implements all major coding requirements from #338: snippet fields in responses, configurable snippet_budget/top_n_with_snippet parameters, default values of 3000 tokens/8 nodes, budget accounting fields, and comprehensive unit/integration tests.
Out of Scope Changes check ✅ Passed All changes are directly aligned with issue #338 objectives: snippet shaping in retrieve responses, MCP tool schema updates, snippet budget tracking, and supporting test cases—with no unrelated modifications.

✏️ 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 issue-338-retrieve-snippets

Warning

There were issues while running some tools. Please review the errors and either fix the tool's configuration or disable the tool if it's a critical failure.

🔧 ESLint

If the error stems from missing dependencies, add them to the package.json file. For unrecoverable errors (e.g., due to private dependencies), disable the tool in the CodeRabbit configuration.

ESLint skipped: no ESLint configuration detected in root package.json. To enable, add eslint to devDependencies.


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.

🧹 Nitpick comments (2)
tests/unit/stdio-slice-surface.test.ts (1)

137-150: 💤 Low value

Snippet line comparison could be fragile with different line endings or formatting.

The snippet line comparison splits on '\n' and trims whitespace. This works for controlled test data but could be fragile if line endings differ (e.g., CRLF vs LF on Windows) or if snippet formatting changes. However, since this is a controlled integration test with known fixture data, this approach is acceptable.

Optional: More robust line comparison

If you want to make the comparison more robust:

     const retrieveSnippetLines = new Set(
       (retrieveNode?.snippet ?? '')
-        .split('\n')
+        .split(/\r?\n/)
         .map((line) => line.trim())
         .filter((line) => line.length > 0),
     )
     const contextPackSnippetLines = new Set(
       (contextPackNode?.snippet ?? '')
-        .split('\n')
+        .split(/\r?\n/)
         .map((line) => line.trim())
         .filter((line) => line.length > 0),
     )

The regex /\r?\n/ handles both Unix (LF) and Windows (CRLF) line endings.

🤖 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/stdio-slice-surface.test.ts` around lines 137 - 150, The
line-splitting in the test is fragile because it uses '\n' only; update the
logic that builds retrieveSnippetLines and contextPackSnippetLines (the code
that calls .split('\n') on retrieveNode?.snippet and contextPackNode?.snippet)
to split on a regex that accepts both LF and CRLF (e.g., use /\r?\n/), then keep
the existing .map(trim).filter steps and the final expect unchanged so
comparisons succeed across platforms.
tests/unit/retrieve.test.ts (1)

2814-2821: 💤 Low value

Consider extracting snippet token counting to a helper function.

The snippet token counting logic is duplicated here and in the third test (lines 2912-2915). While acceptable for test code, extracting it to a local helper function would reduce duplication and improve maintainability.

♻️ Optional refactor to reduce duplication
+    function estimateSnippetTokens(nodes: Array<{ snippet: string | null | undefined }>): number {
+      return nodes.reduce(
+        (total, node) => total + (typeof node.snippet === 'string' && node.snippet.length > 0 ? estimateQueryTokens(node.snippet) : 0),
+        0,
+      )
+    }
+
     const snippetTokenCount = compactResult.matched_nodes.reduce(
       (total, node) => total + (typeof node.snippet === 'string' && node.snippet.length > 0 ? estimateQueryTokens(node.snippet) : 0),
       0,
     )

Or simply:

-    const snippetTokenCount = compactResult.matched_nodes.reduce(
-      (total, node) => total + (typeof node.snippet === 'string' && node.snippet.length > 0 ? estimateQueryTokens(node.snippet) : 0),
-      0,
-    )
+    const snippetTokenCount = estimateSnippetTokens(compactResult.matched_nodes)
🤖 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/retrieve.test.ts` around lines 2814 - 2821, Extract the duplicated
token-counting logic into a small helper function used by the tests: create a
function (e.g., countMatchedNodeTokens(nodes)) that accepts
compactResult.matched_nodes and returns both snippetTokenCount and
compactTokenCount by calling estimateQueryTokens on node.snippet and on the
composed node text (`${node.label} ${node.source_file}:${node.line_number}
${node.snippet ?? ''}`); replace the inline reductions that compute
snippetTokenCount and compactTokenCount with calls to this helper to remove
duplication and keep tests readable.
🤖 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.

Nitpick comments:
In `@tests/unit/retrieve.test.ts`:
- Around line 2814-2821: Extract the duplicated token-counting logic into a
small helper function used by the tests: create a function (e.g.,
countMatchedNodeTokens(nodes)) that accepts compactResult.matched_nodes and
returns both snippetTokenCount and compactTokenCount by calling
estimateQueryTokens on node.snippet and on the composed node text
(`${node.label} ${node.source_file}:${node.line_number} ${node.snippet ?? ''}`);
replace the inline reductions that compute snippetTokenCount and
compactTokenCount with calls to this helper to remove duplication and keep tests
readable.

In `@tests/unit/stdio-slice-surface.test.ts`:
- Around line 137-150: The line-splitting in the test is fragile because it uses
'\n' only; update the logic that builds retrieveSnippetLines and
contextPackSnippetLines (the code that calls .split('\n') on
retrieveNode?.snippet and contextPackNode?.snippet) to split on a regex that
accepts both LF and CRLF (e.g., use /\r?\n/), then keep the existing
.map(trim).filter steps and the final expect unchanged so comparisons succeed
across platforms.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro Plus

Run ID: 6528ddf3-e624-4c49-a10a-b5ab2be553cc

📥 Commits

Reviewing files that changed from the base of the PR and between d7708e8 and 85d5f72.

📒 Files selected for processing (7)
  • src/runtime/retrieve.ts
  • src/runtime/stdio/definitions.ts
  • src/runtime/stdio/tools.ts
  • tests/unit/benchmark-artifact.test.ts
  • tests/unit/mcp-schema-budget.test.ts
  • tests/unit/retrieve.test.ts
  • tests/unit/stdio-slice-surface.test.ts

@mohanagy
mohanagy merged commit 134f94a into next May 27, 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