Logotipo de Safe Refactoring

Safe Refactoring

Comunidad
UnpaidAttention
safe-refactoring

Execute behavior-preserving code restructuring — establish a test safety net first, apply the smallest mechanical transformations in sequence, verify after each, and refuse refactors that lack the coverage to be done safely. Trigger this when the user asks to "refactor", "clean up", "simplify", "restructure", "extract", or "rename" existing working code, or when you initiate a structural improvement yourself. Do NOT trigger for changes meant to alter behavior (that's a feature/fix — use task-planning), or for diagnosing why code is broken (use debugging-methodology) — a refactor by definition starts from green.

Descripción general

EditorUnpaidAttention
Repositoriofable5-methodology
Nombre de la habilidadsafe-refactoring
Estrellas
94
Forks
21
Archivos incluidos
Solo instrucciones
Enlaces
  • Instrucciones en Markdown

    Un archivo SKILL.md que el modelo carga cuando lo necesita, de modo que solo consume tokens cuando la petición encaja con la habilidad.

  • Funciona con cualquier LLM

    Las habilidades de IA están en Markdown, no en código específico de un proveedor, por lo que funcionan con GPT, Claude, Gemini, Grok o un modelo local.

  • Todo en las instrucciones

    Todo lo que necesita el modelo está en las instrucciones: no hay archivos adicionales que sincronizar.

  • Código abierto

    Publicada por UnpaidAttention en GitHub. Revisa el contenido original antes de instalarla.

Instalación

Instala la habilidad de IA Safe Refactoring en TypingMind para usarla con cualquier LLM, o añádela a otro agente que lea SKILL.md.

1

Instalar en TypingMind

TypingMind instala una habilidad directamente desde su carpeta de GitHub: lee SKILL.md, empaqueta los archivos de recursos y guarda el resultado localmente.

  1. Abre la aplicación y ve a Plugins → Habilidades.
  2. Elige «Instalar desde GitHub».
  3. Pega la URL de la carpeta de la habilidad que se muestra a continuación y confirma.
    https://github.com/UnpaidAttention/fable5-methodology/tree/main/skills/safe-refactoring
  4. Activa la habilidad en cada chat en el que quieras tenerla disponible.
Plugins → Habilidades → Añadir habilidad → URL de GitHub; después, pega la URL de la carpeta y pulsa Continuar.
2

Instalar en otro agente

Cualquier agente que lea el formato Agent Skills puede usar esta habilidad: copia la carpeta en el directorio de habilidades de ese agente.

Claude Code — .claude/skills
git clone --depth 1 https://github.com/UnpaidAttention/fable5-methodology.git /tmp/fable5-methodology
mkdir -p .claude/skills
cp -r /tmp/fable5-methodology/skills/safe-refactoring .claude/skills/safe-refactoring
Reinicia Claude Code después de copiarla para que detecte la nueva habilidad.

Úsala en TypingMind

Activa Safe Refactoring en cualquier chat de TypingMind y el modelo se encargará del resto. Su nombre y descripción se incluyen en el prompt del sistema y, en cuanto una petición encaja con la habilidad, el modelo carga las instrucciones completas por sí solo. No tienes que invocarla manualmente y no consume tokens hasta que se utiliza.

El modelo carga Safe Refactoring automáticamente en cuanto una petición es relevante para esa habilidad.

Funciona con cualquier modelo de IA

Las habilidades de IA son instrucciones en Markdown, no código específico de un proveedor, por lo que Safe Refactoring no está vinculada al modelo para el que se creó. Instálala una sola vez en TypingMind y úsala con GPT-5, Claude, Gemini, Grok, DeepSeek, Mistral, Llama o un modelo local que ejecutes tú, todo con tus propias claves API.

  • Se carga solo cuando se necesita

    El prompt del sistema solo incluye el nombre y la descripción. Las instrucciones se cargan con la primera petición que encaja con la habilidad, por lo que una habilidad que no se usa no supone ningún coste.

  • Cambia de modelo durante el chat

    Como la habilidad contiene instrucciones y no código, cambiar de modelo no impide que funcione: el nuevo modelo lee el mismo archivo SKILL.md.

Instrucciones de la habilidad

Este es el contenido de SKILL.md que carga el modelo. Léelo antes de instalar la habilidad: contiene instrucciones que tu modelo seguirá.

Safe Refactoring

A refactor changes structure and preserves behavior — both halves are the definition. Without a way to PROVE behavior is preserved, you are not refactoring; you are rewriting and hoping.

Step 0: Define the behavior contract

State in one or two lines what must be true before and after: "all existing tests pass; the public API of billing/ is unchanged; the CLI output is byte-identical." This contract is what "safe" means for this refactor. If any behavior IS allowed to change, that part is not a refactor — split it out (Step 4).

Step 1: Establish the safety net BEFORE touching anything

  1. Run the existing tests over the affected code. Record the baseline (green, or which failures are pre-existing).
  2. Assess whether the tests actually cover the code you'll restructure: run coverage over the affected files, or inspect — do the tests exercise the branches you're about to move?
  3. Insufficient coverage → write characterization tests first. These capture what the code DOES today (not what it should do): feed representative inputs, assert the actual current outputs. For messy code, golden-master style works: capture today's output for a corpus of inputs into fixture files, assert future output matches byte-for-byte.
  4. Characterization tests are committed/verified BEFORE the first structural edit — they are the net; a net installed after the fall is decoration.

Step 2: The refuse/defer rule

Refuse (or defer pending tests) when ALL of: the code has no meaningful coverage, AND its behavior can't be cheaply characterized (nondeterminism, heavy I/O entanglement, no way to run it), AND the restructuring is more than mechanical. Say exactly that:

"This refactor isn't safe yet: dispatch() has zero coverage and side-effects I can't capture in a harness. I can (a) write characterization tests first (~N tests), or (b) limit to mechanical renames only. Which?"

Refusing a risky refactor is a correct deliverable. A "successful" blind rewrite is a defect with a delay on it.

Step 3: Smallest transformations, verified individually

  1. Decompose into named mechanical steps — rename; extract function/module; inline; move; change signature (with all call sites); replace conditional with early return. One step at a time.
  2. After EACH step: run the affected tests (the verification-loop rhythm). Green → next step; red → the step itself is the suspect, fix or revert it before anything else.
  3. Prefer tool-assisted transformations (LSP rename, IDE extract) over hand edits — then grep for what tools miss: string references, docs, templates, reflection, serialized names, SQL, config keys.
  4. Order steps so the tree compiles between every pair — never a step that requires step N+1 to build.

Step 4: No mixed cargo

If you discover an actual bug mid-refactor: do NOT fix it inside the refactor. Note it, finish (or pause) the refactor to a verified state, then fix the bug as its own change with its own regression test. A diff that both moves code and changes behavior cannot be reviewed for either property. Same for improvements: new features never ride along in a refactor diff.

Step 5: Prove the contract

Full affected suite green; baseline failures unchanged; and check the contract from Step 0 directly (API surface diff, byte-compare the golden outputs). Review the diff explicitly asking one question per hunk: "could this hunk change behavior?" Any hunk answering "yes" that isn't a pure signature-propagation gets scrutiny.

Worked example

Task: "Clean up report.py — 600 lines, one god function."

  • Contract: CLI output byte-identical for all supported flags; tests stay green.
  • Safety net: only 2 tests exist, covering ~20%. Write a golden master: run the CLI over 8 representative fixture inputs (incl. empty file, unicode, flag combinations), save outputs to tests/golden/. Now every future step is checked against reality.
  • Steps: (1) extract parse_args → golden green; (2) extract load_rows → green; (3) extract render_table → RED: one golden diff — a .strip() was lost in the move; restore it, green (the net just paid for itself); (4) move helpers to report/lib.py → green; (5) found an actual bug (crash on zero rows) → NOTED in report, not fixed here.
  • Deliver: structure changed, goldens byte-identical, bug reported separately with a suggested regression test.

Done when

The behavior contract from Step 0 is verified by executed tests (including any characterization tests written first, not after); every transformation step ran green before the next began; the diff contains zero intentional behavior changes; and any bugs discovered are reported separately — not silently fixed in, and not silently left unmentioned.

Preguntas frecuentes

¿Qué hace la habilidad de IA Safe Refactoring?

Execute behavior-preserving code restructuring — establish a test safety net first, apply the smallest mechanical transformations in sequence, verify after each, and refuse refactors that lack the coverage to be done safely. Trigger this when the user asks to "refactor", "clean up", "simplify", "restructure", "extract", or "rename" existing working code, or when you initiate a structural improvement yourself. Do NOT trigger for changes meant to alter behavior (that's a feature/fix — use task-planning), or for diagnosing why code is broken (use debugging-methodology) — a refactor by definiti...

¿Por qué usar Safe Refactoring en TypingMind?

Porque la instalas una vez y la usas con cualquier modelo. Safe Refactoring está escrita en Markdown, no en código específico de un proveedor, por lo que la misma habilidad funciona con GPT-5, Claude, Gemini, Grok o un modelo local, y puedes cambiar de modelo en mitad del chat sin que deje de funcionar. TypingMind utiliza tus propias claves API, de modo que pagas directamente a los proveedores en lugar de pagar una suscripción por puesto, y tus habilidades y chats permanecen en tu propio almacenamiento.

¿Cómo instalo Safe Refactoring en TypingMind?

Abre Plugins → Habilidades → Instalar desde GitHub en TypingMind y pega https://github.com/UnpaidAttention/fable5-methodology/tree/main/skills/safe-refactoring. TypingMind lee el archivo SKILL.md de esa carpeta e instala su contenido como una habilidad que puedes activar en cada chat.

¿Qué modelos de IA pueden usar Safe Refactoring?

Cualquier modelo que conectes en TypingMind. Las habilidades de IA son instrucciones en Markdown, no código específico de un proveedor, por lo que GPT, Claude, Gemini, Grok y los modelos locales pueden cargar esta habilidad cuando una solicitud se corresponda con ella.

¿Con cuántos modelos de IA puedo usar Safe Refactoring?

Con tantos como quieras. Siempre que un modelo admita habilidades, puedes usar Safe Refactoring con él: GPT, Claude, Gemini, Grok, DeepSeek, Mistral, Llama y muchos más, todos en TypingMind con tus propias claves API.

¿Es gratuita la habilidad de IA Safe Refactoring?

UnpaidAttention la ha publicado en GitHub. Consulta el repositorio para conocer las condiciones de la licencia. Solo pagas a tu proveedor de IA por los tokens que utilizas.

¿Qué son las habilidades de IA?

Una habilidad de IA es un conjunto de instrucciones reutilizables que enseña a un modelo de IA a realizar una tarea concreta. Sigue el formato abierto Agent Skills: un archivo SKILL.md con un nombre y una descripción, además de los scripts, plantillas o archivos de referencia que pueda necesitar el modelo. El modelo solo lee las instrucciones cuando tu solicitud se corresponde con la habilidad, por lo que una habilidad instalada no supone ningún coste hasta que se utiliza.

¿En qué se diferencian las habilidades de IA de los plugins o los servidores MCP?

Un plugin o un servidor MCP proporciona al modelo nuevas herramientas que puede invocar: código que se ejecuta en algún lugar y devuelve un resultado. En cambio, una habilidad de IA aporta conocimientos y procedimientos al modelo: cómo abordar una tarea, qué pasos seguir y qué se considera un buen resultado. Las habilidades son instrucciones en Markdown, por lo que no necesitan servidor, clave API ni entorno de ejecución, y funcionan con cualquier modelo.

Ver el directorio

Crea ya tu propio espacio de trabajo con IA

Suscríbete a nuestro boletín para recibir avisos sobre nuevas funciones y próximos sorteos 👇