#!/usr/bin/env bash
# session-brief.sh  -  opt-in SessionStart hook for the pipeline.
#
# Prints the cached session brief for the repository the session opens in (what
# it holds is described in session-brief.mjs). It only reads a file. Starting
# node on every session start costs more than this hook may take, so a detached
# node process builds the cache whenever HEAD or the repository differs from the
# cache header, or a file the cache was built from is newer than it. The cache
# is printed only when its header names this repository's git common directory
# and this HEAD; otherwise nothing is printed this session and a rebuild starts.
#
# Silent and instant unless prefs.global.sessionBrief.enabled is true. Also
# silent in a pipeline or unattended context (MULTI_AGENT_UNATTENDED,
# MULTI_AGENT_TASK_ID, MULTI_AGENT_PHASE), when the host says the session is not
# attended (CLAUDE_CODE_SESSION_ATTENDED set to anything but 1), for an SDK
# entrypoint (CLAUDE_CODE_ENTRYPOINT starting with sdk), outside a git
# repository, with HOME unset, and with MULTI_AGENT_SESSION_BRIEF=0.
# Exits 0 on every path.

case "${1:-}" in
  --help | -h)
    cat <<'USAGE'
session-brief.sh - SessionStart hook: prints the cached, opt-in session brief.
Turn it on with prefs.global.sessionBrief.enabled true; see
multi-agent-refs/features/session-brief.md. Reads the hook payload on stdin
only to ignore it. Exits 0 on every path.
USAGE
    exit 0
    ;;
esac

[ -n "${HOME:-}" ] || exit 0
[ "${MULTI_AGENT_SESSION_BRIEF:-}" = "0" ] && exit 0
[ -n "${MULTI_AGENT_UNATTENDED:-}" ] && [ "${MULTI_AGENT_UNATTENDED}" != "0" ] && exit 0
[ -n "${MULTI_AGENT_TASK_ID:-}${MULTI_AGENT_PHASE:-}" ] && exit 0
[ -n "${CLAUDE_CODE_SESSION_ATTENDED:-}" ] && [ "${CLAUDE_CODE_SESSION_ATTENDED}" != "1" ] && exit 0
[[ "${CLAUDE_CODE_ENTRYPOINT:-}" == sdk* ]] && exit 0

# Off unless the preferences switch it on. Only builtins read the file, and only
# when it is a regular file under 256 KiB (a FIFO or a huge file reads as off).
PREFS="${MULTI_AGENT_PREFS:-$HOME/.claude/multi-agent-preferences.json}"
[ -f "$PREFS" ] || exit 0
PREFS_TEXT=""
IFS= read -r -d '' -n 262144 PREFS_TEXT <"$PREFS" 2>/dev/null
[ "${#PREFS_TEXT}" -lt 262144 ] || exit 0
[[ "$PREFS_TEXT" == *sessionBrief* ]] || exit 0
ON='"sessionBrief"[[:space:]]*:[[:space:]]*\{[^{}]*"enabled"[[:space:]]*:[[:space:]]*true'
[[ "$PREFS_TEXT" =~ $ON ]] || exit 0

export LC_ALL=C
{
  IFS= read -r COMMON
  IFS= read -r TOP
  IFS= read -r HEAD_SHA
} < <(git rev-parse --path-format=absolute --git-common-dir --show-toplevel HEAD 2>/dev/null)
[ -n "${COMMON:-}" ] && [ -n "${TOP:-}" ] || exit 0

if [ -n "${MULTI_AGENT_REPO_SLUG:-}" ]; then
  SLUG="$MULTI_AGENT_REPO_SLUG"
else
  SLUG="${COMMON%/}"
  if [ "${SLUG##*/}" = ".git" ]; then
    SLUG="${SLUG%/.git}"
    SLUG="${SLUG##*/}"
  else
    SLUG="${SLUG##*/}"
    SLUG="${SLUG%.git}"
  fi
fi
SAFE="${SLUG//[^A-Za-z0-9._-]/_}"
[ -n "$SAFE" ] || exit 0

# 32-bit djb2 over the common dir's bytes: the cache file name, as in
# pathHash() in session-brief.mjs.
h=5381
for ((i = 0; i < ${#COMMON}; i++)); do
  printf -v c '%d' "'${COMMON:i:1}"
  h=$(((h * 33 + c) & 0xffffffff))
done
printf -v HASH '%08x' "$h"

MEM="$HOME/.claude/memory/multi-agent"
DIR="$MEM/_session-brief"
CACHE="$DIR/$SAFE-$HASH.json"
STORE="$MEM/$SLUG"
EXPECT="#sb1|$COMMON|$HEAD_SHA"

CONTENT=""
if [ -f "$CACHE" ] && [ ! -L "$CACHE" ]; then
  IFS= read -r -d '' -n 16000 CONTENT <"$CACHE" 2>/dev/null
  [ "${#CONTENT}" -lt 16000 ] || CONTENT=""
fi
HEADER="${CONTENT%%$'\n'*}"

stale=0
if [ "$HEADER" != "$EXPECT" ]; then
  stale=1
else
  for dep in "$STORE/learnings-ledger.jsonl" "$STORE/learnings-feedback.jsonl" \
    "$MEM/_global/learnings-ledger.jsonl" "$HOME/.claude/knowledge/$SLUG/code-graph.json" \
    "$PREFS" "$HOME/.claude/settings.json" "$HOME/.claude/settings.local.json" \
    "$TOP/.claude/settings.json" "$TOP/.claude/settings.local.json" \
    "$HOME/.claude/plugins/installed_plugins.json"; do
    if [ -f "$dep" ] && [ "$dep" -nt "$CACHE" ]; then stale=1; break; fi
  done
fi

if [ "$stale" = "1" ]; then
  CORE="${BASH_SOURCE[0]%/*}/session-brief.mjs"
  if [ -f "$CORE" ] && command -v node >/dev/null 2>&1; then
    (umask 077; mkdir -p "$DIR" 2>/dev/null)
    LOCK="$DIR/$SAFE-$HASH.lock"
    if [ -d "$LOCK" ] && [ -n "$(find "$LOCK" -maxdepth 0 -mmin +5 2>/dev/null)" ]; then
      rmdir "$LOCK" 2>/dev/null
    fi
    if mkdir "$LOCK" 2>/dev/null; then
      nohup node "$CORE" build --cwd "$PWD" </dev/null >/dev/null 2>&1 &
    fi
  fi
fi

# Print only a cache built for this repository and HEAD whose body is one line
# without control characters.
[ "$HEADER" = "$EXPECT" ] || exit 0
BODY="${CONTENT#*$'\n'}"
BODY="${BODY%$'\n'}"
[ -n "$BODY" ] && [ "$BODY" != "$CONTENT" ] || exit 0
[[ "$BODY" == *[[:cntrl:]]* ]] && exit 0
printf '%s\n' "$BODY"
exit 0
