-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinstall_forge.py
More file actions
488 lines (389 loc) · 17.9 KB
/
install_forge.py
File metadata and controls
488 lines (389 loc) · 17.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
#!/usr/bin/env python3
"""Forge Global Installer — Install forge commands globally for Claude Code.
Usage:
python install_forge.py # Install or update (idempotent)
python install_forge.py --check # Verify installation health
python install_forge.py --uninstall # Remove ~/.forge/ and commands from ~/.claude/commands/
python install_forge.py --update-project PATH # Update an existing project to latest version
python install_forge.py --update-project PATH --force # Force update even if version matches
"""
import argparse
import hashlib
import json
import shutil
import subprocess
import sys
from datetime import datetime, timezone
from pathlib import Path
CCFORGE_VERSION = "1.0.3"
FORGE_HOME = Path.home() / ".forge"
CLAUDE_COMMANDS = Path.home() / ".claude" / "commands"
SOURCE_DIR = Path(__file__).resolve().parent # The ccforge/ directory containing this script
PROJECT_LOCAL_COMMANDS = [
"forge-init.md", "forge-build.md", "forge-parallel.md", "forge-status.md", "forge-test.md",
"forge-fix.md", "forge-expand.md", "forge-regression.md", "checkpoint.md", "check-code.md", "review-pr.md",
]
GLOBAL_COMMAND = "forge-create.md"
def check_python_version() -> None:
if sys.version_info < (3, 11):
print(f"Error: Python 3.11+ required (found {sys.version_info.major}.{sys.version_info.minor})")
sys.exit(1)
def venv_python() -> Path:
venv = FORGE_HOME / "venv"
return venv / "Scripts" / "python.exe" if sys.platform == "win32" else venv / "bin" / "python"
def venv_pip() -> Path:
venv = FORGE_HOME / "venv"
return venv / "Scripts" / "pip.exe" if sys.platform == "win32" else venv / "bin" / "pip"
def requirements_hash() -> str:
req = FORGE_HOME / "mcp_server" / "requirements.txt"
return hashlib.sha256(req.read_bytes()).hexdigest()[:16]
# ── Step 1: Copy core files ──────────────────────────────────────────────────
def copy_core_files() -> None:
copies = {
"mcp_server": SOURCE_DIR / "mcp_server",
"api": SOURCE_DIR / "api",
"templates": SOURCE_DIR / ".claude" / "templates",
"skills": SOURCE_DIR / ".claude" / "skills",
"agents": SOURCE_DIR / ".claude" / "agents",
}
for name, src in copies.items():
dst = FORGE_HOME / name
if dst.exists():
shutil.rmtree(dst)
shutil.copytree(src, dst, ignore=shutil.ignore_patterns("__pycache__"))
print(f" Copied {name}/")
# Copy project-local commands (individual files, excluding forge-create.md)
commands_dst = FORGE_HOME / "commands"
commands_dst.mkdir(parents=True, exist_ok=True)
commands_src = SOURCE_DIR / ".claude" / "commands"
for cmd in PROJECT_LOCAL_COMMANDS:
src = commands_src / cmd
if src.exists():
shutil.copy2(src, commands_dst / cmd)
print(f" Copied commands/ ({len(PROJECT_LOCAL_COMMANDS)} project-local commands)")
# ── Step 2: Create venv ──────────────────────────────────────────────────────
def create_venv() -> None:
venv_dir = FORGE_HOME / "venv"
marker = venv_dir / ".forge_marker"
expected = f"{requirements_hash()}|{sys.version}"
if marker.exists() and marker.read_text().strip() == expected:
print(" Venv up to date (skipped)")
return
if venv_dir.exists():
shutil.rmtree(venv_dir)
print(" Creating venv...")
subprocess.run([sys.executable, "-m", "venv", str(venv_dir)], check=True)
print(" Installing dependencies...")
req = FORGE_HOME / "mcp_server" / "requirements.txt"
result = subprocess.run(
[str(venv_pip()), "install", "-r", str(req)],
capture_output=True, text=True,
)
if result.returncode != 0:
print(f" pip install failed:\n{result.stderr}")
sys.exit(1)
marker.write_text(expected)
print(" Venv ready")
# ── Step 3: Copy commands ────────────────────────────────────────────────────
def adapt_forge_create() -> str:
"""Read forge-create.md and replace relative paths with absolute ~/.forge/ paths."""
src = SOURCE_DIR / ".claude" / "commands" / GLOBAL_COMMAND
content = src.read_text(encoding="utf-8")
home = FORGE_HOME.as_posix()
python = venv_python().as_posix()
pip = venv_pip().as_posix()
replacements = [
# Template references
(".claude/templates/coding_prompt.template.md",
f"{home}/templates/coding_prompt.template.md"),
(".claude/templates/testing_prompt.template.md",
f"{home}/templates/testing_prompt.template.md"),
(".claude/templates/project-claude.template.md",
f"{home}/templates/project-claude.template.md"),
# Source directory copy instructions
("Copy `mcp_server/` directory",
f"Copy `{home}/mcp_server/` directory"),
("Copy `api/` directory",
f"Copy `{home}/api/` directory"),
# Playwright skill copy
("cp -r .claude/skills/playwright-cli",
f"cp -r {home}/skills/playwright-cli"),
# Project-local commands copy
("cp .claude/commands/$cmd",
f"cp {home}/commands/$cmd"),
# Project-local agents copy
("cp .claude/agents/$agent",
f"cp {home}/agents/$agent"),
# pip install (replace full line — deps pre-installed in global venv)
("cd $ARGUMENTS && pip install -r mcp_server/requirements.txt",
f"{pip} install -r $ARGUMENTS/mcp_server/requirements.txt"),
# MCP server python command in .mcp.json template
('"command": "python"',
f'"command": "{python}"'),
]
for old, new in replacements:
content = content.replace(old, new)
# Inject version into the {{CCFORGE_VERSION}} placeholder
content = content.replace("{{CCFORGE_VERSION}}", CCFORGE_VERSION)
return content
def copy_commands() -> None:
CLAUDE_COMMANDS.mkdir(parents=True, exist_ok=True)
# Only install forge-create.md globally (adapted with absolute paths)
adapted = adapt_forge_create()
(CLAUDE_COMMANDS / GLOBAL_COMMAND).write_text(adapted, encoding="utf-8")
print(f" Adapted {GLOBAL_COMMAND}")
# Clean up legacy global commands from previous installations
removed = 0
for cmd in PROJECT_LOCAL_COMMANDS:
p = CLAUDE_COMMANDS / cmd
if p.exists():
p.unlink()
removed += 1
if removed:
print(f" Removed {removed} legacy global command(s)")
# ── Step 4: Metadata ─────────────────────────────────────────────────────────
def write_version() -> None:
info = {
"ccforge_version": CCFORGE_VERSION,
"installed_at": datetime.now(timezone.utc).isoformat(),
"source_path": SOURCE_DIR.as_posix(),
"python_version": sys.version,
"platform": sys.platform,
}
(FORGE_HOME / "version.json").write_text(json.dumps(info, indent=2))
print(" Wrote version.json")
# ── Step 5: Verify ───────────────────────────────────────────────────────────
def verify() -> list[str]:
errors: list[str] = []
# Check directories
for name in ["mcp_server", "api", "templates", "skills", "agents", "commands"]:
if not (FORGE_HOME / name).is_dir():
errors.append(f"Missing: ~/.forge/{name}/")
# Check all project-local commands exist in ~/.forge/commands/
for cmd in PROJECT_LOCAL_COMMANDS:
if not (FORGE_HOME / "commands" / cmd).exists():
errors.append(f"Missing project-local command: ~/.forge/commands/{cmd}")
# Check venv python and imports
python = venv_python()
if not python.exists():
errors.append(f"Missing venv python: {python}")
else:
r = subprocess.run(
[str(python), "-c", "import mcp; import sqlalchemy; import pydantic"],
capture_output=True, text=True,
)
if r.returncode != 0:
errors.append(f"Import check failed: {r.stderr.strip()}")
# Check forge-create.md has absolute paths, no leftover relative paths
fc = CLAUDE_COMMANDS / GLOBAL_COMMAND
if fc.exists():
text = fc.read_text(encoding="utf-8")
if FORGE_HOME.as_posix() not in text:
errors.append("forge-create.md missing absolute paths")
if ".claude/templates/" in text:
errors.append("forge-create.md has leftover relative template paths")
if ".claude/commands/$cmd" in text:
errors.append("forge-create.md has leftover relative command paths")
if ".claude/agents/$agent" in text:
errors.append("forge-create.md has leftover relative agent paths")
else:
errors.append("Missing forge-create.md in ~/.claude/commands/")
# Warn if legacy global commands still present
for cmd in PROJECT_LOCAL_COMMANDS:
if (CLAUDE_COMMANDS / cmd).exists():
errors.append(f"Legacy global command still present: ~/.claude/commands/{cmd}")
return errors
# ── CLI actions ───────────────────────────────────────────────────────────────
def install() -> None:
print(f"Installing Forge to {FORGE_HOME}\n")
FORGE_HOME.mkdir(parents=True, exist_ok=True)
print("[1/5] Copying core files...")
copy_core_files()
print("\n[2/5] Setting up Python venv...")
create_venv()
print("\n[3/5] Installing global command (forge-create)...")
copy_commands()
print("\n[4/5] Writing metadata...")
write_version()
print("\n[5/5] Verifying...")
errors = verify()
if errors:
print("\nCompleted with errors:")
for e in errors:
print(f" - {e}")
sys.exit(1)
print("\nInstallation complete. All checks passed.")
print(f"\n Forge home: {FORGE_HOME}")
print(f" Global command: {CLAUDE_COMMANDS / GLOBAL_COMMAND}")
print("\nOpen Claude Code anywhere and run /forge-create to get started.")
def uninstall() -> None:
if FORGE_HOME.exists():
shutil.rmtree(FORGE_HOME)
print(f"Removed {FORGE_HOME}")
else:
print(f"{FORGE_HOME} not found")
# Remove forge-create.md from global commands
fc = CLAUDE_COMMANDS / GLOBAL_COMMAND
if fc.exists():
fc.unlink()
print(f"Removed {GLOBAL_COMMAND} from {CLAUDE_COMMANDS}")
# Also clean up any legacy global commands from older installs
removed = 0
for cmd in PROJECT_LOCAL_COMMANDS:
p = CLAUDE_COMMANDS / cmd
if p.exists():
p.unlink()
removed += 1
if removed:
print(f"Removed {removed} legacy global command(s) from {CLAUDE_COMMANDS}")
print("\nUninstall complete.")
def check() -> None:
print("Checking Forge installation...\n")
if not FORGE_HOME.exists():
print("Not installed. Run: python install_forge.py")
sys.exit(1)
errors = verify()
if errors:
print("Issues found:")
for e in errors:
print(f" - {e}")
print("\nRe-run: python install_forge.py")
sys.exit(1)
print("Installation is healthy.")
vf = FORGE_HOME / "version.json"
if vf.exists():
info = json.loads(vf.read_text())
print(f"\n Version: {info.get('ccforge_version', '?')}")
print(f" Installed: {info.get('installed_at', '?')}")
print(f" Source: {info.get('source_path', '?')}")
print(f" Python: {info.get('python_version', '?').split()[0]}")
# ── Update existing project ────────────────────────────────────────────────────
def update_project(project_path: str, force: bool = False) -> None:
project = Path(project_path).resolve()
# 1. Verify global install exists
if not FORGE_HOME.exists():
print(f"Error: {FORGE_HOME} not found. Run 'python install_forge.py' first.")
sys.exit(1)
# 2. Verify this is a CCForge project
has_autoforge = (project / ".autoforge").is_dir()
has_mcp = (project / "mcp_server" / "feature_mcp.py").is_file()
if not has_autoforge and not has_mcp:
print(f"Error: {project} is not a CCForge project.")
print(" Expected .autoforge/ directory or mcp_server/feature_mcp.py")
sys.exit(1)
# 3. Check current version
version_file = project / ".autoforge" / "version.json"
current_version = None
original_created_at = None
if version_file.exists():
try:
existing_info = json.loads(version_file.read_text(encoding="utf-8"))
current_version = existing_info.get("ccforge_version")
original_created_at = existing_info.get("created_at")
except (json.JSONDecodeError, OSError):
pass
if current_version:
if current_version == CCFORGE_VERSION and not force:
print(f"Already up to date (v{CCFORGE_VERSION}). Use --force to update anyway.")
return
if current_version == CCFORGE_VERSION:
print(f"Forcing update of v{CCFORGE_VERSION}...\n")
else:
print(f"Updating: v{current_version} → v{CCFORGE_VERSION}\n")
else:
print(f"No version found (pre-versioning project), updating to v{CCFORGE_VERSION}...\n")
# 4. Copy files from ~/.forge/ into the project
updated: list[str] = []
# mcp_server/
dst = project / "mcp_server"
if dst.exists():
shutil.rmtree(dst)
shutil.copytree(FORGE_HOME / "mcp_server", dst, ignore=shutil.ignore_patterns("__pycache__"))
updated.append("mcp_server/")
# api/
dst = project / "api"
if dst.exists():
shutil.rmtree(dst)
shutil.copytree(FORGE_HOME / "api", dst, ignore=shutil.ignore_patterns("__pycache__"))
updated.append("api/")
# .claude/commands/ (project-local only)
commands_dst = project / ".claude" / "commands"
commands_dst.mkdir(parents=True, exist_ok=True)
commands_src = FORGE_HOME / "commands"
for cmd in PROJECT_LOCAL_COMMANDS:
src = commands_src / cmd
if src.exists():
shutil.copy2(src, commands_dst / cmd)
updated.append(f".claude/commands/ ({len(PROJECT_LOCAL_COMMANDS)} files)")
# .claude/agents/ — copy all .md files from ~/.forge/agents/
agents_dst = project / ".claude" / "agents"
agents_dst.mkdir(parents=True, exist_ok=True)
agents_src = FORGE_HOME / "agents"
agent_count = 0
if agents_src.is_dir():
for agent_file in sorted(agents_src.iterdir()):
if agent_file.is_file() and agent_file.suffix == ".md":
shutil.copy2(agent_file, agents_dst / agent_file.name)
agent_count += 1
updated.append(f".claude/agents/ ({agent_count} files)")
# .claude/skills/ — copy all skill directories from ~/.forge/skills/
skills_src = FORGE_HOME / "skills"
if skills_src.is_dir():
skill_names = []
for skill_dir in sorted(skills_src.iterdir()):
if skill_dir.is_dir():
skill_dst = project / ".claude" / "skills" / skill_dir.name
if skill_dst.exists():
shutil.rmtree(skill_dst)
shutil.copytree(skill_dir, skill_dst)
skill_names.append(skill_dir.name)
if skill_names:
updated.append(f".claude/skills/ ({', '.join(skill_names)})")
# .autoforge/prompts/ — update generic prompts (not app_spec or initializer)
prompts_dst = project / ".autoforge" / "prompts"
prompts_dst.mkdir(parents=True, exist_ok=True)
templates_src = FORGE_HOME / "templates"
for prompt_name, template_name in [
("coding_prompt.md", "coding_prompt.template.md"),
("testing_prompt.md", "testing_prompt.template.md"),
]:
src = templates_src / template_name
if src.exists():
shutil.copy2(src, prompts_dst / prompt_name)
updated.append(".autoforge/prompts/ (coding_prompt.md, testing_prompt.md)")
# 5. Write/update .autoforge/version.json
(project / ".autoforge").mkdir(parents=True, exist_ok=True)
now = datetime.now(timezone.utc).isoformat()
version_info = {
"ccforge_version": CCFORGE_VERSION,
"created_at": original_created_at or now,
"updated_at": now,
}
version_file.write_text(json.dumps(version_info, indent=2), encoding="utf-8")
updated.append(".autoforge/version.json")
# 6. Report
print("Updated:")
for item in updated:
print(f" - {item}")
print(f"\nProject updated to v{CCFORGE_VERSION}.")
print("\nNot touched: .autoforge/features.db, .autoforge/prompts/app_spec.txt, "
"CLAUDE.md, .mcp.json")
# ── Entry point ───────────────────────────────────────────────────────────────
def main() -> None:
parser = argparse.ArgumentParser(description="Forge Global Installer")
parser.add_argument("--uninstall", action="store_true", help="Remove installation")
parser.add_argument("--check", action="store_true", help="Verify installation health")
parser.add_argument("--update-project", metavar="PATH", help="Update an existing CCForge project to the latest version")
parser.add_argument("--force", action="store_true", help="Force update even if version matches")
args = parser.parse_args()
check_python_version()
if args.uninstall:
uninstall()
elif args.check:
check()
elif args.update_project:
update_project(args.update_project, force=args.force)
else:
install()
if __name__ == "__main__":
main()