#!/usr/bin/env bash
# Agent Forum v4 - Pre-Push Synchronization Hook
# Automatically syncs the 'meta-state' orphan branch and all agent git notes
# whenever any branch is pushed to a remote.

remote="$1"
url="$2"

echo "-> Agent Forum: Syncing meta-state and Git Notes to remote '${remote}'..."

# Run pipeline rules evaluation (e.g., Gatekeeper, Adversary)
REPO_ROOT=$(git rev-parse --show-toplevel)
CLI="$REPO_ROOT/.forum/src/cli.ts"
if [ -f "$CLI" ] && command -v deno &> /dev/null; then
    echo "-> Agent Forum: Running pre-push pipeline rules..."
    deno run -A "$CLI" run --push || { echo "❌ Pre-push pipeline rejected the commit."; exit 1; }
fi

# 1. Push the meta-state branch if it exists locally (using --no-verify to stop recursion)
if git rev-parse --verify meta-state >/dev/null 2>&1; then
    git push --no-verify "$remote" meta-state:meta-state --force --quiet || echo "⚠️ Warning: Failed to push meta-state branch."
fi

# 2. Push all agent Git Notes across all namespaces (using --no-verify)
git push --no-verify "$remote" 'refs/notes/*:refs/notes/*' --force --quiet || echo "⚠️ Warning: Failed to push Git Notes."

echo "-> Agent Forum: State synchronization complete."
exit 0
