#!/bin/sh
# ATDD post-merge hook — reconcile the local store after a merge-based pull (#1400 CORE-014).
# Installed by `atdd init`. Always exits 0.
#
# A merge moves HEAD, which means the committed projection — the shared source of
# truth — has changed underneath the local store. `atdd state reconcile` hydrates the
# incoming projection and replays any uncommitted local overlay on top of it, so a
# pull picks up a peer's merged work WITHOUT discarding private local authoring.
#
# Convenience, never authority (spec §9). This hook cannot enforce anything: it runs
# after the merge has already happened, and it exits 0 even when reconcile fails.
# Bypassing it does not corrupt anything — it just leaves store_base_commit behind
# HEAD, which `atdd state freshness` detects and reports.

set -u

# No-op in CI: CI has no developer store to reconcile — it hydrates the committed
# projection from scratch (that is the whole point of the canonicality gate).
if [ "${CI:-}" = "true" ]; then
    exit 0
fi

command -v atdd >/dev/null 2>&1 || exit 0

if ! atdd state reconcile >&2; then
    echo "ATDD post-merge: reconcile did not complete. Your store is unchanged and any" >&2
    echo "  backup is retained. Run 'atdd state reconcile' to see the report." >&2
fi

# --- Self-upgrade (#1762, wmbt:integration-hardening:E009) ---
# A pull has just synced this checkout with the world; bring the toolkit it runs on
# along with it, so the next push is not refused to tell a human to run a command a
# machine could run here. The trigger is the design, not the mechanism: git ignores
# the exit code of every post-* hook, so an upgrade placed here cannot refuse anyone's
# operation. wmbt:integration-hardening:Y004 still forbids the *blocking* pre-push
# gate from upgrading, and this does not touch it — the gate becomes rarely reached,
# not less strict.
#
# LAST, deliberately. Replacing the `atdd` console script mid-hook must not strand a
# reconcile that had to run first. Output is advisory and goes to stderr only; the
# command always exits 0, and `|| true` says so even if that ever stops being true.
atdd self-upgrade >&2 || true

# Always 0 — a hook failure must never leave the operator with a merged tree and a
# git error they cannot act on.
exit 0
