# Getting started with MandateOps Audit

## The product
Run selected money movement failure tests against your own backend, check captured effects and inspect an evidence report.

## Install
Requirements: a container engine with Compose v2, Bun 1.4.4+ or Node 22+, a containerised test deployment with a health check, and a provider URL you can set by environment variable.

1. Install the SDK and the `mandateops` CLI together, so their versions match: `bun add -d @mandateops/audit @mandateops/cli`, `npm install --save-dev @mandateops/audit @mandateops/cli`, `pnpm add -D @mandateops/audit @mandateops/cli`. A mismatched pair is refused before any test runs, with the fix named.
2. Check the setup: `npx mandateops version` must answer, with your container engine running.

## First payout test
Save as `payout.test.ts` beside your Compose file and run `bun test --timeout 300000`:

```ts
import { expect, test } from "bun:test";
import {
  auditRun,
  defineConfig,
  runLimit,
  type Fixture,
} from "@mandateops/audit";

// Your deployment as it already is: its Compose file, service and port.
const config = defineConfig({
  financialProfile: "payout-effects-only",
  system: {
    compose: "test-stack.yml",
    service: "payments",
    port: 8080,
    // Longest wait between two attempts of one payout; 0: it never retries.
    retryDelayMs: 0,
    // Longest claim a worker holds on an attempt; 0: no leases.
    leaseMs: 0,
    // How long anything may still act on a settled payout.
    quiescenceMs: 1000,
    providerTerms: {
      account: "first-run",
      operation: "payout",
      idempotencyScope: "merchant",
    },
    // Each provider your backend calls: the variables it reads, not their values.
    providers: [
      { name: "bank", urlEnv: "BANK_URL", credentialEnv: "BANK_KEY" },
    ],
    environment: { KEY_MODE: "stable" },
  },
});

// The payout your backend is asked to make, in minor units.
const order = {
  payment: "order-1",
  tenant: "shop",
  agent: "checkout",
  delegation: "weekly-run",
  account: "main",
  destination: "supplier-9",
  currency: "ZAR",
  asset: "zar",
  network: "bank",
  amount: "2500",
};

const submit = (app: string) =>
  fetch(new URL("/payouts", app), {
    method: "POST",
    body: JSON.stringify(order),
  });

// The provider commits, its reply is lost, and your client retries.
async function retryAfterLostResponse({ app, faults, provider }: Fixture) {
  const { payment: reference, amount: amountMinor, ...scope } = order;
  const authorised = await provider.expectPayment({
    ...scope,
    reference,
    amountMinor,
    outcome: "exactly_one_effect",
  });
  // The reference your backend sends the provider for this payment.
  await authorised.bindProviderPayment(reference);
  await faults.loseResponseAfterCommit({
    payment: authorised,
    mode: "cut_connection",
  });
  await submit(app);
  await faults.release();
  await submit(app);
}

// The test's name is also the run's label on the dashboard.
const name = "a retry after a lost response makes one payout";

test(
  name,
  async () => {
    const result = await auditRun(
      { ...config, label: name },
      retryAfterLostResponse,
    );
    expect(result.ci_passed).toBe(true);
  },
  runLimit(config),
);
```

Change the deployment values to yours: the Compose service and port, the names of the variables your backend reads its provider URL and key from, and the payout your backend makes.

Three timings describe your backend, each in milliseconds or `"unknown"`: `retryDelayMs` is the longest wait between two attempts of one payout, `leaseMs` the longest claim a worker holds on an attempt, and `quiescenceMs` how long anything may still act on a settled payout. `quiescenceMs` must be at least `retryDelayMs + leaseMs`, because a late attempt can follow a lease expiry and then a retry delay. When any timing is `"unknown"`, set `drainMs` and the result covers only that window. The observation window and time limits are defaulted, and every resolved value is shown with the result. Bind the reference your backend sends the provider (the format's payment field, or the idempotency key when it has none), and declare the account it really pays; payouts that match no declared payment are reported as unmatched.

## After the first green run: check your backend's own record
A `payout-effects-only` pass checks only the money that left. It does not read your backend's own records, so a backend that reports a paid payout as failed still passes. Add a status adapter to `payout.test.ts`; it reads your backend's status for the payout with a read-only credential:

```ts
import { defineAdapter, type PayoutState } from "@mandateops/audit";

/** Your backend's own record of a payout, mapped to the adapter's states. */
type BackendPayout = { state: PayoutState };

const statusAdapter = defineAdapter({
  status: async ({ backend, viewerCredential, providerPayment }) => {
    const url = new URL(`/payouts/${providerPayment}`, backend);
    const response = await fetch(url, {
      headers: { authorization: `Bearer ${viewerCredential}` },
    });
    const payout = (await response.json()) as BackendPayout;
    return { source: "adapter", payment: providerPayment, state: payout.state };
  },
});

const checked = defineConfig({
  ...config,
  adapter: statusAdapter,
  requiredChecks: ["provider-outcome", "backend-outcome"],
  system: {
    ...config.system,
    credentialEnv: { viewer: "VIEWER_KEY" },
  },
});

test(
  "the backend reports the payout it made",
  async () => {
    const result = await auditRun(checked, retryAfterLostResponse);
    expect(result.ci_passed).toBe(true);
  },
  runLimit(checked),
);
```

`requiredChecks` names what CI requires; without it, the profile's own checks apply. Map your backend's status to one of reserved, executing, unknown, needs_review, failed or confirmed. A backend that reserves funds moves on to the `payout-effects` or `payout-commitment` profile with history and balance readings.

## Exit codes
Codes 0 to 3 are the verdict of `mandateops run` and of an audit test. `trace` and `export` exit 0 once the record is read and shown, and `recheck` exits 0 once the record reproduces: neither means the payment was safe, so read the verdict they print.

| Code | Meaning |
|---|---|
| 0 | Every required check passed. |
| 1 | A required check failed. |
| 2 | Required evidence was missing or inconclusive; `init` also exits 2 when it refuses and writes nothing. |
| 3 | Infrastructure or teardown failure. |
| 10–14 | Upload problems; `mandateops upload --help` names each. |
| 20–22 | `mandateops hosted fetch` wrote no record: 20 the job is still queued or running, 21 it ended without a record or its record is no longer kept, 22 no such job for this key and mode. An answer it cannot read exits 3. |
| 64 | Usage error: the command line was refused. |
| 130 | Interrupted. |

An audit test run through the SDK reports configuration refused before deployment by throwing `AuditUsageError` with the host's message, not by an exit code.

## Privacy of uploads
Before a run is exported or uploaded, database span names keep only their operation (SELECT, INSERT, UPDATE and so on). Table names and query text, including `db.statement` and `db.query.text`, never leave the machine.

## Workspace
Sign in with Google to create a workspace on the free Developer plan; each account founds one free workspace, and upgrading it frees the place for another. Upload runs from the `mandateops` CLI with an agent key; members see verdicts and download run records. Hosted runs of MandateOps example backends, open to every workspace: `mandateops hosted backends` lists the backends and scenarios your workspace can run, `mandateops hosted submit --scenario <name>` queues one (add `--backend <name>` only when several backends run the scenario), `mandateops hosted status` and `mandateops hosted fetch` follow it, and Hosted runs in the workspace shows it. Coding agents get the same as MCP tools (hosted_backends, hosted_submit, hosted_status, hosted_list). To have your own backend hosted for your workspace only, email spha@getmandateops.com. Runs that fail because of MandateOps, as shown by cause: service on the job, don't count (up to 5 a month). A record sealed by another CLI build is MandateOps's only on MandateOps runners with MandateOps backends. Developer: $0.

## Agent integration
Read /llms.txt and /agent-context.json for discovery. Execute tests through the SDK and the `mandateops` CLI.

## Evidence limits
The test provider records test effects, not real settlement. A passing run covers its properties, evidence and observation window. No certification or universal correctness claim is made.
