# Fabrication detection (/docs/fabrication-detection)



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

`applyFabricationGuard` rewrites a synthesized turn before it is persisted. A
streaming client has already received the original deltas, so it gets the
rewrite as a `content.correction` and replaces the text it showed. A client that
opts into the [answer hold](#holding-the-answer-until-the-guards-have-run) never
shows text a guard corrects before the turn completes.

The guard removes and reports four kinds of content: tool calls the model
invented, paragraphs that reference tools that failed or never ran, quantitative
content fabricated when most tools failed, and confessions where the model
retracts prior work mid-message.

It returns `FabricationGuardResult`: a `triggered` boolean, `preservedContent`,
paragraph counts, the `unavailableToolNames` it acted on, and optional
`phantomTools`, `phantomReplacements`, `ungroundedEntities`, `dataInflation` and
`phantomWipeEscalation` slots, filled only when those signals fire.

**Subpath:** `@pleach/core/strategies/fabricationDetectors`

## Holding the answer until the guards have run [#holding-the-answer-until-the-guards-have-run]

The guard runs after synthesis, so its `content.correction` can land after the
terminal `message.complete`. By default a streaming UI shows the deltas as they
arrive, then swaps in the corrected text. To never show text a guard later
corrects, turn on the answer hold. It is off by default.

```tsx
useChat({ api: "/api/chat", holdAnswerUntilTurnComplete: true });
useHarness({ holdAnswerUntilTurnComplete: true });
useSessionMessageStream({ runtime, sessionId, onEvent, holdAnswerUntilTurnComplete: true });
```

* The reply stays hidden until the turn ends, then appears once, already corrected.
* The hold releases on `turn.completed`, an `error` event, or the stream ending,
  throwing or being stopped. `message.complete` and an aborted `graph.exit_meta`
  don't release it, because a correction can still follow.
* The provisional draft is held too. Reasoning, tool calls, tool progress and
  interrupts stay live.
* The bubble is empty during the hold. Render a pending indicator from `status`
  (`useChat`) or `isStreaming` (`useHarness`).
* `{ releaseAfterMs }` also releases once that many milliseconds have passed
  since the turn's first event. It is checked only when an event arrives; there
  is no timer. A guard that runs after that release can still rewrite text the
  user has seen.
* After a Stop, a dropped stream or a `releaseAfterMs` release, the text shown
  may be the uncorrected partial. No guard has finished on it.

Per hook:

* `useChat` holds the assistant bubble. A new `submit` while an answer is held
  settles it in place first, as a Stop does.
* `useHarness` holds every non-user change to `messages`, plus `streamingContent`.
  User messages, `thinkingContent`, `toolOutput` and `batchProgress` stay live.
  Each send has its own hold; a send queued behind a held turn doesn't release
  that turn early.
* `useSessionMessageStream` empties `ctx.visibleText` and the answer text in
  `ctx.parts` while `ctx.answerHeld` is `true`. `onAnswerReleased(ctx)` fires once
  per turn, whether the turn completed, errored, was stopped or threw.

`collectStream` needs no option: it returns after the stream ends, so its `text`
is already corrected. A client that folds events itself wraps the reducer with
`createHeldStreamMessageReducer(true)` from `@pleach/core` and paints its `view(held)`.

## Public exports [#public-exports]

| Export                                    | Kind      | Purpose                                                                                                |
| ----------------------------------------- | --------- | ------------------------------------------------------------------------------------------------------ |
| `applyFabricationGuard`                   | function  | The multi-signal pipeline. Wipes paragraphs, returns the typed result.                                 |
| `contentReferencesMissingTools`           | predicate | Does text mention any tool in `unavailableToolNames` (bare, readable, or alias)?                       |
| `detectBulkFailureFabrication`            | detector  | Quantitative content in a response when most tools failed.                                             |
| `detectSelfFabricationConfession`         | detector  | The model confesses fabricating a prior tool call (matched against `PriorToolUseEntry`).               |
| `detectMethodResultFabricationConfession` | detector  | The model retracts fabricated method-result tables from this turn.                                     |
| `detectDegenerateProseQuality`            | detector  | Garbled text.                                                                                          |
| `detectDataInflation`                     | detector  | The response presents more rows than the tool returned.                                                |
| `isGuardBlockedFailure`                   | predicate | Classifies a failed-tool error as guard-blocked (`BLOCKED:`, `DUPLICATE:`, ...) or a real API failure. |
| `partitionFailedTools`                    | function  | Splits a failed-tool list into `{ apiFailedToolNames, guardBlockedToolNames }`.                        |

## Grounding detectors — offloaded-data & unresolved-job cohort [#grounding-detectors--offloaded-data--unresolved-job-cohort]

The detectors above catch phantom tools and confessions. A second cohort, exported
from the same `@pleach/core/strategies/fabricationDetectors` subpath, checks that
*tabulated* claims are grounded in what the tools returned (the "offloaded
corpus") and that claims aren't attributed to jobs that never resolved. Each
detector ships `DEFAULT_*` tuning constants.

| Export                                                      | Kind       | Purpose                                                                                                           |
| ----------------------------------------------------------- | ---------- | ----------------------------------------------------------------------------------------------------------------- |
| `detectTabulatedRowsAbsentFromRetrieved`                    | detector   | Table rows whose numbers don't appear in the retrieved tool corpus.                                               |
| `detectTabulatedEntitiesAbsentFromRetrieved`                | detector   | Tabulated named entities absent from the retrieved corpus.                                                        |
| `detectTabulatedNumbersAbsentFromToolCorpus`                | detector   | Tabulated numbers absent from the shown tool corpus.                                                              |
| `detectTabulatedRowsShareIdentitySet`                       | detector   | Table rows that all share one identity set, a copy-paste signal.                                                  |
| `detectUnresolvedJobNumericClaim`                           | detector   | Numeric claims attributed to a job that never resolved.                                                           |
| `detectUnresolvedJobCompletionClaim`                        | detector   | Completion claims for a job that never resolved.                                                                  |
| `detectFailedComputeMetricFabrication`                      | detector   | Metric values reported from a compute step that failed.                                                           |
| `detectRecommendationEntityAbsentFromCorpus`                | detector   | Recommended entities absent from the retrieved corpus.                                                            |
| `detectGeneralKnowledgeQuantFabrication`                    | detector   | Quantitative claims presented as general knowledge without structural citations.                                  |
| `subagentClaimsDataWithoutTools`                            | detector   | A subagent presents concrete data with no tool calls behind it.                                                   |
| `createRefClassFabricationDetector`                         | factory    | Builds a reference-class citation detector; ships `DEFAULT_REF_CLASS_PATTERN` and `PERMISSIVE_REF_CLASS_PATTERN`. |
| `offloadedResultCarriesGroundedRows`, `isOffloadedEnvelope` | predicates | Whether an offloaded tool-result envelope carries rows the detectors can check against.                           |
| `buildDataInflationMetadata`, `countStructuralCitations`    | helpers    | Build a data-inflation finding payload; count structural citations in prose.                                      |

## Public types [#public-types]

| Type                                       | Purpose                                                                                                                         |
| ------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------- |
| `FabricationGuardResult`                   | Pipeline result envelope (see fields below).                                                                                    |
| `FabricationGuardResultWithPluginFindings` | Extends `FabricationGuardResult` with `pluginFindings: readonly FabricationFinding[]` — what `applyFabricationGuard` returns.   |
| `FabricationGuardStrategyBundle`           | Strategy shape on `SessionRuntimeConfig.fabricationGuardStrategy`, re-exported via `@pleach/core/types/strategies`.             |
| `FabricationDetector`                      | Plugin-contributed detector: `{ id, version?, detect(ctx) }`.                                                                   |
| `FabricationDetectorContext`               | What a detector receives: `completedTools`, `assistantContent`, `userText`, `knownToolNames`, `guestDeniedTools?`, `callClass`. |
| `FabricationFinding`                       | What a detector returns: `{ detectorId, severity, reason, preservedContent?, evidence? }`.                                      |
| `CompletedToolRecord`                      | Tool envelope a detector indexes against: `{ id, name, status, error?, arguments?, result? }`.                                  |
| `PriorToolUseEntry`                        | Per-call envelope the self-confession detector cross-references.                                                                |

`applyFabricationGuard` has signature
`(params: ApplyFabricationGuardParams, config: ApplyFabricationGuardConfig) => FabricationGuardResultWithPluginFindings`.
`partitionFailedTools(failedToolNames, errors)` returns
`{ apiFailedToolNames, guardBlockedToolNames }`; `isGuardBlockedFailure(errorMessage)`
is the underlying predicate.

## Result shape [#result-shape]

`FabricationGuardResult` carries the variable surface back to the caller.

| Field                       | Type                                      | Set when                                                                                 |
| --------------------------- | ----------------------------------------- | ---------------------------------------------------------------------------------------- |
| `triggered`                 | boolean                                   | Any signal fired.                                                                        |
| `preservedContent`          | string                                    | Always — the cleaned turn body.                                                          |
| `preservedParagraphs`       | number                                    | Paragraphs kept after wipe.                                                              |
| `wipedParagraphs`           | number                                    | Paragraphs removed.                                                                      |
| `unavailableToolNames`      | `string[]`                                | Failed ∪ empty-result ∪ detected phantoms.                                               |
| `apiFailedToolNames`        | `string[]`                                | Real upstream failures (the partition split).                                            |
| `guardBlockedToolNames`     | `string[]`                                | Tools the guard suppressed (`BLOCKED:`, `DUPLICATE:`, …).                                |
| `phantomTools`              | `string[]`                                | Tool names cited in prose that were never executed.                                      |
| `phantomToolsNotInRegistry` | `string[]`                                | Subset of `phantomTools` not in `allKnownToolNames`.                                     |
| `phantomReplacements`       | `{ phantom; replacement }[]`              | Phantom → canonical-tool mappings from `phantomWipeStrategy`.                            |
| `phantomWipeEscalation`     | `{ overlappingTools; sessionWipeCount }`  | The same phantom set was wiped repeatedly in the session.                                |
| `ungroundedEntities`        | `string[]`                                | Named entities in prose absent from tool results. The detector slot defines what counts. |
| `dataInflation`             | `{ toolName; claimedRows; actualRows }[]` | Model presented more rows than the tool returned.                                        |

## `FabricationGuardStrategyBundle` [#fabricationguardstrategybundle]

Hosts populate `FabricationGuardStrategyBundle` (from
`@pleach/core/types/strategies`) once at runtime construction, in
`SessionRuntimeConfig.fabricationGuardStrategy`. `DEFAULT_FABRICATION_GUARD_STRATEGY_BUNDLE`
is an empty bundle (`quantitativePatterns: []`) for tests and hosts without
domain patterns; every optional slot is skipped.

| Slot                                   | Required | What it does                                                                                              |
| -------------------------------------- | -------- | --------------------------------------------------------------------------------------------------------- |
| `quantitativePatterns`                 | yes      | Domain-specific patterns the bulk-failure detector counts.                                                |
| `phantomDetect`                        | no       | Returns phantom tool names cited in `content` that aren't in `executedToolNames`.                         |
| `phantomWipeStrategy`                  | no       | Maps a phantom name to a real-tool replacement.                                                           |
| `phantomWipeTracker`                   | no       | Per-session tracker that populates `phantomWipeEscalation`.                                               |
| `ungroundedEntityDetect`               | no       | Returns entity names cited in prose but absent from `toolResultsRaw`. The host defines what an entity is. |
| `postExecFabricationDetect`            | no       | Returns `true` when prose fabricates results for failed-or-empty tools.                                   |
| `degenerateProseConfig`                | no       | Augments the garbled-prose detector.                                                                      |
| `detectUnqueriedCitations`             | no       | Flags citations to sources never queried.                                                                 |
| `detectIdentifierMismatch`             | no       | Flags identifier mismatches between prose and tool results.                                               |
| `detectMarkdownSmilesMismatch`         | no       | Flags chemical-notation strings that don't match the source table.                                        |
| `detectCellLineAttributionFabrication` | no       | Flags cell-line claims with no grounded source.                                                           |
| `detectProcessClaimWithoutCompute`     | no       | Flags process claims with no successful compute.                                                          |

The first seven slots feed `applyFabricationGuard`. The last five are read
directly by graph nodes.

### `contributeFabricationGuard` plugin hook [#contributefabricationguard-plugin-hook]

A plugin returns a `FabricationGuardImpl` from `contributeFabricationGuard()`. It
is one object carrying `applyFabricationGuard`, `isGuardBlockedFailure`, the
per-signal detectors (`detectBulkFailureFabrication`, `detectUnqueriedCitations`,
`detectSelfFabricationConfession`, `detectMethodResultFabricationConfession`,
`detectIdentifierMismatch`, `detectCellLineAttributionFabrication`,
`detectMarkdownSmilesMismatch`, `detectProcessClaimWithoutCompute`) and the
`contentReferencesMissingTools` predicate.

Findings from `FabricationDetector[]`, registered through the sibling
`contributeFabricationDetectors` hook, merge into the returned
`FabricationGuardResultWithPluginFindings`. It adds a
`pluginFindings: readonly FabricationFinding[]` field to `FabricationGuardResult`;
legacy consumers can ignore it.

See [`contributeFabricationGuard`](/docs/plugin-contract#contributefabricationguard)
for the full method list and registration shape.

### The legacy bag entry [#the-legacy-bag-entry]

`OrchestratorHotpathModules.fabricationGuard` is the legacy untyped entry for the
same surface. The typed bundle and `contributeFabricationGuard` supersede it;
register through the hook. The bag entry remains only as a fallback. See
[`/docs/host-adapter`](/docs/host-adapter) for the bag-retirement story.

## Calling the pipeline [#calling-the-pipeline]

```typescript
import {
  applyFabricationGuard,
} from "@pleach/core/strategies/fabricationDetector";

const result = applyFabricationGuard(
  {
    fullContent: synthesizedTurn,
    failedToolNames: ["search_corpus"],
    emptyResultToolNames: [],
    isResynthesis: false,
    executedToolNames: ["search_corpus", "fetch_url"],
    allKnownToolNames: registry.list(),
    totalToolCount: 2,
    toolResultsRaw: rawToolResultsBlob,
  },
  {
    quantitativePatterns: DOMAIN_QUANTITATIVE_PATTERNS,
  },
);

if (result.triggered) {
  await respondWith(result.preservedContent);
} else {
  await respondWith(synthesizedTurn);
}
```

Only the params envelope and the config are required.

## Running a single detector [#running-a-single-detector]

Detectors are exported individually, so plugin authors and tests can run them
outside the pipeline.

```typescript
import {
  detectBulkFailureFabrication,
  DEFAULT_BULK_FAILURE_PATTERN_THRESHOLD,
} from "@pleach/core/strategies/fabricationDetectors";

const bulk = detectBulkFailureFabrication({
  content: turnBody,
  failedToolCount: 4,
  totalToolCount: 5,
  quantitativePatterns: DOMAIN_QUANTITATIVE_PATTERNS,
});

if (bulk.detected) {
  console.warn(
    `bulk-failure fabrication: ${bulk.matchedPatterns} pattern hits`,
    bulk.matchedExamples,
  );
}
```

The bulk-failure gates ship as exported constants you can tune:
`DEFAULT_BULK_FAILURE_PATTERN_THRESHOLD`, `DEFAULT_BULK_FAILURE_MIN_LENGTH` and
`DEFAULT_BULK_FAILURE_RATIO_THRESHOLD`.

## Contributing a detector through a plugin [#contributing-a-detector-through-a-plugin]

The graph's `FabricationNode` runs every plugin's `contributeFabricationDetectors()`
detectors. A detector reads `completedTools` from the context and returns a
`FabricationFinding` or `null`.

```typescript
// lib/plugins/corpusGuard.ts
import type { HarnessPlugin } from "@pleach/core";
import type { FabricationDetector } from "@pleach/core/plugins";

const emptyResultDetector: FabricationDetector = {
  id: "empty-result-claim",
  detect(ctx) {
    const empty = ctx.completedTools.filter(
      (t) => t.name === "search_corpus" && Array.isArray(t.result) && t.result.length === 0,
    );
    if (empty.length === 0) return null;
    if (!/\bfound\b|\bresults? show\b/i.test(ctx.assistantContent)) return null;
    return {
      detectorId: "empty-result-claim",
      severity: "high",
      reason: "Prose claims results when search_corpus returned an empty array",
      evidence: { emptyToolCalls: empty.map((t) => t.id) },
    };
  },
};

export const corpusGuardPlugin: HarnessPlugin = {
  name: "corpus-guard",
  version: "0.1.0",
  contributeFabricationDetectors: () => [emptyResultDetector],
};
```

Register the plugin once at runtime construction; every turn then runs the detector.

## Host-supplied tool-argument fabrication detectors [#host-supplied-tool-argument-fabrication-detectors]

The detectors above run against synthesized prose. A second class runs against
tool-call **arguments** before dispatch, when the model invents an argument value
with no provenance in the turn's prior tool results. A host-supplied verdict, a
`safetyTier` on the tool definition, and one of two routing destinations combine
to handle it.

Example: a host flags HTTP URLs the model invented, as opposed to URLs a resolver
tool returned earlier in the same turn. The detector returns a verdict, and the
runtime acts on it according to the tool's `safetyTier`.

1. **Tool authors set `safetyTier`** to `"critical"`, `"standard"` or `"advisory"`.
   See [Tools](/docs/tools#safetytier).
2. **The host contributes a detector** that reads the tool name, the args and the
   prior tool results, and returns a verdict with a `reason` and the suspect argument.
3. **The verdict maps to an `ApprovalDecisionKind`.** Hosts can contribute new
   discriminators alongside the detector; see
   [Interrupts](/docs/interrupts#approvaldecisionkind-host-supplied-discriminators).
4. **Routing splits on `safetyTier`:**

   | `safetyTier` | Destination                                                                                                      | User can override?          |
   | ------------ | ---------------------------------------------------------------------------------------------------------------- | --------------------------- |
   | `"critical"` | A hard-halt stage stops dispatch with `_recoverable: false`. This is the operator's pre-committed safety policy. | No                          |
   | `"standard"` | The `InterruptApprovalCard` shows the suspect arg, the mismatch reason and recovery tools.                       | Yes: accept, edit or reject |
   | `"advisory"` | Probe only. The detector fires for observability; no halt, no card.                                              | N/A                         |

A critical tier never reaches the approval card, so the user is never offered a
button that overrides the operator's policy. The hard-halt returns an
unrecoverable envelope with a structured error code and emits a probe, so
dashboards can count hard-halts separately.

A tool author sets `safetyTier` once, the host wires a detector once, and the
runtime owns the routing. New tools inherit it if the detector recognizes their
argument shape.

CI enforces one invariant: &#x2A;*every tool tagged `safetyTier: "critical"` must be
reachable by the host's detector.** A critical tool with no detector coverage
would silently bypass the hard-halt, and CI fails when coverage is missing.

## Adding a custom detector [#adding-a-custom-detector]

Domain-specific detectors register through the `contributeFabricationDetectors`
plugin hook. It returns `readonly FabricationDetector[]`; each detector has an
`id`, an optional `version`, and a synchronous `detect(ctx)` that returns a
`FabricationFinding` or `null`.

```typescript
import type { HarnessPlugin } from "@pleach/core"
import type {
  FabricationDetector,
  FabricationDetectorContext,
  FabricationFinding,
} from "@pleach/core/plugins"

const orderIdDetector: FabricationDetector = {
  id: "order-id-format",
  version: "0.1.0",
  detect(ctx: FabricationDetectorContext): FabricationFinding | null {
    // Order IDs are 8 digits prefixed ORD-. Flag any order-shaped token
    // in the synthesized prose that doesn't match the canonical format.
    const malformed = ctx.assistantContent.match(/\bORD-\d{1,7}\b/g)
    if (!malformed) return null
    return {
      detectorId: "order-id-format",
      severity: "medium",
      reason: "Prose cites an order ID that isn't 8 digits prefixed ORD-",
      evidence: { suspects: malformed },
    }
  },
}

export const myPlugin: HarnessPlugin = {
  name: "domain-detectors",
  version: "0.1.0",
  contributeFabricationDetectors: () => [orderIdDetector],
}
```

Three rules hold for any custom detector:

* **`detect` must be synchronous.** It runs on the hot path, per chunk when streaming.
* **The detector has no side effects.** No telemetry writes, storage reads or
  network calls. Detectors classify; they don't enrich.
* **`severity` is required**: `"low"`, `"medium"` or `"high"`. It reports how
  serious the finding is and appears in the guard's
  `[FabricationGuard] plugin-detector-fired` breadcrumb. It doesn't by itself
  trigger the hard-halt stage or the approval card; that routing keys on the
  tool's `safetyTier`.

A related hook — `contributeFabricationDetectorRules` — lets a
plugin contribute per-detector configuration (regexes, allowlists,
thresholds) without re-implementing the detector itself. See
[Plugin contract](/docs/plugin-contract) for the full surface.

## Commit stamps after a body rewrite [#commit-stamps-after-a-body-rewrite]

The terminal `message.complete` event carries `commitStampSource` and `commitStampMatchesBody`. The second field is `true` when the ledger's last commit stamp describes the exact body the event ships.

Three rewrites change that body after the synthesizer stamps it: the narration strip, the process-fabrication honest frame, and the failed-tool alias banner. Each now re-stamps the body it ships, so `commitStampMatchesBody` stays `true` where it used to read `false`. The strip re-stamps only when its removal is rebased on the shipped body. The honest frame re-stamps only when it resolves as `same-draft` or `reframed`. A body that already diverged from its stamp is never re-stamped.

The alias banner re-stamp needs the banner text the fabrication node recorded. When there is none, as on the plan-coverage path, no re-stamp is made. `@pleach/core/SessionRuntime` exports `restampTerminalAfterFailedAliasBanner` and the stamp-source constants `TERMINAL_BODY_REWRITE_NARRATION_STRIP_STAMP_SOURCE`, `TERMINAL_BODY_REWRITE_PROCESS_FABRICATION_FRAME_STAMP_SOURCE` and `TERMINAL_DISCLOSURE_PREPEND_FAILED_TOOL_ALIAS_STAMP_SOURCE`.

Two more cases stamp a kept body as a fresh terminal commit. A streamed answer that outranks a smaller divergent synthesizer body is stamped when it ships. So is a streamed body that differs from the synthesizer's by at most 64 bytes, when a keep rule retains it and it clears the minimum length for a grounded record. A carryover turn with no synthesizer commit is not stamped.

A delivered body can be rebuilt from the event log: `content.delta` rows fold byte for byte into the body. When a turn streamed chunks but wrote no delta rows, the runtime back-fills them at the terminal.

## A disclosed answer stays [#a-disclosed-answer-stays]

When a turn ran no real tool and the failed-tool disclosure banner is already at the head of the answer, the runtime keeps that answer. It does not swap it for the generic "wasn't able to complete" notice. The banner is the non-destructive response to the finding, so replacing the body under it would discard an answer the reader was already warned about. The skip applies only when the banner is the turn's sole detection and the body has text after it. Any other detection still replaces the answer.

## Undispatched plan steps [#undispatched-plan-steps]

When a planned tool is never dispatched, the runtime passes it to the synthesizer
as `metadata.uncoveredPlanSteps` (a `readonly string[]` on the synthesize seam)
before the detectors run. The synthesizer adds a user-visible note that the step
wasn't run. The note is appended at the terminal synthesis arm, so it sits beside
the grounded content the turn did produce instead of replacing a correct partial
answer.

The runtime handles work that never ran. You add detectors for invented specifics
in work that did run.

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

<Cards>
  <Card title="Safety" href="/docs/safety" description="The wider safety surface — the fabrication guard is one strategy among many." />

  <Card title="The AuditableCall row" href="/docs/auditable-call-row" description="Synthesize rows carry the guard's findings — joinable by `turnId`." />

  <Card title="Plugin contract" href="/docs/plugin-contract" description="`contributeFabricationDetectors` registers domain detectors at plugin load." />

  <Card title="Subpath exports" href="/docs/subpath-exports" description="The full export map — `./strategies/fabricationDetectors`, `./strategies/fabricationDetector`, `./strategies/fabricationGuardTypes`." />
</Cards>
