> ## Documentation Index
> Fetch the complete documentation index at: https://docs.withboundary.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Engine Primitives

> clean, verify, classify, repair, instructions

Low-level building blocks exposed from `@withboundary/contract`. All are pure, synchronous, and side-effect free.

```typescript theme={null}
import {
  clean,
  verify,
  classify,
  repair,
  instructions,
  createConsoleLogger,
} from "@withboundary/contract";
```

Usage guide: [Engine primitives](/guides/engine-primitives).

## `clean`

```typescript theme={null}
function clean(raw: string | null | undefined): unknown;
```

Normalize raw LLM output into a parsed JSON value.

| Input                            | Output                                                       |
| -------------------------------- | ------------------------------------------------------------ |
| `null` / `""`                    | `null`                                                       |
| `"```json\n{\"a\":1}\n```"`      | `{ a: 1 }`                                                   |
| `"Here's the answer: {\"a\":1}"` | `{ a: 1 }`                                                   |
| `"no json here"`                 | `null`                                                       |
| Malformed JSON                   | `null` (or the original raw — callers should still validate) |

## `verify`

```typescript theme={null}
function verify<T>(
  data: unknown,
  schema: ContractSchema<T>,
  rules?: Rule<T>[],
): ContractResult<T>;
```

Validate `data` against `schema` and, if provided, every rule. Returns the same `ContractResult<T>` shape `contract.accept` returns. No LLM involved.

* `result.ok === true` → data passed schema and all rules. `result.data` is typed `T`.
* `result.ok === false` → `result.error.attempts[0]` has the failure `category` (`"VALIDATION_ERROR"` or `"RULE_ERROR"`) and the list of `issues`.

## `classify`

```typescript theme={null}
function classify(raw: string, cleaned: unknown): FailureCategory;
```

Categorize a failed response. Returns one of:

```typescript theme={null}
"EMPTY_RESPONSE" | "REFUSAL" | "NO_JSON" | "TRUNCATED" |
"PARSE_ERROR" | "VALIDATION_ERROR" | "RULE_ERROR" | "RUN_ERROR"
```

Based on the combination of raw string and parsed result:

| `raw`                        | `cleaned`        | Category           |
| ---------------------------- | ---------------- | ------------------ |
| `""` / `null`                | —                | `EMPTY_RESPONSE`   |
| contains refusal language    | `null`           | `REFUSAL`          |
| has text but no JSON         | `null`           | `NO_JSON`          |
| starts valid, ends mid-token | `null` / partial | `TRUNCATED`        |
| malformed JSON               | `null`           | `PARSE_ERROR`      |
| valid JSON, wrong types      | `unknown`        | `VALIDATION_ERROR` |
| right types, rule failed     | `T`              | `RULE_ERROR`       |

## `repair`

```typescript theme={null}
function repair(
  detail: AttemptDetail,
  overrides?: Partial<Record<FailureCategory, RepairFn | false>>,
): Message[] | false;
```

Generate repair messages for a failed attempt. Returns:

* `Message[]` — messages to feed back to the model.
* `false` — the category is disabled (via `overrides[category] = false`), caller should not retry.

### `overrides` shape

```typescript theme={null}
type RepairFn = (detail: AttemptDetail) => Message[];

type RepairOverrides = Partial<Record<FailureCategory, RepairFn | false>>;
```

* `false` — skip retry for this category.
* `(detail) => Message[]` — build custom repair messages for this category.

## `instructions`

```typescript theme={null}
function instructions(schema: ContractSchema<unknown>): string;
```

Generate prompt text from a Zod schema. Includes field types, enums, ranges, and `.describe()` annotations.

```typescript theme={null}
const schema = z.object({
  tier: z.enum(["hot", "warm", "cold"]).describe("lead temperature"),
  score: z.number().min(0).max(100),
});

console.log(instructions(schema));
// Return JSON matching:
// {
//   "tier": one of "hot" | "warm" | "cold" — lead temperature,
//   "score": number (0-100)
// }
```

Called automatically inside `contract.accept` and available on `attempt.instructions`.

The primitive does not take an options object. If you want to append stable text to the generated instructions used by `contract.accept`, configure the contract instead:

```typescript theme={null}
defineContract({
  name: "lead-scoring",
  schema,
  rules,
  instructions: {
    suffix: "\nUse concise strings and include the source signal in each reason.",
  },
});
```

## `createConsoleLogger`

```typescript theme={null}
function createConsoleLogger<T = unknown>(
  options?: ConsoleLoggerOptions,
): ContractLogger<T>;
```

Built-in human-readable logger. Implements the full `ContractLogger` surface and prints formatted traces to `console.log`.

### `ConsoleLoggerOptions`

| Option              | Type      | Default        | Description                                         |
| ------------------- | --------- | -------------- | --------------------------------------------------- |
| `prefix`            | `string`  | `"[contract]"` | Prepended to every line                             |
| `showInstructions`  | `boolean` | `false`        | Print the auto-generated prompt on `onAttemptStart` |
| `showRepairs`       | `boolean` | `false`        | Print repair messages on `onRepairGenerated`        |
| `showRawOutput`     | `boolean` | `false`        | Print `raw` on `onRawOutput`                        |
| `showCleanedOutput` | `boolean` | `false`        | Print `cleaned` on `onCleanedOutput`                |
| `showSuccessData`   | `boolean` | `false`        | Print the accepted `data` on `onRunSuccess`         |
| `maxStringLength`   | `number`  | `1000`         | Truncate printed strings over this length           |

```typescript theme={null}
defineContract({
  schema,
  rules,
  logger: createConsoleLogger({
    showInstructions: true,
    showRepairs: true,
    maxStringLength: 500,
  }),
});
```

The `debug: true` option on `defineContract` / `enforce` is equivalent to `logger: createConsoleLogger()`.

## See also

<CardGroup cols={2}>
  <Card title="Engine primitives guide" icon="gears" href="/guides/engine-primitives">
    Recipes and custom pipelines
  </Card>

  <Card title="Testing contracts" icon="vial" href="/guides/testing-contracts">
    Use verify() for unit tests
  </Card>
</CardGroup>
