Skip to content

Latest commit

 

History

2 Commits

Folders and files

NameName
Last commit message
Last commit date
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

CodeGraft Logo

🌿 CodeGraft

Surgical Code Patching & Grafting Engine with Compiler Verification for Agentic AI
Byte-precision AST refactoring, automatic indentation alignment, and compiler-verified zero-disk-corruption protection for autonomous coding agents.

CI Status Python Version License Protocol


🎯 The Problem CodeGraft Solves

Autonomous coding agents (Cursor, Claude Code, Antigravity, Cline, Windsurf, custom agents) repeatedly fail at brownfield codebase edits:

  1. Lazy Truncation (// TODO: rest of code...): Agents rewrite 1,000-line files with write_to_file, accidentally discarding existing functions, interfaces, or comments.
  2. Context Window Bankruptcy: Reading full files to edit a 5-line function wastes 85%+ of the agent's context window.
  3. Fragile String Replace: Naive search-replace tools fail when whitespace, indentation, or line endings don't match character-for-character.
  4. Syntax Corruption: Agents introduce missing braces or unindented blocks, then spend 5 turns failing to locate the compiler error.

🔬 The Solution: CodeGraft

codegraft operates directly on Tree-sitter Abstract Syntax Trees (AST):

  • Zero Truncation Guarantee: Only the exact byte range of the target symbol (function, method, class) is grafted. Surrounding code, comments, docstrings, and formatting are 100% untouched.
  • Context-Light Outlines (ast_outline): Returns hierarchical symbol trees with line ranges and signatures in < 500 tokens instead of loading 15,000 tokens of file content.
  • Pre-Write Syntax Verification Gate: The grafted AST is compiled and validated in memory. If any syntax error (ERROR or MISSING node) is detected, the write is rejected and disk content remains 100% untouched.
  • Indentation Auto-Alignment: Normalizes incoming code to match the target scope's indentation level (e.g. methods inside classes automatically inherit class body indent).
  • Multi-Language Native: Python, TypeScript, TSX, JavaScript, Go, Rust, and JSON.
  • Model Context Protocol (MCP): Native stdio JSON-RPC 2.0 server ready to plug into Antigravity, Claude Desktop, Cursor, or Cline.

🚀 Installation

# Using uv (recommended)
uv tool install --from . codegraft

# Or editable development install
uv pip install -e .

🛠️ MCP Integration (Agent Configuration)

Add codegraft to your MCP configuration (~/.gemini/config/mcp_config.json or claude_desktop_config.json):

{
  "mcpServers": {
    "codegraft": {
      "command": "uv",
      "args": ["run", "--directory", "C:/ProjectIseng/codegraft", "codegraft", "mcp"]
    }
  }
}

Available MCP Tools

Tool Purpose
ast_outline Extract class/function/method hierarchy without dumping full files (saves 85% context tokens).
ast_get_symbol Retrieve the exact source code of a symbol by name.
ast_patch_symbol Surgically replace a function/method/class with compiler verification before write.
ast_insert_symbol Insert code before, after, inside_start, or inside_end of an existing symbol.
ast_delete_symbol Surgically delete a symbol with clean whitespace hygiene.
ast_check_syntax Check AST syntax validity and extract line-by-line syntax errors.

💻 CLI Usage

# 1. Inspect file outline (without loading entire body into context)
codegraft outline src/api.ts

# 2. View a specific function
codegraft get src/services/user.py calculate_score

# 3. Surgically graft/patch a function
codegraft patch src/services/user.py calculate_score --code "def calculate_score(user):\n    return user.points * 2"

# 4. Insert a new method inside a class
codegraft insert src/models.py --code "def validate(self):\n    return True" --relative-to "User" --position inside_end

# 5. Delete a deprecated method cleanly
codegraft delete src/api.ts oldHandler

# 6. Check syntax validity across multiple files
codegraft check src/complex.rs

# 7. Run MCP Server over stdio
codegraft mcp

🧪 Rigorous Quality Control (131/131 Tests PASS)

uv run pytest -v
============================= 131 passed in 1.84s =============================
  • Python (25 tests): Async, generators, type annotations, try-except, classmethods, properties, nested closures, walrus operator, lambdas.
  • TypeScript / TSX (25 tests): Generics, interfaces, arrow functions, union types, React JSX elements, optional chaining, rest parameters.
  • Go (20 tests): Struct fields, pointer & value receivers, variadics, goroutines, channels, selects, automatic semicolon insertion, EOF newline enforcement.
  • Rust (20 tests): Structs, Result/Option types, lifetimes ('a), impl blocks, mutable references, generics, trait definitions.
  • Stress & Edge Cases (10 tests): Multibyte UTF-8 emojis, 2,000-line files, sequential multi-patching, nested scopes (3 levels).
  • Core Engine & MCP (31 tests): Outline extraction, diffing, dry-run simulation, .bak backups, Windows CRLF preservation, JSON-RPC 2.0 stdio handshake.

🏗️ Architecture

[Agent Intent] ──> [MCP JSON-RPC Stdio / CLI]
                         │
                         ▼
             [CodeGraft Dispatcher]
                         │
        ┌────────────────┼────────────────┐
        ▼                ▼                ▼
 [Tree-sitter AST] [Indentation Engine] [Syntax Verification]
        │                │                │
        └────────────────┼────────────────┘
                         ▼
        [Memory AST Validation: has_error?]
              ├── True  ──> [ABORT: Return Compiler Errors to Agent]
              └── False ──> [Atomic Disk Write + Unified Diff]

🛡️ License

Apache-2.0

About

Surgical Code Patching & Grafting Engine with Compiler Verification for Agentic AI (Tree-sitter, Zero-Truncation, MCP)

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages