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

# Memory and constraints

This page documents two related ABL constructs:

* [`MEMORY:`](#memory) manages session and persistent state.
* [`CONSTRAINTS:`](#constraints) enforces business rules.

***

## MEMORY

Memory in ABL defines how an agent stores, retrieves, and persists information across conversation turns, sessions, and users. The `MEMORY:` block declares four categories: session variables, persistent variables, remember triggers, and recall instructions.

`MEMORY.session` and `MEMORY.persistent` properties stay indented deeper than the field entry.

* Blank lines can separate properties. They do not end the current field or merge adjacent entries.
* Text ABL also accepts `#` and `//` comment-only lines there. YAML accepts `#` comments.
* The next field entry, memory subsection, or top-level block keeps its own boundary.

### Overview

Every agent has access to a memory configuration that controls data lifecycle:

* **Session variables** exist for the duration of a single conversation session.
* **Persistent variables** survive across sessions, scoped to a user or project.
* **Remember triggers** automatically store values when conditions are met.
* **Recall instructions** load stored facts at specific lifecycle events.

```yaml expandable=true theme={null}
MEMORY:
  session:
    - customer_id
    - order_total
      TYPE: number
      DESCRIPTION: "Running total for the current order"
      INITIAL: 0
      RESET: per_session
  persistent:
    - user.preferred_language
    - user.loyalty_tier
      SCOPE: user
  remember:
    - WHEN: user_language IS SET
      STORE: user_language -> user.language
      TTL: "90d"
  recall:
    - ON: session:start
      ACTION: inject_context
      PATHS: [user.preferred_language, user.loyalty_tier]
```

### Session variables

Session variables hold data that is relevant only during a single conversation. They are created when the session starts and discarded when the session ends (unless `RESET: never` is specified).

#### Syntax

```yaml theme={null}
MEMORY:
  session:
    - variable_name
    - variable_name
      TYPE: string
      DESCRIPTION: "Human-readable description"
      INITIAL: "default_value"
      RESET: per_session
```

You can declare a session variable with a bare name (minimal form) or with additional metadata.

#### Properties

| Property | Type | Required | Default | Description |
| - | - | - | - | - |
| `name` | `string` | Yes | -- | Variable name, used as the key in session context. |
| `TYPE` | `string`, `number`, `boolean`, `date`, `array`, `object` | No | -- | Value type for runtime validation and field resolution. |
| `DESCRIPTION` | `string` | No | -- | Human-readable description of the variable's purpose. |
| `INITIAL` | any | No | `null` | Initial value assigned when the session starts. (`initial_value` is accepted as a legacy alias.) |
| `RESET` | `per_session`, `per_activation`, `per_step`, `never` | No | `per_session` | When to reset the variable. See [Reset behavior](#reset-behavior). |
| `READONLY` | `boolean` | No | `false` | When `true`, the model's `__set_context__` cannot write the variable; `SET`, `on_result`, and hooks still can. See [Write authority](#write-authority). |
| `MODEL_WRITERS` | `string[]` | No | -- | Restricts which agents' models may write a shared variable. See [Model writers](#model-writers). |
| `MODEL_VISIBLE` | `boolean` | No | `true` | When `false`, excludes the variable from automatic model context. See [Model-visible session and persistent values](#model-visible-session-and-persistent-values). |

#### Reset behavior

| Value | Behavior |
| - | - |
| `per_session` | Variable is initialized at session start and cleared when the session ends. This is the default. |
| `per_activation` | Variable is reset each time the agent is (re)activated within a session (for example. on re-entry after a handoff). |
| `per_step` | Variable is reset to its initial value at the start of each flow step. Useful for step-scoped accumulators. |
| `never` | Variable persists for the lifetime of the runtime process. Use sparingly; prefer persistent memory instead. |

#### Example: typed session variables

```yaml theme={null}
MEMORY:
  session:
    - cart_items
      TYPE: array
      DESCRIPTION: "Items currently in the shopping cart"
      INITIAL: []
      RESET: per_session
    - attempt_count
      TYPE: number
      INITIAL: 0
      RESET: per_step
```

#### Write authority

> [!WARNING]
>
> **Removed:**`SOURCE`, `FORMAT`, and `DERIVED` on a session variable. A `SOURCE:`/`FORMAT:`/`DERIVED:` line (or the YAML `source:`/`format:`/`derived:` key) is now a compile error — [`E493`](https://koreai.mintlify.site/agent-platform/abl/reference/errors-and-warnings#e493), [`E492`](https://koreai.mintlify.site/agent-platform/abl/reference/errors-and-warnings#e492), and [`E498`](https://koreai.mintlify.site/agent-platform/abl/reference/errors-and-warnings#e498) respectively. `DERIVED` was removed because its every-write recompute cost grew unbounded; `SOURCE`/`FORMAT` were removed alongside it. **Migration:** declare the field `READONLY: true` and compute/write it with an authored `SET`, `on_result` mapping, or hook `SET` (see below). Where you relied on `FORMAT` for kind inference, pass the kind as `MATCH_SCORE`/`MATCHES`/`MATCH_RESULT`'s explicit third argument instead — for example `MATCH_SCORE(said, stored, "email")`.

A session variable can declare `READONLY: true` so the model cannot write it, leaving an authored hook `SET` (or `on_result`, or a FLOW `SET`) to compute its value:

```yaml theme={null}
AGENT: Identity_Check
GOAL: "Confirm the caller before sharing account details"

MEMORY:
  SESSION:
    - NAME: supplied_email
      TYPE: string
    - NAME: profile_email
      TYPE: string
    - NAME: email_verified
      TYPE: boolean
      READONLY: true

HOOKS:
  before_turn:
    SET: email_verified = MATCHES(supplied_email, profile_email, "email")
```

| Property | Values | Meaning |
| - | - | - |
| `READONLY` | `true` | Opt-in. The model's `__set_context__` cannot write the variable; `SET`, `on_result` and hooks still can. Only an explicit `true` opts in. |

In YAML the same key is lowercase: `readonly: true`.

##### READONLY scope

`READONLY` applies to the whole project. When any agent declares a variable `READONLY`, the model of every agent is refused, including an agent that declares the same name without `READONLY`. The refusal applies even before the declaring agent has run.

* A parent object and its child paths overlap. `account.verified` as `READONLY` also refuses a model write of `account`.
* `execution_tree.x` is the same variable as `x` under either spelling.
* A scoped alias of a `READONLY` path is the same variable and is refused too. Examples are a writable `granted_memory` grant, or an unambiguous `execution_tree` leaf mapped to it. In handoff, delegate, and fan-out context, the runtime resolves a leaf through the receiving agent's mapping, not the sender's.
* Remote (A2A) agents are not included.
* The compiler warns with [`SESSION_READONLY_DECLARATION_MISMATCH`](https://koreai.mintlify.site/agent-platform/abl/reference/errors-and-warnings#session_readonly_declaration_mismatch) when agents compiled in the project disagree on `READONLY`. Imported module agents compile as stubs and are not checked.
* The runtime trace decision `set_context_readonly_refused` names the declaring agents in `readonlyDeclarations`.
* The refused model writes are `__set_context__`, `__complete__` outcome fields, and model-supplied handoff, delegate, or fan-out context.
* `MODEL_WRITERS` cannot override `READONLY`. To let one agent's model write a variable that another agent must not write, leave the variable without `READONLY` and list the writer in `MODEL_WRITERS`.

> [!NOTE]
>
> `MATCH_SCORE(said, stored, kind?)` returns 0-100 (or `-1` when there's nothing to judge — a missing value, a PII vault token, or an input over 1,024 characters; `-1` is below every threshold, so a rule written as `MATCH_SCORE(...) >= 70` fails closed). `MATCHES(said, stored, kind?)` is the pass/fail form on the platform's own match bands, and `MATCH_RESULT(said, stored, kind?)` returns `"match"`, `"retry"`, `"mismatch"`, or `"missing"`. These are a **said-versus-stored identity comparison**, not a regex test — the infix `a MATCHES "pattern"` operator is the regex form. `kind` is optional (default `text`); pass `"auto"` to detect the kind from the stored value's shape, or `"exact"` to turn off every voice allowance and require equality after normalization. See [Built-in function reference](https://koreai.mintlify.site/agent-platform/abl/reference/expressions-and-functions.md#built-in-function-reference) for the full signatures, `kind` values, and match bands.

#### Model writers

In a multi-agent project, several agents can share one session field — routing state, a verification result — and by default any agent's model can write it. `MODEL_WRITERS` names exactly which agents' models may:

```yaml theme={null}
AGENT: Coordinator
GOAL: "Collect and route the caller's request"

MEMORY:
  SESSION:
    - NAME: route_choice
      TYPE: string
      MODEL_WRITERS: [Coordinator]
    - NAME: verified_result
      MODEL_WRITERS: []
    - ordinary_state
```

| Declaration | Model-write behavior |
| - | - |
| Omitted everywhere in the project | Ordinary model edits remain allowed (legacy behavior), including correcting or invalidating a previously-written value. Explicit `READONLY` and memory/assignment permissions still apply independently; a tool binding or return mapping does not, by itself, restrict a model write. |
| Omitted on one field, in a project that declares `MODEL_WRITERS` somewhere else | Inferred restrictions apply to that field too — a captured-consent value, a private/gate-owned field, or a protected tool outcome stays protected even without its own explicit declaration; restrictions can follow aliases connected to an explicit declaration elsewhere. |
| `MODEL_WRITERS: [Coordinator, Worker]` | Only the listed agents' models may write the field. |
| `MODEL_WRITERS: []` | Every model is denied; authored writes (`SET`, `on_result`, hooks) still work. |

> [!NOTE]
>
> The two "omitted" rows are easy to conflate, but they're opposite in a project that has adopted `MODEL_WRITERS` anywhere: once the project opts in, unrelated fields pick up inferred protection; a project that has never declared `MODEL_WRITERS` at all stays on the older, ordinary-edit behavior throughout.

The YAML key is `model_writers`. Names are case-sensitive agent names; every explicit declaration of the same shared field across the project must agree, and a conflicting pair fails closed (denied for everyone) rather than picking one. A full-project compile rejects a name that isn't a real agent in the project ([`SESSION_MODEL_WRITER_UNKNOWN`](https://koreai.mintlify.site/agent-platform/abl/reference/errors-and-warnings#session_model_writer_unknown)); compiling a single agent in isolation defers that specific check. An invalid list (not an array of plain agent-name strings) is rejected at parse/compile time ([`MEMORY_MODEL_WRITERS_INVALID`](https://koreai.mintlify.site/agent-platform/abl/reference/errors-and-warnings#memory_model_writers_invalid), [`SESSION_MODEL_WRITERS_INVALID`](https://koreai.mintlify.site/agent-platform/abl/reference/errors-and-warnings#session_model_writers_invalid)) — the field is **not** left silently unprotected on invalid input.

> [!WARNING]
>
> A listed writer can clear an *inferred* return/gate ownership refusal, but it can never override an explicit `READONLY: true`, a private-identity refusal, already-captured consent, or a protected tool-call outcome.

> [!NOTE]
>
> **Authored proof, in brief.** Once a project declares any `MODEL_WRITERS`, a value arriving at a protected field through a `HANDOFF`/`DELEGATE` return `MAP`/`SET` must be traceable to something the platform itself produced — an executed tool result, or a value a hook/`on_result`/`ON_START`/`ESCALATE` action set directly. A value that is merely *model-written* (even copied through an ordinary `SET`), or sourced from raw caller input, secure-input collection, or a confirmation/inference step, does **not** count as proof — even if it's byte-identical to a previously proven value. A return assignment that can't establish this is skipped (the field keeps its prior value) and the runtime traces `RETURN_MODEL_WRITER_UNTRUSTED_SOURCE`. Prefer a static return `MAP`/`SET` path (a literal tool-result field) over a dynamic/computed expression when the source needs to flow into a writer-protected field — an expression the runtime can't statically resolve is treated conservatively and may be refused even when the underlying value is genuinely trustworthy.

> [!WARNING]
>
> An agent that declares any `MODEL_WRITERS` (including an empty `[]`) compiles to IR version `1.2`; an agent with none keeps its existing `1.0`/`1.1` version, and a project's compilation envelope carries the highest version among its agents. A Runtime that doesn't support `1.2` rejects that artifact outright — upgrade the compiler and the Runtime together before authoring or publishing `MODEL_WRITERS`.

#### Model-visible session and persistent values

A session or persistent entry can opt out of **automatic model context** with `MODEL_VISIBLE: false` (YAML: `model_visible: false`). Omitted or `true` preserves the existing automatic projection. The value stays fully available to deterministic expressions, conditions, tools, mappings, persistence, and recall — this is a placement control over what the model sees automatically, not a write-authority or access-scope change:

```yaml theme={null}
AGENT: Catalog_Assistant
GOAL: "Help the customer select an item"

MEMORY:
  SESSION:
    - NAME: catalog_mapping
      TYPE: object
      MODEL_VISIBLE: false
    - NAME: selected_category
      TYPE: string
  PERSISTENT:
    - PATH: user.internal_reference
      SCOPE: user
      ACCESS: read
      MODEL_VISIBLE: false
```

An opted-out entry is left out of automatically serialized model context — including supported voice memory updates and LLM extraction grounding context. An explicit authored reference such as `{{catalog_mapping}}` can still place the value at the intended prompt location, subject to the usual access and sensitive-value rules — `MODEL_VISIBLE: false` is not a guarantee the value can never reach a model, only that it isn't included automatically. Deterministic rule evaluation and ML extraction always see the real value regardless of this setting. An excluded ancestor path excludes its descendants, even one marked `true`. The excluded path must be a literal, dot-separated path — numeric array positions are supported, but a wildcard, a bracket selector, an empty segment, or a `__proto__`/`prototype`/`constructor` segment is rejected ([`MEMORY_MODEL_VISIBLE_PATH_UNSUPPORTED`](https://koreai.mintlify.site/agent-platform/abl/reference/errors-and-warnings#memory_model_visible_path_unsupported)) rather than silently left visible.

> [!NOTE]
>
> Each consuming agent's own memory declaration governs its automatic context. `MODEL_VISIBLE` requires matching authoring, parser/compiler, and Runtime versions deployed together — an older Runtime does not enforce it.

### Persistent variables

Persistent variables survive across sessions. They are stored in a fact store and scoped to either a specific user or to the entire project.

#### Syntax

```yaml expandable=true theme={null}
MEMORY:
  persistent:
    - user.preferred_chains
    - user.wire_history_30d
      SCOPE: user
      TYPE: array
      DESCRIPTION: "Recent wire transfer history"
      ACCESS: readwrite
      DEFAULT_VALUE: []
    - user.ssn
      SCOPE: user
      SENSITIVE: true
      SENSITIVE_DISPLAY: mask
      MASK_CONFIG:
        showFirst: 0
        showLast: 4
        char: "*"
    - project.exchange_rates
      SCOPE: project
      ACCESS: read
```

Persistent variable paths use dot notation. The first segment typically indicates the scope (`user.*` or `project.*`), but you can override this with the `SCOPE` property.

#### Properties

| Property | Type | Required | Default | Description |
| - | - | - | - | - |
| `path` | `string` | Yes | -- | Dot-notation path (for example. `user.preferred_chains`). |
| `SCOPE` | `user`, `project`, `execution_tree` | No | `user` | Ownership scope. See [Scoping rules](#scoping-rules). |
| `ACCESS` | `read`, `write`, `readwrite` | No | `readwrite` | Access direction. Constrains whether the agent can read, write, or both. |
| `TYPE` | `string`, `number`, `boolean`, `date`, `array`, `object` | No | -- | Value type for runtime validation. |
| `UNIT` | `string` | No | -- | Unit of the stored value (for example. `USD`, `km`). Informational metadata only. |
| `DEFAULT_VALUE` | any | No | `null` | Default value when no fact exists in the store. |
| `DESCRIPTION` | `string` | No | -- | Human-readable description. |
| `SENSITIVE` | `boolean` | No | `false` | Marks the value as PII for privacy-aware handling. |
| `SENSITIVE_DISPLAY` | `redact`, `mask`, `replace` | No | -- | How the value is displayed outside its context (when `SENSITIVE: true`). |
| `MASK_CONFIG` | `{showFirst, showLast, char}` | No | -- | Masking configuration when `SENSITIVE_DISPLAY` is `mask`. |

#### Scoping rules

* **User scope** (`SCOPE: user`): Values are unique per authenticated user. Two users in the same project see different values for the same path.
* **Project scope** (`SCOPE: project`): Values are shared across all users within the project. Useful for reference data, feature flags, or global configuration.
* **Execution-tree scope** (`SCOPE: execution_tree`): Values are shared across one handoff tree / long-running execution — visible to the agents participating in that orchestration but not persisted per-user or per-project.

> [!NOTE]
>
> As shorthand, a `READS:` sub-block declares persistent paths with `ACCESS: read`, and a `WRITES:` sub-block declares them with `ACCESS: write` — an alternative to listing each path under `persistent:` with an explicit `ACCESS`.

### Remember triggers

Remember triggers define rules for automatically storing values into persistent memory when a condition is met during conversation.

#### Syntax

```yaml theme={null}
MEMORY:
  remember:
    - WHEN: user_name IS SET
      STORE: user_name -> user.name
      TTL: "90d"
    - WHEN: preferred_language IS SET
      STORE: preferred_language -> user.language
```

Array targets can accumulate values instead of being overwritten, using the block form of `STORE`:

```yaml theme={null}
MEMORY:
  remember:
    - WHEN: search_completed
      STORE:
        value: last_query
        target: user.recent_searches
        operation: append   # overwrite (default) | set | append
        unique: true        # optional — skip duplicates
        maxSize: 10         # optional — FIFO cap
```

The modifiers are only read from the block form; the inline `value -> target`
arrow form always uses `overwrite`. `append`, `unique`, and `maxSize` apply to
`array`-typed targets in `user`, `project`, and `execution_tree` scopes.

#### Properties

| Property | Type | Required | Default | Description |
| - | - | - | - | - |
| `WHEN` | `string` | Yes | -- | Condition expression that triggers the store operation. Evaluated after each turn. |
| `STORE` | `object` | Yes | -- | Value expression and target path. Inline syntax: `value_expr -> target_path`; block form to add modifiers. |
| `operation` | `overwrite`, `append` | No | `overwrite` | Array-write mode. `append` adds to the existing array; `overwrite` replaces the whole value. Block form only. |
| `unique` | `boolean` | No | `false` | When `append`, drop duplicate items (first occurrence kept; deep-equality for objects). Block form only. |
| `maxSize` | `number` | No | -- | When `append`, cap array length, evicting oldest items first (FIFO). Block form only. |
| `TTL` | `string` | No | -- | Time-to-live for the stored fact. After expiration, the value is deleted. Examples: `"30d"`, `"24h"`. |

> [!NOTE]
>
> User- and project-scoped `REMEMBER` writes automatically replace any private config/env value, or a previously saved private copy of one, with `[REDACTED]` before the fact is persisted. This includes values inside a larger string or object, and matching object keys. Array-append writes compare values for uniqueness before redaction and FIFO-limit logic runs. The guard also runs on the final array-append result and again before each persistence attempt, so durable facts stay consistently protected. This does not affect the session value or the value delivered to a configured tool. Only the durable copy written by `REMEMBER` is redacted. An author relying on `REMEMBER` to persist a value derived from a secret should expect `[REDACTED]` in the stored fact, not the real value.

#### TTL format

TTL values use a duration string:

| Suffix | Meaning |
| - | - |
| `s` | Seconds |
| `m` | Minutes |
| `h` | Hours |
| `d` | Days |

Example: `"90d"` means the stored fact expires 90 days after it was written.

### Recall instructions

Recall instructions define when and how to load persistent facts back into the session context. They execute at specific lifecycle events.

#### Syntax

```yaml theme={null}
MEMORY:
  recall:
    - ON: session:start
      ACTION: inject_context
      PATHS: [user.name, user.language, user.preferred_agent]
    - ON: tool:search_flights:after
      ACTION: load_memory
      DOMAIN: "travel_preferences"
    - ON: session:start
      ACTION: prompt_llm
      INSTRUCTION: "Greet the user by name if known"
```

#### Properties

| Property | Type | Required | Default | Description |
| - | - | - | - | - |
| `ON` | `string` | Yes | -- | Lifecycle event that triggers the recall. See [Events](#recall-events). |
| `ACTION` | `string` | No | -- | The concrete action to execute. See [Actions](#recall-actions). |
| `INSTRUCTION` | `string` | Yes | -- | Human-readable instruction for the recall behavior. |
| `PATHS` | `array` | No | -- | Persistent paths to inject (for `inject_context` action). |
| `DOMAIN` | `string` | No | -- | Memory domain filter (for `load_memory` action). |

#### Recall events

`ON:` accepts these canonical lifecycle event patterns:

| Event pattern | When it fires |
| - | - |
| `session:start` | When a new session initializes, before any user input. |
| `session:end` | When a session ends. |
| `agent:<name>:before` | Before a specific agent runs (use `agent:*:before` for any). |
| `agent:<name>:after` | After a specific agent runs (use `agent:*:after` for any). |
| `tool:<name>:after` | After a specific tool runs (use `tool:*:after` for any). |
| `entity:<field>:extracted` | When a named entity/field is extracted from user input. |
| `step:enter:<name>` | On entering a specific flow step. |
| `step:exit:<name>` | On exiting a specific flow step. |

> [!WARNING]
>
> Legacy event names such as `search:before`, `ON_START`, or `ON_SEARCH` are no longer supported and are rejected during compilation — use the canonical patterns above. The `tool:<name>:before` isn't a valid recall event (only `tool:<name>:after`).

#### Recall actions

| Action | Behavior |
| - | - |
| `inject_context` | Loads specified persistent paths directly into the session context as variables. |
| `load_memory` | Loads all facts in the specified domain into context. |
| `prompt_llm` | Passes the instruction text to the LLM as additional context. This is the default action. |

### Accessing memory in expressions

Session variables are accessed by name in expressions and template strings:

```yaml theme={null}
RESPOND: "Hello, {{customer_name}}! Your balance is {{available_balance}}."
```

Persistent variables are accessed through their full dot-notation path:

```yaml theme={null}
SET: greeting = COALESCE(user.name, "valued customer")
```

Variables set via `SET` assignments in flow steps, `ON_START`, or hooks are written to session memory and available for the remainder of the session.

***

## CONSTRAINTS

Constraints are deterministic business rules that the runtime evaluates against the current session state. Authors can still group constraints under named phases for readability, but phase names are currently labels only: the compiler flattens constraints into a single runtime list unless a constraint explicitly gates itself with `WHEN` or a structural checkpoint construct.

### Overview

Constraints enforce guardrails on agent behavior that are separate from LLM instructions. they're deterministic checks evaluated by the runtime, not suggestions to the model. A constraint that fails blocks the current operation and triggers an `ON_FAIL` action.

```yaml theme={null}
CONSTRAINTS:
  always:
    - REQUIRE customer_verified == true
      ON_FAIL: "Please verify your identity first."

  pre_booking:
    - REQUIRE amount <= available_balance
      ON_FAIL: "Insufficient funds. Your available balance is {{available_balance}}."

    - REQUIRE sanctions_clear == true
      ON_FAIL: HANDOFF Compliance_Officer
```

### Phases

Named phases are retained as authoring labels for readability, review, and organization. They do not currently create separate runtime execution phases by themselves.

#### Syntax

```yaml theme={null}
CONSTRAINTS:
  phase_name:
    - REQUIRE condition_expression
      ON_FAIL: action_or_message
```

Use labels like `always`, `pre_booking`, or `eligibility_check` when they help readers understand intent, but use `WHEN` to gate applicability and `BEFORE` only for explicit structural checkpoint targets.

### Requirement rules

Each requirement within a phase uses one of three keywords: `REQUIRE`, `LIMIT`, or `RESTRICT`.

#### REQUIRE

The most common form. Asserts that a condition must be true. If the condition evaluates to false, the `ON_FAIL` action is triggered.

```yaml theme={null}
- REQUIRE account_status == "active"
  ON_FAIL: "Wire transfers require an active account."
```

#### LIMIT

Expresses a numeric boundary. Semantically equivalent to `REQUIRE` with a comparison, but communicates intent more clearly.

```yaml theme={null}
- LIMIT daily_wire_used + amount <= daily_wire_limit
  ON_FAIL: "This would exceed your daily wire limit of {{daily_wire_limit}}."
```

#### RESTRICT

Expresses a prohibition. The condition describes what is forbidden; when it evaluates to true, the constraint fails.

```yaml theme={null}
- RESTRICT beneficiary_country IN ["CU", "IR", "KP", "SY"]
  ON_FAIL: "Transfers to that destination are prohibited under sanctions regulations."
```

#### WHEN

Use `WHEN:` to make a constraint apply only in a specific context without overloading the phase label.

```yaml theme={null}
- REQUIRE ssn IS NOT SET
  WHEN: channel == "voice"
  ON_FAIL: "SSN cannot be collected on voice."
```

#### BEFORE

Use `BEFORE` for structural checkpoints that the runtime knows how to activate.

```yaml theme={null}
- REQUIRE measure_field IS SET BEFORE calling search_aggregate
  ON_FAIL: "Select a measure before running the aggregate search."

- REQUIRE aggregation_validated == true BEFORE returning results
  ON_FAIL: "Validate the aggregation before responding."
```

Supported structural targets today:

* `BEFORE calling <tool_name>`
* `BEFORE returning results`

Non-structural `BEFORE` targets are retained for compatibility, but they are warning-only and have no runtime effect. Prefer `IMPLIES` or `WHEN` for that form.

##### A `BEFORE` rule that cannot be evaluated

At its own checkpoint, CEL alone decides a `BEFORE` rule. The rule blocks when CEL cannot evaluate it. Examples are a field of an unset or empty object, an operator on an unset value or a value of the wrong type, a non-string regex or text-check operand, a rejected pattern, and input over 100,000 characters. In these cases the rule is not satisfied, `ON_FAIL` runs, and the trace carries `evaluationError: { code }`.

Convert or guard explicitly, for example `double(amount) > 0` or `has(consent.status) && ...`.

A `WHEN` gate that cannot be decided means the rule does not apply, unless the gate reads `tool_args`, `response`, or `input`. Rules without `BEFORE` are unchanged.

> [!NOTE]
>
> A `BEFORE calling <tool_name>` rule's `condition` (`REQUIRE`/`LIMIT`/`RESTRICT`) or `WHEN` can read the about-to-be-sent arguments via `tool_args`, but only when the agent sets `EXECUTION: guardrail_builtins: true`. Without it, `tool_args` is unbound: the rule cannot read the arguments, so it never holds, and the tool call is refused. The compiler warns [`GUARDRAIL_BUILTIN_NOT_BOUND`](https://koreai.mintlify.site/agent-platform/abl/reference/errors-and-warnings#guardrail_builtin_not_bound) for this case.
>
> ```yaml theme={null}
> EXECUTION:
>   guardrail_builtins: true
>
> CONSTRAINTS:
>   always:
>     - REQUIRE tool_args.amount <= daily_wire_limit BEFORE calling wire_transfer
>       ON_FAIL: "That exceeds your daily wire limit."
> ```

#### IMPLIES

`IMPLIES` is an inline condition operator (not a top-level keyword) for expressing conditional requirements. `A IMPLIES B` is lowered to `NOT (A) OR (B)` — that is, "if A holds, then B must also hold." Use it inside the condition of a `REQUIRE`/`LIMIT`/`RESTRICT` rule:

```yaml theme={null}
- REQUIRE transfer_type == "international" IMPLIES swift_code IS SET
  ON_FAIL: "International transfers require a SWIFT/BIC code."
```

#### ON\_FAIL actions

`ON_FAIL` accepts a single-line action — a message string, `HANDOFF <Agent>`, or `ESCALATE` — or a structured block. The block form can respond, reset state, and route in one place:

```yaml theme={null}
- REQUIRE amount <= daily_wire_limit
  ON_FAIL:
    RESPOND: "That exceeds your daily limit. Let's re-enter the amount."
    CLEAR: [amount, raw_amount]
    GOTO: collect_amount
```

| Key | Type | Description |
| - | - | - |
| `RESPOND` | `string` | Message sent to the user on failure. |
| `CLEAR` | `string[]` | Session variables to reset on failure, so stale values are recollected. |
| `COLLECT` | `string[]` | Fields to re-collect before retrying. |
| `GOTO` | `string` | Step to route to. A single identifier naming a declared FLOW step; anything else is spoken literally. |
| `RETRY` | `boolean` | Whether to retry the failed operation. |
| `MAX_REPEATS` | `number` | Positive integer. This constraint's own `ON_FAIL` answers this many failures for each agent, condition, and conversation. The next failure uses `ON_EXHAUSTED` (default `ESCALATE`). A passing check between failures does not reset the count. Omit for no cap. |
| `ON_EXHAUSTED` | string or action | Inline action run once `MAX_REPEATS` is used up, for example `ESCALATE "identity_not_confirmed"`. |

> [!NOTE]
>
> The `CLEAR` key lets an `ON_FAIL` block reset dependent state directly — you no longer need a separate `CLEAR`-only step solely to clear variables before a retry. `CLEAR` takes a list (`[field_a, field_b]`) or comma-separated names. It deletes the variables before the runtime handles the failure, and the same list applies on exhaustion. In YAML, write `on_fail` as a lowercase object with lowercase directives and no `action` key.

> [!WARNING]
>
> `GOTO` (and, on `MAX_REPEATS` exhaustion, `ON_EXHAUSTED`'s own `GOTO`) only moves the flow from two checkpoints: a FLOW step's entry/post-extraction checks, and its main `CALL` checkpoint (`BEFORE calling <tool_name>`). `ON_EXHAUSTED: GOTO` specifically only moves the flow from the `CALL` checkpoint — at step-entry and post-extraction, an exhausted constraint still answers with the platform message without transitioning anywhere.
>
> At every other structural checkpoint — `BEFORE returning results`, and a `CALL` inside `ON_INPUT`, `ON_RESULT`, a success/failure branch, a sub-intent, or a step action — `GOTO`, `RETRY`, and `COLLECT` all answer with the platform message and do not move the flow. Write those checkpoints' `ON_FAIL` as a plain `RESPOND`/message, `HANDOFF`, or `ESCALATE` instead of relying on `GOTO` to route you elsewhere.

> [!NOTE]
>
> An `ON_FAIL` `RESPOND` message may use `{{_abl_constraint_fail_count}}` — this failure's 1-based ordinal for the constraint within the current conversation. Pair it with `MAX_REPEATS`/`ON_EXHAUSTED` to vary the message as attempts run out, then hand off once the cap is reached:
>
> ```yaml theme={null}
> - REQUIRE MATCH_SCORE(supplied_email, profile_email) >= 70
>   ON_FAIL:
>     RESPOND: "That doesn't match what's on file (attempt {{_abl_constraint_fail_count}})."
>     MAX_REPEATS: 2
>     ON_EXHAUSTED: ESCALATE "identity_not_confirmed"
> ```

### Constraint properties

| Property | Type | Required | Default | Description |
| - | - | - | - | - |
| `condition` | `string` | Yes | -- | Expression to evaluate. See [Expressions & functions](https://koreai.mintlify.site/agent-platform/abl/reference/expressions-and-functions.md). |
| `WHEN` | `string` | No | -- | Optional applicability gate. The compiler lowers it to implication semantics so the constraint only applies when the gate is true. |
| `ON_FAIL` | `string` or action | Yes | `respond` | Action when the condition fails. See [ON\_FAIL actions](#on_fail-actions). |
| `severity` | `error` or `warning` | No | `error` | `error` blocks execution; `warning` emits a warning but continues. In text ABL, use the `WARN` keyword instead of a `severity:` line. |

### ON\_FAIL actions

The `ON_FAIL` value determines what happens when a constraint fails.

#### String message (respond)

The most common form. Sends a message to the user and halts the current operation.

```yaml theme={null}
ON_FAIL: "Insufficient funds. Available balance: {{available_balance}}."
```

#### HANDOFF

Transfers control to another agent. Active flow and reasoning runtime checkpoints execute the handoff immediately when the constraint fails.

```yaml theme={null}
ON_FAIL: HANDOFF Compliance_Officer
```

#### ESCALATE

Triggers human escalation.

```yaml theme={null}
ON_FAIL: ESCALATE
```

#### Block

Silently blocks the operation without a user-facing message.

```yaml theme={null}
ON_FAIL: BLOCK
```

#### Structured ON\_FAIL block

For more control, use a structured block that combines multiple actions.

```yaml theme={null}
- REQUIRE payment_method IS SET
  ON_FAIL:
    RESPOND: "I need your payment method before proceeding."
    COLLECT: [payment_method]
    THEN: retry
```

##### Structured ON\_FAIL properties

| Property | Type | Required | Default | Description |
| - | - | - | - | - |
| `RESPOND` | `string` | No | -- | Message to send to the user. |
| `COLLECT` | `string[]` | No | -- | Fields to collect from the user before re-evaluating. |
| `GOTO` | `string` | No | -- | Flow step to jump to. |
| `RETRY` | `boolean` | No | `false` | Retry the current step after handling the constraint. |
| `THEN` | `continue` or `retry` | No | -- | What to do after collection: `continue` proceeds, `retry` re-checks. |
| `MAX_REPEATS` | `number` | No | -- | Failures of this constraint (per conversation) answered before `ON_EXHAUSTED` takes over. |
| `ON_EXHAUSTED` | string or action | No | -- | Inline action run once `MAX_REPEATS` is used up. |

#### Collect and retry example

```yaml theme={null}
CONSTRAINTS:
  pre_booking:
    - REQUIRE departure_date IS SET AND return_date IS SET
      ON_FAIL:
        RESPOND: "I need your travel dates to check availability."
        COLLECT: [departure_date, return_date]
        THEN: retry

    - REQUIRE departure_date > NOW()
      ON_FAIL:
        RESPOND: "The departure date must be in the future. What date works for you?"
        COLLECT: [departure_date]
        THEN: retry
```

#### GOTO example

```yaml theme={null}
- REQUIRE user.verified == true
  ON_FAIL:
    RESPOND: "You need to verify your identity first."
    GOTO: identity_verification_step
```

### Severity levels

| Severity | Behavior |
| - | - |
| `error` | Blocks the current operation. The `ON_FAIL` action executes. This is the default. |
| `warning` | Emits a warning event and continues execution. The `ON_FAIL` message is logged, not sent. |

```yaml theme={null}
- WARN fraud_score < 60
  ON_FAIL: "Transaction flagged for review."
```

### Constraint evaluation order

1. Constraint phase names such as `always` or `pre_booking` are labels only; the compiler flattens all constraints into one runtime list.
2. `WHEN` gates a constraint to a specific context, and structural `BEFORE` gates it to supported checkpoints such as tool calls or final responses.
3. Inline flow-step `CHECK` expressions are separate from `CONSTRAINTS` and evaluate directly against `step.check`.
4. Declaration order is preserved in the flattened list.
5. Evaluation stops at the first `error`-severity failure. Warnings do not halt evaluation.

### Template interpolation in messages

`ON_FAIL` message strings support `{{variable}}` interpolation using the current session context:

```yaml theme={null}
- REQUIRE (daily_wire_used + amount) <= daily_wire_limit
  ON_FAIL: "This wire would exceed your daily limit of {{daily_wire_limit}}. You've sent {{daily_wire_used}} today."
```

***

**Related articles:**

* [Guardrails](https://koreai.mintlify.site/agent-platform/abl/reference/guardrails.md) -- input/output safety checks (distinct from business rule constraints)
* [Expressions and functions](https://koreai.mintlify.site/agent-platform/abl/reference/expressions-and-functions.md) -- condition expression syntax
* [Multi-agent and supervisor](https://koreai.mintlify.site/agent-platform/abl/reference/multi-agent-and-supervisor.md) -- HANDOFF and ESCALATE actions referenced in ON\_FAIL
* [Lifecycle and hooks](https://koreai.mintlify.site/agent-platform/abl/reference/lifecycle-and-hooks.md) -- `ON_START` handler where initial memory setup occurs
* [Data types](https://koreai.mintlify.site/agent-platform/abl/reference/data-types-and-utilities.md) -- type definitions used in `TYPE` declarations


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.