Skip to content

Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.

feat(gcp): spend dashboard, budget-alert tests, and burn-observability ops docs

fudjiafdc1e5990c13
diff --git a/docs/gcp-credits.md b/docs/gcp-credits.md
index 36b7c7128..fd21fc86b 100644
--- a/docs/gcp-credits.md
+++ b/docs/gcp-credits.md
@@ -281,6 +281,82 @@ back out.
---
+## Vertex Claude LLM lane (chat & completions) — prompt 02
+
+Routes the platform's Claude/Anthropic LLM traffic through Vertex AI so it bills
+the GCP credit pool instead of a paid Anthropic key. Wired across **every** text
+inference surface, behind two flags, with automatic fallthrough to the existing
+free-first chain on any Vertex failure. Flags off ⇒ behavior is byte-identical to
+before (proven by `tests/vertex-claude.test.js`).
+
+### Flags
+
+| Env var | Effect |
+|---|---|
+| `VERTEX_CLAUDE_ENABLED=1` | Vertex becomes an available Anthropic transport. In `llm.js`/`api/chat.js` it sits in the paid tier **ahead of** first-party Anthropic (GCP credits before a paid key); in `api/llm/anthropic.js` any `provider: anthropic` model streams from Vertex with first-party as the fallback; `/api/brain/chat` gains selectable "· Vertex" Claude rows. |
+| `VERTEX_CLAUDE_PRIMARY=1` | Chain inversion: Vertex Claude is tried **first**, before the free lanes — the platform's default brain becomes real Claude on Vertex. Requires `VERTEX_CLAUDE_ENABLED`. A caller BYOK key still leads (their own billing choice). |
+
+Both require `GOOGLE_CLOUD_PROJECT` (config check). Location: `GOOGLE_CLOUD_LOCATION_CLAUDE`
+(default `global`). Both unset ⇒ zero code-path change.
+
+### Wire format & model mapping
+
+Vertex speaks the Anthropic Messages API with four differences, all handled in
+`api/_lib/vertex-claude.js` (the one shared module — never scatter this):
+
+- Model id in the **URL path**, not the body: `…/publishers/anthropic/models/<id>:streamRawPredict` (stream) / `:rawPredict` (non-stream). Regional endpoints prefix the host (`us-east5-aiplatform.googleapis.com`); `global` uses the bare host.
+- Body gains `"anthropic_version": "vertex-2023-10-16"` and drops `model` (+ `stream`).
+- Auth: `Authorization: Bearer <oauth>` (via `api/_lib/gcp-auth.js` — shared with Imagen) — no `x-api-key`, no `anthropic-version` header.
+- Model id: bare aliases pass through (`claude-sonnet-4-6`); a dated first-party id converts to the `@` form (`claude-haiku-4-5-20251001` → `claude-haiku-4-5@20251001`) via `toVertexModelId()`.
+
+SSE event shapes are identical to first-party, so every existing stream parser works unchanged.
+
+### Surfaces wired
+
+| Surface | Entry point | How Vertex is chosen |
+|---|---|---|
+| Server one-shot completions (agent talk/delegation, personas, x402, crons, vision) | `api/_lib/llm.js` `providerChain()` | `vertexAnthropicProvider()` inserted per flags |
+| Embedded avatar/agent chat widgets (streaming) | `api/llm/anthropic.js` | `provider: anthropic` models routed to Vertex `streamRawPredict`; `x-llm-transport` response header records the transport |
+| Main viewer/agent chat (streaming) | `api/chat.js` `providerOrder()` | synthetic `vertex` provider injected into the ladder |
+| `/brain` comparison page | `api/brain/chat.js` | "Claude … · Vertex" specs via `streamVertex()` |
+
+### Telemetry marker
+
+Vertex traffic is recorded as provider **`vertex-anthropic`** distinctly from
+first-party `anthropic` (in `recordEvent` for `llm.js`/`api/llm/anthropic.js`, and
+`meta.provider` for `api/chat.js` via `route.via`), so prompt 07's spend reporting
+attributes it. The embed proxy also returns an `x-llm-transport: vertex-anthropic`
+response header.
+
+### Smoke test (needs a running dev server + creds)
+
+`scripts/gcp/vertex-llm-smoke.mjs` hits three live surfaces and asserts Vertex served
+each. (Distinct from prompt 01's `vertex-smoke.mjs`, which is a single raw Claude call.)
+
+```bash
+GOOGLE_CLOUD_PROJECT=aerial-vehicle-466722-p5 \
+GCP_SERVICE_ACCOUNT_JSON="$(cat /path/to/vercel-inference-key.json)" \
+VERTEX_CLAUDE_ENABLED=1 VERTEX_CLAUDE_PRIMARY=1 npm run dev # terminal 1
+
+node scripts/gcp/vertex-llm-smoke.mjs # terminal 2
+# (a) POST /api/forge-enhance → asserts provider=vertex-anthropic
+# (b) POST /api/llm/anthropic → asserts x-llm-transport=vertex-anthropic (set SMOKE_AGENT_ID)
+# (c) POST /api/chat → asserts done.provider=vertex (set SMOKE_BEARER)
+```
+
+Browser verification (definition of done): with the flags on, open an embedded agent
+widget page and the main chat, send messages, confirm streamed replies + no console
+errors + `vertex-anthropic` in server logs; then unset the flags and confirm today's
+behavior is intact.
+
+### Deploy & rollback
+
+- **Preview first:** set `VERTEX_CLAUDE_ENABLED=1` (and optionally `VERTEX_CLAUDE_PRIMARY=1`) in Vercel **preview** only. Production flags stay unset — flipping production changes the billing lane and is the owner's call.
+- **Production flip (owner):** `printf '1' | vercel env add VERTEX_CLAUDE_ENABLED production` (+ `VERTEX_CLAUDE_PRIMARY` for chain inversion), then redeploy.
+- **Rollback (instant, no code deploy):** unset `VERTEX_CLAUDE_ENABLED` / `VERTEX_CLAUDE_PRIMARY`. Every lane falls through to Groq → OpenRouter → NVIDIA → paid backstop exactly as before.
+
+---
+
## Vertex image lane (text→3D reference images) — prompt 03
The forge text→3D chain synthesizes a reference image, then reconstructs a GLB
@@ -552,3 +628,387 @@ Firestore `(default)` DB or the GCP project (prints the commands for both).
- **Then:** `scripts/gcp/teardown.sh --apply` to delete the idle resources and zero the bill.
_Revert section last verified against source: 2026-07-06._
+
+---
+
+## GPU worker fleet — self-hosted 3D stack (prompt 04)
+
+Deploys the six Cloud Run L4 GPU workers that back the forge lanes so the paid
+lane stops paying Replicate and the free lane stops being throttled by hosted
+NVIDIA NIM: **TRELLIS** (text/image→3D), **Hunyuan3D**, **TripoSG** (sketch→3D),
+**TripoSR** (fast mesh), **UniRig** (auto-rig), **text2motion**. Everything
+reverts by unsetting env URLs and the `FORGE_SELFHOST_PRIMARY` flag.
+
+> **Status: code wired & tested; deploy blocked on the same gcloud reauth as the
+> foundation above.** The router flag, raised free-lane ceilings, and their tests
+> are landed and green. The six `gcloud builds submit` deploys, weight staging,
+> Vercel env wiring, and E2E verification all need live GCP auth (**Pending human
+> actions**, step 1). Latency/cost cells below are **pre-deploy estimates** — the
+> exact command to replace them with measured values is in *Cost per asset*.
+
+### Router wiring (landed, flag-gated, OFF by default)
+
+Self-host was already the health-aware default when its worker URLs are set
+(`api/_lib/forge-tiers.js` — `freeLaneCandidates` → `resolveBackendIdWithHealth`).
+Prompt 04 adds one flag that makes the fleet *primary* across every tier/path:
+
+- **`FORGE_SELFHOST_PRIMARY=1`** — `freeLaneCandidates` hoists the self-host lanes
+ (`trellis_selfhost`, `hunyuan3d`, `triposg`) ahead of the hosted free lanes
+ (NVIDIA NIM, HuggingFace) for **text** prompts too (photos already led with
+ self-host, since NIM's preview rejects user images). Stable partition — hosted
+ lanes stay intact as fallthrough. A no-op until the worker URLs are configured
+ (unconfigured lanes are filtered out anyway). `api/_lib/forge-tiers.js`
+ `selfHostPrimary()`.
+- The **fallback ladder is unchanged**: self-host error → hosted NIM / HuggingFace
+ / Replicate exactly as today. The flag only reorders *preference*, never removes
+ a safety net.
+- **Revert:** unset `FORGE_SELFHOST_PRIMARY` (and/or the worker URLs) → today's
+ ordering, no redeploy.
+
+Env vars the router reads for the fleet (all bearer-authed with
+`GCP_RECONSTRUCTION_KEY`):
+
+| Env var | Backend | Forge lane |
+|---|---|---|
+| `MODEL_TRELLIS_URL` | `trellis_selfhost` | free/paid image + text→3D (primary) |
+| `GCP_HUNYUAN3D_URL` | `hunyuan3d` | image→3D failover |
+| `GCP_TRIPOSG_URL` | `triposg` | sketch→3D |
+| `GCP_RECONSTRUCTION_URL` | controller `/reconstruct`, `/rig` | avatar scan + UniRig rigging |
+| `GCP_TEXT2MOTION_URL` | text2motion | text→animation clip |
+| `GCP_RECONSTRUCTION_KEY` | shared bearer | all of the above |
+
+### Per-service Cloud Run config
+
+From each worker's `cloudbuild.yaml`. All are `--gpu=1 --gpu-type=nvidia-l4
+--no-gpu-zonal-redundancy --no-cpu-throttling`, region `us-central1` (co-located
+with `three-ws-model-weights`). Weights mount read-only at `/weights` from the
+bucket; every worker uses the async **`POST` → 202 + poll `GET /tasks/{id}`**
+pattern, so the Cloud Run request timeout does **not** gate generation (the long
+work runs post-response under `--no-cpu-throttling`) — no timeout bump is needed.
+
+| Service | CPU / Mem | min→max inst | `MAX_CONCURRENT` | req timeout |
+|---|---|---|---|---|
+| `model-trellis` | 8 / 32Gi | **1**→2 | 1 | 300s |
+| `model-hunyuan3d` | 8 / 32Gi | 0→3 | 1 | 300s |
+| `model-triposg` | 8 / 32Gi | 0→2 | 1 | 300s |
+| `model-triposr` | 4 / 16Gi | 0→2 | 2 | 120s |
+| `unirig` | 4 / 16Gi | **1**→2 | 1 | 180s |
+| `model-text2motion` | 4 / 16Gi | 0→2 | 2 | 120s |
+
+**Credit-window override — min-instances 1 for `model-trellis` and `unirig`.**
+Cold-start on L4 + model load is brutal and instances are ~free on credits, so
+pin the two hottest lanes warm. This is a *temporary* deploy-time override, not
+baked into `cloudbuild.yaml` (min=1 costs money after the credits expire — prompt
+08 reverts it). `deploy-all.sh` does not pass `_MIN_INSTANCES`, so set it after
+deploy:
+
+```bash
+for S in model-trellis unirig; do
+ gcloud run services update "$S" --region us-central1 --min-instances=1
+done
+# Revert at expiry: same loop with --min-instances=0
+```
+
+### Cost per asset
+
+Full-instance Cloud Run L4 rate (GPU + always-allocated CPU + memory,
+`us-central1`, on-demand): **8 vCPU / 32 GiB + L4 ≈ \$1.69/hr**, **4 vCPU / 16 GiB
++ L4 ≈ \$1.20/hr** (L4 GPU ≈ \$0.71/hr; CPU ≈ \$0.0000240/vCPU·s; mem ≈
+\$0.0000025/GiB·s). Per asset:
+
+```
+$/asset = instance_$per_hr × (warm_seconds_per_asset / 3600)
+```
+
+| Service | instance \$/hr | warm s/asset *(estimate)* | \$/asset *(estimate)* |
+|---|---|---|---|
+| `model-trellis` (image→3D) | 1.69 | ~30–60 | \$0.014–0.028 |
+| `model-hunyuan3d` | 1.69 | ~60–120 | \$0.028–0.056 |
+| `model-triposg` (sketch) | 1.69 | ~20–40 | \$0.009–0.019 |
+| `model-triposr` (fast) | 1.20 | ~5–15 | \$0.002–0.005 |
+| `unirig` (rig) | 1.20 | ~20–60 | \$0.007–0.020 |
+| `model-text2motion` | 1.20 | ~10–30 | \$0.003–0.010 |
+
+> These s/asset values are **pre-deploy estimates** from each model's profile, not
+> measured. Every worker already logs the real figure as `elapsed_ms` on its
+> `GET /tasks/{id}` result and in Cloud Logging. Replace the table with measured
+> warm + cold latency post-deploy:
+> ```bash
+> gcloud run services logs read model-trellis --region us-central1 \
+> --format='value(textPayload)' | grep -oE 'done in [0-9.]+s'
+> ```
+> Prompt 08 uses the measured \$/asset × expected volume for the keep/kill
+> decision at credit expiry.
+
+### Raised free-lane ceilings (landed, flag-gated)
+
+The per-principal free ceiling is 60/h to protect the **rate-limited hosted NIM**
+allocation. With the fleet primary that allocation is out of the path, so
+`FORGE_SELFHOST_PRIMARY=1` raises it (`api/_lib/rate-limit.js` — `FREE_HOURLY_BASE`
+feeds `mcp3dGenerateFree` + `mcp3dGenerateFreeTiered`):
+
+- **Default raised ceiling: 240/h** per principal (4×), tunable via
+ `FORGE_FREE_HOURLY_SELFHOST`.
+- **Math:** credit-window free-image fleet = `trellis_selfhost` (max 2) +
+ `hunyuan3d` (max 3) = **5 concurrent L4 slots** at `MAX_CONCURRENT=1`. At a
+ blended ~60 s/asset that is `5 × 3600/60 ≈ 300 assets/h` global throughput, so a
+ single heavy iterator at 240/h stays under the fleet ceiling while the
+ hosted-NIM-era throttle is removed. **Re-tune `FORGE_FREE_HOURLY_SELFHOST` from
+ the measured s/asset once the fleet is live.**
+- **Untouched — abuse/per-IP gates stay intact regardless of the flag:**
+ `mcp3dGenerate` (30/h per-IP paid, fail-closed), `paidDailyPerClient` (60/day),
+ and the global paid envelope `FORGE_PAID_GLOBAL_HOURLY`.
+- **Revert:** unset `FORGE_SELFHOST_PRIMARY` → back to 60/h.
+
+### Deploy runbook (run once gcloud reauth lands — step 1 above)
+
+```bash
+# 0. Generate + set the shared worker bearer key (Cloud Run reads it from the
+# avatar-reconstruction-key secret; deploy-all.sh creates that secret).
+# Set the SAME value in Vercel as GCP_RECONSTRUCTION_KEY (step 4).
+
+# 1. Stage weights into gs://three-ws-model-weights (once; ~80 GB, gcsfuse mode).
+cd workers/deploy
+HF_TOKEN=hf_xxx SERVICES="hunyuan3d trellis triposr triposg unirig" ./stage-weights.sh
+
+# 2. Check L4 quota FIRST (approval can take days). Need >= 4 concurrent for the
+# warm fleet; deploy what fits now and file an increase for the rest.
+gcloud run regions describe us-central1 2>/dev/null # or Console -> Quotas -> nvidia_l4_gpu_allocation
+
+# 3. Build + deploy the mesh/rig fleet, then text2motion (CPU-path helper script).
+PROJECT_ID=aerial-vehicle-466722-p5 \
+ SERVICES="hunyuan3d trellis triposr triposg unirig" ./deploy-all.sh
+PROJECT_ID=aerial-vehicle-466722-p5 SERVICES="text2motion" ./deploy-editing.sh
+
+# 4. Pin the two hot lanes warm for the credit window (see override above).
+for S in model-trellis unirig; do
+ gcloud run services update "$S" --region us-central1 --min-instances=1; done
+
+# 5. Health-check each service directly with the bearer key.
+KEY=$(gcloud secrets versions access latest --secret=avatar-reconstruction-key)
+for S in model-trellis model-hunyuan3d model-triposg model-triposr unirig model-text2motion; do
+ U=$(gcloud run services describe "$S" --region us-central1 --format='value(status.url)')
+ printf '%s: ' "$S"; curl -fsS -H "authorization: Bearer $KEY" "$U/health" || echo "cold - retry"; echo
+done
+
+# 6. Wire Vercel env (PREVIEW first, then production after E2E passes). Use the
+# URLs printed by deploy-all.sh + the key from step 5.
+for E in preview production; do
+ printf '%s' "$MODEL_TRELLIS_URL" | vercel env add MODEL_TRELLIS_URL $E
+ printf '%s' "$GCP_HUNYUAN3D_URL" | vercel env add GCP_HUNYUAN3D_URL $E
+ printf '%s' "$GCP_TRIPOSG_URL" | vercel env add GCP_TRIPOSG_URL $E
+ printf '%s' "$GCP_RECONSTRUCTION_URL" | vercel env add GCP_RECONSTRUCTION_URL $E
+ printf '%s' "$GCP_TEXT2MOTION_URL" | vercel env add GCP_TEXT2MOTION_URL $E
+ printf '%s' "$KEY" | vercel env add GCP_RECONSTRUCTION_KEY $E
+done
+# Flip self-host primary + raised ceilings ONLY after E2E on preview is green:
+printf '1' | vercel env add FORGE_SELFHOST_PRIMARY preview
+```
+
+### E2E verification (definition of done — real outputs, not 200s)
+
+Run against the preview deploy with the URLs set; inspect the actual GLB/clip.
+
+1. **Text→3D free lane** → `trellis_selfhost` → GLB in R2, opens in the viewer.
+2. **Image→3D** with a real photo (what hosted NIM rejects) → GLB.
+3. **Paid `mesh_forge` chain** (reference image → reconstruction) → GLB, with
+ Cloud Logging showing **no Replicate call** (`FORGE_SELFHOST_PRIMARY=1`).
+4. **Rig** a generated GLB through UniRig `/rig` → animation-ready GLB; load it and
+ confirm the skeleton drives the canonical clips (`src/glb-canonicalize.js`).
+5. **text2motion** → one text→motion generation → clip JSON.
+
+Record measured cold + warm latency per path back into *Cost per asset* above, and
+raise `FORGE_FREE_HOURLY_SELFHOST` from the measured throughput before flipping the
+flag in production.
+
+| Path | cold s | warm s | output verified |
+|---|---|---|---|
+| text→3D (trellis) | _pending_ | _pending_ | _pending_ |
+| image→3D (trellis) | _pending_ | _pending_ | _pending_ |
+| mesh_forge (no Replicate) | _pending_ | _pending_ | _pending_ |
+| rig (unirig) | _pending_ | _pending_ | _pending_ |
+| text2motion | _pending_ | _pending_ | _pending_ |
+
+---
+
+## Spend observability & burn-rate control (prompt 07)
+
+$100k over ~2 months is ~$1,600/day. This section is how we **see** the burn in
+real time, **attribute** it to each lane, **alert** before any lane runs away
+(especially the GPU fleet and Vertex Claude if flipped to primary), and guard the
+opposite failure — credits sitting **unused** at expiry. Everything here is code
+that is live and runnable now; the only blocked step is enabling the BigQuery
+billing export (one console action) and the same gcloud reauth as the foundation.
+
+### The burn report — `scripts/gcp/burn-report.mjs`
+
+Reads the BigQuery billing export and prints an attributed report: credit
+consumed to date, spend by service and by lane label, 7d/30d daily burn, runway,
+projected exhaustion vs expiry, and the under-utilization guard.
+
+```bash
+node scripts/gcp/burn-report.mjs # human-readable
+node scripts/gcp/burn-report.mjs --json # machine-readable (dashboard/cron)
+```
+
+Exit codes: `0` on-track/idle, `2` runaway (for CI/cron alerting), `3` billing
+export not wired, `1` unexpected error. Auth: `GCP_SERVICE_ACCOUNT_JSON` if set,
+else the local `gcloud auth print-access-token` (works after `gcloud auth login`).
+
+Config (env or `.env`):
+
+| Env var | Meaning |
+|---|---|
+| `GOOGLE_CLOUD_PROJECT` | project holding the billing dataset |
+| `GCP_BILLING_DATASET` | BigQuery dataset the export writes to (e.g. `billing_export`) |
+| `GCP_BILLING_TABLE` | full export table — **or** derive it from ↓ |
+| `GCP_BILLING_ACCOUNT_ID` | billing account id; derives `gcp_billing_export_v1_<acct>` |
+| `GCP_BILLING_EXPORT_KIND` | `standard` (default) or `resource` (detailed export) |
+| `GCP_CREDIT_TOTAL_USD` | grant size, e.g. `100000` — enables runway + projection |
+| `GCP_CREDIT_EXPIRY` | ISO date the credits expire — enables the exhaustion-vs-expiry check |
+| `GCP_CREDIT_TYPES` | optional override of the credit-type filter (default: `PROMOTION,FREE_TRIAL,COMMITTED_USAGE_DISCOUNT,SUBSCRIPTION_BENEFIT`) |
+
+Shared implementation: `api/_lib/gcp-billing.js` (BigQuery REST + pure projection
+math, covered by `tests/gcp-billing.test.js`). The cron and the dashboard import
+the same module — one source of truth.
+
+### Enable the BigQuery billing export (owner console action — one time)
+
+The CLI **cannot** enable this; it's console-only.
+
+1. **Billing → Billing export → BigQuery export → Edit settings.**
+2. Enable **Standard usage cost** (and optionally **Detailed usage cost** for
+ resource-level rows). Pick/create a dataset in `aerial-vehicle-466722-p5`
+ (e.g. `billing_export`, location `US`).
+3. Data starts flowing within a few hours (no backfill — it's forward-only).
+4. Set `GCP_BILLING_DATASET` + `GCP_BILLING_ACCOUNT_ID` (or `GCP_BILLING_TABLE`),
+ `GCP_CREDIT_TOTAL_USD=100000`, and `GCP_CREDIT_EXPIRY=<date>` in Vercel (for
+ the cron/dashboard) and locally (for the CLI). Verify: `node scripts/gcp/burn-report.mjs`.
+
+### Resource labeling — `scripts/gcp/label-resources.sh`
+
+Attribution only works if every credit-consuming resource carries
+`program=gcp-credits` + `lane=<name>`. This discovers the Cloud Run fleet, jobs,
+and GCS buckets and (retro-)labels them. Dry-run by default.
+
+```bash
+scripts/gcp/label-resources.sh # dry run — prints the plan
+scripts/gcp/label-resources.sh --apply # write the labels (additive, idempotent)
+```
+
+Lanes: `vertex-claude`, `imagen`, `forge-gpu` (the Cloud Run GPU fleet — default
+for every discovered service), `vanity`. Vertex Claude + Imagen are API-billed
+(no Cloud Run service), so they're attributed by `service.description` in the
+report instead of a label. Edit `LANE_OVERRIDES` in the script for exceptions.
+
+### Budgets & alerts — `scripts/gcp/create-budgets.mjs` + the webhook
+
+```bash
+node scripts/gcp/create-budgets.mjs # dry run — prints the plan
+node scripts/gcp/create-budgets.mjs --apply # create/update budgets (idempotent)
+```
+
+Creates an **overall program budget** (= `GCP_CREDIT_TOTAL_USD`, default $100k)
+with threshold alerts at **25 / 50 / 75 / 90 / 100 %** measured on GROSS spend
+(credits excluded, so it tracks grant consumption), plus **per-service** budgets
+for Vertex AI / Cloud Run / Compute Engine (sized from `GCP_SERVICE_BUDGETS` or
+defaults, service ids resolved live from the billing catalog). All publish to one
+Pub/Sub topic (`GCP_BUDGET_PUBSUB_TOPIC`, default `gcp-budget-alerts`).
+
+**Routing to the team:** the topic pushes to `POST /api/webhooks/gcp-budget-alert`,
+which turns each threshold crossing into a Telegram ping via `sendOpsAlert` — the
+PRIVATE ops chat (`TELEGRAM_ALERTS_CHAT_ID`), **never** the holders' channel.
+Deduped per budget+threshold so each crossing pings once/hour.
+
+Wire the push subscription (owner, after `--apply`):
+
+```bash
+# 1. shared secret the handler checks (constant-time)
+printf '<random-secret>' | vercel env add GCP_BUDGET_WEBHOOK_SECRET production
+# 2. let the budgets SA publish to the topic
+gcloud pubsub topics add-iam-policy-binding gcp-budget-alerts \
+ --project=aerial-vehicle-466722-p5 \
+ --member=serviceAccount:billing-budgets.iam.gserviceaccount.com --role=roles/pubsub.publisher
+# 3. push subscription → the webhook (secret in the query string)
+gcloud pubsub subscriptions create gcp-budget-alerts-push \
+ --project=aerial-vehicle-466722-p5 --topic=gcp-budget-alerts \
+ --push-endpoint="https://three.ws/api/webhooks/gcp-budget-alert?token=<random-secret>"
+```
+
+**Test the alert path** (no live budget needed): publish a synthetic notification —
+
+```bash
+gcloud pubsub topics publish gcp-budget-alerts --project=aerial-vehicle-466722-p5 \
+ --message='{"budgetDisplayName":"gcp-credits — program","alertThresholdExceeded":0.9,"costAmount":90000,"budgetAmount":100000,"currencyCode":"USD"}'
+# → a 🔴 ping lands in the ops chat within seconds.
+```
+
+Handler contract (auth 503/401, threshold gate, dedup) is locked by
+`tests/api/gcp-budget-alert.test.js`.
+
+### Internal spend dashboard — `/dashboard/spend`
+
+Admin-gated page (dashboard-next → nav "GCP Spend", `src/dashboard-next/pages/spend.js`),
+backed by `GET /api/admin/gcp-burn` (session-admin **or** `Bearer $CRON_SECRET`).
+Two cross-referenced views:
+
+- **App-side telemetry** (always live, from `usage_events` + `forge_creations`):
+ per-lane LLM cost/tokens (14d), Vertex Claude spend estimate (30d + 24h, by
+ model), forge generations per backend (self-host flagged), and a daily LLM-cost
+ bar chart. This renders even before the billing export is wired.
+- **Billing ground truth** (best-effort, from `buildBurnReport`): credit consumed,
+ runway, projection vs expiry, credit spend by lane label. Degrades to a designed
+ "not wired" panel when the export is absent — the app-side view still shows.
+
+All states designed (loading skeleton, empty, 401/403 lock, error, populated);
+auto-refreshes every 60s.
+
+### Kill-switches (verified no-deploy env flips)
+
+The GPU fleet and Vertex Claude are the two runaway risks. Each reverts by env
+flag alone — no code deploy:
+
+| Lane | Kill switch | Effect |
+|---|---|---|
+| Vertex Claude | `vercel env rm VERTEX_CLAUDE_PRIMARY production` | chat falls back to free/BYOK lanes instantly (see prompt 02 section) |
+| Forge GPU fleet | `vercel env rm FORGE_SELFHOST_PRIMARY production` | routing stops preferring the self-host GPU workers |
+| Imagen | `vercel env add VERTEX_IMAGEN_ENABLED production` = `0` | text→image drops to the free NIM FLUX lane |
+
+**Fast "stop the bleed now" — `scripts/gcp/emergency-stop.sh`** (dry-run by
+default): drops **every** Cloud Run service + job to `--min-instances=0`, cancels
+in-flight job executions, and prints the flag flips above + the spot/batch stop
+commands. Use this for a runaway during the program; use `revert-to-free.sh`
+(prompt 08) for the planned end-of-program teardown.
+
+```bash
+scripts/gcp/emergency-stop.sh # dry run — shows what it would do
+scripts/gcp/emergency-stop.sh --apply # drop min-instances to 0 across the fleet
+```
+
+### Under-utilization guard + daily cron
+
+The projection flags **`underutilized`** when >30% of the grant is projected to
+expire unused (and **`idle`** when there's no burn at all), with per-lane scale-up
+prompts (flip `VERTEX_CLAUDE_PRIMARY` for production chat, raise seed-batch
+volume, bigger vanity runs). Wasting the credits is a tracked failure mode, not
+just overspend.
+
+**`api/cron/gcp-burn-report.js`** runs daily (`0 14 * * *`, registered in
+`vercel.json`) and pings the ops channel with the day's status — runaway and
+under-utilization get distinct, un-deduped signatures so they always land; an
+on-track day posts a quiet one-line status. If the export isn't wired it says so
+once/day rather than erroring.
+
+### Current status (2026-07-06)
+
+Burn rate, exhaustion projection, and full/unused-credit tracking are **wired and
+tested but not yet reporting real numbers** — they require the BigQuery billing
+export (owner console action above) + the same gcloud reauth that blocks the rest
+of the foundation. The moment the export lands and `GCP_CREDIT_TOTAL_USD` /
+`GCP_CREDIT_EXPIRY` are set, `node scripts/gcp/burn-report.mjs` prints the live
+burn rate and days-of-runway, the dashboard fills in, and the daily cron begins
+posting. Until then the app-side lane telemetry on `/dashboard/spend` is the live
+view. Program budget targets for the alerts: Claude-on-Vertex $40–60k, GPU fleet
+$15–25k, Imagen $3–5k, vanity/observability/misc ~$5k.
+
+_Spend-observability section last verified against source: 2026-07-06._
diff --git a/src/dashboard-next/nav.js b/src/dashboard-next/nav.js
index 43189b68d..fc76eeba8 100644
--- a/src/dashboard-next/nav.js
+++ b/src/dashboard-next/nav.js
@@ -64,6 +64,7 @@ export const NAV = [
// ── Account ─────────────────────────────────────────────────────────
{ path: '/dashboard/systems', label: 'Systems', icon: 'pulse', group: 'Account', tags: ['health', 'status', 'monitoring', 'workers', 'crons', 'x402', 'pump', 'agents', 'seeding', 'all systems'] },
+ { path: '/dashboard/spend', label: 'GCP Spend', icon: 'chart', group: 'Account', tags: ['gcp', 'credits', 'burn', 'cost', 'vertex', 'claude', 'imagen', 'forge', 'gpu', 'budget', 'runway', 'billing', 'cloud', 'spend', 'observability'] },
{ path: '/dashboard/account', label: 'Account', icon: 'user', group: 'Account', tags: ['wallets', 'sns', 'delegation', 'profile', 'action log', 'provider keys'] },
{ path: '/dashboard/referrals', label: 'Referrals', icon: 'gift', group: 'Account', tags: ['referral', 'invite', 'membership', 'card', 'refer a friend', 'share', 'rewards', 'position', 'score'] },
{ path: '/dashboard/wallet-grinder', label: 'Wallet Grinder', icon: 'sparkle', group: 'Account', tags: ['vanity', 'grind', 'keypair', 'wallet', 'solana', 'evm', 'ethereum', 'base', 'polygon', 'address', 'prefix', 'suffix'] },
diff --git a/src/dashboard-next/pages/spend.js b/src/dashboard-next/pages/spend.js
new file mode 100644
index 000000000..6f55067db
--- /dev/null
+++ b/src/dashboard-next/pages/spend.js
@@ -0,0 +1,349 @@
+// dashboard-next — GCP Spend page.
+//
+// Internal burn observability for the $100k GCP credit program. Cross-references
+// two sources from /api/admin/gcp-burn:
+// • App-side telemetry (always present) — per-lane LLM cost/tokens, Vertex
+// Claude spend estimate, forge generations per backend.
+// • BigQuery billing ground truth (when wired) — credit consumed, daily burn,
+// runway, projected exhaustion vs expiry, and the under-utilization guard.
+//
+// Admin-gated (the endpoint enforces it; a 403 renders a designed lock state).
+// Auto-refreshes every 60s. Status is conveyed by icon + text + colour.
+
+import { mountShell } from '../shell.js';
+import { requireUser, esc } from '../api.js';
+import {
+ skeletonHTML,
+ emptyStateHTML,
+ errorStateHTML,
+ ensureStateKitStyles,
+ attachRetry,
+} from '../../shared/state-kit.js';
+
+const REFRESH_MS = 60_000;
+
+const STATUS = {
+ 'on-track': { token: 'var(--nxt-success)', label: 'On track', icon: '🟢' },
+ runaway: { token: 'var(--nxt-danger)', label: 'Runaway burn', icon: '🔴' },
+ underutilized: { token: 'var(--nxt-warn)', label: 'Under-utilized', icon: '🟡' },
+ idle: { token: 'var(--nxt-ink-fade)', label: 'Idle', icon: '⚪' },
+ unknown: { token: 'var(--nxt-ink-fade)', label: 'Unknown', icon: '⚪' },
+};
+
+const LANE_LABEL = {
+ 'vertex-claude': 'Vertex Claude',
+ 'forge-gpu': 'Forge GPU fleet',
+ imagen: 'Imagen',
+ other: 'Other (free / BYOK)',
+};
+
+function usd(n) {
+ if (n == null || Number.isNaN(Number(n))) return '—';
+ return `$${Number(n).toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 })}`;
+}
+function compact(n) {
+ const v = Number(n || 0);
+ if (v >= 1e9) return `${(v / 1e9).toFixed(1)}B`;
+ if (v >= 1e6) return `${(v / 1e6).toFixed(1)}M`;
+ if (v >= 1e3) return `${(v / 1e3).toFixed(1)}k`;
+ return String(v);
+}
+function day(d) { return String(d).slice(5); } // MM-DD
+
+// ── Render ──────────────────────────────────────────────────────────────────
+
+function renderBilling(billing) {
+ if (!billing || !billing.available) {
+ return `
+ <section class="sp-panel sp-panel-muted">
+ <div class="sp-panel-head"><h2>Billing ground truth</h2><span class="sp-tag">not wired</span></div>
+ <p class="sp-note">${esc(billing?.reason || 'BigQuery billing export not configured.')}</p>
+ <p class="sp-note-dim">Enable the export + set the billing env vars (see <code>docs/gcp-credits.md</code>), then run <code>node scripts/gcp/burn-report.mjs</code> to verify. The app-side telemetry below is live regardless.</p>
+ </section>`;
+ }
+ const r = billing.report;
+ const p = r.projection;
+ const s = STATUS[p.status] || STATUS.unknown;
+ const usedPct = p.creditTotalUsd ? Math.min(100, (r.totals.creditUsed / p.creditTotalUsd) * 100) : null;
+
+ const stat = (label, value, sub) => `
+ <div class="sp-stat">
+ <div class="sp-stat-label">${esc(label)}</div>
+ <div class="sp-stat-value">${value}</div>
+ ${sub ? `<div class="sp-stat-sub">${sub}</div>` : ''}
+ </div>`;
+
+ const byLane = (r.byLane || []).filter((l) => l.creditUsed > 0.005);
+ const laneRows = byLane.length
+ ? byLane.slice(0, 8).map((l) => `
+ <tr><td>${esc(LANE_LABEL[l.lane] || l.lane)}</td><td class="sp-num">${usd(l.creditUsed)}</td><td class="sp-dim">${esc(l.program)}</td></tr>`).join('')
+ : `<tr><td colspan="3" class="sp-dim">No labeled spend yet — run <code>scripts/gcp/label-resources.sh</code>.</td></tr>`;
+
+ return `
+ <section class="sp-panel" data-status="${esc(p.status)}" style="--s:${s.token}">
+ <div class="sp-panel-head">
+ <h2>Billing ground truth</h2>
+ <span class="sp-badge">${s.icon} ${esc(s.label)}</span>
+ </div>
+ <p class="sp-headline">${esc(p.headline || '')}</p>
+ ${usedPct != null ? `<div class="sp-bar" role="img" aria-label="${usedPct.toFixed(1)}% of grant consumed"><div class="sp-bar-fill" style="width:${usedPct}%"></div></div>` : ''}
+ <div class="sp-stats">
+ ${stat('Credit consumed', usd(r.totals.creditUsed), p.creditTotalUsd ? `of ${usd(p.creditTotalUsd)}` : '')}
+ ${stat('Remaining', usd(p.remainingUsd), '')}
+ ${stat('Burn / day (7d)', usd(r.burn.avg7dPerDay), `${usd(r.burn.avg30dPerDay)} (30d)`)}
+ ${stat('Runway', p.daysRunway == null ? '—' : p.daysRunway === Infinity ? '∞' : `${Math.round(p.daysRunway)}d`, p.exhaustionDate ? `exhausts ${String(p.exhaustionDate).slice(0, 10)}` : '')}
+ ${stat('Expiry', p.expiry ? String(p.expiry).slice(0, 10) : '—', p.daysToExpiry != null ? `${Math.round(p.daysToExpiry)}d away` : '')}
+ ${stat('Projected unused', p.projectedUnusedPct != null ? `${Math.round(p.projectedUnusedPct * 100)}%` : '—', p.projectedUnusedUsd != null ? usd(p.projectedUnusedUsd) : '')}
+ </div>
+ <table class="sp-table">
+ <caption>Credit spend by lane (attribution)</caption>
+ <thead><tr><th>Lane</th><th class="sp-num">Credit used</th><th>Program</th></tr></thead>
+ <tbody>${laneRows}</tbody>
+ </table>
+ </section>`;
+}
+
+function renderDailyChart(series) {
+ if (!series || series.length === 0) return '';
+ const lanes = ['vertex-claude', 'forge-gpu', 'imagen', 'other'];
+ const totals = series.map((d) => lanes.reduce((a, l) => a + (d[l] || 0), 0));
+ const max = Math.max(...totals, 0.0001);
+ const bars = series.map((d, i) => {
+ const h = Math.round((totals[i] / max) * 100);
+ const segs = lanes.map((l) => {
+ const v = d[l] || 0;
+ if (v <= 0) return '';
+ const pct = (v / (totals[i] || 1)) * 100;
+ return `<span class="sp-seg" data-lane="${l}" style="height:${pct}%" title="${esc(LANE_LABEL[l])}: ${usd(v)}"></span>`;
+ }).join('');
+ return `<div class="sp-bar-col" title="${esc(day(d.day))} · ${usd(totals[i])}"><div class="sp-bar-stack" style="height:${h}%">${segs}</div><span class="sp-bar-x">${esc(day(d.day))}</span></div>`;
+ }).join('');
+ return `
+ <section class="sp-panel">
+ <div class="sp-panel-head"><h2>App-side LLM cost / day (14d)</h2></div>
+ <div class="sp-chart" role="img" aria-label="Daily LLM cost by lane, last 14 days">${bars}</div>
+ <div class="sp-legend">
+ <span data-lane="vertex-claude">Vertex Claude</span>
+ <span data-lane="forge-gpu">Forge GPU</span>
+ <span data-lane="imagen">Imagen</span>
+ <span data-lane="other">Other</span>
+ </div>
+ </section>`;
+}
+
+function renderLanes(app) {
+ const lanes = app.lane_totals_14d || [];
+ const vc = app.vertex_claude || {};
+ const forge = app.forge_by_backend || [];
+
+ const laneCards = lanes.length
+ ? lanes.map((l) => `
+ <li class="sp-lane" data-lane="${esc(l.lane)}">
+ <div class="sp-lane-name">${esc(LANE_LABEL[l.lane] || l.lane)}</div>
+ <div class="sp-lane-cost">${usd(l.costUsd)}</div>
+ <div class="sp-lane-meta">${l.requests.toLocaleString()} req · ${compact(l.inputTokens + l.outputTokens)} tok</div>
+ </li>`).join('')
+ : `<li class="sp-empty-inline">No LLM lane usage in the last 14 days.</li>`;
+
+ const forgeRows = forge.length
+ ? forge.map((f) => `
+ <tr>
+ <td>${esc(f.backend)}${f.selfHost ? ' <span class="sp-chip">self-host</span>' : ''}</td>
+ <td class="sp-num">${f.generations30d.toLocaleString()}</td>
+ <td class="sp-num sp-dim">${f.generations24h.toLocaleString()}</td>
+ </tr>`).join('')
+ : `<tr><td colspan="3" class="sp-dim">No forge generations in the last 30 days.</td></tr>`;
+
+ return `
+ <section class="sp-panel">
+ <div class="sp-panel-head"><h2>Lane cost — app-side estimate (14d)</h2></div>
+ <ul class="sp-lanes">${laneCards}</ul>
+ </section>
+
+ <div class="sp-two">
+ <section class="sp-panel">
+ <div class="sp-panel-head"><h2>Vertex Claude</h2></div>
+ <div class="sp-stats sp-stats-sm">
+ <div class="sp-stat"><div class="sp-stat-label">Cost 30d</div><div class="sp-stat-value">${usd(vc.costUsd30d)}</div></div>
+ <div class="sp-stat"><div class="sp-stat-label">Cost 24h</div><div class="sp-stat-value">${usd(vc.costUsd24h)}</div></div>
+ <div class="sp-stat"><div class="sp-stat-label">Requests 30d</div><div class="sp-stat-value">${Number(vc.requests30d || 0).toLocaleString()}</div></div>
+ <div class="sp-stat"><div class="sp-stat-label">Tokens 30d</div><div class="sp-stat-value">${compact((vc.inputTokens30d || 0) + (vc.outputTokens30d || 0))}</div></div>
+ </div>
+ ${(vc.byModel || []).length ? `<table class="sp-table"><thead><tr><th>Model</th><th class="sp-num">Cost</th><th class="sp-num">Req</th></tr></thead><tbody>${vc.byModel.slice(0, 6).map((m) => `<tr><td>${esc(m.model || '—')}</td><td class="sp-num">${usd(m.costUsd)}</td><td class="sp-num sp-dim">${m.requests.toLocaleString()}</td></tr>`).join('')}</tbody></table>` : `<p class="sp-note-dim">No Vertex Claude traffic yet — set <code>VERTEX_CLAUDE_PRIMARY</code> to route production chat through it.</p>`}
+ </section>
+
+ <section class="sp-panel">
+ <div class="sp-panel-head"><h2>Forge generations by backend (30d)</h2></div>
+ <table class="sp-table">
+ <thead><tr><th>Backend</th><th class="sp-num">30d</th><th class="sp-num">24h</th></tr></thead>
+ <tbody>${forgeRows}</tbody>
+ </table>
+ </section>
+ </div>`;
+}
+
+function renderAll(data) {
+ const app = data.app_side || {};
+ const hasAnything = (app.lane_totals_14d || []).length || (app.forge_by_backend || []).length || data.billing?.available;
+ if (!hasAnything) {
+ return emptyStateHTML({
+ icon: '📊',
+ title: 'No spend telemetry yet',
+ body: 'No GCP-lane usage recorded and the billing export isn’t wired. Once Vertex/forge lanes serve traffic (or the BigQuery export lands), this fills in.',
+ actions: [{ label: 'Retry', id: 'sp-retry', primary: true }],
+ }).replace('data-sk-action="sp-retry"', 'data-sk-retry');
+ }
+ return `
+ ${renderBilling(data.billing)}
+ ${renderDailyChart(app.daily_llm_cost_usd)}
+ ${renderLanes(app)}
+ <p class="sp-foot">Generated ${esc(String(data.generated_at || '').slice(0, 19))}Z · kill-switch: <code>scripts/gcp/emergency-stop.sh</code> · report: <code>node scripts/gcp/burn-report.mjs</code></p>`;
+}
+
+function injectStyles() {
+ if (document.getElementById('sp-styles')) return;
+ ensureStateKitStyles();
+ const s = document.createElement('style');
+ s.id = 'sp-styles';
+ s.textContent = `
+ .sp-root { display: flex; flex-direction: column; gap: 1.25rem; padding-bottom: 3rem; }
+ .sp-panel { background: var(--nxt-glass); border: 1px solid var(--nxt-stroke); border-radius: var(--nxt-radius-sm); padding: 1.1rem 1.2rem; --s: var(--nxt-accent); }
+ .sp-panel[data-status] { border-left: 3px solid var(--s); }
+ .sp-panel-muted { opacity: .92; }
+ .sp-panel-head { display: flex; align-items: center; justify-content: space-between; gap: .5rem; margin-bottom: .8rem; }
+ .sp-panel-head h2 { margin: 0; font-size: .95rem; font-weight: 650; color: var(--nxt-ink); }
+ .sp-badge { font-size: .75rem; font-weight: 600; color: var(--s); border: 1px solid color-mix(in srgb, var(--s) 40%, transparent); background: color-mix(in srgb, var(--s) 12%, transparent); padding: .2rem .55rem; border-radius: var(--nxt-radius-pill); white-space: nowrap; }
+ .sp-tag { font-size: .68rem; text-transform: uppercase; letter-spacing: .08em; color: var(--nxt-ink-fade); border: 1px solid var(--nxt-stroke); padding: .15rem .5rem; border-radius: var(--nxt-radius-pill); }
+ .sp-headline { margin: 0 0 .8rem; font-size: .9rem; color: var(--nxt-ink); line-height: 1.5; }
+ .sp-note { margin: 0 0 .5rem; font-size: .85rem; color: var(--nxt-ink-dim); line-height: 1.5; }
+ .sp-note-dim { margin: 0; font-size: .8rem; color: var(--nxt-ink-fade); line-height: 1.5; }
+ .sp-note code, .sp-note-dim code, .sp-foot code, .sp-table code { font-family: var(--nxt-mono, ui-monospace, monospace); font-size: .82em; background: color-mix(in srgb, var(--nxt-ink) 8%, transparent); padding: .05em .35em; border-radius: 4px; }
+
+ .sp-bar { height: 8px; border-radius: 5px; background: color-mix(in srgb, var(--nxt-ink) 10%, transparent); overflow: hidden; margin-bottom: 1rem; }
+ .sp-bar-fill { height: 100%; background: var(--s); border-radius: 5px; transition: width .4s ease; }
+
+ .sp-stats { display: grid; grid-template-columns: repeat(auto-fit, minmax(140px, 1fr)); gap: .75rem; margin-bottom: 1rem; }
+ .sp-stats-sm { grid-template-columns: repeat(auto-fit, minmax(110px, 1fr)); margin-bottom: .6rem; }
+ .sp-stat { background: color-mix(in srgb, var(--nxt-ink) 4%, transparent); border-radius: var(--nxt-radius-sm); padding: .65rem .75rem; }
+ .sp-stat-label { font-size: .7rem; text-transform: uppercase; letter-spacing: .06em; color: var(--nxt-ink-fade); }
+ .sp-stat-value { font-size: 1.15rem; font-weight: 650; color: var(--nxt-ink); margin-top: .15rem; letter-spacing: -.01em; }
+ .sp-stat-sub { font-size: .72rem; color: var(--nxt-ink-fade); margin-top: .1rem; }
+
+ .sp-table { width: 100%; border-collapse: collapse; margin-top: .5rem; font-size: .82rem; }
+ .sp-table caption { text-align: left; font-size: .7rem; text-transform: uppercase; letter-spacing: .06em; color: var(--nxt-ink-fade); padding-bottom: .4rem; }
+ .sp-table th { text-align: left; font-weight: 600; color: var(--nxt-ink-fade); font-size: .72rem; text-transform: uppercase; letter-spacing: .04em; padding: .35rem .5rem; border-bottom: 1px solid var(--nxt-stroke); }
+ .sp-table td { padding: .4rem .5rem; border-bottom: 1px solid color-mix(in srgb, var(--nxt-stroke) 55%, transparent); color: var(--nxt-ink); }
+ .sp-num { text-align: right; font-variant-numeric: tabular-nums; }
+ .sp-dim { color: var(--nxt-ink-fade); }
+ .sp-chip { font-size: .62rem; font-weight: 600; text-transform: uppercase; letter-spacing: .04em; color: var(--nxt-success); border: 1px solid color-mix(in srgb, var(--nxt-success) 40%, transparent); padding: .05rem .35rem; border-radius: var(--nxt-radius-pill); margin-left: .35rem; }
+
+ .sp-lanes { list-style: none; margin: 0; padding: 0; display: grid; grid-template-columns: repeat(auto-fill, minmax(min(100%, 200px), 1fr)); gap: .6rem; }
+ .sp-lane { border: 1px solid var(--nxt-stroke); border-radius: var(--nxt-radius-sm); padding: .7rem .8rem; border-left: 3px solid var(--l, var(--nxt-accent)); }
+ .sp-lane[data-lane="vertex-claude"] { --l: #a78bfa; }
+ .sp-lane[data-lane="forge-gpu"] { --l: #34d399; }
+ .sp-lane[data-lane="imagen"] { --l: #f59e0b; }
+ .sp-lane[data-lane="other"] { --l: var(--nxt-ink-fade); }
+ .sp-lane-name { font-size: .78rem; color: var(--nxt-ink-dim); }
+ .sp-lane-cost { font-size: 1.2rem; font-weight: 680; color: var(--nxt-ink); letter-spacing: -.01em; }
+ .sp-lane-meta { font-size: .72rem; color: var(--nxt-ink-fade); margin-top: .1rem; }
+ .sp-empty-inline { list-style: none; color: var(--nxt-ink-fade); font-size: .82rem; }
+
+ .sp-two { display: grid; grid-template-columns: 1fr 1fr; gap: 1.25rem; }
+ @media (max-width: 720px) { .sp-two { grid-template-columns: 1fr; } }
+
+ .sp-chart { display: flex; align-items: flex-end; gap: 4px; height: 120px; padding-top: .5rem; }
+ .sp-bar-col { flex: 1; display: flex; flex-direction: column; align-items: center; justify-content: flex-end; height: 100%; gap: 3px; }
+ .sp-bar-stack { width: 70%; min-height: 2px; display: flex; flex-direction: column-reverse; border-radius: 3px 3px 0 0; overflow: hidden; background: color-mix(in srgb, var(--nxt-ink) 6%, transparent); }
+ .sp-seg[data-lane="vertex-claude"] { background: #a78bfa; }
+ .sp-seg[data-lane="forge-gpu"] { background: #34d399; }
+ .sp-seg[data-lane="imagen"] { background: #f59e0b; }
+ .sp-seg[data-lane="other"] { background: var(--nxt-ink-fade); }
+ .sp-bar-x { font-size: .6rem; color: var(--nxt-ink-fade); }
+ .sp-legend { display: flex; gap: 1rem; margin-top: .6rem; font-size: .72rem; color: var(--nxt-ink-dim); flex-wrap: wrap; }
+ .sp-legend span { display: inline-flex; align-items: center; gap: .35rem; }
+ .sp-legend span::before { content: ''; width: 9px; height: 9px; border-radius: 2px; }
+ .sp-legend span[data-lane="vertex-claude"]::before { background: #a78bfa; }
+ .sp-legend span[data-lane="forge-gpu"]::before { background: #34d399; }
+ .sp-legend span[data-lane="imagen"]::before { background: #f59e0b; }
+ .sp-legend span[data-lane="other"]::before { background: var(--nxt-ink-fade); }
+
+ .sp-foot { font-size: .74rem; color: var(--nxt-ink-fade); text-align: center; margin: .5rem 0 0; }
+ @media (prefers-reduced-motion: reduce) { .sp-bar-fill { transition: none; } }
+ `;
+ document.head.appendChild(s);
+}
+
+const REFRESH_SVG = '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><polyline points="23 4 23 10 17 10"/><polyline points="1 20 1 14 7 14"/><path d="M3.51 9a9 9 0 0 1 14.85-3.36L23 10M1 14l4.64 4.36A9 9 0 0 0 20.49 15"/></svg>';
+
+(async function boot() {
+ const main = await mountShell();
+ await requireUser();
+ injectStyles();
+
+ main.innerHTML = `
+ <div style="display:flex;align-items:baseline;justify-content:space-between;flex-wrap:wrap;gap:.5rem;margin-bottom:1.5rem">
+ <div>
+ <h1 class="dn-h1" style="margin-bottom:.25rem">GCP Spend</h1>
+ <p class="dn-h1-sub" style="margin:0">Credit burn observability — per-lane cost, runway, and projection vs expiry for the $100k program.</p>
+ </div>
+ <button class="dn-btn" id="sp-refresh" type="button" aria-label="Refresh spend data now" style="display:inline-flex;align-items:center;gap:.4rem;background:rgba(255,255,255,.04);border:1px solid var(--nxt-stroke);border-radius:var(--nxt-radius-sm);padding:.4rem .8rem;font-size:.78rem;color:var(--nxt-ink);cursor:pointer">
+ <span class="sp-refresh-icon" style="display:inline-flex;width:13px;height:13px">${REFRESH_SVG}</span><span>Refresh</span>
+ </button>
+ </div>
+ <div class="sp-root" id="sp-root" aria-busy="true">
+ <div class="sp-panel" aria-hidden="true">${skeletonHTML(4, 'row')}</div>
+ </div>`;
+
+ const root = document.getElementById('sp-root');
+ const refreshBtn = document.getElementById('sp-refresh');
+ let refreshTimer = null;
+
+ function renderAccessError(status) {
+ if (status === 403) {
+ return emptyStateHTML({
+ icon: '🔒',
+ title: 'Admin access required',
+ body: 'The GCP spend dashboard is limited to workspace admins. Ask an admin to grant access if you need burn visibility.',
+ actions: [{ label: 'Back to dashboard', href: '/dashboard' }],
+ });
+ }
+ if (status === 401) {
+ return emptyStateHTML({ icon: '🔑', title: 'Sign in required', body: 'Your session expired. Sign in again to view spend.', actions: [{ label: 'Sign in', href: '/login' }] });
+ }
+ return errorStateHTML({ title: 'Couldn’t load spend', body: `The endpoint returned ${esc(String(status))}. Usually transient — retry.` });
+ }
+
+ async function load() {
+ refreshBtn.disabled = true;
+ root.setAttribute('aria-busy', 'true');
+ try {
+ const res = await fetch('/api/admin/gcp-burn', { credentials: 'include' });
+ if (!res.ok) { root.innerHTML = renderAccessError(res.status); return; }
+ const data = await res.json();
+ root.innerHTML = renderAll(data);
+ } catch (err) {
+ root.innerHTML = errorStateHTML({ title: 'Couldn’t reach the spend endpoint', body: esc(err?.message || 'Check your connection and try again.') });
+ } finally {
+ refreshBtn.disabled = false;
+ root.setAttribute('aria-busy', 'false');
+ }
+ }
+
+ function schedule() {
+ clearTimeout(refreshTimer);
+ refreshTimer = setTimeout(() => load().then(schedule), REFRESH_MS);
+ }
+
+ attachRetry(root, () => { clearTimeout(refreshTimer); load().then(schedule); });
+ refreshBtn.addEventListener('click', () => { clearTimeout(refreshTimer); load().then(schedule); });
+ document.addEventListener('visibilitychange', () => {
+ if (document.hidden) clearTimeout(refreshTimer);
+ else load().then(schedule);
+ });
+
+ await load();
+ schedule();
+})().catch((err) => {
+ const main = document.querySelector('.dn-main-inner') || document.body;
+ main.innerHTML = `<h1 class="dn-h1">GCP Spend</h1><div class="dn-panel"><div class="dn-panel-title" style="color:var(--nxt-danger)">Failed to load</div><div class="dn-panel-sub">${(err?.message || 'unknown').replace(/</g, '&lt;')}</div></div>`;
+});
diff --git a/tests/api/gcp-budget-alert.test.js b/tests/api/gcp-budget-alert.test.js
new file mode 100644
index 000000000..1b427510c
--- /dev/null
+++ b/tests/api/gcp-budget-alert.test.js
@@ -0,0 +1,116 @@
+// /api/webhooks/gcp-budget-alert — Pub/Sub budget push → ops alert.
+//
+// Verifies the security + noise-control contract of the budget webhook:
+// • no shared secret configured → 503 (never accept unauthenticated pings)
+// • wrong token → 401
+// • a real threshold crossing → 200 + exactly one ops alert
+// • an info message (no alertThresholdExceeded) → 200 but NO alert (noise gate)
+// • a subscription-verification ping (no decodable data) → 200, no alert
+
+import { describe, it, expect, beforeEach, vi } from 'vitest';
+
+const sendOpsAlert = vi.fn(async () => {});
+vi.mock('../../api/_lib/alerts.js', () => ({ sendOpsAlert }));
+vi.mock('../../api/_lib/sentry.js', () => ({ captureException: vi.fn() }));
+vi.mock('../../api/_lib/zauth.js', () => ({ instrument: () => null, drain: async () => {} }));
+vi.mock('../../api/_lib/env.js', () => ({ env: { APP_ORIGIN: 'http://localhost:3000' } }));
+
+const { default: handler } = await import('../../api/webhooks/gcp-budget-alert.js');
+
+function pubsubBody(notification) {
+ const data = Buffer.from(JSON.stringify(notification), 'utf8').toString('base64');
+ return JSON.stringify({ message: { data, messageId: '1', publishTime: 'now' }, subscription: 'sub' });
+}
+
+function mkReq({ token = 'secret', body = '', headers = {} } = {}) {
+ const url = `/api/webhooks/gcp-budget-alert${token != null ? `?token=${encodeURIComponent(token)}` : ''}`;
+ const listeners = {};
+ const req = {
+ method: 'POST',
+ url,
+ headers: { 'content-type': 'application/json', ...headers },
+ on(event, cb) { listeners[event] = cb; return req; },
+ destroy() {},
+ };
+ // Deliver the body on the next tick, after readBody attaches its listeners.
+ queueMicrotask(() => {
+ if (body && listeners.data) listeners.data(Buffer.from(body, 'utf8'));
+ if (listeners.end) listeners.end();
+ });
+ return req;
+}
+
+function mkRes() {
+ return {
+ statusCode: 200,
+ headers: {},
+ body: undefined,
+ writableEnded: false,
+ setHeader(k, v) { this.headers[k.toLowerCase()] = v; },
+ end(b) { this.body = b; this.writableEnded = true; },
+ };
+}
+
+async function invoke(opts = {}) {
+ const res = mkRes();
+ await handler(mkReq(opts), res);
+ return { status: res.statusCode, body: res.body ? JSON.parse(res.body) : undefined };
+}
+
+describe('gcp-budget-alert webhook', () => {
+ beforeEach(() => {
+ sendOpsAlert.mockClear();
+ process.env.GCP_BUDGET_WEBHOOK_SECRET = 'secret';
+ });
+
+ it('refuses when no secret is configured (503)', async () => {
+ delete process.env.GCP_BUDGET_WEBHOOK_SECRET;
+ const { status } = await invoke({ token: 'secret', body: pubsubBody({ alertThresholdExceeded: 0.5 }) });
+ expect(status).toBe(503);
+ expect(sendOpsAlert).not.toHaveBeenCalled();
+ });
+
+ it('rejects a wrong token (401)', async () => {
+ const { status } = await invoke({ token: 'nope', body: pubsubBody({ alertThresholdExceeded: 0.5 }) });
+ expect(status).toBe(401);
+ expect(sendOpsAlert).not.toHaveBeenCalled();
+ });
+
+ it('alerts once on a real threshold crossing', async () => {
+ const { status, body } = await invoke({
+ token: 'secret',
+ body: pubsubBody({
+ budgetDisplayName: 'gcp-credits — program',
+ alertThresholdExceeded: 0.9,
+ costAmount: 90000,
+ budgetAmount: 100000,
+ currencyCode: 'USD',
+ }),
+ });
+ expect(status).toBe(200);
+ expect(body.alerted).toBe(true);
+ expect(body.threshold).toBe(0.9);
+ expect(sendOpsAlert).toHaveBeenCalledTimes(1);
+ const [title, detail, opts] = sendOpsAlert.mock.calls[0];
+ expect(title).toContain('90%');
+ expect(detail).toContain('$90,000');
+ expect(opts.signature).toBe('gcp-budget:gcp-credits — program:0.9');
+ });
+
+ it('does NOT alert on an info message with no threshold', async () => {
+ const { status, body } = await invoke({
+ token: 'secret',
+ body: pubsubBody({ budgetDisplayName: 'gcp-credits — program', costAmount: 100, budgetAmount: 100000 }),
+ });
+ expect(status).toBe(200);
+ expect(body.alerted).toBe(false);
+ expect(sendOpsAlert).not.toHaveBeenCalled();
+ });
+
+ it('acks a verification ping with no decodable data', async () => {
+ const { status, body } = await invoke({ token: 'secret', body: JSON.stringify({ message: { messageId: 'x' } }) });
+ expect(status).toBe(200);
+ expect(body.parsed).toBe(false);
+ expect(sendOpsAlert).not.toHaveBeenCalled();
+ });
+});
diff --git a/tests/gcp-billing.test.js b/tests/gcp-billing.test.js
new file mode 100644
index 000000000..e4068f6a6
--- /dev/null
+++ b/tests/gcp-billing.test.js
@@ -0,0 +1,173 @@
+// GCP credit burn — projection math + config resolution contract.
+//
+// The projection is the load-bearing part of spend observability: it decides
+// whether the platform is on track, burning too fast (runaway before expiry), or
+// too slow (>30% of the grant expiring unused). It's pure and deterministic, so
+// it's tested exhaustively here; the BigQuery I/O around it is exercised live.
+
+import { describe, it, expect } from 'vitest';
+import {
+ projectExhaustion,
+ averageDailyBurn,
+ resolveBillingConfig,
+ billingConfigured,
+ BillingUnavailableError,
+ usd,
+} from '../api/_lib/gcp-billing.js';
+
+const NOW = new Date('2026-07-06T00:00:00Z');
+const DAY = 86_400_000;
+
+describe('projectExhaustion', () => {
+ it('flags runaway when credits exhaust before expiry', () => {
+ // $60k used, $2k/day, $100k grant → $40k left / $2k = 20d runway, expiry 90d out.
+ const p = projectExhaustion({
+ creditUsed: 60_000,
+ avgDailyBurn: 2_000,
+ creditTotal: 100_000,
+ now: NOW,
+ expiry: new Date(NOW.getTime() + 90 * DAY),
+ });
+ expect(p.status).toBe('runaway');
+ expect(Math.round(p.daysRunway)).toBe(20);
+ expect(new Date(p.exhaustionDate).getTime()).toBeLessThan(NOW.getTime() + 90 * DAY);
+ expect(p.remainingUsd).toBe(40_000);
+ });
+
+ it('flags underutilized when >30% projected unused at expiry', () => {
+ // $5k used, $100/day, $100k grant, expiry 90d out.
+ // projected = 5k + 100*90 = 14k → 86% unused.
+ const p = projectExhaustion({
+ creditUsed: 5_000,
+ avgDailyBurn: 100,
+ creditTotal: 100_000,
+ now: NOW,
+ expiry: new Date(NOW.getTime() + 90 * DAY),
+ });
+ expect(p.status).toBe('underutilized');
+ expect(p.projectedUnusedPct).toBeGreaterThan(0.3);
+ expect(Math.round(p.projectedSpendByExpiryUsd)).toBe(14_000);
+ });
+
+ it('reports on-track when spend lands within the sweet spot', () => {
+ // $20k used, $900/day, $100k grant, expiry 90d out.
+ // projected = 20k + 900*90 = 101k → capped at 100k → 0% unused; runway 88.9d < 90d?
+ // remaining 80k / 900 = 88.9d runway, expiry 90d → runway>? 88.9<90 so runaway.
+ // Use a burn that lands on-track: $850/day → projected 20k+76.5k=96.5k (3.5% unused),
+ // runway 80k/850=94.1d > 90d → on-track.
+ const p = projectExhaustion({
+ creditUsed: 20_000,
+ avgDailyBurn: 850,
+ creditTotal: 100_000,
+ now: NOW,
+ expiry: new Date(NOW.getTime() + 90 * DAY),
+ });
+ expect(p.status).toBe('on-track');
+ expect(p.projectedUnusedPct).toBeLessThan(0.3);
+ expect(p.daysRunway).toBeGreaterThan(p.daysToExpiry);
+ });
+
+ it('reports idle with infinite runway when there is no burn', () => {
+ const p = projectExhaustion({ creditUsed: 1_000, avgDailyBurn: 0, creditTotal: 100_000, now: NOW, expiry: new Date(NOW.getTime() + 90 * DAY) });
+ expect(p.status).toBe('idle');
+ expect(p.daysRunway).toBe(Infinity);
+ expect(p.projectedUnusedUsd).toBe(99_000);
+ });
+
+ it('degrades gracefully with no credit total (unknown)', () => {
+ const p = projectExhaustion({ creditUsed: 500, avgDailyBurn: 100, creditTotal: null, now: NOW, expiry: null });
+ expect(p.status).toBe('unknown');
+ expect(p.remainingUsd).toBeNull();
+ expect(p.headline).toMatch(/GCP_CREDIT_TOTAL_USD/);
+ });
+
+ it('gives runway without expiry set', () => {
+ const p = projectExhaustion({ creditUsed: 50_000, avgDailyBurn: 1_000, creditTotal: 100_000, now: NOW, expiry: null });
+ expect(p.status).toBe('on-track');
+ expect(Math.round(p.daysRunway)).toBe(50);
+ expect(p.daysToExpiry).toBeNull();
+ });
+});
+
+describe('averageDailyBurn', () => {
+ it('divides the trailing window sum by the requested day count', () => {
+ const daily = [
+ { creditUsed: 100 }, { creditUsed: 200 }, { creditUsed: 300 },
+ { creditUsed: 400 }, { creditUsed: 500 }, { creditUsed: 600 }, { creditUsed: 700 },
+ ];
+ // last 7 sum = 2800 / 7 = 400
+ expect(averageDailyBurn(daily, 7)).toBe(400);
+ // last 3 sum = 1800 / 3 = 600
+ expect(averageDailyBurn(daily, 3)).toBe(600);
+ });
+
+ it('divides by the requested window even with fewer rows (true daily rate)', () => {
+ // A lane live 3 of the last 7 days still reports a real 7-day rate.
+ const daily = [{ creditUsed: 700 }, { creditUsed: 700 }, { creditUsed: 700 }];
+ expect(averageDailyBurn(daily, 7)).toBeCloseTo(300, 5);
+ });
+
+ it('handles the snake_case column name from BigQuery rows', () => {
+ expect(averageDailyBurn([{ credit_used: 70 }], 7)).toBeCloseTo(10, 5);
+ });
+
+ it('returns 0 for empty input', () => {
+ expect(averageDailyBurn([], 7)).toBe(0);
+ expect(averageDailyBurn(null, 7)).toBe(0);
+ });
+});
+
+describe('resolveBillingConfig', () => {
+ it('throws BillingUnavailableError when unconfigured', () => {
+ expect(() => resolveBillingConfig({})).toThrow(BillingUnavailableError);
+ expect(billingConfigured({})).toBe(false);
+ });
+
+ it('derives the standard export table from the billing account id', () => {
+ const cfg = resolveBillingConfig({
+ GOOGLE_CLOUD_PROJECT: 'proj-1',
+ GCP_BILLING_DATASET: 'billing',
+ GCP_BILLING_ACCOUNT_ID: '01ABCD-234567-89EFGH',
+ });
+ expect(cfg.table).toBe('gcp_billing_export_v1_01ABCD_234567_89EFGH');
+ expect(cfg.fqTable).toBe('`proj-1.billing.gcp_billing_export_v1_01ABCD_234567_89EFGH`');
+ });
+
+ it('uses the resource export prefix when kind=resource', () => {
+ const cfg = resolveBillingConfig({
+ GOOGLE_CLOUD_PROJECT: 'p',
+ GCP_BILLING_DATASET: 'd',
+ GCP_BILLING_ACCOUNT_ID: 'AA-BB-CC',
+ GCP_BILLING_EXPORT_KIND: 'resource',
+ });
+ expect(cfg.table).toBe('gcp_billing_export_resource_v1_AA_BB_CC');
+ });
+
+ it('sanitizes credit-type overrides to enum tokens only (no SQL injection)', () => {
+ const cfg = resolveBillingConfig({
+ GOOGLE_CLOUD_PROJECT: 'p',
+ GCP_BILLING_DATASET: 'd',
+ GCP_BILLING_TABLE: 't',
+ GCP_CREDIT_TYPES: "PROMOTION, FREE_TRIAL, '); DROP TABLE x;--",
+ });
+ expect(cfg.creditTypes).toEqual(['PROMOTION', 'FREE_TRIAL']);
+ });
+
+ it('parses the credit total and expiry', () => {
+ const cfg = resolveBillingConfig({
+ GOOGLE_CLOUD_PROJECT: 'p', GCP_BILLING_DATASET: 'd', GCP_BILLING_TABLE: 't',
+ GCP_CREDIT_TOTAL_USD: '100000', GCP_CREDIT_EXPIRY: '2027-07-01',
+ });
+ expect(cfg.creditTotalUsd).toBe(100_000);
+ expect(cfg.creditExpiry.toISOString().slice(0, 10)).toBe('2027-07-01');
+ });
+});
+
+describe('usd', () => {
+ it('formats with two decimals and thousands separators', () => {
+ expect(usd(1234.5)).toBe('$1,234.50');
+ expect(usd(0)).toBe('$0.00');
+ expect(usd(null)).toBe('—');
+ expect(usd(NaN)).toBe('—');
+ });
+});