Skip to content

fix(core): merge grep context hunks#17274

Merged
abhiaiyer91 merged 1 commit into
mainfrom
fix/bug-02-grep-context-line-duplication
May 30, 2026
Merged

fix(core): merge grep context hunks#17274
abhiaiyer91 merged 1 commit into
mainfrom
fix/bug-02-grep-context-line-duplication

Conversation

@mbenhamd

@mbenhamd mbenhamd commented May 29, 2026

Copy link
Copy Markdown
Contributor

Description

Fixes workspace grep context output so overlapping or adjacent context windows are merged before rendering. This prevents the same line from appearing multiple times when matches are near each other.

The grep tool now collects matches for each file, builds merged context hunks, and renders separators only between distinct hunks. It also normalizes fractional contextLines values before calculating line indexes.

Related issue(s)

Fixes #17273

Type of change

  • Bug fix (non-breaking change that fixes an issue)
  • New feature (non-breaking change that adds functionality)
  • Breaking change (fix or feature that would cause existing functionality to change)
  • Documentation update
  • Code refactoring
  • Performance improvement
  • Test update

Checklist

  • I have linked the related issue(s) in the description above
  • I have made corresponding changes to the documentation (if applicable)
  • I have added tests that prove my fix is effective or that my feature works
  • I have addressed all Coderabbit comments on this PR

Validation

  • pnpm --filter ./packages/core test src/workspace/tools/__tests__/grep.test.ts
  • pnpm --filter ./packages/core check
  • pnpm --filter ./packages/core lint
  • pnpm build:core
  • pnpm prettier --check packages/core/src/workspace/tools/grep.ts packages/core/src/workspace/tools/__tests__/grep.test.ts .changeset/salty-rules-scream.md

ELI5

Imagine you're searching a document for specific words. The tool shows you the words you found plus some extra lines around them for context. The bug was: if you have two search results close to each other, those extra "context" lines would get shown twice because each result was showing its own separate context. This PR fixes it by smart merging—now when context windows overlap, the tool shows those lines just once instead of duplicating them.


Overview

This PR fixes a bug in the workspace_grep tool where overlapping or adjacent context windows caused the same source lines to appear multiple times in the output. The solution collects all matches in a file first, then merges nearby matches into unified context "hunks" before rendering output, ensuring each line appears only once and separators (--) only appear between distinct hunks.

Changes

Core Implementation

packages/core/src/workspace/tools/grep.ts — Refactored match output generation:

  • Changed from emitting context immediately per match during line scanning to collecting all matches first
  • Normalizes contextLines values (converting fractional values to integers)
  • Groups nearby matches into merged context hunks when contextLines > 0
  • Renders separators only between distinct hunks (not before first or after last)
  • When contextLines is 0, emits only matched lines
  • Maintains line truncation (MAX_LINE_LENGTH) behavior

Tests

packages/core/src/workspace/tools/tests/grep.test.ts — Added three new test cases:

  1. Verifies overlapping context windows are merged without duplicating context lines
  2. Verifies fractional contextLines values are normalized before rendering
  3. Verifies separate context hunks are rendered with separators between them (and no trailing separator)

Documentation

.changeset/salty-rules-scream.md — Added changeset entry marking this as a patch release for @mastra/core with note: "Fixed grep context output so overlapping matches are shown once."

Review Change Stack

Collect grep matches before rendering context output so overlapping or adjacent context windows are emitted once. Add regression coverage for overlapping hunks, fractional context lines, and separator placement.
@vercel

vercel Bot commented May 29, 2026

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Actions Updated (UTC)
mastra-docs-1.x Ready Ready Preview, Comment May 29, 2026 11:58am
mastra-playground-ui Ready Ready Preview, Comment May 29, 2026 11:58am

Request Review

@changeset-bot

changeset-bot Bot commented May 29, 2026

Copy link
Copy Markdown

🦋 Changeset detected

Latest commit: 797fca4

The changes in this PR will be included in the next version bump.

This PR includes changesets to release 20 packages
Name Type
@mastra/core Patch
mastracode Patch
@mastra/mcp-docs-server Patch
@internal/playground Patch
@mastra/client-js Patch
@mastra/opencode Patch
@mastra/longmemeval Patch
mastra Patch
@mastra/deployer-cloud Patch
@mastra/react Patch
@mastra/playground-ui Patch
@mastra/server Patch
@mastra/deployer Patch
create-mastra Patch
@mastra/express Patch
@mastra/fastify Patch
@mastra/hono Patch
@mastra/koa Patch
@mastra/nestjs Patch
@mastra/temporal Patch

Not sure what this means? Click here to learn what changesets are.

Click here if you're a maintainer who wants to add another changeset to this PR

@coderabbitai

coderabbitai Bot commented May 29, 2026

Copy link
Copy Markdown
Contributor

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: c9c528da-cdd6-44e5-9394-deea724c2145

📥 Commits

Reviewing files that changed from the base of the PR and between fcaf9ba and 797fca4.

📒 Files selected for processing (3)
  • .changeset/salty-rules-scream.md
  • packages/core/src/workspace/tools/__tests__/grep.test.ts
  • packages/core/src/workspace/tools/grep.ts

Walkthrough

This PR fixes the grep tool to eliminate duplicate context lines when matches overlap. The implementation collects all matches during file scan, then post-processes them into merged hunks for emission with separators between distinct hunks.

Changes

Grep overlap fix

Layer / File(s) Summary
Grep context hunk merging algorithm
packages/core/src/workspace/tools/grep.ts
Normalized contextLines, collected matches during the file scan into fileMatches, and replaced per-match context emission with post-scan hunk builder that groups nearby matches and emits merged output with -- separators between hunks and no trailing separator.
Context edge case tests
packages/core/src/workspace/tools/__tests__/grep.test.ts
Added three test cases covering overlapping context window merging, fractional contextLines normalization, and separate hunk rendering with mid-hunk separators.
Release documentation
.changeset/salty-rules-scream.md
Recorded patch-level release note for grep context deduplication fix.

🎯 3 (Moderate) | ⏱️ ~22 minutes

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title is concise (35 characters), uses proper capitalization with imperative mood, and directly describes the main change of merging grep context hunks.
Linked Issues check ✅ Passed The pull request implementation directly addresses all coding requirements from issue #17273: merging overlapping/adjacent context windows, eliminating duplicate lines, normalizing fractional contextLines values, and managing hunk separators correctly.
Out of Scope Changes check ✅ Passed All changes are within scope: the grep.ts refactoring implements the required merging logic, test cases validate the fix, and the changeset documents the patch release appropriately.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.

✏️ 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 fix/bug-02-grep-context-line-duplication

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 install failed. For unrecoverable errors, disable the tool in CodeRabbit configuration.


Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

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

@dane-ai-mastra

Copy link
Copy Markdown
Contributor

PR triage

Linked issue check skipped for core contributor @mbenhamd.


PR complexity score

Factor Value Score impact
Files changed 3 +6
Lines changed 173 +9
Author merged PRs 52 -20
Test files changed Yes -10
Final score -15

Applied label: complexity: low


Changed test gate

Changed Test Gate is pending. The Changed Test Gate / changed-tests check will update the test label when it completes.

@dane-ai-mastra dane-ai-mastra Bot added the tests: green ✅ Changed tests failed against base as expected label May 29, 2026
@abhiaiyer91 abhiaiyer91 merged commit 65a72e7 into main May 30, 2026
101 checks passed
@abhiaiyer91 abhiaiyer91 deleted the fix/bug-02-grep-context-line-duplication branch May 30, 2026 18:39
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

complexity: low Low-complexity PR tests: green ✅ Changed tests failed against base as expected

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[BUG] workspace grep duplicates context lines across adjacent matches

2 participants