#!/usr/bin/env bash
# VERSION: 3
#
# Stop hook — did this session record what it did, and did it record too much?
#
# WHY THIS REPLACED A FIXED STRING. The old global Stop hook echoed the same sentence
# every time: "update context-log.md, 5-8 bullets". It could not tell whether anything
# had been written, so it nagged after sessions that had already logged and stayed
# silent about sessions that wrote 72 KB. One of my logs has a single entry of 72,682
# bytes — 15% of the whole file — under a rule that says 5-8 bullets. A rule nothing
# measures is a rule that gets ignored.
#
# Three things it can actually check:
#   1. Was anything appended?           (delta against the SessionStart marker)
#   2. Was too much appended?           (soft budget, ~2x the stated bullet rule)
#   3. Is the live file due to rotate?  (size ceiling, names the archive to create)
#
# WARN ONLY — never `exit 2`. A blocking Stop hook can trap the agent in a loop, and
# the diagnostic is the point. Everything here exits 0.
#
# INSTALL: save to ~/.claude/hooks/session-log-check.sh (and/or <project>/.claude/hooks/),
# chmod +x, then register it as a Stop hook in the matching settings.json. Pairs with
# session-snapshot.sh, which writes the marker this reads.

set -uo pipefail

ROOT="${CLAUDE_PROJECT_DIR:-$(git rev-parse --show-toplevel 2>/dev/null || pwd)}"
cd "$ROOT" 2>/dev/null || exit 0

# See session-snapshot.sh for the reasoning: one identical file serves as both the
# global and the per-repo copy, and defers to the repo's own when there is one.
_SELF_NAME="$(basename "${BASH_SOURCE[0]}")"
_SELF_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" 2>/dev/null && pwd)"
if [ -f "$ROOT/.claude/hooks/$_SELF_NAME" ] && [ "$_SELF_DIR/$_SELF_NAME" != "$ROOT/.claude/hooks/$_SELF_NAME" ]; then
  exit 0
fi

# A scratch repo has neither a log nor project instructions. Say nothing there —
# an unwanted reminder on every stop is how a hook earns itself a deletion.
[ -f context-log.md ] || [ -f CLAUDE.md ] || exit 0

ENTRY_BUDGET=4096      # ~2x the "5-8 bullets" rule; catches transcripts, not prose
ROTATE_AT=153600       # 150 KB — the live-file ceiling from CLAUDE.md

NOW_BYTES=$(cat context-log*.md 2>/dev/null | wc -c | tr -d ' ')
NOW_BYTES=${NOW_BYTES:-0}

START_BYTES=""
GITDIR="$(git rev-parse --git-dir 2>/dev/null)"
if [ -n "$GITDIR" ] && [ -f "$GITDIR/claude-session-start" ]; then
  START_BYTES="$(cat "$GITDIR/claude-session-start" 2>/dev/null | tr -dc '0-9')"
fi

if [ -n "$START_BYTES" ]; then
  DELTA=$(( NOW_BYTES - START_BYTES ))
  if [ "$DELTA" -le 0 ]; then
    echo "SESSION LOG: nothing was added to context-log.md this session."
    echo "  If real work landed, append one '## YYYY-MM-DD — <what changed>' heading"
    echo "  and 5-8 bullets. If this session was only reading, ignore this."
  elif [ "$DELTA" -gt "$ENTRY_BUDGET" ]; then
    echo "SESSION LOG: this session added $DELTA bytes to the context log (budget ${ENTRY_BUDGET})."
    echo "  The entry is meant to be 5-8 bullets — what changed and what is still open,"
    echo "  not a transcript. Detail belongs in the PR body, build-history.md or"
    echo "  deploy-log.md. Consider trimming before this is committed."
  fi
else
  # No marker: the session predates the hook, or this is not a git repo.
  echo "SESSION LOG: remember to append this session's 5-8 bullet entry to context-log.md."
fi

# Rotation is checked independently of what this session wrote — the file can cross
# the ceiling on someone else's commit, and the point is that it never quietly grows
# past the point where one accidental whole-file read costs half a context window.
LIVE_BYTES=$(wc -c < context-log.md 2>/dev/null | tr -d ' ')
LIVE_BYTES=${LIVE_BYTES:-0}
if [ "$LIVE_BYTES" -gt "$ROTATE_AT" ]; then
  OLDEST="$(grep -ho '[0-9]\{4\}-[0-9]\{2\}-[0-9]\{2\}' context-log.md 2>/dev/null | sort | head -1)"
  ARCHIVE="context-log-archive.md"
  if [ -n "$OLDEST" ]; then
    Y="${OLDEST:0:4}"
    M="${OLDEST:5:2}"
    Q=$(( (10#$M - 1) / 3 + 1 ))
    ARCHIVE="context-log-${Y}-Q${Q}.md"
  fi
  echo "SESSION LOG: context-log.md is $(( LIVE_BYTES / 1024 )) KB — past the 150 KB ceiling, rotation is due."
  echo "  Move the oldest complete quarter into ./${ARCHIVE} (flat at the repo root, so"
  echo "  relative links inside the entries keep resolving). Leave the newest quarter in"
  echo "  context-log.md, which stays the only file sessions append to."
fi

exit 0
