# Enterprise: purchase approval

**What you will learn:** how three reviewers vote at once and a **quorum** (enough votes to
settle the answer) ends the review as soon as the answer is settled, how a run waits days
for a person with no process running at all, and how a new launcher picks it up from the
[journal](../reference/glossary.md#journal). You will run a purchase request from the policy
check to a purchase order.

**Read first:** [Domains](index.md), for what every harness here is made of;
[Security](security.md), the previous domain page, for errands and a run context the plan
builds; [Workflows in depth](../concepts/workflows-in-depth.md) (joins),
[Errands](../concepts/errands.md) and [Durable objects](../concepts/durable-objects.md).

**Time:** about 25 minutes.

`enterprise/purchase_approval` (module `gvn_domains.enterprise.approvals`) takes a purchase
request through a policy check, a review by three reviewers, a person's approval and a
purchase order, and always tells the requester the result.

## 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 purchase approval they look like this:

```mermaid
flowchart LR
    brief(["brief: the purchase request"])
    approver(["a person who approves the order"])
    subgraph harness ["purchase_approval"]
        plan["<b>PurchaseRun</b> plan<br/>extract · review · authorise · notify"]
        policy["policy and tools<br/>check every call"]
        plan -- "tool calls" --> policy
    end
    ports[("your ports<br/>Ledger · Notices")]
    launcher["<b>Launcher</b>"]
    journal[("journal")]
    brief --> launcher
    launcher -- "drives" --> plan
    policy -- "cleared calls" --> ports
    launcher -- "asks" --> approver
    approver -- "approve or deny" --> launcher
    launcher -- "records" --> journal
```

What sets this harness apart from the others: several agents work at once and their votes
are counted, and the one step that commits money waits, possibly for days, on a person.

## The problem

Ada asks to buy two laptops. Before money is committed, someone checks the vendor and the
budget, finance, legal and security each give a view, and a person signs off. It is a
long-running business process: a run can wait days for a person, in no process at all, and
be recovered in another one over the same journal. Whatever the decision, Ada must be told.

## The plan

A run is a `PurchaseRun` [workflow](../concepts/workflows.md). The judgement steps host
agents; the steps whose calls are fully determined by code and trusted data host
[errands](../concepts/errands.md): small actors that make fixed tool calls with no model.

- `extracting`: an agent checks the vendor and the budget;
- `reviewing`: three reviewer agents at once, finance, legal and security;
- `authorising`: an errand issues the purchase order, after a person approves;
- `notifying_order` or `notifying_decline`: an errand tells the requester;
- `ordered`, `declined` or `failed`: the run is over.

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 state's output, the work it asks for; each arrow is labelled
with the input that moves the run along it:

```mermaid
stateDiagram-v2
    authorising : emits authorise
    declined : emits declined
    extracting : emits extract
    failed : emits failed
    idle : emits idle
    notifying_decline : emits notify
    notifying_order : emits notify
    ordered : emits ordered
    reviewing : emits review
    [*] --> idle
    authorising --> failed : order_failed
    authorising --> notifying_order : order_issued
    authorising --> failed : order_not_issued
    authorising --> notifying_decline : order_refused
    extracting --> failed : extraction_failed
    extracting --> reviewing : in_policy
    extracting --> notifying_decline : out_of_policy
    idle --> extracting : started
    notifying_decline --> failed : not_told
    notifying_decline --> failed : notify_failed
    notifying_decline --> declined : told
    notifying_order --> failed : not_told
    notifying_order --> failed : notify_failed
    notifying_order --> ordered : told
    reviewing --> notifying_decline : quorum_against
    reviewing --> authorising : quorum_for
    declined --> [*]
    failed --> [*]
    ordered --> [*]
    note right of idle
        otherwise: stay
    end note
```

`otherwise: stay` means any input not drawn leaves the run where it is.

The table says who works in each stage and how the stage ends. Three words recur in it and
on every domain page. A stage with several children at once is a **fan-out**
([Workflows](../concepts/workflows.md#step-3-a-stage-with-several-children-fanout)); its
**join** decides when the fan-out is over and with which result
([Joins](../concepts/workflows-in-depth.md#joins-when-is-a-fan-out-over)). A **judge** is a
[Decision](../reference/glossary.md#decision) that reads what a stage's child *did* and
picks the stage's result
([Judges](../concepts/workflows-in-depth.md#judges-deciding-on-what-a-child-said)).

| Stage | Who | How it ends |
|---|---|---|
| `extracting` | an agent: `vendor_record`, `budget_remaining` | a judge: `in_policy` only when `vendor_record` says the vendor is approved and the last `budget_remaining` read covers the amount; else `out_of_policy` |
| `reviewing` | three reviewer agents at once (finance, legal, security): `record_verdict` and the reads | `Quorum(2, "favours", classify=...)`: `quorum_for` as soon as two favour, `quorum_against` as soon as two can no longer favour; the third reviewer is then dropped mid-work |
| `authorising` | an errand: `issue_purchase_order` with the request's vendor and amount (needs a person) | routes on the errand's final state: `done` is `order_issued`; `declined` (a person denied it) is `order_refused`; `failed` (the call ran and failed: the order may be half made) is `order_failed`; `refused` (the policy forbade it, or a person denied it in an `approved` answer that named it) is `order_not_issued` |
| `notifying_order`, `notifying_decline` | an errand: `notify` the requester of the news | `told` when it was done, else `not_told` or `notify_failed` |

Every way of declining (out of policy, a quorum against, an approval denied) passes through
`notifying_decline`: the requester is always told. There are two notifying states rather
than one because a [Moore machine](../reference/glossary.md#moore-machine) (a machine whose
states name the work due) remembers only which state it is in, so "notify, then end
ordered" and "notify, then end declined" must be different states; both are built by one
function in the code. `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
actors at work.

Why errands there: once the reviewers have decided, the order is exactly the request's and
the message is exactly the decision. A model could only reword it or get it wrong, so the
reasons a requester reads are stated by code from the run's own record.

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
   authorising        authorise  order_failed -> failed, order_issued -> notifying_order, order_not_issued -> failed, order_refused -> notifying_decline
*  declined           declined   -
   extracting         extract    extraction_failed -> failed, in_policy -> reviewing, out_of_policy -> notifying_decline
*  failed             failed     -
>  idle               idle       started -> extracting
   notifying_decline  notify     not_told -> failed, notify_failed -> failed, told -> declined
   notifying_order    notify     not_told -> failed, notify_failed -> failed, told -> ordered
*  ordered            ordered    -
   reviewing          review     quorum_against -> notifying_decline, quorum_for -> authorising
otherwise: stay
```

## Walking through a run

The blocks below run in order, as one program, in the docs tests.

### 1. The outside world: two ports

The harness reaches the outside world only through its two ports. You implement them; here,
small in-memory versions stand in for a real ledger and mail system. A method that changes
something takes a `key`: an [idempotency key](../reference/glossary.md#idempotency-key),
the same string every time the same call is delivered, so a port that acts once per key
turns a repeat (after a crash, say) into a no-op.

| Port | Methods |
|---|---|
| `Ledger` | `vendor(name)`, `budget(cost_centre)`, `issue_order(request_id, vendor, amount, cost_centre, key)`: an order id; one order per key |
| `Notices` | `notify(person, message, key)`: a notice id; one notice per key |

These two record what they were asked to do, once per key:

```python
import typing

from gvn_domains.enterprise.approvals import Ledger, Notices


class Books(Ledger):
    def __init__(self) -> None:
        self.orders = {}  # key -> (order id, request id, vendor, amount, cost centre)

    async def vendor(self, name: str) -> dict[str, typing.Any] | None:
        return {"approved": name == "Acme", "risk": "low"}

    async def budget(self, cost_centre: str) -> float | None:
        return 5000

    async def issue_order(
        self, request_id: str, vendor: str, amount: float, cost_centre: str, key: str
    ) -> str:
        if key not in self.orders:
            self.orders[key] = (f"PO-{request_id}", request_id, vendor, amount, cost_centre)
        return self.orders[key][0]


class Mail(Notices):
    def __init__(self) -> None:
        self.sent = {}  # key -> (person, message)

    async def notify(self, person: str, message: str, key: str) -> str:
        self.sent.setdefault(key, (person, message))
        return f"notice:{person}"
```

### 2. Building the harness and the brief

The catalog builds the harness by its path from your ports (`Ports.of` files each object
under the port class it implements; see [The catalog](index.md#the-catalog)). A run starts
with the brief `{"request": {"id", "requester", "vendor", "amount", "justification"}}`.

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

books, mail = Books(), Mail()
approvals = catalog().harness(path="enterprise/purchase_approval", ports=Ports.of(books, mail))
request = {
    "id": "PR-88",
    "requester": "ada",
    "vendor": "Acme",
    "amount": 1200,
    "justification": "Two laptops for new hires.",
}
for identity in approvals.toolbox().identities():
    print(identity)
```

```text
gvn_domains.enterprise.approvals.budget_remaining
gvn_domains.enterprise.approvals.issue_purchase_order
gvn_domains.enterprise.approvals.notify
gvn_domains.enterprise.approvals.record_verdict
gvn_domains.enterprise.approvals.vendor_record
```

The toolbox lists each tool by its
[identity](../concepts/tools.md#two-names-the-short-name-and-the-identity): the module that
defines it, a dot and the short name the model sees. The module names the same tools with
constants built without their ports (`READING`, the pair `VENDOR_RECORD` and
`BUDGET_REMAINING`; `RECORD_VERDICT`; `ISSUE_PURCHASE_ORDER`; `NOTIFY`): the plan offers
and declares them, the errands call them, and the policy and evaluation match on them (see
[how a harness names its tools](index.md#how-a-harness-names-its-tools)).

### 3. A model for the extractor and the reviewers

No real model is used. Instead, the function below plays every agent: a fake model will
call it with the **exchange**, everything the model would be shown (the agent's
instructions and the messages so far), and it returns a `Reply`, the model's answer. A
`ToolCall` in that answer is the model asking for a tool; a message whose role is `TOOL`
carries a tool's result back (see [Adding a tool](../tutorials/adding-a-tool.md)).

The extractor looks up the vendor and the `IT-7` budget in one reply. Each reviewer records
a verdict: finance and legal approve, security objects. The module exports the instructions
(`EXTRACT`, and `REVIEWERS`, a mapping from role to instructions), so the function can tell
the agents apart.

```python
from gvn.harness.messages import TOOL, Message, ToolCall
from gvn.harness.ports import Exchange, Reply
from gvn_domains.enterprise.approvals import EXTRACT, REVIEWERS

FAVOURS = {"finance": True, "legal": True, "security": False}


def purchase_model(exchange: Exchange) -> Reply:
    if any(message.role() == TOOL for message in exchange.messages()):
        return Reply(message=Message.assistant(text="Done."))
    if exchange.instructions() == EXTRACT:
        calls = [
            ToolCall(call_id="c1", name="vendor_record", arguments={"vendor": "Acme"}),
            ToolCall(call_id="c2", name="budget_remaining", arguments={"cost_centre": "IT-7"}),
        ]
        return Reply(message=Message.assistant(text="", calls=calls))
    role = next(role for role, text in REVIEWERS.items() if text == exchange.instructions())
    verdict = {"approve": FAVOURS[role], "note": f"{role} view"}
    call = ToolCall(call_id="c1", name="record_verdict", arguments=verdict)
    return Reply(message=Message.assistant(text="", calls=[call]))
```

### 4. The policy check and the review

The [`Launcher`](index.md#the-launcher) takes the harness and the four things every run
needs. Here all four are test fakes from `gvn.testing.fakes` (see
[Testing your harness](../concepts/testing.md)): `FunctionModel` answers with
`purchase_model`, `MemoryJournal` keeps the journal in memory, `RecordingOutput` keeps what
the run would show, and `ManualClock` is a clock that moves only when you move it.
`start` drives the run until it finishes or must wait; `pending()` lists the requests it
waits on, and a request's `origin()` is the address of the actor that made it, here
`PR-88/authorising.1`: run `PR-88`, first visit of stage `authorising`.

```python
import asyncio

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

journal = MemoryJournal()
model = FunctionModel(respond=purchase_model)
launcher = Launcher(
    harness=approvals, model=model, journal=journal, output=RecordingOutput(), clock=ManualClock()
)
waiting = asyncio.run(launcher.start(run_id="PR-88", brief={"request": request}))
print(waiting.status(), waiting.pending()[0].origin())
```

```text
waiting PR-88/authorising.1
```

What happened:

1. **Extracting.** The extractor read the vendor record and the budget of `IT-7`. Its judge
   found the vendor approved and 5000 covering 1200, so the stage ended `in_policy`.
2. **Reviewing.** A fan-out started the three reviewers at once. Each reviewer's outcome is
   classified by a [Decision](../concepts/decisions.md): `favours` when its last recorded
   verdict approves, `opposes` when it objects or recorded none, `review_broke` when it
   failed. This is the built-in `Quorum` join with `classify=`, counting verdicts rather
   than final states. Two in favour settle it, so the stage ended `quorum_for`, whatever
   the third reviewer would have said.
3. **Authorising.** The errand asked to call `issue_purchase_order`, and the policy said a
   person must approve. The run is parked.

### 5. Days later, in another process

A parked run holds no process: everything is in the journal. Here a brand-new launcher,
as another process would build, recovers the run from the same journal and finds the same
pending request:

```python
later = Launcher(
    harness=approvals, model=model, journal=journal, output=RecordingOutput(), clock=ManualClock()
)
recovered = asyncio.run(later.recover(run_id="PR-88"))
request_for_order = recovered.pending()[0]
print(recovered.status(), request_for_order.origin())
```

```text
waiting PR-88/authorising.1
```

### 6. A person approves, the order is issued and Ada is told

`approve` delivers a person's yes to the pending request and drives the run on. `grade`
checks the finished run against the harness's **evaluation**, its statement of what a good
run looks like ([Replay and evaluation](../guides/replay-and-evaluation.md#step-6-evaluations-and-scorecards)):

```python
done = asyncio.run(later.approve(run_id="PR-88", request=request_for_order))
print(done.outcome().state())
print(list(books.orders.values()))
print([person for person, message in mail.sent.values()])
print(asyncio.run(later.grade(run_id="PR-88")).passed())
```

```text
State('ordered')
[('PO-PR-88', 'PR-88', 'Acme', 1200, 'IT-7')]
['ada']
True
```

The order has exactly the request's vendor and amount and the cost centre the extractor
checked. Had the person said no, the stage would have ended `order_refused`, and
`notifying_decline` would have told Ada why.

The evaluation: the run finishes `ordered` or `declined`, nothing is rejected, it takes at
most 40 events, and no order is issued without approval (`Gated([ISSUE_PURCHASE_ORDER])`,
a check on the recorded run that no call to the tool succeeded unless a person approved that call first; see
[checking a safety rule on recorded runs](../concepts/testing.md#checking-a-safety-rule-on-recorded-runs).
It sees the errand's call as well as an agent's).

## What is enforced before any effect

The policy gives every tool call one of three verdicts: `cleared` (it runs),
`needs_approval` (a person is asked first) or `forbidden` (it never runs). It clears the
reads, `record_verdict` and a permitted `notify`;
`issue_purchase_order` needs a person's approval; anything else, and any call the rules
below refuse, is forbidden.

Every actor's [run context](../concepts/run-context.md) is the request; the order errand's
also carries `"cost_centre"`, the centre whose budget the extraction stage found sufficient. One
rule set, `permitted(tool, origin, context, arguments=None)`, is used by the policy (a refused call is `forbidden`: no person is
asked, no tool runs) and again by each tool before its effect:

- `issue_purchase_order` must name exactly the request's vendor and amount and the
  context's cost centre. The request id is not an argument; it is read from the context.
- `notify` may only reach the request's requester.
- An order is issued once per call key, and the ledger issues at most one order per request,
  so a repeated order is refused rather than doubled.

You can ask the policy directly. A `Consultation` is the question the policy answers: the
calls, the identity of each call's tool (the policy matches by identity), the `origin`
(which actor asks) and the run context, here the one the order errand has.

```python
from gvn.harness.tools import Consultation, Tool
from gvn_domains.enterprise.approvals import ISSUE_PURCHASE_ORDER, NOTIFY

purchaser = {"request": request, "cost_centre": "IT-7"}


def verdict(tool: Tool, arguments: dict[str, typing.Any]) -> str:
    call = ToolCall(call_id="c1", name=tool.name(), arguments=arguments)
    consultation = Consultation(
        calls=[call], identities=[tool.identity()], origin="PR-88/authorising.1",
        context=purchaser,
    )
    return approvals.policy().decide(consultation).name()


order = {"vendor": "Acme", "amount": 1200, "cost_centre": "IT-7"}
print(verdict(ISSUE_PURCHASE_ORDER, order))
print(verdict(ISSUE_PURCHASE_ORDER, {**order, "amount": 12000}))
print(verdict(NOTIFY, {"requester": "bob", "message": "Approved."}))
```

```text
needs_approval
forbidden
forbidden
```

The exact order goes to a person. An inflated amount is refused before anyone is asked. A
notice to `bob` is refused: bob did not ask.

## What this harness uses from gvn

The order and the notices are issued by the model-free step, `Errand`, and the evaluation's
`Gated` check sees every actor of a run. The review is the framework's counting join,
`Quorum` with `classify=`. The [domains overview](index.md#what-the-harnesses-use-from-gvn) lists these parts of gvn across all the harnesses.

## How the review decides

The review is the built-in `Quorum`, with two outcomes and a fixed count. A rule such as
"legal may veto" is the `Worst` join with an early verdict, and the
[software review](software.md) shows a join with a veto. The harness's own tests are in
gvn's repository, in `packages/gvn-domains/tests/test_dom_enterprise_approvals.py`.

## Recap

- A fan-out runs reviewers at once; `Quorum` with `classify=` counts their verdicts and ends
  as soon as the answer is settled.
- A run waiting for a person is only a journal; any launcher over it can recover the run.
- Errands state the order and the notices from the run's own record, so a model cannot
  reword or inflate them.
- Every way of declining tells the requester.

**Next:** [Software delivery](sdlc.md), where a release moves through staging to production
and a go/no-go.
