@cristiancorreau/forge 2.9.6 → 2.9.8

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 (53) hide show
  1. package/README.md +1 -1
  2. package/dist/commands/doctor.d.ts.map +1 -1
  3. package/dist/commands/doctor.js +4 -3
  4. package/dist/commands/doctor.js.map +1 -1
  5. package/dist/commands/generate.js +1 -1
  6. package/dist/commands/generate.js.map +1 -1
  7. package/dist/commands/init.js +2 -2
  8. package/dist/commands/init.js.map +1 -1
  9. package/dist/lib/generators/codex.d.ts.map +1 -1
  10. package/dist/lib/generators/codex.js +10 -8
  11. package/dist/lib/generators/codex.js.map +1 -1
  12. package/dist/lib/generators/kiro.d.ts +1 -1
  13. package/dist/lib/generators/kiro.d.ts.map +1 -1
  14. package/dist/lib/generators/kiro.js +15 -16
  15. package/dist/lib/generators/kiro.js.map +1 -1
  16. package/dist/lib/generators/opencode.d.ts.map +1 -1
  17. package/dist/lib/generators/opencode.js +13 -12
  18. package/dist/lib/generators/opencode.js.map +1 -1
  19. package/dist/lib/paths.d.ts +1 -2
  20. package/dist/lib/paths.d.ts.map +1 -1
  21. package/dist/lib/paths.js +12 -16
  22. package/dist/lib/paths.js.map +1 -1
  23. package/dist/version.d.ts +1 -1
  24. package/dist/version.js +1 -1
  25. package/package.json +2 -2
  26. package/assets/adapters/claude-code/generate-claude-md.py +0 -304
  27. package/assets/adapters/codex/generate-codex-config.py +0 -269
  28. package/assets/adapters/codex/hooks/codex.yaml.tpl +0 -43
  29. package/assets/adapters/codex/hooks/forge-codex-finish.sh +0 -158
  30. package/assets/adapters/codex/hooks/forge-codex-start.sh +0 -186
  31. package/assets/adapters/kiro/generate-steering.py +0 -367
  32. package/assets/adapters/opencode/generate-agents-md.py +0 -262
  33. package/assets/core/hooks/pre-bash-check.py +0 -202
  34. package/assets/core/hooks/pre-edit-check.py +0 -317
  35. package/assets/forge.py +0 -1265
  36. package/assets/requirements.txt +0 -2
  37. package/assets/scripts/aitmpl-search.py +0 -808
  38. package/assets/scripts/forge-add-opportunities.py +0 -92
  39. package/assets/scripts/forge-audit.py +0 -1061
  40. package/assets/scripts/forge-generate-all.py +0 -283
  41. package/assets/scripts/forge-init.py +0 -900
  42. package/assets/scripts/forge-migrate-project-yaml.py +0 -397
  43. package/assets/scripts/forge-scaffold-profile.py +0 -181
  44. package/assets/scripts/forge-teardown.py +0 -193
  45. package/assets/scripts/forge-validate-project-yaml.py +0 -457
  46. package/assets/scripts/forge-wizard.py +0 -1003
  47. package/assets/scripts/setup-codex.sh +0 -229
  48. package/assets/scripts/team-install.sh +0 -147
  49. package/assets/scripts/token-stats.py +0 -201
  50. package/dist/lib/python.d.ts +0 -4
  51. package/dist/lib/python.d.ts.map +0 -1
  52. package/dist/lib/python.js +0 -46
  53. package/dist/lib/python.js.map +0 -1
@@ -1,202 +0,0 @@
1
- #!/usr/bin/env python3
2
- """
3
- Forge v2 — PreToolUse hook: pre-bash-check.py
4
- Bloquea comandos destructivos en contexto de producción.
5
-
6
- Contexto crítico: el 2026-04-28, --force-reset fue ejecutado accidentalmente
7
- contra la base de datos de producción de un proyecto real, borrando 225 usuarios
8
- y 35 formularios (recuperados desde backup de Supabase Pro). Este hook existe
9
- para que eso nunca vuelva a pasar.
10
- """
11
-
12
- import json
13
- import os
14
- import re
15
- import sys
16
-
17
-
18
- DEBUG = os.environ.get("DEBUG", "") not in ("", "0", "false", "False")
19
-
20
-
21
- def dbg(msg):
22
- if DEBUG:
23
- print(f"[forge-hook-debug] {msg}", flush=True)
24
-
25
-
26
- def load_project_yaml():
27
- """Walk up from cwd to find project.yaml. Returns dict or {}."""
28
- try:
29
- import yaml
30
- path = os.getcwd()
31
- for _ in range(6):
32
- candidate = os.path.join(path, "project.yaml")
33
- if os.path.isfile(candidate):
34
- with open(candidate) as f:
35
- data = yaml.safe_load(f)
36
- return data if isinstance(data, dict) else {}
37
- parent = os.path.dirname(path)
38
- if parent == path:
39
- break
40
- path = parent
41
- except Exception as e:
42
- dbg(f"project.yaml load error: {e}")
43
- return {}
44
-
45
-
46
- # ---------------------------------------------------------------------------
47
- # Patrones peligrosos hardcodeados
48
- # ---------------------------------------------------------------------------
49
-
50
- DANGEROUS_PATTERNS = [
51
- (r"--force-reset", "--force-reset"),
52
- (r"prisma\s+migrate\s+reset", "prisma migrate reset"),
53
- (r"DROP\s+TABLE", "DROP TABLE"),
54
- (r"TRUNCATE\s+", "TRUNCATE"),
55
- (r"DELETE\s+FROM\s+\w+\s*;", "DELETE FROM sin WHERE"),
56
- (r"DROP\s+DATABASE", "DROP DATABASE"),
57
- (r"dropdb\s+", "dropdb"),
58
- (r"rm\s+-rf\s+/", "rm -rf /"),
59
- (r"git\s+push\s+--force(?!\s+--with-lease)", "git push --force sin --with-lease"),
60
- ]
61
-
62
-
63
- def _match_dangerous(command: str) -> tuple[bool, str]:
64
- """Retorna (matched, pattern_label). Verifica patrones hardcodeados."""
65
- for pattern, label in DANGEROUS_PATTERNS:
66
- if re.search(pattern, command, re.IGNORECASE):
67
- return True, label
68
- return False, ""
69
-
70
-
71
- def _match_project_forbidden(command: str, project: dict) -> tuple[bool, str]:
72
- """Verifica patrones forbidden_in_production del project.yaml."""
73
- try:
74
- rules = project.get("rules", {})
75
- forbidden = rules.get("forbidden_in_production", [])
76
- if not isinstance(forbidden, list):
77
- return False, ""
78
- for pattern in forbidden:
79
- if re.search(pattern, command):
80
- return True, pattern
81
- except Exception as e:
82
- dbg(f"project.yaml forbidden_in_production error: {e}")
83
- return False, ""
84
-
85
-
86
- def _is_production_context(command: str, project: dict) -> bool:
87
- """
88
- Retorna True si el comando se ejecuta en contexto de producción:
89
- - La URL de producción aparece en el comando, o
90
- - Variables de entorno PROD_* / PRODUCTION_* están seteadas en el proceso.
91
- """
92
- # URL de producción del project.yaml
93
- deploy = project.get("deploy", {})
94
- prod_url = deploy.get("production_url", "") or ""
95
- project_id = deploy.get("project_id", "") or ""
96
-
97
- if prod_url and prod_url in command:
98
- dbg(f"production context: URL '{prod_url}' encontrada en comando")
99
- return True
100
- if project_id and project_id in command:
101
- dbg(f"production context: project_id '{project_id}' encontrado en comando")
102
- return True
103
-
104
- # Variables de entorno que sugieren contexto de producción
105
- prod_env_patterns = re.compile(r"^(PROD_|PRODUCTION_|PROD$|PRODUCTION$)", re.IGNORECASE)
106
- for key, value in os.environ.items():
107
- if prod_env_patterns.match(key) and value:
108
- dbg(f"production context: env var '{key}' activa")
109
- return True
110
-
111
- return False
112
-
113
-
114
- def _extract_snippet(command: str, max_len: int = 120) -> str:
115
- """Retorna un extracto legible del comando."""
116
- command = command.strip()
117
- if len(command) <= max_len:
118
- return command
119
- return command[:max_len] + "..."
120
-
121
-
122
- # ---------------------------------------------------------------------------
123
- # Main
124
- # ---------------------------------------------------------------------------
125
-
126
- def main():
127
- try:
128
- raw = sys.stdin.read()
129
- if not raw.strip():
130
- dbg("empty stdin, allowing")
131
- sys.exit(0)
132
- data = json.loads(raw)
133
- except Exception as e:
134
- dbg(f"stdin parse error: {e}")
135
- sys.exit(0)
136
-
137
- try:
138
- tool_name = data.get("tool_name", "")
139
- if tool_name != "Bash":
140
- sys.exit(0)
141
-
142
- tool_input = data.get("tool_input", {})
143
- command = tool_input.get("command", "")
144
- if not command:
145
- sys.exit(0)
146
-
147
- dbg(f"command: {command[:200]!r}")
148
-
149
- project = load_project_yaml()
150
-
151
- # Verificar patrones peligrosos hardcodeados
152
- matched, pattern_label = _match_dangerous(command)
153
-
154
- # Verificar patrones custom del project.yaml
155
- if not matched:
156
- matched, pattern_label = _match_project_forbidden(command, project)
157
-
158
- if not matched:
159
- sys.exit(0)
160
-
161
- # Hay un patrón peligroso — ¿es contexto de producción?
162
- in_production = _is_production_context(command, project)
163
-
164
- snippet = _extract_snippet(command)
165
-
166
- if in_production:
167
- # BLOQUEAR
168
- print(
169
- f"forge: BLOQUEADO — comando destructivo detectado en contexto de producción.\n"
170
- f"\n"
171
- f" Comando: {snippet}\n"
172
- f" Patrón: {pattern_label}\n"
173
- f"\n"
174
- f" Si necesitás ejecutar esto, hacelo MANUALMENTE en la terminal\n"
175
- f" con plena consciencia de que afecta producción.\n"
176
- f"\n"
177
- f" Lección del 2026-04-28: --force-reset borró 225 usuarios y\n"
178
- f" 35 formularios en producción. Este hook existe por eso.",
179
- flush=True,
180
- )
181
- sys.exit(2)
182
- else:
183
- # ADVERTIR — no bloquear
184
- print(
185
- f"forge: ADVERTENCIA — comando potencialmente destructivo detectado.\n"
186
- f"\n"
187
- f" Comando: {snippet}\n"
188
- f" Patrón: {pattern_label}\n"
189
- f"\n"
190
- f" Si esto apunta a producción, cancela y ejecuta manualmente.\n"
191
- f" Confirmá que el contexto es seguro antes de continuar.",
192
- flush=True,
193
- )
194
- sys.exit(0)
195
-
196
- except Exception as e:
197
- dbg(f"unexpected error: {e}")
198
- sys.exit(0)
199
-
200
-
201
- if __name__ == "__main__":
202
- main()
@@ -1,317 +0,0 @@
1
- #!/usr/bin/env python3
2
- """
3
- Forge v2 — PreToolUse hook: pre-edit-check.py
4
- Enforces branch guard, debug detection, and secret detection before file edits.
5
- """
6
-
7
- import json
8
- import os
9
- import re
10
- import subprocess
11
- import sys
12
-
13
-
14
- DEBUG = os.environ.get("DEBUG", "") not in ("", "0", "false", "False")
15
-
16
-
17
- def dbg(msg):
18
- if DEBUG:
19
- print(f"[forge-hook-debug] {msg}", flush=True)
20
-
21
-
22
- def load_project_yaml():
23
- """Walk up from cwd to find project.yaml. Returns dict or {}."""
24
- try:
25
- import yaml
26
- path = os.getcwd()
27
- for _ in range(6):
28
- candidate = os.path.join(path, "project.yaml")
29
- if os.path.isfile(candidate):
30
- with open(candidate) as f:
31
- data = yaml.safe_load(f)
32
- return data if isinstance(data, dict) else {}
33
- parent = os.path.dirname(path)
34
- if parent == path:
35
- break
36
- path = parent
37
- except Exception as e:
38
- dbg(f"project.yaml load error: {e}")
39
- return {}
40
-
41
-
42
- # ---------------------------------------------------------------------------
43
- # File classification helpers
44
- # ---------------------------------------------------------------------------
45
-
46
- CODE_EXTENSIONS = {
47
- ".py", ".ts", ".js", ".tsx", ".jsx",
48
- ".php", ".rb", ".go", ".rs", ".java",
49
- ".cs", ".cpp", ".c", ".sh",
50
- }
51
-
52
- NON_CODE_EXTENSIONS = {
53
- ".md", ".yaml", ".yml", ".json", ".toml", ".txt", ".lock",
54
- }
55
-
56
- ROOT_PROTECTED_NAMES = {"README.md", "CLAUDE.md", "CHANGELOG.md"}
57
-
58
- PROTECTED_DIRS = ("docs/", ".claude/")
59
-
60
-
61
- def is_code_file(file_path):
62
- """Return True if the file path is considered a code file."""
63
- _, ext = os.path.splitext(file_path)
64
- if ext.lower() in CODE_EXTENSIONS:
65
- return True
66
- if ext.lower() in NON_CODE_EXTENSIONS:
67
- return False
68
- # Default: treat unknown extensions as non-code (safe)
69
- return False
70
-
71
-
72
- def is_exempt_from_branch_guard(file_path):
73
- """Return True if the file should be exempt from branch-guard blocking."""
74
- norm = file_path.replace("\\", "/")
75
- # Exempt protected dirs
76
- for d in PROTECTED_DIRS:
77
- if norm.startswith(d) or f"/{d.rstrip('/')}" in norm:
78
- return True
79
- # Exempt root-level protected names
80
- basename = os.path.basename(norm)
81
- if basename in ROOT_PROTECTED_NAMES:
82
- return True
83
- # Exempt root-level *.md files
84
- if basename.endswith(".md") and "/" not in norm.lstrip("./"):
85
- return True
86
- # Exempt root-level *.yaml / *.json config files
87
- if "/" not in norm.lstrip("./"):
88
- _, ext = os.path.splitext(basename)
89
- if ext.lower() in (".yaml", ".yml", ".json"):
90
- return True
91
- return False
92
-
93
-
94
- # ---------------------------------------------------------------------------
95
- # Check 1 — Branch guard
96
- # ---------------------------------------------------------------------------
97
-
98
- PROTECTED_BRANCHES = {"main", "master", "develop"}
99
-
100
-
101
- def check_branch_guard(file_path):
102
- """Block code edits on protected branches."""
103
- try:
104
- result = subprocess.run(
105
- ["git", "branch", "--show-current"],
106
- capture_output=True,
107
- text=True,
108
- timeout=5,
109
- )
110
- branch = result.stdout.strip()
111
- dbg(f"current branch: {branch!r}")
112
- except Exception as e:
113
- dbg(f"git branch error: {e}")
114
- return None
115
-
116
- if branch not in PROTECTED_BRANCHES:
117
- return None
118
-
119
- if not is_code_file(file_path):
120
- return None
121
-
122
- if is_exempt_from_branch_guard(file_path):
123
- return None
124
-
125
- return (
126
- f"forge: edición bloqueada en {branch}. Crea una feature branch:\n"
127
- f" git checkout -b feature/<tema>-$(date +%Y-%m-%d)"
128
- )
129
-
130
-
131
- # ---------------------------------------------------------------------------
132
- # Check 2 — Debug statements
133
- # ---------------------------------------------------------------------------
134
-
135
- def check_debug_statements(file_path, content):
136
- """Warn (not block) if debug statements are found in new content."""
137
- _, ext = os.path.splitext(file_path)
138
- ext = ext.lower()
139
-
140
- if ext not in CODE_EXTENSIONS:
141
- return None
142
-
143
- found = False
144
- basename = os.path.basename(file_path)
145
- norm = file_path.replace("\\", "/")
146
-
147
- if ext in (".ts", ".js", ".tsx", ".jsx"):
148
- if "console.log(" in content or "debugger;" in content:
149
- found = True
150
-
151
- elif ext == ".php":
152
- if "var_dump(" in content or "dd(" in content or "print_r(" in content:
153
- found = True
154
-
155
- elif ext == ".py":
156
- # Skip forge scripts and .agentic/ files
157
- is_forge_script = basename.startswith("forge") and basename.endswith(".py")
158
- in_agentic = ".agentic/" in norm
159
- if not is_forge_script and not in_agentic:
160
- if "print(" in content:
161
- found = True
162
-
163
- elif ext == ".rb":
164
- if re.search(r"^\s*(puts |pp |p )", content, re.MULTILINE):
165
- found = True
166
-
167
- if found:
168
- return (
169
- f"forge: debug statement detectado en {file_path}"
170
- " — recuerda quitarlo antes del commit"
171
- )
172
- return None
173
-
174
-
175
- # ---------------------------------------------------------------------------
176
- # Check 3 — Secret detection
177
- # ---------------------------------------------------------------------------
178
-
179
- SECRET_PATTERN = re.compile(
180
- r'(password|passwd|secret|api_key|apikey|token|private_key)\s*[=:]\s*["\'][^"\']{8,}["\']',
181
- re.IGNORECASE,
182
- )
183
-
184
- LONG_SECRET_PATTERN = re.compile(
185
- r'\b(key|secret|token|password|auth|api_key|apikey)\b\s*[=:]\s*["\'][A-Za-z0-9+/=_\-]{20,}["\']',
186
- re.IGNORECASE,
187
- )
188
-
189
- EXEMPT_EXTENSIONS = {".md"}
190
- EXEMPT_SUFFIXES = (".env.example", ".env.sample")
191
- TEST_PATTERNS = re.compile(r'\.(test|spec)\.')
192
-
193
-
194
- def is_exempt_from_secret_check(file_path):
195
- norm = file_path.replace("\\", "/")
196
- basename = os.path.basename(norm)
197
- _, ext = os.path.splitext(basename)
198
-
199
- if ext.lower() in EXEMPT_EXTENSIONS:
200
- return True
201
- for suffix in EXEMPT_SUFFIXES:
202
- if norm.endswith(suffix):
203
- return True
204
- if TEST_PATTERNS.search(basename):
205
- return True
206
- return False
207
-
208
-
209
- def check_secret_detection(file_path, content):
210
- """Block if hardcoded credentials are detected."""
211
- if is_exempt_from_secret_check(file_path):
212
- return None
213
-
214
- if SECRET_PATTERN.search(content) or LONG_SECRET_PATTERN.search(content):
215
- return (
216
- f"forge: posible credencial hardcodeada detectada en {file_path}."
217
- " Usa variables de entorno."
218
- )
219
- return None
220
-
221
-
222
- # ---------------------------------------------------------------------------
223
- # project.yaml — custom forbidden patterns + enterprise mode
224
- # ---------------------------------------------------------------------------
225
-
226
- def check_project_yaml_patterns(file_path, content, project):
227
- """Check project.yaml forbidden_patterns if present."""
228
- try:
229
- rules = project.get("rules", {})
230
- forbidden = rules.get("forbidden_patterns", [])
231
- if not isinstance(forbidden, list):
232
- return None
233
- for pattern in forbidden:
234
- if re.search(pattern, content):
235
- return (
236
- f"forge: patrón prohibido detectado en {file_path} "
237
- f"(regla: {pattern!r})"
238
- )
239
- except Exception as e:
240
- dbg(f"project.yaml patterns error: {e}")
241
- return None
242
-
243
-
244
- # ---------------------------------------------------------------------------
245
- # Main
246
- # ---------------------------------------------------------------------------
247
-
248
- def main():
249
- try:
250
- raw = sys.stdin.read()
251
- if not raw.strip():
252
- dbg("empty stdin, allowing")
253
- sys.exit(0)
254
-
255
- data = json.loads(raw)
256
- except Exception as e:
257
- dbg(f"stdin parse error: {e}")
258
- sys.exit(0)
259
-
260
- try:
261
- tool_name = data.get("tool_name", "")
262
- tool_input = data.get("tool_input", {})
263
-
264
- file_path = tool_input.get("file_path", "")
265
- if not file_path:
266
- sys.exit(0)
267
-
268
- # Determine new content being written
269
- if tool_name == "Write":
270
- new_content = tool_input.get("content", "")
271
- elif tool_name == "Edit":
272
- new_content = tool_input.get("new_string", "")
273
- else:
274
- sys.exit(0)
275
-
276
- dbg(f"tool={tool_name} file={file_path} content_len={len(new_content)}")
277
-
278
- project = load_project_yaml()
279
- enterprise_mode = project.get("mode", "") == "enterprise"
280
-
281
- # Check 1 — Branch guard
282
- block_msg = check_branch_guard(file_path)
283
- if block_msg:
284
- print(block_msg, flush=True)
285
- sys.exit(2)
286
-
287
- # Check 2 — Debug statements
288
- warn_msg = check_debug_statements(file_path, new_content)
289
- if warn_msg:
290
- if enterprise_mode:
291
- print(warn_msg, flush=True)
292
- sys.exit(2)
293
- else:
294
- print(warn_msg, flush=True)
295
- # fall through — warning only
296
-
297
- # Check 3 — Secret detection
298
- block_msg = check_secret_detection(file_path, new_content)
299
- if block_msg:
300
- print(block_msg, flush=True)
301
- sys.exit(2)
302
-
303
- # project.yaml forbidden patterns
304
- block_msg = check_project_yaml_patterns(file_path, new_content, project)
305
- if block_msg:
306
- print(block_msg, flush=True)
307
- sys.exit(2)
308
-
309
- except Exception as e:
310
- dbg(f"unexpected error: {e}")
311
- sys.exit(0)
312
-
313
- sys.exit(0)
314
-
315
-
316
- if __name__ == "__main__":
317
- main()