#!/bin/sh
# launch-breathe-engine.sh — launch cogitod as a process named "Breathe Engine".
#
# WHY: macOS Activity Monitor shows the kernel process name (comm = the launched
# executable's filename), and Node's process.title is unreliable on macOS 14+
# (it cannot override comm). So instead of `node dist/core/app/index.js` (comm = "node",
# ungroupable), we exec a renamed hardlink of the real node binary. comm then
# reads "Breathe Engine", grouping the daemon under the Breathe brand next to
# BreathFlow — a user can filter Activity Monitor by "Breath" and see them all.
#
# Homebrew's node loads libnode via @loader_path/../lib, so a relocated launcher
# must point DYLD_FALLBACK_LIBRARY_PATH at the real node's lib dir or dyld fails.
set -eu

DIR="${COGITOD_DIR:-$(cd "$(dirname "$0")/.." && pwd)}"
# Which built entry to run. Shipping manifests set COGITOD_ENTRY for each artifact profile;
# the context profile selects dist/monetized/context/runtime/cli-main.js, while full profiles
# select their product-specific entry.
# Fall back to the full bin if a stale bundle lacks the configured entry (pre-split core).
ENTRY="$DIR/${COGITOD_ENTRY:-dist/core/app/index.js}"
[ -f "$ENTRY" ] || ENTRY="$DIR/dist/core/app/index.js"

# Resolve a node binary whose native ABI matches the prebuilt better-sqlite3.
# AUTOMATED version match: we do NOT hardcode "node 22". better-sqlite3 ships a
# prebuilt .node for one NODE_MODULE_VERSION; a mismatched node (e.g. Homebrew
# bumped to 26 / ABI 147) boots far enough to crash on the native module load.
# So we probe candidate node binaries and pick the FIRST that can actually
# construct a Database (v12 loads the binding lazily — a bare require() passes
# even with no .node present). This survives any future pin bump (22 -> 24 -> …)
# as long as deps are installed for that node. The workspace-pinned major (from
# .node-version) is tried first so the common case is a single probe.
# (See memory feedback_launchd_node_abi: fix node resolution, not pnpm.)
REPO_ROOT="${COGITO_REPO_ROOT:-$(cd "$DIR/../.." && pwd)}"

# Config-driven process name. The daemon reads cogitod.name from COGITO_CONFIG
# (applyUserConfig) for its state dir / port, but the branded launcher below and
# node's process.title are chosen BEFORE node parses that file — so a config-only
# run (COGITO_CONFIG set, COGITOD_PROC_NAME unset) would fall back to the default
# name and two instances become indistinguishable in Activity Monitor. Backfill the
# env from the yaml so `name:` alone is authoritative; a real env var still wins.
# Exported so the node child picks it up for process.title too.
if [ -z "${COGITOD_PROC_NAME:-}" ] && [ -n "${COGITO_CONFIG:-}" ] && [ -r "${COGITO_CONFIG:-}" ]; then
  _cfg_name=$(sed -n 's/^[[:space:]]*name:[[:space:]]*\([^#]*\).*$/\1/p' "$COGITO_CONFIG" \
    | head -n1 | sed -e 's/^["'\'']//' -e 's/["'\'']*[[:space:]]*$//')
  [ -n "$_cfg_name" ] && export COGITOD_PROC_NAME="$_cfg_name"
  unset _cfg_name
fi

# Workspace-pinned node major — read whichever pin file exists (.nvmrc / .node-version).
WS_MAJOR=""
for vf in "$REPO_ROOT/.nvmrc" "$REPO_ROOT/.node-version"; do
  [ -f "$vf" ] && { WS_MAJOR="$(cut -d. -f1 < "$vf" | tr -dc '0-9')"; [ -n "$WS_MAJOR" ] && break; }
done
WS_MAJOR="${WS_MAJOR:-22}"

# Candidate list, workspace-pinned major FIRST (matches both 22/bin/node and
# 22.22.3/bin/node mise layouts), then nvm, then homebrew/system fallbacks.
BUNDLED_NODE="$DIR/runtime/node"
CANDIDATES=""
# Bundled node ships next to dist/ (runtime/node) — built against our exact addon
# ABI, present on a stranger's machine that has no node at all. Always tried first,
# and EXCLUSIVELY when present — a stray other candidate silently satisfying the
# probe below must never mask a broken bundled binary (see FATAL check below).
[ -x "$BUNDLED_NODE" ] && CANDIDATES="$BUNDLED_NODE"
if [ ! -x "$BUNDLED_NODE" ] && command -v mise >/dev/null 2>&1; then
  CANDIDATES="$CANDIDATES $(mise which node 2>/dev/null || true)"
fi
if [ ! -x "$BUNDLED_NODE" ]; then
  for n in "$HOME/.local/share/mise/installs/node/${WS_MAJOR}"*/bin/node \
           "$HOME/.local/share/mise/installs/node/${WS_MAJOR}"*/*/bin/node \
           "$HOME/.nvm/versions/node/v${WS_MAJOR}"*/bin/node \
           /opt/homebrew/bin/node /usr/local/bin/node \
           "$HOME/.nvm/versions/node"/*/bin/node /usr/bin/node; do
    [ -x "$n" ] && CANDIDATES="$CANDIDATES $n"
  done
fi
[ -n "${CANDIDATES# }" ] || CANDIDATES="$(command -v node 2>/dev/null || true)"

# PostgreSQL-only runtimes contain no SQLite code. Selecting that provider must
# not probe, install, or load better-sqlite3 as a side effect.
NODE=""
# Keep the probe's stderr instead of discarding it. The FATAL branch below used to print only
# "cannot load its native dependencies" while `2>/dev/null` ate the one line that says WHY —
# and the cause is rarely the ABI mismatch the message implies. v0.1.2's npm split stranded
# better-sqlite3 from its own `bindings` dependency, and the daemon reported nothing but the
# symptom on all three platforms; the real error only appeared when someone re-ran the probe by
# hand with stderr attached. Naming the missing module turns that into a one-line diagnosis.
# Prove the file is writable up front and fall back to /dev/null if it is not: the probe redirects
# stderr into it, so an unwritable path would fail the redirect, leave NODE empty, and turn a
# perfectly good install into the very FATAL this is here to explain.
PROBE_ERR="${TMPDIR:-/tmp}/breathe-engine-probe.$$"
# Order matters: the shell applies redirections left to right, so 2>/dev/null must be established
# BEFORE the one that may fail, or its "No such file or directory" reaches the user's terminal.
: 2>/dev/null >"$PROBE_ERR" || PROBE_ERR=/dev/null
probe_err_clean() { [ "$PROBE_ERR" = /dev/null ] || rm -f "$PROBE_ERR"; }
trap probe_err_clean EXIT HUP INT TERM
if [ "${COGITOD_STORAGE_PROVIDER:-sqlite}" = postgres ]; then
  for cand in $CANDIDATES; do [ -x "$cand" ] && { NODE="$cand"; break; }; done
else
  for cand in $CANDIDATES; do
    [ -x "$cand" ] || continue
    if ( cd "$DIR" && "$cand" -e "new (require('better-sqlite3'))(':memory:')" ) >/dev/null 2>"$PROBE_ERR"; then
      NODE="$cand"; break
    fi
  done
fi
# Self-heal: NO candidate could load better-sqlite3 — the binding is likely absent,
# not just ABI-mismatched (pnpm 10 skips postinstall build scripts unless approved,
# so a reinstall can drop the .node entirely; seen 2026-07-02, crash-looped launchd).
# Run the package's own installer (prebuild-install: downloads the prebuilt binary
# matching the running node's ABI, no compiler needed) with each candidate node,
# then re-probe. One attempt per boot; on failure fall through to the loud WARN.
if [ -z "$NODE" ] && [ "${COGITOD_STORAGE_PROVIDER:-sqlite}" != postgres ]; then
  BS_PKG=""
  for cand in $CANDIDATES; do
    [ -x "$cand" ] || continue
    BS_PKG="$(cd "$DIR" && "$cand" -p "require('path').dirname(require.resolve('better-sqlite3/package.json'))" 2>/dev/null)" && break
  done
  if [ -n "$BS_PKG" ] && [ -x "$BS_PKG/node_modules/.bin/prebuild-install" ]; then
    echo "[Breathe Engine] better-sqlite3 binding unusable — self-healing via prebuild-install…" >&2
    for cand in $CANDIDATES; do
      [ -x "$cand" ] || continue
      # .bin/prebuild-install is pnpm's SHELL wrapper, not JS — execute it directly
      # with the candidate node first on PATH so the wrapper picks that node's ABI.
      ( cd "$BS_PKG" && PATH="$(dirname "$cand"):$PATH" node_modules/.bin/prebuild-install ) >&2 2>&1 || continue
      if ( cd "$DIR" && "$cand" -e "new (require('better-sqlite3'))(':memory:')" ) >/dev/null 2>"$PROBE_ERR"; then
        NODE="$cand"; break
      fi
    done
  fi
fi
# If the bundled node was our only candidate and it never passed the probe (even
# after self-heal), refuse to launch rather than silently falling through — a
# stranger's machine has no other candidate to fall back to anyway, and pretending
# otherwise just trades a clean, immediate failure for a confusing later one.
if [ -z "$NODE" ] && [ -x "$BUNDLED_NODE" ]; then
  echo "[Breathe Engine] FATAL: bundled runtime/node cannot load its native dependencies" >&2
  if [ -s "$PROBE_ERR" ]; then sed 's/^/[Breathe Engine]   /' "$PROBE_ERR" >&2; fi
  exit 1
fi
# Fallback: first runnable candidate (let it fail loudly with the ABI hint).
if [ -z "$NODE" ]; then
  for cand in $CANDIDATES; do [ -x "$cand" ] && { NODE="$cand"; break; }; done
  [ -n "$NODE" ] && echo "[Breathe Engine] WARN: no node could require better-sqlite3; using $NODE — ABI mismatch likely" >&2
fi
[ -n "$NODE" ] && [ -x "$NODE" ] || { echo "[Breathe Engine] node not found — install Node.js" >&2; exit 1; }

# Follow symlinks to the real Mach-O so @loader_path/../lib resolves to libnode.
REAL="$NODE"
while [ -L "$REAL" ]; do
  link="$(readlink "$REAL")"
  case "$link" in /*) REAL="$link" ;; *) REAL="$(dirname "$REAL")/$link" ;; esac
done
LIBDIR="$(cd "$(dirname "$REAL")/../lib" 2>/dev/null && pwd || true)"

# Branded launcher in a writable support dir, NOT the (future signed, read-only)
# app bundle. Hardlink → same inode + code signature; fall back to copy across
# volumes, then to the node path itself if both fail.
# Per-instance so two daemons (e.g. cogitod + cogitod-dev) get their own branded binary
# instead of sharing one hardlink. BINDIR follows the instance's state dir; the process
# name comes from COGITOD_PROC_NAME (config: cogitod.name) so instances are tellable apart.
BINDIR="${BREATHE_STATE_DIR:-$HOME/.cogito/breathe}/libexec/processes"
mkdir -p "$BINDIR"
LAUNCHER="$BINDIR/${COGITOD_PROC_NAME:-Breathe Engine}"
ln -f "$REAL" "$LAUNCHER" 2>/dev/null || cp -f "$REAL" "$LAUNCHER" 2>/dev/null || LAUNCHER="$REAL"

# Build-guard only the runtime workspace packages declared by cogitod's package
# contract. Daemon-owned migrations can remove a workspace dependency; a stale
# hardcoded list would then make the healthy standalone daemon impossible to boot.
TSC="$REPO_ROOT/node_modules/typescript/bin/tsc"
RUNTIME_WORKSPACE_PACKAGES="$("$NODE" - "$DIR/package.json" <<'NODE'
const fs = require('node:fs');
const file = process.argv[2];
try {
  const pkg = JSON.parse(fs.readFileSync(file, 'utf8'));
  for (const name of Object.keys(pkg.dependencies || {})) {
    if (name.startsWith('@evolve/')) console.log(name.slice('@evolve/'.length));
  }
} catch {}
NODE
)"
for pkg in $RUNTIME_WORKSPACE_PACKAGES; do
  # Test RESOLVABILITY, not dist-file existence. Two failure modes both surface as a
  # MODULE_NOT_FOUND crash-loop, and a dist-exists check only catches the first:
  #   1. dist vanished (pnpm install / prune / clean) — the original guarded case.
  #   2. the $DIR/node_modules/@evolve/$pkg SYMLINK got vandalized by an in-lane pnpm
  #      run (coord-lane gives lanes absolute symlinks into main's node_modules) while
  #      the source dist survived — dist-exists then PASSES but require() still throws
  #      (seen 2026-07-03, @evolve/p-db). See memory 66CF512A / 56107744.
  # require.resolve from $DIR covers both. Bundled layout (BreathFlow.app: vendored
  # package, no repo/pnpm) resolves fine, so it continues here before any heal runs.
  ( cd "$DIR" && "$NODE" -e "require.resolve('@evolve/$pkg')" ) >/dev/null 2>&1 && continue
  PKG_DIR="$REPO_ROOT/platform/packages/$pkg"
  echo "[Breathe Engine] @evolve/$pkg unresolvable — restoring links + dist once before boot…" >&2
  if command -v pnpm >/dev/null 2>&1; then
    # pnpm install restores the vandalized node_modules symlink AND runs the package's
    # prepare/build. A --filter build alone would rebuild dist but not the missing link,
    # so it must come first; fall back to it only if dist is still absent afterward.
    ( cd "$REPO_ROOT" && pnpm install ) >&2 || true
    [ -f "$PKG_DIR/dist/core/app/index.js" ] || ( cd "$REPO_ROOT" && pnpm --filter "@evolve/$pkg" build ) >&2 || true
  elif [ -f "$TSC" ]; then
    # No pnpm: tsc directly, then mirror any package-local runtime assets (db ships migrations).
    ( cd "$PKG_DIR" && rm -rf dist && "$NODE" "$TSC" && { [ -d migrations ] && cp -r migrations dist/ || true; } ) >&2 || true
  fi
  if ! ( cd "$DIR" && "$NODE" -e "require.resolve('@evolve/$pkg')" ) >/dev/null 2>&1; then
    echo "[Breathe Engine] FATAL: @evolve/$pkg unresolvable and auto-heal failed." >&2
    echo "[Breathe Engine]   fix: (cd $REPO_ROOT && pnpm install)" >&2
    exit 1
  fi
done

# Daemon children must find the same node this daemon runs on: launchd hands us a
# bare /usr/bin:/bin PATH, so git pre-push hooks (the lefthook stub is #!/usr/bin/env
# node) died with "env: node: No such file or directory" — which silently failed every
# landing-queue push (seen 2026-07-03). Export the resolved node's dir for all children.
export PATH="$(dirname "$NODE"):$PATH"

[ -n "$LIBDIR" ] && export DYLD_FALLBACK_LIBRARY_PATH="$LIBDIR${DYLD_FALLBACK_LIBRARY_PATH:+:$DYLD_FALLBACK_LIBRARY_PATH}"
# Pin the repo cogitod serves — the code now falls back to process.cwd() (project-agnostic
# for strangers), and launchd's WorkingDirectory is /tmp, so without this our daemon would
# resolve the wrong tree. A stranger runs cogitod from / sets COGITO_REPO_ROOT for their repo.
export COGITO_REPO_ROOT="${COGITO_REPO_ROOT:-$REPO_ROOT}"

# Every boot (bundled layout only): install the agent coordination + capture hooks into
# the user's harness configs. We COPY the shipped tree to ~/.cogito/breathe first so the
# wired hook paths survive an app update / move / delete (the .app bundle is read-only and
# versioned) — then wire from there. The copy is deliberately file-refreshing, not
# guarded by a directory sentinel: partial/stale cache trees are exactly how old
# Codex hook entries survived upgrades and duplicated signal context. The installer
# is idempotent, so re-running is safe and ensures a harness installed AFTER first
# boot (e.g. Codex or opencode added a week later) still gets its hooks. Backgrounded
# and `|| true` throughout so wiring NEVER blocks or crash-loops the daemon.
ADAPTERS="$DIR/harness-adapters"
[ -d "$ADAPTERS" ] || ADAPTERS="$DIR/agent-context"
INSTALL_MARKER="${BREATHE_STATE_DIR:-$HOME/.cogito/breathe}/.cogitod-install-in-progress"
# Port preflight. The engine binds without handling EADDRINUSE, so a taken port kills it with an
# unhandled 'error' event — and launchd runs us under KeepAlive{SuccessfulExit:false} with
# ThrottleInterval 10, which makes that death a LOOP: die, respawn ten seconds later, die again,
# appending a full stack trace to cogitod.error.log every cycle. The machine that prompted this had
# 9MB of identical EADDRINUSE traces. Exiting 0 is what breaks the cycle: SuccessfulExit:false means
# launchd does not respawn a clean exit. Staying down with one honest line beats a crash loop, and if
# the holder is another cogitod there is nothing to do anyway — the daemon the user wanted is up.
#
# Probe with $NODE rather than lsof/ss so the check is exactly the bind the engine is about to make,
# on every platform we ship. Only EADDRINUSE (3) stops us; any other probe outcome falls through and
# lets the engine fail loudly on its own terms. A bind between probe and exec is still possible, and
# lands back on the old behaviour for that one cycle.
PORT="${BREATHE_PORT:-24567}"
BIND_HOST="${BREATHE_BIND_HOST:-127.0.0.1}"
set +e
"$NODE" -e '
  const net = require("net");
  const server = net.createServer();
  server.once("error", err => process.exit(err.code === "EADDRINUSE" ? 3 : 0));
  server.once("listening", () => server.close(() => process.exit(0)));
  server.listen(Number(process.argv[1]), process.argv[2]);
' "$PORT" "$BIND_HOST" 2>/dev/null
PORT_PROBE=$?
set -e
if [ "$PORT_PROBE" -eq 3 ]; then
  HOLDER="$(lsof -nP -iTCP:"$PORT" -sTCP:LISTEN -Fc 2>/dev/null | sed -n 's/^c//p' | head -1)"
  case "$HOLDER" in
    *cogitod*|*ogito*|*reathe*)
      echo "[Breathe Engine] $BIND_HOST:$PORT already served by '$HOLDER' — nothing to start." >&2 ;;
    '')
      echo "[Breathe Engine] $BIND_HOST:$PORT is already in use — not starting a second engine." >&2 ;;
    *)
      echo "[Breathe Engine] $BIND_HOST:$PORT is held by '$HOLDER' — not starting." >&2
      echo "[Breathe Engine]   free that port, or set BREATHE_PORT and reload the service." >&2 ;;
  esac
  exit 0
fi

BOOT_WIRING=true
if [ -f "$INSTALL_MARKER" ]; then
  INSTALLER_PID="$(cat "$INSTALL_MARKER" 2>/dev/null || true)"
  if [[ "$INSTALLER_PID" =~ ^[0-9]+$ ]] && kill -0 "$INSTALLER_PID" 2>/dev/null; then
    BOOT_WIRING=false
  else
    rm -f "$INSTALL_MARKER"
  fi
fi
if [ -d "$ADAPTERS" ] && [ "$BOOT_WIRING" = true ]; then
  (
    DEST="$HOME/.cogito/breathe/harness-adapters"
    REFRESH="$ADAPTERS/bin/refresh-harness-adapters.sh"
    if [ ! -x "$REFRESH" ] || ! "$REFRESH" "$ADAPTERS" "$DEST"; then
      echo "warning: failed to stage harness adapters" >&2
    fi
    WIRE="$DEST/bin/install-harness-adapters.sh"
    [ -f "$WIRE" ] || WIRE="$DEST/bin/install-harness-adapters.sh"
    [ -f "$WIRE" ] || WIRE="$DEST/platform/infra/scripts/install/install-agent-context.sh"
    [ -f "$WIRE" ] && AGENT_CONTEXT_HOOKS_ONLY=1 bash "$WIRE" --bundle >/dev/null 2>&1
  ) &
fi

exec "$LAUNCHER" "$ENTRY" --http
