Files
mhattingpete 71429f72e5 feat: Add Anthropic code execution pattern - 90%+ token savings (#15)
* feat: Add Anthropic code execution pattern - 90%+ token savings

Implements the Anthropic code execution pattern for massive token efficiency.
Instead of loading code through context, Claude executes Python locally with
API access - achieving 90-99% token reduction for bulk operations.

## Core Infrastructure (execution-runtime/)

### API Library (importable in execution)
- api/filesystem.py: File operations (copy, paste, search, batch)
- api/code_analysis.py: AST-based analysis (returns metadata, not source)
- api/code_transform.py: Refactoring operations
- api/git_operations.py: Git command wrappers

### Security
- security/sandbox.py: RestrictedPython execution environment
- security/pii_detector.py: Auto-mask 15+ types of secrets/PII

### MCP Server (mcp_server.py)
- execute_python: Run Python with API access
- save_reusable_skill: Save transformation functions
- create_refactoring_session: Stateful operations
- save_session_state: Checkpoint progress
- list_available_apis: API documentation

### Setup & Docs
- setup.sh: One-command installation
- pyproject.toml: Dependencies (FastMCP, RestrictedPython)
- .env.example: Configuration template
- README.md: Comprehensive documentation

## New Skills

### code-execution skill
- Teaches agents when/how to use execution mode
- 3 example scripts showing token savings
- Comprehensive usage patterns

### Enhanced existing skills
- code-transfer: Auto-uses execution for 10+ operations
- code-refactor: Auto-switches for bulk operations

## New Commands

### /pr command
- Quick access to git-pushing skill
- Creates PRs with comprehensive summaries

## Token Savings

| Operation | Files | Traditional | Execution | Savings |
|-----------|-------|-------------|-----------|---------|
| Rename    | 10    | 5K tokens   | 500       | 90%     |
| Refactor  | 50    | 25K tokens  | 600       | 97.6%   |
| Audit     | 100   | 150K tokens | 1K        | 99.3%   |

## Security Features

✅ Sandboxed execution (RestrictedPython)
✅ Resource limits (30s timeout, 256MB memory)
✅ Restricted imports (whitelist only)
✅ Automatic PII/secret masking
✅ Directory access restrictions

## Installation

Users run: ~/.claude/plugins/execution-runtime/setup.sh

Skills automatically activate execution mode for bulk operations (10+ files).

Reference: https://www.anthropic.com/engineering/code-execution-with-mcp

* refactor(git-pushing): enforce smart_commit.sh script usage

Make the smart_commit.sh script mandatory for all git-pushing operations.
Removes manual git command fallback to ensure consistent behavior.

Changes:
- Updated workflow to always use the script
- Removed manual git command instructions
- Simplified examples to show script usage only
- Added clear 'IMPORTANT' notice about script requirement

Benefits:
- Consistent commit message format
- Automatic Claude Code footer
- Better error handling
- Simpler skill instructions for LLM

* refactor: make skills more concise for LLM consumption

Dramatically reduced skill file lengths to be more LLM-friendly:
- code-execution: 541 → 101 lines (81% reduction)
- git-pushing: simplified workflow instructions

Skills are for LLMs to read, not humans. Keeping them concise:
- Focuses on essential information only
- Removes verbose explanations
- Keeps concrete examples
- Clear do's and don'ts

Benefits:
- Faster LLM processing
- Lower token usage for skill loading
- Clearer decision-making for activation

* refactor: drastically reduce visual documentation skill sizes

Reduced skill files by 80-92% for LLM efficiency:
- architecture-diagram-creator: 992 → 83 lines (92%)
- timeline-creator: 601 → 67 lines (89%)
- technical-doc-creator: 525 → 87 lines (83%)
- dashboard-creator: 406 → 79 lines (81%)
- flowchart-creator: 373 → 78 lines (79%)

Total reduction: 2,897 → 394 lines (86% reduction)

Skills are for LLMs, not humans. Kept only:
- Essential activation criteria
- HTML structure templates
- Key component patterns
- Concise workflow steps

Benefits:
- Faster skill loading (86% less tokens)
- Clearer decision-making
- Same functionality, better performance

* refactor: reduce all skill sizes for LLM efficiency (76% reduction)

Reduced all marketplace skills per user requirement for LLM consumption.

Code Operations: 393->84 lines (79%)
Productivity Skills: 821->580 lines (29%)
Engineering Workflow: 492->393 lines (20%)
Visual Documentation: 2897->394 lines (86%)

Total: 4603->1827 lines (76% reduction, -2776 lines)

Pattern: Keep only activation phrases, brief lists, minimal examples, essential workflow steps.
2025-11-10 14:41:28 +01:00

270 lines
6.3 KiB
Python

"""
Git Operations API
Simplified git command wrappers for execution environment.
"""
import subprocess
from pathlib import Path
from typing import Dict, List, Optional
def _run_git_command(args: List[str], cwd: Optional[str] = None) -> Dict[str, any]:
"""
Run git command and return result.
Args:
args: Git command arguments
cwd: Working directory
Returns:
Dict with stdout, stderr, returncode
"""
try:
result = subprocess.run(
['git'] + args,
cwd=cwd or Path.cwd(),
capture_output=True,
text=True,
timeout=30
)
return {
"status": "success" if result.returncode == 0 else "error",
"returncode": result.returncode,
"stdout": result.stdout.strip(),
"stderr": result.stderr.strip()
}
except subprocess.TimeoutExpired:
return {
"status": "error",
"error": "Git command timed out after 30 seconds"
}
except Exception as e:
return {
"status": "error",
"error": str(e)
}
def git_status(cwd: Optional[str] = None) -> Dict[str, any]:
"""
Get git status of repository.
Args:
cwd: Working directory (defaults to current directory)
Returns:
Dict with status information
"""
result = _run_git_command(['status', '--porcelain'], cwd=cwd)
if result["status"] == "success":
# Parse porcelain output
lines = result["stdout"].splitlines()
files = {
"modified": [],
"added": [],
"deleted": [],
"untracked": []
}
for line in lines:
if not line.strip():
continue
status = line[:2]
filepath = line[3:]
if status.strip() == 'M' or 'M' in status:
files["modified"].append(filepath)
elif status.strip() == 'A' or 'A' in status:
files["added"].append(filepath)
elif status.strip() == 'D' or 'D' in status:
files["deleted"].append(filepath)
elif status.strip() == '??':
files["untracked"].append(filepath)
result["files"] = files
result["has_changes"] = len(lines) > 0
return result
def git_add(files: List[str], cwd: Optional[str] = None) -> Dict[str, any]:
"""
Stage files for commit.
Args:
files: List of file paths to stage (or ['.'] for all)
cwd: Working directory
Returns:
Dict with status
"""
return _run_git_command(['add'] + files, cwd=cwd)
def git_commit(message: str, cwd: Optional[str] = None) -> Dict[str, any]:
"""
Create git commit.
Args:
message: Commit message
cwd: Working directory
Returns:
Dict with status and commit hash
"""
result = _run_git_command(['commit', '-m', message], cwd=cwd)
if result["status"] == "success":
# Extract commit hash from output
output = result["stdout"]
if output:
# Typically first line contains hash
first_line = output.splitlines()[0]
# Extract hash (usually in brackets or first word)
import re
match = re.search(r'([0-9a-f]{7,40})', first_line)
if match:
result["commit_hash"] = match.group(1)
return result
def git_push(
remote: str = "origin",
branch: Optional[str] = None,
cwd: Optional[str] = None
) -> Dict[str, any]:
"""
Push commits to remote.
Args:
remote: Remote name (default: origin)
branch: Branch name (defaults to current branch)
cwd: Working directory
Returns:
Dict with status
"""
args = ['push', remote]
if branch:
args.append(branch)
return _run_git_command(args, cwd=cwd)
def create_branch(
branch_name: str,
checkout: bool = True,
cwd: Optional[str] = None
) -> Dict[str, any]:
"""
Create new git branch.
Args:
branch_name: Name of new branch
checkout: Checkout the new branch immediately
cwd: Working directory
Returns:
Dict with status
"""
if checkout:
result = _run_git_command(['checkout', '-b', branch_name], cwd=cwd)
else:
result = _run_git_command(['branch', branch_name], cwd=cwd)
return result
def get_current_branch(cwd: Optional[str] = None) -> Dict[str, any]:
"""
Get current git branch name.
Args:
cwd: Working directory
Returns:
Dict with branch name
"""
result = _run_git_command(['branch', '--show-current'], cwd=cwd)
if result["status"] == "success":
result["branch"] = result["stdout"]
return result
def git_diff(
staged: bool = False,
files: Optional[List[str]] = None,
cwd: Optional[str] = None
) -> Dict[str, any]:
"""
Get git diff.
Args:
staged: Show staged changes (--cached)
files: Specific files to diff
cwd: Working directory
Returns:
Dict with diff output
"""
args = ['diff']
if staged:
args.append('--cached')
if files:
args.extend(files)
result = _run_git_command(args, cwd=cwd)
if result["status"] == "success":
result["diff"] = result["stdout"]
result["has_changes"] = len(result["stdout"]) > 0
return result
def git_log(
max_count: int = 10,
oneline: bool = True,
cwd: Optional[str] = None
) -> Dict[str, any]:
"""
Get git commit history.
Args:
max_count: Maximum number of commits to return
oneline: Use oneline format
cwd: Working directory
Returns:
Dict with commit history
"""
args = ['log', f'--max-count={max_count}']
if oneline:
args.append('--oneline')
result = _run_git_command(args, cwd=cwd)
if result["status"] == "success":
commits = []
for line in result["stdout"].splitlines():
if line.strip():
# Parse oneline format: hash message
parts = line.split(' ', 1)
if len(parts) == 2:
commits.append({
"hash": parts[0],
"message": parts[1]
})
result["commits"] = commits
return result