# Architecture

**What you will learn:** how gvn is put together: its four layers and why code in one layer
may import only the layers inside it. The second part of the page, from
[gvn's own codebase](#gvns-own-codebase) on, is about the source of gvn itself: the things
it must never do, and how each rule is checked mechanically.

**Read first:** [The model behind gvn](../concepts/index.md), whose
[second picture](../concepts/index.md#picture-2-the-layers-of-code) this page expands. It
names machines, actors, requests, fulfillers, ports and the Governor, all introduced there.

**Time:** about 10 minutes for the overview; the tables after it are for looking things up.

This is the first reference page because it is the whole system seen as code: every other
reference page describes one part of what is drawn here. The design document `DESIGN.md`, at
the root of gvn's repository, explains the reasoning in full; that file and the others this
page names by path are in a clone of the repository, not in the installed package.

## The shape of it

### The thesis

An agent harness is a set of complete state machines whose only job is to decide what should
happen next. They never perform I/O. A separate runtime carries out the work they request,
through injected ports, and feeds each result back as the next input. Durability, streaming,
human-in-the-loop, interruption, fast tests and vendor independence are consequences of that
split rather than separate features.

### Four layers, from the inside out

gvn is built as four rings, each one using only the rings inside it:

1. **kernel**: the state machines themselves. A machine is a table of states and of which
   input moves it to which state; the kernel builds such tables, checks they are complete
   (the *verifier*), and turns objects into plain data and back. It uses only the Python
   standard library.
2. **harness**: the actors you build agents from (the reference agent, workflows, errands,
   conversations, and so on), plus tools and messages. An actor wraps a machine and says
   what work it needs done, such as "call the model" or "run this tool", as a *request*. It
   never does that work itself. The harness also defines the **ports**: abstract classes for
   anything from the outside world (a model, a journal, a clock).
3. **runtime**: the `Governor`, the only part that does work. It fulfils each request
   through a port, writes what happened to the journal, and feeds the result back to the
   actor as its next input.
4. **adapters**: one module per real system (Anthropic, OpenAI, Chat Completions services, SQLite, OpenTelemetry...),
   each implementing a port.

Beside them sits the **test kit**, `gvn.testing`: in-memory fakes for every port. Outside
them all sits one small convenience module, `gvn.shortcuts` ([the short
path](../guides/shortcuts.md)), which wires the pieces of the four rings together in one call;
nothing inside imports it. Two sibling packages, [gvn-tools](../tools/index.md) and
[gvn-domains](../domains/index.md), are built on the framework and never imported by it, and a
third, [gvn-workbench](../workbench/index.md), is the development tool that reads a project
built on it ([Packages](#packages) below).

### Imports and runtime calls are different relationships

The import rule describes what code may depend on. Ports let runtime calls reach an
outside system without introducing an outward import: the Governor knows the `Model`
interface, while the object injected into that interface may be an OpenAI adapter.

```mermaid
flowchart LR
    subgraph Imports[Allowed import direction]
        AD[Adapters] --> RT[Runtime]
        RT --> HA[Harness: actors and port ABCs]
        HA --> KE[Kernel]
    end
```

The arrows show layer order, not a requirement to import every adjacent layer. Code may
also import a deeper layer directly. Application setup chooses concrete adapters and
passes them to runtime objects. During execution, calls then follow the injected objects:

```mermaid
flowchart LR
    G[Governor] -->|handle and pending| A[Actor]
    G -->|fulfil| F[Fulfiller]
    F -->|generate through Model port| M[Injected model adapter]
    M -->|network call| V[Vendor service]
    G -->|append through Journal port| J[Injected journal adapter]
    J -->|persist| S[Storage]
    F -. result Event .-> G
    A -. Reaction and Requests .-> G
```

Here arrows represent runtime communication, not imports. `handle` and `pending` are the
two [actor](../concepts/actors-and-events.md) methods the Governor calls: hand it an event,
and ask which requests it now wants. A **fulfiller** is the runtime object that does one kind
of request (see [The Governor](../concepts/governor.md)); a **reaction** is what `handle`
returns, the actor's answer to one event. The actor decides what it wants
through its public interface and never holds a model or journal port. A different model or
journal implementation can be injected without changing the actor.

### Why dependencies point inwards

An inner layer never imports an outer one, so it cannot know that the outer one exists. That
gives three things:

- **The decisions are pure.** The kernel and harness do no I/O and read no clock, so a
  machine given the same inputs always reaches the same state. That is what lets a run be
  replayed from its journal, recovered after a crash, and tested without sleeping or touching the network.
- **Vendors are replaceable.** Only an adapter knows a vendor SDK. Removing a vendor removes
  one module; nothing inside changes.
- **Tests are fast and honest.** Because every outside effect goes through a port, a test
  swaps in a fake, and production code never depends on the fakes.

### How the import contracts enforce it

A rule that is only written down drifts. So the layering is checked by
[import-linter](https://import-linter.readthedocs.io/), a tool that reads every `import`
statement in the code and fails if one breaks a declared **contract**: for example, "the
`kernel` package never imports `runtime`". The contracts run as a test in the default suite,
so a change that imports outwards fails within seconds on the developer's machine. The
[Import contracts](#import-contracts) section below lists all sixteen; a few rules an import
graph cannot express are checked by small tests that read the source instead
([How the rules are enforced](#how-the-rules-are-enforced)).

The rest of this page is the reference. [Layers](#layers) and [Packages](#packages) say
what you import from where. [gvn's own codebase](#gvns-own-codebase) then lists every
contract, the prohibitions and how each is enforced.

## Layers

Dependencies point inwards. Nothing in an inner layer knows that an outer layer exists.

```text
shortcuts  run_agent, FunctionTool: the pieces below, wired in one call
   |
adapters   anthropic, openai, chat_completions, sqlite, postgres, clock, otel, logs  (optional extras)
   |
runtime    Governor, fulfillers, outputs, recovery, replay, evaluation,
           forms (stored-form versions), leasing (one owner per run),
           memory (scopes, the memory tools and fulfiller, the Embedder),
           fork (a run copied from a position), spending (Spend, Rates, Allowance),
           throttles (ThrottledModel and the in-process throttles),
           harnesses (Harness: one packaged job), launching (Launcher: runs a Harness on a Governor),
           inspection (a recorded run read actor by actor)
   |
harness    Agent, Workflow, Errand, Inquiry, Approval, Timer, Conversation, Choice,
           Tool, Toolbox, Transcript, Budget, context window, events, messages,
           answering (who may answer a request)
           ports (ABCs): Model, Journal, Leases, Output, Clock, Memory, Throttle, Fulfiller,
           Progress (and Quiet, a Progress that discards)
   |
kernel     Machine, blueprints, Definition, Verifier, Decision, Durable, Schema
           (standard library only)
```

A few names in that sketch belong to later sections or other pages: `recovery` rebuilds a
run from its journal after a crash; `replay` re-runs a recorded journal; `evaluation` grades
recorded runs against explicit checks; `Leases` is the port that keeps one owner per run when several
processes share a journal ([Running as a service](../guides/running-as-a-service.md));
`Progress` is the port that work in flight, such as a model call, reports streamed text
through, and `Quiet` one that discards
it ([Streaming and observability](../concepts/streaming-and-observability.md)); `fork`
continues a recorded run from a chosen position ([Forking a run](../guides/forking-a-run.md));
`spending` counts what a run spent and holds its allowance, and `Throttle` is the port for a
shared limit on calls ([Spending and rate limits](../guides/spending-and-rate-limits.md));
`answering` decides who may answer a waiting request ([Trust](../concepts/trust.md));
`harnesses` defines what a packaged job is ([Harnesses](../concepts/harnesses.md)), and
`inspection` reads a recorded run actor by actor ([Inspecting a run](../guides/inspecting-a-run.md));
the `Embedder` turns texts into vectors for a memory that recalls by meaning
([Memory](../concepts/memory.md#recall-by-meaning)).

| Layer | Package | What lives there |
|---|---|---|
| kernel | `gvn.kernel` | symbols, states and alphabets; blueprints, definitions and the verifier; machines; decisions; the [Dto](../concepts/durable-objects.md) protocol (how an object is saved as plain data); schemas; diagrams and diffs. Synchronous and pure. |
| harness | `gvn.harness` | actors (the reference agent, workflows, errands, inquiries, approvals, timers, conversations, choices), the context window (an actor's context budget, its gauge and the reduction steps), events and requests, messages, tools, transcript, budget, answering (the entitlement: who may answer a request), and the ports as abstract base classes. Synchronous and pure. |
| runtime | `gvn.runtime` | the `Governor` (asyncio), the built-in fulfillers, ready-made outputs, recovery, replay, evaluation, stored-form versions (`forms`), leases (`leasing`), running a harness (`launching`: the `Launcher`), memory in a run (`memory`: scopes, the recall and remember tools, the fulfiller of `remember` and `recall`, and the `Embedder` the shipped memories take to recall by meaning), forks (`fork`), spending and allowances (`spending`), throttles (`throttles`), the packaged job (`harnesses`: the `Harness` interface) and reading a recorded run actor by actor (`inspection`: `Inspector`, `Inspection`, `Moment`, `Movement`). The only layer that does work, and only through ports. |
| adapters | `gvn.adapters` | one module per vendor or backend: `anthropic`, `openai`, `chat_completions`, `sqlite`, `postgres`, `clock`, `otel`, `logs`. Adapters never import each other. |
| shortcuts | `gvn.shortcuts` | `run_agent` and `FunctionTool`: [the short path](../guides/shortcuts.md), which builds the same objects you would build by hand. The outermost layer: nothing in gvn imports it. |
| test kit | `gvn.testing` | fakes for every port and the contract suites. Sits beside the adapters; nothing in the framework imports it. |

You import each name from the module that defines it, such as
`from gvn.harness.agent import Agent`. The one exception is `TooLate`, the error for an
answer that arrives after its request is gone, which is also importable as
`from gvn.harness import TooLate`.

## Packages

The repository is a uv workspace of four packages:

| Package | Import name | What it is | Depends on |
|---|---|---|---|
| `packages/gvn` | `gvn` | the framework: kernel, harness, runtime, adapters, test kit | nothing (adapters' extras aside) |
| `packages/gvn-domains` | `gvn_domains` | complete example harnesses, organised by domain | `gvn`, through its public surface |
| `packages/gvn-tools` | `gvn_tools` | ready-made tools (files, shell, git, web, Jira Cloud, GitHub, MCP servers) with their safety rules | `gvn.harness` and `gvn.kernel` only |
| `packages/gvn-workbench` | `gvn_workbench` | the [Workbench](../workbench/index.md): a local site for developing, inspecting and evaluating a project's harnesses, installed as a development dependency | `gvn` through its public surface, and `gvn_tools` for its MCP server and client |

The framework imports none of the others, and nothing that ships in a deployment imports the
Workbench.

## gvn's own codebase {#gvns-own-codebase}

Everything above describes gvn as you use it. From here on the page describes the source of
gvn itself: the rules its code follows and the checks that hold it to them. Read it to
judge how the layering is kept, or before you change gvn; you do not need it to build a
harness.

### Import contracts

The contracts live in the root `pyproject.toml` under `[tool.importlinter]` and are checked
by [import-linter](https://import-linter.readthedocs.io/). There are sixteen: eight for the framework,
four for the sibling package [gvn-domains](../domains/index.md), two for the tools
package [gvn-tools](../tools/index.md), and two for the [Workbench](../workbench/index.md).

| Contract | Type | Enforces |
|---|---|---|
| Layers point inwards | `layers`, exhaustive | `shortcuts, console → adapters → evals → runtime → harness → kernel`, never upwards. Exhaustive, so a new top-level subpackage must be placed in a layer before it can merge (only `testing` is exempt). |
| No vendor SDK or third-party I/O below adapters or in shortcuts | `forbidden`, external packages included | `kernel`, `harness`, `runtime` and `shortcuts` cannot import `anthropic`, `openai`, `google`, `mistralai`, `cohere`, `litellm`, `opentelemetry`, `structlog`, `httpx`, `requests`, `aiohttp`, `psycopg`, `asyncpg`, `sqlalchemy`, `redis` or `pydantic`. |
| The test kit stays out of production code | `forbidden` | Nothing in `kernel`, `harness`, `runtime`, `adapters` or `shortcuts` imports `gvn.testing`. |
| Kernel internals | `layers` | `machine → blueprint, diagram, diff → definition → verifier, decision → symbols → durable → schema`. |
| Harness internals | `layers` | `agent, workflow, errand, inquiry, timer, conversation, approval, choice → ports, replies, sensors, answering → actor, tools, transcript, budget, context_window → events, messages`; the actor modules do not import each other. |
| Runtime internals | `layers` | `launching → leasing, harnesses → governor, evaluation, inspection → fulfillers, outputs, replay, memory, fork, throttles → recovery, spending → forms`. |
| Evals internals | `layers` | `running → report → comparison → judging → criteria → statistics, stand_ins → ports, evidence → cases`. |
| The framework never depends on its domains or tools | `forbidden` | Nothing in `gvn` imports `gvn_domains`, `gvn_tools` or `gvn_workbench`. |
| Domains | `layers` | `directory → meta → software, security, enterprise, sdlc, research, service, data, legal, education, finance, worker → launcher → catalog`; the domain modules are independent of each other. |
| Domains stay clean | `forbidden` | Production code in `gvn_domains` imports no vendor SDK and no test kit. |
| Software domain | `layers` | `fleet → web, ai, ticket_to_pull_request → build → ports`: subdomains can import the shared build and ports and are independent of one another. |
| Tools: each family stands alone | `layers` | `files, shell, git, web, jira_cloud, github, mcp → rules, fakes → workspace, process, transport, protocol, retrying`; the families never import each other. |
| Tools depend on the harness interfaces only | `forbidden` | `gvn_tools` never imports `gvn.runtime`, `gvn.adapters`, `gvn.testing` or `gvn_domains`: it uses only `gvn.harness` and `gvn.kernel`. |
| Test kit independence | `independence` | `gvn.testing.fakes` and `gvn.testing.contracts` do not import each other. |
| Nothing that ships depends on the Workbench | `forbidden` | `gvn`, `gvn_domains` and `gvn_tools` never import `gvn_workbench`: a deployed harness does not need it installed. |
| The Workbench reads gvn through its interfaces | `forbidden` | `gvn_workbench` never imports `gvn.testing`, `gvn_domains` or a vendor SDK. |

Two rules cannot be expressed as import-linter contracts, so they are tests over the same
import graph:

- **The kernel is standard library only.** Every import from `gvn.kernel` must resolve to
  `gvn.kernel` itself or to a module in `sys.stdlib_module_names`. A deny-list cannot say
  "nothing third-party", so this is checked positively.
- **Adapters are independent.** No adapter module reaches another, directly or indirectly,
  so removing one vendor touches one module.

The same tests also run import-linter itself, check that every layer exists, and check
that the package declares no runtime dependencies.

### Prohibitions

These are not things left out of scope. They are things the codebase must never do. A
change that introduces one is rejected in review, and where a mechanical check is possible
it fails the build.

- **Never pass state around as dicts, TypedDicts or dataclasses between free functions.**
  State lives inside the object that maintains it and is reached only through that object's
  interface. The one sanctioned plain-data shape is a class's inner `Dto` (see
  [Durable objects](../concepts/durable-objects.md)), used only for serialisation.
- **Never rely on a type checker for correctness.** Hints stay for readers. Every guarantee
  comes from a runtime contract: an ABC (abstract base class), a
  [`Schema`](../concepts/durable-objects.md#deeper-schemas), a constructor that validates
  its own arguments. Type hints are a design choice for people reading the code; gvn never
  reads them to decide behaviour or configuration.
- **Never use pydantic in the core.** It derives validation from type hints, which is the
  dependency gvn rejects.
- **Never ship a "graph of nodes" that is really a workflow.** If a definition cannot pass
  the verifier, it is not a machine and cannot be instantiated.
- **Never perform I/O from a machine or hold a port inside a durable object.** I/O belongs
  to the runtime.
- **Never keep module-level mutable state.** No singletons, no global registries; everything
  is injected.

### Code rules that follow from them

gvn's code follows these rules; `CONTRIBUTING.md`, at the root of the repository, states
them for contributors:

- No public attributes on classes, except the fields of a `Dto`. State lives in underscore
  members and is reached through methods.
- Never touch another object's underscore members.
- Inheritance only to implement an ABC, one level deep. Composition otherwise.
- No I/O, clocks, randomness or id generation in kernel or harness code.
- Durable classes follow `gvn.kernel.durable`, and `from_dto` raises `TypeError` for a Dto
  of another class.
- Errors change nothing: a method that raises leaves the object exactly as it was.

### How the rules are enforced

| Rule | How it is checked |
|---|---|
| Layering, vendor isolation, test kit isolation, internal layering | the import-linter contracts, run as a command and as a test in the default suite |
| Kernel is stdlib only; adapters independent; no runtime dependencies | tests over the import graph and the package's declared dependencies |
| No module-level mutable state; no `global` rebinding | a test that reads the source as syntax trees |
| No public attributes on objects | the same test: no assignment to `self.<public name>` anywhere |
| Behaviour never depends on type hints | the same test: no use of `__annotations__`, `get_type_hints` or `get_annotations` |
| Kernel and harness do no I/O and read no clock | the same test: no imports of `time`, `os`, `asyncio`, `socket`, `sqlite3` and similar, and no calls to `open`, `print` or `input` |
| No private names imported across modules | the same test |
| No reaching into another object's private state | ruff rule `SLF` |
| Machines are complete | the verifier, every time a definition is built or loaded |
| Every durable class refuses another class's Dto | a test that finds every such class by itself and hands each one other classes' Dtos |
| The public API and the stored forms change only on purpose | tests that compare them with frozen copies (see [Stability](stability.md)) |

The syntax-tree checks catch the common ways of breaking a rule. Coupling that is not an import, such as reaching into another object's private
state, is covered by ruff and by those tests. Whether a machine is complete is the
verifier's job, not the linter's.

The tests are in the repository under `packages/gvn/tests/architecture`. They run in the
default test suite and on every change; `CONTRIBUTING.md` gives the commands.

## Recap

- Four layers: kernel (machines), harness (actors and ports), runtime (the Governor, the only
  part that does work) and adapters (real systems). Dependencies point inwards only.
- Sixteen import contracts and a few source-reading tests keep it that way, in the default
  test run.
- The prohibitions are absolute: no state passed around as plain dicts, no reliance on a type
  checker, no I/O in machines, no module-level mutable state.

**Next:** [Interface contracts](interfaces.md), the boundaries in these layers that you use
or implement.
