# Tdd Repair > Reparación dirigida por tests: dado un test que falla, lanza un 'claude -p' acotado (solo Read/Edit/Bash) que arregla el código sin tocar el test, con costo y capacidad limitados. Fuente: https://skillsagentes.com/skills/ruvnet/ruflo/tdd-repair Markdown: https://skillsagentes.com/skills/ruvnet/ruflo/tdd-repair.md Repositorio: https://github.com/ruvnet/ruflo Autor: ruvnet Licencia: MIT Actualizado: hace 2 meses Coste de contexto: 98 tok instalada, 1.6k tok al activarse, 1.6k tok con todos los archivos del bundle Bundle: 1 archivo, 6 KB Permisos que pide: bash ## Instalación Un skill son archivos markdown: los mismos archivos valen para cualquier agente y lo único que cambia es el directorio de destino, es decir la bandera `--agent`. Añade `-g` para instalarlo en todos los proyectos de la máquina. ```bash # Claude Code npx -y skills add ruvnet/ruflo --skill tdd-repair --agent claude-code # Cursor npx -y skills add ruvnet/ruflo --skill tdd-repair --agent cursor # Codex npx -y skills add ruvnet/ruflo --skill tdd-repair --agent codex # Gemini CLI npx -y skills add ruvnet/ruflo --skill tdd-repair --agent gemini # Windsurf npx -y skills add ruvnet/ruflo --skill tdd-repair --agent windsurf # Cline npx -y skills add ruvnet/ruflo --skill tdd-repair --agent cline ``` ## Qué hace - Lanza un 'claude -p' acotado (solo Read/Edit/Bash) para arreglar el código bajo prueba sin modificar el test que falla - Usa el resultado pass/fail del test como única señal de verificación, sin juez LLM aparte - Limita el costo con --max-budget-usd y reintenta hasta --max-attempts antes de rendirse - Devuelve un recibo estructurado con el resultado, intentos realizados y costo total ## Cuándo usarla - Hay un test fallando en CI de un commit reciente y se quiere una corrección verificada - En un flujo TDD local, después de escribir el test que falla primero - Un test que antes pasaba ahora falla y se quiere triar antes de abrir un issue ## Cuándo no - Todavía no existe un test que falle - Se necesita un cambio arquitectónico, no una corrección táctica - El código es de confianza dudosa (Bash puede tocar el filesystem) ## Qué la activa - "Repara el código para que pase este test que falla, con presupuesto de $5" - "Arregla la regresión en tests/auth.test.ts usando el modelo Haiku" ## Antes de instalar - Requiere la CLI de claude instalada y el flag --confirm; sin él solo devuelve un plan en modo dry-run. - Necesita en el PATH: node - runs shell commands ## Archivos - SKILL.md — 6 KB ## SKILL.md Reproducido tal cual desde ruvnet/ruflo bajo MIT. Esta sección es el documento original y está en inglés. Surfaces the **Test-Driven Repair** loop as a ruflo skill. Use when you have a failing test and want the source-under-test fixed automatically, with the test's pass/fail as the verification gate (no LLM-as-judge). ## When to use - Failing CI test from a recent commit — point this at the test file, get a verified fix (or a clear "couldn't repair within budget" receipt). - Local TDD workflow — write the failing test first (`tdd-workflow` skill), then run `tdd-repair` to drive the green. - Regression triage — a previously-green test went red; before opening an issue, spend ~$1 to see if the fix is trivial. ## When NOT to use - **No failing test exists.** Conformant mode (`--no-test-oracle`) is scoped for a follow-up ADR — needs MCTS over repro generation. For now, write a failing test first. - **Architectural changes.** This skill is for tactical "make red green" fixes. Cross-module refactors that incidentally break tests should be done by a human or a swarm. - **Untrusted code.** The headless `claude -p` runs with `--allowedTools Read,Edit,Bash` — no MCP, no network, no arbitrary file writes — but Bash can still touch the filesystem. Don't point this at code you wouldn't `git checkout .` after. ## Algorithm Implementation: [`scripts/tdd-repair/tdd-repair.mjs`](../../scripts/tdd-repair/tdd-repair.mjs). 1. **Pre-flight verify** — run the test command. If it already passes, exit 2 (`test-already-passes`). Repairing a green test is either a no-op or a `--test-command` typo. 2. **Spawn `claude -p`** with a focused prompt: - Failing test file path (read-only intent) - Test command (run only) - Hard constraint: do NOT modify the test - Hard constraint: do NOT add new dependencies 3. **`--allowedTools Read,Edit,Bash`** restricts capability. **`--max-budget-usd`** caps cost per attempt. **`--permission-mode acceptEdits`** auto-accepts file edits within the allowed set. 4. **Re-run the test** to verify. The test's exit code IS the fitness function — no separate sandbox / LLM-as-judge. 5. **If green:** emit `success: true` + per-attempt usage. **If red after `--max-attempts`:** emit `success: false` + receipts. Either way, the workspace is left as `claude -p` modified it (caller can `git diff` to review). ## Output shape ```json { "success": true, "data": { "repaired": true, "attemptsTaken": 1, "mode": "test-driven", "before": { "passed": false, "exitCode": 1 }, "after": { "passed": true, "exitCode": 0, "durationMs": 4321 }, "attempts": [ { "attempt": 1, "claude": { "ok": true, "durationMs": 38421, "usage": { "cost_usd": 0.0234 } }, "verify": { "passed": true } } ], "totalCostUsd": 0.0234, "budgetUsd": 5.0, "budgetExhausted": false, "shape": { "repo": "...", "test": "...", "testCommand": "...", "maxAttempts": 1, "model": "haiku" } } } ``` ## Exit codes | Code | Meaning | |---|---| | 0 | Test green after repair (success) | | 1 | Test still red after `--max-attempts` | | 2 | Config error (test file missing, test already passes, `--no-test-oracle` unsupported, etc.) | | 3 | Claude CLI exited non-zero (infrastructure failure) | | 99 | Reserved for safety tripwire (per ADR-153) | ## Safety posture | Layer | Mechanism | |---|---| | Cost cap | `--max-budget-usd` default $5, divided across `--max-attempts`. Hard ceiling — claude exits when reached. | | Capability cap | `--allowedTools Read,Edit,Bash` — no MCP, no network, no arbitrary writes. | | Scope cap | Prompt forbids modifying the test or adding dependencies. | | Confirmation gate | `--confirm` REQUIRED — without it, returns dry-run plan (mirrors `harness-evolve` / `harness-mint` convention). | | Hard timeout | 15 min total wall-clock; per-attempt budget of `timeoutMs / maxAttempts`. | | Pre-flight | Refuses to run if the test already passes (catches `--test-command` typos). | ## Inspiration Modeled on the **Test-Driven Repair** mode from [agent-harness-generator/packages/darwin-mode](https://github.com/ruvnet/agent-harness-generator/tree/main/packages/darwin-mode) ADR-175. Key design difference: instead of wrapping `metaharness-darwin evolve` (population-based search), we drive a single `claude -p` invocation. Rationale: - The test command IS the fitness function — no need for variant scoring - `claude -p` is already in our stack — no new optional dep - Bounded cost / capability are first-class flags - Resumable via `--session-id` if iteration is needed Conformant mode (no test, write own repro via MCTS) is deferred to a future ADR. ## Example ```bash # Smoke / dry-run (no --confirm yet) node plugins/ruflo-testgen/scripts/tdd-repair/tdd-repair.mjs \ --repo /path/to/myrepo \ --test tests/auth.test.ts \ --test-command "npx vitest run tests/auth.test.ts" # Actually repair (Haiku tier, $5 budget, 1 attempt) node plugins/ruflo-testgen/scripts/tdd-repair/tdd-repair.mjs \ --repo /path/to/myrepo \ --test tests/auth.test.ts \ --test-command "npx vitest run tests/auth.test.ts" \ --confirm # Bigger model + more attempts for harder bugs node plugins/ruflo-testgen/scripts/tdd-repair/tdd-repair.mjs \ --repo . --test tests/regression-2456.test.ts \ --test-command "npm test -- tests/regression-2456.test.ts" \ --model sonnet --max-attempts 3 --budget 15.00 \ --confirm ``` ## Cost ladder | Tier | Model | Per-attempt typical | Use when | |---|---|---:|---| | 1 | Haiku | $0.02 – $0.20 | First try — most "make red green" bugs are tactical | | 2 | Sonnet | $0.30 – $2.00 | Haiku failed, or the bug has multi-file scope | | 3 | Opus | $1.50 – $8.00 | Sonnet failed — architectural reasoning required (rarely worth it for a single failing test) | ## Dónde encaja - Categoría: [Testing y QA](https://skillsagentes.com/categorias/testing-qa.md) — Flujos de testing unitario, de integración y end-to-end. - Creador: [ruvnet](https://skillsagentes.com/creators/ruvnet.md) — 275 skills en el directorio - [Todas las skills](https://skillsagentes.com/skills.md) - [Ranking de instalaciones](https://skillsagentes.com/ranking.md) ## Otras skills del mismo repositorio - [Harness Gepa](https://skillsagentes.com/skills/ruvnet/ruflo/harness-gepa.md): Inspecciona y audita genomas GEPA: carga y valida un genoma, renderiza el system prompt que compila, o clasifica los modos de fallo de una transcripción de ejecución. - [Deepseek Reason](https://skillsagentes.com/skills/ruvnet/ruflo/deepseek-reason.md): Completion en modo razonamiento contra deepseek-reasoner (R1) de DeepSeek. Devuelve el chain-of-thought por separado de la respuesta final. Lee DEEPSEEK_API_KEY y degrada si falta o la API no responde. - [Deepseek Chat](https://skillsagentes.com/skills/ruvnet/ruflo/deepseek-chat.md): Completion de un solo turno contra el modelo deepseek-chat de DeepSeek vía /v1/chat/completions. Lee DEEPSEEK_API_KEY y degrada con status:degraded si falta o la API no responde. Para tareas sin razonamiento. - [Adr Index](https://skillsagentes.com/skills/ruvnet/ruflo/adr-index.md): Construye o reconstruye el índice de ADRs y su grafo de dependencias ejecutando scripts/import.mjs, en vez de cientos de llamadas MCP. - [Agntcy Status](https://skillsagentes.com/skills/ruvnet/ruflo/agntcy-status.md): Muestra el estado de la integración AGNTCY/SLIM/CASA: si los paquetes están instalados, qué transporte está activo y si el enforcement de CASA está habilitado. --- Skills Agentes · [Índice de páginas en markdown](https://skillsagentes.com/sitemap.md) · [Inicio](https://skillsagentes.com/index.md)