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

# Scripted flows

> Author the conversation step by step on a graph: IVR menus, keypad entry, branches and exact lines your agent is held to

## Quickstart

A scripted flow is a [customer flow](https://docs.roark.ai/documentation/simulation-testing/customer-flows.md) whose conversation you write step by step, as a graph the simulated customer follows with the exact lines you authored.

Define a scripted flow [in code](https://docs.roark.ai/documentation/config-as-code/flows.md#scripted-type-scripted) (recommended), or build it on the canvas. This one is a short IVR: an opening line said word for word, a keypad step inside a required **IVR Phone Auth** stage, a menu that branches on the key pressed, both branches meeting again, and a last step that ends the call.

```typescript roark.config.ts theme={"theme":{"light":"everforest-light","dark":"everforest-dark"}}
import { defineConfig, defineScriptedFlow } from '@roarkanalytics/sdk/lib/config';

const appointmentLine = defineScriptedFlow({
  name: 'appointment-line-ivr',
  agents: ['frontdesk'],
  adherence: 'STRICT',
  graph: [
    {
      type: 'CUSTOMER_VERBATIM_TURN',
      content: 'Hi, I am calling about my appointment.',
      stage: { name: 'IVR Phone Auth', required: true, analyze: false },
      steps: [
        {
          type: 'AGENT_TURN',
          content: 'Please enter your account number followed by the pound key.',
          stage: 'IVR Phone Auth',
          steps: [
            {
              type: 'CUSTOMER_DTMF',
              dtmfDigits: '48213#',
              stage: 'IVR Phone Auth',
              steps: [
                {
                  type: 'AGENT_TURN',
                  content: 'Press 1 to hear your appointment time, or 2 to speak to the front desk.',
                  steps: [
                    {
                      type: 'CUSTOMER_DTMF',
                      dtmfDigits: '1',
                      steps: [
                        {
                          type: 'AGENT_TURN',
                          content: 'Your appointment is on Tuesday at 10 AM.',
                          steps: [
                            {
                              ref: 'goodbye',
                              type: 'CUSTOMER_TURN',
                              content: 'Thank the agent and say goodbye.',
                              endsCall: true,
                            },
                          ],
                        },
                      ],
                    },
                    {
                      type: 'CUSTOMER_DTMF',
                      dtmfDigits: '2',
                      steps: [
                        {
                          type: 'AGENT_TURN',
                          content: 'Connecting you to the front desk.',
                          mergeInto: ['goodbye'],
                        },
                      ],
                    },
                  ],
                },
              ],
            },
          ],
        },
      ],
    },
  ],
});

export default defineConfig({ resources: [appointmentLine] });
```

```yaml roark/flows/appointment-line-ivr.yaml theme={"theme":{"light":"everforest-light","dark":"everforest-dark"}}
# yaml-language-server: $schema=https://roark.ai/roark-config.schema.json
kind: flow
type: scripted
name: appointment-line-ivr
agents: [frontdesk]
adherence: STRICT
graph:
  - type: CUSTOMER_VERBATIM_TURN
    content: Hi, I am calling about my appointment.
    stage: { name: IVR Phone Auth, required: true, analyze: false }
    steps:
      - type: AGENT_TURN
        content: Please enter your account number followed by the pound key.
        stage: IVR Phone Auth
        steps:
          - type: CUSTOMER_DTMF
            dtmfDigits: '48213#'
            stage: IVR Phone Auth
            steps:
              - type: AGENT_TURN
                content: Press 1 to hear your appointment time, or 2 to speak to the front desk.
                steps:
                  - type: CUSTOMER_DTMF
                    dtmfDigits: '1'
                    steps:
                      - type: AGENT_TURN
                        content: Your appointment is on Tuesday at 10 AM.
                        steps:
                          - ref: goodbye
                            type: CUSTOMER_TURN
                            content: Thank the agent and say goodbye.
                            endsCall: true
                  - type: CUSTOMER_DTMF
                    dtmfDigits: '2'
                    steps:
                      - type: AGENT_TURN
                        content: Connecting you to the front desk.
                        mergeInto: [goodbye]
```

```bash theme={"theme":{"light":"everforest-light","dark":"everforest-dark"}}
roark config apply roark.config.ts
```

`steps` are a step's next steps, so two of them make a branch, and `mergeInto` joins a step to the one named by that `ref`. Each apply replaces the whole graph. `endsCall` takes effect with `adherence: STRICT`.

### Create it with the SDK

In the REST API and the SDKs a scripted flow has `type: 'SCRIPTED'` and its steps go in `graph`, with `mergeIntoNodeIds` naming the `ref` to join. `replaceGraph` swaps the whole graph of an existing flow.

> [tab] Node
>
> ```typescript theme={"theme":{"light":"everforest-light","dark":"everforest-dark"}}
> const flow = await client.customerFlow.create({
>   type: 'SCRIPTED',
>   title: 'Appointment line IVR',
>   agentIds: ['<agent-id>'],
>   scriptAdherence: 'STRICT',
>   graph: [
>     {
>       type: 'CUSTOMER_VERBATIM_TURN',
>       content: 'Hi, I am calling about my appointment.',
>       stage: { name: 'IVR Phone Auth', required: true, analyze: false },
>       steps: [
>         {
>           type: 'AGENT_TURN',
>           content: 'Please enter your account number followed by the pound key.',
>           stage: { name: 'IVR Phone Auth' },
>           steps: [
>             {
>               type: 'CUSTOMER_DTMF',
>               dtmfDigits: '48213#',
>               stage: { name: 'IVR Phone Auth' },
>               steps: [
>                 {
>                   type: 'AGENT_TURN',
>                   content: 'Press 1 to hear your appointment time, or 2 to speak to the front desk.',
>                   steps: [
>                     {
>                       type: 'CUSTOMER_DTMF',
>                       dtmfDigits: '1',
>                       steps: [
>                         {
>                           type: 'AGENT_TURN',
>                           content: 'Your appointment is on Tuesday at 10 AM.',
>                           steps: [
>                             {
>                               ref: 'goodbye',
>                               type: 'CUSTOMER_TURN',
>                               content: 'Thank the agent and say goodbye.',
>                               endsCall: true,
>                             },
>                           ],
>                         },
>                       ],
>                     },
>                     {
>                       type: 'CUSTOMER_DTMF',
>                       dtmfDigits: '2',
>                       steps: [
>                         {
>                           type: 'AGENT_TURN',
>                           content: 'Connecting you to the front desk.',
>                           mergeIntoNodeIds: ['goodbye'],
>                         },
>                       ],
>                     },
>                   ],
>                 },
>               ],
>             },
>           ],
>         },
>       ],
>     },
>   ],
> })
>
> // Later: replace the whole graph in one call
> await client.customerFlow.replaceGraph(flow.data.id, { graph: [/* the steps, as above */] })
> ```

## Overview

A scripted flow is a [customer flow](https://docs.roark.ai/documentation/simulation-testing/customer-flows.md) whose conversation you write yourself, step by step, instead of a brief the simulated customer improvises from. You draw it on a full-screen canvas as a graph of steps: what the customer says, what your agent should say back, keys the caller presses, pauses, and where the conversation branches.

Every run walks your graph with the exact lines you authored, and each route through it becomes its own variant. Reach for a scripted flow when the conversation has to go a precise way:

* **IVR menus and keypad entry.** Navigate a phone tree, press digits, enter an account number.
* **Deterministic routing.** Check that a given answer leads your agent down the branch you expect.
* **Turn-by-turn checks.** Hold your agent to specific lines, and decide what happens when it says something else.

To start one, pick **Scripted** (**Author the conversation**, then **Open canvas**) when you create a flow; a flow keeps the mode it was created in. For open-ended conversations graded on intent, use an [Improv flow](https://docs.roark.ai/documentation/simulation-testing/improv-flows.md) instead.

![The canvas of an Appointment line IVR scripted flow at 58% zoom. Under Start, a frame labelled IVR Phone Auth, Required holds four steps: 01 Customer (Roark), Exact, Opens the call: Hi, I am calling about my appointment.; 02 Expected agent response: Please enter your account number followed by the pound key.; 03 Customer DTMF (Roark): 48213#; 04 Expected agent DTMF: 1. The graph then branches into 06 Customer (Roark): Ask to confirm the time of the appointment. and 05 Customer (Roark): Ask to move the appointment to next week., which merge into 07 Expected agent response: Let me pull up your appointment., then 08 Customer (Roark), Ends call: Thank the agent and say goodbye. The happy path's steps have darker outlines, and every step has a + below it.](https://mintcdn.com/roark/tTKLl1mcDRsh0H9y/images/simulation-testing/scripted-canvas.png?fit=max\&auto=format\&n=tTKLl1mcDRsh0H9y\&q=85\&s=6a620d833a0b2dcfc9d6a49209d1420e)

***

## The scripted graph

In scripted mode you build the conversation as a directed graph that starts at **Start**. Click the **+** under a step and pick a kind from **Insert step**. Above the kinds, **Connection** says how the new step joins the graph:

* **Continue** (Slip into this path) puts the new step between this step and the next one. **Branch** (Fork alongside) adds it as another next step, starting a new path. You get this choice on a step with exactly one next step. On the last step of a path the **+** simply adds the next step, and on a step that already branches it adds another branch.
* **Merge** (Converge downstream) adds no step: it links this step to one already on the canvas, so two paths meet again. Click **Merge**, then the step to join. It shows only when this step has a step it can join: one that isn't its own next step and doesn't come before it, since a loop isn't allowed. So on some steps, as in the picture below, the **+** offers only Continue and Branch.
* The **+** under **Start** offers **Continue** (goes first instead) and **New opening**: another way into the call, which runs as its own path.

Selecting a step opens the inspector with its fields.

![The step picker open on the canvas. Under Connection, Continue (Slip into this path) is selected beside Branch (Fork alongside). Under Insert step, Agent under test lists Expected response and Expected DTMF; Roark simulated customer lists Speak, Say exactly, Hand over, DTMF, Silence and Audio; Flow control lists Link to flow. Each kind has a one-line description.](https://mintcdn.com/roark/tTKLl1mcDRsh0H9y/images/simulation-testing/scripted-step-picker.png?fit=max\&auto=format\&n=tTKLl1mcDRsh0H9y\&q=85\&s=b8194d34d0803af36454c1c5206918e2)

### Step kinds

The picker groups steps by who acts.

| Group | Step | What it does |
| :- | :- | :- |
| **Agent under test** | **Expected response** | What you expect your agent to say or do next. It also becomes a graded expectation on the path |
| | **Expected DTMF** | Keypad digits you expect your agent to press, for an agent that navigates a menu the simulation plays |
| **Roark simulated customer** | **Speak** | Describe what the customer says; the persona phrases it |
| | **Say exactly** | Words the customer says exactly, without rephrasing. Placed directly under Start, it opens the call: Roark says it the moment the call connects, before your agent speaks |
| | **Hand over** | Another persona takes the phone from here, or the flow persona takes it back. See [Multiple callers](https://docs.roark.ai/documentation/simulation-testing/multiple-callers.md#in-a-scripted-flow) |
| | **DTMF** | The caller presses keypad digits (`0–9`, `*`, `#`; use `#` to mark end-of-input) |
| | **Silence** | The caller waits without speaking for 1 to 60 seconds |
| | **Audio** | Hold music, a hold tone or ringback plays on the line for a set time (up to 600 seconds, 30 by default). It plays when the flow [waits for each expected line](#script-adherence-loose-or-strict) on a voice call; otherwise it is a pause of the same length |
| **Flow control** | **Link to flow** | Splices another scripted flow's steps in at this point |

> [!NOTE]
>
> Over the API and in config as code the step types are `AGENT_TURN` (Expected response), `AGENT_DTMF` (Expected DTMF), `CUSTOMER_TURN` (Speak), `CUSTOMER_VERBATIM_TURN` (Say exactly), `CUSTOMER_HANDOFF`, `CUSTOMER_DTMF`, `CUSTOMER_SILENCE`, `CUSTOMER_AUDIO` and `SCENARIO_LINK` (Link to flow). `CUSTOMER_FIRST_MESSAGE` is the retired name for an opening exact line: it is still accepted, and stored and returned as `CUSTOMER_VERBATIM_TURN`.

> [!NOTE]
>
> **Looking for the Voicemail step?** Voicemail is a run template now, not a step. See [Voicemail Testing](https://docs.roark.ai/documentation/simulation-testing/templates/voicemail-testing.md). A voicemail has no conversation to graph and only one meaningful variable (which greeting plays), so the template runs Roark's recordings directly. Flows that already contain a Voicemail step keep working; you just can't add new ones.

Any step's content can also carry [caller cues](https://docs.roark.ai/documentation/simulation-testing/caller-cues.md) (type `#`) that change the caller's emotion, language or surroundings at that step, or make it cut in while the agent speaks.

### Graph rules

* **Branching is allowed**: give a step multiple outgoing edges to fork the conversation. Over the API, a step's children are its `steps`: one child continues the conversation, and several children (including several top-level entries in `graph`) are alternative branches.
* **Merges are allowed**: branches can rejoin.
* **Cycles are blocked**: the graph must be a DAG, so a conversation always terminates.

### Stages

A **stage** groups the steps that come before the real test, such as an IVR menu or a login. Pick or create one under **Stage** in a step's inspector; the canvas draws it as a frame around its steps.

![The inspector for a Customer (Roark) step whose line reads Thank the agent and say goodbye. Below the line, End the call here is switched on, with the note The call ends after this step, even when an improv flow opens with this flow. Stage is set to IVR Phone Auth, marked Required, with the note A run that ends before getting through IVR Phone Auth is reported but not scored.](https://mintcdn.com/roark/tTKLl1mcDRsh0H9y/images/simulation-testing/scripted-step-inspector.png?fit=max\&auto=format\&n=tTKLl1mcDRsh0H9y\&q=85\&s=a02b8bfc73e747fb48e1e38070c18a4e)

Click a stage's label on the canvas to open it and set two switches. They save as soon as you change them, and apply on every flow that uses the stage. With **Required for a valid run** on, the stage has to be got through: a run that ends without getting past it never reached what you're testing, so it is reported but left out of the score and the run's pass/fail verdict. An agent that never clears the IVR doesn't fail every check in a conversation it never started.

With **Measure what happens here** off, turns inside the stage don't count towards the core call metrics, which suits a stretch nobody is testing, such as an IVR menu; the LLM-judged metrics still read the whole call.

![The panel for a stage named IVR Phone Auth, 4 steps on this flow. Required for a valid run is on, with the note A run that ends before getting through this stage never reached the test. It stays in the report, labelled, and is left out of the score. Measure what happens here is off, with the note Turns inside this stage are left out of the core call metrics: talk time, speech pace, turn and response timings.](https://mintcdn.com/roark/tTKLl1mcDRsh0H9y/images/simulation-testing/scripted-stage-panel.png?fit=max\&auto=format\&n=tTKLl1mcDRsh0H9y\&q=85\&s=f84046426ee54db40c8e0627b0a94641)

In config as code a step's `stage` is a name (`"IVR Phone Auth"`) or an object: `{ name, required, analyze }`.

### Ending the call

When an [improv flow opens with this scripted flow](https://docs.roark.ai/documentation/simulation-testing/customer-flows.md#composing-flows), every path hands over to the improv at its last step. In a flow that [waits for each expected line](#script-adherence-loose-or-strict), set **End the call here** on the last step of a path to end the call there instead, as an IVR does after saying goodbye (`endsCall: true` over the API and in config as code).

### Paths derive variants

Every unique route through the graph from start to finish is a **path**, and when you save the flow, Roark derives one variant per path. Each path card in the right rail shows a generated description of its route. You don't hand-author scripted variants; you shape the graph and the variants follow.

You can still control *who* runs each path: **Add variant for path** creates an extra copy of a path that runs it with a different persona or environment. The rail marks the flow's default variant with a **Default** badge and groups the rest under **Edge cases**, with **Make default** and **Delete variant** available per variant.

How those paths turn into *calls* is a separate choice, covered next in [Branching](#branching-how-paths-become-calls).

### Branching: how paths become calls

A branching graph can be run two ways, chosen with the **Branching** control at the top of the variant rail. Both modes speak the exact lines you authored. The choice decides only *when* a branch is picked and *how many calls* a run places. Neither mode changes how metrics or agent expectations grade.

| | **Simulate every path** | **Adapt to your agent** |
| :- | :- | :- |
| Branch is picked | Up front, when the flow is saved | During the call, from what your agent actually says |
| Calls per run | One per variant the run includes | One per persona among the included variants |
| Coverage | Every included path, every run | One path per call, whichever the agent leads to |
| Best for | Regression suites, full branch coverage, DTMF and IVR entry | Agents whose replies you can't predict; shared blocks linked into other flows |

Take a caller asking for a Tuesday appointment, where the agent's own answer forks the conversation. The info icon next to **Branching** opens **How branching works**, which runs this example both ways:

![The How branching works dialog, One graph, two run behaviors. Two panels show the same graph: the customer says Hi, can I book a cleaning for Tuesday?, the agent replies either Tuesday at 9am is open or Tuesday is fully booked, and the customer answers Perfect, book it. or What about Wednesday?. Simulate every path (2 paths, 2 calls) marks the branches Call 1 and Call 2. Adapt to your agent (2 paths, 1 call) marks the fully booked branch Call 1 and greys out the other as Not taken. Notes below say personas multiply calls in both modes, that goal-level checks belong in an Improv flow, and that the counts are for this flow alone.](https://mintcdn.com/roark/tTKLl1mcDRsh0H9y/images/simulation-testing/branching-explainer.png?fit=max\&auto=format\&n=tTKLl1mcDRsh0H9y\&q=85\&s=4545da881f059203f80655f6ee59c7bf)

**Simulate every path** places two calls. Call 1 always takes the left branch and call 2 always takes the right one, even when your agent says something the other branch was written for. That is the point: a path that stopped matching your agent's behavior surfaces as a failure instead of being quietly routed around.

**Adapt to your agent** places one call. The simulated customer hears which reply your agent actually gave and follows that branch; the branch it didn't take isn't exercised on that call.

The **Branching** picker in the app shows the call count each mode places for the flow you're editing, with every variant running once. A run plan's own configuration wins over that figure: selecting a subset of variants, applying a persona override, or setting an iteration count all change what a run actually places.

> [!NOTE]
>
> **Personas multiply calls in both modes.** Adapt to your agent collapses a flow's paths into one call **per persona**, not one call outright. Five paths across three personas run as three calls. On a collapsed call, variable values come from the primary variant; the sibling variants contribute their path shape, not their own values. Sibling-only variable *names* are still detected and prompted for, so they don't vanish silently.

> [!WARNING]
>
> **Linking a multi-path flow requires Adapt to your agent.** A **Flow link** step targeting a flow that is set to *Simulate every path* and has more than one reachable path fails the run: composed fan-out across linked flows isn't supported yet. Either set the linked flow to **Adapt to your agent**, so the run follows whichever path the agent leads to, or link a single-path flow.

> [!TIP]
>
> Reach for **Adapt to your agent** when you genuinely can't predict the branch: an IVR tree whose menu order varies, or a shared block linked into many flows. Use **Simulate every path** for everything else. It's the mode that gives you coverage you can regress against.

> [!NOTE]
>
> **Adapt to your agent is not looser grading, and it is not goal-level authoring.** Both branching modes speak your exact scripted lines. To have the agent checked against intent ("confirms the caller's name") rather than a script, use an [Improv flow](https://docs.roark.ai/documentation/simulation-testing/customer-flows.md#authoring-modes-improv-vs-scripted) with agent expectations.

> [!NOTE]
>
> Over the API and in config as code this is `branchingMode`: `DETERMINISTIC` (Simulate every path) or `ADAPTIVE` (Adapt to your agent).

![The Branching control at the top of the variant rail, with an info icon beside its heading: Simulate every path (2 calls) is selected above Adapt to your agent (1 call), and below them reads Each path runs as its own call and follows it exactly, whatever your agent says.](https://mintcdn.com/roark/tTKLl1mcDRsh0H9y/images/simulation-testing/branching-picker.png?fit=max\&auto=format\&n=tTKLl1mcDRsh0H9y\&q=85\&s=c7068fa00b3fc0fa927f0499bcd8278e)

> [!WARNING]
>
> Structural edits (adding or deleting nodes or edges) freeze variant editing until you save: "You've edited the graph. Save the flow to refresh its paths before adding or removing variants."

### Script adherence: loose or strict

**Script adherence**, the control under **Branching** in the variant rail, decides how closely each call follows the script. Branching decides how many calls a graph places; adherence decides how each of those calls is walked.

| | **Keep the call moving** (`LOOSE`, the default) | **Wait for each expected line** (`STRICT`) |
| :- | :- | :- |
| How a call runs | The whole script is a guide for the simulated customer, which keeps the call going whatever your agent says | Step by step. At every **Agent** step the simulated customer stays silent until your agent has said the expected line, and only then moves on |
| When your agent says something else | The simulated customer carries on | The [off-script policy](#when-your-agent-goes-off-script) decides |
| Runs on | Voice and chat | Voice calls only, on a standard (non-realtime) voice |

At a strict **Agent** step, everything your agent has said since the step began is checked against the expected line (and, at a branch, against each alternative's line) by an LLM judge. A line your agent delivers across two utterances matches on the second. Each utterance that leaves the line still not delivered is one **off-script attempt**. Where the step expects your agent to press keys, a key press that matches none of the step's options is an attempt too.

> [!NOTE]
>
> Over the API this is `scriptAdherence` (`LOOSE` or `STRICT`) on the customer flow, and the policy below is `offScriptPolicy`. In config files they are `adherence` and `offScript`.

#### When your agent goes off script

With **Wait for each expected line** selected, the variant rail shows **When your agent goes off script**: the policy for every Agent step in the flow. An Agent step can set its own under **When the agent goes off script here** in the inspector, and that one wins at that step.

![The scripted flow's variant rail with Script adherence set to Wait for each expected line, and the When your agent goes off script policy expanded below it: Each time Repeat my last line, After 2 attempts, Then Continue loosely, and Or after left blank](https://mintcdn.com/roark/xnD-bUZQOU-13veO/images/simulation-testing/strict-adherence-policy.png?fit=max\&auto=format\&n=xnD-bUZQOU-13veO\&q=85\&s=0f24c915006595e9ece3f4d5927ce9df)

| Field | API field | What it sets |
| :- | :- | :- |
| **Each time** | `reaction` | What the simulated customer does on each attempt (see below). Default: **Stay silent** |
| **After** | `maxAttempts` | How many attempts before the outcome runs, 1 to 20. Default: 3 |
| **Then** | `then` | The outcome (see below). Default: **Hang up** |
| **Or after** | `waitSeconds` | Seconds of silence from your agent that run the outcome straight away, 1 to 600. Blank: only the run's own silence timeout applies |

The reaction on each attempt:

* **Stay silent** (`STAY_SILENT`): the simulated customer says nothing and keeps listening.
* **Repeat my last line** (`REPEAT`): it says its last scripted line again.
* **Respond, but hold position** (`RESPOND`): it answers once, in character, in a sentence or two, without moving the conversation forward or mentioning anything later in the script.
* **Say a line** (`SAY`): it says the line you give it (`sayLine`).

The outcome when the attempts run out, or your agent stays silent for **Or after** seconds:

| Outcome | What the simulated customer does | What the run shows |
| :- | :- | :- |
| **Hang up** (`HANG_UP`) | Hangs up at once, saying nothing more | The call counts and is scored on what happened up to the hang-up. The calls list shows the ending as **Went off script** |
| **Hang up and invalidate the run** (`HANG_UP_INVALIDATE`) | Hangs up exactly as **Hang up** does | The call is [excluded](https://docs.roark.ai/documentation/simulation-testing/running-simulations.md#calls-that-don’t-count) with reason `SCRIPT_DIVERGED`: no metric scores it and it is left out of every figure in the run. It keeps its transcript and recording |
| **Move on to the next step** (`MOVE_ON`) | Carries on as if your agent had said the line, from the next step on the main path. The next Agent step is strict again | The call carries on and is scored normally |
| **Continue loosely** (`ADAPT`) | From this step to the end of the call it stops waiting for exact lines: at each remaining Agent step it decides for itself when your agent has done what the step asks, then moves on. It still says its own scripted lines | The call carries on and is scored normally. No further off-script attempts are recorded after this point |

> [!NOTE]
>
> A step where your agent is expected to press keys does not follow the flow's policy. Without a policy of its own it waits for keys until just before the run's silence timeout and then hangs up, and the call still counts. Its own policy can only **Stay silent** or **Repeat my last line**, and end with **Hang up**, **Hang up and invalidate the run** or **Move on to the next step**.

> [!TIP]
>
> Use **Hang up and invalidate the run** on a step where a miss makes the rest of the call meaningless, an authentication menu for instance, and keep a gentler policy on the flow.

#### Where an off-script moment shows up

Over the API, the call's transcript marks each off-script moment where it happened. `offScript` is only used for simulations: it appears on entries of `GET /v1/call/{callId}/transcript` for a simulation call that followed a strict scripted flow, never on production calls or chats. An entry has it only when it was one of these, and has no `offScript` key otherwise:

* **An attempt** (`part: "ATTEMPT"`), on your agent's entry: it said or pressed something other than what the step expects, or stayed silent. `cause` is `AGENT_SAID`, `AGENT_PRESSED` or `SILENCE`. `reaction` is what the simulated customer did next when your agent got another try, and `action` is what the policy did when this attempt ended the step: `HANG_UP`, `HANG_UP_INVALIDATE`, `MOVE_ON` or `ADAPT`. The last attempt carries the action.
* **A reaction** (`part: "REACTION"`), on the simulated customer's entry: it was reacting to an attempt rather than following its script. `reaction` is `REPEAT`, `RESPOND`, `SAY` or `STAY_SILENT`, and `step`, `attempt` and `occurredAt` are those of the attempt it answers.

Both carry the `step` it happened at (its `nodeId` in the flow and its expected line, or null for a branch step the call's path does not carry), `attempt` and `maxAttempts`, and `occurredAt`, when the attempt was judged off script. Silence at an Agent step is not a counted attempt, so its `attempt` is null. At a keypress step each wait for keys is one attempt, and the prompt played again is a `REPEAT`.

A moment with no speech gets an entry of its own, in time order, with empty `text` and `startOffsetMs` equal to `endOffsetMs`, so it adds nothing to talk time: your agent's silence, keys your agent pressed that have no transcript line, and the simulated customer staying silent. Keys that already have a line (`[DTMF: 1 2]`) are marked on that line.

```json theme={"theme":{"light":"everforest-light","dark":"everforest-dark"}}
"entries": [
  { "participantId": "c41e8a90-…", "role": "AGENT", "text": "Hello?", "startOffsetMs": 1200, "endOffsetMs": 1900,
    "offScript": { "part": "ATTEMPT", "step": { "nodeId": "5d4c3b2a-…", "text": "Thanks for calling, how can I help?" }, "attempt": 1, "maxAttempts": 2, "cause": "AGENT_SAID", "reaction": "REPEAT", "action": null, "occurredAt": "2025-01-15T14:24:31.412Z" } },
  { "participantId": "7f2d9b16-…", "role": "CUSTOMER", "text": "Hi, I would like to check my account balance.", "startOffsetMs": 3150, "endOffsetMs": 5600,
    "offScript": { "part": "REACTION", "step": { "nodeId": "5d4c3b2a-…", "text": "Thanks for calling, how can I help?" }, "attempt": 1, "maxAttempts": 2, "cause": null, "reaction": "REPEAT", "action": null, "occurredAt": "2025-01-15T14:24:31.412Z" } },
  { "participantId": "c41e8a90-…", "role": "AGENT", "text": "Sorry, who is this?", "startOffsetMs": 6700, "endOffsetMs": 7900,
    "offScript": { "part": "ATTEMPT", "step": { "nodeId": "5d4c3b2a-…", "text": "Thanks for calling, how can I help?" }, "attempt": 2, "maxAttempts": 2, "cause": "AGENT_SAID", "reaction": null, "action": "ADAPT", "occurredAt": "2025-01-15T14:24:38.105Z" } },
  { "participantId": "7f2d9b16-…", "role": "CUSTOMER", "text": "It's Jordan. I just need my current balance, please.", "startOffsetMs": 9300, "endOffsetMs": 12100 }
]
```

A caller entry is marked as a reaction when it starts while the simulated customer was saying its reaction, or up to 750 ms before. No entry has `offScript` on a production call, a chat, a simulation that did not follow a strict flow, or one where your agent stayed on script. Calls from before reactions were recorded have their attempts marked, but no spoken turn marked as a reaction. The transcript route needs the `transcript:read` permission.

A hang-up by the policy ends the call with `endedStatus` `CUSTOMER_ENDED_CALL`, as any hang-up by the simulated customer does. The last attempt's `action` (`HANG_UP` or `HANG_UP_INVALIDATE`) tells the two apart.

**Hang up and invalidate the run** also sets `invalidation` on the job, with `reason: "SCRIPT_DIVERGED"` and a `detail` sentence naming the step's text and what your agent said. See [Calls that don't count](https://docs.roark.ai/documentation/simulation-testing/running-simulations.md#calls-that-don’t-count).

In the app, every attempt and every outcome is recorded against the step it happened at, with what your agent said (or that it said nothing):

* **Transcript tab** of the call: a line with a warning icon at the moment it happened, in the order of the conversation. For a flow set to Repeat my last line, 2 attempts, then Continue loosely:

  * `Off script: expected "Can I have your account number?" but got "How can I help you today?", repeating (attempt 1/2)`
  * `Off script: expected "Can I have your account number?" but got "Are you calling about a bill?", continued loosely (attempt 2/2)`

  The last attempt's line says what the policy did, **hung up**, **hung up, run invalidated**, **moved on** or **continued loosely**, and that line is where the call switched behaviour. A caller turn that was the simulated customer's reaction carries a tag saying so, such as **Off-script reaction: repeated its line**. Silence that ends the step reads `Off script: expected "…" but got nothing, hung up`.
* **Simulation tab** of the call: the script that ran, step by step, with when each step was reached and the same off-script lines under the step they happened at. A moment on a branch alternative that is not on the call's path is listed under **On a branch step**.
* **Calls list** of the run: a call that **Hang up** ended shows **Went off script** as its ending, and its detail says what your agent said or that it stayed silent. The Simulation tab names the step it happened at. An invalidated call shows **Went off script** with one sentence naming the step's text and what your agent said.

![A call's Simulation tab for a flow set to Repeat my last line, 2 attempts, then Continue loosely. Under the Agent Turn step expecting Thanks for calling, how can I help you today? are two attempt lines, repeating (attempt 1/2) and continuing loosely (attempt 2/2), each quoting what the agent said instead, then the outcome line Off script: continued loosely after attempt 2/2](https://mintcdn.com/roark/xnD-bUZQOU-13veO/images/simulation-testing/off-script-simulation-tab.png?fit=max\&auto=format\&n=xnD-bUZQOU-13veO\&q=85\&s=83ace2ea5f872283957dcc3518da4386)

The simulated customer's reactions (**Repeat my last line**, **Respond, but hold position**, **Say a line**) are caller turns in the transcript, marked as reactions: in the Transcript tab the turn carries the tag above, and over the API its entry's `offScript` (see above). **Stay silent** adds no spoken turn.

#### How metrics treat off-script turns

No metric checks for off-script moments. Every metric reads the call's transcript as it was recorded, so off-script turns are scored like any other turn:

* **Repeat my last line, Respond, but hold position, Say a line**: each reaction is a caller turn. Your agent's reply to it counts toward its Response Time, Turn Duration, Latency Spike Count and the other timing metrics exactly as a reply to a scripted line does, and Comprehension Failure grades that caller turn and your agent's reply like any other.
* **Stay silent**: there is no caller turn. When your agent speaks again after a pause, that is the same speaker going on, so no Response Time or Latency Spike is measured for the pause. A pause longer than 3 seconds starts a new agent turn for Turn Duration and Turn Count. Comprehension Failure grades caller turns only, so there is nothing for it to grade.
* The time the simulated customer takes before it reacts counts toward the simulated customer's own timing metrics, not your agent's.
* After **Move on to the next step** or **Continue loosely**, the rest of the call is scored normally. After **Hang up**, the call is scored on what happened up to the hang-up. After **Hang up and invalidate the run**, nothing scores the call.

Today every off-script turn is scored this way. To keep a call whose script broke down out of the results entirely, set that step to **Hang up and invalidate the run**.

***

## Next steps

> [card] [Customer flows](https://docs.roark.ai/documentation/simulation-testing/customer-flows.md)
>
> Variants, expectations, labels and composing flows

> [card] [Flow sequences](https://docs.roark.ai/documentation/simulation-testing/flow-sequences.md)
>
> Run several flows in order for the same customer

> [card] [Multiple callers](https://docs.roark.ai/documentation/simulation-testing/multiple-callers.md)
>
> Hand the phone to another persona mid-call

> [card] [Flows in config as code](https://docs.roark.ai/documentation/config-as-code/flows.md)
>
> Declare scripted graphs in YAML or TypeScript


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