Skip to content

feat(tools): add AST-aware code rewriting via ast-grep #412

@vitali87

Description

@vitali87

Summary

Add ast-grep's pattern-based rewrite capability as a new editing tool, complementing the existing text-based FileEditor (which uses diff-match-patch).

Motivation

Current editing is text-based and fragile (breaks on whitespace changes, cannot scope to functions). ast-grep rewrites are syntax-aware: rename a variable only within its scope, swap function arguments structurally, add decorators to all matching functions. This enables batch transformations where one pattern can fix many occurrences across the codebase.

Implementation

  • codebase_rag/tools/structural_editor.py (~80 lines) agentic tool wrapper
  • codebase_rag/tools/ast_grep_service.py (shared service, replace portion)
  • Add STRUCTURAL_REPLACE to AgenticToolName and MCPToolName enums
  • Add StructuralReplaceChange type to types_defs.py
  • Register as both agentic tool and MCP tool
  • Reuse existing diff visualization and approval workflow from main.py
  • Integrate with the existing approval workflow (generate diffs, user confirms)

Acceptance Criteria

  • Structural replace tool callable by agentic chat and MCP server
  • Pattern-based rewrite using ast-grep's SgRoot.replace() and commit_edits()
  • Dry-run mode that shows diffs without applying changes
  • Integration with existing approval workflow (user confirms before apply)
  • Batch mode: single pattern applied across multiple files
  • Graceful degradation when ast-grep-py is not installed
  • Unit tests for replacement operations

Related

Part of the ast-grep integration initiative:

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementNew feature or request

    Projects

    Status

    No status

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions