# gvn.harness

Actors and what they are made of: agents, workflows, tools, messages, events and requests, plus the ports, which are the interfaces the outside world implements. It builds on the kernel and does no I/O.

The ideas behind it are explained in [Actors and events](../../concepts/actors-and-events.md), [Workflows](../../concepts/workflows.md), [Interface contracts](../interfaces.md). This page is generated from the source, so it lists every public name with its signature and docstring. [Python API](../python.md) has the other packages and an index of every name.

## Modules

| Module | What it holds | Names |
|---|---|---|
| [`gvn.harness.actor`](#gvn.harness.actor) | Actors: the unit the runtime drives | [`NotFinished`](#NotFinished), [`Outcome`](#Outcome), [`Reaction`](#Reaction), [`Standing`](#Standing), [`Actor`](#Actor) |
| [`gvn.harness.agent`](#gvn.harness.agent) | The reference agent: a model that may call tools, under a policy, a turn budget and a context budget | [`Agent`](#Agent) |
| [`gvn.harness.answering`](#gvn.harness.answering) | Answering: who may answer a request that waits on the outside world | [`NotEntitled`](#NotEntitled), [`Answering`](#Answering), [`Authenticated`](#Authenticated) |
| [`gvn.harness.approval`](#gvn.harness.approval) | Approval: an actor that asks a person to approve one named thing and ends approved or declined | [`Approval`](#Approval) |
| [`gvn.harness.budget`](#gvn.harness.budget) | A budget of model turns | [`BudgetExhausted`](#BudgetExhausted), [`Budget`](#Budget) |
| [`gvn.harness.choice`](#gvn.harness.choice) | Choice: a model picks one of a finite, declared set of options | [`answer_for`](#answer_for), [`Choice`](#Choice), [`Chosen`](#Chosen) |
| [`gvn.harness.context_window`](#gvn.harness.context_window) | The context window: how full it is, an actor's budget for it, and how to reduce it | [`recalled_note`](#recalled_note), [`is_recalled_note`](#is_recalled_note), [`model_role_checked`](#model_role_checked), [`recall_checked`](#recall_checked), [`recall_limit_checked`](#recall_limit_checked), [`transcribed`](#transcribed), [`ContextGauge`](#ContextGauge), [`Reduction`](#Reduction), [`ClearToolResults`](#ClearToolResults), [`KeepRecent`](#KeepRecent), [`Summarise`](#Summarise), [`ContextBudget`](#ContextBudget), [`context_budget`](#context_budget), [`ContextCheck`](#ContextCheck), [`FailureCheck`](#FailureCheck) |
| [`gvn.harness.conversation`](#gvn.harness.conversation) | Conversation: an actor that talks with a person over many turns | [`Closing`](#Closing), [`Conversation`](#Conversation) |
| [`gvn.harness.errand`](#gvn.harness.errand) | Errands: tool calls fixed by code, made under the policy, with no model | [`Errand`](#Errand) |
| [`gvn.harness.events`](#gvn.harness.events) | Events and requests: the payload-carrying counterparts of kernel symbols | [`TooLate`](#TooLate), [`Principal`](#Principal), [`Event`](#Event), [`Request`](#Request) |
| [`gvn.harness.inquiry`](#gvn.harness.inquiry) | Inquiries: asking someone outside for content and waiting for the answer | [`Inquiry`](#Inquiry) |
| [`gvn.harness.messages`](#gvn.harness.messages) | Conversation content: messages, tool calls, tool results and attachments | [`Attachment`](#Attachment), [`ToolCall`](#ToolCall), [`ToolResult`](#ToolResult), [`result_attachments`](#result_attachments), [`Message`](#Message) |
| [`gvn.harness.ports`](#gvn.harness.ports) | Ports: what the harness needs from the outside world | [`Signal`](#Signal), [`Output`](#Output), [`Progress`](#Progress), [`Quiet`](#Quiet), [`ModelFailure`](#ModelFailure), [`Exchange`](#Exchange), [`Reply`](#Reply), [`Model`](#Model), [`MemoryFailure`](#MemoryFailure), [`Memory`](#Memory), [`Fulfiller`](#Fulfiller), [`Journal`](#Journal), [`PositionTaken`](#PositionTaken), [`LeaseLost`](#LeaseLost), [`Lease`](#Lease), [`Leases`](#Leases), [`Clock`](#Clock), [`Throttle`](#Throttle), [`Retry`](#ports.Retry) |
| [`gvn.harness.replies`](#gvn.harness.replies) | Model replies: the payloads that answer ``invoke_model``, and structured answers | [`answer_plain`](#answer_plain), [`answer_from_plain`](#answer_from_plain), [`parse_answer`](#parse_answer) |
| [`gvn.harness.sensors`](#gvn.harness.sensors) | Sensors: fixed measurements an actor takes after a watched tool succeeds | [`kept_text`](#kept_text), [`Sensor`](#Sensor), [`readings_note`](#readings_note), [`blocked_note`](#blocked_note), [`is_sensor_note`](#is_sensor_note), [`SensorCheck`](#SensorCheck), [`SensorReadings`](#SensorReadings) |
| [`gvn.harness.timer`](#gvn.harness.timer) | Timers: an actor that waits until a time and ends ``elapsed`` | [`Timer`](#Timer) |
| [`gvn.harness.tools`](#gvn.harness.tools) | Tools: work an actor can ask for, referred to by object and stored by identity | [`denied_detail`](#denied_detail), [`attempt`](#attempt), [`assistant_reply`](#assistant_reply), [`tool_results`](#tool_results), [`answering`](#answering), [`ran_statuses`](#ran_statuses), [`abandoned`](#abandoned), [`settled`](#settled), [`calls_payload`](#calls_payload), [`untrusted_of`](#untrusted_of), [`exposed_by`](#exposed_by), [`exposure_stored`](#exposure_stored), [`exposure_revived`](#exposure_revived), [`route`](#route), [`asked`](#asked), [`judged`](#judged), [`denials`](#denials), [`standing`](#standing), [`refusal_detail`](#refusal_detail), [`refused`](#refused), [`approval_payload`](#approval_payload), [`invoke_payload`](#invoke_payload), [`verdicts_stored`](#verdicts_stored), [`verdicts_revived`](#verdicts_revived), [`returned`](#returned), [`namespace_checked`](#namespace_checked), [`identity_checked`](#identity_checked), [`short_name`](#short_name), [`tool_checked`](#tool_checked), [`tools_given`](#tools_given), [`identities_held`](#identities_held), [`is_call_to`](#is_call_to), [`calls_to`](#calls_to), [`identified_calls`](#identified_calls), [`UnknownTool`](#UnknownTool), [`tool_error`](#tool_error), [`ToolFailure`](#ToolFailure), [`Tool`](#Tool), [`ToolOutput`](#ToolOutput), [`ToolSpec`](#ToolSpec), [`Toolbox`](#Toolbox), [`FixedCall`](#FixedCall), [`run_context`](#run_context), [`Invocation`](#Invocation), [`Consultation`](#Consultation), [`exposure_checked`](#exposure_checked), [`spec_plain`](#spec_plain), [`spec_from_plain`](#spec_from_plain), [`record_from_json_schema`](#record_from_json_schema) |
| [`gvn.harness.transcript`](#gvn.harness.transcript) | The transcript: the ordered record of a conversation, owned by one actor | [`Transcript`](#Transcript) |
| [`gvn.harness.workflow`](#gvn.harness.workflow) | Workflows: actors made of other actors | [`At`](#At), [`After`](#After), [`Result`](#Result), [`Abandoned`](#Abandoned), [`Memo`](#Memo), [`Ending`](#Ending), [`Report`](#Report), [`Join`](#Join), [`AllOf`](#AllOf), [`AnyOf`](#AnyOf), [`Majority`](#Majority), [`AtLeast`](#AtLeast), [`Quorum`](#Quorum), [`Worst`](#Worst), [`Host`](#Host), [`FanOut`](#FanOut), [`Retry`](#workflow.Retry), [`ForEach`](#ForEach), [`Branch`](#Branch), [`Parallel`](#Parallel), [`SettingsMismatch`](#SettingsMismatch), [`PlanRejected`](#PlanRejected), [`Compensate`](#Compensate), [`Plan`](#Plan), [`Workflow`](#Workflow) |

## gvn.harness.actor

Actors: the unit the runtime drives.

An actor turns events into requests and never performs I/O. It owns a machine
(control state) and whatever data it needs, and is Durable as a whole. The
built-in Agent is one actor; workflows and domain harnesses are others. The
runtime knows only this interface.

Internal and external outputs. A machine state's output either names work for
the outside world (it becomes a Request) or names a decision the actor makes
itself, synchronously and without I/O, from its own data. After each step the
actor resolves internal outputs immediately by feeding the decision's outcome to
its machine, and repeats until it reaches an output that is external or names no
work. One ``handle`` call can therefore take several steps.

### NotFinished

```python
from gvn.harness.actor import NotFinished
```

An outcome was asked of an actor that has not reached a final state.

### Outcome

```python
from gvn.harness.actor import Outcome
```

```text
Outcome(state: State, payload: typing.Any = None) -> None
```

How an actor ended: the final state it reached and its result data. Immutable value.

The payload is validated and held once. ``payload()`` hands out a fresh copy the
caller may change; ``view()`` hands out one shared read-only form, built on first
use, for code that only reads.

#### Outcome.state

```text
state() -> State
```

#### Outcome.payload

```text
payload() -> typing.Any
```

The payload as plain JSON: a fresh copy, so changing it changes nothing here.

#### Outcome.view

```text
view() -> typing.Any
```

The payload as a read-only form (mappings are read-only, lists are tuples).

Built once and shared: reading it copies nothing, and nothing can change it.

#### Outcome.to_dto

```text
to_dto() -> Dto
```

A Dto capturing the complete internal state. Does not mutate the object.

#### Outcome.from_dto

```text
from_dto(dto: Dto) -> typing.Self
```

### Reaction

```python
from gvn.harness.actor import Reaction
```

```text
Reaction(
    steps: Iterable[Step],
    requests: Iterable[Request] = (),
    origins: Iterable[str] = (),
    passed: Iterable[Standing] = (),
) -> None
```

What handling one event did. Immutable value.

``steps`` is a tuple of kernel Steps: the step taken for the event, then any
steps taken resolving internal outputs. It is empty only for an ignored
reaction (see ``ignored``). ``requests`` is a tuple of Request: ALL the
requests the actor wants after this event, not only new ones. Law every Actor
keeps: after any ``handle`` call, ``reaction.requests() == actor.pending()``.

``origins`` says which actor took each step. An actor that hosts others returns
the steps of the actor beneath it that handled the event before its own, so it
names an actor for every step: a tuple of actor names as long as ``steps``. An
actor that took every step itself leaves it empty (the default); whoever reads
the reaction knows which actor returned it (``attributed``).

``passed`` names the actors that started and finished while this event was handled:
an actor that hosts others may start one that finishes at once (a child whose
decision is internal), so it stands neither before nor after the event, and the
steps it took on its opening event are not among ``steps``. Each is a Standing at
the final state it ended in, in the order they finished. An actor that started and
still stands after the event is not passed (its host's ``standings()`` list it).
Empty (the default) for an actor that hosts nothing.

#### Reaction.ignored

```text
ignored(requests: Iterable[Request] = ()) -> typing.Self
```

A reaction with no steps (the event changed nothing), carrying ``requests``.

#### Reaction.steps

```text
steps() -> tuple[Step, ...]
```

#### Reaction.requests

```text
requests() -> tuple[Request, ...]
```

The tuple of Requests the actor wants after the event (possibly empty).

#### Reaction.origins

```text
origins() -> tuple[str, ...]
```

The name of the actor that took each step, in step order; empty when the
actor that returned this reaction took them all (see ``attributed``).

#### Reaction.attributed

```text
attributed(name: str) -> tuple[tuple[str, Step], ...]
```

Every step with the name of the actor that took it, in step order.

``name`` is the name of the actor that returned this reaction (a non-empty
str): the steps are its own unless ``origins`` says otherwise.

#### Reaction.passed

```text
passed() -> tuple[Standing, ...]
```

The actors that started and finished while the event was handled, each as a
Standing at its final state, in the order they finished; empty when none did.

#### Reaction.request

```text
request() -> Request | None
```

Convenience: the single request, or None when there are none.

Raises ValueError when there are several.

#### Reaction.rejected

```text
rejected() -> bool
```

True when there are no steps or the event's own step (the first) was not declared.

A rejected event changed nothing in the actor. A rejected reaction may still
carry requests: what the actor wanted before it still wants.

### Standing

```python
from gvn.harness.actor import Standing
```

```text
Standing(name: str, definition: Definition, state: State) -> None
```

Where one actor stands at one moment: its name, the Definition it runs on and
the State it is in. Immutable value.

This is how an actor is read from outside without touching what it holds: a
diagram draws ``definition()`` and marks ``state()``; a hosted actor is told
from its host by ``name()`` (a hosted actor's name starts with its host's name
and ``/``).

#### Standing.name

```text
name() -> str
```

#### Standing.definition

```text
definition() -> Definition
```

#### Standing.state

```text
state() -> State
```

#### Standing.finished

```text
finished() -> bool
```

True when ``state()`` is a final state of ``definition()``.

### Actor

```python
from gvn.harness.actor import Actor
```

```text
Actor()
```

Implement this to make something the Governor can drive.

#### Actor.name

```text
name() -> str
```

The actor's address: a non-empty str, stable for its whole life.

#### Actor.handle

```text
handle(event: Event) -> Reaction
```

Consume an Event and return the Reaction. Synchronous, no I/O.

Raises UnknownSymbol when the event's name is not in the actor's input
alphabet, and ValueError when its payload does not fit what that input
requires; in both cases the actor is unchanged. An event that is valid but
not expected in the current state is not an error: it returns a rejected
Reaction and changes nothing, data included.

Addresses: an event whose ``to()`` is neither None, the actor's own name nor
(for composite actors) the name of something beneath it raises ValueError and
changes nothing. After the call, ``reaction.requests() == self.pending()``.

#### Actor.pending

```text
pending() -> tuple[Request, ...]
```

The tuple of Requests the actor wants from the outside world (empty when none).

In a stable order. Equal to the requests of the Reaction returned by the latest
``handle`` call, with the same ids. This is what lets work be re-issued after a
crash: a revived actor still knows what it was waiting for.

#### Actor.definition

```text
definition() -> Definition
```

The kernel Definition of the actor's control machine.

Callable on the class without an instance; implementations may be static
or class methods.

#### Actor.state

```text
state() -> State
```

The current control State.

#### Actor.standings

```text
standings() -> tuple[Standing, ...]
```

Where this actor stands, and every actor it is hosting at this moment.

A tuple of Standing: this actor's own first, then one for each actor it hosts
now, in hosting order, each followed by those it hosts in turn. Actors that
have finished and are no longer hosted are not listed. Answered without I/O
and without changing anything.

This default answers this actor alone, on ``definition()``. An actor built on
another definition than the one its class answers (the reference Agent with a
structured answer), or one that hosts actors (a Workflow), answers for itself
here.

#### Actor.expected

```text
expected() -> frozenset[Symbol]
```

Frozenset of the Symbols with a declared transition from the current state.

#### Actor.finished

```text
finished() -> bool
```

True when the control state is final.

#### Actor.settles

```text
settles(event: Event) -> bool
```

Could handling ``event`` now leave this actor finished? Does not change anything.

A composite actor asks this of a child before handing it an event, and keeps
what it needs to undo the child only when the answer is True. So the answer
must never be False when the event could finish the actor; True is always
safe. This default answers True. An actor that knows better (from its
definition: an event that cannot reach a final state before the actor stops
to wait for outside work) may answer False to make its hosts cheaper.

#### Actor.model_roles

```text
model_roles() -> frozenset[str]
```

Frozenset of the model roles (``model_role=``) this actor, and
anything it will ever build beneath it, may ask a model fulfiller for. Constant
for the actor's life and answered without I/O, so the wiring can be checked
against it before the actor handles its first event (``Fulfiller.unmet``). This
default answers none; an actor that names a role, or hosts actors that do, says
so here. An actor that asks for a role it did not declare is a programming error.

#### Actor.tool_identities

```text
tool_identities() -> frozenset[str]
```

Frozenset of the identities (``Tool.identity()``) of every tool this actor, and
anything it will ever build beneath it, may ask to have run or offer a model.
Constant for the actor's life and answered without I/O, so the wiring is checked
against it before the actor handles its first event (``Fulfiller.unmet``): the
tool fulfiller reports the identities its toolbox does not hold. This default
answers none; an actor offered tools, or hosting actors that are, says so here.

#### Actor.sensor_identities

```text
sensor_identities() -> frozenset[str]
```

Frozenset of the identities of the measuring tools (gvn.harness.sensors) this
actor, and anything it will ever build beneath it, may ask to have read. Constant
for the actor's life and answered without I/O, so the wiring is checked against it
before the actor handles its first event: the sensor fulfiller reports the
identities its toolbox does not hold, and an actor that names any is refused when
no fulfiller serves ``sense``. This default answers none; an actor built with
sensors, or hosting actors that are, says so here.

#### Actor.interruptible

```text
interruptible() -> bool
```

True when this actor takes the ``interrupted`` input: its machine declares it,
or (a composite actor) it hands it to what it hosts. Answered without I/O and
without changing anything; constant for the actor's life. The Governor asks it
before it drives an actor under an allowance, since reaching an allowance is
delivered as ``interrupted``. This default answers from ``definition()``: whether
``interrupted`` is one of its inputs.

#### Actor.outcome

```text
outcome() -> Outcome
```

The Outcome. Raises NotFinished unless ``finished()``.

## gvn.harness.agent

The reference agent: a model that may call tools, under a policy, a turn budget and a
context budget.

Control flow is the Moore machine below. Outputs marked (internal) are decisions
the agent resolves itself, synchronously, inside ``handle`` (see gvn.harness.actor);
the others become Requests. ``idle``, ``suspended`` and the final states name no work.

    state              output                        input -> next state
    idle               idle                          started -> admitting
    admitting          check_budget (internal)       within_budget -> measuring
                                                     budget_exhausted -> failed
    measuring          check_context (internal)      recall_due -> recalling
                                                     context_fits -> thinking
                                                     remember_due -> remembering
                                                     trim_due -> measuring
                                                     summary_due -> summarising
                                                     context_exhausted -> overflowed
    recalling          recall                        recalled -> measuring
                                                     recall_failed -> measuring
    remembering        remember                      remembered -> measuring
                                                     remember_failed -> measuring
    summarising        invoke_model                  model_replied -> measuring
                                                     model_failed -> measuring
    thinking           invoke_model                  model_replied -> interpreting
                                                     model_failed -> diagnosing
    diagnosing         classify_failure (internal)   failure_final -> failed
                                                     context_exceeded -> admitting
    interpreting       classify_reply (internal)     answered -> completed
                                                     answered_while_blocked -> admitting
                                                     requested_tools -> vetting
                                                     requested_unoffered -> admitting
    vetting            consult_policy                cleared -> acting
                                                     needs_approval -> awaiting_approval
                                                     forbidden -> admitting
    awaiting_approval  request_approval              approved -> acting
                                                     denied -> admitting
    acting             invoke_tools                  tools_returned -> checking_sensors
    checking_sensors   check_sensors (internal)      sensors_due -> sensing
                                                     nothing_due -> admitting
    sensing            sense                         sensed -> admitting
                                                     sense_failed -> admitting
    suspended          suspended                     resumed -> checking_sensors
    completed (final)  completed
    failed (final)     failed
    overflowed (final) overflowed

``interrupted`` is declared in recalling, remembering, summarising, thinking, vetting,
awaiting_approval, acting and sensing, and leads to suspended. Everything else is covered by
``otherwise: stay``. The five internal decisions and the policy verdict are routed with
``branch``, so the verifier holds the machine to every outcome. The five states with an
internal output (admitting, measuring, diagnosing, interpreting, checking_sensors) are left
within the ``handle`` call that entered them: an agent is never at rest in one of them.

Structured answers (``answer=``). An agent built with an ``answer`` (a kernel Record)
runs on a second definition, ``Agent.answering_definition()``: the table above plus
one outcome of classify_reply,

    interpreting       classify_reply (internal)     answer_invalid -> failed

classify_reply answers ``answer_invalid`` when the reply has no tool calls and its text
is not one JSON value the Record admits (gvn.harness.replies.parse_answer); a reply
that does is ``answered``. The model is asked for the answer through the vendor's own
structured output (the request carries the Record, see below), so ``answer_invalid``
is the declared route for a reply the vendor's guarantee did not cover; it is checked
by gvn all the same and never retried. Tool rounds come first: a reply with tool calls
is not an answer. An agent without an answer runs on ``Agent.definition()``.

Context budget (``context_budget=``, gvn.harness.context_window). The
model owns its context window; the agent owns a ``ContextBudget`` for it (fixed when the
agent is built; ``ContextBudget()`` when none is given: nothing is reduced) and a
``ContextGauge`` that measures the conversation from journaled replies. The agent never
counts tokens: the size is the last reply's reported ``input_tokens + output_tokens``.
A budget built with ``remember_dropped=True`` hands what a reduction is about to drop to a
memory first: the agent never touches a memory, it asks for ``remember``
and the runtime fulfils it.

Automatic recall (``recall=``, ``recall_limit=``; off by default). A model recalls through
a tool when it decides to. An agent built with ``recall=True`` also asks a memory itself,
once, for entries that match its prompt, before its model is first called: ``started``
with a prompt whose text is not blank makes it owe a recall, and check_context answers
``recall_due`` (``ContextCheck(..., recall_owed=True)``) before it checks the context, so
the budget measures what the recall added. A blank prompt owes none, and with
``recall=False`` nothing of this happens: the requests, events and routes are the ones an
agent without the option has. The query is the prompt's text: data for the memory, from
the person. The scope is not in the request: the runtime's fulfiller resolves it from
trusted wiring, as for ``remember``. What comes back is untrusted: it enters the
transcript only as one user message whose text is
``gvn.harness.context_window.recalled_note`` of the entries' texts (the fixed header
``RECALLED`` first), never in ``instructions`` and never as an instruction message.

Sensors (``sensors=``, gvn.harness.sensors). A sensor is gvn's post-tool hook: a fixed
measurement the harness author attaches, "after ``write_file`` succeeds, read ``lint``".
After every batch the agent passes through checking_sensors (``SensorCheck`` over the
sensors owed a reading); a sensor is owed one when a tool it watches succeeded in the batch,
once per batch. sensing asks for every owed reading with one ``sense`` request, served by
the runtime from the sensor toolbox (never the model's tools, never the policy); the
readings come back journaled in ``sensed`` and reach the model as ONE user message
(``gvn.harness.sensors.readings_note``, under the fixed header ``READINGS``), never in
``instructions``. A sensor built with ``blocks=True`` whose latest reading is not clean
keeps the agent from finishing: classify_reply answers ``answered_while_blocked`` for a
reply that would complete the run, the agent appends a user message naming the sensors
(``blocked_note``) and goes back through admitting, so the turn budget bounds it. An agent
without sensors takes the same routes as one built before sensors existed: checking_sensors
answers ``nothing_due`` (one more step after each batch and after each resume).

Model role (``model_role=``). None, or the name of the role whose model
the runtime wiring asks (``[A-Za-z][A-Za-z0-9_-]*``, not a vendor's model id). A role
that is not None travels in every ``invoke_model`` payload as ``"model_role"``; a
summary asks the summarising step's role, else the agent's (no key when both are None).

Event payloads (anything else is a ValueError from ``handle``):

    started            {"prompt": str, "attachments": [<plain form of Attachment.Dto>...]}
                       "attachments" optional: images and documents sent with the prompt
    model_replied      {"message": <plain form of an assistant Message.Dto>,
                        "usage": {"input_tokens": int >= 0, "output_tokens": int >= 0,
                                  "cache_read_tokens": int >= 0,
                                  "cache_write_tokens": int >= 0},
                        "context_window": int >= 1}
                       gvn.harness.replies' MODEL_REPLIED. "usage" (its two cache figures
                       too) and "context_window" optional: in thinking they measure the
                       conversation (see the data rules); a summary reply's are not a
                       measurement and are ignored. The message's sealed content never
                       routes and never reaches the policy, an approver, a tool, a
                       summariser or the outcome. "retries" optional: recorded, never used.
    model_failed       {"reason": str} and optionally "retryable", "retry_after", "usage",
                       "retries" (recorded, never used) and "exceeded_context" (true: the
                       vendor refused the conversation as too large; it routes, through
                       classify_failure)
    tools_returned     {"results": [<plain form of ToolResult.Dto>, ...]}  one per pending call
    cleared, needs_approval, forbidden
                       None (that verdict for every call) or {"verdicts": [<one of VERDICTS
                       per pending call, in call order>]}, whose route
                       (gvn.harness.tools.route) must be the symbol
    approved           None (every asked call approved) or {"denied": [{"call_id": str,
                       "reason": str or None}, ...]}: those asked calls denied, the rest
                       approved; an id that was not asked about, or twice, is a ValueError
    denied             {"reason": str} or None: every asked call denied, nothing runs
    remembered         {"entry": str}  the id the memory gave the text (gvn.harness.replies'
                       REMEMBERED); recorded nowhere, only counted
    remember_failed    {"reason": str}  (REMEMBER_FAILED); counted, never stops the run
    recalled           {"entries": [{"id": str, "text": str}, ...]}  at most
                       ``recall_limit`` entries, best first (gvn.harness.replies'
                       RECALLED_REPLY); more is a ValueError
    recall_failed      {"reason": str}  (RECALL_FAILED); counted, never stops the run
    sensed             {"readings": [<one per sensor asked, in the order asked>]}, each
                       {"sensor", "clean": bool, "text": str} or {"sensor", "failed": str}
                       (gvn.harness.sensors); another sensor or order is a ValueError
    sense_failed       {"reason": str}  every sensor asked counts as failed; never stops
                       the run
    interrupted, resumed    None
    within_budget, budget_exhausted, recall_due, context_fits, remember_due, trim_due,
    summary_due, context_exhausted, failure_final, context_exceeded, answered,
    answered_while_blocked, requested_tools, requested_unoffered, sensors_due,
    nothing_due (and answer_invalid)
                       internal; an Event carrying one of these from outside is a ValueError

Request payloads:

    invoke_model       thinking: {"instructions": str, "messages": [<Message.Dto plain>...],
                        "tools": [<identity of each tool offered, sorted>...],
                        "context": {...}}
                       plus "answer": <the Record's JSON Schema> for an agent built with
                       an answer (gvn.harness.replies.answer_plain), and "model_role":
                       str for an agent built with one
                       summarising: {"instructions": <the step's brief()>,
                        "messages": [<the step's asking(older), Message.Dto plain>...],
                        "tools": [], "context": {...}}  never "answer"; plus
                        "model_role": the step's role, else the agent's, when either is set
    remember           {"text": <ContextBudget.dropping(transcript): the transcript of what
                        the step now due would drop>, "context": {...}}
    recall             {"query": <the prompt's text>, "limit": <recall_limit>,
                        "context": {...}}  no scope: the fulfiller resolves it
    sense              {"readings": [{"sensor": <name>, "tool": <identity of its measuring
                        tool>, "arguments": {...}}, ...], "context": {...}}  one entry per
                        sensor owed a reading, in the order the sensors were given
    consult_policy     {"calls": [<ToolCall.Dto plain>...], "identities": [<the identity
                        of each call's tool>...], "context": {...}}  plus "exposure":
                        [<source>...] (sorted) once the exposure is not empty
    request_approval   {"calls": [...], "identities": [...], "text": str, "context": {...}}
                       only the calls a person is asked about; when some are not, also
                       "positions" and "beside" (gvn.harness.tools.approval_payload);
                       plus "exposure" as for consult_policy
    invoke_tools       {"calls": [...], "identities": [...], "context": {...}}  every
                       pending call; when some are refused, also "refused"
                       (gvn.harness.tools.invoke_payload)

Per-call verdicts (gvn.harness.tools). The policy judges each call; the symbol it answers
routes. A person is asked only about calls needing approval with no forbidden call before
them. ``approved`` may deny some of those; ``denied`` abandons the whole reply. Acting runs
the calls that are cleared or approved, and ``invoke_tools`` carries the others as refused
(forbidden, denied, or skipped), so every call is answered and none of those runs. If
nothing is left to run, acting still asks ``invoke_tools``, which runs nothing.

``context`` is the agent's run context (``{}`` when it has none): trusted plain
JSON from the code that built the agent, fixed for its life, never from a model.
The runtime hands it to tools (``Invocation``) and to the policy
(``Consultation``) and never sends it to the model. ``text`` in request_approval
is the text of the assistant message that asked for the calls, so an approver
sees the agent's explanation.

Exposure (gvn.harness.tools ``Tool.untrusted``). Text that comes back from outside the
deployment (a web page, an issue, a server reached over MCP) may be written to steer the
model that reads it. The agent does not trace which later argument such text influenced;
it records which untrusted sources its model has read so far, its *exposure*, and hands
that to the policy and the approver with every later call (``Consultation.exposure()``).
The tools offered whose ``untrusted()`` is True are read once, when the agent is built. A
sensor's reading, the prompt and the run context are never sources.

Request ids are ``"<agent name>/<machine step count>"``.

Requests and addresses:

* ``pending()`` is a tuple: ``()`` when the state names no external work, else
  ``(request,)`` for the state's output. The agent wants at most one thing at a time.
* Every Reaction carries ``requests=pending()`` as it stands after the event, so
  ``reaction.requests() == agent.pending()`` holds after every ``handle`` call. A
  rejected event (one the current state does not declare) returns a Reaction whose
  single step is that undeclared Step and whose requests are the unchanged
  ``pending()``; the agent itself is unchanged.
* ``event.to()`` must be None or the agent's own name. Any other address is a
  ValueError, raised before any other validation, and changes nothing.

Durable form: the Dto stores the machine as a ``Machine.Position`` (definition
fingerprint, state, step count), not the whole definition. The definition is
code (``Agent.definition()``); revival places the machine onto it with
``Machine.at``, which compares fingerprints and does not recompute one.

Data rules, applied only when the event's step was declared:

* started appends the user message; with ``recall=True`` and a prompt whose text is not
  blank, the agent then owes a recall for that text.
* recall_due (a recall is owed): recalling asks for ``recall`` (the request above) and
  counts one ``"asked"``. ``recalled`` with entries appends ONE user message,
  ``recalled_note(<the entries' texts, in order>)``, and adds their number to
  ``"found"``; with none it appends nothing. ``recall_failed`` appends nothing and
  counts one ``"failed"``: a memory that fails does not stop the run. Either answer
  settles the recall, and the check is made again. An interruption while recalling
  leaves the recall owed: after resume it is asked again under a new id (a read, so
  repeating it is harmless). Recalling spends no turn. A recall still owed when the
  agent reaches a final state is dropped.
* model_replied in thinking appends the assistant
  message and measures the conversation: ``gauge.measure(usage, context_window)``
  (no "usage": the size is unknown; no "context_window": the window last known stays).
  tools_returned appends one tool message with the results.
* Entering thinking spends one turn of the budget. The check_budget decision
  answers budget_exhausted when no turn remains. Summary calls spend no turn.
* check_context is ``ContextCheck(budget, gauge, remembered, recall_owed)``: recall_due
  while a recall is owed, else ``ContextBudget.verdict(gauge, transcript, remembered)``
  (gvn.harness.context_window). It is made only in measuring, where every tool call
  is answered, so a reduction never separates a call from its result.
* trim_due (the first step that applies needs no model): the transcript becomes
  ``step.reduced(transcript)``, then ``gauge.reduced()``, and the check is made again.
* remember_due (only with ``remember_dropped``): remembering asks for ``remember``
  (the request above). ``remembered`` and ``remember_failed`` both mark this loss as
  handed over, count one of ``"remembered"`` / ``"unremembered"``, and the check is made
  again with ``remembered=True`` (``ContextCheck``), which answers trim_due or
  summary_due: nothing else changed while remembering. A memory that fails does not
  stop the run. The mark is cleared whenever a reduction is applied (a trim, a summary
  or its fallback), so the next step's loss is handed over in its turn; a summary round
  is one loss, so the mark stays set through summarising (and through an interruption
  of it). An interruption while remembering leaves the mark unset: after resume the
  request is issued again under a new id, so that loss may be remembered twice.
* summary_due: summarising asks the model to summarise (the request above). A
  model_replied there whose text is not blank replaces the transcript with
  ``step.summarised(text, recent)`` (its calls are ignored); a blank one, and
  model_failed, give ``step.fallback().reduced(transcript)``. Then ``gauge.reduced()``
  and the check is made again. The step is the one the check found: the transcript
  does not change while summarising, so it is found again from it.
* tools_returned settles the batch and owes a reading to every sensor due after it
  (``Sensor.due`` over the batch's attempts: a watched tool ``ok``); check_sensors is
  ``SensorCheck`` over the sensors owed. ``sensed`` records each reading (the latest per
  sensor; a taken one counts in ``"taken"``, a failed one in ``"failed"``), appends ONE
  user message ``readings_note(...)`` and owes nothing more; ``sense_failed`` appends
  nothing and counts every sensor owed as failed. An interruption while sensing leaves
  the readings owed: resumed goes through checking_sensors, which asks for them again under
  a new id (measurements are reads). Sensing spends no turn.
* classify_reply answers answered_while_blocked, before anything else, for a reply
  without calls while a blocking sensor's latest reading is not clean (a reading that
  failed, or none yet, does not block): the agent appends one user message,
  ``blocked_note(...)`` (the sensors' names and latest readings), counts one
  ``"blocked"`` and goes back through admitting. budget_exhausted while a blocking sensor
  reads not clean names those sensors in the failure reason.
* model_failed in thinking goes to classify_failure (``FailureCheck`` over the
  payload's "exceeded_context"). failure_final: the run fails with the model failure
  reason. context_exceeded: ``gauge.refused()``, no failure reason is stored, and the
  agent goes back through admitting, so the turn budget bounds the retries and the
  next check asks for a reduction or answers context_exhausted.
* context_exhausted ends the run in ``overflowed``. With ``ContextBudget()`` a
  conversation the vendor refuses ends there (nothing can be reduced), not in failed.
* classify_reply answers answered when the last assistant message has no
  calls; requested_unoffered when it has calls and any of them names (by short
  name, which is what the model sends) none of the tools the agent was offered;
  else requested_tools. Each call is then known by the identity of the offered tool
  of that short name, and every request and attempt records it. The agent only ever runs the
  tools it was offered: an unoffered call is never sent to the policy, to
  approval or to the tools.
* requested_unoffered abandons the whole batch, like forbidden: one tool message
  with a failed ToolResult per call. A call to an unoffered tool says
  ``tool '<name>' was not offered to this agent``; the others say the batch was
  abandoned because of it. The model is then asked again (budget permitting).
* The transcript must stay well formed for any vendor: whenever pending calls
  are abandoned (forbidden, denied, interrupted while vetting, awaiting approval
  or acting), the agent appends a tool message with a failed ToolResult for
  every pending call, saying why.
* Exposure only grows. tools_returned adds the identity of every call of the batch to an
  untrusted tool whose tool actually ran (``gvn.harness.tools.exposed_by``): status
  ``ok``, or ``failed`` unless its result is a tool error saying the tool was never run
  (``unknown_tool``, ``invalid_arguments``); a refused, skipped, abandoned or unoffered
  call adds nothing. ``recalled`` with entries adds
  ``gvn.harness.tools.RECALLED_SOURCE`` (what a memory holds is untrusted, whoever wrote
  it). Nothing else adds to it, and nothing removes from it: a trim, a summary, an
  interruption or a revival keeps it, since a summary of tainted text is tainted.
* Every tool call is settled exactly once, with one of these statuses, when its
  answering tool message is appended, and its attempt is kept then, beside the
  transcript (a reduced transcript no longer holds every call): ``ok`` and ``failed``
  (the tool ran and its result says succeeded or failed; tools_returned),
  ``forbidden`` (the policy), ``denied`` (a person), ``skipped`` (not run because an
  earlier call of the reply was refused), ``unoffered`` (a call to a tool not
  offered), ``abandoned`` (interrupted, bundled with an unoffered call, or
  cleared in a reply a person denied).
* Outcome: completed carries {"text": &lt;the final assistant text>,
  "tools": [...], "attempts": [...], "reductions": {...}}, plus "answer": &lt;the validated
  data> for an agent built with an answer, and "citations": [...] when the final reply
  carries citations (``Message.citations``; data to show, never routed); failed carries
  {"reason": &lt;the model failure reason, that the budget was exhausted, or why the final
  reply is not a valid answer>, "attempts": [...], "reductions": {...}}; overflowed
  carries {"reason": &lt;that the context budget was exhausted, and whether the vendor
  refused the conversation or its measured size reached the limit>, "attempts": [...],
  "reductions": {...}}.
  "attempts" lists every tool call the model made in the run, once each, in the
  order it made them (batch by batch, each batch in call order), as
  {"name": &lt;tool short name>, "identity": &lt;the offered tool's identity, None for an
  unoffered call>, "arguments": &lt;the call's arguments>, "status": &lt;above>,
  "detail": &lt;the content of the ToolResult answering it>}: the tool's content
  for ok and failed, the reason text for the others; a later reduction does not
  change it. "tools" is the ok attempts, in the same order, as {"name", "identity",
  "arguments", "content"}. Match an entry to a tool with
  ``gvn.harness.tools.is_call_to`` / ``calls_to``, by identity. "reductions" is {"trimmed":
  &lt;trim_due reductions>, "summarised":
  &lt;summaries kept>, "fell_back": &lt;summaries that failed or came back blank>,
  "remembered": &lt;losses a memory took>, "unremembered": &lt;losses whose remember failed>}.
  Every outcome also carries "recalls": {"asked": &lt;recall requests issued>, "found":
  &lt;entries appended from recalls>, "failed": &lt;recall requests answered recall_failed>}
  (all 0 for an agent built with ``recall=False``), and "readings": {"taken": &lt;readings
  taken>, "failed": &lt;readings that failed>, "blocked": &lt;finishing replies refused>,
  "latest": {&lt;sensor>: {"clean", "text"} or {"failed"}}} (zeros and ``{}`` for an agent
  without sensors). Every outcome also carries "exposure": [&lt;source>...] (sorted), only
  when the exposure is not empty.

Constants: `CONTEXT_OUTCOMES`, `FAILURE_OUTCOMES`, `ASSISTANT`, `MODEL_FAILED`, `MODEL_REPLIED`, `RECALL_FAILED`, `RECALLED_REPLY`, `REMEMBER_FAILED`, `REMEMBERED`, `SENSE_FAILED`, `SENSED`, `SENSOR_OUTCOMES`, `APPROVED_PAYLOAD`, `ATTEMPT_STATUSES`, `INTERRUPTED_DETAIL`, `RECALLED_SOURCE`, `TOOLS_RETURNED`, `VERDICT_PAYLOAD`, `VERDICTS`.

### Agent

```python
from gvn.harness.agent import Agent
```

```text
Agent(
    name: str,
    instructions: str,
    tools: Toolbox | Iterable[Tool] = (),
    turns: int = 10,
    context: Mapping[str, typing.Any] | None = None,
    answer: Record | None = None,
    context_budget: ContextBudget | None = None,
    model_role: str | None = None,
    recall: bool = False,
    recall_limit: int = 5,
    sensors: Iterable[Sensor] = (),
) -> None
```

Implement this to make something the Governor can drive.

#### Agent.definition

```text
definition() -> Definition
```

The verified Definition of the machine above (a new equal one or a shared one).

#### Agent.answering_definition

```text
answering_definition() -> Definition
```

The verified Definition an agent built with an ``answer`` runs on: the machine
above plus ``interpreting --answer_invalid--> failed``. Same states and finals.

#### Agent.answer

```text
answer() -> Record | None
```

The answer schema (a kernel Record) the agent was built with, or None.

#### Agent.context_budget

```text
context_budget() -> ContextBudget
```

The ContextBudget the agent was built with (``ContextBudget()`` when none was).

#### Agent.model_role

```text
model_role() -> str | None
```

None, or the name of the role whose model the agent asks.

#### Agent.recall

```text
recall() -> bool
```

Whether the agent asks a memory, by itself, for entries matching its prompt.

#### Agent.recall_limit

```text
recall_limit() -> int
```

The most entries the agent's own recall asks for (an int >= 1).

#### Agent.model_roles

```text
model_roles() -> frozenset[str]
```

Frozenset of the model roles this actor may ask for (``Actor.model_roles``):
its own and those its context budget's steps name.

#### Agent.sensors

```text
sensors() -> tuple[Sensor, ...]
```

The tuple of the agent's Sensors, in the order given.

#### Agent.sensor_identities

```text
sensor_identities() -> frozenset[str]
```

Frozenset of the identities of its sensors' measuring tools
(``Actor.sensor_identities``).

#### Agent.name

```text
name() -> str
```

The actor's address: a non-empty str, stable for its whole life.

#### Agent.handle

```text
handle(event: Event) -> Reaction
```

Consume an Event and return the Reaction. Synchronous, no I/O.

Raises UnknownSymbol when the event's name is not in the actor's input
alphabet, and ValueError when its payload does not fit what that input
requires; in both cases the actor is unchanged. An event that is valid but
not expected in the current state is not an error: it returns a rejected
Reaction and changes nothing, data included.

Addresses: an event whose ``to()`` is neither None, the actor's own name nor
(for composite actors) the name of something beneath it raises ValueError and
changes nothing. After the call, ``reaction.requests() == self.pending()``.

#### Agent.pending

```text
pending() -> tuple[Request, ...]
```

``()`` or ``(request,)``: the external work the current state names.

#### Agent.state

```text
state() -> State
```

The current control State.

#### Agent.standings

```text
standings() -> tuple[Standing, ...]
```

Where the agent stands (``Actor.standings``): on the definition it was built
with, ``answering_definition()`` for an agent built with an ``answer`` and
``definition()`` otherwise, revived ones included. It hosts no one.

#### Agent.expected

```text
expected() -> frozenset[Symbol]
```

Frozenset of the Symbols with a declared transition from the current state.

#### Agent.finished

```text
finished() -> bool
```

True when the control state is final.

#### Agent.settles

```text
settles(event: Event) -> bool
```

Could handling ``event`` leave the agent finished (see ``Actor.settles``)?

Read from the definition and the agent's own data, without changing anything:

* not declared here: False (a rejected event changes nothing);
* the step lands in a final state: True;
* it lands in ``admitting`` (check_budget): True when the budget is already
  exhausted (nothing is spent before the check); else True when the gauge says
  the conversation is over its limit or refused and no reduction step applies
  to the transcript as it stands (one that applies now still applies once the
  event has appended its messages, so the check cannot then answer
  ``context_exhausted``); else False;
* it lands in ``diagnosing`` (classify_failure, from ``model_failed`` in
  thinking): without ``exceeded_context`` the run fails (True); with it the
  agent goes back through admitting with a refused gauge, answered as above;
* it lands in ``interpreting`` (classify_reply, from ``model_replied``): a reply
  without calls completes or fails, or is blocked by a sensor (True); one whose
  calls are all offered goes on to vetting and waits (False); one naming an
  unoffered tool goes back
  through admitting, answered as above with the gauge the reply measures;
* it lands in ``measuring`` from summarising: False, since a reduction leaves
  nothing measured, so the check cannot answer ``context_exhausted``;
* it lands in ``measuring`` from remembering (``remembered``,
  ``remember_failed``): False. Nothing changed since the check answered
  ``remember_due``, so with the loss handed over it answers trim_due or
  summary_due, and after a trim nothing is measured, as above;
* it lands in ``measuring`` from recalling (``recalled``, ``recall_failed``): True
  when the gauge alone says the context is exhausted (whether a reduction step
  would apply once the note is in is not worked out), else False: the check can
  then only reduce, ask the model or ask a memory;
* it lands in ``checking_sensors`` (``tools_returned``, ``resumed``): False when a
  reading is owed already (the agent asks for it and waits); else answered as for
  admitting, which it reaches when no sensor is due (whether one is due after the
  batch is not worked out: True is then the safe answer);
* anywhere else the agent stops to wait (an external request, idle, suspended):
  False.

Anything the agent would refuse (not an Event, an unknown symbol, a payload that
does not parse where it is read) answers True.

#### Agent.outcome

```text
outcome() -> Outcome
```

The Outcome. Raises NotFinished unless ``finished()``.

#### Agent.instructions

```text
instructions() -> str
```

The instructions (str) given at construction.

#### Agent.tool_identities

```text
tool_identities() -> frozenset[str]
```

Frozenset of the identities of the tools this agent was offered
(``Actor.tool_identities``).

#### Agent.exposure

```text
exposure() -> frozenset[str]
```

Frozenset of the sources of untrusted content the agent's model has read so far:
the identity of each untrusted tool whose result it was handed, and
``gvn.harness.tools.RECALLED_SOURCE`` once a recall of its own appended notes.
Empty until then; it only grows (see the module docstring).

#### Agent.context

```text
context() -> dict[str, typing.Any]
```

A fresh copy of the run context; ``{}`` when the agent was built without one.

#### Agent.transcript

```text
transcript() -> tuple[Message, ...]
```

Tuple of every Message the agent keeps, oldest first (as the context budget
kept them).

#### Agent.turns

```text
turns() -> int
```

The model turns the agent was built with (its ``turns`` argument), however
many are spent; ``turns_remaining()`` says how many are left.

#### Agent.turns_remaining

```text
turns_remaining() -> int
```

#### Agent.to_dto

```text
to_dto() -> Agent.Dto
```

A Dto capturing the complete internal state. Does not mutate the object.

#### Agent.from_dto

```text
from_dto(dto: Dto) -> typing.Self
```

Rehydrate. TypeError for a foreign Dto; ValueError for an inconsistent one,
including one whose position names a definition other than ``Agent.definition()``
or a state it does not have, or a state the agent is never at rest in.

## gvn.harness.answering

Answering: who may answer a request that waits on the outside world.

An actor that needs a person asks for it (``request_approval``, ``request_input``, a
harness's own external kind) and the run parks. The answer arrives later through
``Governor.answer``, possibly in another process, from whatever entry point the
deployment has: a web handler, a chat integration, a command line. Two questions
are then open, and this module is where gvn answers them:

* WHO answered. The entry point knows: it authenticated the caller (a session, a signed
  token, a chat platform's user id). It says so by passing a ``Principal``
  (``gvn.harness.events``) as ``Governor.answer(..., by=principal)``. gvn does not
  authenticate anyone; it carries what the entry point vouches for, stamps it on the
  answering Event (``Event.by()``), and so journals it with the event. From then on it is
  part of the run's record: the actor that receives the event can read it, a hosted actor
  receives it with the event, replay and recovery reproduce it, and an evaluation check
  can demand it (``gvn.runtime.evaluation.AnsweredBy``).

* WHETHER they may. A Governor built with ``entitlement=`` asks that Decision before it
  hands any answer to the actor. Its outcomes are ``ENTITLEMENTS``; its subject is an
  ``Answering``: the request, the answering event, and the principal (None when the
  entry point named nobody). ``not_entitled`` refuses the answer with ``NotEntitled``:
  nothing is journaled, nothing is signalled, the actor is unchanged and still waits.
  The rule is ordinary code over finite outcomes, like a tool policy, so it is tested
  offline the same way.

A rule reads trusted data only: the principal's claims come from the entry point, the
request's ``context`` from the code that built the actor. It must not read what a model
wrote into the request (an explanation text, a call's arguments) to decide who may
answer.

This module does no I/O.

Constants: `ENTITLEMENTS`.

### NotEntitled

```python
from gvn.harness.answering import NotEntitled
```

An answer was refused because the Governor's entitlement Decision judged that the
one who gave it may not answer that request. Nothing was journaled or signalled and
the actor is unchanged: the request still waits for an answer from someone who may.
The message names the request, its kind and the principal's subject and issuer (or
says that nobody was named); it never includes the principal's claims.

Raised by the runtime (``gvn.runtime.governor.Governor.answer``); defined here so
that code answering requests can catch it with the harness alone.

### Answering

```python
from gvn.harness.answering import Answering
```

```text
Answering(request: Request, event: Event, by: Principal | None = None) -> None
```

One answer about to be given, as an entitlement Decision sees it. Immutable value,
equal by content.

``request``: the Request being answered (``gvn.harness.events.Request``). ``event``:
the answering Event as the caller gave it (before the Governor addresses and stamps
it). ``by``: the ``gvn.harness.events.Principal`` the entry point vouches for, or
None when it named nobody. TypeError otherwise.

#### Answering.request

```text
request() -> Request
```

The Request being answered.

#### Answering.kind

```text
kind() -> str
```

The request's kind, as a str (``"request_approval"``).

#### Answering.context

```text
context() -> dict[str, typing.Any]
```

A fresh copy of the request payload's ``"context"`` when it is a dict (the
trusted run context the standard requests carry), else ``{}``.

#### Answering.event

```text
event() -> Event
```

The answering Event.

#### Answering.by

```text
by() -> Principal | None
```

The Principal who answers, or None.

### Authenticated

```python
from gvn.harness.answering import Authenticated
```

```text
Authenticated(issuers: Iterable[str] | None = None) -> None
```

The entitlement that asks only that somebody was named: ``entitled`` when the
answer carries a Principal (from one of ``issuers``, when given), else
``not_entitled``.

``issuers``: None (any principal, whoever vouched for it, including one that names
no issuer), or a non-empty iterable of non-empty strs (not a str: TypeError): the
principal's ``issuer()`` must be one of them, so a principal with no issuer is
refused. Either way, an answer with no principal is never entitled.
TypeError/ValueError otherwise. Judging anything but an ``Answering`` is a TypeError.

The smallest useful rule: with it, no request of a run is ever answered
anonymously. A deployment's own rule (this team approves refunds, the requester may
not approve their own change) is a Decision of its own with the same outcomes.

#### Authenticated.outcomes

```text
outcomes() -> Alphabet
```

The Alphabet of every answer this decision can give. Must not vary over time.

#### Authenticated.judge

```text
judge(subject: object) -> Symbol
```

Inspect ``subject`` and return one Symbol from ``outcomes()``.

## gvn.harness.approval

Approval: an actor that asks a person to approve one named thing and ends approved or declined.

An Approval is the human gate on its own: it makes no tool call and runs nothing.
It asks a person ``request_approval`` and waits as long as it takes. While it waits it
is just data: the run parks on the request, which no fulfiller runs (declare it
external on the Governor), and the verdict arrives later as an ``approved`` or
``denied`` event, possibly in another process.

    state              output            input -> next state
    idle               idle              started -> awaiting_approval
    awaiting_approval  request_approval  approved -> approved
                                         denied -> declined
                                         interrupted -> suspended
    suspended          suspended         resumed -> awaiting_approval
    approved, declined (final)

Every other input is covered by ``otherwise: stay``: it is rejected and changes
nothing. Final states absorb everything. There is no internal decision.

Event payloads (anything else is a ValueError that changes nothing):

    denied                              {"reason": str} or None
    started, approved, interrupted, resumed   None

While awaiting approval, ``pending()`` is one Request with id
``"<name>/request_approval"`` (stable for the life of the approval: after an interrupt
and resume the question is the same Request, so an answer tied to it is accepted),
kind ``request_approval`` and the standard payload

    {"calls": [], "identities": [], "text": str, "context": {...}, "approve": <label>}

so approvers and ``Gated``-style checks can recognise it by ``approve``. ``context``
is trusted data from the code that built the approval. The person's ``reason`` is
UNTRUSTED text: it is kept in the outcome and must never route or be copied into a
run context.

Outcome payload, in both final states: ``{"approve": <label>, "reason": str or None}``
(``reason`` is only ever set when declined), plus ``"answered_by"``: the plain form of
the ``gvn.harness.events.Principal`` the ``approved`` or ``denied`` event that ended it
came from (``Event.by()``), only when it came from one. That principal is what the
deployment's entry point vouched for (``Governor.answer(..., by=)``), so it is trusted,
unlike ``reason``. An approval answered by nobody named has no ``"answered_by"``.

### Approval

```python
from gvn.harness.approval import Approval
```

```text
Approval(
    name: str,
    label: str,
    text: str = '',
    context: Mapping[str, typing.Any] | None = None,
) -> None
```

Asks a person to approve one named thing and ends approved or declined.

#### Approval.definition

```text
definition() -> Definition
```

The verified Definition of the machine above (shared).

#### Approval.name

```text
name() -> str
```

The actor's address: a non-empty str, stable for its whole life.

#### Approval.label

```text
label() -> str
```

What is being approved.

#### Approval.text

```text
text() -> str
```

What the person is shown.

#### Approval.context

```text
context() -> dict[str, typing.Any]
```

A fresh copy of the context; ``{}`` when none was given.

#### Approval.answered_by

```text
answered_by() -> Principal | None
```

The Principal the ``approved`` or ``denied`` event that ended this approval came
from, or None (not ended yet, or answered by nobody named).

#### Approval.handle

```text
handle(event: Event) -> Reaction
```

Consume an Event and return the Reaction. Synchronous, no I/O.

Raises UnknownSymbol when the event's name is not in the actor's input
alphabet, and ValueError when its payload does not fit what that input
requires; in both cases the actor is unchanged. An event that is valid but
not expected in the current state is not an error: it returns a rejected
Reaction and changes nothing, data included.

Addresses: an event whose ``to()`` is neither None, the actor's own name nor
(for composite actors) the name of something beneath it raises ValueError and
changes nothing. After the call, ``reaction.requests() == self.pending()``.

#### Approval.settles

```text
settles(event: Event) -> bool
```

Could handling ``event`` now finish this approval? Only a declared step into a
final state can. Anything handle would refuse answers True.

#### Approval.pending

```text
pending() -> tuple[Request, ...]
```

``()`` or ``(request,)``: built once per state entered, never per call.

#### Approval.state

```text
state() -> State
```

The current control State.

#### Approval.expected

```text
expected() -> frozenset[Symbol]
```

Frozenset of the Symbols with a declared transition from the current state.

#### Approval.finished

```text
finished() -> bool
```

True when the control state is final.

#### Approval.outcome

```text
outcome() -> Outcome
```

The Outcome. Raises NotFinished unless ``finished()``.

#### Approval.to_dto

```text
to_dto() -> Approval.Dto
```

A Dto capturing the complete internal state. Does not mutate the object.

#### Approval.from_dto

```text
from_dto(dto: Dto) -> typing.Self
```

Rehydrate. TypeError for a foreign Dto; ValueError for one no Approval could have
produced: no name or label, a position on another definition, a reason outside
declined, who answered outside a final state.

## gvn.harness.budget

A budget of model turns.

### BudgetExhausted

```python
from gvn.harness.budget import BudgetExhausted
```

``spend`` was called with nothing left.

### Budget

```python
from gvn.harness.budget import Budget
```

```text
Budget(turns: int) -> None
```

Counts down from a fixed allowance. ``turns`` must be an int >= 1 (not a bool).

#### Budget.spend

```text
spend() -> None
```

Use one turn. Raises BudgetExhausted, changing nothing, when none remain.

#### Budget.exhausted

```text
exhausted() -> bool
```

#### Budget.remaining

```text
remaining() -> int
```

#### Budget.allowance

```text
allowance() -> int
```

The turns the budget was built with, however many are spent.

#### Budget.to_dto

```text
to_dto() -> Dto
```

A Dto capturing the complete internal state. Does not mutate the object.

#### Budget.from_dto

```text
from_dto(dto: Dto) -> typing.Self
```

ValueError if ``spent`` exceeds ``allowance``.

## gvn.harness.choice

Choice: a model picks one of a finite, declared set of options.

A Decision (gvn.kernel.decision) routes on data with a finite set of outcomes. A Choice
lets a model make that kind of decision soundly: the options are declared up front,
the model is asked for its pick through the vendor's own structured output (an enum
the service constrains decoding to), gvn checks the pick is one of the options, and the
pick is journaled with the event that brought it. A workflow then routes on it with
``Chosen``, a Decision over the same options, so a model's pick is never free text that
routes: it is one member of a declared set, or the Choice fails.

    state        output                     input -> next state
    idle         idle                       started -> asking
    asking       invoke_model               model_replied -> checking
                                            model_failed -> failed
    checking     check_choice (internal)    chosen -> chosen
                                            unchosen -> failed
    suspended    suspended                  resumed -> asking
    chosen (final), failed (final)

``interrupted`` is declared in asking and leads to suspended. Everything else is
``otherwise: stay``: rejected, changing nothing. ``chosen`` and ``unchosen`` are
internal: an Event carrying one from outside is a ValueError. check_choice answers
``chosen`` when the reply has no tool calls and its text is one JSON value
``{"choice": <one of the options>, "explanation": str}``; else ``unchosen`` (a Choice
offers no tools, and the vendor's guarantee does not cover a refusal or every model).
Nothing is retried: a failed Choice is a declared route the host handles.

Event payloads (anything else is a ValueError that changes nothing):

    started          {"prompt": str, "attachments": [<plain Attachment.Dto>, ...]}
                     "attachments" optional: images and documents to decide about
    model_replied, model_failed    as gvn.harness.replies
    interrupted, resumed           None

A Choice is one model call and keeps no context budget: a reply's "context_window" and
a failure's "exceeded_context" are accepted, journaled with the event, and change
nothing (a call refused as too large fails the Choice as any model failure does).

Request: ``invoke_model`` with id ``"<name>/invoke_model"`` (the same for the Choice's
whole life, across crash and interrupt/resume: asking again is harmless) and payload
``{"instructions": &lt;the instructions, then a sentence naming the options>, "messages":
[the prompt], "tools": [], "context": {...}, "answer": &lt;the answer schema's JSON
Schema>}``, with ``"model_role": &lt;the role>`` when the Choice names one (the runtime wiring gives that role's model the call). ``context`` is the run
context (``{}`` when none): trusted data from code, never sent to the model.

Outcome: chosen carries ``{"choice": str, "explanation": str}`` (the explanation is the
model's one sentence: shown to people, never routed); failed carries ``{"reason":
str}``.

Durable form: the machine's Position on ``Choice.definition()``, the options, the
prompt and the reply (plain Message Dtos, None until they exist), the failure reason,
the context and the model role.

Constants: `MODEL_FAILED`, `MODEL_REPLIED`.

### answer_for

```python
from gvn.harness.choice import answer_for
```

```text
answer_for(options: Iterable[str]) -> Record
```

The answer schema of a Choice over ``options``: ``{"choice": OneOf(*options),
"explanation": Text()}``.

### Choice

```python
from gvn.harness.choice import Choice
```

```text
Choice(
    name: str,
    instructions: str,
    options: Iterable[str],
    context: Mapping[str, typing.Any] | None = None,
    model_role: str | None = None,
) -> None
```

Implement this to make something the Governor can drive.

#### Choice.definition

```text
definition() -> Definition
```

#### Choice.name

```text
name() -> str
```

The actor's address: a non-empty str, stable for its whole life.

#### Choice.options

```text
options() -> tuple[str, ...]
```

Tuple of the option names, in the order given.

#### Choice.model_role

```text
model_role() -> str | None
```

None, or the name of the role whose model makes the pick.

#### Choice.model_roles

```text
model_roles() -> frozenset[str]
```

Frozenset of the model roles this actor may ask for (``Actor.model_roles``).

#### Choice.answer

```text
answer() -> Record
```

The answer schema the model is asked to fill (see ``answer_for``).

#### Choice.state

```text
state() -> State
```

The current control State.

#### Choice.expected

```text
expected() -> frozenset[Symbol]
```

Frozenset of the Symbols with a declared transition from the current state.

#### Choice.finished

```text
finished() -> bool
```

True when the control state is final.

#### Choice.pending

```text
pending() -> tuple[Request, ...]
```

The tuple of Requests the actor wants from the outside world (empty when none).

In a stable order. Equal to the requests of the Reaction returned by the latest
``handle`` call, with the same ids. This is what lets work be re-issued after a
crash: a revived actor still knows what it was waiting for.

#### Choice.handle

```text
handle(event: Event) -> Reaction
```

Consume an Event and return the Reaction. Synchronous, no I/O.

Raises UnknownSymbol when the event's name is not in the actor's input
alphabet, and ValueError when its payload does not fit what that input
requires; in both cases the actor is unchanged. An event that is valid but
not expected in the current state is not an error: it returns a rejected
Reaction and changes nothing, data included.

Addresses: an event whose ``to()`` is neither None, the actor's own name nor
(for composite actors) the name of something beneath it raises ValueError and
changes nothing. After the call, ``reaction.requests() == self.pending()``.

#### Choice.settles

```text
settles(event: Event) -> bool
```

True exactly when ``event`` would end the Choice: a model's answer while
asking (it is chosen or fails), or anything the Choice would refuse.

#### Choice.outcome

```text
outcome() -> Outcome
```

The Outcome. Raises NotFinished unless ``finished()``.

#### Choice.to_dto

```text
to_dto() -> Choice.Dto
```

A Dto capturing the complete internal state. Does not mutate the object.

#### Choice.from_dto

```text
from_dto(dto: Dto) -> typing.Self
```

TypeError for a foreign Dto; ValueError for an inconsistent one.

### Chosen

```python
from gvn.harness.choice import Chosen
```

```text
Chosen(options: Iterable[str], failed: str) -> None
```

A Host judge that routes a workflow on a Choice's pick.

``options``: the Choice's options (the same names, any order). ``failed``: the symbol
the stage ends with when the Choice failed; it must not be one of the options. Its
outcomes are the options and ``failed``; it decides on a workflow ``Ending`` (or an
Outcome): a chosen Choice answers its choice, a failed one ``failed``.

    Host(actor_class=Choice, make=..., start=...,
         judge=Chosen(options=("refund", "replace", "escalate"), failed="undecided"))

#### Chosen.outcomes

```text
outcomes() -> Alphabet
```

The Alphabet of every answer this decision can give. Must not vary over time.

#### Chosen.judge

```text
judge(subject: object) -> Symbol
```

Inspect ``subject`` and return one Symbol from ``outcomes()``.

## gvn.harness.context_window

The context window: how full it is, an actor's budget for it, and how to reduce it.

A model's context window is a property of the model (``Model.context_window()``). What an
actor does as its conversation fills that window is the actor's own: a ``ContextBudget``,
fixed when the actor is built. This module holds the three pieces an actor composes:

    ContextGauge     the actor's measurement: how many tokens the conversation held at the
                     last model reply, and how many the model can hold. Stateful, Durable.
    ContextBudget    the setting: how much of the window the actor may use, when a
                     reduction is due, and the reduction steps to try, in order.
                     Immutable, Durable.
    ContextCheck     the Decision an actor routes on before it asks its model:
                     ``recall_due``, ``context_fits``, ``remember_due``, ``trim_due``,
                     ``summary_due`` or ``context_exhausted``.
    FailureCheck     the Decision over a model failure: ``failure_final`` or
                     ``context_exceeded`` (the vendor refused the conversation as too large).

Measurement never counts tokens here and never asks a model. It is read from journaled
events, as time is: every ``model_replied`` carries the tokens the call reported
(``usage``) and, when the model knows it, its context window (gvn.harness.replies). The
conversation's size after a reply is that call's ``input_tokens + output_tokens``: exact,
the same on every vendor, and the same on replay. Two things follow, by design:

* Nothing is known before the first reply, and messages appended since the last reply
  (tool results, a person's answer) are not measured until the next one.
* What measurement misses, the vendor catches: a call refused because the conversation
  does not fit arrives as ``model_failed`` with ``exceeded_context`` true, and the gauge
  records the refusal, so the next check asks for a reduction or answers
  ``context_exhausted``.

The budget. ``ContextBudget(limit=1.0, reduce_at=None, reduce_over=None, steps=(),
remember_dropped=False)``:

    limit        the most the conversation may hold: an int (tokens, >= 1) or a float
                 (a share of the model's window, 0 < share <= 1; the default is all of it)
    reduce_at    when a reduction is due, in the same two forms; None means at ``limit``
    reduce_over  None, or an int >= 1: a reduction is also due once the transcript holds
                 more messages than this, whatever their size (it bounds what is stored)
    steps        the reduction steps (below), tried in the order given
    remember_dropped
                 a bool: whether what a step is about to take out of the conversation is
                 first handed to a memory (below)

A share of an unknown window is an unknown threshold, and an unknown threshold is never
crossed: until the model's window is known (or when the model never says), only token
numbers, ``reduce_over`` and the vendor's refusal apply.

The check, made whenever the actor is about to ask its model:

    the actor owes a recall for the user message it just took (``recall_owed``, below)
                               -> ``recall_due``
    else a reduction is due (the vendor refused the last call, or the measurement reached
    ``reduce_at``, or the transcript is longer than ``reduce_over``) and a step applies
                               -> ``remember_due`` when the budget remembers what is
                                  dropped, this step's loss has not been handed over
                                  yet and it is not empty (a step that drops only
                                  recalled notes loses nothing a memory lacks); else
                                  ``trim_due`` (the step needs no model) or
                                  ``summary_due`` (it needs one), for the first that applies
    else the vendor refused the last call, or the measurement reached ``limit``
                               -> ``context_exhausted``
    else                       -> ``context_fits``

After a reduction the actor tells the gauge (``reduced``): the old measurement no longer
describes the transcript, so nothing is known until the next reply measures it again. A
step applies only when it would change the transcript, so repeated reductions end.

Reduction steps (each an immutable Durable value, equal by content):

    ClearToolResults(keep)     replace the content of every tool result older than the
                               last ``keep`` tool messages with ``CLEARED``, dropping its
                               attachments; calls, and whether a result failed, stay
    KeepRecent(messages)       keep only the last ``messages`` messages (after a user
                               message saying ``OMITTED`` when they would otherwise not
                               start with a user message)
    Summarise(keep, brief="")  have a model summarise all but the last ``keep`` messages
                               and keep that summary in their place

Remembering what is dropped (``remember_dropped=True``). Reducing loses text for good. A
budget that remembers hands it to a memory first (``gvn.harness.ports.Memory``): on
``remember_due`` the actor issues one ``remember`` request whose text is
``budget.dropping(messages)``, the transcript of exactly what the step that is due would
take out (``Reduction.dropped``), and waits for ``remembered`` or ``remember_failed``.
Either way it then checks again, saying that this loss was handed over (``remembered=True``
to ``ContextCheck``), and the step runs. A memory that fails does not stop the run: the
actor counts it and reduces anyway, as it would have without a memory. What is remembered
is untrusted conversation content, without sealed content and with attachments described,
not kept.

Recalling. A model recalls through a tool (``gvn.runtime.memory``); an
actor built with ``recall=True`` also recalls by itself, once for each user message it
takes whose text is not blank: it owes a recall, ``ContextCheck(..., recall_owed=True)``
answers ``recall_due`` before anything else, the actor issues one ``recall`` request and,
when entries come back, appends ONE user message whose text is ``recalled_note(texts)``:
the header ``RECALLED`` and then one block per entry. That note is untrusted content
(never an instruction message, never the actor's instructions) and, for size and for every
reduction step, an ordinary message. It came from a memory, so what a step drops is handed
back to one without it: ``Reduction.dropped``, ``ContextBudget.dropping`` and
``transcribed`` leave out every recalled note (``is_recalled_note``: a user message whose
text starts with ``RECALLED``), and a step that drops nothing else asks for no
``remember``. A person who types the header at the start of a message is read the same
way: that message is not handed to a memory when it is dropped.

Which model. ``Summarise(keep, brief="", model_role=None)``: None asks the actor's own
model; a name asks the model the runtime wiring gives that role
(``gvn.runtime.fulfillers.ModelFulfiller``), so a small model can do the summarising.

A cut never splits a tool call from its result, nor an instruction message from the user
message it follows: where a cut would fall on one, it moves back, so ``KeepRecent(n)``
may keep a little more than ``n``.

Sealed content (``Message.sealed``: a vendor's signed thinking) is bound by the vendor to
everything that preceded it, so it stays valid only while the history before it is
unchanged. Every step here changes that history, so the messages a step returns carry no
sealed content. That is the price of reducing on gvn's side: the model does not get its
earlier thinking back, and the vendor's cache of the conversation restarts. A vendor's own
server-side reduction (an adapter setting) avoids both, for that vendor only; gvn then
simply measures a smaller conversation. Sealed content is never sent to a summariser.

Attachments are not sent to a summariser either: it is shown what each one was
(``Attachment.descriptor()``) in its place. A summary is model-written content made from
untrusted text: it is kept as a user message starting with ``SUMMARY_PREFIX``, which says
so, and it never enters a run context or a route.

Constants: `ABC`, `ASSISTANT`, `INSTRUCTION`, `TOOL`, `USER`, `CONTEXT_OUTCOMES`, `FAILURE_OUTCOMES`, `CLEARED`, `OMITTED`, `RECALLED`, `SUMMARY_PREFIX`, `DEFAULT_BRIEF`, `ASK`, `ATTACHMENTS_NOT_SHOWN`.

### recalled_note

```python
from gvn.harness.context_window import recalled_note
```

```text
recalled_note(texts: Iterable[str]) -> str
```

The text of the note an actor appends with what it recalled: ``RECALLED``, then one
block per text in the order given, each block separated from the one before by a
blank line (``"\n\n"``). ``texts``: a non-empty iterable of str (an entry's text, as
the memory gave it). TypeError/ValueError otherwise.

### is_recalled_note

```python
from gvn.harness.context_window import is_recalled_note
```

```text
is_recalled_note(message: Message) -> bool
```

Whether ``message`` (a Message) is a note of what an actor recalled: a user message
whose text starts with ``RECALLED``. A person's message that starts so is read the
same way.

### model_role_checked

```python
from gvn.harness.context_window import model_role_checked
```

```text
model_role_checked(value: object) -> str | None
```

``value`` as a model role: None, or a name as tool names are
(``[A-Za-z][A-Za-z0-9_-]*``). A role is a name the runtime wiring maps to a Model
(``gvn.runtime.fulfillers.ModelFulfiller``); it is not a vendor's model id.
TypeError/ValueError otherwise.

### recall_checked

```python
from gvn.harness.context_window import recall_checked
```

```text
recall_checked(value: object) -> bool
```

``value`` as an actor's ``recall`` setting: a bool, strictly. TypeError otherwise.

### recall_limit_checked

```python
from gvn.harness.context_window import recall_limit_checked
```

```text
recall_limit_checked(value: object) -> int
```

``value`` as an actor's ``recall_limit``: the most entries one automatic recall asks
for, an int >= 1. TypeError/ValueError otherwise.

### transcribed

```python
from gvn.harness.context_window import transcribed
```

```text
transcribed(messages: Iterable[Message]) -> str
```

``messages`` as text for a memory: one block per message, in order, separated by
blank lines. Sealed content is left out, an attachment is described rather than kept
(as for a summariser), a call is shown with its name and arguments and a result with
its call id and content, as JSON. Recalled notes (``is_recalled_note``) are left out:
they came from a memory. Every other message leaves a block, so the text is ``""``
only when there is no message but recalled notes.

### ContextGauge

```python
from gvn.harness.context_window import ContextGauge
```

```text
ContextGauge() -> None
```

What an actor knows of its conversation's size. The only ways to change it are
``measure``, ``refused`` and ``reduced``.

A new gauge knows nothing. ``tokens()`` is the size at the last measured reply, or
None; ``window()`` the model's context window as last reported, or None;
``was_refused()`` whether the vendor refused the last call as too large.

#### ContextGauge.measure

```text
measure(usage: Mapping[str, int] | None, window: int | None = None) -> None
```

Record a model reply. ``usage``: None, or the reply's reported tokens (a
mapping with ``input_tokens`` and ``output_tokens``, ints >= 0): the conversation
now holds their sum. None leaves the size unknown. ``window``: None (keep what is
known) or the model's context window (int >= 1). A reply means the call was not
refused. TypeError/ValueError otherwise, changing nothing.

#### ContextGauge.refused

```text
refused() -> None
```

Record that the vendor refused the last call because the conversation does not
fit the model's context window.

#### ContextGauge.reduced

```text
reduced() -> None
```

Record that the transcript was reduced: its size is unknown until the next
measured reply, and an earlier refusal no longer describes it.

#### ContextGauge.tokens

```text
tokens() -> int | None
```

#### ContextGauge.window

```text
window() -> int | None
```

#### ContextGauge.was_refused

```text
was_refused() -> bool
```

#### ContextGauge.to_dto

```text
to_dto() -> ContextGauge.Dto
```

A Dto capturing the complete internal state. Does not mutate the object.

#### ContextGauge.from_dto

```text
from_dto(dto: Dto) -> typing.Self
```

### Reduction

```python
from gvn.harness.context_window import Reduction
```

```text
Reduction()
```

One way to make a transcript smaller. The built-in steps implement it; a
``ContextBudget`` holds only those (it must be able to store and revive them).

A step that ``summarises()`` needs a model (see ``Summarise``); any other returns the
reduced transcript itself (``reduced``).

#### Reduction.applies

```text
applies(messages: Iterable[Message]) -> bool
```

Whether this step would change ``messages`` (an iterable of Message).

#### Reduction.summarises

```text
summarises() -> bool
```

Whether this step needs a model call (True only for ``Summarise``).

#### Reduction.dropped

```text
dropped(messages: Iterable[Message]) -> tuple[Message, ...]
```

The messages of ``messages`` whose content this step would take out, in order
(a tuple; empty when the step does not apply), recalled notes left out: they came
from a memory. ``transcribed`` turns them into the text a memory is given.

### ClearToolResults

```python
from gvn.harness.context_window import ClearToolResults
```

```text
ClearToolResults(keep: int) -> None
```

Replace old tool results with ``CLEARED``, keeping the last ``keep`` tool messages
as they are (int >= 1: the newest result may not have been read by the model yet).

The calls stay, each result keeps its call id and whether it failed, and the
attachments of a cleared result are dropped: the transcript keeps its shape and loses
its bulk. No message is removed. TypeError/ValueError otherwise.

#### ClearToolResults.keep

```text
keep() -> int
```

#### ClearToolResults.summarises

```text
summarises() -> bool
```

Whether this step needs a model call (True only for ``Summarise``).

#### ClearToolResults.applies

```text
applies(messages: Iterable[Message]) -> bool
```

Whether this step would change ``messages`` (an iterable of Message).

#### ClearToolResults.reduced

```text
reduced(messages: Iterable[Message]) -> tuple[Message, ...]
```

``messages`` with every old tool result cleared, and without sealed content
when anything was cleared; ``messages`` unchanged when nothing was.

#### ClearToolResults.dropped

```text
dropped(messages: Iterable[Message]) -> tuple[Message, ...]
```

Each tool message that would be cleared, after the assistant message whose
calls it answers (so the results can be read with what was asked).

#### ClearToolResults.to_dto

```text
to_dto() -> ClearToolResults.Dto
```

A Dto capturing the complete internal state. Does not mutate the object.

#### ClearToolResults.from_dto

```text
from_dto(dto: Dto) -> typing.Self
```

### KeepRecent

```python
from gvn.harness.context_window import KeepRecent
```

```text
KeepRecent(messages: int) -> None
```

Keep the last ``messages`` messages (an int >= 1), never splitting a call from its
result or an instruction from the user message before it. Everything older is gone
for the model. A transcript must start with a user message for every vendor, so when
the kept messages would not, a user message saying ``OMITTED`` is put before them (and
is not counted). TypeError/ValueError otherwise.

#### KeepRecent.messages

```text
messages() -> int
```

#### KeepRecent.summarises

```text
summarises() -> bool
```

Whether this step needs a model call (True only for ``Summarise``).

#### KeepRecent.applies

```text
applies(messages: Iterable[Message]) -> bool
```

Whether this step would change ``messages`` (an iterable of Message).

#### KeepRecent.reduced

```text
reduced(messages: Iterable[Message]) -> tuple[Message, ...]
```

The kept messages, without sealed content when any were dropped.

#### KeepRecent.dropped

```text
dropped(messages: Iterable[Message]) -> tuple[Message, ...]
```

Everything before the cut, without the note of an earlier drop and without
recalled notes.

#### KeepRecent.to_dto

```text
to_dto() -> KeepRecent.Dto
```

A Dto capturing the complete internal state. Does not mutate the object.

#### KeepRecent.from_dto

```text
from_dto(dto: Dto) -> typing.Self
```

### Summarise

```python
from gvn.harness.context_window import Summarise
```

```text
Summarise(keep: int, brief: str = '', model_role: str | None = None) -> None
```

Replace all but the last ``keep`` messages with a model's summary of them.

``keep``: int >= 1. ``brief``: str, the summariser's instructions (``DEFAULT_BRIEF``
when empty). ``model_role``: None (the actor's own model) or the name of the role
whose model writes the summary (see the module docstring; a name as tool names are).
This step only says what to ask and what to keep; the actor asks its
model (one ``invoke_model`` request with ``brief()`` as instructions, ``asking(older)``
as messages and no tools) and then keeps ``summarised(text, recent)``. A summary that
fails, or comes back blank, falls back to ``fallback()`` for that round. It does not
apply when all it could summarise is an earlier summary or the note of an earlier
drop (``OMITTED``), so a failing summariser is not asked again about nothing. A lone
recalled note is summarised like any message: the summary then stands alone, and the
step stops applying.
TypeError/ValueError otherwise.

#### Summarise.model_role

```text
model_role() -> str | None
```

None, or the name of the role whose model writes the summary.

#### Summarise.dropped

```text
dropped(messages: Iterable[Message]) -> tuple[Message, ...]
```

What a summary would replace (``split(messages)[0]``), when the step applies,
without recalled notes.

#### Summarise.keep

```text
keep() -> int
```

#### Summarise.brief

```text
brief() -> str
```

The summariser's instructions: the brief given, else ``DEFAULT_BRIEF``.

#### Summarise.summarises

```text
summarises() -> bool
```

Whether this step needs a model call (True only for ``Summarise``).

#### Summarise.applies

```text
applies(messages: Iterable[Message]) -> bool
```

Whether this step would change ``messages`` (an iterable of Message).

#### Summarise.split

```text
split(messages: Iterable[Message]) -> tuple[tuple[Message, ...], tuple[Message, ...]]
```

``(older, recent)``: what a summary replaces and what stays.

#### Summarise.asking

```text
asking(older: Iterable[Message]) -> tuple[Message, ...]
```

``older`` without sealed content and with each attachment described rather than
sent, then the request to summarise.

#### Summarise.summarised

```text
summarised(text: str, recent: Iterable[Message]) -> tuple[Message, ...]
```

The summary as a user message, then ``recent`` without sealed content.

#### Summarise.fallback

```text
fallback() -> KeepRecent
```

The step used for a round whose summary failed: ``KeepRecent(keep)``.

#### Summarise.to_dto

```text
to_dto() -> Summarise.Dto
```

A Dto capturing the complete internal state. Does not mutate the object.

#### Summarise.from_dto

```text
from_dto(dto: Dto) -> typing.Self
```

### ContextBudget

```python
from gvn.harness.context_window import ContextBudget
```

```text
ContextBudget(
    limit: int | float = 1.0,
    reduce_at: int | float | None = None,
    reduce_over: int | None = None,
    steps: Iterable[Reduction] = (),
    remember_dropped: bool = False,
) -> None
```

How much of its model's context window an actor may use, and what it does as the
conversation fills it. Immutable, equal by content. See the module docstring for the
four settings and the check. ``ContextBudget()`` sets no number of its own: the
conversation may fill the model's window, and nothing is reduced.
TypeError/ValueError for anything the module docstring does not allow, and for a
``reduce_at`` above a ``limit`` given in the same form.

#### ContextBudget.remember_dropped

```text
remember_dropped() -> bool
```

Whether what a step takes out is first handed to a memory.

#### ContextBudget.model_roles

```text
model_roles() -> frozenset[str]
```

Frozenset of the model roles the steps name (``Summarise(model_role=)``);
empty when none does.

#### ContextBudget.dropping

```text
dropping(messages: Iterable[Message]) -> str
```

The text a memory is given before the step that applies to ``messages`` runs:
``transcribed`` of what that step would take out, recalled notes left out (``""``
when it would take out nothing else). ValueError when no step applies.

#### ContextBudget.limit

```text
limit() -> int | float
```

#### ContextBudget.reduce_at

```text
reduce_at() -> int | float | None
```

#### ContextBudget.reduce_over

```text
reduce_over() -> int | None
```

#### ContextBudget.steps

```text
steps() -> tuple[Reduction, ...]
```

Tuple of the reduction steps, in the order they are tried.

#### ContextBudget.step

```text
step(messages: Iterable[Message]) -> Reduction | None
```

The first step that applies to ``messages``, or None.

#### ContextBudget.verdict

```text
verdict(
    gauge: ContextGauge,
    messages: Iterable[Message],
    remembered: bool = False,
) -> Symbol
```

The Symbol of CONTEXT_OUTCOMES for ``gauge`` (a ContextGauge) and ``messages``
(the transcript), by the check in the module docstring, never ``recall_due`` (a
recall is the actor's, see ``ContextCheck``). ``remembered`` (a bool): whether
what the step now due would drop was already handed to a memory (or the memory
failed), so ``remember_due`` is not answered again; it is not answered either
when the step drops nothing but recalled notes. Changes nothing.

#### ContextBudget.to_dto

```text
to_dto() -> ContextBudget.Dto
```

A Dto capturing the complete internal state. Does not mutate the object.

#### ContextBudget.from_dto

```text
from_dto(dto: Dto) -> typing.Self
```

ValueError for a step kind this module does not have, or settings the
constructor would refuse.

### context_budget

```python
from gvn.harness.context_window import context_budget
```

```text
context_budget(value: ContextBudget | None) -> ContextBudget
```

``value`` as a ContextBudget: None is ``ContextBudget()``. TypeError otherwise.

### ContextCheck

```python
from gvn.harness.context_window import ContextCheck
```

```text
ContextCheck(
    budget: ContextBudget,
    gauge: ContextGauge,
    remembered: bool = False,
    recall_owed: bool = False,
) -> None
```

check_context: does the conversation fit the budget, is a reduction due, or is the
budget exhausted? ``decide(messages)`` judges the transcript against the ``budget``
and ``gauge`` it was built with; ``remembered`` is passed to ``ContextBudget.verdict``.
``recall_owed`` (a bool): the actor owes a recall for the user message it just took;
then the answer is ``recall_due``, before anything else, so that what the recall adds
is in the transcript when the context is checked.

#### ContextCheck.outcomes

```text
outcomes() -> Alphabet
```

The Alphabet of every answer this decision can give. Must not vary over time.

#### ContextCheck.judge

```text
judge(subject: object) -> Symbol
```

Inspect ``subject`` and return one Symbol from ``outcomes()``.

### FailureCheck

```python
from gvn.harness.context_window import FailureCheck
```

```text
FailureCheck()
```

classify_failure: did the model call fail because the conversation does not fit the
model's context window? ``decide(exceeded)`` takes the ``exceeded_context`` flag of a
``model_failed`` payload (a bool set by the vendor's adapter, never by a model).

#### FailureCheck.outcomes

```text
outcomes() -> Alphabet
```

The Alphabet of every answer this decision can give. Must not vary over time.

#### FailureCheck.judge

```text
judge(subject: object) -> Symbol
```

Inspect ``subject`` and return one Symbol from ``outcomes()``.

## gvn.harness.conversation

Conversation: an actor that talks with a person over many turns.

A Conversation thinks and uses tools exactly as the reference Agent does (the same
request kinds and payloads, the same policy, approval and statuses), but a reply
without tool calls goes to a person instead of ending the run: it asks
``request_input`` and parks until the person answers. The model ends the
conversation by calling the built-in ``close`` tool, offered automatically, with one
of the conversation's declared ``closings``. It is a separate actor: it shares
pieces of the tool loop with the Agent (gvn.harness.tools), and the management of its
context window with every actor (gvn.harness.context_window), not its machine.

    state                output                       input -> next state
    idle                 idle                         started -> admitting
    admitting            check_steps (internal)       within_steps -> measuring
                                                      steps_exhausted -> failed
    measuring            check_context (internal)     recall_due -> recalling
                                                      context_fits -> thinking
                                                      remember_due -> remembering
                                                      trim_due -> measuring
                                                      summary_due -> summarising
                                                      context_exhausted -> overflowed
    recalling            recall                       recalled -> measuring
                                                      recall_failed -> measuring
    remembering          remember                     remembered -> measuring
                                                      remember_failed -> measuring
    summarising          invoke_model                 model_replied -> measuring
                                                      model_failed -> measuring
    thinking             invoke_model                 model_replied -> interpreting
                                                      model_failed -> diagnosing
    diagnosing           classify_failure (internal)  failure_final -> failed
                                                      context_exceeded -> admitting
    interpreting         classify_reply (internal)    spoke -> listening
                                                      requested_tools -> vetting
                                                      requested_unoffered -> admitting
                                                      requested_close -> closed
                                                      requested_close_while_blocked
                                                        -> admitting
    vetting              consult_policy               cleared -> acting
                                                      needs_approval -> awaiting_approval
                                                      forbidden -> admitting
    awaiting_approval    request_approval             approved -> acting
                                                      denied -> admitting
    acting               invoke_tools                 tools_returned -> checking_sensors
    checking_sensors     check_sensors (internal)     sensors_due -> sensing
                                                      nothing_due -> admitting
    sensing              sense                        sensed -> admitting
                                                      sense_failed -> admitting
    listening            request_input                answered -> counting
                                                      withdrawn -> left
                                                      instructed -> listening
    counting             check_turns (internal)       turns_remain -> admitting
                                                      turns_exhausted -> exhausted
    suspended            suspended                    resumed -> checking_sensors
    suspended_listening  suspended                    resumed -> listening
    closed, exhausted, left, failed, overflowed (final)

``interrupted`` is declared in recalling, remembering, summarising, thinking, vetting,
awaiting_approval, acting and sensing (leading to suspended) and in listening (leading to
suspended_listening, so that resuming asks the person the same question again, not the
model). Everything else is ``otherwise: stay``: rejected, changing nothing. The six internal
decisions and the policy verdict are routed with ``branch``, so the verifier holds
the machine to every outcome. Text from the model or the person, a summary and an
instruction never route.

Event payloads (anything else is a ValueError that changes nothing):

    started          {"text": str, "attachments": [<plain form of Attachment.Dto>...]}
                     trusted text from the code that starts the conversation, appended
                     as a user message with the attachments (optional: images and
                     documents sent after the text, each checked as
                     ``Message.user(..., attachments=)`` checks it). With no
                     attachments, the text may be "" only when the conversation
                     continues a ``thread`` that does not end with an assistant
                     message; then nothing is appended.
    model_replied    {"message": <plain form of an assistant Message.Dto>,
                      "usage": {"input_tokens": int >= 0, "output_tokens": int >= 0,
                                "cache_read_tokens": int >= 0,
                                "cache_write_tokens": int >= 0},
                      "context_window": int >= 1}
                     "usage" and "context_window" optional, and usage's two cache
                     figures too; "retries" may be present (gvn.harness.replies). In
                     thinking, usage and context_window are the conversation's
                     measurement (see the data rules); nothing else reads them. The
                     message's sealed content never routes and never reaches the
                     policy, an approver, a tool, a summariser or the outcome.
    model_failed     {"reason": str}, optionally with "retryable", "retry_after",
                     "usage", "retries" (recorded, never routed) and
                     "exceeded_context": bool, set by the vendor's adapter when the
                     vendor refused the conversation as too large; only in thinking
                     does it route (through classify_failure).
    tools_returned   {"results": [<plain form of ToolResult.Dto>, ...]}  one per pending call
    cleared, needs_approval, forbidden, approved, denied
                     as the agent's (gvn.harness.agent): per-call verdicts and per-call
                     denials ride on them as data
    answered         {"text": str, "by": str or None, "data": {...} or None,
                      "attachments": [<plain form of Attachment.Dto>...]}; "by", "data"
                     and "attachments" may be absent, and "choice" may be present only
                     as None (the answer family of gvn.harness.inquiry). A text longer
                     than ``limit`` is a ValueError. The attachments (an image or a PDF
                     the person sends) are checked as on ``started``; the ``limit``
                     counts the text only.
    withdrawn        None or {"by": str or None}
    instructed       {"text": non-empty str}: trusted text from harness code (never
                     from the person or a model) for the model to read after the
                     person's next answer: the trusted channel into a running
                     conversation (see the data rules)
    remembered       {"entry": str}: the id the memory gave what it now holds
                     (gvn.harness.replies ``REMEMBERED``); recorded only as a count
    remember_failed  {"reason": str} (``REMEMBER_FAILED``); recorded only as a count
    recalled         {"entries": [{"id": str, "text": str}, ...]}: at most
                     ``recall_limit`` entries, best first (gvn.harness.replies
                     ``RECALLED_REPLY``); more is a ValueError
    recall_failed    {"reason": str} (``RECALL_FAILED``); recorded only as a count
    sensed           {"readings": [...]}, sense_failed {"reason": str}: as the agent's
                     (gvn.harness.agent, gvn.harness.sensors)
    interrupted, resumed    None
    within_steps, steps_exhausted, recall_due, context_fits, remember_due, trim_due,
    summary_due,
    context_exhausted, failure_final, context_exceeded, spoke, requested_tools,
    requested_unoffered, requested_close, requested_close_while_blocked, turns_remain,
    turns_exhausted, sensors_due, nothing_due
                     internal; an Event carrying one from outside is a ValueError

Request payloads (the last four of the agent's kinds are exactly the agent's):

    invoke_model       {"instructions": str, "messages": [<Message.Dto plain>...],
                        "tools": [identity...], "provided": [<spec plain>],
                        "context": {...}, "model_role": str}
                       ``model_role`` only when the conversation names one.
                       ``tools`` is the identities of the conversation's tools, sorted
                       (``close`` is not among them: it is carried).
                       ``provided`` carries the spec of ``close`` (gvn.harness.tools
                       ``spec_plain``: name, description, arguments as JSON Schema with
                       ``closing`` one of the closings), so the ``ModelFulfiller`` offers
                       it without any host registering it. While summarising: the
                       ``Summarise`` step's ``brief()`` as instructions, its
                       ``asking(older)`` as messages, ``"tools": []``, no
                       ``provided``, and as ``model_role`` the step's role, else the
                       conversation's, else none.
    remember           {"text": str, "context": {...}}
                       ``text`` is ``budget.dropping(messages)``: the transcript of
                       exactly what the step now due will take out
    recall             {"query": str, "limit": int, "context": {...}}
                       ``query`` is the text of the user message just taken,
                       ``limit`` the conversation's ``recall_limit``; no scope: the
                       fulfiller resolves it from trusted wiring
    sense              {"readings": [{"sensor", "tool", "arguments"}, ...],
                        "context": {...}}  as the agent's
    consult_policy     {"calls": [<ToolCall.Dto plain>...], "identities": [...],
                        "context": {...}}  plus "exposure": [<source>...] (sorted) once
                        the exposure is not empty
    request_approval   {"calls": [...], "identities": [...], "text": str, "context": {...}}
                       plus "exposure" as for consult_policy
    invoke_tools       {"calls": [...], "identities": [...], "context": {...}}
    request_input      {"audience": str, "text": <the model's reply>, "choices": [],
                        "limit": int or None, "turn": int, "context": {...}}
                       ``turn``: which exchange with the person this is, counting
                       from 1 (the same number the request id ends with)

``context`` is the run context (``{}`` when none was given): trusted plain JSON from
the code that built the conversation, fixed for its life, never from a model or the
person.

Request ids. ``request_input`` has id ``"<name>/request_input#<turn>"``, ``turn``
counting from 1 (code that needs the turn reads the payload's ``"turn"`` rather than
parsing the id): it is the same Request (id and payload) for as long as that turn's
question stands, across ``instructed``, interrupt/resume, crash and revival, so an
answer tied to it (``Governor.answer``) stays valid while the run is parked. Every
other request has id ``"<name>/<machine step count>"``, as the agent's: stable across
a crash (a revived conversation asks for the same work under the same id), but NOT
across interrupt/resume, which asks the model again under a new id; an effect that
must happen at most once is keyed by what it is, from the trusted context (see
``Tool.run``). Ids restart in a new Conversation, also one built with ``thread=``:
give each its own name.

Data rules, applied only when the event's step was declared:

* started appends the user message (see above). model_replied in thinking appends
  the assistant message; tools_returned appends one tool message with the results;
  answered appends the person's text, with their attachments, as a user message:
  ``by`` and ``data`` are checked and dropped, and the person's text and attachments
  never reach a context, a request other than invoke_model, or a route.
* instructed (only while listening) holds its text; a second one is joined to it,
  in order, with a blank line. The next answered appends the held text as
  ``Message.instruction`` directly after the person's user message, and nothing is
  held any more; withdrawn drops it. It survives interrupt/resume and revival, and
  the question (request_input) does not change. Only this rule creates an
  instruction message: never a model reply, a tool result or an answer.
* check_steps answers steps_exhausted when ``steps`` model calls were made in this
  turn, else within_steps. Entering thinking spends one step. A turn begins with
  started and with every answered; summary calls are not steps.
* The context: the conversation owns a ``ContextGauge`` and its ``ContextBudget``
  (gvn.harness.context_window), and check_context is that module's ``ContextCheck``
  over the transcript. Every tool call is answered in measuring, so reductions
  happen only there.
  - model_replied in thinking measures: ``gauge.measure(usage, context_window)``. A
    summary call's usage is not a measurement of the conversation.
  - trim_due: the transcript becomes ``step.reduced(messages)`` for the budget's
    first step that applies (one that needs no model), then ``gauge.reduced()``.
  - summary_due: ``invoke_model`` as above for the budget's first step that applies
    (a ``Summarise``). In summarising, a model_replied with text keeps
    ``step.summarised(text, recent)`` (its calls are ignored); a blank reply, and
    model_failed, keep ``step.fallback().reduced(messages)``. Then
    ``gauge.reduced()``. The budget's own rules end repeated reductions.
  - classify_failure is ``FailureCheck`` over the payload's ``exceeded_context``.
    failure_final stores the reason (the conversation fails); context_exceeded calls
    ``gauge.refused()`` and stores nothing: the route goes back through admitting,
    so the step budget bounds the retries.
  - context_exhausted: the final state overflowed, with a reason.
  - remember_due (only with ``ContextBudget(remember_dropped=True)``): the
    ``remember`` request above. The conversation keeps one flag, "this loss was handed
    over": remembered and remember_failed set it and count one each, and check_context
    is ``ContextCheck(budget, gauge, flag)``, so the step then runs (a memory that
    fails does not stop the conversation: it reduces anyway). Applying a reduction
    (trim_due, a summary or its fallback) clears the flag, so the next step's loss is
    handed over in its turn; a summary round is one loss, so the flag stays set
    through summarising. An interruption while remembering sets nothing: after
    resuming, the same loss is asked to be remembered again, under a new request id.
    An instruction held while listening is not touched by any of this.
* Automatic recall (``recall=True``; off by default, and then none of this happens: the
  requests, events and routes are those of a conversation without the option). started
  that appends a user message whose text is not blank, and every answered whose text is
  not blank, make the conversation owe a recall for that text; check_context answers
  recall_due before it checks the context (``ContextCheck(..., recall_owed=True)``), so
  the budget measures what the recall adds, and since admitting and counting come
  first, a turn that cannot reach the model (its turns used up) recalls nothing.
  recalling asks for ``recall`` (above) and counts one ``"asked"``. ``recalled`` with
  entries appends ONE user message, ``recalled_note(<their texts, in order>)``
  (gvn.harness.context_window: the header ``RECALLED``, then one block per entry),
  after the person's message and the instruction that follows it, and adds their
  number to ``"found"``; with none it appends nothing. ``recall_failed`` appends
  nothing and counts one ``"failed"``: a failing memory does not stop the
  conversation. An interruption while recalling leaves the recall owed: after
  resuming it is asked again under a new id (a read: repeating it is harmless).
  Recalling spends no step. The note is not the person's: it is never counted as a
  turn, never measured against ``limit``, and an answer is never the note. It is
  untrusted content (never an instruction message, never in ``instructions``); the
  query is the person's text, data for the memory; the scope is resolved by the
  fulfiller from trusted wiring, never sent. A ``thread`` carried to a next
  conversation keeps the notes, and when the conversation ends right after recalling
  (a failed or overflowed turn), its thread ends with a note: code that reads the
  person's last message from a thread skips messages for which
  ``gvn.harness.context_window.is_recalled_note`` is true.
* Sensors (``sensors=``, gvn.harness.sensors), exactly as the agent's: tools_returned
  owes a reading to every sensor a watched tool's success makes due, checking_sensors
  (``SensorCheck``) sends a conversation that owes some to sensing, ``sensed`` appends
  ONE user message (``readings_note``) and records the latest reading per sensor,
  ``sense_failed`` counts them failed, and an interruption while sensing leaves them
  owed (resumed goes through checking_sensors). A blocking sensor blocks the CLOSING,
  never a reply to the person: a valid close while one reads not clean is
  requested_close_while_blocked, whose close call is settled ``blocked`` with a failed
  result naming the sensors (``blocked_note``), and the conversation goes back through
  admitting, so the step budget bounds it; steps_exhausted then names those sensors.
* classify_reply answers spoke when the reply has no calls; requested_close when its
  only call is ``close`` with arguments exactly ``{"closing": &lt;one of closings>,
  "text": str}`` (requested_close_while_blocked when a blocking sensor's latest reading
  is not clean); requested_unoffered when any call names a tool not offered or is a
  ``close`` call that is not that; else requested_tools.
* requested_unoffered abandons the batch, as the agent does: every call that is a
  bad ``close`` or names a tool not offered is settled ``unoffered``, the others
  ``abandoned``. requested_close settles the close call ``ok`` (detail
  ``{"closing": ...}``), so the transcript stays well formed.
* Verdicts, approvals and refusals are per call, exactly as the agent's: forbidden
  and denied settle the reply's calls with a failed result each (forbidden, skipped,
  denied or abandoned), interrupted (while vetting, awaiting approval or acting)
  abandons them, and acting runs only the calls cleared or approved.
* Exposure, exactly as the agent's (gvn.harness.agent): the conversation records which
  untrusted sources its model has read and hands them to the policy and the approver.
  The tools offered whose ``untrusted()`` is True are read once, when it is built.
  A conversation that continues a ``thread`` starts with the exposure of the
  conversation that left it (``thread_exposure``: that outcome's ``"exposure"``): a
  model handed a transcript holding untrusted text has read it. tools_returned adds the
  identity of every call to an untrusted tool whose tool actually ran
  (``gvn.harness.tools.exposed_by``: ``ok``, or ``failed`` unless the tool was never
  run); ``recalled`` with entries adds ``gvn.harness.tools.RECALLED_SOURCE``. Nothing
  else adds to it (not the person's answers, not an instruction, not ``close``), and
  nothing removes it: a reduction, an interruption, a new turn and a revival all keep
  it.
* answered counts a turn; check_turns answers turns_exhausted when ``turns`` answers
  have been received. turns_remain starts a new turn: its attempts start empty.
* Every settled call is recorded twice: in the attempts of the current turn, and as one
  count in the tally, under its tool's identity and status (``close`` under
  ``"close"``). A call naming a tool not offered is counted under ``"*"``, so the tally
  is bounded by the offered tools (with ``close`` and ``"*"``) times the statuses.
  Calls name tools by short name (what the model sends); each is known by the identity
  of the offered tool of that name, recorded in every request and attempt (None for
  ``close`` and for a call not offered).

A transcript (the one kept, and a ``thread=``) is well formed when every batch of
calls is answered by the tool message right after it, every tool message answers the
batch right before it, and every instruction message directly follows a user message.

Outcome, in every final state:

    {"closing": <the closing, or None unless closed>,
     "text": <closed: the close call's text; otherwise the last assistant text, "">,
     "turns": <answers received>,
     "attempts": [<as the agent's, for the last turn only: every tool call made since
                   the last turn began (``close`` included), in order>],
     "tally": {<tool identity, "close" or "*">: {<status>: count}}  over the whole
               conversation,
     "reductions": {"trimmed": int, "summarised": int, "fell_back": int,
                    "remembered": int, "unremembered": int},
     "recalls": {"asked": <recall requests issued>, "found": <entries appended>,
                 "failed": <recall requests answered recall_failed>}  (0s when off),
     "readings": {"taken", "failed", "blocked", "latest": {...}}  as the agent's,
     "thread": <plain form of the Transcript.Dto as kept, without sealed content:
                what ``thread=`` takes>}

failed and overflowed add ``"reason"``; every final state adds ``"exposure"``:
[&lt;source>...] (sorted), only when the exposure is not empty: what a next conversation
takes as ``thread_exposure`` with the ``thread``. A host routes on the closing through
``Closing(closings)``, a Decision over the finite set (closings plus exhausted, left,
failed, overflowed). ``remembered`` and ``unremembered`` count the answers to
``remember`` (remembered, remember_failed).

Durable form: the Dto holds the machine's Position, the transcript as reduced, the
pending calls, this turn's attempts, the tally, the context budget and gauge, the
reduction counts, the "handed over" flag, the model role, the instruction held while
listening, the recall settings, the text whose recall is owed, the recall counts, the
sensors with their readings, and (when not empty) the untrusted tools, the exposure and
the part of it that came with the thread.
With a budget whose steps bound the transcript (``KeepRecent``, ``Summarise`` with
``reduce_over``) it is bounded by the budget and one turn's work (``steps`` replies), not
by the conversation's length; with ``ContextBudget()`` the transcript alone grows. The
journal keeps every event, so replay rebuilds the same state.

Constants: `CONTEXT_OUTCOMES`, `FAILURE_OUTCOMES`, `ASSISTANT`, `INSTRUCTION`, `TOOL`, `USER`, `MODEL_FAILED`, `MODEL_REPLIED`, `RECALL_FAILED`, `RECALLED_REPLY`, `REMEMBER_FAILED`, `REMEMBERED`, `SENSE_FAILED`, `SENSED`, `SENSOR_OUTCOMES`, `APPROVED_PAYLOAD`, `ATTEMPT_STATUSES`, `INTERRUPTED_DETAIL`, `RECALLED_SOURCE`, `TOOLS_RETURNED`, `VERDICT_PAYLOAD`, `VERDICTS`, `CLOSE`, `ENDINGS`.

### Closing

```python
from gvn.harness.conversation import Closing
```

```text
Closing(closings: Iterable[str] = ('closed',)) -> None
```

Routes on how a conversation ended: its closing when closed, else the final state.

``Closing(closings)``: the conversation's closings (distinct names, none of
``ENDINGS``). ``outcomes()`` is those names plus exhausted, left, failed and
overflowed.
``judge`` takes the conversation's Outcome, or anything whose ``outcome()`` is one
(a workflow's Ending), so a hosting stage is ``Host(..., judge=Closing(closings))``.
Only the closing (a name from the finite set) and the final state are read: never
the text. TypeError for any other subject.

#### Closing.outcomes

```text
outcomes() -> Alphabet
```

The Alphabet of every answer this decision can give. Must not vary over time.

#### Closing.judge

```text
judge(subject: object) -> Symbol
```

Inspect ``subject`` and return one Symbol from ``outcomes()``.

### Conversation

```python
from gvn.harness.conversation import Conversation
```

```text
Conversation(
    name: str,
    instructions: str,
    audience: str,
    tools: Toolbox | Iterable[Tool] = (),
    closings: Iterable[str] = ('closed',),
    turns: int = 20,
    steps: int = 10,
    context_budget: ContextBudget | None = None,
    thread: Transcript.Dto | Mapping[str, typing.Any] | None = None,
    context: Mapping[str, typing.Any] | None = None,
    limit: int | None = None,
    model_role: str | None = None,
    recall: bool = False,
    recall_limit: int = 5,
    sensors: Iterable[Sensor] = (),
    thread_exposure: Iterable[str] = (),
) -> None
```

Talks with a person over many turns, using tools as the agent does.

#### Conversation.definition

```text
definition() -> Definition
```

The verified Definition of the machine above (shared).

#### Conversation.name

```text
name() -> str
```

The actor's address: a non-empty str, stable for its whole life.

#### Conversation.instructions

```text
instructions() -> str
```

#### Conversation.audience

```text
audience() -> str
```

#### Conversation.tool_identities

```text
tool_identities() -> frozenset[str]
```

Frozenset of the identities of the tools offered besides ``close``
(``Actor.tool_identities``).

#### Conversation.closings

```text
closings() -> tuple[str, ...]
```

The tuple of closing names, in the order given.

#### Conversation.context_budget

```text
context_budget() -> ContextBudget
```

The ContextBudget (an immutable value).

#### Conversation.limit

```text
limit() -> int | None
```

#### Conversation.model_role

```text
model_role() -> str | None
```

None, or the name of the role whose model the conversation asks.

#### Conversation.model_roles

```text
model_roles() -> frozenset[str]
```

Frozenset of the model roles this actor may ask for (``Actor.model_roles``):
its own and those its context budget's steps name.

#### Conversation.recall

```text
recall() -> bool
```

Whether the conversation asks a memory, by itself, for entries matching each
message of the person.

#### Conversation.sensors

```text
sensors() -> tuple[Sensor, ...]
```

The tuple of the conversation's Sensors, in the order given.

#### Conversation.sensor_identities

```text
sensor_identities() -> frozenset[str]
```

Frozenset of the identities of its sensors' measuring tools
(``Actor.sensor_identities``).

#### Conversation.recall_limit

```text
recall_limit() -> int
```

The most entries each of the conversation's own recalls asks for.

#### Conversation.context

```text
context() -> dict[str, typing.Any]
```

A fresh copy of the run context; ``{}`` when none was given.

#### Conversation.exposure

```text
exposure() -> frozenset[str]
```

Frozenset of the sources of untrusted content the conversation's model has read
so far: the identity of each untrusted tool whose result it was handed, and
``gvn.harness.tools.RECALLED_SOURCE`` once a recall of its own appended notes.
Empty until then; it only grows (see the module docstring).

#### Conversation.transcript

```text
transcript() -> tuple[Message, ...]
```

Tuple of the Messages kept, oldest first.

#### Conversation.turns_used

```text
turns_used() -> int
```

How many answers the person has given.

#### Conversation.turns_remaining

```text
turns_remaining() -> int
```

#### Conversation.state

```text
state() -> State
```

The current control State.

#### Conversation.expected

```text
expected() -> frozenset[Symbol]
```

Frozenset of the Symbols with a declared transition from the current state.

#### Conversation.finished

```text
finished() -> bool
```

True when the control state is final.

#### Conversation.pending

```text
pending() -> tuple[Request, ...]
```

``()`` or ``(request,)``: built once per state entered, never per call.

#### Conversation.handle

```text
handle(event: Event) -> Reaction
```

Consume an Event and return the Reaction. Synchronous, no I/O.

Raises UnknownSymbol when the event's name is not in the actor's input
alphabet, and ValueError when its payload does not fit what that input
requires; in both cases the actor is unchanged. An event that is valid but
not expected in the current state is not an error: it returns a rejected
Reaction and changes nothing, data included.

Addresses: an event whose ``to()`` is neither None, the actor's own name nor
(for composite actors) the name of something beneath it raises ValueError and
changes nothing. After the call, ``reaction.requests() == self.pending()``.

#### Conversation.settles

```text
settles(event: Event) -> bool
```

Could handling ``event`` leave the conversation finished? Changes nothing.

Not declared here: False. A step into a final state: True. Into admitting
(check_steps): True when this turn's steps are used up (nothing is spent
before the check) or when the context could be exhausted (the gauge, as the
event leaves it, says the vendor refused the last call or the last reply
reached the budget's limit; whether a reduction step would still apply is not
worked out, so this may say True for an event that ends in a reduction). Into
measuring from summarising: False (a reduction leaves the size unknown, which
never exhausts the budget). Into measuring from remembering: False (the step
whose loss was handed over still applies, so a reduction follows). Into
measuring from recalling: True when the gauge alone says the context is
exhausted (whether a step would then apply is not worked out), else False. Into
diagnosing (a model failure): True, except that a refusal as too large is True
exactly when the steps are used up or no reduction step applies. Into
interpreting (a model reply): True for a valid close call alone, False for a
reply to the person or offered tools, and for a refused batch or a close a
sensor blocks as for admitting, with the reply measured. Into checking_sensors
(tools returned, resumed): False when readings are owed already, else as for
admitting (a sensor due after the batch is not worked out: True is safe). Into counting (an
answer): True when that answer is the last turn allowed, else as for
admitting. Anywhere else the conversation stops to wait: False. Not an Event,
an unknown symbol or a payload that does not parse: True (an event ``handle``
refuses changes nothing, so either answer is safe).

#### Conversation.outcome

```text
outcome() -> Outcome
```

The Outcome. Raises NotFinished unless ``finished()``.

#### Conversation.to_dto

```text
to_dto() -> Conversation.Dto
```

A Dto capturing the complete internal state. Does not mutate the object.

#### Conversation.from_dto

```text
from_dto(dto: Dto) -> typing.Self
```

Rehydrate. TypeError for a foreign Dto; ValueError for one no Conversation
could have produced (bad settings, a position on another definition, pending
calls, a failure, a closing or a held instruction where the state does not have
them, counters past their allowance, a transcript that is not well formed as
the state says, summarising with no summary step that applies, remembering
with nothing to remember, memory counts or a "handed over" flag the budget and
the state rule out, an invalid model role).

## gvn.harness.errand

Errands: tool calls fixed by code, made under the policy, with no model.

An Errand is the smallest actor that does something to the outside world: a
batch of tool calls chosen by code (a plan's ``make`` function, say, as
``gvn.harness.tools.FixedCall``: a call id, the Tool object, the arguments), passed
through the policy and, when the policy asks for it, a person's approval, then
run once. It issues exactly the reference agent's request kinds with exactly
its payloads, so the standard fulfillers serve it unchanged and checks that read
those requests (``Gated``) see it. One request carries the whole batch.

Control flow is the Moore machine below. ``check_results`` is a decision the
errand resolves itself inside ``handle``; the other outputs of vetting,
awaiting_approval and acting become Requests.

    state              output                      input -> next state
    idle               idle                        started -> vetting
    vetting            consult_policy              cleared -> acting
                                                   needs_approval -> awaiting_approval
                                                   forbidden -> refused
    awaiting_approval  request_approval            approved -> acting
                                                   denied -> declined
    acting             invoke_tools                tools_returned -> checking
    checking           check_results (internal)    succeeded -> done
                                                   call_failed -> failed
                                                   call_refused -> refused
    suspended          suspended                   resumed -> vetting
    done, failed, refused, declined (final)

``interrupted`` is declared in vetting, awaiting_approval and acting and leads to
suspended. Every other input is covered by ``otherwise: stay``: it is rejected
and changes nothing. Final states absorb everything. The policy verdict and
check_results are routed with ``branch``, so the verifier holds the machine to
every outcome. ``succeeded``, ``call_failed`` and ``call_refused`` are internal: an
Event carrying one from outside is a ValueError.

check_results reads the status of every call once the tools returned: ``call_failed``
when a call that ran failed (a failure wins over a refusal); else ``call_refused`` when
some call did not run because it was refused (``forbidden``, ``denied`` or ``skipped``);
else ``succeeded``. So a host can route "a tool failed" and "the policy or a person
refused part of the batch" apart.

Event payloads (anything else is a ValueError that changes nothing):

    tools_returned     {"results": [<plain form of ToolResult.Dto>, ...]}, exactly one
                       result per call of the errand, in any order; "retries" optional
                       (gvn.harness.tools.TOOLS_RETURNED): recorded, never used
    cleared, needs_approval, forbidden, approved, denied
                       as the agent's (gvn.harness.agent): per-call verdicts and per-call
                       denials ride on them as data
    started, interrupted, resumed   None

Request payloads (the reference agent's, see gvn.harness.agent):

    consult_policy     {"calls": [<ToolCall.Dto plain>...], "identities": [<the identity
                        of each call's tool>...], "context": {...}}
    request_approval   {"calls": [...], "identities": [...], "text": str, "context": {...}}
                       only the calls asked about, with "positions" and "beside" when
                       not all are
    invoke_tools       {"calls": [...], "identities": [...], "context": {...}}  with
                       "refused" when some are

Verdicts are per call, as the agent's (gvn.harness.tools): a person is asked only about
the calls that need it, and acting runs only the calls cleared or approved; the others
are answered refused, and a refusal skips every later call that is not independent.

Request ids are ``"<errand name>/<request kind>"`` (``"<name>/consult_policy"``,
``"<name>/request_approval"``, ``"<name>/invoke_tools"``): stable for the life of
the errand, because the batch is fixed by construction and the same work must
carry the same identity. ``Request.origin()`` is the errand's name; the three ids
are distinct, and a request of one kind is the same Request (id, kind and
payload) every time the errand asks for it. ``context`` is the run
context (``{}`` when none was given): trusted data from the code that built the
errand, handed to the policy and to every tool. ``text`` is what a person asked
to approve is shown.

Outcome payload, in every final state: ``{"attempts": [...]}``, one entry per call
in the order given, ``{"name", "identity", "arguments", "status", "detail"}``, with the
statuses and details of gvn.harness.tools (the same as the agent's attempts):

    done       every call ``ok``, detail the tool's content
    failed     at least one call that ran is ``failed``; the others ``ok``, or
               ``forbidden``, ``denied`` or ``skipped`` for a call that did not run
    refused    no call that ran failed, and at least one call did not run. Either the
               policy forbade the batch (from vetting: ``forbidden`` per call, ``skipped``
               for a call needing approval after a forbidden one, details
               ``FORBIDDEN_DETAIL`` / ``SKIPPED_DETAIL``), or the errand acted on part
               of it (from checking: ``ok`` per call that ran, ``forbidden``, ``denied``
               or ``skipped`` per call that did not)
    declined   ``denied`` per call asked about, detail ``denied_detail(reason)``; the
               others ``forbidden``, ``skipped``, or ``abandoned`` (cleared, but the
               person's denial abandons the whole batch)

With bare verdict symbols (one verdict for the batch) these are exactly: done every
call ok, failed some call failed, refused every call forbidden, declined every call
denied.

``abandoned`` appears only as said above: an errand interrupted while acting drops the batch in
flight (a late ``tools_returned`` is rejected while suspended) and, once resumed,
goes back to vetting and asks again for the whole batch. Because ids are stable,
that repeat carries the same request ids, so ``ToolFulfiller`` gives every tool the
same key (``"<name>/invoke_tools#<call id>"``) as before the interrupt, and as
after a crash: for tools idempotent by key, each call's effect is applied exactly
once across crashes AND interrupt/resume.

What does NOT carry over: an approval or a verdict given before the interrupt.
Resuming re-vets, and asks for approval again if the policy says so; the question
is the same Request, so an answer tied to it (``Governor.answer``) is accepted for
the new asking. The Governor treats a request that disappears (suspended) and
reappears (resumed) as new work and fulfils it again, at least once, under the
same key; a result of the cancelled flight is discarded by the Governor.

Constants: `APPROVED_PAYLOAD`, `REFUSALS`, `TOOLS_RETURNED`, `VERDICT_PAYLOAD`, `VERDICTS`.

### Errand

```python
from gvn.harness.errand import Errand
```

```text
Errand(
    name: str,
    calls: Iterable[FixedCall],
    context: Mapping[str, typing.Any] | None = None,
    text: str = '',
) -> None
```

A batch of tool calls fixed by code, made under the policy, with no model.

#### Errand.definition

```text
definition() -> Definition
```

The verified Definition of the machine above (shared).

#### Errand.name

```text
name() -> str
```

The actor's address: a non-empty str, stable for its whole life.

#### Errand.calls

```text
calls() -> tuple[ToolCall, ...]
```

The tuple of ToolCalls this errand makes, in the order given.

#### Errand.identities

```text
identities() -> tuple[str, ...]
```

The tuple of the identity of each call's tool, in call order.

#### Errand.tool_identities

```text
tool_identities() -> frozenset[str]
```

Frozenset of the identities of the tools its calls name
(``Actor.tool_identities``).

#### Errand.context

```text
context() -> dict[str, typing.Any]
```

A fresh copy of the run context; ``{}`` when none was given.

#### Errand.text

```text
text() -> str
```

What a person asked to approve is shown.

#### Errand.handle

```text
handle(event: Event) -> Reaction
```

Consume an Event and return the Reaction. Synchronous, no I/O.

Raises UnknownSymbol when the event's name is not in the actor's input
alphabet, and ValueError when its payload does not fit what that input
requires; in both cases the actor is unchanged. An event that is valid but
not expected in the current state is not an error: it returns a rejected
Reaction and changes nothing, data included.

Addresses: an event whose ``to()`` is neither None, the actor's own name nor
(for composite actors) the name of something beneath it raises ValueError and
changes nothing. After the call, ``reaction.requests() == self.pending()``.

#### Errand.settles

```text
settles(event: Event) -> bool
```

Could handling ``event`` now finish this errand? Read from the definition:
only a declared step into a final state, or into ``checking`` (which always
ends in done, failed or refused), can. Anything handle would refuse answers True.

#### Errand.pending

```text
pending() -> tuple[Request, ...]
```

``()`` or ``(request,)``: built once per state entered, never per call.

#### Errand.state

```text
state() -> State
```

The current control State.

#### Errand.expected

```text
expected() -> frozenset[Symbol]
```

Frozenset of the Symbols with a declared transition from the current state.

#### Errand.finished

```text
finished() -> bool
```

True when the control state is final.

#### Errand.outcome

```text
outcome() -> Outcome
```

The Outcome. Raises NotFinished unless ``finished()``.

#### Errand.to_dto

```text
to_dto() -> Errand.Dto
```

A Dto capturing the complete internal state. Does not mutate the object.

#### Errand.from_dto

```text
from_dto(dto: Dto) -> typing.Self
```

Rehydrate. TypeError for a foreign Dto; ValueError for one no Errand could have
produced: no name or calls, duplicate call ids, identities that are not one per
call naming its tool, a position on another definition
or at rest in ``checking``, results outside done/failed/refused (or missing there
but in refused) or not answering the calls in order or disagreeing with the state,
a reason outside declined.

## gvn.harness.events

Events and requests: the payload-carrying counterparts of kernel symbols.

An Event says something happened. A Request says a machine wants work done.
Both are immutable values, equal by content, Durable, with plain-JSON payloads.
A Principal says who an event from outside came from, as the deployment's entry
point vouches for it (``gvn.harness.answering``).

Constants: `READ_CLOCK`, `CLOCK_READ`, `WAKE_AT`, `WOKE`, `ANSWERS`.

### TooLate

```python
from gvn.harness.events import TooLate
```

```text
TooLate(message: str, result: object) -> None
```

An answer to a request came after a deadline that had already passed: the
deadline was applied first (its ``woke`` journaled), the answered request went
away, and the run was driven on from there. ``result()`` is how that drive ended
(the runtime's Result: waiting or finished).

Raised by the runtime (``gvn.runtime.governor.Governor.answer``); defined here so
that code answering requests can catch it with the harness alone.

#### TooLate.result

```text
result() -> object
```

The Result of driving the run on after the deadline (waiting or finished).

### Principal

```python
from gvn.harness.events import Principal
```

```text
Principal(
    subject: str,
    issuer: str | None = None,
    claims: Mapping[str, typing.Any] | None = None,
) -> None
```

Who an event from outside came from: a person or system that the deployment's
entry point authenticated and vouches for. Immutable value, equal by content.

gvn authenticates nobody. The entry point (a web handler, a chat integration, a
command line) does, and hands what it vouches for to ``Governor.answer(...,
by=principal)``, which stamps it on the answering Event (``Event.by()``).

``subject``: who, a non-empty str stable within the issuer (a user id, an email).
``issuer``: None or a non-empty str, who vouched: the identity provider's name or
URL. ``claims``: None or a dict of plain JSON (groups, roles, whatever the entry
point took from the authenticated session), copied; ``{}`` when None.
TypeError/ValueError for anything malformed.

The claims are TRUSTED data, and only because they come from the entry point: never
build a Principal from what a model wrote or from an answer's own payload. They are
journaled with the event, but ``repr`` (and every message gvn writes) shows only the
subject and issuer, never the claims.

#### Principal.subject

```text
subject() -> str
```

Who: a non-empty str, stable within the issuer.

#### Principal.issuer

```text
issuer() -> str | None
```

Who vouched for the subject, a str, or None.

#### Principal.claims

```text
claims() -> dict[str, typing.Any]
```

A fresh copy of the claims (a dict; ``{}`` when none were given).

#### Principal.to_dto

```text
to_dto() -> Dto
```

A Dto capturing the complete internal state. Does not mutate the object.

#### Principal.from_dto

```text
from_dto(dto: Dto) -> typing.Self
```

Rehydrate. TypeError for a foreign Dto; ValueError for an empty subject or
issuer.

### Event

```python
from gvn.harness.events import Event
```

```text
Event(
    name: str | Symbol,
    payload: typing.Any = None,
    to: str | None = None,
    by: Principal | None = None,
) -> None
```

An input (named by an input symbol) plus the data that came with it, optionally
an address, and optionally who it came from.

The address (``to``) names the actor the event is for; None means the actor it is
delivered to. ``by`` is the Principal an outside answer came from, as the entry
point vouched for it (``Governor.answer(..., by=)`` stamps it; None for every event
nobody outside vouched for). Both are part of the event's identity (equality, hash,
plain form). The plain form carries ``"by"`` only when the event has one, so an
event without it reads and writes exactly as before there was one.

#### Event.to

```text
to() -> str | None
```

The name of the actor the event is for, or None.

#### Event.by

```text
by() -> Principal | None
```

The Principal this event came from, or None.

#### Event.addressed

```text
addressed(to: str | None) -> typing.Self
```

An equal event with a different address (None clears it); who it came from
is kept.

#### Event.answered_by

```text
answered_by(by: Principal | None) -> typing.Self
```

An equal event that says who it came from (None clears it). TypeError unless
``by`` is a Principal or None.

#### Event.name

```text
name() -> str
```

The name of the input this event is, a str (a machine that needs the Symbol
looks the name up in its own input alphabet).

#### Event.payload

```text
payload() -> typing.Any
```

The payload; containers are returned as fresh copies.

#### Event.to_dto

```text
to_dto() -> Dto
```

A Dto capturing the complete internal state. Does not mutate the object.

#### Event.from_dto

```text
from_dto(dto: Dto) -> typing.Self
```

### Request

```python
from gvn.harness.events import Request
```

```text
Request(request_id: str, kind: str | Symbol, payload: typing.Any = None) -> None
```

An output symbol plus the data needed to do the work, and a stable request id.

The request id is deterministic, so the same request re-issued after a crash
carries the same id. Request ids have the form ``"<actor name>/<step count>"``:
the part before the last ``"/"`` is the name of the actor that issued the
request (``origin()``); actor names may themselves contain ``"/"``.

#### Request.request_id

```text
request_id() -> str
```

#### Request.origin

```text
origin() -> str
```

The issuing actor's name: everything before the last ``"/"`` of the request id.

#### Request.kind

```text
kind() -> Symbol
```

The output Symbol naming the work.

#### Request.payload

```text
payload() -> typing.Any
```

#### Request.to_dto

```text
to_dto() -> Dto
```

A Dto capturing the complete internal state. Does not mutate the object.

#### Request.from_dto

```text
from_dto(dto: Dto) -> typing.Self
```

## gvn.harness.inquiry

Inquiries: asking someone outside for content and waiting for the answer.

An Inquiry asks one audience (a person, a team, a counterparty: whoever the
channel behind ``request_input`` reaches) one question, and waits as long as it
takes. While it waits it is just data: the run parks on its ``request_input``
request, which no fulfiller runs (declare it external on the Governor), and the
answer arrives later as an ``answered`` event, possibly in another process.

    state      output         input -> next state
    idle       idle           started -> asking
    asking     request_input  answered -> answered
                              withdrawn -> withdrawn
                              interrupted -> suspended
    suspended  suspended      resumed -> asking
    answered, withdrawn (final)

Every other input is covered by ``otherwise: stay``: it is rejected and changes
nothing. Final states absorb everything. There is no internal decision.

Event payloads (anything else, or a text longer than ``limit``, is a ValueError
that changes nothing):

    started      {"question": non-blank str}
    answered     {"text": str, "choice": str, "by": str or None, "data": {...} or None}
                 "choice" is required exactly when the inquiry has choices, and must be
                 one of them; without choices it may be absent or None. "by" (who
                 answered, recorded as given) and "data" (structured fields added by the
                 channel that received the answer) may be absent, meaning None.
    withdrawn    None or {"by": str or None}
    interrupted, resumed   None

While asking, ``pending()`` is one Request with id ``"<name>/<machine step count>"``,
kind ``request_input`` and payload

    {"audience": str, "question": str, "choices": [str...], "limit": int or None,
     "context": {...}}

Outcome payload:

    answered    {"audience", "question", "choice": str or None, "text", "by", "data"}
    withdrawn   {"audience", "question", "by"}

    Either also carries "answered_by": the plain form of the
    ``gvn.harness.events.Principal`` the ``answered`` or ``withdrawn`` event that ended
    the inquiry came from (``Event.by()``), only when it came from one.

TRUST. ``text`` and ``data`` are UNTRUSTED input from outside the system, as is
``by``: it is what the channel wrote into the payload, recorded as given, not
authenticated. ``answered_by`` is the opposite: what the deployment's entry point
authenticated and vouched for (``Governor.answer(..., by=)``), stamped on the event
by the Governor, never taken from the payload. Plan code must never copy ``text``,
``data`` or ``by`` into a run context, nor let them choose a tool's target or
arguments that a policy relies on. ``choice`` is the only part meant to route a run, and only
through a judge Decision whose outcomes are the choices. ``context`` is the
opposite: trusted data from the code that built the inquiry, shown with the
question.

### Inquiry

```python
from gvn.harness.inquiry import Inquiry
```

```text
Inquiry(
    name: str,
    audience: str,
    choices: Iterable[str] = (),
    limit: int | None = None,
    context: Mapping[str, typing.Any] | None = None,
) -> None
```

Asks one audience one question and waits, as long as it takes, for the answer.

#### Inquiry.definition

```text
definition() -> Definition
```

The verified Definition of the machine above (shared).

#### Inquiry.name

```text
name() -> str
```

The actor's address: a non-empty str, stable for its whole life.

#### Inquiry.audience

```text
audience() -> str
```

#### Inquiry.choices

```text
choices() -> tuple[str, ...]
```

The tuple of choice names (empty when the answer is free text only).

#### Inquiry.limit

```text
limit() -> int | None
```

The longest answer text accepted, or None.

#### Inquiry.context

```text
context() -> dict[str, typing.Any]
```

A fresh copy of the context; ``{}`` when none was given.

#### Inquiry.question

```text
question() -> str | None
```

The question asked, or None before ``started``.

#### Inquiry.answered_by

```text
answered_by() -> Principal | None
```

The Principal the ``answered`` or ``withdrawn`` event that ended this inquiry
came from, or None (not ended yet, or answered by nobody named).

#### Inquiry.handle

```text
handle(event: Event) -> Reaction
```

Consume an Event and return the Reaction. Synchronous, no I/O.

Raises UnknownSymbol when the event's name is not in the actor's input
alphabet, and ValueError when its payload does not fit what that input
requires; in both cases the actor is unchanged. An event that is valid but
not expected in the current state is not an error: it returns a rejected
Reaction and changes nothing, data included.

Addresses: an event whose ``to()`` is neither None, the actor's own name nor
(for composite actors) the name of something beneath it raises ValueError and
changes nothing. After the call, ``reaction.requests() == self.pending()``.

#### Inquiry.settles

```text
settles(event: Event) -> bool
```

Could handling ``event`` now finish this inquiry? Only a declared step into a
final state can (there are no internal decisions). Anything handle would refuse
answers True.

#### Inquiry.pending

```text
pending() -> tuple[Request, ...]
```

``()`` or ``(request,)``: built once per state entered, never per call.

#### Inquiry.state

```text
state() -> State
```

The current control State.

#### Inquiry.expected

```text
expected() -> frozenset[Symbol]
```

Frozenset of the Symbols with a declared transition from the current state.

#### Inquiry.finished

```text
finished() -> bool
```

True when the control state is final.

#### Inquiry.outcome

```text
outcome() -> Outcome
```

The Outcome. Raises NotFinished unless ``finished()``.

#### Inquiry.to_dto

```text
to_dto() -> Inquiry.Dto
```

A Dto capturing the complete internal state. Does not mutate the object.

#### Inquiry.from_dto

```text
from_dto(dto: Dto) -> typing.Self
```

Rehydrate. TypeError for a foreign Dto; ValueError for one no Inquiry could have
produced: a bad name, audience, choices or limit, a position on another
definition, a question present when it should not be (or missing, or blank), an
answer outside answered or one that breaks the choices or limit, a withdrawal
outside withdrawn, who answered outside a final state.

## gvn.harness.messages

Conversation content: messages, tool calls, tool results and attachments.

Immutable values, equal by content, each Durable. All content is plain JSON
(see gvn.kernel.schema). Constructors validate and raise TypeError/ValueError;
nothing here relies on type hints.

Constants: `USER`, `ASSISTANT`, `TOOL`, `INSTRUCTION`, `IMAGE`, `DOCUMENT`, `IMAGE_TYPES`, `DOCUMENT_TYPES`, `ATTACHMENT_LIMIT`, `URL_LIMIT`, `RESULT_ATTACHMENTS`, `RESULT_ATTACHMENT_LIMIT`.

### Attachment

```python
from gvn.harness.messages import Attachment
```

```text
Attachment(*args: object, **kwargs: object) -> None
```

An image or a document (PDF) sent to a model inside a user message. Immutable value.

Build with ``Attachment.image(...)`` or ``Attachment.document(...)``, giving exactly one
of ``data`` (the file's bytes, with its ``media_type``) or ``url`` (an ``https://``
address the vendor fetches itself). Data is checked: at most ATTACHMENT_LIMIT bytes, a
media type from IMAGE_TYPES or DOCUMENT_TYPES, and leading bytes that match it (a PNG
must start like a PNG). A URL is not fetched or checked by gvn; a document URL must
name a PDF. ``title`` (documents only) is shown to the model with the document.
``cited`` (documents only, default False) asks the vendor to cite passages of this
document in its reply (Anthropic only; OpenAI does not cite document inputs, and the
flag has no effect there). Anthropic cannot cite and give a structured answer in the
same call: an Exchange with both fails (see gvn.adapters.anthropic).

Durable form: ``{"kind": "image" | "document", "media_type", "data": <base64>}`` or
``{"kind", "url"}``, with ``"title"`` and ``"cited"`` present only when set. Data is
inline base64 by design: the journal stays the one record of a run, with no second
store to keep in step, back up or lose; the cost is about 1.33 bytes per byte of
media in the journal record that brings it and again in each of the (at most two)
kept snapshots of the actor that holds it, and nowhere else.

#### Attachment.image

```text
image(
    data: bytes | bytearray | memoryview | None = None,
    media_type: str | None = None,
    url: str | None = None,
) -> typing.Self
```

An image: ``data`` (bytes) with ``media_type`` (one of IMAGE_TYPES), or ``url``.

#### Attachment.document

```text
document(
    data: bytes | bytearray | memoryview | None = None,
    media_type: str | None = 'application/pdf',
    url: str | None = None,
    title: str | None = None,
    cited: bool = False,
) -> typing.Self
```

A PDF: ``data`` (bytes) or ``url``; ``title`` None or a non-empty str; ``cited`` a
bool (see the class docstring).

#### Attachment.kind

```text
kind() -> str
```

IMAGE or DOCUMENT.

#### Attachment.media_type

```text
media_type() -> str | None
```

The media type (str), or None for an image given by URL.

#### Attachment.url

```text
url() -> str | None
```

The URL (str), or None when the attachment carries its bytes.

#### Attachment.data

```text
data() -> bytes | None
```

The bytes, decoded afresh, or None for an attachment given by URL.

#### Attachment.encoded

```text
encoded() -> str | None
```

The bytes as standard base64 text (what vendors take), or None for a URL.

#### Attachment.size

```text
size() -> int
```

How many bytes the attachment carries (0 for a URL).

#### Attachment.title

```text
title() -> str | None
```

#### Attachment.cited

```text
cited() -> bool
```

#### Attachment.descriptor

```text
descriptor() -> dict[str, typing.Any]
```

What the attachment is, without its bytes, as plain JSON: ``{"kind", "media_type",
"size"}`` for data, ``{"kind", "url"}`` for a URL, with ``"title"`` when set. What a
reader that must not receive the media (a summariser) is shown instead.

#### Attachment.to_dto

```text
to_dto() -> Dto
```

A Dto capturing the complete internal state. Does not mutate the object.

#### Attachment.from_dto

```text
from_dto(dto: Dto) -> typing.Self
```

ValueError for a Dto that breaks the rules the builders enforce.

### ToolCall

```python
from gvn.harness.messages import ToolCall
```

```text
ToolCall(call_id: str, name: str, arguments: Mapping[str, typing.Any]) -> None
```

A model's request to run one tool. ``call_id`` is the id the model gave this call
(a ToolResult answers it by the same id). ``arguments`` is a dict of plain JSON.

#### ToolCall.call_id

```text
call_id() -> str
```

#### ToolCall.name

```text
name() -> str
```

#### ToolCall.arguments

```text
arguments() -> dict[str, typing.Any]
```

A fresh plain dict; mutating it does not affect the call.

#### ToolCall.to_dto

```text
to_dto() -> Dto
```

A Dto capturing the complete internal state. Does not mutate the object.

#### ToolCall.from_dto

```text
from_dto(dto: Dto) -> typing.Self
```

### ToolResult

```python
from gvn.harness.messages import ToolResult
```

```text
ToolResult(
    call_id: str,
    content: typing.Any,
    failed: bool = False,
    attachments: Iterable[Attachment] = (),
) -> None
```

What running one tool call produced. ``content`` is plain JSON; ``failed`` marks errors.

Attachments. A result may also carry images and documents (``Attachment``) for the model
to see after its content: a screenshot, a page an MCP server rendered. ``attachments`` is
an iterable of Attachment: at most RESULT_ATTACHMENTS of them, holding at most
RESULT_ATTACHMENT_LIMIT bytes together, none ``cited`` (citations are asked for on a
user's documents only). They are journaled inline, like a user message's attachments.
They are data: no policy, approver or route sees them, and an outcome's attempts carry
the content only. The Dto field ``attachments`` (their plain Dto forms) is present only
when there are some, so results without any, and journals written before it existed,
are unchanged. TypeError/ValueError otherwise.

#### ToolResult.call_id

```text
call_id() -> str
```

#### ToolResult.content

```text
content() -> typing.Any
```

#### ToolResult.failed

```text
failed() -> bool
```

#### ToolResult.attachments

```text
attachments() -> tuple[Attachment, ...]
```

Tuple of Attachment (empty unless the tool returned some).

#### ToolResult.to_dto

```text
to_dto() -> Dto
```

A Dto capturing the complete internal state. Does not mutate the object.

#### ToolResult.from_dto

```text
from_dto(dto: Dto) -> typing.Self
```

ValueError for attachments the constructor would refuse.

### result_attachments

```python
from gvn.harness.messages import result_attachments
```

```text
result_attachments(attachments: Iterable[Attachment]) -> tuple[Attachment, ...]
```

The tuple of a tool result's attachments, checked against the per-result caps.

``attachments``: an iterable of Attachment. TypeError for anything else; ValueError for
more than RESULT_ATTACHMENTS, more than RESULT_ATTACHMENT_LIMIT bytes together, or a
``cited`` document.

### Message

```python
from gvn.harness.messages import Message
```

```text
Message(*args: object, **kwargs: object) -> None
```

One turn of a conversation. Build with ``user``, ``assistant``, ``tool`` or
``instruction``.

A user message has text. An assistant message has text (possibly empty), zero or
more calls and zero or more sealed records. A tool message has one or more
results. An instruction message has non-empty text and nothing else. Calling the
plain constructor directly raises TypeError.

Instructions. An instruction message is trusted text from the code that runs the
harness, given while a conversation is under way (the instructions an actor is built
with are not messages). An adapter sends it with the vendor's own authority for such
text (Anthropic: a ``system`` message inside ``messages``; OpenAI: a ``developer``
message), never as something the person said. Only harness code may create one: no
model reply, tool result or person's answer ever becomes an instruction message. It
always directly follows a user message (the actor that appends it sees to that; some
vendors require it).

Sealed content. ``sealed`` is what a vendor requires back unmodified with the
assistant turn it belongs to (Anthropic's signed ``thinking`` and
``redacted_thinking`` blocks): a tuple of plain-JSON records
``{"vendor": str, "model": str, "block": {...}}`` in the order the vendor sent
them, ``vendor`` and ``model`` non-empty. A record may also carry ``"layout"``, a
list of plain JSON the vendor's adapter owns (Anthropic's: the order of the
turn's original blocks, see gvn.adapters.anthropic). It is opaque to gvn: only
the adapter of that vendor reads it (others are ignored, so a harness can change
vendor mid-journal; which models' records an adapter sends is its own rule). It is part of
the message's value (equality, the Dto, the journal, the transcript), but nothing
routes on it and it never reaches a tool, a policy, an approver, a summariser or
an outcome. The Dto field ``sealed`` is present only when there is sealed
content, so messages without any, and journals written before it existed, are
unchanged.

Attachments. A user message may carry images and documents (``Attachment``) after
its text, in order. The Dto field ``attachments`` (their plain Dto forms) is present
only when there are some. A tool message's attachments are on its results
(``ToolResult.attachments``), never on the message itself.

Citations. An assistant message may carry the vendor's citations: a tuple of
plain-JSON records ``{"vendor": str, "start": int, "end": int, "source": {...}}``,
each saying that the characters ``text[start:end]`` rest on ``source`` (the vendor's
own description of the cited passage or page, kept as the vendor sent it). They are
data for people and code that shows sources: nothing routes on them and adapters do
not send them back. The Dto field ``citations`` is present only when there are some.

#### Message.user

```text
user(text: str, attachments: Iterable[Attachment] = ()) -> typing.Self
```

``attachments``: an iterable of Attachment, sent after the text.

#### Message.assistant

```text
assistant(
    text: str = '',
    calls: Iterable[ToolCall] = (),
    sealed: Iterable[Mapping[str, typing.Any]] = (),
    citations: Iterable[Mapping[str, typing.Any]] = (),
) -> typing.Self
```

``calls`` is an iterable of ToolCall; ``sealed`` an iterable of sealed records and
``citations`` an iterable of citation records (see the class docstring), copied.
TypeError/ValueError for anything else.

#### Message.tool

```text
tool(results: Iterable[ToolResult]) -> typing.Self
```

``results`` is a non-empty iterable of ToolResult.

#### Message.instruction

```text
instruction(text: str) -> typing.Self
```

Trusted text from the code that runs the harness (see the class docstring).
``text``: a non-empty str.

#### Message.role

```text
role() -> str
```

USER, ASSISTANT, TOOL or INSTRUCTION.

#### Message.text

```text
text() -> str
```

#### Message.calls

```text
calls() -> tuple[ToolCall, ...]
```

Tuple of ToolCall (empty unless an assistant message requested tools).

#### Message.results

```text
results() -> tuple[ToolResult, ...]
```

Tuple of ToolResult (empty unless a tool message).

#### Message.sealed

```text
sealed() -> tuple[dict[str, typing.Any], ...]
```

Tuple of fresh copies of the sealed records, in order (empty unless an assistant
message carries any). Mutating them does not affect the message.

#### Message.attachments

```text
attachments() -> tuple[Attachment, ...]
```

Tuple of Attachment (empty unless a user message carries any).

#### Message.citations

```text
citations() -> tuple[dict[str, typing.Any], ...]
```

Tuple of fresh copies of the citation records, in order (empty unless an
assistant message carries any).

#### Message.to_dto

```text
to_dto() -> Dto
```

``calls`` and ``results`` hold the plain forms of the ToolCall/ToolResult Dtos;
``sealed``, ``attachments`` and ``citations`` are present only when not empty.

#### Message.from_dto

```text
from_dto(dto: Dto) -> typing.Self
```

## gvn.harness.ports

Ports: what the harness needs from the outside world.

Each port is an ABC. Implementations live in gvn.adapters (real) and gvn.testing
(fakes); every implementation must pass the port's contract suite in
gvn.testing.contracts. Nothing in the harness or kernel imports an
implementation.

Constants: `ABC`, `ASSISTANT`, `EVENT`, `REJECTED`, `REQUEST`, `DELTA`, `WAITING`, `FINISHED`, `SIGNAL_KINDS`.

### Signal

```python
from gvn.harness.ports import Signal
```

```text
Signal(
    kind: str,
    actor: str,
    sequence: int,
    at: float,
    data: dict[str, typing.Any],
) -> None
```

One observable thing that happened in a run. Immutable value.

``kind`` is one of SIGNAL_KINDS (ValueError otherwise). ``actor`` is the
actor's name. ``sequence`` counts signals per Governor from 0, so consumers
can order and detect gaps. ``at`` is the Clock's time. ``data`` is plain JSON
as documented beside each kind.

#### Signal.kind

```text
kind() -> str
```

#### Signal.actor

```text
actor() -> str
```

#### Signal.sequence

```text
sequence() -> int
```

#### Signal.at

```text
at() -> float
```

#### Signal.data

```text
data() -> dict[str, typing.Any]
```

A fresh copy of the data dict.

### Output

```python
from gvn.harness.ports import Output
```

```text
Output()
```

Receives every Signal. Structured logs, tracing and user streams implement this.

#### Output.emit

```text
emit(signal: Signal) -> None
```

Take one Signal. Synchronous; must return promptly and must not block on I/O.

The Governor swallows and counts any exception raised here: an observer
can never break a run.

### Progress

```python
from gvn.harness.ports import Progress
```

```text
Progress()
```

Handed to work in flight so it can report partial results.

#### Progress.text

```text
text(fragment: str) -> None
```

Report a fragment of generated text (a non-empty str).

### Quiet

```python
from gvn.harness.ports import Quiet
```

```text
Quiet()
```

A Progress that discards everything it is given.

For calling a Model or Fulfiller directly when nobody is listening. It still
checks each fragment as the port requires: TypeError unless it is a str,
ValueError if it is empty.

#### Quiet.text

```text
text(fragment: str) -> None
```

Report a fragment of generated text (a non-empty str).

### ModelFailure

```python
from gvn.harness.ports import ModelFailure
```

```text
ModelFailure(
    reason: str,
    retryable: bool = False,
    retry_after: float | None = None,
    usage: dict[str, int] | None = None,
    exceeded_context: bool = False,
) -> None
```

A model call failed. Adapters translate every vendor error into this.

``reason``: a non-empty str a person can act on. ``retryable``: whether sending the
same request again may succeed. ``retry_after``: None, or the seconds (a finite number
>= 0) the vendor asked to wait before another attempt (its ``retry-after`` header).
``usage``: None, or the tokens the failed call spent, when the vendor said (a reply
refused or cut off at its token limit is billed): ``{"input_tokens",
"output_tokens", "cache_read_tokens", "cache_write_tokens"}``, ints >= 0, the cache
figures parts of ``input_tokens`` as in Reply. ``exceeded_context``: True when the
vendor refused or cut the call because the conversation sent does not fit the model's
context window (never together with ``retryable``: the same request would be refused
again). It is the one fact about a failure an actor routes on (gvn.harness.context_window).
TypeError/ValueError otherwise.

#### ModelFailure.reason

```text
reason() -> str
```

A str a person can act on.

#### ModelFailure.retryable

```text
retryable() -> bool
```

#### ModelFailure.retry_after

```text
retry_after() -> float | None
```

Seconds the vendor asked to wait before another attempt (float), or None.

#### ModelFailure.usage

```text
usage() -> dict[str, int] | None
```

A fresh dict of the tokens the failed call spent, or None when unknown.

#### ModelFailure.exceeded_context

```text
exceeded_context() -> bool
```

Whether the conversation sent did not fit the model's context window.

### Exchange

```python
from gvn.harness.ports import Exchange
```

```text
Exchange(
    instructions: str,
    messages: Iterable[Message],
    tools: Iterable[ToolSpec] = (),
    answer: Record | None = None,
) -> None
```

Everything a model needs for one call. Immutable value.

``instructions`` is a str (the system prompt). ``messages`` is a non-empty
sequence of Message. ``tools`` is a sequence of ToolSpec. ``answer`` is None or a
``gvn.kernel.schema.Record``: the shape the final reply must have. With an answer, a
model that replies without tool calls replies with one JSON value that the Record
admits, as its text; adapters ask the vendor's own structured output for it
(constrained decoding, where the service guarantees the shape) and fail, naming what
cannot be expressed, when the vendor cannot express the Record exactly. A reply that
calls tools is not an answer and is not constrained.

#### Exchange.instructions

```text
instructions() -> str
```

#### Exchange.messages

```text
messages() -> tuple[Message, ...]
```

Tuple of Message.

#### Exchange.tools

```text
tools() -> tuple[ToolSpec, ...]
```

Tuple of ToolSpec.

#### Exchange.answer

```text
answer() -> Record | None
```

The Record the final reply must match, or None.

### Reply

```python
from gvn.harness.ports import Reply
```

```text
Reply(
    message: Message,
    input_tokens: int = 0,
    output_tokens: int = 0,
    cache_read_tokens: int = 0,
    cache_write_tokens: int = 0,
    *,
    model: str | None = None,
    provider: str | None = None,
) -> None
```

A model's complete answer. Immutable value.

``message`` must be an assistant Message. Token counts are ints >= 0:

* ``input_tokens``: every input token the call processed, read from a cache or
  not (Anthropic: ``input_tokens + cache_creation_input_tokens +
  cache_read_input_tokens``; OpenAI: ``prompt_tokens``, which includes cached ones).
* ``cache_read_tokens``: the part of ``input_tokens`` read from the vendor's prompt
  cache (billed at the cache-read price).
* ``cache_write_tokens``: the part of ``input_tokens`` written to the cache (billed
  at the cache-write price).
* ``output_tokens``: the tokens generated, thinking included.

So the uncached input is ``input_tokens - cache_read_tokens - cache_write_tokens``;
a sum of the two cache figures above ``input_tokens`` is a ValueError.

``model`` (keyword): None, or a non-empty str naming the model that produced this
reply as the vendor reported it (which may differ from the id that was asked for).
The ``ModelFulfiller`` journals it with the reply; None leaves it to
``Model.name()``. TypeError/ValueError otherwise.

``provider`` (keyword): None, or a non-empty str naming the service that produced this
reply (as ``Model.provider()`` names one); the ``ModelFulfiller`` journals it with the
reply; None leaves it to ``Model.provider()``. TypeError/ValueError otherwise.

#### Reply.message

```text
message() -> Message
```

#### Reply.input_tokens

```text
input_tokens() -> int
```

Every input token, cached or not (see the class docstring).

#### Reply.output_tokens

```text
output_tokens() -> int
```

#### Reply.cache_read_tokens

```text
cache_read_tokens() -> int
```

The part of ``input_tokens`` read from the prompt cache.

#### Reply.cache_write_tokens

```text
cache_write_tokens() -> int
```

The part of ``input_tokens`` written to the prompt cache.

#### Reply.model

```text
model() -> str | None
```

The name of the model that produced this reply as the vendor reported it, or
None when the reply does not say.

#### Reply.provider

```text
provider() -> str | None
```

The name of the service that produced this reply, or None when the reply does
not say.

#### Reply.usage

```text
usage() -> dict[str, int]
```

``{"input_tokens", "output_tokens", "cache_read_tokens", "cache_write_tokens"}``:
the four counts as plain JSON, named as the constructor names them, the form
journaled with ``model_replied``.

### Model

```python
from gvn.harness.ports import Model
```

```text
Model()
```

Helper class that provides a standard way to create an ABC using
inheritance.

#### Model.generate

```text
async def generate(exchange: Exchange, progress: Progress) -> Reply
```

Run one model call and return the complete Reply.

Text fragments are reported to ``progress`` as they arrive; their
concatenation equals the reply message's text. Raises ModelFailure for any
failure. Must honour cancellation (asyncio.CancelledError) promptly.

#### Model.name

```text
name() -> str | None
```

What to call this model in the record of what it cost: a non-empty str (an
adapter gives the vendor's model id), or None when it has none (the default).
Constant for the object's life. The ``ModelFulfiller`` journals it with every
answer whose Reply does not name its own model (``Reply.model()``).

#### Model.provider

```text
provider() -> str | None
```

Which service serves this model: a non-empty lower-case str naming the provider
as OpenTelemetry's GenAI conventions name it where they do (``"anthropic"``,
``"openai"``, ``"deepseek"``, ...), or None when it has none to give (the default).
Constant for the object's life. The ``ModelFulfiller`` journals it with every
answer whose Reply does not name its own provider (``Reply.provider()``), so a
run's record says which service each call went to.

#### Model.context_window

```text
context_window() -> int | None
```

How many tokens one call to this model can hold (its context window): an
int >= 1, or None when unknown (the default). A fact about the model, constant
for the object's life. The ``ModelFulfiller`` journals it with every reply, which
is how an actor's ``ContextBudget`` learns it (gvn.harness.context_window).

### MemoryFailure

```python
from gvn.harness.ports import MemoryFailure
```

```text
MemoryFailure(reason: str) -> None
```

A memory could not remember, recall or forget. ``reason`` is a non-empty str for people
and logs (TypeError/ValueError otherwise).

#### MemoryFailure.reason

```text
reason() -> str
```

### Memory

```python
from gvn.harness.ports import Memory
```

```text
Memory()
```

What outlives a conversation and a run: text kept under a scope, found again by a
query. A notebook on disk, a search index over documents (retrieval), a vector store:
each is an implementation. It is not the context window (``Model.context_window()``)
nor an actor's budget for it (gvn.harness.context_window): those bound what the model
sees now; a memory holds what can be brought back later.

``scope`` is always a non-empty str naming whose memory this is (a tenant, a harness,
one run, one actor). It is chosen by harness code (``gvn.runtime.memory.MemoryScope``),
never by a model. An implementation keeps scopes apart: nothing remembered under one
scope is ever recalled under another.

What a memory holds was written by models, people and tools: it is untrusted content.
gvn hands recalled text to a model only as a tool result, never as instructions.

A memory can also forget (``forget``, ``forget_all``): a deployment that stores
people's text must be able to delete it. Only harness code calls them; no tool offers
them to a model.

#### Memory.remember

```text
async def remember(scope: str, text: str, key: str) -> str
```

Keep ``text`` (a non-empty str) under ``scope`` and return the entry's id (a
non-empty str, unique within the scope).

``key`` is a non-empty str that identifies this act of remembering: work is
delivered at least once, so the same ``scope`` and ``key`` may arrive again after
a crash. Then nothing new is kept and the first entry's id is returned (whatever
the text). Once the method returns, the entry survives the process. Raises
MemoryFailure when it cannot keep the text, which includes a memory that is
read-only. Must honour cancellation promptly.

#### Memory.recall

```text
async def recall(scope: str, query: str, limit: int) -> list[dict[str, str]]
```

The entries under ``scope`` that best match ``query`` (a str; what "match"
means is the implementation's), best first, at most ``limit`` (an int >= 1): a
list of ``{"id": str, "text": str}``, a fresh copy, empty when nothing matches.
Raises MemoryFailure when it cannot search. Must honour cancellation promptly.

#### Memory.forget

```text
async def forget(scope: str, entry: str) -> bool
```

Remove the entry whose id is ``entry`` (a non-empty str, as ``remember`` and
``recall`` give it) from ``scope`` (a non-empty str). True when an entry was
removed; False, with nothing changed, when ``scope`` holds no entry with that id
(an id that belongs to another scope included: scopes are kept apart here too).

Once the method returns, the removal survives the process and the entry is never
recalled again. Ids are never reused within a scope: a later ``remember`` gets a
new id. The entry's idempotency key goes with it, so ``remember`` with the same
``scope`` and ``key`` afterwards keeps a NEW entry (a new id, the new text).
Forgetting twice is safe: the second call returns False. Raises MemoryFailure
when it cannot remove, which includes a memory that is read-only. Must honour
cancellation promptly.

#### Memory.forget_all

```text
async def forget_all(scope: str) -> int
```

Remove every entry of ``scope`` (a non-empty str) and return how many were
removed (0 for a scope that holds nothing). No other scope is touched.

Once the method returns, the removal survives the process and none of those
entries is recalled again. Ids are never reused within a scope, and the entries'
idempotency keys go with them: ``remember`` with a key the scope used before
keeps a NEW entry. Raises MemoryFailure when it cannot remove, which includes a
memory that is read-only. Must honour cancellation promptly.

### Fulfiller

```python
from gvn.harness.ports import Fulfiller
```

```text
Fulfiller()
```

Fulfils one kind of Request: does the work it asks for and returns the Event that
answers it.

#### Fulfiller.fulfil

```text
async def fulfil(request: Request, progress: Progress) -> Event
```

Fulfil ``request`` and return the Event describing the result.

Expected failures are reported as Events, not raised. Must honour
cancellation promptly.

#### Fulfiller.unmet

```text
unmet(actor: Actor) -> str | None
```

What ``actor`` needs of this fulfiller that it cannot give: a str for people
(it names what is missing), or None when nothing is (the default). Synchronous,
no I/O, and it changes nothing. The Governor asks every fulfiller before it
lets an actor handle an event, and refuses to drive the actor while any answers
a str, so a wiring error surfaces before the run starts rather than inside it.

### Journal

```python
from gvn.harness.ports import Journal
```

```text
Journal()
```

An append-only record per run, plus snapshots. Records and states are plain JSON dicts.

``run_id`` is always a non-empty str. Everything returned is a copy: mutating it
does not change the journal. Once a method returns, what it wrote survives the
process.

Fencing. ``append`` and ``save_snapshot`` take ``fence``: None (the default) writes
unconditionally, as a journal always has. An int is the fence of the Lease (see
``Leases``) under which the caller writes: the write is made only if, at the moment
it is made, the run's current lease (taken and not released, expired or not) in the
lease store that shares this journal's storage has exactly that fence. Otherwise
nothing is written and ``LeaseLost`` is raised. The check and the write are one
atomic step, so a process whose lease passed to another holder cannot add a single
record after the new holder took the run. A journal with no lease store refuses
every fenced write. Callers that never pass ``fence`` need nothing of this.

One writer at a time. A run's records are written by whoever drives it, and a
driver names the place it writes to: ``begin`` for the run's opening, ``append``
with ``position`` after that. A write that names a place another writer already
took raises ``PositionTaken`` and writes nothing, so two drivers of one run (two
starts under one name, two processes resuming one run without leases) cannot
interleave their records: the first write of the one that lost is refused. The
Governor always names the place. A fenced write is checked for its fence first
(``LeaseLost``), then for its place.

``runs`` lists the ids of the runs the journal holds, in pages if the caller wants.

#### Journal.begin

```text
async def begin(
    run_id: str,
    state: dict[str, typing.Any],
    record: dict[str, typing.Any],
    fence: int | None = None,
) -> None
```

Durably begin ``run_id``, as one atomic step: keep ``state`` as its snapshot
taken after 0 records (its first snapshot and its latest) and add ``record`` at
position 0 (fenced as the class says).

Made only if the run has no record and no snapshot at that moment; otherwise
``PositionTaken`` is raised and nothing is written. So a run is never left
with a birth snapshot and no opening record, and of several callers beginning
one run exactly one succeeds while the others change nothing.

#### Journal.append

```text
async def append(
    run_id: str,
    record: dict[str, typing.Any],
    fence: int | None = None,
    position: int | None = None,
) -> None
```

Durably add ``record`` at the end of ``run_id`` (fenced as the class says).

``position``: None (the default) adds at the end wherever that is. An int >= 0
(TypeError / ValueError otherwise) is where the caller believes the end is:
the record is added only if the run has exactly ``position`` records at the
moment of the write (the check and the write are one atomic step); otherwise
``PositionTaken`` is raised and nothing is written.

#### Journal.read

```text
async def read(run_id: str, start: int = 0) -> tuple[dict[str, typing.Any], ...]
```

Tuple of the records of ``run_id`` from position ``start`` (an int >= 0), in order.

Empty for an unknown run or a ``start`` at or past the end.

#### Journal.length

```text
async def length(run_id: str) -> int
```

How many records ``run_id`` has; 0 for an unknown run.

#### Journal.runs

```text
async def runs(after: str | None = None, limit: int | None = None) -> tuple[str, ...]
```

The ids of the runs this journal holds, as a tuple in ascending order.

A run is held once it has a record or a snapshot. The order is that of
Python's ``str`` comparison (by code point) on every storage, so a caller can
read a long list in pages: ``after`` (None, or a str, which need not be a run
the journal holds) leaves out every id that is not greater than it, and
``limit`` (None, or an int >= 1) keeps at most that many of the ids that are
left, the lowest ones. TypeError for an ``after`` that is neither None nor a
str or a ``limit`` that is neither None nor an int (a bool is not an int
here); ValueError for a ``limit`` below 1. Empty when no run fits.

#### Journal.save_snapshot

```text
async def save_snapshot(
    run_id: str,
    sequence: int,
    state: dict[str, typing.Any],
    fence: int | None = None,
) -> None
```

Durably keep ``state`` as the snapshot of ``run_id`` taken after ``sequence`` records
(fenced as the class says).

``sequence`` is an int >= 0: the state reflects exactly the records at
positions below it. Two snapshots are kept per run: the first one ever
saved, and the one with the highest sequence; saving a lower one than is
already held changes nothing (beyond becoming the first, if it is).

#### Journal.latest_snapshot

```text
async def latest_snapshot(run_id: str) -> tuple[int, dict[str, typing.Any]] | None
```

``(sequence, state)`` for the highest-sequence snapshot of ``run_id``, or None.

#### Journal.first_snapshot

```text
async def first_snapshot(run_id: str) -> tuple[int, dict[str, typing.Any]] | None
```

``(sequence, state)`` for the first snapshot ever saved for ``run_id``, or None.

The first snapshot is kept for good (later saves never replace it), so a
run can always be replayed from its beginning.

### PositionTaken

```python
from gvn.harness.ports import PositionTaken
```

A journal write was refused because the run is not where its writer believed:
``begin`` found the run already begun, or ``append`` with ``position`` found the
run with another number of records. Another writer is (or was) driving the run.
Nothing was written.

### LeaseLost

```python
from gvn.harness.ports import LeaseLost
```

A fenced write was refused: the run's lease has passed to another holder (or was
released), so the writer no longer owns the run. Nothing was written.

### Lease

```python
from gvn.harness.ports import Lease
```

```text
Lease(run_id: str, pool: str, holder: str, fence: int, until: float) -> None
```

The right to drive one run until a time. Immutable value.

``run_id``: the run. ``pool``: the name of the workers that may pick the run up
when it is due (a Launcher uses its harness's name). ``holder``: who holds it, a
name for people reading errors (it grants nothing). ``fence``: an int >= 1 that
grows by one each time the run is acquired: writes made under the lease carry it,
and the journal refuses those of an older one. ``until``: when the lease expires
(seconds since the epoch, as the Clock reads them) unless renewed.

#### Lease.run_id

```text
run_id() -> str
```

#### Lease.pool

```text
pool() -> str
```

#### Lease.holder

```text
holder() -> str
```

#### Lease.fence

```text
fence() -> int
```

#### Lease.until

```text
until() -> float
```

### Leases

```python
from gvn.harness.ports import Leases
```

```text
Leases()
```

Who drives which run, and when each run next needs driving.

A store of one row per run: its current lease (if any), its fence, and its ``due``
time. It shares storage with a Journal, which checks fences against it (Journal's
docstring). Times are seconds since the epoch, passed in by the caller from its
Clock: the store reads no clock. Every method is atomic with respect to every other
caller of the same storage, in this process or another.

Expiry. A lease is expired once ``until <= now`` for the ``now`` a caller passes.
An expired lease is still the run's current lease (its fence still writes) until
someone acquires the run; then the fence grows and the old holder's writes are
refused. So clocks that disagree can delay a takeover or allow one early, but never
let two holders write.

The schedule. Each run has a ``due``: None (nothing to do until someone outside
acts) or a time. ``acquire`` sets it to ``now`` (a run being driven needs driving as
soon as its holder disappears); ``release`` sets it to what the holder says (the
earliest wake-up of a parked run, or None). A run is *claimable* by ``pool`` when
its pool is ``pool``, ``due <= now``, and it has no lease or an expired one.

#### Leases.acquire

```text
async def acquire(
    run_id: str,
    pool: str,
    holder: str,
    now: float,
    until: float,
) -> Lease | None
```

Take ``run_id`` for ``holder`` until ``until`` (> ``now``), or None.

Succeeds only when the run has no lease or an expired one (the same holder
included: a lease is never taken twice). On success the run's fence grows by
one (1 for a run never leased), its pool becomes ``pool``, its ``due`` becomes
``now``, and the new Lease is returned. On failure nothing changes.
TypeError / ValueError for bad arguments.

#### Leases.renew

```text
async def renew(lease: Lease, until: float) -> Lease | None
```

Extend ``lease`` to ``until``: the renewed Lease (same fence), or None when the
lease is no longer the run's current one (taken over or released). An expired
lease nobody took is renewed.

#### Leases.release

```text
async def release(lease: Lease, due: float | None = None) -> bool
```

Give ``lease`` back and set the run's ``due`` (None or a finite number).

True if released; False, with nothing changed, when it was no longer the
run's current lease. The fence is kept: the next acquire makes a higher one,
and a released lease writes nothing more.

#### Leases.holder

```text
async def holder(run_id: str) -> Lease | None
```

The run's current Lease (taken and not released; expired or not), or None.

#### Leases.due

```text
async def due(pool: str, now: float, limit: int) -> tuple[str, ...]
```

Tuple of up to ``limit`` (an int >= 1) run ids claimable by ``pool`` at ``now``,
earliest ``due`` first (ties by run id). Answered from an index: it does not
read every run.

#### Leases.earliest

```text
async def earliest(pool: str) -> float | None
```

The earliest time at which some run of ``pool`` with a ``due`` becomes
claimable (``max(due, until)`` for a leased run), or None if no run of the pool
has a ``due``. A time already past means some run is claimable now.

### Clock

```python
from gvn.harness.ports import Clock
```

```text
Clock()
```

Helper class that provides a standard way to create an ABC using
inheritance.

#### Clock.now

```text
now() -> float
```

Seconds since the epoch, as a float. Never goes backwards.

#### Clock.sleep

```text
async def sleep(seconds: float) -> None
```

Return once ``seconds`` (>= 0) have passed on this clock.

### Throttle

```python
from gvn.harness.ports import Throttle
```

```text
Throttle()
```

Holds calls back so that a shared limit holds: so many at once, so many per period.

One Throttle object is shared by everything the limit covers (every model object of
one vendor account, across every actor and run a process drives), which is what makes
the limit hold across them. It decides only WHEN a call may start; it never refuses
one. Waiting is not journaled: a run is the same run however long it was held back.
A deadline still fires while a call waits here (the Governor sleeps on a ``wake_at``
whenever other work is in flight).

``gvn.runtime.throttles`` holds the in-process implementations and ``ThrottledModel``,
which applies one to a Model. An implementation that coordinates several processes (a
shared store) is an adapter; every implementation passes
``gvn.testing.contracts.ThrottleContract``.

#### Throttle.acquire

```text
async def acquire() -> None
```

Return once one more call may start under the limit. A caller that returns
from here must call ``release`` exactly once when its call has ended, however it
ended. Must honour cancellation promptly, and a wait that is cancelled holds
nothing: no ``release`` is owed for it.

#### Throttle.release

```text
release() -> None
```

The call admitted by one earlier ``acquire`` has ended. Synchronous, no I/O,
never blocks.

#### Throttle.hold_off

```text
hold_off(seconds: float) -> None
```

The service asked its callers to wait ``seconds`` (a finite number >= 0, not a
bool: TypeError/ValueError otherwise; a ``retry-after``): admit nothing new
before that much time has passed. Calls already admitted are not affected, and
a later, shorter request never shortens a longer one in force. The default
checks ``seconds`` and does nothing more: a limit on how many calls run at once
has no notion of time.

### ports.Retry

```python
from gvn.harness.ports import Retry
```

```text
Retry(
    attempts: int,
    clock: Clock,
    first_delay: float = 1.0,
    longest_delay: float = 30.0,
    jitter: Callable[[], float] | None = None,
) -> None
```

How a fulfiller retries a call that failed retryably: exponential backoff with
jitter, sleeping on a Clock. Immutable.

It serves the ModelFulfiller (given one with ``retry=``, for a ``ModelFailure`` that is
retryable) and each tool (declared by the tool itself, ``Tool.retry()``, for a
``ToolFailure`` that is retryable; the ToolFulfiller applies it); each fulfiller
decides what counts as retryable and records the retries, a Retry only says how long
to wait and when to stop.

``attempts``: how many times one call may be made in all (an int >= 1; 1 never
retries). ``clock``: the Clock to sleep on between attempts (the Governor's, so a
fake clock makes tests instant). ``first_delay``: seconds before the first retry
(> 0); each later retry waits twice as long as the one before, up to
``longest_delay`` (>= ``first_delay``). ``jitter``: None, or a callable returning a float in
[0, 1) for each delay (pass a seeded source in tests), which scales the delay into its
upper half (``delay * (0.5 + jitter() / 2)``) so callers that failed together do not
retry together. With None, whoever applies the Retry supplies the source: the model
and tool fulfillers pass ``random.random`` (the harness layer holds no randomness of
its own), so a Retry built without ``jitter`` is spread all the same.

The service's ``retry-after`` wins: a failure that carries one waits at least that
long; one asking for more than ``longest_delay`` is not retried (the failure is
reported with its ``retry_after``, for a scheduler to act on). TypeError/ValueError
for anything malformed.

#### ports.Retry.attempts

```text
attempts() -> int
```

#### ports.Retry.clock

```text
clock() -> Clock
```

#### ports.Retry.delay

```text
delay(
    attempt: int,
    retry_after: float | None = None,
    jitter: Callable[[], float] | None = None,
) -> float | None
```

Seconds to wait after failed attempt number ``attempt`` (counting from 1) before
the next one, or None when there is no next one (attempts used up, or the vendor
asks to wait longer than ``longest_delay``). ``jitter``: the source to use when
the Retry was built without one (None: the delay is not spread).

## gvn.harness.replies

Model replies: the payloads that answer ``invoke_model``, and structured answers.

Every actor that asks ``invoke_model`` validates its answer with the schemas here, so
the reference Agent, the Conversation and the Choice read the same shapes:

    model_replied   {"message": <plain form of an assistant Message.Dto>,
                     "usage": {"input_tokens", "output_tokens", "cache_read_tokens",
                               "cache_write_tokens"},
                     "retries": [<retry>, ...],
                     "context_window": int >= 1,
                     "model": str, "provider": str}
    model_failed    {"reason": str, "retryable": bool, "retry_after": float >= 0,
                     "usage": {...}, "retries": [<retry>, ...],
                     "exceeded_context": bool, "model": str, "provider": str}

Everything but ``message`` and ``reason`` is optional; journals written before a field
existed lack it. ``context_window`` is the model's context window in tokens
(``Model.context_window()``), present when the model knows it. ``model`` names the model
that answered (``Reply.model()``, else ``Model.name()``; on a failure, ``Model.name()``),
present when known, so a run's cost can be split by model. ``provider`` names the
service that answered (``Reply.provider()``, else ``Model.provider()``; on a failure,
``Model.provider()``), present when known. ``usage`` is what the call reported (on a
failure, what the failed call spent, when the vendor said). ``retries`` lists the
attempts the ``ModelFulfiller`` made and gave up on before this answer, oldest first,
each ``{"reason": str, "waited": seconds slept before the next attempt, "retry_after":
seconds the vendor asked for (when it did), "usage": {...} (when known), "model": the
attempted model's name (when known), "provider": the attempted model's provider (when
known)}``. ``retry_after`` on a failure is the delay the vendor asked for before another
attempt. All of it is recorded, never routed, with one
exception: ``exceeded_context`` (present only when true) says the vendor refused the call
because the conversation does not fit the model's context window, and an actor that
manages its window routes on it through a Decision (gvn.harness.context_window).

Structured answers. An actor may ask for its final reply to be data of a declared
shape: an ``answer``, a ``gvn.kernel.schema.Record``. It travels in the request payload as
its JSON Schema (``answer_plain``) and is rebuilt on the other side
(``answer_from_plain``), so only a Record that survives that round trip unchanged is
accepted: one built from the kernel's own schemas (Text, Integer, Number, Boolean,
OneOf, Nullable, ListOf, MapOf, Json, Record). ``parse_answer`` is the check gvn makes
of a reply's text, whatever the vendor guaranteed.

Constants: `USAGE`, `MODEL_NAME`, `RETRY`, `MODEL_REPLIED`, `MODEL_FAILED`, `REMEMBERED`, `REMEMBER_FAILED`, `RECALLED_REPLY`, `RECALL_FAILED`, `ANSWER_PREVIEW`.

### answer_plain

```python
from gvn.harness.replies import answer_plain
```

```text
answer_plain(answer: Record) -> dict[str, typing.Any]
```

The JSON Schema form of ``answer`` (a Record), as it travels in a request.

TypeError unless a Record; ValueError when the Record does not survive the round trip
through its JSON Schema (it uses a schema the kernel does not ship, such as a DtoOf or
one of your own), naming why.

### answer_from_plain

```python
from gvn.harness.replies import answer_from_plain
```

```text
answer_from_plain(plain: Mapping[str, typing.Any]) -> Record
```

The Record an ``answer_plain`` form describes. ValueError for anything else.

### parse_answer

```python
from gvn.harness.replies import parse_answer
```

```text
parse_answer(answer: Schema, text: str) -> tuple[typing.Any, str | None]
```

``(data, None)`` when ``text`` is one JSON value that ``answer`` admits, else
``(None, problem)`` with a reason a person can act on (quoting at most
ANSWER_PREVIEW characters of the text). ``data`` is plain JSON (lists, dicts).

## gvn.harness.sensors

Sensors: fixed measurements an actor takes after a watched tool succeeds. A sensor is
gvn's post-tool hook (a gate that can change behaviour is a state with a
Decision; this one observes and feeds back).

A ``Sensor`` says "after one of these tools succeeds, call this measuring tool with these
arguments". The harness author attaches sensors to an Agent or a Conversation
(``sensors=``); the model never chooses them and never sees the measuring tools. When the
tools of a batch have returned, the actor's machine passes through ``checking_sensors``
(``SensorCheck``: ``sensors_due`` or ``nothing_due``) and, when a sensor is due, through
``sensing``, which asks the runtime for the readings with one ``sense`` request. The
readings are journaled with their answer and reach the model as ONE user message under the
fixed header ``READINGS`` (``readings_note``), before its next reply: no extra model call
is spent. They are untrusted data, never an instruction.

When a sensor is due. A sensor is due after a batch in which a call to a tool it watches
SUCCEEDED (its attempt is ``ok``): a failed, refused or abandoned call makes it due for
nothing. It takes one reading per batch, however many watched calls the batch held. Due
sensors are read in the order the actor was given them.

A reading. A measuring tool is an ordinary ``Tool`` whose result is ``READING``:
``{"clean": bool, "text": str}`` (the tool decides what clean means; the text is what the
model is shown, cut to the sensor's ``limit``). Measuring tools are served from their own
toolbox by ``gvn.runtime.fulfillers.SensorFulfiller``; they are never offered to the model
and do not pass through the policy or a person's approval, so only read-only measurements
belong in that toolbox.

The ``sense`` request and its answers (the payload shapes; ``SensorReadings`` builds and
checks them):

    sense         {"readings": [{"sensor": <name>, "tool": <identity of the measuring tool>,
                                 "arguments": {...}}, ...], "context": {...}}
                  one entry per due sensor, in the actor's order
    sensed        {"readings": [<one entry per asked sensor, in the order asked>]}: each
                  entry {"sensor", "clean": bool, "text": str} for a reading taken, or
                  {"sensor", "failed": <why, a str>} for one that could not be (its tool
                  failed, or returned something that is not a READING). A failed sensor
                  does not fail the others.
    sense_failed  {"reason": str}: nothing could be served; every asked sensor counts as
                  failed with that reason.

Blocking (``blocks=True``). A blocking sensor whose LATEST reading is not clean keeps the
actor from finishing: the reply that would finish it (an Agent's answer, a Conversation's
close) is refused with a message naming the sensors (``blocked_note``) and the model is
asked again, within the actor's own turn or step budget. A sensor that never took a
reading, or whose latest reading failed, does not block.

Counts. ``SensorReadings.summary()`` is the ``"readings"`` block of the actor's outcome:
``{"taken", "failed", "blocked", "latest": {sensor: {"clean", "text"} or {"failed"}}}``,
so a Decision between stages (a gate) can route on what a sensor read last.

What is kept. A reading's text, and a failed reading's reason, is kept to at most
``STORED_READING`` characters (``kept_text``: the head, marked ``[cut: kept K of N
characters]`` when cut), whatever the sensor's ``limit``: gvn's ``SensorFulfiller`` cuts it
before the ``sensed`` answer is journaled, and the actor cuts it again when it accepts the
answer (``SensorReadings.checked``), so its snapshot and its outcome hold at most that much
even when the answer came from outside. The model is shown that kept text, cut to the
sensor's ``limit``.

Constants: `USER`, `SENSOR_OUTCOMES`, `READING`, `SENSED`, `SENSE_FAILED`, `READINGS`, `BLOCKED`, `DEFAULT_LIMIT`, `STORED_READING`.

### kept_text

```python
from gvn.harness.sensors import kept_text
```

```text
kept_text(text: str) -> str
```

``text`` (a str) as it is kept: unchanged when it has at most ``STORED_READING``
characters; otherwise its head followed by ``"\n[cut: kept K of N characters]"``, the
whole at most ``STORED_READING`` characters, so a text kept once is kept unchanged
again. TypeError for anything but a str.

### Sensor

```python
from gvn.harness.sensors import Sensor
```

```text
Sensor(
    name: str,
    after: Tool | Toolbox | Iterable[Tool],
    tool: Tool,
    arguments: Mapping[str, typing.Any] | None = None,
    blocks: bool = False,
    limit: int = 2000,
) -> None
```

One fixed measurement: after a watched tool succeeds, call ``tool`` with ``arguments``.
Immutable value, equal by content.

``name``: the label of its readings, ``[a-z][a-z0-9_]*``, unique among one actor's
sensors. ``after``: the Tools it watches (one Tool, an iterable of Tool or a Toolbox;
at least one; a str is a TypeError saying to pass the tool); each must be offered to
the actor that carries the sensor (the actor checks). ``tool``: the measuring Tool,
served by the sensor toolbox (``gvn.runtime.fulfillers.SensorFulfiller``), never
offered to the model. ``arguments``: None (``{}``) or a dict of plain JSON, fixed, and
checked here against ``tool.arguments()``. ``blocks``: a bool; True keeps the actor
from finishing while its latest reading is not clean. ``limit``: the most characters
of a reading's text shown to the model (an int >= 1). TypeError/ValueError otherwise.

Only identities are kept (``after()``, ``tool()``), so a Sensor is durable.

#### Sensor.name

```text
name() -> str
```

#### Sensor.after

```text
after() -> frozenset[str]
```

Frozenset of the identities of the tools it watches.

#### Sensor.tool

```text
tool() -> str
```

The identity of the measuring tool.

#### Sensor.arguments

```text
arguments() -> dict[str, typing.Any]
```

A fresh copy of the fixed arguments.

#### Sensor.blocks

```text
blocks() -> bool
```

#### Sensor.limit

```text
limit() -> int
```

#### Sensor.due

```text
due(attempts: Iterable[Mapping[str, typing.Any]]) -> bool
```

Whether this sensor is due after a batch whose attempts are ``attempts`` (the
plain attempt entries of ``gvn.harness.tools.attempt``): a call to a watched tool
succeeded (status ``ok``), matched by identity.

#### Sensor.asked

```text
asked() -> dict[str, typing.Any]
```

This sensor's entry of a ``sense`` request: ``{"sensor", "tool", "arguments"}``.

#### Sensor.to_dto

```text
to_dto() -> Dto
```

A Dto capturing the complete internal state. Does not mutate the object.

#### Sensor.from_dto

```text
from_dto(dto: Dto) -> typing.Self
```

Rehydrate. TypeError for a foreign Dto; ValueError for a bad name, no watched
tool, or an identity that is not one (the arguments were checked against the
measuring tool when the sensor was made, and are not checked again).

### readings_note

```python
from gvn.harness.sensors import readings_note
```

```text
readings_note(
    sensors: Iterable[Sensor],
    entries: Sequence[Mapping[str, typing.Any]],
) -> str
```

The text of the user message that brings a batch's readings to the model:
``READINGS``, then one block per entry (``{"sensor", "clean", "text"}`` or
``{"sensor", "failed"}``), in order, separated by blank lines: the sensor's name,
``clean``/``not clean`` (or ``no reading`` with why) and the text cut to the sensor's
limit. ``sensors``: the Sensors, by name. ValueError for no entry.

### blocked_note

```python
from gvn.harness.sensors import blocked_note
```

```text
blocked_note(
    sensors: Sequence[Sensor],
    latest: Mapping[str, Mapping[str, typing.Any]],
) -> str
```

The text that refuses a finishing reply: ``BLOCKED``, the sensors' names, then their
latest readings as ``readings_note`` shows them. ``sensors``: the blocking Sensors (at
least one), ``latest``: their latest readings by name.

### is_sensor_note

```python
from gvn.harness.sensors import is_sensor_note
```

```text
is_sensor_note(message: Message) -> bool
```

Whether ``message`` (a Message) is one an actor appended for its sensors: a user
message whose text starts with ``READINGS`` or ``BLOCKED``. A person's message that
starts so is read the same way.

### SensorCheck

```python
from gvn.harness.sensors import SensorCheck
```

```text
SensorCheck()
```

check_sensors: is a sensor due? ``decide(owed)`` takes the names of the sensors owed
a reading (a tuple of str, as ``SensorReadings.owed()`` gives): ``sensors_due`` when
there is one, else ``nothing_due``.

#### SensorCheck.outcomes

```text
outcomes() -> Alphabet
```

The Alphabet of every answer this decision can give. Must not vary over time.

#### SensorCheck.judge

```text
judge(subject: object) -> Symbol
```

Inspect ``subject`` and return one Symbol from ``outcomes()``.

### SensorReadings

```python
from gvn.harness.sensors import SensorReadings
```

```text
SensorReadings(
    sensors: Iterable[Sensor] = (),
    offered: Iterable[str] = frozenset(),
) -> None
```

An actor's sensors and what they have read: which are owed a reading, how many
readings were taken and failed, how often a finishing reply was blocked, and each
sensor's latest reading. Mutable; changed only by the actor that holds it.

``SensorReadings(sensors, offered)``: ``sensors`` an iterable of Sensor (a str or
anything else is a TypeError), names distinct; ``offered`` the identities of the tools
the actor is offered (a frozenset of str): every watched tool must be among them
(ValueError naming the sensor and the tools). No sensor is a valid set: the actor then
behaves as one without sensors (``SensorCheck`` answers ``nothing_due``).

#### SensorReadings.sensors

```text
sensors() -> tuple[Sensor, ...]
```

The tuple of Sensors, in the order given.

#### SensorReadings.identities

```text
identities() -> frozenset[str]
```

Frozenset of the identities of the measuring tools.

#### SensorReadings.owed

```text
owed() -> tuple[str, ...]
```

The names of the sensors owed a reading, in the sensors' order (a tuple).

#### SensorReadings.owe

```text
owe(attempts: Iterable[Mapping[str, typing.Any]]) -> None
```

After a batch: owe a reading to every sensor due (``Sensor.due``).

#### SensorReadings.asking

```text
asking(context: dict[str, typing.Any]) -> dict[str, typing.Any]
```

The payload of the ``sense`` request for the readings owed.

#### SensorReadings.checked

```text
checked(
    readings: Sequence[Mapping[str, typing.Any]],
) -> tuple[dict[str, typing.Any], ...]
```

``readings`` (the entries of a ``sensed`` payload) as plain entries, once each is
a reading of the sensor owed at its place (``{"sensor", "clean", "text"}`` or
``{"sensor", "failed"}``), each text and reason as it is kept (``kept_text``);
ValueError naming the problem otherwise.

#### SensorReadings.took

```text
took(entries: Sequence[Mapping[str, typing.Any]]) -> str
```

``sensed``: record ``entries`` (as ``checked`` gives them); returns the text of
the note that brings them to the model.

#### SensorReadings.failed_all

```text
failed_all(reason: str) -> None
```

``sense_failed``: every sensor owed a reading failed, for ``reason`` (kept as
``kept_text`` keeps it).

#### SensorReadings.blocking

```text
blocking() -> tuple[Sensor, ...]
```

The tuple of the blocking sensors whose latest reading is not clean (one that
never read, or whose latest reading failed, does not block).

#### SensorReadings.refuse_finish

```text
refuse_finish() -> str
```

A finishing reply was refused: count it, and return the text that says why.

#### SensorReadings.blocking_names

```text
blocking_names() -> str
```

The names of ``blocking()``, joined for a reason: ``"lint, tests"``.

#### SensorReadings.summary

```text
summary() -> dict[str, typing.Any]
```

The ``"readings"`` block of an outcome: ``{"taken", "failed", "blocked",
"latest": {sensor: {"clean", "text"} or {"failed"}}}`` (a fresh copy).

#### SensorReadings.to_dto

```text
to_dto() -> Dto
```

A Dto capturing the complete internal state. Does not mutate the object.

#### SensorReadings.from_dto

```text
from_dto(dto: Dto) -> typing.Self
```

Rehydrate. TypeError for a foreign Dto; ValueError for repeated sensor names, an
owed or latest name that is no sensor's, or a latest reading of another shape.

## gvn.harness.timer

Timers: an actor that waits until a time and ends ``elapsed``.

A Timer never reads a clock. It is given its time either as an absolute ``at``
(epoch seconds, from trusted data) or as a duration ``after``, in which case it
asks ``read_clock`` once and computes ``at = now + after`` from the JOURNALED
answer. Either way the time it waits for is data, held in its Dto and in the
``wake_at`` request it issues: a crash neither loses nor moves it, and replay sees
the same time. Who answers ``wake_at`` (the Governor sleeping in-process, or a
scheduler outside once the time has come) is the runtime's business.

    state       output               input -> next state
    idle        idle                 started -> scheduling
    scheduling  schedule (internal)  known -> waiting
                                     unknown -> reading
    reading     read_clock           clock_read -> waiting
                                     interrupted -> suspended
    waiting     wake_at              woke -> elapsed
                                     interrupted -> suspended
    suspended   suspended            resumed -> scheduling
    elapsed (final)

``schedule`` is a decision the timer resolves itself inside ``handle``: ``known``
when its ``at`` is known (given, or already computed from a clock reading),
``unknown`` otherwise. So a timer given ``at`` goes straight from idle to waiting,
one given ``after`` reads the clock first, and a resumed timer goes back to
whichever it was doing. ``known`` and ``unknown`` are internal: an Event carrying
one from outside is a ValueError. Every other input is covered by ``otherwise:
stay``: it is rejected and changes nothing. The final state absorbs everything.

Event payloads (anything else is a ValueError that changes nothing):

    clock_read   {"now": number}   (finite; an int is taken as a float)
    woke         None or any JSON object (its content is ignored)
    started, interrupted, resumed   None

Requests, with ids stable for the timer's whole life (the same Request after an
interrupt and resume, and after a crash):

    reading    "<name>/read_clock"  kind read_clock  payload {}
    waiting    "<name>/wake_at"     kind wake_at     payload {"at": float}

Outcome (elapsed): ``{"at": float}``, the time waited for.

Constants: `CLOCK_READ`, `READ_CLOCK`, `WAKE_AT`.

### Timer

```python
from gvn.harness.timer import Timer
```

```text
Timer(name: str, at: float | None = None, after: float | None = None) -> None
```

Waits until a time, given as ``at`` or computed from a journaled clock reading.

#### Timer.definition

```text
definition() -> Definition
```

The verified Definition of the machine above (shared).

#### Timer.name

```text
name() -> str
```

The actor's address: a non-empty str, stable for its whole life.

#### Timer.at

```text
at() -> float | None
```

The time waited for (a float), or None while it is not known yet.

#### Timer.after

```text
after() -> float | None
```

The duration given (a float), or None for a timer given ``at``.

#### Timer.handle

```text
handle(event: Event) -> Reaction
```

Consume an Event and return the Reaction. Synchronous, no I/O.

Raises UnknownSymbol when the event's name is not in the actor's input
alphabet, and ValueError when its payload does not fit what that input
requires; in both cases the actor is unchanged. An event that is valid but
not expected in the current state is not an error: it returns a rejected
Reaction and changes nothing, data included.

Addresses: an event whose ``to()`` is neither None, the actor's own name nor
(for composite actors) the name of something beneath it raises ValueError and
changes nothing. After the call, ``reaction.requests() == self.pending()``.

#### Timer.settles

```text
settles(event: Event) -> bool
```

Could handling ``event`` now finish this timer? Only ``woke`` while waiting can.
Anything handle would refuse answers True.

#### Timer.pending

```text
pending() -> tuple[Request, ...]
```

``()`` or ``(request,)``: built once per state entered, never per call.

#### Timer.state

```text
state() -> State
```

The current control State.

#### Timer.expected

```text
expected() -> frozenset[Symbol]
```

Frozenset of the Symbols with a declared transition from the current state.

#### Timer.finished

```text
finished() -> bool
```

True when the control state is final.

#### Timer.outcome

```text
outcome() -> Outcome
```

The Outcome. Raises NotFinished unless ``finished()``.

#### Timer.to_dto

```text
to_dto() -> Timer.Dto
```

A Dto capturing the complete internal state. Does not mutate the object.

#### Timer.from_dto

```text
from_dto(dto: Dto) -> typing.Self
```

Rehydrate. TypeError for a foreign Dto; ValueError for one no Timer could have
produced: an empty name, a negative ``after``, neither ``at`` nor ``after``, a
position on another definition or in ``scheduling`` (never at rest), ``at``
unknown while waiting or elapsed, or ``at`` together with ``after`` before the
clock was read.

## gvn.harness.tools

Tools: work an actor can ask for, referred to by object and stored by identity.

A Tool does I/O, so it runs in the runtime, never inside an actor. Code that builds an
actor, a plan, a policy or a check passes the Tool objects themselves (or a Toolbox);
a str where a tool is expected is a TypeError. Each tool has two names:

* ``name()``: the short name the model sees and calls (``"write_file"``). It is unique
  among the tools one actor is offered (and so among the specs of one model request);
  a Toolbox, the runtime's whole set, may hold same-named tools of different identities.
* ``identity()``: ``namespace() + "." + name()`` (``"gvn_tools.files.write_file"``),
  unique across the system. ``namespace()`` is the defining module unless a tool class
  that backs many tools takes one. Stored data (an actor's Dto, a request's payload, an
  outcome's attempts) records the identity next to the short name, and everything that
  matches a tool (a policy, an evaluation check, a judge, the refusal of a tool not
  offered, the runtime's toolbox) matches by identity. An identity is a label that is
  compared, never resolved to code.

The standard requests that carry calls (``consult_policy``, ``request_approval``,
``invoke_tools``) carry ``"identities"``: one identity per entry of ``"calls"``, in the
same order (``identified_calls`` reads them back). ``invoke_model`` carries ``"tools"``:
the identities of the tools offered, sorted.

Run context: an agent may be built with a ``context``, a plain JSON dict of trusted
data from the code that built it (which alert, which customer, which release),
never from a model. It reaches a tool as part of the ``Invocation`` passed to
``Tool.run``, and a policy as part of the ``Consultation`` it decides on, so both
can enforce data constraints before any effect.

Constants: `ABC`, `ASSISTANT`, `VERDICTS`, `ATTEMPT_STATUSES`, `FORBIDDEN_DETAIL`, `INTERRUPTED_DETAIL`, `REFUSALS`, `SKIPPED_DETAIL`, `ABANDONED_DETAIL`, `VERDICT_PAYLOAD`, `APPROVED_PAYLOAD`, `TOOL_REJECTED`, `TOOL_UNAVAILABLE`, `TOOL_ERRORS`, `TOOL_RETRY`, `TOOLS_RETURNED`, `RECALLED_SOURCE`.

### denied_detail

```python
from gvn.harness.tools import denied_detail
```

```text
denied_detail(reason: str | None = None) -> str
```

The detail of a call a person denied, with their reason (a str) when one was given.

### attempt

```python
from gvn.harness.tools import attempt
```

```text
attempt(
    call: ToolCall,
    status: str,
    detail: typing.Any,
    identity: str | None,
) -> dict[str, typing.Any]
```

One attempt entry, ``{"name", "identity", "arguments", "status", "detail"}``, as
plain JSON.

``call``: the ToolCall. ``status``: one of ATTEMPT_STATUSES. ``detail``: plain JSON,
the result content for ``ok``/``failed``, else the reason text. ``identity``: the
identity of the tool the call names, or None when the call names no tool the actor
was offered (``unoffered``, a refused ``close``). Match an entry to a tool with
``is_call_to``, never by its ``"name"``. TypeError/ValueError otherwise.

### assistant_reply

```python
from gvn.harness.tools import assistant_reply
```

```text
assistant_reply(plain: object, symbol: str = 'model_replied') -> Message
```

The assistant Message rebuilt from ``plain`` (a ``Message.Dto`` plain form).

ValueError, naming ``symbol``, unless it rebuilds, is an assistant message and its tool
call ids are unique.

### tool_results

```python
from gvn.harness.tools import tool_results
```

```text
tool_results(
    plains: Iterable[object],
    symbol: str = 'tools_returned',
) -> tuple[ToolResult, ...]
```

Tuple of ToolResult rebuilt from plain ``ToolResult.Dto`` forms. ValueError otherwise.

### answering

```python
from gvn.harness.tools import answering
```

```text
answering(pending: Iterable[ToolCall], results: Iterable[ToolResult]) -> Message
```

The tool Message answering ``pending`` (ToolCalls) with ``results`` (ToolResults).

ValueError unless there is exactly one result per pending call, in any order.

### ran_statuses

```python
from gvn.harness.tools import ran_statuses
```

```text
ran_statuses(
    pending: Iterable[ToolCall],
    results: Iterable[ToolResult],
) -> tuple[str, ...]
```

``ok``/``failed`` per pending call, in call order, from the results that answer them.

### abandoned

```python
from gvn.harness.tools import abandoned
```

```text
abandoned(calls: Iterable[ToolCall], why: str) -> Message
```

The tool Message answering every call in ``calls`` with a failed result saying ``why``.

### settled

```python
from gvn.harness.tools import settled
```

```text
settled(
    calls: Iterable[ToolCall],
    identities: Iterable[str | None],
    message: Message,
    statuses: Iterable[str],
) -> list[dict[str, typing.Any]]
```

The attempts of a batch: ``calls`` answered by the tool ``message``, one status each;
``identities``: per call, its tool's identity or None (see ``attempt``).

### calls_payload

```python
from gvn.harness.tools import calls_payload
```

```text
calls_payload(
    calls: Iterable[ToolCall],
    identities: Iterable[str],
    context: dict[str, typing.Any],
    text: str | None = None,
    exposure: Iterable[str] = (),
) -> dict[str, typing.Any]
```

The payload of ``consult_policy``/``invoke_tools`` (``text`` None) or of
``request_approval`` (``text`` the explanation shown to the approver):
``{"calls", "identities", "text"?, "context", "exposure"?}``, ``identities`` one per
call. ``exposure``: the sources of untrusted content the actor's model has read
(``exposure_checked``: TypeError/ValueError otherwise); present, sorted, only when
there is some, so a payload without exposure is exactly what it was before
exposure existed. ``invoke_tools`` never carries it.

### untrusted_of

```python
from gvn.harness.tools import untrusted_of
```

```text
untrusted_of(tools: Iterable[Tool]) -> tuple[str, ...]
```

The sorted tuple of the identities of ``tools`` (an iterable of Tool) whose
``untrusted()`` is True: what an actor records, once, when it is built.

TypeError, naming the tool, when one's ``untrusted()`` returns anything but a bool.

### exposed_by

```python
from gvn.harness.tools import exposed_by
```

```text
exposed_by(
    attempts: Iterable[Mapping[str, typing.Any]],
    untrusted: Container[str],
) -> frozenset[str]
```

The frozenset of sources a settled batch adds to an actor's exposure.

``attempts``: the batch's attempt entries (``attempt``); ``untrusted``: the identities
of the actor's untrusted tools (any container of str). A source is the identity of
an attempt that calls one of ``untrusted`` and whose tool actually ran: status
``ok``, or ``failed`` unless its detail is a tool error (``tool_error``) saying the
tool was never run (``unknown_tool``, ``invalid_arguments``). A refused, skipped,
abandoned, unoffered or blocked call adds nothing. Pure; never raises for attempts
an actor made.

### exposure_stored

```python
from gvn.harness.tools import exposure_stored
```

```text
exposure_stored(
    untrusted: Collection[str],
    exposure: Collection[str],
) -> dict[str, list[str]]
```

The optional durable fields ``{"untrusted", "exposure"}`` of an actor: each a
sorted list of identities, present only when not empty (so an actor that has no
untrusted tool and has read nothing stores exactly what it stored before).

### exposure_revived

```python
from gvn.harness.tools import exposure_revived
```

```text
exposure_revived(
    untrusted: Iterable[str] | None,
    exposure: Iterable[str] | None,
    tools: Iterable[str],
    recall: bool,
    inherited: Iterable[str] = (),
) -> tuple[tuple[str, ...], frozenset[str]]
```

``(untrusted identities as a sorted tuple, exposure as a frozenset)`` from an
actor's stored fields (each a list, or None when absent).

``tools``: the identities of the tools the actor is offered. ``recall``: whether it
recalls by itself. ``inherited``: the sources that arrived with what the actor was
given to continue (a Conversation's ``thread_exposure``); none by default.

ValueError unless ``untrusted`` is sorted, free of duplicates and among ``tools``;
``exposure`` is sorted, free of duplicates and holds ``inherited`` (exposure only
grows); and each of its sources is one of ``untrusted``, one of ``inherited``, or
``RECALLED_SOURCE`` for an actor that recalls. Every identity must pass
``identity_checked`` (TypeError/ValueError otherwise).

### route

```python
from gvn.harness.tools import route
```

```text
route(verdicts: Sequence[str]) -> str
```

The VERDICTS symbol name a reply with these per-call verdicts routes on.

``needs_approval`` when a person is asked about some call (``asked``); else ``cleared``
when some call is cleared; else ``forbidden``.

### asked

```python
from gvn.harness.tools import asked
```

```text
asked(verdicts: Iterable[str]) -> tuple[int, ...]
```

The positions of the calls a person is asked about: each call needing approval with no
forbidden call before it (a call after a forbidden one is skipped, so asking is moot).

### judged

```python
from gvn.harness.tools import judged
```

```text
judged(
    symbol: str,
    payload: Mapping[str, typing.Any] | None,
    count: int,
) -> tuple[str, ...]
```

The per-call verdict names of a ``consult_policy`` answer for ``count`` calls.

``symbol``: the answer's name (one of VERDICTS); ``payload``: None (that verdict for
every call) or ``{"verdicts": [...]}`` already structurally valid. ValueError, naming
``symbol``, unless there is one verdict per call and ``symbol`` is their ``route``.

### denials

```python
from gvn.harness.tools import denials
```

```text
denials(
    payload: Mapping[str, typing.Any] | None,
    calls: Sequence[ToolCall],
    verdicts: Sequence[str],
) -> dict[str, str | None]
```

``{call id: reason or None}`` of an ``approved`` answer (payload structurally valid).

ValueError unless every id names a call a person was asked about, at most once.

### standing

```python
from gvn.harness.tools import standing
```

```text
standing(
    calls: Iterable[ToolCall],
    verdicts: Sequence[str],
    denied: Mapping[str, str | None] | None = None,
) -> tuple[tuple[str, str | None] | None, ...]
```

Per call, in call order: None when it may run, else ``(status, reason)`` with status one
of REFUSALS: forbidden by the policy, skipped (needed approval after a forbidden call),
or denied by a person (``denied``: ``{call id: reason or None}``).

### refusal_detail

```python
from gvn.harness.tools import refusal_detail
```

```text
refusal_detail(status: str, reason: str | None = None) -> str
```

The detail (failed ToolResult content) of a call refused with ``status`` (REFUSALS).

### refused

```python
from gvn.harness.tools import refused
```

```text
refused(
    calls: Sequence[ToolCall],
    verdicts: Sequence[str],
    reason: str | None = None,
) -> tuple[Message, tuple[str, ...]]
```

``(tool Message, statuses)`` settling a reply none of whose calls runs: after a
``forbidden`` route, or a ``denied`` answer (``reason``: the person's, or None). Asked
calls are denied; cleared ones abandoned with the reply.

### approval_payload

```python
from gvn.harness.tools import approval_payload
```

```text
approval_payload(
    calls: Sequence[ToolCall],
    identities: Sequence[str],
    verdicts: Sequence[str],
    text: str,
    context: dict[str, typing.Any],
    exposure: Iterable[str] = (),
) -> dict[str, typing.Any]
```

The payload of ``request_approval`` for ``calls`` (with their tools' ``identities``)
judged ``verdicts``.

``calls``: only the calls a person is asked about (``asked``), with ``identities``
theirs. When some calls of the reply are not asked about, two more keys say so:
``positions``, the position in the reply of each asked call, and ``beside``, the
others as context for the approver, ``{"position", "verdict", "call", "identity"}``
each (``needs_approval`` there means it came after a forbidden call and will not
run). When every call is asked about, the payload is ``calls_payload(calls,
identities, context, text, exposure)`` exactly. ``exposure``: as for
``calls_payload``, the last key, present only when not empty, so the approver
knows what untrusted content the model had read when it asked.

### invoke_payload

```python
from gvn.harness.tools import invoke_payload
```

```text
invoke_payload(
    calls: Iterable[ToolCall],
    identities: Iterable[str],
    standings: Iterable[tuple[str, str | None] | None],
    context: dict[str, typing.Any],
) -> dict[str, typing.Any]
```

The payload of ``invoke_tools``: ``calls_payload(calls, identities, context)``, plus,
when some call is refused, ``"refused"``: one entry per call, None (it runs) or
``{"status": <one of REFUSALS>, "reason": str or None}``.

### verdicts_stored

```python
from gvn.harness.tools import verdicts_stored
```

```text
verdicts_stored(
    verdicts: Sequence[str],
    denied: Mapping[str, str | None],
    implied: str | None,
) -> dict[str, typing.Any]
```

The optional durable fields ``{"verdicts", "denied"}`` of an actor's verdicts.

``implied``: the verdict name the actor's state implies for every call when nothing is
stored (``needs_approval`` awaiting approval, ``cleared`` once acting, ``forbidden``
once refused), or None. ``verdicts`` is left out when it says no more than that (a
reply whose calls all needed approval and were all approved counts as cleared), so a
run judged with bare symbols stores exactly what it stored before per-call verdicts.

### verdicts_revived

```python
from gvn.harness.tools import verdicts_revived
```

```text
verdicts_revived(
    verdicts: Sequence[str] | None,
    denied: Iterable[Mapping[str, typing.Any]] | None,
    calls: Sequence[ToolCall],
    implied: str | None,
) -> tuple[tuple[str, ...], dict[str, str | None]]
```

``(verdicts, {call id: reason})`` from stored fields (None when absent) of an actor
holding ``calls`` whose state implies ``implied`` (see ``verdicts_stored``). ValueError
for fields no actor could have stored.

### returned

```python
from gvn.harness.tools import returned
```

```text
returned(
    calls: Sequence[ToolCall],
    standings: Iterable[tuple[str, str | None] | None],
    results: Sequence[ToolResult],
) -> tuple[Message, tuple[str, ...]]
```

``(tool Message, statuses)`` answering ``calls`` with ``results`` (ToolResults).

ValueError unless there is exactly one result per call, and every refused call's result
is failed. Statuses: a refused call keeps its refusal; a call that was let run is
``skipped`` when its result is failed with content ``SKIPPED_DETAIL``, else ``ok`` or
``failed``.

### namespace_checked

```python
from gvn.harness.tools import namespace_checked
```

```text
namespace_checked(namespace: str) -> str
```

``namespace`` when it is a dotted identifier (``"gvn_tools.files"``: one or more
Python identifiers joined by dots); TypeError unless a str, ValueError otherwise.

### identity_checked

```python
from gvn.harness.tools import identity_checked
```

```text
identity_checked(identity: str) -> str
```

``identity`` when it is a tool identity, ``<namespace>.<name>`` with a namespace
``namespace_checked`` accepts and a valid tool name; TypeError unless a str,
ValueError otherwise. How stored identities are checked when read back.

### short_name

```python
from gvn.harness.tools import short_name
```

```text
short_name(identity: str) -> str
```

The short name (what the model sees) of a tool identity: its last segment.

### tool_checked

```python
from gvn.harness.tools import tool_checked
```

```text
tool_checked(tool: Tool, role: str = 'tool') -> Tool
```

``tool`` when it is a Tool; TypeError otherwise (a str says to pass the tool).

### tools_given

```python
from gvn.harness.tools import tools_given
```

```text
tools_given(
    tools: Toolbox | Iterable[Tool],
    role: str = 'tools',
    one_name_each: bool = True,
) -> tuple[Tool, ...]
```

The tools of ``tools``, a Toolbox or an iterable of Tool, as a tuple sorted by
identity, each identity once (the same tool given twice counts once).

A str, or a str among them, is a TypeError saying to pass the tool; anything that is
not a Tool is a TypeError. With ``one_name_each`` (what one actor is offered), two
tools with one short name but different identities are a ValueError naming both
identities: the model could not tell them apart. ``role`` names the argument in
errors. A Toolbox is checked exactly like a list of its tools: it may hold two tools
of one short name, which one actor may not be offered.

### identities_held

```python
from gvn.harness.tools import identities_held
```

```text
identities_held(identities: Iterable[str], role: str = 'tools') -> tuple[str, ...]
```

A sorted tuple of the stored ``identities`` (each ``identity_checked``), as an
actor's Dto holds them; ValueError unless sorted, free of duplicates and with one
identity per short name.

### is_call_to

```python
from gvn.harness.tools import is_call_to
```

```text
is_call_to(entry: object, tool: Tool) -> bool
```

Whether ``entry`` is a call to ``tool`` (a Tool): an outcome's attempt or ``"tools"``
entry, or anything with an ``"identity"``, compared with ``tool.identity()``. How a
judge or a Decision that reads a child's tool results picks a tool's calls; never
compare the ``"name"``. TypeError unless ``tool`` is a Tool.

### calls_to

```python
from gvn.harness.tools import calls_to
```

```text
calls_to(
    entries: Iterable[Mapping[str, typing.Any]],
    tool: Tool,
) -> list[Mapping[str, typing.Any]]
```

The entries among ``entries`` (an outcome's ``"attempts"`` or ``"tools"``) that are
calls to ``tool`` (``is_call_to``), as a list in their order.

### identified_calls

```python
from gvn.harness.tools import identified_calls
```

```text
identified_calls(
    payload: Mapping[str, typing.Any],
    symbol: str = 'the request',
) -> tuple[tuple[ToolCall, ...], tuple[str, ...]]
```

``(calls, identities)`` of a ``consult_policy``, ``request_approval`` or
``invoke_tools`` payload: a tuple of ToolCall and a tuple of their tools' identities.

ValueError, naming ``symbol``, when the calls do not rebuild, ``"identities"`` is
missing or not one identity per call, or an identity does not name its call's tool.

### UnknownTool

```python
from gvn.harness.tools import UnknownTool
```

No tool with that name is in the toolbox.

### tool_error

```python
from gvn.harness.tools import tool_error
```

```text
tool_error(detail: object) -> str | None
```

The error kind (one of TOOL_ERRORS) a failed call's content names, or None.

``detail``: a failed ToolResult's content, or a ``failed`` attempt's ``"detail"``. None
when it is not ``{"error": <kind>, "detail": str}`` (optionally with ``"retry_after"``):
a refused or skipped call's text, or anything else. Pure: a judge (a Decision over an
actor's outcome) routes on it. Read it only for a failed call: a tool's successful
result could take the same shape.

### ToolFailure

```python
from gvn.harness.tools import ToolFailure
```

```text
ToolFailure(
    reason: str,
    retryable: bool = False,
    retry_after: float | None = None,
) -> None
```

A tool call failed for a reason the tool understands. ``Tool.run`` raises it.

``reason``: a non-empty str the model (and a person) can act on. ``retryable``: True
when the service could not be reached or asked to wait (an outage, a timeout, a rate
limit), so the same call may succeed later; False (the default) when the service
answered and refused (a business refusal, not found, not permitted, invalid for the
service), so repeating it would be refused again. ``retry_after``: None, or the
seconds (a finite number >= 0) the service asked to wait before another attempt (its
``Retry-After``); it matters only when ``retryable``. TypeError/ValueError otherwise.

The ToolFulfiller reports a non-retryable failure as ``tool_rejected`` and a retryable
one, once any retries are used up, as ``tool_unavailable``.

#### ToolFailure.reason

```text
reason() -> str
```

A str the model and a person can act on.

#### ToolFailure.retryable

```text
retryable() -> bool
```

Whether the same call may succeed later (the service was not reached).

#### ToolFailure.retry_after

```text
retry_after() -> float | None
```

Seconds the service asked to wait before another attempt (float), or None.

### Tool

```python
from gvn.harness.tools import Tool
```

```text
Tool()
```

Helper class that provides a standard way to create an ABC using
inheritance.

#### Tool.name

```text
name() -> str
```

The short name the model sees and calls. Matches ``[A-Za-z][A-Za-z0-9_-]*``.
Unique among the tools one actor is offered; a Toolbox may hold same-named tools
of different identities.

#### Tool.namespace

```text
namespace() -> str
```

Where the tool comes from, a dotted identifier: the module that defines the
tool's class (``type(self).__module__``) unless a tool overrides it. A tool class
that backs many tools (one per configuration) takes a namespace at construction,
so tools of one class configured apart have different identities.

#### Tool.identity

```text
identity() -> str
```

``namespace() + "." + name()``: the tool's label across the system, what stored
data records and what everything that matches a tool compares. Never override
it (``gvn.testing.contracts.ToolContract`` checks).

#### Tool.description

```text
description() -> str
```

What the tool does, written for the model.

#### Tool.arguments

```text
arguments() -> Record
```

A gvn.kernel.schema.Record describing the arguments dict.

#### Tool.run

```text
async def run(arguments: dict[str, typing.Any], invocation: Invocation) -> typing.Any
```

Do the work. ``arguments`` already satisfies ``arguments()``. Returns plain JSON, or
a ``ToolOutput`` when the model should also see images or documents (a screenshot):
its content is the result's JSON and its attachments go to the model after it.

``invocation`` is the ``Invocation``: which run asked (``invocation.origin()``), with
what trusted data (``invocation.context()``), under which idempotency key
(``invocation.key()``). A tool that must stay within the run's data (only this
alert's hosts, only this customer) checks ``invocation.context()`` and raises
rather than act outside it.

``invocation.key()`` is a non-empty str that identifies this call: it is the same every
time the same call of the same run is (re)issued, and different for every
other call. Work is delivered at least once, so after a crash the same call
may run again with the same key. A tool with side effects should use the
key to make repeats harmless, for example by passing it to the service it
calls as that service's idempotency key, or by remembering the keys it has
completed (in storage that outlives the process) and not repeating them.

What the key does not cover. An Agent that is interrupted after a tool
acted, and then resumed, asks its model again: the next call is a new
call with a new key, even when it asks for the same thing. (An Errand's
batch is fixed, so its keys stay the same across interrupt and resume.)
An effect that must happen at most once whatever happens to the run
(a payment, a deployment, a signature) should therefore be keyed by
what it is, built from the trusted ``invocation.context()`` (for example
``"promote:<service>:<version>"``), not by ``invocation.key()`` alone.

Failure. A tool that understands why a call failed raises ``ToolFailure``:
``retryable=True`` when the service could not be reached or asked to wait (an
outage, a timeout, a rate limit; pass its ``retry_after`` when it gave one),
``retryable=False`` (the default) when it answered and refused (not found, not
permitted, invalid for the service, a business rule). The runtime turns it into a
failed ToolResult of kind ``tool_rejected`` or ``tool_unavailable``, and may run a
retryable call again under the same ``invocation.key()`` (when the tool declares a
``retry()``), which a tool already tolerates. Any other exception is reported as
``tool_raised``: a defect in the tool, never retried. See ``TOOL_ERRORS``.

#### Tool.independent

```text
independent() -> bool
```

True when a call to this tool neither depends on nor affects any other call in the
same reply (a pure read). Independent calls next to each other may run at the same
time; everything else runs in the order the model asked.

False unless a tool overrides it. Must return a bool (the Toolbox checks).

#### Tool.untrusted

```text
untrusted() -> bool
```

True when what this tool returns may hold text written by someone the deployer
does not control: a web page, an issue or a ticket, an email, a record in another
system, the answer of a server reached over a protocol. Such text may be written
to steer the model that reads it, so gvn tracks it: an actor that hands a result
of this tool to its model records the tool's identity in its *exposure*, and every
later ``consult_policy`` and ``request_approval`` of that actor carries the
exposure, so a policy and an approver judge a call knowing what the model had
read when it made it (``Consultation.exposure()``).

False unless a tool overrides it. Constant for the tool's life. Must return a
bool (the Toolbox and the actors check).

#### Tool.retry

```text
retry() -> object | None
```

How a call of this tool is tried again when it fails retryably: None (one attempt)
or a ``gvn.harness.ports.Retry`` (how many attempts in all, how long to wait
between them). Constant for the tool's life.

The retry belongs to the tool because only the tool knows whether repeating a call
is safe. Every attempt carries the same ``Invocation``, so the same idempotency key:
a tool should declare a Retry only when a repeat under that key is harmless (a pure
read, or a service that honours the key). A search may deserve five attempts and a
payment none. Only a ``ToolFailure`` with ``retryable=True`` is ever retried.

None unless a tool overrides it. The ToolFulfiller checks what it returns: anything
other than None or a Retry is a TypeError naming the tool (a broken tool
definition, not a failed call).

### ToolOutput

```python
from gvn.harness.tools import ToolOutput
```

```text
ToolOutput(content: typing.Any, attachments: Iterable[Attachment] = ()) -> None
```

What a tool returns when the model should see media as well as JSON. Immutable value,
equal by content.

``content``: plain JSON, the result as a tool returning JSON alone would return it.
``attachments``: an iterable of ``gvn.harness.messages.Attachment``, sent to the model
after the content, within the per-result caps (``RESULT_ATTACHMENTS`` attachments,
``RESULT_ATTACHMENT_LIMIT`` bytes together, no ``cited`` document). The runtime turns
it into a ``ToolResult`` carrying both. A tool that returns plain JSON is unaffected.
TypeError/ValueError for anything else.

#### ToolOutput.content

```text
content() -> typing.Any
```

A fresh copy of the JSON content.

#### ToolOutput.attachments

```text
attachments() -> tuple[Attachment, ...]
```

Tuple of Attachment, in the order given.

### ToolSpec

```python
from gvn.harness.tools import ToolSpec
```

```text
ToolSpec(name: str, description: str, arguments: Record) -> None
```

What a model needs to know about a tool. Immutable value, equal by content.

#### ToolSpec.name

```text
name() -> str
```

#### ToolSpec.description

```text
description() -> str
```

#### ToolSpec.arguments

```text
arguments() -> Record
```

The Record schema.

#### ToolSpec.to_json_schema

```text
to_json_schema() -> dict[str, typing.Any]
```

``arguments().to_json_schema()``.

### Toolbox

```python
from gvn.harness.tools import Toolbox
```

```text
Toolbox(tools: Toolbox | Iterable[Tool] = ()) -> None
```

A fixed set of tools, looked up by identity. Immutable after construction.

``tools``: an iterable of Tool (or another Toolbox). Construction checks each tool's
contract at runtime: it must be a Tool (a str is a TypeError saying to pass the
tool), its name valid, its namespace a dotted identifier, its identity its namespace
and name joined by a dot, its description a non-empty str, its arguments a Record,
its ``independent()`` and ``untrusted()`` bools. Raises TypeError/ValueError
otherwise, and ValueError for two tools with one identity. Two tools may share a
short name when their
identities differ (a deployment holding ``a.write`` and ``b.write``): what one actor
is offered, and so one model request, still holds one tool per short name (the actor
and the ModelFulfiller check). An empty toolbox is allowed.

#### Toolbox.tool

```text
tool(identity: str) -> Tool
```

The Tool whose identity is ``identity`` (a str, as stored data holds it), or
UnknownTool. For the runtime, which reads identities from requests.

#### Toolbox.tools

```text
tools() -> tuple[Tool, ...]
```

Tuple of every Tool, in identity order.

#### Toolbox.identities

```text
identities() -> tuple[str, ...]
```

Tuple of the identities, sorted.

#### Toolbox.specs

```text
specs(identities: Iterable[str] | None = None) -> tuple[ToolSpec, ...]
```

Tuple of ToolSpec in identity order; all tools, or only those whose identities
are in ``identities`` (an iterable of str, as stored data holds them; UnknownTool
if one is absent).

### FixedCall

```python
from gvn.harness.tools import FixedCall
```

```text
FixedCall(call_id: str, tool: Tool, arguments: dict[str, typing.Any]) -> None
```

One tool call fixed by code (an Errand's): which tool, with what arguments, under
which call id. Immutable value, equal by content.

``call_id``: a non-empty str, unique within the batch. ``tool``: the Tool (a str is a
TypeError saying to pass the tool). ``arguments``: a dict of plain JSON. Only the
tool's identity and short name are kept: ``tool_call()`` is the ToolCall sent to the
policy and the tools, ``identity()`` its tool's identity. TypeError/ValueError
otherwise.

#### FixedCall.call_id

```text
call_id() -> str
```

#### FixedCall.tool_call

```text
tool_call() -> ToolCall
```

The ToolCall: call id, the tool's short name, the arguments.

#### FixedCall.identity

```text
identity() -> str
```

The identity of the tool called.

### run_context

```python
from gvn.harness.tools import run_context
```

```text
run_context(context: Mapping[str, typing.Any] | None) -> dict[str, typing.Any] | None
```

Validate and copy a run context: None stays None, a dict of plain JSON is copied.

The one rule for every actor that takes a ``context`` (Agent, Errand, Inquiry) and
for Invocation/Consultation. TypeError unless None or a mapping; ValueError if it
is not plain JSON.

### Invocation

```python
from gvn.harness.tools import Invocation
```

```text
Invocation(
    key: str,
    origin: str,
    context: Mapping[str, typing.Any] | None = None,
) -> None
```

One tool call as the tool sees it. Immutable value, equal by content.

``key``: the idempotency key (non-empty str). ``origin``: the name of the actor
that asked (non-empty str). ``context``: the agent's run context, None or a
dict of plain JSON (copied). TypeError/ValueError otherwise.

#### Invocation.key

```text
key() -> str
```

The idempotency key: the same whenever the same call of the same run is re-issued.

#### Invocation.origin

```text
origin() -> str
```

The name of the actor that requested the call.

#### Invocation.context

```text
context() -> dict[str, typing.Any]
```

A fresh copy of the run context (``{}`` when the agent has none).

### Consultation

```python
from gvn.harness.tools import Consultation
```

```text
Consultation(
    calls: Iterable[ToolCall],
    identities: Iterable[str],
    origin: str,
    context: Mapping[str, typing.Any] | None = None,
    reply: Iterable[ToolCall] | None = None,
    reply_identities: Iterable[str] | None = None,
    position: int | None = None,
    *,
    exposure: Iterable[str] = (),
) -> None
```

What a tool policy decides on. Immutable value, equal by content.

``calls``: a non-empty iterable of ToolCall (kept as a tuple). ``identities``: the
identity of each call's tool, one per call in the same order (each must name the
tool its call names). ``origin``: the name of the actor asking (non-empty str).
``context``: the agent's run context, None or a dict of plain JSON (copied).
TypeError/ValueError otherwise.

Matching a tool. A policy rule names the Tool object and matches by identity:
``consultation.calls_to(write_file)`` is the judged calls to that tool (empty when
there are none); ``identities()`` the identities themselves. Never compare a call's
short ``name()``: two tools from different places may share it.

The reply. A model's reply may hold several calls, and ``PolicyFulfiller`` judges
them one at a time: each consultation's ``calls()`` is the one call judged, and
``reply()`` all the calls of the reply in the order the model made them, with
``position()`` the judged call's index there. A policy that judges a call in the
light of the others ("delete only if no push in the same reply", "at most one
refund per reply") reads ``reply()``, ``reply_calls_to(tool)`` and ``position()``;
one that does not keeps working unchanged. ``reply``: None (the reply is ``calls``;
``position()`` is then None) or a non-empty iterable of ToolCall, with
``reply_identities`` one identity per reply call; given, ``calls`` must be exactly
one call and ``position`` an int (not a bool) with ``reply[position]`` that call
(and its identity that call's).

Exposure. ``exposure`` (keyword; none by default): an iterable of the sources of
untrusted content the asking actor's model had read when it made these calls, each a
str accepted by ``identity_checked`` (the identity of a tool whose ``untrusted()`` is
True and whose result reached the model, or ``RECALLED_SOURCE`` for notes recalled
from a memory). Kept as a frozenset (``exposure()``); a str, or anything that is not
an iterable of such identities, is a TypeError/ValueError. A policy reads it to
judge a call in the light of what its model may have been told: "clear a push while
the model has read nothing from outside, ask a person once it has".
``exposed_to(tool)`` says whether a given tool's results are among the sources.

#### Consultation.of

```text
of(
    calls: Iterable[tuple[Tool, dict[str, typing.Any]]],
    origin: str,
    context: Mapping[str, typing.Any] | None = None,
    exposure: Iterable[Tool | str] = (),
) -> typing.Self
```

A Consultation of ``calls``: a non-empty iterable of ``(tool, arguments)``
pairs, each a Tool (a str is a TypeError saying to pass the tool) and a dict of
plain JSON, as one reply that made them in that order. Each becomes a ToolCall
to the tool's short name with the call id ``"c1"``, ``"c2"``, ..., and the
tool's identity is recorded beside it. ``origin`` and ``context`` as for the
constructor. How a test or an example asks a policy about calls without
writing the parallel ``calls`` and ``identities`` itself:
``policy.decide(Consultation.of([(write_file, {"path": "a"})], "agent"))``.
``exposure``: as for the constructor, except that a Tool may stand for its own
identity (``exposure=[fetch_page]``). TypeError/ValueError otherwise.

#### Consultation.calls

```text
calls() -> tuple[ToolCall, ...]
```

Tuple of the ToolCalls to judge, in the order the model made them.

#### Consultation.identities

```text
identities() -> tuple[str, ...]
```

Tuple of the identity of each judged call's tool, in ``calls()`` order.

#### Consultation.calls_to

```text
calls_to(tool: Tool) -> tuple[ToolCall, ...]
```

Tuple of the judged calls to ``tool`` (a Tool), matched by identity.

#### Consultation.reply

```text
reply() -> tuple[ToolCall, ...]
```

Tuple of every ToolCall of the model's reply, in its order (``calls()`` when the
consultation was made for the whole reply).

#### Consultation.reply_identities

```text
reply_identities() -> tuple[str, ...]
```

Tuple of the identity of each reply call's tool, in ``reply()`` order.

#### Consultation.reply_calls_to

```text
reply_calls_to(tool: Tool) -> tuple[ToolCall, ...]
```

Tuple of the reply's calls to ``tool`` (a Tool), matched by identity.

#### Consultation.position

```text
position() -> int | None
```

The index in ``reply()`` of the one call judged, or None when ``calls()`` is the
whole reply.

#### Consultation.origin

```text
origin() -> str
```

The name of the actor whose calls these are.

#### Consultation.context

```text
context() -> dict[str, typing.Any]
```

A fresh copy of the run context (``{}`` when the agent has none).

#### Consultation.exposure

```text
exposure() -> frozenset[str]
```

Frozenset of the sources of untrusted content the asking actor's model had
read when it made these calls (see the class docstring); empty when none.

#### Consultation.exposed_to

```text
exposed_to(tool: Tool) -> bool
```

True when ``tool`` (a Tool) is among the sources of ``exposure()``.

### exposure_checked

```python
from gvn.harness.tools import exposure_checked
```

```text
exposure_checked(exposure: Iterable[str]) -> frozenset[str]
```

A frozenset of the sources in ``exposure``: an iterable (not a str, bytes or
mapping: TypeError) of strs each accepted by ``identity_checked`` (TypeError /
ValueError otherwise). What ``Consultation`` keeps and what an actor stores.

### spec_plain

```python
from gvn.harness.tools import spec_plain
```

```text
spec_plain(spec: ToolSpec) -> dict[str, typing.Any]
```

The plain form of a ToolSpec. TypeError unless a ToolSpec.

### spec_from_plain

```python
from gvn.harness.tools import spec_from_plain
```

```text
spec_from_plain(plain: Mapping[str, typing.Any]) -> ToolSpec
```

The ToolSpec a ``spec_plain`` form describes; equal to the one it was made from.

ValueError when it is not such a form (including a JSON Schema no kernel schema makes).

### record_from_json_schema

```python
from gvn.harness.tools import record_from_json_schema
```

```text
record_from_json_schema(plain: Mapping[str, typing.Any]) -> Record
```

The kernel Record whose ``to_json_schema()`` is ``plain``, rebuilt exactly.

The inverse of ``Record.to_json_schema()`` for a Record built from the kernel's own
schemas (Text, Integer, Number, Boolean, OneOf, Nullable, ListOf, MapOf, Json and
Record): how a schema that travelled as JSON Schema (a carried tool's arguments, an
agent's answer) becomes a schema again. ValueError, saying why, for anything else:
a JSON Schema no kernel schema renders, or one that does not describe an object.

## gvn.harness.transcript

The transcript: the ordered record of a conversation, owned by one actor.

### Transcript

```python
from gvn.harness.transcript import Transcript
```

```text
Transcript(messages: Iterable[Message] = ()) -> None
```

Append-only. The only way to change it is ``append``.

An actor that reduces its conversation (gvn.harness.context_window) does not cut a
transcript: it starts a new one from the messages it keeps.

#### Transcript.append

```text
append(message: Message) -> None
```

Add a Message at the end. TypeError for anything else.

#### Transcript.messages

```text
messages() -> tuple[Message, ...]
```

Tuple of every Message, oldest first.

#### Transcript.last

```text
last() -> Message
```

The newest Message. LookupError when empty.

#### Transcript.to_dto

```text
to_dto() -> Dto
```

A Dto capturing the complete internal state. Does not mutate the object.

#### Transcript.from_dto

```text
from_dto(dto: Dto) -> typing.Self
```

## gvn.harness.workflow

Workflows: actors made of other actors.

A workflow is an Actor whose control machine moves between stages. A stage hosts
one child actor (Host), fans out to several of one class at once (FanOut), runs one
child per item of a list with a window and retries (ForEach), or runs children of
different classes at once (Parallel). Children live inside the workflow: the whole
tree is one durable object with one journal, so a workflow that is waiting costs
nothing and replays deterministically. A Plan may also declare compensations
(Compensate) that the kernel verifier proves every way to an undone final state
passes through.

How it behaves:

* Entering a state that has a stage creates the stage's children and hands each
  its start event. Children are named ``"<workflow>/<stage>.<visit>"`` (hosted),
  ``"<workflow>/<stage>.<visit>.<index>"`` (FanOut, Parallel) or
  ``"<workflow>/<stage>.<visit>.<index>.<attempt>"`` (ForEach); ``visit`` counts
  entries into the stage from 1, ``index`` counts children (items, branches) from 0,
  ``attempt`` counts a ForEach item's attempts from 1.
* The workflow wants whatever its active children want: ``pending()`` is their
  pending requests, in child order. Request ids begin with the child's name, so
  results find their way back (see ``Request.origin`` and ``Event.to``).
* An event addressed to a child (``event.to()`` is the child's name, or lies
  beneath it) is handed to that child. If no active child matches, the event is
  ignored (``Reaction.ignored()``): a result arriving after its child was dropped
  is normal, not an error.
* When a hosted child finishes, its final state is looked up in the stage's
  routes, or, for a Host with a ``judge``, the judge Decision decides on an
  ``Ending`` (the child's Outcome, the workflow's Memo at that moment and the
  stage's name); the resulting symbol is fed to the workflow's machine. When a
  fan-out child finishes, the stage's Join decides whether the stage is over;
  if it is, the remaining children are dropped (their requests disappear, and
  the runtime cancels that work). A FanOut whose ``count`` is 0 and which names
  an ``empty`` symbol ends at once with that symbol.
* ForEach: ``items(memo)`` is listed on entering the stage; at most ``window``
  children run, items starting in list order. When a child finishes, its ``Retry``
  (if any) may start another attempt at the same item at once (a new child, so new
  request ids); otherwise the item is final, its Result (with its attempt) is
  recorded, the Join decides on the final Outcomes so far (``total`` = items), and,
  if the stage goes on, the next item not started yet starts. A Parallel's Join
  decides on each finished child's verdict (``Branch.verdict``), shown to it as an
  Outcome whose state is named after the verdict; the Results keep the real ones.
* An event addressed to the workflow itself (``to`` is None or its own name) is
  fed to its own machine if the symbol is one of its inputs. If instead the
  symbol is listed in the plan's ``relay``, it is handed to every active child
  (re-addressed to each); it is rejected only if every child rejected it or
  there are none. Any other symbol raises UnknownSymbol. An event addressed
  elsewhere raises ValueError.
* Symbols the workflow's own stages produce (every Host route value, every Host
  judge outcome, every Join outcome, every FanOut ``empty`` symbol and every
  ``expired`` symbol in the plan) are internal, like an Agent's decision
  symbols: an own-addressed event carrying one that would take a declared step
  raises ValueError ("... is produced by stage ..., it cannot be delivered from
  outside") and changes nothing. Where it would not be declared it is rejected like any other
  unexpected input, since it could change nothing either way. Relay names
  cannot be internal: they must not be inputs, and every internal symbol is one.
* The payload of the event that takes the workflow out of its initial state is
  kept as its input.
* Outcome: the final state, with payload ``{"input": &lt;input>, "history":
  {&lt;stage>: [[{"index": i, "name": &lt;child name>, "outcome": &lt;Outcome.Dto plain>},
  ...], ...]}}`` (a ForEach result retried also has ``"attempt"``, an int >= 2):
  every finished visit of every stage, in order, each as its
  Results (fan-out children that were dropped before finishing are absent;
  ``index`` says which are present). Built once and shared. Read it with
  ``Report`` (``results(stage)`` is the latest finished visit; ``report(stage)``
  opens a child that was itself a workflow). Two keys are added only when not
  empty: ``"expired": {<stage>: [<visit number>, ...]}`` (visits that ended at
  their deadline) and ``"trimmed": {<stage>: <count>}`` (see ``retain`` below).
* Deadlines. A stage with ``deadline``/``expired`` calls ``deadline(memo)``
  on entering the stage. ``At(t)`` makes the workflow ask ``wake_at {"at": t}``;
  ``After(s)`` makes it first ask ``read_clock {}`` and, on ``clock_read {"now"}``,
  ask ``wake_at {"at": now + s}`` (the time comes from the journaled answer, so a
  crash neither loses nor moves it); None means no deadline for this visit. These
  requests are the workflow's own, listed after its children's: ids
  ``"<workflow>/<stage>#<visit>/read_clock"`` and ``".../wake_at"``, stable for the
  visit's life, so answers come addressed to ``"<workflow>/<stage>#<visit>"``.
  ``woke`` there while the stage is active ends the visit at once: running
  children are dropped (their requests disappear and the runtime cancels that
  work), finished fan-out children keep their Results, the visit is recorded as
  expired (``Memo.expired``, ``Report.expired``) and the workflow takes the
  ``expired`` symbol. Each dropped child is recorded as an ``Abandoned``: its index,
  name, the state it was in and the kinds of the requests it had pending
  (``Memo.abandoned``, ``Report.abandoned``; outcome key ``"abandoned"``), so plan
  code can tell work that was cut mid-flight (and so may or may not have happened)
  from work never asked for. When the stage ends first the deadline goes with it; an
  answer for it afterwards is ignored, like a late answer for a dropped child. Only
  ``clock_read`` and ``woke`` may be addressed to a deadline (UnknownSymbol
  otherwise); ``clock_read`` without a finite number ``now`` is a ValueError; one
  that is not expected (the time is already known) is rejected. A relayed
  ``interrupted`` pauses the deadline: its request is withdrawn and its time is
  kept, so the deadline is never moved. A relayed ``resumed`` asks again with the
  same id and the same time (which may have passed by then: it is answered at
  once). The workflow's Reaction then includes the deadline's step after its
  children's.
* ``retain`` (Host, ForEach): once a stage has more than ``retain`` finished visits,
  the earlier ones keep each Result's index, name, attempt and final state with
  payload None;
  ``Memo.trimmed(stage)`` / ``Report.trimmed(stage)`` say how many; an expired
  trimmed visit's Abandoned children keep index, name and state, with no kinds. Stored state
  then grows by a name and a state per visit, not by whole outcomes.

As everywhere: an event that raises or is rejected changes nothing.

Details:

* A visit ends whenever the workflow's machine takes a declared step out of the
  stage's state (by a route, a judge, a join's answer, an empty fan-out, or an
  event of its own; a declared self-loop ends the visit and starts the next one).
  Its Results are appended to the stage's history at that moment; until then
  ``Memo.results`` shows the previous visit, so a stage that is entered again can
  see what it produced last time. ``Memo.visits`` counts the visit in progress.
* Every finished visit is kept, in the workflow and in its Dto (trimmed by a Host's
  ``retain``). A loop is bounded by its machine (typically a judge giving up when
  ``memo.visits(stage)`` reaches a limit); an unbounded loop makes the Dto grow
  with every round.
* ``settles`` for a deadline's answers: ``woke`` (when expected) settles exactly
  when the ``expired`` symbol leads into a final state or a stage; a valid
  ``clock_read`` never does; anything refused does.
* A Reaction's steps are the steps of the child that handled the event (for a
  relayed event: of every child that accepted it, in child order; if none did, of
  the children that rejected it), followed by the workflow's own steps (a deadline's
  step among them). Steps that new children take on their opening events are not
  included. The reaction names each step's actor (``Reaction.origins``): a child's
  steps as the child's reaction attributes them (``attributed(child.name())``, so a
  hosted workflow's own attribution is kept at any depth), the workflow's own steps
  by the workflow's name. A reaction with no steps names no one.
* A child started while an event is handled may finish within it too (a child whose
  decision is internal, or a whole chain of such stages). It stands neither before nor
  after the event and its opening steps are not among the Reaction's, so the Reaction
  names it in ``Reaction.passed``: every child this workflow started and saw finish
  while handling the event, as a Standing at its final state, in the order they
  finished, each preceded by what that child's own reactions passed (a hosted
  workflow's passed actors are handed on unchanged, at any depth, as its attribution
  is). That covers every way a child starts: a stage entered, a later stage entered
  in the same event, a ForEach item's next attempt or next item. A child started in
  the event that finished but was dropped before it was recorded (a Join that had
  already answered) is passed too, after those recorded. A child started in the event
  that still stands after it is not passed: ``standings()`` lists it.
* ``standings()`` is the workflow's own Standing (its plan's definition and its
  state), then, for each active child in child order, that child's ``standings()``.
* A child that rejects its opening event, or raises on it, is a mistake in the
  plan: ``handle`` raises ValueError naming the stage, and changes nothing. So is
  plan code (a judge, a join, a classify Decision, a stage function) that raises
  while an event is handled: the error propagates and the workflow is unchanged.
* Undo: before a child handles an event, what undoes it is kept only when this event
  can finish it (``child.settles(event)``, see ``Actor.settles``) AND its finishing
  can run plan code here (a judge, a custom join or a ``classify`` Decision, or an
  answer leading into a state with a stage). Routes and the built-in joins without
  ``classify`` are pure and cannot fail, so for them the answer is worked out in
  advance for every final state the child could reach. The local check runs first,
  so a deep tree asks ``settles`` only where it matters. What is kept: a leaf
  actor's Dto; for a workflow child, its ``checkpoint(event)``, which holds only that
  workflow's own fields and, recursively, what undoes the one child the event
  reaches. So undo costs the path the event travels, never the subtree below it, and
  a host undoes a workflow child with ``rollback`` (the same object, put back).
* Each child's wanted requests are kept from the Reaction it last returned (the
  Actor law makes them equal to its ``pending()``), so ``pending()`` does not walk
  the tree. A child rebuilt by an undo is asked again.
* ``settles`` (this class): an own event settles when its declared step lands in a
  final state or a state with a stage; an event for a child settles when the child
  settles on it and some answer its finishing could give leads into a final state
  or a stage; an ignored or rejected event does not; anything refused does.

Constants: `ABC`, `MOORE`, `ITEMS_LIMIT`.

### At

```python
from gvn.harness.workflow import At
```

```text
At(at: float) -> None
```

A stage deadline at an absolute time. Immutable value.

``at``: epoch seconds, a finite int or float (TypeError / ValueError otherwise),
taken from trusted data; ``at()`` returns it as a float.

#### At.at

```text
at() -> float
```

### After

```python
from gvn.harness.workflow import After
```

```text
After(seconds: float) -> None
```

A stage deadline some seconds after the stage is entered. Immutable value.

``seconds``: a positive, finite int or float (TypeError / ValueError otherwise);
``seconds()`` returns it as a float. The workflow asks ``read_clock`` on entering
the stage and computes the time from the journaled answer.

#### After.seconds

```text
seconds() -> float
```

### Result

```python
from gvn.harness.workflow import Result
```

```text
Result(index: int, name: str, outcome: Outcome, attempt: int = 1) -> None
```

One finished child of a stage visit. Immutable value.

``index()``: the child's index in its fan-out (0 for a hosted child; for a ForEach,
the item's position in its list; for a Parallel, the branch's). ``name()``: the
child's actor name. ``outcome()``: its Outcome. ``attempt()``: which attempt at its
item this child was (always 1 outside a ForEach with ``retry``). ``state()`` and
``payload()`` delegate to the outcome, so a Result reads like an Outcome.

#### Result.index

```text
index() -> int
```

#### Result.name

```text
name() -> str
```

#### Result.outcome

```text
outcome() -> Outcome
```

#### Result.attempt

```text
attempt() -> int
```

Which attempt at its item this child was, from 1.

#### Result.state

```text
state() -> State
```

The outcome's final State.

#### Result.payload

```text
payload() -> typing.Any
```

The outcome's payload (a fresh copy).

#### Result.view

```text
view() -> typing.Any
```

The outcome's payload, read-only and shared (``Outcome.view``): no copy.

#### Result.plain

```text
plain() -> dict[str, typing.Any]
```

``{"index", "name", "outcome"}`` with the outcome as its plain Dto, and
``"attempt"`` when it is not 1.

#### Result.to_dto

```text
to_dto() -> Result.Dto
```

A Dto capturing the complete internal state. Does not mutate the object.

#### Result.from_dto

```text
from_dto(dto: Dto) -> typing.Self
```

### Abandoned

```python
from gvn.harness.workflow import Abandoned
```

```text
Abandoned(index: int, name: str, state: State, kinds: Iterable[Symbol | str]) -> None
```

A child that was still running when its stage's deadline passed. Immutable value.

``index()`` and ``name()`` as for a Result; ``state()``: the State the child was in
when it was dropped; ``kinds()``: tuple of the Symbols naming the kinds of the
requests it had pending then (its ``pending()``, in order, repeats kept; for a
workflow child that includes what its own children and deadline wanted). Nothing
else is kept (no payloads, no text). A pending kind says the work was asked for
and cut mid-flight: it may or may not have happened.

#### Abandoned.index

```text
index() -> int
```

#### Abandoned.name

```text
name() -> str
```

#### Abandoned.state

```text
state() -> State
```

#### Abandoned.kinds

```text
kinds() -> tuple[Symbol, ...]
```

#### Abandoned.plain

```text
plain() -> dict[str, typing.Any]
```

``{"index", "name", "state", "kinds": [name, ...]}``.

#### Abandoned.trimmed

```text
trimmed() -> Abandoned
```

The same child with no kinds (what ``retain`` keeps of an old visit).

### Memo

```python
from gvn.harness.workflow import Memo
```

```text
Memo(
    input: typing.Any,
    history: Mapping[str, Iterable[Iterable[Result]]],
    visits: Mapping[str, int],
    expired: Mapping[str, Iterable[int]] | None = None,
    trimmed: Mapping[str, int] | None = None,
    abandoned: Mapping[str, Iterable[Iterable[Abandoned]]] | None = None,
) -> None
```

A read-only view of a workflow's data, handed to a plan's code.

#### Memo.input

```text
input() -> typing.Any
```

The workflow's input payload (a fresh copy).

#### Memo.results

```text
results(stage: str) -> tuple[Result, ...]
```

Tuple of the Results of the latest finished visit of ``stage``; empty if none.

#### Memo.history

```text
history(stage: str) -> tuple[tuple[Result, ...], ...]
```

Tuple with one entry per finished visit of ``stage``, in order: a tuple of Results.

#### Memo.visits

```text
visits(stage: str) -> int
```

How many times ``stage`` has been entered, counting the entry in progress.

#### Memo.expired

```text
expired(stage: str) -> tuple[int, ...]
```

Tuple of the numbers (from 1) of the finished visits of ``stage`` that ended at
their deadline, in order. Such a visit's entry in ``history`` holds the Results of
the children that had finished by then (none for a Host).

#### Memo.trimmed

```text
trimmed(stage: str) -> int
```

How many of the first finished visits of ``stage`` were trimmed by the Host's
``retain``: their Results keep index, name and final state, with payload None.

#### Memo.abandoned

```text
abandoned(stage: str) -> tuple[tuple[Abandoned, ...], ...]
```

One entry per expired visit of ``stage``, aligned with ``expired(stage)``: a
tuple of the Abandoned children (still running when the deadline passed), in
index order. ``zip(memo.expired(s), memo.abandoned(s))`` pairs them. A visit
trimmed by ``retain`` keeps its children's index, name and state, with no kinds.

### Ending

```python
from gvn.harness.workflow import Ending
```

```text
Ending(outcome: Outcome, memo: Memo, stage: str) -> None
```

What a Host's judge decides on. Immutable.

``outcome()``: the hosted child's Outcome. ``memo()``: the workflow's Memo at that
moment (``visits`` counts the visit being judged; ``history`` holds only the
visits that finished before it). ``stage()``: the stage's state name.

#### Ending.outcome

```text
outcome() -> Outcome
```

#### Ending.memo

```text
memo() -> Memo
```

#### Ending.stage

```text
stage() -> str
```

### Report

```python
from gvn.harness.workflow import Report
```

```text
Report(outcome: Outcome) -> None
```

A reader for a workflow's Outcome. Immutable.

``Report(outcome)``: TypeError unless an Outcome; ValueError unless its payload has
the shape of a workflow outcome (``{"input": ..., "history": {stage: [[{"index",
"name", "outcome"}, ...], ...]}}``, and optionally ``"expired": {stage: [visit
number, ...]}``, ``"abandoned": {stage: [[{"index", "name", "state", "kinds"},
...], ...]}`` (one list per expired visit) and ``"trimmed": {stage: count}``,
present only when not empty).
Nothing is copied until it is read; Results are built per stage on first use.

#### Report.outcome

```text
outcome() -> Outcome
```

The Outcome this Report reads.

#### Report.state

```text
state() -> State
```

The workflow's final State.

#### Report.input

```text
input() -> typing.Any
```

The workflow's input payload (a fresh copy).

#### Report.stages

```text
stages() -> tuple[str, ...]
```

Tuple of the names of the stages with at least one finished visit, in the order
they were first entered.

#### Report.history

```text
history(stage: str) -> tuple[tuple[Result, ...], ...]
```

Tuple with one entry per finished visit of ``stage``: a tuple of Results.

#### Report.results

```text
results(stage: str) -> tuple[Result, ...]
```

Tuple of the Results of the latest finished visit of ``stage``; empty if none.

#### Report.expired

```text
expired(stage: str) -> tuple[int, ...]
```

Tuple of the numbers (from 1) of the visits of ``stage`` that ended at their
deadline (see ``Memo.expired``).

#### Report.trimmed

```text
trimmed(stage: str) -> int
```

How many of the first visits of ``stage`` keep only names and states (see
``Memo.trimmed``).

#### Report.abandoned

```text
abandoned(stage: str) -> tuple[tuple[Abandoned, ...], ...]
```

As ``Memo.abandoned``: per expired visit, the tuple of Abandoned children.

#### Report.report

```text
report(stage: str, index: int = 0) -> Report
```

The Report of child ``index`` in ``stage``'s latest visit, itself a workflow.

ValueError when that child is not there (never visited, dropped, or another
index) or did not end as a workflow.

### Join

```python
from gvn.harness.workflow import Join
```

```text
Join()
```

Decides when a fan-out stage is over, and how. Implement ``outcomes`` and ``judge``.

#### Join.outcomes

```text
outcomes() -> Alphabet
```

The Alphabet of symbols this join can feed the workflow. Must not vary.

#### Join.judge

```text
judge(finished: tuple[Outcome, ...], total: int, memo: Memo) -> Symbol | None
```

``finished``: tuple of the Outcomes so far, in child order. ``total``: children in
all. ``memo``: the workflow's Memo (``visits`` counts the visit in progress).

Return a Symbol from ``outcomes()`` to end the stage, or None to keep
waiting. Must return a Symbol once ``len(finished) == total``.

#### Join.decide

```text
decide(finished: Iterable[Outcome], total: int, memo: Memo) -> Symbol | None
```

``judge`` with its contract enforced.

Raises UndeclaredOutcome (gvn.kernel.decision) for an answer outside
``outcomes()``, or for None when every child has finished. TypeError if
``finished`` is not a sequence of Outcomes, ``total`` not an int or ``memo``
not a Memo; ValueError if ``total`` is below 1 or below ``len(finished)``.

### AllOf

```python
from gvn.harness.workflow import AllOf
```

```text
AllOf(success: str, reached: str, missed: str, classify: Decision | None = None) -> None
```

Waits for every child. ``reached`` if all succeeded, else ``missed``.

A child succeeded when its final state is named ``success``, or, given
``classify`` (a kernel Decision over a child's Outcome), when
``classify.decide(outcome)`` is the symbol named ``success``.
Immutable value: equal to another AllOf with the same parts.

#### AllOf.outcomes

```text
outcomes() -> Alphabet
```

The Alphabet of symbols this join can feed the workflow. Must not vary.

#### AllOf.classify

```text
classify() -> Decision | None
```

The classify Decision, or None when children are counted by final state.

#### AllOf.success

```text
success() -> str
```

The verdict that counts as a child's success (the ``success`` it was built with).

#### AllOf.reached

```text
reached() -> str
```

The name of the symbol answered when every child succeeded (``reached``).

#### AllOf.missed

```text
missed() -> str
```

The name of the symbol answered when some child did not succeed (``missed``).

#### AllOf.judge

```text
judge(finished: tuple[Outcome, ...], total: int, memo: Memo) -> Symbol | None
```

``finished``: tuple of the Outcomes so far, in child order. ``total``: children in
all. ``memo``: the workflow's Memo (``visits`` counts the visit in progress).

Return a Symbol from ``outcomes()`` to end the stage, or None to keep
waiting. Must return a Symbol once ``len(finished) == total``.

### AnyOf

```python
from gvn.harness.workflow import AnyOf
```

```text
AnyOf(success: str, reached: str, missed: str, classify: Decision | None = None) -> None
```

``reached`` as soon as one child succeeds; ``missed`` if none does.

Success as for AllOf. Immutable value: equal to another AnyOf with the same parts.

#### AnyOf.outcomes

```text
outcomes() -> Alphabet
```

The Alphabet of symbols this join can feed the workflow. Must not vary.

#### AnyOf.classify

```text
classify() -> Decision | None
```

The classify Decision, or None when children are counted by final state.

#### AnyOf.success

```text
success() -> str
```

The verdict that counts as a child's success (the ``success`` it was built with).

#### AnyOf.reached

```text
reached() -> str
```

The name of the symbol answered as soon as one child succeeded (``reached``).

#### AnyOf.missed

```text
missed() -> str
```

The name of the symbol answered when every child finished and none succeeded
(``missed``).

#### AnyOf.judge

```text
judge(finished: tuple[Outcome, ...], total: int, memo: Memo) -> Symbol | None
```

``finished``: tuple of the Outcomes so far, in child order. ``total``: children in
all. ``memo``: the workflow's Memo (``visits`` counts the visit in progress).

Return a Symbol from ``outcomes()`` to end the stage, or None to keep
waiting. Must return a Symbol once ``len(finished) == total``.

### Majority

```python
from gvn.harness.workflow import Majority
```

```text
Majority()
```

A Quorum count: more than half of the children (``total // 2 + 1``). Immutable
value; all Majority objects are equal.

#### Majority.needed

```text
needed(total: int) -> int
```

How many successes out of ``total`` (an int >= 1) children reach the count.

### AtLeast

```python
from gvn.harness.workflow import AtLeast
```

```text
AtLeast(fraction: int | float | Fraction) -> None
```

A Quorum count: at least ``fraction`` of the children, rounded up.

``fraction``: an int, float or ``fractions.Fraction`` (not a bool) with
``0 < fraction <= 1``; TypeError / ValueError otherwise. A float is read as the
decimal it prints as, so ``AtLeast(0.1).needed(10) == 1``. ``AtLeast(0.5)`` is
"at least half". Immutable value: equal to another AtLeast of the same fraction.

#### AtLeast.fraction

```text
fraction() -> Fraction
```

The fraction, as a ``fractions.Fraction``.

#### AtLeast.needed

```text
needed(total: int) -> int
```

How many successes out of ``total`` (an int >= 1) children reach the count.

### Quorum

```python
from gvn.harness.workflow import Quorum
```

```text
Quorum(
    count: int | Majority | AtLeast,
    success: str,
    reached: str,
    missed: str,
    classify: Decision | None = None,
    *,
    wait: bool = False,
    veto: Mapping[str, str] | None = None,
) -> None
```

Counts the children that succeed against ``count``.

``count``: an int >= 1, ``Majority()`` or ``AtLeast(fraction)``; the latter two are
worked out from the stage's number of children each time. A child's verdict is the
name of its final state, or, given ``classify`` (a kernel Decision over a child's
Outcome), the name of the symbol it answers; it succeeded when that verdict is
``success``.

By default the join ends as soon as the result is settled either way: ``reached``
once ``count`` children succeeded, ``missed`` once that can no longer happen; the
other children are dropped. Keyword-only:

* ``wait`` (default False): when True, reaching the count does not end the stage:
  the join waits for every child (so every result is collected) and then answers
  ``reached``. It still answers ``missed`` at once when the count becomes
  unreachable (unless a veto could still change that, below).
* ``veto`` (default None): a mapping of verdict name -> symbol name. As soon as a
  finished child's verdict is a veto verdict, the stage ends with that verdict's
  symbol and the rest are dropped (should several finish in one event, the first in
  child order decides). Veto verdicts are checked before counting; ``success``
  cannot be one. Every veto symbol is an outcome the plan must route, and plan
  checking refuses a veto verdict the children cannot have. The join ends only
  once its answer is settled, so with a veto whose symbol is not ``missed`` an
  unreachable count waits for every child (a later veto would change the answer)
  before answering ``missed``; reaching the count ends it as ``wait`` says.

``outcomes()``: ``reached``, ``missed`` and every veto symbol. Immutable value:
equal to another Quorum with the same parts.

#### Quorum.outcomes

```text
outcomes() -> Alphabet
```

The Alphabet of symbols this join can feed the workflow. Must not vary.

#### Quorum.count

```text
count() -> int | Majority | AtLeast
```

The count: an int, a Majority or an AtLeast.

#### Quorum.classify

```text
classify() -> Decision | None
```

The classify Decision, or None when children are counted by final state.

#### Quorum.success

```text
success() -> str
```

The verdict that counts as a child's success (the ``success`` it was built with).

#### Quorum.reached

```text
reached() -> str
```

The name of the symbol answered when the count is reached (``reached``).

#### Quorum.missed

```text
missed() -> str
```

The name of the symbol answered when the count can no longer be reached
(``missed``).

#### Quorum.wait

```text
wait() -> bool
```

True when reaching the count waits for every child.

#### Quorum.veto

```text
veto() -> dict[str, Symbol] | None
```

A fresh dict of veto verdict name -> Symbol, or None.

#### Quorum.needed

```text
needed(total: int) -> int
```

How many of ``total`` children must succeed (an int).

#### Quorum.judge

```text
judge(finished: tuple[Outcome, ...], total: int, memo: Memo) -> Symbol | None
```

``finished``: tuple of the Outcomes so far, in child order. ``total``: children in
all. ``memo``: the workflow's Memo (``visits`` counts the visit in progress).

Return a Symbol from ``outcomes()`` to end the stage, or None to keep
waiting. Must return a Symbol once ``len(finished) == total``.

### Worst

```python
from gvn.harness.workflow import Worst
```

```text
Worst(
    order: Iterable[tuple[str, str]],
    classify: Decision | None = None,
    early: Iterable[str] = (),
) -> None
```

The worst verdict wins.

``order``: a non-empty sequence of ``(verdict, symbol)`` pairs, worst first; verdict
names are distinct, symbols may repeat. A child's verdict is the name of its final
state, or, given ``classify`` (a kernel Decision over a child's Outcome), the name of
the symbol ``classify.decide(outcome)`` answers. ``early``: verdicts that end the
stage at once, dropping the other children, answering that verdict's symbol (when
several finished children have early verdicts, the worst of them). Otherwise the
join waits for every child and answers the symbol of the worst verdict present.

Every symbol in ``order`` is an outcome the plan must route. A verdict missing from
``order`` is caught by plan checking where it can be (the final states of the
stage's actor class, or ``classify``'s outcomes) and raises UndeclaredOutcome when
it happens otherwise. Immutable value: equal to another Worst with the same parts.

#### Worst.outcomes

```text
outcomes() -> Alphabet
```

The Alphabet of symbols this join can feed the workflow. Must not vary.

#### Worst.order

```text
order() -> tuple[tuple[str, Symbol], ...]
```

Tuple of ``(verdict name, Symbol)`` pairs, worst first.

#### Worst.early

```text
early() -> frozenset[str]
```

Frozenset of the verdict names that end the stage at once.

#### Worst.classify

```text
classify() -> Decision | None
```

The classify Decision, or None when verdicts are final state names.

#### Worst.judge

```text
judge(finished: tuple[Outcome, ...], total: int, memo: Memo) -> Symbol | None
```

``finished``: tuple of the Outcomes so far, in child order. ``total``: children in
all. ``memo``: the workflow's Memo (``visits`` counts the visit in progress).

Return a Symbol from ``outcomes()`` to end the stage, or None to keep
waiting. Must return a Symbol once ``len(finished) == total``.

### Host

```python
from gvn.harness.workflow import Host
```

```text
Host(
    actor_class: type[Actor],
    make: Callable[[str, Memo], Actor],
    start: Callable[[Memo], Event],
    routes: Mapping[str, str] | None = None,
    judge: Decision | None = None,
    deadline: Callable[[Memo], At | After | None] | None = None,
    expired: str | None = None,
    retain: int | None = None,
) -> None
```

A stage with one child. Immutable.

``actor_class``: the child's class, an Actor subclass.
``make(name, memo)``: returns the child, an instance of ``actor_class`` whose
    ``name()`` is ``name`` (and, for a routed Host, whose class has the same final
    states as ``actor_class``).
``start(memo)``: returns the Event handed to the new child.
``routes``: mapping of child final state name -> workflow input symbol name.
    Must have exactly one entry per final state of ``actor_class.definition()``.
``judge``: a ``gvn.kernel.decision.Decision`` used instead of ``routes`` when the
    way on depends on data. When the child finishes, the workflow feeds
    ``judge.decide(ending)`` to its own machine, where ``ending`` is an Ending
    (the child's Outcome, the workflow's Memo at that moment, the stage's name);
    ``judge.outcomes()`` are the symbols the stage can end with. A judge can give
    up a loop with ``ending.memo().visits(ending.stage()) >= limit``.

``deadline(memo)``: None, or a function returning ``At(t)``, ``After(seconds)`` or
    None (no deadline for this visit), called on entering the stage. ``expired``:
    the symbol the stage ends with when its deadline passes first (an internal
    symbol that needs a declared transition). Both or neither (ValueError).
``retain``: None (keep every visit), or an int >= 1: only the latest ``retain``
    finished visits keep their children's full Outcomes; earlier ones are trimmed
    to index, name and final state (see ``Memo.trimmed``).

Exactly one of ``routes`` and ``judge`` (ValueError for both or neither).
TypeError/ValueError at construction for anything that can be checked there.
A judge that raises while a child event is handled (UndeclaredOutcome
included) is a plan error: it propagates and the workflow is unchanged.

#### Host.actor_class

```text
actor_class() -> type[Actor]
```

#### Host.retain

```text
retain() -> int | None
```

How many finished visits keep full Outcomes, or None for all of them.

#### Host.expired

```text
expired() -> Symbol | None
```

The Symbol the stage ends with at its deadline, or None when it has none.

#### Host.timed

```text
timed() -> bool
```

True when the stage was built with a deadline function (and so an ``expired``
symbol). Does not call it: whether a visit gets a deadline is ``deadline(memo)``.

#### Host.deadline

```text
deadline(memo: Memo) -> At | After | None
```

Call ``deadline`` and check its result: At, After or None (always None when
the stage has no deadline function). TypeError if it returns anything else.

#### Host.routes

```text
routes() -> dict[str, str] | None
```

A fresh dict of final state name -> symbol name, or None for a judged Host.

#### Host.judge

```text
judge() -> Decision | None
```

The Decision that ends the stage, or None for a routed Host.

#### Host.child

```text
child(name: str, memo: Memo) -> Actor
```

Call ``make`` and check its result (TypeError/ValueError if it breaks the contract).

#### Host.opening

```text
opening(memo: Memo) -> Event
```

Call ``start`` and check it returned an Event.

### FanOut

```python
from gvn.harness.workflow import FanOut
```

```text
FanOut(
    actor_class: type[Actor],
    count: Callable[[Memo], int],
    make: Callable[[str, int, Memo], Actor],
    start: Callable[[int, Memo], Event],
    join: Join,
    empty: str | None = None,
    deadline: Callable[[Memo], At | After | None] | None = None,
    expired: str | None = None,
) -> None
```

A stage with several children running at once. Immutable.

``count(memo)``: how many children, an int >= 1, or 0 when ``empty`` is given.
``make(name, index, memo)``: returns child number ``index``.
``start(index, memo)``: returns that child's start Event.
``join``: the Join that decides when the stage is over.
``empty``: None, or a symbol name the stage ends with at once when ``count`` is 0
    (it needs a declared transition, and it is an internal symbol). Without it a
    zero count is a ValueError.
``deadline`` and ``expired``: as for Host. At the deadline the children still
    running are dropped; those that finished keep their Results.

#### FanOut.actor_class

```text
actor_class() -> type[Actor]
```

#### FanOut.expired

```text
expired() -> Symbol | None
```

The Symbol the stage ends with at its deadline, or None when it has none.

#### FanOut.timed

```text
timed() -> bool
```

True when the stage was built with a deadline function (and so an ``expired``
symbol). Does not call it: whether a visit gets a deadline is ``deadline(memo)``.

#### FanOut.deadline

```text
deadline(memo: Memo) -> At | After | None
```

As ``Host.deadline``.

#### FanOut.join

```text
join() -> Join
```

#### FanOut.empty

```text
empty() -> Symbol | None
```

The Symbol a zero count ends the stage with, or None.

#### FanOut.size

```text
size(memo: Memo) -> int
```

Call ``count`` and check its result.

#### FanOut.child

```text
child(name: str, index: int, memo: Memo) -> Actor
```

#### FanOut.opening

```text
opening(index: int, memo: Memo) -> Event
```

### workflow.Retry

```python
from gvn.harness.workflow import Retry
```

```text
Retry(attempts: int, on: Iterable[str], classify: Decision | None = None) -> None
```

How a ForEach tries an item again when an attempt at it failed. Immutable value.

``attempts``: the most attempts per item, an int >= 1 (1 means never again).
``on``: the verdicts that mean "failed, try again": a non-empty sequence of names.
``classify``: None, when a child's verdict is the name of its final state, or a
kernel Decision over the child's Outcome whose answer's name is the verdict.

An attempt whose verdict is in ``on`` is followed by another attempt at the same
item, as long as fewer than ``attempts`` were made; any other verdict, or the last
attempt, is the item's final result. Plan checking refuses an ``on`` verdict the
children cannot have. Equal to another Retry with the same parts.

#### workflow.Retry.attempts

```text
attempts() -> int
```

#### workflow.Retry.on

```text
on() -> frozenset[str]
```

Frozenset of the verdict names that mean "try again".

#### workflow.Retry.classify

```text
classify() -> Decision | None
```

#### workflow.Retry.verdict

```text
verdict(outcome: Outcome) -> str
```

The verdict name of a child's ``outcome`` (its final state, or classified).

#### workflow.Retry.again

```text
again(outcome: Outcome, attempt: int) -> bool
```

True when attempt number ``attempt`` (from 1), which ended with ``outcome``, is
followed by another attempt at the same item.

### ForEach

```python
from gvn.harness.workflow import ForEach
```

```text
ForEach(
    actor_class: type[Actor],
    items: Callable[[Memo], Iterable[typing.Any]],
    make: Callable[[str, typing.Any, Memo], Actor],
    start: Callable[[typing.Any, Memo], Event],
    join: Join,
    retry: Retry | None = None,
    window: int | None = None,
    limit: int = 1000,
    empty: str | None = None,
    deadline: Callable[[Memo], At | After | None] | None = None,
    expired: str | None = None,
    retain: int | None = None,
) -> None
```

A stage with one child per item of a list known only when the stage is entered.
Immutable.

``actor_class``: the children's class, an Actor subclass.
``items(memo)``: returns the items, a sequence of plain JSON values, from trusted
    data (the workflow's input, or an earlier stage's results; never text a model or
    a person wrote). It is called on entering the stage and again when a stored run
    is revived during the visit: it must be a pure function of the memo.
``make(name, item, memo)``: returns the child for ``item`` (a fresh plain copy).
``start(item, memo)``: returns that child's start Event.
``join``: the Join that decides when the stage is over. It sees each item's FINAL
    Outcome (the last attempt's), in item order, and ``total`` is the number of
    items; an attempt that is followed by another is never shown to it.
``retry``: None (one attempt per item) or a Retry.
``window``: None (every item at once) or an int >= 1: the most children running at
    once. Items start in list order; when an item is final, the next one starts.
``limit``: the most items a visit may have, an int >= 1 (default ``ITEMS_LIMIT``);
    ``items`` returning more is a plan error (ValueError).
``empty``: None, or the symbol the stage ends with at once when there are no items
    (an internal symbol that needs a declared transition). Without it, no items is a
    ValueError.
``deadline``, ``expired``: as for Host. At the deadline the attempts still running
    are dropped (recorded as Abandoned), items not started yet are never started,
    and items already final keep their Results.
``retain``: as for Host.

Children are named ``"<workflow>/<stage>.<visit>.<index>.<attempt>"``: ``index`` is
the item's position in the list and ``attempt`` counts from 1. A retry is a new
child with a new name, so every request it makes has a new id (and every tool call a
new idempotency key), visibly. A visit stores, besides its children, a fingerprint
of the item list (revival refuses a list that changed) and each child's attempt
number, never the items themselves.

#### ForEach.actor_class

```text
actor_class() -> type[Actor]
```

#### ForEach.join

```text
join() -> Join
```

#### ForEach.retry

```text
retry() -> Retry | None
```

The Retry, or None for one attempt per item.

#### ForEach.window

```text
window() -> int | None
```

The most children running at once, or None for no limit.

#### ForEach.limit

```text
limit() -> int
```

The most items a visit may have.

#### ForEach.empty

```text
empty() -> Symbol | None
```

The Symbol no items ends the stage with, or None.

#### ForEach.expired

```text
expired() -> Symbol | None
```

The Symbol the stage ends with at its deadline, or None when it has none.

#### ForEach.timed

```text
timed() -> bool
```

True when the stage was built with a deadline function (and so an ``expired``
symbol). Does not call it: whether a visit gets a deadline is ``deadline(memo)``.

#### ForEach.retain

```text
retain() -> int | None
```

How many finished visits keep full Outcomes, or None for all of them.

#### ForEach.deadline

```text
deadline(memo: Memo) -> At | After | None
```

As ``Host.deadline``.

#### ForEach.attempts

```text
attempts() -> int
```

The most attempts per item (1 without a Retry).

#### ForEach.listed

```text
listed(memo: Memo) -> tuple[typing.Any, ...]
```

Call ``items`` and check its result: a tuple of the items, each frozen plain
JSON. TypeError unless a sequence of plain values; ValueError for more than
``limit`` items, or none without ``empty``.

#### ForEach.child

```text
child(name: str, item: typing.Any, memo: Memo) -> Actor
```

Call ``make`` with a fresh copy of ``item`` and check its result.

#### ForEach.opening

```text
opening(item: typing.Any, memo: Memo) -> Event
```

Call ``start`` with a fresh copy of ``item`` and check it returned an Event.

### Branch

```python
from gvn.harness.workflow import Branch
```

```text
Branch(
    actor_class: type[Actor],
    make: Callable[[str, Memo], Actor],
    start: Callable[[Memo], Event],
    verdicts: Mapping[str, str] | None = None,
    classify: Decision | None = None,
) -> None
```

One child of a Parallel stage. Immutable.

``actor_class``: the child's class, an Actor subclass.
``make(name, memo)``: returns the child. ``start(memo)``: its start Event.
``verdicts``: a mapping of the child's final state name -> verdict name, with
    exactly one entry per final state of ``actor_class``; or
``classify``: a kernel Decision over the child's Outcome, whose answer's name is the
    verdict. Exactly one of the two (ValueError otherwise).

A verdict is a name the stage's join counts or ranks, shared by every branch, so
children of different kinds can be joined by one rule.

#### Branch.actor_class

```text
actor_class() -> type[Actor]
```

#### Branch.classify

```text
classify() -> Decision | None
```

The classify Decision, or None when verdicts come from the ``verdicts`` mapping.

#### Branch.verdicts

```text
verdicts() -> dict[str, str] | None
```

A fresh dict of final state name -> verdict name, or None with ``classify``.

#### Branch.possible

```text
possible() -> frozenset[str]
```

Frozenset of every verdict name this branch can give.

#### Branch.verdict

```text
verdict(outcome: Outcome) -> str
```

The verdict name of the child's ``outcome``.

#### Branch.child

```text
child(name: str, memo: Memo) -> Actor
```

Call ``make`` and check its result.

#### Branch.opening

```text
opening(memo: Memo) -> Event
```

### Parallel

```python
from gvn.harness.workflow import Parallel
```

```text
Parallel(
    branches: Iterable[Branch],
    join: Join,
    deadline: Callable[[Memo], At | After | None] | None = None,
    expired: str | None = None,
) -> None
```

A stage running children of different kinds at once, one per Branch. Immutable.

``branches``: a non-empty sequence of Branch; child ``i`` is made by branch ``i``.
``join``: the Join that decides when the stage is over. It sees each finished
    child's VERDICT as an Outcome whose final state is named after it (no payload),
    in branch order, so ``AllOf``, ``AnyOf``, ``Quorum`` and ``Worst`` count and rank
    verdicts across kinds; it must not have a ``classify`` of its own (plan checking
    refuses one: classify each Branch instead). The children's real Outcomes are the
    visit's Results.
``deadline``, ``expired``: as for FanOut.

Children are named ``"<workflow>/<stage>.<visit>.<index>"`` as in a FanOut.

#### Parallel.branches

```text
branches() -> tuple[Branch, ...]
```

Tuple of the Branches, in child order.

#### Parallel.join

```text
join() -> Join
```

#### Parallel.expired

```text
expired() -> Symbol | None
```

The Symbol the stage ends with at its deadline, or None when it has none.

#### Parallel.timed

```text
timed() -> bool
```

True when the stage was built with a deadline function (and so an ``expired``
symbol). Does not call it: whether a visit gets a deadline is ``deadline(memo)``.

#### Parallel.deadline

```text
deadline(memo: Memo) -> At | After | None
```

As ``Host.deadline``.

#### Parallel.possible

```text
possible() -> frozenset[str]
```

Frozenset of every verdict name some branch can give.

#### Parallel.verdicts

```text
verdicts(results: Iterable[Result]) -> tuple[Outcome, ...]
```

The join's view of ``results`` (Results of this stage): one Outcome per
Result, whose final state is named after the child's verdict.

### SettingsMismatch

```python
from gvn.harness.workflow import SettingsMismatch
```

A stored workflow was refused because it was made under other settings: the
``settings`` fingerprint in its Dto (absent counts as None) differs from its plan's
``settings_fingerprint()``. The run is continued by the code it started on.

### PlanRejected

```python
from gvn.harness.workflow import PlanRejected
```

```text
PlanRejected(problems: Iterable[str]) -> None
```

A plan does not hold together. ``problems()`` is a tuple of every reason, as str.

#### PlanRejected.problems

```text
problems() -> tuple[str, ...]
```

### Compensate

```python
from gvn.harness.workflow import Compensate
```

```text
Compensate(
    stage: str,
    by: str,
    done: Iterable[str],
    untouched: Iterable[str] = (),
) -> None
```

Declares that the stage of state ``stage`` has effects that the stage of state
``by`` undoes. Immutable value, given to a Plan with its ``undone`` final states.

``stage``, ``by``: state names (str). ``done``: a non-empty sequence of symbol names:
``by`` has undone the effects when it ends with one of them. ``untouched``: a
sequence of symbol names (default none): ``stage`` ends with one of them only when
it changed nothing (a payment refused before any money moved), so that visit needs
no compensation. The Plan checks the rest: both states have stages, each stage can
end with each of its symbols, and none of them is that stage's ``expired`` symbol
(work cut at a deadline may have done anything, and has undone nothing).

#### Compensate.stage

```text
stage() -> str
```

The name of the state whose stage has effects.

#### Compensate.by

```text
by() -> str
```

The name of the state whose stage compensates them.

#### Compensate.done

```text
done() -> frozenset[Symbol]
```

Frozenset of the Symbols ``by`` ends with when it has compensated.

#### Compensate.untouched

```text
untouched() -> frozenset[Symbol]
```

Frozenset of the Symbols ``stage`` ends with only when it changed nothing.

### Plan

```python
from gvn.harness.workflow import Plan
```

```text
Plan(
    definition: Definition,
    stages: Mapping[State | str, Host | FanOut | ForEach | Parallel],
    relay: Iterable[Symbol | str] = (),
    compensations: Iterable[Compensate] = (),
    undone: Iterable[State | str] = (),
    model_roles: Iterable[str] = (),
    tools: Iterable[Tool] | Toolbox = (),
    sensor_tools: Iterable[Tool] | Toolbox = (),
    settings: typing.Any = None,
) -> None
```

What a workflow does: a verified control machine and the stage of each state.

Immutable, and checked as a whole at construction; every problem is reported
together in PlanRejected:

* ``definition`` must be a Moore Definition (TypeError if not a Definition).
* every key of ``stages`` must be a non-final state of the definition, and
  every value a Host, FanOut, ForEach or Parallel; the initial state has no stage.
* for a Host, every symbol in its routes (or every outcome of its judge) must
  have a declared transition out of that state (so every way the child can
  end is routed explicitly).
* for a FanOut, ForEach or Parallel, every symbol in its join's outcomes, and its
  ``empty`` symbol if any, must have a declared transition out of that state; a
  Worst join's order must cover every verdict the children can have, a Quorum's
  veto verdicts and a ForEach's retry verdicts must be verdicts they can have, and
  a Parallel's join must not classify.
* for a stage with a deadline, its ``expired`` symbol must have a declared
  transition out of that state (a stage has a deadline function and an
  ``expired`` symbol together or neither: the stages refuse one alone).
* every ``relay`` name must be a valid symbol name that is not an input of the
  definition.
* ``compensations`` (a sequence of Compensate) and ``undone`` (final state names)
  come together or not at all. Every way the machine can walk into an ``undone``
  final state must, after entering each compensated stage (unless that visit
  ended on one of its ``untouched`` symbols), leave its ``by`` stage on a ``done``
  symbol, in reverse order of the stages; the verifier proves it over the
  definition's graph (``Verifier.examine_compensations``) and each problem names
  the walk that breaks it.

``stages`` is a mapping keyed by state name (str) or State; ``relay`` an
iterable of names (str) or Symbols. TypeError if they are not.

``model_roles``: an iterable of the model roles (each as
``gvn.harness.context_window.model_role_checked`` accepts, TypeError/ValueError
otherwise) that the children this plan builds, and anything beneath them, may ask
for. It is what a workflow answers for ``model_roles()``, so the wiring is checked
against it before the run starts (``gvn.harness.ports.Fulfiller.unmet``). Building a
child whose ``model_roles()`` names a role the plan does not declare is a ValueError
naming the workflow, the stage, the child and the roles, so any test that reaches the
stage finds an undeclared role. A plan is code, so this is never stored.

``tools``: the Tools (an iterable of Tool, or a Toolbox; a str is a TypeError saying
to pass the tool) that the children this plan builds, and anything beneath them, may
be offered or call, declared as ``model_roles`` is: it is what a workflow answers for
``tool_identities()``, so the runtime's toolbox is checked against their identities
before the run starts, and building a child whose ``tool_identities()`` holds one the
plan does not declare is a ValueError naming the workflow, the stage, the child and
the identities. Tools of different children may share a short name; only identities
are kept, and never stored.

``sensor_tools``: the measuring Tools (gvn.harness.sensors) the sensors of the
children this plan builds, and of anything beneath them, may read, declared as
``tools`` is: it is what a workflow answers for ``sensor_identities()``, so the sensor
toolbox is checked against them before the run starts, and building a child whose
``sensor_identities()`` holds one the plan does not declare is a ValueError naming the
workflow, the stage, the child and the identities.

``settings``: None, or plain JSON data (anything ``gvn.kernel.schema.Json``
accepts, SchemaViolation otherwise; a copy is kept) saying what the plan's own
code was built from: everything its stage functions, judges, joins and deadlines
put into the run that the definition does not show, such as instructions,
conventions, limits and model choices, or simply a version string for code that
holds such things itself. The definition's fingerprint covers the machine; the
settings cover the behaviour around it. A workflow stores
``settings_fingerprint()`` and a stored workflow revives only under a plan with
the same one (``SettingsMismatch``), so a run is never continued by stage
functions other than the ones it started with. The plan's code does not read
the settings through the plan: pass the same data to both.

#### Plan.name

```text
name() -> str
```

The definition's name.

#### Plan.definition

```text
definition() -> Definition
```

#### Plan.stage

```text
stage(state: State) -> Host | FanOut | ForEach | Parallel | None
```

The Host, FanOut, ForEach or Parallel of ``state`` (a State), or None.

#### Plan.stages

```text
stages() -> Mapping[State, Host | FanOut | ForEach | Parallel]
```

Which states have a stage, and which: a read-only mapping of State to its
Host, FanOut, ForEach or Parallel, holding only the states that have one, in
the order of ``definition().states()``. Runs no plan code.

#### Plan.relay

```text
relay() -> frozenset[Symbol]
```

Frozenset of the relayed Symbols.

#### Plan.compensations

```text
compensations() -> tuple[Compensate, ...]
```

Tuple of the Compensate declarations, as given.

#### Plan.undone

```text
undone() -> frozenset[State]
```

Frozenset of the final States that mean the run was undone.

#### Plan.model_roles

```text
model_roles() -> frozenset[str]
```

Frozenset of the model roles the plan declares (``model_roles=``).

#### Plan.tool_identities

```text
tool_identities() -> frozenset[str]
```

Frozenset of the identities of the tools the plan declares (``tools=``).

#### Plan.sensor_identities

```text
sensor_identities() -> frozenset[str]
```

Frozenset of the identities of the measuring tools the plan declares
(``sensor_tools=``).

#### Plan.settings

```text
settings() -> typing.Any
```

A fresh copy of the settings the plan was given (``settings=``), or None.

#### Plan.settings_fingerprint

```text
settings_fingerprint() -> str | None
```

What a stored workflow of this plan must match to revive: a str, or None.

None when this plan was given no settings and no Workflow class that its
stages name (a Host's or FanOut's or ForEach's ``actor_class``, each Branch of
a Parallel) has a plan with a fingerprint of its own. Otherwise the SHA-256
hex digest of canonical JSON (sorted keys, no whitespace) holding this plan's
settings and, for each such Workflow class that has one, its plan's own
``settings_fingerprint()``, placed by stage state name and, for a Parallel,
branch index. So a change of settings anywhere beneath a workflow, in a
stage it has not entered yet as much as in the one it is in, changes the
fingerprint of every plan above it. Only settings enter it: definitions,
class names and code do not. Equal settings (as JSON values, whatever the key
order) give equal fingerprints. Worked out once per Plan.

#### Plan.produced

```text
produced() -> Mapping[Symbol, str]
```

Read-only mapping of every symbol a stage produces (route values, judge and
join outcomes, ``empty`` and ``expired`` symbols) to the name of the first stage (by
state name) producing it. These symbols are internal: a workflow refuses them
from outside.

#### Plan.after

```text
after(state: State) -> Mapping[Symbol, State]
```

Read-only mapping of each symbol the stage of ``state`` (a State) can end with
to the State it leads to; empty when ``state`` has no stage.

#### Plan.leads

```text
leads(state: State) -> frozenset[Symbol]
```

Frozenset of the symbols in ``after(state)`` that lead into a state with a stage
(ending the stage that way opens the next one, which runs plan code).

### Workflow

```python
from gvn.harness.workflow import Workflow
```

```text
Workflow(name: str) -> None
```

Subclass this and implement ``plan`` to define a workflow.

    class Review(Workflow):
        @classmethod
        def plan(cls):
            return REVIEW_PLAN        # a module-level Plan, built once

``plan`` must return the same Plan every time. Everything else is provided
here. The implementer of this class defines its inner Dto, which must capture
the machine position, input, every finished visit of every stage and every
active child (each child's own plain Dto). ``from_dto`` rebuilds children
through the actor class named by the plan's stage, raises TypeError for a
foreign Dto and ValueError for a Dto made by a different plan (compare plan
names and the definition fingerprint held in the machine position), and
``SettingsMismatch`` (a ValueError) for a Dto whose ``settings`` fingerprint is not
the plan's ``settings_fingerprint()``, checked before any child is rebuilt, so
nothing of a refused Dto is loaded. A checkpoint and its ``rollback`` stay within
one plan and check nothing.

#### Workflow.plan

```text
plan() -> Plan
```

The Plan this workflow follows.

#### Workflow.definition

```text
definition() -> Definition
```

``cls.plan().definition()``.

#### Workflow.name

```text
name() -> str
```

The actor's address: a non-empty str, stable for its whole life.

#### Workflow.model_roles

```text
model_roles() -> frozenset[str]
```

The roles its plan declares (``Plan.model_roles()``): every child it builds is
checked against them.

#### Workflow.tool_identities

```text
tool_identities() -> frozenset[str]
```

The identities of the tools its plan declares (``Plan.tool_identities()``):
every child it builds is checked against them.

#### Workflow.sensor_identities

```text
sensor_identities() -> frozenset[str]
```

The identities of the measuring tools its plan declares
(``Plan.sensor_identities()``): every child it builds is checked against them.

#### Workflow.interruptible

```text
interruptible() -> bool
```

True when ``interrupted`` is an input of its plan's definition or is relayed
to its children (``Plan.relay()``).

#### Workflow.handle

```text
handle(event: Event) -> Reaction
```

Consume an Event and return the Reaction. Synchronous, no I/O.

Raises UnknownSymbol when the event's name is not in the actor's input
alphabet, and ValueError when its payload does not fit what that input
requires; in both cases the actor is unchanged. An event that is valid but
not expected in the current state is not an error: it returns a rejected
Reaction and changes nothing, data included.

Addresses: an event whose ``to()`` is neither None, the actor's own name nor
(for composite actors) the name of something beneath it raises ValueError and
changes nothing. After the call, ``reaction.requests() == self.pending()``.

#### Workflow.settles

```text
settles(event: Event) -> bool
```

Could handling ``event`` leave this workflow finished (see ``Actor.settles``)?

An own event: True when its declared step lands in a final state or in a state
with a stage (whose children may finish at once and cascade on). An event for a
child: True when that child settles on it and its finishing could take this
workflow on into a final state or a stage. An event that would be ignored or
rejected answers False; anything ``handle`` would refuse answers True.

#### Workflow.checkpoint

```text
checkpoint(event: Event) -> _Checkpoint
```

What ``rollback`` needs to undo this workflow's handling of ``event``.

For a host that is about to hand ``event`` to this workflow and may have to undo
it afterwards (when its own plan code raises). Cheap: it holds this workflow's own
fields and, recursively, what undoes the children ``event`` reaches (the
addressed child, or every child for a relayed event); children created on the
way are simply forgotten, children dropped are unchanged objects. The result is
opaque; it is valid only for the one ``handle`` call that follows. Changes
nothing. TypeError if ``event`` is not an Event.

#### Workflow.rollback

```text
rollback(checkpoint: object) -> None
```

Undo the ``handle`` call made since ``checkpoint`` was taken.

TypeError unless a checkpoint; ValueError if it was taken by another workflow or
if this workflow changed more than once since (only the next ``handle`` call can
be undone).

#### Workflow.pending

```text
pending() -> tuple[Request, ...]
```

The tuple of Requests the actor wants from the outside world (empty when none).

In a stable order. Equal to the requests of the Reaction returned by the latest
``handle`` call, with the same ids. This is what lets work be re-issued after a
crash: a revived actor still knows what it was waiting for.

#### Workflow.state

```text
state() -> State
```

The current control State.

#### Workflow.standings

```text
standings() -> tuple[Standing, ...]
```

Where this workflow and everything it hosts stand (``Actor.standings``).

Its own Standing first (its plan's definition and its current state), then, for
each active child in child order, that child's ``standings()``, so a hosted
workflow lists its own children in turn. Finished children are no longer
hosted and are not listed. No I/O; changes nothing.

#### Workflow.expected

```text
expected() -> frozenset[Symbol]
```

The workflow machine's own expected symbols (children's are not included).

#### Workflow.finished

```text
finished() -> bool
```

True when the control state is final.

#### Workflow.outcome

```text
outcome() -> Outcome
```

The Outcome: ``{"input": ..., "history": {stage: [[result, ...], ...]}}``.

Built once when first asked for in a final state and then shared (an Outcome is
immutable and a final workflow never changes). Each result is
``{"index", "name", "outcome": <Outcome.Dto plain>}``. Read it with ``Report``.

#### Workflow.active

```text
active() -> tuple[str, ...]
```

Tuple of the names of the active children, in child order.

#### Workflow.to_dto

```text
to_dto() -> Workflow.Dto
```

A Dto capturing the complete internal state. Does not mutate the object.

#### Workflow.from_dto

```text
from_dto(dto: Dto) -> typing.Self
```

Rehydrate. TypeError for a foreign Dto; ValueError for one made by another plan
or one that does not hold together (for a running ForEach visit, also when its
``items`` function now lists items with another fingerprint).
