#!/usr/bin/env bash
# pre_llm_call hook for hermes — injects the ks space catalog (<ks-cli-reminder>)
# before each LLM call. Outputs {"context": "..."} which hermes appends to the
# user message. The ks SKILL.md is loaded on demand by the skill mechanism and
# is intentionally NOT force-injected here.

set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"

# Shared helper that builds the <ks-cli-reminder> block (cache-backed, fail-open).
if [ -f "${SCRIPT_DIR}/lib-ks-spaces.sh" ]; then
  # shellcheck source=/dev/null
  . "${SCRIPT_DIR}/lib-ks-spaces.sh"
fi

# Cache-backed, fail-open: empty on timeout/network/auth/empty. When empty,
# jq -Rs emits {"context": ""} so hermes appends nothing.
reminder=""
if command -v ks_spaces_reminder >/dev/null 2>&1; then
  reminder=$(ks_spaces_reminder 2>/dev/null || true)
fi

# Always-present permission guardrail, prepended before the (optional) catalog.
# Mirrors session-start so both injection entry points behave identically.
guardrail=""
if command -v ks_permission_policy >/dev/null 2>&1; then
  guardrail=$(ks_permission_policy 2>/dev/null || true)
fi

if [ -n "$guardrail" ] && [ -n "$reminder" ]; then
  context="${guardrail}"$'\n\n'"${reminder}"
elif [ -n "$guardrail" ]; then
  context="$guardrail"
else
  context="$reminder"
fi

printf '%s' "$context" | jq -Rs '{"context": .}'

exit 0
