# Asking a person

**What you will learn:** how a run asks a person a question and waits for an answer with
content, how the answer is checked, and which parts of it you may trust.

**Read first:** [Humans and interruption](human-in-the-loop.md). **Time:** about 10 minutes.

## Where this sits

This page is about the person in the [loop that runs](index.md#picture-1-the-loop-that-runs)
again, this time asked a question rather than for a yes or no. The asking is done by an
**actor** of its own, the `Inquiry`, from the harness layer. Like an approval, its request is
answered from outside. The Governor returns a waiting result, and the run's recorded
history lets it recover the pending request. The answer comes back later as an event.

## The problem: yes or no is not enough

[Approval](human-in-the-loop.md) is one kind of question a run can put to a person: yes or
no. Often a run needs *content*: a lawyer's decision on a clause, a learner's answer, a
customer's account number.

Picture a contract negotiation. The run reaches clause 4.2, a liability cap, and must ask the
lawyer: counter, concede, or walk away? The lawyer may answer next week, from another
process, with a free-text note attached.

`gvn.harness.inquiry.Inquiry` is the actor for that. It asks one **audience** one question and
waits, as long as it takes, for the answer.

## Step 1: build the question

An Inquiry is built with the name of the run step, who is asked, and optionally the choices
the answer must pick from:

```python
from gvn.harness.events import Event
from gvn.harness.inquiry import Inquiry

ask_lawyer = Inquiry(
    name="deal/ask",
    audience="lawyer",
    choices=("counter", "concede", "walk_away"),
    limit=500,
    context={"contract": "MSA-9", "clause": "4.2"},
)
```

- `audience`: who is asked, a name such as `lawyer` or `learner`. The channel that delivers
  `request_input` decides what it means.
- `choices`: when given, the answer must pick one of them.
- `limit`: the longest answer text accepted, or `None`.
- `context`: trusted data shown with the question (see [run context](run-context.md)).

The question itself arrives with the `started` event. Handling it shows the request the
inquiry makes:

```python
step = ask_lawyer.handle(Event("started", {"question": "Accept a 2x liability cap?"}))
(request,) = step.requests()
print(request.kind().name(), request.payload()["audience"], request.payload()["choices"])
```

```text
request_input lawyer ['counter', 'concede', 'walk_away']
```

## Step 2: the machine

The Inquiry is a small machine. It asks, then either gets an answer or is withdrawn; it can
be interrupted and resumed like any actor.

```mermaid
stateDiagram-v2
    [*] --> idle
    idle --> asking : started
    asking --> answered : answered
    asking --> withdrawn : withdrawn
    asking --> suspended : interrupted
    suspended --> asking : resumed
    answered --> [*]
    withdrawn --> [*]
```

While `asking`, the inquiry wants one `request_input` request with payload
`{"audience", "question", "choices", "limit", "context"}`. No fulfiller runs it: declare it
external, and the Governor **parks** the run on it: it records that the run is waiting and
returns, with no process held while the person thinks.

## Step 3: wait, then answer from another process

Here one Governor parks the question and another recovers it from the same in-memory
journal. To do this across processes, use a [persistent journal](../guides/running-as-a-service.md#step-1-a-journal-every-process-can-reach):

```python
import asyncio

from gvn.runtime.governor import Governor, Result
from gvn.runtime.recovery import Recovery
from gvn.testing.fakes import ManualClock, MemoryJournal, RecordingOutput

journal = MemoryJournal()


def process() -> Governor:
    return Governor(
        fulfillers={},
        external=["request_input"],
        journal=journal,
        output=RecordingOutput(),
        clock=ManualClock(),
    )


question = Event("started", {"question": "Accept a 2x liability cap?"})
first_question = Inquiry(name="deal/q1", audience="lawyer", choices=("counter", "concede"))
waiting = asyncio.run(process().deliver(actor=first_question, event=question))
print(waiting.status(), [pending.kind().name() for pending in waiting.pending()])
```

```text
waiting ['request_input']
```

Now the answer. `Recovery` rebuilds the inquiry from the journal. `Governor.answer`
checks the pending request and addresses the event to the actor that asked:

```python
async def later() -> Result:
    revived = await Recovery(journal=journal).recover(run_id="deal/q1", actor_class=Inquiry)
    (pending,) = revived.pending()
    answer = {"text": "Counter at 1.5x.", "choice": "counter", "by": "ana@legal"}
    return await process().answer(actor=revived, request=pending, event=Event("answered", answer))


print(asyncio.run(later()).outcome().payload())
```

```text
{'audience': 'lawyer', 'question': 'Accept a 2x liability cap?', 'text': 'Counter at 1.5x.', 'choice': 'counter', 'by': 'ana@legal', 'data': None}
```

The answer is `{"text", "choice", "by", "data"}`:

- `choice` is required exactly when there are choices;
- `by` is the text the channel wrote for who answered, recorded as given (who answered, as
  authenticated, is `answered_by`, [below](#who-answered));
- `data` holds structured fields the channel adds.

An answer that does not fit (a missing or unknown choice, a text over the limit, an unknown
field) is a `ValueError` and the inquiry keeps waiting. `withdrawn` (with `None` or
`{"by": ...}`) ends it without an answer.

## What to trust

`text`, `data` and `by` come from outside the system. They are **untrusted**: your code (in a [workflow](workflows.md), later, the plan's code)
must never copy them into a run context, nor let them pick a tool's target or the arguments a
policy relies on. `choice` is the one part meant to route a run, and only through a
[Decision](decisions.md) whose outcomes are the choices (in a workflow, such a Decision is
the stage's *judge*):

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

ROUTES = Alphabet.of("counter", "concede", "walk_away")


class LawyersCall(Decision):
    def outcomes(self) -> Alphabet:
        return ROUTES

    def judge(self, outcome: object) -> Symbol:
        return ROUTES.named(outcome.payload()["choice"])


ask_lawyer.handle(Event("answered", {"text": "Too risky for us.", "choice": "walk_away"}))
print(LawyersCall().decide(ask_lawyer.outcome()))
```

```text
Symbol('walk_away')
```

The Decision reads only `choice`, which the Inquiry has already checked against the finite
set of choices. The free text never decides where the run goes.

## Who answered {#who-answered}

The payload's `"by"` is whatever the channel wrote into the answer. Who answered, as the
deployment knows it, comes another way: the **entry point** that received the answer (a web
handler, a chat integration) has authenticated the person, and passes what it vouches for as
`Governor.answer(..., by=principal)`, a `gvn.harness.events.Principal(subject, issuer,
claims)`. The Governor stamps the principal on the answering event and journals it with the
event, and the Inquiry keeps it in its outcome as `"answered_by"`, beside the payload's `"by"`:

```python
from gvn.harness.events import Principal

ana = Principal("ana@legal.example", issuer="corp-sso", claims={"groups": ["legal"]})


async def answered_by_ana() -> Result:
    second_question = Inquiry(name="deal/q2", audience="lawyer", choices=("counter", "concede"))
    (pending,) = (await process().deliver(actor=second_question, event=question)).pending()
    answer = {"text": "Concede.", "choice": "concede", "by": "Ana from legal"}
    return await process().answer(
        actor=second_question, request=pending, event=Event("answered", answer), by=ana
    )


outcome = asyncio.run(answered_by_ana()).outcome().payload()
print(outcome["by"])
print(outcome["answered_by"])
```

```text
Ana from legal
{'subject': 'ana@legal.example', 'issuer': 'corp-sso', 'claims': {'groups': ['legal']}}
```

`"by"` is untrusted text; `"answered_by"` is trusted, because it comes from the entry point
and never from the answer's payload. A Governor built with `entitlement=` also decides
whether that principal may answer the question at all. [Trust](trust.md) covers the
principal and the entitlement.

## In a harness

The [Launcher](../domains/index.md#the-launcher) (`gvn.runtime.launching`, the ready-made wiring between
a harness and a Governor, which starts, answers and recovers runs) treats `request_input` as
external and delivers an answer with `Launcher.reply(run_id, request, event)`, which goes
through `Governor.answer`: an answer to a request the run is not waiting on is refused, with
nothing journaled. The [legal](../domains/legal.md), [education](../domains/education.md) and
[finance](../domains/finance.md) harnesses park on inquiries this way.

## Recap

- An `Inquiry` asks one audience one question and waits for an answer with content.
- Its `request_input` request is external: the Governor parks the run on it.
- The answer is `{"text", "choice", "by", "data"}`, checked against `choices` and `limit`.
- Only `choice` may route a run, through a Decision; `text`, `data` and `by` are untrusted.
- Who answered, as the entry point vouches for it, is `answered_by`, from
  `Governor.answer(..., by=)`.

**Next:** [Errands](errands.md), tool calls fixed by code and made safely, with no model.
