aiox-core 5.0.0 → 5.0.2

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 (91) hide show
  1. package/.aiox-core/data/entity-registry.yaml +5297 -1814
  2. package/.aiox-core/data/registry-update-log.jsonl +2 -0
  3. package/.aiox-core/development/templates/service-template/README.md.hbs +158 -158
  4. package/.aiox-core/development/templates/service-template/__tests__/index.test.ts.hbs +237 -237
  5. package/.aiox-core/development/templates/service-template/client.ts.hbs +403 -403
  6. package/.aiox-core/development/templates/service-template/errors.ts.hbs +182 -182
  7. package/.aiox-core/development/templates/service-template/index.ts.hbs +120 -120
  8. package/.aiox-core/development/templates/service-template/package.json.hbs +87 -87
  9. package/.aiox-core/development/templates/service-template/types.ts.hbs +145 -145
  10. package/.aiox-core/development/templates/squad-template/LICENSE +21 -21
  11. package/.aiox-core/infrastructure/scripts/tool-resolver.js +4 -4
  12. package/.aiox-core/infrastructure/templates/aiox-sync.yaml.template +182 -182
  13. package/.aiox-core/infrastructure/templates/coderabbit.yaml.template +279 -279
  14. package/.aiox-core/infrastructure/templates/github-workflows/ci.yml.template +169 -169
  15. package/.aiox-core/infrastructure/templates/github-workflows/pr-automation.yml.template +330 -330
  16. package/.aiox-core/infrastructure/templates/github-workflows/release.yml.template +196 -196
  17. package/.aiox-core/infrastructure/templates/gitignore/gitignore-aiox-base.tmpl +63 -63
  18. package/.aiox-core/infrastructure/templates/gitignore/gitignore-brownfield-merge.tmpl +18 -18
  19. package/.aiox-core/infrastructure/templates/gitignore/gitignore-node.tmpl +85 -85
  20. package/.aiox-core/infrastructure/templates/gitignore/gitignore-python.tmpl +145 -145
  21. package/.aiox-core/install-manifest.yaml +58 -58
  22. package/.aiox-core/local-config.yaml.template +71 -71
  23. package/.aiox-core/monitor/hooks/lib/__init__.py +1 -1
  24. package/.aiox-core/monitor/hooks/lib/enrich.py +58 -58
  25. package/.aiox-core/monitor/hooks/lib/send_event.py +47 -47
  26. package/.aiox-core/monitor/hooks/notification.py +29 -29
  27. package/.aiox-core/monitor/hooks/post_tool_use.py +45 -45
  28. package/.aiox-core/monitor/hooks/pre_compact.py +29 -29
  29. package/.aiox-core/monitor/hooks/pre_tool_use.py +40 -40
  30. package/.aiox-core/monitor/hooks/stop.py +29 -29
  31. package/.aiox-core/monitor/hooks/subagent_stop.py +29 -29
  32. package/.aiox-core/monitor/hooks/user_prompt_submit.py +38 -38
  33. package/.aiox-core/product/templates/adr.hbs +125 -125
  34. package/.aiox-core/product/templates/dbdr.hbs +241 -241
  35. package/.aiox-core/product/templates/engine/elicitation.js +2 -3
  36. package/.aiox-core/product/templates/epic.hbs +212 -212
  37. package/.aiox-core/product/templates/pmdr.hbs +186 -186
  38. package/.aiox-core/product/templates/prd-v2.0.hbs +216 -216
  39. package/.aiox-core/product/templates/prd.hbs +201 -201
  40. package/.aiox-core/product/templates/story.hbs +263 -263
  41. package/.aiox-core/product/templates/task.hbs +170 -170
  42. package/.aiox-core/product/templates/tmpl-comment-on-examples.sql +158 -158
  43. package/.aiox-core/product/templates/tmpl-migration-script.sql +91 -91
  44. package/.aiox-core/product/templates/tmpl-rls-granular-policies.sql +104 -104
  45. package/.aiox-core/product/templates/tmpl-rls-kiss-policy.sql +10 -10
  46. package/.aiox-core/product/templates/tmpl-rls-roles.sql +135 -135
  47. package/.aiox-core/product/templates/tmpl-rls-simple.sql +77 -77
  48. package/.aiox-core/product/templates/tmpl-rls-tenant.sql +152 -152
  49. package/.aiox-core/product/templates/tmpl-rollback-script.sql +77 -77
  50. package/.aiox-core/product/templates/tmpl-seed-data.sql +140 -140
  51. package/.aiox-core/product/templates/tmpl-smoke-test.sql +16 -16
  52. package/.aiox-core/product/templates/tmpl-staging-copy-merge.sql +139 -139
  53. package/.aiox-core/product/templates/tmpl-stored-proc.sql +140 -140
  54. package/.aiox-core/product/templates/tmpl-trigger.sql +152 -152
  55. package/.aiox-core/product/templates/tmpl-view-materialized.sql +133 -133
  56. package/.aiox-core/product/templates/tmpl-view.sql +177 -177
  57. package/.aiox-core/scripts/pm.sh +0 -0
  58. package/.claude/hooks/code-intel-pretool.cjs +107 -0
  59. package/.claude/hooks/enforce-architecture-first.py +196 -196
  60. package/.claude/hooks/mind-clone-governance.py +192 -192
  61. package/.claude/hooks/read-protection.py +151 -151
  62. package/.claude/hooks/slug-validation.py +176 -176
  63. package/.claude/hooks/sql-governance.py +182 -182
  64. package/.claude/hooks/write-path-validation.py +194 -194
  65. package/LICENSE +33 -33
  66. package/bin/aiox-graph.js +0 -0
  67. package/bin/aiox-minimal.js +0 -0
  68. package/bin/aiox.js +0 -0
  69. package/docs/guides/aios-workflows/README.md +247 -0
  70. package/docs/guides/aios-workflows/bob-orchestrator-workflow.md +1536 -0
  71. package/package.json +1 -1
  72. package/packages/aiox-install/bin/aiox-install.js +0 -0
  73. package/packages/aiox-install/bin/edmcp.js +0 -0
  74. package/packages/aiox-pro-cli/bin/aiox-pro.js +0 -0
  75. package/packages/installer/src/wizard/pro-setup.js +210 -123
  76. package/pro/README.md +66 -0
  77. package/pro/license/degradation.js +220 -0
  78. package/pro/license/errors.js +450 -0
  79. package/pro/license/feature-gate.js +354 -0
  80. package/pro/license/index.js +181 -0
  81. package/pro/license/license-api.js +679 -0
  82. package/pro/license/license-cache.js +523 -0
  83. package/pro/license/license-crypto.js +303 -0
  84. package/scripts/check-markdown-links.py +352 -352
  85. package/scripts/dashboard-parallel-dev.sh +0 -0
  86. package/scripts/dashboard-parallel-phase3.sh +0 -0
  87. package/scripts/dashboard-parallel-phase4.sh +0 -0
  88. package/scripts/glue/README.md +355 -0
  89. package/scripts/glue/compose-agent-prompt.cjs +362 -0
  90. package/scripts/install-monitor-hooks.sh +0 -0
  91. package/.aiox-core/lib/build.json +0 -1
@@ -1,151 +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
- ".aiox-core/development/agents/*.md",
33
- ".aiox-upstream/.aiox-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()
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
+ ".aiox-core/development/agents/*.md",
33
+ ".aiox-upstream/.aiox-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()
@@ -1,176 +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()
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()