"""Codex installation, onboarding, and hook-trust documentation checks."""
from pathlib import Path

ROOT = Path(__file__).resolve().parent.parent
DOC = (ROOT / "docs" / "codex.md").read_text(encoding="utf-8")
INIT = (ROOT / "dcs" / "workflows" / "init.md").read_text(encoding="utf-8")
README = (ROOT / "README.md").read_text(encoding="utf-8")

checks = []


def check(name, ok):
    checks.append((ok, name))
    print(f"{'PASS' if ok else 'FAIL'}  {name}")


check("install and update commands are documented",
      "dcs install --target codex" in DOC and "dcs install --target all" in DOC)
check("uninstall and prior marketplace restoration are documented",
      "dcs uninstall --target codex" in DOC
      and "restores recorded collisions and marketplace state" in DOC
      and "exact file inventory" in DOC and "preserves modified owned files" in DOC
      and "Missing, legacy, or malformed inventories" in DOC)
check("supported local-plugin installation is explicit",
      "codex plugin marketplace list --json" in DOC
      and "codex plugin add dcs-seat-models@dcs-command-system" in DOC
      and "codex plugin list --available --json" in DOC)
check("native manifest migration and discovery are explicit",
      all(item in DOC for item in ("dcs/Codex/plugin/plugin.json",
          "plugin/.codex-plugin/plugin.json", "exact inventory digest before migration",
          "foreign or modified manifest at either path", "before home writes",
          "native app-server `hooks/list`", "all five plugin-sourced definitions",
          "untrusted status", "executes no hooks and writes no trust",
          "list all five untrusted definitions without warnings or errors", "showed zero DCS hooks",
          "discovery alone does not establish enforcement")))
check("all supported hook events are named",
      all(f"`{event}`" in DOC for event in
          ("PreToolUse", "UserPromptSubmit", "PostToolUse", "SubagentStop", "Stop")))
check("trust review and protected-edit UAT are required",
      "`/hooks`" in DOC and "Before IAP approval" in DOC and "direct protected edit" in DOC
      and "Bash/unified-exec" in DOC and "repeat both paths" in DOC
      and "Repeat review and trust after hook definitions change" in DOC
      and "Until that UAT succeeds" in DOC)
check("trust cannot be inferred from files or plugin installation",
      "does not trust hook definitions" in DOC
      and "do not prove that hooks are trusted" in DOC)
check("hook coverage limits are disclosed",
      "may bypass hooks" in DOC and "Hook errors or timeouts" in DOC)
check("model controls and six seats are documented",
      "dcs models show --target codex" in DOC
      and "dcs models set --target codex" in DOC
      and all(f"`{seat}`" in DOC for seat in
              ("commander", "chief", "safety-officer", "specialist", "analyst", "weak")))
check("five profile seats share chief and weak is per-call",
      "six canonical profiles" in DOC
      and "five profile seats" in DOC
      and "both `dcs-planning-chief` and `dcs-logistics-chief` use the shared `chief` seat" in DOC
      and "per-call model override rather than a profile seat" in DOC
      and "supported agent-spawn option" in DOC
      and "do not claim parity" in DOC)
check("model precedence and project-routing evidence are documented",
      "Codex-home `dcs-seats.json`" in DOC
      and "project `.dcs/config.json` field `codex_seat_models`" in DOC
      and "verified by a supported Codex spawn" in DOC)
check("shipped map and explicit overrides are documented",
      all(item in DOC for item in ("`commander` = `gpt-6-astra`", "`chief` = `gpt-6.1-sol`",
          "`safety-officer` = `gpt-6-astra`", "`specialist` = `gpt-6.1-sol`",
          "`analyst` = `gpt-6-luna`", "`weak` = `gpt-6-luna`",
          "`--seat-token weak`", "`--task-model terra --bounded-task <one-task-description>`",
          "not a seventh seat")))
check("runtime reads and shell coverage are bounded",
      "every file named by an explicit Read instruction" in DOC
      and "does not expand implicit includes" in DOC
      and all(f"`{tool}`" in DOC for tool in ("Bash", "exec_command", "shell_command", "unified_exec"))
      and "conservatively refuses opaque or unsupported shell commands" in DOC
      and "does not fully parse arbitrary shell programs" in DOC
      and "not proof that a live spawn used it" in DOC)
check("supported shell forms and approval boundaries are documented",
      all(item in DOC for item in ("`pwd`", "`cat <path>`", "`grep -n`", "`dcs_log.py`",
          "token ledger", "`python tests/test_<name>.py`", "`git add`", "`git commit -m`",
          "current Safety pass", "`verdict_rerun.py`", "`dcs_log.py run` requires a prepared and admitted instance",
          "absolute execution working directory")))
check("collision recovery and default profile conflicts are explicit",
      "uninstall exits nonzero" in DOC and "original bytes and recovery marker" in DOC
      and "only inventoried files" in DOC and "conflicting custom `default`" in DOC
      and "whose name cannot be determined safely" in DOC
      and "`message`" in DOC and "`agent_type=default`" in DOC)
check("unsupported assurances are absent",
      all(claim not in DOC.lower() for claim in (
          "hook presence proves trust", "shell writes bypass approval by design",
          "arbitrary shell programs are fully parsed", "effective spawn routing is proven")))
check("onboarding points to Codex trust and UAT guidance",
      "5b. Codex target" in INIT and "`docs/codex.md`" in INIT)
check("existing Claude and DSH guidance remains present",
      "Claude Code target" in INIT and "DSH target" in INIT
      and "claude" in README.lower() and "dsh" in README.lower())
check("ten command skills are documented",
      "all ten DCS command skills" in DOC and all(f"/dcs-{name}" in README for name in
          ("init", "run", "new", "plan", "execute", "close", "status", "esg", "loop", "deploy")))
check("isolated acceptance separates login, review, trust and observed children",
      all(item in DOC for item in ("CODEX_SQLITE_HOME", "sqlite_home", "cli_auth_credentials_store",
          "codex login status", "--no-daemon", "current non-managed", "verify persisted trust",
          "completed child results", "failed or cancelled", "reasoning effort")))
check("observer and enforcement evidence are distinguished from declarations",
      all(item in DOC for item in ("uat-observer/hooks.example.json", "not enabled automatically",
          "DCS_MODEL_OBSERVER_LOG", "Automated payload and registration diagnostics establish files and declarations only",
          "write_stdin", "may bypass hooks", "unchanged bytes before approval")))
check("restoration and fixture exception stay bounded",
      all(item in DOC for item in ("exact prior local marketplace root", "installed/enabled state",
          "refusal before mutation", "never to governing homes", "retain recovery records")))
check("canonical provenance and unsupported command are honest",
      all(item in DOC for item in ("`dcs/workflows/deploy.md` step 7", "adapted runtime resource path is separate",
          "ENVIRONMENT failure, not a pass or a skip", "no minimum Codex version is established")))

check("exact independent inventory commands are runnable",
      all(item in DOC for item in (
          "python dcs/tools/codex_transform.py --check-runtime-operations --project-root <PROJECT_ROOT> --project-instructions <PROJECT_ROOT>/AGENTS.md",
          "python dcs/tools/codex_transform.py --repo-root . --check-packaged-runtime",
          "complete inventory population, tested command instances, and native/Owner observations")))
check("prepared setup, task and child authorization are explicit",
      all(item in DOC for item in ("Before ACTIVE", "matching Owner receipt", "setup approval grants no incident execution",
          "prepare --request <REQUEST> --output <PREPARED>", "run --prepared <PREPARED>",
          "not repeated Owner approval", "current IAP and task", "separately admitted exact child descriptors",
          "mandatory canonical authority", "distinct path and exact identity", "start inclusive and end exclusive")))
check("apply ordering and effects boundaries are explicit",
      all(item in DOC for item in ("first-inline evidence parser", "post-mutation outcomes",
          "Only NOT-ELIGIBLE selects a specialist", "no retry, rollback or specialist fallback",
          "descendant effects", "no universal descendant confinement", "independent Owner identity")))
check("pending owner acceptance and native registration remain separate",
      all(item in DOC for item in ("Pending Owner UAT checklist", "this checklist has not been completed",
          "codex plugin list --available --json", "trust and enforcement unverified", "not a native collision-recovery observation",
          "outside Git", "never copy or log its contents")))

check("close route and observed native boundaries are explicit",
      all(item in DOC for item in ("immutable `close-lifecycle` plan", "fresh, single-use instance",
          "record integrity and admitted verdict rerun", "one non-fast-forward merge",
          "removes the exact registered worktree without force", "no second merge",
          "completed 12 receipts with assistance", "dubious-ownership", "approved linked-worktree bytes used CRLF",
          "primary checkout used LF", "do not authorize a general bypass", "external integration and worktree actions",
          "all 12 advancing receipts", "no manual EOL substitution", "Tracked blobs matched",
          "python -B tests/fixtures/codex-install/close_eol.py --verify-native-evidence <SESSION_JSONL_PATH>")))

failed = [name for ok, name in checks if not ok]
print(f"{len(checks) - len(failed)}/{len(checks)} passed")
raise SystemExit(1 if failed else 0)
