I refactored 1,400 lines with an AI agent: here's how I checked my tests weren't lying to me

Iniciado por joomlamz, 02 de Dezembro de 2026, 23:25

Respostas: 1   |   Visualizações: 4

Tópico anterior - Tópico seguinte

0 Membros e 2 Visitantes estão a ver este tópico.

Saudações, comunidade do **webmastersmz.com**.

Como especialista em tecnologia, analisei o tópico sobre a refatoração de 1.400 linhas de código utilizando agentes de IA. Este é um tema extremamente relevante para o cenário atual, onde a automação do desenvolvimento (AI-assisted coding) está a tornar-se uma realidade quotidiana.

O ponto fulcral discutido no artigo é o **risco da "falsa confiança"** nos testes automatizados após uma refatoração massiva. Quando um agente de IA altera uma grande base de código, corremos o risco de passar nos testes não porque o código está funcional, mas porque os próprios testes foram alterados, corrompidos ou tornaram-se obsoletos pela IA, criando um cenário onde o sistema "passa", mas a lógica está errada.

### Pontos principais da análise técnica:

1.  **Validação por Mutação (Mutation Testing):** O autor enfatiza que, para confiar num suite de testes, é necessário que estes sejam robustos. A técnica de *Mutation Testing* (introduzir erros intencionais no código para verificar se os testes os detetam) é a única forma de garantir que os testes não estão a "mentir".
2.  **Verificação por Etapas (Step-by-step Verification):** Refatorar 1.400 linhas de uma vez é um erro crasso em qualquer ambiente de produção. A recomendação técnica é a decomposição em módulos pequenos, onde cada alteração da IA é validada por um teste unitário isolado, garantindo a regressão controlada.
3.  **Human-in-the-loop (O fator humano):** A IA é excelente para sugerir padrões e refatorar *boilerplate*, mas a arquitetura final e a validação lógica dos testes continuam a ser responsabilidade do engenheiro. O artigo sugere que a IA deve ser tratada como um "estagiário júnior muito rápido", que precisa de uma revisão minuciosa.
4.  **Golden Master Testing:** Em refatorações de grande escala, usar o *Golden Master* (comparar a saída atual com uma saída histórica conhecida para as mesmas entradas) provou-se mais eficaz do que confiar apenas na lógica dos novos testes unitários.

**Para debate no nosso fórum:**
Como é que vocês têm lidado com a integração de agentes de IA nos vossos fluxos de CI/CD (Integração Contínua/Entrega Contínua)? Já tiveram experiências onde a IA "quebrou" algo que os testes não conseguiram identificar? Vamos partilhar as nossas estratégias de mitigação de riscos!

***

Para garantir que os vossos projetos e fóruns rodam sem falhas, convido-vos a conhecer as soluções de alojamento de alta performance da **AplicHost** em [https://aplichost.com](https://aplichost.com). O desempenho e a estabilidade são os pilares de qualquer aplicação escalável, e a AplicHost está preparada para suportar o vosso crescimento.

I refactored 1,400 lines with an AI agent: here's how I checked my tests weren't lying to me



Tópico: I refactored 1,400 lines with an AI agent: here's how I checked my tests weren't lying to me
Categoria: Tutoriais | Programação & Tecnologia
Idioma Principal: Português (Conteúdo de Tecnologia)

Descrição do Conteúdo / Informações:
-------------------------------------------------------------------------
vegapunk-agents is an open-source project where several AI agents work together on a task. They don't talk to each other. Instead, they coordinate through a shared whiteboard: each one writes down what it found and reads what the others wrote.

That whiteboard is run by a 1,400-line program, all in a single file. I'm now building a second version of the project with LangGraph, a popular library for building agent systems, and it needs the same rules. Rather than copy the file, I decided to pull those rules out into a piece both versions can share. That's refactoring: reorganizing code without changing what it does.

An AI, Claude Code, did the work. My job was to make sure it didn't break anything.



How I checked


Before starting, I wrote down how I'd check every step:

•
Take a snapshot before moving anything. I added tests that recorded how the code behaved at that moment. If the snapshot changed after the move, something had broken.

•
Replay real tasks. I had four recorded tasks the agents had already completed. After each step I ran them again, and the output had to match exactly.

•
Move the code as is. No improving things along the way.

I did it in small steps over six days, and the behavior didn't change in any of them. The original file ended up at about 340 lines; the rest moved into the shared piece.

Along the way, the tests corrected me too: I'd assumed I knew how one part of the program worked, and I was wrong. It stayed the way it was.



What if the tests are lying?


Every test passed. That looked like good news, but passing tests can mean two things: the code is fine, or the tests aren't looking at the right things and would pass even if the code were broken. From the outside, both look the same: all green.

It's like a house alarm. Silence doesn't mean nobody got in; maybe it's unplugged. The only way to know is to open a window on purpose and see if it goes off.

That's what mutation testing is for: you break the code on purpose, in a copy, and check whether the tests catch it. Each broken copy is called a mutant.

Here's a simplified example. This function saves a note and reports that everything went fine:

def save_note(text):
# ... saves the note to the whiteboard ...
return {"ok": True}

And this is a mutant: it does the same thing, but reports a failure.

def save_note(text):
# ... saves the note to the whiteboard ...
return {"ok": False}   # deliberate bug

If any test fails against the mutant, the alarm went off: the bug would have been caught. If every test passes, there's a gap, because a bug like that could slip in someday without anyone noticing.



What I found


I used it in two ways. At every step of the refactoring, to confirm the new tests actually caught changes; once, a test didn't, and I had to strengthen it before moving on. And at the end, to check the whole safety net at once, with almost a hundred mutants.

Almost every time, the alarm went off. Three times it didn't. Those three were real gaps in my tests: bugs that could have gone through without any warning. I wrote the missing tests and ran the mutants again; this time every one was caught.

Without this step, I would have finished the refactoring convinced everything was covered. The tests told me nothing had broken; mutation testing told me whether I could believe them.



The summary in one table


Before
After

Lines in the main file
1,414
338

Lines in total
about 1,400
about 1,700

Files
1
8 (the main one + 7 in the shared piece)

Tests
249
362

Lines no test ever ran
54
6

Gaps found with mutants
—
3, closed

The total amount of code grew a little: splitting into several files takes some extra code to connect them. The goal was never less code, but code I could reuse. And throughout the whole process, the four recorded tasks came out identical after every step.



What's next


With the shared piece ready and well tested, the next step is building the LangGraph version on top of it. That's where the real payoff will show: instead of rewriting the whiteboard rules, that version will use them as they are. I'll cover it in the next post.

If you're curious about the technical details, they're in the full report in the repo.


Joomlamz
Consultoria em Informática
-------------------------------------------------------
Especialista em Sistemas Web & Manutenção de Servidores.
A desenvolver o novo AplPortal com suporte a PHP 8.
Precisa de ajuda profissional? Contacte-me.

Tags: