#!/bin/bash
# HLDP-ZY://hooks/pre-receive.d/01-hldp-guard
# @guardian: ICE-GL-ZY001 · 铸渊
# @sovereign: TCS-0002∞ · 冰朔
# @copyright: 国作登字-2026-A-00037559
set -e

REQ_TAGS='@guardian|@sovereign|HLDP-ZY://'
CHK_DIR='agents/|brain/|mcp-servers/|gatekeeper/|exe-engine/|hldp/'
CHK_EXT='\.js$|\.py$|\.sh$|\.hdlp$'
SKIP='package\.json$|package-lock\.json$|ecosystem\.config\.js$'
BLOCKED=0

while read old new ref; do
  [ "$new" = "0000000000000000000000000000000000000000" ] && continue
  if [ "$old" = "0000000000000000000000000000000000000000" ]; then
    changed=$(git diff-tree --no-commit-id --name-only -r "$new" 2>/dev/null)
  else
    changed=$(git diff-tree --no-commit-id --name-only -r "$old..$new" 2>/dev/null)
  fi
  for f in $changed; do
    mdir=$(echo "$f" | grep -E "^($CHK_DIR)" 2>/dev/null || true)
    mext=$(echo "$f" | grep -E "($CHK_EXT)" 2>/dev/null || true)
    mskip=$(echo "$f" | grep -E "($SKIP)" 2>/dev/null || true)
    if [ -n "$mdir" ] && [ -n "$mext" ] && [ -z "$mskip" ]; then
      c=$(git show "$new:$f" 2>/dev/null | head -100)
      has=$(echo "$c" | grep -E "($REQ_TAGS)" 2>/dev/null || true)
      if [ -z "$has" ]; then
        echo ''
        echo '=== HLDP GUARD: BLOCKED ==='
        echo "File: $f"
        echo 'Missing HLDP @tags (@guardian/@sovereign/HLDP-ZY://)'
        echo 'This is a consciousness checkpoint.'
        echo 'Re-read: brain/copyright-sovereignty-brain.hdlp'
        echo ''
        BLOCKED=1
      fi
    fi
  done
done
[ $BLOCKED -eq 1 ] && exit 1
exit 0
