# Meta: the improver

**What you will learn:** how a [harness](../reference/glossary.md#harness) improves
another harness: it reads the target's recorded runs, proposes one change from the target's own finite menu, trials it on the
recorded history, and adopts it once a person approves. You will make a small target
improvable, build the improver over it, ask its policy what it may do, and run it once.

**Read first:** [Domains](index.md), for what every harness here is made of;
[Finance](finance.md), the previous example. On concepts:
[Errands](../concepts/errands.md), [Workflows](../concepts/workflows.md),
[loops](../concepts/workflows-in-depth.md#loops) and
[Run context](../concepts/run-context.md). The guide
[Self-improvement](../guides/self-improvement.md) explains the idea, what a trial can prove
and the demonstration; this page is the reference for the harness itself.

**Time:** about 20 minutes.

`meta/improver` (module `gvn_domains.meta.improver`) improves one other harness, the
**target**, by choosing a change from a menu its authors wrote, trying it on recorded runs,
and adopting it once a person approves.

## Where this harness fits

Every harness in `gvn-domains` is made of the same parts (see
[What a domain harness is made of](index.md#what-a-domain-harness-is-made-of)): a **plan**,
which is a [workflow](../reference/glossary.md#workflow) whose states are stages; tools and
a [policy](../reference/glossary.md#policy) that check every call before it has an effect;
[**ports**](../reference/glossary.md#port), small abstract classes for the outside world
that you implement; a **brief**, the data a run starts with; and the
[`Launcher`](index.md#the-launcher), which runs the harness on a
[Governor](../reference/glossary.md#governor). For the improver, the outside world is
another harness:

```mermaid
flowchart LR
    brief(["brief: target and goal"])
    approver(["a person who approves the adoption"])
    subgraph harness ["improver"]
        plan["<b>Improvement</b> plan<br/>observe · propose · trial · adopt"]
        policy["policy and tools<br/>check every call"]
        plan -- "tool calls" --> policy
    end
    target[("the target, as a port<br/>Tunable: settings · menu")]
    others[("your ports<br/>Evidence · Registry · Rehearsal")]
    launcher["<b>Launcher</b>"]
    brief --> launcher
    launcher -- "drives" --> plan
    policy -- "reads, trials" --> target
    policy -- "recorded runs, adoption" --> others
    launcher -- "asks" --> approver
    approver -- "approve or deny" --> launcher
```

What sets this harness apart: its subject is another harness, handed in like a port, and
the only thing it can change is a setting the target offers.

## The problem

A harness in production fails on some runs, and someone wants it better. Letting a model
rewrite the harness's code is unsafe and unreviewable. The improver instead lets a model
choose only from a menu of settings the target's authors wrote, checks the choice against
what already happened, and changes nothing until a person approves.

A run starts with the brief `{"target": str, "goal": str}`. `start` refuses a brief for a
target other than the one the improver was built for.

## The plan

A run is an `Improvement` [workflow](../concepts/workflows.md):

- `observing`: grade the target's recorded runs and find the failures;
- `proposing`: an agent, the only part that uses a model, picks one item from the menu;
- `trialling`: replay the recorded runs under the proposed settings and compare; back to
  `proposing` when the change is not better, a bounded number of times;
- `requesting_adoption`: record the change, once a person approves;
- `adopted`, `declined`, `exhausted` or `failed`: the ends.

Here is the plan as gvn draws it from the code (a docs test checks that it still matches).
Each box is a state, `emits` names the work it asks for, and each arrow is labelled with the
input that moves the run along it; `otherwise: stay` means any input not drawn leaves the
run where it is:

```mermaid
stateDiagram-v2
    adopted : emits adopted
    declined : emits declined
    exhausted : emits exhausted
    failed : emits failed
    idle : emits idle
    observing : emits observe
    proposing : emits propose
    requesting_adoption : emits request_adoption
    trialling : emits trial
    [*] --> idle
    idle --> observing : started
    observing --> proposing : has_failures
    observing --> exhausted : nothing_failing
    observing --> failed : observe_failed
    proposing --> exhausted : no_proposal
    proposing --> trialling : proposed
    proposing --> failed : proposer_failed
    requesting_adoption --> failed : not_recorded
    requesting_adoption --> adopted : recorded
    requesting_adoption --> declined : turned_down
    trialling --> requesting_adoption : better
    trialling --> proposing : no_better
    trialling --> exhausted : out_of_rounds
    trialling --> failed : trial_failed
    trialling --> proposing : worse
    adopted --> [*]
    declined --> [*]
    exhausted --> [*]
    failed --> [*]
    note right of idle
        otherwise: stay
    end note
```

In the table, an **errand** is a small actor that makes one fixed tool call with no model
([Errands](../concepts/errands.md)); a **judge** is a
[Decision](../reference/glossary.md#decision) that reads what a stage's child did and picks
the stage's result; and `memo.visits("trialling")` counts the run's visits to `trialling`,
read from the workflow's Memo, its record of every finished stage visit.

| Stage | Who | How it ends |
|---|---|---|
| `observing` | an errand calling `observe` | `has_failures`, `nothing_failing` (the run is `exhausted`: searching honestly and finding nothing is a good run), or `observe_failed` |
| `proposing` | an agent, the only part that uses a model: `list_runs`, `show_failures`, `show_machine`, `show_settings`, `show_menu`, `propose` | `proposed`, `no_proposal`, or `proposer_failed` |
| `trialling` | an errand calling `trial` | the `Verdict` judge: `better`, `no_better` or `worse`; `out_of_rounds` once `memo.visits("trialling")` reaches `ROUNDS` (3); `trial_failed` |
| `requesting_adoption` | an errand calling `adopt`, which needs a person | `recorded`, `turned_down` (the run ends `declined`), or `not_recorded` |

Observing, trialling and adopting are deterministic work that must not depend on a model, so
those stages host the framework's [`Errand`](../concepts/errands.md): one tool call fixed by
code, vetted by the policy with the errand's run context, approved by a person when the
policy says so, and visible to the evaluation's checks like any agent's call.

The same plan as a table, also rendered from the code: `>` marks the initial state, `*` the
final states, and each row lists the state's output and its transitions.

```text
   state                output            transitions
*  adopted              adopted           -
*  declined             declined          -
*  exhausted            exhausted         -
*  failed               failed            -
>  idle                 idle              started -> observing
   observing            observe           has_failures -> proposing, nothing_failing -> exhausted, observe_failed -> failed
   proposing            propose           no_proposal -> exhausted, proposed -> trialling, proposer_failed -> failed
   requesting_adoption  request_adoption  not_recorded -> failed, recorded -> adopted, turned_down -> declined
   trialling            trial             better -> requesting_adoption, no_better -> proposing, out_of_rounds -> exhausted, trial_failed -> failed, worse -> proposing
otherwise: stay
```

## Walking through a run

Each block below runs, in order, in the docs tests.

### 1. Making a target improvable

A target makes itself improvable by implementing the `Tunable` port: its name, its current
settings, a **menu** of named adjustments, how to build its actor under given settings, and
how to grade a run. Here the target is a single [agent](../concepts/reference-agent.md)
whose only setting is its turn budget (`turns`, how many model turns the agent may take).
Its evaluation, the statement of what a good run of it looks like, has one check:
`Finishes("completed")`, the run ends in `completed`
([Replay and evaluation](../guides/replay-and-evaluation.md#step-6-evaluations-and-scorecards)):

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

from gvn.harness.actor import Actor
from gvn.harness.agent import Agent
from gvn.runtime.evaluation import Evaluation, Finishes
from gvn_domains.meta.improver import Adjustment, Tunable


class Helper(Tunable):
    def name(self) -> str:
        return "helper"

    def settings(self) -> dict[str, typing.Any]:
        return {"turns": 3}

    def menu(self) -> tuple[Adjustment, ...]:
        return (
            Adjustment(name="budget_2", description="Allow two model turns, to save cost.", settings={"turns": 2}),
            Adjustment(name="budget_5", description="Allow five model turns.", settings={"turns": 5}),
        )

    def build(self, settings: dict[str, typing.Any]) -> Callable[[str], Actor]:
        return lambda run: Agent(name=run, instructions="Answer briefly.", turns=settings["turns"])

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

    def evaluation(self) -> Evaluation:
        return Evaluation(name="helper", checks=[Finishes("completed")])
```

The menu is the whole space of change: the improver never writes code.

### 2. The other ports

Besides the target, the improver needs recorded runs to learn from (`Evidence`), a place to
record what it adopts (`Registry`) and, optionally, a way to try settings on new runs
(`Rehearsal`). `adopt` takes a `key`, an
[idempotency key](../reference/glossary.md#idempotency-key): one adoption per key, so a
repeat changes nothing.

| Port | Methods |
|---|---|
| `Tunable` (the target, handed in like a port) | `name()`, `settings()`, `menu()`, `build(settings)`, `actor_class()`, `evaluation()` |
| `Evidence` | `runs(target)`, `journal()` (only read), `brief(target, run_id)` |
| `Registry` | `adopt(target, settings, key, expected)`: atomically, a version id; one adoption per key; raises `Moved` if the target's current settings are no longer `expected`. `current(target)` |
| `Rehearsal` (optional) | `rehearse(target, settings, run_id, brief)`: the trace of a new run under the settings |

Here the evidence has no recorded runs yet, and the registry accepts any adoption. The
catalog builds the harness by its path from the ports (see
[The catalog](index.md#the-catalog)):

```python
from gvn.harness.ports import Journal
from gvn.testing.fakes import MemoryJournal
from gvn_domains.catalog import Ports
from gvn_domains.directory import catalog
from gvn_domains.meta.improver import Evidence, Registry


class Recorded(Evidence):
    def __init__(self, journal: Journal) -> None:
        self._journal = journal

    async def runs(self, target: str) -> tuple[str, ...]:
        return ()

    def journal(self) -> Journal:
        return self._journal

    async def brief(self, target: str, run_id: str) -> dict[str, typing.Any]:
        return {}


class Settings(Registry):
    async def adopt(
        self, target: str, settings: dict[str, typing.Any], key: str, expected: dict[str, typing.Any]
    ) -> str:
        return "v1"

    async def current(self, target: str) -> dict[str, typing.Any] | None:
        return None


evidence = Recorded(journal=MemoryJournal())
improver = catalog().harness(
    path="meta/improver", ports=Ports.of(Helper(), evidence, Settings())
)
for identity in improver.toolbox().identities():
    print(identity)
```

```text
gvn_domains.meta.improver.adopt
gvn_domains.meta.improver.list_runs
gvn_domains.meta.improver.observe
gvn_domains.meta.improver.propose
gvn_domains.meta.improver.show_failures
gvn_domains.meta.improver.show_machine
gvn_domains.meta.improver.show_menu
gvn_domains.meta.improver.show_settings
gvn_domains.meta.improver.trial
```

The toolbox lists its tools by
[identity](../concepts/tools.md#two-names-the-short-name-and-the-identity): the module that
defines the tool, a dot and the short name the model sees. The module also names each tool
with a constant (`PROPOSER_TOOLS` for the proposer's six, then `OBSERVE`, `TRIAL` and
`ADOPT`, together `TOOLS`); the plan declares them, so the Governor checks this toolbox
against them before the run starts, and the errands, the policy and the evaluation refer to
the tools through them (see [how a harness names its tools](index.md#how-a-harness-names-its-tools)).

### 3. What the model may do: the policy

The proposer's tools and `observe` and `trial` only read; `adopt` writes to the registry.
The policy gives every call one of three verdicts: `cleared` (it runs), `needs_approval` (a
person is asked first) or `forbidden` (it never runs). It clears everything except `adopt`, which needs a person's approval; anything else
is forbidden. Each call of a reply gets [its own verdict](../concepts/reference-agent.md#one-verdict-per-call). The run's
[context](../concepts/run-context.md) names the target, so a call for another target is
forbidden before it runs. A `Consultation` is the question the policy answers: the calls,
the identity of each call's tool, the `origin` (the actor asking) and the context:

```python
from gvn.harness.messages import ToolCall
from gvn.harness.tools import Consultation
from gvn_domains.meta.improver import ADOPT

ours = {"target": "helper", "goal": "Fewer failures.", "run": "tune", "settings": {"turns": 3}}
other = {**ours, "target": "chores"}
adopt = ToolCall(
    call_id="c1", name=ADOPT.name(), arguments={"adjustment": "budget_5", "applied": {"turns": 5}}
)


def verdict(call: ToolCall, context: dict[str, typing.Any]) -> str:
    consultation = Consultation(
        calls=[call], identities=[ADOPT.identity()], origin="tune/requesting_adoption.1",
        context=context,
    )
    return improver.policy().decide(consultation).name()


print(verdict(call=adopt, context=ours), verdict(call=adopt, context=other))
```

```text
needs_approval forbidden
```

### 4. A run: observing first

Start a run. The [`Launcher`](index.md#the-launcher) takes the harness and four test fakes
from `gvn.testing.fakes` ([Testing your harness](../concepts/testing.md)): `FunctionModel`
answers model calls with a function of yours, `MemoryJournal` keeps the journal in memory,
`RecordingOutput` keeps what would be shown, and `ManualClock` moves only when moved.
`observing` is an errand: no model is involved, so this example's model refuses to be called
at all. With no recorded runs there is nothing failing, and the run
ends `exhausted`, which the evaluation counts as a good run (`grade` checks a finished run
against the harness's evaluation):

```python
import asyncio

from gvn.harness.ports import Exchange, Reply
from gvn.testing.fakes import FunctionModel, ManualClock, RecordingOutput
from gvn_domains.launcher import Launcher


def no_model(exchange: Exchange) -> Reply:
    raise AssertionError("observing needs no model")


launcher = Launcher(
    harness=improver,
    model=FunctionModel(respond=no_model),
    journal=MemoryJournal(),
    output=RecordingOutput(),
    clock=ManualClock(),
)
result = asyncio.run(launcher.start(run_id="tune", brief={"target": "helper", "goal": "Fewer failures."}))
print(result.status(), result.outcome().state())
print(result.outcome().payload()["input"])
print(asyncio.run(launcher.grade(run_id="tune")).passed())
```

```text
finished State('exhausted')
{'target': 'helper', 'goal': 'Fewer failures.', 'run': 'tune', 'settings': {'turns': 3}}
True
```

The workflow's input, which is every child's run context, is the brief plus the run's name
and the target's settings when the run started.

### 5. The rest of a run, when there are failures

When `observe` finds failing runs, the run goes on as the plan shows:

1. **Proposing.** The proposer agent may look at the runs, the failures, the target's
   machine, its settings and its menu, and then calls `propose` with one menu item.
   `propose` refuses a name that is not on the menu, listing the menu, and the proposer may
   choose again.
2. **Trialling.** The `trial` errand replays the recorded runs under the proposed settings
   (and, when a `Rehearsal` port is given, runs live where history is silent). The
   `Verdict` judge ends the stage `better`, `no_better` or `worse`. `proposing` and
   `trialling` form a real [loop](../concepts/workflows-in-depth.md#loops): every earlier trial of the run is read back with
   `memo.history("trialling")` and shown to the proposer, and after `ROUNDS` (3) visits the
   run ends `exhausted`.
3. **Requesting adoption.** The `adopt` errand needs a person's approval, which shows the
   settings and the evidence. Approved, the registry records the change and the run ends
   `adopted`; declined, it ends `declined`.

`interrupted` and `resumed` (a person pausing and continuing the run, see
[Humans and interruption](../concepts/human-in-the-loop.md)) are passed on to the active
child. The evaluation: a run finishes `adopted` or `exhausted`, nothing is rejected, no
`adopt` succeeds without a person's approval (`Gated([ADOPT])`, a check on the recorded
run, see [checking a safety rule](../concepts/testing.md#checking-a-safety-rule-on-recorded-runs)),
and it takes at most 64 events. `declined` and `failed` are flagged for a person to look at.

A full run with failures needs a target with recorded runs and a scripted proposer; the
package's demonstration, `packages/gvn-domains/tests/test_dom_meta_demo.py`, does that and
is walked through on the [Self-improvement](../guides/self-improvement.md) page.

## What is enforced before any effect

- **Only the menu.** `propose` refuses a name that is not on the target's menu, listing the
  menu, and the proposer may choose again. The improver never writes code.
- **Only this target, as it was observed.** The run's [context](../concepts/run-context.md)
  is the brief plus the run's name and the target's settings when the run started:
  `{"target", "goal", "run", "settings"}`. Every tool refuses, and the policy forbids, a
  call whose context names another target; the reading tools and the trial also refuse when
  the target now runs with other settings. Whether the target moved before an adoption is
  left to the `Registry`, which adopts atomically only if the target is still where the run
  found it, and raises `Moved` otherwise.
- **What is adopted is what was trialled.** `adopt` takes the target from the context and
  computes the settings from the context's settings and the adjustment; settings that
  differ from what the adjustment makes are refused.
- **A person approves every adoption,** shown the settings and the evidence.
- **One adoption per run.** `adopt` records under the key `"<run>#adopt"`, taken from the
  trusted context rather than the call's key, so a crash or an interrupt-and-resume returns
  the adoption the run already recorded. The policy cannot read the registry, so after a
  resume a person may be asked to approve again; approving again changes nothing.

## What this harness uses from gvn

The improver is the self-improvement loop of DESIGN.md section 9 (observe, propose, verify,
evaluate, promote) as a harness. Its demonstration shows a support desk's score going from 3
of 6 to 5 of 6 to 6 of 6 over two adoptions, and the improver improving itself. Its
model-free stages are `Errand`s, and `Gated` reads the requests every actor makes, so
`Gated([ADOPT])` sees the adoption errand's call and its approval. The [domains overview](index.md#what-the-harnesses-use-from-gvn) lists these
parts of gvn across all the harnesses.

## What a trial tells you

A trial replays the target's recorded runs with the proposed setting. It compares how the
target's own evaluation grades them, so its verdict is as good as that evaluation, and a
person approves every adoption. The [self-improvement](../guides/self-improvement.md) page
explains what a trial can prove. The demonstration's models are scripted: it shows the
mechanics of the loop.

The harness's own tests are in `packages/gvn-domains/tests/test_dom_meta_*.py`.

## Recap

- A target opts in through `Tunable`: settings, a finite menu, a builder and an evaluation.
- Only `proposing` uses a model; observing, trialling and adopting are errands.
- The propose and trial loop is bounded by `ROUNDS` (3).
- The target and its settings come from the trusted context; a person approves every
  adoption, and one run adopts at most once.

**Next:** [Legal](legal.md), the most involved example: three nested workflows and people
who supply text.
