# Interface contracts

**What you will learn:** which interfaces of gvn you use or implement when you build a
harness, where each one sits in the whole system, and what an implementation of each must
promise. It is a focused contract reference, not an exhaustive list of every public name;
the defining modules' docstrings specify detailed signatures and errors. The
[stability policy](stability.md#the-public-api) explains which names belong to the public
API.

**Read first:** [The model behind gvn](../concepts/index.md) and
[Architecture](architecture.md), or the first three [tutorials](../tutorials/index.md).
**Time:** about 10 minutes to read; the tables are for looking things up.

## Where this sits

An **interface** here is a boundary between your code and gvn's: a class you subclass or
call, whose behaviour is fixed by a contract rather than by its implementation. Every box of
the [loop picture](../concepts/index.md#picture-1-the-loop-that-runs) has one. The actor's
machine and its decisions live in the kernel and harness; the ports that reach the outside
world are defined in the harness and implemented by adapters; the Governor in the runtime
connects them.

## The shape of it

```mermaid
flowchart LR
    subgraph decide ["Deciding (kernel, harness): pure, no I/O"]
        direction TB
        actor["Actor<br/>handle · pending · outcome"]
        decision["Decision<br/>outcomes · judge"]
        stages["Workflow stages and Plan<br/>Host · FanOut · ForEach · Parallel"]
        decision --> actor
        stages --> actor
    end
    governor["Governor<br/>(runtime)"]
    subgraph doing ["Doing (through ports)"]
        direction TB
        fulfiller["Fulfiller"]
        tool["Tool"]
        ports["Model · Journal · Leases · Clock · Output · Memory · Throttle"]
    end
    actor -- "requests" --> governor
    governor -- "events" --> actor
    governor --> fulfiller
    fulfiller --> tool
    fulfiller --> ports
```

The left side **decides**: an [actor](../concepts/actors-and-events.md) takes events and
names the work it wants as requests; a [Decision](../concepts/decisions.md) turns data into
one of a fixed set of symbols; workflow stages compose actors into a bigger actor. None of it
does input or output. The right side **does**: the [Governor](../concepts/governor.md) hands
each request to a fulfiller, which reaches tools and outside services only through
**ports**, the abstract classes in `gvn.harness.ports` that adapters and fakes implement.

You meet these interfaces in that order of likelihood. Most harnesses compose ready-made
actors and write decisions and tools; fewer implement a port; few write a new actor. The
table below picks the boundary for a task, and the sections after it give each contract in
detail.

## Choose the boundary you need

| You want to… | Use or implement | Contract and example |
|---|---|---|
| Run the standard model/tool loop | `Agent` or `run_agent` | [Reference agent](../concepts/reference-agent.md), [short path](../guides/shortcuts.md) |
| Compose existing actors | `Host`, `FanOut`, `ForEach`, `Parallel`, `Plan`, `Workflow` | [Stage parameters below](#workflow-stage-parameters), [Workflows](../concepts/workflows.md) |
| Add a new pure branching rule | `Decision` | [Decision](#decision): declared finite outcomes and no I/O |
| Add an operation with effects | `Tool` | [Tool](#tool): explicit input schema, a stable identity and repeat-safe effects |
| Measure after a tool succeeds and show the model the result | `Sensor`, a measuring `Tool` and `SensorFulfiller` | [Sensor](#sensor): a read-only measurement that returns a reading |
| Add a vendor or infrastructure implementation | A port from `gvn.harness.ports` | [Ports](#ports): model, journal, leases, clock, output, memory or throttle |
| Let the memories gvn ships recall by meaning through an embedding model of your choice | An `Embedder` from `gvn.runtime.memory` | [Embedder](#embedder), [Recall by meaning](../concepts/memory.md#recall-by-meaning) |
| Hold calls to a shared limit (so many at once, so many per period) | A `Throttle`, applied with `ThrottledModel` | [Ports](#ports), [Spending and rate limits](../guides/spending-and-rate-limits.md) |
| Decide who may answer a waiting request | An entitlement `Decision` (`Governor(entitlement=)`) | [Decision](#decision): outcomes `ENTITLEMENTS`, subject an `Answering` |
| Define a different event/request protocol | `Actor` | [Actor](#actor): state ownership, deterministic requests, atomic event handling |
| Save your own stateful object | `Durable` and its inner `Dto` | [Durable objects](../concepts/durable-objects.md) |
| Replace a domain subsystem | An application-owned brief/result contract | [Designing a large harness](../guides/large-harnesses.md) |
| Package a whole job so it can be launched, evaluated and drawn | `Harness` from `gvn.runtime.harnesses`, run by `Launcher` from `gvn.runtime.launching` | [Harnesses](../concepts/harnesses.md) |

## Actor

Import `Actor`, `Outcome`, `Reaction` and `NotFinished` from `gvn.harness.actor`; import
`Event` and `Request` from `gvn.harness.events`. A `Reaction` is what an actor returns for
one event: whether it was accepted or rejected, and the requests now wanted. An `Outcome` is
a finished actor's final state with its result data. `NotFinished` is the error for asking a
running actor for its outcome.

| Method | Responsibility |
|---|---|
| `name()` | Return the non-empty stable address of this actor. |
| `definition()` | Return its control `Definition`, callable on the class before an instance exists. |
| `handle(event)` | Synchronously handle an `Event` and return a `Reaction`, without I/O. Resolve internal decisions before returning external requests. |
| `pending()` | Return every currently wanted `Request`, in stable order, with stable ids. |
| `state()`, `expected()`, `finished()` | Expose the control position (the machine's current state), the symbols the actor explicitly expects now, and whether the actor is final. |
| `outcome()` | Return the final `Outcome`; raise `NotFinished` before a final state. |
| `to_dto()`, `from_dto(dto)` | Save and restore the whole actor, including owned children. |
| `settles(event)` | Conservatively report whether the event could finish the actor. The default `True` is safe; returning `False` must never miss a possible finish. |
| `interruptible()` | Return `True` when the actor takes the `interrupted` input: its machine declares it, or (a composite actor such as a workflow) it relays it to what it hosts. Constant for the actor's life and answered without I/O. A Governor with an allowance asks it first and refuses an actor that answers `False`, since reaching the allowance is delivered as `interrupted` ([Spending and rate limits](../guides/spending-and-rate-limits.md)). The default answers from `definition()`. |
| `standings()` | Return a tuple of `Standing` (from `gvn.harness.actor`: a name, the `Definition` it runs on, a `State`): this actor's own first, then one for every actor it hosts now, each followed by those it hosts in turn. Answered without I/O. The default answers this actor alone on `definition()`; an actor built on another definition than its class's, or one that hosts actors, answers for itself. [Inspection](../guides/inspecting-a-run.md) reads it. |
| `model_roles()`, `tool_identities()`, `sensor_identities()` | Return, as frozensets, every model role, every [tool identity](glossary.md#tool-identity) and every measuring tool's identity (its [sensors'](../concepts/sensors.md)) this actor, and anything it will build beneath it, may need. Constant for the actor's life and answered without I/O: the Governor checks the wiring against them before the actor handles an event. The defaults answer none. |

A `Reaction` from an actor that hosts others also says who took each step and who passed:
`origins` (the name of the actor that took each step, read with `attributed(name)`) and `passed`
(the actors that started and finished while the event was handled, each as a `Standing` at its
final state). `Workflow` fills both, at any depth.

The central laws are `reaction.requests() == actor.pending()` after a handled event, and
that a rejected or raising event leaves the actor unchanged. An unknown symbol raises
`UnknownSymbol`; an invalid payload or address raises `ValueError`. An input known to the
machine but unexpected in the current state returns a rejected reaction.

`Outcome.state()` describes the terminal control state. `payload()` returns a fresh copy
of its data; `view()` supplies a read-only form. Plain JSON validity is not a domain schema:
the application still needs to check that, for example, a successful build contains the
artifact its parent requires. See [Actors and events](../concepts/actors-and-events.md).

## Workflow stage parameters

Import the stage classes and `Plan` from `gvn.harness.workflow`. A **stage** is the recipe
that creates a parent workflow's children for one of its states; a `Plan` ties the parent's
machine to its stages ([Workflows](../concepts/workflows.md)). The **memo** passed to stage
functions is the parent's read-only view of its starting input and finished stage results;
an **`Ending`** is what a judge reads: the child's outcome, the memo and the stage's name.

| Parameter | Meaning and obligation |
|---|---|
| `actor_class` | The child type the stage creates and restores; must implement `Actor`. |
| `make(name, memo)` | Construct a hosted child with exactly the supplied address. Fan-out/item stages also pass an index or item; see their examples. |
| `start(memo)` | Build the child's opening `Event` from the parent's data. It must be accepted by the child. |
| `routes` | Map every child final state to a parent input (for an `Agent` or a `Conversation`, that includes `overflowed`). Use when routing depends on how the child ended. |
| `judge` | A `Decision` over an `Ending` when routing also depends on result data or the parent's memo. Use instead of `routes`. |
| `join` | Decide when a group is settled and which parent input it produces. Declare every possible answer. |
| `definition` on `Plan` | The verified Moore machine that controls the parent. |
| `stages` on `Plan` | Map non-initial, non-final parent states to stage recipes. Every stage-produced symbol needs a declared transition. |
| `relay` on `Plan` | Events addressed to the parent that should be forwarded to its active children; they must not be parent-machine inputs. |
| `model_roles` on `Plan` | Every model role a child, or anything beneath it, may ask for. Building a child that names another is a `ValueError`. |
| `tools` on `Plan` | Every Tool (objects, or a `Toolbox`) a child, or anything beneath it, may be offered or call. The workflow answers their identities for `tool_identities()`, so the runtime's toolbox is checked before the run; building a child that needs a tool not declared is a `ValueError`. Children may use same-named tools of different identities. |
| `sensor_tools` on `Plan` | Every measuring Tool the [sensors](../concepts/sensors.md) of a child, or of anything beneath it, may read, declared as `tools` is. The workflow answers their identities for `sensor_identities()`, checked against the sensor toolbox before the run; building a child whose sensors read one not declared is a `ValueError`. |
| `settings` on `Plan` | `None`, or plain JSON data: what the plan's stage functions, judges, joins and deadlines were built from (instructions, conventions, limits, model choices, or a version string). `Plan.settings()` returns a copy; `Plan.settings_fingerprint()` is a str, or `None` with no settings anywhere beneath the plan, taking in the settings of every workflow class beneath it. A workflow stores it, and a stored workflow revives only under the same one, otherwise `SettingsMismatch` (a `ValueError`). Pass as settings the data your stage functions read; gvn compares settings, not code. See [Workflows in depth](../concepts/workflows-in-depth.md#settings). |

Stage construction checks child terminal-state routing; plan construction checks that stage
outcomes have declared parent transitions. Checking that a child's JSON result has the
content its parent needs is the application's job. `Memo` exposes the parent's starting input and recorded stage
results; it does not give callbacks permission to mutate a child's private state.

[Workflows](../concepts/workflows.md) gives a complete example. [Workflows in depth](../concepts/workflows-in-depth.md)
and the linked guides specify joins, item/window/retry parameters, deadlines and compensation.

## Decision

Import `Decision` and `UndeclaredOutcome` from `gvn.kernel.decision`.

Implement `outcomes()` to return a fixed `Alphabet` and `judge(subject)` to return one
`Symbol` in it. Callers use `decide(subject)`, which checks the answer and raises
`UndeclaredOutcome` for an undeclared one. Exceptions from `judge` propagate. A Decision is
synchronous and pure; request I/O through an actor, then classify its result.

The subject is defined by the use site: a tool policy sees a `Consultation` (the tool call
being judged with its tool's identity, the model reply it came from, which actor asked, and
its run context; `consultation.calls_to(tool)` tells whether it calls a given Tool, and
`consultation.exposure()` names the untrusted sources the actor's model had read), a
workflow judge an `Ending`, an entitlement (`Governor(entitlement=)`, outcomes
`ENTITLEMENTS` from `gvn.harness.answering`) an `Answering` (the request, the answering
event and the `Principal` the entry point named, or `None`). An entitlement reads trusted
data only: the principal and the request's context, never what a model wrote.
[Trust](../concepts/trust.md) shows both. Declaring outcomes makes routing checkable; your tests check
that `judge` answers correctly. [Decisions](../concepts/decisions.md) introduces the pattern.

## Tool

Import `Tool`, `Invocation`, `Toolbox` and `FixedCall` from `gvn.harness.tools`.

Implement `name()`, `description()`, `arguments()` and async `run(arguments, invocation)`.
`name()` is the short name the model sees; the description explains the operation to the
model, and `arguments()` returns an explicit `Record` schema. Every tool also has
`namespace()`, by default the module that defines its class, and `identity()`,
`namespace() + "." + name()`, which gvn stores and matches on; never override `identity()`.
A class that backs many tools (one per configuration) takes a `namespace=` when it is built
and returns it from `namespace()`. A `Toolbox` holds each identity once and may hold
same-named tools of different identities; the tools one actor is offered have one tool per
short name. Code refers to a tool by passing the object (`Agent(tools=[...])`,
`FixedCall(call_id, tool, arguments)`, `Plan(tools=...)`, policy and evaluation helpers); a
str is a `TypeError`. See [Tools](../concepts/tools.md). Runtime invocation validates the
arguments before running the tool. The result is plain JSON or `ToolOutput` for JSON plus
attachments (images or documents returned to the model). An exception becomes a failed tool result.

`Invocation` supplies the issuing actor's address, its trusted
[run context](../concepts/run-context.md), and a stable call key, the call's
[idempotency key](../concepts/run-context.md#idempotency-keys): the same key on a repeated
delivery of the same call, so the effect can be made once. Check domain scope in the tool
before acting, and make repeated delivery safe using that key. A crash may repeat the same call with the same key; a new model
call after interruption may have a new key. A business effect that must happen only once
needs a business identifier as well. `independent()` defaults to `False`; override with
`True` only for an operation independent of other calls in the reply. `retry()` defaults to
`None` (one attempt); return a `gvn.harness.ports.Retry` only when repeating the call under
the same key is safe, and raise `ToolFailure(..., retryable=True)` for a failure worth
trying again. `untrusted()` defaults to `False`; return `True` when the tool's results may
hold text written by someone the deployer does not control (a web page, an issue, an email,
another system's record), and an actor that hands such a result to its model records the
tool's identity in its exposure ([Trust](../concepts/trust.md)). It returns a bool,
constant for the tool's life.

The reusable suite `ToolContract` (in `gvn.testing.contracts`; implement `make_tool()`)
checks the short name, the namespace, the identity and the description of a tool as it would
be deployed, that `independent()` and `untrusted()` answer a bool and `untrusted()` the same
one every time, and that `retry()` answers `None` or a `Retry`. See [Adding a tool](../tutorials/adding-a-tool.md), [Tools](../concepts/tools.md),
[Run context](../concepts/run-context.md) and [Crash and resume](../tutorials/durability.md).

## Sensor

Import `Sensor` from `gvn.harness.sensors` and `SensorFulfiller` from
`gvn.runtime.fulfillers`. A [sensor](../concepts/sensors.md) is gvn's post-tool hook:
`Sensor(name, after, tool, arguments=None, blocks=False, limit=2000)` says "after one of the
`after` tools succeeds, call `tool` with `arguments`". Pass it to an `Agent` or a
`Conversation` as `sensors=[...]` (or to `run_agent` with `sensor_tools=`); every watched tool
must be offered to that actor, and sensor names are unique per actor. The arguments are
checked against the measuring tool's schema when the sensor is built.

A measuring tool is an ordinary [Tool](#tool) whose result is a **reading**,
`{"clean": bool, "text": str}`; the tool decides what clean means. It is served by
`SensorFulfiller(toolbox)`, registered for the `sense` kind, from a toolbox of its own: it is
never offered to the model and never asked of the policy or a person, so it must be a
read-only measurement. A tool that fails or returns anything else gives a failed reading;
the run goes on. What is kept of a reading is bounded apart from what is shown: `limit` is
the most characters of its text the model is shown, while every reading's text (and a failed
reading's reason) is kept to at most `STORED_READING` characters (20,000), whatever the
`limit`. `kept_text(text)` does the cut, the head followed by
`[cut: kept K of N characters]`: the `SensorFulfiller` applies it before the `sensed` answer
is journaled, and the actor applies it again when it accepts an answer, so its snapshot, its
outcome and the `event` signal of `sensed` never carry more. `SensorFulfiller.unmet(actor)` names the measuring tools its toolbox lacks;
the Governor also refuses an actor with sensors when nothing serves `sense`, before
anything is journaled. `gvn.runtime.evaluation.Sensed(label, sensor_name, accepts)` grades
what a sensor read in a recorded run.

## Ports

Import ports from `gvn.harness.ports`. Use real implementations from `gvn.adapters` or fakes
from `gvn.testing.fakes`. In the table, an `Exchange` is what a model is asked (instructions,
messages, tools, an optional answer schema) and a `Reply` what it answers; `Progress`
receives streamed text; `ModelFailure` is the one error a model reports failure with; a
`Signal` is one observation the Governor emits to an `Output`. A **fence** is the number a
[lease](glossary.md#lease) carries so that a journal can refuse a write from a process that
no longer owns the run ([Running as a service](../guides/running-as-a-service.md)). Port implementations are outside the durable actor; a restored
actor receives work through the new process's injected ports.

| Port | Main operations | Implementation obligation | Reusable tests |
|---|---|---|---|
| `Model` | async `generate(exchange, progress)`; `context_window()`; `provider()` | Return a `Reply` with the tokens the call reported, report text through `Progress`, translate vendor errors to `ModelFailure`, with `exceeded_context=True` when the vendor refused the conversation as too large for the model's context window. `context_window()` returns the window in tokens, or `None` (the default) when unknown; it is constant for the object's life. `provider()` names the service that serves the model, a lower-case str as the OpenTelemetry GenAI conventions name it (`"anthropic"`, `"openai"`), or `None` (the default); constant for the object's life, and journaled with every answer whose `Reply` does not name its own. | `ModelContract` |
| `Journal` | async `begin`, `append` (with `position`), `read`, `length`, `runs`, `save_snapshot`, `latest_snapshot`, `first_snapshot` | Preserve ordered records and snapshots, return independent data, honor write fences when supplied, list the runs held in code point order. `begin` writes a run's birth snapshot and opening record as one atomic step, and a write to a place another writer took raises `PositionTaken` and writes nothing. | `JournalContract` |
| `Leases` | async `acquire`, `renew`, `release`, `holder`, `due`, `earliest` | Coordinate ownership and schedule parked runs using caller-supplied time; preserve fencing rules. | `LeasesContract` |
| `Clock` | `now()`, async `sleep(seconds)` | Provide time and nonblocking waiting; tests inject a manual clock. | `ClockContract` |
| `Output` | synchronous `emit(signal)` | Return promptly; never block on I/O. Observer exceptions are swallowed and counted by the Governor. | `OutputContract` |
| `Memory` | async `remember(scope, text, key)`, `recall(scope, query, limit)`, `forget(scope, entry)`, `forget_all(scope)` | Keep text under a scope and return its id; the same scope and key again keeps nothing new and returns the first id. Never recall across scopes. Return at most `limit` fresh `{"id", "text"}` entries, best first; what "match" means is the implementation's. Forget one entry (True when one was removed) or every entry of a scope (how many were removed); a forgotten entry is never recalled again and its id is never reused. Raise `MemoryFailure` when it cannot; refuse bad arguments with `TypeError`/`ValueError`; honour cancellation. See [Memory](../concepts/memory.md). | `MemoryContract` |
| `Throttle` | async `acquire()`, `release()`, `hold_off(seconds)` | Decide only when a call may start, never refuse one. A caller that returns from `acquire` calls `release` exactly once when its call ends; a cancelled `acquire` holds nothing. `hold_off` admits nothing new for that many seconds (a vendor's retry-after) without shortening a longer hold in force; the default only checks the number. Waiting is not journaled. One object is shared by everything the limit covers. `ThrottledModel(model, throttle)` in `gvn.runtime.throttles` applies one to a `Model`. | `ThrottleContract` |
| `Fulfiller` | async `fulfil(request, progress)`; `unmet(actor)` | Turn a request into its result `Event`; the Governor associates the result with its origin. `unmet(actor)` returns None, or a str naming what this fulfiller lacks for the actor (a model role, a tool identity, a measuring tool); the Governor asks it before the actor handles an event and raises `Unfulfillable` on a str, before anything is journaled. | Test its request/result protocol and error behavior. |

The built-in fulfillers (`gvn.runtime.fulfillers`, and `MemoryFulfiller` in
`gvn.runtime.memory`) sit between the Governor and these ports. One of them takes more than
one port implementation: `ModelFulfiller(model, toolbox, retry=None, roles=None)` serves a
request that names a `"model_role"` with that role's model from `roles` (a mapping of role
name to `Model`), every other request with `model`, and raises `ValueError` for a role it
does not have ([A model per role](../guides/vendors.md#a-model-per-role)). `ModelFulfiller`
and `ToolFulfiller` each report, from `unmet`, the tool identities of an actor that their
toolbox does not hold ([checked before the run starts](../concepts/tools.md#checked-before-the-run-starts)),
and `SensorFulfiller` the measuring tools of an actor's sensors that its toolbox does not
hold.

The reusable suites live in `gvn.testing.contracts`. [Testing your harness](../concepts/testing.md)
shows how to use them; [Architecture](architecture.md) describes dependency rules.

### Embedder {#embedder}

An `Embedder` (import it from `gvn.runtime.memory`) is not a port: no actor, tool, fulfiller
or Governor sees one. It is what the memories gvn ships, `SqliteMemory` and `ListMemory`, take
as an optional argument to recall by meaning as well as by words; a `Memory` of your own
never needs one.

| Interface | Main operations | Implementation obligation | Reusable tests |
|---|---|---|---|
| `Embedder` | `name()`; async `embed(texts)` | `name()` is a non-empty str, constant, the same for every object whose vectors may be compared and different otherwise; no I/O. `embed` returns, for a non-empty list of non-empty str, a fresh list with one vector per text in the same order: lists of finite floats, of one length on every call, none all zeros; the same text gives the same vector. Raise `EmbedderFailure` when it cannot; honour cancellation. `OpenAIEmbedder` (in `gvn.adapters.openai`) and the fake `HashingEmbedder` implement it. See [Recall by meaning](../concepts/memory.md#recall-by-meaning). | `EmbedderContract` |

## Saved state and implementation changes

A [Dto](../concepts/durable-objects.md) is an object's serialization interface, not permission for consumers to inspect its
private layout. Round-trip laws test restoration of behavior. Versioned stored forms (the
numbered shapes of what gvn writes to a journal) govern upgrades of journal records and
snapshots; see [Stability](stability.md).

Changing a child's internal implementation for a **new run** and resuming an **existing
run** under changed code are different operations. The latter also needs compatible saved
state and compatible replay behavior, beyond a matching control graph.

**Next:** the [scale benchmark](scale.md), which measures what these layers cost at
10,000 agents.
