# Inspecting a run

This guide reads a recorded run back from its journal (the durable record of every event of
a run) to answer "which actor did what, and when?". At the end you can point at the event
where each actor of a run moved, and at the first event where a changed version of the
harness would have done something else.

A recorded run is a list of events. **Inspection** reads it back actor by actor: for every
journal record, which actor took which step, where every actor of the run stood afterwards,
which actors started or finished, and which requests began and ended. It is what the
[Workbench](../workbench/runs.md) shows on a run page, and you can read the same from Python.

- **You will be able to:** list the runs of a journal, inspect one, read each moment's
  movements and standings, find the moments of one actor, see an actor that started and
  finished within one event, and find the first position at which a changed actor would do
  something else.
- **Read first:** [Workflows](../concepts/workflows.md) and
  [Replay and evaluation](replay-and-evaluation.md), of which inspection is the finer reading.
- **Time:** about 15 minutes.

## Where this fits

In the [big picture](../quickstart.md#the-big-picture), the Governor writes every event of a
run to the **journal**. This guide works on that box alone, after the run: it reads the
records and nothing else, so it needs no model, tool or person. Two readers start from the
same records: replay, which follows the run's own actor, and inspection, which follows
every actor in the run.

```mermaid
flowchart LR
    journal[("Journal<br/>birth snapshot + records")]
    replay["Replay<br/>a Trace: the run's own actor,<br/>frame by frame"]
    inspector["Inspector<br/>an Inspection: every actor,<br/>moment by moment"]
    changed["A changed actor"]
    divergence["divergence()<br/>the first position<br/>where the two differ"]
    journal --> replay
    journal --> inspector
    changed --> inspector
    inspector --> divergence
```

[Replay](replay-and-evaluation.md) reads a run as a `Trace`: for every event, the steps it
caused and the state of the run's own actor. That is enough to grade a run, not to look into
one. A [workflow](../concepts/workflows.md) (an actor whose states run other actors, its
children) hosts actors, those may host others, and one event moves several of them at
once: an answer finishes a child, and its finishing moves the workflow.

`gvn.runtime.inspection` reads the same records into an `Inspection`. Like replay, it only calls
`actor.handle`: it fulfils nothing, journals nothing and emits nothing, and it reads stored forms
exactly as replay does.

| Object | What it is |
|---|---|
| `Inspector(journal)` | reads runs from a journal: `recorded(run_id, actor_class)` as they happened, `against(run_id, actor)` fed to a changed actor |
| `Inspection` | a whole run: its `moments()`, `start()` and `standings()`, `finished()` and `outcome()`, the `actors()` that ever stood in it, `of(name)`, `at(sequence)`, `divergence(other)` |
| `Moment` | one record: `sequence()`, `at()`, `event()`, `movements()`, `standings()`, `began()`, `ended()`, `pending()`, `rejected()`, `error()` |
| `Movement` | what one actor did on one event: `before()`, `after()`, `steps()`, `started()`, `left()`, `ended()` |
| `Standing` (in `gvn.harness.actor`) | where one actor stands: its `name()`, the `definition()` it runs on, its `state()`, and `finished()` |

## Step 1: record a run

The run to inspect is a two-stage workflow: a drafting agent, then a polishing agent that
rewrites the draft. The model is a `FunctionModel`, a fake whose reply is a function of the
question; here it wraps the prompt in `<...>`.

```python
import asyncio
from collections.abc import Callable

from gvn.harness.agent import Agent
from gvn.harness.events import Event
from gvn.harness.messages import Message
from gvn.harness.ports import Exchange, Reply
from gvn.harness.tools import Toolbox
from gvn.harness.workflow import Host, Memo, Plan, Workflow
from gvn.kernel.blueprint import MooreBlueprint
from gvn.kernel.symbols import Alphabet
from gvn.runtime.fulfillers import ModelFulfiller
from gvn.runtime.governor import Governor
from gvn.testing.fakes import FunctionModel, ManualClock, MemoryJournal, RecordingOutput

NOTE_MACHINE = (
    MooreBlueprint(name="note")
    .inputs("started", "drafted", "draft_failed", "polished", "polish_failed")
    .outputs("idle", "draft", "polish", "done", "failed")
    .state(name="idle", output="idle")
    .state(name="drafting", output="draft")
    .state(name="polishing", output="polish")
    .state(name="done", output="done", final=True)
    .state(name="failed", output="failed", final=True)
    .initial(name="idle")
    .on(source="idle", input="started", target="drafting")
    .branch(
        source="drafting",
        outcomes=Alphabet.of("drafted", "draft_failed"),
        routes={"drafted": "polishing", "draft_failed": "failed"},
    )
    .branch(
        source="polishing",
        outcomes=Alphabet.of("polished", "polish_failed"),
        routes={"polished": "done", "polish_failed": "failed"},
    )
    .otherwise_stay()
    .build()
)


def writer(role: str, reached: str, missed: str, prompt: Callable[[Memo], str]) -> Host:
    return Host(
        actor_class=Agent,
        make=lambda name, memo: Agent(name=name, instructions=f"You {role}.", turns=2),
        start=lambda memo: Event("started", payload={"prompt": prompt(memo)}),
        routes={"completed": reached, "failed": missed, "overflowed": missed},
    )


def draft_prompt(memo: Memo) -> str:
    return memo.input()["topic"]


def polish_prompt(memo: Memo) -> str:
    return memo.results("drafting")[0].payload()["text"]


class Note(Workflow):
    @classmethod
    def plan(cls) -> Plan:
        return Plan(
            definition=NOTE_MACHINE,
            stages={
                "drafting": writer("draft", "drafted", "draft_failed", draft_prompt),
                "polishing": writer("polish", "polished", "polish_failed", polish_prompt),
            },
        )


def wrap(exchange: Exchange) -> Reply:
    return Reply(message=Message.assistant(text=f"<{exchange.messages()[0].text()}>"))


journal = MemoryJournal()
governor = Governor(
    fulfillers={"invoke_model": ModelFulfiller(model=FunctionModel(respond=wrap), toolbox=Toolbox())},
    journal=journal,
    output=RecordingOutput(),
    clock=ManualClock(),
)
asyncio.run(governor.deliver(actor=Note(name="note-1"), event=Event("started", payload={"topic": "Moore"})))
print(asyncio.run(journal.runs()))  # ('note-1',)
```

`Journal.runs(after=None, limit=None)` gives the ids of the runs a journal holds, in code point
order. `after` leaves out every id not greater than it and `limit` keeps at most that many, so a
long journal is read a page at a time. Every journal gvn ships answers it, and
`JournalContract` checks it for a journal of your own.

## Step 2: inspect it

`Inspector(journal).recorded(run_id, actor_class)` rebuilds the actor from the run's first
snapshot and hands it every record again, exactly as recovery does:

```python
from gvn.runtime.inspection import Inspector

inspection = asyncio.run(Inspector(journal).recorded("note-1", Note))
print(inspection.finished(), inspection.outcome().state().name(), len(inspection))
print(inspection.actors())
for moment in inspection.moments():
    print(moment.sequence(), moment.event().name(), moment.event().to())
    for movement in moment.movements():
        steps = [f"{step.source().name()}->{step.target().name()}" for step in movement.steps()]
        print("   ", movement.name(), movement.started(), movement.left(), movement.ended().name(), steps)
```

```text
True done 3
('note-1', 'note-1/drafting.1', 'note-1/polishing.1')
0 started None
    note-1 False False drafting ['idle->drafting']
    note-1/drafting.1 True False thinking []
1 model_replied note-1/drafting.1
    note-1/drafting.1 False True completed ['thinking->interpreting', 'interpreting->completed']
    note-1 False False polishing ['drafting->polishing']
    note-1/polishing.1 True False thinking []
2 model_replied note-1/polishing.1
    note-1/polishing.1 False True completed ['thinking->interpreting', 'interpreting->completed']
    note-1 False False done ['polishing->done']
```

Read moment 1: the model's reply arrived for the drafter, which went to `completed` and left; its
ending moved the workflow from `drafting` to `polishing`; and the polisher started, in
`thinking`. One event, three actors.

A `Movement` says:

- `before()` and `after()`: the actor's state before and after the event; `before()` is None
  for an actor that started on it, `after()` None for one no longer hosted after it;
- `steps()`: the steps it took, in order, each with its source, input, target, output and
  whether it was declared;
- `started()` and `left()`: whether it started on this event, and whether it is no longer hosted
  after it;
- `ended()`: the state it was in when the event had been handled.

The movements come in a fixed order: the actors that took steps, by their first step, then the
actors that passed (below), then those that started, then those that left without a step.

A moment is `rejected()` when the event changed nothing, and has an `error()` when `handle`
raised for it; a recorded run has none unless the actor's code changed since.

## Step 3: standings, and one actor's moments

A **standing** is where one actor stands: its name, the definition it runs on, and its state.
`Moment.standings()` lists every actor of the run once the moment is handled: the run's own actor
first, then each actor it hosts, each followed by those it hosts in turn.
`Inspection.at(sequence)` is the same for a position, and `Inspection.of(name)` the moments in
which one actor moved:

```python
print(inspection.at(1))
print([moment.sequence() for moment in inspection.of("note-1/polishing.1")])
print([moment.sequence() for moment in inspection.of("note-1/drafting.1")])
```

```text
(Standing('note-1', 'note', 'polishing'), Standing('note-1/polishing.1', 'agent', 'thinking'))
[1, 2]
[0, 1]
```

`of(name, beneath=True)` also counts the moments of every actor hosted beneath `name`.

Standings come from the actors themselves: `Actor.standings()` answers an actor's own standing
and those of every actor it hosts now. `Workflow` answers for its active children, and `Agent`
for the definition it was built with, which for an agent with a
[structured answer](structured-answers.md) is not its class's own. A diagram of any actor in the
run can be drawn in the state it had at any position from these.

## Actors that pass within one event

Some actors start and finish while one event is handled: an actor that decides at once, or a
chain of such stages. Such an actor stands neither before nor after the event, so standings
alone would miss it. A workflow reports it in its `Reaction` (`Reaction.passed()`: each such
actor as a `Standing` at its final state, in the order they finished), and the inspection gives
it a movement with `before()` and `after()` None, `started()` and `left()` True, and `ended()`
its final state.

Here a filing workflow's first stage hosts a child workflow that is stamped the moment it
starts:

```python
STAMP_MACHINE = (
    MooreBlueprint(name="stamp")
    .inputs("started")
    .outputs("idle", "stamped")
    .state(name="idle", output="idle")
    .state(name="stamped", output="stamped", final=True)
    .initial(name="idle")
    .on(source="idle", input="started", target="stamped")
    .otherwise_stay()
    .build()
)


class Stamp(Workflow):
    @classmethod
    def plan(cls) -> Plan:
        return Plan(definition=STAMP_MACHINE, stages={})


FILING_MACHINE = (
    MooreBlueprint(name="filing")
    .inputs("started", "stamped", "stamp_failed")
    .outputs("idle", "stamp", "done", "failed")
    .state(name="idle", output="idle")
    .state(name="stamping", output="stamp")
    .state(name="done", output="done", final=True)
    .state(name="failed", output="failed", final=True)
    .initial(name="idle")
    .on(source="idle", input="started", target="stamping")
    .branch(
        source="stamping",
        outcomes=Alphabet.of("stamped", "stamp_failed"),
        routes={"stamped": "done", "stamp_failed": "failed"},
    )
    .otherwise_stay()
    .build()
)


class Filing(Workflow):
    @classmethod
    def plan(cls) -> Plan:
        stamping = Host(
            actor_class=Stamp,
            make=lambda name, memo: Stamp(name=name),
            start=lambda memo: Event("started"),
            routes={"stamped": "stamped"},
        )
        return Plan(definition=FILING_MACHINE, stages={"stamping": stamping})


filings = MemoryJournal()
filing_governor = Governor(fulfillers={}, journal=filings, output=RecordingOutput(), clock=ManualClock())
asyncio.run(filing_governor.deliver(actor=Filing(name="filing-1"), event=Event("started")))
filed = asyncio.run(Inspector(filings).recorded("filing-1", Filing))
for movement in filed.moment(0).movements():
    print(movement.name(), movement.before(), movement.after(), movement.started(), movement.left(), movement.ended())
print(filed.actors())
```

```text
filing-1 State('idle') State('done') False False State('done')
filing-1/stamping.1 None None True True State('stamped')
('filing-1', 'filing-1/stamping.1')
```

The stamp never stands anywhere, yet it is listed: it passed in moment 0 and ended `stamped`, and
the filing's own steps show what its ending caused, `idle` → `stamping` → `done` in the same
moment. The release review's `ChecklistGate` passes the same way in every run's first moment.

## Against a change

`Inspector.against(run_id, actor)` feeds the recorded events of a run to an actor you built,
fresh, and returns its inspection. `recorded(...).divergence(against(...))` is the first journal
position at which the changed actor does something else, or None when it never does. Here a
stricter note treats every draft as a failure:

```python
class StrictNote(Workflow):
    @classmethod
    def plan(cls) -> Plan:
        return Plan(
            definition=NOTE_MACHINE,
            stages={
                "drafting": writer("draft", "draft_failed", "draft_failed", draft_prompt),
                "polishing": writer("polish", "polished", "polish_failed", polish_prompt),
            },
        )


changed = asyncio.run(Inspector(journal).against("note-1", StrictNote(name="note-1")))
position = inspection.divergence(changed)
print(position)
print(inspection.moment(position).movement("note-1").after(), changed.moment(position).movement("note-1").after())
print(changed.outcome().state(), changed.moment(2).rejected())
```

```text
1
State('polishing') State('failed')
State('failed') True
```

At position 1 the recorded run moved to `polishing` and the changed one to `failed`. From there
the changed run is finished, so the polisher's reply at position 2 is rejected. Two moments
differ when they differ in being rejected, in whether `handle` raised, in their movements (actor
names relative to each run's own actor, states, steps and where each ended) or in the kinds of
the requests that began and ended. Only moments are compared, never `start()`.

As with replay, the recorded replies are reused: a changed actor that would ask the model
something else is fed the old answer. Divergence shows changes in the machine and in how a
workflow reads its children; what a model would answer to a changed request needs fresh runs
([Evals](../evals/index.md)). The Workbench's replay view is this call, for a version the project
offers ([Evaluating a change](../workbench/evaluating-a-change.md)).

## Recap

- `Journal.runs` lists a journal's runs, in pages.
- `Inspector(journal).recorded(run_id, actor_class)` reads a run as an `Inspection`: one
  `Moment` per record, each with every actor's `Movement`, every `Standing`, and the requests
  that began, ended and remain.
- An actor that starts and finishes within one event appears as a movement that both started
  and left, ending in its final state (`Reaction.passed`).
- `Inspector.against(run_id, actor)` and `Inspection.divergence` give the first position at which
  a changed actor does something else.

**Next:** to carry a run on from the position you found, with a different answer or a fresh
model call, read [Forking a run](forking-a-run.md); to grade many recorded runs against a
change at once, read [Replay and evaluation](replay-and-evaluation.md#step-4-replay-against-a-change).
