aios-core 4.0.2 → 4.0.4

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 (145) hide show
  1. package/.aios-core/.session/current-session.json +14 -0
  2. package/.aios-core/core/registry/registry-schema.json +166 -166
  3. package/.aios-core/core/registry/service-registry.json +6585 -6585
  4. package/.aios-core/data/registry-update-log.jsonl +113 -0
  5. package/.aios-core/development/scripts/approval-workflow.js +642 -642
  6. package/.aios-core/development/scripts/backup-manager.js +606 -606
  7. package/.aios-core/development/scripts/branch-manager.js +389 -389
  8. package/.aios-core/development/scripts/code-quality-improver.js +1311 -1311
  9. package/.aios-core/development/scripts/commit-message-generator.js +849 -849
  10. package/.aios-core/development/scripts/conflict-resolver.js +674 -674
  11. package/.aios-core/development/scripts/dependency-analyzer.js +637 -637
  12. package/.aios-core/development/scripts/diff-generator.js +351 -351
  13. package/.aios-core/development/scripts/elicitation-engine.js +384 -384
  14. package/.aios-core/development/scripts/elicitation-session-manager.js +299 -299
  15. package/.aios-core/development/scripts/git-wrapper.js +461 -461
  16. package/.aios-core/development/scripts/manifest-preview.js +244 -244
  17. package/.aios-core/development/scripts/metrics-tracker.js +775 -775
  18. package/.aios-core/development/scripts/modification-validator.js +554 -554
  19. package/.aios-core/development/scripts/pattern-learner.js +1224 -1224
  20. package/.aios-core/development/scripts/performance-analyzer.js +757 -757
  21. package/.aios-core/development/scripts/refactoring-suggester.js +1138 -1138
  22. package/.aios-core/development/scripts/rollback-handler.js +530 -530
  23. package/.aios-core/development/scripts/security-checker.js +358 -358
  24. package/.aios-core/development/scripts/template-engine.js +239 -239
  25. package/.aios-core/development/scripts/template-validator.js +278 -278
  26. package/.aios-core/development/scripts/test-generator.js +843 -843
  27. package/.aios-core/development/scripts/transaction-manager.js +589 -589
  28. package/.aios-core/development/scripts/usage-tracker.js +673 -673
  29. package/.aios-core/development/scripts/validate-filenames.js +226 -226
  30. package/.aios-core/development/scripts/version-tracker.js +526 -526
  31. package/.aios-core/development/scripts/yaml-validator.js +396 -396
  32. package/.aios-core/development/templates/service-template/README.md.hbs +158 -158
  33. package/.aios-core/development/templates/service-template/__tests__/index.test.ts.hbs +237 -237
  34. package/.aios-core/development/templates/service-template/client.ts.hbs +403 -403
  35. package/.aios-core/development/templates/service-template/errors.ts.hbs +182 -182
  36. package/.aios-core/development/templates/service-template/index.ts.hbs +120 -120
  37. package/.aios-core/development/templates/service-template/package.json.hbs +87 -87
  38. package/.aios-core/development/templates/service-template/types.ts.hbs +145 -145
  39. package/.aios-core/development/templates/squad-template/LICENSE +21 -21
  40. package/.aios-core/docs/SHARD-TRANSLATION-GUIDE.md +335 -0
  41. package/.aios-core/docs/component-creation-guide.md +458 -0
  42. package/.aios-core/docs/session-update-pattern.md +307 -0
  43. package/.aios-core/docs/standards/AIOS-FRAMEWORK-MASTER.md +1963 -0
  44. package/.aios-core/docs/standards/AIOS-LIVRO-DE-OURO-V2.1-SUMMARY.md +1190 -0
  45. package/.aios-core/docs/standards/AIOS-LIVRO-DE-OURO-V2.1.md +439 -0
  46. package/.aios-core/docs/standards/AIOS-LIVRO-DE-OURO.md +5398 -0
  47. package/.aios-core/docs/standards/V3-ARCHITECTURAL-DECISIONS.md +523 -0
  48. package/.aios-core/docs/template-syntax.md +267 -0
  49. package/.aios-core/docs/troubleshooting-guide.md +625 -0
  50. package/.aios-core/infrastructure/templates/aios-sync.yaml.template +193 -193
  51. package/.aios-core/infrastructure/templates/coderabbit.yaml.template +279 -279
  52. package/.aios-core/infrastructure/templates/github-workflows/ci.yml.template +169 -169
  53. package/.aios-core/infrastructure/templates/github-workflows/pr-automation.yml.template +330 -330
  54. package/.aios-core/infrastructure/templates/github-workflows/release.yml.template +196 -196
  55. package/.aios-core/infrastructure/templates/gitignore/gitignore-aios-base.tmpl +63 -63
  56. package/.aios-core/infrastructure/templates/gitignore/gitignore-brownfield-merge.tmpl +18 -18
  57. package/.aios-core/infrastructure/templates/gitignore/gitignore-node.tmpl +85 -85
  58. package/.aios-core/infrastructure/templates/gitignore/gitignore-python.tmpl +145 -145
  59. package/.aios-core/infrastructure/tests/utilities-audit-results.json +501 -0
  60. package/.aios-core/install-manifest.yaml +97 -97
  61. package/.aios-core/local-config.yaml.template +68 -68
  62. package/.aios-core/manifests/agents.csv +1 -0
  63. package/.aios-core/manifests/schema/manifest-schema.json +190 -190
  64. package/.aios-core/manifests/tasks.csv +121 -0
  65. package/.aios-core/manifests/workers.csv +204 -0
  66. package/.aios-core/monitor/hooks/lib/__init__.py +1 -1
  67. package/.aios-core/monitor/hooks/lib/enrich.py +58 -58
  68. package/.aios-core/monitor/hooks/lib/send_event.py +47 -47
  69. package/.aios-core/monitor/hooks/notification.py +29 -29
  70. package/.aios-core/monitor/hooks/post_tool_use.py +45 -45
  71. package/.aios-core/monitor/hooks/pre_compact.py +29 -29
  72. package/.aios-core/monitor/hooks/pre_tool_use.py +40 -40
  73. package/.aios-core/monitor/hooks/stop.py +29 -29
  74. package/.aios-core/monitor/hooks/subagent_stop.py +29 -29
  75. package/.aios-core/monitor/hooks/user_prompt_submit.py +38 -38
  76. package/.aios-core/product/templates/adr.hbs +125 -125
  77. package/.aios-core/product/templates/component-react-tmpl.tsx +98 -98
  78. package/.aios-core/product/templates/dbdr.hbs +241 -241
  79. package/.aios-core/product/templates/engine/schemas/adr.schema.json +102 -102
  80. package/.aios-core/product/templates/engine/schemas/dbdr.schema.json +205 -205
  81. package/.aios-core/product/templates/engine/schemas/epic.schema.json +175 -175
  82. package/.aios-core/product/templates/engine/schemas/pmdr.schema.json +175 -175
  83. package/.aios-core/product/templates/engine/schemas/prd-v2.schema.json +300 -300
  84. package/.aios-core/product/templates/engine/schemas/prd.schema.json +152 -152
  85. package/.aios-core/product/templates/engine/schemas/story.schema.json +222 -222
  86. package/.aios-core/product/templates/engine/schemas/task.schema.json +154 -154
  87. package/.aios-core/product/templates/epic.hbs +212 -212
  88. package/.aios-core/product/templates/eslintrc-security.json +32 -32
  89. package/.aios-core/product/templates/github-actions-cd.yml +212 -212
  90. package/.aios-core/product/templates/github-actions-ci.yml +172 -172
  91. package/.aios-core/product/templates/pmdr.hbs +186 -186
  92. package/.aios-core/product/templates/prd-v2.0.hbs +216 -216
  93. package/.aios-core/product/templates/prd.hbs +201 -201
  94. package/.aios-core/product/templates/shock-report-tmpl.html +502 -502
  95. package/.aios-core/product/templates/story.hbs +263 -263
  96. package/.aios-core/product/templates/task.hbs +170 -170
  97. package/.aios-core/product/templates/tmpl-comment-on-examples.sql +158 -158
  98. package/.aios-core/product/templates/tmpl-migration-script.sql +91 -91
  99. package/.aios-core/product/templates/tmpl-rls-granular-policies.sql +104 -104
  100. package/.aios-core/product/templates/tmpl-rls-kiss-policy.sql +10 -10
  101. package/.aios-core/product/templates/tmpl-rls-roles.sql +135 -135
  102. package/.aios-core/product/templates/tmpl-rls-simple.sql +77 -77
  103. package/.aios-core/product/templates/tmpl-rls-tenant.sql +152 -152
  104. package/.aios-core/product/templates/tmpl-rollback-script.sql +77 -77
  105. package/.aios-core/product/templates/tmpl-seed-data.sql +140 -140
  106. package/.aios-core/product/templates/tmpl-smoke-test.sql +16 -16
  107. package/.aios-core/product/templates/tmpl-staging-copy-merge.sql +139 -139
  108. package/.aios-core/product/templates/tmpl-stored-proc.sql +140 -140
  109. package/.aios-core/product/templates/tmpl-trigger.sql +152 -152
  110. package/.aios-core/product/templates/tmpl-view-materialized.sql +133 -133
  111. package/.aios-core/product/templates/tmpl-view.sql +177 -177
  112. package/.aios-core/product/templates/token-exports-css-tmpl.css +240 -240
  113. package/.aios-core/quality/schemas/quality-metrics.schema.json +233 -233
  114. package/.aios-core/scripts/migrate-framework-docs.sh +300 -300
  115. package/.aios-core/scripts/pm.sh +0 -0
  116. package/.claude/hooks/enforce-architecture-first.py +196 -0
  117. package/.claude/hooks/install-hooks.sh +41 -0
  118. package/.claude/hooks/mind-clone-governance.py +192 -0
  119. package/.claude/hooks/pre-commit-mmos-guard.sh +99 -0
  120. package/.claude/hooks/pre-commit-version-check.sh +156 -0
  121. package/.claude/hooks/read-protection.py +151 -0
  122. package/.claude/hooks/slug-validation.py +176 -0
  123. package/.claude/hooks/sql-governance.py +182 -0
  124. package/.claude/hooks/write-path-validation.py +194 -0
  125. package/.claude/rules/agent-authority.md +105 -0
  126. package/.claude/rules/coderabbit-integration.md +93 -0
  127. package/.claude/rules/ids-principles.md +112 -0
  128. package/.claude/rules/story-lifecycle.md +139 -0
  129. package/.claude/rules/workflow-execution.md +150 -0
  130. package/LICENSE +48 -48
  131. package/README.md +30 -7
  132. package/bin/aios-minimal.js +0 -0
  133. package/bin/aios.js +15 -15
  134. package/package.json +2 -4
  135. package/packages/aios-install/bin/aios-install.js +0 -0
  136. package/packages/aios-install/bin/edmcp.js +0 -0
  137. package/packages/aios-pro-cli/bin/aios-pro.js +0 -0
  138. package/scripts/check-markdown-links.py +352 -352
  139. package/scripts/dashboard-parallel-dev.sh +0 -0
  140. package/scripts/dashboard-parallel-phase3.sh +0 -0
  141. package/scripts/dashboard-parallel-phase4.sh +0 -0
  142. package/scripts/glue/README.md +355 -0
  143. package/scripts/glue/compose-agent-prompt.cjs +362 -0
  144. package/scripts/install-monitor-hooks.sh +0 -0
  145. package/.aios-core/lib/build.json +0 -1
@@ -0,0 +1,151 @@
1
+ #!/usr/bin/env python3
2
+ """
3
+ Hook: Read Protection
4
+
5
+ REGRA: Arquivos protegidos DEVEM ser lidos completamente (sem limit/offset).
6
+
7
+ Este hook intercepta chamadas Read e bloqueia leitura parcial em arquivos
8
+ que requerem contexto completo para edição segura.
9
+
10
+ Exit Codes:
11
+ - 0: Permitido
12
+ - 2: Bloqueado (arquivo protegido com limit/offset)
13
+ """
14
+
15
+ import json
16
+ import sys
17
+ import os
18
+ import fnmatch
19
+ from pathlib import Path
20
+
21
+ # =============================================================================
22
+ # CONFIGURAÇÃO: Arquivos que DEVEM ser lidos completamente
23
+ # =============================================================================
24
+
25
+ PROTECTED_PATTERNS = [
26
+ # Configuração do Claude
27
+ ".claude/CLAUDE.md",
28
+ ".claude/rules/*.md",
29
+ ".claude/settings*.json",
30
+
31
+ # Definições de agentes
32
+ ".aios-core/development/agents/*.md",
33
+ ".aios-upstream/.aios-core/development/agents/*.md",
34
+
35
+ # Documentação crítica
36
+ "docs/mmos/ARCHITECTURE_RULES.md",
37
+ "supabase/docs/SCHEMA.md",
38
+
39
+ # Configuração do projeto
40
+ "package.json",
41
+ "tsconfig.json",
42
+ "tsconfig.*.json",
43
+
44
+ # Arquivos de código críticos
45
+ "app/components/ui/icons/icon-map.ts",
46
+
47
+ # Migrations (sempre ler completo antes de editar)
48
+ "supabase/migrations/*.sql",
49
+ ]
50
+
51
+ # =============================================================================
52
+ # LÓGICA DO HOOK
53
+ # =============================================================================
54
+
55
+ def get_project_root():
56
+ """Obtém o root do projeto via variável de ambiente ou cwd."""
57
+ return os.environ.get("CLAUDE_PROJECT_DIR", os.getcwd())
58
+
59
+ def normalize_path(file_path: str, project_root: str) -> str:
60
+ """Normaliza path para relativo ao projeto."""
61
+ if file_path.startswith(project_root):
62
+ return file_path[len(project_root):].lstrip("/")
63
+ if file_path.startswith("/"):
64
+ # Path absoluto fora do projeto
65
+ return file_path
66
+ return file_path
67
+
68
+ def matches_protected_pattern(relative_path: str) -> bool:
69
+ """Verifica se o path corresponde a algum padrão protegido."""
70
+ for pattern in PROTECTED_PATTERNS:
71
+ if fnmatch.fnmatch(relative_path, pattern):
72
+ return True
73
+ # Também verificar se é substring (para paths com wildcards)
74
+ if "*" not in pattern and pattern in relative_path:
75
+ return True
76
+ return False
77
+
78
+ def has_partial_read_params(tool_input: dict) -> tuple[bool, str]:
79
+ """Verifica se a chamada Read tem parâmetros de leitura parcial."""
80
+ limit = tool_input.get("limit")
81
+ offset = tool_input.get("offset")
82
+
83
+ reasons = []
84
+ if limit is not None:
85
+ reasons.append(f"limit={limit}")
86
+ if offset is not None and offset != 0:
87
+ reasons.append(f"offset={offset}")
88
+
89
+ return len(reasons) > 0, ", ".join(reasons)
90
+
91
+ def main():
92
+ # Ler input do stdin
93
+ try:
94
+ input_data = json.load(sys.stdin)
95
+ except json.JSONDecodeError:
96
+ # Se não conseguir parsear, permitir (fail-open)
97
+ sys.exit(0)
98
+
99
+ tool_name = input_data.get("tool_name", "")
100
+ tool_input = input_data.get("tool_input", {})
101
+
102
+ # Só processar Read
103
+ if tool_name != "Read":
104
+ sys.exit(0)
105
+
106
+ file_path = tool_input.get("file_path", "")
107
+ if not file_path:
108
+ sys.exit(0)
109
+
110
+ # Normalizar path
111
+ project_root = get_project_root()
112
+ relative_path = normalize_path(file_path, project_root)
113
+
114
+ # Verificar se é arquivo protegido
115
+ if not matches_protected_pattern(relative_path):
116
+ sys.exit(0)
117
+
118
+ # Verificar se tem parâmetros de leitura parcial
119
+ is_partial, partial_reason = has_partial_read_params(tool_input)
120
+
121
+ if not is_partial:
122
+ # Leitura completa, permitir
123
+ sys.exit(0)
124
+
125
+ # BLOQUEAR: Tentando ler arquivo protegido parcialmente
126
+ error_message = f"""
127
+ ╔══════════════════════════════════════════════════════════════════════════════╗
128
+ ║ 🛑 READ PROTECTION: Arquivo protegido deve ser lido completamente ║
129
+ ╠══════════════════════════════════════════════════════════════════════════════╣
130
+ ║ ║
131
+ ║ Arquivo: {relative_path[:58]:<58} ║
132
+ ║ Problema: {partial_reason:<57} ║
133
+ ║ ║
134
+ ║ REGRA: Este arquivo está na lista de arquivos protegidos. ║
135
+ ║ Arquivos protegidos DEVEM ser lidos completamente para evitar: ║
136
+ ║ - Edições com contexto incompleto ║
137
+ ║ - Duplicações acidentais ║
138
+ ║ - Breaking changes não intencionais ║
139
+ ║ ║
140
+ ║ SOLUÇÃO: Remova os parâmetros 'limit' e 'offset' da chamada Read. ║
141
+ ║ ║
142
+ ║ ✅ Read(file_path="{relative_path[:40]}")
143
+ ║ ❌ Read(file_path="...", limit=100) ║
144
+ ║ ║
145
+ ╚══════════════════════════════════════════════════════════════════════════════╝
146
+ """
147
+ print(error_message, file=sys.stderr)
148
+ sys.exit(2)
149
+
150
+ if __name__ == "__main__":
151
+ main()
@@ -0,0 +1,176 @@
1
+ #!/usr/bin/env python3
2
+ """
3
+ Hook: Slug Validation
4
+
5
+ REGRA: Todos os slugs DEVEM usar snake_case (underscores, não hyphens).
6
+
7
+ Este hook intercepta comandos SQL que inserem/atualizam slugs e valida
8
+ o formato antes de permitir a operação.
9
+
10
+ Pattern válido: ^[a-z0-9]+(_[a-z0-9]+)*$
11
+ Exemplos válidos: jose_carlos_amorim, alan_nicolas, elon_musk
12
+ Exemplos inválidos: jose-carlos-amorim, JoseAmorim, ELON_MUSK
13
+
14
+ Exit Codes:
15
+ - 0: Permitido
16
+ - 2: Bloqueado (slug com formato inválido)
17
+ """
18
+
19
+ import json
20
+ import sys
21
+ import re
22
+
23
+ # =============================================================================
24
+ # CONFIGURAÇÃO
25
+ # =============================================================================
26
+
27
+ # Pattern válido para slugs
28
+ SLUG_PATTERN = re.compile(r"^[a-z0-9]+(_[a-z0-9]+)*$")
29
+
30
+ # Tabelas que têm coluna slug
31
+ TABLES_WITH_SLUG = [
32
+ "minds",
33
+ "contents",
34
+ "content_projects",
35
+ "tools",
36
+ "drivers",
37
+ "mapping_systems",
38
+ "frameworks",
39
+ ]
40
+
41
+ # =============================================================================
42
+ # LÓGICA DO HOOK
43
+ # =============================================================================
44
+
45
+ def extract_slug_values(command: str) -> list[tuple[str, str]]:
46
+ """
47
+ Extrai valores de slug de comandos SQL INSERT/UPDATE.
48
+
49
+ Returns:
50
+ Lista de tuplas (table, slug_value)
51
+ """
52
+ found = []
53
+ command_upper = command.upper()
54
+
55
+ for table in TABLES_WITH_SLUG:
56
+ table_upper = table.upper()
57
+
58
+ # Detectar INSERT INTO table (..., slug, ...) VALUES (..., 'value', ...)
59
+ insert_pattern = rf"INSERT\s+INTO\s+{table}\s*\([^)]*\bslug\b[^)]*\)\s*VALUES\s*\(([^)]+)\)"
60
+ insert_match = re.search(insert_pattern, command, re.IGNORECASE)
61
+ if insert_match:
62
+ values_str = insert_match.group(1)
63
+ # Extrair valores entre aspas
64
+ slug_values = re.findall(r"'([^']+)'", values_str)
65
+ for sv in slug_values:
66
+ # Verificar se parece um slug (não é UUID, não é número)
67
+ if not re.match(r"^[0-9a-f-]{36}$", sv) and not sv.isdigit():
68
+ found.append((table, sv))
69
+
70
+ # Detectar UPDATE table SET slug = 'value'
71
+ update_pattern = rf"UPDATE\s+{table}\s+.*SET\s+.*\bslug\s*=\s*'([^']+)'"
72
+ update_match = re.search(update_pattern, command, re.IGNORECASE)
73
+ if update_match:
74
+ found.append((table, update_match.group(1)))
75
+
76
+ return found
77
+
78
+ def validate_slug(slug: str) -> tuple[bool, str]:
79
+ """
80
+ Valida se o slug está no formato correto.
81
+
82
+ Returns:
83
+ (is_valid, error_message)
84
+ """
85
+ if SLUG_PATTERN.match(slug):
86
+ return True, ""
87
+
88
+ errors = []
89
+
90
+ if "-" in slug:
91
+ errors.append("contém hyphens (use underscores)")
92
+ if any(c.isupper() for c in slug):
93
+ errors.append("contém maiúsculas (use lowercase)")
94
+ if slug.startswith("_") or slug.endswith("_"):
95
+ errors.append("começa ou termina com underscore")
96
+ if "__" in slug:
97
+ errors.append("contém underscores duplos")
98
+ if not errors:
99
+ errors.append("formato inválido")
100
+
101
+ return False, ", ".join(errors)
102
+
103
+ def main():
104
+ # Ler input do stdin
105
+ try:
106
+ input_data = json.load(sys.stdin)
107
+ except json.JSONDecodeError:
108
+ sys.exit(0)
109
+
110
+ tool_name = input_data.get("tool_name", "")
111
+ tool_input = input_data.get("tool_input", {})
112
+
113
+ # Só processar Bash
114
+ if tool_name != "Bash":
115
+ sys.exit(0)
116
+
117
+ command = tool_input.get("command", "")
118
+ if not command:
119
+ sys.exit(0)
120
+
121
+ # Extrair slugs do comando
122
+ slug_values = extract_slug_values(command)
123
+
124
+ if not slug_values:
125
+ sys.exit(0)
126
+
127
+ # Validar cada slug
128
+ invalid_slugs = []
129
+ for table, slug in slug_values:
130
+ is_valid, error = validate_slug(slug)
131
+ if not is_valid:
132
+ invalid_slugs.append((table, slug, error))
133
+
134
+ if not invalid_slugs:
135
+ sys.exit(0)
136
+
137
+ # BLOQUEAR: Slug inválido detectado
138
+ slug_errors = "\n".join([
139
+ f"║ • {table}.slug = '{slug[:30]}' → {error[:30]:<30} ║"
140
+ for table, slug, error in invalid_slugs[:5]
141
+ ])
142
+
143
+ # Sugerir correção
144
+ suggestions = "\n".join([
145
+ f"║ • '{slug}' → '{slug.lower().replace('-', '_')}'{'':>30} ║"
146
+ for _, slug, _ in invalid_slugs[:5]
147
+ ])
148
+
149
+ error_message = f"""
150
+ ╔══════════════════════════════════════════════════════════════════════════════╗
151
+ ║ 🛑 SLUG VALIDATION: Formato de slug inválido ║
152
+ ╠══════════════════════════════════════════════════════════════════════════════╣
153
+ ║ ║
154
+ ║ Slugs inválidos detectados: ║
155
+ {slug_errors}
156
+ ║ ║
157
+ ║ REGRA: Todos os slugs DEVEM usar snake_case ║
158
+ ║ ║
159
+ ║ Pattern válido: ^[a-z0-9]+(_[a-z0-9]+)*$ ║
160
+ ║ ✅ jose_carlos_amorim ║
161
+ ║ ✅ alan_nicolas ║
162
+ ║ ❌ jose-carlos-amorim (hyphen) ║
163
+ ║ ❌ JoseAmorim (camelCase) ║
164
+ ║ ║
165
+ ║ Sugestões de correção: ║
166
+ {suggestions}
167
+ ║ ║
168
+ ║ POR QUÊ: Slugs inconsistentes causam falhas silenciosas no frontend. ║
169
+ ║ ║
170
+ ╚══════════════════════════════════════════════════════════════════════════════╝
171
+ """
172
+ print(error_message, file=sys.stderr)
173
+ sys.exit(2)
174
+
175
+ if __name__ == "__main__":
176
+ main()
@@ -0,0 +1,182 @@
1
+ #!/usr/bin/env python3
2
+ """
3
+ Hook: SQL Governance
4
+
5
+ REGRA: Comandos SQL que criam/alteram/deletam objetos de banco DEVEM ser aprovados.
6
+
7
+ Este hook intercepta comandos Bash que contêm SQL perigoso e bloqueia
8
+ operações não autorizadas em banco de dados.
9
+
10
+ Exit Codes:
11
+ - 0: Permitido
12
+ - 2: Bloqueado (SQL perigoso detectado)
13
+ """
14
+
15
+ import json
16
+ import sys
17
+ import os
18
+ import re
19
+
20
+ # =============================================================================
21
+ # CONFIGURAÇÃO: Patterns SQL que requerem aprovação
22
+ # =============================================================================
23
+
24
+ DANGEROUS_PATTERNS = [
25
+ # DDL - Criação
26
+ (r"\bCREATE\s+TABLE\b", "CREATE TABLE"),
27
+ (r"\bCREATE\s+VIEW\b", "CREATE VIEW"),
28
+ (r"\bCREATE\s+MATERIALIZED\s+VIEW\b", "CREATE MATERIALIZED VIEW"),
29
+ (r"\bCREATE\s+FUNCTION\b", "CREATE FUNCTION"),
30
+ (r"\bCREATE\s+TRIGGER\b", "CREATE TRIGGER"),
31
+ (r"\bCREATE\s+INDEX\b", "CREATE INDEX"),
32
+ (r"\bCREATE\s+TYPE\b", "CREATE TYPE"),
33
+ (r"\bCREATE\s+SCHEMA\b", "CREATE SCHEMA"),
34
+ (r"\bCREATE\s+EXTENSION\b", "CREATE EXTENSION"),
35
+ (r"\bCREATE\s+POLICY\b", "CREATE POLICY"),
36
+
37
+ # DDL - Alteração
38
+ (r"\bALTER\s+TABLE\b", "ALTER TABLE"),
39
+ (r"\bALTER\s+VIEW\b", "ALTER VIEW"),
40
+ (r"\bALTER\s+FUNCTION\b", "ALTER FUNCTION"),
41
+
42
+ # DDL - Deleção
43
+ (r"\bDROP\s+TABLE\b", "DROP TABLE"),
44
+ (r"\bDROP\s+VIEW\b", "DROP VIEW"),
45
+ (r"\bDROP\s+FUNCTION\b", "DROP FUNCTION"),
46
+ (r"\bDROP\s+TRIGGER\b", "DROP TRIGGER"),
47
+ (r"\bDROP\s+INDEX\b", "DROP INDEX"),
48
+ (r"\bDROP\s+SCHEMA\b", "DROP SCHEMA"),
49
+ (r"\bDROP\s+POLICY\b", "DROP POLICY"),
50
+
51
+ # DML Perigoso
52
+ (r"\bTRUNCATE\b", "TRUNCATE"),
53
+ (r"\bDELETE\s+FROM\b(?!.*\bWHERE\b)", "DELETE without WHERE"),
54
+
55
+ # Backup proibido (criar tabela como cópia)
56
+ (r"\bCREATE\s+TABLE\b.*\bAS\s+SELECT\b", "CREATE TABLE AS SELECT (backup proibido)"),
57
+
58
+ # Storage
59
+ (r"\bINSERT\s+INTO\s+storage\.buckets\b", "INSERT INTO storage.buckets"),
60
+ ]
61
+
62
+ # Patterns que indicam contexto seguro (não bloquear)
63
+ SAFE_CONTEXTS = [
64
+ r"--.*$", # Comentário SQL
65
+ r"SELECT\s+.*\bFROM\b", # Query de leitura
66
+ r"information_schema", # Query de metadata
67
+ r"pg_catalog", # Query de sistema
68
+ r"\bEXPLAIN\b", # Explain plan
69
+ ]
70
+
71
+ # Comandos que são sempre permitidos
72
+ ALLOWED_COMMANDS = [
73
+ "supabase migration", # CLI de migration
74
+ "supabase db push", # Push de migrations
75
+ "supabase db pull", # Pull de schema
76
+ "pg_dump", # Backup (exportar)
77
+ "psql.*-f.*migrations", # Aplicar migration file
78
+ ]
79
+
80
+ # =============================================================================
81
+ # LÓGICA DO HOOK
82
+ # =============================================================================
83
+
84
+ def extract_sql_from_command(command: str) -> str:
85
+ """Extrai possível SQL de um comando bash."""
86
+ # Remover aspas externas se houver
87
+ sql = command
88
+
89
+ # Detectar SQL inline em psql -c
90
+ psql_match = re.search(r'psql.*-c\s+["\'](.+?)["\']', command, re.DOTALL)
91
+ if psql_match:
92
+ sql = psql_match.group(1)
93
+
94
+ # Detectar heredoc
95
+ heredoc_match = re.search(r'<<["\']?(\w+)["\']?\s*\n(.+?)\n\1', command, re.DOTALL)
96
+ if heredoc_match:
97
+ sql = heredoc_match.group(2)
98
+
99
+ return sql.upper()
100
+
101
+ def is_safe_context(command: str) -> bool:
102
+ """Verifica se o comando está em contexto seguro."""
103
+ command_lower = command.lower()
104
+
105
+ for allowed in ALLOWED_COMMANDS:
106
+ if re.search(allowed, command_lower):
107
+ return True
108
+
109
+ return False
110
+
111
+ def detect_dangerous_sql(command: str) -> list[tuple[str, str]]:
112
+ """Detecta patterns SQL perigosos no comando."""
113
+ sql = extract_sql_from_command(command)
114
+ detected = []
115
+
116
+ for pattern, description in DANGEROUS_PATTERNS:
117
+ if re.search(pattern, sql, re.IGNORECASE):
118
+ detected.append((pattern, description))
119
+
120
+ return detected
121
+
122
+ def main():
123
+ # Ler input do stdin
124
+ try:
125
+ input_data = json.load(sys.stdin)
126
+ except json.JSONDecodeError:
127
+ # Se não conseguir parsear, permitir (fail-open)
128
+ sys.exit(0)
129
+
130
+ tool_name = input_data.get("tool_name", "")
131
+ tool_input = input_data.get("tool_input", {})
132
+
133
+ # Só processar Bash
134
+ if tool_name != "Bash":
135
+ sys.exit(0)
136
+
137
+ command = tool_input.get("command", "")
138
+ if not command:
139
+ sys.exit(0)
140
+
141
+ # Verificar se é contexto seguro
142
+ if is_safe_context(command):
143
+ sys.exit(0)
144
+
145
+ # Detectar SQL perigoso
146
+ dangerous = detect_dangerous_sql(command)
147
+
148
+ if not dangerous:
149
+ sys.exit(0)
150
+
151
+ # BLOQUEAR: SQL perigoso detectado
152
+ detected_list = "\n".join([f"║ • {desc:<64} ║" for _, desc in dangerous[:5]])
153
+
154
+ error_message = f"""
155
+ ╔══════════════════════════════════════════════════════════════════════════════╗
156
+ ║ 🛑 SQL GOVERNANCE: Operação de banco requer aprovação ║
157
+ ╠══════════════════════════════════════════════════════════════════════════════╣
158
+ ║ ║
159
+ ║ Operações detectadas: ║
160
+ {detected_list}
161
+ ║ ║
162
+ ║ REGRA: Comandos que criam/alteram/deletam objetos de banco DEVEM: ║
163
+ ║ ║
164
+ ║ 1. Ser propostos ao usuário ANTES de executar ║
165
+ ║ 2. Incluir justificativa e análise de impacto ║
166
+ ║ 3. Aguardar aprovação explícita ║
167
+ ║ ║
168
+ ║ EXCEÇÕES PERMITIDAS: ║
169
+ ║ • supabase migration (CLI oficial) ║
170
+ ║ • pg_dump (backup/export) ║
171
+ ║ • Aplicar migrations existentes em supabase/migrations/ ║
172
+ ║ ║
173
+ ║ AÇÃO: Proponha as mudanças ao usuário e aguarde aprovação. ║
174
+ ║ Use o formato: Schema/SQL + Justificativa + Impacto ║
175
+ ║ ║
176
+ ╚══════════════════════════════════════════════════════════════════════════════╝
177
+ """
178
+ print(error_message, file=sys.stderr)
179
+ sys.exit(2)
180
+
181
+ if __name__ == "__main__":
182
+ main()