# Agent onboarding

Use a private customer CLI and scoped project keys to connect one transactional
email without a service checkout, database access, AWS credentials or browser.
This guide describes the **1.2.0**; deploy the matching service before
using these commands in production. The live Sledge proof used 1.1.0's lower-level
operations, which remain supported.

## 1. Receive the project handoff

The verified owner/operator supplies a project slug, API URL, private CLI archive
and SHA-256, sender/privacy details, and separate publisher/runtime keys through
your secret manager. Initial admission is operator work: verified sender, sole
feedback route, ownership, sending limits and finite inactive-contact retention.
New projects start paused; only the operator enables the approved scope.
[Add a project](add-a-project.md) covers that procedure. Public registration and
a public npm package are unavailable.

```sh
shasum -a 256 ./mailwerk-customer-cli-1.2.0.tgz
pnpm add -D ./mailwerk-customer-cli-1.2.0.tgz
pnpm exec mailwerk --version
```

Compare the supplied hash. Node 24+ is required. Inject `MAILWERK_URL` and the
**publisher** key as `MAILWERK_API_KEY` through your secret manager. Never put
keys in prompts, arguments, source or receipts.

```sh
pnpm exec mailwerk setup --project acme --path src/mailwerk.mjs
```

Use the supplied slug; `.ts` generates TypeScript. Setup reads live prerequisites
on every run, gives ordered actions and safely creates the client. Repeating it
preserves the identical file; a different existing file causes a conflict. Use
`init --update` only for an intentional client upgrade. No wizard state is stored.
Publisher readiness includes a missing runtime capability: this is expected.
Switch to the runtime key for the final readiness check.

`setup` checks stored configuration and permissions, **not** DNS, credential
validity or mailbox delivery. `deliveryVerified` stays false. `operations NAME`
and [OpenAPI](/openapi.json) describe the exact live contracts. Existing keys do
not gain new grants: request a newly issued scoped key if access is refused.

## 2. Preview and publish

Save reusable copy as `sign-in-template.json`:

```json
{
  "descriptor": {
    "key": "sign_in_code",
    "subject": "Your sign-in code",
    "class": "transactional",
    "variables": ["code"]
  },
  "body": "<mj-section css-class=\"mw-surface\"><mj-column><mj-text css-class=\"mw-text\" font-size=\"24px\" font-weight=\"700\">{{code}}</mj-text><mj-text css-class=\"mw-text\">Enter this code to sign in. It expires in 10 minutes.</mj-text></mj-column></mj-section>"
}
```

```sh
pnpm exec mailwerk preview --from sign-in-template.json --out review.json
# Inspect review.json: rendered HTML/text, static subject and footer.
pnpm exec mailwerk publish --from review.json
```

Mailwerk supplies the brand, imprint and privacy footer. Preview stages this
revision and reviews it alongside all currently active templates/lifecycles;
it does not activate anything. The receipt binds the exact selection to this
project, service URL and active base. Publish activates only that reviewed
selection. Repeating a successful publish returns `unchanged`.

A concurrent publication makes the receipt stale: create and inspect a **new**
preview file, then publish it. Never edit revision maps or hashes to defeat a
conflict. Receipts preserve existing files. Publishing never unpauses a project.
An author key may preview; only a publisher can activate. Neither can send.

Use static subjects. Actual codes belong only in transient send variables, never
source, contact properties, events, IDs, logs or preview receipts. Transactional
mail needs no marketing consent or unsubscribe control. See [authoring](authoring.md).

## 3. Make one application call

Switch to the **runtime** key and repeat `setup --project acme`. All prerequisites
must pass. The deployed product holds only `MAILWERK_URL`, `MAILWERK_API_KEY` and
the generated client; publisher credentials stay in the authoring environment.

```js
import { transactional, message, deleteContact } from './mailwerk.mjs';

export async function sendSignInCode({ contactId, email, code, requestId }) {
  return transactional({
    template: 'sign_in_code', externalId: contactId, email,
    requestId, variables: { code },
  }, { timeoutMs: 12_000 });
}

export async function inspectSignInRequest(requestId) {
  return message(requestId);
}

export async function eraseSignInContact(contactId) {
  return deleteContact(contactId, { fenceMissing: true });
}
```

The app owns authentication: generate the code, store its short-lived hash,
enforce expiry/attempts and verify it. Persist a random account-lifecycle UUID
before the first call, even before an account exists. Reuse it as `externalId`;
a deliberate signup after deletion gets a new UUID. Do not derive it from an
address. Mailwerk upserts that contact without reviving an erased identity.

Persist a separate random UUID `requestId` for each new code request. An identical
retry returns the same message and known outcome, without another send or contact
update. A changed email, template, variables or external ID with that request ID
returns `409 conflict`. Codes are transient; the stored request fingerprint is
keyed. Do not store plaintext codes merely to enable retries; status lookup needs
only the request UUID.

| Outcome | Meaning and action |
|---|---|
| `sent` | SES accepted it; this alone does not prove delivery. Keep the valid code. |
| `unknown` | Acceptance is uncertain. Keep request/code state; inspect status, never automatically resend. |
| `failed` | Definite failure. Correct the cause before creating a new deliberate request. |
| Network error | Query the same request ID; do not infer failure from a timeout. |
| Status `404` | No visible ledger entry yet; an in-flight request may still claim. Replay only the identical request ID/content if retrying. |
| `409` | Request changed or its privacy-limited replay metadata was erased; do not bypass this with a new automatic request. |

```sh
pnpm exec mailwerk message REQUEST_UUID
pnpm exec mailwerk reliability --window 7d
```

Status separates acceptance from delivery/bounce/complaint feedback and includes
explicit retry guidance. Signed matching feedback can resolve an unknown send.
It never guesses, resends or switches providers. `delivered` means recipient
mail-server acceptance, not inbox placement. The older `send` API retains its
`duplicate` semantics; this guide's richer replay behavior is `transactional`.

Erase remotely **before** deleting the local identity/reference or revoking its
identity-provider account. Abort deletion on erasure failure and retain the
reference for retry. Missing-contact fencing prevents delayed first admission
from undoing deletion. Inactive contacts without confirmed consent or active
lifecycles are erased under the project's configured policy (Sledge: 30 days,
by the next successful daily cleanup). Local age is not proof of remote erasure.
Erasure clears request fingerprints and recipient data; replay is then refused.
Suppression and minimal replay tombstones survive under separate retention.

## 4. Prove the integration

Use an isolated HTTP/transport fixture first: acceptance, definite failure,
unknown/timeout, identical/conflicting retry, suppression, erasure failure and
delayed admission. Confirm no code reaches stored data or logs. Fake transport
proves the integration, not delivery.

Live proof requires approval for the exact sender, owned recipient and bounded
send count. Receive a code through the app, inspect SPF/DKIM/DMARC, complete login
and verify signed delivery feedback. Do not repeat ambiguous sends as tests.
Sledge passed actual mailbox/login and simulator feedback proof on 23 September
2026 using 1.1.0. That proves its integration, not a new customer's sender or this
version's production rollout.

For MCP, run `mailwerk mcp` from the same private package. Start with `docs_read`,
`operations_list`, `onboarding_status`, then `content_preview`, inspect the result
and pass its exact selection/base/hash to `content_activate`. Use
`transactional_send`, `messages_get` and `reliability_report` for runtime work.
CLI receipt files are a convenience; the operation contracts and grants are the
same through HTTP and MCP. See [CLI and MCP](cli.md).

## Measure reliability honestly

`reliability` counts distinct messages claimed in the selected window, with
accepted/failed/unknown outcomes, signed-feedback coverage and first-delivery
p50/p95 latency. Duplicate feedback never increases the message denominator.
Empty latency cohorts return null. Pre-claim refusals and service outages are
outside this ledger; this is neither availability nor inbox-placement measurement.

Before making a reliability comparison, observe 30 consecutive days of ordinary
approved traffic: report request count, unknown fraction/oldest age, feedback
coverage and latency with sample size. Measure application request success and
availability separately, including outages that cannot reach this ledger. Record
provider incidents and retention limits. Compare equivalent workloads and windows;
one local run, low-volume traffic or a provider acceptance percentage cannot prove
superiority. No extra sends, recurring jobs or provider spend are implied.
