#!/usr/bin/env bash
# UserPromptSubmit hook: inject the standing prompt-optimiser directive as
# additionalContext on every turn, so the agent restates each non-trivial
# prompt via the prompt-optimiser skill before acting on it. Mirrors
# doctrine.sh: emit hookSpecificOutput.additionalContext via python3,
# fail-open with exit 0.
#
# Compliance is behavioural, not deterministic. A hook cannot force a skill
# call; the directive steers the agent, it does not gate the turn. The raw
# prompt always still reaches the model (UserPromptSubmit output is ADDED to
# the prompt, never substituted), so "the restatement governs" is an
# instruction to the agent, not a removal of the original text.
#
# Input  (stdin, UserPromptSubmit contract): { "prompt": "...", ... } — drained
#         and ignored; the directive is standing and prompt-independent.
# Output (stdout JSON):
#   { "hookSpecificOutput": { "hookEventName": "UserPromptSubmit",
#                             "additionalContext": "<directive>" } }
#
# Fail-open: if python3 is unavailable or JSON encoding fails, exit 0 with no
# stdout. The hook must never block or corrupt a turn.

set -uo pipefail

# Drain stdin; the directive does not depend on the prompt text.
cat >/dev/null 2>&1 || true

# Fail-open if the JSON encoder is unavailable.
command -v python3 >/dev/null 2>&1 || exit 0

DIRECTIVE=$(cat <<'DIRECTIVE_EOF'
PROMPT-OPTIMISER DIRECTIVE (standing)
Before acting on this turn's request, run the prompt-optimiser skill on the user's raw prompt in its in-session restatement mode, then treat the restated task as the authoritative statement of what was asked and proceed from it. Set aside your own first reading of the raw wording; the restatement governs. The raw prompt stays in context for reference only.
Skip the restatement when the prompt is a one-word confirmation, a slash-command invocation, or a direct continuation of the immediately preceding turn; restatement adds nothing in those cases.
DIRECTIVE_EOF
)

OUT=$(printf '%s' "$DIRECTIVE" | python3 -c '
import json, sys
ctx = sys.stdin.read()
print(json.dumps({
    "hookSpecificOutput": {
        "hookEventName": "UserPromptSubmit",
        "additionalContext": ctx,
    }
}))
' 2>/dev/null) || exit 0

[ -n "$OUT" ] || exit 0
printf '%s\n' "$OUT"
echo "[prompt-optimiser-directive] injected len=${#DIRECTIVE}" >&2
exit 0
