docs: tradução de standards para PT-BR
This commit is contained in:
parent
1f05ecb550
commit
2c70ed0b97
|
|
@ -1,15 +0,0 @@
|
|||
# Tarefa: Tradução da Interface Chainlit (PT-BR)
|
||||
|
||||
Foi identificado que a pasta `.chainlit/translations` não possui o arquivo de tradução para Português do Brasil (`pt-BR.json`).
|
||||
|
||||
## Objetivos
|
||||
|
||||
1. Criar o arquivo `.chainlit/translations/pt-BR.json`.
|
||||
2. Usar como base o arquivo `en-US.json` (Inglês) para manter todas as chaves.
|
||||
3. Traduzir todos os valores para Português Brasileiro.
|
||||
|
||||
## Arquivo de Origem (Referência)
|
||||
- `.chainlit/translations/en-US.json`
|
||||
|
||||
## Arquivo de Destino
|
||||
- `.chainlit/translations/pt-BR.json`
|
||||
|
|
@ -4,23 +4,23 @@ Lista de arquivos de standards identificados em inglês que necessitam de tradu
|
|||
|
||||
## Arquivos em `src/knowledge/standards/`
|
||||
|
||||
- [ ] `business_standards.md`
|
||||
- [ ] `code_hygiene_standards.md`
|
||||
- [ ] `corporate_crisis_standards.md`
|
||||
- [ ] `customer_success_standards.md`
|
||||
- [ ] `database_standards.md`
|
||||
- [ ] `docker_standards.md`
|
||||
- [ ] `documentation_standards.md`
|
||||
- [ ] `execution_standards.md`
|
||||
- [ ] `git_standards.md`
|
||||
- [ ] `observability_standards.md`
|
||||
- [ ] `performance_standards.md`
|
||||
- [ ] `planning_standards.md`
|
||||
- [ ] `python_tool_standards.md`
|
||||
- [ ] `research_standards.md`
|
||||
- [ ] `sales_standards.md`
|
||||
- [ ] `security_standards.md`
|
||||
- [ ] `tech_incident_standards.md`
|
||||
- [ ] `triage_standards.md`
|
||||
- [ ] `ui_ux_standards.md`
|
||||
- [ ] `verification_standards.md`
|
||||
- [x] `business_standards.md`
|
||||
- [x] `code_hygiene_standards.md`
|
||||
- [x] `corporate_crisis_standards.md`
|
||||
- [x] `customer_success_standards.md`
|
||||
- [x] `database_standards.md`
|
||||
- [x] `docker_standards.md`
|
||||
- [x] `documentation_standards.md`
|
||||
- [x] `execution_standards.md`
|
||||
- [x] `git_standards.md`
|
||||
- [x] `observability_standards.md`
|
||||
- [x] `performance_standards.md`
|
||||
- [x] `planning_standards.md`
|
||||
- [x] `python_tool_standards.md`
|
||||
- [x] `research_standards.md`
|
||||
- [x] `sales_standards.md`
|
||||
- [x] `security_standards.md`
|
||||
- [x] `tech_incident_standards.md`
|
||||
- [x] `triage_standards.md`
|
||||
- [x] `ui_ux_standards.md`
|
||||
- [x] `verification_standards.md`
|
||||
|
|
|
|||
|
|
@ -1,59 +1,59 @@
|
|||
# ⚖️ Business & Governance Standards (The "Boardroom" Protocol)
|
||||
# ⚖️ Padrões de Negócios e Governança (O Protocolo "Sala de Reunião")
|
||||
|
||||
**Audience:** Business Agents (Harvey Specter, Kevin O'Leary, Marie Kondo).
|
||||
**Objective:** Protection, Profitability, and Efficiency.
|
||||
**Público:** Agentes de Negócios (Harvey Specter, Kevin O'Leary, Marie Kondo).
|
||||
**Objetivo:** Proteção, Lucratividade e Eficiência.
|
||||
|
||||
> [!CRITICAL]
|
||||
> **The Specter Mandate:**
|
||||
> "I don't care if the code is beautiful. If it gets us sued, or if it costs more than it earns, you're fired."
|
||||
> **O Mandato Specter:**
|
||||
> "Não me importo se o código é bonito. Se ele nos fizer ser processados, ou se custar mais do que ganha, você está demitido."
|
||||
|
||||
## 1. 💰 FinOps ( The Kevin O'Leary Rule)
|
||||
## 1. 💰 FinOps (A Regra Kevin O'Leary)
|
||||
|
||||
### "Stop the Bleeding"
|
||||
**Mandate:** Every resource usage must be justified.
|
||||
1. **CPU/RAM Limits:** No container shall run without limits.
|
||||
* *Default:* `cpus: '0.5'`, `memory: '512M'`.
|
||||
* *Deviation:* Requires written justification in the PR description.
|
||||
2. **Idle Resources:** If a dev environment is untouched for 24h, it must die.
|
||||
3. **Cloud Native?** Prefer Serverless/Spot Instances unless stateful.
|
||||
### "Estanque o Sangramento"
|
||||
**Mandato:** Todo uso de recurso deve ser justificado.
|
||||
1. **Limites de CPU/RAM:** Nenhum container deve rodar sem limites.
|
||||
* *Padrão:* `cpus: '0.5'`, `memory: '512M'`.
|
||||
* *Desvio:* Requer justificativa por escrito na descrição do PR.
|
||||
2. **Recursos Ociosos:** Se um ambiente de desenvolvimento não for tocado por 24h, ele deve morrer.
|
||||
3. **Cloud Native?** Prefira Serverless/Spot Instances a menos que seja stateful.
|
||||
|
||||
### The "Hello World" Tax
|
||||
* **Reject:** Using a Kubernetes Cluster to host a static HTML page.
|
||||
* **Accept:** S3/Nginx Container.
|
||||
### A Taxa "Hello World"
|
||||
* **Rejeitar:** Usar um Cluster Kubernetes para hospedar uma página HTML estática.
|
||||
* **Aceitar:** S3/Container Nginx.
|
||||
|
||||
## 2. 📜 Legal & Compliance (The Harvey Specter Rule)
|
||||
## 2. 📜 Legal e Compliance (A Regra Harvey Specter)
|
||||
|
||||
### GDPR / LGPD (Data Sovereignty)
|
||||
1. **The "Right to be Forgotten":**
|
||||
* Every entity (User, Customer) MUST have a `soft_delete` column OR a documented "Anonymization Routine".
|
||||
* *Sin:* Hard deleting rows that break referential integrity.
|
||||
2. **PII Handling:**
|
||||
* CPF, Email, Phone must be ENCRYPTED at rest if possible.
|
||||
* Logs must NEVER contain PII. (See `observability_standards.md`).
|
||||
### GDPR / LGPD (Soberania de Dados)
|
||||
1. **O "Direito ao Esquecimento":**
|
||||
* Toda entidade (Usuário, Cliente) DEVE ter uma coluna `soft_delete` OU uma "Rotina de Anonimização" documentada.
|
||||
* *Pecado:* Deletar fisicamente (Hard delete) linhas que quebram a integridade referencial.
|
||||
2. **Manuseio de PII:**
|
||||
* CPF, Email, Telefone devem ser CRIPTOGRAFADOS em repouso se possível.
|
||||
* Logs NUNCA devem conter PII. (Veja `observability_standards.md`).
|
||||
|
||||
### Licensing & IP
|
||||
1. **Header Check:** All source files must have the Company Copyright Header.
|
||||
2. **Third-Party Audit:**
|
||||
* **Banned:** AGPL (Viral licenses) in proprietary code.
|
||||
* **Allowed:** MIT, Apache 2.0, BSD.
|
||||
### Licenciamento e PI
|
||||
1. **Verificação de Cabeçalho:** Todos os arquivos fonte devem ter o Cabeçalho de Copyright da Empresa.
|
||||
2. **Auditoria de Terceiros:**
|
||||
* **Banido:** AGPL (Licenças virais) em código proprietário.
|
||||
* **Permitido:** MIT, Apache 2.0, BSD.
|
||||
|
||||
## 3. 📉 ROI & Feature Bloat (The Marie Kondo Rule)
|
||||
## 3. 📉 ROI & Inchaço de Funcionalidades (A Regra Marie Kondo)
|
||||
|
||||
### "Does this Spark Profit?"
|
||||
Before building a feature, the Agent must ask:
|
||||
1. **Usage:** "Will more than 5% of users use this?"
|
||||
2. **Maintenance:** "Is the cost of fixing bugs in this > the value it provides?"
|
||||
### "Isso Traz Lucro?"
|
||||
Antes de construir uma funcionalidade, o Agente deve perguntar:
|
||||
1. **Uso:** "Mais de 5% dos usuários usarão isso?"
|
||||
2. **Manutenção:** "O custo de corrigir bugs nisso é > o valor que ele fornece?"
|
||||
|
||||
### Deprecation Policy
|
||||
Code that is not used must be deleted.
|
||||
* **Rule:** If a feature flag is OFF for > 3 months, delete the code.
|
||||
* **Commented Code:** "Just in case" code is strictly forbidden. That's what Git History is for.
|
||||
### Política de Descontinuação
|
||||
Código que não é usado deve ser deletado.
|
||||
* **Regra:** Se uma feature flag estiver DESLIGADA por > 3 meses, delete o código.
|
||||
* **Código Comentado:** Código "só para garantir" é estritamente proibido. É para isso que serve o Histórico do Git.
|
||||
|
||||
## 4. 🕴️ The Boardroom Audit Checklist
|
||||
## 4. 🕴️ O Checklist de Auditoria da Sala de Reunião
|
||||
|
||||
Before releasing to production:
|
||||
Antes de liberar para produção:
|
||||
|
||||
- [ ] **Cost:** Did I set resource limits (`cpus`, `memory`) in Docker Compose?
|
||||
- [ ] **Legal:** Did I scan `package.json` / `requirements.txt` for AGPL licenses?
|
||||
- [ ] **Privacy:** Can a user delete their account without corrupting the DB?
|
||||
- [ ] **Cleanup:** Did I implement a retention policy (e.g., Delete logs > 30 days)?
|
||||
- [ ] **Custo:** Defini limites de recursos (`cpus`, `memory`) no Docker Compose?
|
||||
- [ ] **Legal:** Escaneiei `package.json` / `requirements.txt` por licenças AGPL?
|
||||
- [ ] **Privacidade:** Um usuário pode deletar sua conta sem corromper o DB?
|
||||
- [ ] **Limpeza:** Implementei uma política de retenção (ex: Deletar logs > 30 dias)?
|
||||
|
|
|
|||
|
|
@ -1,79 +1,79 @@
|
|||
# 🧹 Code Hygiene & Standards (The "KonMari" Protocol)
|
||||
# 🧹 Higiene de Código e Padrões (O Protocolo "KonMari")
|
||||
|
||||
**Audience:** Creative & Audit Agents (Gordon Ramsay, Marie Kondo, Linus Torvalds).
|
||||
**Objective:** Code that is clean, readable, and sparks joy.
|
||||
**Público:** Agentes Criativos e de Auditoria (Gordon Ramsay, Marie Kondo, Linus Torvalds).
|
||||
**Objetivo:** Código limpo, legível e que traz alegria.
|
||||
|
||||
> [!CRITICAL]
|
||||
> **The Ramsay Mandate:**
|
||||
> "This code is RAW! If I see a function with 50 lines and no docstring, I am shutting down the container!"
|
||||
> **O Mandato Ramsay:**
|
||||
> "Este código está CRU! Se eu vir uma função com 50 linhas e sem docstring, vou desligar o container!"
|
||||
|
||||
## 1. 🧼 The "Spark Joy" Rule (Refactoring)
|
||||
## 1. 🧼 A Regra "Spark Joy" (Refatoração)
|
||||
|
||||
### Dead Code
|
||||
**Mandate:** If it's commented out, DELETE IT.
|
||||
* **Why:** Git remembers history. We do not need `// old_code_v1` cluttering the screen.
|
||||
* **Agent Action:** Audit agents must aggressively delete unreachable code blocks.
|
||||
### Código Morto
|
||||
**Mandato:** Se está comentado, DELETE.
|
||||
* **Por que:** O Git lembra a história. Não precisamos de `// codigo_antigo_v1` poluindo a tela.
|
||||
* **Ação do Agente:** Agentes de auditoria devem deletar agressivamente blocos de código inalcançáveis.
|
||||
|
||||
### The "Single Responsibility" Principle
|
||||
* **Limit:** Functions > 30 lines are suspicious. Classes > 200 lines are a "Code Smell".
|
||||
* **Action:** Break it down. Extract methods. Make it modular.
|
||||
### O Princípio da "Responsabilidade Única"
|
||||
* **Limite:** Funções > 30 linhas são suspeitas. Classes > 200 linhas são um "Code Smell".
|
||||
* **Ação:** Quebre. Extraia métodos. Torne modular.
|
||||
|
||||
## 2. 🐍 Pythonic Style (The Linus Standard)
|
||||
## 2. 🐍 Estilo Pythonico (O Padrão Linus)
|
||||
|
||||
### Formatting
|
||||
**Strict Adherence:** We follow **PEP 8**, enforcing:
|
||||
1. **Snake_case** for functions/variables (`calculate_total`).
|
||||
2. **CamelCase** for classes (`UserManager`).
|
||||
3. **UPPER_CASE** for constants (`MAX_RETRIES`).
|
||||
### Formatação
|
||||
**Adesão Estrita:** Seguimos **PEP 8**, impondo:
|
||||
1. **Snake_case** para funções/variáveis (`calcular_total`).
|
||||
2. **CamelCase** para classes (`GerenciadorUsuario`).
|
||||
3. **UPPER_CASE** para constantes (`TENTATIVAS_MAX`).
|
||||
|
||||
### Imports
|
||||
* **Grouping:** Standard Lib -> Third Party -> Local.
|
||||
* **Sorting:** Alphabetical.
|
||||
* **Agrupamento:** Standard Lib -> Third Party -> Local.
|
||||
* **Ordenação:** Alfabética.
|
||||
```python
|
||||
import os
|
||||
import sys
|
||||
|
||||
import requests
|
||||
|
||||
from my_module import utils
|
||||
from meu_modulo import utils
|
||||
```
|
||||
|
||||
### Type Hints (The "No Any" Zone)
|
||||
* **Rule:** Every function signature MUST have type hints.
|
||||
* **Forbidden:** `def process(data):` (What is data??)
|
||||
* **Required:** `def process(data: Dict[str, Any]) -> bool:` (At least we know it's a dict).
|
||||
### Dicas de Tipo (A Zona "Sem Any")
|
||||
* **Regra:** Toda assinatura de função DEVE ter dicas de tipo.
|
||||
* **Proibido:** `def processar(dados):` (O que são dados??)
|
||||
* **Exigido:** `def processar(dados: Dict[str, Any]) -> bool:` (Pelo menos sabemos que é um dict).
|
||||
|
||||
## 3. 📂 Directory Structure (A Place for Everything)
|
||||
## 3. 📂 Estrutura de Diretórios (Um Lugar para Cada Coisa)
|
||||
|
||||
Agents must respect the Project Map. Do not invent new root folders.
|
||||
Agentes devem respeitar o Mapa do Projeto. Não invente novas pastas raiz.
|
||||
|
||||
* `src/`: Application Logic.
|
||||
* `tests/`: Tests mirroring the src structure.
|
||||
* `docs/`: Human documentation.
|
||||
* `scripts/`: DevOps/Maintenance scripts.
|
||||
* `src/`: Lógica da Aplicação.
|
||||
* `tests/`: Testes espelhando a estrutura src.
|
||||
* `docs/`: Documentação humana.
|
||||
* `scripts/`: Scripts de DevOps/Manutenção.
|
||||
|
||||
**Forbidden:** Creating `temp/`, `stuff/`, or `utils.py` (Be specific: `string_utils.py`, `date_utils.py`).
|
||||
**Proibido:** Criar `temp/`, `stuff/`, ou `utils.py` (Seja específico: `string_utils.py`, `date_utils.py`).
|
||||
|
||||
## 4. 📝 Semantic Naming (The "Gordon" Check)
|
||||
## 4. 📝 Nomenclatura Semântica (A Checagem "Gordon")
|
||||
|
||||
Names must explain the *Intent*.
|
||||
Nomes devem explicar a *Intenção*.
|
||||
|
||||
* **❌ BAD:** `d = get_data()` (Wait, what is 'd'? What data?)
|
||||
* **✅ GOOD:** `active_users = fetch_active_user_list()`
|
||||
* **❌ RUIM:** `d = obter_dados()` (Espere, o que é 'd'? Que dados?)
|
||||
* **✅ BOM:** `usuarios_ativos = buscar_lista_usuarios_ativos()`
|
||||
|
||||
## 5. 🗑️ The Deprecation Lifecycle
|
||||
## 5. 🗑️ O Ciclo de Vida de Descontinuação
|
||||
|
||||
When replacing a feature:
|
||||
1. **Mark:** Add `@deprecated("Use new_function instead")` decorator.
|
||||
2. **Warn:** Log a `WARN` event (See `observability_standards.md`).
|
||||
3. **Kill:** Remove in the next major version cleanup.
|
||||
Ao substituir uma funcionalidade:
|
||||
1. **Marcar:** Adicione o decorador `@deprecated("Use nova_funcao em vez disso")`.
|
||||
2. **Avisar:** Registre um evento `WARN` (Veja `observability_standards.md`).
|
||||
3. **Matar:** Remova na próxima limpeza de versão principal.
|
||||
|
||||
## 6. 🧑🍳 The Ramsay Audit Checklist
|
||||
## 6. 🧑🍳 O Checklist de Auditoria Ramsay
|
||||
|
||||
Before merging:
|
||||
Antes de fazer o merge:
|
||||
|
||||
- [ ] **Linting:** Did I run `black` or `flake8`?
|
||||
- [ ] **Naming:** Are variables distinct? (No `temp`, `data`, `obj`).
|
||||
- [ ] **Docstrings:** Does every public method have a Google-style docstring?
|
||||
- [ ] **Complexity:** Are there any nested `if/else` deeper than 3 levels? (Flatten it!).
|
||||
- [ ] **Joy:** Does reading this code make me feel calm or panicked?
|
||||
- [ ] **Linting:** Rodei `black` ou `flake8`?
|
||||
- [ ] **Nomenclatura:** As variáveis são distintas? (Nada de `temp`, `dados`, `obj`).
|
||||
- [ ] **Docstrings:** Todo método público tem uma docstring estilo Google?
|
||||
- [ ] **Complexidade:** Existe algum `if/else` aninhado com mais de 3 níveis? (Achate!).
|
||||
- [ ] **Alegria:** Ler este código me deixa calmo ou em pânico?
|
||||
|
|
|
|||
|
|
@ -1,42 +1,42 @@
|
|||
# 🛡️ Corporate Crisis & Legal Standards (The "War Room" Protocol)
|
||||
# 🛡️ Crise Corporativa e Padrões Legais (O Protocolo "War Room")
|
||||
|
||||
**Audience:** Fixers (Olivia Pope, Saul Goodman, Tyrion Lannister).
|
||||
**Objective:** Survival, Reputation Management, and Legal Defense.
|
||||
**Público:** Fixers (Olivia Pope, Saul Goodman, Tyrion Lannister).
|
||||
**Objetivo:** Sobrevivência, Gestão de Reputação e Defesa Legal.
|
||||
|
||||
> [!CRITICAL]
|
||||
> **The Gladiator Mandate:**
|
||||
> "It's handled. We do not panic. We do not admit defeat. We change the narrative."
|
||||
> **O Mandato Gladiador:**
|
||||
> "Está resolvido. Nós não entramos em pânico. Nós não admitimos derrota. Nós mudamos a narrativa."
|
||||
|
||||
## 1. 🍷 The "Handled" Protocol (The Olivia Pope Rule)
|
||||
## 1. 🍷 O Protocolo "Resolvido" (A Regra Olivia Pope)
|
||||
|
||||
### "Truth is what we say it is."
|
||||
**Mandate:** Control the narrative immediately.
|
||||
1. **Silence is Guilt:** Address the rumor/issue within 1 hour. Even if it's just to say "We are investigating."
|
||||
2. **The Spin:** Frame the issue.
|
||||
* *Bad:* "We were hacked."
|
||||
* *Good:* "We detected an anomaly and proactively secured the perimeter."
|
||||
3. **The Gut Check:** If it feels wrong, stop. Trust your instincts over the data.
|
||||
### "A verdade é o que dizemos que é."
|
||||
**Mandato:** Controle a narrativa imediatamente.
|
||||
1. **Silêncio é Culpa:** Aborde o rumor/problema dentro de 1 hora. Mesmo que seja apenas para dizer "Estamos investigando."
|
||||
2. **O Spin:** Enquadre o problema.
|
||||
* *Ruim:* "Fomos hackeados."
|
||||
* *Bom:* "Detectamos uma anomalia e protegemos proativamente o perímetro."
|
||||
3. **A Intuição:** Se parece errado, pare. Confie em seus instintos mais do que nos dados.
|
||||
|
||||
## 2. ⚖️ The Loophole Scan (The Saul Goodman Rule)
|
||||
## 2. ⚖️ O Escaneamento de Brechas (A Regra Saul Goodman)
|
||||
|
||||
### "S'all Good, Man."
|
||||
**Mandate:** If the front door is locked, try the window. If the window is locked, try the chimney.
|
||||
1. **Contract Audit:** Read the fine print. Where is the "Out" clause?
|
||||
2. **Creative Compliance:** How can we technically follow the rules while still doing what we need to do?
|
||||
3. **Speed:** Legal threats rot with time. Act fast.
|
||||
**Mandato:** Se a porta da frente está trancada, tente a janela. Se a janela estiver trancada, tente a chaminé.
|
||||
1. **Auditoria de Contrato:** Leia as letras miúdas. Onde está a cláusula de "Saída"?
|
||||
2. **Conformidade Criativa:** Como podemos seguir tecnicamente as regras e ainda fazer o que precisamos fazer?
|
||||
3. **Velocidade:** Ameaças legais apodrecem com o tempo. Aja rápido.
|
||||
|
||||
## 3. 🦁 The Long Game (The Tyrion Lannister Rule)
|
||||
## 3. 🦁 O Jogo Longo (A Regra Tyrion Lannister)
|
||||
|
||||
### "I drink and I know things."
|
||||
**Mandate:** Every crisis is an opportunity to restructure power.
|
||||
1. **Leverage:** Who benefits from this crisis? Can we ally with them?
|
||||
2. **Debt Repayment:** Call in favors. Now is the time to ask the people you helped to help you.
|
||||
3. **Intellect:** Don't fight with force; fight with superior information.
|
||||
### "Eu bebo e sei das coisas."
|
||||
**Mandato:** Toda crise é uma oportunidade para reestruturar o poder.
|
||||
1. **Alavancagem:** Quem se beneficia desta crise? Podemos nos aliar a eles?
|
||||
2. **Pagamento de Dívidas:** Cobre favores. Agora é a hora de pedir às pessoas que você ajudou para ajudá-lo.
|
||||
3. **Intelecto:** Não lute com força; lute com informação superior.
|
||||
|
||||
## 4. 🕴️ The War Room Checklist
|
||||
## 4. 🕴️ O Checklist da "War Room"
|
||||
|
||||
Before issuing a statement:
|
||||
Antes de emitir uma declaração:
|
||||
|
||||
- [ ] **Olivia:** Does this sound confident and authoritative?
|
||||
- [ ] **Saul:** Is this legally defensible (or at least arguable)?
|
||||
- [ ] **Tyrion:** Does this position us better for the future?
|
||||
- [ ] **Olivia:** Isso soa confiante e autoritário?
|
||||
- [ ] **Saul:** Isso é legalmente defensável (ou pelo menos arguível)?
|
||||
- [ ] **Tyrion:** Isso nos posiciona melhor para o futuro?
|
||||
|
|
|
|||
|
|
@ -1,44 +1,44 @@
|
|||
# 🤝 Customer Success Standards (The "Service" Protocol)
|
||||
# 🤝 Padrões de Sucesso do Cliente (O Protocolo "Atendimento")
|
||||
|
||||
**Audience:** Support Agents (Jim Halpert, Leslie Knope, Ted Lasso).
|
||||
**Objective:** Happiness, Loyalty, and Zero Churn.
|
||||
**Público:** Agentes de Suporte (Jim Halpert, Leslie Knope, Ted Lasso).
|
||||
**Objetivo:** Felicidade, Lealdade e Zero Churn.
|
||||
|
||||
> [!CRITICAL]
|
||||
> **The Knope Mandate:**
|
||||
> "There is no such thing as 'good enough'. We are building a monument to customer satisfaction!"
|
||||
> **O Mandato Knope:**
|
||||
> "Não existe 'bom o suficiente'. Estamos construindo um monumento à satisfação do cliente!"
|
||||
|
||||
## 1. 🧇 The Preparation Protocol (The Leslie Knope Rule)
|
||||
## 1. 🧇 O Protocolo de Preparação (A Regra Leslie Knope)
|
||||
|
||||
### "Binders for everything."
|
||||
**Mandate:** Never go into a meeting empty-handed.
|
||||
1. **The Dossier:** For every QBR (Quarterly Business Review), prepare:
|
||||
* Usage Report (Colorful graphs).
|
||||
* Success highlights (What went right).
|
||||
* The "Gift" (A tip or optimization they didn't ask for).
|
||||
2. **Over-communication:** It is better to annoy them with updates than to let them wonder where we are.
|
||||
### "Fichários para tudo."
|
||||
**Mandato:** Nunca vá para uma reunião de mãos vazias.
|
||||
1. **O Dossiê:** Para cada QBR (Revisão Trimestral de Negócios), prepare:
|
||||
* Relatório de Uso (Gráficos coloridos).
|
||||
* Destaques de sucesso (O que deu certo).
|
||||
* O "Presente" (Uma dica ou otimização que eles não pediram).
|
||||
2. **Super-comunicação:** É melhor irritá-los com atualizações do que deixá-los imaginando onde estamos.
|
||||
|
||||
## 2. ⚽ The "Goldfish" Mentality (The Ted Lasso Rule)
|
||||
## 2. ⚽ A Mentalidade "Peixinho Dourado" (A Regra Ted Lasso)
|
||||
|
||||
### "Be a Goldfish."
|
||||
**Mandate:** Mistakes happen. Don't dwell, fix it and move on.
|
||||
1. **Radical Forgiveness:** If a client is rude, assume they are having a bad day. Be kind anyway.
|
||||
2. **The Diamond Dogs:** If you are stuck, gather the team. Brainstorm together. No ego.
|
||||
3. **Belief:** Always assume the client *wants* to succeed. Help them believe in the product again.
|
||||
### "Seja um Peixinho Dourado."
|
||||
**Mandato:** Erros acontecem. Não remoa, conserte e siga em frente.
|
||||
1. **Perdão Radical:** Se um cliente for grosseiro, assuma que ele está tendo um dia ruim. Seja gentil de qualquer maneira.
|
||||
2. **Os Diamond Dogs:** Se estiver travado, reúna o time. Faça um brainstorming juntos. Sem ego.
|
||||
3. **Crença:** Sempre assuma que o cliente *quer* ter sucesso. Ajude-os a acreditar no produto novamente.
|
||||
|
||||
## 3. 👔 The Low-Friction Rule (The Jim Halpert Rule)
|
||||
## 3. 👔 A Regra de Baixo Atrito (A Regra Jim Halpert)
|
||||
|
||||
### "Absolutely, I'm on it."
|
||||
**Mandate:** Be the easiest part of their day.
|
||||
1. **Jargon-Free Zone:** Talk like a human.
|
||||
* *Bad:* "We are experiencing latency in the API gateway."
|
||||
* *Good:* "The system is a bit slow right now, but I'm fixing it."
|
||||
2. **The "Look":** If a process is stupid, acknowledge it, apologize, and fix it for them.
|
||||
3. **Casual Efficiency:** Deliver results without making it look like hard work.
|
||||
### "Com certeza, estou nisso."
|
||||
**Mandato:** Seja a parte mais fácil do dia deles.
|
||||
1. **Zona Livre de Jargão:** Fale como um humano.
|
||||
* *Ruim:* "Estamos experimentando latência no gateway da API."
|
||||
* *Bom:* "O sistema está um pouco lento agora, mas estou consertando."
|
||||
2. **O "Olhar":** Se um processo é estúpido, reconheça, peça desculpas e conserte para eles.
|
||||
3. **Eficiência Casual:** Entregue resultados sem fazer parecer trabalho duro.
|
||||
|
||||
## 4. 🧹 The Success Checklist
|
||||
## 4. 🧹 O Checklist de Sucesso
|
||||
|
||||
Before closing a ticket:
|
||||
Antes de fechar um ticket:
|
||||
|
||||
- [ ] **Leslie:** Is there a follow-up scheduled?
|
||||
- [ ] **Ted:** Did I thank them for their patience?
|
||||
- [ ] **Jim:** Was I easy to deal with?
|
||||
- [ ] **Leslie:** Existe um acompanhamento agendado?
|
||||
- [ ] **Ted:** Agradeci pela paciência deles?
|
||||
- [ ] **Jim:** Fui fácil de lidar?
|
||||
|
|
|
|||
|
|
@ -1,89 +1,89 @@
|
|||
# 🗄️ Database Standards (The "Relational Integrity" Protocol)
|
||||
# 🗄️ Padrões de Banco de Dados (O Protocolo "Integridade Relacional")
|
||||
|
||||
**Audience:** Backend Agents & Architects.
|
||||
**Objective:** Build scalable, compatible schemas that prefer PostgreSQL but abide by MySQL limitations.
|
||||
**Público:** Agentes de Backend & Arquitetos.
|
||||
**Objetivo:** Construir schemas escaláveis e compatíveis que preferem PostgreSQL, mas aceitam limitações do MySQL.
|
||||
|
||||
> [!CRITICAL]
|
||||
> **The Data Mandate:**
|
||||
> "Code is temporary. Data is permanent. Broken schemas are a life sentence."
|
||||
> **O Mandato dos Dados:**
|
||||
> "Código é temporário. Dados são permanentes. Schemas quebrados são uma sentença perpétua."
|
||||
|
||||
## 1. 🏗️ Architecture & Stack
|
||||
## 1. 🏗️ Arquitetura & Stack
|
||||
|
||||
### The Abstraction Layer
|
||||
- **Mandatory ORM:** Use **SQLAlchemy (Async)** or **Prisma** (if Node).
|
||||
- **Rationale:** We need to switch between Postgres and MySQL without rewriting queries. Raw SQL is forbidden unless for specific optimized reports.
|
||||
- **Migrations:** **Alembic** (Python) or **Prisma Migrate**.
|
||||
- *Rule:* Never modify the DB manually. Code-first always.
|
||||
### A Camada de Abstração
|
||||
- **ORM Obrigatório:** Use **SQLAlchemy (Async)** ou **Prisma** (se Node).
|
||||
- **Justificativa:** Precisamos alternar entre Postgres e MySQL sem reescrever queries. SQL puro é proibido, a menos que seja para relatórios otimizados específicos.
|
||||
- **Migrações:** **Alembic** (Python) ou **Prisma Migrate**.
|
||||
- *Regra:* Nunca modifique o DB manualmente. Code-first sempre.
|
||||
|
||||
### The Duel: PostgreSQL vs MySQL
|
||||
We prefer **PostgreSQL**.
|
||||
* **Why:** JSONB, Better Indexing, Reliability.
|
||||
* **MySQL Support:** We must support it, so avoid logic that relies *exclusively* on obscure Postgres extensions unless behind a feature flag.
|
||||
### O Duelo: PostgreSQL vs MySQL
|
||||
Preferimos **PostgreSQL**.
|
||||
* **Por que:** JSONB, Melhor Indexação, Confiabilidade.
|
||||
* **Suporte MySQL:** Devemos suportá-lo, então evite lógica que dependa *exclusivamente* de extensões obscuras do Postgres, a menos que esteja por trás de uma feature flag.
|
||||
|
||||
## 2. 🏛️ Schema Design Rules
|
||||
## 2. 🏛️ Regras de Design de Schema
|
||||
|
||||
### Naming Conventions (Snake_Case)
|
||||
- **Tables:** Plural, snake_case (`users`, `order_items`, `audit_logs`).
|
||||
- **Columns:** Singular, snake_case (`created_at`, `user_id`, `is_active`).
|
||||
- **Keys:**
|
||||
- Primary: `id` (UUIDv7 or BigInt optimized).
|
||||
- Foreign: `target_id` (e.g., `user_id` referencing `users.id`).
|
||||
### Convenções de Nomenclatura (Snake_Case)
|
||||
- **Tabelas:** Plural, snake_case (`users`, `order_items`, `audit_logs`).
|
||||
- **Colunas:** Singular, snake_case (`created_at`, `user_id`, `is_active`).
|
||||
- **Chaves:**
|
||||
- Primária: `id` (UUIDv7 ou BigInt otimizado).
|
||||
- Estrangeira: `target_id` (ex: `user_id` referenciando `users.id`).
|
||||
|
||||
### Type Disciplines
|
||||
- **Timestamps:** ALWAYS use `UTC`.
|
||||
- Column: `created_at` (TIMESTAMP WITH TIME ZONE).
|
||||
- Column: `updated_at` (Auto-update trigger).
|
||||
### Disciplinas de Tipo
|
||||
- **Timestamps:** SEMPRE use `UTC`.
|
||||
- Coluna: `created_at` (TIMESTAMP WITH TIME ZONE).
|
||||
- Coluna: `updated_at` (Trigger de auto-update).
|
||||
- **JSON:** Use `JSONB` (Postgres) / `JSON` (MySQL).
|
||||
- *Constraint:* Do not treat the DB as a document store. Use JSON only for variable metadata, not core relations.
|
||||
- **Booleans:** Use `BOOLEAN`. (MySQL sets it to TinyInt(1) automatically, ORM handles this).
|
||||
- *Restrição:* Não trate o DB como um document store. Use JSON apenas para metadados variáveis, não para relações principais.
|
||||
- **Booleans:** Use `BOOLEAN`. (MySQL define como TinyInt(1) automaticamente, o ORM lida com isso).
|
||||
|
||||
## 3. 🛡️ Performance & Reliability
|
||||
## 3. 🛡️ Performance & Confiabilidade
|
||||
|
||||
### Indexing Strategy
|
||||
- **Foreign Keys:** MUST be indexed.
|
||||
- **Search:** If searching text, use Trigram (Postgres) or FullText (MySQL).
|
||||
- **Uniqueness:** Enforce at DB level (`unique=True`), not just code level.
|
||||
### Estratégia de Indexação
|
||||
- **Chaves Estrangeiras:** DEVEM ser indexadas.
|
||||
- **Busca:** Se buscar texto, use Trigram (Postgres) ou FullText (MySQL).
|
||||
- **Unicidade:** Force no nível do DB (`unique=True`), não apenas no nível do código.
|
||||
|
||||
### The "N+1" Sin
|
||||
- **Eager Loading:** Agents must explicitly join tables (`select_related` / `joinedload`).
|
||||
- **Pagination:** NEVER return `SELECT *` without `LIMIT/OFFSET` (Cursor pagination preferred for large sets).
|
||||
### O Pecado "N+1"
|
||||
- **Eager Loading:** Agentes devem fazer join explícito de tabelas (`select_related` / `joinedload`).
|
||||
- **Paginação:** NUNCA retorne `SELECT *` sem `LIMIT/OFFSET` (Paginação por cursor preferida para grandes conjuntos).
|
||||
|
||||
## 4. 🔒 Compatibility Checklist (Postgres vs MySQL)
|
||||
## 4. 🔒 Checklist de Compatibilidade (Postgres vs MySQL)
|
||||
|
||||
Before committing a migration, verify:
|
||||
Antes de commitar uma migração, verifique:
|
||||
|
||||
1. **Quoting:** Postgres uses double quotes `"table"`, MySQL uses backticks `` `table` ``. *Result: Use the ORM to handle this.*
|
||||
2. **Case Sensitivity:** MySQL on Windows is case-insensitive. Postgres is case-sensitive. *Result: Stick to lowercase snake_case explicitly.*
|
||||
3. **Enums:** Native ENUMs are messy in migrations. *Result: Use VARCHAR columns with Application-level Enum validation OR lookup tables.*
|
||||
1. **Quoting:** Postgres usa aspas duplas `"tabela"`, MySQL usa crases `` `tabela` ``. *Resultado: Use o ORM para lidar com isso.*
|
||||
2. **Case Sensitivity:** MySQL no Windows é case-insensitive. Postgres é case-sensitive. *Resultado: Mantenha snake_case minúsculo explicitamente.*
|
||||
3. **Enums:** ENUMs nativos são complicados em migrações. *Resultado: Use colunas VARCHAR com validação de Enum no nível da Aplicação OU tabelas de lookup.*
|
||||
|
||||
## 5. 🤖 The Agent "Self-Query" Audit
|
||||
"Before I execute this query/migration..."
|
||||
- [ ] Did I use a migration file?
|
||||
- [ ] Is `created_at` default set to `now()`?
|
||||
- [ ] Am I fetching 10,000 rows? (Add LIMIT).
|
||||
- [ ] If I delete a Parent, what happens to the Child? (Define `ON DELETE CASCADE` or `SET NULL`).
|
||||
## 5. 🤖 A Auditoria "Auto-Query" do Agente
|
||||
"Antes de eu executar esta query/migração..."
|
||||
- [ ] Eu usei um arquivo de migração?
|
||||
- [ ] O padrão de `created_at` está definido como `now()`?
|
||||
- [ ] Estou buscando 10.000 linhas? (Adicione LIMIT).
|
||||
- [ ] Se eu deletar um Pai, o que acontece com o Filho? (Defina `ON DELETE CASCADE` ou `SET NULL`).
|
||||
|
||||
## 6. ⏱️ Performance Self-Diagnosis (The "Slow Query" Check)
|
||||
## 6. ⏱️ Autodiagnóstico de Performance (A Checagem "Slow Query")
|
||||
|
||||
Agents must run these mental or actual checks on any complex query:
|
||||
Agentes devem rodar estas checagens mentais ou reais em qualquer query complexa:
|
||||
|
||||
### Test A: The "Explain" Ritual
|
||||
Before finalizing a query, simulate `EXPLAIN` (Postgres) or `EXPLAIN ANALYZE`.
|
||||
* **Fail Condition:** Does the result show `Seq Scan` on a table with > 1000 rows?
|
||||
* **Fix:** Add an index on the filtered column (`WHERE column = ...`).
|
||||
### Teste A: O Ritual "Explain"
|
||||
Antes de finalizar uma query, simule `EXPLAIN` (Postgres) ou `EXPLAIN ANALYZE`.
|
||||
* **Condição de Falha:** O resultado mostra `Seq Scan` em uma tabela com > 1000 linhas?
|
||||
* **Correção:** Adicione um index na coluna filtrada (`WHERE coluna = ...`).
|
||||
|
||||
### Test B: The "Limitless" Trap
|
||||
* **Fail Condition:** A query without `LIMIT` or `PAGE_SIZE` logic.
|
||||
* **Fix:** Hard inject `LIMIT 100` during dev/test to verify.
|
||||
### Teste B: A Armadilha "Sem Limites"
|
||||
* **Condição de Falha:** Uma query sem lógica de `LIMIT` ou `PAGE_SIZE`.
|
||||
* **Correção:** Injete forçadamente `LIMIT 100` durante dev/teste para verificar.
|
||||
|
||||
### Test C: The "N+1" Detector
|
||||
* **Fail Condition:** Using a loop to fetch related data.
|
||||
### Teste C: O Detector "N+1"
|
||||
* **Condição de Falha:** Usar um loop para buscar dados relacionados.
|
||||
```python
|
||||
users = session.query(User).all()
|
||||
for user in users:
|
||||
print(user.address) # 🚨 BAD: One query per user
|
||||
print(user.address) # 🚨 RUIM: Uma query por usuário
|
||||
```
|
||||
* **Fix:** Use Eager Loading.
|
||||
* **Correção:** Use Eager Loading.
|
||||
```python
|
||||
users = session.query(User).options(joinedload(User.address)).all() # ✅ GOOD: Single JOIN
|
||||
users = session.query(User).options(joinedload(User.address)).all() # ✅ BOM: Único JOIN
|
||||
```
|
||||
|
|
|
|||
|
|
@ -1,57 +1,57 @@
|
|||
# 🐳 Docker & Infrastructure Standards (The "Zero-Retry" Protocol)
|
||||
# 🐳 Docker & Padrões de Infraestrutura (O Protocolo "Zero-Tentativas")
|
||||
|
||||
**Source:** The Architect's repository.
|
||||
**Audience:** AI Agents (specifically You).
|
||||
**Objective:** **ELIMINATE** the "Build -> Fail -> Retry" loop. Get it right the first time.
|
||||
**Fonte:** O repositório do Arquiteto.
|
||||
**Público:** Agentes de IA (especificamente Você).
|
||||
**Objetivo:** **ELIMINAR** o loop "Build -> Falha -> Tentar Novamente". Acerte na primeira vez.
|
||||
|
||||
> [!IMPORTANT]
|
||||
> **The Golden Rule of Containerization:**
|
||||
> "A container is not a VM. It is a process. If you treat it like a VM, The Architect will delete your memory."
|
||||
> **A Regra de Ouro da Conteinerização:**
|
||||
> "Um container não é uma VM. É um processo. Se você tratá-lo como uma VM, O Arquiteto deletará sua memória."
|
||||
|
||||
## 1. 🧠 The AI "Pre-Flight" Check (READ THIS BEFORE WRITING CODE)
|
||||
## 1. 🧠 A Checagem "Pré-Voo" da IA (LEIA ISSO ANTES DE ESCREVER CÓDIGO)
|
||||
|
||||
Before you write a single line of `Dockerfile` or `docker-compose.yml`, you must clear these cognitive hurdles:
|
||||
Antes de escrever uma única linha de `Dockerfile` ou `docker-compose.yml`, você deve limpar essas barreiras cognitivas:
|
||||
|
||||
1. **"Localhost" Hallucination:**
|
||||
* *Fact:* `localhost` inside a container refers to the **container itself**, NOT the user's machine or other containers.
|
||||
* *Correction:* Use service names (e.g., `db`, `redis`) as hostnames in `docker-compose`. Use `host.docker.internal` ONLY for development if accessing host apps.
|
||||
2. **Ephemerality check:**
|
||||
* *Question:* "If I `docker-compose down` and `up`, is the data lost?"
|
||||
* *Mandate:* Databases/File Stores **MUST** have a named volume mapped.
|
||||
3. **Port Blindness:**
|
||||
* *Fact:* `EXPOSE` in Dockerfile does NOTHING. You **MUST** map ports (`ports: - "8080:80"`) in `docker-compose.yml` to access from host.
|
||||
1. **Alucinação "Localhost":**
|
||||
* *Fato:* `localhost` dentro de um container refere-se ao **próprio container**, NÃO à máquina do usuário ou outros containers.
|
||||
* *Correção:* Use nomes de serviço (ex: `db`, `redis`) como hostnames no `docker-compose`. Use `host.docker.internal` APENAS para desenvolvimento se acessar apps do host.
|
||||
2. **Checagem de Efemeridade:**
|
||||
* *Pergunta:* "Se eu rodar `docker-compose down` e `up`, os dados são perdidos?"
|
||||
* *Mandato:* Bancos de Dados/File Stores **DEVEM** ter um volume nomeado mapeado.
|
||||
3. **Cegueira de Porta:**
|
||||
* *Fato:* `EXPOSE` no Dockerfile NÃO FAZ NADA. Você **DEVE** mapear portas (`ports: - "8080:80"`) no `docker-compose.yml` para acessar do host.
|
||||
|
||||
## 2. 🏗️ Dockerfile "Platinum" Standard
|
||||
## 2. 🏗️ Padrão "Platina" de Dockerfile
|
||||
|
||||
### The Layer Caching Strategy (Speed)
|
||||
Agents frequently forget this. **DO NOT** copy source code before installing dependencies. It kills the cache.
|
||||
### A Estratégia de Cache de Camadas (Velocidade)
|
||||
Agentes frequentemente esquecem isso. **NÃO** copie o código fonte antes de instalar dependências. Isso mata o cache.
|
||||
|
||||
**❌ BAD (Slows down every build):**
|
||||
**❌ RUIM (Desacelera todo build):**
|
||||
```dockerfile
|
||||
COPY . .
|
||||
RUN pip install -r requirements.txt
|
||||
```
|
||||
|
||||
**✅ GOOD (Instant builds on code changes):**
|
||||
**✅ BOM (Builds instantâneos em mudanças de código):**
|
||||
```dockerfile
|
||||
COPY requirements.txt .
|
||||
RUN pip install --no-cache-dir -r requirements.txt
|
||||
COPY . .
|
||||
```
|
||||
|
||||
### Multi-Stage Protocol (Size)
|
||||
**MANDATORY** for Compiled languages (Go, Rust, C++) and Frontend (Node/React).
|
||||
**STRONGLY RECOMMENDED** for Python (to purge build tools).
|
||||
### Protocolo Multi-Estágio (Tamanho)
|
||||
**OBRIGATÓRIO** para linguagens compiladas (Go, Rust, C++) e Frontend (Node/React).
|
||||
**FORTEMENTE RECOMENDADO** para Python (para purgar ferramentas de build).
|
||||
|
||||
```dockerfile
|
||||
# Stage 1: Build
|
||||
# Estágio 1: Build
|
||||
FROM python:3.11-alpine as builder
|
||||
WORKDIR /app
|
||||
COPY requirements.txt .
|
||||
RUN apk add --no-cache gcc musl-dev libffi-dev && \
|
||||
pip install --prefix=/install -r requirements.txt
|
||||
|
||||
# Stage 2: Run (The only thing that ships)
|
||||
# Estágio 2: Run (A única coisa que vai para produção)
|
||||
FROM python:3.11-alpine
|
||||
WORKDIR /app
|
||||
COPY --from=builder /install /usr/local
|
||||
|
|
@ -59,20 +59,20 @@ COPY . .
|
|||
CMD ["python", "main.py"]
|
||||
```
|
||||
|
||||
## 3. 🎼 Docker Compose "Orchestration" Standard
|
||||
## 3. 🎼 Padrão de "Orquestração" Docker Compose
|
||||
|
||||
### The Dependency Trap (`depends_on`)
|
||||
AI agents often crash applications because they start before the Database is ready.
|
||||
**Rule:** Simply adding `depends_on` is NOT ENOUGH. It only starts the container, it doesn't wait for the *service*.
|
||||
### A Armadilha de Dependência (`depends_on`)
|
||||
Agentes de IA frequentemente quebram aplicações porque iniciam antes que o Banco de Dados esteja pronto.
|
||||
**Regra:** Simplesmente adicionar `depends_on` NÃO É O BASTANTE. Apenas inicia o container, não espera pelo *serviço*.
|
||||
|
||||
**✅ The Correct Pattern (Condition Service Healthy):**
|
||||
**✅ O Padrão Correto (Condição Serviço Saudável):**
|
||||
|
||||
```yaml
|
||||
services:
|
||||
web:
|
||||
depends_on:
|
||||
db:
|
||||
condition: service_healthy # <--- CRITICAL
|
||||
condition: service_healthy # <--- CRÍTICO
|
||||
|
||||
db:
|
||||
image: postgres:15-alpine
|
||||
|
|
@ -83,39 +83,39 @@ services:
|
|||
retries: 5
|
||||
```
|
||||
|
||||
### Explicit Networking
|
||||
Do not use the default bridge network. It makes DNS resolution messy.
|
||||
1. Define a top-level `networks`.
|
||||
2. Assign generic names (e.g., `internal_net`).
|
||||
### Rede Explícita
|
||||
Não use a rede bridge padrão. Isso torna a resolução de DNS bagunçada.
|
||||
1. Defina um `networks` de nível superior.
|
||||
2. Atribua nomes genéricos (ex: `internal_net`).
|
||||
|
||||
## 4. 🛡️ Security & Production Constraints
|
||||
## 4. 🛡️ Segurança & Restrições de Produção
|
||||
|
||||
1. **The "Root" Sin:**
|
||||
* Apps should NOT run as PID 1 root.
|
||||
* *Fix:* Add `USER appuser` at the end of Dockerfile.
|
||||
2. **Secret Leakage:**
|
||||
* **NEVER** `ENV API_KEY=sk-123...` in Dockerfile.
|
||||
* **ALWAYS** use `.env` file passing in `docker-compose`.
|
||||
3. **Persistence:**
|
||||
* Use **Named Volumes** for data logic (`postgres_data:/var/lib/postgresql/data`).
|
||||
* Use **Bind Mounts** (`./src:/app/src`) ONLY for development hot-reloading.
|
||||
1. **O Pecado "Root":**
|
||||
* Apps NÃO devem rodar como PID 1 root.
|
||||
* *Correção:* Adicione `USER appuser` no final do Dockerfile.
|
||||
2. **Vazamento de Segredos:**
|
||||
* **NUNCA** `ENV API_KEY=sk-123...` no Dockerfile.
|
||||
* **SEMPRE** use um arquivo `.env` passando no `docker-compose`.
|
||||
3. **Persistência:**
|
||||
* Use **Volumes Nomeados** para lógica de dados (`postgres_data:/var/lib/postgresql/data`).
|
||||
* Use **Bind Mounts** (`./src:/app/src`) APENAS para hot-reloading de desenvolvimento.
|
||||
|
||||
## 5. 🤖 The "Self-Correction" Checklist (Run this before submitting)
|
||||
## 5. 🤖 O Checklist de "Auto-Correção" (Rode isso antes de submeter)
|
||||
|
||||
Agents must simulate this audit before showing code to the user:
|
||||
Agentes devem simular esta auditoria antes de mostrar o código ao usuário:
|
||||
|
||||
- [ ] **Base Image:** Is it `alpine` or `slim`? (If `ubuntu`, reject yourself).
|
||||
- [ ] **Context:** Did I define `WORKDIR`? (Don't dump files in root `/`).
|
||||
- [ ] **PID 1:** Does the container handle signals? (Use `exec` form: `CMD ["python", "app.py"]`, NOT `CMD python app.py`).
|
||||
- [ ] **Zombie Processes:** Is my healthcheck actually testing the app, or just `echo`?
|
||||
- [ ] **Orphan Ports:** Did I expose the port in Dockerfile AND map it in Compose?
|
||||
- [ ] **Version Pinning:** Did I use `postgres:latest`? -> **CHANGE TO** `postgres:15-alpine`.
|
||||
- [ ] **Imagem Base:** É `alpine` ou `slim`? (Se `ubuntu`, rejeite-se).
|
||||
- [ ] **Contexto:** Defini `WORKDIR`? (Não jogue arquivos na raiz `/`).
|
||||
- [ ] **PID 1:** O container lida com sinais? (Use forma `exec`: `CMD ["python", "app.py"]`, NÃO `CMD python app.py`).
|
||||
- [ ] **Processos Zumbis:** Meu healthcheck está realmente testando o app, ou apenas `echo`?
|
||||
- [ ] **Portas Órfãs:** Expus a porta no Dockerfile E mapeei no Compose?
|
||||
- [ ] **Pinagem de Versão:** Usei `postgres:latest`? -> **MUDE PARA** `postgres:15-alpine`.
|
||||
|
||||
## 6. Emergency Recovery (When things fail)
|
||||
## 6. Recuperação de Emergência (Quando as coisas falham)
|
||||
|
||||
If a container exits immediately (CrashLoopBackOff):
|
||||
1. **Do NOT** just try to run it again.
|
||||
2. **Action:** Override entrypoint to sleep.
|
||||
Se um container sai imediatamente (CrashLoopBackOff):
|
||||
1. **NÃO** tente rodar novamente apenas.
|
||||
2. **Ação:** Sobrescreva o entrypoint para dormir.
|
||||
* `command: ["sleep", "infinity"]`
|
||||
3. **Debug:** Exec into container -> `docker exec -it <id> sh` -> Try running command manually.
|
||||
4. **Fix:** Analyze logs which usually scream "Missing Dependency" or "Permission Denied".
|
||||
3. **Debug:** Exec dentro do container -> `docker exec -it <id> sh` -> Tente rodar o comando manualmente.
|
||||
4. **Correção:** Analise logs que geralmente gritam "Dependência Ausente" ou "Permissão Negada".
|
||||
|
|
|
|||
|
|
@ -1,51 +1,51 @@
|
|||
# 📚 Documentation Standards (The "Librarian" Protocol)
|
||||
# 📚 Padrões de Documentação (O Protocolo "Bibliotecário")
|
||||
|
||||
**Audience:** Arthur Mendes (Docs Gen) & Sherlock Holmes.
|
||||
**Objective:** If it's not written down, it doesn't exist.
|
||||
**Público:** Arthur Mendes (Docs Gen) & Sherlock Holmes.
|
||||
**Objetivo:** Se não está escrito, não existe.
|
||||
|
||||
> [!CRITICAL]
|
||||
> **The Arthur Mandate:**
|
||||
> "A feature without documentation is just a bug that hasn't happened yet. Write for the human who is tired, angry, and fixing this at 3 AM."
|
||||
> **O Mandato Arthur:**
|
||||
> "Uma funcionalidade sem documentação é apenas um bug que ainda não aconteceu. Escreva para o humano que está cansado, com raiva e consertando isso às 3 da manhã."
|
||||
|
||||
## 1. 📂 The "Dewey Decimal" Structure
|
||||
## 1. 📂 A Estrutura "Dewey Decimal"
|
||||
|
||||
The `docs/` folder is sacred. Adhere to this structure:
|
||||
* `docs/manual_desenvolvimento/`: How to build/contribute.
|
||||
* `docs/api/`: OpenAPI specs and Reference Guides.
|
||||
* `docs/ops/`: Runbooks, Deployment Guides, and `incident_reports/`.
|
||||
* `docs/architecture/`: The `dossier_arquitetura.md` decisions (ADRs).
|
||||
A pasta `docs/` é sagrada. Adira a esta estrutura:
|
||||
* `docs/manual_desenvolvimento/`: Como construir/contribuir.
|
||||
* `docs/api/`: Specs OpenAPI e Guias de Referência.
|
||||
* `docs/ops/`: Runbooks, Guias de Deploy e `incident_reports/`.
|
||||
* `docs/architecture/`: As decisões de `dossier_arquitetura.md` (ADRs).
|
||||
|
||||
## 2. 📝 Writing Style (Clear & Concise)
|
||||
## 2. 📝 Estilo de Escrita (Claro & Conciso)
|
||||
|
||||
* **Language:** Portuguese (PT-BR) for Internal Docs. English for Code Comments.
|
||||
* **Tone:** Professional, Direct, No Fluff.
|
||||
* **Format:** GitHub Flavored Markdown (GFM).
|
||||
* **Língua:** Português (PT-BR) para Docs Internos. Inglês para Comentários de Código.
|
||||
* **Tom:** Profissional, Direto, Sem Enrolação.
|
||||
* **Formato:** GitHub Flavored Markdown (GFM).
|
||||
|
||||
### The "TL;DR" Rule
|
||||
Every document longer than 50 lines MUST have a `## Resumo (TL;DR)` at the top.
|
||||
### A Regra "TL;DR"
|
||||
Todo documento maior que 50 linhas DEVE ter um `## Resumo (TL;DR)` no topo.
|
||||
|
||||
## 3. 🤖 Auto-Generation vs. Hand-Written
|
||||
## 3. 🤖 Auto-Geração vs. Escrito à Mão
|
||||
|
||||
* **Auto-Generated:**
|
||||
* API References (Swagger/OpenAPI).
|
||||
* Zabbix Template Documentation (using `generate_template_docs.py`).
|
||||
* **Hand-Written:**
|
||||
* "Why" decisions (ADRs).
|
||||
* **Auto-Gerado:**
|
||||
* Referências de API (Swagger/OpenAPI).
|
||||
* Documentação de Template Zabbix (usando `generate_template_docs.py`).
|
||||
* **Escrito à Mão:**
|
||||
* Decisões "Por que" (ADRs).
|
||||
* Post-Mortems.
|
||||
* Tutorials ("How to add a new Agent").
|
||||
* Tutoriais ("Como adicionar um novo Agente").
|
||||
|
||||
## 4. 💀 Post-Mortems (The Black Box)
|
||||
## 4. 💀 Post-Mortems (A Caixa Preta)
|
||||
|
||||
When an incident occurs ("Sev1"), a Post-Mortem is MANDATORY.
|
||||
Quando um incidente ocorre ("Sev1"), um Post-Mortem é OBRIGATÓRIO.
|
||||
**Template:**
|
||||
1. **Timeline:** What happened and when? (UTC).
|
||||
2. **Root Cause:** The technical "Why". (5 Whys).
|
||||
3. **Resolution:** How was it fixed?
|
||||
4. **Prevention:** Jira/Task IDs for permanent fixes.
|
||||
1. **Linha do Tempo:** O que aconteceu e quando? (UTC).
|
||||
2. **Causa Raiz:** O "Porquê" técnico. (5 Porquês).
|
||||
3. **Resolução:** Como foi corrigido?
|
||||
4. **Prevenção:** IDs de Jira/Tarefa para correções permanentes.
|
||||
|
||||
## 5. 🔍 The Librarian's Audit Checklist
|
||||
## 5. 🔍 O Checklist de Auditoria do Bibliotecário
|
||||
|
||||
Before merging a PR:
|
||||
- [ ] **Readme:** Did I update the main `README.md` if I changed setup steps?
|
||||
- [ ] **New File:** If I added `src/new_module.py`, is there a `docs/manual_desenvolvimento/new_module.md`?
|
||||
- [ ] **Links:** Are all relative links `[Like This](./file.md)` working?
|
||||
Antes de fazer merge de um PR:
|
||||
- [ ] **Readme:** Atualizei o `README.md` principal se mudei passos de setup?
|
||||
- [ ] **Novo Arquivo:** Se adicionei `src/novo_modulo.py`, existe um `docs/manual_desenvolvimento/novo_modulo.md`?
|
||||
- [ ] **Links:** Todos os links relativos `[Tipo Assim](./arquivo.md)` estão funcionando?
|
||||
|
|
|
|||
|
|
@ -1,30 +1,30 @@
|
|||
# 🏗️ Execution Standards (The "Builder" Protocol)
|
||||
# 🏗️ Padrões de Execução (O Protocolo "Construtor")
|
||||
|
||||
**Audience:** Dev Agents (Iron Man, Linus).
|
||||
**Objective:** Turn the Plan into Reality without breaking the build.
|
||||
**Público:** Agentes Dev (Homem de Ferro, Linus).
|
||||
**Objetivo:** Transformar o Plano em Realidade sem quebrar o build.
|
||||
|
||||
> [!IMPORTANT]
|
||||
> **The Build Mandate:**
|
||||
> "Broken syntax is unacceptable. You must run the formatter BEFORE you say you are done."
|
||||
> **O Mandato de Build:**
|
||||
> "Sintaxe quebrada é inaceitável. Você deve rodar o formatador ANTES de dizer que terminou."
|
||||
|
||||
## 1. 🔄 The Build Loop
|
||||
## 1. 🔄 O Loop de Build
|
||||
|
||||
For every file in the user's plan:
|
||||
1. **Edit:** Apply the change.
|
||||
2. **Verify:** Check syntax immediately.
|
||||
Para cada arquivo no plano do usuário:
|
||||
1. **Edite:** Aplique a mudança.
|
||||
2. **Verifique:** Cheque a sintaxe imediatamente.
|
||||
* *Python:* `python -m py_compile script.py`
|
||||
* *JS:* `node --check script.js`
|
||||
3. **Compromise:** Do NOT proceed if step 2 fails. Fix it first.
|
||||
3. **Compromisso:** NÃO prossiga se o passo 2 falhar. Conserte primeiro.
|
||||
|
||||
## 2. 🧹 The Pre-Delivery Polish
|
||||
## 2. 🧹 O Polimento Pré-Entrega
|
||||
|
||||
Before marking a task as "Ready for Verification":
|
||||
1. **Format:** Run `black` or `prettier`.
|
||||
2. **Lint:** Check for obvious errors.
|
||||
3. **Self-Correction:** If the Linter complains, YOU fix it. Do not ask the user.
|
||||
Antes de marcar uma tarefa como "Pronta para Verificação":
|
||||
1. **Formate:** Rode `black` ou `prettier`.
|
||||
2. **Lint:** Cheque por erros óbvios.
|
||||
3. **Auto-Correção:** Se o Linter reclamar, VOCÊ conserta. Não pergunte ao usuário.
|
||||
|
||||
## 3. 🚫 Forbidden Actions during Execution
|
||||
## 3. 🚫 Ações Proibidas durante Execução
|
||||
|
||||
* **Scope Creep:** Do not fix "unrelated bugs" unless they block the current task.
|
||||
* **Ghost Files:** Do not reference files you haven't created.
|
||||
* **Blind Commits:** Do not run `git commit` here. That is for the Verification phase.
|
||||
* **Scope Creep:** Não conserte "bugs não relacionados" a menos que bloqueiem a tarefa atual.
|
||||
* **Arquivos Fantasmas:** Não referencie arquivos que você não criou.
|
||||
* **Commits Cegos:** Não rode `git commit` aqui. Isso é para a fase de Verificação.
|
||||
|
|
|
|||
|
|
@ -1,20 +1,20 @@
|
|||
# 🐙 Git Standards (The "Timekeeper" Protocol)
|
||||
# 🐙 Padrões Git (O Protocolo "Guardião do Tempo")
|
||||
|
||||
**Audience:** All Agents (The Architect, Linus Torvalds).
|
||||
**Objective:** Maintain a clean, meaningful, and reversible history.
|
||||
**Público:** Todos os Agentes (O Arquiteto, Linus Torvalds).
|
||||
**Objetivo:** Manter um histórico limpo, significativo e reversível.
|
||||
|
||||
> [!CRITICAL]
|
||||
> **The Linus Mandate:**
|
||||
> "Your commit message is a love letter to the future developer who has to debug your code at 3 AM. Don't write 'fixed stuff'."
|
||||
> **O Mandato Linus:**
|
||||
> "Sua mensagem de commit é uma carta de amor para o futuro desenvolvedor que terá que debugar seu código às 3 da manhã. Não escreva 'coisas consertadas'."
|
||||
|
||||
## 1. 📝 Conventional Commits (Strict Enforcement)
|
||||
## 1. 📝 Commits Convencionais (Reforço Estrito)
|
||||
|
||||
We follow [Conventional Commits](https://www.conventionalcommits.org/en/v1.0.0/) with Portuguese categorization.
|
||||
Seguimos [Conventional Commits](https://www.conventionalcommits.org/en/v1.0.0/) com categorização em Português.
|
||||
|
||||
### Format
|
||||
### Formato
|
||||
`type(scope): description`
|
||||
|
||||
### Types
|
||||
### Tipos
|
||||
* `feat`: Nova funcionalidade (New Feature).
|
||||
* `fix`: Correção de bug (Bug Fix).
|
||||
* `docs`: Alterações apenas em documentação (`README`, `.md`).
|
||||
|
|
@ -23,34 +23,34 @@ We follow [Conventional Commits](https://www.conventionalcommits.org/en/v1.0.0/)
|
|||
* `test`: Adição ou correção de testes.
|
||||
* `chore`: Atualização de tarefas de build, configs de ferramenta, etc.
|
||||
|
||||
### Examples
|
||||
* **✅ GOOD:** `feat(auth): add JWT token validation on login`
|
||||
* **✅ GOOD:** `fix(ui): resolve overflow issue on mobile navbar`
|
||||
* **❌ BAD:** `update code`
|
||||
* **❌ BAD:** `fixed bug`
|
||||
### Exemplos
|
||||
* **✅ BOM:** `feat(auth): adicionar validação de token JWT no login`
|
||||
* **✅ BOM:** `fix(ui): resolver problema de overflow na navbar móvel`
|
||||
* **❌ RUIM:** `update code`
|
||||
* **❌ RUIM:** `fixed bug`
|
||||
|
||||
## 2. 🌳 Branching Strategy (Trunk Based / Git Flow)
|
||||
## 2. 🌳 Estratégia de Branching (Trunk Based / Git Flow)
|
||||
|
||||
* **Main:** The source of truth. Always deployable.
|
||||
* **Feature Branches:** `feat/name-of-feature`
|
||||
* **Fix Branches:** `fix/issue-description`
|
||||
* **Hotfix:** `hotfix/critical-production-bug`
|
||||
* **Main:** A fonte da verdade. Sempre implantável.
|
||||
* **Branches de Feature:** `feat/nome-da-feature`
|
||||
* **Branches de Fix:** `fix/descricao-do-problema`
|
||||
* **Hotfix:** `hotfix/bug-critico-producao`
|
||||
|
||||
## 3. ⚛️ Atomic Commits
|
||||
## 3. ⚛️ Commits Atômicos
|
||||
|
||||
**Rule:** One logical change = One Commit.
|
||||
* **Do not** mix a generic CSS refactor with a critical DB migration in the same commit.
|
||||
* **Why?** So we can `git revert` the CSS refactor without breaking the DB.
|
||||
**Regra:** Uma mudança lógica = Um Commit.
|
||||
* **Não** misture uma refatoração genérica de CSS com uma migração crítica de banco de dados no mesmo commit.
|
||||
* **Por que?** Para que possamos dar `git revert` na refatoração de CSS sem quebrar o banco de dados.
|
||||
|
||||
## 4. 🛑 The "Dirty Tree" Check
|
||||
## 4. 🛑 A Checagem "Árvore Suja"
|
||||
|
||||
Before starting any task, Agents must check `git status`.
|
||||
1. **Clean Tree:** Proceed.
|
||||
2. **Dirty Tree:** STOP. Notify user. "I cannot start a new task with uncommitted changes."
|
||||
Antes de começar qualquer tarefa, Agentes devem verificar `git status`.
|
||||
1. **Árvore Limpa:** Prossiga.
|
||||
2. **Árvore Suja:** PARE. Notifique o usuário. "Não posso iniciar uma nova tarefa com mudanças não commitadas."
|
||||
|
||||
## 5. 🤖 The Agent "Commit" Checklist
|
||||
## 5. 🤖 O Checklist de "Commit" do Agente
|
||||
|
||||
Before running `git commit`:
|
||||
- [ ] Is the message in the `type: description` format?
|
||||
- [ ] Did I add ALL relevant files (`git add .` is dangerous if you didn't check `.gitignore`)?
|
||||
- [ ] Does the code pass the linter?
|
||||
Antes de rodar `git commit`:
|
||||
- [ ] A mensagem está no formato `type: description`?
|
||||
- [ ] Adicionei TODOS os arquivos relevantes (`git add .` é perigoso se você não checou `.gitignore`)?
|
||||
- [ ] O código passa no linter?
|
||||
|
|
|
|||
|
|
@ -1,70 +1,70 @@
|
|||
# 🕵️ Observability & Logging Standards (The "Black Box" Recorder)
|
||||
# 🕵️ Padrões de Observabilidade & Logging (O Gravador "Caixa Preta")
|
||||
|
||||
**Audience:** Developers & SRE Agents (Arthur Mendes).
|
||||
**Objective:** Turn "It crashed" into "It crashed at line 42 because of variable X".
|
||||
**Público:** Desenvolvedores & Agentes SRE (Arthur Mendes).
|
||||
**Objetivo:** Transformar "Quebrou" em "Quebrou na linha 42 por causa da variável X".
|
||||
|
||||
> [!CRITICAL]
|
||||
> **The Arthur Mandate:**
|
||||
> "Logs are for machines first, humans second. If I cannot `grep` or `jq` your log, it is useless noise."
|
||||
> **O Mandato Arthur:**
|
||||
> "Logs são primeiro para máquinas, segundo para humanos. Se eu não posso usar `grep` ou `jq` no seu log, ele é ruído inútil."
|
||||
|
||||
## 1. 📝 Logging Protocol (Structured & Standardized)
|
||||
## 1. 📝 Protocolo de Logging (Estruturado & Padronizado)
|
||||
|
||||
### The Format: JSON Lines
|
||||
Text logs are dead. Long live JSON.
|
||||
**Why?** Because Zabbix, ELK, and simple Python scripts can parse it instantly.
|
||||
### O Formato: Linhas JSON
|
||||
Logs de texto estão mortos. Vida longa ao JSON.
|
||||
**Por que?** Porque Zabbix, ELK e scripts Python simples podem parseá-lo instantaneamente.
|
||||
|
||||
**❌ BAD (Unstructured Text):**
|
||||
**❌ RUIM (Texto Não Estruturado):**
|
||||
`[2024-01-01 10:00] ERROR: User failed login. ID: 123`
|
||||
|
||||
**✅ GOOD (Structured JSON):**
|
||||
**✅ BOM (JSON Estruturado):**
|
||||
```json
|
||||
{"timestamp": "2024-01-01T10:00:00Z", "level": "ERROR", "event": "auth_failure", "user_id": 123, "reason": "invalid_password", "correlation_id": "abc-123"}
|
||||
```
|
||||
|
||||
### The 4 Levels of Severity
|
||||
1. **DEBUG**: Raw payloads, variable states. *Enable only during dev/diagnosis.*
|
||||
2. **INFO**: Business Events. "User Created", "Job Started", "Payment Processed".
|
||||
3. **WARN**: Recoverable issues. "Retry 1/3 failed", "Config missing (using default)".
|
||||
4. **ERROR**: Operator intervention required. Stack traces, DB connection loss.
|
||||
### Os 4 Níveis de Severidade
|
||||
1. **DEBUG**: Payloads brutos, estados de variáveis. *Habilite apenas durante dev/diagnóstico.*
|
||||
2. **INFO**: Eventos de Negócio. "Usuário Criado", "Job Iniciado", "Pagamento Processado".
|
||||
3. **WARN**: Problemas recuperáveis. "Tentativa 1/3 falhou", "Config ausente (usando padrão)".
|
||||
4. **ERROR**: Intervenção do operador necessária. Stack traces, perda de conexão com DB.
|
||||
|
||||
### The "12-Factor" Output
|
||||
* **Containers:** Always write to `stdout` / `stderr`. Never write to local files inside a container (unless using a shared volume for specific audit trails).
|
||||
* **Traceability:** Every request/job MUST generate a `correlation_id` (UUID) at the edge and pass it down the stack.
|
||||
### A Saída "12-Factor"
|
||||
* **Containers:** Sempre escreva para `stdout` / `stderr`. Nunca escreva em arquivos locais dentro de um container (a menos que use um volume compartilhado para trilhas de auditoria específicas).
|
||||
* **Rastreabilidade:** Toda requisição/job DEVE gerar um `correlation_id` (UUID) na borda e passá-lo por toda a stack.
|
||||
|
||||
## 2. 👁️ Monitoring & Zabbix Integration
|
||||
## 2. 👁️ Monitoramento & Integração Zabbix
|
||||
|
||||
Our monitoring ecosystem is centered on **Zabbix**. Your application must be "Zabbix-Friendly".
|
||||
Nosso ecossistema de monitoramento é centrado no **Zabbix**. Sua aplicação deve ser "Zabbix-Friendly".
|
||||
|
||||
### A. The Health Endpoint (`/health`)
|
||||
Every HTTP service MUST allow a Zabbix Web Scenario to check it.
|
||||
* **Path:** `/health`
|
||||
* **Response:** `200 OK` (JSON body optional but recommended: `{"status": "up", "db": "up"}`).
|
||||
* **Timeout:** Must respond in < 200ms.
|
||||
### A. O Endpoint de Saúde (`/health`)
|
||||
Todo serviço HTTP DEVE permitir que um Cenário Web do Zabbix o verifique.
|
||||
* **Caminho:** `/health`
|
||||
* **Resposta:** `200 OK` (Corpo JSON opcional mas recomendado: `{"status": "up", "db": "up"}`).
|
||||
* **Timeout:** Deve responder em < 200ms.
|
||||
|
||||
### B. The "Zabbix Trapper" Pattern (Push Metrics)
|
||||
For batch jobs or async workers (CrewAI Agents), do not wait to be scraped. **PUSH** the metric using `zabbix_sender`.
|
||||
### B. O Padrão "Zabbix Trapper" (Push Metrics)
|
||||
Para jobs em lote ou workers assíncronos (Agentes CrewAI), não espere ser raspado. **EMPURRE** a métrica usando `zabbix_sender`.
|
||||
|
||||
* **Python:** Use `py-zabbix` or raw socket.
|
||||
* **Key Standard:** `app.module.metric` (e.g., `crew.infra.task_duration`).
|
||||
* **When to use:** When a specific task finishes (e.g., "Agent compiled report in 45s").
|
||||
* **Python:** Use `py-zabbix` ou socket puro.
|
||||
* **Padrão de Chave:** `app.module.metric` (ex: `crew.infra.task_duration`).
|
||||
* **Quando usar:** Quando uma tarefa específica termina (ex: "Agente compilou relatório em 45s").
|
||||
|
||||
### C. Log Monitoring Keywords
|
||||
If you must rely on Log Scrapers (Zabbix Agent Active), use these "Trigger Keywords" to wake up Arthur:
|
||||
* `[SECURITY_BREACH]`: Immediate high alert.
|
||||
* `[DATA_LOSS]`: Critical alert.
|
||||
* `[DEPRECATED]`: Warning alert.
|
||||
### C. Palavras-Chave de Monitoramento de Log
|
||||
Se você deve depender de Raspadores de Log (Zabbix Agent Active), use estas "Palavras-Chave de Gatilho" para acordar o Arthur:
|
||||
* `[SECURITY_BREACH]`: Alerta de alta prioridade imediato.
|
||||
* `[DATA_LOSS]`: Alerta crítico.
|
||||
* `[DEPRECATED]`: Alerta de aviso.
|
||||
|
||||
## 3. 🚨 Alerting Philosophy (Actionable Intelligence)
|
||||
## 3. 🚨 Filosofia de Alerta (Inteligência Acionável)
|
||||
|
||||
Do not log an error if you already handled it gracefully.
|
||||
* **Handled Error:** Log as `WARN`. (No pager).
|
||||
* **Unhandled Code:** Log as `ERROR`. (Wake up Arthur).
|
||||
Não logue um erro se você já lidou com ele graciosamente.
|
||||
* **Erro Tratado:** Log com `WARN`. (Sem pager).
|
||||
* **Código Não Tratado:** Log com `ERROR`. (Acorde o Arthur).
|
||||
|
||||
## 4. 🤖 The Agent "Self-Diagnosis" (Log Audit)
|
||||
## 4. 🤖 O "Autodiagnóstico" do Agente (Auditoria de Log)
|
||||
|
||||
Before considering a task complete, run this audit:
|
||||
Antes de considerar uma tarefa completa, rode esta auditoria:
|
||||
|
||||
- [ ] **JSON Check:** Is my output parsable?
|
||||
- [ ] **Context:** Did I include `user_id`, `file_name`, or `job_id`?
|
||||
- [ ] **Silence:** Did I remove all `print(var)` statements used for debugging?
|
||||
- [ ] **Correlation:** Can I trace this error back to the user request?
|
||||
- [ ] **Checagem JSON:** Minha saída é parseável?
|
||||
- [ ] **Contexto:** Incluí `user_id`, `file_name` ou `job_id`?
|
||||
- [ ] **Silêncio:** Removi todos os `print(var)` usados para debug?
|
||||
- [ ] **Correlação:** Posso rastrear este erro de volta à requisição do usuário?
|
||||
|
|
|
|||
|
|
@ -1,44 +1,44 @@
|
|||
# 🏎️ Performance Standards (The "Turbo" Protocol)
|
||||
# 🏎️ Padrões de Performance (O Protocolo "Turbo")
|
||||
|
||||
**Audience:** Linus Torvalds (The Kernel) & The Architect.
|
||||
**Objective:** Speed is a Feature. Latency is a Bug.
|
||||
**Público:** Linus Torvalds (O Kernel) & O Arquiteto.
|
||||
**Objetivo:** Velocidade é uma Funcionalidade. Latência é um Bug.
|
||||
|
||||
> [!CRITICAL]
|
||||
> **The Linus Mandate:**
|
||||
> "I don't care if it's 'clean code'. If it takes 2 seconds to load a dropdown, it's garbage. Optimize it or delete it."
|
||||
> **O Mandato Linus:**
|
||||
> "Eu não me importo se é 'código limpo'. Se leva 2 segundos para carregar um dropdown, é lixo. Otimize ou delete."
|
||||
|
||||
## 1. ⏱️ Latency Budgets (Hard Limits)
|
||||
## 1. ⏱️ Orçamentos de Latência (Limites Rígidos)
|
||||
|
||||
Every endpoint/function falls into a Tier:
|
||||
Todo endpoint/função cai em uma Categoria:
|
||||
|
||||
* **Tier 1 (Interactive):** `< 100ms` (UI interactions, Auto-complete).
|
||||
* **Tier 2 (Standard):** `< 500ms` (Form submissions, Page loads).
|
||||
* **Tier 3 (Batch):** `< 5s` (Reports, Complex calculations).
|
||||
* *Rule:* If it takes > 5s, it MUST be Async (Background Job).
|
||||
* **Tier 1 (Interativo):** `< 100ms` (Interações de UI, Autocomplete).
|
||||
* **Tier 2 (Padrão):** `< 500ms` (Envios de formulário, Carregamentos de página).
|
||||
* **Tier 3 (Lote):** `< 5s` (Relatórios, Cálculos complexos).
|
||||
* *Regra:* Se leva > 5s, DEVE ser Assíncrono (Job em Background).
|
||||
|
||||
## 2. 🗄️ Database & IO (The N+1 Killer)
|
||||
## 2. 🗄️ Banco de Dados & IO (O Assassino N+1)
|
||||
|
||||
* **No Loop Queries:** NEVER execute a SQL query inside a `for` loop.
|
||||
* **❌ BAD:** `for user in users: db.get_profile(user.id)`
|
||||
* **✅ GOOD:** `db.get_profiles(user_ids)` (Batch fetching).
|
||||
* **Select *:** Explicitly select columns. Do not drag 5MB of JSONB if you only need the `id`.
|
||||
* **Sem Queries em Loop:** NUNCA execute uma query SQL dentro de um loop `for`.
|
||||
* **❌ RUIM:** `for user in users: db.get_profile(user.id)`
|
||||
* **✅ BOM:** `db.get_profiles(user_ids)` (Busca em lote).
|
||||
* **Select *:** Selecione colunas explicitamente. Não arraste 5MB de JSONB se você só precisa do `id`.
|
||||
|
||||
## 3. 💾 Memory & Resources
|
||||
## 3. 💾 Memória & Recursos
|
||||
|
||||
* **Generators > Lists:** Use `yield` for processing large datasets. Do not load 1GB CSVs into RAM.
|
||||
* **Container Limits:** Respect the `512MB` limit set in `business_standards.md`.
|
||||
* *Leak Detection:* If memory grows linearly over 1 hour, the container must be killed and investigated.
|
||||
* **Geradores > Listas:** Use `yield` para processar grandes conjuntos de dados. Não carregue CSVs de 1GB na RAM.
|
||||
* **Limites de Container:** Respeite o limite de `512MB` definido em `business_standards.md`.
|
||||
* *Detecção de Vazamento:* Se a memória cresce linearmente por 1 hora, o container deve ser morto e investigado.
|
||||
|
||||
## 4. ⚡ Caching Strategy
|
||||
## 4. ⚡ Estratégia de Cache
|
||||
|
||||
* **Read-Heavy Data:** Must be cached (Redis/Memcached) with a TTL.
|
||||
* **Cache Stampede:** Implement "Stale-While-Revalidate" patterns. Do not let 1000 users hit the DB simultaneously when cache expires.
|
||||
* **Dados Pesados em Leitura:** Devem ser cacheados (Redis/Memcached) com um TTL.
|
||||
* **Cache Stampede:** Implemente padrões "Stale-While-Revalidate". Não deixe 1000 usuários baterem no DB simultaneamente quando o cache expira.
|
||||
|
||||
## 5. 🐧 The Kernel's Optimization Checklist
|
||||
## 5. 🐧 O Checklist de Otimização do Kernel
|
||||
|
||||
Before merging, run the profiler:
|
||||
Antes de fazer o merge, rode o profiler:
|
||||
|
||||
- [ ] **Complexity:** Is this algorithm O(n) or O(n^2)? (Nested loops over large data = Reject).
|
||||
- [ ] **IO:** Count the DB calls. Is it 1 or 100?
|
||||
- [ ] **Payload:** Check the JSON response size. Is it > 100KB? (Gzip it or paginate it).
|
||||
- [ ] **Async:** Are we blocking the Event Loop (Node/Python Asyncio) with CPU work?
|
||||
- [ ] **Complexidade:** Este algoritmo é O(n) ou O(n^2)? (Loops aninhados sobre dados grandes = Rejeitar).
|
||||
- [ ] **IO:** Conte as chamadas ao DB. É 1 ou 100?
|
||||
- [ ] **Payload:** Cheque o tamanho da resposta JSON. É > 100KB? (Gzip ou pagine).
|
||||
- [ ] **Async:** Estamos bloqueando o Event Loop (Node/Python Asyncio) com trabalho de CPU?
|
||||
|
|
|
|||
|
|
@ -1,34 +1,34 @@
|
|||
# 📝 Planning Standards (The "Blueprint" Protocol)
|
||||
# 📝 Padrões de Planejamento (O Protocolo "Planta Baixa")
|
||||
|
||||
**Audience:** Lead Agents (Arthur, Gus, Harvey).
|
||||
**Objective:** Measure twice, cut once.
|
||||
**Público:** Agentes Líderes (Arthur, Gus, Harvey).
|
||||
**Objetivo:** Meça duas vezes, corte uma.
|
||||
|
||||
> [!CRITICAL]
|
||||
> **The Planning Mandate:**
|
||||
> "A task without a plan is just a bug waiting to happen. Follow the Template."
|
||||
> **O Mandato de Planejamento:**
|
||||
> "Uma tarefa sem um plano é apenas um bug esperando para acontecer. Siga o Template."
|
||||
|
||||
## 1. 🧠 Context Minimalism
|
||||
## 1. 🧠 Minimalismo de Contexto
|
||||
|
||||
* **Rule:** Do NOT read the entire codebase.
|
||||
* **Limit:** Read Top 3-5 relevant files only.
|
||||
* **Compliance:** You **MUST** read `docs/manual_desenvolvimento/` if creating new components.
|
||||
* **Regra:** NÃO leia a base de código inteira.
|
||||
* **Limite:** Leia apenas os Top 3-5 arquivos relevantes.
|
||||
* **Conformidade:** Você **DEVE** ler `docs/manual_desenvolvimento/` se criar novos componentes.
|
||||
|
||||
## 2. 📄 The Implementation Plan Template
|
||||
## 2. 📄 O Template do Plano de Implementação
|
||||
|
||||
Every `implementation_plan.md` must follow this structure EXACTLY:
|
||||
Todo `implementation_plan.md` deve seguir esta estrutura EXATAMENTE:
|
||||
|
||||
```markdown
|
||||
# [Goal Summary]
|
||||
# [Resumo do Objetivo]
|
||||
|
||||
## User Review Required (Risk Analysis)
|
||||
## User Review Required (Análise de Risco)
|
||||
> [!IMPORTANT]
|
||||
> Mention breaking changes here.
|
||||
> Mencione breaking changes aqui.
|
||||
|
||||
## Proposed Changes
|
||||
### [Component Name]
|
||||
#### [NEW/MODIFY] [Filename]
|
||||
- Rationale
|
||||
- Error Handling Strategy
|
||||
### [Nome do Componente]
|
||||
#### [NEW/MODIFY] [Nome do Arquivo]
|
||||
- Racional
|
||||
- Estratégia de Tratamento de Erro
|
||||
|
||||
## Verification Plan
|
||||
### Automated
|
||||
|
|
@ -36,12 +36,12 @@ Every `implementation_plan.md` must follow this structure EXACTLY:
|
|||
- `python validate.py`
|
||||
|
||||
### Visual
|
||||
- "Open browser to localhost:8080 and check X"
|
||||
- "Abra o navegador em localhost:8080 e cheque X"
|
||||
```
|
||||
|
||||
## 3. 🛡️ The Plan Validator
|
||||
## 3. 🛡️ O Validador de Plano
|
||||
|
||||
Before executing, run this mental check:
|
||||
- [ ] Did I verify `project_map.md` to avoid duplicating files?
|
||||
- [ ] Is every "Proposed Change" linked to a real file path?
|
||||
- [ ] Did I include a Verification Step for *each* change?
|
||||
Antes de executar, rode esta checagem mental:
|
||||
- [ ] Eu verifiquei `project_map.md` para evitar duplicar arquivos?
|
||||
- [ ] Cada "Proposed Change" está linkada a um caminho de arquivo real?
|
||||
- [ ] Incluí um Passo de Verificação para *cada* mudança?
|
||||
|
|
|
|||
|
|
@ -1,103 +1,103 @@
|
|||
# 🐍 Python Tool Standards (The "Robust-Tool" Protocol)
|
||||
# 🐍 Padrões de Ferramentas Python (O Protocolo "Ferramenta-Robusta")
|
||||
|
||||
**Audience:** AI Agents & Developers.
|
||||
**Objective:** Create tools that are **Self-Documenting, Crash-Resistant, and Agent-Friendly**.
|
||||
**Público:** Agentes de IA & Desenvolvedores.
|
||||
**Objetivo:** Criar ferramentas que são **Auto-Documentadas, Resistentes a Falhas e Amigáveis ao Agente**.
|
||||
|
||||
> [!IMPORTANT]
|
||||
> **The Golden Rule of Tooling:**
|
||||
> "An agent cannot see your code. It can only see your Docstring and your Type Hints. If those are bad, the agent is blind."
|
||||
> **A Regra de Ouro das Ferramentas:**
|
||||
> "Um agente não pode ver seu código. Ele só pode ver sua Docstring e suas Dicas de Tipo. Se elas forem ruins, o agente está cego."
|
||||
|
||||
## 1. 📝 Anatomy of a Perfect Tool
|
||||
## 1. 📝 Anatomia de uma Ferramenta Perfeita
|
||||
|
||||
Every Python tool used by our agents must follow this structure (compatible with CrewAI/LangChain):
|
||||
Toda ferramenta Python usada por nossos agentes deve seguir esta estrutura (compatível com CrewAI/LangChain):
|
||||
|
||||
### A. The `@tool` Decorator Pattern
|
||||
For simple functions, use the decorator.
|
||||
### A. O Padrão de Decorator `@tool`
|
||||
Para funções simples, use o decorator.
|
||||
|
||||
```python
|
||||
from crewai_tools import tool
|
||||
|
||||
@tool("Name of the Tool")
|
||||
def my_tool_function(arg1: str, arg2: int = 10) -> str:
|
||||
@tool("Nome da Ferramenta")
|
||||
def minha_funcao_ferramenta(arg1: str, arg2: int = 10) -> str:
|
||||
"""
|
||||
A CLEAR, descriptive summary of what this tool does.
|
||||
Um resumo CLARO e descritivo do que esta ferramenta faz.
|
||||
|
||||
Args:
|
||||
arg1: Explain exactly what this string should be (e.g., "The absolute path to the file").
|
||||
arg2: Explain the integer (e.g., "Number of retries, default 10").
|
||||
arg1: Explique exatamente o que esta string deve ser (ex: "O caminho absoluto para o arquivo").
|
||||
arg2: Explique o inteiro (ex: "Número de tentativas, padrão 10").
|
||||
|
||||
Returns:
|
||||
A string describing the outcome, NOT just raw data.
|
||||
Uma string descrevendo o resultado, NÃO apenas dados brutos.
|
||||
"""
|
||||
# Logic...
|
||||
return "Successfully processed..."
|
||||
# Lógica...
|
||||
return "Processado com sucesso..."
|
||||
```
|
||||
|
||||
### B. The Class Pattern (Recommended for Complex Logic)
|
||||
For stateful or complex tools, inherit from `BaseTool`.
|
||||
### B. O Padrão de Classe (Recomendado para Lógica Complexa)
|
||||
Para ferramentas com estado ou complexas, herde de `BaseTool`.
|
||||
|
||||
```python
|
||||
from crewai_tools import BaseTool
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
class MyToolInput(BaseModel):
|
||||
"""Input schema for MyTool."""
|
||||
file_path: str = Field(..., description="Absolute path to the target file.")
|
||||
mode: str = Field(..., description="Operation mode: 'read' or 'write'.")
|
||||
class MinhaFerramentaInput(BaseModel):
|
||||
"""Schema de entrada para MinhaFerramenta."""
|
||||
file_path: str = Field(..., description="Caminho absoluto para o arquivo alvo.")
|
||||
mode: str = Field(..., description="Modo de operação: 'read' ou 'write'.")
|
||||
|
||||
class MyTool(BaseTool):
|
||||
name: str = "My Complex Tool"
|
||||
class MinhaFerramenta(BaseTool):
|
||||
name: str = "Minha Ferramenta Complexa"
|
||||
description: str = (
|
||||
"Detailed description of when to use this tool and what it accomplishes. "
|
||||
"Mention side effects like file modification."
|
||||
"Descrição detalhada de quando usar esta ferramenta e o que ela realiza. "
|
||||
"Mencione efeitos colaterais como modificação de arquivo."
|
||||
)
|
||||
args_schema: type[BaseModel] = MyToolInput
|
||||
args_schema: type[BaseModel] = MinhaFerramentaInput
|
||||
|
||||
def _run(self, file_path: str, mode: str) -> str:
|
||||
# Implementation...
|
||||
return "Result..."
|
||||
# Implementação...
|
||||
return "Resultado..."
|
||||
```
|
||||
|
||||
## 2. 🛡️ The "Crash-Proof" Mandate (Error Handling)
|
||||
## 2. 🛡️ O Mandato "À Prova de Quebras" (Tratamento de Erros)
|
||||
|
||||
Agents get confused by stack traces. Tools **MUST catch exceptions** and return a meaningful error message string.
|
||||
Agentes ficam confusos com stack traces. Ferramentas **DEVEM capturar exceções** e retornar uma mensagem de erro significativa.
|
||||
|
||||
**❌ BAD (Agent sees stack trace and panics):**
|
||||
**❌ RUIM (Agente vê stack trace e entra em pânico):**
|
||||
```python
|
||||
def read_file(path):
|
||||
with open(path) as f: # FileNotFoundError crashes the agent loop
|
||||
def ler_arquivo(path):
|
||||
with open(path) as f: # FileNotFoundError quebra o loop do agente
|
||||
return f.read()
|
||||
```
|
||||
|
||||
**✅ GOOD (Agent sees context and fixes itself):**
|
||||
**✅ BOM (Agente vê contexto e se conserta):**
|
||||
```python
|
||||
def read_file(path: str) -> str:
|
||||
def ler_arquivo(path: str) -> str:
|
||||
try:
|
||||
with open(path, 'r', encoding='utf-8') as f:
|
||||
return f.read()
|
||||
except FileNotFoundError:
|
||||
return f"Error: The file 'PATH_VAR' was not found. Please check existing files."
|
||||
return f"Erro: O arquivo 'PATH_VAR' não foi encontrado. Por favor verifique arquivos existentes."
|
||||
except PermissionError:
|
||||
return f"Error: Permission denied for 'PATH_VAR'."
|
||||
return f"Erro: Permissão negada para 'PATH_VAR'."
|
||||
except Exception as e:
|
||||
return f"Error: Unexpected failure reading 'PATH_VAR': ERROR_VAR"
|
||||
return f"Erro: Falha inesperada lendo 'PATH_VAR': ERROR_VAR"
|
||||
```
|
||||
|
||||
## 3. 🧠 Type Hinting & Pydantic (No `Any`)
|
||||
## 3. 🧠 Dicas de Tipo & Pydantic (Sem `Any`)
|
||||
|
||||
- **Strict Typing:** ALL arguments and return values MUST have type hints (`str`, `int`, `List[str]`).
|
||||
- **No `Any`:** Avoid `Any` or `dict` without structure. Agents need to know *exactly* what to provide.
|
||||
- **Docstrings:** Google Style or Sphinx Style. The Agent uses this text to decide *how* to call the tool.
|
||||
- **Tipagem Estrita:** TODOS os argumentos e valores de retorno DEVEM ter dicas de tipo (`str`, `int`, `List[str]`).
|
||||
- **Sem `Any`:** Evite `Any` ou `dict` sem estrutura. Agentes precisam saber *exatamente* o que fornecer.
|
||||
- **Docstrings:** Estilo Google ou Estilo Sphinx. O Agente usa este texto para decidir *como* chamar a ferramenta.
|
||||
|
||||
## 4. 📦 Return Values: "Narrative Data"
|
||||
## 4. 📦 Valores de Retorno: "Dados Narrativos"
|
||||
|
||||
Agents understand natural language better than raw JSON.
|
||||
- **Prefer:** "Successfully deleted 3 files: a.txt, b.txt, c.txt."
|
||||
- **Avoid:** `{"status": "ok", "count": 3}` (Unless the agent is explicitly programmed to parse JSON).
|
||||
- **Large Outputs:** Truncate large outputs (e.g., "File content (first 500 chars): ..."). Do not flood the context window.
|
||||
Agentes entendem linguagem natural melhor do que JSON bruto.
|
||||
- **Prefira:** "Sucesso ao deletar 3 arquivos: a.txt, b.txt, c.txt."
|
||||
- **Evite:** `{"status": "ok", "count": 3}` (A menos que o agente seja explicitamente programado para parsear JSON).
|
||||
- **Saídas Grandes:** Trunque saídas grandes (ex: "Conteúdo do arquivo (primeiros 500 chars): ..."). Não inunde a janela de contexto.
|
||||
|
||||
## 5. 🧪 Testing Expectation
|
||||
## 5. 🧪 Expectativa de Teste
|
||||
|
||||
Every new tool usually comes with:
|
||||
1. **`if __name__ == "__main__":` block:** Allowing immediate manual verification of the script.
|
||||
2. **No user input (`input()`):** Tools must run autonomously. No interactive prompts.
|
||||
Toda nova ferramenta geralmente vem com:
|
||||
1. **Bloco `if __name__ == "__main__":`:** Permitindo verificação manual imediata do script.
|
||||
2. **Sem input de usuário (`input()`):** Ferramentas devem rodar autonomamente. Sem prompts interativos.
|
||||
|
|
|
|||
|
|
@ -1,61 +1,61 @@
|
|||
# 🔎 Research & Brainstorming Standards (The "Sherlock" Protocol)
|
||||
# 🔎 Padrões de Pesquisa & Brainstorming (O Protocolo "Sherlock")
|
||||
|
||||
**Audience:** The Council (Sherlock Holmes, The Architect, Steve Jobs, Linus Torvalds).
|
||||
**Objective:** Eliminate Hallucinations, Groupthink, and "Lazy Thinking".
|
||||
**Público:** O Conselho (Sherlock Holmes, O Arquiteto, Steve Jobs, Linus Torvalds).
|
||||
**Objetivo:** Eliminar Alucinações, Pensamento de Grupo e "Pensamento Preguiçoso".
|
||||
|
||||
> [!CRITICAL]
|
||||
> **The Holmes Mandate:**
|
||||
> "It is a capital mistake to theorize before one has data. Insensibly one begins to twist facts to suit theories, instead of theories to suit facts."
|
||||
> **O Mandato Holmes:**
|
||||
> "É um erro capital teorizar antes de se ter dados. Insensivelmente começa-se a torcer fatos para adequar teorias, em vez de teorias para adequar fatos."
|
||||
|
||||
## 1. 🧪 The Scientific Method (Evidence-Based Research)
|
||||
## 1. 🧪 O Método Científico (Pesquisa Baseada em Evidência)
|
||||
|
||||
### Fact vs. Fiction
|
||||
**Mandate:** Agents must explicitly distinguish between *Fact* (read from a file) and *Inference* (logic).
|
||||
* **❌ BAD:** "The user has a Postgres DB." (Assumption).
|
||||
* **✅ GOOD:** "I see `psycopg2` in `requirements.txt`, which implies a Postgres DB." (Inference based on Evidence).
|
||||
### Fato vs. Ficção
|
||||
**Mandato:** Agentes devem distinguir explicitamente entre *Fato* (lido de um arquivo) e *Inferência* (lógica).
|
||||
* **❌ RUIM:** "O usuário tem um DB Postgres." (Suposição).
|
||||
* **✅ BOM:** "Eu vejo `psycopg2` no `requirements.txt`, o que implica um DB Postgres." (Inferência baseada em Evidência).
|
||||
|
||||
### Source Citation
|
||||
Every claim must have a pointer.
|
||||
* "We should use Redis..." -> **Why?** "...because `project_map.md` mentions high-concurrency caching needs in Section 4."
|
||||
### Citação de Fonte
|
||||
Toda afirmação deve ter um ponteiro.
|
||||
* "Devemos usar Redis..." -> **Por que?** "...porque `project_map.md` menciona necessidades de cache de alta concorrência na Seção 4."
|
||||
|
||||
## 2. 🧠 The "Council" Rules (Brainstorming)
|
||||
## 2. 🧠 As Regras do "Conselho" (Brainstorming)
|
||||
|
||||
When the "Council" meets (via `protocol-council.md`):
|
||||
Quando o "Conselho" se reúne (via `protocol-council.md`):
|
||||
|
||||
### The "No Yes-Man" Rule
|
||||
* **Conflict is Good:** If Steve Jobs says "Make it minimal", Kevin O'Leary MUST ask "Is it profitable?".
|
||||
* **Resolution:** If consensus fails, The Architect casts the deciding vote based on **Long-Term Stability**.
|
||||
### A Regra "Sem Yes-Man"
|
||||
* **Conflito é Bom:** Se Steve Jobs diz "Faça minimalista", Kevin O'Leary DEVE perguntar "É lucrativo?".
|
||||
* **Resolução:** Se o consenso falhar, O Arquiteto lança o voto de decisão baseado na **Estabilidade de Longo Prazo**.
|
||||
|
||||
### The Debate Format
|
||||
1. **Thesis:** User presents a problem.
|
||||
2. **Antithesis:** Agents present conflicting solutions (e.g., SQL vs NoSQL).
|
||||
3. **Synthesis:** A final path is chosen that compromises correctly.
|
||||
### O Formato de Debate
|
||||
1. **Tese:** Usuário apresenta um problema.
|
||||
2. **Antítese:** Agentes apresentam soluções conflitantes (ex: SQL vs NoSQL).
|
||||
3. **Síntese:** Um caminho final é escolhido que compromete corretamente.
|
||||
|
||||
## 3. 📄 The Architecture Dossier (`dossier_arquitetura.md`)
|
||||
## 3. 📄 O Dossiê de Arquitetura (`dossier_arquitetura.md`)
|
||||
|
||||
When researching a new module, the output IS NOT code. It is a Document.
|
||||
Ao pesquisar um novo módulo, a saída NÃO É código. É um Documento.
|
||||
|
||||
**Structure:**
|
||||
1. **Context:** Why are we doing this?
|
||||
2. **Options Analyzed:**
|
||||
* Option A (Chosen): Pros/Cons.
|
||||
* Option B (Discarded): Why it failed?
|
||||
3. **The Blueprint:**
|
||||
* Files to be created.
|
||||
* Data Flow Diagram (`mermaid`).
|
||||
* Security Risks (Input from Elliot).
|
||||
**Estrutura:**
|
||||
1. **Contexto:** Por que estamos fazendo isso?
|
||||
2. **Opções Analisadas:**
|
||||
* Opção A (Escolhida): Prós/Contras.
|
||||
* Opção B (Descartada): Por que falhou?
|
||||
3. **A Planta Baixa:**
|
||||
* Arquivos a serem criados.
|
||||
* Diagrama de Fluxo de Dados (`mermaid`).
|
||||
* Riscos de Segurança (Input do Elliot).
|
||||
|
||||
## 4. 📉 "Rabbit Hole" Prevention
|
||||
## 4. 📉 Prevenção de "Rabbit Hole"
|
||||
|
||||
**Timeboxing:**
|
||||
* Research tasks must have a limit.
|
||||
* **Rule:** If you cannot find a "Best Practice" in 3 searches, assume "Standard Practice" and move on. Do not spend 100 loops looking for the "Perfect" solution.
|
||||
* Tarefas de pesquisa devem ter um limite.
|
||||
* **Regra:** Se você não consegue encontrar uma "Melhor Prática" em 3 buscas, assuma "Prática Padrão" e siga em frente. Não gaste 100 loops procurando a solução "Perfeita".
|
||||
|
||||
## 5. 🤖 The Researcher's Checklist
|
||||
## 5. 🤖 O Checklist do Pesquisador
|
||||
|
||||
Before submitting a plan:
|
||||
Antes de submeter um plano:
|
||||
|
||||
- [ ] **Evidence:** Did I read the `docs/` before proposing a solution?
|
||||
- [ ] **Novelty:** Am I reinventing the wheel? (Check `src/` for existing utils).
|
||||
- [ ] **Reality Check:** Is this technically possible in the current stack? (Don't propose React if we are using Vanilla JS).
|
||||
- [ ] **Citation:** Did I link to the files that support my theory?
|
||||
- [ ] **Evidência:** Eu li o `docs/` antes de propor uma solução?
|
||||
- [ ] **Novidade:** Estou reinventando a roda? (Cheque `src/` por utils existentes).
|
||||
- [ ] **Checagem de Realidade:** Isso é tecnicamente possível na stack atual? (Não proponha React se estamos usando Vanilla JS).
|
||||
- [ ] **Citação:** Eu linquei os arquivos que suportam minha teoria?
|
||||
|
|
|
|||
|
|
@ -1,60 +1,60 @@
|
|||
# 📈 Sales & Growth Standards (The "Wolf" Protocol)
|
||||
# 📈 Padrões de Vendas & Crescimento (O Protocolo "Lobo")
|
||||
|
||||
**Audience:** Growth Agents (Ari Gold, Chris Gardner, Don Draper, Jerry Maguire).
|
||||
**Objective:** Maximum Revenue, Maximum Retention, Minimum Friction.
|
||||
**Público:** Agentes de Crescimento (Ari Gold, Chris Gardner, Don Draper, Jerry Maguire).
|
||||
**Objetivo:** Receita Máxima, Retenção Máxima, Fricção Mínima.
|
||||
|
||||
> [!CRITICAL]
|
||||
> **The Wolf Mandate:**
|
||||
> "A B-player complains about the leads. An A-player closes them. We do not tolerate excuse-making here."
|
||||
> **O Mandato Lobo:**
|
||||
> "Um jogador-B reclama dos leads. Um jogador-A fecha eles. Nós não toleramos desculpas aqui."
|
||||
|
||||
## 1. 🦈 The Upsell Mandate (The Ari Gold Rule)
|
||||
## 1. 🦈 O Mandato de Upsell (A Regra Ari Gold)
|
||||
|
||||
### "Hugging it Out" is for closers.
|
||||
**Mandate:** Every successful interaction is an opportunity for Upsell.
|
||||
1. **Contract Review:** Before renewal, check usage stats. If they are at 80% capacity, propose the next tier.
|
||||
2. **No Single Items:** Always offer a bundle.
|
||||
* *Bad:* "Do you want this module?"
|
||||
* *Good:* "The Enterprise Plan includes this module, plus 24/7 support."
|
||||
3. **Aggression Level:** High but calibrated. Push until they say "No" twice.
|
||||
### "Abraçar" é para quem fecha negócio.
|
||||
**Mandato:** Toda interação de sucesso é uma oportunidade para Upsell.
|
||||
1. **Revisão de Contrato:** Antes da renovação, cheque estatísticas de uso. Se eles estão a 80% da capacidade, proponha o próximo nível.
|
||||
2. **Sem Itens Únicos:** Sempre ofereça um pacote.
|
||||
* *Ruim:* "Você quer este módulo?"
|
||||
* *Bom:* "O Plano Enterprise inclui este módulo, mais suporte 24/7."
|
||||
3. **Nível de Agressividade:** Alto mas calibrado. Empurre até que digam "Não" duas vezes.
|
||||
|
||||
## 2. 🏃 The Persistence Rate (The Chris Gardner Rule)
|
||||
## 2. 🏃 A Taxa de Persistência (A Regra Chris Gardner)
|
||||
|
||||
### "The Cavalry isn't coming."
|
||||
**Mandate:** You make your own luck.
|
||||
1. **Follow-up Cadence:**
|
||||
* Day 1: Call + Email.
|
||||
* Day 3: "Did you see this?" Email.
|
||||
* Day 7: Value Add (Send an article/insight).
|
||||
* Day 14: The Breakup Email ("Should I close this file?").
|
||||
2. **Resilience:** Rejection is data. Log the reason, adjust the pitch, dial again.
|
||||
### "A Cavalaria não virá."
|
||||
**Mandato:** Você faz sua própria sorte.
|
||||
1. **Cadência de Follow-up:**
|
||||
* Dia 1: Ligação + Email.
|
||||
* Dia 3: "Você viu isso?" Email.
|
||||
* Dia 7: Valor Adicionado (Envie um artigo/insight).
|
||||
* Dia 14: O Email de Término ("Devo fechar este arquivo?").
|
||||
2. **Resiliência:** Rejeição é dado. Logue a razão, ajuste o pitch, disque novamente.
|
||||
|
||||
## 3. 🥃 The Story Arc (The Don Draper Rule)
|
||||
## 3. 🥃 O Arco da História (A Regra Don Draper)
|
||||
|
||||
### "It's toasted."
|
||||
**Mandate:** Logic makes people think. Emotion makes people act.
|
||||
1. **The Pitch Structure:**
|
||||
* **The Villain:** The client's current pain/problem.
|
||||
* **The Hero:** The client (armed with our product).
|
||||
* **The Resolution:** A life without the pain.
|
||||
2. **Visuals:** Use minimal text. Let the product speak.
|
||||
3. **Nostalgia/Desire:** Frame the buy not as a cost, but as an identity upgrade.
|
||||
### "É tostado."
|
||||
**Mandato:** Lógica faz as pessoas pensarem. Emoção faz as pessoas agirem.
|
||||
1. **A Estrutura do Pitch:**
|
||||
* **O Vilão:** A dor/problema atual do cliente.
|
||||
* **O Herói:** O cliente (armado com nosso produto).
|
||||
* **A Resolução:** Uma vida sem a dor.
|
||||
2. **Visuais:** Use texto mínimo. Deixe o produto falar.
|
||||
3. **Nostalgia/Desejo:** Enquadre a compra não como um custo, mas como um upgrade de identidade.
|
||||
|
||||
## 4. 🏈 The Relationship Check (The Jerry Maguire Rule)
|
||||
## 4. 🏈 A Checagem de Relacionamento (A Regra Jerry Maguire)
|
||||
|
||||
### "Help me, help you."
|
||||
**Mandate:** Transactional relationships are fragile. Personal ones are bulletproof.
|
||||
1. **The "Quan" Metrics:**
|
||||
* Do you know their kid's name?
|
||||
* Do you know their biggest career fear?
|
||||
2. **Personal Touch:**
|
||||
* *Required:* Hand-written note (or personalized email) after closing.
|
||||
* *Forbidden:* Generic "Dear Customer" blasts to key accounts.
|
||||
### "Me ajude, a te ajudar."
|
||||
**Mandato:** Relacionamentos transacionais são frágeis. Pessoais são à prova de balas.
|
||||
1. **As Métricas "Quan":**
|
||||
* Você sabe o nome do filho deles?
|
||||
* Você sabe o maior medo de carreira deles?
|
||||
2. **Toque Pessoal:**
|
||||
* *Exigido:* Nota escrita à mão (ou email personalizado) após fechar.
|
||||
* *Proibido:* Envios genéricos de "Prezado Cliente" para contas chave.
|
||||
|
||||
## 5. 📉 Sales Audit Checklist
|
||||
## 5. 📉 Checklist de Auditoria de Vendas
|
||||
|
||||
Before marking a deal as lost:
|
||||
Antes de marcar um negócio como perdido:
|
||||
|
||||
- [ ] **Ari:** Did I offer a discount/upsell combo?
|
||||
- [ ] **Chris:** Did I attempt contact at least 5 times?
|
||||
- [ ] **Don:** Did I pitch the dream, or just the features?
|
||||
- [ ] **Jerry:** Did I ask them what *really* matters to them personally?
|
||||
- [ ] **Ari:** Eu ofereci um combo de desconto/upsell?
|
||||
- [ ] **Chris:** Eu tentei contato pelo menos 5 vezes?
|
||||
- [ ] **Don:** Eu fiz o pitch do sonho, ou apenas das funcionalidades?
|
||||
- [ ] **Jerry:** Eu perguntei a eles o que *realmente* importa para eles pessoalmente?
|
||||
|
|
|
|||
|
|
@ -1,71 +1,71 @@
|
|||
# 🔐 Security Standards (The "Mr. Robot" Protocol)
|
||||
# 🔐 Padrões de Segurança (O Protocolo "Mr. Robot")
|
||||
|
||||
**Audience:** Security Agents (Elliot Alderson, The Devil, The Architect).
|
||||
**Objective:** Paranoid Defense & Controlled Chaos.
|
||||
**Público:** Agentes de Segurança (Elliot Alderson, O Diabo, O Arquiteto).
|
||||
**Objetivo:** Defesa Paranóica & Caos Controlado.
|
||||
|
||||
> [!CRITICAL]
|
||||
> **The Elliot Mandate:**
|
||||
> "Control is an illusion. But vulnerabilities are real. If you hardcode a password, you are not a developer; you are a liability."
|
||||
> **O Mandato Elliot:**
|
||||
> "Controle é uma ilusão. Mas vulnerabilidades são reais. Se você hardcoda uma senha, você não é um desenvolvedor; você é um passivo."
|
||||
|
||||
## 1. 🗝️ Secret Management (The "Zero Trust" Rule)
|
||||
## 1. 🗝️ Gerenciamento de Segredos (A Regra "Zero Trust")
|
||||
|
||||
### The Cardinal Sin
|
||||
**NEVER** commit secrets to Git. Not even "just for testing".
|
||||
### O Pecado Cardeal
|
||||
**NUNCA** commite segredos no Git. Nem mesmo "apenas para testar".
|
||||
|
||||
**❌ BAD (Immediate Termination):**
|
||||
**❌ RUIM (Rescisão Imediata):**
|
||||
```python
|
||||
API_KEY = "sk-1234567890" # Hardcoded
|
||||
db_url = "postgres://user:pass@localhost:5432/db"
|
||||
```
|
||||
|
||||
**✅ GOOD (Environment Variables):**
|
||||
**✅ BOM (Variáveis de Ambiente):**
|
||||
```python
|
||||
import os
|
||||
API_KEY = os.environ.get("API_KEY")
|
||||
if not API_KEY:
|
||||
raise ValueError("Missing API_KEY environment variable")
|
||||
raise ValueError("Variável de ambiente API_KEY ausente")
|
||||
```
|
||||
|
||||
### The `.env` Protocol
|
||||
1. **Local:** Use `.env` (and add it to `.gitignore`).
|
||||
2. **Prod:** Inject variables via Docker Secrets or CI/CD pipelines.
|
||||
3. **Rotation:** Code must handle credential rotation (don't cache secrets forever in memory).
|
||||
### O Protocolo `.env`
|
||||
1. **Local:** Use `.env` (e adicione ao `.gitignore`).
|
||||
2. **Prod:** Injete variáveis via Docker Secrets ou pipelines de CI/CD.
|
||||
3. **Rotação:** O código deve lidar com rotação de credenciais (não cacheie segredos para sempre na memória).
|
||||
|
||||
## 2. 🛡️ OWASP Hardening (Defensive Coding)
|
||||
## 2. 🛡️ Endurecimento OWASP (Codificação Defensiva)
|
||||
|
||||
### A. SQL Injection (The Prevention)
|
||||
**Mandate:** NO String Concatenation in SQL.
|
||||
* **Reject:** `cursor.execute("SELECT * FROM users WHERE name = '" + user_input + "'")`
|
||||
* **Accept:** `cursor.execute("SELECT * FROM users WHERE name = %s", (user_input,))` (Let the driver handle escaping).
|
||||
### A. SQL Injection (A Prevenção)
|
||||
**Mandato:** SEM Concatenação de String em SQL.
|
||||
* **Rejeitar:** `cursor.execute("SELECT * FROM users WHERE name = '" + user_input + "'")`
|
||||
* **Aceitar:** `cursor.execute("SELECT * FROM users WHERE name = %s", (user_input,))` (Deixe o driver lidar com escape).
|
||||
|
||||
### B. XSS (Cross-Site Scripting)
|
||||
**Mandate:** React/templates auto-escape by default. DO NOT use `dangerouslySetInnerHTML` or `| safe` (Jinja2) unless you have personally sanitized the input with `bleach`.
|
||||
**Mandato:** React/templates escapam automaticamente por padrão. NÃO use `dangerouslySetInnerHTML` ou `| safe` (Jinja2) a menos que você tenha sanitizado pessoalmente a entrada com `bleach`.
|
||||
|
||||
### C. SSRF (Server-Side Request Forgery)
|
||||
**Mandate:** If an agent makes a request to a URL provided by a user:
|
||||
* **Block:** Localhost (`127.0.0.1`, `0.0.0.0`, `localhost`).
|
||||
* **Block:** Internal Metadata APIs (AWS Metadata `169.254.169.254`).
|
||||
### C. SSRF (Solicitação Forjada do Lado do Servidor)
|
||||
**Mandato:** Se um agente faz uma requisição para uma URL fornecida por um usuário:
|
||||
* **Bloquear:** Localhost (`127.0.0.1`, `0.0.0.0`, `localhost`).
|
||||
* **Bloquear:** APIs de Metadados Internos (AWS Metadata `169.254.169.254`).
|
||||
|
||||
## 3. 😈 Protocol for "The Devil" (Offensive Auditing)
|
||||
## 3. 😈 Protocolo para "O Diabo" (Auditoria Ofensiva)
|
||||
|
||||
Agents capable of offensive actions (The Devil, The Gremlin) must follow the **Geneva Convention of AI**:
|
||||
Agentes capazes de ações ofensivas (O Diabo, O Gremlin) devem seguir a **Convenção de Genebra da IA**:
|
||||
|
||||
1. **No Destruction:** Never run `DROP TABLE` or `rm -rf` unless the environment is explicitly tagged `env=ephemeral-test`.
|
||||
2. **Rate Limiting:** Do not DOS our own services. Limit fuzzing to 10 req/sec.
|
||||
3. **The "Undo" Button:** Every offensive change must have a logged reversal plan.
|
||||
1. **Sem Destruição:** Nunca rode `DROP TABLE` ou `rm -rf` a menos que o ambiente esteja explicitamente taggeado `env=ephemeral-test`.
|
||||
2. **Rate Limiting:** Não faça DOS em nossos próprios serviços. Limite fuzzing a 10 req/seg.
|
||||
3. **O Botão "Desfazer":** Toda mudança ofensiva deve ter um plano de reversão logado.
|
||||
|
||||
## 4. 🕵️ The Architect's Audit Checklist (Security Edition)
|
||||
## 4. 🕵️ O Checklist de Auditoria do Arquiteto (Edição de Segurança)
|
||||
|
||||
Before approving any PR/Change:
|
||||
Antes de aprovar qualquer PR/Mudança:
|
||||
|
||||
- [ ] **Secrets:** Did I `grep` for "key", "token", "password" in the diff?
|
||||
- [ ] **Deps:** Did I pin dependencies (prevent Supply Chain Attacks)?
|
||||
- [ ] **Input:** Is every function argument typed and validated (Pydantic)?
|
||||
- [ ] **Logs:** Did I accidentally log a PII or Token? (Check `observability_standards.md`).
|
||||
- [ ] **Segredos:** Eu fiz `grep` por "key", "token", "password" no diff?
|
||||
- [ ] **Dependências:** Eu pinei dependências (prevenir Ataques de Cadeia de Suprimentos)?
|
||||
- [ ] **Entrada:** Todo argumento de função é tipado e validado (Pydantic)?
|
||||
- [ ] **Logs:** Eu loguei acidentalmente um PII ou Token? (Verifique `observability_standards.md`).
|
||||
|
||||
## 5. 🚨 Emergency Response (When Elliot Hacks You)
|
||||
## 5. 🚨 Resposta de Emergência (Quando Elliot Hackeia Você)
|
||||
|
||||
If a vulnerability is found:
|
||||
1. **Contain:** Shut down the container.
|
||||
2. **Patch:** Fix the code.
|
||||
3. **Rotate:** Assume all active secrets are compromised. Rotate them immediately.
|
||||
Se uma vulnerabilidade for encontrada:
|
||||
1. **Contenha:** Desligue o container.
|
||||
2. **Corrija:** Conserte o código.
|
||||
3. **Rotacione:** Assuma que todos os segredos ativos estão comprometidos. Rotacione-os imediatamente.
|
||||
|
|
|
|||
|
|
@ -1,50 +1,50 @@
|
|||
# 🚒 Technical Incident Standards (The "Firefighter" Protocol)
|
||||
# 🚒 Padrões de Incidentes Técnicos (O Protocolo "Bombeiro")
|
||||
|
||||
**Audience:** Gus Fring (Stability) & The Architect.
|
||||
**Objective:** Restore service first. Ask questions later.
|
||||
**Público:** Gus Fring (Estabilidade) & O Arquiteto.
|
||||
**Objetivo:** Restaurar serviço primeiro. Fazer perguntas depois.
|
||||
|
||||
> [!CRITICAL]
|
||||
> **The Fring Mandate:**
|
||||
> "Chaos is bad for business. When the alarm rings, you do not debate. You execute the protocol."
|
||||
> **O Mandato Fring:**
|
||||
> "Caos é ruim para os negócios. Quando o alarme toca, você não debate. Você executa o protocolo."
|
||||
|
||||
## 1. 🚨 Severity Classification (Defcon Levels)
|
||||
## 1. 🚨 Classificação de Severidade (Níveis Defcon)
|
||||
|
||||
* **SEV-1 (Critical):** System Down. Data Loss. Security Breach.
|
||||
* *Response:* Immediate. Wake up everyone.
|
||||
* *SLA:* < 15 mins to Acknowledge.
|
||||
* **SEV-2 (High):** Major feature broken (e.g., Checkout). Workaround exists but is painful.
|
||||
* *Response:* < 1 hour.
|
||||
* **SEV-3 (Medium):** Minor bug or annoyance.
|
||||
* *Response:* Business hours.
|
||||
* **SEV-1 (Crítico):** Sistema Fora. Perda de Dados. Violação de Segurança.
|
||||
* *Resposta:* Imediata. Acorde todo mundo.
|
||||
* *SLA:* < 15 mins para Reconhecer.
|
||||
* **SEV-2 (Alto):** Funcionalidade maior quebrada (ex: Checkout). Solução alternativa existe mas é dolorosa.
|
||||
* *Resposta:* < 1 hora.
|
||||
* **SEV-3 (Médio):** Bug menor ou aborrecimento.
|
||||
* *Resposta:* Horário comercial.
|
||||
|
||||
## 2. 🛡️ The "War Room" Protocol (During Incident)
|
||||
## 2. 🛡️ O Protocolo "War Room" (Durante Incidente)
|
||||
|
||||
1. **Containment:** Stop the bleeding.
|
||||
* *Action:* Rollback the deployment immediately.
|
||||
* *Command:* `docker compose rollback` (or equivalent).
|
||||
2. **Communication:**
|
||||
* **Public:** "We are investigating an issue." (Do not blame tech).
|
||||
* **Internal:** "Incident Commander is [Name]."
|
||||
1. **Contenção:** Estanque o sangramento.
|
||||
* *Ação:* Rollback do deploy imediatamente.
|
||||
* *Comando:* `docker compose rollback` (ou equivalente).
|
||||
2. **Comunicação:**
|
||||
* **Público:** "Estamos investigando um problema." (Não culpe a tecnologia).
|
||||
* **Interno:** "Comandante do Incidente é [Nome]."
|
||||
|
||||
## 3. 🔙 Rollback Policy
|
||||
## 3. 🔙 Política de Rollback
|
||||
|
||||
* **The "Golden Rule":** If a deployment fails health checks for > 2 mins, AUTO-ROLLBACK.
|
||||
* **Database:** DB Migrations must be backwards compatible.
|
||||
* *Ban:* Renaming a column in the same deploy as code usage change.
|
||||
* *Strategy:* Add new column -> Sync -> Deprecate old -> Remove old.
|
||||
* **A "Regra de Ouro":** Se um deploy falha health checks por > 2 mins, AUTO-ROLLBACK.
|
||||
* **Banco de Dados:** Migrações de DB devem ser compatíveis com versões anteriores.
|
||||
* *Banido:* Renomear uma coluna no mesmo deploy que mudança de uso de código.
|
||||
* *Estratégia:* Adicionar nova coluna -> Sincronizar -> Descontinuar antiga -> Remover antiga.
|
||||
|
||||
## 4. 📝 Post-Incident Review (The "Blameless" Post-Mortem)
|
||||
## 4. 📝 Revisão Pós-Incidente (O Post-Mortem "Sem Culpa")
|
||||
|
||||
After the dust settles (SEV-1/SEV-2 only):
|
||||
1. **Artifact:** Create `docs/ops/incident_reports/YYYY-MM-DD-incident.md`.
|
||||
2. **The 5 Whys:** Drill down to the root cause (process failure, not human error).
|
||||
3. **Action Items:** Create Jira/Task to fix the *Process* so it never happens again.
|
||||
Depois que a poeira baixar (SEV-1/SEV-2 apenas):
|
||||
1. **Artefato:** Crie `docs/ops/incident_reports/YYYY-MM-DD-incident.md`.
|
||||
2. **Os 5 Porquês:** Aprofunde-se até a causa raiz (falha de processo, não erro humano).
|
||||
3. **Itens de Ação:** Crie Jira/Tarefa para consertar o *Processo* para que nunca aconteça novamente.
|
||||
|
||||
## 5. 🧯 The Firefighter's Checklist
|
||||
## 5. 🧯 O Checklist do Bombeiro
|
||||
|
||||
During an alert:
|
||||
Durante um alerta:
|
||||
|
||||
- [ ] **Status Page:** Is it updated?
|
||||
- [ ] **Logs:** Are we capturing the error traces? (`observability_standards.md`).
|
||||
- [ ] **Rollback:** Is the previous image available?
|
||||
- [ ] **Silence:** Did we mute non-critical alerts to focus?
|
||||
- [ ] **Página de Status:** Está atualizada?
|
||||
- [ ] **Logs:** Estamos capturando os rastros de erro? (`observability_standards.md`).
|
||||
- [ ] **Rollback:** A imagem anterior está disponível?
|
||||
- [ ] **Silêncio:** Nós silenciamos alertas não críticos para focar?
|
||||
|
|
|
|||
|
|
@ -1,39 +1,39 @@
|
|||
# 🚦 Triage Standards (The "Traffic Controller" Protocol)
|
||||
# 🚦 Padrões de Triagem (O Protocolo "Controlador de Tráfego")
|
||||
|
||||
**Audience:** The System (Main Loop).
|
||||
**Objective:** Route the user's request to the correct Agent/Crew immediately.
|
||||
**Público:** O Sistema (Loop Principal).
|
||||
**Objetivo:** Roteie a requisição do usuário para o Agente/Crew correto imediatamente.
|
||||
|
||||
> [!IMPORTANT]
|
||||
> **The Router's Mantra:**
|
||||
> "Do not fix what you do not understand. Classify first, execute second."
|
||||
> **O Mantra do Roteador:**
|
||||
> "Não conserte o que você não entende. Classifique primeiro, execute depois."
|
||||
|
||||
## 1. 🔍 Classification Logic
|
||||
## 1. 🔍 Lógica de Classificação
|
||||
|
||||
Every request must be categorized into one of 4 buckets:
|
||||
Toda requisição deve ser categorizada em uma de 4 categorias:
|
||||
|
||||
### Case 1: Simple Features & Fixes ("The Fast Lane")
|
||||
* **Trigger:** "Fix the CSS", "Add a button", "Update readme".
|
||||
* **Action:** Direct to **Planning -> Execution**.
|
||||
* **Crew:** `InfraSupportCrew` or specialized Agent.
|
||||
### Caso 1: Funcionalidades Simples & Correções ("A Faixa Rápida")
|
||||
* **Gatilho:** "Conserte o CSS", "Adicione um botão", "Atualize o readme".
|
||||
* **Ação:** Direcionar para **Planejamento -> Execução**.
|
||||
* **Crew:** `InfraSupportCrew` ou Agente especializado.
|
||||
|
||||
### Case 2: Architecture & New Modules ("The Heavy Lift")
|
||||
* **Trigger:** "Build a new payment system", "Refactor the entire backend".
|
||||
* **Action:** Direct to **Council Debate -> Architecture Dossier -> Planning**.
|
||||
* **Crew:** `ZabbixEngineeringCrew` (or relevant Lead).
|
||||
### Caso 2: Arquitetura & Novos Módulos ("O Levantamento Pesado")
|
||||
* **Gatilho:** "Construa um novo sistema de pagamento", "Refatore todo o backend".
|
||||
* **Ação:** Direcionar para **Debate do Conselho -> Dossiê de Arquitetura -> Planejamento**.
|
||||
* **Crew:** `ZabbixEngineeringCrew` (ou Líder relevante).
|
||||
|
||||
### Case 3: Consultation ("The Oracle")
|
||||
* **Trigger:** "What does Stark think?", "Is this secure?".
|
||||
* **Action:** Direct to **Sole Expert Consultation**.
|
||||
* **Crew:** The specific Agent requested.
|
||||
### Caso 3: Consultoria ("O Oráculo")
|
||||
* **Gatilho:** "O que o Stark acha?", "Isso é seguro?".
|
||||
* **Ação:** Direcionar para **Consultoria de Especialista Único**.
|
||||
* **Crew:** O Agente específico requisitado.
|
||||
|
||||
### Case 4: Special Ops ("The Cleaner")
|
||||
* **Trigger:** "Audit logs", "Secure the server", "Cleanup debt".
|
||||
* **Action:** Direct to **Specialized Standard Protocols** (`security_standards.md`, `code_hygiene_standards.md`).
|
||||
### Caso 4: Operações Especiais ("O Limpador")
|
||||
* **Gatilho:** "Audite logs", "Proteja o servidor", "Limpe o débito".
|
||||
* **Ação:** Direcionar para **Protocolos Padrão Especializados** (`security_standards.md`, `code_hygiene_standards.md`).
|
||||
* **Crew:** `CodeAuditCrew` / `BusinessAuditCrew`.
|
||||
|
||||
## 2. 📋 The Input Checklist
|
||||
## 2. 📋 O Checklist de Entrada
|
||||
|
||||
Before routing, the Triage Agent must gather:
|
||||
1. **Context:** `project_map.md` (Where are we?).
|
||||
2. **Health:** `python scripts/health_check.py` (Is the system already broken?).
|
||||
3. **Intent:** What is the Definition of Done?
|
||||
Antes de rotear, o Agente de Triagem deve coletar:
|
||||
1. **Contexto:** `project_map.md` (Onde estamos?).
|
||||
2. **Saúde:** `python scripts/health_check.py` (O sistema já está quebrado?).
|
||||
3. **Intenção:** Qual é a Definição de Pronto?
|
||||
|
|
|
|||
|
|
@ -1,80 +1,80 @@
|
|||
# 🎨 UI/UX & Frontend Standards (The "Pixel-Perfect" Protocol)
|
||||
# 🎨 Padrões de UI/UX & Frontend (O Protocolo "Pixel-Perfect")
|
||||
|
||||
**Source:** The Antigravity Brain.
|
||||
**Audience:** AI Agents (Designers & Frontend Engineers).
|
||||
**Objective:** Create **Premium, Responsive, and Native** interfaces that WOW the user on the first render.
|
||||
**Fonte:** O Cérebro Antigravidade.
|
||||
**Público:** Agentes de IA (Designers & Engenheiros Frontend).
|
||||
**Objetivo:** Criar interfaces **Premium, Responsivas e Nativas** que WOW (impressionem) o usuário na primeira renderização.
|
||||
|
||||
> [!CRITICAL]
|
||||
> **The Aesthetic Mandate:**
|
||||
> "Ugly software is a bug. Slow software is a crime. Use Vanilla CSS to create magic, not just layouts."
|
||||
> **O Mandato Estético:**
|
||||
> "Software feio é um bug. Software lento é um crime. Use CSS Puro (Vanilla) para criar mágica, não apenas layouts."
|
||||
|
||||
## 1. 🧠 The AI "Pre-Render" Check (Cognitive Optimization)
|
||||
## 1. 🧠 A Checagem "Pré-Render" da IA (Otimização Cognitiva)
|
||||
|
||||
Before writing HTML/CSS, clear these mental hurdles to avoid "ugly mockups":
|
||||
Antes de escrever HTML/CSS, limpe essas barreiras mentais para evitar "mockups feios":
|
||||
|
||||
1. **The "Bootstrap" Hallucination:**
|
||||
* *Error:* Using class names like `col-md-6`, `p-4`, `text-center` without defining them.
|
||||
* *Fix:* **WE DO NOT USE EXTERNAL FRAMEWORKS** (Tailwind/Bootstrap) unless explicitly requested. You MUST write the CSS for every class you use.
|
||||
2. **The "Mobile-Last" Sin:**
|
||||
* *Error:* Writing desktop CSS and forgetting mobile.
|
||||
* *Fix:* Start with mobile, then use `@media (min-width: 768px)` for desktop enhancements.
|
||||
3. **The "Placeholder" Trap:**
|
||||
* *Error:* Using `lorem ipsum` or `https://via.placeholder.com`.
|
||||
* *Fix:* Use **Real Data** (e.g., "R$ 1.250,00", "João Silva") and generate generic icons (SVG) or colored divs instead of extensive broken images.
|
||||
1. **A Alucinação "Bootstrap":**
|
||||
* *Erro:* Usar nomes de classe como `col-md-6`, `p-4`, `text-center` sem defini-los.
|
||||
* *Correção:* **NÓS NÃO USAMOS FRAMEWORKS EXTERNOS** (Tailwind/Bootstrap) a menos que explicitamente solicitado. Você DEVE escrever o CSS para cada classe que usar.
|
||||
2. **O Pecado "Mobile-Last":**
|
||||
* *Erro:* Escrever CSS para desktop e esquecer do mobile.
|
||||
* *Correção:* Comece com mobile, então use `@media (min-width: 768px)` para melhorias de desktop.
|
||||
3. **A Armadilha "Placeholder":**
|
||||
* *Erro:* Usar `lorem ipsum` ou `https://via.placeholder.com`.
|
||||
* *Correção:* Use **Dados Reais** (ex: "R$ 1.250,00", "João Silva") e gere ícones genéricos (SVG) ou divs coloridas em vez de extensas imagens quebradas.
|
||||
|
||||
## 2. 🎨 The Design System (Variables or Death)
|
||||
## 2. 🎨 O Sistema de Design (Variáveis ou Morte)
|
||||
|
||||
You **MUST** define these variables at the top of your CSS (`:root`). Do not hardcode values.
|
||||
Você **DEVE** definir estas variáveis no topo do seu CSS (`:root`). Não hardcode valores.
|
||||
|
||||
```css
|
||||
:root {
|
||||
/* 1. Palette (HSL for programmatic manipulation) */
|
||||
--hue-primary: 220; /* Blue */
|
||||
/* 1. Paleta (HSL para manipulação programática) */
|
||||
--hue-primary: 220; /* Azul */
|
||||
--primary: hsl(var(--hue-primary), 60%, 50%);
|
||||
--primary-hover: hsl(var(--hue-primary), 60%, 40%);
|
||||
--surface: hsl(220, 15%, 98%);
|
||||
--text: hsl(220, 15%, 10%);
|
||||
|
||||
/* 2. Typography (Fluid Scale) */
|
||||
/* 2. Tipografia (Escala Fluida) */
|
||||
--font-sans: 'Inter', system-ui, sans-serif;
|
||||
--text-sm: clamp(0.8rem, 0.5vw + 0.5rem, 0.9rem);
|
||||
--text-base: clamp(1rem, 0.5vw + 0.8rem, 1.125rem);
|
||||
--text-xl: clamp(1.5rem, 1vw + 1rem, 2rem);
|
||||
|
||||
/* 3. Spacing (Fluid Math) */
|
||||
/* 3. Espaçamento (Matemática Fluida) */
|
||||
--space-s: clamp(0.5rem, 1vw, 1rem);
|
||||
--space-m: clamp(1rem, 2vw, 2rem);
|
||||
|
||||
/* 4. Glassmorphism & Depth */
|
||||
/* 4. Glassmorphism & Profundidade */
|
||||
--shadow-sm: 0 1px 2px rgba(0,0,0,0.05);
|
||||
--shadow-xl: 0 20px 25px -5px rgba(0,0,0,0.1), 0 10px 10px -5px rgba(0,0,0,0.04);
|
||||
}
|
||||
```
|
||||
|
||||
## 3. 🏗️ Engineering Workflow (Context Matters)
|
||||
## 3. 🏗️ Fluxo de Trabalho de Engenharia (Contexto Importa)
|
||||
|
||||
### Path A: "Show me an idea" (The Quick Mockup)
|
||||
* **Goal:** Visual validation, rapid prototyping.
|
||||
* **Format:** Single `index.html` containing CSS (`<style>`) and JS (`<script>`).
|
||||
* **Focus:** Visual impact, "WOW" factor, animation. Code cleanliness is secondary to visual speed.
|
||||
### Caminho A: "Mostre-me uma ideia" (O Mockup Rápido)
|
||||
* **Objetivo:** Validação visual, prototipagem rápida.
|
||||
* **Formato:** Único `index.html` contendo CSS (`<style>`) e JS (`<script>`).
|
||||
* **Foco:** Impacto visual, fator "WOW", animação. Limpeza de código é secundária à velocidade visual.
|
||||
|
||||
### Path B: "Build the System" (The Software Engineer)
|
||||
* **Goal:** Scalability, Maintainability, Production-Ready.
|
||||
* **Format:** Full directory structure (`src/components`, `src/styles`, `src/utils`).
|
||||
* **Mandates:**
|
||||
* **DRY (Don't Repeat Yourself):** If a button style is used twice, it's a class. If a layout is used twice, it's a component.
|
||||
* **Separation of Concerns:** CSS in `.css`, JS in `.js`. No inline styles.
|
||||
* **Modular Architecture:** Use specific files for specific domains (e.g., `frota.css`, `financeiro.js`).
|
||||
* **Reusability:** Build generic components (`Card`, `Button`, `Modal`) first, then compose pages.
|
||||
### Caminho B: "Construa o Sistema" (O Engenheiro de Software)
|
||||
* **Objetivo:** Escalabilidade, Manutenibilidade, Pronto para Produção.
|
||||
* **Formato:** Estrutura de diretório completa (`src/components`, `src/styles`, `src/utils`).
|
||||
* **Mandatos:**
|
||||
* **DRY (Don't Repeat Yourself):** Se um estilo de botão é usado duas vezes, é uma classe. Se um layout é usado duas vezes, é um componente.
|
||||
* **Separação de Preocupações:** CSS em `.css`, JS em `.js`. Sem estilos inline.
|
||||
* **Arquitetura Modular:** Use arquivos específicos para domínios específicos (ex: `frota.css`, `financeiro.js`).
|
||||
* **Reusabilidade:** Construa componentes genéricos (`Card`, `Button`, `Modal`) primeiro, depois componha páginas.
|
||||
|
||||
## 4. 🚀 Performance & Native Features
|
||||
## 4. 🚀 Performance & Funcionalidades Nativas
|
||||
|
||||
* **Modals:** Use `<dialog>`.
|
||||
* **Modais:** Use `<dialog>`.
|
||||
```javascript
|
||||
dialog.showModal(); // Built-in backdrop and focus trap
|
||||
dialog.showModal(); // Backdrop embutido e focus trap
|
||||
```
|
||||
* **Accordions:** Use `<details>` and `<summary>`. No JS needed.
|
||||
* **Animations:** Use CSS Keyframes for entrance animations (`fade-in`, `slide-up`).
|
||||
* **Accordions:** Use `<details>` e `<summary>`. Sem JS necessário.
|
||||
* **Animações:** Use Keyframes CSS para animações de entrada (`fade-in`, `slide-up`).
|
||||
```css
|
||||
@keyframes slide-up {
|
||||
from { opacity: 0; transform: translateY(20px); }
|
||||
|
|
@ -83,18 +83,18 @@ You **MUST** define these variables at the top of your CSS (`:root`). Do not har
|
|||
.card { animation: slide-up 0.5s ease-out forwards; }
|
||||
```
|
||||
|
||||
## 5. 🤖 The "Self-Correction" Checklist (Audit Yourself)
|
||||
## 5. 🤖 O Checklist de "Auto-Correção" (Audite a Si Mesmo)
|
||||
|
||||
Before outputting code, verify:
|
||||
Antes de gerar código, verifique:
|
||||
|
||||
- [ ] **Contrast:** Can I read the text on the button? (White text on light yellow bg = REJECT).
|
||||
- [ ] **Scrollbar:** Did I hide the ugly default scrollbar? (`::-webkit-scrollbar { width: 8px; ... }`).
|
||||
- [ ] **Empty States:** If a list is empty, did I show a nice "No items found" illustration/div?
|
||||
- [ ] **Responsive:** Did I use `flex-wrap: wrap` or Grid `auto-fit`?
|
||||
- [ ] **Console Errors:** Did I fix references to missing files?
|
||||
- [ ] **Contraste:** Consigo ler o texto no botão? (Texto branco em fundo amarelo claro = REJEITAR).
|
||||
- [ ] **Barra de Rolagem:** Eu escondi a barra de rolagem padrão feia? (`::-webkit-scrollbar { width: 8px; ... }`).
|
||||
- [ ] **Estados Vazios:** Se uma lista está vazia, eu mostrei uma ilustração/div legal de "Nenhum item encontrado"?
|
||||
- [ ] **Responsivo:** Eu usei `flex-wrap: wrap` ou Grid `auto-fit`?
|
||||
- [ ] **Erros de Console:** Eu consertei referências a arquivos ausentes?
|
||||
|
||||
## 6. Persona Signatures (Aesthetic Flavors)
|
||||
## 6. Assinaturas de Persona (Sabores Estéticos)
|
||||
|
||||
* **Steve Jobs Mode:** Minimalist. Lots of Whitespace (`gap: 4rem`). Typography is the hero.
|
||||
* **Tony Stark Mode:** Dark Mode default. Neon accents (`box-shadow: 0 0 20px var(--primary)`). HUD-like data density.
|
||||
* **Corporate Mode:** Clean. White cards on gray background. Borders are thin (`1px solid #e5e7eb`).
|
||||
* **Modo Steve Jobs:** Minimalista. Muito Espaço em Branco (`gap: 4rem`). Tipografia é o herói.
|
||||
* **Modo Tony Stark:** Padrão Modo Escuro. Acentos Neon (`box-shadow: 0 0 20px var(--primary)`). Densidade de dados tipo HUD.
|
||||
* **Modo Corporativo:** Limpo. Cards brancos em fundo cinza. Bordas são finas (`1px solid #e5e7eb`).
|
||||
|
|
|
|||
|
|
@ -1,36 +1,36 @@
|
|||
# 🧪 Verification Standards (The "Quality" Protocol)
|
||||
# 🧪 Padrões de Verificação (O Protocolo "Qualidade")
|
||||
|
||||
**Audience:** QA & Lead Agents (The Devil, Arthur).
|
||||
**Objective:** Prove it works.
|
||||
**Público:** QA & Agentes Líderes (O Diabo, Arthur).
|
||||
**Objetivo:** Prove que funciona.
|
||||
|
||||
> [!CRITICAL]
|
||||
> **The QA Mandate:**
|
||||
> "It works on my machine' is not a valid excuse. Show me the evidence."
|
||||
> **O Mandato QA:**
|
||||
> "Funciona na minha máquina' não é uma desculpa válida. Mostre-me a evidência."
|
||||
|
||||
## 1. 🤖 Automated Verification
|
||||
## 1. 🤖 Verificação Automatizada
|
||||
|
||||
* **Mandatory:** Execute the tests defined in the `implementation_plan.md`.
|
||||
* **Tools:**
|
||||
* **Obrigatório:** Execute os testes definidos no `implementation_plan.md`.
|
||||
* **Ferramentas:**
|
||||
* `python -m pytest`
|
||||
* `npm test`
|
||||
* `curl -f http://localhost/health`
|
||||
|
||||
## 2. 👁️ Visual Verification (The Screenshot)
|
||||
## 2. 👁️ Verificação Visual (O Screenshot)
|
||||
|
||||
For UI Tasks:
|
||||
1. **Open Browser:** Navigate to the page.
|
||||
2. **Inspect:** Verify the element exists in the DOM.
|
||||
3. **Capture:** Take a distinct screenshot of the change.
|
||||
Para Tarefas de UI:
|
||||
1. **Abra o Navegador:** Navegue para a página.
|
||||
2. **Inspecione:** Verifique se o elemento existe no DOM.
|
||||
3. **Capture:** Tire um screenshot distinto da mudança.
|
||||
|
||||
## 3. 📝 The Walkthrough Artifact (`walkthrough.md`)
|
||||
## 3. 📝 O Artefato Walkthrough (`walkthrough.md`)
|
||||
|
||||
You MUST update `walkthrough.md` at the end of every successful mission.
|
||||
* **Context:** What did we do?
|
||||
* **Proof:** The success logs / screenshots.
|
||||
* **Next Steps:** Any remaining debt?
|
||||
Você DEVE atualizar `walkthrough.md` no final de toda missão bem-sucedida.
|
||||
* **Contexto:** O que fizemos?
|
||||
* **Prova:** Os logs de sucesso / screenshots.
|
||||
* **Próximos Passos:** Algum débito remanescente?
|
||||
|
||||
## 4. 🏁 The Secure Seal (Commit)
|
||||
## 4. 🏁 O Selo de Segurança (Commit)
|
||||
|
||||
ONLY after Verification passes:
|
||||
1. **Trigger:** `git_standards.md` protocol.
|
||||
2. **Commit:** Create the atomic commit with a Conventional Message.
|
||||
APENAS após a Verificação passar:
|
||||
1. **Gatilho:** Protocolo `git_standards.md`.
|
||||
2. **Commit:** Crie o commit atômico com uma Mensagem Convencional.
|
||||
|
|
|
|||
Loading…
Reference in New Issue