#!/bin/bash
# check-append-only.sh — fails (exit 1) if any STAGED change to an append-only
# vault file removes lines. Append-only files per HQ-Vault/_System/CLAUDE.md:
#
#   HQ-Vault/01_Daily/*.md
#   HQ-Vault/<project>/_Brain/_Log.md
#   HQ-Vault/<project>/_AgentLog/*.md
#   HQ-Vault/_System/CuratorLog.md
#   HQ-Vault/_System/Conflicts.md
#
# Lines may be ADDED freely. Removing/rewriting prior lines is a protocol
# violation — append a correction with a backlink to the original instead.
#
# Called from scripts/auto-sync.sh before commit. Also runs locally as
# `bash scripts/check-append-only.sh` (returns 0 if clean, 1 if violations).
#
# Returns 0 immediately if no append-only files are staged.

set -u

# Patterns are POSIX BRE for grep -E
APPEND_ONLY_PATTERNS='HQ-Vault/01_Daily/.*\.md$|HQ-Vault/.+/_Log\.md$|HQ-Vault/.+/_AgentLog/.*\.md$|HQ-Vault/_System/CuratorLog\.md$|HQ-Vault/_System/Conflicts\.md$|HQ-Vault/_System/AgentLog/events\.ndjson$'

# Files staged in this commit, only Modified (M) — newly added (A) and renamed (R)
# don't have a prior version to compare against, so they can't violate append-only.
staged_files=$(git diff --cached --name-only --diff-filter=M | grep -E "$APPEND_ONLY_PATTERNS" || true)

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

violations=()
while IFS= read -r f; do
  [ -z "$f" ] && continue
  # --numstat returns: <added>\t<removed>\t<path>. Use removed count directly,
  # avoiding diff-header / leading-dash regex pitfalls.
  removed=$(git diff --cached --numstat -- "$f" | awk '{print $2}')
  if [ -n "$removed" ] && [ "$removed" != "-" ] && [ "$removed" -gt 0 ] 2>/dev/null; then
    violations+=("$f (-$removed lines)")
  fi
done <<< "$staged_files"

if [ ${#violations[@]} -gt 0 ]; then
  echo "APPEND-ONLY VIOLATION — commit blocked." >&2
  echo "" >&2
  echo "These files are append-only per HQ-Vault/_System/CLAUDE.md (AI Team Protocol):" >&2
  for v in "${violations[@]}"; do
    echo "  - $v" >&2
  done
  echo "" >&2
  echo "If a prior entry was wrong, append a correction with a backlink to" >&2
  echo "the original — never rewrite history. To override (use sparingly):" >&2
  echo "  git commit --no-verify   (NOT recommended)" >&2
  exit 1
fi

exit 0
