Open MercatoDocsSearch docsAPI reference

Framework

Building on the Communications Hub

If your module acts on incoming mail, subscribe to the Communications Hub event and use its normalized message. If you are adding a new mail or chat service, implement the provider side so other modules can use the same send and receive paths.

Two things a developer can do with the Communications Hub, covered in that order:

  1. Consume it – react to inbound messages and send outbound ones from your own module, without knowing which provider is behind the channel.
  2. Extend it – ship a new provider package so a transport the hub does not support yet becomes one more channel.

Both parts use @open-mercato/channel-discord as the worked example. Discord is the interesting case because it breaks three assumptions the email providers never did: its recipients are not email addresses, its inbound arrives over a WebSocket instead of a webhook or a poll, and its interactions endpoint needs a synchronous signed response. If your transport is unusual, it is probably unusual in one of those ways.

Info · Scope

This page is the hub's extension guide. For the hub's own architecture, entities, environment variables and deploy runbook see Communications Hub; for the ChannelAdapter type itself, read packages/core/src/modules/communication_channels/lib/adapter.ts – it is the contract, and it is commented.


Part 1 – Consume the hub from your own module

Everything here works the same whether the channel behind it is Gmail, IMAP or Discord. That is the point of the hub: your module talks to messages and channels, never to a provider.

React to an inbound message

When a message arrives on any channel, the hub materialises it into the Messages module and emits communication_channels.message.received. Subscribe to it from a file under your module's subscribers/ directory – auto-discovery picks it up, no registration needed:

// packages/<pkg>/src/modules/<module>/subscribers/on-channel-message.ts
import type { EntityManager } from '@mikro-orm/postgresql'
import { findOneWithDecryption } from '@open-mercato/shared/lib/encryption/find'
import { Message } from '@open-mercato/core/modules/messages/data/entities'

export const metadata = {
  event: 'communication_channels.message.received',
  persistent: true,
  id: 'my_module:on-channel-message',
}

type MessageReceivedPayload = {
  messageId: string
  externalMessageId: string
  channelLinkId: string
  conversationId: string
  channelId: string
  providerKey: string
  channelType: string
  direction: 'inbound'
  tenantId: string
  organizationId: string | null
}

type SubscriberContext = { resolve: <T = unknown>(name: string) => T }

export default async function handler(
  payload: MessageReceivedPayload,
  ctx: SubscriberContext,
): Promise<void> {
  if (payload.providerKey !== 'discord') return

  const scope = { tenantId: payload.tenantId, organizationId: payload.organizationId ?? null }
  const em = ctx.resolve<EntityManager>('em').fork()
  const message = await findOneWithDecryption(
    em,
    Message,
    { id: payload.messageId, ...scope, deletedAt: null },
    undefined,
    scope,
  )
  if (!message) return

  // …your logic, using message.body / message.subject / message.threadId
}

Three rules this example encodes, all of which matter:

The other events worth subscribing to

EventFires whenKey payload fields
communication_channels.message.receivedAn inbound message was ingestedmessageId, conversationId, channelId, providerKey, direction
communication_channels.message.sentAn outbound message reached the providermessageId, channelId, providerKey
communication_channels.message.delivery_failedOutbound delivery gave upmessageId, channelId, providerKey
communication_channels.conversation.createdA message opened a new external conversationconversationId, externalConversationId, channelId
communication_channels.contact.resolvedAn inbound sender matched a CRM personconversationId, contactPersonId
communication_channels.reaction.added / .removedA reaction landed, from either directionreactionId, messageId, emoji, reactedByExternalId, reactedByDisplayName
communication_channels.channel.requires_reauth / .disconnected / .deletedChannel lifecyclechannelId

Every payload carries tenantId and organizationId. The message and reaction events also declare clientBroadcast: true, so they reach the browser over SSE – see the DOM Event Bridge if you want a backoffice page to react live rather than in a worker.

Send a message through the hub

There is no "post to Discord" call, by design. Your module composes a Message; the hub's outbound bridge notices the message belongs to a channel-linked thread and delivers it through whichever adapter owns that channel:

messages.messages.compose            (your module)
        │
        ▼
messages.message.sent                (event)
        │
        ▼
subscribers/outbound-bridge.ts       (hub — resolves the channel from the thread mapping)
        │
        ▼
deliver-outbound-message command → ChannelAdapter.sendMessage

Replying inside an existing conversation is the easy case, and the one you want: set parentMessageId to the message you are replying to and the thread mapping resolves the channel for you.

import type { CommandBus } from '@open-mercato/shared/lib/commands'
import { resolveCommunicationChannelsSystemUserId } from '@open-mercato/core/modules/communication_channels/lib/system-user'

const commandBus = ctx.resolve<CommandBus>('commandBus')
const userId = await resolveCommunicationChannelsSystemUserId(em, scope.tenantId, null)

await commandBus.execute('messages.messages.compose', {
  input: {
    type: 'channel.discord',
    visibility: 'public' as const,
    subject: 'Discord reply',
    body: 'Thanks — someone from the team will pick this up shortly.',
    bodyFormat: 'markdown' as const,
    priority: 'normal' as const,
    sendViaEmail: false,
    parentMessageId: inbound.threadId ?? inbound.id,
    isDraft: false,
    tenantId: scope.tenantId,
    organizationId: scope.organizationId,
    userId,
  },
  ctx: {
    container: { resolve: (name: string) => ctx.resolve(name) } as never,
    auth: null,
    organizationScope: null,
    selectedOrganizationId: scope.organizationId,
    organizationIds: scope.organizationId ? [scope.organizationId] : null,
  } as never,
})

Nothing in that snippet is Discord-specific except the type string and the body format. The same code replies over Gmail if the thread's channel is a Gmail channel.

For a user-initiated send from a channel the user owns, prefer the sendAsUser facade – either over HTTP (POST /api/communication_channels/send-as-user, communication_channels.manage) or in process via DI, which avoids an HTTP self-call:

import type { sendAsUser as SendAsUser } from '@open-mercato/core/modules/communication_channels/lib/send-as-user'

const sendAsUser = container.resolve<typeof SendAsUser>('communicationChannelsSendAsUser')
const result = await sendAsUser(container, { userId, tenantId, organizationId, auth }, {
  userChannelId,
  to: ['[email protected]'],
  subject: 'Order #1042',
  body: { plain: 'Shipped this morning.' },
})
if (!result.ok) { /* result.status carries 403 / 404 / 409 / 422 */ }

To send files, add attachments: [{ kind: 'attachment', attachmentId, owner: { entityId, recordId } }] (at most 10, and 25 MB in total unless the adapter declares maxTotalBytes). Each item names a file from the attachments module and the record that owns it; as with parentMessageId, your code must already have checked that the user may read that record. The hub checks the rest – the adapter advertises fileSharing, the file is readable in the user's tenant and organization and owned by owner, its type is in supportedMimeTypes, its size fits – and answers 422 with a code (attachments_unsupported, attachment_not_found, attachment_type_not_allowed, attachments_too_large, …) otherwise. Only the references are stored; the delivery worker reads the bytes when it sends.

On the adapter side, fileSharing: true means convertOutbound receives attachments whose content holds the file bytes. Send those (or call resolveOutboundAttachmentBytes from communication_channels/lib/outbound-attachments) and never fetch attachment.url. Declare the provider's limits in the capabilities: maxFileSize per file and, when it differs from 25 MB, maxTotalBytes for the raw total of one message.

Warning · send-as-user is email-shaped today

The HTTP route validates to as a list of email addresses, so it rejects a Discord channel snowflake before the adapter is consulted. The in-process facade does not apply that validation, but it is still built around an email-shaped message (subject, externalEmail). For a non-email provider, the compose path above is the supported route, and POST /api/communication_channels/channels/{id}/test-send is the only endpoint that validates the recipient against the provider's own recipientFormat. Widening the remaining outbound routes is tracked in #4976; do not work around it by calling a provider's REST client directly.

The security context your code runs in

ConcernWhat actually happens
Tenant scopingNothing implicit. Subscribers and workers run outside a request, so every query filters on the tenantId / organizationId from the event payload. Cross-tenant reads are a bug, not a configuration mistake.
Outbound identityThe message is attributed to the composing userId, and to the tenant's system user when there is no human author (resolveCommunicationChannelsSystemUserId). What the recipient sees is provider-dependent: Gmail shows the connected mailbox; Discord always shows the bot. Discord has no send-on-behalf-of-a-user mechanism for bots.
ACLcommunication_channels.connect_user_channel to connect a personal channel, communication_channels.connect_tenant_channel for a tenant-wide one, .manage to send as a user, .react to react, .channel.import_history for backfill. Use requireFeatures in route/page metadata; never requireRoles.
Channel ownershipA user-scoped channel can only be sent through by its owner – sendAsUser returns 403 otherwise, and personal channels are not exposed to admins.
CredentialsEncrypted at rest per tenant. Adapters receive plaintext only inside the call; your module never handles them.
Non-deliverable channelsguardOutboundCreate maps requires_reauth / disconnected to a 422 with field errors before anything is enqueued. Do not bypass it.

Part 2 – Build a channel provider

A provider is a workspace package that registers one ChannelAdapter. The hub's webhook router, connect routes, admin UI and outbound worker discover it by providerKey; no hub change is required to add one.

1. Scaffold the package

Copy the build/watch/jest/tsconfig templates from an existing provider and follow the layout:

packages/channel-myprovider/
├── package.json
├── tsconfig.json
└── src/
    └── modules/
        └── channel_myprovider/
            ├── index.ts            # module metadata
            ├── integration.ts      # integration manifest (admin UI, credential fields, health)
            ├── acl.ts              # feature ids
            ├── setup.ts            # adapter registration + tenant defaults
            ├── di.ts               # DI bindings (adapter, health check)
            ├── lib/
            │   ├── adapter.ts      # the ChannelAdapter
            │   ├── capabilities.ts # the capability contract
            │   ├── credentials.ts  # zod schema for the credential blob
            │   ├── convert-outbound.ts
            │   ├── normalize-inbound.ts
            │   └── health.ts
            └── i18n/en.json

Add { id: 'channel_myprovider', from: '@open-mercato/channel-myprovider' } to apps/mercato/src/modules.ts, then yarn generate.

2. Declare the credential blob

A zod schema in lib/credentials.ts is the single definition of what the provider stores. Use .passthrough(), not .strict() – the hub's connect command stashes bookkeeping fields alongside your values:

export const discordCredentialsSchema = z
  .object({
    botToken: z.string().min(1, 'Bot token required'),
    applicationId: z.string().min(1, 'Application ID required'),
    publicKey: z
      .string()
      .regex(/^[0-9a-fA-F]+$/, 'Public key must be hex')
      .refine((value) => value.length === 64, 'Public key must be a 32-byte (64 hex char) Ed25519 key'),
    guildId: z.string().optional(),
    defaultChannelId: z.string().optional(),
  })
  .passthrough()

The same schema drives validateCredentials, so a bad field comes back as a field-level error in the connect form rather than as a channel that cannot authenticate.

If your credentials carry no email-shaped username, email or fromAddress, return a stable externalIdentifier from a successful validateCredentials (Discord returns discord:<applicationId>). The hub keys heal-on-reconnect on that identifier: without it, every reconnect inserts a new channel row next to the old one instead of updating it.

3. Write the capability contract – and be honest in it

capabilities is not documentation. The hub routes work on these flags: a true that nothing implements is work silently dropped, and the registry only catches five of those pairs at boot (reactions → sendReaction/removeReaction, editMessage, deleteMessage, conversationHistory → fetchHistory). Everything else is on you.

Declare false for anything you have not implemented, and say why in a comment – the reason is what stops the next person flipping it back optimistically. From packages/channel-discord/.../lib/capabilities.ts:

export const discordCapabilities: ChannelCapabilities = {
  recipientFormat: 'provider-native',   // Discord recipients are channel snowflakes, not addresses
  richText: true,
  reactions: true,
  editMessage: true,
  deleteMessage: true,
  conversationHistory: true,
  interactiveComponents: true,          // the signed route defers, then a worker replaces the
                                        // "thinking…" placeholder — the round-trip closes
  supportedBodyFormats: ['text', 'markdown'],
  maxBodyLength: 2000,                  // Discord's own REST limit on `content`
  realtimePush: true,                   // a gateway worker delivers inbound; do not poll this channel

  threading: false,        // convertOutbound can emit a reply reference, but no hub producer
                           // writes the metadata key it reads — the branch is unreachable
  fileSharing: false,      // outbound attachments are dropped; there is no multipart upload
  inlineImages: false,
  richBlocks: false,
  typingIndicators: false,
  presence: false,
  stickers: false,
  readReceipts: false,
  deliveryReceipts: false,
  multiReactionPerUser: false,
  contactCards: false,
  locationSharing: false,
  voiceNotes: false,
}

The file itself carries a longer reason beside each false, and one beside a flag that is deliberately absent: AI auto-reply adds no capability flag, because ChannelCapabilities describes what the hub may hand the adapter. Auto-reply is a subscriber on the hub's generic message.received event, so a flag for it would route adapter work that does not exist.

Warning · A true flag is not the same as a reachable feature

The registry proves the method exists. It cannot prove anything calls it. Discord's conversationHistory: true is honest by that test – fetchHistory is implemented – but the flag's only consumer is the polling worker, which realtimePush: true tells to skip this channel, so no Discord channel ever pages its history. editMessage / deleteMessage are further along the same spectrum: implemented, declared, and called by no hub surface for any provider today.

Before you declare a capability, follow it forward: which code path invokes the method, and is that path enabled for a channel with the rest of your flags? Note the answer in the comment beside the flag. A capability that is true, implemented, and unreachable is not a lie, but a user told the feature works will experience it as one.

Two flags decide more than they look like they do:

recipientFormat tells the hub how to validate an outbound recipient. It defaults to 'email', so a provider that omits it and is not addressed by email has no working outbound path at all – every recipient is rejected as "not a valid email address". 'provider-native' switches the hub to transport safety only (length plus the ^[A-Za-z0-9._:@+-]+$ allowlist), which means your adapter owns the format check and must keep treating the value as untrusted: it is about to be interpolated into a REST path.

realtimePush decides whether the hub polls the channel. It defaults to true (nothing is polled), and only an explicit false opts you into hub-managed polling with fetchHistory. Declare true only when you really do own a real-time delivery path – otherwise inbound is silently dead.

4. Implement the adapter

Five methods are required; the rest are opt-in and must match your flags.

class DiscordChannelAdapter implements ChannelAdapter {
  readonly providerKey = 'discord'
  readonly channelType = 'discord'
  readonly capabilities = discordCapabilities
  // readonly channelScope = 'tenant'   // omit for the default: one channel per user

  async sendMessage(input: SendMessageInput): Promise<SendMessageResult> { /* … */ }
  async verifyWebhook(input: VerifyWebhookInput): Promise<InboundMessage> { /* … */ }
  async getStatus(input: GetMessageStatusInput): Promise<MessageStatus> { /* … */ }
  async convertOutbound(input: ConvertOutboundInput): Promise<ChannelNativeContent> { /* … */ }
  async normalizeInbound(raw: InboundMessage): Promise<NormalizedInboundMessage> { /* … */ }
}

sendMessage returns a result rather than throwing, and the shape of that result is how the hub learns what happened:

try {
  const message = await getDiscordRestClient().createMessage(/* … */)
  return {
    externalMessageId: message.id,
    conversationId: `discord-channel:${message.channel_id}`,
    status: 'sent',
    metadata: { discordChannelId: message.channel_id, discordMessageId: message.id },
  }
} catch (error) {
  if (error instanceof DiscordApiError && error.status === 401) {
    // Protocol sentinel: the hub classifies this and flips the channel to
    // requires_reauth, which fires the operator notification and the outbound guard.
    return { externalMessageId: '', status: 'failed', error: 'requires_reauth' }
  }
  return { externalMessageId: '', status: 'failed', error: String(error) }
}

normalizeInbound maps the provider payload onto the hub's canonical shape. Pick an externalConversationId prefix that identifies your provider (discord-channel:<id>, gmail-thread:<id>) so everything in one remote conversation threads into one hub conversation.

Tip · Resolve the destination in one place, and prefer the conversation

An outbound message can name its destination in more than one place. Discord resolves them in a fixed order – provider metadata, then the conversation's own id, then the recipient from metadata.to, then the configured default. The conversation deliberately outranks the recipient so a stray to can never redirect a reply out of its own thread; the recipient only decides when there is no conversation to belong to, which is exactly the test-send case. Validating a recipient and then quietly ignoring it is worse than rejecting it.

5. verifyWebhook must fail closed

This is the security-critical method, and the trap is that its contract is inverted from what it looks like. The shared api/post/webhook/[provider] route treats a non-throwing return as "verified" and pins the request to that candidate channel's tenant. A best-effort implementation that returns normally on an unverified request is a tenant-spoofing fail-open.

So there are exactly two correct behaviours:

async verifyWebhook(input: VerifyWebhookInput): Promise<InboundMessage> {
  const rawBody = typeof input.rawBody === 'string' ? input.rawBody : input.rawBody.toString('utf-8')
  const interaction = parseInteractionBody(rawBody)
  if (!interaction) {
    // Not ours — Discord messages arrive over the gateway. Ack without tenant-scoped work.
    return { raw: {}, eventType: 'other', metadata: { reason: 'discord-uses-gateway-for-messages' } }
  }

  const parsed = discordCredentialsSchema.safeParse(input.credentials)
  const headers = normalizeHeaders(input.headers)
  const ok = verifyDiscordSignature({
    publicKeyHex: parsed.success ? parsed.data.publicKey : '',
    signatureHex: headers['x-signature-ed25519'],
    timestamp: headers['x-signature-timestamp'],
    rawBody,
  })
  if (!ok) throw new Error('[internal] Discord interaction signature verification failed')

  return { raw: { discordInteraction: interaction }, eventType: 'other' }
}

The verification helper itself is fail-closed too: it returns false on a missing header, a malformed key or any error, and never true on doubt.

Signature verification alone is not freshness. A captured request stays cryptographically valid forever, so a provider whose signature covers a timestamp needs an explicit replay window on top. Note that the snippet above does not have one: the adapter's verifyWebhook proves the signature and nothing more. Discord's replay guard (±300 seconds, checked before the signature fan-out so a replay costs no crypto work) lives on the dedicated route below, which is where real interactions are actually served. Put the guard on whichever surface the provider genuinely receives traffic on, and do not assume a signature check implies one.

When you need your own signed route

A provider whose handshake must be answered synchronously cannot use the shared webhook route, which only 202-acks. Ship your own route from the provider package instead of changing the hub – Discord does exactly this for its Interactions endpoint:

// api/interactions/route.ts  →  /api/channel_discord/interactions
export const metadata = {
  path: '/channel_discord/interactions',
  POST: {
    requireAuth: false,   // the Ed25519 signature IS the auth, and it is fail-closed
    rateLimit: { points: 120, duration: 60, keyPrefix: 'discord_interactions' },
  },
}

An unauthenticated route needs a cost story as well as a security story. Reject everything decidable from the request alone – missing, malformed or wrong-length signature header, stale timestamp – before loading a single candidate channel, so unsigned traffic costs zero database round-trips and zero credential decrypts. Then verify against the candidates: the one whose key verifies is what pins the tenant. If a body carries an id you can narrow candidates by, treat it as narrowing only – it is unverified input and must never be an authorization decision, and a body claiming nothing falls back to the full candidate set rather than being let through.

A synchronous handshake usually comes with a deadline, and the work you actually want to do will not fit inside it. Discord closes an interaction that is not answered within three seconds, so the route does only what is fast – verify, then return a deferred acknowledgement – and hands the two slow halves to workers/discord-interactions.ts: writing the interaction into the hub's inbound queue under the matched tenant, and replacing the "thinking…" placeholder with the real message over Discord's interaction-webhook endpoints.

Unlike the gateway worker, this one rides the ordinary module queue and the app's standard worker runner, so no operator has to start it. Make the split idempotent: the hub dedups on (channel_id, external_message_id), and using the interaction snowflake as that external id means a retry after a failed follow-up re-enqueues the same job harmlessly instead of duplicating the record.

6. Inbound over something that is not a webhook

Discord does not POST messages anywhere: they arrive on a persistent WebSocket. The pattern for any socket-, stream-, or long-poll-based transport is a provider-owned worker that bridges into the hub's existing queues, so the hub itself stays unchanged:

Gateway WebSocket (provider-owned worker)
        │
        ▼
buildInboundMessageJob(...)  →  communication-channels-inbound queue
buildReactionJob(...)        →  communication-channels-reactions queue
        │
        ▼
the hub's existing inbound / reaction processors  →  ingest command  →  Messages

The jobs are the same ones the webhook route enqueues, so normalizeInbound runs exactly as it would have. A worker file under workers/ is auto-discovered; declare concurrency: 1 when the transport requires a single connection per credential.

Four things this pattern gets wrong if you skip them:

7. Persist provider state, tenant-scoped

Providers that resume a session need somewhere to keep a cursor. CommunicationChannel.channelState is a JSONB column for exactly that – but a socket callback fires long after the job handler returned, so nothing scopes the write for you:

export async function persistDiscordChannelState(params: {
  em: EntityManager
  channelId: string
  scope: { tenantId: string; organizationId: string | null }
  patch: DiscordChannelStatePatch
}): Promise<'written' | 'skipped' | 'not_found'> {
  const fork = params.em.fork()
  const channel = await findOneWithDecryption(
    fork,
    CommunicationChannel,
    { id: params.channelId, tenantId: params.scope.tenantId, organizationId: params.scope.organizationId, deletedAt: null },
    undefined,
    { tenantId: params.scope.tenantId, organizationId: params.scope.organizationId ?? params.scope.tenantId },
  )
  if (!channel) return 'not_found'
  const merged = mergeDiscordChannelState(channel.channelState, params.patch, new Date())
  if (!merged) return 'skipped'
  channel.channelState = merged
  await fork.flush()
  return 'written'
}

The rules that make it safe: capture the scope up front from the row the job loaded and replay it on every write, filter by tenant_id / organization_id and never by id alone, run on a fresh em.fork() so the flush does not ride on a stale request context, merge only the keys you own so a concurrent edit elsewhere in the blob is not clobbered, and drop a patch that would rewind a cursor – a late callback from a superseded connection must not overwrite fresher state.

8. Integration manifest, health check and DI

integration.ts is what the Integrations admin UI renders: title, description, credential fields (with helpText – the operator reads it while looking at the provider's console), API versions, and the health-check service name.

export const integration: IntegrationDefinition = {
  id: 'channel_discord',
  title: 'Discord',
  category: 'communication',
  hub: 'communication_channels',
  providerKey: 'discord',
  package: '@open-mercato/channel-discord',
  credentials: { fields: [ /* key, label, type: 'secret' | 'text', required, helpText */ ] },
  healthCheck: { service: 'channelDiscordHealthCheck' },
}

Make the health check a real probe – a cheap authenticated call such as GET /users/@me – rather than a credentials-present check, and map the failure modes to actionable messages (401 → "token rejected"). Then register both the adapter and the health check under the exact service name the manifest declares; if that name does not resolve, the channel reports permanently unhealthy:

// di.ts
export function register(container: AppContainer): void {
  if (!hasChannelAdapter('discord')) registerChannelAdapter(getDiscordChannelAdapter())
  container.register({
    channelDiscordAdapter: asValue(getDiscordChannelAdapter()),
    channelDiscordHealthCheck: asValue(channelDiscordHealthCheck),
  })
}

setup.ts registers the adapter at import time as well – the registry is process-wide, so guard with hasChannelAdapter to stay idempotent across dev-mode HMR and repeated test imports – and is where defaultRoleFeatures and any onTenantCreated work (such as applying an env preset through the standard credentials service) belong.

9. Add a connect surface

Ship a connect widget from your package, injected into the profile page's channel list, rather than asking the hub to know about you:

// widgets/injection-table.ts
export const injectionTable: ModuleInjectionTable = {
  'profile:communication-channels:connect': [
    { widgetId: 'channel_discord.injection.connect', priority: 120 },
  ],
}

The widget collects the credential fields and posts them to the hub's own connect route (POST /api/communication_channels/channels/connect/credentials for a user-owned channel, …/connect/tenant-credentials for a tenant-wide one), gated by communication_channels.connect_user_channel. Use apiCall and useGuardedMutation; never raw fetch. All user-facing strings go through useT() and your module's i18n/ files.

The hub renders this spot inside the profile page's Connect channel dropdown, one provider per full-width stacked row, so installing more providers lengthens the list instead of widening the page header. Ship a single control sized by the container – a Button works; avoid fixed widths – and keep any credential Dialog inside the widget: the hub keeps injected widgets mounted while the dropdown is closed precisely so a dialog opened from a row survives the dropdown closing behind it.

10. Verify it

yarn generate && yarn build:packages && yarn test
yarn mercato configs cache structural --all-tenants   # after any modules.ts change

Unit-test the pure parts – capability/method parity, signature verification (every rejection path, not just the happy one), inbound normalization, outbound conversion, the state-merge rules. Ship integration specs under __integration__/ that drive the real app for everything that does not need a live remote account: adapter registration, fail-closed credential validation, the signed route's rejections, reaction round-trip through the thread mapping, tenant-scoped health guards. Where a sub-assertion genuinely needs a live account, say so in the spec and name the unit test that owns that half – a stated ceiling is worth more than a test that pretends.


Previous: Dependency injection container · Next: Building a Gateway Provider