# @pleach/compliance (/docs/compliance)



Pruning shears at the garden wall: what crosses the boundary, in what shape,
with what scrub. `@pleach/compliance` is the regulated-environment add-on to
`@pleach/core`. It ships four `Scrubber` implementations that gate event log
writes, plus an opt-in tenant-isolation RLS template and `auditRlsPolicies()`,
a checker you wire into your own CI.

It targets deployments where the audit ledger is evidence, such as healthcare,
finance and govtech. For Part 11 and ALCOA+, see
[Part 11 and ALCOA+](/docs/compliance/part-11-alcoa). For broker-dealer
records and supervision, see [SEC and FINRA rules](/docs/compliance/sec-finra).

> **Beta.** `@pleach/compliance` ships **beta** for the first release. The
> scrubbers, the RLS template and `auditRlsPolicies()` are the stable part. The
> **attestation / audit-report** surface is the beta part. Signing uses the key
> store you provide (KMS or Vault); see [Attestation](/docs/attestation#beta).

Scrubbers run at the persistence boundary of `@pleach/core`'s
`EventLogWriter`. The RLS template partitions rows in the database, and
`auditRlsPolicies()` confirms from your CI that the partition is live.

**Package:** `@pleach/compliance` ([not on npm yet](</docs/install#not-on-npm-yet>)) · **Source:** [github.com/pleachhq/compliance](<https://www.getpleach.com/docs/compliance>)

## Install [#install]

<Tabs items="['npm', 'pnpm', 'yarn', 'bun']" groupId="pkg">
  <Tab value="npm">
    ```bash
    npm install @pleach/compliance
    ```
  </Tab>

  <Tab value="pnpm">
    ```bash
    pnpm add @pleach/compliance
    ```
  </Tab>

  <Tab value="yarn">
    ```bash
    yarn add @pleach/compliance
    ```
  </Tab>

  <Tab value="bun">
    ```bash
    bun add @pleach/compliance
    ```
  </Tab>
</Tabs>

```typescript
import {
  SsnUsScrubber,
  CreditCardScrubber,
  UsDriverLicenseScrubber,
  KeyedRegexScrubber,
} from "@pleach/compliance";
```

The package exports the four scrubber classes (instantiate with `new`), the
`complianceProfilePlugin(profile)` factory that bundles them by profile
(`"hipaa"` / `"gdpr"` / `"pci-dss"` / `"soc2"`), `createComplianceRuntime`, and
`scrubbersForProfile(profile)` for hand-rolled plugins. The published README is
the source of truth for export names and constructor options.

## The four bundled scrubbers [#the-four-bundled-scrubbers]

Each implements the `Scrubber` contract from `@pleach/core/scrubbers`,
documented in [Scrubbers](/docs/scrubbers).

| Scrubber                  | Pattern                                                                       | Redaction key     |
| ------------------------- | ----------------------------------------------------------------------------- | ----------------- |
| `SsnUsScrubber`           | US Social Security numbers (`NNN-NN-NNNN`; unseparated `NNNNNNNNN` is opt-in) | `[REDACTED:SSN]`  |
| `CreditCardScrubber`      | Credit-card-shaped digit runs that pass a check-digit and issuer-range test   | `[REDACTED:CARD]` |
| `UsDriverLicenseScrubber` | US driver's license numbers, by state format                                  | `[REDACTED:DL]`   |
| `KeyedRegexScrubber`      | Generic pattern and key adapter, the building block hosts extend              | caller-supplied   |

The original digits never reach storage. Order numbers, session ids and similar
digit runs pass through `CreditCardScrubber` untouched. Pass
`new CreditCardScrubber({ validateIin: false })` to skip the issuer-range test
if you process exotic card-network ranges.

If `UsDriverLicenseScrubber` doesn't cover a state yet, open an issue on the
package repo rather than fork the scrubber.

The bundled regex set is these four. International tax IDs, EU formats and
sector-specific identifiers aren't in it; use `KeyedRegexScrubber` for those.

## `KeyedRegexScrubber` — the extension hook [#keyedregexscrubber--the-extension-hook]

`KeyedRegexScrubber` is the scrubber you most often instantiate directly. It
stays inside the `Scrubber` contract and inherits matched-spans audit
reporting.

```typescript
// lib/compliance/tenantMrnPlugin.ts
import { KeyedRegexScrubber } from "@pleach/compliance";
import type { HarnessPlugin } from "@pleach/core";

const mrnScrubber = new KeyedRegexScrubber({
  id: "tenant-mrn",
  entries: [
    {
      name:        "mrn",
      pattern:     /\b\d{7}\b/g,
      replacement: "[REDACTED:MRN]",
    },
  ],
});

export const tenantCompliancePlugin: HarnessPlugin = {
  name: "tenant-mrn-compliance",
  contributeScrubbers: () => [mrnScrubber],
};
```

The `name` (here `"mrn"`) appears in the matched-spans report. Pick one that
reads in a compliance review. The `replacement` is a string or a function
`(match, name) => string`.

For several identifier families, register separate `entries` on one scrubber,
or use one scrubber per family to group the report by scrubber `id`.

## Advanced redaction [#advanced-redaction]

The four bundled scrubbers are keyed regexes. For redaction that
regex can't express — clinical PHI, named-entity detection, or a
model-driven pass — `@pleach/compliance/redaction` ships a composable
pipeline and three heavier scrubbers, each on its own subpath.

`createPipeline({ scrubbers })` runs scrubbers in order; each is a
`PipelineScrubber` that returns redacted text plus `ScrubMatch`
records. `createRedactionGate({ pipeline })` wraps a pipeline into an
`ingress`/`egress` gate you place at a trust boundary.

| Scrubber                 | Subpath                                           | Detects via                                                              |
| ------------------------ | ------------------------------------------------- | ------------------------------------------------------------------------ |
| `createPHIScrubber`      | `@pleach/compliance/redaction/scrubbers/phi`      | tiered PHI patterns; `strictness` of `"standard"` \| stricter tiers      |
| `createPresidioScrubber` | `@pleach/compliance/redaction/scrubbers/presidio` | a Presidio `endpoint`; `DEFAULT_PRESIDIO_ENTITY_TYPES` unless overridden |
| `createLLMScrubber`      | `@pleach/compliance/redaction/scrubbers/llm`      | a model call; `DEFAULT_LLM_SCRUBBER_INSTRUCTION` unless overridden       |

```typescript
import { createPipeline, createRedactionGate } from "@pleach/compliance/redaction"
import { createPHIScrubber } from "@pleach/compliance/redaction/scrubbers/phi"
import { createPresidioScrubber } from "@pleach/compliance/redaction/scrubbers/presidio"

const gate = createRedactionGate({
  pipeline: createPipeline({
    scrubbers: [
      createPHIScrubber({ strictness: "standard" }),
      createPresidioScrubber({ endpoint: process.env.PRESIDIO_URL! }),
    ],
  }),
})

const clean = await gate.ingress(rawText, { tenantId })
```

The Presidio and LLM scrubbers reach a network service, so run them in the
redaction path, not the audit-write path. The PHI scrubber is pure regex and
safe to run inline.

### Choosing a redaction failure policy [#choosing-a-redaction-failure-policy]

By default, when a scrubber does not complete, the pipeline returns the text it
has and reports the failure, so a live request path keeps serving. For
regulated workloads, set `failClosed: true`, or read `complete` and `failures`
and decide per call:

* `PipelineResult` carries `failures` and `complete`. An *absent* `failures`
  means the pipeline doesn't report, so read `complete === true` as the only
  affirmative pass.
* `gate.ingressDetailed(...)` / `gate.egressDetailed(...)` return a
  `RedactionOutcome`: the text alongside the per-scrubber failures.
* `createRedactionGate({ pipeline, failClosed: true })` makes the plain
  `ingress`/`egress` **throw** `RedactionIncompleteError` instead of returning
  text that was not fully scrubbed.

Set `failClosed: true` wherever incomplete scrubbing must stop the request.

## Wiring tenant isolation into your own CI [#wiring-tenant-isolation-into-your-own-ci]

Installing `@pleach/compliance` adds no gate to your build and ships no install
scripts. Toward tenant isolation it ships a schema tier you apply and a checker
you call yourself.

### The tenant RLS schema tier [#the-tenant-rls-schema-tier]

The tenant fences ship as the package's schema tier, applied with the
same CLI as the core bundle:

```bash
npx @pleach/core schema --apply --with @pleach/compliance
```

The tier fences each tenant-scoped table: the event log and the call ledger
always, plus the error table and the `@pleach/gateway` tables when they exist.
Re-run the tier after you add `@pleach/gateway`.

The default resolver reads the `pleach.tenant_id` setting. Your server sets it
per transaction (`SELECT set_config('pleach.tenant_id', $1, true)`). An
unscoped request reaches no fenced rows.

* `service_role` bypasses the fence. Every other role is held to it.
* Restrictive policies only narrow access; they grant nothing.
* The tier refuses to install over a resolver that returns a value when no
  tenant is set. On Supabase, define your own resolver first that reads the
  tenant from a claim the user cannot edit (for example
  `auth.jwt() -> 'app_metadata'`).

The old `@pleach/compliance/tenant-rls/policies.sql` export now raises an
error when run, so an old deploy script that applies it fails loudly.

### `auditRlsPolicies()` — the checker [#auditrlspolicies--the-checker]

```typescript
import { auditRlsPolicies, TENANT_RLS_TABLES } from "@pleach/compliance/tenant-rls";

const report = await auditRlsPolicies({
  pool,
  expectedTables: TENANT_RLS_TABLES, // or the subset you have installed
});

const gaps = report.filter((r) => !r.compliant);
if (gaps.length > 0) throw new Error(`RLS gaps: ${JSON.stringify(gaps)}`);
```

`pool` is duck-typed: `pg`, `postgres.js` and a Supabase service-role client all
satisfy it. The function returns one row per expected table, and throwing on a
gap is what makes it a gate. See
[Multi-tenant](/docs/multi-tenant#rls-policy-templates--auditor) for the full
option shape.

### What Pleach's own CI covers [#what-pleachs-own-ci-covers]

Pleach's CI checks that core's event log write paths carry the tenant column.
Tenant RLS lives in your database: apply the tier, then call
`auditRlsPolicies()` in your own CI. See [Release checks](/docs/audit-gates).

## Proving the audit trail is intact [#proving-the-audit-trail-is-intact]

A partial page can't say the trail is valid. `queryAudit` grades each page
`valid`, `incomplete`, or `tampered`, and nearly every page reads `incomplete`
at best. `verifyAuditTrail` walks the whole trail and is the only whole-trail
`valid` verdict.

| `AuditChainStatus` | Meaning                                                                                                                                                                                     |
| ------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `valid`            | Every row from the start of the chain was checked, the store confirmed the start, and nothing is missing.                                                                                   |
| `incomplete`       | Every link that could be checked holds, but part of the chain wasn't checkable: a partial page, an unconfirmed start, or a truncated walk. An empty result is `incomplete` too. Not a pass. |
| `tampered`         | A link failed, or a row is provably missing.                                                                                                                                                |

Both functions ship on `@pleach/compliance/audit` and are re-exported from the
package root. `ComplianceRuntime` doesn't wrap them: its
`verifyChain({ chatId })` is a separate per-chat check through
`verifyChainForChat`.

### Why a page caps at `incomplete` [#why-a-page-caps-at-incomplete]

A page reports `valid` only when it starts at the beginning of the trail (no
`cursor`, no `from`) and has no next cursor. Any other page is a partial view
and caps at `incomplete`. Cursors are not authenticated, so treat a page that
starts from one as partial. A missing or mismatched boundary reads `tampered`
(see `chainsBoundaryLinked`); a linked one still doesn't make the page `valid`.
Verify the whole trail when you need `valid`.

Render `chainStatus`, never `chainValid` alone. `chainValid` is `true` only
when `chainStatus` is `valid`.

### Cursors [#cursors]

Cursors are opaque. `queryAudit` hands your store the lower bound as
`filter.after`. `encodeAuditCursor`, `decodeAuditCursor` and
`compareAuditRowKey` are exported for store authors.

A tenant-wide export is an ordering view, not a completeness guarantee. For a
complete export of a live tenant, page per chat or read a quiesced range.

### `verifyAuditTrail` [#verifyaudittrail]

```typescript
import { verifyAuditTrail, exportAuditPdf } from "@pleach/compliance/audit";

const trail = await verifyAuditTrail(store, { tenantId, chatId });

if (trail.chainStatus !== "valid") {
  throw new Error(`Audit trail ${trail.chainStatus} (pages=${trail.pages}, truncated=${trail.truncated})`);
}

const pdfBytes = await exportAuditPdf({
  rows: trail.rows,
  metadata: {
    tenantId,
    framework: "soc2",
    chainValid: trail.chainValid,
    chainStatus: trail.chainStatus,
    verifiedFrom: trail.verifiedFrom, // "genesis-walk"
  },
});
```

| Option                       | Default | Notes                                                        |
| ---------------------------- | ------- | ------------------------------------------------------------ |
| `tenantId`                   | —       | Required.                                                    |
| `chatId`                     | —       | One chat's trail. Omit it to walk every chain in the tenant. |
| `firstChainedSequenceNumber` | `1`     | Set it for a chat with a legacy unchained prefix.            |
| `pageSize`                   | `1000`  | 1–10000 rows per `listRows` call.                            |
| `maxPages`                   | `1000`  | 1–10000, counting the final empty read.                      |

Hitting `maxPages` before the trail ends sets `truncated: true` and caps the
verdict at `incomplete`. A row outside the requested tenant or chat makes the
walk throw rather than grade it.

`exportAuditPdf` prints `CHAIN: VALID` only when `chainStatus` is
`valid`, `chainValid` is `true`, `verifiedFrom` is `"genesis-walk"`,
and there's at least one row. A `queryAudit` page carries no
`verifiedFrom`, so its PDF prints INCOMPLETE at best.

### What your store must confirm [#what-your-store-must-confirm]

`AuditStoreLike.verifyChain(rows, slice)` is called once per contiguous run of
one chain. When `slice.startsAtGenesis` is set, return
`{ valid, genesisChecked: true }` after checking the first row against the
genesis seed. A bare `true` is accepted as the link verdict but caps that chain
at `incomplete`.

Don't call core's `verifyChain()` unchanged: it reads every slice that starts
mid-chain as `tampered`. When `slice.mayStartMidChain` is set, check links from
`rows[0].prevRowHash`, and match `slice.expectedPrevRowHash` when it's present.

### Ready-made stores: SQLite and Postgres [#ready-made-stores-sqlite-and-postgres]

`@pleach/compliance/audit/stores` ships two `AuditStoreLike`
implementations over the core event log, so you don't have to write
one for a pleach store:

```typescript
import { createSqliteAuditStore, createPgAuditStore } from "@pleach/compliance/audit/stores";
import { verifyAuditTrail } from "@pleach/compliance/audit";

const store = createSqliteAuditStore("./pleach.db"); // or createPgAuditStore(pool)
try {
  const trail = await verifyAuditTrail(store, { tenantId, chatId });
} finally {
  await store.close();
}
```

| Factory                                | Reads                                                                                                                                                                                                                                      |
| -------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `createSqliteAuditStore(pathOrHandle)` | A `pleach.db` path, opened read-only, or an open handle you own (`close()` then leaves it open)                                                                                                                                            |
| `createPgAuditStore(client, options?)` | A Postgres database with the core schema. A `pg` Pool runs each query in a read-only transaction; any other client needs `ownsSession: true` or `readOnly: false`. Pass `key` for a keyed (HMAC) chain. `close()` does not end your client |

Both return a `ClosableAuditStore` (`AuditStoreLike` plus `close()`).

* **Chat chains only.** `listRows` returns chat-kind chains only. Read other
  chain kinds with `pleach audit verify`.
* **`tenantId` is required**, and `limit` must be 1–10000 (default 1000).
* **`genesisChecked`** is `true` only when the run starts at the chain's first
  chained row and the caller set `startsAtGenesis`.
* **Tail evidence.** For tail evidence, use the Postgres store or hold an
  anchored head yourself.
* Verifying a long trail page by page is slow.

### What you provide alongside `valid` [#what-you-provide-alongside-valid]

`valid` grades the rows the store holds. For evidence that covers the
whole trail, you provide:

* **An anchored head per chain.** Compare the last row against it with `verifyChainAnchors` on `@pleach/core/eventLog`.
* **An anchored set of chain heads per tenant**, so the set of chats is itself evidence.
* **Chat-wide verification for multi-chain chats.** A chain can legitimately skip ordinals another chain in the same chat occupies. This primitive reads such a gap as a missing row (fail closed), so verify those chats with core's `verifyChainForChat`.

`AuditableCallQuery.streamByTimeRange` takes a `tenantId` option and yields only
that tenant's records. Omitting it streams every tenant, is deprecated, and
becomes required at the next `auditRecordVersion` bump.

## Deployment pattern [#deployment-pattern]

Register the package once when you construct your `SessionRuntime`. The
scrubbers wire into `EventLogWriter`; your code doesn't call them directly.

```typescript
import { SessionRuntime } from "@pleach/core";
import { complianceProfilePlugin } from "@pleach/compliance";

const runtime = new SessionRuntime({
  storage,
  checkpointer,
  userId:   req.user.id,
  tenantId: req.user.orgId,
  plugins:  [complianceProfilePlugin("hipaa") /* , gatewayPlugin, ... */],
});
```

`complianceProfilePlugin(profile)` accepts `"hipaa" | "gdpr" | "pci-dss" | "soc2"`
and returns a `HarnessPlugin` with that profile's scrubbers. Use
`scrubbersForProfile(profile)` to hand-roll the plugin. Custom
`KeyedRegexScrubber` instances register through their own plugin alongside it.

Installation does not wire tenant isolation: apply the RLS template to your
schema and call `auditRlsPolicies()` from your own CI step.

## What you pair it with [#what-you-pair-it-with]

`@pleach/compliance` covers redaction, the tenant RLS template and its check,
audit queries and reports, and the determinism certifier. Pair it with:

* **[`@pleach/gateway`](/docs/gateway)** for gateway-level auth and
  rate limiting on the outbound provider call.
* **`@pleach/core/eventLog`** for the tamper-evident hash chain. Stamping runs
  behind an `EventLogWriter` option, on by default, and verification
  (`verifyChainForChat`, `generateProof`) ships in the same subpath. The
  `TamperEvidence` plug-point in `@pleach/core/audit` keeps its no-op default
  for hosts that route attestation elsewhere.
* **`@pleach/core/attestation`** for signed envelopes over individual
  audit rows. See [Attestation](/docs/attestation).
* **[`@pleach/replay`](/docs/replay)** (`replayTurn`, `fromSnapshot`,
  `fork`, `aggregateMultiTenant&#x60;) and &#x2A;*[`@pleach/eval`](/docs/eval)**
  (scoring and diff) to re-run and score recorded turns.
  `@pleach/compliance/determinism` (`createDeterminismCertifier`,
  `verifyDeterminism`) certifies that a re-run reproduced the
  original. See [Determinism](/docs/determinism#compliance-certifier).
* **`KeyedRegexScrubber`** for identifiers beyond the four bundled
  regex scrubbers, such as international tax IDs, EU formats and
  sector-specific identifiers, and `@pleach/compliance/redaction` for
  PHI, Presidio and LLM redaction. See
  [Advanced redaction](#advanced-redaction).

Package versions and release status are on [Packages](/docs/packages).

## Adopting in stages [#adopting-in-stages]

To take the scrubbers now and defer the RLS template, register only the
scrubbers through a custom plugin. `auditRlsPolicies()` throws on the first
uncovered table, so wiring it into CI early means a red build until the tables
are covered.

```typescript
// lib/compliance/scrubbersOnlyPlugin.ts
import {
  SsnUsScrubber,
  CreditCardScrubber,
  UsDriverLicenseScrubber,
} from "@pleach/compliance";
import type { HarnessPlugin } from "@pleach/core";

export const scrubbersOnlyPlugin: HarnessPlugin = {
  name: "compliance-scrubbers-only",
  contributeScrubbers: () => [
    new SsnUsScrubber(),
    new CreditCardScrubber(),
    new UsDriverLicenseScrubber(),
  ],
};
```

The RLS template stays unapplied, so apply it before you treat rows as
tenant-isolated. Switch to the full `complianceProfilePlugin("hipaa")` (or your
profile) once `auditRlsPolicies()` comes back clean.

## Related SKUs [#related-skus]

* [`@pleach/core`](/docs/core) — the substrate this package wraps.
  Scrubbers run at `EventLogWriter`'s persistence boundary.
* [`@pleach/gateway`](/docs/gateway) — emits the cost events that compliance's
  attestation runtime reads.
* [`@pleach/replay`](/docs/replay) — `verifyChainIntegrity` walks the
  hash-chained event log that compliance writes.
* [`@pleach/eval`](/docs/eval) — scoring + diff over replayed,
  scrubbed event logs.

For the full SKU map see [Which SKU do I need?](/docs/which-sku).

## Where to go next [#where-to-go-next]

<Cards>
  <Card title="Scrubbers" href="/docs/scrubbers" description="The `Scrubber` contract — event-type allowlists, matched-spans, and the `contributeScrubbers` hook." />

  <Card title="Multi-tenant" href="/docs/multi-tenant" description="Where `tenantId` lives in the substrate and the production tenant-isolation checklist." />

  <Card title="Tenant facet" href="/docs/multi-tenant#the-runtimetenant-facet" description="`runtime.tenant.id` — reading the substrate's tenant identity inside plugins and tool handlers." />

  <Card title="Audit ledger" href="/docs/audit-ledger" description="The `ProviderDecisionLedger` and the three compliance plug-points the package will extend." />
</Cards>
