|
| 1 | +#!/usr/bin/env python3 |
| 2 | +"""sync_all.py — additive sync of dotforge template + stack rules into every |
| 3 | +registered project. |
| 4 | +
|
| 5 | +Scope (additive only, by design — full merge is the interactive skill): |
| 6 | +- Adds missing template/hooks/*.sh files |
| 7 | +- Adds missing stack rules for each detected stack (per .forge-manifest.json) |
| 8 | +- Updates .forge-manifest.json: version + synced_at + per-file hashes |
| 9 | +- NEVER touches: |
| 10 | + * existing hook files (preserves project-local customizations) |
| 11 | + * .claude/settings.json (allow/deny merge needs human review) |
| 12 | + * CLAUDE.md (custom sections risk) |
| 13 | + * .claude/rules/domain/ (project-owned per sync-template skill) |
| 14 | +
|
| 15 | +For full merge sync (settings.json union, CLAUDE.md sections), use the |
| 16 | +interactive /forge sync skill per-project. |
| 17 | +
|
| 18 | +Usage: |
| 19 | + python3 scripts/sync_all.py # apply |
| 20 | + python3 scripts/sync_all.py --dry-run # preview |
| 21 | +""" |
| 22 | +from __future__ import annotations |
| 23 | + |
| 24 | +import argparse |
| 25 | +import hashlib |
| 26 | +import json |
| 27 | +import shutil |
| 28 | +import sys |
| 29 | +from datetime import date |
| 30 | +from pathlib import Path |
| 31 | + |
| 32 | +try: |
| 33 | + import yaml |
| 34 | +except ImportError: |
| 35 | + print("ERROR: pyyaml required", file=sys.stderr) |
| 36 | + sys.exit(2) |
| 37 | + |
| 38 | +DOTFORGE = Path(__file__).resolve().parent.parent |
| 39 | +REGISTRY = DOTFORGE / "registry/projects.local.yml" |
| 40 | +TEMPLATE_HOOKS = DOTFORGE / "template/hooks" |
| 41 | +STACKS_DIR = DOTFORGE / "stacks" |
| 42 | +TODAY = date.today().isoformat() |
| 43 | +VERSION = (DOTFORGE / "VERSION").read_text().strip() |
| 44 | + |
| 45 | + |
| 46 | +def sha256(p: Path) -> str: |
| 47 | + return "sha256:" + hashlib.sha256(p.read_bytes()).hexdigest() |
| 48 | + |
| 49 | + |
| 50 | +def detect_stacks_from_manifest(claude_dir: Path) -> list[str]: |
| 51 | + m = claude_dir / ".forge-manifest.json" |
| 52 | + if not m.exists(): |
| 53 | + return [] |
| 54 | + try: |
| 55 | + return json.loads(m.read_text()).get("stacks", []) or [] |
| 56 | + except Exception: |
| 57 | + return [] |
| 58 | + |
| 59 | + |
| 60 | +def add_missing_hooks(claude_dir: Path, dry: bool) -> list[str]: |
| 61 | + hooks_dir = claude_dir / "hooks" |
| 62 | + if not hooks_dir.exists(): |
| 63 | + return [] |
| 64 | + added = [] |
| 65 | + for tmpl in sorted(TEMPLATE_HOOKS.glob("*.sh")): |
| 66 | + target = hooks_dir / tmpl.name |
| 67 | + if not target.exists(): |
| 68 | + if not dry: |
| 69 | + shutil.copy2(tmpl, target) |
| 70 | + target.chmod(0o755) |
| 71 | + added.append(tmpl.name) |
| 72 | + return added |
| 73 | + |
| 74 | + |
| 75 | +def add_missing_stack_rules(claude_dir: Path, stacks: list[str], dry: bool) -> list[str]: |
| 76 | + rules_dir = claude_dir / "rules" |
| 77 | + if not rules_dir.exists() or not stacks: |
| 78 | + return [] |
| 79 | + added = [] |
| 80 | + for stack in stacks: |
| 81 | + src_rules = STACKS_DIR / stack / "rules" |
| 82 | + if not src_rules.exists(): |
| 83 | + continue |
| 84 | + for rule in sorted(src_rules.glob("*.md")): |
| 85 | + target = rules_dir / rule.name |
| 86 | + if not target.exists(): |
| 87 | + if not dry: |
| 88 | + shutil.copy2(rule, target) |
| 89 | + added.append(f"{stack}/{rule.name}") |
| 90 | + return added |
| 91 | + |
| 92 | + |
| 93 | +def update_manifest(claude_dir: Path, stacks: list[str], dry: bool) -> bool: |
| 94 | + """Refresh manifest: version + synced_at + per-file hashes for managed files.""" |
| 95 | + manifest_path = claude_dir / ".forge-manifest.json" |
| 96 | + existing = {} |
| 97 | + if manifest_path.exists(): |
| 98 | + try: |
| 99 | + existing = json.loads(manifest_path.read_text()) |
| 100 | + except Exception: |
| 101 | + existing = {} |
| 102 | + |
| 103 | + files = existing.get("files", {}) |
| 104 | + # Hash each managed file currently in .claude/ |
| 105 | + for hook in (claude_dir / "hooks").glob("*.sh") if (claude_dir / "hooks").exists() else []: |
| 106 | + rel = f".claude/hooks/{hook.name}" |
| 107 | + files[rel] = {"hash": sha256(hook), "source": "template"} |
| 108 | + for rule in (claude_dir / "rules").glob("*.md") if (claude_dir / "rules").exists() else []: |
| 109 | + rel = f".claude/rules/{rule.name}" |
| 110 | + existing_entry = files.get(rel) |
| 111 | + if not isinstance(existing_entry, dict): |
| 112 | + files[rel] = {"hash": sha256(rule), "source": "template+stacks"} |
| 113 | + else: |
| 114 | + existing_entry["hash"] = sha256(rule) |
| 115 | + |
| 116 | + new_manifest = { |
| 117 | + "dotforge_version": VERSION, |
| 118 | + "synced_at": TODAY, |
| 119 | + "stacks": stacks, |
| 120 | + "files": files, |
| 121 | + "sync_method": "additive", |
| 122 | + "sync_note": "Settings.json + CLAUDE.md + domain/ NOT touched. Run interactive /forge sync per-project for full merge.", |
| 123 | + } |
| 124 | + |
| 125 | + if dry: |
| 126 | + return True |
| 127 | + manifest_path.write_text(json.dumps(new_manifest, indent=2) + "\n") |
| 128 | + return True |
| 129 | + |
| 130 | + |
| 131 | +def main() -> int: |
| 132 | + ap = argparse.ArgumentParser() |
| 133 | + ap.add_argument("--dry-run", action="store_true") |
| 134 | + args = ap.parse_args() |
| 135 | + |
| 136 | + with open(REGISTRY) as f: |
| 137 | + data = yaml.safe_load(f) |
| 138 | + |
| 139 | + print(f"═══ ADDITIVE SYNC → v{VERSION} ═══") |
| 140 | + print(f"Dry-run: {args.dry_run}\n") |
| 141 | + |
| 142 | + summary = [] |
| 143 | + for proj in data["projects"]: |
| 144 | + name = proj["name"] |
| 145 | + path = Path(proj["path"]) |
| 146 | + if str(path) == ".": |
| 147 | + path = DOTFORGE |
| 148 | + if not path.exists(): |
| 149 | + print(f"── {name:<20} SKIP (missing path)") |
| 150 | + summary.append((name, "missing", 0, 0)) |
| 151 | + continue |
| 152 | + claude_dir = path / ".claude" |
| 153 | + if not claude_dir.exists(): |
| 154 | + print(f"── {name:<20} SKIP (no .claude/)") |
| 155 | + summary.append((name, "no .claude", 0, 0)) |
| 156 | + continue |
| 157 | + |
| 158 | + stacks = detect_stacks_from_manifest(claude_dir) |
| 159 | + added_hooks = add_missing_hooks(claude_dir, args.dry_run) |
| 160 | + added_rules = add_missing_stack_rules(claude_dir, stacks, args.dry_run) |
| 161 | + update_manifest(claude_dir, stacks, args.dry_run) |
| 162 | + |
| 163 | + bits = [] |
| 164 | + if added_hooks: |
| 165 | + bits.append(f"+{len(added_hooks)} hooks: {', '.join(added_hooks)}") |
| 166 | + if added_rules: |
| 167 | + bits.append(f"+{len(added_rules)} stack rules: {', '.join(added_rules)}") |
| 168 | + if not bits: |
| 169 | + bits.append("manifest refreshed only") |
| 170 | + |
| 171 | + print(f"── {name:<20} {' | '.join(bits)}") |
| 172 | + summary.append((name, "synced", len(added_hooks), len(added_rules))) |
| 173 | + |
| 174 | + print("\n═══ SUMMARY ═══") |
| 175 | + total_hooks = sum(s[2] for s in summary) |
| 176 | + total_rules = sum(s[3] for s in summary) |
| 177 | + synced = sum(1 for s in summary if s[1] == "synced") |
| 178 | + print(f"Projects synced: {synced}/{len(summary)}") |
| 179 | + print(f"Total hooks added: {total_hooks}") |
| 180 | + print(f"Total stack rules added: {total_rules}") |
| 181 | + print(f"Manifest version: v{VERSION}") |
| 182 | + if args.dry_run: |
| 183 | + print("\n(dry-run: no files written)") |
| 184 | + else: |
| 185 | + print("\nNote: settings.json / CLAUDE.md / domain/ NOT touched. Run") |
| 186 | + print(" interactive /forge sync per-project for full merge.") |
| 187 | + return 0 |
| 188 | + |
| 189 | + |
| 190 | +if __name__ == "__main__": |
| 191 | + sys.exit(main()) |
0 commit comments