#!/usr/bin/env python3 # -*- coding: utf-8 -*- """`casan init` / `casan verify-harness` (Plan-21 hybrid adoption). Adopt CASAN into an EXISTING project by writing only per-project config — the shared harness stays under $CASAN_HOME and is NOT copied into the repo. This is the codegraph-style flow: global install once, then `casan init` per project. What init writes into the target repo: .casan/config.json project id, enforcement/integration mode, clients .casan/version.lock pinned harness version + gate-code integrity hash .casan/agentic.env Plan-20 bridge feature flags .specify/ runtime state root marker (logs/traces/admissions) .claude/settings.json Plan-20 Claude Code hooks (--client claude|all) .codex/hooks.json+config Plan-20 Codex hooks (--client codex|all) `verify` recomputes the resolved harness gate-code hash and compares it to version.lock — the pin+VERIFY half. Drift/tamper of the global harness relative to what the project pinned is caught here (preserves the Plan-16 "gates are trusted code" guarantee even though the harness lives outside the repo). stdlib-only. Resolves the harness via CASAN_HARNESS_ROOT (set by the global launcher) or --harness. """ from __future__ import annotations import argparse import json import os import re import sys import time PROJECT_RE = re.compile(r"^[a-z][a-z0-9-]{1,62}$") def now_iso(): return time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()) def resolve_harness(explicit): for cand in (explicit, os.environ.get("CASAN_HARNESS_ROOT")): if cand and os.path.isdir(os.path.join(cand, "scripts", "bash")): return os.path.abspath(cand) install = os.environ.get("CASAN_INSTALL_ROOT") if install: c = os.path.join(install, "packages", "casan-harness") if os.path.isdir(c): return os.path.abspath(c) # Fallback: this file lives at packages/casan-devkit/casan-init.py. c = os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "casan-harness")) return c if os.path.isdir(c) else None def install_root(harness): if os.environ.get("CASAN_INSTALL_ROOT"): return os.path.abspath(os.environ["CASAN_INSTALL_ROOT"]) return os.path.abspath(os.path.join(harness, "..", "..")) def harness_version(harness): for p in (os.path.join(install_root(harness), "VERSION"), os.path.join(harness, "..", "..", "VERSION")): try: with open(p, "r", encoding="utf-8") as fh: v = fh.read().strip() if v: return v except (OSError, IOError): continue return "0.0.0" def compute_live(harness): """ALWAYS recompute the gate-code hash from the actual files on disk. Used by verify so a tampered harness cannot hide behind a stale recorded hash.""" sys.path.insert(0, os.path.join(harness, "scripts", "python")) try: import harness_hash # noqa: E402 return harness_hash.compute(harness), "computed" except Exception as exc: # noqa: BLE001 return "unavailable:%s" % exc, "error" def compute_harness_hash(harness): """For PINNING at init: use the value recorded at install time if present (it equals a live compute of the same files), else compute live. Verify must NOT use this — it must call compute_live() to detect drift.""" recorded = os.path.join(install_root(harness), ".harness-hash") try: with open(recorded, "r", encoding="utf-8") as fh: v = fh.read().strip() if v: return v, "recorded" except (OSError, IOError): pass return compute_live(harness) def _write(path, text, backups): if os.path.exists(path): bak = path + ".casan-bak" if not os.path.exists(bak): with open(path, "r", encoding="utf-8", errors="replace") as fh: old = fh.read() with open(bak, "w", encoding="utf-8") as fh: fh.write(old) backups.append(bak) os.makedirs(os.path.dirname(path), exist_ok=True) with open(path, "w", encoding="utf-8") as fh: fh.write(text) def _copy_template(src, dst, backups): try: with open(src, "r", encoding="utf-8") as fh: _write(dst, fh.read(), backups) return True except (OSError, IOError): return False def cmd_init(args): harness = resolve_harness(args.harness) if not harness: sys.stderr.write("casan init: cannot locate the harness. Install CASAN first " "(install.sh) or set CASAN_HARNESS_ROOT.\n") return 1 target = os.path.abspath(args.target or os.getcwd()) if not os.path.isdir(target): sys.stderr.write("casan init: target is not a directory: %s\n" % target) return 66 project = args.project or re.sub(r"[^a-z0-9-]", "-", os.path.basename(target).lower()).strip("-") if not PROJECT_RE.match(project): sys.stderr.write("casan init: --project must match ^[a-z][a-z0-9-]{1,62}$ (got %r)\n" % project) return 64 clients = ["claude", "codex"] if args.client == "all" else [args.client] version = harness_version(harness) hhash, hsource = compute_harness_hash(harness) created = [] backups = [] def created_add(p): created.append(os.path.relpath(p, target)) # ── .casan/config.json ── cfg_dir = os.path.join(target, ".casan") cfg = { "schema_version": "21.1", "project_id": project, "created_at": now_iso(), "enforcement_mode": args.mode, "integration_mode": args.integration_mode, "clients": clients, "harness_version": version, "adoption_model": "hybrid-global", } p = os.path.join(cfg_dir, "config.json") _write(p, json.dumps(cfg, ensure_ascii=False, indent=2) + "\n", backups); created_add(p) # ── .casan/version.lock (pin) ── lock = { "harness_version": version, "harness_hash": hhash, "hash_algo": "sha256", "hash_source": hsource, "install_root": install_root(harness), "recorded_at": now_iso(), } p = os.path.join(cfg_dir, "version.lock") _write(p, json.dumps(lock, ensure_ascii=False, indent=2) + "\n", backups); created_add(p) # ── .casan/agentic.env (Plan-20 flags) ── env_lines = [ "# CASAN Plan-20 agentic bridge flags. Source before starting the client.", "CASAN_AGENTIC_BRIDGE_ENABLED=1", "CASAN_AGENTIC_ENFORCEMENT_MODE=%s" % args.mode, "CASAN_AGENTIC_INTEGRATION_MODE=%s" % args.integration_mode, "", ] p = os.path.join(cfg_dir, "agentic.env") _write(p, "\n".join(env_lines), backups); created_add(p) # ── .specify/ state root marker ── specify = os.path.join(target, ".specify") os.makedirs(os.path.join(specify, "state"), exist_ok=True) os.makedirs(os.path.join(specify, "logs"), exist_ok=True) gi = os.path.join(specify, ".gitignore") if not os.path.exists(gi): _write(gi, "# CASAN runtime state — do not commit\nlogs/\nstate/\n", backups); created_add(gi) # ── Plan-20 client hooks from the harness adapters ── ad = os.path.join(harness, "adapters") if "claude" in clients: if _copy_template(os.path.join(ad, "claude-code", "settings.template.json"), os.path.join(target, ".claude", "settings.json"), backups): created_add(os.path.join(target, ".claude", "settings.json")) if "codex" in clients: for src, dst in (("hooks.template.json", "hooks.json"), ("config.template.toml", "config.toml")): if _copy_template(os.path.join(ad, "codex", src), os.path.join(target, ".codex", dst), backups): created_add(os.path.join(target, ".codex", dst)) # ── manifest (so uninstall/verify know what init created) ── manifest = { "created": created, "backups": [os.path.relpath(b, target) for b in backups], "project_id": project, "at": now_iso(), } p = os.path.join(cfg_dir, "init-manifest.json") _write(p, json.dumps(manifest, ensure_ascii=False, indent=2) + "\n", backups) print(json.dumps({ "status": "initialized", "project_id": project, "target": target, "harness_version": version, "harness_hash": hhash, "enforcement_mode": args.mode, "clients": clients, "created": created, "note": ("harness NOT copied into repo (hybrid model); " "run `casan verify-harness` to check the pin"), }, ensure_ascii=False, indent=2)) if hsource == "error": sys.stderr.write("casan init: WARNING — could not compute harness hash; " "pin verification will be unavailable.\n") return 0 def cmd_verify(args): harness = resolve_harness(args.harness) if not harness: sys.stderr.write("casan verify-harness: cannot locate the harness.\n") return 1 target = os.path.abspath(args.target or os.getcwd()) lock_path = os.path.join(target, ".casan", "version.lock") if not os.path.exists(lock_path): sys.stderr.write("casan verify-harness: no .casan/version.lock (run `casan init` first).\n") return 1 with open(lock_path, "r", encoding="utf-8") as fh: lock = json.load(fh) expected = lock.get("harness_hash") actual, _src = compute_live(harness) # live recompute — never the cached hash ok = (expected == actual) and expected and not str(expected).startswith("unavailable") result = { "status": "ok" if ok else "drift", "expected": expected, "actual": actual, "harness_version_lock": lock.get("harness_version"), "harness_version_now": harness_version(harness), "harness_root": harness, } print(json.dumps(result, ensure_ascii=False, indent=2)) if not ok: sys.stderr.write("HARNESS_INTEGRITY_DRIFT — the resolved harness does not match the " "project pin. The global harness changed or was tampered.\n") return 3 return 0 def main(argv=None): parser = argparse.ArgumentParser(prog="casan-init", description="CASAN hybrid adoption") sub = parser.add_subparsers(dest="cmd") pi = sub.add_parser("init", help="adopt CASAN into the current project (config only)") pi.add_argument("--target", help="project root (default: cwd)") pi.add_argument("--project", help="project id (^[a-z][a-z0-9-]{1,62}$; default: dir name)") pi.add_argument("--client", choices=["claude", "codex", "all"], default="all") pi.add_argument("--mode", choices=["observe", "enforce"], default="observe") pi.add_argument("--integration-mode", dest="integration_mode", choices=["project_hook", "managed_hook", "casan_owned"], default="project_hook") pi.add_argument("--harness", help="override harness root") pv = sub.add_parser("verify", help="verify the resolved harness matches the project pin") pv.add_argument("--target", help="project root (default: cwd)") pv.add_argument("--harness", help="override harness root") args = parser.parse_args(argv) if args.cmd == "init": return cmd_init(args) if args.cmd == "verify": return cmd_verify(args) parser.print_help() return 64 if __name__ == "__main__": sys.exit(main())