#!/usr/bin/env bash
# check-constitution.sh — the final vote. Exits non-zero on the first violation.
# Wire into .git/hooks/pre-commit so it runs whether the agent remembers it or not:
#   ln -sf ../../ops/check-constitution.sh .git/hooks/pre-commit
set -euo pipefail

fail() { echo "✗ RULE $1: $2" >&2; exit 1; }

# Rule 1 — not on main
[ "$(git branch --show-current)" != main ] || fail 1 "on main branch"

# Rule 3 — tests green
make test >/dev/null 2>&1 || fail 3 "make test failed"

# Rule 4 — no secrets in the staged diff
if git diff --cached | grep -Eiq '(api[_-]?key|secret|password|token)\s*[:=]\s*.+'; then
  fail 4 "possible secret in staged diff"
fi

# Rule 6 — file budget
n=$(git diff --cached --name-only | wc -l | tr -d ' ')
[ "$n" -le 20 ] || fail 6 "$n files staged (max 20)"

# Rule 7 — the OS is off-limits to automated edits
if git diff --cached --name-only | grep -q '^ops/'; then
  # Allow it only if a human sets ALLOW_OPS_EDIT=1 for this commit.
  [ "${ALLOW_OPS_EDIT:-0}" = "1" ] || fail 7 "automated edit under ops/ (set ALLOW_OPS_EDIT=1 to override by hand)"
fi

echo "✓ constitution: all rules pass"
