#!/bin/bash
# PostCompact hook: re-inject optimization state summary into Claude's context.
# Reads .codeflash/.compact-state.json and echoes a concise summary to stdout.
# Output goes directly into Claude's context as a system reminder.

set -euo pipefail

INPUT=$(cat)
CWD=$(echo "$INPUT" | jq -r '.cwd // empty' 2>/dev/null)
CWD="${CWD:-${CLAUDE_PROJECT_DIR:-$(pwd)}}"

STATE_FILE="$CWD/.codeflash/.compact-state.json"

# Nothing to inject if no saved state
if [ ! -f "$STATE_FILE" ]; then
  exit 0
fi

# Build and emit summary in a single jq call
jq -r '
  "[codeflash state] Phase: \(.phase // "unknown")"
  + " | Experiments: \(.experiments.total // 0) (\(.experiments.keeps // 0) keeps, \(.experiments.discards // 0) discards)"
  + " | Branch: \(.branch // "unknown")"
  + (if (.next_target // "") != "" then " | Next target: \(.next_target)" else "" end)
  + (if (.guard // "") != "" then " | Guard: \(.guard)" else "" end)
' "$STATE_FILE"
echo "Read .codeflash/HANDOFF.md and .codeflash/results.tsv for full session state."

exit 0
