Pular para o conteúdo

← Do card ao pull request: o que aprendi construindo um agente de software de verdade

Do card ao pull request: o que aprendi construindo um agente de software de verdade

Português ↔ English

O problema não era gerar código

Existe uma diferença enorme entre um modelo que escreve código e um agente que consegue participar de um processo de engenharia.

Eu percebi isso construindo o DevAgent.

A ideia inicial parece simples: pegar um card do backlog, entender a tarefa, alterar o repositório e abrir um pull request. Em uma demo, dá para montar algo parecido rapidamente. Em um fluxo que você aceitaria colocar perto de um repositório real, a história muda completamente.

O problema nunca foi "como fazer o LLM gerar TypeScript".

O problema era: como fazer uma máquina trabalhar dentro das mesmas restrições que tornam um time de software confiável?

O pull request virou a fronteira de segurança

A primeira decisão importante foi proibir o agente de entregar diretamente na branch principal.

Parece óbvio, mas isso muda a arquitetura inteira.

O produto do agente não é código em produção. O produto é um pull request revisável.

txt
Card
  ↓
Entendimento da tarefa
  ↓
Plano
  ↓
Branch isolada
  ↓
Alterações
  ↓
Lint / Typecheck / Testes
  ↓
Diff + resumo
  ↓
Pull Request
  ↓
Revisão humana

Isso reaproveita um contrato que equipes já entendem: diff, checks, comentários, aprovação e merge.

Em vez de inventar uma interface paralela para revisar IA, eu prefiro fazer a IA entrar pela porta que já existe.

O card precisa ser especificação suficiente

Uma das tentações em sistemas de agentes é criar uma nova linguagem de prompt que só o agente entende.

Eu evitei isso.

Se o time precisa preencher quinze campos artificiais para a automação funcionar, a automação começou a transferir trabalho em vez de removê-lo.

O input primário continua sendo o card.

Isso obriga o agente a responder algumas perguntas antes de editar qualquer coisa:

  • Qual é o comportamento esperado?
  • Quais arquivos parecem relacionados?
  • Existe código semelhante no projeto?
  • Há critério de aceitação explícito?
  • Existe ambiguidade suficiente para bloquear a execução?

A última pergunta é especialmente importante.

Autonomia não é continuar a qualquer custo. Um agente útil também precisa saber quando não tem informação suficiente para agir.

Planejar antes de escrever reduz desperdício

Meu primeiro impulso foi deixar o agente explorar e alterar ao mesmo tempo. Funciona, mas gera um comportamento caro: ele descobre tarde que seguiu a abstração errada e precisa desfazer meia implementação.

Separar uma etapa curta de planejamento melhorou o fluxo.

O plano não precisa virar um documento de arquitetura. Algo assim já é suficiente:

json
{
  "goal": "Adicionar filtro por status na listagem de pedidos",
  "filesLikelyAffected": [
    "src/modules/orders/application/list-orders.ts",
    "src/app/orders/page.tsx"
  ],
  "checks": [
    "preservar paginação",
    "validar enum de status",
    "adicionar teste do filtro"
  ],
  "risk": "low"
}

Com isso, fica mais fácil impor orçamento, detectar tarefas grandes demais e decidir se vale delegar a execução.

Ferramenta não é permissão

Outro aprendizado importante: dar uma ferramenta ao agente não significa dar liberdade irrestrita para usá-la.

Eu trato capacidades como permissões explícitas.

Por exemplo:

ts
const policy = {
  filesystem: {
    read: ['src/**', 'tests/**', 'package.json'],
    write: ['src/**', 'tests/**'],
    deny: ['.env*', '.git/**'],
  },
  shell: {
    allow: ['npm test', 'npm run lint', 'npm run typecheck'],
    denyNetwork: true,
  },
  git: {
    canCreateBranch: true,
    canPushBranch: true,
    canMerge: false,
    canForcePush: false,
  },
}

Esse é um ponto que eu considero mais importante que escolher entre dois modelos com alguns pontos de diferença em benchmark.

O modelo pode ser excelente. Se o harness permite que ele faça coisas demais sem controle, a arquitetura continua ruim.

Teste não é etapa final; é ferramenta de raciocínio

No DevAgent, o agente não roda a suíte apenas depois de "terminar".

Os testes fazem parte do loop.

Uma execução simplificada fica assim:

ts
for (let attempt = 1; attempt <= MAX_ATTEMPTS; attempt++) {
  await implementNextStep()

  const result = await runChecks()

  if (result.ok) break

  await inspectFailure(result)
}

O detalhe importante é o limite.

Sem budget, um agente pode entrar em uma espiral de tentativa e erro que parece produtividade porque existe muita atividade, mas não existe avanço proporcional.

Eu prefiro limitar:

  • número de tentativas;
  • tempo total;
  • quantidade de arquivos alterados;
  • custo de modelo;
  • comandos permitidos.

Quando o limite é atingido, ele entrega contexto para um humano em vez de fingir que está quase lá.

O diff é uma fonte de verdade melhor que a explicação do modelo

Modelos são muito bons em escrever resumos convincentes. Isso é justamente um motivo para não confiar apenas no resumo.

Antes de abrir o PR, o agente precisa comparar a intenção com o que realmente mudou.

Eu gosto de pensar em três camadas:

  1. Intent — o que o card pediu.
  2. Evidence — diff, testes e logs.
  3. Narrative — a explicação do agente.

A narrativa só é útil quando está ancorada nas evidências.

O corpo do PR pode ter uma estrutura previsível:

md
## O que mudou
- Adicionado filtro de status na consulta de pedidos.
- Estado do filtro sincronizado com a URL.

## Por quê
Implementa o critério de aceitação do card #184.

## Validação
- npm run lint ✅
- npm run typecheck ✅
- npm test ✅

## Risco / observações
Baixo. Sem alteração de schema ou contrato externo.

Isso reduz muito o custo cognitivo de quem revisa.

Nem toda tarefa deveria entrar no agente

Esse talvez seja o insight mais útil do projeto.

O objetivo não é automatizar 100% do backlog.

Tarefas boas para delegação têm algumas características:

  • escopo pequeno ou médio;
  • comportamento observável;
  • testes existentes ou fáceis de criar;
  • poucas decisões de produto;
  • baixo risco de dados e infraestrutura;
  • definição de pronto clara.

Já tarefas com requisito ambíguo, migração irreversível, decisão arquitetural grande ou impacto de segurança deveriam escalar para um humano cedo.

Eu prefiro um agente que conclui 40% das tarefas certas com alta confiança do que um que tenta 100% e cria uma revisão infernal.

Onde Jev e modelos especializados começam a ficar interessantes

Uma consequência dessa arquitetura é que nem toda decisão precisa passar pelo mesmo LLM que escreve código.

"Esta tarefa é adequada para automação?", "qual ferramenta devo chamar?" ou "o resultado precisa de revisão extra?" são perguntas de decisão, não de redação.

É por isso que modelos especializados em decisão, como o recém-lançado Jev, me parecem uma direção interessante: o agente pode continuar usando um modelo generativo para planejar ou editar código e uma camada separada para roteamento, classificação ou gates.

Mais modelos não significam necessariamente mais complexidade. Às vezes significam responsabilidades mais claras.

O que eu mudaria numa próxima versão

Três coisas estão no topo da lista.

1. Avaliação por tarefa, não por sensação

Quero registrar para cada execução:

  • completou sem intervenção?
  • quantas tentativas?
  • checks passaram na primeira vez?
  • o PR foi aceito, editado ou descartado?
  • quanto custou?
  • qual foi o tempo até merge?

Sem isso, "o agente está melhor" vira opinião.

2. Memória de repositório com validade explícita

Convenções estáveis podem ser persistidas. Detalhes de implementação mudam e precisam expirar.

Memória sem política de invalidação vira dívida técnica invisível.

3. Mais gates determinísticos

Quanto mais consigo tirar do LLM e colocar em código, melhor:

  • schema validation;
  • limites de arquivos;
  • branch policy;
  • teste obrigatório;
  • assinatura de commits;
  • regras de segurança.

O modelo deve resolver o que é ambíguo. Código deve continuar resolvendo o que é exato.

A principal lição

Construir o DevAgent mudou a pergunta que eu faço sobre agentes.

Antes eu perguntava: "qual modelo programa melhor?"

Hoje eu pergunto: "qual sistema transforma capacidade de modelo em trabalho verificável?"

É uma pergunta menos glamourosa, mas muito mais próxima do que empresas realmente precisam.

Um agente útil não é aquele que parece um desenvolvedor em uma demo. É aquele que consegue entrar no processo, respeitar limites, produzir evidência e deixar a decisão final clara para quem responde pelo software.

Referências

The hard part was not generating code

There is a huge difference between a model that can write code and an agent that can participate in an engineering process.

I learned that while building DevAgent.

The initial idea sounds simple: take a backlog card, understand the task, change the repository, and open a pull request. You can demo something like that quickly. Building a workflow you would actually allow near a real repository is a very different problem.

The hard part was never "how do I make an LLM generate TypeScript?"

The real question was: how do I make a machine work inside the same constraints that make a software team reliable?

The pull request became the safety boundary

The first important decision was to prevent the agent from delivering directly to the main branch.

That sounds obvious, but it changes the architecture.

The product of the agent is not production code. It is a reviewable pull request.

txt
Backlog card
    ↓
Understand task
    ↓
Plan
    ↓
Isolated branch
    ↓
Changes
    ↓
Lint / Typecheck / Tests
    ↓
Diff + summary
    ↓
Pull Request
    ↓
Human review

This reuses a contract engineering teams already understand: diffs, checks, comments, approvals, and merge controls.

Instead of inventing a separate AI review interface, I would rather make the AI enter through the door that already exists.

The card should be a sufficient specification

One temptation with agent systems is to invent a second prompt language that only the agent understands.

I avoided that.

If the team needs to fill in fifteen artificial fields before automation works, the automation has started moving work around instead of removing it.

The backlog card remains the primary input.

That forces the agent to answer a few questions before touching code:

  • What behavior is expected?
  • Which files are likely related?
  • Is there a similar implementation already in the project?
  • Are the acceptance criteria explicit?
  • Is the task ambiguous enough that execution should stop?

That last question matters a lot.

Autonomy does not mean continuing at any cost. A useful agent also needs to know when it does not have enough information to act.

Planning before writing reduces waste

My first instinct was to let the agent explore and edit at the same time. It works, but creates an expensive failure mode: the agent discovers late that it followed the wrong abstraction and has to undo half the implementation.

A short planning stage made the workflow cleaner.

The plan does not need to become an architecture document. Something like this is already useful:

json
{
  "goal": "Add a status filter to the orders list",
  "filesLikelyAffected": [
    "src/modules/orders/application/list-orders.ts",
    "src/app/orders/page.tsx"
  ],
  "checks": [
    "preserve pagination",
    "validate status enum",
    "add filter test"
  ],
  "risk": "low"
}

Now it is easier to impose budgets, detect tasks that are too large, and decide whether execution should be delegated at all.

A tool is not a permission

Another important lesson: giving an agent a tool should not mean giving it unrestricted freedom to use that tool.

I think about capabilities as explicit permissions.

ts
const policy = {
  filesystem: {
    read: ['src/**', 'tests/**', 'package.json'],
    write: ['src/**', 'tests/**'],
    deny: ['.env*', '.git/**'],
  },
  shell: {
    allow: ['npm test', 'npm run lint', 'npm run typecheck'],
    denyNetwork: true,
  },
  git: {
    canCreateBranch: true,
    canPushBranch: true,
    canMerge: false,
    canForcePush: false,
  },
}

I consider this more important than a few benchmark points between two models.

A model can be excellent. If the harness lets it do too much without controls, the system is still poorly designed.

Tests are not the final step; they are a reasoning tool

In DevAgent, the agent does not run the test suite only after it thinks it is done.

Checks are part of the loop.

A simplified execution looks like this:

ts
for (let attempt = 1; attempt <= MAX_ATTEMPTS; attempt++) {
  await implementNextStep()

  const result = await runChecks()

  if (result.ok) break

  await inspectFailure(result)
}

The important detail is the limit.

Without a budget, an agent can enter a trial-and-error spiral that looks productive because there is a lot of activity, while actual progress barely moves.

I prefer to limit:

  • number of attempts;
  • total execution time;
  • number of modified files;
  • model cost;
  • allowed commands.

When a limit is reached, the agent should hand useful context to a human instead of pretending it is almost finished.

The diff is a better source of truth than the model's explanation

Models are very good at writing convincing summaries. That is exactly why the summary should not be the only thing we trust.

Before opening the PR, the agent needs to compare the original intent with what actually changed.

I like to separate three layers:

  1. Intent — what the card asked for.
  2. Evidence — diff, tests, and logs.
  3. Narrative — the agent's explanation.

The narrative is useful only when it is grounded in evidence.

A PR body can stay predictable:

md
## What changed
- Added a status filter to the order query.
- Synced filter state with the URL.

## Why
Implements the acceptance criteria from card #184.

## Validation
- npm run lint ✅
- npm run typecheck ✅
- npm test ✅

## Risk / notes
Low. No schema or external contract changes.

That lowers the cognitive cost of review substantially.

Not every task belongs in an agent

This may be the most useful insight from the project.

The goal is not to automate 100% of the backlog.

Good delegation candidates usually have a few properties:

  • small or medium scope;
  • observable behavior;
  • existing tests or tests that are easy to add;
  • few product decisions;
  • low data and infrastructure risk;
  • a clear definition of done.

Tasks with ambiguous requirements, irreversible migrations, major architecture decisions, or meaningful security impact should escalate to a human early.

I would rather have an agent complete 40% of the right tasks with high confidence than attempt 100% and create a review nightmare.

Where Jev and specialized models become interesting

One consequence of this architecture is that not every decision needs to go through the same LLM that writes the code.

"Is this task suitable for automation?", "which tool should I call?", or "does this result need extra review?" are decision problems, not writing problems.

That is why decision-focused models such as the newly released Jev are interesting to me. A generative model can still plan and edit code while a separate layer handles routing, classification, or gates.

More models do not necessarily mean more complexity. Sometimes they mean clearer responsibilities.

What I would change in the next version

Three things are at the top of the list.

1. Evaluate tasks, not vibes

For every run I want to record:

  • did it finish without intervention?
  • how many attempts did it need?
  • did checks pass on the first try?
  • was the PR accepted, edited, or rejected?
  • how much did it cost?
  • how long did it take to merge?

Without that, "the agent is getting better" is just an opinion.

2. Repository memory with explicit validity

Stable conventions can be persisted. Implementation details change and should expire.

Memory without an invalidation policy becomes invisible technical debt.

3. More deterministic gates

The more I can move out of the LLM and into code, the better:

  • schema validation;
  • file limits;
  • branch policy;
  • required tests;
  • commit rules;
  • security checks.

The model should solve ambiguity. Code should keep solving exact rules.

The main lesson

Building DevAgent changed the question I ask about software agents.

I used to ask: "which model codes best?"

Now I ask: "which system turns model capability into verifiable work?"

It is a less glamorous question, but it is much closer to what companies actually need.

A useful agent is not one that looks like a developer in a demo. It is one that can enter the process, respect limits, produce evidence, and keep the final decision clear for the people responsible for the software.

References