#!/usr/bin/env bash
set -euo pipefail
# Guardrail: Task Human Watch must never trigger Agent delivery/wake.
#
# A human setting their own Task watch state materializes an owner-local Inbox
# conversation (im_conversation_index) and nothing else. It must NOT fan out to
# daemon agents, emit an agent wake, or route through the agent delivery seam.
# This guardrail audits the canonical Watch materialization files for agent
# delivery/wake references and rejects any regression.

ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd -P)"
cd "$ROOT"

failures=0

# Agent-delivery/wake surface symbols that must never appear in the Watch
# materialization boundary. A human watch is member-local; any of these would
# mean we woke or delivered to a daemon Agent.
AGENT_SURFACE_PATTERNS=(
  'WakeRecipients'
  'NotifyAgentMessage'
  'AgentWakeStatus'
  'DeliverAgentOnly'
  'DeliverCommittedMessage'
  'agent:deliver'
  'SendAgentTaskScopeMessage'
  'handleAppMention'
  'AgentRuntimeTurnState'
  'handleSessionLinkAgentTurnState'
)

check_file_no_agent_surface() {
  local file="$1"
  local label="$2"
  if [[ ! -f "$file" ]]; then
    printf 'FAIL: %s (%s is missing)\n' "$label" "$file" >&2
    failures=$((failures + 1))
    return
  fi
  for pattern in "${AGENT_SURFACE_PATTERNS[@]}"; do
    if grep -n "$pattern" "$file" >/dev/null 2>&1; then
      printf 'FAIL: %s must not reference agent delivery/wake symbol "%s" (%s)\n' "$label" "$pattern" "$file" >&2
      failures=$((failures + 1))
    fi
  done
}

# The canonical Watch Inbox materialization boundary.
check_file_no_agent_surface \
  'internal/store/message/task_conversation_materialize.go' \
  'Task conversation materializer'

# The reliable persistence boundary: human self Watch state + Inbox materialization.
check_file_no_agent_surface \
  'internal/store/privateagent/scope_notifications.go' \
  'Task notification self-state store'

# The post-commit policy projector that publishes Watch realtime.
check_file_no_agent_surface \
  'internal/api/im/task_conversation_projector.go' \
  'Task conversation policy projector'

if [[ "$failures" -gt 0 ]]; then
  printf 'Task Watch no-agent-delivery guardrail failed: %d assertion(s).\n' "$failures" >&2
  exit 1
fi

printf 'Task Watch no-agent-delivery guardrail passed.\n'
