# Domains

`gvn-domains` is a package of complete, working harnesses built with gvn: a support desk, a
release train, a contract review and twelve more. This page shows what every one of them is
made of and how they differ, then the shared pieces you use to build, run and test any of
them.

- **You will learn:** what a domain harness is made of and where each part sits in gvn's
  big picture; which example to read for the feature you care about; and the three pieces
  every example shares: the catalog, the `Launcher` and the contract test suite.
- **Read first:** the [quickstart](../quickstart.md) (its big picture is the frame for this
  page), the [tutorials](../tutorials/index.md) and the concept pages
  [Workflows](../concepts/workflows.md) and [The Governor](../concepts/governor.md). Each
  domain page also names the concept pages it relies on.
- **Time:** about 15 minutes for this page; 15 to 30 minutes for each domain page.

## What the domains package is

A [**harness**](../reference/glossary.md#harness) is the program around a model: its agents,
tools, policy, records and evaluation. `gvn-domains` is a sibling package of fifteen
complete harnesses built with gvn, in eleven domains: customer service, software
engineering, security, enterprise back-office work, software delivery, research, data
pipelines, education, finance, legal work, and harnesses that improve other harnesses.

- **Built as you would build.** It uses gvn only through its public interface.
- **Worked examples.** Each harness is a complete program you can read, build with your
  own ports, or copy from.

The companion package is `gvn-domains` (import name `gvn_domains`). It depends on the
core `gvn` package, so `pip install gvn-domains` installs both.

## What a domain harness is made of

Every harness in the package has the same five parts. Each one is a box of the
[quickstart's big picture](../quickstart.md#the-big-picture), packaged for one kind of job:

- **A plan.** A run is one [**workflow**](../reference/glossary.md#workflow): an
  [actor](../reference/glossary.md#actor) (a verified state machine) whose states are
  **stages**. Each working stage hosts one or more
  [reference agents](../concepts/reference-agent.md), and the stage ends through a
  **judge**: a [Decision](../reference/glossary.md#decision) that reads what the agent
  *did*, such as which tool it called, and picks the next stage. The plan is the actor of
  the big picture.
- **Tools and a policy.** The toolbox holds every tool the agents may call; the
  [policy](../reference/glossary.md#policy) gives each call a verdict (run it, ask a person
  first, or refuse it). They are the tool and policy
  [fulfillers](../reference/glossary.md#fulfiller) of the big picture. The plan names the
  same tools, as objects, so the runtime can check before a run starts that its toolbox
  holds every tool the plan's agents will be offered (see
  [how a harness names its tools](#how-a-harness-names-its-tools)).
- **Ports.** A [**port**](../reference/glossary.md#port) is a small abstract class for
  something the harness needs from the outside world: a knowledge base, a ticket system, a
  ledger. The harness's tools call the ports; you supply the implementations. This is what
  lets one harness run over your real systems in production and over in-memory fakes in a
  test.
- **A brief and an evaluation.** The **brief** is the data a run starts with (a customer and
  their question, say), checked against a schema. Harness code uses it to build each actor's
  [run context](../reference/glossary.md#run-context). Tools and policy receive that context.
  Harness code separately selects what to include in a model prompt. The model cannot change
  the context. The **evaluation** says what a good run looks like, checked on the run's
  recorded [trace](../reference/glossary.md#trace).
- **A launcher.** The `Launcher` wires a harness, a model, a
  [journal](../reference/glossary.md#journal), an output and a clock into one
  [Governor](../reference/glossary.md#governor), starts runs from a brief, and passes a
  person's answers in.

Two more pieces surround every harness: the **catalog**, which lists the harnesses by path
and builds one from your ports, and the **contract test suite**, which checks every harness
the same way, crashes included.

```mermaid
flowchart LR
    you(["You, or your application"])
    person(["A person who approves"])
    catalog["<b>Catalog</b><br/>builds a harness by path"]
    subgraph harness ["One harness"]
        direction TB
        plan["<b>Plan</b><br/>a workflow: stages, agents, judges"]
        tools["<b>Toolbox and policy</b>"]
        evaluation["<b>Evaluation</b>"]
    end
    ports["<b>Ports</b><br/>your systems, or fakes"]
    launcher["<b>Launcher</b>"]
    governor["<b>Governor</b> and journal"]
    you -- "your ports" --> catalog
    catalog -- "builds" --> harness
    tools -- "call" --> ports
    you -- "brief" --> launcher
    person -- "approve or deny" --> launcher
    launcher -- "wires and drives" --> governor
    governor -- "runs" --> plan
```

Read it from the left: you give the catalog your port implementations and it builds a
harness; you give the launcher a brief and it starts a run on a Governor; the Governor feeds
events to the plan, fulfils its requests with the harness's model, tools and policy, and
journals everything; when the policy asks for a person, the run waits until the answer comes
in through the launcher.

When adapting a worked example into a larger application, use
[Designing a large harness](../guides/large-harnesses.md) to choose a stable input/result
boundary. A framework `Actor` interface and a domain contract solve different parts of
that problem.

## How the domains differ

All the harnesses share those five parts. They differ in the shape of their plan (a
straight line, a loop, agents side by side, workflows inside workflows), in who answers from
outside (a person approving, a person writing text, a deadline), and in what they must undo
when something fails. Each domain page is a worked example of one such feature: the
real-world problem, the harness drawn as a diagram, then a walk through one run in the order
it happens. Pick the page that shows the feature you want to learn:

| I want to learn... | Read | Concept page |
|---|---|---|
| a workflow whose stages host agents; judges that route on what an agent did; run context; a person approving a tool call | [Customer service](service.md) | [Workflows](../concepts/workflows.md), [Run context](../concepts/run-context.md) |
| a bounded loop (a stage revisited a limited number of times); agents fanned out side by side; a counting join (a rule for when a stage of several agents is over) | [Research](research.md) | [Workflows in depth](../concepts/workflows-in-depth.md) |
| one plan shared by several technology stacks; a review panel that must agree; a small model for summaries, through a model role | [Software: feature builds](software.md) | [Workflows](../concepts/workflows.md), [A model per role](../guides/vendors.md#a-model-per-role) |
| a conversation that agrees requirements with a developer; a review loop nested inside a test loop; separate approvals for pushing and opening a pull request | [From a ticket to a pull request](ticket-to-pull-request.md) | [Conversations](../concepts/conversations.md), [Workflows in depth](../concepts/workflows-in-depth.md) |
| a stage that makes tool calls without a model; a policy scoped by trusted data | [Security](security.md) | [Errands](../concepts/errands.md), [Run context](../concepts/run-context.md) |
| an approval on its own; a quorum of reviewers | [Enterprise](enterprise.md) | [Humans and interruption](../concepts/human-in-the-loop.md), [Workflows in depth](../concepts/workflows-in-depth.md) |
| a join that takes the worst verdict and can end early | [Software delivery](sdlc.md) | [Workflows in depth](../concepts/workflows-in-depth.md) |
| a saga: undoing what was done when a later step fails | [Data](data.md) | [Errands](../concepts/errands.md) |
| a multi-turn conversation with a person, kept within a context budget; a memory per learner that later lessons recall from | [Education](education.md) | [Conversations](../concepts/conversations.md), [Context management](../concepts/context-management.md), [Memory](../concepts/memory.md) |
| deadlines; asking an outside party for content and waiting for days | [Finance](finance.md) | [Time](../concepts/time.md), [Asking a person](../concepts/asking-a-person.md) |
| a harness that improves another harness by trial and replay | [Meta](meta.md) | [Replay and evaluation](../guides/replay-and-evaluation.md) |
| a change rolled across many repositories: canary, a person's go, waves | [Software: fleet campaign](software.md#fleet-upgrade-campaign) | [Workflows](../concepts/workflows.md) |
| nested workflows; people who supply text; a veto | [Legal](legal.md) | [Workflows in depth](../concepts/workflows-in-depth.md), [Asking a person](../concepts/asking-a-person.md) |

If you read them in order, go from the simplest to the most involved:

1. [Customer service](service.md): three agent stages, one approval. Start here.
2. [Research](research.md): a loop and a fan-out.
3. [Software](software.md): one plan for several stacks; later on the page, the fleet
   campaign, which hosts those builds per repository.
4. [From a ticket to a pull request](ticket-to-pull-request.md): a conversation with the
   developer, then nested review and test loops.
5. [Security](security.md): stages without a model, and scope from the brief.
6. [Enterprise](enterprise.md): quorum and approval.
7. [Software delivery](sdlc.md): a worst-verdict join.
8. [Data](data.md): compensation.
9. [Education](education.md): a conversation, and a memory across lessons.
10. [Finance](finance.md): deadlines and outside answers.
11. [Meta](meta.md): a harness that works on harnesses.
12. [Legal](legal.md): three nested workflows and several people.

### The harnesses

Every harness, its catalog path, the actor class of its runs and the final states a run can
end in:

| Path | Page | Run actor | Ends in |
|---|---|---|---|
| `service/support_desk` | [Customer service](service.md) | `SupportRun` | `resolved`, `escalated`, `failed` |
| `software/web/django`, `software/web/node`, `software/ai/openai_python` | [Software](software.md) | `DjangoBuild`, `NodeBuild`, `OpenAIPythonBuild` | `delivered`, `rejected`, `failed` |
| `software/fleet/upgrade_campaign` | [Software](software.md#fleet-upgrade-campaign) | `Campaign` | `completed`, `halted`, `stopped` |
| `software/ticket_to_pull_request` | [From a ticket to a pull request](ticket-to-pull-request.md) | `TicketToPullRequest` | `delivered`, `rejected`, `abandoned`, `failed` |
| `security/threat_remediation` | [Security](security.md) | `RemediationRun` | `contained`, `dismissed`, `escalated`, `failed` |
| `enterprise/purchase_approval` | [Enterprise](enterprise.md) | `PurchaseRun` | `ordered`, `declined`, `failed` |
| `sdlc/release_train` | [Software delivery](sdlc.md) | `ReleaseRun` | `released`, `rolled_back`, `held`, `failed` |
| `research/deep_research` | [Research](research.md) | `ResearchRun` | `reported`, `inconclusive`, `failed` |
| `data/pipeline_backfill` | [Data](data.md) | `BackfillRun` | `published`, `rolled_back`, `aborted`, `needs_operator`, `failed` |
| `education/tutoring_session` | [Education](education.md) | `TutoringSession` | `mastered`, `practised`, `failed` |
| `finance/payment_dispute` | [Finance](finance.md) | `DisputeRun` | `won`, `lost`, `conceded`, `unresolved`, `failed` |
| `legal/contract_review` | [Legal](legal.md) | `ContractRun` | `signed`, `walked_away`, `unsigned`, `failed` |
| `meta/improver` | [Meta](meta.md) | `Improvement` | `adopted`, `declined`, `exhausted`, `failed` |

Each page shows the run's plan as a transition table (each state, the work it asks for, and
where each input leads) and a diagram, both rendered from the code with [`gvn.kernel.diagram`](../guides/diagrams-and-diffs.md). A docs test renders them
again and fails if a page no longer matches its harness.

The rest of this page goes one level down: the `Harness` interface every harness implements,
then the catalog, the launcher and the contract suite, each with its options last.

## The `Harness` interface

In code, a harness is an object that implements the `Harness` abstract base class, defined
in `gvn.runtime.harnesses` and importable from `gvn_domains.catalog` too
([Harnesses](../concepts/harnesses.md) explains it on its own). It holds configuration and
injected ports only: every run is a new
actor, and all run state lives in that actor, and so in the journal. Each method hands out
one of the parts described [above](#what-a-domain-harness-is-made-of):

| Method | Returns |
|---|---|
| `name()`, `summary()` | a path-safe name (`[a-z][a-z0-9_]*`) and one sentence saying what job it does |
| `brief()` | the schema of the brief a run is started with: a `Record` (a [schema](../reference/glossary.md#schema) of named fields) |
| `actor_class()` | the actor class of its runs: what [`Recovery`](../tutorials/durability.md) rebuilds after a crash and [`Replay`](../guides/replay-and-evaluation.md) rebuilds from a recording |
| `start(run_id, brief)` | a fresh actor named `run_id` and the event that starts it; deterministic |
| `toolbox()` | every tool any of its agents may call, built over its ports: the same tools its plan declares (see [below](#how-a-harness-names-its-tools)) |
| `policy()` | the tool policy: a [Decision](../concepts/decisions.md) over a `Consultation` (the calls of one model reply) whose outcomes are `VERDICTS` (`cleared`, `needs_approval`, `forbidden`), as in [A policy and approval](../tutorials/agent-with-approval.md) |
| `evaluation()` | an `Evaluation`: the checks a good run's trace must pass (see [Replay and evaluation](../guides/replay-and-evaluation.md)) |

Three more methods have defaults, and a harness overrides them only when it needs what they
declare. The [launcher](#what-the-launcher-wires) reads all three:

| Method | Returns | Default |
|---|---|---|
| `fulfillers()` | extra request kinds its actors make, each with the fulfiller that does that work | none |
| `external()` | extra request kinds answered from outside the process | none |
| `model_roles()` | the [model roles](../guides/vendors.md#a-model-per-role) its actors name: a tuple of distinct role names, each of which needs a model at launch | none: every model call goes to the launcher's one model |

A harness with a [memory](../concepts/memory.md) uses the first. It takes the
`gvn.harness.ports.Memory` as a port like any other (its catalog entry names it), and
`fulfillers()` returns `{"remember": MemoryFulfiller(memory, scope)}` (from
`gvn.runtime.memory`), so that what its actors' context budgets drop is handed to that
memory; a `RecallTool` or `RememberTool` over the same memory goes in its `toolbox()`. The
[tutoring session](education.md) is built this way. A harness whose actors name a model
role, such as the [feature builds](software.md), which have a small model write summaries,
lists it in `model_roles()`.

Every harness in the package fills those methods the same way: a
[workflow](../concepts/workflows.md) whose stages host
[reference agents](../concepts/reference-agent.md), judges that decide from what the agents
*did* (the `attempts`, that is the tool calls, in each agent's outcome), the brief as every
agent's [run context](../concepts/run-context.md), and a policy and tools that enforce the
same rules before any effect.

### How a harness names its tools

A tool has two names: its **short name**, `name()`, which the model sees, and its
**identity**, `identity()`: its namespace, a dot and its short name
(`gvn_domains.service.support.search_knowledge`), which gvn stores and matches on. Tools are
passed as objects, never as names ([Tools](../concepts/tools.md) explains both). A harness
refers to its tools in two places: its plan, policy, judges and evaluation name them before
any port exists, and its `toolbox()` holds the ones that run. So every harness module is
laid out the same way:

- **One module-level constant per tool**, such as `SEARCH_KNOWLEDGE = SearchKnowledge()`. A
  tool that calls a port is built here without its port: it names the tool and refuses to
  run.
- **A `TOOLS` tuple** of those constants, and the plan declares them:
  `Plan(..., tools=TOOLS)` (see [what a workflow declares](../concepts/tools.md#what-a-workflow-declares)).
  Agents are offered tuples of constants (`tools=ROUTING`), errands make
  `FixedCall("c0", NOTIFY, {...})`, the policy matches with `consultation.calls_to(OPEN_TICKET)`,
  judges read an outcome with `calls_to(...)` and `is_call_to(...)`, and the evaluation
  checks `Gated([OPEN_TICKET])`.
- **`toolbox()` builds the same classes over the harness's ports**, so each tool it holds
  has the identity of the constant that names it.

Because the plan declares its tools, the run actor answers them for `tool_identities()`, and
the Governor the launcher builds checks the harness's toolbox against them
[before the run starts](../concepts/tools.md#checked-before-the-run-starts): a toolbox
that lacks a tool, or holds a same-named tool from another package, is refused with
`Unfulfillable` before anything is journaled.

## The catalog

The catalog is how you find a harness and build it. Harnesses are described separately from
being built, so you can browse them before you have written any ports. An `Entry` names a
harness, says what it does and which ports it needs, and builds it from a `Ports` map.
`Domain`s form a tree of entries, and a `Catalog` is addressed by path, such as
`"software/web/django"`. Here is the whole catalog, printed without any ports:

```python
from gvn_domains.directory import catalog

everything = catalog()
print(everything.outline())
```

```text
data/: Keeping data pipelines right.
  pipeline_backfill: Backfills a dataset's bad partitions: diagnose, plan, snapshot, stage, swap, validate, publish with approval, or restore every swap. [needs Lineage, Warehouse]
education/: Teaching a learner.
  tutoring_session: Teaches one learner a topic in a conversation until mastery, then records a note. [needs Curriculum, Memory, Records]
enterprise/: Back-office work that people must sign off.
  purchase_approval: Takes a purchase request through policy, a review quorum and approval to an order. [needs Ledger, Notices]
finance/: Money and its disputes.
  payment_dispute: Handles a card payment dispute: evidence, contest or accept, a ruling, the books. [needs Evidence, Ledger, Scheme]
legal/: Contracts and other legal work.
  contract_review: Reviews a contract against the playbook, negotiates redlines, then signs or walks away. [needs Documents, Playbook, Signing]
meta/: Harnesses that work on harnesses.
  improver: Improves another harness: proposes a setting from its menu, trials it, adopts it. [needs Evidence, Registry, Tunable; optional Rehearsal]
research/: Finding things out and reporting them.
  deep_research: Researches a question in bounded rounds of gathering, synthesis and critique. [needs Library]
sdlc/: Getting software from merged to running.
  release_train: Takes a release from candidate to production through assessment, staging and a go/no-go. [needs Changes, Deployments]
security/: Responding to threats.
  threat_remediation: Responds to a security alert: triage, investigate, contain with approval, or escalate. [needs Containment, Oncall, Telemetry]
service/: Customer service.
  support_desk: Answers a customer from the knowledge base, or opens a ticket for a person. [needs Knowledge, Tickets]
software/: Building software features.
  ticket_to_pull_request: Takes one ticket, refined with its developer, to a reviewed and tested pull request. [needs ChangeRequests, Checkout, Tickets, Workspace]
  ai/: Features built on language models.
    openai_python: Builds a feature of a Python app that calls a model API, with evaluation cases. [needs ChangeRequests, Workspace]
  fleet/: One change across many repositories.
    upgrade_campaign: Rolls one change across many repositories: a canary, a person's go, then bounded waves. [needs ChangeRequests, Workspaces]
  web/: Web applications.
    django: Builds a feature in a Django project: plan, implement, test, review, open a pull request. [needs ChangeRequests, Workspace]
    node: Builds a feature in a Node service: plan, implement, test, review, open a pull request. [needs ChangeRequests, Workspace]
```

`directory.catalog()` builds a fresh catalog on each call; nothing is kept at module level.
`paths()` lists every entry path and `entry(path)` returns one entry. Asking an entry what it
`requires()` tells you which ports to write. An unknown path raises `UnknownHarness`, naming
the nearest prefix that does exist:

```python
from gvn_domains.catalog import UnknownHarness

print(everything.entry(path="service/support_desk").requires())
try:
    everything.entry(path="software/web/rails")
except UnknownHarness as error:
    print(error)
```

```text
(<class 'gvn_domains.service.support.Knowledge'>, <class 'gvn_domains.service.support.Tickets'>)
no harness at 'software/web/rails': the nearest prefix is 'software/web' (a domain)
```

To build a harness, give the catalog your port implementations. `Ports.of(...)` files each
instance under the port class it implements. Asking for a port gives the object filed under
exactly that class, or else the one object that is an instance of it; if two objects match,
that is a `ValueError`, and `Ports.of` refuses two objects whose port classes inherit from one
another. A missing port raises `MissingPort`, naming it, before anything is built:

```python
# not runnable: MyKnowledgeBase and MyTicketSystem are your implementations.
from gvn_domains.catalog import Ports

desk = everything.harness(
    path="service/support_desk",
    ports=Ports.of(MyKnowledgeBase(), MyTicketSystem()),
)
```

Each domain page shows this with small in-memory ports you can run.

## The Launcher

The `Launcher` (defined in `gvn.runtime.launching`, and importable from `gvn_domains.launcher` too) is how you run a harness, yours or one of these. It is the wiring
between a harness and a [Governor](../concepts/governor.md), the runtime object that drives
actors and hands their requests to [fulfillers](../reference/glossary.md#fulfiller). You
give it a harness, a model, a journal, an output and a clock; it builds the Governor, and
from then on you talk to runs by name: start one from a brief, answer it when it waits for a
person, recover it after a crash.

This is the shape of a support run with a real model and journal. The application waits for
an authenticated person's decision before calling `approve` or `deny`.

```python
# not runnable: a template using the application's approval channel.
launcher = Launcher(
    harness=desk, model=model, journal=journal, output=output, clock=clock,
    entitlement=approval_entitlement,
)
result = await launcher.start(
    run_id="case-17",
    brief={"customer": "Ada", "question": "How do I reset my password?"},
)
if result.status() == "waiting":
    request = next(item for item in result.pending() if item.kind().name() == "request_approval")
    approved, principal = await authenticated_approval(request)
    if approved:
        result = await launcher.approve(run_id="case-17", request=request, by=principal)
    else:
        result = await launcher.deny(run_id="case-17", request=request, by=principal)
```

`start` drives the run until it finishes or waits. When an answer arrives, the application
passes it to the `Launcher`, which drives the run again. The channel supplies the
authenticated `Principal` and the entitlement rule checks whether that principal can
answer the request. See [Trust](../concepts/trust.md) for both responsibilities.

| Method | Does |
|---|---|
| `start(run_id, brief)` | starts a new run and drives it until it finishes or waits |
| `approve(run_id, request, except_calls=None, by=None)` | approves the calls in a pending approval request, except any call IDs named in `except_calls`. `by` identifies the authenticated approver. |
| `deny(run_id, request, reason=None, by=None)` | denies all calls in a pending approval request. `reason` gives the reason and `by` identifies the authenticated approver. |
| `wake(run_id)` | answers every wake-up that is due and drives on: a scheduler's call, once `result.due()` has passed |
| `reply(run_id, request, event, by=None)` | answers a pending external request through `Governor.answer`. `by` identifies the authenticated answerer. |
| `recover(run_id)` | rebuilds a run from the journal after a crash, and drives on |
| `interrupt(run_id)`, `resume(run_id)` | interrupts a live run; resumes a suspended one |
| `trace(run_id)`, `grade(run_id)` | the recorded [trace](../guides/replay-and-evaluation.md) of a run, and the harness's evaluation of it |
| `actor(run_id)` | the live actor, for inspection |
| `forget(run_id)` | releases a run from the launcher's memory; the journal keeps everything |

### What the launcher wires

Every request an actor makes has a **kind**, and the Governor needs one fulfiller per kind
(see [The Governor](../concepts/governor.md)). The launcher's Governor fulfils
`invoke_model` with the model, `invoke_tools` with the harness's toolbox and
`consult_policy` with its policy. `request_approval` and `request_input` are **external**:
answered from outside, by a person or another system, through `approve`, `deny` or `reply`.
A harness that needs more declares it: `Harness.fulfillers()` returns extra request kinds
and their fulfillers (`remember`, for a harness with a memory), and `Harness.external()`
extra kinds answered from outside (both empty by default). A kind that is claimed twice is a
`ValueError` when the launcher is built.

Model calls can go to more than one model. An actor that names a
[model role](../guides/vendors.md#a-model-per-role) has its calls served by that role's
model, and every other call goes to `model`. `Launcher(..., model_roles=None)` takes the
mapping of role name to `Model`, and the launcher checks it against `Harness.model_roles()`
when it is built: a harness that names a role the mapping lacks is refused with a
`ValueError` naming every missing role, before any run starts. So a missing model is found at
launch, not halfway through a run when the first summary is due. A role in the mapping that
the harness does not name is not used. `read_clock` and `wake_at` are not among the launcher's own kinds: the Governor
handles them itself (unless a harness names them), sleeping on a wake-up within
`sleep_within` seconds (default 60) and otherwise letting the run park.

### Answering per call, and in turn

An approval request may ask about several calls of one reply (see
[several calls in one reply](../concepts/human-in-the-loop.md#several-calls-in-one-reply)).
`approve` with `except_calls` answers them call by call: the calls it names are denied and the
rest approved, and a call id the request did not ask about is a `ValueError`, with nothing
journaled:

```python
# not runnable: the shape of a per-call answer.
request = result.pending()[0]
asked = [call["call_id"] for call in request.payload()["calls"]]  # e.g. ['c1', 'c2']
result = await launcher.approve(
    run_id="case-17", request=request, except_calls={"c2": "not that customer"}, by=principal
)
```

A call that arrives while another call is driving the same run (an answer, a wake, a resume)
waits its turn, first come first served, and is checked when its turn comes: an answer made
stale by the call ahead of it, for instance by a deadline that passed, is refused then, with
nothing journaled.

### Runs held in a process, several processes, and other options

A launcher keeps the actors it started or recovered, by run name, until you `forget` them; a
long-lived launcher should forget each run once it has finished. A new launcher, including
one in another process, can `recover(run_id)` with the same journal and a harness that
matches the recorded actor and its wiring.

When several processes share a journal, give each launcher the lease store and a `holder`
name (`leases=..., holder=...`). A [**lease**](../reference/glossary.md#lease) is the
time-limited right to drive one run; with leases, one process at a time drives each run,
and a `Worker` wakes parked runs when they are due
([Running as a service](../guides/running-as-a-service.md) teaches both). `forms=` passes
your [stored-form registry](../reference/stability.md) (how saved actors are read back as
your code changes) to its Governor, Recovery and Replay; by default it is
`Forms(tools=harness.toolbox())`, so a record stored before tools had identities is read as
naming the harness's tools. The Governor it builds uses
growing [snapshot](../reference/glossary.md#snapshot) spacing (`snapshot_growth=0.5`), so
saving a long run stays linear in its length.

## The contract every harness passes

A harness promises more than "it runs once": a run must reach the right end, pass its own
evaluation, replay the same way, and survive a crash at any point without doing an effect
twice. `HarnessContract` (in `gvn_domains.testing`) is the test suite that checks all of
that. Every harness in the package passes it, and you can run it over your own. It builds on
[Testing your harness](../concepts/testing.md), whose
[crash matrix](../concepts/testing.md#a-crash-matrix) and
[contract suites](../concepts/testing.md#contract-suites) it packages for harnesses.

You subclass it in a pytest module, build the harness over fake ports, and list
**scenarios**. A scenario is one scripted run: a brief, a function deciding every model
reply, the answers a person gives, the final state the run must reach, and whether the
harness's own evaluation should pass on it. A scenario can show a bad run being caught
(`passes=False`).

```python
# not runnable: a pytest module; pytest collects the test methods.
from gvn_domains.catalog import Harness
from gvn_domains.testing import HarnessContract, Scenario


class TestSupportDesk(HarnessContract):
    def make_world(self) -> object:
        return World()  # holds the fake ports' state

    def make_harness(self, world: object) -> Harness:
        return SupportDesk(knowledge=world.knowledge(), tickets=world.tickets())

    def scenarios(self) -> tuple[Scenario, ...]:
        return (
            Scenario(
                name="answers from the knowledge base",
                brief={...},
                model=answering,
                ends="resolved",
            ),
            ...,
        )
```

A scenario's `model` is a function from an `Exchange` (what the agent sends the model: its
instructions and messages) to a `Reply`, the same kind of function
[`FunctionModel(respond=...)`](../tutorials/durability.md) takes. The **world** is your own
object holding the fake ports' state, so the checks below can look at what the run did.

### What it checks

For the harness and each scenario, it checks:

- the metadata is well formed, `start` is deterministic and refuses a brief its schema does
  not admit, the actor's definition is verified, the toolbox holds every tool the
  started actor declares and every tool a run asks for, and every model role a run asks for is one `Harness.model_roles()` names;
- each scenario runs to its final state through a Launcher, and the evaluation passes or
  fails on its trace as the scenario says;
- the recorded trace has no rejected events, and replaying it reproduces the final state;
- the live actor round-trips through JSON text at every point where it waits;
- **the crash matrix**: the run is killed at a journal append (the moment one event record
  is written), recovered with a fresh Launcher over the same world, and must end in the same
  state with the same outcome (for a parked run: the same state and the same pending
  requests).

Work in flight at a crash runs again, so a tool may run twice. Making that harmless is the
job of the tool and its port, by the call's
[idempotency key](../reference/glossary.md#idempotency-key) (a string that is the same each
time the same call is delivered, see [Run context](../concepts/run-context.md)); a world
that records effects lets a harness's own tests check it.

### Answers from people

A scenario's `approvals` is a sequence consumed in order, one item each time the run waits
for approval: `True` approves every call asked about, `False` denies them all. To answer per
call, an item may instead be an `ApproveExcept`, naming the call ids (as the scripted model
made them) that the person denies; the others are approved:

```python
from gvn_domains.testing import ApproveExcept

partly = ApproveExcept("c2", reason="not that customer")
print(partly.event().name(), partly.event().payload())
# approved {'denied': [{'call_id': 'c2', 'reason': 'not that customer'}]}
```

The call ids are positional (`ApproveExcept("c1", "c2", reason=...)`) because there may be
several.

A scenario's `replies` is a function `request -> Event | None` that answers every other
external request (a `request_input`, a harness's own kind) through `Launcher.reply`, also
after recovery. Returning `None` leaves the run **parked** (waiting, at no cost, for an
answer that has not come): `ends` then names the state it waits in, and the scenario shows a
run genuinely waiting on a person rather than a scripted fulfiller answering for one.

### Model roles and memory

A harness that names model roles needs a model for each in every Launcher the contract
builds. `Scenario(..., model_roles=None)` takes a mapping of role name to a function
`exchange -> Reply`, like `model`, scripting the model that serves that role; every Launcher
of the scenario gets it, the crashed run's and the recovering one's alike. A scenario that
leaves out a role the harness names fails, because the Launcher refuses it.

A harness with a memory takes its `Memory` as a port, so the world holds it (a
`gvn.testing.fakes.ListMemory`, say): a scenario's `world` function can put entries in it
first, and `check_world` can read what the run kept.

### How many crashes

By default the crash matrix uses a deterministic **sample** of appends (the first three,
the last three and evenly spaced ones between, at most twelve, alternating between crashing
before and after the record is written), which keeps the suite fast. Set
`exhaustive = True` on the class, or the environment variable `GVN_EXHAUSTIVE=1`, to crash at
every append in both modes. In a clone of gvn's repository, this runs the package's own
harnesses that way:

```bash
GVN_EXHAUSTIVE=1 uv run pytest packages/gvn-domains/tests -q
```

A scenario's `crash_at`, a function from the clean run's journal records to `(at, after)`
points, adds **forced crash points** to the sample: the one crash that would make an effect
run twice, say, found by reading the records.

### Timed scenarios

Time moves only when the contract moves it, on a `ManualClock` (the test clock you move by
hand, from the [tutorials](../tutorials/deadline.md)). A scenario's `horizon` (in seconds)
lets the contract, whenever the run waits and nobody answers, move the clock exactly to
`result.due()` and call `Launcher.wake`, deadline by deadline, but never beyond the horizon;
a deadline beyond it leaves the run parked, and `ends` names the state it is parked in. A
call stuck on slow work is moved forward to the clock's earliest sleeper the same way.
Ending `approvals` with `UNANSWERED` gives an approver who never answers, so a deadline can
win over a person; a `replies` function returning `None` does the same for other requests.
`make_clock(world)` returns the clock every Launcher over a world uses, so fakes that read
time share it. With a horizon, the crash matrix also checks that each wake-up keeps one time
across the whole journal, that a recovered run asks for exactly the clean run's wake-ups
(neither lost nor moved), and that every `woke` is journaled at or after its time.

### Hooks into the world

Three hooks let a harness assert what its fake world holds:

| Hook | Called |
|---|---|
| `check_world(world, scenario, result)` | after every clean run and every crashed-and-recovered run, with the final Result ("exactly one ticket") |
| `check_crashes(scenario, worlds)` | once per scenario after its crash matrix, with the world of every crashed run, for assertions across crashes |
| `bind(world, journal)` | each time a Launcher is built over a world, so a fake can check what was durably recorded before an effect |

## What the harnesses use from gvn

The harnesses are built from the framework's own parts, and each domain page says which it
uses: the model-free stage ([`Errand`](../concepts/errands.md)), asking a person
for content ([`Inquiry`](../concepts/asking-a-person.md)) or a yes or no
([`Approval`](../concepts/human-in-the-loop.md)), [time](../concepts/time.md) (timers, stage
deadlines, a scheduler's `wake`), multi-turn [conversations](../concepts/conversations.md),
counting and veto joins, and evaluation checks such as `Gated(when=...)`, `Parks`, `By` and
`ApprovedFirst` (see [Replay and evaluation](../guides/replay-and-evaluation.md)). The data
harness adds a fan-out over items with retries
([`ForEach`](../guides/items-and-retries.md)) and compensation the verifier proves
([`Compensate`](../guides/compensation.md)); a stage of children of different kinds is
[`Parallel`](../guides/mixed-stages.md).

## Architecture

The package has its own import contracts, run with gvn's (see
[Architecture](../reference/architecture.md) for what an import contract is):

- the framework never imports `gvn_domains`;
- inside the package: `directory` over `meta` over the domain modules over `launcher` over
  `catalog`, and the domain modules (software, security, enterprise, sdlc, research,
  service, data, legal, education, finance) never import each other;
- production code imports no vendor SDK and no test kit;
- in the software domain, `fleet` sits over the `web` and `ai` subdomains, which share the
  `build` plan and the `ports` and never import each other.

## Scale

Besides the framework's [scale benchmark](../reference/scale.md) of 10,000 toy agents, a
second suite drives the real harnesses. Its
measured run mixes 2,000 runs of nine of the harnesses, started together on one Governor
(about 1,000 events per second, all 2,000 runs holding a model call at once), parks and
recovers 1,000 runs waiting for approval (about 75 KB of heap per parked run, world and
journal included), and costs each harness alone (at most 26 ms of processor time per run). The
suite is part of gvn's repository, where `packages/gvn-domains/tests/scale/README.md` holds
the full numbers. Run it from the root of a clone with:

```bash
uv run pytest packages/gvn-domains/tests/scale -m scale -n 0 -p no:randomly -s
```

## Recap

- `gvn-domains` holds fifteen harnesses that use gvn only through its public interface.
- A harness is a plan (a workflow whose stages host agents and end through judges), tools
  and a policy, ports, a brief and an evaluation; the catalog builds it from your ports, and
  the `Launcher` runs it on one Governor.
- The domains differ in the shape of their plan, in who answers from outside, and in what
  they undo; the table [above](#how-the-domains-differ) says which page shows what.
- `HarnessContract` checks every harness the same way, crash matrix included.

**Next:** [Customer service](service.md), the smallest harness and the model for the rest.
