#!/bin/bash
# ~/.panopticon/bin/pre-tool-hook  (PAN-800)
#
# Fires on Claude Code PreToolUse. POSTs agent.activity_changed(working, tool)
# to the dashboard. No runtime.json writes — AgentStateService's
# SubscriptionRef is the source of truth now.
#
# Never blocks Claude Code: strict timeout, silent failure, pending-events
# buffering via pan-hook-lib.

set +e

SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
# shellcheck source=pan-hook-lib.sh
. "$SCRIPT_DIR/pan-hook-lib.sh" 2>/dev/null || exit 0

pan_resolve_agent_id || exit 0

TOOL_INFO=$(cat 2>/dev/null || echo '{}')
TOOL_NAME="unknown"
if command -v jq >/dev/null 2>&1; then
  TOOL_NAME=$(echo "$TOOL_INFO" | jq -r '.tool_name // "unknown"' 2>/dev/null || echo "unknown")
fi

TS=$(date -Iseconds)
# jq -n produces correctly-escaped JSON even if TOOL_NAME contains quotes.
if command -v jq >/dev/null 2>&1; then
  BODY=$(jq -n --arg tool "$TOOL_NAME" --arg ts "$TS" \
    '{kind: "activity", activity: "working", tool: $tool, timestamp: $ts}')
else
  BODY="{\"kind\":\"activity\",\"activity\":\"working\",\"tool\":\"$TOOL_NAME\",\"timestamp\":\"$TS\"}"
fi

pan_emit_event "$AGENT_ID" "$BODY"
exit 0
