<!--
Auto Error Fixer
Part of the Bles Software agent skills repository:
https://www.bles-software.com/claude-skills

Install for Claude Code:
  mkdir -p ~/.claude/skills/auto-error-fixer
  mv auto-error-fixer.md ~/.claude/skills/auto-error-fixer/SKILL.md

Install for Codex:
  mkdir -p ~/.codex/skills/auto-error-fixer
  mv auto-error-fixer.md ~/.codex/skills/auto-error-fixer/SKILL.md

For Gemini CLI and other agents, drop the body of this file into the
project instruction file the agent already reads.

Note: in production this skill also ships 1 helper file(s) alongside
SKILL.md. The procedure below is complete and self-contained; the helpers are
convenience scripts you can rebuild from the steps described here.
-->

---
name: auto-error-fixer
description: |
  Autonomous error detection and self-healing code evolution pattern.
  Monitors a log file continuously, detects fixable Python errors, deduplicates
  by signature hash, creates dev-tasks.json, and launches plan-to-code-async
  for autonomous fix execution with real-time Telegram progress updates.
  Use when adding self-healing capability to a Python service, bot, or daemon.
  Reusable pattern — works in any project that has a log file and uses plan-to-code-async.
allowed-tools: Read, Write, Bash, Glob, Grep
---

# Auto Error Fixer — Self-Healing Code Evolution

Adds autonomous error detection and fixing to any Python service.
When a fixable error appears in the log, the system creates a dev-tasks.json
and launches `plan-to-code-async` — which fixes the code and sends Telegram updates automatically.

## Quick Start

```bash
# 1. Copy the auto_evolver.py template to your project
cp ~/.claude/skills/auto-error-fixer/references/auto_evolver_template.py \
   your_project/services/darwin/auto_evolver.py

# 2. Initialize in your orchestrator/main loop
from services.darwin.auto_evolver import get_auto_evolver
auto_evolver = get_auto_evolver()
auto_evolver.initialize()   # seeks log to current end (ignores old errors)

# 3. Call scan() every ~90s from your background loop
await auto_evolver.scan()

# 4. That's it — errors trigger plan-to-code-async automatically
```

## How It Works

```
Log file (new lines every 90s)
    │
    ▼
_extract_errors()     ← groups ERROR + Traceback blocks
    │
    ▼
_is_fixable()         ← skip network/SSL/transient, keep code bugs
    │
    ▼
_signature() + cooldown check  ← deduplicate, prevent fix loops
    │
    ▼
Write dev-tasks.json  ← state/darwin/fixes/<timestamp>/
    │
    ▼
subprocess.Popen(launch.sh)   ← detached, start_new_session=True
    │
    ▼
plan-to-code-async    ← fixes code + sends Telegram progress updates
```

## Error Classification

**Skip (transient / external — not fixable):**
- `TelegramRetryAfter`, `Network is unreachable`, `Connection refused`
- `httpx`, `aiohttp`, `SSL`, `TimeoutError`, `Rate limit`, `Flood control`

**Fix (code bugs — autonomous repair):**
- `AttributeError`, `NameError`, `KeyError`, `TypeError`, `ValueError`
- `ImportError`, `SyntaxError`, `RuntimeError`, `UnboundLocalError`
- `IndexError`, `AssertionError`, `exit code -9`, `SIGKILL`, `NoneType object`

## Configuration Constants

```python
ERROR_COOLDOWN_S = 600   # 10 min between retries for same error signature
MAX_FIXES_PER_DAY = 5    # safety cap on autonomous fixes
SCAN_INTERVAL = 90       # seconds between log scans (set in caller loop)
```

## Integrating into an Orchestrator Loop

```python
# In your background _loop():
_auto_evolve_interval = 90
_last_auto_evolve_check = 0.0

while self._running:
    now = time.time()

    if self._auto_evolver and now - _last_auto_evolve_check >= _auto_evolve_interval:
        _last_auto_evolve_check = now
        try:
            await self._auto_evolver.scan()
        except Exception as e:
            logger.warning(f"auto_evolver scan failed: {e}")

    await asyncio.sleep(30)
```

## dev-tasks.json Format Written Per Fix

```json
{
  "project": "AutoEvolver Fix: AttributeError (20260222_143012)",
  "project_root": "/absolute/path/to/project",
  "test_framework": "pytest",
  "instructions": "Fix production bug. Read files before editing. Never break existing functionality.",
  "tasks": [{
    "id": "1-fix-attributeerror",
    "step": 1,
    "title": "Fix AttributeError in production",
    "description": "Error log + traceback + file hints + restart instructions",
    "files_to_modify": ["telegram_bot/bot.py"],
    "status": "pending",
    "attempts": 0,
    "errors": []
  }]
}
```

## Restart After Fix

The task description instructs Claude to restart the bot if core files were modified:

```
If bot.py or any core service file was modified, restart:
  /path/to/scripts/restart-bot.sh 'Auto-Evolver: <description>'
```

## State Files

| File | Purpose |
|------|---------|
| `state/darwin/fixes/<ts>/dev-tasks.json` | Per-fix task file |
| `state/darwin/auto_fixes.jsonl` | Audit log of all fix attempts |
| `state/darwin/fix_cooldowns.json` | Persisted error cooldowns |

## Reference Implementation

- Full source: See [references/auto_evolver_template.py](references/auto_evolver_template.py)
- Production instance: `~/teleclaudious/telegram_bot/services/darwin/auto_evolver.py`
- Orchestrator integration: `~/teleclaudious/telegram_bot/services/darwin/orchestrator.py`
