#!/usr/bin/env bash
# Codex wire canary launcher (spec/codex-wire-capture-replay.spec.md, "Live
# canary lane"): resolves the wire corpus + the pinned @openai/codex version
# and runs the ReScript canary bin (HarnessCodexWireCanaryMain.res).
#
#   codex-wire-canary.sh corpus            the scheduled corpus check
#                                          (fidelity + shape baseline +
#                                          freshness vs the pinned codex)
#   codex-wire-canary.sh fresh <capture>   drift-diff a freshly recorded
#                                          canary capture BEFORE promotion
#
# The canary corpus is every wire capture the replay lane treats as real
# wire truth: test/fixtures/agent-raw-replay/wire-corpus/*.ndjson plus the
# real-probe session (test/fixtures/agent-raw-replay/real-probe/codex.ndjson).
# The committed shape baseline lives beside the corpus
# (wire-corpus/shape-baseline.json); the vitest corpus gate pins the same
# set, so this script and the test cannot disagree silently.
#
# Build the ReScript package first (`npx rescript build
# packages/linzumi-cli-rescript`); the CLI test pipeline already does.
set -euo pipefail

here="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
cli_root="$(cd "$here/.." && pwd)"
bin_module="$cli_root/../linzumi-cli-rescript/src/harness/HarnessCodexWireCanaryMain.res.mjs"
baseline="$cli_root/test/fixtures/agent-raw-replay/wire-corpus/shape-baseline.json"

if [[ ! -f "$bin_module" ]]; then
  echo "codex-wire-canary: compiled module missing at $bin_module - run: npx rescript build <repo>/packages/linzumi-cli-rescript" >&2
  exit 66
fi

mode="${1:-}"
case "$mode" in
  corpus)
    pinned_version="$(node -p "require('$cli_root/package.json').dependencies['@openai/codex'].replace(/^[^0-9]*/, '')")"
    captures=("$cli_root"/test/fixtures/agent-raw-replay/wire-corpus/*.ndjson)
    captures+=("$cli_root/test/fixtures/agent-raw-replay/real-probe/codex.ndjson")
    exec node "$bin_module" corpus \
      --baseline "$baseline" \
      --pinned-codex-version "$pinned_version" \
      "${captures[@]}"
    ;;
  fresh)
    shift
    if [[ $# -lt 1 ]]; then
      echo "codex-wire-canary: fresh mode needs the freshly recorded capture path" >&2
      exit 64
    fi
    exec node "$bin_module" fresh --baseline "$baseline" "$@"
    ;;
  *)
    echo "codex-wire-canary: unknown mode '${mode}' (use corpus or fresh)" >&2
    exit 64
    ;;
esac
