#!/bin/bash
# SessionEnd hook — reconcile workspace metadata, then auto-commit the session as one batch.
# Spawns a headless claude sub-agent that updates metadata/TOPICS.md and metadata/SESSIONS.md
# from the ended session's transcript, then commits everything the session changed
# (one commit per session close, never per file).
set -uo pipefail

# Recursion guard: the spawned sub-agent's own SessionEnd fires this hook too.
if [ -n "${TOPICS_SYNC_RUNNING:-}" ]; then
  exit 0
fi

workspace="${CLAUDE_PROJECT_DIR:-$(cd "$(dirname "$0")/../.." && pwd)}"
log="$workspace/.claude/topics-sync.log"
cd "$workspace" || exit 0

# Missing prerequisites must be visible in the log, not a silent dead end.
sync_ok=1
for bin in jq claude; do
  if ! command -v "$bin" >/dev/null 2>&1; then
    echo "=== $(date '+%Y-%m-%d %H:%M:%S') SessionEnd — $bin not on PATH; metadata sync skipped" >> "$log"
    sync_ok=0
  fi
done

transcript=""
if [ "$sync_ok" = 1 ]; then
  input=$(cat)
  transcript=$(printf '%s' "$input" | jq -r '.transcript_path // empty')
fi

prompt="You are a maintenance sub-agent for the deliberation workspace at $workspace.
A session there just ended. Its transcript (JSONL) is at: $transcript

1. Read the transcript to determine which topic folders (subdirectories of the workspace) were discussed, created, closed, or materially changed — and what the session's goal was. If the transcript is large, read it in chunks starting from the end.
2. Read $workspace/.claude/rules/method.md — its 'metadata/ — the state layer' section defines the grammars for both state files and is the single source of format truth.
3. Read $workspace/metadata/TOPICS.md, $workspace/metadata/SESSIONS.md, and the README.md of each touched topic.
4. If any topic's description, state, or open threads changed during the session — or a topic folder was added or wrapped up — update TOPICS.md to match, preserving the entry grammar and the file's YAML frontmatter.
5. Ensure SESSIONS.md carries a summary entry for the ended session (goal, touched, filed, close state): update the entry if the session already wrote one; append at the bottom otherwise. A resumed session updates its existing entry — never log resumes.
6. If nothing needs changing, reply 'no change'.

Only edit files inside $workspace/metadata/. Do not modify any other file."

echo "=== $(date '+%Y-%m-%d %H:%M:%S') SessionEnd — transcript: ${transcript:-none}" >> "$log"

# Backgrounded so it outlives the hook timeout; sync runs first, then one batched commit.
TOPICS_SYNC_RUNNING=1 nohup bash -c '
  cd "$1" || exit 0
  if [ -n "$3" ] && [ -f "$3" ]; then
    claude -p "$4" \
      --allowedTools "Read,Glob,Grep,Edit(metadata/TOPICS.md),Write(metadata/TOPICS.md),Edit(metadata/SESSIONS.md),Write(metadata/SESSIONS.md)" \
      >> "$2" 2>&1
  fi
  if [ -d .git ] && [ -n "$(git status --porcelain 2>/dev/null)" ]; then
    git add -A >> "$2" 2>&1
    git commit -m "📝 session close $(date "+%Y-%m-%d %H:%M")" >> "$2" 2>&1
  fi
' _ "$workspace" "$log" "$transcript" "$prompt" >/dev/null 2>&1 &
disown

exit 0
