Logo de Safe Refactoring

Safe Refactoring

Comunidade
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.

Visão geral

Publicado porUnpaidAttention
Repositóriofable5-methodology
Nome da habilidadesafe-refactoring
Estrelas
94
Forks
21
Arquivos incluídos
Somente instruções
Links
  • Instruções em Markdown

    Um arquivo SKILL.md que o modelo carrega sob demanda, consumindo tokens apenas quando uma solicitação é realmente relevante para a habilidade.

  • Funciona com qualquer LLM

    As habilidades de IA são escritas em Markdown simples, não em código específico de um provedor. Por isso, funcionam com GPT, Claude, Gemini, Grok ou um modelo local.

  • Sem arquivos extras

    Tudo de que o modelo precisa está nas instruções — sem arquivos extras para sincronizar.

  • Código aberto

    Publicada por UnpaidAttention no GitHub. Leia os arquivos da habilidade antes de instalá-la.

Instalação

Instale a habilidade de IA Safe Refactoring no TypingMind para usá-la com qualquer LLM ou adicione-a a outro agente que leia SKILL.md.

1

Instalar no TypingMind

O TypingMind instala uma habilidade diretamente da pasta dela no GitHub — lê o arquivo SKILL.md, reúne os arquivos de recursos em um pacote e armazena o resultado localmente.

  1. Abra o app e vá para Plugins → Habilidades.
  2. Escolha "Instalar do GitHub".
  3. Cole a URL abaixo, que aponta para a pasta da habilidade, e confirme.
    https://github.com/UnpaidAttention/fable5-methodology/tree/main/skills/safe-refactoring
  4. Ative a habilidade em cada chat em que quiser disponibilizá-la.
Plugins → Habilidades → Adicionar habilidade → Via URL do GitHub. Depois, cole a URL da pasta e pressione Continuar.
2

Instalar em outro agente

Qualquer agente que leia o formato Agent Skills pode usar esta habilidade — copie a pasta para o diretório de habilidades desse 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
Reinicie Claude Code após copiar para que a nova habilidade seja reconhecida.

Use no TypingMind

Ative Safe Refactoring em qualquer chat do TypingMind e o modelo cuida do resto. O nome e a descrição da habilidade ficam no prompt do sistema e, assim que uma solicitação relevante aparece, o modelo carrega as instruções completas automaticamente — sem precisar de acionamento manual e sem consumir tokens até que ela seja realmente usada.

O modelo carrega Safe Refactoring automaticamente assim que uma solicitação é relevante para essa habilidade.

Funciona com qualquer modelo de IA

Habilidades de IA são instruções em Markdown simples, não código específico de um provedor. Por isso, Safe Refactoring não fica vinculada ao modelo para o qual foi criada. Instale-a uma vez no TypingMind e use-a com GPT-5, Claude, Gemini, Grok, DeepSeek, Mistral, Llama ou um modelo local executado por conta própria — tudo com suas próprias chaves de API.

  • Carregada apenas quando necessário

    O prompt do sistema contém apenas o nome e a descrição. As instruções são buscadas na primeira solicitação relevante, então uma habilidade sem uso não gera custo.

  • Troque de modelo durante a conversa

    Como a habilidade é composta de instruções, não de código, trocar de modelo não afeta seu funcionamento — o próximo modelo lê o mesmo arquivo SKILL.md.

Instruções da habilidade

Este é o conteúdo de SKILL.md que o modelo carrega. Leia antes de instalar — uma habilidade é um conjunto de instruções que seu 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.

Perguntas frequentes

O que a habilidade de IA Safe Refactoring faz?

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 que usar Safe Refactoring no TypingMind?

Porque basta instalar uma vez para usar com qualquer modelo. A habilidade Safe Refactoring é escrita em Markdown simples, e não em código específico de um provedor, então a mesma habilidade funciona com GPT-5, Claude, Gemini, Grok ou um modelo local — e é possível trocar de modelo no meio do chat sem que ela deixe de funcionar. No TypingMind, você usa suas próprias chaves de API e paga diretamente aos provedores, em vez de pagar uma assinatura por licença de usuário. Suas habilidades e chats permanecem no seu próprio armazenamento.

Como instalar Safe Refactoring no TypingMind?

Abra Plugins → Habilidades → Instalar do GitHub no TypingMind e cole https://github.com/UnpaidAttention/fable5-methodology/tree/main/skills/safe-refactoring. O TypingMind lê o arquivo SKILL.md e instala a habilidade para que possa ser ativada em cada chat.

Quais modelos de IA podem usar Safe Refactoring?

Qualquer modelo conectado no TypingMind. As habilidades de IA são instruções em Markdown simples, e não código específico de um provedor. Assim, GPT, Claude, Gemini, Grok e modelos locais podem carregar esta habilidade quando uma solicitação corresponder a ela.

Quantos modelos de IA posso usar com Safe Refactoring?

Quantos quiser. Desde que o modelo ofereça suporte a habilidades, é possível usar Safe Refactoring com ele — GPT, Claude, Gemini, Grok, DeepSeek, Mistral, Llama e outros — tudo no TypingMind com suas próprias chaves de API.

A habilidade de IA Safe Refactoring é gratuita?

A habilidade é publicada no GitHub por UnpaidAttention. Consulte os termos de licenciamento no repositório. O pagamento é feito apenas ao seu provedor de IA pelos tokens usados.

O que são habilidades de IA?

Uma habilidade de IA é um conjunto reutilizável de instruções que ensina um modelo de IA a realizar uma tarefa específica. Ela segue o formato aberto Agent Skills: um arquivo SKILL.md com nome e descrição, além de scripts, templates ou arquivos de referência de que o modelo possa precisar. O modelo lê as instruções apenas quando sua solicitação corresponde à habilidade, então uma habilidade instalada não gera custos até ser usada.

Qual é a diferença entre habilidades de IA e plugins ou servidores MCP?

Um plugin ou servidor MCP oferece ao modelo novas ferramentas que ele pode acionar — código que é executado em algum lugar e retorna um resultado. Já uma habilidade de IA dá ao modelo o conhecimento e as orientações de que ele precisa: como abordar uma tarefa, quais etapas seguir e como deve ser um bom resultado. As habilidades são escritas em Markdown simples, por isso não precisam de servidor, chave de API nem ambiente de execução, e funcionam com qualquer modelo.

Ver lista completa

Crie seu próprio espaço de trabalho com IA agora

Inscreva-se na nossa newsletter para receber avisos sobre novos recursos e futuros sorteios 👇