# `Nous.Plugins.InputGuard.Engine`
[🔗](https://github.com/nyo16/nous/blob/v0.21.1/lib/nous/plugins/input_guard/engine.ex#L1)

The strategy engine shared by `Nous.Plugins.InputGuard` and
`Nous.Plugins.DecisionGuard`: run a list of
`Nous.Plugins.InputGuard.Strategy` modules over a text, aggregate their
verdicts and fail closed on strategies that produced none.

`run/4` reads these keys from `config` (see `Nous.Plugins.InputGuard` for
their meaning and defaults): `:strategies`, `:aggregation`,
`:short_circuit`, `:fail_closed`, `:strategy_timeout`, `:on_violation`.

## Dropped strategies

A strategy that errors, times out or returns `{:error, reason}` is
*dropped*: it produced no verdict. With `:fail_closed` (default `true`) a
drop counts as a flagging vote against the configured strategy count, and
when that could change the outcome — under `:any` always, under
`:majority` when the drops could make up the majority, under `:all` when
every survivor flagged (including when every strategy dropped) — the result
is a fail-closed one: severity `:suspicious`, `metadata: %{fail_closed:
true, dropped_strategies: n}`. Callers map that marker to their own action
(`Nous.Plugins.InputGuard.Policy` blocks by default). With `fail_closed:
false` a drop counts as a vote that did not flag, so if every strategy
drops the input is `:safe`.

## Options

  * `:telemetry_prefix` - prefix of the engine's events (see below).
    Default: `[:nous, :input_guard]`.
  * `:label` - prefix of log messages. Default: `"InputGuard"`.
  * `:fail_closed_on` - the survivors' verdicts a fail-closed result may
    replace. Default: `[:safe]`. `Nous.Plugins.InputGuard` passes
    `[:safe, :suspicious]`, so a `:suspicious` survivor cannot downgrade a
    detector outage to a warning; `Nous.Plugins.DecisionGuard` keeps the
    default and escalates a `:suspicious` verdict. A `:blocked` verdict is
    never replaced.

## Telemetry

Both events carry the run correlation keys (`trace_id`, `agent_run_id`,
`parent_agent_run_id`; see `Nous.Telemetry`).

  * `prefix ++ [:strategy_verdict]` - one strategy finished, was killed at
    `:strategy_timeout`, or dropped.
    * Measurements: `%{duration: native_time}`
    * Metadata: `%{strategy: module, severity: :safe | :suspicious |
      :blocked | nil, reason: String.t() | nil, details: map(), error: term | nil}`.
      `details` is the strategy's `Nous.Plugins.InputGuard.Result` `metadata`
      (e.g. `top_similarity`, `probabilities`); a dropped strategy has
      `severity: nil`, `details: %{}` and the failure in `error`
      (`:timeout` when it was killed). `reason` and `details` may quote the
      classified input; scrub them before forwarding events off-box.
  * `prefix ++ [:strategy_dropped]` - one or more strategies errored, timed
    out or returned `{:error, reason}`.
    * Measurements: `%{count: integer}`
    * Metadata: `%{aggregation: :any | :majority | :all, fail_closed: boolean}`

The aggregate verdict is not an engine event: `Nous.Plugins.InputGuard`
emits `[:nous, :input_guard, :verdict]` itself, and DecisionGuard its own
`[:nous, :decision_guard, :verdict]`.

# `aggregate`

```elixir
@spec aggregate([Nous.Plugins.InputGuard.Result.t()], non_neg_integer(), map()) ::
  Nous.Plugins.InputGuard.Result.t()
```

The survivors' verdict over strategy `results` under `config[:aggregation]`
(`:any`, default; `:majority`; `:all`), against `configured_count`
configured strategies: the aggregation `run/4` applies before its
fail-closed check for dropped strategies. A configured strategy missing
from `results` counts as a vote that did not flag, so a caller holding
per-strategy results with drops applies its own fail-closed rule (see the
moduledoc). Pure; calibration sweeps (`Nous.Eval.Guard`) re-aggregate
recorded per-strategy results with it.

# `evaluate`

```elixir
@spec evaluate(String.t(), Nous.Agent.Context.t() | nil, map(), keyword()) ::
  {Nous.Plugins.InputGuard.Result.t(),
   %{strategies: non_neg_integer(), dropped: non_neg_integer()}}
```

`run/4`, also returning how many strategies were configured and how many
dropped: `{result, %{strategies: non_neg_integer, dropped: non_neg_integer}}`.

# `message_text`

```elixir
@spec message_text(Nous.Message.t(), keyword()) ::
  {:ok, String.t()} | {:error, term(), String.t()}
```

The text a guard classifies for `message`: what a provider will read.

The OpenAI, Anthropic and Gemini adapters send `metadata.content_parts`
instead of `content` whenever it is a list, so for such a message the parts
are classified (each as the adapters render it as text, joined with spaces).
`content` is added when it says something the parts do not: a message whose
two halves disagree must not pass on the half that is never sent. Otherwise
this is `content`, or its text parts joined with spaces.

A binary part with a `text/*` media type (an `:image` part's `media_type`,
or a base64 `data:` URL) is sent as a document by Gemini / Vertex AI, so it
is decoded and its text classified. Other binary parts (images, PDFs) are
not: they are classified as their placeholder only.

Returns `{:ok, text}`, or `{:error, reason, text}` when a `text/*` part
could not be decoded within `opts[:max_decoded_bytes]` (an integer, or a
0-arity function returning one; default `0`, i.e. never decode) or is not
valid UTF-8. `text` then has that part as its placeholder, and the caller
must treat the message as not fully classified.

# `run`

```elixir
@spec run(String.t(), Nous.Agent.Context.t() | nil, map(), keyword()) ::
  Nous.Plugins.InputGuard.Result.t()
```

Runs the configured strategies over `input` and returns the aggregated
`Nous.Plugins.InputGuard.Result`, after the fail-closed check for dropped
strategies (see the moduledoc). Calls `config[:on_violation]` when the
result is not `:safe`.

`ctx` is handed to every strategy; it is `nil` on surfaces that have no
agent context (see `c:Nous.Plugins.InputGuard.Strategy.check/3`).

# `sanitize_reason`

```elixir
@spec sanitize_reason(term()) :: String.t()
```

Collapses whitespace and caps a strategy reason at 300 characters.

A reason may come from an LLM judge whose output is influenced by the
(untrusted) input, so it must not smuggle instructions or formatting into
the trusted system/assistant message it is embedded in.

# `unchecked_user_inputs`

```elixir
@spec unchecked_user_inputs(Nous.Agent.Context.t(), atom(), keyword()) :: [
  {{:ok, String.t()} | {:error, term(), String.t()}, non_neg_integer()}
]
```

Every user message the guard has not classified yet, oldest first, as
`{message_text(message, opts), index}`.

The window starts after the later of the index stored in
`ctx.deps[last_checked_key]` (default `-1`) and the last `:assistant`
message: all user messages the model has not answered yet, which is every
message queued in this turn (several `Nous.AgentServer.steer/2` calls, or
`:message_history` ending in user messages), not just the newest one.
Messages the model already answered are history and are not classified
again on each run. `opts` go to `message_text/2` (`:max_decoded_bytes`).

---

*Consult [api-reference.md](api-reference.md) for complete listing*
