Workflows

Every workflow of the platform as a chart, drawn from the code rather than from memory: the routes in apps/api, the services in packages/core, the GitHub Actions workflows and the Terraform modules. Sequence diagrams show who talks to whom, state diagrams show the lifecycles the database persists, flowcharts show the decisions. Each section links to the page that explains the details.

System overview

flowchart LR
  subgraph agents["Agent platforms"]
    muse["Meta Muse, Claude, ChatGPT or a partner agent"]
  end
  subgraph gcp["GCP project snappy-agents-sandbox or snappy-agents-prod"]
    lb["Global HTTPS load balancer, managed cert, Cloud Armor"]
    iap["Identity-Aware Proxy backend for /admin"]
    api["Cloud Run agents-api: /oauth, /v1, /mcp, /webhooks, /internal/tasks, /admin, /docs"]
    sql[("Cloud SQL Postgres, private IP in the VPC")]
    tasks["Cloud Tasks queue"]
    sched["Cloud Scheduler: expire-checkouts every 5 min"]
    sm[("Secret Manager")]
    nat["Cloud NAT, static egress IP"]
  end
  subgraph ext["Third parties"]
    snappy["Snappy Public API v3"]
    stripe["Stripe Checkout"]
    sendgrid["SendGrid email"]
    twilio["Twilio SMS"]
    anthropic["Anthropic API, negotiation AI"]
  end
  shopper["Shopper browser: sign-in, consent, payment page"]
  ops["Operators, Google Workspace accounts"]
  muse -->|"OAuth 2.1 + PKCE, then REST /v1 or MCP /mcp"| lb
  shopper --> lb
  ops -->|"/admin"| lb
  lb --> api
  lb -->|"/admin*"| iap --> api
  api --> sql
  api -->|"enqueue"| tasks
  tasks -->|"POST /internal/tasks/:task with OIDC"| api
  sched --> api
  api -->|"read latest, add versions"| sm
  api --> nat
  nat --> snappy
  nat --> stripe
  nat --> sendgrid
  nat --> twilio
  nat --> anthropic
  stripe -->|"/webhooks/stripe, signed"| lb
  snappy -->|"/webhooks/snappy, HMAC"| lb
  twilio -->|"/webhooks/twilio, STOP/START/HELP"| lb

One container image per environment serves everything behind a global HTTPS load balancer; /admin* is routed through a second, Identity-Aware-Proxy-enabled backend of the same Cloud Run service. Durable background work (placing orders after payment, refunds, notifications, callbacks, order syncs) goes through Cloud Tasks, which pushes back into /internal/tasks/:task with an OIDC token. Provider credentials live in Secret Manager and are entered through the admin portal. See Architecture and the Operations runbook.

Agent connection and OAuth 2.1

sequenceDiagram
  autonumber
  participant A as Agent platform
  participant S as agents.snappy.com
  participant U as Shopper browser
  A->>S: GET /mcp or /v1/* without a token
  S-->>A: 401 with WWW-Authenticate Bearer resource_metadata=/.well-known/oauth-protected-resource
  A->>S: GET /.well-known/oauth-protected-resource, then /.well-known/oauth-authorization-server
  S-->>A: issuer, endpoints, PKCE S256 only, scopes, registration_endpoint
  A->>S: POST /oauth/register (client_name, redirect_uris, auth method none by default)
  S-->>A: 201 client_id (client_secret only for confidential clients)
  A->>U: open /oauth/authorize with response_type=code, scope, state, code_challenge
  U->>S: GET /oauth/authorize
  S-->>U: sign-in page, flow kept in a signed cookie session for 30 min
  alt Email code
    U->>S: POST /oauth/authorize/otp (email)
    S-->>U: code page, 6-digit code sent by email (shown inline outside prod)
    U->>S: POST /oauth/authorize/verify (code)
  else Google
    U->>S: POST /oauth/authorize/google (Google ID token)
  end
  S-->>U: consent page listing scopes, with a Limit to read-only switch
  U->>S: POST /oauth/authorize/consent (allow, read_only drops orders:write)
  S-->>U: 302 to redirect_uri with code, state and iss (code valid 5 min, single use)
  U->>A: callback with code
  A->>S: POST /oauth/token grant_type=authorization_code, code, code_verifier
  S-->>A: access_token 60 min, refresh_token 30 days when offline_access was granted
  A->>S: Bearer calls to /v1/* or /mcp
  A->>S: POST /oauth/token grant_type=refresh_token
  S-->>A: new access and refresh token, old refresh token revoked (same family)
  Note over A,S: Replaying a code or reusing a rotated refresh token revokes every token of that family
  A->>S: POST /oauth/revoke (token)
  S-->>A: 200, the token and its family are revoked

An agent discovers the authorization server from the WWW-Authenticate challenge on its first unauthenticated call, registers itself dynamically (RFC 7591) and sends the user through authorization code + PKCE (S256 only). The hosted page signs the user in with an email code or Google and shows a consent screen whose read-only switch drops orders:write from the grant. Refresh tokens rotate on every use; reusing a rotated one, or replaying a code, revokes the whole family. See OAuth 2.1 and MCP endpoint.

Catalog, quote, cart checkout, payment and confirmation

sequenceDiagram
  autonumber
  participant A as Agent
  participant S as agents.snappy.com
  participant U as Shopper
  participant ST as Stripe
  participant Q as Cloud Tasks
  participant SN as Snappy API
  A->>S: GET /v1/search, /v1/products/:id, /v1/variants/:id/availability
  S->>SN: products, variants, live availability per country
  S-->>A: all-in price per country (item + shipping + duties + service fee)
  A->>S: POST /v1/quotes (variantId) once per cart line
  S-->>A: qt_ with the price locked for 15 min
  A->>S: POST /v1/checkouts (quotes, recipient, address, notify, smsConsent, callbackUrl)
  S->>SN: validate the address for physical items
  S->>ST: create one Checkout Session, one line per item, expires with the checkout (30 min)
  S-->>A: chk_ pending_payment with paymentUrl, statusUrl, eventsUrl, nextStep
  A->>U: hand over paymentUrl, never ask for card details
  U->>ST: pays on the hosted Stripe page
  ST->>S: POST /webhooks/stripe checkout.session.completed (signature verified, deduped by event id)
  S->>S: paid amount and currency must match the quote, otherwise failed and refunded
  S->>Q: enqueue place-order, dedupe key place-chk_
  Q->>S: POST /internal/tasks/place-order with an OIDC token
  loop One Snappy order per item
    S->>SN: POST /v3/orders with idempotencyKey chk_:index
    SN-->>S: order id and tracking link, or a 4xx rejection for that item
  end
  S->>S: confirmed, partially_confirmed (rejected items refunded) or failed (refunded in full)
  S->>Q: enqueue notify-purchase-confirmed and agent-callback when callbackUrl is set
  par Poll or stream
    A->>S: GET /v1/checkouts/:id or GET /v1/checkouts/:id/events (SSE, Last-Event-ID resumes)
    S-->>A: status, items with orderIds, nextStep
  and Signed callback
    S->>A: POST callbackUrl with X-Snappy-Agents-Timestamp and X-Snappy-Agents-Signature
  end
  S-->>U: receipt by email (SendGrid) and by SMS (Twilio, only with consent on file)

The agent never touches money: it quotes each item (15-minute price lock), creates one checkout for the cart and hands the user a hosted Stripe link. Stripe's signed checkout.session.completed webhook moves the checkout to paid and enqueues place-order, which creates one Snappy order per item with idempotencyKey = <checkout id>:<item index> so retries can never double-order. Confirmation reaches the agent by polling, SSE or a signed callback, and the receipt reaches the user by email and, with consent, SMS. See Checkout flow and the Quickstart.

Checkout state machine

stateDiagram-v2
  [*] --> pending_payment: POST /v1/checkouts, Stripe session created
  pending_payment --> paid: checkout.session.completed, amount and currency match
  pending_payment --> failed: payment amount or currency mismatch
  pending_payment --> expired: 30 min passed or checkout.session.expired
  pending_payment --> cancelled: POST /v1/checkouts/:id/cancel
  expired --> paid: payment completed after the checkout had expired
  paid --> placing: place-order task starts
  placing --> placing: retryable Snappy error, task retried with the same idempotency keys
  placing --> confirmed: every item placed at Snappy
  placing --> partially_confirmed: some items rejected by Snappy, their amount refunded
  placing --> failed: no item could be placed
  failed --> refunded: refund-checkout task, full refund on the original payment
  confirmed --> [*]
  partially_confirmed --> [*]
  refunded --> [*]
  expired --> [*]
  cancelled --> [*]

pending_payment is the only state the agent can cancel. After payment the amount and currency are checked against the quote; a mismatch is marked failed and refunded without placing anything. placing keeps retrying retryable Snappy errors with the same idempotency keys; definitive 4xx rejections make the checkout partially_confirmed (the rejected items' amounts are refunded) or failed then refunded. Stale pending_payment checkouts are expired lazily on read and by the expire-checkouts job every five minutes. See Checkout flow.

Order lifecycle and Snappy webhooks

flowchart TD
  placed["ord_ created by the place-order task: stage confirmed, nextActions cancel + track"] --> source{"what moves it"}
  source -->|"Snappy webhook POST /webhooks/snappy, HMAC verified, deduped by event id"| sync["sync-order task: pull the order from Snappy, map fulfilment and delivery status"]
  source -->|"GET /v1/orders/:id?refresh=true or admin Resync"| sync
  sync --> stage{"stage"}
  stage -->|processing| processing["processing"]
  stage -->|inTransit| shipped["shipped: notify-shipping email and SMS with tracking"]
  stage -->|outForDelivery| ofd["out_for_delivery: notified"]
  stage -->|delivered| delivered["delivered: notified"]
  stage -->|"cancelled or refunded at Snappy"| cancelledS["cancelled or refunded"]
  cancel["POST /v1/orders/:id/cancel by the agent, or Cancel and refund in the admin portal"] --> snc{"Snappy accepts the cancellation?"}
  snc -->|"yes, still unfulfilled"| refund["Stripe refund of this item, idempotency key cancel:ord_"] --> cancelled["cancelled: order_cancelled email"]
  snc -->|"no, Snappy answers 422"| notc["409 order_not_cancellable with nextAction request_support"]
  notc --> support["Support request: return, damaged, wrong item, not received"]
  support --> partial["Operator refund, partial or full, on the original payment and recorded on the order"]

Each placed item is its own ord_ row whose stage is derived from Snappy's order, fulfilment and delivery status. Snappy's signed webhooks (and ?refresh=true) enqueue a sync-order task; a change to shipped, out for delivery or delivered also sends the shipping notification. Cancellation is attempted at Snappy and refunds the item's amount when accepted; once fulfilment started, the error carries nextAction: request_support. See Checkout flow, after the purchase.

Open agentic commerce protocols (ACP, UCP, feeds)

sequenceDiagram
  autonumber
  participant P as Agent platform (ChatGPT over ACP, Google or Shop over UCP)
  participant S as agents.snappy.com
  participant PSP as Stripe, or the fake provider on sandbox
  participant Q as Cloud Tasks
  participant SN as Snappy API
  P->>S: GET /.well-known/acp.json, or /.well-known/ucp and /.well-known/jwks.json
  P->>S: POST /acp/checkout_sessions or /ucp/v1/checkout-sessions with a platform key and Idempotency-Key (ACP adds API-Version, UCP adds UCP-Agent and an optional RFC 9421 signature)
  S->>S: platform key checked before validation, idempotency key claimed (replay, conflict or in flight)
  S->>SN: variants, products, availability for the ship-to country
  S-->>P: pcs_ session with live totals, fulfillment options and messages (missing buyer info, out of stock), UCP adds ap2.merchant_authorization
  P->>S: update (ACP POST, UCP PUT) with the address, items, buyer
  P->>S: complete with the payment credential (ACP spt_, UCP Google Pay token, optionally an AP2 checkout mandate)
  S->>S: verify the mandate (UCP), re-price (a price_change warning stops here), create guest user and quotes, pre-allocate chk_
  S->>PSP: PaymentIntent with the delegated token, idempotency key scoped to the checkout
  alt declined or needs authentication
    S-->>P: 200 with the session still open and a payment_declined or requires_3ds message
  else succeeded
    S->>SN: POST /v3/orders per unit with idempotencyKey chk_ plus index (retryable errors continue on the place-order task)
    S-->>P: completed session with order id, number and permalink_url
    S->>Q: enqueue protocol-order-event on every order event (created, confirmed, shipped, delivered, canceled, refunded)
    Q->>S: POST /internal/tasks/protocol-order-event
    S->>P: ACP order_create or order_update with Merchant-Signature, UCP order entity to Google's endpoint (API key) or the platform URL (RFC 9421), 12 attempts
  end
  Note over S: expire-protocol-sessions every 10 min expires open sessions past the TTL and purges idempotency keys older than 48 h

A protocol session is the platform's view of a cart; the money and the orders go through the same checkout, placement, refund and notification paths as the connector, which is why the sequence ends in chk_ and ord_ rows. Product feeds (/feeds/products.jsonl, /feeds/google.csv, /feeds/products.csv, feed token, 30 min cache) are how the platforms learn the variant ids they put in line_items. See Agentic commerce.

Post-purchase support

flowchart TD
  start["Agent: POST /v1/orders/:id/support-requests or MCP request_support (type, summary, details, preferredResolution, contact)"] --> chk{"checks"}
  chk -->|"order already refunded in full"| e1["409 order_already_refunded"]
  chk -->|"type cancel while the order is still cancellable"| e2["409 use_cancel_endpoint, nextAction cancel"]
  chk -->|"an open request exists for this order"| same["the existing open request is returned"]
  chk -->|ok| create["sup_ created with status open, event support.requested on the timeline"]
  create --> opsmail["Email to the support mailbox (settings.supportEmail) with the full order context"]
  create --> ack["Acknowledgement email to the contact address"]
  opsmail --> portal["Admin portal: Support list and detail"]
  portal --> take["Take: status in_progress, assignedTo"]
  take --> decide{"Resolution"}
  decide -->|"Refund"| refund["Refund, partial or full, on the original Stripe payment, idempotency key support:id:amount, recorded on the order"] --> resolved["resolved, resolution refund"]
  decide -->|"Replacement"| repl["status resolved, resolution replacement, note"] --> resolved2["resolved"]
  decide -->|"Reject"| rej["status rejected, note"]
  resolved --> mail["support_resolved email to the user, event support.resolved, audit log entry"]
  resolved2 --> mail
  rej --> mail
  list["Agent: GET /v1/support-requests or GET /v1/orders/:id/support-requests"] -.-> create

A support request is a structured record (return, damaged, wrong item, not received, other) tied to one order, with one open request per order. Support is emailed the full context, the user gets an acknowledgement, and operators resolve it in the portal with a partial or full refund on the original payment, a replacement or a rejection; the user is emailed the outcome and the action is audited. See Checkout flow, support requests and the Operations runbook.

flowchart TD
  subgraph outbound["Sending an SMS: checkout notify.sms or a receipt by SMS"]
    want["number given"] --> opt{"latest consent record for the number revoked by STOP?"}
    opt -->|yes| e1["422 sms_opted_out: use email or ask the user to text START"]
    opt -->|no| has{"active consent on file?"}
    has -->|yes| send["send through the Twilio Messaging Service (A2P 10DLC)"]
    has -->|no| flag{"smsConsent true in the request?"}
    flag -->|no| e2["422 sms_consent_required with the consentText to read to the user"]
    flag -->|yes| rec["consent recorded: phone, user, agent client, source, text, timestamp"] --> send
    send --> first["the first message ends with Reply STOP to opt out, every message is stored"]
  end
  subgraph inbound["Inbound keyword: POST /webhooks/twilio"]
    hook["Twilio posts From, Body, MessageSid"] --> sig{"X-Twilio-Signature valid for the public URL?"}
    sig -->|no| e3["401 webhook_signature_invalid"]
    sig -->|yes| dedupe["deduped by MessageSid"] --> kw{"keyword"}
    kw -->|"STOP, STOPALL, UNSUBSCRIBE, CANCEL, END, QUIT"| stop["consent revoked (an opt-out is recorded even without prior consent), reply: unsubscribed, text START to resubscribe"]
    kw -->|"START, UNSTOP, YES"| startk["consent recorded with source sms_keyword, reply: resubscribed"]
    kw -->|"HELP, INFO"| help["reply with the support contact and opt-out instructions"]
    kw -->|other| none["no action, empty TwiML"]
  end

Texting a US number needs prior express consent (TCPA/CTIA), so a number is only texted with an active consent record, and smsConsent: true is accepted only after the agent read the consent text to the user. Inbound keywords arrive on /webhooks/twilio, are signature-checked and deduplicated, and STOP revokes consent for good until the user texts START; the messaging service also refuses to send to an opted-out number as a second line of defence. See Checkout flow, SMS consent and Security and data.

Price negotiation decision pipeline

flowchart TD
  req["negotiate_price or POST /v1/negotiations: variantId, requestedPrice, competitorPrice, competitorUrl, competitorName, message, previousNegotiationId"] --> guard{"negotiation enabled, user active, variant available in the country?"}
  guard -->|no| err["409 negotiation_disabled, 403 user_suspended or 422 variant_unavailable_in_country"]
  guard -->|yes| round["round: previousNegotiationId or an open conversation inside offerTtlMinutes continues (the prior offer is superseded), an identical open ask returns the same offer"]
  round --> ev{"competitorUrl given and verifyCompetitorUrl on?"}
  ev -->|yes| fetch["fetch the page server-side (public hosts only, 5 s, 1 MB) and read the price from JSON-LD, meta tags, microdata or text"]
  fetch --> evres["evidence.verified when the page price is within 2% or 0.50 of the claim in the quote currency, otherwise evidence.mismatch or evidence.unverified"]
  ev -->|no| claim["a competitorPrice without a link is an unverified shopper_claim"]
  evres --> rules
  claim --> rules
  rules["rules: floor = list minus maxDiscountPercent (per-product override, cost plus margin when allowBelowCost is off), price match, goodwill, maxRounds, then accept, counter or reject"] --> mode{"mode ai, room below list, round within maxRounds?"}
  mode -->|no| decided
  mode -->|yes| key{"Anthropic key configured in Integrations?"}
  key -->|no| skip["ai.skipped: the rules decide"] --> decided
  key -->|yes| ai["Claude through the Messages API: item, list, floor, ask, words, evidence, the rules suggestion, up to 3 web searches when onlinePriceCheck is on, answer through the submit_decision tool"]
  ai -->|"error or timeout"| fail["ai.failed: the rules decide"] --> decided
  ai --> clamp["clamp the price into floor..list, recompute accept, counter or reject"] --> decided
  decided["decided: neg_ offered or rejected, expiresAt = now + offerTtlMinutes, customer message, every step in the event log"]
  decided --> accept["accept_offer or createQuote with negotiationId before expiresAt"] --> quote["qt_ with discountAmount, 15 min lock, negotiation applied"] --> checkout["create_checkout, Stripe charges the discounted total"]
  decided -.->|"admin override: a new offer at any price down to zero, or a rejection, with a note"| decided

A negotiation gathers evidence (a cited competitor page is fetched and its listed price read), lets the deterministic rules fix the floor and a decision of their own, and in ai mode lets Claude reason inside those bounds with up to three web searches. The model's price is clamped into [floor, list] and the decision recomputed, so neither the model nor a shopper's prompt can push a price under the floor; without an Anthropic key, or when the call fails, the rules' decision stands. Operators see every step and can override any decision. See Price negotiation.

Negotiation status machine

stateDiagram-v2
  [*] --> offered: decision accept or counter
  [*] --> rejected: decision reject, the list price stands
  offered --> applied: accept_offer or createQuote with negotiationId, quoteId set
  offered --> expired: offerTtlMinutes passed, marked on the next read
  offered --> superseded: a later round for the same item replaced it
  offered --> offered: admin override with a new price and TTL, decidedBy admin
  offered --> rejected: admin override reject
  rejected --> offered: admin override with an offer
  expired --> offered: admin override with an offer
  superseded --> offered: admin override with an offer
  rejected --> [*]: the shopper can negotiate again, next round inside the window
  applied --> [*]: the quote goes to checkout, cannot be overridden
  expired --> [*]
  superseded --> [*]

An offer is tied to the shopper, the variant and the country it was priced for and lives for offerTtlMinutes. Accepting it turns it into a normal 15-minute quote and marks it applied; a new round supersedes it; expiry is marked lazily on read. An admin override reopens any negotiation that has not been applied. See Price negotiation.

Admin portal operations

flowchart TD
  op["Operator opens https://host/admin"] --> lb["Load balancer routes /admin* to the IAP-enabled backend of the same Cloud Run service"]
  lb --> iap["Identity-Aware Proxy: Google sign-in, organisation accounts only"]
  iap --> app["App verifies X-Goog-IAP-JWT-Assertion, audience must be a backend of this project"]
  app --> dom{"email on the allowed domain and listed in admins (or in ADMIN_EMAILS for the first bootstrap)?"}
  dom -->|no| deny["403 admin_domain or admin_not_allowlisted"]
  dom -->|yes| role{"role"}
  role -->|viewer| read["Read: dashboard, users, orders, checkouts, support, negotiations, integrations status, settings, admins, audit log, webhook deliveries"]
  role -->|admin| write["Write: every action is written to the audit log with actor, action, target and data"]
  write --> users["Users: suspend, revoke agent tokens"]
  write --> orders["Orders: cancel and refund, resync from Snappy, resend receipt"]
  write --> support["Support: take, refund partial or full, resolve, reject"]
  write --> neg["Negotiations: override with a new offer or a rejection"]
  write --> integ["Integrations: save or remove credentials (Secret Manager), test connection"]
  write --> settings["Settings: service fee, ship-to countries, order cap, maintenance mode, support contacts, negotiation bounds and AI prompt (10 s cache)"]
  write --> clients["Agent clients: pre-provision, disable"]
  write --> admins["Admins: add viewer or admin, remove"]
  write --> audit[("audit_log")]
  alt["Session mode (ADMIN_AUTH_MODE=session): Google ID token sign-in, or the local-only dev sign-in with an ADMIN_EMAILS address, into a signed cookie"] -.-> dom

In the cloud the portal sits behind Identity-Aware Proxy; the app then verifies the IAP assertion and applies its own allowlist with viewer and admin roles. Viewers read everything, admins act, and every privileged action lands in the audit log. Settings changes take effect within ten seconds and credential changes on the next request, without a redeploy. See Operations runbook, admin portal.

CI/CD and infrastructure

flowchart TD
  pr["Pull request"] --> ci["CI test job: pnpm install, build packages, typecheck, unit and component tests with coverage, build api, admin and docs, export and lint the OpenAPI document"]
  pr --> docker["CI docker job: build the image, boot it with fixtures, fake payments and sink messaging, curl healthz, readyz, manifest, openapi, docs, admin, then the Playwright smoke of the real user path on desktop and mobile"]
  pr --> tofuv["CI terraform job: tofu fmt and validate on every root"]
  pr -->|"infra/terraform/** changed"| plan["Infrastructure: format, validate every root and run the mocked module tests, with no cloud identity"]
  main["Push to main"] --> ci
  main --> docker
  main --> tofuv
  main -->|"any path except infra/** and *.md"| deploy["Deploy sandbox: pnpm test gate, Workload Identity Federation as the deployer SA, build and push the image to Artifact Registry, gcloud run deploy agents-api with only the image changed, smoke the public path"]
  main -->|"infra/terraform/** changed"| apply["Infrastructure: plan and apply sandbox with the apply service account"]
  dispatch["workflow_dispatch"] -->|"Deploy with environment=prod"| gate{"GitHub prod environment: required reviewers approve"}
  gate -->|approved| deployprod["Deploy prod: same steps, prod GCP identities are bound to the prod environment claim"]
  dispatch -->|"Infrastructure with environment=prod"| gate2{"prod approval"}
  gate2 -->|approved| applyprod["plan, and apply only when apply=true"]
  dispatch -->|"Logs with environment, minutes, path"| logs["Logs: load balancer requests, Cloud Run requests and application lines at WARNING or above, read with the plan service account"]
  human["Once, by a human: infra/terraform/bootstrap creates the two projects, state buckets, WIF pool and CI identities, then their outputs become GitHub environment variables"] -.-> plan

Pull requests run the full CI (typecheck, tests, image build and browser smoke, Terraform validate) and, when infrastructure changed, format, validate and the mocked module tests (no cloud identity on a pull request). Merging to main deploys sandbox and applies sandbox infrastructure; production is a manual dispatch that waits for the GitHub prod environment approval, and the prod GCP identities can only be impersonated with that approval. See Operations runbook and Architecture.

Secrets and integrations

flowchart TD
  tf["Terraform creates the secret containers, never the values: snappy-api-key, snappy-webhook-secret, stripe-secret-key, stripe-webhook-secret, sendgrid-api-key, twilio-auth-token, anthropic-api-key, google-ucp-order-webhook-key, catalog-feed-token, ucp-signing-keys"] --> sm[("Secret Manager")]
  keys["The app itself writes ucp-signing-keys: the first UCP profile request generates the ES256 key, Protocols → Generate new signing key adds a version"] --> sm
  boot["Once per environment, by an operator with gcloud: auth-token-secret, tasks-shared-secret (database-url is written by Terraform)"] --> sm
  admin["Admin portal, Integrations, admin role"] -->|"PUT /admin/api/integrations/:id"| svc["IntegrationsService.update"]
  svc -->|"secret fields"| add["addSecretVersion: the new version becomes latest (the container is created only if genuinely missing)"] --> sm
  svc -->|"non-secret fields: account id, billing method, from email, SIDs, base URLs"| db[("settings row: values, plus masked last4 and updatedAt for secrets")]
  svc --> bump["integrations version incremented, audit integration.updated"]
  bump --> dyn["Dynamic providers (Snappy client, Stripe, SendGrid, Twilio, Anthropic) rebuild on the next request when the version changed, no redeploy"]
  dyn -->|"read latest, 60 s cache"| sm
  test["Test connection: POST /admin/api/integrations/:id/test"] --> probe["Snappy billing methods, Stripe balance, SendGrid scopes, Anthropic models, Twilio account"]
  lookup["Snappy lookup: a key typed once lists accounts, then billing methods, and is never stored"] --> probe
  remove["Remove: DELETE /admin/api/integrations/:id"] --> clear["disable every ENABLED version of its secrets, clear its fields, audit integration.removed"] --> sm
  clear --> fallback["Provider falls back: fixture catalog and fake pay page on sandbox, sink messaging, rules-only negotiation, a *_not_configured error on prod"]

Terraform owns the secret containers, operators own the values. A credential saved in the Integrations page becomes a new Secret Manager version; the dynamic providers notice the version change on the next request, so keys rotate without a deploy and never pass through the repository, CI or the database (only a masked last-4 and a timestamp are stored). Removing an integration disables its secret versions and the platform degrades to its fixture, fake or sink modes on sandbox. See Operations runbook, credentials.

Snappy Agents · agents.snappy.com · support@snappy.com