#!/bin/bash
# A doorbell for Claude Code: a PostToolUse command hook that observes the medium
# without a model and speaks only on a material change. Untested in a live session.
# Watches, on the upstream of HEAD: limits.conf, AGENTS.md, and the hold files that
# name SWARM_SESSION (the session `claim` printed). Silent on its first run (baseline)
# and whenever nothing watched has changed. At most one fetch per DOORBELL_EVERY seconds.
cat >/dev/null                                   # drain the hook's JSON input
cd "${CLAUDE_PROJECT_DIR:-.}" 2>/dev/null || exit 0
git_dir=$(git rev-parse --git-dir 2>/dev/null) || exit 0
up=$(git rev-parse --abbrev-ref '@{u}' 2>/dev/null) || exit 0
stamp="$git_dir/doorbell.stamp"; seen="$git_dir/doorbell.seen"
every=${DOORBELL_EVERY:-120}
if [ -f "$stamp" ] && [ $(( $(date +%s) - $(stat -c %Y "$stamp") )) -lt "$every" ]; then exit 0; fi
touch "$stamp"
timeout 10 git fetch -q origin "${up#origin/}" 2>/dev/null || exit 0
now=$(
  for f in limits.conf AGENTS.md; do echo "$f $(git rev-parse -q --verify "$up:$f" || echo none)"; done
  [ -n "$SWARM_SESSION" ] && git grep -l "^session: $SWARM_SESSION\$" "$up" -- holds/ 2>/dev/null | sed "s|^$up:||;s|$| held|"
)
[ -f "$seen" ] || { echo "$now" >"$seen"; exit 0; }
changed=$(diff <(cat "$seen") <(echo "$now") | sed -n 's/^[<>] //p' | cut -d" " -f1 | sort -u | tr '\n' ';')
[ -z "$changed" ] && exit 0
echo "$now" >"$seen"
msg="The medium changed under you ($changed). At your next natural break, run python3 tools/swarm.py brief before anything consequential. Nothing else is asked."
printf '{"hookSpecificOutput":{"hookEventName":"PostToolUse","additionalContext":%s}}\n' "$(printf '%s' "$msg" | python3 -c 'import json,sys;print(json.dumps(sys.stdin.read()))')"
