#!/usr/bin/env bash
# serve_gemma4_opencode.sh — canonical hf2q serve launcher for the
# Gemma 4 Ara 26B APEX GGUF, tuned for opencode agentic coding.
#
# Verified 2026-08-03 on M5 Max (docs/adr/diary/ADR-017-persistent-block-prefix-cache.md
# "gemma-hybrid-lcp" addenda):
#
#   LCP partial-prefill resume
#                           Built-in default-on under the production hybrid
#                           regime post-"gemma-hybrid-lcp" (opt out with
#                           HF2Q_KV_LCP_RESUME=0); the launcher no longer
#                           sets it (ADR-062 D1: launchers need no HF2Q_*
#                           variables for qualified behavior).
#   HF2Q_KV_LCP_LONG_RESUME
#                           Dropped: it only takes effect on fifo-serial
#                           (inert on this launcher's inflight-batched
#                           scheduler; ADR-062 D1).
#   HF2Q_KV_LCP_RESUME_CAPACITY
#                           Removed (#730): the registry budget is the typed
#                           `--lcp-resume-budget` flag, whose built-in
#                           default is a host-independent 8GiB (this
#                           launcher's qualified capacity). The launcher
#                           passes it explicitly when the selected binary
#                           supports it and otherwise preserves that binary's
#                           previous default.
#   Cross-slot admission   Built-in Gemma 4 default: an idle slot group waits
#                           up to 25 ms for peer agent requests so their
#                           appended suffixes share one transformer-body pass
#                           (active decode is never delayed). HF2Q_CROSS_SLOT_ADMIT=0
#                           and HF2Q_ADMIT_COALESCE_US remain explicit engine
#                           overrides; no launcher variable is required.
#   --mmproj                Gemma 4 vision tower (optional; enables image
#                           parts in chat completions). Delete the flag for
#                           a text-only server.
#   --overflow-policy reject
#                           opencode manages its own compaction; the server
#                           must 400 on overflow (OpenAI semantics).
#   --scheduler inflight-batched --max-slots 4
#                           Four independent agent sessions make progress.
#                           Every slot retains Gemma's full model context;
#                           neither context nor KV capacity is divided by N.
#   --kv-cache-budget       Shared physical high-water across full-context
#                           slots. MAX_SLOTS=8 is the np8-like setting.
#   --default-repetition-penalty 1.05
#                           Loop mitigation (2026-08-03), same knob as
#                           serve_qwen36_opencode.sh — opencode cannot send
#                           repetition_penalty, so omission-clients sampled
#                           with 1.0 and long sessions looped (the garbage
#                           then re-primed via compacted history). Applied
#                           only when the client omits the param (explicit
#                           values win), only to generated tokens (never the
#                           prompt), never to the T=0 GPU argmax path.
#
# FAMILY TEMPLATE AND PREFILL ROUTING:
#   The loader uses the GGUF-embedded Gemma APEX template and validates its
#   native turn, tool-call, and tool-response markers before inference.
#
#   Short cold prompts still auto-route through the existing eager batched
#   path when its O(n²) overhead fits a budget fixed once at model load:
#   (total physical RAM − model file bytes) / 6 (#738). Free RAM at request
#   time is not an input, so a prompt always takes the same route. Other
#   models a multi-model pool keeps resident are not reserved; such servers
#   should set HF2Q_SERVE_BATCHED_PREFILL=0. Overhead is config-dependent:
#     default (tensor-mm globals): ~72 B/seq² — masks + pf_kq scratch
#       ⇒ batched envelope ≈ ≤16K tokens on a 128 GB box (16 GB model)
#     HF2Q_GLOBAL_FA=1 (FA globals): ~8 B/seq² — masks only
#       ⇒ batched envelope ≈ ≤50K tokens
#   Long plain-text SlotAware prompts instead install resumable states. Each
#   Metal transaction contains at most 4,096 aggregate rows; each installed
#   lane keeps its own chunk of up to 4,096 rows (as when prefilled alone),
#   and only chunks that fit together share a transaction (#725), so the
#   watchdog boundary is never multiplied by MAX_SLOTS.
#   Long soft-token work remains fail-closed until it has a resumable graph.
#
#   Normal follow-ups use zero-copy live-prefix reuse and process only the
#   uncached suffix: vec-hybrid attention in 256-query chunks, or tiled F16
#   flash attention in bounded 1,024-query sliding / 4,096-query global
#   chunks under WARM_TILED_ATTENTION=1 (ADR-063 Stage 2, opt-in). On the
#   vec-hybrid route a real 6,784-token OpenCode tool turn reused 6,780
#   tokens and completed a 6,042-token tool-result suffix at about 909 tok/s
#   with the exact required answer.
#   Env escapes (neither should be necessary):
#     HF2Q_SERVE_BATCHED_PREFILL=0  force linear route always
#     HF2Q_SERVE_BATCHED_PREFILL=1  force batched route always (can
#         reproduce the 2026-08-03 command-buffer OOM — diagnostic only)
#     BATCHED=0 (this script)        disables both SerialFifo and slot-aware
#                                    batched prefill for parity diagnostics
#     FULL_INPUT_CHECKPOINT=0|1      (this script) forwards
#                                    HF2Q_GEMMA_FULL_INPUT_CHECKPOINT; unset
#                                    keeps the hf2q default (on where
#                                    supported). 0 is the A/B kill switch.
#     JOINT_WARM_PREFILL=0|1         (this script) forwards
#                                    HF2Q_GEMMA_JOINT_WARM_PREFILL; unset
#                                    keeps the hf2q default (on). 0 is the
#                                    A/B kill switch (per-slot warm prefill).
#     JOINT_COLD_PREFILL=0|1         (this script) forwards
#                                    HF2Q_GEMMA_JOINT_COLD_PREFILL; unset
#                                    keeps the hf2q default (on). 0 is the
#                                    A/B kill switch (per-slot cold turn 0).
#     WARM_TILED_ATTENTION=0|1|tensor (this script) forwards
#                                    HF2Q_GEMMA_WARM_TILED_ATTENTION; unset
#                                    keeps the hf2q default (the tensor-API
#                                    route, gap F1). 0 is the kill switch
#                                    (vec-hybrid warm attention); 1 opts in
#                                    to tiled F16.
#     PREFILL_MOE_DOWN=flat|slotted  (this script) forwards
#                                    HF2Q_GEMMA_PREFILL_MOE_DOWN; unset
#                                    keeps the hf2q default (slotted). flat
#                                    is the bitwise A/B arm (ADR-063
#                                    Q4-GEMMA-PREFILL-MOE).
#     MM_ID_SCHEDULE=grid|compact    (this script) forwards
#                                    HF2Q_MM_ID_SCHEDULE; unset keeps the
#                                    mlx-native expert-matmul schedule
#                                    default. grid is the bitwise A/B arm.
#     Q5_0_TENSOR_MM=0|1             (this script) forwards
#                                    HF2Q_Q5_0_TENSOR_MM, the Q5_0 tensor
#                                    matmul route (published as
#                                    active_controls.q5_0_tensor_mm); unset
#                                    keeps the Gemma 4 default (on). 0 is
#                                    the kill switch (simdgroup route).
#     ROUTING_OVERLAP=0|1            (this script) forwards
#                                    HF2Q_GEMMA_ROUTING_OVERLAP; unset keeps
#                                    it off. 1 prints the V2 [ROUTING_OVERLAP]
#                                    decode-workload histograms at worker exit
#                                    (diagnostic, untimed runs only).
#     DECODE_ATTN_NE=0|2|4           (this script) forwards
#                                    HF2Q_GEMMA_DECODE_ATTN_NE; unset keeps
#                                    the hf2q default (4, the gap-program NE
#                                    head split of d256 decode attention).
#                                    0 is the kill switch (stock decode
#                                    attention).
#     DECODE_DENSE=stock|row_exact|mma
#                                    (this script) forwards
#                                    HF2Q_GEMMA_DECODE_DENSE; unset keeps the
#                                    hf2q default (row_exact). stock is the
#                                    kill switch.
#
# NOT enabled (documented follow-ups, do NOT turn on blindly):
#   * Disk persistence of the LCP registry for gemma (ADR-017 spiller
#     family) — the gemma spill codecs were written for the dense/HB
#     regimes; hybrid-regime (F16-K + TQ-HB V) spill needs its own audit
#     + byte-identity gate. In-memory LCP only: server restarts lose the
#     cache (prefill cost only, never a correctness event).
#   * HF2Q_F16_KV=1 — the F16 dense-KV opt-in has a KNOWN regression vs
#     F32 on gemma4 (ADR-009: sourdough 3656→3095). Keep F32 dense.
#
# Prefix-cache stack:
#   1. PromptCache — exact-repeat requests replay instantly (greedy-only).
#   2. Per-slot live-prefix reuse — each agent's next turn appends to its own
#      resident dense+hybrid KV without displacing another agent.
#   3. LCP registry — short or branched prefixes may resume from dual-leg
#      snapshots when they fit the configured byte budget.
#
# Usage:
#   scripts/serve_gemma4_opencode.sh            # foreground (default)
#   PORT=8086 scripts/serve_gemma4_opencode.sh  # override port
set -euo pipefail

SCRIPT_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)
source "$SCRIPT_DIR/hf2q_process_guard.sh"

MODEL="${MODEL:-/opt/hf2q/models/gemma4/gemma4-ara-2pass-APEX-Q5_K_M.gguf}"
MMPROJ="${MMPROJ:-/opt/hf2q/models/gemma4/mmproj-gemma4-f16.gguf}"
HOST="${HOST:-127.0.0.1}"
PORT="${PORT:-8081}"
if [[ -n "${LCP_CAPACITY+set}" ]]; then
    echo "LCP_CAPACITY is retired (#730); set LCP_RESUME_BUDGET (e.g. 8GiB) instead" >&2
    exit 2
fi
LCP_RESUME_BUDGET="${LCP_RESUME_BUDGET:-8GiB}"
HF2Q_BIN="${HF2Q_BIN:-/opt/hf2q/target/release/hf2q}"
MAX_SLOTS="${MAX_SLOTS:-4}"
KV_CACHE_BUDGET_BYTES="${KV_CACHE_BUDGET_BYTES:-51539607552}" # 48 GiB shared

[[ -f "$MODEL" ]] || { echo "model not found: $MODEL" >&2; exit 3; }
[[ -x "$HF2Q_BIN" ]] || { echo "hf2q binary not found: $HF2Q_BIN (cargo build --release)" >&2; exit 3; }
SERVE_HELP=$("$HF2Q_BIN" serve --help 2>&1) || {
    echo "failed to inspect serve options from: $HF2Q_BIN" >&2
    exit 3
}
if [[ "$SERVE_HELP" == *"--lcp-resume-budget"* ]]; then
    LCP_RESUME_BUDGET_SUPPORTED=1
else
    LCP_RESUME_BUDGET_SUPPORTED=0
fi
if ! [[ "$PORT" =~ ^[0-9]+$ ]] || (( PORT < 1 || PORT > 65535 )); then
    echo "PORT must be an integer from 1 through 65535 (got: $PORT)" >&2
    exit 3
fi
if ! [[ "$MAX_SLOTS" =~ ^[0-9]+$ ]] || (( MAX_SLOTS < 1 || MAX_SLOTS > 8 )); then
    echo "MAX_SLOTS must be from 1 through 8 (got: $MAX_SLOTS)" >&2
    exit 3
fi
if ! [[ "$KV_CACHE_BUDGET_BYTES" =~ ^[0-9]+$ ]] || (( KV_CACHE_BUDGET_BYTES < 1 )); then
    echo "KV_CACHE_BUDGET_BYTES must be a positive integer (got: $KV_CACHE_BUDGET_BYTES)" >&2
    exit 3
fi

# Refuse before loading the model when another service already owns the port.
if command -v lsof >/dev/null 2>&1; then
    PORT_LISTENER="$(lsof -nP -iTCP:"$PORT" -sTCP:LISTEN 2>/dev/null || true)"
    if [[ -n "$PORT_LISTENER" ]]; then
        echo "$HOST:$PORT is already in use — refusing before model load" >&2
        printf '%s\n' "$PORT_LISTENER" >&2
        echo "choose a free port, for example: PORT=8090 $0" >&2
        exit 2
    fi
elif command -v nc >/dev/null 2>&1 && nc -z "$HOST" "$PORT" >/dev/null 2>&1; then
    echo "$HOST:$PORT is already in use — refusing before model load" >&2
    echo "choose a free port, for example: PORT=8090 $0" >&2
    exit 2
fi

# One-model-at-a-time guard (feedback_oom_prevention): a 26B-class model
# holds ~25-35 GB of unified memory; concurrent inference processes on
# one box OOM it (measured 2026-08-03).
RUNTIME_PIDS="$(hf2q_active_serve_pids)"
if [[ -n "$RUNTIME_PIDS" ]]; then
    echo "another hf2q server is already running — refusing before model load" >&2
    echo "pid(s): ${RUNTIME_PIDS//$'\n'/, }" >&2
    echo "stop that server before starting Gemma" >&2
    exit 1
fi

# BATCHED unset = engine auto-routes per request (recommended; see
# header). BATCHED=0 forces the linear route; BATCHED=1 forces batched
# (diagnostic only — can reproduce the 92K command-buffer OOM).
# ${BATCHED_ENV:+...} expands to NOTHING when unset/empty, so the env
# var reaches the server only on explicit operator request (macOS bash
# 3.2 + set -u safe: the :+ form never trips unbound-variable).
BATCHED_ENV=""
if [[ "${BATCHED:-}" == "0" ]]; then
    BATCHED_ENV=0
elif [[ "${BATCHED:-}" == "1" ]]; then
    BATCHED_ENV=1
fi
FULL_INPUT_ENV=""
case "${FULL_INPUT_CHECKPOINT:-}" in
    "") ;;
    0|1) FULL_INPUT_ENV="$FULL_INPUT_CHECKPOINT" ;;
    *)
        echo "FULL_INPUT_CHECKPOINT must be 0, 1 or unset" >&2
        exit 2
        ;;
esac
JOINT_WARM_ENV=""
case "${JOINT_WARM_PREFILL:-}" in
    "") ;;
    0|1) JOINT_WARM_ENV="$JOINT_WARM_PREFILL" ;;
    *)
        echo "JOINT_WARM_PREFILL must be 0, 1 or unset" >&2
        exit 2
        ;;
esac
JOINT_COLD_ENV=""
case "${JOINT_COLD_PREFILL:-}" in
    "") ;;
    0|1) JOINT_COLD_ENV="$JOINT_COLD_PREFILL" ;;
    *)
        echo "JOINT_COLD_PREFILL must be 0, 1 or unset" >&2
        exit 2
        ;;
esac
WARM_TILED_ENV=""
case "${WARM_TILED_ATTENTION:-}" in
    "") ;;
    0|1|tensor) WARM_TILED_ENV="$WARM_TILED_ATTENTION" ;;
    *)
        echo "WARM_TILED_ATTENTION must be 0, 1, tensor or unset" >&2
        exit 2
        ;;
esac
PREFILL_MOE_DOWN_ENV=""
case "${PREFILL_MOE_DOWN:-}" in
    "") ;;
    flat|slotted) PREFILL_MOE_DOWN_ENV="$PREFILL_MOE_DOWN" ;;
    *)
        echo "PREFILL_MOE_DOWN must be flat, slotted or unset" >&2
        exit 2
        ;;
esac
MM_ID_SCHEDULE_ENV=""
case "${MM_ID_SCHEDULE:-}" in
    "") ;;
    grid|compact) MM_ID_SCHEDULE_ENV="$MM_ID_SCHEDULE" ;;
    *)
        echo "MM_ID_SCHEDULE must be grid, compact or unset" >&2
        exit 2
        ;;
esac
Q5_0_TENSOR_MM_ENV=""
case "${Q5_0_TENSOR_MM:-}" in
    "") ;;
    0|1) Q5_0_TENSOR_MM_ENV="$Q5_0_TENSOR_MM" ;;
    *)
        echo "Q5_0_TENSOR_MM must be 0, 1 or unset" >&2
        exit 2
        ;;
esac
ROUTING_OVERLAP_ENV=""
case "${ROUTING_OVERLAP:-}" in
    "") ;;
    0|1) ROUTING_OVERLAP_ENV="$ROUTING_OVERLAP" ;;
    *)
        echo "ROUTING_OVERLAP must be 0, 1 or unset" >&2
        exit 2
        ;;
esac
DECODE_ATTN_NE_ENV=""
case "${DECODE_ATTN_NE:-}" in
    "") ;;
    0|2|4) DECODE_ATTN_NE_ENV="$DECODE_ATTN_NE" ;;
    *)
        echo "DECODE_ATTN_NE must be 0, 2, 4 or unset" >&2
        exit 2
        ;;
esac
DECODE_DENSE_ENV=""
case "${DECODE_DENSE:-}" in
    "") ;;
    stock|row_exact|mma) DECODE_DENSE_ENV="$DECODE_DENSE" ;;
    *)
        echo "DECODE_DENSE must be stock, row_exact, mma or unset" >&2
        exit 2
        ;;
esac

# Build argv through positional parameters. This is safe on macOS bash 3.2
# when the optional projector or versioned LCP budget flag is absent.
set -- \
    --model "$MODEL" \
    --host "$HOST" \
    --port "$PORT" \
    --overflow-policy reject \
    --scheduler inflight-batched \
    --max-slots "$MAX_SLOTS" \
    --kv-cache-budget "$KV_CACHE_BUDGET_BYTES"
if [[ -f "$MMPROJ" ]]; then
    set -- "$@" --mmproj "$MMPROJ"
fi
if [[ "$LCP_RESUME_BUDGET_SUPPORTED" == 1 ]]; then
    set -- "$@" --lcp-resume-budget "$LCP_RESUME_BUDGET"
else
    echo "selected hf2q binary predates --lcp-resume-budget; preserving its built-in LCP behavior" >&2
fi
set -- "$@" --default-repetition-penalty "${REP_PENALTY:-1.05}"

exec env \
    ${BATCHED_ENV:+HF2Q_SERVE_BATCHED_PREFILL="$BATCHED_ENV"} \
    ${FULL_INPUT_ENV:+HF2Q_GEMMA_FULL_INPUT_CHECKPOINT="$FULL_INPUT_ENV"} \
    ${JOINT_WARM_ENV:+HF2Q_GEMMA_JOINT_WARM_PREFILL="$JOINT_WARM_ENV"} \
    ${JOINT_COLD_ENV:+HF2Q_GEMMA_JOINT_COLD_PREFILL="$JOINT_COLD_ENV"} \
    ${WARM_TILED_ENV:+HF2Q_GEMMA_WARM_TILED_ATTENTION="$WARM_TILED_ENV"} \
    ${PREFILL_MOE_DOWN_ENV:+HF2Q_GEMMA_PREFILL_MOE_DOWN="$PREFILL_MOE_DOWN_ENV"} \
    ${MM_ID_SCHEDULE_ENV:+HF2Q_MM_ID_SCHEDULE="$MM_ID_SCHEDULE_ENV"} \
    ${Q5_0_TENSOR_MM_ENV:+HF2Q_Q5_0_TENSOR_MM="$Q5_0_TENSOR_MM_ENV"} \
    ${ROUTING_OVERLAP_ENV:+HF2Q_GEMMA_ROUTING_OVERLAP="$ROUTING_OVERLAP_ENV"} \
    ${DECODE_ATTN_NE_ENV:+HF2Q_GEMMA_DECODE_ATTN_NE="$DECODE_ATTN_NE_ENV"} \
    ${DECODE_DENSE_ENV:+HF2Q_GEMMA_DECODE_DENSE="$DECODE_DENSE_ENV"} \
    ${BATCHED_ENV:+HF2Q_PREFILL_SLOT_BATCHED="$BATCHED_ENV"} \
    "$HF2Q_BIN" -v serve "$@"
