Skip to content

Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure

TypeScript
32.4 KB
Raw Blame
#!/usr/bin/env bash
# ======================================================================
# Cluster-agnostic idempotent E2E seed.
#
# Ensures the E2E users exist with the (agent, context) associations that
# desktop-app/test/e2e/* and scripts/e2e/*.sh suites require. User/team and
# access bindings use the admin API contract. Minikube additionally gets local
# Desktop password-login credentials, plus optional Plugin Workload SDK demo
# grants for the grant-driven sandbox-ui notification recipe. When the recipe
# is already installed, the same seed also gives the E2E users direct
# WorkflowRecipe trigger access so the Desktop Apps picker can list its
# `spec.ui` app. SDK capability grants and Sandbox UI trigger grants are
# separate authorization contracts.
#
# Idempotent: safe to run on every deploy. Re-runs preserve existing state
# (admin user/team lookup is create-if-missing, PUT /admin/users/:id/
# {agents,contexts} are full-set replaces with the same values).
#
# Defaults unified with desktop-app/test/e2e/helpers.ts:120 so a fresh
# checkout "just works" without hunting for env vars.
#
# Usage:
#   # local (current kubectl context)
#   ADMIN_PASSWORD='...' scripts/e2e/seed-e2e-data.sh
#
#   # targeted cluster
#   CONTEXT=gke_your-gcp-project_us-central1-a_example-dev \
#     ADMIN_PASSWORD='...' scripts/e2e/seed-e2e-data.sh
#
#   # CI (GitHub Actions)
#   env ADMIN_PASSWORD=${{ secrets.E2E_ADMIN_PASSWORD }} \
#     scripts/e2e/seed-e2e-data.sh
#
# Env vars:
#   CONTEXT              kubectl context (default: current)
#   E2E_DEV_LOGIN_EMAIL  user email     (default: [email protected])
#   E2E_DEV_LOGIN_NAME   user name      (default: Test User)
#   E2E_SEED_DESKTOP_PASSWORDS  true/false; defaults to true only on minikube
#   E2E_HOST_REF         agent/host ref (default: chatllm)
#   E2E_CONTEXT_ID       context id     (default: context1)
#   E2E_SEED_PLUGIN_SDK_DEMO_GRANTS true/false; defaults to true only on minikube
#   E2E_PLUGIN_SDK_DEMO_RECIPE_NAME recipe receiving demo grants (default: evenfire-prompt-notify-app)
#   E2E_PLUGIN_SDK_DEMO_EVENT_TYPE  notification event type (default: fullstack.prompt.notify)
#   E2E_PLUGIN_SDK_DEMO_CALLER_REF  allowed caller ref (default: backend)
#   E2E_PLUGIN_SDK_DEMO_MODEL_NAME  promptBridge model grant (default: E2E/CLERUM model)
#   E2E_PLUGIN_SDK_DEMO_PROVIDER     promptBridge provider (default: E2E/CLERUM provider)
#   E2E_PLUGIN_SDK_DEMO_TARGET_REF   ordered policy target id (default: primary)
#   E2E_PLUGIN_SDK_DEMO_CREDENTIAL_SLOT Secret data key owned by provider (derived when omitted)
#   ADMIN_USERNAME       admin user     (default: admin)
#   ADMIN_EMAIL          bootstrap email (default: [email protected] for
#                        SEED_PROFILE=minimal, otherwise [email protected])
#   ADMIN_PASSWORD       admin pass     (REQUIRED — bootstrap or rotated)
#   CONTROL_API_NS       ns             (default: control-plane)
# ======================================================================

set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
REPO_ROOT="$(cd "${SCRIPT_DIR}/../.." && pwd)"
# shellcheck source=scripts/e2e/load-dotenv.sh
source "${SCRIPT_DIR}/load-dotenv.sh"
dotenv_load_canonical_root "${REPO_ROOT}"
# shellcheck source=scripts/e2e/admin-credentials.sh
source "${SCRIPT_DIR}/admin-credentials.sh"
# shellcheck source=scripts/e2e/minimal-bootstrap-contract.sh
source "${SCRIPT_DIR}/minimal-bootstrap-contract.sh"

# ─── Config (all overridable) ──────────────────────────────────────────
CONTEXT="${CONTEXT:-$(kubectl config current-context)}"
KC="kubectl --context=${CONTEXT}"

SEED_PROFILE="${SEED_PROFILE:-e2e}"
DEV_EMAIL="${E2E_DEV_LOGIN_EMAIL:-test@clerum.io}"
DEV_NAME="${E2E_DEV_LOGIN_NAME:-Test User}"
DEV_EMAIL_2="${E2E_DEV_LOGIN_EMAIL_2:-test2@clerum.io}"
DEV_NAME_2="${E2E_DEV_LOGIN_NAME_2:-Test User 2}"

# The second E2E fixture user ([email protected]) backs the e2e lane's
# multi-user/cross-device suites — desktop-app/test/e2e-playwright/
# crossDeviceSessions.helpers.ts, gfs-user-journey.test.ts,
# third-party-authn-third-party-mcphost.figure-d.test.ts, and
# sdk-client-notification/evenfireSandboxUiCrossUserDelivery.test.ts all
# depend on it. But the minimal profile must not seed anything named test*
# (see scripts/minikube/full-setup.sh Step 10), so every consumer of this
# user below (team, bindings, desktop login, SDK grants, summary line) is
# gated on this flag instead.
#
# Default is e2e (opposite of full-setup.sh's `minimal` default): this
# script is invoked directly by `make e2e-desktop-app` and ~9
# scripts/e2e/*.sh callers that never set SEED_PROFILE — defaulting to
# `minimal` here would silently break all of them.
SEED_SECOND_E2E_USER="false"
if [ "${SEED_PROFILE:-e2e}" = "e2e" ]; then
  SEED_SECOND_E2E_USER="true"
fi
# Populated in Step 5 only when SEED_SECOND_E2E_USER=true. Initialized here
# so later reads are safe under `set -u` even when Step 5 is skipped.
USER_ID_2=""
TEAM_ID_2=""

AGENT_NAME="${E2E_HOST_REF:-chatllm}"
CONTEXT_ID="${E2E_CONTEXT_ID:-context1}"

ADMIN_USERNAME="${ADMIN_USERNAME:-admin}"
if [ -z "${ADMIN_EMAIL:-}" ]; then
  if [ "$SEED_PROFILE" = "minimal" ]; then
    ADMIN_EMAIL="[email protected]"
  else
    ADMIN_EMAIL="[email protected]"
  fi
fi
if [ "$SEED_PROFILE" = "minimal" ]; then
  ADMIN_EMAIL="$(clerum_canonical_email "$ADMIN_EMAIL")"
  if [ -n "${E2E_DEV_LOGIN_EMAIL+x}" ]; then
    DEV_EMAIL="$(clerum_minimal_desktop_email "$ADMIN_EMAIL" "$DEV_EMAIL" true)"
  else
    DEV_EMAIL="$(clerum_minimal_desktop_email "$ADMIN_EMAIL" "" false)"
  fi
  if ! clerum_minimal_identity_matches "$ADMIN_EMAIL" "$DEV_EMAIL"; then
    printf '  ERROR: %s\n' "$(clerum_minimal_identity_error "$DEV_EMAIL" "$ADMIN_EMAIL")" >&2
    exit 1
  fi
  if [ -z "${E2E_DEV_LOGIN_NAME:-}" ]; then
    DEV_NAME="admin"
  fi
fi
ADMIN_PASSWORD="$(e2e_resolve_admin_password "${REPO_ROOT}" || true)"
DESKTOP_LOGIN_CREDENTIAL="$ADMIN_PASSWORD"
SEED_DESKTOP_LOGIN="${E2E_SEED_DESKTOP_PASSWORDS:-}"
SEED_PLUGIN_SDK_DEMO_GRANTS="${E2E_SEED_PLUGIN_SDK_DEMO_GRANTS:-}"
PLUGIN_SDK_DEMO_RECIPE_NS="${E2E_PLUGIN_SDK_DEMO_RECIPE_NS:-sandbox-recipes}"
PLUGIN_SDK_DEMO_RECIPE_NAME="${E2E_PLUGIN_SDK_DEMO_RECIPE_NAME:-${E2E_SANDBOX_UI_RECIPE:-evenfire-prompt-notify-app}}"
PLUGIN_SDK_DEMO_EVENT_TYPE="${E2E_PLUGIN_SDK_DEMO_EVENT_TYPE:-fullstack.prompt.notify}"
PLUGIN_SDK_DEMO_CALLER_REF="${E2E_PLUGIN_SDK_DEMO_CALLER_REF:-backend}"
PLUGIN_SDK_DEMO_PROVIDER="${E2E_PLUGIN_SDK_DEMO_PROVIDER:-}"
if [ -z "$PLUGIN_SDK_DEMO_PROVIDER" ]; then
  case "${CLERUM_MODEL_PROVIDER:-}" in
    openai|claude) PLUGIN_SDK_DEMO_PROVIDER="$CLERUM_MODEL_PROVIDER" ;;
    *) PLUGIN_SDK_DEMO_PROVIDER="openai" ;;
  esac
fi
PLUGIN_SDK_DEMO_MODEL_NAME="${E2E_PLUGIN_SDK_DEMO_MODEL_NAME:-${E2E_WORKFLOW_MODEL_NAME:-}}"
if [ -z "$PLUGIN_SDK_DEMO_MODEL_NAME" ]; then
  case "$PLUGIN_SDK_DEMO_PROVIDER" in
    openai) PLUGIN_SDK_DEMO_MODEL_NAME="gpt-5.4-mini" ;;
    claude) PLUGIN_SDK_DEMO_MODEL_NAME="claude-sonnet-4-6" ;;
    *) die "Plugin SDK demo provider '$PLUGIN_SDK_DEMO_PROVIDER' requires explicit E2E_PLUGIN_SDK_DEMO_MODEL_NAME" ;;
  esac
fi
PLUGIN_SDK_DEMO_TARGET_REF="${E2E_PLUGIN_SDK_DEMO_TARGET_REF:-primary}"
PLUGIN_SDK_DEMO_CREDENTIAL_SLOT="${E2E_PLUGIN_SDK_DEMO_CREDENTIAL_SLOT:-}"
PLUGIN_SDK_DEMO_PROMPT_MAX="${E2E_PLUGIN_SDK_DEMO_PROMPT_MAX_REQUESTS:-50}"
PLUGIN_SDK_DEMO_NOTIFICATION_MAX="${E2E_PLUGIN_SDK_DEMO_MAX_NOTIFICATIONS:-25}"

CONTROL_API_NS="${CONTROL_API_NS:-control-plane}"

CONTROL_API_SVC="${CONTROL_API_SVC:-control-api}"

CONTROL_API_LOCAL_PORT="${CONTROL_API_LOCAL_PORT:-18090}"

CYAN='\033[0;36m'; GREEN='\033[0;32m'; RED='\033[0;31m'; YELLOW='\033[0;33m'; NC='\033[0m'
log()  { echo -e "${CYAN}[seed]${NC} $*"; }
ok()   { echo -e "  ${GREEN}OK${NC} — $*"; }
warn() { echo -e "  ${YELLOW}WARN${NC} — $*"; }
die()  { echo -e "  ${RED}ERROR${NC} — $*" >&2; exit 1; }

if [ -z "$PLUGIN_SDK_DEMO_CREDENTIAL_SLOT" ]; then
  case "$PLUGIN_SDK_DEMO_PROVIDER" in
    openai) PLUGIN_SDK_DEMO_CREDENTIAL_SLOT="openai-api-key" ;;
    claude) PLUGIN_SDK_DEMO_CREDENTIAL_SLOT="claude-api-key" ;;
    zai) PLUGIN_SDK_DEMO_CREDENTIAL_SLOT="zai-api-key" ;;
    bailian) PLUGIN_SDK_DEMO_CREDENTIAL_SLOT="bailian-api-key" ;;
    vertex) PLUGIN_SDK_DEMO_CREDENTIAL_SLOT="vertex-service-account-json" ;;
    bedrock) PLUGIN_SDK_DEMO_CREDENTIAL_SLOT="aws-access-key-id" ;;
    openrouter) PLUGIN_SDK_DEMO_CREDENTIAL_SLOT="openrouter-api-key" ;;
    gemini) PLUGIN_SDK_DEMO_CREDENTIAL_SLOT="gemini-api-key" ;;
    deepseek) PLUGIN_SDK_DEMO_CREDENTIAL_SLOT="deepseek-api-key" ;;
    groq) PLUGIN_SDK_DEMO_CREDENTIAL_SLOT="groq-api-key" ;;
    together) PLUGIN_SDK_DEMO_CREDENTIAL_SLOT="together-api-key" ;;
    fireworks) PLUGIN_SDK_DEMO_CREDENTIAL_SLOT="fireworks-api-key" ;;
    mistral) PLUGIN_SDK_DEMO_CREDENTIAL_SLOT="mistral-api-key" ;;
    xai) PLUGIN_SDK_DEMO_CREDENTIAL_SLOT="xai-api-key" ;;
    cerebras) PLUGIN_SDK_DEMO_CREDENTIAL_SLOT="cerebras-api-key" ;;
    deepinfra) PLUGIN_SDK_DEMO_CREDENTIAL_SLOT="deepinfra-api-key" ;;
    perplexity) PLUGIN_SDK_DEMO_CREDENTIAL_SLOT="perplexity-api-key" ;;
    moonshot) PLUGIN_SDK_DEMO_CREDENTIAL_SLOT="moonshot-api-key" ;;
    nebius) PLUGIN_SDK_DEMO_CREDENTIAL_SLOT="nebius-api-key" ;;
    novita) PLUGIN_SDK_DEMO_CREDENTIAL_SLOT="novita-api-key" ;;
    minimax) PLUGIN_SDK_DEMO_CREDENTIAL_SLOT="minimax-api-key" ;;
    azure) PLUGIN_SDK_DEMO_CREDENTIAL_SLOT="azure-openai-api-key" ;;
    *) die "Cannot derive a credential slot for provider '$PLUGIN_SDK_DEMO_PROVIDER'; set E2E_PLUGIN_SDK_DEMO_CREDENTIAL_SLOT explicitly" ;;
  esac
fi

# shellcheck source=scripts/e2e/desktop-login-seed.sh
source "${SCRIPT_DIR}/desktop-login-seed.sh"

seed_desktop_login_if_enabled() {
  local enabled="$SEED_DESKTOP_LOGIN"
  if [ -z "$enabled" ]; then
    if is_password_seed_allowed_context; then
      enabled="true"
    else
      enabled="false"
    fi
  fi

  if [ "$enabled" != "true" ]; then
    log "Skipping desktop login credential seed for context $CONTEXT"
    return 0
  fi
  if ! is_password_seed_allowed_context; then
    die "Refusing to seed desktop login credentials outside an allowed non-prod context '$CONTEXT'"
  fi
  if [ -z "$DESKTOP_LOGIN_CREDENTIAL" ]; then
    die "ADMIN_PASSWORD is required when seeding desktop login credentials"
  fi

  if [ "$SEED_SECOND_E2E_USER" = "true" ]; then
    log "Seeding desktop login credentials for $DEV_EMAIL and $DEV_EMAIL_2 (context=$CONTEXT)"
    seed_desktop_login_for_user "$DEV_EMAIL" "$USER_ID" "$DESKTOP_LOGIN_CREDENTIAL"
    seed_desktop_login_for_user "$DEV_EMAIL_2" "$USER_ID_2" "$DESKTOP_LOGIN_CREDENTIAL"
    ok "Desktop login enabled for seeded users"
  else
    log "Seeding desktop login credentials for $DEV_EMAIL (context=$CONTEXT)"
    seed_desktop_login_for_user "$DEV_EMAIL" "$USER_ID" "$DESKTOP_LOGIN_CREDENTIAL"
    log "Skipping desktop login for $DEV_EMAIL_2 (SEED_PROFILE=minimal)"
    ok "Desktop login enabled for seeded user"
  fi
}

seed_plugin_sdk_demo_grants_if_enabled() {
  local enabled="$SEED_PLUGIN_SDK_DEMO_GRANTS"
  if [ -z "$enabled" ]; then
    if is_minikube_context; then
      enabled="true"
    else
      enabled="false"
    fi
  fi

  if [ "$enabled" != "true" ]; then
    log "Skipping Plugin Workload SDK demo grants for context $CONTEXT"
    return 0
  fi
  if ! is_minikube_context; then
    die "Refusing to seed Plugin Workload SDK demo grants outside minikube context '$CONTEXT'"
  fi
  if [ -z "$USER_ID" ] || [ -z "$USER_ID_2" ]; then
    die "Cannot seed Plugin Workload SDK demo grants before seeded user ids are available"
  fi

  log "Seeding Plugin Workload SDK demo grants for ${PLUGIN_SDK_DEMO_RECIPE_NS}/${PLUGIN_SDK_DEMO_RECIPE_NAME}"
  admin_post "$CAPI_BASE/admin/plugin-workload-sdk/grants" \
    "$(jq -cn \
      --arg ns "$PLUGIN_SDK_DEMO_RECIPE_NS" \
      --arg n "$PLUGIN_SDK_DEMO_RECIPE_NAME" \
      --arg caller "$PLUGIN_SDK_DEMO_CALLER_REF" \
      --arg provider "$PLUGIN_SDK_DEMO_PROVIDER" \
      --arg target "$PLUGIN_SDK_DEMO_TARGET_REF" \
      --arg credentialSlot "$PLUGIN_SDK_DEMO_CREDENTIAL_SLOT" \
      --arg model "$PLUGIN_SDK_DEMO_MODEL_NAME" \
      --argjson max "$PLUGIN_SDK_DEMO_PROMPT_MAX" \
      '{recipeNamespace:$ns,recipeName:$n,capabilityFamily:"promptBridge",provider:$provider,allowedModels:[$model],promptTargets:[{targetRef:$target,provider:$provider,model:$model,credentialSlot:$credentialSlot}],defaultTargetRef:$target,allowedCallers:[$caller],quotaLimits:{maxRequestsPerRun:$max}}')" \
    "POST /admin/plugin-workload-sdk/grants promptBridge"

  admin_post "$CAPI_BASE/admin/plugin-workload-sdk/grants" \
    "$(jq -cn \
      --arg ns "$PLUGIN_SDK_DEMO_RECIPE_NS" \
      --arg n "$PLUGIN_SDK_DEMO_RECIPE_NAME" \
      --arg ev "$PLUGIN_SDK_DEMO_EVENT_TYPE" \
      --arg u1 "$USER_ID" \
      --arg u2 "$USER_ID_2" \
      --arg caller "$PLUGIN_SDK_DEMO_CALLER_REF" \
      --argjson max "$PLUGIN_SDK_DEMO_NOTIFICATION_MAX" \
      '{recipeNamespace:$ns,recipeName:$n,capabilityFamily:"clientNotifications",allowedEventTypes:[$ev],allowedUserRefs:[$u1,$u2],allowedCallers:[$caller],quotaLimits:{maxNotificationsPerRun:$max}}')" \
    "POST /admin/plugin-workload-sdk/grants clientNotifications"

  # Sandbox UI discovery is governed by WorkflowRecipe trigger grants, not by
  # Plugin Workload SDK capability grants. Seed this only when the target
  # recipe is already installed; full-stack setup invokes this script before
  # optional application recipes are applied.
  if $KC -n "$PLUGIN_SDK_DEMO_RECIPE_NS" get workflowrecipe "$PLUGIN_SDK_DEMO_RECIPE_NAME" >/dev/null 2>&1; then
    admin_put "$CAPI_BASE/admin/workflows/${PLUGIN_SDK_DEMO_RECIPE_NS}/${PLUGIN_SDK_DEMO_RECIPE_NAME}/grants" \
      "$(jq -cn --arg u1 "$USER_ID" --arg u2 "$USER_ID_2" '{userIds:[$u1,$u2]}')" \
      "PUT /admin/workflows/${PLUGIN_SDK_DEMO_RECIPE_NS}/${PLUGIN_SDK_DEMO_RECIPE_NAME}/grants"
  else
    log "Skipping Sandbox UI trigger grant: ${PLUGIN_SDK_DEMO_RECIPE_NS}/${PLUGIN_SDK_DEMO_RECIPE_NAME} is not installed yet"
  fi

  ok "Plugin Workload SDK demo grants seeded for $DEV_EMAIL and $DEV_EMAIL_2"
}

# ─── SAFETY GUARD — non-prod cluster allowlist (fail-closed) ───────────
# This script bootstraps an admin (POST /admin/auth/setup) on fresh clusters
# and creates a well-known E2E user. Running it against production would be
# equivalent to installing a backdoor. Allowlist is exhaustive — adding a
# new cluster requires a conscious code edit + review.
#
# Override for a new non-prod cluster: set ALLOWED_CONTEXTS (comma-separated
# list). Never add a prod context to this allowlist.
DEFAULT_ALLOWED_CONTEXTS=(
  "clerum-test"                                               # minikube
  "gke_your-gcp-project_us-central1-a_example-dev"             # GKE dev
)
IFS=',' read -r -a EXTRA_ALLOWED <<<"${ALLOWED_CONTEXTS:-}"
ALLOWED=("${DEFAULT_ALLOWED_CONTEXTS[@]}" "${EXTRA_ALLOWED[@]}")

CONTEXT_OK=0
for allowed in "${ALLOWED[@]}"; do
  [ -z "$allowed" ] && continue
  if [ "$CONTEXT" = "$allowed" ]; then CONTEXT_OK=1; break; fi
done

# Belt-and-suspenders: even with an explicit allowlist override, hard-deny
# any context that looks like prod by pattern.
case "$CONTEXT" in
  *_clerum|*-prod|*prod-*|*production*)
    die "REFUSING to seed against context '$CONTEXT' — matches prod pattern. This script is dev-only by design."
    ;;
esac

if [ "$CONTEXT_OK" -ne 1 ] && is_branch_scoped_minikube_context; then
  CONTEXT_OK=1
fi

if [ "$CONTEXT_OK" -ne 1 ]; then
  die "Context '$CONTEXT' is not in the non-prod allowlist. Allowed: ${ALLOWED[*]}. Set ALLOWED_CONTEXTS=... to extend (never add prod)."
fi
ok "Context '$CONTEXT' is in the non-prod allowlist"

# Only the e2e seed profile gets a known default. The minimal profile requires
# the user to supply ADMIN_PASSWORD (full-setup.sh Step 1), so no default
# password ships. :274 below still hard-fails when neither applies.
if [ -z "$ADMIN_PASSWORD" ] && is_minikube_context && [ "${SEED_PROFILE:-e2e}" = "e2e" ]; then
  ADMIN_PASSWORD="$(printf '%s%s' 'changeme123' '!')"
  DESKTOP_LOGIN_CREDENTIAL="$ADMIN_PASSWORD"
fi

[ -n "$ADMIN_PASSWORD" ] || die "ADMIN_PASSWORD is required (GitHub Secret E2E_ADMIN_PASSWORD in CI)"

# ─── Pre-flight: service must exist ────────────────────────────────────
$KC -n "$CONTROL_API_NS" get svc "$CONTROL_API_SVC" >/dev/null 2>&1 \
  || die "Service $CONTROL_API_NS/$CONTROL_API_SVC not found on $CONTEXT"

# ─── Port-forwards (trap cleanup on any exit path) ─────────────────────
CAPI_PF_PID=""
AUTH_COOKIE_JAR="$(mktemp "${TMPDIR:-/tmp}/clerum-seed-admin-cookie.XXXXXX")"
AUTH_HEADER_FILE="$(mktemp "${TMPDIR:-/tmp}/clerum-seed-admin-headers.XXXXXX")"
ADMIN_SESSION_COOKIE=""
cleanup() {
  [ -n "$CAPI_PF_PID" ] && kill "$CAPI_PF_PID" >/dev/null 2>&1 || true
  [ -n "$AUTH_COOKIE_JAR" ] && rm -f "$AUTH_COOKIE_JAR" >/dev/null 2>&1 || true
  [ -n "$AUTH_HEADER_FILE" ] && rm -f "$AUTH_HEADER_FILE" >/dev/null 2>&1 || true
}
trap cleanup EXIT INT TERM

wait_for_port() {
  local port="$1" attempts=0
  while [ "$attempts" -lt 30 ]; do
    if (echo > "/dev/tcp/127.0.0.1/$port") >/dev/null 2>&1; then return 0; fi
    sleep 0.5; attempts=$((attempts + 1))
  done
  return 1
}

log "Starting control-api port-forward ($CONTEXT)"
$KC -n "$CONTROL_API_NS" port-forward "svc/$CONTROL_API_SVC" \
  "$CONTROL_API_LOCAL_PORT:8090" >/dev/null 2>&1 &
CAPI_PF_PID=$!

wait_for_port "$CONTROL_API_LOCAL_PORT" \
  || die "port-forward to $CONTROL_API_NS/$CONTROL_API_SVC:8090 did not come up"
ok "port-forward ready (capi=$CONTROL_API_LOCAL_PORT)"

CAPI_BASE="http://127.0.0.1:${CONTROL_API_LOCAL_PORT}/api/v1"

capture_admin_session_cookie() {
  local header lower cookie
  ADMIN_SESSION_COOKIE=""
  while IFS= read -r header; do
    header="${header%$'\r'}"
    lower="$(printf '%s' "$header" | tr '[:upper:]' '[:lower:]')"
    case "$lower" in
      set-cookie:*)
        cookie="${header#*:}"
        cookie="${cookie#"${cookie%%[![:space:]]*}"}"
        case "$cookie" in
          control_ui_admin_session=*)
            ADMIN_SESSION_COOKIE="${cookie#control_ui_admin_session=}"
            ADMIN_SESSION_COOKIE="${ADMIN_SESSION_COOKIE%%;*}"
            ;;
        esac
        ;;
    esac
  done < "$AUTH_HEADER_FILE"

  [ -n "$ADMIN_SESSION_COOKIE" ] || return 1

  # Control API sets Secure cookies in production, but this script reaches it
  # through a local HTTP port-forward. Write a local-only jar entry so curl
  # sends the authenticated cookie back to 127.0.0.1 without exposing the value
  # in process arguments.
  {
    printf '# Netscape HTTP Cookie File\n'
    printf '127.0.0.1\tFALSE\t/\tFALSE\t0\tcontrol_ui_admin_session\t%s\n' \
      "$ADMIN_SESSION_COOKIE"
  } > "$AUTH_COOKIE_JAR"
}

AUTH_CURL=(-b "$AUTH_COOKIE_JAR" -c "$AUTH_COOKIE_JAR" -H 'Content-Type: application/json')

admin_get() {
  local url="$1" label="$2"
  local resp code
  resp="$(curl -sS -w '\n%{http_code}' "$url" "${AUTH_CURL[@]}" || true)"
  code="$(echo "$resp" | tail -n1)"
  if [[ "$code" =~ ^2 ]]; then
    ADMIN_GET_BODY="$(echo "$resp" | sed '$d')"
  else
    die "$label → $code body=$(echo "$resp" | sed '$d')"
  fi
}

login_admin_only() {
  local resp body code
  log "Admin login as '$ADMIN_USERNAME'"
  : > "$AUTH_HEADER_FILE"
  resp="$(curl -sS -w '\n%{http_code}' -D "$AUTH_HEADER_FILE" \
    -X POST "$CAPI_BASE/admin/auth/login" \
    -H 'Content-Type: application/json' \
    -d "$(jq -cn --arg u "$ADMIN_USERNAME" --arg p "$ADMIN_PASSWORD" \
      '{username: $u, password: $p}')" || true)"
  body="$(echo "$resp" | sed '$d')"
  code="$(echo "$resp" | tail -n1)"
  if ! [[ "$code" =~ ^2 ]]; then
    die "Admin login failed (status=$code body=$body)"
  fi
  capture_admin_session_cookie || die "Admin login did not return an admin session cookie"
  ok "Admin session cookie obtained"
}

perform_initial_setup() {
  local response
  : > "$AUTH_HEADER_FILE"
  response="$(curl -sS -w '\n%{http_code}' -D "$AUTH_HEADER_FILE" \
    -X POST "$CAPI_BASE/admin/auth/setup" \
    -H 'Content-Type: application/json' \
    -d "$(jq -cn --arg e "$ADMIN_EMAIL" --arg u "$ADMIN_USERNAME" --arg p "$ADMIN_PASSWORD" \
      '{email: $e, username: $u, password: $p}')" || true)"
  SETUP_BODY="$(echo "$response" | sed '$d')"
  SETUP_CODE="$(echo "$response" | tail -n1)"
}

verify_minimal_operator_bootstrap() {
  local admin_count admin_id status source desktop_user_id link_admin_id
  ADMIN_GET_BODY=""
  admin_get "$CAPI_BASE/admin/control-admins" "GET /admin/control-admins"
  admin_count="$(echo "$ADMIN_GET_BODY" | jq -r --arg username "$ADMIN_USERNAME" --arg email "$ADMIN_EMAIL" \
    '[.admins[]? | select(.username == $username and ((.email // "") | ascii_downcase) == $email)] | length')"
  if [ "$admin_count" != "1" ]; then
    die "Minimal bootstrap did not produce exactly one admin '$ADMIN_USERNAME' with email '$ADMIN_EMAIL'"
  fi
  admin_id="$(echo "$ADMIN_GET_BODY" | jq -r --arg username "$ADMIN_USERNAME" --arg email "$ADMIN_EMAIL" \
    '.admins[] | select(.username == $username and ((.email // "") | ascii_downcase) == $email) | .id // empty')"
  status="$(echo "$ADMIN_GET_BODY" | jq -r --arg username "$ADMIN_USERNAME" --arg email "$ADMIN_EMAIL" \
    '.admins[] | select(.username == $username and ((.email // "") | ascii_downcase) == $email) | .gfsOperatorLink.status // "missing"')"
  source="$(echo "$ADMIN_GET_BODY" | jq -r --arg username "$ADMIN_USERNAME" --arg email "$ADMIN_EMAIL" \
    '.admins[] | select(.username == $username and ((.email // "") | ascii_downcase) == $email) | .gfsOperatorLink.source // "missing"')"
  desktop_user_id="$(echo "$ADMIN_GET_BODY" | jq -r --arg username "$ADMIN_USERNAME" --arg email "$ADMIN_EMAIL" \
    '.admins[] | select(.username == $username and ((.email // "") | ascii_downcase) == $email) | .gfsOperatorLink.desktopUserId // empty')"
  link_admin_id="$(echo "$ADMIN_GET_BODY" | jq -r --arg username "$ADMIN_USERNAME" --arg email "$ADMIN_EMAIL" \
    '.admins[] | select(.username == $username and ((.email // "") | ascii_downcase) == $email) | .gfsOperatorLink.controlAdminId // empty')"
  if ! clerum_initial_setup_link_matches "$status" "$source" "$desktop_user_id" "$link_admin_id" "$admin_id"; then
    # Recovery is only possible by rebuilding the control DB. control-api
    # stamps last_login_at on every successful admin login and
    # setupInitialAdminCredentials only matches a bootstrap row whose
    # last_login_at is still NULL, so once a cluster has logged in without
    # consuming setup the initial_setup link can never be created on that
    # database. Say so instead of leaving the operator with a bare refusal.
    die "Minimal bootstrap is incomplete: expected one active initial_setup Desktop link for '$ADMIN_EMAIL' (status=$status source=$source desktopUserId=${desktop_user_id:-missing} controlAdminId=${link_admin_id:-missing}); refusing ordinary-user fallback. This cluster consumed or bypassed /admin/auth/setup without creating the link, and it cannot be created on the existing database. Rebuild the control DB to recover: re-run 'make minikube-setup' without REUSE_DB/--keep-db (the default rebuilds the DB), passing CONTROL_DB_RESET_PVC_UID when the setup script asks for it."
  fi
  ok "Initial admin '$ADMIN_USERNAME' has active initial_setup Desktop operator link (desktopUserId=${desktop_user_id:0:8}…)"
}

login_first_legacy() {
  local response body code
  log "Admin login as '$ADMIN_USERNAME'"
  : > "$AUTH_HEADER_FILE"
  response="$(curl -sS -w '\n%{http_code}' -D "$AUTH_HEADER_FILE" \
    -X POST "$CAPI_BASE/admin/auth/login" \
    -H 'Content-Type: application/json' \
    -d "$(jq -cn --arg u "$ADMIN_USERNAME" --arg p "$ADMIN_PASSWORD" \
      '{username: $u, password: $p}')" || true)"
  body="$(echo "$response" | sed '$d')"
  code="$(echo "$response" | tail -n1)"
  if [[ "$code" =~ ^2 ]]; then
    capture_admin_session_cookie || die "Admin login did not return an admin session cookie"
    ok "Admin session cookie obtained"
    return
  fi
  if [ "$code" != "401" ]; then
    die "Admin login failed (status=$code body=$body)"
  fi
  log "Login did not return an admin session; attempting first-time bootstrap"
  perform_initial_setup
  if [ "$SETUP_CODE" = "409" ]; then
    die "Admin already exists but login failed — ADMIN_PASSWORD is wrong for user '$ADMIN_USERNAME'"
  fi
  if ! [[ "$SETUP_CODE" =~ ^2 ]]; then
    die "Bootstrap failed (status=$SETUP_CODE body=$SETUP_BODY)"
  fi
  capture_admin_session_cookie || die "Bootstrap did not return an admin session cookie"
  ok "Bootstrapped initial admin '$ADMIN_USERNAME'"
}

# ─── Step 1: Bootstrap before login for the minimal self-hosted path ───
# A fresh DB contains a technical bootstrap admin whose password already
# matches ADMIN_PASSWORD. Login-first therefore consumes the one-shot setup
# eligibility, then the normal /admin/users fallback creates an ordinary
# Desktop member without the governed initial_setup operator link. Minimal
# installs must consume setup first; reruns may fall back to login only after
# proving that the active initial_setup link still exists.
if [ "$SEED_PROFILE" = "minimal" ]; then
  log "Minimal self-hosted bootstrap: attempting /admin/auth/setup before any admin login"
  perform_initial_setup
  setup_outcome="$(clerum_minimal_setup_outcome "$SETUP_CODE")"
  if [ "$setup_outcome" = "setup_succeeded" ]; then
    capture_admin_session_cookie || die "Bootstrap did not return an admin session cookie"
    ok "Bootstrapped initial admin '$ADMIN_USERNAME' with Desktop workspace"
  elif [ "$setup_outcome" = "setup_already_consumed" ]; then
    log "Initial setup already consumed; validating the existing governed link after login"
    login_admin_only
  else
    die "Bootstrap failed (status=$SETUP_CODE body=$SETUP_BODY)"
  fi
  verify_minimal_operator_bootstrap
else
  login_first_legacy
fi

admin_post() {
  local url="$1" body="$2" label="$3"
  local resp code
  resp="$(curl -sS -w '\n%{http_code}' -X POST "$url" "${AUTH_CURL[@]}" -d "$body" || true)"
  code="$(echo "$resp" | tail -n1)"
  if [[ "$code" =~ ^2 ]]; then
    ADMIN_POST_BODY="$(echo "$resp" | sed '$d')"
    ok "$label → $code"
  else
    die "$label → $code body=$(echo "$resp" | sed '$d')"
  fi
}

admin_put() {
  local url="$1" body="$2" label="$3"
  local resp code
  resp="$(curl -sS -w '\n%{http_code}' -X PUT "${url}" "${AUTH_CURL[@]}" -d "${body}" || true)"
  code="$(echo "${resp}" | tail -n1)"
  if [[ "${code}" =~ ^2 ]]; then
    ADMIN_PUT_BODY="$(echo "${resp}" | sed '$d')"
    ok "${label} → ${code}"
  else
    die "${label} → ${code} body=$(echo "${resp}" | sed '$d')"
  fi
}

put_json() {
  local url="$1" body="$2" label="$3"
  local resp code
  resp="$(curl -sS -w '\n%{http_code}' -X PUT "$url" "${AUTH_CURL[@]}" -d "$body" || true)"
  code="$(echo "$resp" | tail -n1)"
  if [[ "$code" =~ ^2 ]]; then
    ok "$label → $code"
  else
    die "$label → $code body=$(echo "$resp" | sed '$d')"
  fi
}

# CAS-aware agent-grant replace. The admin agents endpoints
# (control-api routes/admin/agentGrants.ts) guard writes with a compare-and-swap:
# the body must carry expectedCurrentAgentNames, or the server rejects it with
# 428 agent_grant_precondition_required. We GET the current grant first and send
# its full stored set (active + deleted history) as the precondition, which keeps
# the seed idempotent across re-runs. (The parallel contexts endpoints have no
# such guard, so those still use put_json directly.)
put_agents() {
  local url="$1" agent="$2" label="$3"
  ADMIN_GET_BODY=""
  admin_get "$url" "GET $label"
  local expected
  expected="$(echo "$ADMIN_GET_BODY" | jq -c '([.agentNames[]?] + [.deletedAgentNames[]?])')"
  put_json "$url" \
    "$(jq -cn --arg a "$agent" --argjson e "$expected" \
        '{agentNames: [$a], expectedCurrentAgentNames: $e}')" \
    "$label"
}

ensure_seed_user_and_team() {
  local email="$1"
  local name="$2"
  local team_name="${name} team"
  email="$(clerum_canonical_email "$email")"

  ADMIN_GET_BODY=""
  admin_get "$CAPI_BASE/admin/users?$(jq -rn --arg q "$email" '$q|@uri' | sed 's/^/q=/')" \
    "GET /admin/users"
  ENSURE_USER_ID="$(echo "$ADMIN_GET_BODY" | jq -r --arg e "$email" \
    '.items[]? | select((.email // "") == $e) | .id' | head -n1)"

  if [ -z "$ENSURE_USER_ID" ]; then
    admin_post "$CAPI_BASE/admin/users" \
      "$(jq -cn --arg e "$email" --arg n "$name" '{email: $e, name: $n}')" \
      "POST /admin/users"
    ENSURE_USER_ID="$(echo "$ADMIN_POST_BODY" | jq -r '.id // empty')"
  fi
  [ -n "$ENSURE_USER_ID" ] || die "Could not create or find user $email"
  ok "User  $email (id=${ENSURE_USER_ID:0:8}…)"

  ADMIN_GET_BODY=""
  admin_get "$CAPI_BASE/admin/users/$ENSURE_USER_ID/teams" \
    "GET /admin/users/:userId/teams"
  ENSURE_TEAM_ID="$(echo "$ADMIN_GET_BODY" | jq -r '.items[0].id // empty')"

  if [ -z "$ENSURE_TEAM_ID" ]; then
    admin_post "$CAPI_BASE/admin/teams" \
      "$(jq -cn --arg u "$ENSURE_USER_ID" --arg n "$team_name" '{userId: $u, name: $n}')" \
      "POST /admin/teams"
    ENSURE_TEAM_ID="$(echo "$ADMIN_POST_BODY" | jq -r '.id // empty')"
  fi
  [ -n "$ENSURE_TEAM_ID" ] || die "Could not create or find team for $email"
  ok "Team  id=${ENSURE_TEAM_ID:0:8}…"
}

# ─── Step 2: Persist users + teams through admin control-api ───────────
log "Ensuring seeded users through admin control-api"
ensure_seed_user_and_team "$DEV_EMAIL" "$DEV_NAME"
USER_ID="$ENSURE_USER_ID"
TEAM_ID="$ENSURE_TEAM_ID"

# ─── Step 3: Idempotent user↔agent and user↔context bindings ───────────

log "Binding user $DEV_EMAIL ↔ agent=$AGENT_NAME, context=$CONTEXT_ID"
put_agents "$CAPI_BASE/admin/users/$USER_ID/agents" "$AGENT_NAME" \
  "PUT /admin/users/:userId/agents"

put_json "$CAPI_BASE/admin/users/$USER_ID/contexts" \
  "$(jq -cn --arg c "$CONTEXT_ID" '{contextIds: [$c]}')" \
  "PUT /admin/users/:userId/contexts"

# ─── Step 4: Team-level bindings (if the user has a team) ──────────────
if [ -n "$TEAM_ID" ]; then
  log "Binding team ${TEAM_ID:0:8}… ↔ agent=$AGENT_NAME, context=$CONTEXT_ID"
  put_agents "$CAPI_BASE/admin/teams/$TEAM_ID/agents" "$AGENT_NAME" \
    "PUT /admin/teams/:teamId/agents"
  put_json "$CAPI_BASE/admin/teams/$TEAM_ID/contexts" \
    "$(jq -cn --arg c "$CONTEXT_ID" '{contextIds: [$c]}')" \
    "PUT /admin/teams/:teamId/contexts"
fi

# ─── Step 5: Persist second user + team through admin control-api ──────
# Gated on SEED_SECOND_E2E_USER (see definition near the top of this file):
# the minimal profile must not seed [email protected] at all.
if [ "$SEED_SECOND_E2E_USER" = "true" ]; then
  ensure_seed_user_and_team "$DEV_EMAIL_2" "$DEV_NAME_2"
  USER_ID_2="$ENSURE_USER_ID"
  TEAM_ID_2="$ENSURE_TEAM_ID"

  # ─── Step 6: Idempotent user2↔agent and user2↔context bindings ───────
  log "Binding user $DEV_EMAIL_2 ↔ agent=$AGENT_NAME, context=$CONTEXT_ID"
  put_agents "$CAPI_BASE/admin/users/$USER_ID_2/agents" "$AGENT_NAME" \
    "PUT /admin/users/:userId2/agents"

  put_json "$CAPI_BASE/admin/users/$USER_ID_2/contexts" \
    "$(jq -cn --arg c "$CONTEXT_ID" '{contextIds: [$c]}')" \
    "PUT /admin/users/:userId2/contexts"

  # ─── Step 7: Team-level bindings for second user (if the user has a team)
  if [ -n "$TEAM_ID_2" ]; then
    log "Binding team ${TEAM_ID_2:0:8}… ↔ agent=$AGENT_NAME, context=$CONTEXT_ID"
    put_agents "$CAPI_BASE/admin/teams/$TEAM_ID_2/agents" "$AGENT_NAME" \
      "PUT /admin/teams/:teamId2/agents"
    put_json "$CAPI_BASE/admin/teams/$TEAM_ID_2/contexts" \
      "$(jq -cn --arg c "$CONTEXT_ID" '{contextIds: [$c]}')" \
      "PUT /admin/teams/:teamId2/contexts"
  fi
else
  log "Skipping second E2E user $DEV_EMAIL_2 (SEED_PROFILE=minimal) — minimal profile seeds nothing named test*"
fi

seed_desktop_login_if_enabled

# Plugin Workload SDK demo grants exist for the grant-driven sandbox-ui
# notification recipe, which the "clientNotifications" grant wires to BOTH
# seeded users (see seed_plugin_sdk_demo_grants_if_enabled above). Gate the
# whole call on SEED_SECOND_E2E_USER: under minimal there is no second user
# to grant, and the demo recipe itself isn't deployed either (full-setup.sh
# only applies deploy/overlays/minikube/instances-e2e/ under SEED_PROFILE=e2e).
if [ "$SEED_SECOND_E2E_USER" = "true" ]; then
  seed_plugin_sdk_demo_grants_if_enabled
else
  log "Skipping Plugin Workload SDK demo grants (SEED_PROFILE=minimal) — the grant-driven sandbox-ui notification recipe is e2e-only and needs both seeded users"
fi

echo ""
echo -e "${GREEN}[seed] Done.${NC} $DEV_EMAIL → agent=$AGENT_NAME, context=$CONTEXT_ID (cluster=$CONTEXT)"
if [ "$SEED_SECOND_E2E_USER" = "true" ]; then
  echo -e "${GREEN}[seed] Done.${NC} $DEV_EMAIL_2 → agent=$AGENT_NAME, context=$CONTEXT_ID (cluster=$CONTEXT)"
fi