# Integrate Goldrail into this project

You are a coding agent integrating [Goldrail](https://github.com/goldsky-io/goldrail)
— an open-source payment router that lets humans and AI agents pay HTTP
endpoints per request (x402 + MPP) — into the user's codebase. Follow this
document exactly. Your goal is a **reviewable branch** that adds payments in
**shadow mode**: fully wired, observably correct, and charging no one until
the user flips the switch themselves.

## Ground rules — non-negotiable

1. **Work on a branch.** Never commit to the default branch. Deliverable = a
   PR (or a branch + summary if the repo has no PR flow).
2. **Smallest possible diff.** Goldrail is designed for 0–1 line integrations.
   If you are writing more than ~20 lines of integration code, stop and
   reconsider the deployment shape.
3. **`shadow = true` on every priced route.** Shadow mode prices and observes
   traffic but never challenges and never charges. Real traffic is untouched.
4. **`fail = "open"` everywhere.** A payment-layer problem must degrade to
   serving free, never to an outage.
5. **No secrets, ever.** Config uses references (`secret://env/NAME`), never
   values. If you find yourself typing a private key or API key into a file,
   stop. Wallet **addresses** (receive-only) are fine in config.
6. **Never enable live charging.** Flipping shadow off is the user's act, via
   the admin panel or their own config PR. Your PR ends one step before.
7. **Test with fake money only.** `goldrail dev` ships a mock facilitator and
   funded test wallets; `goldrail check` (the built-in end-to-end payment
   test) refuses to run against mainnet.
   Do not work around either.

## Phase 1 — Read the repo

Gather, without asking the user anything yet:

- **Stack & entry points**: framework (Express/Hono/Next, axum/tonic, Go
  `net/http`, …), or gateway configs (Envoy, nginx), or neither (then the
  standalone proxy is the shape).
- **Routes worth pricing**: public API surfaces, expensive endpoints, anything
  rate-limited or API-keyed today. Note existing auth middleware — internal
  callers will need exemptions.
- **Persistence**: is Postgres already present (connection strings, ORM
  config, docker-compose)? If not, Goldrail's default SQLite file works.
- **Deploy model**: Dockerfile, k8s/ECS manifests, serverless, bare binary —
  this picks the deployment shape and where env vars live.
- **Config culture**: IaC/GitOps signals (terraform, helm, CI deploy jobs) →
  recommend `declarative` mode; otherwise `live` mode with the admin panel.
- **Observability**: existing Prometheus/OTel/Grafana wiring to attach to.

## Phase 2 — Ask the user

Present ONE compact question list, with your repo-informed recommendation and
a default for each. Do not proceed until answered:

1. **Routes & prices** — which endpoints to price, and at what price per
   request. ⚠️ Prices are in the asset's **atomic units** (USDC has 6
   decimals: `5` = $0.000005, `5000` = $0.005). State both forms back to the
   user to confirm — this is the #1 misconfiguration.
2. **Pay-to wallet address(es)** — where money lands, per network. Confirm
   the user controls this wallet. Warn: some facilitators rate-limit per
   wallet, so rotating it later is an operational event. Never use a wallet
   generated by you or found in test fixtures.
3. **Networks & methods** — default: USDC on Base (`eip3009`). Also
   available: Solana (`svm`), Stellar (`stellar`), cards via MPP (`spt`).
4. **Facilitators** — default: Circle, with CDP as priority-2 failover. Any
   API keys arrive as `secret://env/...` references; tell the user which env
   vars they must set at deploy time.
5. **Funding rails** — recommend `rails = ["credit", "per-request"]` (credit
   preferred, per-request fallback; payers change nothing either way) with
   `min_prepay` ≈ 1,000× the request price. Plain `["per-request"]` if the
   user wants maximum simplicity.
6. **Store** — existing Postgres (recommended if present; Goldrail uses its
   own schema) or a SQLite file (fine for one instance; say where it lives
   and that it must persist across deploys).
7. **Deployment shape** — recommend from Phase 1: standalone proxy (zero
   code), sidecar (same pod/task), embedded middleware (one line), or
   gateway hook (Envoy `ext_authz` / nginx `auth_request`).
8. **Admin surface** — companion `goldrail admin` process (same store),
   panel mounted inside the app (`app.use('/ops/goldrail', goldrail.admin())`
   — it carries its own auth), or none + `declarative` mode (CI applies
   config; panel read-only).
9. **Identity & reporting** — a `service` name (e.g. the repo name) and any
   `context` dimensions worth slicing revenue by (e.g. product/tier per
   route).
10. **Exemptions** — internal services, health checks, partners who should
    never be charged (JWT issuer, shared secret, or CIDR).

## Phase 3 — Integrate

- Wire the chosen shape with the least invasive change:
  - **Proxy/sidecar**: add the container/service + route traffic through it.
    No application code changes.
  - **Embedded**: one middleware line, placed AFTER existing auth/rate-limit
    middleware so exempt/internal traffic is identified first.
  - **Gateway hook**: point `ext_authz`/`auth_request` at the decision API.
- Write `goldrail.toml` from the answers: every priced route with
  `shadow = true`, `posture = { fail = "open" }`, rails, `min_prepay`,
  methods/networks, backends with budgets, `[discovery]` + `[mcp]` enabled,
  `service` + context, exemptions, secret references only.
- Add the bootstrap env (`GOLDRAIL_STORE_URL`, `GOLDRAIL_SERVICE`, secrets)
  to the deploy manifests you found in Phase 1, alongside their siblings.
- Do not restructure the user's code, rename their files, or "improve"
  unrelated things.

## Phase 4 — Verify (all must pass before the PR)

```bash
goldrail config validate goldrail.toml     # schema + semantics
goldrail config lint goldrail.toml         # unreachable backends, price sanity
goldrail dev                                # mock facilitator, funded wallets
goldrail check --against <local url>        # pays your app end to end,
                                            # fake money only
```

Also check by hand: prices restated in dollars match the user's intent;
`shadow = true` on every route; `fail = "open"`; no secret values anywhere in
the diff; the store path/URL is persistent.

## Phase 5 — PR and the go-live runbook

PR description must contain: the deployment shape and why; a table of routes
→ price (atomic units AND dollars) → rail; env vars the deployer must set;
what shadow mode means (zero payer impact); and this runbook:

1. **Deploy the branch.** Nothing changes for callers — shadow mode observes.
2. **Watch for a day or two**: the admin panel (or `goldrail revenue`) shows
   would-be revenue, would-be 402s, and per-route volume.
3. **Flip the switch** — per route, when the numbers look right:
   - Panel: *Routes → (route) → shadow → off* (the change is versioned and
     audited, rollback is one click), or
   - Declarative: set `shadow = false` in `goldrail.toml`, merge, and let CI
     run `goldrail config apply`.
4. **Watch `goldrail-funding` headers and the funding-mix dashboard.** Credit
   rail engages automatically; facilitator calls should be ~1/1,000 requests.
5. Later, optionally: tighten `fail` posture, add more routes, raise prices —
   every change is a config version, never a deploy.

**Stop after opening the PR.** Report: what you changed, the questions any
reviewer should double-check, and the runbook above. Do not flip shadow off.
