#!/usr/bin/env python3
"""orch_post_bash.py — PostToolUse audit logger for /orchestrate (fail-OPEN).

Wired in ~/.claude/settings.json on the Bash/Edit/Write matcher. PostToolUse hooks must
NEVER block the tool (it already ran) — this always exits 0 and swallows every error.

v1 scope: append a lightweight action record to <run_dir>/actions.jsonl for every tool
call made while an orchestrate run is active. This is a complement to the hash-chained
ORCH_LOG.jsonl SSOT (which only the guard writes) — a flat, append-only audit trail of
what the engine actually DID, supporting post-hoc reasoning + the reversibility audit.

Deliberately NOT in v1 (skill-driven instead, more reliable than command-parsing here):
dispatch status.json -> ORCH_STATE auto-sync, and per-edit validate+checkpoint. Add per
the DOGFOOD_DIRECTIVE only if a real failure shows the skill-driven path is insufficient.
"""
import json
import sys
from pathlib import Path

ACTIVE = Path.home() / ".claude" / "orchestrate" / "active_run"


def _now_iso():
    import datetime as dt
    return dt.datetime.now(dt.timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")


def main() -> int:
    try:
        payload = json.load(sys.stdin)
    except Exception:
        return 0
    try:
        if not ACTIVE.exists():
            return 0
        run_dir = Path(ACTIVE.read_text(encoding="utf-8").strip())
        if not run_dir or not run_dir.is_dir():
            return 0
        ti = payload.get("tool_input") or {}
        rec = {
            "ts": _now_iso(),
            "tool": payload.get("tool_name"),
            "command": (ti.get("command") or "")[:500],
            "file_path": ti.get("file_path"),
            "ok": (payload.get("tool_response") or {}).get("success", None),
        }
        with open(run_dir / "actions.jsonl", "a", encoding="utf-8") as fh:
            fh.write(json.dumps(rec, ensure_ascii=False) + "\n")
    except Exception:
        pass  # fail-open: a post-hook must never break the session
    return 0


if __name__ == "__main__":
    sys.exit(main())
