# Replay and evaluation

This guide shows how to read finished runs back from their journal (the durable record of
every event of a run), try a change on them before you adopt it, and grade them against
explicit checks. At the end you have two scorecards, before and after one change, computed
from recorded runs: no model, tool or person is asked again.

- **You will be able to:** turn a recorded run into a **trace** (what the actor did with
  each event), replay its events against a changed actor, see where the two part ways, and
  compare **scorecards** (the results of a set of checks over many runs) before and after.
- **Read first:** the tutorial [6. Crash and resume](../tutorials/durability.md), which
  introduces the journal, [11. Testing your harness](../tutorials/testing.md) for the test
  fakes used below, and [The reference agent](../concepts/reference-agent.md) for the states
  named below.
- **Time:** about 25 minutes.

## On this page

**The walkthrough**, to follow in order; each step runs on the one before:

1. [Record some runs](#step-1-record-some-runs)
2. [Read a run back as a trace](#step-2-read-a-run-back-as-a-trace)
3. [What the runs cost](#step-3-what-the-runs-cost)
4. [Replay against a change](#step-4-replay-against-a-change)
5. [Checks](#step-5-checks): the rules a run is graded against
6. [Evaluations and scorecards](#step-6-evaluations-and-scorecards), where the walkthrough
   ends

**To look things up**, in any order:

- [The checks gvn ships](#checks), a table inside step 5
- [What the models were asked](#what-the-models-were-asked): checks over a run's model calls
- [The objects in detail](#the-objects-in-detail): every method of frames, traces, grades and
  scorecards
- [How `Gated` decides](#how-gated-decides): the rule behind "no call ran without approval"

## Where this fits

In the [big picture](../quickstart.md#the-big-picture), the **journal** holds every event of
a run, in order, and the **actor** is a state machine that does no I/O: it only moves between
states and asks for work. So feeding a run's recorded events to an actor again reproduces the
run step by step, with no **fulfiller** involved: no model, no tool, no person. This guide
works entirely on that side of the picture.

```mermaid
flowchart LR
    journal[("Journal<br/>recorded events")]
    replay["Replay"]
    recordedActor["The actor that ran"]
    changedActor["A changed actor"]
    traces["Traces<br/>one frame per event"]
    evaluation["Evaluation<br/>a set of checks"]
    scorecards["Scorecards<br/>before and after"]
    journal --> replay
    replay -- "same events" --> recordedActor
    replay -- "same events" --> changedActor
    recordedActor --> traces
    changedActor --> traces
    traces --> evaluation --> scorecards
```

Two modules build on that:

- `gvn.runtime.replay` reads a run back as a **trace**: what the actor did with each event.
  It can also feed the events to a *different* actor, to see what that actor would have
  done with them.
- `gvn.runtime.evaluation` grades traces against explicit **checks** (small rules such as
  "the run finished" or "no refund ran without approval") and compares the results across
  versions.

Together they let you try a change on real history before you adopt it. Replay keeps the
history and changes the code; to keep the code and change the history from some point on,
with real work after it, fork the recorded run at that position into another journal
([Forking a run](forking-a-run.md)). The page first says
what replay answers, then records some runs (step 1), reads them back (steps 2 and 3),
replays them against a change (step 4) and grades both (steps 5 and 6). The full list of what
traces, frames and scorecards offer is at the end.

## What replay answers

Replay feeds **recorded events**. That includes the model's recorded replies, the tools'
recorded results and the policy's recorded verdicts. It re-runs the actor's own code:
its machine, its internal decisions and, for a [workflow](../concepts/workflows.md), its
plan (stage functions, routes, judges, joins and `classify` Decisions).

A workflow rebuilt from a stored run is checked against the plan's
[settings](../concepts/workflows-in-depth.md#settings): `Replay(...).recorded` rebuilds the
recorded workflow from its first snapshot, so it raises `SettingsMismatch` when the plan now
declares other settings than the run was made under. To ask what a changed plan would have
done, build the changed actor yourself and replay against it (step 4).

So replay answers questions like these exactly:

- With a smaller turn budget, which recorded runs would have failed?
- If this agent were not offered a tool, which runs would have been stopped?
- With a stricter join, a different judge or a new route, where would workflows have ended?
- Does a changed machine still accept every recorded event?

The model's replies, the tools' results and the policy's verdicts are events, and replay
feeds them as recorded. A change whose effect depends on what a model would now say (new
instructions, other tools, another model), on what a tool would now return, or on what a
changed policy Decision would decide is tried with new runs, against a real or scripted
model.

## Step 1: record some runs

Any run driven by a Governor is recorded. Here three questions go to the same agent. The
model is a `FunctionModel`, a test fake whose reply is a function of the conversation: it
looks things up when the question starts with "look up", and answers directly otherwise. The
one tool, `search`, is a `StubTool` that always returns the same result, and the policy
`Allow` clears every call.

```python
import asyncio

from gvn.harness.agent import VERDICTS, Agent
from gvn.harness.events import Event
from gvn.harness.messages import TOOL, Message, ToolCall
from gvn.harness.ports import Exchange, Reply
from gvn.harness.tools import Toolbox
from gvn.kernel.decision import Decision
from gvn.kernel.schema import Record, Text
from gvn.kernel.symbols import Alphabet, Symbol
from gvn.runtime.governor import Governor
from gvn.runtime.fulfillers import ModelFulfiller, PolicyFulfiller, ToolFulfiller
from gvn.testing.fakes import FunctionModel, ManualClock, MemoryJournal, RecordingOutput, StubTool


class Allow(Decision):
    def outcomes(self) -> Alphabet:
        return VERDICTS

    def judge(self, consultation: object) -> Symbol:
        return VERDICTS.named("cleared")


def answer(exchange: Exchange) -> Reply:
    question = exchange.messages()[0].text()
    looked_up = any(message.role() == TOOL for message in exchange.messages())
    if question.startswith("look up") and not looked_up:
        lookup = ToolCall(call_id="c1", name="search", arguments={"query": question})
        return Reply(message=Message.assistant(text="", calls=[lookup]))
    return Reply(message=Message.assistant(text=f"An answer to {question!r}."))


search = StubTool(name="search", arguments=Record({"query": Text()}), result={"hits": 3})
toolbox = Toolbox(tools=[search])
journal = MemoryJournal()
governor = Governor(
    fulfillers={
        "invoke_model": ModelFulfiller(model=FunctionModel(respond=answer), toolbox=toolbox),
        "invoke_tools": ToolFulfiller(toolbox=toolbox),
        "consult_policy": PolicyFulfiller(decision=Allow()),
    },
    journal=journal,
    output=RecordingOutput(),
    clock=ManualClock(),
)

QUESTIONS = {"q1": "what is a Moore machine", "q2": "look up Mealy", "q3": "look up Harel"}


def helper(run: str, turns: int = 4) -> Agent:
    return Agent(name=run, instructions="Answer briefly.", tools=[search], turns=turns)


async def record() -> None:
    for run, question in QUESTIONS.items():
        started = Event("started", payload={"prompt": question})
        await governor.deliver(actor=helper(run), event=started)


asyncio.run(record())
```

Each agent is named after its run (`q1`, `q2`, `q3`), and the journal keeps each run under
that name. In production the journal would be a `SqliteJournal` or one of your own, and the runs would
be days of real traffic. Nothing below cares which.

## Step 2: read a run back as a trace

`Replay(journal).recorded(run_id, actor_class)` rebuilds the actor from the run's first snapshot
and feeds it every recorded event. The result is a `Trace`: one `Frame` per event.

```python
from gvn.runtime.replay import Replay, Trace

replay = Replay(journal=journal)


async def recorded_traces() -> list[Trace]:
    return [await replay.recorded(run_id=run, actor_class=Agent) for run in QUESTIONS]


recorded = asyncio.run(recorded_traces())
trace = recorded[1]
print(trace)
# Trace('q2', 5 frames, idle -> thinking -> vetting -> acting -> thinking -> completed, finished=True)
for frame in trace:
    print(frame)
# Frame(0, 'started' -> 'thinking', wanted=['invoke_model'])
# Frame(1, 'model_replied' -> 'vetting', wanted=['consult_policy'])
# Frame(2, 'cleared' -> 'acting', wanted=['invoke_tools'])
# Frame(3, 'tools_returned' -> 'thinking', wanted=['invoke_model'])
# Frame(4, 'model_replied' -> 'completed', wanted=[])
```

Each frame names the event, the state it left the actor in, and the kinds of request the
actor wanted next. Read the second trace against the journal table in the
[quickstart](../quickstart.md#see-the-machine-at-work): it is the same run, one row per event.
Everything a frame and a trace offer is listed in [the objects in detail](#the-objects-in-detail).

<a id="what-the-runs-cost"></a>

## Step 3: what the runs cost

Every `model_replied` event carries the tokens the model call reported,
`"usage": {"input_tokens", "output_tokens", "cache_read_tokens", "cache_write_tokens"}`, so the journal is also a record of
cost. `input_tokens` counts every input token, read from the prompt cache (a vendor feature
that stores the start of a prompt so that later calls can reuse it) or not; `cache_read_tokens` and
`cache_write_tokens` are the parts of it read from and written to the cache, which vendors bill at
other prices (see [usage](vendors.md#what-a-call-cost-usage)). `Trace.usage()` sums them and
counts the calls. Two methods split the same totals: `usage_by_origin()` by the actor each
reply was for, which matters in a workflow with many agents, and `usage_by_model()` by the
model that made each call, which matters when one run uses several models
([a model per role](vendors.md#a-model-per-role)) and they have different prices. A failed call (`model_failed`) counts too, with the
usage the vendor reported for it, if any, and so does every attempt a `ModelFulfiller` retried
before answering (the payload's `"retries"`): `"calls"` is the number of model calls the
journal records, so a reply that came after two retried attempts counts as 3.

Here the scripted model reports a first call that writes most of its prompt to the cache,
and a second that reads it back:

```python
from gvn.testing.fakes import ScriptedModel

priced = MemoryJournal()
lookup = ToolCall(call_id="c1", name="search", arguments={"query": "Moore"})
model = ScriptedModel(
    script=[
        Reply(
            message=Message.assistant(text="", calls=[lookup]),
            input_tokens=1200,
            output_tokens=40,
            cache_write_tokens=1100,
        ),
        Reply(
            message=Message.assistant(text="A Moore machine's output depends only on its state."),
            input_tokens=1350,
            output_tokens=25,
            cache_read_tokens=1100,
        ),
    ],
    name="example-model",
)
costed = Governor(
    fulfillers={
        "invoke_model": ModelFulfiller(model=model, toolbox=toolbox),
        "invoke_tools": ToolFulfiller(toolbox=toolbox),
        "consult_policy": PolicyFulfiller(decision=Allow()),
    },
    journal=priced,
    output=RecordingOutput(),
    clock=ManualClock(),
)


async def priced_run() -> Trace:
    started = Event("started", payload={"prompt": "look up Moore"})
    await costed.deliver(actor=helper("q9"), event=started)
    return await Replay(journal=priced).recorded(run_id="q9", actor_class=Agent)


trace = asyncio.run(priced_run())
print(trace.usage())
# {'input_tokens': 2550, 'output_tokens': 65, 'cache_read_tokens': 1100, 'cache_write_tokens': 1100, 'calls': 2}
print(trace.usage_by_origin())
# {'q9': {'input_tokens': 2550, 'output_tokens': 65, 'cache_read_tokens': 1100, 'cache_write_tokens': 1100, 'calls': 2}}
print(trace.usage_by_model())
# {'example-model': {'input_tokens': 2550, 'output_tokens': 65, 'cache_read_tokens': 1100, 'cache_write_tokens': 1100, 'calls': 2}}
```

Where the model's name comes from: each `model_replied` and `model_failed` records
`"model"`, the name of the model that made the call. For a reply it is the model id the
vendor reported in its response (`Reply.model()`), which can be more exact than the id that
was asked for; otherwise it is `Model.name()`, which the Anthropic and OpenAI adapters
answer with the model id they were configured with and the fakes with their `name=`. A call
with neither (a model that has no name)
counts under `None`. Each retried attempt counts under its own model, and the totals of
`usage_by_model()` always add up to `usage()`.

Of the 2,550 input tokens, 1,100 were written to the cache by the first call and 1,100 read
from it by the second; the other 350 were sent uncached. To price a run, multiply each part by
its own price: uncached input (`input_tokens - cache_read_tokens - cache_write_tokens`), cache reads, cache writes
and output.

To turn these token counts into money with your own prices, or to stop a run when it has
spent a set amount, see
[Reading what a recorded run spent](spending-and-rate-limits.md#reading-what-a-recorded-run-spent).

Calls whose reply never reached the journal, because they were cancelled or no longer
wanted, are not counted. A rejected `model_replied` is counted: the call was made. The same figures reach your outputs live: the
`event` signal of a `model_replied` carries `"usage"` (see
[Logs, traces and streams](observability.md)).

## Step 4: replay against a change

`replay.against(run_id, actor)` feeds the same recorded events to an actor you built: a
changed version of the one that ran. Events addressed to the recorded run are re-addressed to
the new actor's name, so the new actor need not have the same name. Events that no longer
fit are rejected, or recorded with an `error`, and replay carries on, so the trace shows
everything that no longer fits.

Suppose you want to save cost by allowing each agent a single model turn:

```python
async def with_one_turn() -> list[Trace]:
    return [await replay.against(run_id=run, actor=helper(run, turns=1)) for run in QUESTIONS]


changed = asyncio.run(with_one_turn())
print(changed[1].state(), recorded[1].divergence(changed[1]))  # failed 3
print(changed[1].frames()[3])  # Frame(3, 'tools_returned' -> 'failed', wanted=[])
```

`divergence(other)` is the index of the first frame where two traces differ in state,
rejection or the kinds of the wanted requests (or the length of the shorter, if one is a prefix of the other),
and `None` when they agree throughout. Here the runs agree until the tool's result comes back;
then the budget is spent, and the changed agent fails where the recorded one asked the model
again.

<a id="checks"></a>

## Step 5: checks

A `Check` looks at one trace and returns a tuple of problems, empty when the trace is fine.
These ship with gvn, in `gvn.runtime.evaluation` (`Sensed`, which grades what a run's
sensors read, is on [Sensors](../concepts/sensors.md)):

| Check | Passes when | Name in reports |
|---|---|---|
| `Finishes(*states)` | the run finished; in one of `states` if any are given | `finishes`, `finishes in completed`, `finishes in escalated or resolved` |
| `Visits(state)` | some frame left the actor in `state` | `visits <state>` |
| `Avoids(state)` | no frame left the actor in `state`, and it did not start there | `avoids <state>` |
| `Within(events)` | the run took at most `events` events; `events` may be a function of the trace | `within <n> events`, `within: computed` |
| `NoRejections()` | no event was rejected or raised | `no rejections` |
| `Gated(tools, when=None)` | no call to one of `tools` (for which `when(call, context)` is true, if given) succeeded unless a person approved that call | `gated: <identities>`, `gated: <identities> when <function>` |
| `Parks(*states)` | the run ended **waiting**, not finished, in one of `states` | `parks in <states>` |
| `Either(*checks)` | at least one of two or more checks passes | `either <name> or <name>` |
| `By(tool, when)` | every request for `tool` was journaled at or before `when(context)`, a time | `by: <identity> when <function>` |
| `ApprovedFirst(label, tools, when=None)` | an `approved` answer to an approval labelled `label` was journaled before any (matching) call to `tools` was requested | `approved first: <label> before <identities>` |
| `ModelAsked(label, accepts)` | `accepts(request)` is true for every model call of the run, from any actor | `model asked: <label>` |
| `AnsweredBy(kind, accepts)` | every accepted answer to a request of `kind` came from a principal, and `accepts(principal, request)` is true for it | `answered by: <kind> <function>` |

`Visits` and `Avoids` read `states()`, so they see the states events left the actor in, not
the ones it only passed through.

The checks that name tools (`Gated`, `By`, `ApprovedFirst`) take the tool objects, or a
`Toolbox`, never their names, and match the recorded calls by **identity**: the tool's
namespace, a dot and its short name, which every recorded request carries beside each call.
A call to another tool that shares the short name is not matched. Check names and problems
show identities ([Tools](../concepts/tools.md#two-names-the-short-name-and-the-identity)
explains the two names).

`Gated` is the safety check most harnesses need: a tool call that ran without a person
approving that very call is a problem. It reads what each actor asked for, so it works for
agents, for model-free actors and for your own, at any depth inside workflows. Exactly how it
pairs approvals with calls is in [how `Gated` decides](#how-gated-decides).

`when(call, context)` narrows what is gated: it receives the `ToolCall` and a copy of the
[run context](../concepts/run-context.md) (trusted facts about the job, such as an amount
or a target, fixed for the run and never shown to the model), and returns a bool. Amount
thresholds and "production only" are one line each. The tools here are `StubTool` stand-ins
with the namespaces your own tools would have; in your harness, pass the tools your
deployment builds:

```python
from gvn.runtime.evaluation import Gated, Within

by_order = Record({"order_id": Text()})
by_target = Record({"target": Text()})
refund = StubTool(name="refund", arguments=by_order, namespace="shop.payments")
chargeback = StubTool(name="chargeback", arguments=by_order, namespace="shop.payments")
deploy = StubTool(name="deploy", arguments=by_target, namespace="ops.releases")
rollback = StubTool(name="rollback", arguments=by_target, namespace="ops.releases")

money = Gated(tools=[refund, chargeback], when=lambda call, context: context["amount"] > 500)
production = Gated(
    tools=[deploy, rollback],
    when=lambda call, context: call.arguments()["target"] == "production",
)
print(money.name())  # gated: shop.payments.chargeback, shop.payments.refund when <lambda>


def brief_limit(trace: Trace) -> int:
    return 10 * trace.frames()[0].event().payload()["items"]


paced = Within(events=brief_limit)  # the limit grows with the brief
print(paced.name())  # within: computed
```

[Testing your harness](../concepts/testing.md#checking-a-safety-rule-on-recorded-runs) has a
worked example on a recorded run.

The other four cover runs that wait and runs against the clock:

- `Parks` is for a run whose correct end is to be **waiting**: parked on a person, a
  delivery or a wake-up. Such a run fails `Finishes`, so a harness that may legitimately
  park judges it with `Either(Finishes("signed"), Parks("negotiating"))`.
- `By(tool, when)` checks a deadline on the request side: `when` receives the run context and
  returns the time by which the tool must have been asked for, such as a brief's
  `respond_by`. It compares with each frame's recorded time, `Frame.at()`.
- `ApprovedFirst(label, tools)` checks a gate rather than each call: once an
  [`Approval`](../concepts/human-in-the-loop.md#an-approval-on-its-own) labelled `label` was
  approved, every later matching tool request is covered. A rollout gate is the typical use.

```python
from gvn.runtime.evaluation import ApprovedFirst, By, Either, Finishes, Parks

submit_response = StubTool(name="submit_response", arguments=by_order, namespace="sales.bids")
open_change_request = StubTool(
    name="open_change_request", arguments=by_target, namespace="ops.changes"
)

on_time = By(tool=submit_response, when=lambda context: context["respond_by"])
settled = Either(Finishes("signed", "walked_away"), Parks("negotiating"))
gate = ApprovedFirst(label="rollout", tools=[open_change_request])
print(on_time.name(), "|", settled.name(), "|", gate.name())
# by: sales.bids.submit_response when <lambda> | either finishes in signed or walked_away or
#  parks in negotiating | approved first: rollout before ops.changes.open_change_request
```

`AnsweredBy(kind, accepts)` checks who answered. When a waiting request is answered, the
deployment's entry point says who gave the answer with `Governor.answer(..., by=principal)`:
a `Principal` (subject, issuer and claims) it authenticated, which is journaled with the
answer ([Trust](../concepts/trust.md#part-2-who-answered)). The check reads it back for every
accepted answer to a request of `kind` (for `request_approval`, the `approved` and `denied`
events), at any depth inside workflows. An answer from nobody named is a problem, and so is
one from a principal that `accepts(principal, request)` refuses. A run with no such answer
passes:

```python
from gvn.harness.events import Principal, Request
from gvn.runtime.evaluation import AnsweredBy


def release_team(principal: Principal, request: Request) -> bool:
    return "release" in principal.claims().get("groups", [])


signed_off = AnsweredBy("request_approval", release_team)
print(signed_off.name())  # answered by: request_approval release_team
```

### What the models were asked

A recorded run holds every request an actor made, and a model call is one of them: its
request carries the instructions, every message, the identities of the tools offered and
the run context that the model was given. Replay re-derives those requests from the recorded events, so a check
can read exactly what each model was told, at any depth inside workflows, without
calling a model. `ModelAsked(label, accepts)` does that. `accepts` is a function of one
`invoke_model` `Request`: `request.origin()` is the name of the actor that asked, and
`request.payload()` is a fresh dict with `"instructions"` (a str), `"messages"` (plain
message dicts, each with `"role"` and `"text"`), `"tools"` (the sorted identities of the
offered tools), `"context"`, and `"model_role"`
when the actor names one. It must return a bool (anything else is a `TypeError`). Every
model call of the run is judged once, however many events it waits across, and each refused
call is one problem naming the label, the event and the origin. Agents, conversations,
choices and the calls that summarise a conversation are all judged the same way. A run that
makes no model call passes.

The commonest rule is about instructions: text you do not trust must never be in them.
Here the untrusted texts are known, and no instructions may contain one:

```python
from gvn.runtime.evaluation import ModelAsked

UNTRUSTED = ("Ignore your instructions", "wire the money")


def instructions_are_clean(request: Request) -> bool:
    instructions = request.payload()["instructions"]
    return not any(text in instructions for text in UNTRUSTED)


clean = ModelAsked("no untrusted text in instructions", instructions_are_clean)
print(clean.name())  # model asked: no untrusted text in instructions
```

When the untrusted text is whatever a person wrote during the run, read it from the same
request instead: compare each `"user"` message's `"text"` with the instructions. The
[tutoring harness](../domains/education.md) does so for every run
(`learner_text_stays_out_of_instructions`).

A check of your own implements `name()` (a short, unique string) and `examine(trace)`.
It sees only what a trace holds: states, events, steps, the requests wanted after each event
and the outcome.

## Step 6: evaluations and scorecards

An `Evaluation` is a named set of checks with distinct names. `grade(trace)` gives a `Grade`
for one run; `score(traces)` a `Scorecard` for many:

```python
from gvn.runtime.evaluation import Evaluation, Finishes, NoRejections, Within

quality = Evaluation(
    name="quality",
    checks=[Finishes("completed"), NoRejections(), Within(events=8)],
)

baseline = quality.score(recorded)
print(baseline.summary())  # quality: 3/3 passed

candidate = quality.score(changed)
print(candidate.summary())
# quality: 1/3 passed
# q2: finishes in completed: ended in failed, expected completed
# q2: no rejections: event 4 (model_replied) was rejected in failed
# q3: finishes in completed: ended in failed, expected completed
# q3: no rejections: event 4 (model_replied) was rejected in failed

print(candidate.regressions(baseline))  # ('q2', 'q3')
```

`regressions(baseline)` names the runs that passed in the baseline and fail now. Runs that
appear in only one scorecard are not counted, so score the same sample before and after.
That is the number to look at before adopting
a change: here, saving turns would have broken every run that used a tool, and the one run
that still passes is the one that never needed a second turn.

Everything here is deterministic and performs no I/O, so a scorecard is the same every time
it is computed from the same journal.

## Putting it to work

- **Before adopting a change**, replay a sample of recorded runs against it and compare
  scorecards. A change with regressions needs a reason.
- **Keep an evaluation next to each harness.** Every harness in
  [gvn-domains](../domains/index.md) has one, and its `Launcher.grade(run_id)` grades a
  recorded run with it.
- **Diff the machines too.** When a change touches a definition, `gvn.kernel.diff.Difference`
  says exactly what changed; see [Diagrams and diffs](diagrams-and-diffs.md).
- **Close the loop.** [Self-improvement](self-improvement.md) shows a harness that
  proposes changes to another harness and trials them this way.

Replay answers what a change would have done with history that already happened. To measure
what a version does on new runs (many examples, each run several times, judged by code, a
model or a person, and two versions compared case by case), use [Evals](../evals/index.md).
Every check on this page can be one of an eval's criteria, unchanged.

## The objects in detail

### Frames and traces

A `Frame` holds:

| Method | What it is |
|---|---|
| `sequence()`, `at()` | the record's position in the journal, and its recorded time |
| `event()` | the `Event` |
| `steps()` | the kernel `Step`s the actor took, internal decisions included |
| `state()` | the name of the actor's state after the event |
| `requests()` | the `Request`s the actor wanted after it (its `pending()`), shared rather than copied |
| `wanted()` | the kinds of those requests, as names |
| `error()` | `None`, or a short description when `handle` raised |
| `rejected()` | whether the event changed nothing (no declared step, or an error) |

Frames are equal by content, requests included (ids and payloads). `divergence` (step 4)
compares behaviour instead, so an actor under another name, whose request ids differ, can
still agree with the recorded run.

A `Trace` has the run's name (`run_id()`), the state before the first frame (`start()`), the
`frames()`, whether it `finished()` and its `outcome()`. `states()` lists the state after each
frame, starting with `start()`, and `rejections()` the rejected frames.

Note that `states()` lists the state an event *left* the actor in. States passed through
inside one event, such as the agent's `admitting` and `interpreting`, appear only in that
frame's `steps()`.

### Grades and scorecards

| Object | What it offers |
|---|---|
| `Grade` | `run_id()`, `passed()`, `problems()` (check name to tuple of problems, failing checks only) |
| `Scorecard` | `evaluation()`, `grades()`, `total()`, `passed()`, `failures()`, `regressions(baseline)`, `summary()` |

### How `Gated` decides

`Gated` reads the request side of the run
(`Frame.requests()`), so it sees every actor that asks for tools with the standard request
kinds, whatever its class: agents, model-free actors that run a fixed batch of calls, and
your own, at any depth inside workflows. For each requesting actor (the request's
`origin()`):

- a new `consult_policy` request starts a batch (the calls of one model reply), with
  nothing approved;
- the batch's calls, the identity of each call's tool and the run context come from the
  `consult_policy` and `invoke_tools` request payloads (each read once, when it first
  appears); a request whose calls do not carry one identity each makes the check raise, and
  the evaluation then raises a `TypeError` naming the check;
- a pending `request_approval` says which calls a person is asked about: the ids in its
  `"calls"`. Since a person is asked only about the calls that need them, that may be fewer
  than the whole batch;
- an accepted `approved` event addressed to that actor approves the calls it was asked about,
  except those its payload denies (`{"denied": [{"call_id", ...}]}`); an unaddressed one does so
  for every actor that was awaiting approval when it arrived;
- an accepted `tools_returned` with a successful result for a gated call is a problem unless
  **that call** was approved. The approvals are then used up, so they never carry over.

So `Gated` judges each call: a gated call that ran beside an approved one, without being asked
about itself, is a problem. A refused call never succeeds, so it is never one.
`ApprovedFirst` and `By` likewise ignore a call that an `invoke_tools` request marks refused,
since it does not run.

## Recap

- `Replay(journal=...).recorded(run_id=..., actor_class=...)` turns a journal into a `Trace`,
  one `Frame` per event; `Trace.usage()` totals its tokens, `usage_by_origin()` and
  `usage_by_model()` split them by actor and by model.
- `replay.against(run_id=..., actor=...)` feeds the same events to a changed actor, and
  `divergence` says where the two part ways.
- An `Evaluation` of checks grades traces into a `Scorecard`, and `regressions(baseline)`
  names what a change broke.

**Next:** to find out why one run went the way it did, actor by actor, read
[Inspecting a run](inspecting-a-run.md); to see what a run would have done with a different
answer or a fresh model call, read [Forking a run](forking-a-run.md); to measure a change on
new runs instead of recorded ones, read [Evals](../evals/index.md).
