Browse documentation
Guides
View Markdown
On this page

A coding agent on your own repository

This guide builds an agent that fixes a bug in a git repository: it reads the code, edits a file, runs the tests with a person's approval, and commits the fix. At the end you have a complete harness you can point at your own checkout.

If you want to see every part of gvn working together in one program before you build your own, this is the page to read: real tools, a policy, a person's approval, a journal on disk and a result you can read back, from an empty directory to a commit. You put it together one piece at a time, and check each piece before adding the next.

  • You will be able to: give an agent file, shell and git tools over a repository, decide which of its calls need a person, approve them, read what it did, and swap in a real model.
  • Read first: the tutorials up to 5. A policy and approval, 6. Crash and resume and 12. A real model and ready-made tools. The Tools section, later in these docs, covers each tool family in depth; this guide explains what it uses as it goes.
  • Time: about 30 minutes.

Where this fits

This guide fills in every box of the big picture with something real. The actor is gvn's ready-made agent. The fulfillers are a model, the tools from gvn-tools (gvn's package of ready-made tools) and a policy built from those tools' recommended rules. The person who approves is asked before a test run. The journal is a SQLite file, so a run that waits for that person survives a crash.

flowchart LR
    repo[("Your repository")]
    workspace["Workspace<br/>the one directory tools may touch"]
    toolbox["Toolbox<br/>file, shell and git tools"]
    rules["Policy<br/>merged rules of the three families"]
    model["Model"]
    governor["Governor"]
    agent["Agent<br/>a verified state machine"]
    journal[("SQLite journal")]
    person(["A person who approves"])
    repo --- workspace --- toolbox
    agent -- "requests" --> governor
    governor -- "events" --> agent
    governor -- "invoke_model" --> model
    governor -- "consult_policy" --> rules
    governor -- "invoke_tools" --> toolbox
    governor -- "request_approval" --> person
    governor -- "records" --> journal

You build it from the bottom up: the repository and its workspace (step 1), each tool family tried by hand (steps 2 to 4), the policy (step 5), the agent and its model (step 6), the governor and journal (step 7), and then a run with an approval (steps 8 to 10). Only the model changes for real use (step 11).

Every example on this page runs offline in the docs tests: the model is a ScriptedModel that plays a sensible agent. The repository, the file edits, the test run and the commit are real. You need git and python3 on your PATH.

Step 1: a repository and a workspace

The agent needs a repository to work on. Here a tiny one is made on the spot, with a bug: total() is off by one. When you use this for real, point the workspace at your own checkout instead.

The git commands set GIT_CONFIG_GLOBAL and GIT_CONFIG_NOSYSTEM, so that your own git configuration plays no part in the example:

import os
import pathlib
import subprocess

ISOLATED = {"GIT_CONFIG_GLOBAL": os.devnull, "GIT_CONFIG_NOSYSTEM": "1"}
repo = pathlib.Path("shop")
repo.mkdir()
(repo / "prices.py").write_text("def total(prices):\n    return sum(prices) - 1\n")
(repo / "test_prices.py").write_text(
    "import unittest\n"
    "from prices import total\n\n\n"
    "class TotalTest(unittest.TestCase):\n"
    "    def test_total(self):\n"
    "        self.assertEqual(total([1, 2]), 3)\n"
)
git_environment = {**os.environ, **ISOLATED}
for argv in (
    ["git", "init", "-q", "-b", "main"],
    ["git", "add", "-A"],
    ["git", "-c", "user.name=me", "-c", "[email protected]", "commit", "-q", "-m", "Start"],
):
    subprocess.run(argv, cwd=repo, env=git_environment, check=True)

Now draw the boundary. A Workspace is the one directory the tools may touch; every path a model gives is resolved inside it:

from gvn_tools.workspace import Workspace

workspace = Workspace(root=repo.resolve())
print(workspace.root().name)  # shop

Step 2: the file tools

A tool family is a group of tools over one kind of thing, built over the same limits. The file tools read, list, search, write and edit files inside the workspace. Before an agent uses them, use one yourself, to see what the agent will see. A tool runs with the arguments a model would send, and an Invocation that names the call: its key is the call's idempotency key, a string that is the same every time the same call of the same run is delivered, and origin names who asked. files.tools returns the family's tools as a named tuple, so you pick one by attribute:

import asyncio

from gvn.harness.tools import Invocation
from gvn_tools import files

file_tools = files.tools(workspace=workspace)
read_file = file_tools.read_file
by_hand = Invocation(key="by-hand/1#c1", origin="me")

source = asyncio.run(read_file.run(arguments={"path": "prices.py"}, invocation=by_hand))
print(source["text"])
# def total(prices):
#     return sum(prices) - 1

There is the bug. The file tools refuse any path outside the workspace and never write into .git; the Files page lists exactly what they refuse.

Step 3: the shell tool

To check a fix, the agent must run the tests. The shell tool runs one program from a list you give it, with its arguments as a list, never through a shell. It runs programs through a Commands port (an interface the tool calls, so a test can put a fake behind it); LocalCommands() starts real processes, with no shell and a clean environment, so the API keys of this process never reach them.

Run the tests yourself first. They fail, because of the bug:

from gvn_tools import shell
from gvn_tools.process import LocalCommands

commands = LocalCommands()
shell_tools = shell.tools(workspace=workspace, commands=commands, programs=["python3"])
run_command = shell_tools.run_command

tests = {"argv": ["python3", "-m", "unittest", "-q"]}
outcome = asyncio.run(run_command.run(arguments=tests, invocation=by_hand))
print(outcome["exit"])  # 1: a test fails

A failing program is a result, not an error: the exit code and the output go back to the model, which reads them.

Step 4: the git tools

The git tools give the agent status, diff, log, branches, commits and pushes, each building its own git command line. Give them an author for the commits, and the same ISOLATED environment so your configuration stays out of it:

from gvn_tools import git

git_tools = git.tools(
    workspace=workspace,
    commands=commands,
    author=("Coding agent", "[email protected]"),
    environment=ISOLATED,
)
git_log = git_tools.git_log
history = asyncio.run(git_log.run(arguments={"count": 1}, invocation=by_hand))
print([(entry["author"], entry["message"]) for entry in history["commits"]])  # [('me', 'Start')]

Step 5: the rules

The tools decide what is possible. The policy decides which of the possible calls need a person first. Each family's rules(...) takes the tuple its tools(...) built and returns its recommended policy as a Rules object, a policy written as a list of rules per tool; merged joins two of them into one. Put the tools into one Toolbox too, the collection the runtime runs them from.

Each tool has two names. The model sees its short name, read_file. gvn stores and matches it by its identity: its namespace (the module that defines it), a dot and the short name, so a read_file from another package is never confused with this one. That is why everything here passes the tool objects, never their names (Tools):

from gvn.harness.tools import Toolbox

toolbox = Toolbox(tools=[*file_tools, *shell_tools, *git_tools])
policy = files.rules(file_tools).merged(shell.rules(shell_tools)).merged(git.rules(git_tools))
print(toolbox.identities())
# ('gvn_tools.files.edit_file', 'gvn_tools.files.list_files', 'gvn_tools.files.read_file',
#  'gvn_tools.files.search_files', 'gvn_tools.files.write_file', 'gvn_tools.git.git_commit',
#  'gvn_tools.git.git_create_branch', 'gvn_tools.git.git_diff', 'gvn_tools.git.git_log',
#  'gvn_tools.git.git_push', 'gvn_tools.git.git_status', 'gvn_tools.shell.run_command')

Ask the policy about a few calls, to see it decide. A policy is asked with a Consultation: the calls of one model reply (ToolCalls, each with an id, the short name the model wrote and arguments), the identity of each call's tool, and the origin, the name of the actor asking. Consultation.of builds one from (tool, arguments) pairs. decide returns one of the three verdicts:

import typing

from gvn.harness.messages import ToolCall
from gvn.harness.tools import Consultation, Tool


def verdict(tool: Tool, arguments: dict[str, typing.Any]) -> str:
    consultation = Consultation.of([(tool, arguments)], origin="fix-17")
    return policy.decide(consultation).name()


edit = {"path": "prices.py", "old": "- 1", "new": ""}
print(verdict(file_tools.edit_file, edit))  # cleared
print(verdict(run_command, tests))  # needs_approval
print(verdict(git_tools.git_push, {"branch": "main"}))  # forbidden

What this policy allows, before any person is asked:

  • reading, searching, writing and editing files inside the repository, but never in .git;
  • git status, diff, log, branching and committing: cleared, because every commit is recorded and reversible;
  • running python3, with any arguments: needs approval every time. The shell tool is not a sandbox, and python3 can run anything, so a person reads each command first. List a program as quiet in shell.rules(shell_tools, quiet=[...]) only when a repeat of it is harmless and you trust what it may be asked to do. When the model asks for an edit and a test run in one reply (real models usually do), each call is judged on its own: the person is asked only about the test run, with the edit shown beside it as context, and once they answer the calls run in the order given, the edit first;
  • pushing: needs approval, and never to main or master;
  • anything else: forbidden.

Step 6: the agent and its model

The reference agent is a verified state machine that asks a model what to do, asks the policy about the tools the model wants, waits for a person when the policy says so, and runs the tools. It does no I/O itself; it only says what it wants next.

For this guide the model is a ScriptedModel: it gives the replies you write, in order. A small helper makes one reply, with an optional tool call. The model writes each call with the tool's short name, as a real model does:

from gvn.harness.messages import Message
from gvn.harness.ports import Reply
from gvn.testing.fakes import ScriptedModel


def says(
    text: str,
    tool: str | None = None,
    arguments: dict[str, typing.Any] | None = None,
    call_id: str = "c1",
) -> Reply:
    calls = [ToolCall(call_id=call_id, name=tool, arguments=arguments)] if tool else []
    return Reply(message=Message.assistant(text=text, calls=calls))


model = ScriptedModel(
    script=[
        says("Let me look at the code.", tool="read_file", arguments={"path": "prices.py"},
             call_id="c1"),
        says("It subtracts one.", tool="edit_file",
             arguments={"path": "prices.py", "old": "sum(prices) - 1", "new": "sum(prices)"},
             call_id="c2"),
        says("Now the tests.", tool="run_command", arguments=tests, call_id="c3"),
        says("They pass. Committing.", tool="git_commit",
             arguments={"paths": ["prices.py"], "message": "Fix total() off by one"},
             call_id="c4"),
        says("Fixed total() and committed the fix."),
    ]
)

Now the agent itself. Its name names the run, its instructions are the system prompt, and tools is the tools it is offered, here the whole toolbox. The agent keeps their identities, and offers the model one tool per short name:

from gvn.harness.agent import Agent

agent = Agent(
    name="fix-17",
    instructions="You fix bugs in this repository. Run the tests before committing.",
    tools=toolbox,
)
print(agent.state().name())  # idle

Step 7: the Governor and its journal

The agent says what it wants; the Governor does it. It hands each kind of request to a fulfiller: the model for invoke_model, the toolbox for invoke_tools, the policy for consult_policy. A request kind listed as external is not fulfilled here: the run stops and waits for an answer from outside, here a person's approval.

Every event goes into the journal first. A SqliteJournal keeps it in a file, so a run that waits for a person can be picked up later, by another process, after a crash:

from gvn.adapters.sqlite import SqliteJournal
from gvn.runtime.fulfillers import ModelFulfiller, PolicyFulfiller, ToolFulfiller
from gvn.runtime.governor import Governor
from gvn.testing.fakes import ManualClock, RecordingOutput

journal = SqliteJournal(path="agent.db")
governor = Governor(
    fulfillers={
        "invoke_model": ModelFulfiller(model=model, toolbox=toolbox),
        "invoke_tools": ToolFulfiller(toolbox=toolbox),
        "consult_policy": PolicyFulfiller(decision=policy),
    },
    external=["request_approval"],
    journal=journal,
    output=RecordingOutput(),
    clock=ManualClock(),
)

RecordingOutput keeps what the run reports, and ManualClock is a clock that moves only when told to: both are test fakes from gvn.testing.fakes.

Step 8: start the run and watch it wait

Deliver the first event, started, with the task as the prompt. The agent reads the file and edits it, both cleared. Then it asks to run the tests, which needs approval, so the run stops and says what it is waiting for. governor.deliver returns a result: its status() is WAITING while the run waits for an answer from outside, and pending() lists the requests it waits on:

from gvn.harness.events import Event, Request
from gvn.runtime.governor import WAITING, Result

task = Event("started", payload={"prompt": "total() is off by one."})
result = asyncio.run(governor.deliver(actor=agent, event=task))
print(result.status() == WAITING)  # True
request = result.pending()[0]
print([call["arguments"] for call in request.payload()["calls"]])
# [{'argv': ['python3', '-m', 'unittest', '-q']}]

In a real deployment the request goes to whoever approves, and the run waits as long as it takes, in no process at all (see Humans and interruption). The edit has already been made:

print((repo / "prices.py").read_text())
# def total(prices):
#     return sum(prices)

Step 9: approve

Here the person is a few lines of code. They approve every command except inline code (python3 -c ...), which they deny with a reason. An approval request may ask about several calls at once, so the answer is per call: approved with no payload approves them all, and approved with {"denied": [{"call_id", "reason"}]} denies the calls it names and approves the rest. The request carries the identity of each call's tool, and identified_calls reads the calls and their identities back, so the person's code picks the shell calls by the tool, not by a name:

from gvn.harness.tools import identified_calls

INLINE = "inline code is not approved; run a module or a script file"


def answer_for(request: Request) -> Event:
    calls, identities = identified_calls(request.payload())
    denied = [
        {"call_id": call.call_id(), "reason": INLINE}
        for call, identity in zip(calls, identities)
        if identity == run_command.identity() and "-c" in call.arguments()["argv"][1:]
    ]
    return Event("approved", {"denied": denied} if denied else None)

The run carries on until it finishes or waits again:

async def approve_until_done(result: Result) -> Result:
    while result.status() == WAITING:
        request = result.pending()[0]
        print("approving", [call["name"] for call in request.payload()["calls"]])
        answer = answer_for(request)
        result = await governor.answer(actor=agent, request=request, event=answer)
    await journal.close()
    return result


result = asyncio.run(approve_until_done(result))
# approving ['run_command']

This loop over governor.answer is approval at the Governor's own level; the recipe Stop a tool call until a person approves is the same call as one small script. The same mechanism has two more forms: run_agent(..., approve=your_function) runs this loop for you (The short path), and a service answers with launcher.approve(..., by=), which takes the run's lease first (Running as a service).

Only the test run needed a person. The commit after it was cleared by the policy. Had the person denied a command, the model would have read the reason as that call's failed result, and any later call in the same reply that is not a pure read would have been skipped (see several calls in one reply).

Step 10: read the result

The finished run's outcome holds the agent's last text and every tool call it attempted. Each attempt carries the tool's short "name", shown here, and its "identity", which is what code that reads the attempts matches on:

payload = result.outcome().payload()
print(payload["text"])  # Fixed total() and committed the fix.
print([(attempt["name"], attempt["status"]) for attempt in payload["attempts"]])
# [('read_file', 'ok'), ('edit_file', 'ok'), ('run_command', 'ok'), ('git_commit', 'ok')]
print(payload["attempts"][2]["detail"]["exit"])  # 0: the tests pass

The commit carries the call's key as a trailer, which is how a repeat after a crash finds it instead of committing twice:

log = subprocess.run(
    ["git", "log", "-1", "--format=%an: %s%n%(trailers:key=Gvn-Key,valueonly)"],
    cwd=repo, env=git_environment, capture_output=True, text=True, check=True,
)
print(log.stdout.strip())
# Coding agent: Fix total() off by one
# fix-17/25#c4

Everything the run did is in agent.db. If the process had died while waiting for the approval, a new process would rebuild the agent from it with Recovery and carry on (see the tutorial Crash and resume).

Step 11: swap in a real model

Replace the scripted model with a vendor adapter (see Using a vendor model). With Anthropic's adapter, for instance:

# not runnable: it needs an API key and a model id in the environment.
import os

import anthropic

from gvn.adapters.anthropic import AnthropicModel

model = AnthropicModel(
    client=anthropic.AsyncAnthropic(), model=os.environ["MODEL_ID"], max_tokens=8192
)

The model id comes from the environment variable MODEL_ID, as in the quickstart and the vendors guide, so changing models is a change of configuration. Everything else stays the same: the tools, the policy, the approvals. Give the agent a real turns= budget (the most model turns a run may take) for real work, and a clock that tells the time (SystemClock from gvn.adapters.clock).

What a live run showed

A harness like this one was run with claude-haiku-5-5 on a temporary repository: it fixed a one-line bug and committed it in 9 of 9 runs, for well under a cent each, and a crash after the commit was recovered without a second commit. The model put the edit and the test run in one reply every time, which is why a reply's calls run in order. With prompt caching and per-call approval, six live tests (these three, plus checks of carried thinking, caching and effort) passed 18 of 18 times over three runs; the approver was asked only about run_command, and a warm fix-and-commit run cost about a quarter of its uncached price. The details and the costs are in Live runs.

Running it safely

What the tools enforce, and what you add around them:

  • Isolate the machine. The shell tool restricts which programs run and where, but an approved command runs with this process's permissions. Run the harness in a container or a VM when the repository or the model is not trusted.
  • Treat what files, programs and git print as data. A file in the repository can hold text written to steer the model; the policy and the tools bound what the model is persuaded to try.
  • .git is protected from the file tools. A command you approve can still write there; hooks stay off unless you turn them on.
  • A refused call is a result. When a tool refuses (a path outside the workspace, a program not on the list), the model gets a failed result saying why and may try something else. Check payload["attempts"] for statuses other than ok.
  • Point the workspace at the repository's top level, which the git tools require (see Git).

Recap

You built the harness in layers: a workspace; file, shell and git tools confined to it; a policy that clears the safe calls and asks a person about running programs and pushing; the reference agent with a model; and a Governor with a durable journal that waits for the person and records everything. Only the model changes between this page and a real run.

Next: to check recorded runs like this one against a rule such as "every test run was approved", read Replay and evaluation; to cap what a run with a real model may spend, read Spending and rate limits.