#!/usr/bin/env bash
# Product installer for Cogitod harness adapters.
#
# This is the only installer shipped in the Cogitod harness-adapter bundle. It assumes
# cogitod already exists on the machine and wires local agent clients to it:
# - Claude Code MCP + MCP hooks
# - Codex MCP + command hook transport
# - opencode MCP + transport plugin
#
# It intentionally ships no development bootstrap helpers or build-time tooling.

set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
HARNESS_ADAPTERS="$(cd "$SCRIPT_DIR/.." && pwd)"
HOOK_MANIFEST="$HARNESS_ADAPTERS/hooks/agent-hook-manifest.json"
CODEX_HOOK_PROJECTOR="$HARNESS_ADAPTERS/bin/project-codex-hooks.sh"
CODEX_HOOK_SHIM="$HARNESS_ADAPTERS/bin/hook-shim.sh"
BOUNDARY_GATE="$HARNESS_ADAPTERS/bin/breathe-boundary-gate.mjs"
WORKER_HEARTBEAT="$HARNESS_ADAPTERS/bin/worker-heartbeat.sh"
SESSION_BUDGET="$HARNESS_ADAPTERS/bin/session-budget.sh"
OPENCODE_PLUGIN="$HARNESS_ADAPTERS/opencode/breathe-context.mjs"
[ -f "$OPENCODE_PLUGIN" ] || OPENCODE_PLUGIN="$HARNESS_ADAPTERS/opencode/breathe-context.ts"
SOURCE_CONTEXT_EXPORTER="$HARNESS_ADAPTERS/bin/source-context-export.sh"
HARNESS_EXEC="$HARNESS_ADAPTERS/bin/cogito-harness-exec.sh"
HARNESS_RUNNER="$HARNESS_ADAPTERS/bin/cogito-harness-runner.sh"
# The promotion route file is the machine's authority on which port owns the
# canonical `breathe` name. Prefer it over BREATHE_PORT — mirrors endpoint() in
# ensure-agent-setup.ts so the two writers never disagree. Without it, an install
# run from a shell carrying a stale BREATHE_PORT repoints every agent at the wrong
# daemon, and that failure is silent: the client connects fine and reads the wrong
# (usually empty) store instead of erroring.
ROUTED_PORT="$(sed -n '1{/^[0-9][0-9]*$/p;}' "$HOME/.cogito/breathe/router/active-port" 2>/dev/null || true)"
ENDPOINT="${BREATHE_MCP_ENDPOINT:-http://127.0.0.1:${ROUTED_PORT:-${BREATHE_PORT:-24567}}}"
MCP_PROFILE="${BREATHE_MCP_PROFILE:-${COGITOD_DEFAULT_MCP_PROFILE:-agent}}"
case "$MCP_PROFILE" in agent|app|full|experimental) ;; *) echo "invalid MCP profile: $MCP_PROFILE" >&2; exit 2;; esac

if [ "${1:-}" = "--bundle" ]; then
  shift
  [ "$#" -eq 0 ] || { echo "usage: install-harness-adapters.sh [--bundle]" >&2; exit 2; }
  INSTALLED_ADAPTERS="$HOME/.cogito/breathe/harness-adapters"
  if [ "$HARNESS_ADAPTERS" != "$INSTALLED_ADAPTERS" ]; then
    mkdir -p "$INSTALLED_ADAPTERS"
    chmod -R u+w "$INSTALLED_ADAPTERS" 2>/dev/null || true
    cp -R "$HARNESS_ADAPTERS/." "$INSTALLED_ADAPTERS/"
    rm -rf "$INSTALLED_ADAPTERS/skills"
    if [ -d "$HARNESS_ADAPTERS/skills" ]; then
      mkdir -p "$INSTALLED_ADAPTERS/skills"
      cp -R "$HARNESS_ADAPTERS/skills/." "$INSTALLED_ADAPTERS/skills/"
    elif [ -d "$HARNESS_ADAPTERS/../../infra/skills" ]; then
      mkdir -p "$INSTALLED_ADAPTERS/skills"
      cp -R "$HARNESS_ADAPTERS/../../infra/skills/." "$INSTALLED_ADAPTERS/skills/"
    fi
  fi
  exec "$INSTALLED_ADAPTERS/bin/install-harness-adapters.sh"
fi
[ "$#" -eq 0 ] || { echo "usage: install-harness-adapters.sh [--bundle]" >&2; exit 2; }

G='\033[0;32m'; Y='\033[1;33m'; C='\033[0;36m'; B='\033[1m'; N='\033[0m'
ok() { echo -e "  ${G}✓${N}  $1"; }
warn() { echo -e "  ${Y}!${N}  $1"; }
step() { echo -e "\n${C}${B}▸ $1${N}"; }

need_file() {
  local path="$1" label="$2"
  if [ ! -f "$path" ]; then
    echo "missing shipped $label: $path" >&2
    exit 1
  fi
}

validate_hook_manifest_contract() {
  python3 - "$HOOK_MANIFEST" <<'PY'
import json
import sys
from pathlib import Path

manifest = json.loads(Path(sys.argv[1]).read_text())
events = manifest.get("events")
matrix = manifest.get("harness_capabilities")
if manifest.get("version", 0) < 2 or not isinstance(events, list) or not isinstance(matrix, dict):
    raise SystemExit("hook manifest must be version 2 with events and harness_capabilities")

canonical = {}
for event in events:
    event_id = event.get("id")
    if not event_id or event_id in canonical:
        raise SystemExit(f"invalid or duplicate canonical event id: {event_id!r}")
    # transport_only events run as a local command with no daemon tool behind them, so they
    # declare a hook but no mcp_tool — and must NOT claim one they never call.
    if not event.get("hook"):
        raise SystemExit(f"canonical event {event_id} must declare hook")
    if event.get("transport_only"):
        if event.get("mcp_tool"):
            raise SystemExit(f"transport_only event {event_id} must not declare mcp_tool")
    elif not event.get("mcp_tool"):
        raise SystemExit(f"canonical event {event_id} must declare hook and mcp_tool")
    canonical[event_id] = event

for harness in ("claude", "codex", "opencode"):
    capability = matrix.get(harness)
    if not isinstance(capability, dict):
        raise SystemExit(f"missing harness capability matrix: {harness}")
    projections = capability.get("events")
    if not isinstance(projections, list) or not projections:
        raise SystemExit(f"missing hook projections for {harness}")
    for projection in projections:
        event_id = projection.get("event_id")
        if event_id not in canonical:
            raise SystemExit(f"{harness} projection references unknown event_id: {event_id!r}")
        if not (projection.get("event") or projection.get("pluginEvent")):
            raise SystemExit(f"{harness} projection for {event_id} lacks host event")
PY
}

install_manifest_json_hooks() {
  local path="$1" harness="$2" manifest="$3" heartbeat="$4" shim="$5"
  mkdir -p "$(dirname "$path")"
  python3 - "$path" "$harness" "$manifest" "$heartbeat" "$BOUNDARY_GATE" "$shim" "$SESSION_BUDGET" <<'PY'
import json, shlex, sys
from pathlib import Path

path, harness, manifest_path, heartbeat, boundary_gate, shim, session_budget = sys.argv[1:8]
p = Path(path).expanduser()
try:
    data = json.loads(p.read_text()) if p.exists() else {}
except Exception:
    data = {}

manifest = json.loads(Path(manifest_path).read_text())
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

items = project_manifest_items(manifest, harness)
hooks = data.setdefault("hooks", {})
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"

canonical = {(i["event"], i.get("matcher", ""), mcp_tool_for(i)) for i in items}
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_lifecycle_tools = {
    "agent_hook_brief", "agent_hook_capture", "agent_hook_pre_tool",
    "agent_hook_post_tool", "agent_hook_session_stop",
}

def hook_name(command: str) -> str:
    try:
        parts = shlex.split(command)
    except ValueError:
        parts = command.split()
    for idx, part in enumerate(parts):
        if Path(part).name == "worker-heartbeat.sh":
            return "agent_hook_post_tool"
        # Dedup identity only. session-budget is transport_only — no MCP tool behind it — so it
        # takes mcp_tool_for()'s fallback, and this must return the SAME value or the reinstall
        # pass cannot recognize its own previous entry and appends a duplicate each run. Its
        # (event, matcher) differs from worker-heartbeat's, so sharing the fallback is unambiguous.
        if Path(part).name == "session-budget.sh":
            return "agent_hook_post_tool"
        if Path(part).name == "breathe-boundary-gate.mjs":
            return "breathe-boundary"
        if Path(part).name == "hook-shim.sh" and idx + 1 < len(parts):
            return legacy_hook_aliases.get(parts[idx + 1], parts[idx + 1])
    return ""

def entry_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", "")
    return hook_name(first.get("command", ""))

def unsupported_breathe_lifecycle(event, entry) -> bool:
    if event not in ("SessionStart", "SessionEnd"):
        return False
    return any(
        hook.get("type") == "mcp_tool" and hook.get("server") == "breathe"
        for hook in (entry.get("hooks") or [])
    )

for event, entries in list(hooks.items()):
    kept = []
    for entry in entries:
        matcher = entry.get("matcher", "")
        name = entry_name(entry)
        if (
            name in ("breathe-boundary", "lifecycle")
            or (event, matcher, name) in canonical
            or (harness == "claude" and name in superseded_lifecycle_tools)
            or unsupported_breathe_lifecycle(event, entry)
            or (
                harness == "codex"
                and ((event, matcher, name) in superseded_codex_pre_hooks
                     or (event, matcher, name) in superseded_codex_post_hooks)
            )
        ):
            continue
        kept.append(entry)
    hooks[event] = kept

for item in items:
    event = item["event"]
    matcher = item.get("matcher", "")
    mode = item.get("mode", "")
    phase = item.get("phase", "")
    if item.get("transport") == "command":
        home = str(Path.home()) + "/"
        portable = lambda value: '"${HOME}/' + value[len(home):] + '"' if value.startswith(home) else shlex.quote(value)
        if item.get("hook") == "breathe-boundary":
            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"'
            command = "sh -c " + shlex.quote(node_resolver) + " " + portable(boundary_gate)
            target = boundary_gate
        elif item.get("hook") == "worker-heartbeat":
            # Invoked THROUGH bash, not as a bare path. The bare form only ever worked because
            # the installer chmodded the source +x, which mutated a tracked repo file to make
            # its own output runnable. Dropping that chmod without this would leave the hook
            # pointing at a non-executable file and fail at runtime, so the two move together.
            command = "bash " + portable(heartbeat)
            target = heartbeat
        # Context budget runs as a plain command, not through the shim: it must not depend on the
        # daemon being up. The whole point is to bound a session, and a session whose daemon died
        # is exactly when an unbounded context is most likely.
        elif item.get("hook") == "session-budget":
            command = portable(session_budget) + " gate"
            target = session_budget
        else:
            command = " ".join(filter(None, [f"BREATHE_HARNESS={shlex.quote(harness)}", portable(shim), shlex.quote(item.get("hook", "")), shlex.quote(phase), shlex.quote(mode)]))
            target = shim
        # Wiring a path the bundle does not carry costs the developer an error on every single
        # prompt and buys nothing, so leave the entry out instead. The bundler already fails the
        # build on this; that check owns the fix, and this one owns the blast radius when a bundle
        # slips through anyway. The prune pass above has already dropped any stale entry, so the
        # hook ends up absent rather than broken.
        if not Path(target).exists():
            print(f"⚠️  skipping {item.get('hook','')} {event} hook: {target} is not in this bundle", file=sys.stderr)
            continue
        hook = {"type": "command", "command": command, "statusMessage": item["status"]}
        if item.get("async") is True:
            hook["async"] = True
        timeout = item.get("timeout")
        if isinstance(timeout, (int, float)) and timeout > 0:
            hook["timeout"] = timeout
    else:
        hook = {"type": "mcp_tool", "server": "breathe", "tool": mcp_tool_for(item), "statusMessage": item["status"]}
    tool_input = {"harness": harness}
    if phase:
        tool_input["phase"] = phase
        tool_input["host_event"] = event
    if mode:
        tool_input["mode"] = mode
    hook["input"] = tool_input
    entry = {"hooks": [hook]}
    if matcher:
        entry["matcher"] = matcher
    hooks.setdefault(event, []).append(entry)

# The statusline is the only nudge channel that costs zero context, so the routine "how full am I"
# signal lives there and in-context text is reserved for the thresholds that must interrupt.
# Only claimed if unset or already ours — a hand-written statusline is the developer's, not ours.
if harness == "claude" and Path(session_budget).name == "session-budget.sh":
    existing = data.get("statusLine") or {}
    ours = "session-budget.sh" in str(existing.get("command", ""))
    if not Path(session_budget).exists():
        # A dead pointer we wrote is ours to retract — otherwise the developer keeps staring at a
        # blank statusline that no reinstall ever clears. A hand-written one is theirs; leave it.
        if ours:
            data.pop("statusLine", None)
            print(f"⚠️  removed statusline: {session_budget} is not in this bundle", file=sys.stderr)
    elif not existing or ours:
        home = str(Path.home()) + "/"
        sb = ('"${HOME}/' + session_budget[len(home):] + '"') if session_budget.startswith(home) \
            else shlex.quote(session_budget)
        data["statusLine"] = {"type": "command", "command": sb + " statusline", "padding": 0}

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

merge_codex_toml() {
  local path="$1"
  mkdir -p "$(dirname "$path")"
  python3 - "$path" "$ENDPOINT/mcp?profile=$MCP_PROFILE" "$SCRIPT_DIR/../harness-runtime-manifest.json" <<'PY'
import json, os, re, sys
from pathlib import Path

p = Path(sys.argv[1]).expanduser()
url = sys.argv[2]
manifest_path = Path(sys.argv[3])
text = p.read_text() if p.exists() else ""
try:
    optional = json.loads(manifest_path.read_text()).get("optional_codex_mcp", {})
except Exception:
    optional = {}
# This machine runs one canonical cogitod. Development/experimental product
# profiles remain release targets, but must never leak into harness discovery.
text = re.sub(
    r'(?ms)^\[mcp_servers\.breathe(?:[-_](?:dev|exp|experimental))(?:\.[^\]]+)?\]\n.*?(?=^\[|\Z)',
    '',
    text,
)
for name, policy in optional.items():
    if policy.get("missing_absolute_command") != "remove":
        continue
    escaped = re.escape(name)
    main = re.search(rf'(?ms)^\[mcp_servers\.{escaped}\]\n(.*?)(?=^\[|\Z)', text)
    command = re.search(r'(?m)^\s*command\s*=\s*["\']([^"\']+)["\']', main.group(1)) if main else None
    if command and os.path.isabs(command.group(1)) and not os.access(command.group(1), os.X_OK):
        text = re.sub(rf'(?ms)^\[mcp_servers\.{escaped}(?:\.[^\]]+)?\]\n.*?(?=^\[|\Z)', '', text)
section = '[mcp_servers.breathe]\nurl = "{}"\n'.format(url)
pattern = r'(?ms)^\[mcp_servers\.breathe\]\n.*?(?=^\[|\Z)'
if re.search(pattern, text):
    text = re.sub(pattern, section, text).rstrip() + "\n"
else:
    text = (section + "\n" + text).rstrip() + "\n"
p.write_text(text)
PY
}

merge_opencode_config() {
  local path="$1"
  mkdir -p "$(dirname "$path")"
  python3 - "$path" "$ENDPOINT/mcp?profile=$MCP_PROFILE" "$OPENCODE_PLUGIN" <<'PY'
import json, sys
from pathlib import Path

path, url, plugin = sys.argv[1:4]
p = Path(path).expanduser()
try:
    data = json.loads(p.read_text()) if p.exists() else {}
except Exception:
    data = {}
data["$schema"] = data.get("$schema") or "https://opencode.ai/config.json"
mcp = data.setdefault("mcp", {})
mcp["breathe"] = {
    "type": "remote",
    "url": url,
    "enabled": True,
    "timeout": 30000,
    # OpenCode expands this at process startup, so one global MCP definition
    # still scopes every fresh harness to the repository it was launched in.
    "headers": {"X-Working-Directory": "{env:PWD}"},
}
plugins = data.setdefault("plugin", [])
plugins[:] = [
    item for item in plugins
    if not (
        isinstance(item, str)
        and (
            item.endswith("/platform/infra/skills/_adapters/opencode/breathe-context.ts")
            or item.endswith("/platform/infra/opencode/breathe-context.ts")
            or item.endswith("/opencode/breathe-context.ts")
            or item.endswith("/opencode/breathe-context.mjs")
        )
    )
]
if plugin not in plugins:
    plugins.append(plugin)
p.write_text(json.dumps(data, indent=2) + "\n")
PY
}

normalize_breathe_mcp() {
  python3 - "$HOME/.claude.json" "$HOME/.claude/settings.json" "$ENDPOINT/mcp?profile=$MCP_PROFILE" <<'PY'
import json, sys
from pathlib import Path

cfg_path, settings_path, url = sys.argv[1:4]

p = Path(cfg_path).expanduser()
try:
    data = json.loads(p.read_text()) if p.exists() else {}
except Exception:
    data = {}
if isinstance(data, dict):
    servers = data.setdefault("mcpServers", {})
    want = {"type": "http", "url": url}
    changed = False
    for name in list(servers):
        if name != "breathe" and __import__("re").fullmatch(r"breathe[-_](?:dev|exp|experimental)(?:[-_].*)?", name):
            del servers[name]
            changed = True
    if servers.get("breathe") != want:
        servers["breathe"] = want
        changed = True
    if changed:
        p.write_text(json.dumps(data, indent=2) + "\n")

# MCP lifecycle hooks are now the supported transport; leave them intact.
PY
}

install_source_context_exporter() {
  local dest="$HOME/.cogito/breathe/bin/source-context-export"
  mkdir -p "$(dirname "$dest")"
  cat > "$dest" <<EOF
#!/usr/bin/env bash
exec "$SOURCE_CONTEXT_EXPORTER" "\$@"
EOF
  chmod +x "$dest" 2>/dev/null || true
}

install_skill_adapters() {
  local root source target skill_root="$HARNESS_ADAPTERS/skills"
  [ -d "$skill_root" ] || skill_root="$HARNESS_ADAPTERS/../../infra/skills"
  for root in "$HOME/.claude/skills" "${CODEX_HOME:-$HOME/.codex}/skills" "$HOME/.config/opencode/skills"; do
    mkdir -p "$root"
    for source in "$skill_root"/*; do
      [ -f "$source/SKILL.md" ] || continue
      target="$root/$(basename "$source")"
      if [ -e "$target" ] && [ ! -L "$target" ]; then warn "Preserving unmanaged skill: $target"; continue; fi
      ln -sfn "$source" "$target"
    done
  done
}

# Codex resolves agent roles ONLY from $CODEX_HOME/agents/*.toml. It never scans a
# repository-level .codex/agents/, so the adapters harness_materialize writes into each
# repo are invisible to Codex until they are projected here. Verified against codex-cli
# 0.146.0: with no role file present Codex exposes no spawn_agent tool at all.
#
# These must be COPIES, not symlinks. Codex's role scan keeps only entries whose dirent
# type is a regular file, so a symlinked role is silently skipped — an 87-role symlink
# farm still yields AGENT_ROLE_COUNT=0. Skills tolerate symlinks; roles do not.
# Ownership is tracked in a sidecar manifest so a re-run can retire withdrawn roles
# without touching a role the user hand-wrote.
install_codex_agent_roles() {
  local source target name root="${CODEX_HOME:-$HOME/.codex}/agents"
  local manifest="$root/.cogito-managed"
  local agent_root="$HARNESS_ADAPTERS/agents"
  [ -d "$agent_root" ] || agent_root="$HARNESS_ADAPTERS/../../../.codex/agents"
  [ -d "$agent_root" ] || return 0
  mkdir -p "$root"
  # Retire previously managed roles this bundle no longer ships.
  if [ -f "$manifest" ]; then
    while IFS= read -r name; do
      [ -n "$name" ] || continue
      [ -f "$agent_root/$name" ] || rm -f "$root/$name"
    done < "$manifest"
  fi
  : > "$manifest.next"
  for source in "$agent_root"/*.toml; do
    [ -f "$source" ] || continue
    name="$(basename "$source")"
    target="$root/$name"
    if [ -e "$target" ] && ! grep -qxF "$name" "$manifest" 2>/dev/null; then
      warn "Preserving unmanaged agent role: $target"; continue
    fi
    cp -f "$source" "$target"
    printf '%s\n' "$name" >> "$manifest.next"
  done
  mv -f "$manifest.next" "$manifest"
  warn_if_model_lacks_multi_agent
}

# Installed roles are inert unless the configured model advertises multi_agent_version.
# gpt-5.3-codex-spark does not, and Codex reports no spawn_agent tool at all on it —
# indistinguishable from "the roles were never installed" unless we say so here.
warn_if_model_lacks_multi_agent() {
  local model catalog
  model="$(sed -n 's/^model[[:space:]]*=[[:space:]]*"\([^"]*\)".*/\1/p' \
    "${CODEX_HOME:-$HOME/.codex}/config.toml" 2>/dev/null | head -1)"
  [ -n "$model" ] || return 0
  catalog="$(codex debug models 2>/dev/null)" || return 0
  case "$catalog" in *"$model"*) ;; *) return 0;; esac
  printf '%s' "$catalog" | python3 -c '
import json,sys
model=sys.argv[1]
try: data=json.load(sys.stdin)
except Exception: sys.exit(0)
items=data if isinstance(data,list) else data.get("models",data)
if isinstance(items,dict): items=list(items.values())
for m in items:
    if isinstance(m,dict) and (m.get("id") or m.get("slug") or m.get("name"))==model:
        sys.exit(0 if m.get("multi_agent_version") else 3)
sys.exit(0)
' "$model" 2>/dev/null || \
    warn "Codex model \"$model\" has no multi_agent_version; agent roles stay inert until you switch models."
}

install_human_launch_shims() {
  python3 - "$HARNESS_ADAPTERS/harness-runtime-manifest.json" "$HARNESS_EXEC" "$HARNESS_RUNNER" <<'PY'
import json, os, shlex, shutil, stat, sys, tempfile
from pathlib import Path

manifest_path, exec_src, runner_src = map(Path, sys.argv[1:4])
policy = json.loads(manifest_path.read_text()).get("human_launch", {})
if not policy.get("enabled_by_default", False):
    raise SystemExit(0)
home = Path.home()
shim_dir = home / policy["shim_subdir"]
libexec = home / policy["libexec_subdir"]
shim_dir.mkdir(parents=True, exist_ok=True)
libexec.mkdir(parents=True, exist_ok=True)
for source in (exec_src, runner_src, manifest_path.parent / "lib/breathe-port.sh"):
    target = libexec / source.name
    fd, temp_name = tempfile.mkstemp(dir=libexec, prefix=f".{source.name}.")
    os.close(fd)
    temp = Path(temp_name)
    try:
        shutil.copy2(source, temp)
        temp.chmod(temp.stat().st_mode | stat.S_IWUSR | stat.S_IXUSR)
        temp.replace(target)
    finally:
        temp.unlink(missing_ok=True)

runtime_path = home / ".cogito/breathe/harness-runtime.json"
try: previous = json.loads(runtime_path.read_text())
except Exception: previous = {}
if not isinstance(previous, dict): previous = {}
owned = {str(shim_dir.resolve()), str(libexec.resolve())}
path_dirs = [Path(p) for p in os.environ.get("PATH", "").split(os.pathsep) if p]
def valid_real(path):
    if not path: return None
    p = Path(path).expanduser()
    try:
        resolved = p.resolve()
        is_file = resolved.is_file()
    except OSError: return None
    if not p.is_absolute() or not is_file or not os.access(resolved, os.X_OK): return None
    if any(str(resolved).startswith(root + os.sep) for root in owned): return None
    return str(p)
def resolve_real(command):
    for directory in path_dirs:
        candidate = valid_real(directory / command)
        if candidate: return candidate
    return valid_real(previous.get("harnesses", {}).get(command, {}).get("real"))
def shell_case(values, mode):
    if not values: return ""
    cases = "|".join(shlex.quote(v) for v in values)
    if mode == "first": return f'case "${{1:-}}" in {cases}) export COGITOD_LAUNCH_MODE=direct;; esac\n'
    return f'for _arg in "$@"; do case "$_arg" in {cases}) export COGITOD_LAUNCH_MODE=direct;; esac; done\n'

runtime = {"version": 1, "harnesses": {}}
activation_safe = True
for harness, item in policy.get("harnesses", {}).items():
    command = item.get("command", harness)
    real = resolve_real(command)
    if not real: continue
    runtime["harnesses"][command] = {"real": real}
    target = shim_dir / command
    if target.exists():
        try: managed = "cogitod-managed-human-launch" in target.read_text(errors="ignore")
        except OSError: managed = False
        if not managed:
            print(f"warning: preserving unowned launch shim {target}", file=sys.stderr)
            activation_safe = False
            continue
    body = "#!/usr/bin/env bash\n# cogitod-managed-human-launch\nset -u\n"
    body += shell_case(item.get("noninteractive_subcommands", []), "first")
    body += shell_case(item.get("noninteractive_flags", []), "all")
    body += f'exec {shlex.quote(str(libexec / exec_src.name))} {shlex.quote(harness)} {shlex.quote(real)} "$@"\n'
    temp = target.with_suffix(".tmp")
    temp.write_text(body); temp.chmod(0o755); temp.replace(target)
runtime_path.write_text(json.dumps(runtime, indent=2) + "\n")

marker = policy.get("profile_marker", "cogitod-human-launch")
block = (f"# >>> {marker} >>>\n"
         f'case ":$PATH:" in *":$HOME/{policy["shim_subdir"]}:"*) ;; '
         f'*) export PATH="$HOME/{policy["shim_subdir"]}:$PATH";; esac\n'
         f"# <<< {marker} <<<")
for relative in policy.get("profiles", []):
    profile = home / relative
    text = profile.read_text() if profile.exists() else ""
    start, end = f"# >>> {marker} >>>", f"# <<< {marker} <<<"
    if not activation_safe:
        if start in text and end in text:
            before, rest = text.split(start, 1); _, after = rest.split(end, 1)
            profile.write_text((before.rstrip() + "\n" + after.lstrip()).lstrip("\n"))
        continue
    if start in text and end in text:
        before, rest = text.split(start, 1); _, after = rest.split(end, 1)
        before, after = before.rstrip(), after.lstrip("\n")
        text = (before + "\n\n" if before else "") + block
        text += "\n\n" + after if after else "\n"
    else:
        text = text.rstrip() + ("\n\n" if text.strip() else "") + block + "\n"
    profile.write_text(text)
PY
}

step "Installing cogitod agent context"
need_file "$HOOK_MANIFEST" "hook manifest"
need_file "$CODEX_HOOK_PROJECTOR" "Codex hook projector"
need_file "$CODEX_HOOK_SHIM" "Codex hook shim"
need_file "$BOUNDARY_GATE" "fail-closed Breathe boundary"
need_file "$WORKER_HEARTBEAT" "worker heartbeat sidecar"
need_file "$OPENCODE_PLUGIN" "opencode plugin"
need_file "$SOURCE_CONTEXT_EXPORTER" "source-context exporter"
need_file "$HARNESS_EXEC" "human-launch wrapper"
need_file "$HARNESS_RUNNER" "human-launch runner"
validate_hook_manifest_contract
ok "Hook manifest contract validated"
# $WORKER_HEARTBEAT is deliberately absent: it is tracked 0644 and invoked as
# `bash …/worker-heartbeat.sh`, so it never needs the bit — and chmodding it here mutates a
# TRACKED REPO FILE as a side effect of installing. That dirties every developer checkout the
# installer touches and, once committed, ships the wrong mode downstream (it is 100755 on qa
# today, which is what fails the release contract). The other four are already tracked 0755,
# so this is a no-op for them and only restores the bit after a mode-losing copy.
chmod +x "$CODEX_HOOK_PROJECTOR" "$CODEX_HOOK_SHIM" "$BOUNDARY_GATE" "$SOURCE_CONTEXT_EXPORTER" 2>/dev/null || true

install_manifest_json_hooks "$HOME/.claude/settings.json" claude "$HOOK_MANIFEST" "$WORKER_HEARTBEAT" "$CODEX_HOOK_SHIM"
normalize_breathe_mcp
ok "Claude configured: hooks + breathe MCP"

merge_codex_toml "$HOME/.codex/config.toml"
"$CODEX_HOOK_PROJECTOR" --global --manifest "$HOOK_MANIFEST"
install_codex_agent_roles
ok "Codex configured: hooks + breathe MCP + agent roles"

merge_opencode_config "$HOME/.config/opencode/opencode.jsonc"
ok "opencode configured: plugin + breathe MCP"

install_source_context_exporter
ok "Source-context export command installed: ~/.cogito/breathe/bin/source-context-export"

install_skill_adapters
ok "Context skills installed for Claude, Codex, and opencode"

install_human_launch_shims
ok "Interactive agent launch shims reconciled: ~/.cogito/breathe/shims"

ok "cogitod agent context setup complete"
