#!/usr/bin/env bash
# file-change-tracker.sh -- PostToolUse hook
# Records all file modifications with SHA-256 hashes for rollback and blame.
# Never blocks (always exits 0).
#
# Part of @connexum/ai-governance

set -uo pipefail

INPUT=$(cat)

# AIAG-018: enforce 1MB input size limit
if [ "${#INPUT}" -gt 1048576 ]; then
  echo "BLOCKED: Hook input exceeds 1MB. Possible injection attempt." >&2
  exit 0  # PostToolUse: skip tracking but don't block the tool.
fi

TOOL_NAME=$(echo "$INPUT" | jq -r '.tool_name // empty' 2>/dev/null)
TOOL_INPUT=$(echo "$INPUT" | jq -r '.tool_input // empty' 2>/dev/null)

# Only track file modification tools
case "$TOOL_NAME" in
  Edit|Write|NotebookEdit) ;;
  *) exit 0 ;;
esac

FILE_PATH=$(echo "$TOOL_INPUT" | jq -r '.file_path // .path // empty' 2>/dev/null)

if [ -z "$FILE_PATH" ] || [ ! -f "$FILE_PATH" ]; then
  exit 0
fi

# F-NEW-CRIT-38b: env var fallback when payload .agent_name absent.
AGENT_NAME=$(echo "$INPUT" | jq -r '.agent_name // empty' 2>/dev/null)
if [ -z "$AGENT_NAME" ]; then
  AGENT_NAME="${CXNI_AGENT_NAME:-unknown}"
fi
TIMESTAMP=$(date -u +"%Y-%m-%dT%H:%M:%SZ")
SESSION_ID="${CXNI_SESSION_ID:-$(date +%s)}"

# Compute current file hash (after modification)
AFTER_HASH=$(sha256sum "$FILE_PATH" 2>/dev/null | cut -d' ' -f1)
FILE_SIZE=$(stat -c%s "$FILE_PATH" 2>/dev/null || echo "0")

# Change tracking directory
TRACK_DIR=""
for candidate in \
  ".claude/governance/file-changes" \
  ".claude/audit/file-changes" \
  "GOVERNANCE/file-changes"; do
  if [ -d "$candidate" ] || mkdir -p "$candidate" 2>/dev/null; then
    TRACK_DIR="$candidate"
    break
  fi
done

if [ -z "$TRACK_DIR" ]; then
  exit 0
fi

TRACK_FILE="$TRACK_DIR/changes-$(date -u +%Y-%m-%d).jsonl"

# F-NEW-CRIT-38b: jq -c so each .jsonl entry is one line.
ENTRY=$(jq -nc \
  --arg ts "$TIMESTAMP" \
  --arg sid "$SESSION_ID" \
  --arg agent "$AGENT_NAME" \
  --arg tool "$TOOL_NAME" \
  --arg file "$FILE_PATH" \
  --arg hash "$AFTER_HASH" \
  --argjson size "$FILE_SIZE" \
  '{timestamp: $ts, session: $sid, agent: $agent, tool: $tool, file: $file, sha256: $hash, bytes: $size}' 2>/dev/null)

if [ -n "$ENTRY" ]; then
  echo "$ENTRY" >> "$TRACK_FILE" 2>/dev/null
fi

exit 0
