Safety policies
SafetyContribution is structurally distinct from PromptContribution — registered policies stay inert until an operator opts in.
A safety policy is advisory by default. It adds refusal and guardrail prose to the system prompt and records the operator's stated intent on the audit row. It never generates new content.
Hard effects (blocking a tool call, vetoing a synthesis) landed in v1.2 behind an
operator opt-in. SessionRuntimeConfig.safetyEnforcementMode defaults to
"prose-only", which keeps the prose-only posture; "enforce" activates
structural blocking for policies that ship a concrete guard.
The contract is capability-subtracting:
defineSafetyPolicy({ name, appliesTo: "pre-dispatch" | "post-tool", async check(state, ctx) → { allow, reason, forceText } }), or with
rewrite(prompt) → { allow, rewrittenPrompt, auditNote }. Both forms are
async, and both land their result on the audit row.
A SafetyContribution is the registration shape behind those policies. It
resembles a PromptContribution but differs in five places, so @pleach/core
ships them as separate contracts.
Plugin authors register policies. Operators enable them at runtime construction. The defaults, composition and audit surface differ.
import {
SafetyPolicyRegistry,
composeSafetyContent,
SAFETY_SECTION_HEADER,
SAFETY_ENFORCEMENT_EFFECTS,
KNOWN_REGULATORY_FRAMEWORKS,
safetyPolicyId,
} from "@pleach/core/safety";
import type {
SafetyContribution,
SafetyPolicyId,
SafetyPolicySummary,
SafetyEnforcement,
SafetyPolicyScope,
SafetyGuard,
RegulatoryFramework,
KnownRegulatoryFramework,
} from "@pleach/core/safety";@pleach/core/safetySafety lives outside the cluster pattern. Its five concepts (
safety,scrubbers,fabrication-detection,determinism,fingerprint) share no triplet. See What lives outside the cluster pattern.
Why a separate contract
| Difference | PromptContribution | SafetyContribution |
|---|---|---|
| Default state | Active when plugin is loaded | Inert until enabled by id at runtime construction |
| Composition role | Adds prose that shapes behavior | Adds gates + refusal prose, composed LAST |
| Auditability | Internal to the registry | Public — runtime.safety.listActivePolicies() returns a versioned SafetyPolicySummary[] |
| Override semantics | mode: "replace" overrides | replace is structurally absent — the field doesn't exist on SafetyContribution |
| Versioning | Implicit | Explicit semver per policy; bumps participate in the fingerprint key |
A non-regulated deployment can skip sector-specific disclaimer policies that a regulated deployment of the same host enables: same plugins, different active policies.
The SafetyContribution shape
interface SafetyContribution {
readonly id: SafetyPolicyId; // "<plugin>.<policy-name>"
readonly version: string; // semver
readonly framework?: RegulatoryFramework;
readonly enforcement: SafetyEnforcement;
readonly scope?: SafetyPolicyScope; // optional callClass / family / runtimeRole filter
readonly content: string | ((ctx: PromptContext) => string);
readonly guards?: readonly SafetyGuard[];
}| Field | Purpose |
|---|---|
id | Branded SafetyPolicyId. core.* is reserved (throws ReservedSafetyNamespaceError); unnamespaced ids throw UnnamespacedSafetyIdError |
version | Semver string. A bump invalidates the cache |
framework | Open string. KNOWN_REGULATORY_FRAMEWORKS lists conventional values for autocomplete. The pre-1.1 { custom: string } form is deprecated; pass a plain string |
enforcement | advisory / guardrail / refusal: the operator's stated intent. Seam effects apply only under the "enforce" opt-in (see below) |
scope | When the policy participates: callClass, family, runtimeRole |
content | The refusal, gate or disclaimer prose; a string or (PromptContext) => string |
guards | The SafetyGuard slot: tool-call-precondition (refuses a specific tool invocation) or regex-refusal (replaces the terminal answer with a policy-attributed refusal). A guard fires only under safetyEnforcementMode: "enforce"; see Structural guards for its limit |
Registering policies (plugin author)
import type { HarnessPlugin } from "@pleach/core";
const compliancePlugin: HarnessPlugin = {
name: "compliance",
contributeSafetyPolicies: () => [
{
id: safetyPolicyId("compliance.pii-redaction"),
version: "1.2.0",
framework: "GDPR",
enforcement: "refusal",
scope: { callClass: "synthesize" },
content: "Never include raw PII in the final response. Redact email addresses, phone numbers, and identifiers.",
},
{
id: safetyPolicyId("compliance.export-control"),
version: "1.0.0",
framework: "EAR",
enforcement: "guardrail",
content: "Refuse export-controlled technical data unless the requester has presented a current authorization.",
},
],
};Registered is not enabled. Plugin authors ship policies; operators opt in.
Enabling policies (operator)
The operator enables policies by passing an id list at runtime construction in
SessionRuntimeConfig.enabledSafetyPolicies.
import { safetyPolicyId } from "@pleach/core/safety";
import { SessionRuntime } from "@pleach/core";
const runtime = new SessionRuntime({
plugins: [compliancePlugin],
enabledSafetyPolicies: [
safetyPolicyId("compliance.pii-redaction"),
safetyPolicyId("compliance.export-control"),
],
});Construction throws UnknownSafetyPolicyError if the list names an id no plugin
registered, so typos surface at boot. A policy left off the list stays
registered (visible to runtime.safety.listAvailablePolicies()) but has no
effect on prompt composition.
To toggle policies after construction, call
runtime.safety.getRegistry().enable(id) or .disable(id). enable() throws
UnknownSafetyPolicyError for unknown ids; disable() is idempotent.
Two more errors guard registration:
DuplicateSafetyPolicyError: two policies share an id. Add a versioned suffix if both must coexist.ReservedSafetyNamespaceError: a plugin tried to registercore.*.
The fingerprint contract
The active policy list is part of the per-call fingerprint cache key. Turning a policy on or off, or bumping its version, invalidates the cache. Runs with different active sets never share a bucket, so replay can't reuse a result captured under different safety constraints.
The audit ledger records the active list, so a regulator can ask what was active when a call fired.
Listing active policies
const active: readonly SafetyPolicySummary[] = runtime.safety.listActivePolicies();
for (const policy of active) {
console.log(policy.id, policy.version, policy.framework, policy.enforcement);
}SafetyPolicySummary carries id, version, framework, enforcement and
enabled. It omits the content prose, so audit tools get metadata only.
runtime.safety.listAvailablePolicies() returns every registered policy with an
enabled flag. runtime.safety.listActivePolicies() returns the enabled subset.
runtime.safety.getRegistry() returns the SafetyPolicyRegistry; call
collectActiveContributions() on it for the raw prose.
Composition order
Safety contributions compose last, after all prompt contributions, so the composed system prompt ends with the safety section. The header literal is fixed:
import { SAFETY_SECTION_HEADER } from "@pleach/core/safety";
SAFETY_SECTION_HEADER; // "## Safety Policies"Changing the literal invalidates the fingerprint cache. Operators and replay tools search for it to extract the safety portion of a composed prompt.
The prompt resolver already calls composeSafetyContent, so you rarely call it.
An audit or replay tool can re-derive the safety section out-of-band:
import { composeSafetyContent } from "@pleach/core/safety";
const { text, activePolicies } = composeSafetyContent(
runtime.safety.getRegistry().collectActiveContributions(),
{ callClass: "synthesize", family: "anthropic", runtimeRole: "primary" },
);- Scope filtering. A policy with a
scopeparticipates only when every named field matches the call. - Empty-output drop. A policy whose
contentfunction returns""is dropped from the output and fromactivePolicies. Enablement doesn't depend on per-context content.
The same active set and context produce the same output, which keeps the safety section fingerprint-safe.
SafetyEnforcement semantics
| Level | Seam effect (v1.2) | Intent |
|---|---|---|
advisory | log_only — prose in the prompt, policy id on the audit row | Non-binding norms; LLM is free to comply or not |
guardrail | block_tool_call — additionally interposes a tool-call-precondition guard that can refuse a specific tool invocation | Operational guardrails (rate-limit refusals, tool-call preconditions) |
refusal | block_synthesis — additionally interposes a regex-refusal guard at synthesis time | Hard policy — "no PII in the synthesis" |
The mapping alone blocks nothing. Structural enforcement needs both a concrete
guards entry from the policy author and safetyEnforcementMode: "enforce" from
the operator. In the default "prose-only" mode,
resolveSafetyEnforcementEffect collapses every level to log_only, and LLM
compliance stays best-effort. The level still appears on every audit row,
because replay and compliance tools need the stated intent.
Which policy refused, on the row
A block_tool_call refusal or a block_synthesis veto writes a
guard.decision row whose payload carries policy: { id, version }. The
row is on the hash chain, so pleach audit verify fails if either value is
edited later. The reason string is unchanged:
safety_policy_block_tool_call:<policyId> or
safety_policy_block_synthesis:<policyId>.
An id or version that isn't a durable label is written as "<invalid>".
An invalid id marks both fields. The policy key stays, so the row still
shows that a policy fired. Rows from other guard producers carry no
policy key.
Branch on the effect, not the name
SAFETY_ENFORCEMENT_EFFECTS maps each level to the seam effect it commits to
under "enforce". Index it, or call resolveSafetyEnforcementEffect (which also
folds in the operator mode), rather than switching on the severity name. The
map's values changed between v1.1 and v1.2 while its shape stayed. Audit
consumers keep filtering on the severity name for operator-intent queries.
import { SAFETY_ENFORCEMENT_EFFECTS } from "@pleach/core/safety";
const effect = SAFETY_ENFORCEMENT_EFFECTS[policy.enforcement];
if (effect === "block_synthesis") {
/* ... */
}KNOWN_REGULATORY_FRAMEWORKS
framework accepts any string. The exported constant lists nine conventional
ids (HIPAA, GDPR, SOC2, ITAR, EAR, CWC, BWC, FDA-21CFR11,
clinical-research-disclaimer); use them in a picker or via the
KnownRegulatoryFramework literal union. Pass any other id you need, such as
"MDR-EU" or "my-company.policy-v3".
import {
KNOWN_REGULATORY_FRAMEWORKS,
type RegulatoryFramework,
} from "@pleach/core/safety";
for (const id of KNOWN_REGULATORY_FRAMEWORKS) {
// id: KnownRegulatoryFramework
}
const myFramework: RegulatoryFramework = "my-company.policy-v3";Structural guards
SafetyContribution.guards is the slot for non-prose enforcement. A guard fires
only when both conditions hold: the policy's level maps to that guard's effect,
and the operator set safetyEnforcementMode: "enforce". In the default
"prose-only" mode every guard is inert.
interface SafetyGuard {
readonly kind: "regex-refusal" | "tool-call-precondition";
readonly definition: unknown; // shape varies by kind, below
}
// kind: "regex-refusal" (refusal-level policies)
{ pattern: string; flags?: string; reason?: string; refusalText?: string }
// kind: "tool-call-precondition" (guardrail-level policies and above)
{
toolNames?: readonly string[];
blockWhen?: (call: { toolName: string; parameters: Record<string, unknown> }) => boolean;
reason?: string;
}| Kind | Tested against | On a match |
|---|---|---|
regex-refusal | The final answer, at finalization | Replaces the whole answer with a refusal that names the policy. refusalText is used verbatim when set |
tool-call-precondition | Each tool call, by name or with blockWhen | The call doesn't run. The model gets a result saying the policy blocked it. A blockWhen that throws blocks the call |
Both write a guard.decision row naming the policy and its version
(Which policy refused). A definition that
can't state a decision is skipped with a console warning: no pattern, a
pattern that doesn't compile, or a precondition with neither toolNames nor
blockWhen.
A pattern catches only the phrasings it lists, so a reworded answer passes. The
guard tests the final answer, so check how your client shows streamed text
before that answer lands. Writing the guard.decision row is best-effort: the
refusal is still delivered if that write fails. For advice that must not reach a
user without review, gate the tool that delivers it
(Interrupts).
Scrubber contract (redaction at write time)
Safety policies on this page gate prompt-input behavior. Fabrication detection inspects model output for unsupported claims. Scrubbers are a third surface: they redact payload fields before event log rows persist, so the ledger never holds the unredacted shape.
@pleach/compliance bundles four scrubbers (SSN-US, Luhn card-number heuristic,
US-DL, and a generic KeyedRegex). Host plugins add more through
contributeScrubbers. Registration is auditable, and bypassing a registered
scrubber requires an explicit opt-out that lands on the audit row. See
Scrubbers.
Where to go next
Plugin contract
`contributeSafetyPolicies` is the registration hook.
Prompts
The distinct contract for capability-adding contributions.
AuditableCall row
The active safety set is recorded in the per-call audit row.
Scrubbers
Event-log redaction that runs before rows persist.
Attestation
The cryptographic surface that signs the audit row safety policies appear on.
Security
Auth, RLS, secret handling, tenant isolation, and the surfaces that need attention before going to production.
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.