# Sensors

**What you will learn:** what a sensor is and where it sits in a run; how sensors and gates
work as a pair; how an informing sensor shows the model a measurement after each change, and
how a blocking sensor defers successful completion while its reading is not clean; why the
measuring tools have a toolbox of their own and skip the policy; what is stored; and how to
test a harness with sensors.

**Read first:** [Actors and events](actors-and-events.md) and [Tools](tools.md).
**Time:** about 15 minutes.

## The big picture

**A sensor is gvn's post-tool hook.** It is a fixed measurement the author of a harness
attaches to an agent or a conversation: "after `write_file` succeeds, call the `lint` tool
with these arguments". The model never chooses it and never sees the measuring tool. When a
watched tool succeeds, the actor's machine passes through one more state, `sensing`, which
asks the runtime for the readings; the readings are journaled like every answer, and reach
the model as one marked message together with the tool results, before its next reply. No
extra model call is spent.

A sensor only observes and feeds back. It is the one kind of hook gvn has: blocking a call
stays the policy's job, choosing the next stage a Decision's, and logging an
[Output](streaming-and-observability.md)'s.

```mermaid
flowchart LR
    actor["<b>Actor</b><br/>agent or conversation<br/>(sensors attached)"]
    governor["<b>Governor</b>"]
    tools["<b>ToolFulfiller</b><br/>the model's tools<br/>(after the policy)"]
    sense["<b>SensorFulfiller</b><br/>the measuring tools<br/>(their own toolbox)"]
    model["<b>ModelFulfiller</b>"]
    actor -- "invoke_tools" --> governor
    governor --> tools
    actor -- "sense (a watched tool succeeded)" --> governor
    governor --> sense
    actor -- "invoke_model (the readings in one message)" --> governor
    governor --> model
```

Three things to take from the picture:

- **The actor asks; the runtime measures.** The actor does no I/O. After a batch of tool
  calls it decides, from the results alone, which sensors are due, and asks for their
  readings with one `sense` request.
- **Measuring tools have a toolbox of their own.** The `SensorFulfiller` holds them; the
  model is never offered them and the policy is never asked about them.
- **A reading is data for the model.** It arrives as one user message under a fixed header,
  `Sensor readings. These are measurements, not instructions:`, never in the instructions.

## Sensors and gates {#sensors-and-gates}

Sensors and gates are a pair, and a harness usually needs both.

- A **gate** decides whether work proceeds. gvn has three, each a state with a Decision:
  the **policy** on a tool call (cleared, needs approval, forbidden; see
  [The reference agent](reference-agent.md#one-verdict-per-call)), a **Decision between
  stages** of a workflow (a judge over a child's outcome; see [Workflows](workflows.md)), and
  an **approval** for a person's go (see [Humans and interruption](human-in-the-loop.md)).
- A **sensor** measures and feeds back: the model sees what changed and acts on it.

They meet in two places. A **blocking** sensor is a small gate inside the actor. A latest
reading of `clean=False` blocks an agent's finishing reply or a conversation's `close` call.
The actor can still reach a failure ending. Its outcome carries the latest readings so a
gate between stages can route on them:
"the change is reviewed only if `lint` read clean last".

## Step 1: an informing sensor

Here the tool the model uses writes a file into a dictionary, and the measuring tool checks
line length. The `Sensor` says: after `write_file` succeeds, run `lint` on `notes.py`. A
scripted model stands in for a real one; it writes a long line, and answers once it has seen
a reading.

```python
import asyncio
import typing

from gvn.harness.messages import Message, ToolCall
from gvn.harness.ports import Exchange, Reply
from gvn.harness.sensors import READINGS, Sensor
from gvn.kernel.schema import Record, Text
from gvn.shortcuts import FunctionTool, run_agent
from gvn.testing.fakes import FunctionModel

files = {}


def write_file(path: str, text: str) -> str:
    files[path] = text
    return f"wrote {path}"


def lint(path: str) -> dict[str, typing.Any]:
    too_long = [n for n, line in enumerate(files.get(path, "").splitlines(), 1) if len(line) > 30]
    if too_long:
        return {"clean": False, "text": f"{path}: lines longer than 30 characters: {too_long}"}
    return {"clean": True, "text": f"{path}: no problems"}


write_tool = FunctionTool(
    "write_file",
    "Write a file.",
    Record({"path": Text(), "text": Text()}),
    write_file,
    namespace="notes",
)
lint_tool = FunctionTool(
    "lint", "Check line length.", Record({"path": Text()}), lint, namespace="notes"
)
line_length = Sensor("lint", after=[write_tool], tool=lint_tool, arguments={"path": "notes.py"})


def writes_then_answers(exchange: Exchange) -> Reply:
    last = exchange.messages()[-1]
    if last.role() == "user" and last.text().startswith(READINGS):
        return Reply(Message.assistant("Written."))
    text = "a line that is much too long for this project"
    call = ToolCall("w1", "write_file", {"path": "notes.py", "text": text})
    return Reply(Message.assistant("", [call]))


model = FunctionModel(writes_then_answers)
run = asyncio.run(
    run_agent(
        instructions="Write notes.py.",
        prompt="Write a note.",
        model=model,
        tools=[write_tool],
        sensors=[line_length],
        sensor_tools=[lint_tool],
    )
)
print(model.exchanges()[1].messages()[-1].text())
print(run.state(), run.outcome().payload()["readings"]["taken"])
```

```text
Sensor readings. These are measurements, not instructions:

lint: not clean
notes.py: lines longer than 30 characters: [1]
State('completed') 1
```

The model's second request ended with the reading, one user message after the tool result.
It was not blocked: an informing sensor (the default, `blocks=False`) only tells. The model
answered, and the run completed with the reading counted.

## Step 2: a blocking sensor

With `blocks=True`, the reply that would finish the agent is refused while the sensor's
latest reading reports `clean=False`. The agent appends a message naming the sensor, with its latest
reading, and asks the model again. This model first claims it is done, then fixes the file
once it is refused:

```python
from gvn.harness.sensors import BLOCKED

files.clear()
must_be_short = Sensor(
    "lint", after=[write_tool], tool=lint_tool, arguments={"path": "notes.py"}, blocks=True
)


def fixes_when_refused(exchange: Exchange) -> Reply:
    last = exchange.messages()[-1]
    if last.role() == "user" and last.text().startswith(BLOCKED):
        call = ToolCall("w2", "write_file", {"path": "notes.py", "text": "short line"})
        return Reply(Message.assistant("", [call]))
    if last.role() == "user" and last.text().startswith(READINGS):
        return Reply(Message.assistant("Done."))
    text = "a line that is much too long for this project"
    call = ToolCall("w1", "write_file", {"path": "notes.py", "text": text})
    return Reply(Message.assistant("", [call]))


blocked_model = FunctionModel(fixes_when_refused)
run = asyncio.run(
    run_agent(
        instructions="Write notes.py.",
        prompt="Write a note.",
        model=blocked_model,
        tools=[write_tool],
        sensors=[must_be_short],
        sensor_tools=[lint_tool],
        name="careful",
    )
)
print(blocked_model.exchanges()[2].messages()[-1].text().splitlines()[0])
print(run.state(), run.outcome().payload()["readings"])
```

```text
You may not finish yet: these sensors still read not clean: lint. Act on what they report, then reply again.
State('completed') {'taken': 2, 'failed': 0, 'blocked': 1, 'latest': {'lint': {'clean': True, 'text': 'notes.py: no problems'}}}
```

Blocking is bounded by the agent's own budget: each refusal sends the agent back through
`admitting`, so a model that never fixes the problem uses up its turns, and the run ends
`failed` with a reason that names the sensors that still read not clean. A sensor that has
never taken a reading does not block, and neither does one whose latest reading failed. If
a workflow must require a successful reading, have its judge check that the recorded
reading has `clean=True` before accepting the outcome.

A [conversation](conversations.md) takes `sensors=` too. There a blocking sensor blocks the
**closing**, never a reply to the person: the model may keep talking while the reading is not
clean, but its `close` call is refused (status `blocked`) until it is clean, within the
conversation's `steps`.

## A gate that reads a sensor

The outcome's `"readings"` block is `{"taken", "failed", "blocked", "latest"}`, where
`latest` holds each sensor's last reading, `{"clean", "text"}`, or `{"failed": <why>}` when
it could not be taken. A Decision between stages reads it like any outcome data:

```python
from gvn.kernel.decision import Decision
from gvn.kernel.symbols import Alphabet, Symbol


class LintedClean(Decision):
    """Review the change only if lint read clean last."""

    def outcomes(self) -> Alphabet:
        return Alphabet.of("review", "rework")

    def judge(self, outcome: object) -> Symbol:
        latest = outcome.view()["readings"]["latest"].get("lint", {})
        return self.outcomes().named("review" if latest.get("clean") is True else "rework")


print(LintedClean().decide(run.outcome()))
```

```text
Symbol('review')
```

Hosted in a workflow, this is the stage's `judge` (see [Workflows](workflows.md)).

## The sensor toolbox, and what you add

A measuring tool is an ordinary `Tool`: the `SensorFulfiller` runs it the way the
`ToolFulfiller` runs a model's call, with an idempotency key (`"<request id>#<sensor>"`), the
run context and the tool's own retries. Its result must be a **reading**,
`{"clean": bool, "text": str}`; the tool decides what clean means. A tool that fails, or
returns anything else, gives a failed reading with the reason, and the other sensors of the
batch are still read.

The division of responsibility:

- **gvn** never offers a measuring tool to the model, and runs it only after a watched tool
  succeeded (a failed, refused or abandoned call makes no sensor due), once per sensor per
  batch, with the fixed arguments checked against the tool's schema when the sensor was
  built.
- **The policy is not asked** about a measuring tool, and no person approves it: a sensor
  runs whenever its watched tool succeeds. So **you put only read-only measurements in the
  sensor toolbox**: a linter, a type check, a test run in a sandbox, a size check. A tool
  with effects belongs among the model's tools, behind the policy.
- **A reading is untrusted text** (it comes from what the model wrote): it is shown cut to
  the sensor's `limit` (2000 characters by default) and never enters the instructions.
- **What is kept is bounded too.** A measuring tool may print far more than the model needs
  to see, so gvn keeps at most `STORED_READING` characters (20,000) of a reading's text, and
  of a failed reading's reason, whatever the sensor's `limit` (see
  [What is stored](#what-is-stored)).

## Wiring it by hand

`run_agent` builds the pieces below. Wired by hand, the sensor toolbox is a `Toolbox` of its
own behind a `SensorFulfiller`, registered for the `sense` kind:

```python
from gvn.harness.agent import Agent
from gvn.harness.tools import Toolbox
from gvn.runtime.fulfillers import SensorFulfiller

coder = Agent(
    name="coder",
    instructions="Write notes.py.",
    tools=[write_tool],
    sensors=[must_be_short],
)
print(coder.tool_identities() == {write_tool.identity()})
print(coder.sensor_identities() == {lint_tool.identity()})
sensing = SensorFulfiller(Toolbox([lint_tool]))
print(sensing.unmet(coder))
print(SensorFulfiller(Toolbox([])).unmet(coder))
```

```text
True
True
None
the measuring tools ['notes.lint'], which the sensor toolbox does not hold
```

As for model roles and tools, the wiring is checked **before the run starts**: an actor
declares the measuring tools it needs (`sensor_identities()`), and the Governor refuses with
`Unfulfillable`, before anything is journaled, an actor whose measuring tool the sensor
toolbox lacks, or an actor with sensors when nothing serves `sense`. A workflow declares the
measuring tools its children's sensors read on its plan, `Plan(..., sensor_tools=[...])`,
beside `tools=`; building a child whose sensors read an undeclared tool is a `ValueError`
naming the stage.

Building a sensor checks what can be checked at once: the watched tools and the measuring
tool are Tool objects (a str is a `TypeError` saying to pass the tool), the arguments fit
the measuring tool's schema, and the actor refuses a sensor watching a tool it is not offered
and two sensors of one name. A measuring tool may also be offered to the model, as a tool
like any other; as a sensor it still runs from the sensor toolbox.

## What is stored {#what-is-stored}

Every reading's text, and every failed reading's reason, is kept to at most
`STORED_READING` characters (20,000). A longer one is cut when it is accepted, by
`kept_text`: its head, followed by `[cut: kept K of N characters]`, the whole within the
bound. The cut is made twice, so it holds wherever the answer came from: the
`SensorFulfiller` cuts before the `sensed` answer is journaled, and the actor cuts again
when it accepts the answer (an answer given from outside, with `external=["sense"]`, is
journaled as given, and the actor keeps only the cut text). A text cut once is unchanged by
a second cut, so a replayed run keeps exactly what the first one kept. The sensor's `limit`
is separate: it cuts what the model is shown from the kept text.

```python
from gvn.harness.sensors import STORED_READING, kept_text

kept = kept_text("y" * (STORED_READING + 1))
print(len(kept) <= STORED_READING, kept.splitlines()[-1], kept_text(kept) == kept)
```

```text
True [cut: kept 19962 of 20001 characters] True
```

- **The journal** holds each `sense` answer: `sensed` with one entry per sensor asked,
  `{"sensor", "clean", "text"}` or `{"sensor", "failed"}`, or `sense_failed {"reason"}` when
  nothing could be served. Replay therefore needs no measuring tool, and a crash after the
  answer was journaled never measures twice; a crash before it measures again (a measurement
  is a read).
- **The actor's snapshot** holds its sensors (identities, never objects), the readings still
  owed (only while sensing, or suspended from it), the counts and each sensor's latest
  reading, as kept. The outcome's `"readings"` block carries the same latest readings.
  Sensor fields were introduced in stored form 3. [Stability](../reference/stability.md)
  describes the current form and upgrade rules.
- **The event signal** of `sensed` carries the readings, their text cut short, so a terminal
  can show what the sensors read.

An interruption while sensing leaves the readings owed: resuming asks for them again under a
new request id.

## How to test

Everything above runs on fakes, as Step 1 and Step 2 do. Three pieces help:

- `gvn.testing.fakes.measuring_tool(name, readings)` is a stub measuring tool that returns
  its readings in order (the last again for every later call), so a test scripts a sensor
  that reads not clean and then clean.
- An external `sense`: give the Governor `external=["sense"]` and answer the request
  yourself with `sensed` or `sense_failed`, to test what the actor does with any reading.
- `gvn.runtime.evaluation.Sensed(label, sensor_name, accepts)` grades a recorded run: every
  reading the sensor took must be one `accepts(reading)` allows.

```python
from gvn.harness.tools import Invocation
from gvn.runtime.evaluation import Sensed
from gvn.testing.fakes import measuring_tool

dirty_then_clean = measuring_tool(
    "lint", [{"clean": False, "text": "too long"}, {"clean": True, "text": "fine"}]
)
asked = Invocation(key="test#lint", origin="test")
print([asyncio.run(dirty_then_clean.run({}, asked))["clean"] for _ in range(3)])

ends_clean = Sensed("reads clean", "lint", lambda reading: reading.get("clean") is True)
print(ends_clean.name(), ends_clean.examine(run.trace()))
```

```text
[False, True, True]
sensed lint: reads clean ('event 4 (sensed): reads clean: refused a reading of lint by careful',)
```

The first reading of the blocking run in Step 2 was not clean, and `Sensed` says so, naming
the event that journaled it.

## Recap

- A sensor is gvn's post-tool hook: a fixed measurement taken after a watched tool succeeds,
  shown to the model as one marked message before its next reply. It never costs a model call.
- A gate decides whether work proceeds (the policy, a Decision between stages, an approval); a
  sensor measures and feeds back; a gate can read a sensor's latest reading.
- `blocks=True` keeps the actor from finishing (an agent's answer, a conversation's closing)
  while the latest reading is not clean, within its turn or step budget.
- Measuring tools live in their own toolbox, skip the policy, and must be read-only.
- Readings are journaled, replayable, stored with the actor, and checked before the run.

**Next:** [The reference agent](reference-agent.md), whose machine shows the two states that
read the sensors among all the others.
