Regulated-domain agent
An agent for teams under HIPAA, SOC 2, PCI, FedRAMP or 21 CFR Part 11 review. Constrained routing, PII gate, append-only ledger keyed for the regulator's query. Pleach supplies the evidence; you own the validation.
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 maps each topic to what Pleach provides and what your QMS provides. For broker-dealers, the SEC and FINRA page 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 if one runtime serves many regulated customers. Internal knowledge agent if grounding comes from a private corpus you must cite from. Customer support agent if the regulated turn is part of a longer-lived support session.
What you're 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
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.
// 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 and Providers for routing and Multi-tenant for the three-place isolation pattern.
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.
// 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:
- The policy text reaches the model before any tool call fires.
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.- 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);defineSafetyPolicycarries the operator-stated guidance alongside it. See Safety.
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 for the full list and Audit ledger for the schema.
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
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). Tool-event previews are on
(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.
- Read the session's events in sequence (Event log).
message.userholds the question. The CGM tool'stool.startedandtool.completedrows say when it read. The preview holds the readings it returned, and records whether it was cut short. - Rebuild the reply the user saw with
messageProjection, corrections included (Event log projections). - Look for a
guard.decisionrow 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). - Read the call row behind the reply for the provider, the model and any fallback (The auditable call row).
- 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). - Run
verifyAuditTrailfor the tamper verdict (Proving the audit trail is intact).
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).
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.
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.
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 for the recording modes and Determinism for what replay does and doesn't promise.
Bundled scrubbers from @pleach/compliance
@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:
// 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:
hipaacovers SSN, driver's licence and card.gdprandsoc2cover SSN and card.pci-dsscovers card numbers only.
See the 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), 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:
// 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 for the contract and the bundled-set
guarantees.
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.
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 for the full set and schemas.
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).
With the tenant facet, that turns "we stamp the tenant
everywhere" from a code-review promise into a CI invariant. See
Recipes (recipes 11 and 13) for the PHI-gate and hash-chain
verification walks, and Packages for the SKU status table.
Project layout
This is the heaviest delta of the six shapes. On top of the
baseline, 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 scansWhat changes from the baseline:
compliance/wires the three audit hooks (tamper evidence, PII redaction, typed records), each from@pleach/compliance. Keeping them adjacent makes the audit claim a single-directory read.safety/family-lock.tsenforces provider routing at session start.permittedFamiliespins which model families a session can reach, and the family lock fails closed if the wrong family is requested mid-turn. An auditor asks to see this file first.ledger/gdpr-soft-delete.tsis 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 directUPDATEwould erase the trail GDPR requires..github/workflows/compliance.ymlruns your tenant checks (auditRlsPolicies()plus your own tenant-predicate scans), so the invariant is enforced in your build.
Where to go next
Compliance
The @pleach/compliance plugin — scrubbers, hash chain, typed records, and the CI gates that come with it.
Scrubbers
The scrubber contract, the four bundled scrubbers, and how to add your own.
Hash chain
How each event-log row carries the previous row's hash, and the verification walk.
Typed records
The typed audit records and their schemas.
Tenant facet
The tenant config the audit row and the chain both lean on.
Safety
The capability-subtracting policy contract — refuse, rewrite, or annotate, but never generate.
Providers
The family-strict cascade and the permittedFamilies constraint that locks it.
Audit ledger
The call ledger schema, indexes, and retention.
Eval and replay
runtimeMode, recording, and the diff engine that powers replay defense.
Multi-tenant SaaS agent
The multi-tenant SaaS agent shape — recurring per-tenant pattern, the primitives that handle it, the ops surface around it.
Swarm agent
An agent that spawns subagents at scale — deep sequential loops, parallel fan-out, supervisor/worker topologies, recursive delegation — with cost ceilings and a session-tree audit walk.