# Regulated-domain agent (/docs/regulated-domain-agent)



A regulated-domain agent is the use case where "we have audit logs" stops
being the answer and "show me the chain of custody for turn T" becomes the
question. Pleach supplies the evidence as the agent runs: provider routing
is constrained at session start, a PII gate runs before the prompt leaves
the process, and every call writes one append-only row keyed by turn, tool
and agent depth. You own the validation.

Validation teams call that question *reconstructibility*: could a competent
third party, working only from the audit trail, reconstruct what the agent
did, on which inputs, through which model, months later? The recorded event
log is the artifact that answers it, and a replay re-serves it in order to
show what ran. It's the bar a computer-system-validation (CSV) or GAMP 5
audit-trail review already applies. Your validation team owns the review.
The [Part 11 and ALCOA+ page](/docs/compliance/part-11-alcoa) maps each
topic to what Pleach provides and what your QMS provides. For broker-dealers,
the [SEC and FINRA page](/docs/compliance/sec-finra) does the same with a
grade on each topic.

This page walks the four pieces auditors ask about: provider routing
constraints, the PII gate, the audit row, and the replay path.

**Related shapes.**
[Multi-tenant SaaS agent](/docs/multi-tenant-saas-agent) if one
runtime serves many regulated customers.
[Internal knowledge agent](/docs/internal-knowledge-agent) if
grounding comes from a private corpus you must cite from.
[Customer support agent](/docs/customer-support-agent) if the
regulated turn is part of a longer-lived support session.

## What you're building [#what-youre-building]

A turn loop for a regulated domain: a clinical decision-support helper, a
claims-review assistant, a know-your-customer reviewer, an FERPA-bound
tutor. The shape is the same in any framework:

* Provider routing is locked to a vetted family list at session start.
* A PII redaction policy gates the call before it dispatches.
* The ledger row carries enough identity to answer "who, what, when"
  without joining four tables.
* The turn is replayable for as long as the storage adapter keeps the
  inputs.

`@pleach/core` gives you the constrained routing, the PII gate contract, the
auditable row and the replay. `@pleach/compliance` adds the bundled
scrubbers, the tamper-evident hash chain, the typed audit records a
regulator reads first, and `auditRlsPolicies()` for checking tenant scoping
in your own CI.

## Lock provider routing at session start [#lock-provider-routing-at-session-start]

`permittedFamilies` narrows the family-strict cascade to a vetted
set. A model family that isn't on the list can't be picked, even
as a fallback.

```typescript
// lib/runtime.ts
import { SessionRuntime, definePleachPlugin } from "@pleach/core";

export function buildClinicalRuntime(req: AuthedRequest) {
  return new SessionRuntime({
    provider:     anthropicProvider,
    storage:      new SupabaseAdapter({ client: supabase }),
    checkpointer: new SupabaseSaver({ client: supabase }),
    plugins:      [definePleachPlugin("clinical-tools", {
      tools:          clinicalTools,
      safetyPolicies: [phiRedaction, refuseOnUncertainty],
    })],
    permittedFamilies: new Set(["anthropic-bedrock", "azure-openai"]),
    tenantId:       req.tenantId,          // e.g. hospital_id
    organizationId: req.organizationId,
    userId:         req.userId,
  });
}
```

Under a BAA or FedRAMP boundary, the family lock isn't a hint. Routing
stays inside the families you list, and a provider not on the list is never
reached. The list is recorded at session start, so the constraint is
auditable.

See [Family lock](/docs/family-lock) and [Providers](/docs/providers) for
routing and [Multi-tenant](/docs/multi-tenant) for the three-place isolation
pattern.

## Gate PII before the prompt leaves the process [#gate-pii-before-the-prompt-leaves-the-process]

A pre-dispatch safety policy runs before the provider call. If it rewrites
the message, the provider sees the rewrite. If it refuses, the call doesn't
happen.

```typescript
// lib/safety/phiRedaction.ts
import { defineSafetyPolicy, safetyPolicyId } from "@pleach/core/safety";

export const phiRedaction = defineSafetyPolicy({
  id:          safetyPolicyId("regulated-domain.phi-redaction"),
  version:     "1.0.0",
  framework:   "HIPAA",
  enforcement: "guardrail",
  content: ({ runtimeRole }) => `
[PHI policy ${runtimeRole ?? "default"}]
Before responding, scrub identifiers that match
common PHI patterns (MRN, SSN, DOB, account
numbers, full names paired with conditions).
Replace each occurrence with the literal token
"[REDACTED]". Do not paraphrase around the
redaction — the original token never leaves.
  `.trim(),
});
```

Three details matter:

1. The policy text reaches the model before any tool call fires.
2. `enforcement: "guardrail"` records the operator's stated intent on every
   ledger row that consults this policy, so a later audit can ask which
   turns ran under the PHI guardrail. See [Audit ledger](/docs/audit-ledger).
3. The contract is **capability-subtracting**: a safety policy can refuse or
   constrain, but never generates new content. Per-pattern scrubbing lives
   in `@pleach/compliance` (see [Scrubbers](/docs/scrubbers));
   `defineSafetyPolicy` carries the operator-stated guidance alongside it.
   See [Safety](/docs/safety).

## What the audit row carries [#what-the-audit-row-carries]

Every call writes one row. Each row answers the questions an auditor reads
first.

| Audit question                          | Answered by                  |
| --------------------------------------- | ---------------------------- |
| Is this row out of order or duplicated? | Its record identifier        |
| Which covered entity is this for?       | The tenant                   |
| What was the unit of work?              | The user turn                |
| What did the agent invoke?              | The tool called              |
| Did a child agent do this?              | Whether a child agent ran it |
| Which user turn does this roll up to?   | The top-level turn           |
| Which model produced this?              | The model that ran           |
| Did routing stay inside the BAA list?   | The provider that ran        |
| When did this happen?                   | The recorded time            |

See [Auditable call row](/docs/auditable-call-row) for the full
list and [Audit ledger](/docs/audit-ledger) for the schema.

## The "chain of custody for turn T" query [#the-chain-of-custody-for-turn-t-query]

A regulator hands the engineer a turn and a question. One query on your
ledger returns that turn's record in order, including every child agent at
any depth: no joins, no log correlation, no grep. A query by session does
the same for a whole session.

### Worked example: a diabetes coach's reply under review [#worked-example-a-diabetes-coachs-reply-under-review]

**Example: a reply that nudged an insulin dose.** A team ships a chat coach for
adults with type 1 or type 2 diabetes as software as a medical device. It reads
the user's continuous glucose monitor (CGM) through a tool and suggests changes
to meals, activity and sleep. Its intended use excludes dosing advice. A
`refusal` safety policy, run with `safetyEnforcementMode: "enforce"`, carries a
`regex-refusal` guard that replaces any reply suggesting a dose change
([Safety](/docs/safety)). Tool-event previews are on
([What a tool row holds](/docs/event-log#what-a-tool-row-holds)).

A user with type 1 diabetes asks about a high reading after dinner. The reply
suggests skipping the bedtime snack and taking "a little extra" at the next
meal. Overnight the user goes low and reports it. The reviewer asks which
readings the coach had, what it said, whether the dosing guard fired, and which
release was live.

1. Read the session's events in sequence ([Event log](/docs/event-log)).
   `message.user` holds the question. The CGM tool's `tool.started` and
   `tool.completed` rows say when it read. The preview holds the readings it
   returned, and records whether it was cut short.
2. Rebuild the reply the user saw with `messageProjection`, corrections
   included
   ([Event log projections](/docs/event-log-projections#messageprojection)).
3. Look for a `guard.decision` row on that turn. A veto names the id and
   version of the policy that replaced the reply. Here there is none: "a
   little extra" matched no pattern, so the reply went out
   ([Which policy refused](/docs/safety#which-policy-refused-on-the-row)).
4. Read the call row behind the reply for the provider, the model and any
   fallback ([The auditable call row](/docs/auditable-call-row)).
5. Take the config-manifest hash from those rows to
   `npx @pleach/core audit changes <hash> --tenant <id>` for the change that
   was live ([Config manifest](/docs/config-manifest)).
6. Run `verifyAuditTrail` for the tamper verdict
   ([Proving the audit trail is intact](/docs/compliance#verifyaudittrail)).

The missing guard row shows that no pattern matched. It doesn't show the guard
was enough. A pattern catches only the phrasings someone wrote down, so the
finding feeds your risk file and the next pattern set. Advice that must not
reach a user unreviewed belongs behind an approval gate on a tool, not in free
text ([Interrupts](/docs/interrupts)).

Model inputs are kept as hashes, so the record shows what the model was given
and returned, not how it reasoned. Replay re-serves this record and doesn't
re-derive the answer. For which version served one output across a change, see
the [Part 11 example](/docs/compliance/part-11-alcoa#when-the-record-is-asked-for).

## Replay for audit defense [#replay-for-audit-defense]

A recorded turn can be replayed months later. Replay re-serves the recorded
calls from the event log and shows what ran. It doesn't run the model again
to re-derive the answer.

```typescript
import { createReplayRuntime } from "@pleach/replay";

const replayRuntime = createReplayRuntime({
  sessionRuntime: runtime,
  tenantId,
});

const replay = await replayRuntime.replayTurn({
  chatId:    sessionId,
  tenantId,
  messageId: turnId,
});

// `replay.state` is the reconstructed HydratedHarnessState (typed `unknown`):
// the tools that fired, the model's answer, the redaction notes, and the
// family choice all hang off the rehydrated turn state.
console.log(replay.state);
```

An auditor asking "how did the system reach this conclusion?" gets the
recorded walkthrough of the original decision, and the engineer walks the
recorded turn instead of reconstructing from logs. Re-running the original
execution is a separate, version-pinned exercise that replay doesn't
guarantee.

See [Eval and replay](/docs/eval-and-replay) for the recording modes and
[Determinism](/docs/determinism) for what replay does and doesn't promise.

## Bundled scrubbers from `@pleach/compliance` [#bundled-scrubbers-from-pleachcompliance]

`@pleach/compliance` ships four scrubbers implementing the `Scrubber`
contract from `@pleach/core`. They cover the identifiers a US-regulated host
hits first:

| Scrubber     | Matches                     | Notes                                       |
| ------------ | --------------------------- | ------------------------------------------- |
| `SSN-US`     | US Social Security Numbers  | dashed and run-on forms                     |
| `Luhn`       | Credit card numbers         | Luhn-validated, not pattern-only            |
| `US-DL`      | US driver's license numbers | per-state format set                        |
| `KeyedRegex` | host-supplied identifiers   | parameterized; one registration per pattern |

Scrubbers register at runtime construction through the plugin's
`contributeScrubbers` hook, into the same pre-dispatch gate the
`phiRedaction` policy plugs into.

The fastest wiring is a profile-keyed factory that returns a `HarnessPlugin`
with the canonical bundle for the regulatory regime:

```typescript
// lib/runtime.ts
import { SessionRuntime } from "@pleach/core";
import {
  complianceProfilePlugin,
  KeyedRegexScrubber,
} from "@pleach/compliance";

const compliance = complianceProfilePlugin("hipaa", {
  // Host-specific identifiers layer on top of the profile bundle.
  // KeyedRegexScrubber takes an `entries` array; each entry carries
  // the pattern + replacement + a stable name for audit-trail attribution.
  extraScrubbers: [
    new KeyedRegexScrubber({
      id: "mrn",
      entries: [
        { name: "MRN", pattern: /\bMRN-\d{7}\b/g, replacement: "[MRN-REDACTED]" },
      ],
    }),
    new KeyedRegexScrubber({
      id: "ein",
      entries: [
        { name: "EIN", pattern: /\b\d{2}-\d{7}\b/g, replacement: "[EIN-REDACTED]" },
      ],
    }),
  ],
});

export function buildRegulatedRuntime(req: AuthedRequest) {
  return new SessionRuntime({
    plugins: [compliance],
    // ...routing, storage, tools, tenant as above
  });
}
```

The supported profile names are `"hipaa" | "gdpr" | "pci-dss" | "soc2"`.
Each maps to a curated subset of the bundled scrubbers:

* `hipaa` covers SSN, driver's licence and card.
* `gdpr` and `soc2` cover SSN and card.
* `pci-dss` covers card numbers only.

See the [scrubbers](/docs/compliance#the-four-bundled-scrubbers) section of
Compliance. Each profile is a starting set. For clinical PHI, add the
shipped `createPHIScrubber` from `@pleach/compliance/redaction/scrubbers/phi`
in a redaction pipeline (see
[Advanced redaction](/docs/compliance#advanced-redaction)), and add your own
identifiers with `KeyedRegexScrubber`.

To wire scrubbers by hand, or compose them with other plugin contributions
in one plugin literal, use `definePleachPlugin` from `@pleach/core`:

```typescript
// lib/plugins/myCompliancePlugin.ts
import { definePleachPlugin } from "@pleach/core";
import {
  SsnUsScrubber,
  CreditCardScrubber,
  UsDriverLicenseScrubber,
} from "@pleach/compliance/scrubbers";

export const myCompliancePlugin = definePleachPlugin("my-compliance", {
  scrubbers: [
    new SsnUsScrubber(),
    new CreditCardScrubber(),
    new UsDriverLicenseScrubber(),
  ],
  // ...other contributions (safety policies, prompts, tools, etc.)
});
```

`KeyedRegexScrubber` is the host's extension point: a regulated SaaS adds
its domain identifiers without forking the core scrubber set. See
[Scrubbers](/docs/scrubbers) for the contract and the bundled-set
guarantees.

## Tamper-evident hash chain on the event log [#tamper-evident-hash-chain-on-the-event-log]

Each event-log row carries the hash of the row before it. A malicious
database write to any row breaks the chain at that row and every row after
it, and a verifier reports where.

Writing the chain and verifying it both ship in `@pleach/core`. The writer
runs behind an event-log writer option, and `@pleach/replay@0.1.0` consumes
the verifier. Pin `@pleach/core` and `@pleach/replay` to matching versions
when you run the chain in production. See [Hash chain](/docs/hash-chain).

## Typed audit records [#typed-audit-records]

Two record shapes matter most in regulated domains:

* **Synthesis quality record**, written for every synthesized answer. A
  reviewer can ask whether an answer tripped a fabrication or degeneration
  guard, and how many retries and how much latency it took.
* **Interrupt decision record**, written when a human-in-the-loop interrupt
  resolves. A reviewer can ask why it fired, who resolved it, which branch
  they chose, and when. A clinician override is one row.

Both carry the audit row's identity and chain into the event log. See
[Typed records](/docs/typed-records) for the full set and schemas.

## Tenant checks in your CI [#tenant-checks-in-your-ci]

Pleach's CI checks that core's event-log write paths carry a tenant
identifier. Core's base schema ships owner and service-role policies, and
the tenant policies come with `@pleach/compliance`.

Installing `@pleach/compliance` adds no check to your build. Apply the
tenant RLS tier and call `auditRlsPolicies()` from a CI step (see
[Wiring tenant isolation into your own CI](/docs/compliance#wiring-tenant-isolation-into-your-own-ci)).
With the [tenant facet](/docs/tenant-facet), that turns "we stamp the tenant
everywhere" from a code-review promise into a CI invariant. See
[Recipes](/docs/recipes) (recipes 11 and 13) for the PHI-gate and hash-chain
verification walks, and [Packages](/docs/packages) for the SKU status table.

## Project layout [#project-layout]

This is the heaviest delta of the six shapes. On top of the
[baseline](/docs/project-layout#a-layout-that-works), regulated deployments
add a `compliance/` module wiring `@pleach/compliance` into all three
audit-ledger hooks, lock provider selection at the runtime construction
site, and keep the wiring an auditor reads in one place.

```
my-app/
  src/
    pleach/
      runtime.ts                # SessionRuntime with permittedFamilies + @pleach/compliance plug-ins
      compliance/
        scrubbers.ts            # the bundled scrubber set from @pleach/compliance
        hash-chain.ts           # tamper-evident chain wiring on the event log
        typed-records.ts        # typed audit records
      safety/
        family-lock.ts          # → /docs/family-lock — provider routing pinned at session start
      ledger/
        gdpr-soft-delete.ts     # the GDPR entry point (callable, audited)
    app/
      api/agents/[id]/route.ts
  .github/
    workflows/
      compliance.yml            # your tenant checks: auditRlsPolicies() + tenant-predicate scans
```

What changes from the baseline:

* **`compliance/` wires the three audit hooks** (tamper evidence, PII
  redaction, typed records), each from
  [`@pleach/compliance`](/docs/compliance). Keeping them adjacent makes the
  audit claim a single-directory read.
* **`safety/family-lock.ts` enforces provider routing at session start.**
  `permittedFamilies` pins which model families a session can reach, and the
  [family lock](/docs/family-lock) fails closed if the wrong family is
  requested mid-turn. An auditor asks to see this file first.
* **`ledger/gdpr-soft-delete.ts` is callable code, not a SQL migration.**
  Soft-delete runs through the ledger's typed entry point, so the deletion
  is itself an audited event. A direct `UPDATE` would erase the trail GDPR
  requires.
* **`.github/workflows/compliance.yml` runs your tenant checks**
  (`auditRlsPolicies()` plus your own tenant-predicate scans), so the
  [invariant](#tenant-checks-in-your-ci) is enforced in your build.

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

<Cards>
  <Card title="Compliance" href="/docs/compliance" description="The @pleach/compliance plugin — scrubbers, hash chain, typed records, and the CI gates that come with it." />

  <Card title="Scrubbers" href="/docs/scrubbers" description="The scrubber contract, the four bundled scrubbers, and how to add your own." />

  <Card title="Hash chain" href="/docs/hash-chain" description="How each event-log row carries the previous row's hash, and the verification walk." />

  <Card title="Typed records" href="/docs/typed-records" description="The typed audit records and their schemas." />

  <Card title="Tenant facet" href="/docs/tenant-facet" description="The tenant config the audit row and the chain both lean on." />

  <Card title="Safety" href="/docs/safety" description="The capability-subtracting policy contract — refuse, rewrite, or annotate, but never generate." />

  <Card title="Providers" href="/docs/providers" description="The family-strict cascade and the permittedFamilies constraint that locks it." />

  <Card title="Audit ledger" href="/docs/audit-ledger" description="The call ledger schema, indexes, and retention." />

  <Card title="Eval and replay" href="/docs/eval-and-replay" description="runtimeMode, recording, and the diff engine that powers replay defense." />
</Cards>
