#!/usr/bin/env bash
# SessionStart context-token lanes: every hook that can inject additionalContext is capped
# to a few-line verdict + a pointer to a persisted full report, never the whole payload.
# See docs/plans/2026-08-15-sessionstart-context-cap.md.
set -uo pipefail

REPO_ROOT=$(cd "$(dirname "${BASH_SOURCE[0]}")/../../../.." && pwd)
MODULE="$REPO_ROOT/modules/workstation/claude"
PASS=0
FAIL=0
ok() { PASS=$((PASS + 1)); printf 'ok   %s\n' "$1"; }
no() { FAIL=$((FAIL + 1)); printf 'FAIL %s\n     %s\n' "$1" "$2"; }

TESTROOT=$(mktemp -d -t sessionstart-context-cap.XXXXXX)
trap 'rm -rf "$TESTROOT"' EXIT
FAKE_HOME="$TESTROOT/home"
mkdir -p "$FAKE_HOME"

# --- agent-session-ledger: 20 abandoned sessions still yield a few-line body -------------
BODY_OUT=$(HOME="$FAKE_HOME" node --input-type=module -e "
import { renderNotificationBody } from '$MODULE/hooks/agent-session-ledger.mjs';
const fresh = Array.from({ length: 20 }, (_, i) => ({
  ledgerId: 'sess-' + i,
  runtime: 'claude',
  project: 'repo-' + i,
  branch: 'main',
  dirtyCount: 3,
  idleMs: 60000,
  cwd: '/tmp/repo-' + i,
  sessionId: 'sid-' + i,
}));
process.stdout.write(renderNotificationBody(fresh));
")
BODY_LINES=$(printf '%s' "$BODY_OUT" | grep -c '^' || true)
BODY_BYTES=$(printf '%s' "$BODY_OUT" | wc -c)
if [ "$BODY_LINES" -le 15 ]; then ok "agent-session-ledger: 20 dead sessions stay <=15 lines ($BODY_LINES)"
else no "agent-session-ledger: 20 dead sessions stay <=15 lines" "got $BODY_LINES lines"; fi
if [ "$BODY_BYTES" -le 3072 ]; then ok "agent-session-ledger: 20 dead sessions stay <=3072 bytes ($BODY_BYTES)"
else no "agent-session-ledger: 20 dead sessions stay <=3072 bytes" "got $BODY_BYTES bytes"; fi
case "$BODY_OUT" in
  *"20 agent sessions died in this folder with uncommitted work"*) ok "agent-session-ledger: verdict count survives the cap";;
  *) no "agent-session-ledger: verdict count survives the cap" "count line missing/wrong"; ;;
esac
PERSISTED=$(printf '%s' "$BODY_OUT" | grep -o "$FAKE_HOME/.local/state/overdeck/session-context/agent-session-ledger/[^ )]*" | head -1)
if [ -n "$PERSISTED" ] && [ -f "$PERSISTED" ]; then
  LINES_IN_FILE=$(grep -c '^-' "$PERSISTED" || true)
  if [ "$LINES_IN_FILE" -eq 20 ]; then ok "agent-session-ledger: persisted file holds all 20 sessions"
  else no "agent-session-ledger: persisted file holds all 20 sessions" "got $LINES_IN_FILE entries"; fi
else
  no "agent-session-ledger: persisted file holds all 20 sessions" "pointer missing or file absent: $PERSISTED"
fi

# --- dead-advisor-remind: already compliant, guarded against regression ------------------
DA_HOME="$TESTROOT/da-home"
mkdir -p "$DA_HOME/.claude/dead-advisor-state"
printf 'agent-xyz\n' > "$DA_HOME/.claude/dead-advisor-state/sess-da.id"
DA_OUT=$(HOME="$DA_HOME" node "$MODULE/hooks/dead-advisor-remind.mjs" <<<'{"hook_event_name":"SessionStart","source":"compact","session_id":"sess-da"}' \
  | node -e 'let s="";process.stdin.on("data",d=>s+=d).on("end",()=>{try{process.stdout.write(JSON.parse(s).hookSpecificOutput.additionalContext)}catch{}})')
DA_LINES=$(printf '%s' "$DA_OUT" | grep -c '^' || true)
DA_BYTES=$(printf '%s' "$DA_OUT" | wc -c)
if [ "$DA_LINES" -le 10 ]; then ok "dead-advisor-remind: stays <=10 lines ($DA_LINES)"
else no "dead-advisor-remind: stays <=10 lines" "got $DA_LINES lines"; fi
if [ "$DA_BYTES" -le 1024 ]; then ok "dead-advisor-remind: stays <=1024 bytes ($DA_BYTES)"
else no "dead-advisor-remind: stays <=1024 bytes" "got $DA_BYTES bytes"; fi

# --- hooks with no additionalContext at all: SessionStart injects nothing ----------------
LTJ_HOME="$TESTROOT/ltj-home"
mkdir -p "$LTJ_HOME/.claude/projects"
LTJ_TP="$LTJ_HOME/.claude/projects/sess-ltj.jsonl"
: > "$LTJ_TP"
LTJ_OUT=$(HOME="$LTJ_HOME" node "$MODULE/hooks/live-transcript-journal.mjs" \
  <<<"{\"hook_event_name\":\"SessionStart\",\"session_id\":\"sess-ltj\",\"transcript_path\":\"$LTJ_TP\"}")
if [ -z "$LTJ_OUT" ]; then ok "live-transcript-journal: SessionStart emits no additionalContext"
else no "live-transcript-journal: SessionStart emits no additionalContext" "got: $LTJ_OUT"; fi

if [ -f "$MODULE/hooks/context-mode-cache-heal.mjs" ]; then
  CMCH_OUT=$(HOME="$TESTROOT/cmch-home" node "$MODULE/hooks/context-mode-cache-heal.mjs" \
    <<<'{"hook_event_name":"SessionStart","session_id":"sess-cmch"}' 2>/dev/null)
  if [ -z "$CMCH_OUT" ]; then ok "context-mode-cache-heal: SessionStart emits no additionalContext"
  else no "context-mode-cache-heal: SessionStart emits no additionalContext" "got: $CMCH_OUT"; fi
fi

printf '\n%d passed, %d failed\n' "$PASS" "$FAIL"
[ "$FAIL" -eq 0 ]
