medium priority low complexity deployment pending devops specialist Tier 7

Acceptance Criteria

A deployment shell script exists at scripts/deploy-badge-criteria-edge-function.sh that executes the full deploy sequence with a single command
Script deploys the edge function using `supabase functions deploy badge-criteria-edge-function --no-verify-jwt` (or with JWT verification as per team standard)
Script validates that required environment secrets (SUPABASE_URL, SUPABASE_SERVICE_ROLE_KEY, FCM_SERVICE_ACCOUNT_JSON, FCM_PROJECT_ID) are set before deploying and exits with error code 1 if any are missing
Script verifies the database webhook pointing to the edge function exists after deploy by querying Supabase webhook configuration via the management API
A smoke test step in the script invokes the deployed function with a synthetic test payload and asserts a 200 response within 5 seconds
A runbook document at docs/runbooks/badge-criteria-edge-function.md covers: deploy steps, rollback procedure, log query commands, and 5 common failure scenarios with resolution steps
Rollback procedure documents how to redeploy the previous function version using a tagged git SHA
Log query commands use the Supabase CLI log streaming syntax and include a sample query filtering badge_evaluation_logs by org_id and date range
The runbook documents the webhook trigger configuration (table: activities, event: INSERT) for re-registration if lost
Script and runbook are reviewed and approved by at least one other team member before merge (checklist item in PR template)

Technical Requirements

frameworks
Supabase CLI
Bash (POSIX-compatible shell script)
apis
Supabase Management API (webhook verification)
Supabase Edge Functions REST API (smoke test invoke)
Firebase Cloud Messaging (FCM) API v1 (credentials configuration)
data models
badge_evaluation_logs
bufdir_export_audit_log
performance requirements
Full deploy script must complete within 3 minutes under normal network conditions
Smoke test assertion must timeout and fail fast if function does not respond within 5 seconds
security requirements
Deploy script must not echo or print secret values — only confirm their presence using `[ -z "$VAR" ]` checks
FCM_SERVICE_ACCOUNT_JSON must be stored as a Supabase secret (supabase secrets set), never written to disk during deploy
Script must be executable only by users with Supabase project owner role
Runbook must explicitly warn against using production service role key in local test environments

Execution Context

Execution Tier
Tier 7

Tier 7 - 84 tasks

Can start after Tier 6 completes

Implementation Notes

Structure the deploy script with clearly separated phases: (1) pre-flight checks (env var validation), (2) deploy, (3) webhook verification, (4) smoke test. Use `set -euo pipefail` at the top of the bash script for strict error handling. For webhook verification, use the Supabase Management API (`/v1/projects/{ref}/database/webhooks`) with the project ref and service role to list webhooks and grep for the badge-criteria-edge-function URL. Smoke test payload should use a known test peer_mentor_id from the seed database (document which UUID to use).

The runbook should include a quick-reference table at the top: symptom → likely cause → resolution step. For the rollback section, document the `git tag` naming convention used in the project and the exact `supabase functions deploy` command with `--import-map` if applicable. Include estimated resolution times for each failure scenario to help on-call engineers prioritize.

Testing Requirements

Script testing: (1) run script with a missing environment variable and assert exit code 1 with descriptive error message, (2) run script in dry-run mode (if implemented) and assert it prints all steps without executing, (3) run smoke test step against a deployed staging function and assert 200 response. Runbook review: have a team member unfamiliar with the edge function follow the rollback procedure in staging and confirm it succeeds. Verify all log query commands in the runbook execute without syntax errors against the staging Supabase instance.

Component
Badge Criteria Edge Function
infrastructure medium
Epic Risks (3)
medium impact medium prob technical

Supabase Edge Functions may experience cold start latency of 500ms–2s when they have not been invoked recently. If evaluation latency consistently exceeds the 2-second UI expectation, the celebration overlay timing SLA cannot be met without the optimistic UI fallback from the UI epic.

Mitigation & Contingency

Mitigation: Keep the edge function warm by scheduling a lightweight health-check invocation every 5 minutes in production. Optimise the function size to minimise Deno module load time. Implement the optimistic UI path in badge-bloc (from the UI epic) as the primary UX path so cold start only affects server-side reconciliation, not perceived responsiveness.

Contingency: If cold starts remain problematic, migrate badge evaluation to a Supabase database function (pl/pgsql) triggered directly by a database trigger on activity insert, eliminating the Edge Function overhead entirely for the evaluation logic while keeping Edge Function only for FCM notification dispatch.

high impact low prob integration

Supabase database webhooks can fail silently if the edge function returns a non-2xx response or times out. A missed webhook means a peer mentor does not receive a badge they earned, which is both a functional defect and a trust issue for organisations relying on milestone tracking.

Mitigation & Contingency

Mitigation: Implement idempotent webhook processing: the edge function reads the activity ID from the webhook payload and checks whether evaluation for this activity has already run (via an audit log query) before proceeding. Add Supabase webhook retry configuration (3 retries with exponential backoff). Monitor webhook failure rates via Supabase logs alert.

Contingency: Implement a nightly reconciliation job (Supabase scheduled function) that scans all activities from the past 24 hours, re-evaluates badge criteria for any peer mentor with no corresponding evaluation log entry, and awards any missing badges. Alert operations if reconciliation awards more than 5% of badges, indicating systematic webhook failure.

high impact low prob security

The evaluation service loads badge definitions per organisation, but a misconfigured RLS policy or incorrect organisation scoping in the edge function could cause one organisation's badge criteria to be evaluated against another organisation's peer mentor activity data, leading to incorrect or cross-contaminated badge awards.

Mitigation & Contingency

Mitigation: The edge function must extract organisation_id from the webhook payload activity record and pass it explicitly to every database query. Write a security test that seeds two organisations with distinct badge definitions and verifies that evaluating a peer mentor in org A never reads or awards org B definitions. Use Supabase service role key only within the edge function, never the anon key.

Contingency: If cross-org contamination is detected in audit logs, immediately disable the edge function webhook, run a targeted SQL query to identify and revoke incorrectly awarded badges, notify affected organisations, and perform a full security review of all RLS policies on badge-related tables before re-enabling.