# Extending Pleach (/docs/extending)



Pleach assumes you'll extend the runtime. This page maps each thing
you can add to three facts: the interface you implement, the call that
registers it, and what the addition has to satisfy.

<Callout type="info" title="Two extension surfaces — know which one you're on">
  **Host extension** — you add a plugin, a prompt block, a tool, or a
  runtime strategy from *your* repo against the published `@pleach/*`
  surface. You edit no substrate source. Pleach's CI already checked
  that surface, and you can add checks for your own rules (see
  [Add your own checks](#add-your-own-checks)).

  **Upstream contribution** — you add a node to the canonical builder,
  a member to `EventLogInput`, or a sibling `@pleach/*` SKU. You edit
  substrate source, so Pleach's CI runs against your change. The
  [contributing](/docs/contributing) flow covers this path.

  Most consumer work is host extension.
</Callout>

## The extension map [#the-extension-map]

| You're adding                              | Interface                                                                          | Register via                                                                                         | What it has to satisfy                                                                                                                                                                                 |
| ------------------------------------------ | ---------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| A **graph node**                           | `StateGraphNodeMetadata` + `NodeFn` ([nodes](/docs/nodes))                         | `graph.addNode(name, fn, meta)`, or a plugin's `extraGraphNodes()`                                   | A `stageId`, plus declared `subscribes` and `writes`. Edges stay on the lattice.                                                                                                                       |
| A **state channel**                        | `Channel<T>` ([channels](/docs/channels))                                          | a node's `subscribes` / `writes` metadata — there is **no** `contributeChannels` hook                | Reached through a node. Reducer commutativity is a [determinism contract](/docs/determinism).                                                                                                          |
| An **event type / writer**                 | `PluginEventDefinition` ([event log](/docs/event-log))                             | `contributeEventTypes()`                                                                             | A producer, and `scrubbableFields` for its free-text paths.                                                                                                                                            |
| A **scrubber** (the "clearer")             | `Scrubber` ([scrubbers](/docs/scrubbers))                                          | `contributeScrubbers()`                                                                              | It covers the fields the scrubbable-fields allowlist lists. Your own event types list theirs in `scrubbableFields`.                                                                                    |
| A **plugin hook** (sibling SKU / upstream) | a `contribute*` hook on `HarnessPlugin` ([plugin contract](/docs/plugin-contract)) | the hook itself, returning the contribution                                                          | A paired collector, a consumer, and a [namespace](/docs/plugins/namespaces).                                                                                                                           |
| A **system-prompt block**                  | `PromptContribution` ([prompts](/docs/prompts))                                    | `contributePrompts()` / `contributeRuntimeAwarePrompts()` — helpers `appendPrompt`, `prependPersona` | Static blocks fold into the [config-manifest](/docs/config-manifest) fingerprint, so keep them deterministic. A `core.*` slot is replaced only from `contributeRuntimeAwarePrompts()` (`replaceCore`). |
| A **custom audit field**                   | `PluginAuditPayload` ([typed records](/docs/typed-records))                        | `contributeAuditEmitter()` → `pluginPayloads` — **not** a new column                                 | The structural column set is locked.                                                                                                                                                                   |
| An **audit-ledger adapter**                | `ProviderDecisionLedger` ([audit ledger](/docs/audit-ledger))                      | `setProviderDecisionLedgerFactory(...)`                                                              | The row your adapter persists has to match the locked shape.                                                                                                                                           |
| A **storage adapter**                      | `StorageAdapter` ([storage](/docs/storage))                                        | runtime config / `appRegistries`                                                                     | No shape requirement beyond the interface. Application code doesn't change when you swap adapters.                                                                                                     |

The shape is the same across rows: each addition supplies the one
fact the ledger needs to stay joinable, such as a stage, a producer, or
a scrubber entry.

## Nodes: the consumer path vs the builder path [#nodes-the-consumer-path-vs-the-builder-path]

The [new-node checklist](/docs/nodes#new-node-checklist) on the nodes
page describes editing the canonical builder — `NODE_STAGE_MAP` from
`@pleach/core/graph/topology`. That's the **upstream** path. A host adding a
node from a plugin takes a different one:

```typescript
// A plugin contributes nodes; the builder calls each factory once at compile time.
const retrievalPlugin: HarnessPlugin = {
  name: "tenant-retrieval",
  extraGraphNodes: () => [{
    name: "tenantRetrieval",
    factory: (ctx) => async (state) => ({ retrieved: await ctx.search(state.query) }),
    metadata: { stageId: "tool-loop", acceptsSeam: null, subscribes: ["query"], writes: ["retrieved"] },
  }],
}
```

A plugin-registered node carries its `stageId` in its own `metadata`.
It never enters the static `NODE_STAGE_MAP`, which covers the default
graph only. The fact your node must satisfy is the same: a valid stage,
and declared channels.

## The locked row, and the slot that isn't [#the-locked-row-and-the-slot-that-isnt]

The single most common extension instinct the substrate refuses:
adding a column to the audit row. The structural column set —
tenant, turn, stage, provider, model, status,
plus the JSON payload bag — is a cross-SKU
contract. No plugin, config field, or adapter alters it.

The sanctioned path for "I need to record *my* thing on the row" is
`pluginPayloads` — a namespaced, versioned slot the locked contract
reserves for exactly this:

```typescript
const extractionQualityPlugin: HarnessPlugin = {
  name: "extraction-quality",
  contributeAuditEmitter: () => ({
    // Emitted alongside the locked columns; your plugin owns the wire shape.
    record: (call) => ({
      pluginId: "extraction-quality",
      subKind: "score",
      data: { confidence: scoreFor(call), schemaVersion: 1 },
    }),
  }),
}
```

Your payload rides one row per call, joinable by turn id like every
other field, without touching the structural columns every consumer
reads. The version lives in your `data`, not in the substrate's
`AuditRecordVersion`, because the contract didn't move. See [typed records](/docs/typed-records) for the five
first-party payload kinds this slot generalizes.

## Add your own checks [#add-your-own-checks]

Pleach's CI protects the surface you consume, not *your* rules. A
per-tenant key that must never reach logs, a domain tool that must have
a matching detector, a feature flag past its sunset: those are yours to
check. The pattern is at
[Release checks](/docs/audit-gates#add-your-own-checks): one rule per
script, a failure that names file and line, wired into your PR-blocking
CI.

## Agent-driven self-extension [#agent-driven-self-extension]

Errors that name the problem are a feedback loop an agent can drive.
An agent extending the runtime can run the loop unattended:

1. Write the addition: a node, a scrubber, a `pluginPayloads` emitter
   for the tenant's need.
2. Run it with `npx @pleach/core dev --plugin … --scenarios … --assert …`.
3. Read the failure. It names what's missing: a stage or a channel
   declaration.
4. Apply the fix and re-run.

The failure is the correction signal. An agent that can't see why its
node was rejected can't self-correct; one that reads the node's name
and the missing field can.

To push self-optimization further, feed the extension contract into
the agent's *own* system prompt. A host that wants its agent to tune
its plugin set, prompt blocks, or tool selection to a tenant's needs
can inject the rules at turn time:

```typescript
const selfTuningPlugin: HarnessPlugin = {
  name: "self-tuning",
  // Per-turn prompt the operating agent reads — the extension contract as context.
  contributeRuntimeAwarePrompts: (ctx) => [{
    id: "self-tuning.extension-guide",
    mode: "append",
    content: extensionContractFor(ctx.tenant), // rules, slots, and the locked columns
  }],
}
```

The agent then proposes additions that already respect the rules,
because the rules are in its context. Static guidance (the locked
column set, the `pluginPayloads` slot) belongs in
`contributePrompts` so it folds into the fingerprint; per-tenant
guidance belongs in `contributeRuntimeAwarePrompts` so it stays out
of the cache key. See [prompts](/docs/prompts) and the
[plugin contract](/docs/plugin-contract) for the composition rules.

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

<Cards>
  <Card title="Plugin contract" href="/docs/plugin-contract" description="The full HarnessPlugin hook surface every extension point above registers through." />

  <Card title="Release checks" href="/docs/audit-gates" description="What Pleach's CI checks, organized by subsystem." />

  <Card title="Nodes" href="/docs/nodes" description="The node shape, the new-node checklist, and the plugin-registered node path." />

  <Card title="Scrubbers" href="/docs/scrubbers" description="The clearer contract and the contributeScrubbers hook for regulated identifiers." />

  <Card title="Typed records" href="/docs/typed-records" description="The pluginPayloads slot and the first-party payload kinds it generalizes." />
</Cards>
