IA & Agentes
GitHub Copilot a fundo [1] - AGENTS.md e custom instructions: ensinando as regras do seu repo
GitHub Copilot in depth [1] - AGENTS.md and custom instructions
Fala dataholics, hoje começa série nova por aqui: GitHub Copilot a fundo. Eu já tinha falado dele na série do ecossistema de Copilots, só que ali foi sobrevoo e ficou faltando justamente a parte que muda o resultado no dia a dia, que é como você configura esse bicho. Vamos começar pelo básico que quase ninguém faz bem feito: ensinar as regras do seu repositório pro agente.

O que veremos nesse post:
Por que o Copilot entrega código com cara de outro projeto
AGENTS.md, o arquivo que virou padrão de mercado
copilot-instructions.md e as instruções por pasta
Onde cada arquivo funciona (a matriz que ninguém lê)
O que escrever e o que NÃO escrever ali dentro
O problema real
Você pede pro Copilot criar um endpoint novo e ele volta com requests quando o projeto todo usa httpx, escreve teste em unittest quando o repo é pytest inteiro, e ainda inventa uma pasta que não existe. Aí o pessoal culpa o modelo, troca pro modelo mais caro e o resultado continua torto, porque o problema não estava no modelo e sim no fato de que ninguém contou pro agente como esse projeto funciona.
Um dev novo no time recebe onboarding, lê o README, pergunta no Teams e em dois dias já escreve no padrão. O agente entra no repo sem nada disso e tem que adivinhar pelo que consegue ler no contexto daquela requisição, então ele adivinha pela média da internet e a média da internet não é o seu time.
AGENTS.md, o padrão que pegou
O jeito mais direto de resolver é um AGENTS.md na raiz do repositório. Ele nasceu como convenção aberta e hoje é lido por GitHub Copilot, Claude Code, Cursor, Gemini CLI e mais um monte de ferramenta, ou seja, você escreve uma vez e serve pro time inteiro mesmo que cada um use um agente diferente. Isso na prática é ótimo, porque acabou aquela briga de "eu uso outra ferramenta, não vou manter o arquivo de vocês".
E tem um detalhe bacana: dentro do AGENTS.md você pode usar @ seguido de um caminho relativo pra incluir outro arquivo, então dá pra manter o arquivo principal enxuto e apontar pros documentos que já existem no repo.
# AGENTS.md
## Stack
Python 3.12, FastAPI, httpx, pytest. Sem requests, sem unittest.
Package manager: uv (nunca pip install direto).
## Comandos
uv sync
uv run pytest -q
ruff check . --fix
## Estrutura
app/routers/ endpoints
app/services/ regra de negocio
app/repo/ acesso a dados (nada de SQL fora daqui)
## Convencoes
Nome de funcao em snake_case, sem abreviacao.
Toda funcao publica com type hint e docstring de uma linha.
Detalhes de deploy: @docs/deploy.mdReginaldo, e se eu já tenho um CLAUDE.md aqui no projeto?
Boa, esse caso é comum e resolve fácil, porque o Copilot trata AGENTS.md, CLAUDE.md e GEMINI.md como o mesmo tipo de instrução de agente. Você não precisa manter três arquivos duplicados brigando entre si, escolhe um como fonte da verdade e deixa os outros só apontando pra ele com o @caminho.
copilot-instructions.md e as instruções por pasta
Do lado específico do Copilot existem dois arquivos que valem conhecer. O primeiro é o .github/copilot-instructions.md, que é a instrução do repositório inteiro e é o arquivo com maior cobertura de todos, funciona em praticamente toda superfície do Copilot. O segundo é o .github/instructions/*.instructions.md, que é onde a coisa fica interessante, porque ele aceita um applyTo no frontmatter e só entra em cena quando o agente mexe naquele caminho.
---
applyTo: "app/repo/**/*.py"
---
Nessa pasta a regra e diferente:
- Nunca montar SQL por concatenacao de string, sempre parametro.
- Toda query nova precisa de um teste em tests/repo.
- Retornar dataclass, nao dict solto.Isso resolve o problema clássico do arquivo único gigante. Em vez de escrever "quando você estiver na camada de dados faça X, quando estiver no front faça Y" e rezar pro modelo lembrar disso lá no fim de um prompt de 400 linhas, você fatia a regra por pasta e o agente só carrega o que interessa pro arquivo que ele está tocando. Menos contexto queimado e regra mais respeitada.
Onde cada arquivo funciona
Esse é o ponto que gera mais confusão, porque nem todo arquivo é lido em toda superfície. A documentação tem essa matriz e vale colar aqui, porque tem gente configurando instrução por pasta e reclamando que o chat do github.com ignora, quando na verdade ele nem suporta.
.github/copilot-instructions.md: funciona em tudo, chat do github.com, VS Code, cloud agent, code review e CLI.
*.instructions.md com applyTo: VS Code, cloud agent, code review e CLI. NÃO vale no chat do github.com.
AGENTS.md, CLAUDE.md, GEMINI.md: VS Code, cloud agent, code review e CLI. Também fica de fora do chat do github.com.
Instruções pessoais em ~/.copilot/: chat do github.com e CLI, e como o nome diz, valem só pra você.
Instruções de organização (configuradas no settings da org, não em arquivo): chat do github.com, cloud agent e code review.
DETALHE IMPORTANTE: essas camadas somam, elas não se substituem. Se a org define uma regra e o repo define outra, as duas chegam no agente, e se elas se contradizem o resultado fica na sorte. Vale combinar com o time o que é regra de org (segurança, licença, o que nunca pode) e o que é regra de repo (stack, comando, estrutura).
O que escrever e o que deixar de fora
O que funciona de verdade é informação que o agente não consegue deduzir sozinho e que ele erraria se tentasse: stack com versão, gerenciador de pacote, comando de build e de teste, layout de pastas, convenção de nome e as proibições explícitas do tipo "não use tal lib". Comando de teste é o que dá mais retorno por linha escrita, porque o agente que sabe rodar o teste se corrige sozinho e devolve código que já passou.
O que não funciona é transformar o arquivo em manifesto. Já vi arquivo de instrução com a história da empresa, o organograma e o code of conduct, e eu acho isso pior do que não ter arquivo, porque todo request paga o custo desse contexto e o agente dilui a regra que importa no meio da prosa. Meu jeito de fazer: arquivo raiz curto, do tamanho de um README de projeto pequeno, e o resto fatiado com applyTo.
Uma coisa que eu ainda não tenho medição bonita pra mostrar, mas que sinto no uso: depois que você coloca comando de teste e as proibições explícitas, cai muito o retrabalho de review. Não é que o agente virou sênior, é que ele parou de errar as coisas bobas.
RESUMO
AGENTS.md na raiz: padrão aberto, serve pro Copilot e pros outros agentes, aceita @caminho pra incluir arquivo.
.github/copilot-instructions.md: instrução do repo com a maior cobertura de superfícies.
.github/instructions/*.instructions.md com applyTo: regra por caminho, o recurso mais subutilizado dos três.
Camada pessoal e camada de organização existem e somam com as do repo.
Escreva stack, comandos, estrutura e proibições. Deixe de fora manifesto e história da empresa.
No próximo post da série a gente sobe um degrau e vai pra Agent Skills, que é quando você quer que o agente carregue um conhecimento mais pesado só na hora que precisa dele, sem pagar contexto o tempo todo. Comenta aí se você já tem AGENTS.md nos seus repos ou se o Copilot ainda está adivinhando.
Referências:
https://docs.github.com/en/copilot/reference/custom-instructions-support
https://docs.github.com/copilot/customizing-copilot/adding-custom-instructions-for-github-copilot
Fique bem e até a próxima.
#githubcopilot #agentsmd #copilot #ia #agentes #datainaction
Hey dataholics, a new series starts today: GitHub Copilot in depth. I already covered it in the Copilot ecosystem series, but that was a flyover and it skipped the part that actually changes your day to day results, which is how you configure this thing. Let's start with the basics that almost nobody does properly: teaching your repository rules to the agent.

What we will see in this post:
Why Copilot ships code that looks like it came from another project
AGENTS.md, the file that became a market standard
copilot-instructions.md and path scoped instructions
Where each file actually works (the matrix nobody reads)
What to write there and what NOT to write
The real problem
You ask Copilot for a new endpoint and it comes back using requests when the whole project runs on httpx, writes the test in unittest when the repo is pytest all the way, and invents a folder that does not exist. Then people blame the model, switch to the most expensive one and the result is still crooked, because the problem was never the model, it was that nobody told the agent how this project works.
A new dev joining the team gets onboarding, reads the README, asks around on Teams and in two days is already writing in the house style. The agent lands in the repo with none of that and has to guess from whatever it can read in that request context, so it guesses based on the average of the internet and the average of the internet is not your team.
AGENTS.md, the standard that stuck
The most direct fix is an AGENTS.md in the repository root. It started as an open convention and today it is read by GitHub Copilot, Claude Code, Cursor, Gemini CLI and a pile of other tools, so you write it once and it serves the whole team even if everyone uses a different agent. That is great in practice, because it ends the old argument of "I use another tool, I am not maintaining your file".
And there is a nice detail: inside AGENTS.md you can use @ followed by a relative path to include another file, so you can keep the main file lean and point to documents that already live in the repo.
# AGENTS.md
## Stack
Python 3.12, FastAPI, httpx, pytest. No requests, no unittest.
Package manager: uv (never pip install directly).
## Commands
uv sync
uv run pytest -q
ruff check . --fix
## Structure
app/routers/ endpoints
app/services/ business rules
app/repo/ data access (no SQL outside of here)
## Conventions
Function names in snake_case, no abbreviations.
Every public function with a type hint and a one line docstring.
Deploy details: @docs/deploy.mdReginaldo, what if I already have a CLAUDE.md in this project?
Good one, that case is common and easy to solve, because Copilot treats AGENTS.md, CLAUDE.md and GEMINI.md as the same kind of agent instruction. You do not need three duplicated files fighting each other, pick one as the source of truth and leave the others just pointing at it with the @path.
copilot-instructions.md and path scoped instructions
On the Copilot specific side there are two files worth knowing. The first is .github/copilot-instructions.md, the repository wide instruction and the one with the broadest coverage of them all, working on practically every Copilot surface. The second is .github/instructions/*.instructions.md, which is where it gets interesting, because it takes an applyTo in the frontmatter and only kicks in when the agent touches that path.
---
applyTo: "app/repo/**/*.py"
---
The rules are different in this folder:
- Never build SQL by string concatenation, always parameters.
- Every new query needs a test in tests/repo.
- Return a dataclass, not a loose dict.That solves the classic problem of the one giant file. Instead of writing "when you are in the data layer do X, when you are in the front end do Y" and praying the model remembers it at the end of a 400 line prompt, you slice the rule per folder and the agent only loads what matters for the file it is touching. Less context burned and rules that actually get followed.
Where each file works
This is the point that causes the most confusion, because not every file is read on every surface. The docs have this matrix and it is worth pasting here, because there are people setting up path scoped instructions and complaining that chat on github.com ignores them, when the truth is it does not even support them.
.github/copilot-instructions.md: works everywhere, chat on github.com, VS Code, cloud agent, code review and CLI.
*.instructions.md with applyTo: VS Code, cloud agent, code review and CLI. Does NOT work in chat on github.com.
AGENTS.md, CLAUDE.md, GEMINI.md: VS Code, cloud agent, code review and CLI. Also left out of chat on github.com.
Personal instructions in ~/.copilot/: chat on github.com and CLI, and as the name says, they only apply to you.
Organization instructions (set in the org settings, not in a file): chat on github.com, cloud agent and code review.
IMPORTANT: these layers add up, they do not replace each other. If the org defines one rule and the repo defines another, both reach the agent, and if they contradict each other the outcome is a coin flip. Worth agreeing with your team on what is an org rule (security, licensing, hard nos) and what is a repo rule (stack, commands, structure).
What to write and what to leave out
What really works is information the agent cannot figure out on its own and would get wrong if it tried: stack with versions, package manager, build and test commands, folder layout, naming conventions and the explicit bans like "do not use that library". The test command gives the best return per line written, because an agent that knows how to run the tests fixes itself and hands you code that already passes.
What does not work is turning the file into a manifesto. I have seen instruction files with the company history, the org chart and the code of conduct, and I think that is worse than having no file at all, because every request pays for that context and the agent dilutes the rule that matters in the middle of the prose. My way of doing it: a short root file, about the size of a small project README, and everything else sliced up with applyTo.
One thing I still do not have a pretty measurement for, but I feel while using it: once you add the test command and the explicit bans, review rework drops a lot. The agent did not become a senior, it just stopped making the silly mistakes.
RECAP
AGENTS.md in the root: open standard, serves Copilot and the other agents, takes @path to include files.
.github/copilot-instructions.md: repo instruction with the broadest surface coverage.
.github/instructions/*.instructions.md with applyTo: path scoped rules, the most underused of the three.
Personal and organization layers exist and add up with the repo ones.
Write stack, commands, structure and bans. Leave out manifestos and company history.
In the next post of the series we go one level up into Agent Skills, which is when you want the agent to load heavier knowledge only at the moment it needs it, without paying for that context all the time. Tell me in the comments if you already have AGENTS.md in your repos or if Copilot is still guessing.
References:
https://docs.github.com/en/copilot/reference/custom-instructions-support
https://docs.github.com/copilot/customizing-copilot/adding-custom-instructions-for-github-copilot
Stay well and see you next time.
#githubcopilot #agentsmd #copilot #ai #agents #datainaction
Gostou? Tem mais no YouTube e no LinkedIn.
Enjoyed it? There's more on YouTube and LinkedIn.