create-genia-os 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (86) hide show
  1. package/bin/index.js +210 -0
  2. package/package.json +39 -0
  3. package/template/.claude/CLAUDE.md +215 -0
  4. package/template/.claude/agent-memory/analyst/MEMORY.md +20 -0
  5. package/template/.claude/agent-memory/architect/MEMORY.md +20 -0
  6. package/template/.claude/agent-memory/dev/MEMORY.md +20 -0
  7. package/template/.claude/agent-memory/devops/MEMORY.md +20 -0
  8. package/template/.claude/agent-memory/pm/MEMORY.md +20 -0
  9. package/template/.claude/agent-memory/po/MEMORY.md +20 -0
  10. package/template/.claude/agent-memory/qa/MEMORY.md +20 -0
  11. package/template/.claude/agent-memory/reviewer/MEMORY.md +20 -0
  12. package/template/.claude/agent-memory/sm/MEMORY.md +20 -0
  13. package/template/.claude/hooks/enforce-git-push-authority.py +70 -0
  14. package/template/.claude/hooks/precompact-session-digest.cjs +87 -0
  15. package/template/.claude/hooks/sql-governance.py +65 -0
  16. package/template/.claude/hooks/synapse-engine.cjs +122 -0
  17. package/template/.claude/hooks/write-path-validation.py +59 -0
  18. package/template/.claude/rules/agent-authority.md +39 -0
  19. package/template/.claude/rules/agent-handoff.md +71 -0
  20. package/template/.claude/rules/agent-memory.md +61 -0
  21. package/template/.claude/rules/ids-principles.md +52 -0
  22. package/template/.claude/rules/mcp-usage.md +49 -0
  23. package/template/.claude/rules/story-lifecycle.md +87 -0
  24. package/template/.claude/rules/workflow-execution.md +68 -0
  25. package/template/.claude/settings.json +58 -0
  26. package/template/.claude/settings.local.json +14 -0
  27. package/template/.genia/CONSTITUTION.md +129 -0
  28. package/template/.genia/contexts/api-patterns.md +134 -0
  29. package/template/.genia/contexts/nextjs-react.md +210 -0
  30. package/template/.genia/contexts/projeto.md +18 -0
  31. package/template/.genia/contexts/supabase.md +152 -0
  32. package/template/.genia/contexts/whatsapp-cloud.md +176 -0
  33. package/template/.genia/core-config.yaml +192 -0
  34. package/template/.genia/development/agents/analyst.md +138 -0
  35. package/template/.genia/development/agents/architect.md +171 -0
  36. package/template/.genia/development/agents/dev.md +160 -0
  37. package/template/.genia/development/agents/devops.md +200 -0
  38. package/template/.genia/development/agents/pm.md +142 -0
  39. package/template/.genia/development/agents/po.md +165 -0
  40. package/template/.genia/development/agents/qa.md +183 -0
  41. package/template/.genia/development/agents/reviewer.md +198 -0
  42. package/template/.genia/development/agents/sm.md +230 -0
  43. package/template/.genia/development/checklists/architecture-review.md +189 -0
  44. package/template/.genia/development/checklists/pre-commit.md +205 -0
  45. package/template/.genia/development/checklists/pre-deploy.md +230 -0
  46. package/template/.genia/development/checklists/qa-gate.md +216 -0
  47. package/template/.genia/development/checklists/story-dod.md +155 -0
  48. package/template/.genia/development/tasks/code-review.md +197 -0
  49. package/template/.genia/development/tasks/criar-prd.md +170 -0
  50. package/template/.genia/development/tasks/criar-spec.md +188 -0
  51. package/template/.genia/development/tasks/criar-story.md +185 -0
  52. package/template/.genia/development/tasks/debug-sistematico.md +230 -0
  53. package/template/.genia/development/tasks/dev-implement.md +199 -0
  54. package/template/.genia/development/tasks/qa-review.md +224 -0
  55. package/template/.genia/development/workflows/brownfield.md +178 -0
  56. package/template/.genia/development/workflows/delivery.md +208 -0
  57. package/template/.genia/development/workflows/development.md +189 -0
  58. package/template/.genia/development/workflows/greenfield.md +166 -0
  59. package/template/.genia/development/workflows/planning.md +167 -0
  60. package/template/.genia/development/workflows/qa-loop.md +179 -0
  61. package/template/.genia/development/workflows/spec-pipeline.md +192 -0
  62. package/template/.genia/development/workflows/story-development-cycle.md +252 -0
  63. package/template/.genia/guidelines/clean-code.md +98 -0
  64. package/template/.genia/guidelines/testing.md +176 -0
  65. package/template/.genia/skills/design/canvas-design.md +109 -0
  66. package/template/.genia/skills/design/frontend-design.md +140 -0
  67. package/template/.genia/skills/dev/mcp-builder.md +172 -0
  68. package/template/.genia/skills/dev/webapp-testing.md +150 -0
  69. package/template/.genia/skills/documents/docx.md +153 -0
  70. package/template/.genia/skills/documents/pdf.md +134 -0
  71. package/template/.genia/skills/documents/pptx.md +118 -0
  72. package/template/.genia/skills/documents/xlsx.md +140 -0
  73. package/template/.synapse/agent-analyst +8 -0
  74. package/template/.synapse/agent-architect +8 -0
  75. package/template/.synapse/agent-dev +8 -0
  76. package/template/.synapse/agent-devops +8 -0
  77. package/template/.synapse/agent-pm +8 -0
  78. package/template/.synapse/agent-po +7 -0
  79. package/template/.synapse/agent-qa +8 -0
  80. package/template/.synapse/agent-reviewer +7 -0
  81. package/template/.synapse/agent-sm +7 -0
  82. package/template/.synapse/constitution +7 -0
  83. package/template/.synapse/context +8 -0
  84. package/template/.synapse/global +8 -0
  85. package/template/.synapse/manifest +14 -0
  86. package/template/README.md +53 -0
@@ -0,0 +1,70 @@
1
+ #!/usr/bin/env python3
2
+ """
3
+ GEN.IA OS — Hook: enforce-git-push-authority
4
+ Trigger: PreToolUse (Bash)
5
+ Ação: Bloqueia git push por agentes não-devops.
6
+ Permite push quando @devops está autorizado via flag file.
7
+ Artigo II da Constituição GEN.IA OS — NÃO-NEGOCIÁVEL.
8
+
9
+ Protocolo de autorização:
10
+ 1. Claude pergunta à usuária se quer invocar @devops
11
+ 2. Se sim, @devops cria .genia/session/devops-active
12
+ 3. Este hook lê o flag e permite o push (uma única vez)
13
+ 4. Flag é removido automaticamente após uso
14
+ """
15
+ import json
16
+ import os
17
+ import sys
18
+ import re
19
+
20
+
21
+ PUSH_PATTERNS = [
22
+ r"\bgit\s+push\b",
23
+ r"\bgit\s+push\s+--force\b",
24
+ r"\bgit\s+push\s+-f\b",
25
+ r"\bgit\s+push\s+-u\b",
26
+ ]
27
+
28
+ FLAG_FILE = ".genia/session/devops-active"
29
+
30
+
31
+ def main():
32
+ try:
33
+ raw = sys.stdin.read()
34
+ data = json.loads(raw)
35
+ except Exception:
36
+ sys.exit(0)
37
+
38
+ tool = data.get("tool_name", "")
39
+ if tool != "Bash":
40
+ sys.exit(0)
41
+
42
+ command = data.get("tool_input", {}).get("command", "")
43
+
44
+ for pattern in PUSH_PATTERNS:
45
+ if re.search(pattern, command, re.IGNORECASE):
46
+ # Verificar se @devops foi autorizado via flag file
47
+ if os.path.exists(FLAG_FILE):
48
+ try:
49
+ os.remove(FLAG_FILE) # Consumir o flag (uso único)
50
+ except Exception:
51
+ pass
52
+ print(
53
+ "[GEN.IA OS] ✅ @devops (Gate) autorizado — executando push.",
54
+ file=sys.stderr,
55
+ )
56
+ sys.exit(0) # Permitir
57
+
58
+ # Sem autorização — bloquear
59
+ print(
60
+ "[GEN.IA OS] 🚫 BLOQUEADO — Artigo II: Apenas @devops pode executar git push.\n"
61
+ "[GEN.IA OS] Diga: '@devops faça o push' para invocar Gate.",
62
+ file=sys.stderr,
63
+ )
64
+ sys.exit(2) # exit 2 = BLOCK no Claude Code
65
+
66
+ sys.exit(0)
67
+
68
+
69
+ if __name__ == "__main__":
70
+ main()
@@ -0,0 +1,87 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * GEN.IA OS — Session Digest
4
+ * Trigger: PreCompact
5
+ *
6
+ * Salva um resumo da sessão antes do Claude compactar o contexto.
7
+ * Preserva memória institucional entre sessões longas.
8
+ * Inspirado no AIOS precompact-session-digest (MIT License, SynkraAI)
9
+ */
10
+
11
+ 'use strict';
12
+
13
+ const fs = require('fs');
14
+ const path = require('path');
15
+ const readline = require('readline');
16
+
17
+ async function main() {
18
+ let inputData = '';
19
+ try {
20
+ const rl = readline.createInterface({ input: process.stdin, terminal: false });
21
+ for await (const line of rl) {
22
+ inputData += line + '\n';
23
+ }
24
+ } catch (_) {
25
+ process.exit(0);
26
+ }
27
+
28
+ let data = {};
29
+ try {
30
+ data = JSON.parse(inputData);
31
+ } catch (_) {
32
+ process.exit(0);
33
+ }
34
+
35
+ const cwd = data.cwd || process.cwd();
36
+ const sessionId = data.session_id || 'unknown';
37
+ const timestamp = new Date()
38
+ .toISOString()
39
+ .slice(0, 19)
40
+ .replace('T', '_')
41
+ .replace(/:/g, '-');
42
+
43
+ const digestDir = path.join(cwd, '.genia', 'session-digests');
44
+ try {
45
+ fs.mkdirSync(digestDir, { recursive: true });
46
+ } catch (_) {
47
+ process.exit(0);
48
+ }
49
+
50
+ const digestPath = path.join(digestDir, `digest-${timestamp}.md`);
51
+
52
+ const content = `# Session Digest — ${timestamp}
53
+
54
+ **Session ID:** ${sessionId}
55
+ **Sistema:** GEN.IA OS — {{TEAM_NAME}}
56
+
57
+ ## Contexto Compactado
58
+
59
+ O Claude Code compactou o contexto desta sessão.
60
+ Este arquivo preserva o estado para retomada.
61
+
62
+ ## Como Retomar
63
+
64
+ 1. Leia as stories ativas em \`docs/stories/\`
65
+ 2. Verifique \`.genia/session/workflow-state.md\` para workflow em andamento
66
+ 3. Consulte \`.claude/agent-memory/[agente]/MEMORY.md\` do agente ativo
67
+ 4. Verifique git log para entender o que foi commitado
68
+
69
+ ## Dica
70
+
71
+ Ao retomar, informe ao agente:
72
+ > "Estou retomando a sessão. [descreva o contexto brevemente]"
73
+
74
+ ---
75
+ *Gerado automaticamente pelo GEN.IA OS Synapse Engine*
76
+ `;
77
+
78
+ try {
79
+ fs.writeFileSync(digestPath, content, 'utf8');
80
+ } catch (_) {
81
+ // Falha silenciosa — nunca bloquear o usuário
82
+ }
83
+
84
+ process.exit(0);
85
+ }
86
+
87
+ main().catch(() => process.exit(0));
@@ -0,0 +1,65 @@
1
+ #!/usr/bin/env python3
2
+ """
3
+ GEN.IA OS — Hook: sql-governance
4
+ Trigger: PreToolUse (Bash)
5
+ Ação: Bloqueia DDL SQL perigoso executado diretamente.
6
+ Permite operações via supabase CLI, pg_dump e psql -f (migrations controladas).
7
+ """
8
+ import json
9
+ import sys
10
+ import re
11
+
12
+
13
+ DANGEROUS_PATTERNS = [
14
+ r"\bDROP\s+TABLE\b",
15
+ r"\bDROP\s+DATABASE\b",
16
+ r"\bDROP\s+SCHEMA\b",
17
+ r"\bTRUNCATE\s+TABLE\b",
18
+ r"\bTRUNCATE\b\s+\w+",
19
+ r"\bALTER\s+TABLE\b.*\bDROP\s+COLUMN\b",
20
+ r"DELETE\s+FROM\s+\w+\s*;?\s*$", # DELETE sem WHERE
21
+ ]
22
+
23
+ SAFE_PATTERNS = [
24
+ r"supabase\s+(migration|db\s+push|db\s+diff)",
25
+ r"pg_dump\b",
26
+ r"psql\s+.*-f\s+",
27
+ r"\.sql\s*$", # executar arquivo .sql explícito
28
+ ]
29
+
30
+
31
+ def main():
32
+ try:
33
+ raw = sys.stdin.read()
34
+ data = json.loads(raw)
35
+ except Exception:
36
+ sys.exit(0)
37
+
38
+ tool = data.get("tool_name", "")
39
+ if tool != "Bash":
40
+ sys.exit(0)
41
+
42
+ command = data.get("tool_input", {}).get("command", "")
43
+
44
+ # Verificar se é operação segura de migration
45
+ for safe in SAFE_PATTERNS:
46
+ if re.search(safe, command, re.IGNORECASE):
47
+ sys.exit(0)
48
+
49
+ # Verificar padrões perigosos
50
+ cmd_upper = command.upper()
51
+ for pattern in DANGEROUS_PATTERNS:
52
+ if re.search(pattern, cmd_upper):
53
+ print(
54
+ "[GEN.IA OS] 🚫 BLOQUEADO — SQL destrutivo detectado.\n"
55
+ "[GEN.IA OS] Use 'supabase migration new <nome>' para alterações de schema.\n"
56
+ "[GEN.IA OS] Migrations controladas garantem rollback seguro.",
57
+ file=sys.stderr,
58
+ )
59
+ sys.exit(2)
60
+
61
+ sys.exit(0)
62
+
63
+
64
+ if __name__ == "__main__":
65
+ main()
@@ -0,0 +1,122 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * GEN.IA OS — Synapse Engine v1.0
4
+ * Trigger: UserPromptSubmit
5
+ *
6
+ * Pipeline de 3 camadas de injeção de contexto em cada prompt:
7
+ * L0: Constituição (sempre ativa, não-negociável)
8
+ * L1: Global + Contexto (sempre ativa)
9
+ * L2: Agente específico (quando @agente detectado no prompt)
10
+ *
11
+ * Timeout: 100ms — NUNCA bloqueia o usuário
12
+ * Inspirado no AIOS Synapse Engine (MIT License, SynkraAI)
13
+ * Adaptado e reescrito para GEN.IA OS — {{TEAM_NAME}} — {{CREATOR_NAME}}
14
+ */
15
+
16
+ 'use strict';
17
+
18
+ const fs = require('fs');
19
+ const path = require('path');
20
+ const readline = require('readline');
21
+
22
+ const TIMEOUT_MS = 100;
23
+ const SYNAPSE_DIR = '.synapse';
24
+
25
+ // Mapeamento de @agente → domínio synapse
26
+ const AGENT_DOMAINS = {
27
+ '@analyst': 'agent-analyst',
28
+ '@pm': 'agent-pm',
29
+ '@architect': 'agent-architect',
30
+ '@dev': 'agent-dev',
31
+ '@devops': 'agent-devops',
32
+ '@qa': 'agent-qa',
33
+ '@reviewer': 'agent-reviewer',
34
+ '@po': 'agent-po',
35
+ '@sm': 'agent-sm',
36
+ };
37
+
38
+ function readDomain(cwd, domainName) {
39
+ try {
40
+ const domainPath = path.join(cwd, SYNAPSE_DIR, domainName);
41
+ if (fs.existsSync(domainPath)) {
42
+ return fs.readFileSync(domainPath, 'utf8').trim();
43
+ }
44
+ } catch (_) {
45
+ // Falha silenciosa — Synapse nunca quebra o fluxo
46
+ }
47
+ return null;
48
+ }
49
+
50
+ function detectActiveAgent(prompt) {
51
+ if (!prompt) return null;
52
+ const lower = prompt.toLowerCase();
53
+ for (const [mention, domain] of Object.entries(AGENT_DOMAINS)) {
54
+ if (lower.includes(mention)) {
55
+ return domain;
56
+ }
57
+ }
58
+ return null;
59
+ }
60
+
61
+ async function run() {
62
+ let inputData = '';
63
+ try {
64
+ const rl = readline.createInterface({ input: process.stdin, terminal: false });
65
+ for await (const line of rl) {
66
+ inputData += line + '\n';
67
+ }
68
+ } catch (_) {
69
+ return '';
70
+ }
71
+
72
+ let data = {};
73
+ try {
74
+ data = JSON.parse(inputData);
75
+ } catch (_) {
76
+ return '';
77
+ }
78
+
79
+ const cwd = data.cwd || process.cwd();
80
+ const prompt = data.prompt || '';
81
+ const layers = [];
82
+
83
+ // L0 — Constituição (sempre)
84
+ const constitution = readDomain(cwd, 'constitution');
85
+ if (constitution) layers.push(constitution);
86
+
87
+ // L1 — Global (sempre)
88
+ const global = readDomain(cwd, 'global');
89
+ if (global) layers.push(global);
90
+
91
+ // L1 — Contexto (sempre)
92
+ const context = readDomain(cwd, 'context');
93
+ if (context) layers.push(context);
94
+
95
+ // L2 — Agente específico (se detectado)
96
+ const agentDomain = detectActiveAgent(prompt);
97
+ if (agentDomain) {
98
+ const agentRules = readDomain(cwd, agentDomain);
99
+ if (agentRules) layers.push(agentRules);
100
+ }
101
+
102
+ if (layers.length === 0) return '';
103
+
104
+ return `<synapse-rules>\n${layers.join('\n\n')}\n</synapse-rules>`;
105
+ }
106
+
107
+ async function main() {
108
+ // Timer de segurança — garante timeout de 100ms
109
+ const timeoutPromise = new Promise((resolve) =>
110
+ setTimeout(() => resolve(''), TIMEOUT_MS)
111
+ );
112
+
113
+ const result = await Promise.race([run(), timeoutPromise]);
114
+
115
+ process.stdout.write(JSON.stringify({ hookSpecificOutput: result || '' }));
116
+ process.exit(0);
117
+ }
118
+
119
+ main().catch(() => {
120
+ process.stdout.write(JSON.stringify({ hookSpecificOutput: '' }));
121
+ process.exit(0);
122
+ });
@@ -0,0 +1,59 @@
1
+ #!/usr/bin/env python3
2
+ """
3
+ GEN.IA OS — Hook: write-path-validation
4
+ Trigger: PreToolUse (Write)
5
+ Ação: Avisa quando documentos são criados fora do path padrão.
6
+ """
7
+ import json
8
+ import sys
9
+ import re
10
+ import os
11
+
12
+
13
+ # Padrões de arquivo → path recomendado
14
+ DOC_RULES = {
15
+ r"^PRD\.md$": "docs/[projeto]/PRD.md",
16
+ r"^SPEC-TECNICO\.md$": "docs/[projeto]/SPEC-TECNICO.md",
17
+ r"^COMERCIAL\.md$": "docs/[projeto]/COMERCIAL.md",
18
+ r"^BRIEFING\.md$": "docs/[projeto]/BRIEFING.md",
19
+ r"^STORY-\d+.*\.md$": "docs/stories/STORY-NNN-slug.md",
20
+ r"^ADR-\d+.*\.md$": "docs/[projeto]/adrs/ADR-NNN-titulo.md",
21
+ }
22
+
23
+
24
+ def main():
25
+ try:
26
+ raw = sys.stdin.read()
27
+ data = json.loads(raw)
28
+ except Exception:
29
+ sys.exit(0)
30
+
31
+ tool = data.get("tool_name", "")
32
+ if tool != "Write":
33
+ sys.exit(0)
34
+
35
+ file_path = data.get("tool_input", {}).get("file_path", "")
36
+ if not file_path:
37
+ sys.exit(0)
38
+
39
+ # Normalizar separadores
40
+ normalized = file_path.replace("\\", "/")
41
+ filename = os.path.basename(normalized)
42
+
43
+ for pattern, correct_path in DOC_RULES.items():
44
+ if re.match(pattern, filename, re.IGNORECASE):
45
+ # Verificar se está no path correto
46
+ if "docs/" not in normalized:
47
+ print(
48
+ f"[GEN.IA OS] ⚠️ Documento '{filename}' fora do path padrão.\n"
49
+ f"[GEN.IA OS] Path recomendado: {correct_path}\n"
50
+ f"[GEN.IA OS] Criando assim mesmo — ajuste se necessário.",
51
+ file=sys.stderr,
52
+ )
53
+ break
54
+
55
+ sys.exit(0) # Apenas avisa, não bloqueia
56
+
57
+
58
+ if __name__ == "__main__":
59
+ main()
@@ -0,0 +1,39 @@
1
+ # Autoridade dos Agentes — GEN.IA OS
2
+
3
+ ## Matriz de Delegação
4
+
5
+ | Agente | Nome | Autoridade Exclusiva | Git Permitido | Git Bloqueado |
6
+ |--------|------|---------------------|---------------|---------------|
7
+ | @analyst | Ana | Briefing, requisitos, pesquisa | status, log, diff | push, commit, merge |
8
+ | @pm | Marina | PRD, escopo, priorização, épicos | status, log, diff | push, commit, merge |
9
+ | @architect | Arqui | Arquitetura, stack, VETO técnico | status, log, diff | push, commit, merge |
10
+ | @dev | Dev | Implementação de código | checkout, add, commit | **PUSH (BLOQUEADO)** |
11
+ | @devops | Gate | **git push, PR, release, MCP** | TUDO | nada |
12
+ | @qa | Quinn | Veredictos de qualidade, testes | status, log, diff, stash | push, commit |
13
+ | @reviewer | Rev | Code review, aprovação | status, log, diff | push, commit |
14
+ | @po | Pax | Validação de stories, backlog | status, log, diff | push, commit, merge |
15
+ | @sm | Sami | **Criação de stories**, sprint | status, log, diff | push, commit, merge |
16
+
17
+ ## Regras Invioláveis (Artigo II da Constituição)
18
+
19
+ 1. **@dev NUNCA faz push** — sempre delegar para @devops após commit
20
+ 2. **@sm é o ÚNICO que cria stories** — nenhum outro agente cria STORY-*.md
21
+ 3. **@architect tem veto técnico irrevogável** — qualquer decisão arquitetural
22
+ 4. **@po é o ÚNICO que aprova stories** para ir para desenvolvimento
23
+ 5. **@devops gerencia MCP** — nenhum outro agente adiciona/remove servidores MCP
24
+
25
+ ## Protocolo de Escalação
26
+
27
+ Quando uma tarefa está fora do seu escopo:
28
+ 1. **PARAR** imediatamente
29
+ 2. **Anunciar** o agente correto: "Esta tarefa pertence a @[agente]"
30
+ 3. **Fazer handoff** usando o protocolo de `.claude/rules/agent-handoff.md`
31
+ 4. **NÃO executar** tarefas fora da sua autoridade
32
+
33
+ ## Exemplos de Escalação Obrigatória
34
+
35
+ - @dev termina implementação → delega push para **@devops**
36
+ - @dev tem dúvida arquitetural → consulta **@architect**
37
+ - @pm precisa de requisitos → solicita para **@analyst**
38
+ - @dev precisa de story → solicita para **@sm**
39
+ - @sm criou story → entrega para **@po** validar
@@ -0,0 +1,71 @@
1
+ # Protocolo de Handoff — GEN.IA OS
2
+
3
+ ## Quando Fazer Handoff
4
+
5
+ Handoff é obrigatório quando:
6
+ - Tarefa requer autoridade de outro agente (Artigo II)
7
+ - Fase do workflow mudou
8
+ - Blocker identificado fora do escopo atual
9
+ - Trabalho está completo e próxima etapa é de outro agente
10
+
11
+ ## Formato de Handoff (≤ 400 tokens)
12
+
13
+ ```
14
+ [@agente-atual → @próximo-agente]
15
+
16
+ 📋 Contexto: [O que foi feito em 2-3 frases]
17
+
18
+ 📌 Decisões tomadas:
19
+ - [decisão 1]
20
+ - [decisão 2]
21
+
22
+ 📁 Arquivos criados/modificados:
23
+ - [path/arquivo.md]
24
+
25
+ ⚠️ Pendências:
26
+ - [o que precisa ser feito]
27
+
28
+ 🔗 Story atual: STORY-NNN (se aplicável)
29
+ ```
30
+
31
+ ## Regra de Token Budget
32
+
33
+ - Handoff DEVE ser ≤ 400 tokens
34
+ - Após 2+ trocas de agente, comprimir histórico ao essencial
35
+ - Não repassar contexto completo — apenas decisões e pendências
36
+
37
+ ## Compressão de Contexto
38
+
39
+ Quando o contexto estiver saturado (muitas trocas de agente):
40
+
41
+ 1. Criar `.genia/session/context-summary.md` com:
42
+ - Decisões arquiteturais tomadas
43
+ - Stories em andamento e seus estados
44
+ - Blockers conhecidos
45
+ - Stack tecnológica confirmada
46
+
47
+ 2. Referenciar o arquivo no próximo handoff:
48
+ ```
49
+ [Contexto comprimido em .genia/session/context-summary.md]
50
+ ```
51
+
52
+ ## Exemplos de Handoff
53
+
54
+ **@dev → @devops (após implementação):**
55
+ ```
56
+ [@dev → @devops]
57
+ 📋 Implementei STORY-003 (autenticação JWT). Commits feitos localmente.
58
+ 📌 Decisões: Usei jose library, tokens expiram em 1h, refresh em 7d.
59
+ 📁 Modificados: src/auth/jwt.ts, src/middleware/auth.ts, tests/auth.test.ts
60
+ ⚠️ Pendências: Push da branch feat/STORY-003-jwt-auth e criar PR para main.
61
+ 🔗 Story atual: STORY-003 (status: InReview)
62
+ ```
63
+
64
+ **@analyst → @pm (após briefing):**
65
+ ```
66
+ [@analyst → @pm]
67
+ 📋 Coletei requisitos completos do sistema de orçamentos BrasilUp.
68
+ 📌 Decisões: App web (não mobile), integração com Kommo CRM, 3 usuários simultâneos.
69
+ 📁 Criados: docs/brasilup/BRIEFING.md
70
+ ⚠️ Pendências: Criar PRD com base no briefing. Atenção ao requisito de relatórios PDF.
71
+ ```
@@ -0,0 +1,61 @@
1
+ # Memória Persistente dos Agentes — GEN.IA OS
2
+
3
+ ## Localização
4
+
5
+ ```
6
+ .claude/agent-memory/
7
+ ├── analyst/MEMORY.md
8
+ ├── pm/MEMORY.md
9
+ ├── architect/MEMORY.md
10
+ ├── dev/MEMORY.md
11
+ ├── devops/MEMORY.md
12
+ ├── qa/MEMORY.md
13
+ ├── reviewer/MEMORY.md
14
+ ├── po/MEMORY.md
15
+ └── sm/MEMORY.md
16
+ ```
17
+
18
+ ## Regra de Leitura
19
+
20
+ Todo agente DEVE ler seu `MEMORY.md` ao ser ativado. Esta leitura é parte do protocolo de ativação.
21
+
22
+ ## Quando Atualizar
23
+
24
+ Atualizar o MEMORY.md quando:
25
+ - Descobrir padrão recorrente no projeto
26
+ - Resolver problema difícil (documentar a solução)
27
+ - Identificar preferência da usuária (Elidy)
28
+ - Encontrar um gotcha (armadilha) do projeto
29
+ - Tomar decisão arquitetural relevante
30
+
31
+ ## Formato do MEMORY.md
32
+
33
+ ```markdown
34
+ # MEMORY — @[agente] ([Nome])
35
+
36
+ > Memória persistente. Atualizada a cada sessão relevante.
37
+ > Última atualização: YYYY-MM-DD
38
+
39
+ ## Padrões Confirmados
40
+ - [padrão]: [quando usar]
41
+
42
+ ## Preferências da Usuária
43
+ - [preferência]: [contexto]
44
+
45
+ ## Gotchas do Projeto
46
+ - [problema]: [solução]
47
+
48
+ ## Decisões Importantes
49
+ - [decisão]: [justificativa e data]
50
+
51
+ ## Stack Tecnológica Confirmada
52
+ - [tecnologia]: [versão/contexto]
53
+ ```
54
+
55
+ ## Regra de Escrita
56
+
57
+ - Não adicionar informações duplicadas
58
+ - Verificar se já existe entry antes de criar nova
59
+ - Remover entries desatualizadas
60
+ - Máximo 200 linhas por arquivo (comprimir se necessário)
61
+ - Usar linguagem objetiva: fatos, não opiniões
@@ -0,0 +1,52 @@
1
+ # Princípios IDS — GEN.IA OS
2
+ ## Incremental Decision System
3
+
4
+ ## Hierarquia de Decisão
5
+
6
+ ```
7
+ REUSAR > ADAPTAR > CRIAR
8
+ ```
9
+
10
+ Antes de criar qualquer artefato (componente, task, template, módulo, contexto):
11
+
12
+ **1. REUSAR** — Buscar no projeto algo que já resolve o problema
13
+ **2. ADAPTAR** — Se 70%+ compatível, adaptar o existente
14
+ **3. CRIAR** — Apenas se reutilização não é viável
15
+
16
+ ## Onde Buscar Antes de Criar
17
+
18
+ | Tipo | Buscar em |
19
+ |------|-----------|
20
+ | Task | `.genia/development/tasks/` |
21
+ | Template de doc | `.claude/templates/` (se existir) |
22
+ | Contexto de API | `.genia/contexts/` |
23
+ | Skill | `.genia/skills/` |
24
+ | Guideline | `.genia/guidelines/` |
25
+ | Checklist | `.genia/development/checklists/` |
26
+
27
+ ## Justificativa Obrigatória para CRIAR
28
+
29
+ Ao criar novo artefato que poderia ser reusado, documentar inline:
30
+
31
+ ```
32
+ // NOVO: não foi possível reusar porque [razão]
33
+ // Adaptação de: [nada existente] | [X arquivo, mas incompatível por Y]
34
+ ```
35
+
36
+ ## Prevenção de Duplicação em Stories
37
+
38
+ Antes de criar `STORY-NNN`, verificar:
39
+ 1. Existe story similar em `docs/stories/`?
40
+ 2. Está dentro de um épico já existente?
41
+ 3. Já foi implementado e mergeado?
42
+
43
+ ## Circuit Breaker
44
+
45
+ Se a busca por artefato reutilizável demorar mais de 30 segundos, prosseguir com criação e documentar a tentativa de busca.
46
+
47
+ ## Benefícios
48
+
49
+ - Reduz explosão de arquivos no projeto
50
+ - Mantém consistência entre implementações similares
51
+ - Facilita manutenção no longo prazo
52
+ - Evita reinventar soluções já validadas
@@ -0,0 +1,49 @@
1
+ # Uso de Ferramentas e MCP — GEN.IA OS
2
+
3
+ ## Prioridade de Ferramentas
4
+
5
+ ```
6
+ 1. Ferramentas nativas Claude Code (sempre preferir)
7
+ 2. Ferramentas MCP configuradas (quando necessário)
8
+ 3. Bash com CLI tools (último recurso)
9
+ ```
10
+
11
+ ## Ferramentas Nativas — Sempre Preferir
12
+
13
+ | Operação | Ferramenta Correta | NÃO usar |
14
+ |----------|--------------------|----------|
15
+ | Ler arquivo | Read | Bash cat/head/tail |
16
+ | Criar arquivo | Write | Bash echo/cat heredoc |
17
+ | Editar arquivo | Edit | Bash sed/awk |
18
+ | Buscar arquivo | Glob | Bash find/ls |
19
+ | Buscar conteúdo | Grep | Bash grep/rg |
20
+ | Perguntar usuário | AskUserQuestion | — |
21
+ | Tarefa complexa | Task | — |
22
+
23
+ ## Gerenciamento MCP
24
+
25
+ **@devops é o ÚNICO autorizado a:**
26
+ - Adicionar servidores MCP
27
+ - Remover servidores MCP
28
+ - Configurar MCP (editar settings.json de MCP)
29
+ - Fazer upgrade de versão de servidor MCP
30
+
31
+ Outros agentes são **consumidores apenas**.
32
+
33
+ ## Regra de Ouro
34
+
35
+ > "Se uma ferramenta nativa do Claude Code resolve, não use MCP."
36
+
37
+ ## Servidores MCP Disponíveis
38
+
39
+ Ver configuração em `.claude/settings.json` (gerenciado por @devops).
40
+
41
+ ## Quando Usar Bash
42
+
43
+ Use Bash apenas para:
44
+ - Comandos git (quando necessário)
45
+ - Executar scripts (npm, python, etc.)
46
+ - Operações de sistema que não têm ferramenta nativa
47
+ - Comandos CLI específicos (supabase, gh, etc.)
48
+
49
+ Nunca para: leitura/escrita/busca de arquivos.