#!/usr/bin/env bash
# Internal projector for canonical cogitod-backed Codex hooks.
#
# Hook behavior lives in cogitod. Current Codex hook configs do not accept
# type=mcp_tool, so this installer writes command transport entries that call
# the shipped shim; the shim forwards to the daemon hook routes.
set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
HARNESS_ADAPTERS="$(cd "$SCRIPT_DIR/.." && pwd)"
REPO="$HARNESS_ADAPTERS"
if [ -d "$HARNESS_ADAPTERS/../../cogitod" ]; then
  REPO="$(cd "$HARNESS_ADAPTERS/../../.." && pwd)"
fi
MANIFEST="$HARNESS_ADAPTERS/hooks/agent-hook-manifest.json"
BOUNDARY_GATE="$HARNESS_ADAPTERS/bin/breathe-boundary-gate.mjs"
[ -f "$MANIFEST" ] || MANIFEST="$REPO/platform/cogitod/harness-adapters/hooks/agent-hook-manifest.json"
TARGET="$REPO/.codex/hooks.json"
GLOBAL=0
SHIM=""

while [ "$#" -gt 0 ]; do
  case "$1" in
    --global)
      GLOBAL=1
      TARGET="$HOME/.codex/hooks.json"
      ;;
    --target)
      TARGET="${2:?--target requires a path}"
      shift
      ;;
    --shim)
      SHIM="${2:?--shim requires a path}"
      shift
      ;;
    --manifest)
      MANIFEST="${2:?--manifest requires a path}"
      shift
      ;;
    *)
      echo "usage: project-codex-hooks.sh [--global] [--target PATH] [--shim PATH] [--manifest PATH]" >&2
      exit 2
      ;;
  esac
  shift
done

if [ -z "$SHIM" ]; then
  for candidate in \
    "$HOME/.cogito/breathe/harness-adapters/bin/hook-shim.sh" \
    "$HARNESS_ADAPTERS/bin/hook-shim.sh" \
    "$HOME/.cogito/breathe/agent-context/bin/hook-shim.sh"
  do
    if [ -f "$candidate" ]; then
      SHIM="$candidate"
      break
    fi
  done
fi
[ -n "$SHIM" ] || SHIM="$HOME/.cogito/breathe/harness-adapters/bin/hook-shim.sh"

# Global hook configuration must never retain a path into the checkout that happened
# to run the installer. Agent lanes/worktrees are disposable, so prefer the boundary
# gate installed beside the stable global shim whenever it is available.
if [ "$GLOBAL" -eq 1 ]; then
  INSTALLED_BOUNDARY_GATE="$(dirname "$SHIM")/breathe-boundary-gate.mjs"
  if [ -f "$INSTALLED_BOUNDARY_GATE" ]; then
    BOUNDARY_GATE="$INSTALLED_BOUNDARY_GATE"
  fi
fi

mkdir -p "$(dirname "$TARGET")"
python3 - "$TARGET" "$MANIFEST" "$GLOBAL" "$SHIM" "$BOUNDARY_GATE" <<'PY'
import json
import shlex
import sys
from pathlib import Path

target, manifest_path, global_install, shim, boundary_gate = sys.argv[1:6]
p = Path(target).expanduser()
manifest = json.loads(Path(manifest_path).read_text())
global_install = global_install == "1"

try:
    data = json.loads(p.read_text()) if p.exists() else {}
except Exception:
    data = {}

hooks = data.setdefault("hooks", {})

def project_manifest_items(manifest, harness):
    if "harness_capabilities" not in manifest:
        return manifest.get(harness, [])
    canonical = {
        item.get("id"): item
        for item in manifest.get("events", [])
        if item.get("id")
    }
    projected = []
    capability = manifest.get("harness_capabilities", {}).get(harness, {})
    for projection in capability.get("events", []):
        base = canonical.get(projection.get("event_id"), {})
        item = dict(base)
        item.update(projection)
        item["hook"] = projection.get("hook") or base.get("hook", "")
        item["status"] = projection.get("status") or base.get("status", "")
        item["mcp_tool"] = projection.get("mcp_tool") or base.get("mcp_tool", "")
        projected.append({k: v for k, v in item.items() if v not in ("", None)})
    return projected

def mcp_tool_for(item):
    if item.get("mcp_tool"):
        return item["mcp_tool"]
    hook = item.get("hook", "")
    event = item.get("event", "")
    if hook == "brief":
        return "agent_hook_brief"
    if hook == "capture":
        return "agent_hook_session_stop" if event in ("Stop", "SessionEnd") else "agent_hook_capture"
    if event == "PreToolUse":
        return "agent_hook_pre_tool"
    if event == "PostToolUse":
        return "agent_hook_post_tool"
    if event in ("Stop", "SessionEnd"):
        return "agent_hook_session_stop"
    return "agent_hook_post_tool"

items = project_manifest_items(manifest, "codex")
canonical_hooks = {(h["event"], h.get("matcher", ""), h.get("hook", "")) for h in items}
canonical_mcp_tools = {(h["event"], h.get("matcher", ""), mcp_tool_for(h)) for h in items}
legacy_scripts = {
    "pre-tool-use-comprehension.sh",
    "pre-tool-use-collision-warn.sh",
    "pre-tool-use-commit-mutex.sh",
    "post-tool-use-edit-capture.sh",
}
legacy_hook_aliases = {
    "edit-capture": "capture",
    "subagent-stop": "capture",
}
superseded_codex_pre_hooks = {
    ("PreToolUse", "Edit", "edit-mutex"),
    ("PreToolUse", "Edit", "comprehension"),
    ("PreToolUse", "Edit", "deprecated-warn"),
    ("PreToolUse", "Edit", "coord-claim"),
    ("PreToolUse", "Edit", "collision-warn"),
    ("PreToolUse", "Write", "edit-mutex"),
    ("PreToolUse", "Write", "deprecated-warn"),
    ("PreToolUse", "Write", "coord-claim"),
    ("PreToolUse", "Write", "collision-warn"),
}
superseded_codex_post_hooks = {
    ("PostToolUse", "Edit", "capture"),
    ("PostToolUse", "Write", "capture"),
    ("PostToolUse", "Bash", "bash-commit"),
    ("PostToolUse", "*", "signal-sense"),
    ("PostToolUse", "*", "post-tool"),
}
superseded_codex_lifecycle_hooks = {
    ("SessionStart", "", "brief"),
    ("SessionStart", "", "agent_hook_brief"),
    ("SessionEnd", "", "capture"),
    ("SessionEnd", "", "agent_hook_session_stop"),
}
managed_legacy_hooks = {
    "brief", "capture", "pre-edit", "commit-mutex", "post-tool", "session-stop",
}

def entry_tool_name(entry) -> str:
    entry_hooks = entry.get("hooks") or []
    if not entry_hooks:
        return ""
    first = entry_hooks[0]
    if first.get("type") == "mcp_tool":
        return first.get("tool", "")
    command = first.get("command", "")
    try:
        parts = shlex.split(command)
    except ValueError:
        parts = command.split()
    if not parts:
        return ""
    for i, part in enumerate(parts):
        if Path(part).name == "breathe-boundary-gate.mjs":
            return "breathe-boundary"
        if Path(part).name == "hook-shim.sh" and i + 1 < len(parts):
            return legacy_hook_aliases.get(parts[i + 1], parts[i + 1])
    for part in parts:
        if Path(part).name in legacy_scripts:
            return Path(part).name
    return ""

for event, entries in list(hooks.items()):
    kept = []
    for entry in entries:
        matcher = entry.get("matcher", "")
        entry_hooks = entry.get("hooks") or []
        command = entry_hooks[0].get("command", "") if entry_hooks else ""
        name = entry_tool_name(entry)
        unguarded_global = (
            global_install
            and name
            and not command.lstrip().startswith('test -f "${CODEX_PROJECT_DIR:-$PWD}/.codex/hooks.json" || ')
        )
        if (
            name == "breathe-boundary"
            or unguarded_global
            or
            name in legacy_scripts
            or name in managed_legacy_hooks
            or (event, matcher, name) in canonical_hooks
            or (event, matcher, name) in canonical_mcp_tools
            or (event, matcher, name) in superseded_codex_pre_hooks
            or (event, matcher, name) in superseded_codex_post_hooks
            or (event, matcher, name) in superseded_codex_lifecycle_hooks
        ):
            continue
        kept.append(entry)
    if kept:
        hooks[event] = kept
    else:
        hooks.pop(event, None)

for item in items:
    event = item["event"]
    matcher = item.get("matcher", "")
    mode = item.get("mode", "")
    phase = item.get("phase", "")
    home = str(Path.home()) + "/"
    shim_command = '"${HOME}/' + shim[len(home):] + '"' if shim.startswith(home) else shlex.quote(shim)
    node_resolver = 'node_bin=$(command -v node 2>/dev/null); [ -n "$node_bin" ] || for c in "$HOME/.local/share/mise/shims/node" "$HOME/.nvm/current/bin/node" /opt/homebrew/bin/node /usr/local/bin/node; do [ -x "$c" ] && node_bin="$c" && break; done; exec "$node_bin" "$0"'
    gate_token = '"${HOME}/' + boundary_gate[len(home):] + '"' if boundary_gate.startswith(home) else shlex.quote(boundary_gate)
    boundary_command = "sh -c " + shlex.quote(node_resolver) + " " + gate_token
    command = boundary_command if item["hook"] == "breathe-boundary" else " ".join(
        ["BREATHE_HARNESS=codex", shim_command, shlex.quote(item["hook"])]
        + ([shlex.quote(phase)] if phase else [])
        + ([shlex.quote(mode)] if mode else [])
    )
    if global_install:
        command = 'test -f "${CODEX_PROJECT_DIR:-$PWD}/.codex/hooks.json" || ' + command
    hook = {
        "type": "command",
        "command": command,
        "statusMessage": item["status"],
    }
    entry = {"hooks": [hook]}
    if matcher:
        entry["matcher"] = matcher
    hooks.setdefault(event, []).append(entry)

p.write_text(json.dumps(data, indent=2) + "\n")
PY
