Skip to content
pleach
Operate

Scrubbers — redaction at write time

The Scrubber contract that gates event log writes through allowlisted redactors — SSN-US, Luhn, US-DL, KeyedRegex out of the box, plus the contributeScrubbers plugin hook.

Scrubbers are one concept in the safety & determinism thematic island — siblings of safety, fabrication detection, determinism, and 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) or fabrication detection (/docs/fabrication-detection). Scrubbers sit on the persistence boundary, downstream of synthesis.

Subpath@pleach/core/scrubbers

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.

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

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

ScrubberCoversNotes
SsnUsScrubberUS Social Security numbersRedacts the matched span
CreditCardScrubberCredit card numbersValidated, 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
UsDriverLicenseScrubberUS driver's license numbersFormats vary by state
KeyedRegexScrubberHost-defined patternsFor 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.

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.

// 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

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

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

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

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:

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.

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

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

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 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.

WriterDefaultOpt out / replace
Postgres EventLogWriterOnredaction: "off", or scrubbers
PostgresProviderDecisionLedgerOnredactor: null or piiRedactorNoop(), or your own PIIRedactor
Quickstart route ledgerOnauditLedgerRedactor
createPleachAgent KV ledgerOnredactor
createSqliteDurableStore event logOnredaction: "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.

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

  • 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.
  • They don't redact error text, logs or probes. The runtime's credential and infrastructure redactor does that; see /docs/redaction.
  • They don't detect fabricated output. See /docs/fabrication-detection.
  • They don't replace tamper-evidence. The 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

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.

// 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), 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).
  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).

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.

What's 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. The scrubber ("the clearer") is one row in the extension map.

Where to go next