Code Editor Skill
Code Editor Skill
How to Use This Skill
- Review the patterns and examples below
- Apply the relevant patterns to your implementation
- Follow the best practices outlined in this skill
Production-ready autonomous code modification agent with multi-file orchestration, dependency-aware modifications, and checkpoint recovery. Optimized for ~15x token multiplication in multi-agent systems.
When to Use This Skill
✅ Use code-editor when:
- Implementing features with 3+ file modifications
- Need automatic dependency resolution (package.json, Cargo.toml)
- Want syntax validation before commit (Python, TS, TSX, JSX, Rust)
- Require rollback capability for safe autonomous editing
- Working on full-stack features (backend + frontend + tests)
- Need token-efficient incremental editing
❌ Don't use code-editor when:
- Single file changes (use Edit tool directly)
- Simple text replacements
- Documentation-only updates
- Quick bug fixes in 1-2 files
Core Capabilities
1. Multi-File Orchestration
Coordinate changes across multiple files with dependency tracking.
Example:
Implementing user profile editing:
- Create ProfileEditor.tsx (frontend component)
- Create PUT /api/v5/users/me/profile (backend endpoint)
- Update package.json (add form validation library)
- Update Cargo.toml (add backend dependencies)
- All changes validated before commit
2. Checkpoint/Rollback System
Create state snapshots before modifications for safe rollback.
Workflow:
- Create checkpoint → 2. Apply modifications → 3. Validate → 4. Rollback if errors
Checkpoint Storage: .coditect/checkpoints/ (persists across sessions)
3. Syntax Validation
Multi-language syntax checking before commit:
| Language | Validator | Method |
|---|---|---|
| Python | AST parsing | ast.parse(content) |
| TypeScript | Type annotation detection | Pattern matching |
| TSX/JSX | React component validation | JSX pattern matching |
| JavaScript | Bracket matching | Structural validation |
| Rust | Cargo check | cargo check |
4. Dependency Management
Automatic package.json and Cargo.toml updates based on detected imports.
Features:
- Extract ES6 imports (
import X from 'Y') - Extract CommonJS requires (
const X = require('Y')) - Extract Python imports (
from X import Y) - Extract Rust crate imports (
use crate::X) - Resolve versions with default version map
- Validate against existing dependencies
5. Token Optimization
Incremental editing with minimal context per file (max 5000 tokens).
Token Budgets:
| Scenario | Files | Budget | Typical Usage | Savings |
|---|---|---|---|---|
| Single Component | 1 | 2,500 | 1,800 | - |
| Simple Feature | 3-5 | 15,000 | 12,000 | 20% |
| Complex Feature | 5-10 | 30,000 | 25,000 | 37% |
| Small Refactor | 10-20 | 50,000 | 40,000 | 40% |
| Large Refactor | 20-50 | 100,000 | 85,000 | 45% |
Optimization Techniques:
- Extract minimal context (imports + relevant code + exports)
- Batch similar operations
- Validate incrementally
Usage Pattern
Step 1: Initialize Code Editor
from code_editor import CodeEditorAgent
editor = CodeEditorAgent()
Step 2: Define Edit Request
result = await editor.process_edit_request(
feedback="Add user profile editing with form validation",
files=[
{"path": "/src/App.tsx", "content": "..."},
{"path": "/backend/src/handlers/users.rs", "content": "..."}
],
package_json={"dependencies": {"react": "^18.2.0"}},
cargo_toml={"dependencies": {"actix-web": "4.0"}}
)
Step 3: Handle Result
if result["success"]:
# Apply changes
for file in result["files"]:
write_file(file["path"], file["content"])
# Update dependencies
write_file("package.json", result["package_json"])
write_file("Cargo.toml", result["cargo_toml"])
else:
# Rollback
restored = await editor.restore_checkpoint(result["checkpoint_id"])
print(f"Rolled back {len(restored)} files")
Execution Workflow
Phase 1: Analysis & Planning
- Parse feedback to identify required operations
- Determine operation types (create, modify, delete, rename)
- Estimate token usage
- Assess risk level (low, medium, high)
- Plan validation steps
Phase 2: Execute Modifications
- Apply all edit operations atomically
- Track dependencies added/removed
- Maintain file integrity (checksums)
Phase 3: Validation
- Syntax check all modified files
- Identify validation errors
- Attempt auto-fix for common issues
Phase 4: Dependency Resolution
- Extract all imports from modified files
- Identify missing dependencies
- Resolve package versions
- Update package.json/Cargo.toml
Phase 5: Final Validation
- Comprehensive quality check
- Syntax validation (all files must pass)
- Circular dependency detection
- Unused component detection
- Quality score (0.0-1.0, threshold: 0.5)
Data Models
CodeFile (Immutable)
@dataclass(frozen=True)
class CodeFile:
path: str # File path
content: str # File content
language: str # File extension (py, ts, tsx, rs)
size: int # Content length
checksum: str # SHA-256 hash
EditOperation (Atomic)
@dataclass
class EditOperation:
file_path: str
operation_type: Literal["create", "modify", "delete", "rename"]
old_content: Optional[str]
new_content: Optional[str]
line_range: Optional[tuple[int, int]]
dependencies_added: List[str]
dependencies_removed: List[str]
EditPlan
@dataclass
class EditPlan:
objective: str # User's feedback
operations: List[EditOperation]
estimated_tokens: int # Token budget
risk_level: Literal["low", "medium", "high"]
rollback_strategy: str # "checkpoint_restore"
validation_steps: List[str] # Validation phases
Integration with T2 Orchestrator
Orchestrator Phase 3: Implementation
Phase 3: Implementation
├─ Use code-editor skill to implement ProfileEditor component
│ - Create src/components/ProfileEditor.tsx
│ - Update src/App.tsx imports
│ - Add form validation dependencies
│ - Checkpoint before/after modifications
│
├─ Use code-editor skill to implement backend endpoint
│ - Create backend/src/handlers/profile.rs
│ - Update Cargo.toml dependencies
│ - Validate Rust syntax
│
└─ Validate with TDD validator (tests must pass)
Integration Workflow
- Orchestrator delegates → Code editor generates code
- Code editor validates → Syntax + dependencies
- TDD validator tests → Run tests, check coverage
- Quality gate validates → Security, performance, accessibility
- Completion gate validates → All deliverables present
Error Recovery
Automatic Recovery
- Syntax errors → Auto-fix common issues (brackets, imports)
- Missing imports → Add required imports
- Circular deps → Restructure imports
- Build failures → Rollback to checkpoint
Manual Recovery
# On failure, restore previous state
if not result["success"]:
restored = await editor.checkpoint_manager.restore_checkpoint(
result["checkpoint_id"]
)
print(f"Restored {len(restored)} files to last checkpoint")
Common Auto-Fixes
- Bracket Matching - Fix unclosed brackets
- Import Resolution - Add missing import statements
- Dependency Updates - Auto-add to package.json/Cargo.toml
- Type Errors - Add missing type annotations (TypeScript)
Best Practices
DO ✅
- Create checkpoints before major changes
- Validate syntax before returning
- Use minimal file context (extract imports + relevant code + exports)
- Batch similar operations (all creates, then modifies, then deletes)
- Remove unused code automatically
- Test in isolated environment first
DON'T ❌
- Modify protected files (main.tsx, index.html, Cargo.toml [package] section)
- Skip dependency validation
- Ignore token budgets (max 100K per operation)
- Apply untested changes to production
- Forget error boundaries
- Use OPFS as primary storage (use FoundationDB)
T2-Specific Patterns
Frontend Feature Addition
await editor.process_edit_request(
feedback="""
Add analytics dashboard with:
- Dashboard.tsx component with charts
- Route at /dashboard
- Navigation link in Header.tsx
- Use recharts for visualization
- Use shadcn/ui for UI components
""",
files=existing_files,
package_json=package_json
)
Backend API Endpoint
await editor.process_edit_request(
feedback="""
Add PUT /api/v5/users/me/profile endpoint:
- Handler in backend/src/handlers/profile.rs
- JWT auth middleware
- FoundationDB session validation
- Return updated user data
""",
files=backend_files,
cargo_toml=cargo_toml
)
Full-Stack Feature
# Combine frontend + backend in single request
await editor.process_edit_request(
feedback="""
Implement user profile editing:
Frontend:
- ProfileEditor.tsx component with form validation
- Update App.tsx routing
- Add @hookform/resolvers dependency
Backend:
- PUT /api/v5/users/me/profile in profile.rs
- Validate user owns session
- Update FDB user record
- Add validator crate dependency
""",
files=frontend_files + backend_files,
package_json=package_json,
cargo_toml=cargo_toml
)
Performance Metrics
Expected Success Rates
- Syntax validation: >95% accuracy
- Dependency resolution: >90% accuracy
- Rollback success: >99% reliability
- Token efficiency: 30-40% reduction vs manual
Quality Thresholds
- Validation score >= 0.5 → PASS
- Validation score 0.5-0.8 → WARNING (manual review)
- Validation score < 0.5 → FAIL (automatic rollback)
Monitoring
# Track metrics
editor.metrics["successes"][-1] # Last successful operation
editor.metrics["failures"] # All failures
# Performance tracking
{
"avg_execution_time": 15.3, # seconds
"success_rate": 0.94, # 94% success
"avg_tokens_per_file": 2500,
"rollback_rate": 0.06 # 6% require rollback
}
Troubleshooting
| Issue | Solution |
|---|---|
| High token usage | Reduce file context, batch operations |
| Validation failures | Check syntax validators installed (npm, cargo) |
| Slow execution | Enable parallel processing for independent files |
| Missing dependencies | Ensure package managers installed (npm, cargo) |
| Rollback loops | Review error patterns, adjust auto-fix rules |
| Checkpoint corruption | Verify .coditect/checkpoints/ permissions |
Alerts
- Token usage > 10K per file → Review scope
- Rollback rate > 20% → Check validation
- Execution time > 60s → Consider parallelization
- Validation score < 0.5 → Auto-rollback triggered
Advanced Features
1. Incremental Context Extraction
MAX_CONTEXT_PER_FILE = 5000
def extract_minimal_context(file: File) -> str:
"""Extract only necessary code sections"""
sections = [
get_imports(file), # Import statements
get_relevant_code(file), # Relevant functions/components
get_exports(file) # Export statements
]
return '\n'.join(sections)
2. Batch Operations
def batch_similar_changes(tasks: List[Task]) -> List[BatchOperation]:
"""Group similar modifications"""
batches = defaultdict(list)
for task in tasks:
operation_type = classify_operation(task)
batches[operation_type].append(task)
return [
BatchOperation(type=op_type, tasks=tasks)
for op_type, tasks in batches.items()
]
3. Parallel File Processing
# Process independent files in parallel
async with asyncio.TaskGroup() as tg:
for file in files:
tg.create_task(process_file(file))
Reference Materials
- Quickstart Guide: See
quickstart.mdfor quick start examples and API reference - Configuration Guide: See
config.mdfor agent configuration details - Implementation: See
implementation.pyfor Python source code (906 lines)
Multi-Context Window Support
This skill supports long-running code editing tasks across multiple context windows using Claude 4.5's enhanced state management capabilities.
State Tracking
Checkpoint State (JSON):
{
"checkpoint_id": "ckpt_20251129_143022",
"files_modified": [
{"path": "src/App.tsx", "operations": ["modify"], "checksum": "abc123"},
{"path": "backend/src/handlers/users.rs", "operations": ["create"], "checksum": "def456"}
],
"dependencies_added": ["react-hook-form", "validator"],
"validation_status": "passed",
"token_usage": 12500,
"created_at": "2025-11-29T14:30:22Z"
}
Progress Notes (Markdown):
# Code Editor Progress - 2025-11-29
## Completed
- Created ProfileEditor.tsx (150 lines)
- Added PUT /api/v5/users/me/profile endpoint
- Updated package.json with form validation deps
## In Progress
- Validating TypeScript syntax (1 error remaining)
- Running integration tests
## Next Actions
- Fix type error in ProfileEditor.tsx:45
- Complete validation phase
- Apply changes if validation passes
Session Recovery
When starting a fresh context window after code editing work:
- Load Checkpoint State: Read
.coditect/checkpoints/latest.json - Review Progress Notes: Check
code-editor-progress.mdfor narrative context - Verify File State: Use Read tool to confirm file modifications
- Check Git Status:
git statusto see uncommitted changes - Resume Validation: Re-run syntax validators on modified files
Recovery Commands:
# 1. Check latest checkpoint
cat .coditect/checkpoints/latest.json | jq '.files_modified'
# 2. Review progress
tail -20 code-editor-progress.md
# 3. Verify git state
git status --short
# 4. Resume validation
python -m py_compile modified_file.py # Python
tsc --noEmit modified_file.ts # TypeScript
cargo check # Rust
State Management Best Practices
Checkpoint Files (JSON Schema):
- Store in
.coditect/checkpoints/code-editor-{timestamp}.json - Include file checksums (SHA-256) for integrity validation
- Track dependencies added/removed for rollback
- Record validation results for quick resume
Progress Tracking (Markdown Narrative):
- Maintain
code-editor-progress.mdwith timestamp entries - Document decision rationale (why certain changes made)
- Note validation failures and fixes attempted
- List next steps for context continuity
Git Integration:
- Create checkpoint before major modifications
- Commit frequently with descriptive messages
- Use conventional commit format for consistency
- Tag checkpoints:
git tag checkpoint-code-editor-{timestamp}
Progress Checkpoints
Natural Breaking Points:
- After file analysis phase (before modifications)
- After each file successfully modified and validated
- After dependency resolution complete
- Before final quality validation
- After rollback (if needed)
Checkpoint Creation Pattern:
# Automatic checkpoint creation at critical phases
if files_modified_count > 3 or token_usage > 10000:
create_checkpoint({
"files": modified_files,
"deps": dependencies_added,
"validation": validation_results,
"tokens": current_token_usage
})
Example: Multi-Context Feature Implementation
Context Window 1: Analysis & First Files
{
"checkpoint_id": "ckpt_feature_start",
"phase": "analysis_complete",
"files_analyzed": 5,
"files_modified": 2,
"next_action": "Modify remaining 3 files",
"token_usage": 8500
}
Context Window 2: Remaining Files & Validation
# Resume from checkpoint
cat .coditect/checkpoints/ckpt_feature_start.json
# Continue modifications
# (Context restored in 2 minutes vs 15 minutes from scratch)
# Complete validation
{
"checkpoint_id": "ckpt_feature_complete",
"phase": "validation_complete",
"all_tests_passed": true,
"token_usage": 6200
}
Token Savings: 8500 (first context) + 6200 (second context) = 14700 total vs. 25000 without checkpoint = 41% reduction
See docs/CLAUDE-4.5-BEST-PRACTICES.md for complete multi-context patterns.
Success Output
When this skill is successfully applied, you should see:
✅ SKILL COMPLETE: code-editor
Completed:
- [x] Multi-file modifications applied (3-10 files)
- [x] Syntax validation passed for all languages
- [x] Dependencies resolved and updated (package.json/Cargo.toml)
- [x] Checkpoint created before modifications
- [x] Integration tests passed (or flagged for review)
- [x] Token budget respected (<100K for operation)
Outputs:
- Modified source files with validated syntax
- Updated dependency manifests (package.json, Cargo.toml)
- Checkpoint file (.coditect/checkpoints/ckpt_TIMESTAMP.json)
- Validation report (syntax errors, circular deps, unused imports)
- Quality score (0.0-1.0, threshold 0.5 for auto-commit)
Example Output:
Operation: "Add user profile editing"
- Files Modified: 5 (ProfileEditor.tsx, profile.rs, App.tsx, package.json, Cargo.toml)
- Syntax Validation: ✅ PASS (TypeScript, Rust)
- Dependencies Added: react-hook-form@7.48.0, validator@0.13.11
- Checkpoint ID: ckpt_20251204_143022
- Quality Score: 0.87 (PASS - auto-commit safe)
- Token Usage: 25,400 (within 100K budget)
Completion Checklist
Before marking this skill as complete, verify:
- All file modifications applied without conflicts
- Syntax validation passed for modified files (Python/TS/TSX/Rust)
- Dependencies extracted and added to manifests
- No circular dependencies detected
- Unused imports removed automatically
- Checkpoint created and validated (.coditect/checkpoints/)
- Quality score ≥0.5 (or manual review flagged if <0.5)
- Token usage <100K for operation
- Integration tests run (or planned if not automated)
- Rollback tested (can restore from checkpoint)
Failure Indicators
This skill has FAILED if:
- ❌ Syntax errors in modified files (Python AST parse failed, TSC errors, cargo check failed)
- ❌ Missing imports not auto-resolved
- ❌ Circular dependency introduced (A imports B imports A)
- ❌ Dependencies not added to package.json/Cargo.toml
- ❌ No checkpoint created (can't rollback)
- ❌ Quality score <0.5 without manual review flag
- ❌ Token usage >100K (exceeded budget)
- ❌ Protected files modified (main.tsx, index.html, [package] section of Cargo.toml)
- ❌ Integration tests failing without investigation
When NOT to Use
Do NOT use this skill when:
- Single file changes - Use Edit tool directly, code-editor adds unnecessary overhead
- Simple text replacements - Regex find-replace is faster
- Documentation-only updates - Markdown editing doesn't need syntax validation
- Quick bug fixes (1-2 files) - Manual editing is faster for small changes
- Non-code files - JSON/YAML/config files don't benefit from code-editor
- Read-only operations - Analyzing code without modifications
- Binary files - Images, fonts, compiled assets
Use alternatives:
- Single file → Edit tool
- Batch text changes → sed/awk or Edit with regex
- Documentation → Direct Write tool
- Config changes → Edit tool with validation command after
- Analysis only → Read tool + grep
Anti-Patterns (Avoid)
| Anti-Pattern | Problem | Solution |
|---|---|---|
| No checkpoint before major changes | Can't rollback if validation fails | Always create checkpoint first |
| Skipping syntax validation | Broken code committed | Run validators before returning (ast.parse, tsc, cargo check) |
| Ignoring token budget | Operation costs $5+ in tokens | Use minimal context extraction, batch operations |
| Modifying protected files | Breaking changes to core infrastructure | Exclude main.tsx, index.html, package section of Cargo.toml |
| No dependency validation | Missing packages break builds | Extract imports, resolve versions, update manifests |
| Wildcard imports | import * hides dependencies | Use explicit imports for clarity |
| No error boundaries | One file failure breaks entire operation | Validate incrementally, isolate failures |
| OPFS for persistence | Browser storage unreliable | Use FoundationDB or cloud storage for checkpoints |
| No quality gate | Low-quality code auto-committed | Require quality score ≥0.5 or manual review |
Principles
This skill embodies CODITECT automation principles:
#1 Recycle → Extend → Re-Use → Create
- Recycle checkpoints - Restore previous state when validation fails
- Extend existing files - Modify incrementally rather than rewriting
- Re-use validation logic - Python AST, TypeScript tsc, Rust cargo check
- Create only when needed - Don't generate boilerplate unnecessarily
#2 First Principles Thinking
- Understand dependencies - Imports are contracts, must be resolved
- Syntax validation first - Catch errors before commit, not in CI
- Token efficiency - Extract minimal context (imports + relevant code + exports)
#5 Eliminate Ambiguity
- Explicit file paths - Absolute paths in checkpoints for clarity
- Clear validation results - PASS/FAIL with specific error messages
- Quality score threshold - ≥0.5 is unambiguous gate for auto-commit
#6 Clear, Understandable, Explainable
- Checkpoint manifest - JSON with files, checksums, dependencies
- Validation reports - Show exactly which files/lines failed
- Quality breakdown - Explain why score is 0.87 (syntax=100%, deps=90%, etc.)
#8 No Assumptions
- Test rollback - Verify checkpoint restore works before relying on it
- Validate versions - Don't assume latest dependency versions are compatible
- Check file existence - Verify target files exist before modifying
#10 Automation First
- Auto-extract imports - No manual dependency tracking
- Auto-fix common errors - Bracket matching, missing imports
- Auto-checkpoint - Triggered by file count or token usage thresholds
Version History
- v2.0 - Multi-agent orchestration, checkpoint system, T2 integration
- v1.5 - Added TypeScript/TSX validation
- v1.0 - Basic code editing with rollback
License
MIT - Use freely in production with attribution
Status: Production-ready ✅
Token Efficiency: 30-40% reduction for multi-file features
Integration: T2 Orchestrator Phase 3 (Implementation)
Checkpoint Storage: .coditect/checkpoints/ (session-aware, persistent)