# Scrubbers — redaction at write time (/docs/scrubbers)



Scrubbers are one concept in the **safety & determinism**
[thematic island](/docs/concept-clusters#what-lives-outside-the-cluster-pattern) —
siblings of [safety](/docs/safety),
[fabrication detection](/docs/fabrication-detection),
[determinism](/docs/determinism), and [fingerprint](/docs/fingerprint).

A `Scrubber` gates writes into the event log. Before a row persists, every
registered scrubber runs against the payload and rewrites matched spans. Only the
redacted form reaches storage.

This isn't prompt-input scrubbing ([`/docs/safety`](/docs/safety)) or fabrication
detection ([`/docs/fabrication-detection`](/docs/fabrication-detection)). Scrubbers
sit on the persistence boundary, downstream of synthesis.

**Subpath:** `@pleach/core/scrubbers`

## The `Scrubber` contract [#the-scrubber-contract]

A scrubber has an `id` and a `scrub(input, ctx)` method. It takes one string plus
context and returns the redacted string with attribution metadata. Scrubbers
don't declare event types; scoping is global.

```typescript
import type { Scrubber } from "@pleach/core/scrubbers";
```

A single allowlist, `SCRUBBABLE_FIELDS`, keyed by event type, names the dotted
field paths each event type exposes to redaction. The chain applies every
registered scrubber to every allowlisted field.

`scrub` returns a `ScrubResult`: `{ redacted, matchCount, matchedScrubberIds }`.
`redacted` equals the input when nothing matched, and `matchedScrubberIds` is `[]`
when none fired. These feed the `event.redacted` audit meta-event, so a security
dashboard or SOC2 evidence export can count redactions per type without
re-scanning stored rows. The result returns no original text, offsets or spans.

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

These four ship in `@pleach/compliance` (see [`/docs/compliance`](/docs/compliance)).

| Scrubber                  | Covers                      | Notes                                                                                                                                                                                                         |
| ------------------------- | --------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `SsnUsScrubber`           | US Social Security numbers  | Redacts the matched span                                                                                                                                                                                      |
| `CreditCardScrubber`      | Credit card numbers         | Validated, to cut false positives on other numeric content. Leaves the fractional digits of a decimal a double could print (`0.4111111111111111`) unless a card word such as `card` or `visa` comes before it |
| `UsDriverLicenseScrubber` | US driver's license numbers | Formats vary by state                                                                                                                                                                                         |
| `KeyedRegexScrubber`      | Host-defined patterns       | For custom identifiers such as medical record numbers, tax IDs or employee ids                                                                                                                                |

Each is an independent implementation of the `Scrubber` contract. Hosts that need a
new regulated identifier use `KeyedRegexScrubber` rather than waiting for an
upstream addition.

Redaction that patterns can't express, such as clinical PHI, named-entity
detection or a model-driven pass, lives in a separate pipeline:
`createPHIScrubber`, `createPresidioScrubber` and `createLLMScrubber` under
`@pleach/compliance/redaction`. See
[Advanced redaction](/docs/compliance#advanced-redaction).

## The `contributeScrubbers` plugin hook [#the-contributescrubbers-plugin-hook]

Hosts register additional scrubbers through the `HarnessPlugin` contract. The
runtime composes contributions from every loaded plugin into the registry the
event log writer consults.

```typescript
// lib/plugins/tenantCompliancePlugin.ts
import type { HarnessPlugin } from "@pleach/core";
import type { Scrubber } from "@pleach/core/scrubbers";

const tenantIdentifierScrubber: Scrubber = {
  /* shape defined below in the custom example */
};

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

Scrubbers chain in plugin registration order: one scrubber's output is the next
one's input. The runtime won't reorder them, so sequence scrubbers that match
overlapping spans explicitly.

## Event-type allowlist coverage [#event-type-allowlist-coverage]

Every event type core writes has an entry in `SCRUBBABLE_FIELDS`, and CI checks
this. An empty entry (`[]`) means "audited, no scrubbable fields".

### Declaring scrubbable fields on a plugin event type [#declaring-scrubbable-fields-on-a-plugin-event-type]

An event type you declare through `contributeEventTypes` lists its own
free-text payload paths with `scrubbableFields`:

```typescript
contributeEventTypes() {
  return {
    "ticket.opened": {
      payload: { note: "string", priority: "string" },
      scrubbableFields: ["payload.note"],
    },
  };
}
```

Omit `scrubbableFields` and the row is stored as written, and the probe
`[C8:unscrubbed-event-type]` fires. A path may be written `note` or
`payload.note`. On a writer with a key registry, the same paths are also sealed
under the row's subject key.

Rules for using it:

* **Core entries win.** A plugin declares its own event types only. A
  core type, a `domain.`-prefixed kind, or a plugin whose name contains
  a dot is ignored with a warning.
* **Declarations take effect on the writer you give them to**:
  `EventLogWriter`, `createPgEventLogWriter` and `createSqliteDurableStore`.
  `plugins` passed to `createPleachRuntime` or `createPleachAgent` don't reach
  the writer. Pass the plugin list to `EventLogWriter` (as `plugins` or
  `pluginManager`), or build a `scrubbableFieldsLookup` with
  `createScrubbableFieldsLookup` from `@pleach/core/scrubbers` and pass it to
  `createPgEventLogWriter` or `createSqliteDurableStore`.
* **Sealed fields aren't queryable.** Leave fields the host filters on out of
  `scrubbableFields`.
* **Paths follow field names.** Update the path when you rename a payload field.
* **Keep personal data out of payloads** where you can. Scrubbers redact only
  what they recognize.

### Registering your host's `domain.*` event types [#registering-your-hosts-domain-event-types]

A plugin can't declare a `domain.`-prefixed type, and core carries none.
Register the ones your host writes with `registerHostScrubbableFields`
from `@pleach/core/scrubbers`, before you build any event-log writer:

```typescript
import { registerHostScrubbableFields } from "@pleach/core/scrubbers";

const unregister = registerHostScrubbableFields({
  "domain.billing.invoice_sent": ["payload.note"],
  "domain.billing.invoice_paid": [], // audited, nothing to scrub
});
```

A registered type resolves like a core entry in every reader, and it
wins over a plugin's `scrubbableFields`. An unregistered `domain.*` type
is stored as written, and `[C8:unscrubbed-event-type]` fires.
Registration is process-wide and additive: two registrations of one key
union their paths, and the returned function removes only its own
entries. A key core already declares, a malformed key, a reserved kind
or an unscrubbable path is skipped with a `console.warn`.
`listHostScrubbableFields()` returns what's registered.

```typescript
import { createPleachAgent } from "@pleach/core";
import type { HarnessPlugin } from "@pleach/core";
import { createEventLogScrubberSource } from "@pleach/core/plugins";
import { createScrubbableFieldsLookup } from "@pleach/core/scrubbers";
import { createSqliteDurableStore } from "@pleach/core/store";

const ticketPlugin: HarnessPlugin = {
  name: "ticket",
  version: "1.0.0",
  contributeEventTypes: () => ({
    "ticket.opened": {
      payload: { note: "string" },
      scrubbableFields: ["payload.note"],
    },
  }),
};
const plugins = [ticketPlugin];

const scrubbableFieldsLookup = createScrubbableFieldsLookup(
  createEventLogScrubberSource(plugins).collectEventTypes(),
);
const db = createSqliteDurableStore("./pleach.db", { scrubbableFieldsLookup });
const agent = createPleachAgent({ plugins, db });
```

## `EventLogWriter` integration [#eventlogwriter-integration]

The writer applies scrubbers when it persists. Consumer code doesn't touch the
scrubber registry, and registering a scrubber needs no call-site change.

```typescript
import { EventLogWriter } from "@pleach/core/eventLog";

await writer.append({
  type: "tool.completed",
  sessionId,
  turnId,
  payload: { /* ... */ },
});
```

There's one write surface and no raw path that skips scrubbers. Bypassing
redaction would mean bypassing the writer, which also carries the hash chain,
tenant scoping and the append-only invariant.

## The audit ledgers scrub too [#the-audit-ledgers-scrub-too]

The direct call-row ledgers bypass the event log, so they run the same scrubber
chain themselves, on by default. `PostgresProviderDecisionLedger`, the quickstart
route's durable ledger and the `createPleachAgent` KV ledger apply
`createScrubberChainRedactor()` (`@pleach/core/audit`) under the
`SCRUBBABLE_FIELDS["audit.recorded"]` allowlist. A call row and its
`audit.recorded` event store the same redacted shape.

| Writer                               | Default | Opt out / replace                                                  |
| ------------------------------------ | ------- | ------------------------------------------------------------------ |
| Postgres `EventLogWriter`            | On      | `redaction: "off"`, or `scrubbers`                                 |
| `PostgresProviderDecisionLedger`     | On      | `redactor: null` or `piiRedactorNoop()`, or your own `PIIRedactor` |
| Quickstart route ledger              | On      | `auditLedgerRedactor`                                              |
| `createPleachAgent` KV ledger        | On      | `redactor`                                                         |
| `createSqliteDurableStore` event log | On      | `redaction: "off"`, or explicit `scrubbers`                        |

The SQLite event log matches Postgres. With no `scrubbers`, the built-in set
redacts emails, prefixed API keys, JWTs and phone numbers before the row is
hashed, and stores an `event.redacted` receipt beside each redacted row.
`redaction: "off"` stores rows verbatim and disables explicit `scrubbers` too.

The phone check leaves a slice of a space-joined integer list alone, so
`203 305 4410` inside `101 203 305 4410 4412 4415` stays as written. A bare
`415 555 1234` is still redacted when it stands alone, sits next to a comma
or another phone number, or follows a phone word such as `call` or `tel` on
the same line. Numbers written with parentheses, dots, hyphens or `+1` are
redacted as before.

A ledger redactor that throws never stores the raw row: the row is written
withheld. See
[What the ledger scrubs before storing](/docs/auditable-call-row#what-the-ledger-scrubs-before-storing).

If you add your own event-write route, send it through the writer so the chain
runs on it. Registering a scrubber for an event type is enough; no route change is needed.

## What scrubbers do NOT do [#what-scrubbers-do-not-do]

* **They don't redact prompt inputs sent to the model.** A scrubber runs after the
  model has seen the data, so it protects the *persisted* surface, not the
  *model* surface. Use safety policies for that; see [`/docs/safety`](/docs/safety).
* **They don't redact error text, logs or probes.** The runtime's credential and
  infrastructure redactor does that; see [`/docs/redaction`](/docs/redaction).
* **They don't detect fabricated output.** See
  [`/docs/fabrication-detection`](/docs/fabrication-detection).
* **They don't replace tamper-evidence.** The [hash chain](/docs/hash-chain)
  shows a row hasn't changed since write; scrubbers shape what the row contains.
* **They don't dedupe.** Scrubbers are stateless across rows, so the same input
  always gives the same output.

## Custom scrubber example [#custom-scrubber-example]

A tenant with internal employee identifiers shaped `EMP-` followed by six digits
can register a `KeyedRegexScrubber`. It takes an `id` and one or more `entries`,
each a `name`, `pattern` and `replacement`. You supply the replacement string.
There is no `eventTypes` field; scoping comes from `SCRUBBABLE_FIELDS`.

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

const employeeIdScrubber = new KeyedRegexScrubber({
  id: "internal-pii",
  entries: [
    {
      name:        "employee-id",
      pattern:     /\bEMP-\d{6}\b/g,
      replacement: "[REDACTED:EMPLOYEE_ID]",
    },
  ],
});

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

Register the plugin once at runtime construction. Every write through
`EventLogWriter` then runs the scrubber against the allowlisted fields, and rows
persist with your `replacement` (here `[REDACTED:EMPLOYEE_ID]`) in place of the
match.

The entry `name` appears in `matchedScrubberIds` as `<id>:<name>`. Pick a name
that reads well in a compliance review, such as `employee-id`.

**Example: a Social Security number in an HR question.** An employee pastes
their US Social Security number into an internal benefits question. A security
reviewer asks whether the number reached the stored record. The host loaded
`complianceProfilePlugin("gdpr")`, which includes `SsnUsScrubber`, on a durable
event store.

1. The default SQLite redactor covers emails, API keys, JWTs and phone
   numbers, not SSNs. The profile adds `SsnUsScrubber`
   ([Compliance](/docs/compliance)), which matches `NNN-NN-NNNN`.
2. The writer scrubs the `message.user` row before it hashes it. The stored
   prompt holds `[REDACTED:SSN]` where the number was
   ([Event log](/docs/event-log)).
3. An `event.redacted` row beside it names the scrubber that matched and how
   many spans. It carries no original text or offsets.
4. `verifyChainForChat` passes. The hash covers the redacted form, so there is
   nothing to reconcile against the original ([Hash chain](/docs/hash-chain)).

The scrubber runs after the model saw the text, so the number reached the
provider. Redaction is pattern-based: an SSN typed without separators, or
written out in words, isn't caught by default. Prompt-side controls are in
[Safety](/docs/safety).

## What's required when you add a scrubber [#whats-required-when-you-add-a-scrubber]

A scrubber registered through `contributeScrubbers` adds redaction coverage for
the fields `SCRUBBABLE_FIELDS` lists. A plugin that declares a new type through
`contributeEventTypes` lists its free-text paths in `scrubbableFields`; see
[Event-type allowlist coverage](#event-type-allowlist-coverage). The scrubber
("the clearer") is one row in the [extension map](/docs/extending).

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

<Cards>
  <Card title="Safety policies" href="/docs/safety" description="Prompt-input scrubbing and refusal contracts — the synthesis-time counterpart to write-time scrubbers." />

  <Card title="Compliance" href="/docs/compliance" description="Where the four bundled scrubbers (SSN-US, Luhn, US-DL, KeyedRegex) ship from." />

  <Card title="Plugin contract" href="/docs/plugin-contract" description="The HarnessPlugin surface that exposes the contributeScrubbers hook." />

  <Card title="Audit ledger" href="/docs/audit-ledger" description="The audit row every redacted event is joinable against by turnId." />
</Cards>
