# Harnesses

**What you will learn:** what gvn means by a harness as an object: one packaged job, with the
actor that does it, what a run is started with, its tools, its policy and what a good run looks
like. You will see how a project offers harnesses by name, and how a `Launcher` runs one.

**Read first:** [The Governor](governor.md), [The reference agent](reference-agent.md) and
[Workflows](workflows.md). **Time:** about 15 minutes.

## Where this sits

Every page so far built actors and wired a Governor by hand: the model fulfiller, the tool
fulfiller, the policy, the requests a person answers. That wiring belongs to the job, not to
each run. A **harness** packages it once:

```mermaid
flowchart LR
    subgraph harness ["Harness: one packaged job"]
        direction TB
        actor["actor_class()<br/>the entry actor"]
        start["brief() and start()<br/>what a run is started with"]
        tools["toolbox() and policy()"]
        evaluation["evaluation()<br/>what a good run looks like"]
    end
    project["Project<br/>offers harnesses by name"]
    launcher["Launcher<br/>wires a Governor"]
    governor["Governor"]
    journal[("Journal")]
    workbench["Workbench, evals<br/>read it"]
    project --> harness
    harness --> launcher --> governor --> journal
    harness --> workbench
```

A harness holds configuration and the ports its tools need, nothing more. Every run is a new
actor, and all run state lives in that actor and so in the journal. One harness object can
start any number of runs, in any number of processes.

The interface is `Harness`, defined in `gvn.runtime.harnesses`. Three things read it: the
[`Launcher`](#running-a-harness) wires a Governor from it, an [eval](../evals/index.md) runs
versions of it, and the [Workbench](../workbench/index.md) draws it from its entry actor down.

## What a harness says

| Method | Returns |
|---|---|
| `name()` | a name of lowercase letters, digits and underscores starting with a letter (`[a-z][a-z0-9_]*`), unique among its siblings |
| `summary()` | one sentence: what job it does |
| `brief()` | the [schema](../reference/glossary.md#schema) of the [brief](../reference/glossary.md#brief), what a run is started with: a `Record` of named fields |
| `actor_class()` | the actor class of its runs, the **entry actor**: what [recovery](../tutorials/durability.md) and [replay](../guides/replay-and-evaluation.md) rebuild |
| `start(run_id, brief)` | a fresh actor named `run_id` and the event that starts it; deterministic |
| `toolbox()` | every [tool](tools.md) any of its actors may call |
| `policy()` | a [Decision](decisions.md) over a `Consultation` whose outcomes are `VERDICTS`: which calls run, which need a person, which are forbidden |
| `evaluation()` | an `Evaluation`: the checks a good run's trace passes ([Replay and evaluation](../guides/replay-and-evaluation.md#step-6-evaluations-and-scorecards)) |

Three more have defaults, for a harness that needs what they declare:

| Method | Returns | Default |
|---|---|---|
| `fulfillers()` | extra request kinds its actors make, each with its fulfiller (`remember` for a harness with a [memory](memory.md)) | none |
| `external()` | extra request kinds answered from outside the process, beyond `request_approval` and `request_input` | none |
| `model_roles()` | the [model roles](../guides/vendors.md#a-model-per-role) its actors name; each needs a model at launch | none |

## A harness in code

A harness that answers one question with one agent and no tools:

```python
import asyncio
import typing

from gvn.harness.actor import Actor
from gvn.harness.agent import VERDICTS, Agent
from gvn.harness.events import Event
from gvn.harness.tools import Toolbox
from gvn.kernel.decision import Decision
from gvn.kernel.schema import Record, Text
from gvn.kernel.symbols import Alphabet, Symbol
from gvn.runtime.evaluation import Evaluation, Finishes
from gvn.runtime.harnesses import Harness

INSTRUCTIONS = "Answer in one sentence."


class NothingRuns(Decision):
    """The policy of a harness with no tools: any call is forbidden."""

    def outcomes(self) -> Alphabet:
        return VERDICTS

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


class Answering(Harness):
    """Answers one question with one agent and no tools."""

    def name(self) -> str:
        return "answering"

    def summary(self) -> str:
        return "Answers one question in one sentence."

    def brief(self) -> Record:
        return Record({"question": Text()})

    def actor_class(self) -> type[Actor]:
        return Agent

    def start(self, run_id: str, brief: dict[str, typing.Any]) -> tuple[Actor, Event]:
        self.brief().require(brief)
        agent = Agent(name=run_id, instructions=INSTRUCTIONS, turns=2)
        return agent, Event("started", payload={"prompt": brief["question"]})

    def toolbox(self) -> Toolbox:
        return Toolbox()

    def policy(self) -> Decision:
        return NothingRuns()

    def evaluation(self) -> Evaluation:
        return Evaluation("answering", [Finishes("completed")])
```

The entry actor here is gvn's reference `Agent`. In a larger harness it is usually a
[workflow](workflows.md) whose stages host agents, errands and questions to people; the
release review example's `ReleaseReviewHarness` starts a `ReleaseReview` workflow, and takes the
CI port its one tool reads through its constructor, so the same harness runs over a fixed CI
server in development and the real one in production.

## Running a harness

`Launcher`, from `gvn.runtime.launching`, is the wiring between a harness and a
[Governor](governor.md). Give it a harness, a model, a journal, an output and a clock; it builds
the Governor with the harness's toolbox and policy, and from then on you talk to runs by name:

```python
from gvn.harness.messages import Message
from gvn.harness.ports import Reply
from gvn.runtime.launching import Launcher
from gvn.testing.fakes import ManualClock, MemoryJournal, RecordingOutput, ScriptedModel

journal = MemoryJournal()
launcher = Launcher(
    harness=Answering(),
    model=ScriptedModel(script=[Reply(message=Message.assistant(text="A Moore machine names its outputs per state."))]),
    journal=journal,
    output=RecordingOutput(),
    clock=ManualClock(),
)
result = asyncio.run(launcher.start("q-1", {"question": "What is a Moore machine?"}))
print(result.status(), result.outcome().payload()["text"])
print(asyncio.run(launcher.grade("q-1")))
```

```text
finished A Moore machine names its outputs per state.
Grade('q-1', passed)
```

What the Launcher wires:

- `invoke_model` goes to the model (and a call naming a model role to that role's model, from
  `model_roles=`; every role the harness names must be given, or the Launcher is refused before
  any run starts);
- `invoke_tools` to the harness's toolbox, `consult_policy` to its policy;
- `request_approval` and `request_input` are external: a person answers, through `approve`,
  `deny` or `reply`;
- the harness's own `fulfillers()` and `external()` on top.

`start`, `reply`, `approve`, `deny`, `wake`, `resume`, `recover`, `trace` and `grade` take the
run's id. With leases, every call takes the run's lease first, so several processes can share one
journal. [Domains](../domains/index.md#the-launcher) covers the Launcher's options in full.

## How a project offers harnesses

A project is the object the `gvn` command line and the Workbench load
([Writing the project](../evals/project.md)). It offers its harnesses by name:

```python {.no-run}
from gvn.console.project import Project

project = Project(
    root,
    versions={"baseline": ReleaseVersion("baseline", ReleaseReview)},
    environments={"fixed_ci": FixedCiWorlds()},
    journal=journal,
    results=results,
    model=model,
    clock=clock,
    harnesses=[ReleaseReviewHarness(FixedCi(CI_BUILDS))],
)
print(project.harnesses())              # ('release_review',)
harness = project.harness("release_review")
```

`Project.harnesses()` gives the names, sorted; `Project.harness(name)` the harness, or
`NotOffered` naming what the project does offer. Two harnesses of one name are refused.
`Project.model()`, `Project.clock()` and `Project.model_role(name)` give what the project was
built with, so a tool that drives one of its harnesses (the Workbench answering a run, for
example) uses the project's own wiring.

A harness and a version are different things. A **version** (`Subject`) is one variant the evals
run by name, such as `baseline` or `candidate`; a **harness** is the packaged job, with its tools
and policy. The release review offers one harness and two versions of its workflow.

## Recap

- A harness is one packaged job: entry actor, brief and start, toolbox, policy, evaluation, and
  optionally extra fulfillers, external kinds and model roles.
- `Harness` is defined in `gvn.runtime.harnesses`; `Launcher` in `gvn.runtime.launching` wires a
  Governor from one and runs its runs by name.
- A `Project` offers harnesses by name (`harnesses=`), which is how the Workbench finds them.

**Next:** [Testing your harness](testing.md).
