# Research: deep research

Deep research has the same parts as every
[domain harness](index.md#what-a-domain-harness-is-made-of). What is new here is the shape of
its plan: a stage that runs several agents side by side, and a loop that goes round a
bounded number of times.

| Part | In deep research |
|---|---|
| Plan | `ResearchRun`, a workflow: scope, gather (several researchers at once), synthesise, critique, and back to gather on gaps |
| Tools and policy | tools that read the library or record a decision; all cleared, nobody is asked |
| Ports | `Library`, read only |
| Brief and evaluation | a question and a depth (the most rounds); a good report cites only sources that were read |
| Launcher | runs it on a Governor |

**What you will learn:** how a harness runs several agents side by side, counts how many of
them succeeded, and goes round a loop a bounded number of times. You will run a two-round
study over a small in-memory library and read the report it produced.

**Read first:** [Customer service](service.md), the simplest harness, which this page builds
on; [Workflows](../concepts/workflows.md) (stages and fan-outs),
[Workflows in depth](../concepts/workflows-in-depth.md) (joins and loops) and
[Decisions](../concepts/decisions.md).

**Time:** about 20 minutes.

`research/deep_research` (module `gvn_domains.research.deep`) answers a question from a
library of sources, in bounded rounds.

## The problem

A question such as "Can a small town run on solar power all year?" needs several facts, each
from a different source. One agent can break the question up, several can look things up at
once, another can write a report and a critic can ask for another round on the gaps. Left
alone, that loop could run forever, and the report could cite sources nobody read.

## The harness at a glance

A run is a `ResearchRun` [workflow](../concepts/workflows.md), one stage per role, with a
real loop:

- `idle`: the run exists but has not started;
- `scoping`: an agent breaks the question into sub-questions;
- `gathering`: one researcher per sub-question, all at once;
- `synthesising`: a writer drafts a report from what was found;
- `critiquing`: a critic accepts the draft or names gaps, which sends the run back to
  `gathering`;
- `salvaging`: when gathering falls short, a writer writes up what there is;
- `reported`, `inconclusive` or `failed`: the run is over.

The plan as gvn renders it from the code: 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:

```text
   state         output        transitions
   critiquing    critique      accepted -> reported, exhausted -> inconclusive, revise -> gathering, unchecked -> inconclusive
*  failed        failed        -
   gathering     gather        gathered -> synthesising, nothing_to_research -> salvaging, scattered -> salvaging
>  idle          idle          started -> scoping
*  inconclusive  inconclusive  -
*  reported      reported      -
   salvaging     salvage       salvaged -> inconclusive, unsalvaged -> inconclusive
   scoping       scope         scoped -> gathering, scoping_failed -> failed
   synthesising  synthesise    draft_failed -> failed, drafted -> critiquing, redraft_failed -> inconclusive
otherwise: stay
```

```mermaid
stateDiagram-v2
    critiquing : emits critique
    failed : emits failed
    gathering : emits gather
    idle : emits idle
    inconclusive : emits inconclusive
    reported : emits reported
    salvaging : emits salvage
    scoping : emits scope
    synthesising : emits synthesise
    [*] --> idle
    critiquing --> reported : accepted
    critiquing --> inconclusive : exhausted
    critiquing --> gathering : revise
    critiquing --> inconclusive : unchecked
    gathering --> synthesising : gathered
    gathering --> salvaging : nothing_to_research
    gathering --> salvaging : scattered
    idle --> scoping : started
    salvaging --> inconclusive : salvaged
    salvaging --> inconclusive : unsalvaged
    scoping --> gathering : scoped
    scoping --> failed : scoping_failed
    synthesising --> failed : draft_failed
    synthesising --> critiquing : drafted
    synthesising --> inconclusive : redraft_failed
    failed --> [*]
    inconclusive --> [*]
    reported --> [*]
    note right of idle
        otherwise: stay
    end note
```

Two of these stages are what this page is about. `gathering` is a **fan-out**: one stage
that starts several child agents at once, here one researcher per sub-question. When they
have finished, a **join** (the rule that decides when a fan-out is over, and with what
result) counts how many succeeded. `critiquing` can send the run back to `gathering`: a real
cycle in the plan, which a **judge** (a [Decision](../concepts/decisions.md) over what the
critic did) bounds by counting rounds. The walk-through below shows both; the exact rule each
stage ends by is in [Each stage in detail](#each-stage-in-detail) at the end.

## Walking through a run

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

### 1. The outside world: a library

The harness needs one port, and only reads from it:

| Port | Methods |
|---|---|
| `Library` (read only) | `search(query)`: a list of `{"id", "title"}`, best first; `read(source)`: `{"id", "title", "text"}` |

This shelf holds three sources and finds those whose title shares a word with the query:

```python
from gvn_domains.research.deep import Library

SOURCES = {
    "S1": {"title": "Solar output in winter", "text": "Panels yield a fifth in winter."},
    "S2": {"title": "Battery storage costs", "text": "Storage costs halved since 2020."},
    "S3": {"title": "Grid demand peaks", "text": "Demand peaks on winter evenings."},
}


class Shelf(Library):
    async def search(self, query: str) -> list[dict[str, str]]:
        words = query.lower().split()
        return [
            {"id": source_id, "title": source["title"]}
            for source_id, source in SOURCES.items()
            if any(word in source["title"].lower() for word in words)
        ]

    async def read(self, source: str) -> dict[str, str]:
        return {"id": source, **SOURCES[source]}
```

### 2. Building the harness

A brief is `{"question": str, "depth": int}`, with `depth` from 1 to 3 (`MAX_DEPTH`): the
most rounds of critique the run may hold.

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

research = catalog().harness(path="research/deep_research", ports=Ports.of(Shelf()))
for identity in research.toolbox().identities():
    print(identity)
```

```text
gvn_domains.research.deep.accept
gvn_domains.research.deep.add_subquestion
gvn_domains.research.deep.read_source
gvn_domains.research.deep.reject
gvn_domains.research.deep.request_revision
gvn_domains.research.deep.search
```

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 also names each tool with a
constant (`SEARCH`, `READ_SOURCE`, `ADD_SUBQUESTION`, `ACCEPT`, `REQUEST_REVISION`,
`REJECT`, grouped as `RESEARCH_TOOLS`, `VERDICT_TOOLS` and `TOOLS`); the plan declares
`TOOLS` and the agents, policy and judges refer to the tools through the constants (see
[how a harness names its tools](index.md#how-a-harness-names-its-tools)).

### 3. What the model may do

Nothing leaves the system: every tool reads the library or records a decision. So the policy
clears the six tools (`search`, `read_source`, `add_subquestion`, `accept`,
`request_revision`, `reject`) and forbids anything else. No person is ever asked, and no
[run context](../concepts/run-context.md) is needed. You can ask the policy directly, with a
`Consultation`: the calls an agent wants to make, the identity of each call's tool, and
where they come from. The policy matches each call by its tool's identity. (In a run, the
policy is asked about each call of a reply on its own.)

```python
import typing

from gvn.harness.messages import ToolCall
from gvn.harness.tools import Consultation, Tool
from gvn.kernel.schema import Record
from gvn.testing.fakes import StubTool
from gvn_domains.research.deep import SEARCH


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="study/gathering.1.0"
    )
    return research.policy().decide(consultation).name()


send_email = StubTool("send_email", Record({}))  # a tool the harness does not have
print(verdict(SEARCH, {"query": "Moore machines"}))
print(verdict(send_email, {}))
```

```text
cleared
forbidden
```

### 4. A model to play every role

A `FunctionModel` stands in for the real model. Each agent is told its role by its
instructions, which the module exports (`SCOPE`, `RESEARCH`, `SYNTHESISE`, `CRITIQUE`), so
the function can tell the roles apart. First, two small helpers: one builds a reply that
calls tools, the other reads the results the agent has been given so far. They use the
message shapes from the [tutorials](../tutorials/first-agent.md): a `Reply` wraps one
`Message` from the model, which may carry `ToolCall`s; a message with the role `TOOL`
brings tool results back to the agent.

```python
from gvn.harness.messages import TOOL, Message
from gvn.harness.ports import Exchange, Reply


def calling(*calls: tuple[str, dict[str, typing.Any]]) -> Reply:
    """A reply that calls each (name, arguments) pair."""
    tool_calls = [
        ToolCall(call_id=f"c{number}", name=name, arguments=arguments)
        for number, (name, arguments) in enumerate(calls)
    ]
    return Reply(message=Message.assistant(text="", calls=tool_calls))


def saying(text: str) -> Reply:
    return Reply(message=Message.assistant(text=text))


def results_so_far(exchange: Exchange) -> list[typing.Any]:
    messages = exchange.messages()
    return [r.content() for m in messages if m.role() == TOOL for r in m.results()]
```

Now the roles. The scoper adds one sub-question. A researcher searches, reads the first hit
and answers citing its id. The writer joins every finding into a report. The critic asks for
one more round on grid demand in round 1, and accepts in round 2.

```python
from gvn_domains.research.deep import CRITIQUE, RESEARCH, SCOPE, SYNTHESISE


def study_model(exchange: Exchange) -> Reply:
    role, prompt = exchange.instructions(), exchange.messages()[0].text()
    found = results_so_far(exchange)
    if role == SCOPE:
        if found:
            return saying("Scoped.")
        return calling(("add_subquestion", {"text": "solar winter"}))
    if role == RESEARCH:
        if not found:
            question = prompt.split("Sub-question: ")[1]
            return calling(("search", {"query": question}))
        if "results" in found[-1]:
            return calling(("read_source", {"id": found[-1]["results"][0]["id"]}))
        return saying(f"{found[-1]['text']} [{found[-1]['id']}]")
    if role == SYNTHESISE:
        findings = [line for line in prompt.splitlines() if "(read: " in line]
        claims = [line.removeprefix("- ").split(" (read: ")[0] for line in findings]
        return saying("Report: " + " ".join(claims))
    if role == CRITIQUE and found:
        return saying("Checked.")
    if "Round 1 of" in prompt:
        return calling(("request_revision", {"gaps": ["grid demand peaks"]}))
    return calling(("accept", {}))
```

### 5. Starting a run that goes round twice

The brief asks for depth 2, so the critic may send the run back once.

```python
import asyncio

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

launcher = Launcher(
    harness=research,
    model=FunctionModel(respond=study_model),
    journal=MemoryJournal(),
    output=RecordingOutput(),
    clock=ManualClock(),
)
study_brief = {"question": "Can a small town run on solar power all year?", "depth": 2}
result = asyncio.run(launcher.start(run_id="study", brief=study_brief))
print(result.status(), result.outcome().state())
print(report(result.outcome()))
```

```text
finished State('reported')
Report: Panels yield a fifth in winter. [S1] Demand peaks on winter evenings. [S3]
```

Here is what happened, in order:

1. **Scoping.** The scoper called `add_subquestion` once, so the stage ended `scoped`.
2. **Gathering, round 1.** The stage is a fan-out: it starts one researcher per distinct
   sub-question, at most 4 (`MAX_QUESTIONS`), all at once. Sizes come from data, here one
   researcher. A researcher succeeds when it completed having read at least one source.
3. **The join.** A `Quorum` counts the researchers' verdicts: `gathered` when at least half
   succeed. The join waits for every researcher, so slow ones are not cut off, and stops
   early only once half can no longer succeed. It counts with `AtLeast(0.5)` rather than
   `Majority()`: on an even number of researchers, half is enough.
4. **Synthesising and critiquing.** The writer drafted a report from S1. The critic, in round
   1 of 2, called `request_revision` naming one gap, and its judge answered `revise`, so the
   run went back to `gathering`.
5. **Round 2.** One researcher per gap the critic named found S3. Every round reads what all
   earlier rounds found through `memo.history("gathering")`, so the new draft holds both
   findings. The critic accepted, and the run ended `reported`.

The **bound** lives in the critique judge: it answers `revise` only while
`memo.visits("critiquing")` is below the brief's depth, and a revision asked for in the last
round is `exhausted`. The critic of the last round is offered `reject` instead of
`request_revision`, so it is told plainly that no round is left. The judge is a
[Decision](../concepts/decisions.md): a finite,
declared set of outcomes, every one of which the plan must route, so `exhausted` is a
transition the verifier sees rather than a check hidden in code.

The workflow's outcome keeps every visit of every stage. `Report` (from
`gvn.harness.workflow`) is a reader over that outcome; `history(stage)` gives one entry per
visit of the stage, each holding its children's results, here one
researcher in each of the two gatherings:

```python
from gvn.harness.workflow import Report

print([len(visit) for visit in Report(result.outcome()).history("gathering")])
```

```text
[1, 1]
```

`report(outcome)` returns the best report a finished run holds, whatever its final state:
the salvaged report when gathering fell short, else the latest draft. `interrupted` and
`resumed` are relayed to every active agent (see
[Humans and interruption](../concepts/human-in-the-loop.md)).

### 6. Grading the run

The evaluation has two checks of its own beside the usual ones: the run finishes
`reported`, nothing is rejected, it takes at most 120 events, it held **at most `depth`
critiques** (`WithinDepth`), and a reported run's report **cites sources, and only sources a
researcher read** (`CitesWhatWasRead`, read from the outcome's history).

```python
grade = asyncio.run(launcher.grade(run_id="study"))
print(grade.passed())
```

```text
True
```

## Each stage in detail

How each stage ends, in the plan's own terms. `memo` is the workflow's
[`Memo`](../concepts/workflows.md), its read-only record of every finished stage;
`memo.visits("critiquing")` counts how many times `critiquing` has run. `Quorum`, `AtLeast`
and a `FanOut`'s `empty` symbol are explained in
[Workflows in depth](../concepts/workflows-in-depth.md#joins-when-is-a-fan-out-over) and
[Workflows](../concepts/workflows.md).

| Stage | Agents and tools | How it ends |
|---|---|---|
| `scoping` | `add_subquestion` | `scoped`, or `scoping_failed` |
| `gathering` | one researcher per sub-question (first visit) or per gap the last critic named (later visits), at once: `search`, `read_source` | `Quorum(AtLeast(0.5), ..., wait=True)`: `gathered` when at least half the researchers succeed, once every researcher has finished; `scattered` as soon as that has become impossible; with nobody to start, the `FanOut`'s `empty` symbol `nothing_to_research` ends the stage at once |
| `synthesising` | a writer | `drafted`; `draft_failed` on the first round; `redraft_failed` on a later round, where an earlier draft exists |
| `critiquing` | `accept`, and `request_revision` while rounds remain, else `reject` | a judge: `accepted`; `revise` while `memo.visits("critiquing")` is below the brief's depth; `exhausted` when a revision is asked for in the last round, or the critic rejected the draft; `unchecked` when the critic failed or gave no verdict |
| `salvaging` | a writer | `salvaged` or `unsalvaged`, both `inconclusive`: what there is is written up |

## What is enforced before any effect

There are no effects outside the run: the library is only read. What the harness enforces
is the shape of the work. The depth bound lives in the critique judge, which the machine
must route, and the citation rule is checked on every recorded run.

## What this harness uses from gvn

The gather stage joins with gvn's counting join: `Quorum` with `AtLeast` and `wait`. The
[domains overview](index.md#what-the-harnesses-use-from-gvn) lists the parts of gvn the harnesses use.

## What the citation check covers

Citations are checked against what was read: a report that cites a source a researcher read
passes. The harness's own tests are in gvn's repository, in
`packages/gvn-domains/tests/test_dom_research_deep.py`.

## Recap

- A fan-out starts one agent per item the data names; a `Quorum` decides when enough of them
  succeeded.
- A loop is a real cycle in the plan, bounded by a judge that counts visits.
- The workflow's outcome keeps every round, so later rounds and the evaluation can read
  earlier ones.

**Next:** [Software](software.md), where one plan serves several technology stacks and a
fleet campaign hosts whole builds as its stages.
