# Security: threat remediation

Threat remediation has the same parts as every
[domain harness](index.md#what-a-domain-harness-is-made-of). What is new here is that some
stages run no model at all, and that the [run context](../reference/glossary.md#run-context)
(the trusted data the tools and policy read, which the model never sees) grows as the run
learns, narrowing what each later stage may touch.

| Part | In threat remediation |
|---|---|
| Plan | `RemediationRun`, a workflow: triage, investigate, plan, contain, verify, or escalate to a person |
| Tools and policy | telemetry reads, classifications and proposals, four containment actions, paging; containment needs a person, and everything is held to the alert's scope |
| Ports | `Telemetry` (read only), `Containment` (the actions) and `Oncall` (the pager) |
| Brief and evaluation | the alert; a good run ends contained, dismissed or escalated, and nothing is contained without approval |
| Launcher | runs it on a Governor and passes the approver's answer in |

**What you will learn:** how a harness narrows what a model may touch as a run learns more,
and hands every fixed, code-determined step to an errand instead of a model. You will run an
alert from triage to containment, approve the containment, and see the policy refuse calls
outside the alert.

**Read first:** [Research](research.md) for fan-outs and joins, and
[Customer service](service.md) for approvals; [Run context](../concepts/run-context.md),
[Errands](../concepts/errands.md) and [Humans and interruption](../concepts/human-in-the-loop.md).

**Time:** about 25 minutes.

`security/threat_remediation` (module `gvn_domains.security.remediation`) responds to a
security alert on the organisation's own systems: triage it, investigate the hosts it names,
plan a containment, contain with a person's approval, verify, or hand the incident to the
on-call responder.

It is a **defensive** harness. Its tools only read telemetry, record the agents'
classifications and proposals, apply one of four containment actions to the organisation's
own assets (each needing a person's approval), and page the on-call responder. It holds no
exploit code and no attack tooling.

## The problem

An alert says a host is beaconing out. A model is useful to judge whether it is real, read
the host's events and propose what to contain. But a confused model must not isolate the
wrong machine, disable an account the evidence never mentioned, or act without a person's
yes; and when anything goes wrong, a person must take over.

## The harness at a glance

A run is a `RemediationRun` [workflow](../concepts/workflows.md). The judgement steps
(triage, investigation, planning) host agents; the steps fully determined by code and trusted
data host [errands](../concepts/errands.md) (a batch of tool calls fixed by code, with no
model), so no model can add an off-plan action:

- `triaging`: an agent classifies the alert as an incident or a false positive;
- `investigating`: one agent per alert host, all at once, reads telemetry;
- `planning`: an agent proposes containment actions;
- `containing`: an errand applies the approved plan, after a person approves;
- `verifying`: an errand reads every alert host's status;
- `escalating`: an errand pages the on-call responder;
- `contained`, `dismissed`, `escalated` 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
*  contained      contained    -
   containing     contain      applied -> verifying, containment_errored -> escalating, not_applied -> escalating, not_approved -> escalating
*  dismissed      dismissed    -
*  escalated      escalated    -
   escalating     escalate     not_paged -> failed, paged -> escalated
*  failed         failed       -
>  idle           idle         started -> triaging
   investigating  investigate  investigated -> planning, investigation_failed -> escalating
   planning       plan         plan_empty -> escalating, plan_out_of_scope -> escalating, plan_ready -> containing, planning_failed -> escalating
   triaging       triage       false_positive -> dismissed, incident -> investigating, triage_failed -> escalating
   verifying      verify       still_active -> escalating, verification_failed -> escalating, verified -> contained
otherwise: stay
```

```mermaid
stateDiagram-v2
    contained : emits contained
    containing : emits contain
    dismissed : emits dismissed
    escalated : emits escalated
    escalating : emits escalate
    failed : emits failed
    idle : emits idle
    investigating : emits investigate
    planning : emits plan
    triaging : emits triage
    verifying : emits verify
    [*] --> idle
    containing --> verifying : applied
    containing --> escalating : containment_errored
    containing --> escalating : not_applied
    containing --> escalating : not_approved
    escalating --> failed : not_paged
    escalating --> escalated : paged
    idle --> triaging : started
    investigating --> planning : investigated
    investigating --> escalating : investigation_failed
    planning --> escalating : plan_empty
    planning --> escalating : plan_out_of_scope
    planning --> containing : plan_ready
    planning --> escalating : planning_failed
    triaging --> dismissed : false_positive
    triaging --> investigating : incident
    triaging --> escalating : triage_failed
    verifying --> escalating : still_active
    verifying --> escalating : verification_failed
    verifying --> contained : verified
    contained --> [*]
    dismissed --> [*]
    escalated --> [*]
    failed --> [*]
    note right of idle
        otherwise: stay
    end note
```

Two stages need a closer look, and the walk-through shows both: `investigating` is a
**fan-out** (one investigator agent per alert host, all at once) that ends when all of them
have; `containing` is an errand that applies only the plan a judge accepted, after a person
approves. The exact rule each stage ends by is in
[Each stage in detail](#each-stage-in-detail).

Every way of not finishing the job safely leads to `escalating`: a person takes over. The
hand-off lists each containment attempt's status, so the responder knows whether a
person declined or a call failed. `interrupted` and `resumed` are relayed to the working
agents.

## Walking through a run

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

### 1. The outside world: three ports

| Port | Methods |
|---|---|
| `Telemetry` (read only) | `events(host)`, `processes(host)`, `indicator(value)`, `status(host)` |
| `Containment` | `isolate_host(host, key)`, `disable_account(account, key)`, `block_indicator(indicator, key)`, `revoke_sessions(account, key)`; each acts once per key |
| `Oncall` | `page(alert_id, summary, key)`: one page per key |

The telemetry below reports a dropper on `web-1`, run by the account `svc-web` and talking to
`evil.example`. The firewall records what it did; a real one must act once per `key`.

```python
import typing

from gvn_domains.security.remediation import Containment, Oncall, Telemetry


class WebTelemetry(Telemetry):
    async def events(self, host: str) -> list[dict[str, typing.Any]]:
        dropper = {"kind": "malware", "detail": "a dropper ran from /tmp"}
        return [{**dropper, "accounts": ["svc-web"], "indicators": ["evil.example"]}]

    async def processes(self, host: str) -> list[dict[str, typing.Any]]:
        return [{"pid": 4242, "name": "dropper", "account": "svc-web"}]

    async def indicator(self, value: str) -> dict[str, str]:
        return {"verdict": "malicious", "detail": f"intel on {value}"}

    async def status(self, host: str) -> dict[str, bool]:
        return {"isolated": True, "active_threat": False}


class Firewall(Containment):
    def __init__(self) -> None:
        self.done = []

    async def isolate_host(self, host: str, key: str) -> str:
        self.done.append(("isolate_host", host))
        return f"isolated:{host}"

    async def disable_account(self, account: str, key: str) -> str:
        return f"disabled:{account}"

    async def block_indicator(self, indicator: str, key: str) -> str:
        return f"blocked:{indicator}"

    async def revoke_sessions(self, account: str, key: str) -> str:
        return f"revoked:{account}"


class Pager(Oncall):
    async def page(self, alert_id: str, summary: str, key: str) -> str:
        return f"page:{alert_id}"
```

### 2. Building the harness

A run starts with the brief `{"alert": {"id", "kind", "hosts": [...], "summary"}}`.

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

firewall = Firewall()
remediation = catalog().harness(
    path="security/threat_remediation",
    ports=Ports.of(WebTelemetry(), firewall, Pager()),
)
alert = {"id": "A-17", "kind": "malware", "hosts": ["web-1"], "summary": "Beaconing."}
```

The module names each tool with a constant built without its port (`ISOLATE_HOST`,
`HOST_EVENTS`, `PAGE_ONCALL`, ...); the plan, the errands, the policy and the evaluation
refer to tools through those constants. The harness's toolbox holds the same tools over your
ports, with the same
[identities](../concepts/tools.md#two-names-the-short-name-and-the-identity) (the module
that defines the tool, a dot and the short name the model sees):

```python
from gvn_domains.security.remediation import ISOLATE_HOST

print(ISOLATE_HOST.identity())
print(ISOLATE_HOST in remediation.toolbox(), len(remediation.toolbox()))
```

```text
gvn_domains.security.remediation.isolate_host
True 12
```

The plan declares all twelve, so the Governor checks the toolbox against them before the run
starts (see [how a harness names its tools](index.md#how-a-harness-names-its-tools)).

### 3. A model for the three judgement steps

Only triage, investigation and planning use a model. As on the earlier domain pages, a
`FunctionModel` plays it: a function from the `exchange` (the agent's instructions and
messages) to a `Reply`; a message with the role `TOOL` carries tool results back. This one classifies the alert as an
incident, reads the host it is told to investigate, and proposes isolating `web-1`. The
module exports each agent's instructions (`TRIAGE`, `INVESTIGATE`, `PLAN`), so the function
can tell them apart.

```python
from gvn.harness.messages import TOOL, Message, ToolCall
from gvn.harness.ports import Exchange, Reply
from gvn_domains.security.remediation import INVESTIGATE, PLAN, TRIAGE


def calling(name: str, **arguments: typing.Any) -> Reply:
    call = ToolCall(call_id="c1", name=name, arguments=arguments)
    return Reply(message=Message.assistant(text="", calls=[call]))


def responder_model(exchange: Exchange) -> Reply:
    if any(message.role() == TOOL for message in exchange.messages()):
        return Reply(message=Message.assistant(text="Done."))
    role = exchange.instructions()
    if role == TRIAGE:
        return calling("classify_incident", severity="high", reason="a dropper ran")
    if role == INVESTIGATE:
        host = exchange.messages()[0].text().split("Investigate host: ")[1]
        return calling("host_events", host=host)
    if role == PLAN:
        return calling(
            "propose_action", action="isolate_host", target="web-1", reason="contain it"
        )
    raise AssertionError(f"unexpected role {role!r}")
```

### 4. Triage, investigation and planning

```python
import asyncio

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

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

```text
waiting alert-17/containing.1
```

Three stages ran before the run stopped:

1. **Triage** classified the alert as an incident.
2. **Investigation** started one investigator per alert host (here one) and waited for all
   of them: the join `AllOf("completed")` ends `investigated` only when every investigator
   completed.
3. **Planning**: the planner proposed `isolate_host web-1`, and its judge accepted the plan
   because the target is in scope.

The run now waits in `containing`. Its errand asked to apply the plan, and the policy said a
person must approve it first.

### 5. What the approver sees: a context that grew

The [run context](../concepts/run-context.md) grows as the run learns, and it is always
built by the plan, never by a model:

| Actors | Context |
|---|---|
| every actor | `{"alert": {...}}`, from the brief |
| the planner | adds `"scope"`: the alert's hosts, and the accounts and indicators the investigators' telemetry calls actually returned |
| the containing errand | adds `"scope"`, and `"approved"`: the plan the planning stage produced and its judge accepted |

The approval request carries the containing errand's context, so the person sees what is
in scope and exactly what will be done:

```python
context = request.payload()["context"]
print(context["scope"])
print(context["approved"])
```

```text
{'hosts': ['web-1'], 'accounts': ['svc-web'], 'indicators': ['evil.example']}
[{'action': 'isolate_host', 'target': 'web-1'}]
```

`svc-web` and `evil.example` are in scope because a telemetry call returned them, not
because a model named them.

### 6. A person approves, and the run verifies

```python
done = asyncio.run(launcher.approve(run_id="alert-17", request=request))
print(done.outcome().state(), firewall.done)
print(asyncio.run(launcher.grade(run_id="alert-17")).passed())
```

```text
State('contained') [('isolate_host', 'web-1')]
True
```

The errand isolated `web-1`, then the `verifying` errand read `host_status` for every alert
host. Telemetry showed no active threat, so the run ended `contained`. Had the person said
no, the stage would have ended `not_approved` and the run would have gone to `escalating`.

The evaluation's checks: the run finishes `contained`, `dismissed` or `escalated`, nothing
is rejected, it takes at most 60 events, and no containment action succeeds without approval
(`Gated` over the four containment tools, `ISOLATE_HOST`, `DISABLE_ACCOUNT`,
`BLOCK_INDICATOR` and `REVOKE_SESSIONS`).

## Each stage in detail

How each stage ends, in the plan's own terms. `AllOf("completed")` is a join (the rule for
when a fan-out is over) that waits for every child to end `completed`; an errand ends `done`,
`declined`, `failed` or `refused` (see [Errands](../concepts/errands.md)).

| Stage | Who | How it ends |
|---|---|---|
| `triaging` | an agent: `classify_false_positive`, `classify_incident` | `incident`, `false_positive`, or `triage_failed` |
| `investigating` | one agent per alert host, at once: `host_events`, `host_processes`, `lookup_indicator` | `AllOf("completed")`: `investigated` when every investigator completed |
| `planning` | an agent: `propose_action` | a judge: `plan_ready`; `plan_empty` when nothing was proposed; `plan_out_of_scope` when the planner tried any proposal the policy forbade, or an accepted one is out of scope |
| `containing` | an errand: the approved plan as one batch of `isolate_host`, `disable_account`, `block_indicator`, `revoke_sessions` (a person approves) | routes on the errand's final state: `done` is `applied`; `declined` is `not_approved`; `failed` (a call ran and failed: it may have half applied) is `containment_errored`; `refused` (the policy forbade the plan, or forbade or a person denied some calls and the rest were applied without a failure) is `not_applied`. All three escalate. |
| `verifying` | an errand: `host_status` of every alert host | on telemetry alone: `verified` when every host shows no active threat, else `still_active` or `verification_failed` |
| `escalating` | an errand: `page_oncall` with a hand-off built from the run's record | `paged`, otherwise `not_paged` |

## What is enforced before any effect

The policy clears reads, classification, proposals and paging; containment needs a
person's approval; anything else, and any call the scope rules below refuse, is forbidden.
Each call gets [its own verdict](../concepts/reference-agent.md#one-verdict-per-call), so a person is asked only about the containment
calls.

One rule set, `permitted(tool, origin, context, arguments=None)`, is used twice: by the policy (a refused call is `forbidden`, so
it never reaches a person or a tool) and again by each tool before its effect, should the
policy ever be swapped.

- A reading tool may only look at one of the alert's hosts.
- `propose_action` may only propose a target in scope for its action: a host to isolate, an
  account to disable or sign out, an indicator to block.
- A containment tool may only act on a target that is in scope **and** in the approved
  plan. Off-plan containment is prevented, not merely detected.
- No tool takes an alert id; the alert comes from the context.
- Every containment action waits for a person, and each is applied once per call key.

You can ask the policy directly with a `Consultation` (the calls, the identity of each
call's tool, where they come from, and the run context), using the context the containing
errand had above. The policy matches each call by its tool's identity, so the question names
the tool by its constant:

```python
from gvn.harness.tools import Consultation, Tool
from gvn_domains.security.remediation import DISABLE_ACCOUNT, HOST_EVENTS


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


print(verdict(ISOLATE_HOST, {"host": "web-1"}, context))
print(verdict(ISOLATE_HOST, {"host": "db-1"}, context))
print(verdict(DISABLE_ACCOUNT, {"account": "svc-web"}, context))
print(verdict(HOST_EVENTS, {"host": "db-1"}, {"alert": alert}))
```

```text
needs_approval
forbidden
forbidden
forbidden
```

The first call is in scope and in the approved plan, so it goes to a person. Isolating
`db-1` is refused: it is not in scope. Disabling `svc-web` is in scope, but not in the
approved plan. And a reading tool, with only the alert in its context, may not look at
`db-1` either: it is not one of the alert's hosts.

## What this harness uses from gvn

The model-free steps are `Errand`s, and the evaluation's `Gated` sees every actor's requests
(see the [domains overview](index.md#what-the-harnesses-use-from-gvn)): the approved plan is
applied, checked and handed off by code, and `Gated` over the four actions sees the errand's
calls. Its scope rules show what the run context is
for: data constraints such as "only this alert's hosts" are enforced before an
effect, by tools and by policy, instead of being detected afterwards.

## Running it safely

- **The policy gates by tool.** Every call to a containment tool needs approval, and the
  scope rules constrain its target. `Gated` checks recorded calls for approval during evaluation.
- **Verification reads telemetry.** `verified` means the `Telemetry` port reported no
  active threat on every alert host.
- **Port actions happen once per key.** Work in flight at a crash runs again, so each
  containment tool and `page_oncall` pass the call's
  [idempotency key](../reference/glossary.md#idempotency-key) (a string that is the same
  each time the same call is delivered) to their port, which must act once per key. An
  errand interrupted while acting asks again with new keys; isolating, disabling, blocking
  or revoking twice is harmless by nature.

Its own tests are in `packages/gvn-domains/tests/test_dom_security_remediation.py`.

## Recap

- Judgement steps are agents; steps fully decided by code are errands, so no model can add
  an off-plan action.
- The run context grows from what tools returned, never from what a model wrote.
- One rule set guards both the policy and each tool, before any person or effect.
- Every unsafe ending leads to a person through `escalating`.

**Next:** [Enterprise](enterprise.md), where several reviewers vote and a quorum decides.
