> This page is for MVS Pay.

> For clean Markdown of any page, append .md to the page URL.
> For a complete documentation index, see https://docs.mvscloud.com/llms.txt.
> For AI client integration (Claude Code, Cursor, etc.), connect to the MCP server at https://docs.mvscloud.com/_mcp/server.

# Payouts & Instant Payouts

This page covers how money leaves the platform: Hyperswitch-native **payouts**, their MVS **settlement** sidecar and approval workflow, **payout methods** (push-to-card debit cards and Plaid-linked ACH bank accounts), the Plaid **Link → exchange** flow, **instant payouts** against a linked method, and the async **settlement reconciliation** that the Temporal `pay-crons` worker performs.

The two architectural rules to internalize before reading further:

1. **Hyperswitch is the source of truth for the money movement.** Every payout is a Hyperswitch payout object. MVS only stores *sidecar* rows (`SettlementExtension`, `InstantPayoutRequest`, `PayoutMethod`, `PlaidItem`) for things Hyperswitch does not model — an approval gate, funding-attempt history, ACH bank linking, and operator visibility. See [Hyperswitch pivot](/mvs-pay/guides/concepts/hyperswitch-pivot).
2. **There are two services.** The Next.js dashboard app (`apps/mvs-pay`) is the customer/operator-facing API; it proxies to the **extensions service** (`apps/mvs-pay-extensions`, a Hono app) which owns the sidecar tables, the Plaid integration, and the tenant-scoped Prisma client. See [Extensions service](/mvs-pay/guides/surfaces/extensions-service).

> **Note**
>
> Plaid bank linking, instant payouts against Plaid methods, and the encrypted-token storage are **Phase 5 / M24** work. They are wired end-to-end in code, but Plaid **production** credentials are not yet provisioned — only sandbox keys are usable today (production access carries a 5–10 business-day Plaid approval SLA). See the [Plaid Link runbook](/mvs-pay/guides/operations/runbooks/plaid-link).

## Vocabulary

| Term                     | What it is                                                                                                                                              | Where it lives                 |
| ------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------ |
| **Payout**               | A Hyperswitch payout object — the actual transfer of funds out.                                                                                         | Hyperswitch (source of truth)  |
| **SettlementExtension**  | MVS sidecar for a payout: approval gate, platform notes, links to funding attempts. Keyed by `hyperswitchPayoutId`.                                     | `settlement_extension` table   |
| **PayoutMethod**         | A destination: a push-to-card debit card (tokenized by Hyperswitch) **or** a Plaid-verified ACH bank account.                                           | `payout_method` table          |
| **InstantPayoutRequest** | One attempt to push funds to a `PayoutMethod`. Tracks status + Hyperswitch payout id + failure detail. Doubles as the per-settlement "funding attempt." | `instant_payout_request` table |
| **PlaidItem**            | Plaid linked-bank metadata (institution, account mask, verification status, webhook state). One row per Plaid Item, unique per org.                     | `plaid_item` table             |

These models are also documented in [Data model](/mvs-pay/guides/concepts/data-model).

## Plain payouts (Hyperswitch-native)

The dashboard's payout surface is a thin pass-through to Hyperswitch with a settlement sidecar attached on create.

### Extensions service routes

`apps/mvs-pay-extensions/src/routes/payouts.ts` is a near-verbatim proxy to the Hyperswitch payouts API — no sidecar logic, no tenant table writes:

| Method & path                  | Hyperswitch call                                   |
| ------------------------------ | -------------------------------------------------- |
| `POST /v1/payouts`             | `hyperswitch.payouts.create(body, idempotencyKey)` |
| `GET /v1/payouts/:id`          | `hyperswitch.payouts.get(id)`                      |
| `POST /v1/payouts/:id/confirm` | `hyperswitch.payouts.confirm(id)`                  |
| `POST /v1/payouts/:id/cancel`  | `hyperswitch.payouts.cancel(id)`                   |
| `GET /v1/payouts`              | `hyperswitch.payouts.list()`                       |

Errors are mapped through `mapErr`: a `HyperswitchApiError` is re-emitted as `{ error: <responseBody> }` with the upstream status (via `asContentfulStatus`); anything else re-throws. The `idempotency-key` header is forwarded to Hyperswitch on create.

See the API Reference tab for request/response shapes.

### Dashboard app: payout + sidecar

`apps/mvs-pay/app/api/payouts/route.ts` is where the **settlement sidecar** is created. On `POST /api/payouts`:

1. Authenticate with the `settlements:write` scope.
2. Create the Hyperswitch payout via the SDK (`mvsPayClient(...).payouts.create`). An `idempotency-key` header is honored; otherwise one is synthesized as `mvspay_<orgId>_<uuid>`.
3. If the response has no `payout_id`, fail `502` — we refuse to persist a sidecar we cannot key.
4. Upsert a `SettlementExtension` keyed on `hyperswitchPayoutId` with `approvalStatus: "PENDING"`.

`GET /api/payouts` lists Hyperswitch payouts (scope `settlements:read`) and joins each with its org-scoped `settlementExtension`. Note the explicit tenant guard: even after a `findUnique` on the globally-unique `hyperswitchPayoutId`, the row is discarded unless `ext.organizationId === organizationId`.

```mermaid
flowchart LR
  A[Dashboard POST /api/payouts] --> B[SDK payouts.create]
  B --> C[Hyperswitch payout object]
  C -->|payout_id| D[upsert SettlementExtension\napprovalStatus=PENDING]
  D --> E[201 payout + extension]
```

## Settlements & the approval gate

`SettlementExtension` (`schema.prisma`, `model SettlementExtension`) is the MVS-only workflow layer over a Hyperswitch payout. Selected fields:

```prisma
model SettlementExtension {
  id                    String   @id @default(cuid())
  organizationId        String
  merchantExtensionId   String?
  hyperswitchPayoutId   String   @unique
  hyperswitchMerchantId String?

  // Platform approval workflow — MVS-specific gate before payout funds.
  approvalStatus  String    @default("PENDING") // PENDING, APPROVED, REJECTED
  approvedAt      DateTime?
  approvedBy      String?
  rejectedAt      DateTime?
  rejectedBy      String?
  rejectionReason String?
  reviewDeadline  DateTime?
  platformNotes   String?

  instantPayoutRequests InstantPayoutRequest[]
}
```

The relationship that matters operationally: **one `SettlementExtension` has many `InstantPayoutRequest` rows** — each one a funding attempt. Hyperswitch has no per-settlement funding-attempt API, so this history lives entirely in MVS tables.

> **Warning**
>
> The `approvalStatus` column models an approve/reject gate, but the **enforcement** of that gate (refusing to fund a settlement that is still `PENDING`/`REJECTED`) is **not** implemented in the instant-payout create path described below — it checks the payout *method*'s `enabled`/`verified` flags, not the settlement's `approvalStatus`. If you are adding hard approval enforcement, that check does not exist yet; treat the gate as advisory/operator-facing today.

### Funding-attempt history

`apps/mvs-pay-extensions/src/routes/settlements.ts` exposes one read endpoint:

```
GET /v1/settlements/:id/funding-attempts
```

`:id` may be the `SettlementExtension` cuid **or** its globally-unique `hyperswitchPayoutId` — it resolves with an `OR` filter that is always tenant-scoped by `organizationId` (the isolation boundary). It then returns the `InstantPayoutRequest` rows for that settlement, newest-first.

The dashboard surfaces this at `GET /api/settlements/[id]/funding-attempts` (`apps/mvs-pay/app/api/settlements/[id]/funding-attempts/route.ts`, scope `settlements:read`), proxying through `mvsPayClient.settlements.fundingAttempts`.

## Payout methods

A `PayoutMethod` is a payout *destination*. Two flavors share the table:

| `type`                   | Created by                                                     | `hyperswitchPaymentMethodId`           | Verification signal                         |
| ------------------------ | -------------------------------------------------------------- | -------------------------------------- | ------------------------------------------- |
| `PAYMENT_CARD` (default) | `POST /v1/payout-methods` with a Hyperswitch payment-method id | Real Hyperswitch token                 | Token must still resolve in Hyperswitch     |
| `BANK_ACCOUNT`           | Plaid `/v1/plaid/exchange`                                     | Synthetic handle `plaid:<plaidItemId>` | `accessTokenEnc` + `plaidAccountId` present |

The synthetic id for bank accounts is deliberate: there is no Hyperswitch payment-method id for an ACH account, so the Plaid Item id is used as a stable, unique handle to satisfy the `@unique` constraint on `hyperswitchPaymentMethodId`.

### Routes

`apps/mvs-pay-extensions/src/routes/payout-methods.ts`. All routes require `tenant.organizationId` (else `400 tenant_required`) and are Prisma-scoped to that org.

| Method & path                             | Behavior                                                                                                                                                             |
| ----------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `GET /v1/payout-methods`                  | List org's methods, newest-first.                                                                                                                                    |
| `POST /v1/payout-methods`                 | Create a push-to-card method from a `hyperswitch_payment_method_id` + `hyperswitch_merchant_id` (+ optional card display fields). Defaults `type` to `PAYMENT_CARD`. |
| `GET /v1/payout-methods/:id/verification` | Return `{ verified, verificationId, lastVerifiedAt, plaidVerifiedAt, pushToCardEligible }`. `404` if not owned.                                                      |
| `POST /v1/payout-methods/:id/verify`      | Flip `verified=true` (see logic below). `404` if not owned.                                                                                                          |
| `DELETE /v1/payout-methods/:id`           | Tenant-scoped `deleteMany`; returns `{ ok: true }`.                                                                                                                  |

### Verify logic

`POST /v1/payout-methods/:id/verify` branches on how the method was created:

#### Ownership check first

`findFirst` scoped by `id` + `organizationId`. A no-match returns `404 not_found` — never a blind success — so you cannot verify a method another org owns.

#### Plaid-backed bank account

If `accessTokenEnc` **and** `plaidAccountId` are present, the account was already verified at Link/exchange time. Trust that signal: set `verified=true`, stamp `lastVerifiedAt`, and set `plaidVerifiedAt` if not already set.

#### Push-to-card debit card

Otherwise the Hyperswitch token must still resolve — call `hyperswitch.paymentMethods.get(method.hyperswitchPaymentMethodId)`. A missing/invalid token returns `payment_method_unverifiable` with the upstream status and must **not** pass. Only on success do we flip `verified=true`.

The `PayoutMethod` model carries several push-to-card eligibility columns (`pushToCardEligible`, `domesticPushToCard`, `crossBorderPushToCard`) that are present in the schema but **not populated** by any route in this directory today — treat them as reserved for a future eligibility-probe step.

## Plaid ACH linking

The end-to-end goal: let an org link a real bank account via Plaid Auth and use it as an instant-payout destination, without ever storing a raw Plaid access token in the database in plaintext.

### Configuration & gating

Plaid config lives in `apps/mvs-pay-extensions/src/config/index.ts` under `config.plaid`:

| Field           | Env var                | Notes                                                       |
| --------------- | ---------------------- | ----------------------------------------------------------- |
| `clientId`      | `PLAID_CLIENT_ID`      | non-secret but environment-scoped                           |
| `secret`        | `PLAID_SECRET`         | sandbox vs prod secret                                      |
| `environment`   | `PLAID_ENV`            | `sandbox` (default) / `development` / `production`          |
| `webhookUrl`    | `PLAID_WEBHOOK_URL`    | baked into link tokens; must terminate at `/webhooks/plaid` |
| `webhookSecret` | `PLAID_WEBHOOK_SECRET` | optional HMAC verification key                              |

`isPlaidConfigured()` returns true only when both `clientId` and `secret` are set. The Plaid client (`apps/mvs-pay-extensions/src/services/plaid-client.ts`) is a lazily-constructed `PlaidApi` singleton; it throws if instantiated while unconfigured. Both Plaid routes short-circuit to **`503 plaid_not_configured`** before the client is ever built, so that throw only fires on local-dev misconfiguration.

### Token & secret storage

There are two stores in play, and the comments in the schema and code do not fully agree — worth knowing:

* **`PayoutMethod.accessTokenEnc`** and **`PlaidItem.accessTokenEnc`** hold the AES-256-GCM ciphertext of the Plaid access token, produced by `encryptForOrg(organizationId, accessToken)` from `@mvs/secrets/encryption`. Wire format is `v1:<iv-base64>:<tag-base64>:<ciphertext-base64>`, and the org id is mixed into the GCM **AAD** (`org:<id>`) so a ciphertext leaked from one org cannot be decrypted under another. The key comes from `MVS_PAY_KMS_KEY` (production refuses to start without it; non-prod falls back to a deterministic scrypt-derived dev key).
* **`PlaidItem.accessTokenSecretName`** stores a reference string (`PLAID_ACCESS_TOKEN_<itemId>`). The model comment describes access tokens living in Infisical under `/tenants/{slug}/PLAID_ACCESS_TOKEN_{itemId}`, with only the name reference in the DB. In current code (`/v1/plaid/exchange`) the encrypted token is written directly to `accessTokenEnc`; `accessTokenSecretName` is set but the Infisical-stored-token path is the legacy/older-row story. New rows resolve via `accessTokenEnc`.

> **Warning**
>
> Nothing in this directory **decrypts** `accessTokenEnc` yet. The instant-payout create path (below) drives Hyperswitch off `hyperswitchPaymentMethodId`, which for a Plaid bank account is the synthetic `plaid:<id>` handle — **not** a real Hyperswitch payment method. So while a Plaid bank account can be linked, verified, and have an `InstantPayoutRequest` row created against it, the actual ACH transfer rail is not wired through Hyperswitch in this code path. See "Known gaps" below before promising customers ACH payouts.

### Link flow

`apps/mvs-pay-extensions/src/routes/plaid.ts` exposes two endpoints. Both emit a `phiAudit.logAccess` entry attributing the action to the org.

**`POST /v1/plaid/link-token`** mints a short-lived `link_token` for the browser-side `usePlaidLink` hook / `<MvsPayInstantPayoutPicker>` component:

```ts
const request: LinkTokenCreateRequest = {
  user: { client_user_id: tenant.organizationId },
  client_name: "MVS Pay",
  products: [Products.Auth],
  country_codes: [CountryCode.Us],
  language: "en",
  ...(config.plaid.webhookUrl ? { webhook: config.plaid.webhookUrl } : {}),
};
```

**`POST /v1/plaid/exchange`** trades the single-use `public_token` for a long-lived access token and persists the linked account. Body: `{ public_token, account_id }`. Steps:

1. `400 missing_fields` if either field is absent.
2. `itemPublicTokenExchange({ public_token })` → `access_token` + `item_id`.
3. `accountsGet({ access_token })` → accounts + institution id.
4. Find the chosen `account_id` in the item; `404 account_not_found_in_item` if missing.
5. `encryptForOrg(orgId, accessToken)` → ciphertext.
6. **Upsert** a `PlaidItem` on the `(organizationId, itemId)` compound unique. Re-link resets `lastErrorCode`/`lastErrorMessage`/`loginRequiredAt` to null and sets `verificationStatus: "verified"`.
7. **Create** a `PayoutMethod` (`type: "BANK_ACCOUNT"`, synthetic `plaid:<plaidItemId>` handle, `verified: true`, `plaidVerifiedAt: now`, `hyperswitchMerchantId: ""`).
8. Return `{ payoutMethodId }` for the caller to hand to the instant-payout picker.

```mermaid
sequenceDiagram
  participant UI as Browser (Plaid Link)
  participant Ext as extensions /v1/plaid
  participant Plaid as Plaid API
  participant DB as mvs-pay DB

  UI->>Ext: POST /link-token
  Ext->>Plaid: linkTokenCreate (Auth, US)
  Plaid-->>Ext: link_token
  Ext-->>UI: { link_token }
  Note over UI,Plaid: user authenticates bank in Link iframe
  UI->>Ext: POST /exchange { public_token, account_id }
  Ext->>Plaid: itemPublicTokenExchange
  Plaid-->>Ext: access_token, item_id
  Ext->>Plaid: accountsGet
  Plaid-->>Ext: accounts[]
  Ext->>DB: upsert PlaidItem (encrypt token, AAD=org)
  Ext->>DB: create PayoutMethod (BANK_ACCOUNT, verified)
  Ext-->>UI: { payoutMethodId }
```

### Tenant scoping & error mapping

Every Prisma query in these routes filters by `tenant.organizationId`, and the org id is bound into the ciphertext AAD so a leaked column value cannot be replayed cross-org. Plaid errors are funneled through `describePlaidError`:

| Condition                                       | HTTP status | Body `error`           |
| ----------------------------------------------- | ----------- | ---------------------- |
| `INVALID_PUBLIC_TOKEN` / `INVALID_ACCESS_TOKEN` | `400`       | `invalid_token`        |
| Plaid responded `401`                           | `401`       | `plaid_unauthorized`   |
| anything else                                   | `502`       | `plaid_upstream_error` |

### Sanitized Plaid logging

> **Warning**
>
> **Never log a raw Plaid/axios error.** A raw axios error serializes `err.config.data`, `err.config.headers`, and `err.response.config`, which would leak the Plaid `access_token`, `public_token`, and our Plaid API `secret` / `client_id` into the logs.

`plaid.ts` enforces this with a dedicated `plaidErrorLogFields(err)` helper that extracts **only** three safe fields — the Plaid `error_code`, `error_message`, and HTTP `status` — and that is the only shape ever passed to `logger.warn`:

```ts
logger.warn(
  {
    plaidError: plaidErrorLogFields(err), // { code, message, status } only
    organizationId: tenant.organizationId,
  },
  "[plaid/exchange] Plaid call failed",
);
```

If you add new Plaid call sites, reuse `plaidErrorLogFields` — do not spread the error object into a log line.

### Plaid webhooks

`apps/mvs-pay-extensions/src/routes/webhooks-plaid.ts` ingests Plaid's single configured webhook URL (`/webhooks/plaid`). Behavior:

* **Signature**: in **production** an unset `PLAID_WEBHOOK_SECRET` fails closed (`503 not_configured`) — this state-mutating, internet-facing endpoint never silently skips verification in prod. If a secret is configured, the `Plaid-Verification` header must match an HMAC-SHA256 of the raw body (`timingSafeEqual`), else `401 signature_invalid`. Outside production an unset secret is tolerated for sandbox/pre-rotation testing.
* **Lookup**: `findPlaidItemByItemId` finds the row by `item_id` (globally unique via the `(organizationId, itemId)` index), then re-acquires a tenant-scoped client with the resolved `organizationId` for the update. Unknown items are ack'd as `{ ok: true, ignored: true }`.

Handled events:

| Event                         | Effect                                                                                                                                                                             |
| ----------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `ITEM:ERROR`                  | `verificationStatus = "broken"`, stamp `lastErrorCode`/`lastErrorMessage`; set `loginRequiredAt` if `ITEM_LOGIN_REQUIRED`.                                                         |
| `ITEM:PENDING_EXPIRATION`     | `verificationStatus = "pending_expiration"`; operator notification is **currently just a `logger.warn`** — real alerting via `@mvs/mail` is a follow-on milestone (not yet wired). |
| `AUTH:AUTOMATICALLY_VERIFIED` | Already covered at exchange time; ack `{ alreadyVerified: true }` and stamp `lastWebhookAt`.                                                                                       |
| (default)                     | Ack `{ unhandled: true }`, stamp `lastWebhookAt`/`webhookStatus`. Plaid retries non-2xx only.                                                                                      |

The webhook signature scheme here is the **simple HMAC fallback**; the runbook flags that production should rotate to Plaid's JWT-based verification.

## Instant payouts

An instant payout pushes funds to a previously-linked, verified `PayoutMethod` and tracks the attempt in `InstantPayoutRequest`.

### Model

```prisma
model InstantPayoutRequest {
  id                    String   @id @default(cuid())
  organizationId        String
  hyperswitchMerchantId String
  hyperswitchPayoutId   String?  // set once the Hyperswitch payout is created
  settlementExtensionId String?  // links this attempt to a settlement
  payoutMethodId        String
  amount                Int
  currency              String   @default("USD")
  status                String   @default("PENDING") // PENDING, REQUESTED, COMPLETED, FAILED
  fundingTransferId     String?
  failureCode           String?
  failureMessage        String?
  rail                  String   @default("INSTANT")
  requestedAt           DateTime @default(now())
  requestedBy           String?
  completedAt           DateTime?
  failedAt              DateTime?
}
```

`payoutMethod` is `onDelete: Restrict` — you cannot delete a `PayoutMethod` that has attempts pointing at it.

### Status state machine

```mermaid
stateDiagram-v2
  [*] --> PENDING: row created
  PENDING --> REQUESTED: Hyperswitch payout created (payout_id stored)
  PENDING --> FAILED: Hyperswitch create threw
  REQUESTED --> COMPLETED: reconciler sees succeeded/success/completed
  REQUESTED --> FAILED: reconciler sees failed/cancelled/expired/reversed
  COMPLETED --> [*]
  FAILED --> [*]
```

### Create flow

`apps/mvs-pay-extensions/src/routes/instant-payouts.ts`, `POST /v1/instant-payouts`. Requires `tenant.organizationId`. Body: `{ payout_method_id, amount, currency?, settlement_extension_id?, requested_by?, tenant_patient_id?, metadata? }`.

#### PHI audit

Emit `phiAudit.logAccess` (`resourceType: "instant_payout"`, `subAction: "instant_payout.create"`), carrying `tenant_patient_id` if supplied.

#### Resolve & gate the method

`findFirst` the `PayoutMethod` scoped by `id` + `organizationId`. `404 payout_method_not_found` if absent; `400 payout_method_not_verified` if `!enabled || !verified`.

#### Persist the attempt (PENDING)

Create the `InstantPayoutRequest` row up front (`status: "PENDING"`), copying `hyperswitchMerchantId` from the method and the optional `settlement_extension_id`. This guarantees operator visibility even if the Hyperswitch call fails.

#### Create the Hyperswitch payout

`hyperswitch.payouts.create({ amount, currency, payout_method_data: { payment_method_id: method.hyperswitchPaymentMethodId }, confirm: true, auto_fulfill: true, metadata: { mvs_org_id, mvs_instant_payout_request_id } }, idempotencyKey)`.

#### Record outcome

On success: store `hyperswitchPayoutId`, flip to `REQUESTED`, return the row plus `hyperswitch_payout_id`. On `HyperswitchApiError` (or any throw): flip to `FAILED`, stamp `failureMessage` + `failedAt`, and surface the upstream status.

> **Tip**
>
> Forward an `idempotency-key` header. It is passed straight to `hyperswitch.payouts.create`, so a retried request will not double-fund.

`GET /v1/instant-payouts` (paginated by `?limit`, default 50) and `GET /v1/instant-payouts/:id` are tenant-scoped reads.

### Dashboard entry points

* `POST /api/settlements/[id]/instant-payout` (`apps/mvs-pay/...`, scope `settlements:write`) — request an instant payout *for a settlement*. It accepts `payoutMethodId` (or legacy `paymentInstrumentId`), a positive `amount`, optional `currency`, and forwards an `idempotency-key`. It calls `client.instantPayouts.request({ ..., settlement_extension_id: id })`, which is how `InstantPayoutRequest.settlementExtensionId` gets populated and the attempt shows up under that settlement's funding-attempt history.

```mermaid
flowchart TD
  A[Dashboard POST /api/settlements/:id/instant-payout] --> B[SDK instantPayouts.request]
  B --> C[Ext POST /v1/instant-payouts]
  C --> D{method enabled & verified?}
  D -- no --> E[400 payout_method_not_verified]
  D -- yes --> F[create InstantPayoutRequest PENDING]
  F --> G[hyperswitch.payouts.create confirm+auto_fulfill]
  G -- ok --> H[REQUESTED + payout_id]
  G -- error --> I[FAILED + failureMessage]
  H -.async reconcile.-> J[COMPLETED / FAILED]
```

## Async settlement via the Temporal worker

The create path leaves a successful attempt in `REQUESTED` — it does **not** wait for the payout to actually settle. Reconciliation is owned by the `pay-crons` Temporal worker.

### The reconciliation workflow

`packages/temporal-workflows/src/workflows/mvs-pay.ts` defines `instantPayoutSettlementWorkflow`, scheduled every **15 minutes** (`packages/temporal-workflows/src/schedules/pay-crons.ts`, schedule id `pay-crons.instant-payout.settlement`, cron `*/15 * * * *`). Workflow code is deterministic; the side-effecting work is in the activity `runInstantPayoutSettlement` (`packages/temporal-workflows/src/activities/mvs-pay.ts`), proxied with a 10-minute start-to-close timeout and the Hyperswitch-API retry policy.

What the activity does (default `limit: 100` per run):

1. Load `InstantPayoutRequest` rows where `status === "REQUESTED"`, oldest-first.
2. Skip any without a `hyperswitchPayoutId` (nothing to reconcile yet).
3. `hyperswitch.payouts.get(payoutId)` and read `status`:
   * `succeeded` / `success` / `completed` → `COMPLETED` (+ `completedAt`).
   * `failed` / `cancelled` / `expired` / `reversed` → `FAILED` (+ `failedAt`, `failureCode`, `failureMessage`).
   * anything else → leave as `REQUESTED`, count as processed.
4. Return `{ processed, errors, details: { completed, failed, scanned } }`.

```mermaid
flowchart LR
  S[Temporal schedule\nevery 15m] --> W[instantPayoutSettlementWorkflow]
  W --> A[runInstantPayoutSettlement]
  A --> Q[(rows status=REQUESTED)]
  Q --> G[hyperswitch.payouts.get]
  G --> M{terminal status?}
  M -- succeeded --> C[status=COMPLETED]
  M -- failed/cancelled/expired/reversed --> F[status=FAILED]
  M -- pending --> R[leave REQUESTED]
```

> **Note**
>
> This activity uses the **global** `getMvsPayDb()` (no org filter) because it scans all orgs' `REQUESTED` rows. That is intentional for a platform-wide reconciler, but it means it is the one settlement code path that is *not* tenant-scoped — keep that in mind when modifying it.

### Related pay-crons (context)

The same `pay-crons` queue runs five other scheduled workflows. They are not payout-settlement but are listed so you know what else touches these tables / Hyperswitch:

| Schedule                         | Cadence           | Purpose                                                                          |
| -------------------------------- | ----------------- | -------------------------------------------------------------------------------- |
| `hyperswitchEventReplayWorkflow` | every 30m         | Retry non-delivered Hyperswitch webhook events.                                  |
| `residualEstimationWorkflow`     | monthly 1st 06:00 | Snapshot per-merchant gross/fees/net residual into `MerchantExtension.metadata`. |
| `residualChecksWorkflow`         | daily 10:00       | Alert on connector-fee % drift vs. baseline.                                     |
| `disputeSlaMonitorWorkflow`      | daily 09:00       | `DISPUTE_DEADLINE` notifications for overdue disputes.                           |
| `deviceHealthMonitorWorkflow`    | every 30m         | `DEVICE_OFFLINE` notifications for stale devices.                                |

(`webhookDlqDrainerWorkflow` and `successRateReconcileWorkflow` also run on this queue.)

## Known gaps & honesty checklist

#### Plaid ACH payout rail is not actually wired through Hyperswitch

A Plaid `BANK_ACCOUNT` `PayoutMethod` carries a synthetic `hyperswitchPaymentMethodId` of `plaid:<plaidItemId>` and an empty `hyperswitchMerchantId`. The instant-payout create path passes that handle to `hyperswitch.payouts.create` as `payment_method_id`. Hyperswitch will not recognize a `plaid:` handle, so an instant payout against a Plaid-linked account is expected to fail at the Hyperswitch call (landing the row in `FAILED`). The link/verify/store half is real; the ACH *disbursement* half is not. Push-to-card debit methods (real Hyperswitch tokens) are the working rail today.

#### accessTokenEnc is written but never decrypted in this code

No route or activity in the payouts/instant-payouts/plaid surface calls `decryptForOrg`. The encrypted Plaid access token is stored correctly but is not yet consumed by any disbursement flow.

#### Settlement approval gate is advisory, not enforced

`SettlementExtension.approvalStatus` exists and is set to `PENDING` on payout creation, but the instant-payout path does not check it before funding. There is no code that blocks a payout because its settlement is unapproved.

#### PENDING_EXPIRATION alerting is log-only

The Plaid `ITEM:PENDING_EXPIRATION` webhook only emits a `logger.warn`. Operator notification via `@mvs/mail` is a stated follow-on milestone and is not implemented.

#### Webhook signature is HMAC fallback, not Plaid JWT

`webhooks-plaid.ts` verifies an HMAC-SHA256 of the raw body against `PLAID_WEBHOOK_SECRET`. The runbook flags that production should move to Plaid's JWT verification; that rotation is not done.

#### Plaid production not provisioned

Only sandbox keys are usable today. Production cutover (separate `client_id`/`secret`, `PLAID_ENV=production`, prod `MVS_PAY_KMS_KEY`, prod webhook URL behind the WAF) is documented but pending Plaid's use-case approval. The KMS-key re-encryption migration referenced in rotation is a TODO tracked separately.

#### push-to-card eligibility columns unpopulated

`pushToCardEligible`, `domesticPushToCard`, `crossBorderPushToCard` exist on `PayoutMethod` but are not set by any route here.

## Where to go next

#### [Plaid Link runbook](/mvs-pay/guides/operations/runbooks/plaid-link)

Step-by-step credential provisioning, sandbox verification, webhook simulation, and production cutover.

#### [Secrets rotation](/mvs-pay/guides/operations/runbooks/secrets-rotation)

Rotating `PLAID_SECRET`, `PLAID_WEBHOOK_SECRET`, and the `MVS_PAY_KMS_KEY` data-encryption key.

#### [Extensions service](/mvs-pay/guides/surfaces/extensions-service)

The Hono app that owns these routes and the tenant-scoped Prisma client.

#### [Data model](/mvs-pay/guides/concepts/data-model)

Full schema for `SettlementExtension`, `PayoutMethod`, `InstantPayoutRequest`, `PlaidItem`.

#### [Hyperswitch pivot](/mvs-pay/guides/concepts/hyperswitch-pivot)

Why Hyperswitch is the source of truth and MVS only stores sidecars.

#### [Web SDK](/mvs-pay/guides/surfaces/sdk)

`payouts`, `instantPayouts`, and `settlements` client methods used by the dashboard.