Edit large files without losing your mind. grafty indexes code into structural units (functions, classes, headings) so you can reference specific pieces instead of showing entire files. Perfect for LLM agents, batch refactoring, and token-efficient workflows.
# Instead of asking an LLM to show you the whole 500-line file...
# Just show what matters:
grafty show "src/main.py:py_function:parse_config"
# Returns only that function (10 lines). Token-efficient. ✅Problem: When you edit large files, you have two bad choices:
- Show the entire file (expensive tokens, noise, context bloat)
- Use line numbers (fragile, breaks when file changes)
Solution: grafty understands structure. Reference code by what it is, not where it is:
src/main.py:py_function:parse_config← Still the same function even if movedREADME.md:md_heading:Installation← Still the same section even if reorderedtasks.org:org_heading_preamble:Phase 1← Edit intro, keep subsections intact
Result: Safe, bounded, token-efficient editing. For you, for LLM agents, for batch refactoring.
✅ Show bounded snippets — Instead of sending entire files to LLMs, show just the function/class/section they need
✅ Refactor safely — Replace, insert, delete with atomic writes and dry-run preview
✅ Batch edit — Find all functions matching a pattern, apply changes across files
✅ Understand structure — Index any codebase and see what's inside (no LSP needed)
✅ Integration-friendly — Works with Git, generates clean unified diffs
✅ LLM-native — Designed for agents: selectors are stable, output is bounded
Let's say you have a file with a function that needs fixing:
# src/validators.py
def validate_email(email):
# Naive implementation that doesn't work
if "@" in email:
return True
return FalseInstead of:
# ❌ Show me lines 5-10 (brittle, what if the file changes?)
# ❌ Show me the whole file (50 lines, tokens wasted on context)You do:
# ✅ Show me the validate_email function
grafty show "src/validators.py:py_function:validate_email"
# Output:
# ──── src/validators.py:py_function:validate_email (lines 2-5)
# def validate_email(email):
# if "@" in email:
# return True
# return FalseThen replace it:
# Preview the change first (dry-run)
grafty replace "src/validators.py:py_function:validate_email" \
--text "def validate_email(email):
\"\"\"Validate email using basic RFC rules.\"\"\"
return bool(re.match(r'^[a-zA-Z0-9+._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$', email))" \
--dry-run
# See the unified diff before applying
# Apply it when ready
grafty replace "src/validators.py:py_function:validate_email" \
--text "..." --apply --backupThat's it. Safe, clean, token-efficient. Works with any language grafty supports.
grafty is available as a system tool. Just use it:
grafty --help # Should work
grafty index . # Index your projectIf it's not installed yet:
# Clone the repo
git clone https://github.com/apcooley/grafty.git
cd grafty
# Install as a system tool
python3 -m pip install -e .
# or: uv pip install -e .
# Verify it works
grafty --help# Clone and set up
git clone https://github.com/apcooley/grafty.git
cd grafty
# Install dependencies (auto-managed by uv)
uv sync
# Run with development environment
uv run grafty index .
uv run grafty show "file.py:py_function:my_func"
uv run pytest tests/ # Run tests- Python 3.10+ (any OS: Linux, macOS, Windows WSL)
- Tree-sitter (auto-installed via dependencies, no manual setup needed)
- Git (optional, for validation and patch checking)
That's it! No complicated setup.
grafty index src/main.py
# Output shows everything grafty found:
# src/main.py (12 nodes)
# [py_class ] DataProcessor (lines 1-50)
# [py_method] __init__ (lines 2-10)
# [py_method] parse (lines 12-30)
# [py_method] validate (lines 32-50)
# [py_function] main (lines 52-65)# Show just the parse method
grafty show "src/main.py:py_class:DataProcessor.parse"
# or
grafty show "src/main.py:py_method:parse"
# Output: just the method, bounded (no token waste)# Create a file with your new implementation
cat > new_validate.py << 'EOF'
def validate_email(email):
"""Validate email using basic RFC rules."""
return bool(re.match(r'^[a-zA-Z0-9+._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$', email))
EOF
# Use grafty to replace the old function with the new one
grafty replace "src/validators.py:py_function:validate_email" \
--file new_validate.py \
--dry-run # Preview first
# See the unified diff, then apply when ready
grafty replace "src/validators.py:py_function:validate_email" \
--file new_validate.py \
--apply --backup# See what changed
git diff src/main.py
# Or re-show the node to confirm
grafty show "src/main.py:py_method:parse"Done! You just edited a structured piece of code safely and efficiently.
| Language | What You Can Edit | Example |
|---|---|---|
| Python (.py) | Classes, methods, functions, docstrings | file.py:py_function:parse_configfile.py:py_docstring:parse_config |
| JavaScript (.js, .jsx) | Functions, classes, methods, JSDoc | app.js:js_function:handlerapp.js:js_jsdoc:handler |
| TypeScript (.ts, .tsx) | Functions, classes, methods, interfaces, types, enums, TSDoc | app.ts:ts_interface:Configapp.ts:ts_doc:handler |
| Go (.go) | Functions, methods, types, structs, doc comments | main.go:go_function:mainmain.go:go_doc:main |
| Rust (.rs) | Functions, structs, impls, traits, macros, doc comments | lib.rs:rs_struct:DataProcessorlib.rs:rs_doc:process |
| Bash (.sh, .bash) | Functions, doc comments | deploy.sh:bash_function:backup_dbdeploy.sh:bash_doc:backup_db |
| Java (.java) | Classes, interfaces, enums, methods, constructors, Javadoc | Service.java:java_method:authenticateService.java:java_doc:authenticate |
| Markdown (.md) | Headings, sections, intro paragraphs | README.md:md_heading:Installation |
| Org-mode (.org) | Headings, subtrees, intro paragraphs | tasks.org:org_heading:Phase 1 |
| Clojure (.clj/.cljs) | Namespaces, defs, macros, docstrings | core.clj:clj_defn:my_funccore.clj:clj_docstring:my_func |
| HTML (.html, .htm) | Elements, IDs, classes, attributes | index.html:html_id:mainpage.html:html_class:container |
| CSS (.css) | Rules, selectors | style.css:css_rule:.containertheme.css:css_selector:nav ul li |
Structural Selectors — Reference code by structure, not line numbers
grafty show "src/main.py:py_function:validate" # Stable, even if file changesLine Numbers (When You Need Them) — Quick fixes with simple ranges
grafty show "src/main.py:42" # Single line
grafty show "src/main.py:42-50" # Range of linesHeading Preambles — Edit section intros without destroying subsections (Markdown & Org-mode)
# Edit just the intro text of a heading, preserve all subheadings
grafty replace "README.md:md_heading_preamble:Installation" \
--text "# Installation\n\nNew intro here." \
--applyDocumentation Extraction — Read/update docs independently from code (Python, JS/TS, Go, Rust, Clojure, Java, Bash)
# Show only the docstring, not implementation
grafty show "validators.py:py_docstring:validate_email"
# Update JSDoc without touching code
grafty replace "api.ts:ts_doc:handleRequest" \
--text "/**\n * Handles HTTP requests.\n * @param req Request\n */" \
--apply
# Find all undocumented functions (search returns empty for missing docstrings)
grafty search "*" --kind "py_function" --json | \
jq -r '.[] | select(.name as $n | (grafty search $n --kind "py_docstring" --json | length) == 0)'Insert Command — Programmatically add code at precise locations
# Insert at specific line
grafty insert "app.py" --line 42 --text "# TODO: refactor" --apply
# Insert method at end of class
grafty insert "models.py:py_class:User" --inside-end \
--text " def validate(self): pass" --apply
# Insert import before first function
grafty insert "utils.py:py_function:main" --before \
--text "import logging" --applyPattern Search — Find nodes by name pattern
grafty search "*validate*" # All validation functions
grafty search "test_*" --path "tests/" # All tests in tests/ directory
grafty search "*handler*" --kind "js_function" # JS handlers onlyDry-Run Mode — Always preview before applying
grafty replace ... --dry-run # Shows unified diff
grafty replace ... --apply # Apply if it looks goodAtomic Writes — No partial changes, no corruption
- Changes are written to temp file, then renamed (atomic)
- Optional automatic backups (
.bakfiles) - Safe to use even with long-running processes
Safety Guarantees — Peace of mind when editing
grafty replace ... --apply --backup # Auto-backup
grafty replace ... --dry-run # Preview first
grafty check my.patch # Validate patchesProblem: Your agent is writing code for a 500-line file. Show it just the function it needs to edit:
# Instead of context bloat, agent gets bounded output
grafty show "src/processing.py:py_function:process_data"
# Agent writes new implementation
# You apply it
grafty replace "src/processing.py:py_function:process_data" \
--text "$(agent_output)" --apply --backupBenefits:
- Smaller context window (save 100+ tokens per operation)
- Agents stay focused on one piece at a time
- Patch diff makes changes auditable before applying
Problem: You need to rename a function across 10 files and update all callers.
# Find all calls to old_name
grafty search "old_name*"
# Replace them systematically
grafty replace "src/main.py:py_function:old_name" --file new_impl.py --apply
grafty replace "src/utils.py:py_function:old_name" --file new_impl.py --apply
# ... (repeatable, safe)Benefits:
- No need for IDE refactoring (works anywhere: CLI, remote, scripts)
- Every change generates a visible diff
- Easy to automate or batch
Problem: You need to update docstrings or comments in Markdown without affecting code examples.
# Edit just the intro of a section (keep examples, code blocks intact)
grafty show "DESIGN.md:md_heading_preamble:Architecture"
grafty replace "DESIGN.md:md_heading_preamble:Architecture" \
--file new_intro.txt --applyBenefits:
- Edit documentation structure without touching nested examples
- Precise, bounded changes
- Great for collaborative docs (less merge conflicts)
Problem: You're building an auto-fixer that applies changes to multiple repos.
# grafty generates clean unified diffs
grafty replace "src/api.py:py_function:old_handler" \
--file new_handler.py --patch-out my_changes.patch
# Apply the patch in CI/CD
git apply my_changes.patch
# Or review first
git apply --check my_changes.patchBenefits:
- Standard unified diff format (works with
git apply,patchcommand, etc.) - Dry-run lets you validate before pushing
- Integrates with existing git workflows
Once you're familiar with the basics, check these for deeper knowledge:
- USAGE.md — Detailed command reference with all flags and options
- ARCHITECTURE_DECISIONS.md — Why grafty was built this way (for the curious)
- CHANGELOG.md — Version history and feature releases
- DESIGN.md — Original architecture sketches and design rationale
For development:
cd ~/source/grafty
uv sync # Install dev dependencies
uv run pytest tests/ -v # Run tests (all 37 passing)
uv run ruff check grafty/ # Lint codeAbsolutely. Safety is a core design principle:
✅ Atomic writes — Changes written to temp file, then renamed (no partial writes)
✅ Dry-run mode — Always preview with --dry-run before applying
✅ Automatic backups — Optional --backup creates .bak files
✅ Patch validation — grafty check my.patch uses git apply --check
✅ Clear diffs — Every change shows unified diff so you can audit it
Golden rule: Use --dry-run first, review the diff, then apply if it looks good.
Easy recovery:
-
Backup exists — If you used
--backup, restore from.bak:cp src/main.py.bak src/main.py
-
Git history — If it's in a git repo:
git checkout src/main.py # Revert the whole file git diff # See what changed (before your edit)
-
Try again — Use
--dry-runnext time to preview first.
Yes! grafty is designed for LLM workflows:
# Pseudocode: LLM workflow with grafty
current_state = subprocess.run([
"grafty", "show",
"src/main.py:py_function:validate"
]).stdout
prompt = f"""
Here's the current implementation:
{current_state}
Make it better.
"""
new_code = llm.generate(prompt)
# Apply the change
subprocess.run([
"grafty", "replace",
"src/main.py:py_function:validate",
"--text", new_code,
"--apply", "--backup"
])Benefits for LLM use:
- Bounded output (agent sees exactly what it needs to edit)
- Stable selectors (function name doesn't change when file does)
- Clean diffs for review
- Token-efficient (show 20 lines, not 500)
grafty skips them, but you can still use line-based editing as a fallback:
# Works on any text file
grafty show "unknown.txt:42-50"
grafty replace "unknown.txt:42-50" --text "new content" --applyFor maximum impact, focus grafty on code files (Python, JS, Go, Rust, Markdown, Org).
sed works on patterns; grafty understands structure:
sed -i 's/old_name/new_name/g'might rename variables, function names, comments—too broadgrafty show "file.py:py_function:old_name"is precise—it's definitely that functiongrafty replacehandles nested scopes correctly (methods inside classes)
IDE refactoring is great locally; grafty works everywhere:
- No IDE installation needed
- Works on remote machines, in CI/CD, in containers
- Scriptable for batch operations
- Works across the web via simple CLI calls
Use both! IDE for interactive work, grafty for automation and edge cases.
Yes. grafty outputs standard unified diffs:
grafty replace "src/main.py:py_function:handler" \
--file new_impl.py \
--patch-out my_changes.patch
# my_changes.patch is a standard unified diff
# Use standard merge tools:
git apply my_changes.patch
patch < my_changes.patchIf conflicts arise, use git's 3-way merge or your favorite merge tool.
| Feature | grafty | LSP |
|---|---|---|
| Setup | Single install, works everywhere | Per-language, requires LSP server |
| Portability | CLI, works remote, in containers | IDE-centric |
| Symbol knowledge | Tree-sitter (syntax-based) | Compiler-aware (semantic) |
| For LLMs | Perfect (bounded output) | Overkill (better for IDE) |
| Batch editing | ✅ Great | ❌ Not designed for this |
| Type awareness | Limited (syntax only) | Full (compiler-aware) |
Bottom line: grafty is for editing; LSP is for IDE integration. Use grafty for agents and batch work.
- Questions? Check
USAGE.mdor rungrafty --help - Bug report? Open an issue on GitHub
- Feature request? See the Roadmap for what's planned
grafty is actively developed. Here's what's coming:
Current: Phase 3 ✅ Complete in v0.4.0 (Line-number editing, error messages, query language)
Future phases: See docs/ROADMAP.md for phases 4–7 (safety, visualization, performance, extended languages)
Right now, you can:
- ✅ Install grafty (
pip install -e .or use system install) - ✅ Index your codebase (
grafty index .) - ✅ Show bounded snippets (
grafty show "file.py:py_function:func") - ✅ Make safe edits (
grafty replace ... --dry-run --apply) - ✅ Search for code (
grafty search "*pattern*")
Pick a file, try it:
# Pick any Python, JS, Go, Rust, Markdown, or Org file
grafty index myfile.py
# Pick a function or class name
grafty show "myfile.py:py_function:my_func"
# Try editing it
grafty replace "myfile.py:py_function:my_func" \
--text "def my_func():\n return 42" \
--dry-runQuestions? Check USAGE.md or run grafty --help.
Contributions welcome! See docs/CONTRIBUTING.md for:
- How to set up your development environment
- Starter tasks organized by complexity (Low/Medium/High)
- How to run tests and validate your work
- The design philosophy behind grafty
Good starter issues:
- Bug reports with reproducers
- Documentation improvements
- Performance profiling
- Real-world use case feedback
Want to add a language? Check the phase breakdown in docs/ROADMAP.md (Phase 7).
MIT — Use freely, modify, distribute. See LICENSE for details.
Happy editing! 🎯
Made for humans and LLMs alike.