# Rules

`gvn_tools.rules.Rules` builds a tool policy from a few lines: which calls may run at once,
which need a person first, and which are never allowed.

- **You will learn:** how to build a `Rules` step by step from tool objects, how a condition (`when`) narrows a
  rule, how `exposed` makes a rule depend on what the model has read, how the calls of one reply are judged, and how to merge the families' rules.
- **Read first:** [Tools](index.md), whose step 4 shows a policy deciding.
- **Time:** about 10 minutes.

## Where a policy sits

In the picture of [where tools plug in](index.md#where-tools-plug-in), a policy is what the
**policy fulfiller** asks before any tool call runs. The tools refuse what is outside their
limits whatever the policy says; a policy decides something else: **which calls need a
person** before they run, and which are not allowed at all. Each family's `rules(...)` gives
a recommended policy for the tools it is given, as a `Rules`. This page shows how to write
one yourself, change a family's, and merge several.

A `Rules` is a kernel [Decision](../concepts/decisions.md): an object that looks at a subject
and answers with one of a fixed set of outcomes. Its subject is a `Consultation` (the calls
being judged, the identity of each call's tool, the actor that asked, the run's context, and
which untrusted sources the actor's model had read) and its outcomes are gvn's three **verdicts**: `cleared` (run it), `needs_approval` (ask a
person first) and `forbidden` (never), listed in `gvn.harness.tools.VERDICTS`. So it goes
wherever gvn takes a policy: the policy fulfiller (`PolicyFulfiller(decision=rules)`), or the
`policy()` of a [domain harness](../domains/index.md).

A rule names its tools as **objects**, and matches a call by its tool's **identity**: the
tool's namespace, a dot and its short name, which the consultation records for each call. So
a rule for one tool never matches another package's tool that shares its short name
([Tools](../concepts/tools.md) explains the two names).

## Building one, a rule at a time

The running example is a small refunds desk with four tools: `read_ledger`, `refund`,
`delete_ledger` and `transfer`. [`FunctionTool`](../guides/shortcuts.md) makes each from a
function; the namespace `refunds` is the desk's, so the identity of `refund` is
`refunds.refund`.

### Step 1: one cleared tool, everything else forbidden

Start with an empty `Rules` and clear one tool. A small helper puts calls to the policy, as a
model reply would hold them (a tool and its arguments each), and prints its verdict.
`Consultation.of` builds the consultation from those pairs: it numbers the calls (`c1`, `c2`,
...) and records each tool's identity beside its call:

```python
import typing

from gvn.harness.messages import ToolCall
from gvn.harness.tools import Consultation, Tool
from gvn.kernel.schema import Integer, Record
from gvn.shortcuts import FunctionTool
from gvn_tools.rules import Rules


def done(**arguments: typing.Any) -> dict[str, bool]:
    return {"done": True}


def desk_tool(name: str, arguments: Record = Record({})) -> FunctionTool:
    return FunctionTool(name, f"The desk's {name}.", arguments, done, namespace="refunds")


read_ledger = desk_tool("read_ledger")
refund = desk_tool("refund", Record({"amount": Integer()}))
delete_ledger = desk_tool("delete_ledger")
transfer = desk_tool("transfer")


def verdict(
    policy: Rules, *calls: tuple[Tool, dict[str, typing.Any]], context: dict[str, typing.Any] | None = None
) -> str:
    return policy.decide(Consultation.of(calls, origin="agent", context=context)).name()


policy = Rules(default="forbidden").clear(read_ledger)
print(verdict(policy, (read_ledger, {})))  # cleared
print(verdict(policy, (transfer, {})))  # forbidden: no rule names it, so the default decides
```

`default` is the verdict for a call no rule matches. `"forbidden"` is the default default;
keep it, so that a tool you forgot to name can never run.

A rule takes the tool, never its name. A string is refused when the rule is built:

```python
try:
    Rules().clear("read_ledger")
except TypeError as error:
    print(error)
```

```text
a rule's tools: got the str 'read_ledger' where a tool is expected; pass the Tool object itself (tools are referred to by object, never by name)
```

### Step 2: a tool that needs a person

`approve` adds a rule that asks a person first, and `forbid` one that never allows the call.
Each method returns a **new** `Rules`; the one it was called on is unchanged:

```python
desk = policy.approve(refund).forbid(delete_ledger)
print(verdict(desk, (refund, {"amount": 40})))  # needs_approval
print(verdict(policy, (refund, {"amount": 40})))  # forbidden: the earlier policy did not change
```

A rule matches by identity. Payroll's `refund` has the same short name, but it is another
tool, and no rule of the desk names it:

```python
payroll_refund = FunctionTool(
    "refund", "Refund a payslip.", Record({"amount": Integer()}), done, namespace="payroll"
)
print(payroll_refund.identity())  # payroll.refund
print(verdict(desk, (payroll_refund, {"amount": 40})))  # forbidden
```

### Step 3: a condition with `when`

Asking a person about every refund is slow. A rule can carry a condition, `when`: a function
of the call and the run's [context](../concepts/run-context.md) that returns a bool. The run
context is trusted data fixed when the run starts, here the amount above which a refund needs
a person:

```python
def large(call: ToolCall, context: dict[str, typing.Any]) -> bool:
    amount = call.arguments().get("amount")
    return isinstance(amount, int) and amount > context.get("approval_over", 0)


desk = (
    Rules(default="forbidden")
    .clear(read_ledger)
    .approve(refund, when=large)  # tried first: a large refund needs a person
    .clear(refund)  # otherwise cleared
    .forbid(delete_ledger)
)
context = {"approval_over": 100}
small_refund = (refund, {"amount": 40})
big_refund = (refund, {"amount": 400})
print(verdict(desk, small_refund, context=context))  # cleared
print(verdict(desk, big_refund, context=context))  # needs_approval
```

For one call, the rules for its tool are tried **in the order they were added**; the first
whose `when` holds gives the verdict (a rule without `when` always holds). That is why the
conditional `approve` comes before the plain `clear`.

### Step 4: several calls in one reply

A model may ask for several calls in one reply. In a run, `PolicyFulfiller` asks the policy
about **each call on its own**, so each call gets its own verdict: the read is cleared and
only the big refund waits for a person (see
[one verdict per call](../concepts/reference-agent.md#one-verdict-per-call)). `verdicts`
shows what each call of a consultation gets:

```python
reply = Consultation.of([(read_ledger, {}), big_refund], origin="agent", context=context)
print([each.name() for each in desk.verdicts(reply)])  # ['cleared', 'needs_approval']
```

Asked directly about several calls at once, as a single Decision, a `Rules` answers with the
**strictest** verdict of them: forbidden, then needs_approval, then cleared. That is what the
`verdict` helper above does when you pass it more than one call:

```python
print(verdict(desk, (read_ledger, {}), big_refund, context=context))  # needs_approval
print(verdict(desk, (read_ledger, {}), (delete_ledger, {})))  # forbidden
```

A rule sees one call. A policy that judges a call in the light of the rest of the reply ("at
most one refund per reply", "delete only if nothing is pushed in the same reply") is written
as a Decision of your own that reads `Consultation.reply()`, `reply_calls_to(tool)` and
`position()`; the
[reference agent page](../concepts/reference-agent.md#a-policy-that-reads-the-whole-reply)
shows one.

### Step 5: what the model has read, with `exposed` {#a-rule-that-reads-the-exposure}

A consultation also carries the asking actor's **exposure**: the untrusted sources its model
had read when it made the call, such as a tool whose results are text other people wrote
([Trust](../concepts/trust.md) explains how an actor records it). A rule's `exposed=` reads
it: `exposed=False` holds only while the exposure is empty, `exposed=True` only once it is
not, and `None`, the default, holds either way. The desk gains a tool that reads the
customer's messages, which declares its results untrusted; `StubTool`, a test tool from
`gvn.testing.fakes`, stands in for it:

```python
from gvn.testing.fakes import StubTool

read_inbox = StubTool(name="read_inbox", arguments=Record({}), namespace="refunds", untrusted=True)

careful_desk = (
    Rules(default="forbidden")
    .clear(read_ledger, read_inbox)
    .clear(refund, exposed=False)  # tried first: nothing from outside read yet
    .approve(refund)  # otherwise a person decides
)


def after_reading(policy: Rules, *calls: tuple[Tool, dict[str, typing.Any]]) -> str:
    consultation = Consultation.of(calls, origin="agent", exposure=[read_inbox])
    return policy.decide(consultation).name()


print(verdict(careful_desk, small_refund))  # cleared
print(after_reading(careful_desk, small_refund))  # needs_approval
```

The exposure says which sources the model had read, not which of them its arguments came
from: once the model has read the inbox, every refund it asks for goes to a person.
`exposed` and `when` combine: a rule holds when both do.

### What the methods take

- `Rules(default="forbidden")`: the verdict for a call no rule matches. Keep the default.
- `clear(*tools, when=None, exposed=None)`, `approve(*tools, when=None, exposed=None)`,
  `forbid(*tools, when=None, exposed=None)` add a rule for each tool (a Tool object; a
  string is a `TypeError`) and return a **new** Rules; the one they were called on is
  unchanged. `exposed` is `None`, `True` or `False` (anything else is a `TypeError`).
- A rule matches a call by its tool's identity. For one call, the rules for its tool are
  tried **in the order they were added**; the first that holds gives the verdict. A rule
  holds when its `exposed` and its `when` both hold (a rule with neither always holds).
- In a run, each call of a reply is judged on its own. `verdicts(consultation)` gives each
  call's verdict; deciding a consultation of several calls at once gives the **strictest**:
  forbidden, then needs_approval, then cleared.

## `when`

`when(call, context)` receives the `ToolCall` and a fresh copy of the run's trusted
[context](../concepts/run-context.md) (`{}` when there is none), and must return a bool;
anything else is a `TypeError`. The call's arguments come from a model: they are untrusted
and possibly malformed, so a predicate must not assume their shape, as `large` above checks
the type before comparing. Anything a predicate raises propagates, so the policy fails
closed.

## Merging the families

Each tool family's `rules(...)` takes the family's tools, the named tuple its `tools(...)`
built, and returns its recommended Rules for them. A harness that uses several families
merges them:

```python
import pathlib

from gvn_tools import files, git, shell
from gvn_tools.fakes import FakeCommands
from gvn_tools.workspace import Workspace

project = pathlib.Path("project")
project.mkdir()
workspace = Workspace(root=project.resolve())
file_tools = files.tools(workspace=workspace)
shell_tools = shell.tools(workspace=workspace, commands=FakeCommands(), programs=["pytest"])
git_tools = git.tools(workspace=workspace, commands=FakeCommands())

merged = (
    files.rules(file_tools)
    .merged(shell.rules(shell_tools, quiet=["pytest"]))
    .merged(git.rules(git_tools))
)
print(merged.default(), len(merged.entries()))  # forbidden 14
```

`merged(other)` holds the rules of both. It is a `ValueError` when the defaults differ, or
when a tool (one identity) has rules on both sides that are not identical (the same
verdicts, the same predicate objects, the same `exposed`, in the same order): the result would otherwise depend
on which side came first.

```python
try:
    files.rules(file_tools).merged(Rules().approve(file_tools.write_file))
except ValueError as error:
    print(error)  # both rules decide 'gvn_tools.files.write_file', differently
```

To change a family's verdict, build the rules for its tools yourself instead of merging two
opinions about the same tool. You pick each tool from the family's tuple by its short name.
For instance, a policy that lets the file tools read freely but asks a person before any
write:

```python
careful_files = (
    Rules()
    .clear(file_tools.read_file, file_tools.list_files, file_tools.search_files)
    .approve(file_tools.write_file, file_tools.edit_file)
)
write = (file_tools.write_file, {"path": "notes.txt", "text": "hi"})
print(verdict(careful_files.merged(shell.rules(shell_tools)), write))  # needs_approval
```

`entries()` lists the rules as `(tool, verdict, when or None, exposed or None)` in the order
added, each `tool` the Tool object the rule was given and `exposed` the rule's `True` or
`False`, and `default()` the default, for inspection and tests.

## Recap

- Start from `Rules()` (everything forbidden), then `clear`, `approve` and `forbid` tools,
  passed as objects; each call returns a new `Rules`. A string is a `TypeError`.
- A rule matches a call by its tool's identity, so a same-named tool from another package is
  not matched.
- A `when` condition narrows a rule, and `exposed` makes it hold only before (`False`) or
  after (`True`) the model has read untrusted content; rules for one tool are tried in the
  order added.
- Each call of a reply is judged on its own; merging refuses two different opinions about one
  tool.

**Next:** [Testing with the tools](testing.md).
