> For the complete documentation index, see [llms.txt](https://docs.labs.ai/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.labs.ai/conversations-and-orchestration/hitl.md).

# Human-in-the-Loop (HITL)

The HITL framework lets you insert **human approval gates** into AI agent conversations. It works on **both surfaces**:

| Surface                 | Trigger                                       | Pause state         | Use case                                         |
| ----------------------- | --------------------------------------------- | ------------------- | ------------------------------------------------ |
| **Regular 1:1**         | `PAUSE_CONVERSATION` action in behavior rules | `AWAITING_HUMAN`    | Single-agent pipelines needing human checkpoints |
| **Group conversations** | `requiresApproval: true` on a phase           | `AWAITING_APPROVAL` | Multi-agent orchestration needing oversight      |

***

## Why Two Surfaces?

The two surfaces exist because regular and group conversations have fundamentally different execution models — and therefore different natural "pause points."

### Regular 1:1: Action-Driven

A regular conversation runs a **linear pipeline** of lifecycle tasks (parse → behavior rules → output → templating → …). The natural pause point is **between tasks in the pipeline**, triggered by a behavior rule emitting the reserved `PAUSE_CONVERSATION` action.

This is **opt-in per turn**: whether to pause depends on runtime conditions (user intent, slot values, context). Behavior rules are EDDI's existing mechanism for conditional actions — reusing them keeps the logic in configuration, not Java.

For a rule pause, `hitlConfig`'s `approvalTimeout`/`timeoutPolicy`/`pauseReason` only control **timeout behavior** — the actual triggering is in the behavior rules. Without a rule emitting `PAUSE_CONVERSATION`, none of them do anything. (`hitlConfig.toolApprovals` is a separate trigger that needs no behavior rule — see [Tool-Level Approval Gating](#tool-level-approval-gating).)

### Group: Config-Driven

A group conversation runs a **structured pipeline of phases** (Opinion → Challenge → Synthesis). "Should this phase be reviewed?" is a design-time decision — a boolean on the phase definition (`requiresApproval: true`).

### Granularity (group only)

| Granularity         | Semantics                                                                                                                                                                              |
| ------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **PHASE** (default) | Pause after the phase's repeats fully complete. Resume advances to the **next** phase.                                                                                                 |
| **TASK**            | For **EXECUTE phases only**: each task result is individually submitted for approval; resume **re-enters the same phase** so approved/retried tasks and their dependents can continue. |

> \[!IMPORTANT] `granularity: "TASK"` only changes behavior for EXECUTE phases (they have a task list). A non-EXECUTE phase with `requiresApproval: true` **falls back to a PHASE-style pause** — the gate is never silently skipped.

***

## Surface 1: Regular 1:1 Conversations

### How It Works

```
User sends message
  └→ Pipeline executes: Parse → BehaviorRules → Output → Templating
       └→ Rule emits PAUSE_CONVERSATION action
            └→ LifecycleManager detects the action was ADDED by this task
                 └→ Conversation pauses:
                      ├→ state = AWAITING_HUMAN
                      ├→ bookmark: workflowId + absolute task index + pausedAt
                      ├→ timeout policy copied into the bookmark
                      └→ one-shot timeout schedule armed (if finite policy)

⏸️ Conversation is paused — say() is rejected promptly with 409, undo/redo return 409

Human reviews → POST /agents/{conversationId}/resume with a decision
  └→ REJECTED → remaining pipeline tasks are skipped, state = READY
       (onRejection: REVISE and a note → the model revises its answer instead, see below)
  └→ APPROVED → pipeline resumes from the bookmarked task + 1
       └→ Remaining tasks (output, templating, …) execute normally
```

**Ordering guarantee — the pause is durable before you are told about it.** A turn that ends `AWAITING_HUMAN` is answered (the synchronous `say` response, the streaming `done` event, and the response to a `resume` that re-pauses) only *after* the pause has been committed. When a client reacts to that answer by calling `GET /agents/{conversationId}/approval-status`, `pending-approvals` or `resume`, it therefore always finds the pause it was told about, with its `pauseId` and `pauseDetails`. If the commit does not happen — a concurrent end or cancel won the race, or the store failed — the answer carries the state the store actually holds (for example `ENDED` or `EXECUTION_INTERRUPTED`), never a phantom `AWAITING_HUMAN`. Ordinary turns are unaffected: they are answered as soon as the pipeline finishes, as before. Group member turns that pause get the same guarantee, since they run through the same `say`.

**While paused, user input is rejected without being consumed**: `POST /agents/{conversationId}` returns `409 Conflict` immediately with a body directing to the resume endpoint — the message is *not* queued and *not* processed. The same applies if a pause commits in the narrow window after a message was accepted (the turn is skipped and answered with `409` instead of executing against the paused conversation). Chat clients should render "awaiting approval" and disable input until the decision lands.

### Configuration

```json
{
  "hitlConfig": {
    "approvalTimeout": "PT15M",
    "timeoutPolicy": "AUTO_REJECT",
    "pauseReason": "Account deletion requires manager sign-off"
  }
}
```

| Field                 | Type                                                              | Default             | Description                                                                                                                                                                                                                                                                 |
| --------------------- | ----------------------------------------------------------------- | ------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `approvalTimeout`     | ISO-8601 duration (`"PT30S"`, `"PT15M"`)                          | `null`              | Time before the timeout policy fires. Required for finite policies.                                                                                                                                                                                                         |
| `timeoutPolicy`       | `AUTO_APPROVE` \| `AUTO_REJECT` \| `ABORT` \| `WAIT_INDEFINITELY` | `WAIT_INDEFINITELY` | What happens when the timeout expires.                                                                                                                                                                                                                                      |
| `pauseReason`         | string, ≤ 500 chars                                               | `null`              | Approver-facing text shown in pending-approval listings and approval-status — answers "what am I approving?". Falls back to a generic reason when absent.                                                                                                                   |
| `onRejection`         | `SKIP` \| `REVISE` (case-insensitive)                             | `SKIP`              | What a `REJECTED` decision on a rule pause does. `SKIP` skips the remaining tasks and shows the note. `REVISE` has the model revise the answer it gave before the pause, with the note as feedback. See [Revise with the reviewer's note](#revise-with-the-reviewers-note). |
| `maxRevisionsPerTurn` | integer, `1`..`10`                                                | `3`                 | Under `REVISE`, how many revisions one turn may take. A rejection after that skips.                                                                                                                                                                                         |
| `requirePlanHash`     | boolean                                                           | `false`             | Strict [plan binding](#plan-binding-planhash): a human decision without the pause's `planHash` is refused with `400`. `eddi.hitl.plan-hash.strict=true` turns it on for every agent and group.                                                                              |

The same `hitlConfig` also holds `toolApprovals` ([Tool-Level Approval Gating](#tool-level-approval-gating)), `review` ([HITL Review & Audit](https://docs.labs.ai/conversations-and-orchestration/hitl/hitl-review-and-audit.md)), `approvalContext` ([HITL Approval Card Context](https://docs.labs.ai/conversations-and-orchestration/hitl/hitl-approval-context.md)), `oversight` ([HITL Oversight](https://docs.labs.ai/conversations-and-orchestration/hitl/hitl-oversight.md)) and `notify` ([Email notifications](#email-notifications)).

Validation happens at **save time** (and on ZIP import): a finite policy without a valid positive `approvalTimeout` (or a malformed duration like `"30m"`, or an overlong `pauseReason`) is rejected with an actionable 400 — it never degrades silently to wait-forever at runtime.

### Behavior Rule (the actual trigger)

```json
{
  "name": "Pause for deletion approval",
  "actions": ["PAUSE_CONVERSATION"],
  "conditions": [
    { "type": "inputmatcher", "configs": { "expressions": "delete_account(*)" } }
  ]
}
```

`PAUSE_CONVERSATION` is a **reserved action** (like `CONVERSATION_START`, `CONVERSATION_END`, `STOP_CONVERSATION`, `CONTINUE_CONVERSATION`). Do not reuse it as a quick-reply expression.

**Pauses and self-continuation.** A turn that pauses never arms a [self-continuation](https://docs.labs.ai/conversations-and-orchestration/long-jobs.md): only a turn that settles is followed by its own next turn. A continuation that falls due while the conversation is `AWAITING_HUMAN` is not run; the turn resumed from the pause may emit `CONTINUE_CONVERSATION` again, and is followed like any settled turn.

### REST API

| Method | Path                                       | Description                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   |
| ------ | ------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `POST` | `/agents/{conversationId}/resume`          | Submit a decision (`{"verdict": "APPROVED"\|"REJECTED", "note": "...", "pauseId": "..."}` — verdict is case-insensitive). `pauseId` is optional: when set (from `approval-status`), the decision applies only while the conversation is still in that pause; if it has since been resumed and paused again on a different request the decision is refused with `409` and the current pause is left untouched. The group approve body accepts the same field inside its `decision`, and the MCP `resume_conversation` and `approve_group_phase` tools take it as an optional argument (`pauseId` from `get_approval_status` / `get_group_approval_status`; a changed pause answers `errorCode: PAUSE_CHANGED`) |
| `GET`  | `/agents/{conversationId}/approval-status` | Pause summary: `state`, `pausedAt`, `pauseId` (pass it back as the decision's `pauseId` — see below), `planHash` (pass it back as the decision's `planHash` — see [Plan Binding](#plan-binding-planhash); `""` for a pause committed before plan hashing), `pauseReason`, `timeoutPolicy`, `approvalTimeout` (render the auto-decision deadline as `pausedAt + approvalTimeout`), `pauseDetails` — structured, computed at read time (see below). `?detail=full` for the whole snapshot — approver-only callers get `full` only while the conversation is paused, `403` otherwise                                                                                                                             |
| `GET`  | `/agents/pending-approvals?limit=200`      | List paused conversations as summaries (bounded, max 1000). Non-admin/non-approver callers get their own conversations, filtered *inside* the query — the limit applies after the owner restriction, so a personal inbox is never starved by other users' backlog                                                                                                                                                                                                                                                                                                                                                                                                                                             |
| `POST` | `/agents/{conversationId}/cancel`          | Cancel a paused (or same-pod running) conversation                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            |

The body also takes an optional `planHash` (from `approval-status`): the decision then applies only to exactly that plan — a different one is refused with `409` (`planHash does not match`), and with [strict plan binding](#plan-binding-planhash) a human decision without it is a `400`.

**Being told instead of polling.** A signed-in client holding [`GET /me/events`](https://docs.labs.ai/conversations-and-orchestration/user-events.md) receives `approval.pending` when a turn or tool call pauses that it may decide (the owner, while they may still `USE` the agent, and every admin and approver — the rules of [Who May Decide](#who-may-decide)), and `approval.decided` when it is decided, cancelled or times out. Ids only; read the details here. Group gates arrive the same way, with `surface: "group"`.

Status codes are discriminating: `400` invalid body (missing verdict, note > 4 KB, a missing `planHash` under strict binding — the pause is **not** consumed), `404` unknown conversation, `409` not in a resumable state (body names the current state) or a decision for another pause or plan, `200` success. HITL operations on a conversation whose descriptor is missing (legacy/corruption) fail **closed** — only admins/approvers may act on them.

#### `pauseDetails` shape

`pauseDetails` is computed at read time from the snapshot (nothing new is persisted) and is `null` once the conversation is no longer paused. Its shape depends on `hitlPauseType`:

* **`TOOL_CALL`** (a gated tool call paused for approval):

  ```json
  {
    "type": "TOOL_CALL",
    "calls": [
      {"callId": "call-1", "toolName": "sendEmail", "source": "mcp",
       "arguments": "{\"to\":\"[REDACTED]\"}", "argsTruncated": false, "gateReason": "mcp:*"}
    ],
    "executedUngatedCalls": ["getCurrentDateTime"],
    "outcomeUnknown": []
  }
  ```

  `arguments` is always the **redacted, capped** value (`argumentsRedacted`) — the raw arguments never appear in this response. `outcomeUnknown` lists callIds that have an `EXECUTING` journal entry — i.e. a prior approval crashed mid-execution and the outcome is genuinely unknown; it is empty in the common case.
* **`RULE`** (a behavior-rule `PAUSE_CONVERSATION`, including legacy snapshots with no `hitlPauseType` recorded):

  ```json
  {"type": "RULE", "reason": "Account deletion requires manager sign-off", "actions": ["PAUSE_CONVERSATION", "notify_manager"]}
  ```

  `actions` is the `ACTIONS` data of the paused step.

While a conversation is paused, `approval-status` also carries `approvalContext` — the blocks of `hitlConfig.approvalContext` rendered once when the pause was committed (`null` when none is configured); see [HITL Approval Card Context](https://docs.labs.ai/conversations-and-orchestration/hitl/hitl-approval-context.md).

`GET /agents/pending-approvals` entries also carry `pauseType` (`RULE`/`TOOL_CALL`; a pause stored without a type — rule pauses before 6.4 — is reported as `RULE`) and `toolNames` (names only, no arguments) so inbox UIs can badge tool-call pauses without a second round trip.

The listing has no offset parameter, so a caller sees at most `limit` entries. The Manager's **Approvals** page asks for 200 and, when exactly that many come back, says that more are pending than it shows (decide some and the rest move up) instead of presenting the first 200 as the whole queue. The group inbox does the same with its own list.

### What the Agent Sees After a Decision

| Where                           | Key                                                                  | Notes                                                                                    |
| ------------------------------- | -------------------------------------------------------------------- | ---------------------------------------------------------------------------------------- |
| Templates (same turn, APPROVED) | `{memory.current.hitlDecision}`, `{memory.current.hitlDecisionNote}` | Conversation output written at resume time                                               |
| Properties (this + later turns) | `{properties.hitlVerdict}`                                           | Conversation-scoped property — next-turn behavior rules can react via a property matcher |
| Raw step data (pipeline tasks)  | `hitl:decision_verdict`, `hitl:decision_note`, `hitl:decision_by`    | Not template-accessible (colon keys)                                                     |

On **REJECTED**, the remaining pipeline tasks are skipped (the actions that would have triggered API calls are still in the step — they must not run) and a public output message with the reviewer's note is emitted so UIs render feedback. Under `onRejection: REVISE` a rejection with a note revises the answer instead; see below.

### Revise with the reviewer's note

`hitlConfig.onRejection: "REVISE"` turns a rejection into a request for a better answer. It suits a workflow in which a rule pauses **after** the model answered so that a person reviews the draft:

```json
{
  "hitlConfig": {
    "onRejection": "REVISE",
    "maxRevisionsPerTurn": 2,
    "pauseReason": "Review the draft reply before it is sent"
  }
}
```

The approval API is unchanged: the reviewer rejects with a note, over REST `POST /agents/{conversationId}/resume` (`{"verdict": "REJECTED", "note": "Too formal; mention the refund date"}`), the MCP `resume_conversation` tool or the Manager's Approvals page.

**What happens.** The same model is asked once more, over the exact request that produced the draft (system prompt, history, retrieved context and any tool results, kept with the pause), with the draft as the assistant's turn and the note as the user's next message. The revision replaces the draft, and the pipeline continues from the task after the model's. A rule that paused on the draft therefore pauses again on the revision, and the reviewer sees it before it goes out. Approve it, or reject it again with another note.

* **The note is data.** It is human-written, so it may go in the user role, but it is never template source: it is put into the message by concatenation, not run through the template engine.
* **No tool runs again.** The revision is one model call with no tools. A draft that came from a tool loop is re-asked over its tool results, the way an output guardrail re-asks a final answer.
* **The same checks apply.** The revision passes `responseValidation` and the task's output guardrails, and the spend gate is asked first (`maxCostPerConversationUsd`, the tenant budget). The revision's tokens and cost are recorded on the step like any answer's.
* **Tasks after the model's run again**, from the one after the model's task up to and past the pause. Output that the draft and those tasks wrote is cut back first, so nothing appears twice. Keep side effects (an `httpcall` that sends something) **after** the pause, which is the usual design anyway.
* **Templates can tell.** `{memory.current.hitlRevision}` holds the revision's number. `{memory.current.hitlDecision}` reads `REJECTED` (the decision on the draft) while the revision runs and awaits review, and is overwritten by the next decision on the same turn: once the revision is approved, the step reads `APPROVED`.

**When a rejection still skips.** In all of these cases the rejection behaves exactly as under `SKIP`:

| Case                                                                                                                                                                                                                         | `hitl:revision:outcome` |
| ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------- |
| The decision has no note (blank counts as none). A Slack Reject button counts as none too: the note it records is its own attribution, not a request                                                                         | `no_note`               |
| The decision is automated: a timeout's `AUTO_REJECT`, a group's `system:group`                                                                                                                                               | `automated`             |
| There is no answer to revise: the pause came before the model ran in this turn, the answer came from a later task or workflow, or its request was over `eddi.hitl.revision.transcript-max-bytes` (default 256 KB)            | `no_answer`             |
| The turn has had `maxRevisionsPerTurn` revisions already                                                                                                                                                                     | `exhausted`             |
| The revision could not be produced: the LLM configuration changed since the pause, a spend limit is reached, the model failed or returned nothing, or the revision failed `responseValidation` or was blocked by a guardrail | `failed`                |

**Which pauses.** Only behavior-rule (`RULE`) pauses. A rejected **tool call** (`TOOL_CALL` pause) is not a rejected answer: the model already receives the rejection, with the note, as that call's tool result and answers from there, under either policy. Group discussions are not affected either (a member's own pause is cancelled inside a group, see [Group members](#group-members)).

**Records.** The step keeps `hitl:revision:outcome` (`{outcome, round}`) as part of the turn's HITL record, the `hitl.approval` audit entry carries `onRejection: REVISE` for a rejection under the policy, and the revision itself is an ordinary LLM task entry in the audit ledger (model, response, tokens, cost). The counter `eddi_hitl_revision_total{outcome}` counts the outcomes. The request kept with the pause (`hitl:revision:candidate`) is internal: it is withheld from `returnDetailed` and from an approver's `approval-status?detail=full`, the raw read `GET /conversationstore/conversations/{conversationId}` serves only its draft and bookkeeping (never `transcriptJson`, the frozen request with the compiled system prompt; the redo cache an undo fills is covered too), it is scrubbed of secret input and secret context like the rest of the step, and it is removed from the step when the pause is decided.

**Approve with an edit instead.** With `hitlConfig.review.allowAnswerEdits` an approver can replace the answer under review instead of rejecting it — see [HITL Review & Audit](https://docs.labs.ai/conversations-and-orchestration/hitl/hitl-review-and-audit.md#rule-pause-edits).

### Secret context on resume

A client that sends a per-turn credential as a **secret context** value (`"secret": true`, e.g. `userToken` used as `Bearer {context.userToken}` in an httpcalls header) loses it when the turn pauses: it is replaced by the placeholder `<secret context>` before anything is stored. A task that runs after the pause and needs the credential, such as an approved HTTP tool call acting as the user, would otherwise send the placeholder. Re-supply the value in the resume body, in the same shape as a `say` request's `context`:

```json
{
  "verdict": "APPROVED",
  "context": {
    "userToken": { "type": "string", "value": "eyJ...", "secret": true }
  }
}
```

Two restrictions, both enforced with a **400 before the pause is consumed** (so the same pause can be decided again): an entry must be marked `secret: true`, and the paused turn must have carried that key as a secret. An approval cannot inject new or non-secret data into the turn it approves. The values are visible to the resumed tasks only and get the same treatment as on `say`: never persisted, returned or audited; after the turn the stored step holds the placeholder again.

Only the REST `POST /agents/{conversationId}/resume` body can carry it. Timeout auto-resolution, Slack approvals, the MCP `resume_conversation` tool (tool arguments are logged and audited) and group-conversation resumes pass no context, so a call that needs the credential still fails there with the "secret context expired" error, and the approver should resume over REST instead.

**Fingerprint behaviour.** Before this feature an approved, pinned `http` call was refused on resume ("the request changed after it was approved"): re-resolving the request met the placeholder and failed, which the pin check treats as fail-closed; an unpinned call failed at execution with the same expired-secret error. With the value re-supplied, the re-resolved request is compared against the pin as usual and nothing else is relaxed. Headers are fingerprinted in redacted form, so an identical re-supplied token matches, and so does a rotated token in a header the redactor recognises as a credential (such as `Authorization`). A different token that lands in the URI, a query parameter, the body, or a header the redactor does not treat as a credential changes the fingerprint and the call is refused: fail closed.

### Reply and approver on resume

**Opt-in reply.** By default `POST /agents/{conversationId}/resume` answers with an empty `200` as soon as the resume is accepted, and existing callers are unchanged. Pass any of the `say` query parameters (`returnCurrentStepOnly`, `returnDetailed`, `returningFields`) and the request instead waits for the resumed turn and returns it as a `say` response: the same JSON shape, built by the same snapshot conversion, so secret context appears as its placeholder and output filtering is identical.

```
POST /agents/{conversationId}/resume?returnCurrentStepOnly=true
```

The wait is asynchronous like `say`, bounded by `systemRuntime.agentTimeoutInSeconds`; past it the answer is `408` while the turn keeps running (read the conversation afterwards). A re-pause is answered with the paused snapshot; a turn that ends in `ERROR` carries the same `error` object as on `say`, and `Retry-After` is set when it failed with a provider wait; a resume that was dropped before it ran (cancelled or ended in between: `410` when the conversation ended, otherwise `409`; or refused by the coordinator, which restores the pause: `409`) is answered at once instead of waiting for the timeout; a resume the runtime abandons (the agent-timeout watchdog, or a failure that escapes the resume itself) is answered with the state the store then holds (`EXECUTION_INTERRUPTED` or `ERROR`), unless the `408` already went out; and validation errors keep their status (`400` before the pause is consumed, `404`, `409`, `500`) whether or not the reply was requested. Once any one flag is present, the others default as on `say` (`returnDetailed=false`, `returnCurrentStepOnly=true`).

### Streaming the resume (`POST /agents/{conversationId}/resume/stream`)

A live chat that renders the resumed turn as it happens uses the streaming twin of the reply: the same body, the same query flags, the same roles and the same checks, answered as Server-Sent Events. **Access: a streamed reply is a read.** `/resume/stream` needs the owner-or-admin access `say` needs, like `/resume` with reply flags. An approver-only caller (`eddi-approver`, neither owner nor admin) gets `403` before the pause is touched, so the pause is not consumed; such callers decide with the plain `POST /agents/{conversationId}/resume` (no reply flags). Admission is shared with `/resume`, so every refusal it has (`400` malformed decision, unknown `toolDecisions`, bad secret context; `403`; `404`; `409` not paused / agent not deployed / `pauseId` no longer current; `503` shutting down) is the same plain HTTP error and **nothing has been written to the stream yet**. The stream's keep-alive starts only once the decision was accepted.

After acceptance the stream carries `hitl_resume` (`{"pauseId","verdict"}`, once, before anything of the continued turn), then `task_start`/`tool_call`/`tool_result`/`token`/`task_complete` as on a streamed `say`, and ends with `done`. If the continued turn pauses again, `approval_required` (`{"pauseId","pauseType","callCount"}`) is sent right before `done`, and only after the new pause is persisted (the same ordering guarantee as above) — so a client that reacts by calling `approval-status` or `resume` finds the pause. `/stream` sends the same `approval_required` when a streamed `say` ends paused. Every `tool_result` follows its `tool_call` in the same stream: a gated call that the resume settles without running (declined, or skipped, replayed or outcome-unknown) is announced with a `tool_call` (with its `toolDisplay`, if configured) immediately before its `tool_result`. A declined call has `status: "rejected"`; an approved one runs and is reported like any live call. The `tool_call`/`tool_result` events carry the tool name, call id, status and duration, never arguments or results; the agent's [`toolDisplay`](https://docs.labs.ai/agent-configuration/langchain.md#showing-a-tool-call-to-a-watching-client-tooldisplay) can add a label and a few allow-listed argument values to `tool_call`. **`task_complete.toolTrace` still carries redacted arguments and results**, so a client that forwards events to end users must drop it.

A resume that was accepted and then dropped (cancelled or ended in between, or refused by the coordinator) ends with an `error` event whose `code` is `conversation_ended`, `awaiting_approval`, `conversation_busy` or `resume_dropped`; a failure of the resumed turn, or losing the cluster lease, ends with `error` as well. A resumed turn the agent-timeout watchdog gave up on and whose pipeline never returned ends with `error` code `turn_timeout`, once the stream has carried none of its events for `systemRuntime.agentTimeoutInSeconds` plus one keep-alive interval (see `eddi.streaming.keepalive-interval-seconds` in the [configuration reference](https://docs.labs.ai/deployment-and-infrastructure/configuration-reference.md)). A vanished client does **not** cancel the resumed turn by default: a resume is a deliberate human decision, its approved tool calls may already have run, and cancelling would discard the turn and its trace while the side effects stay. The turn finishes and persists, and the client reads the outcome when it reconnects. `eddi.streaming.resume-cancel-on-client-disconnect` (default `false`) governs the resume stream only; set it to `true` to cancel (and discard) the resumed turn when nobody is watching. `/stream` keeps `eddi.streaming.cancel-on-client-disconnect` (default `true`). The non-streaming `/resume`, Slack, MCP and timeout resumes are unchanged.

The stored trace of the turn keeps each call's identity: `tool_call`, `tool_result` and `tool_error` entries carry `callId`; an approved call adds `hitl_approved {tool, callId}`, which records the human's **verdict**, not that the call ran (it is written before the checks that can still skip an approved call: truncated arguments, request changed, self-conversation, self-ungating - those add their own `hitl_*` entry after it); `hitl_rejected` adds the reviewer's own note for that call (`toolDecisions[callId].note`, redacted) and the call's arguments, redacted like the `tool_call` entry's.

**A reply is a read.** Deciding a pause and reading the conversation are separate rights. Resume admits an approver-only caller (the `eddi-approver` role, neither owner nor admin), but the reply returns the conversation, and with `returnCurrentStepOnly=false` or `returnDetailed=true` that can be its whole history. So a request carrying any reply flag also needs the owner-or-admin access `say` needs. An approver-only caller who asks for a reply gets `403` before the resume runs, so the pause is untouched and can still be decided without the flags. This is the same boundary as the approver read scope described further down.

**Approver when nobody is authenticated.** With an authenticated principal, `decidedBy` is that principal and the body value is ignored. If no one is authenticated (anonymous deployments) and the body carries a non-blank `decidedBy`, it is recorded as `unverified:<value>`, trimmed, cut to 128 characters, with every character outside `[A-Za-z0-9._@:+-]` replaced by `_`. **`unverified:` is a claim made by the caller, not an identity**: nothing checks it, so do not use it for authorization, only as a hint in the audit trail. Because it is not an identity, `unverified:` is a reserved principal prefix: an identity provider token whose name starts with it is refused at authentication, so no signed-in user can appear as an unverified claim.

### A pause and a new agent version

Conversations can follow compatible versions of their agent ([Running conversations and new agent versions](https://docs.labs.ai/conversations-and-orchestration/deployment-management-of-agents.md#running-conversations-and-new-agent-versions)), but never while paused: a resume finishes on the version that paused, under that version's gates, and the conversation moves only on the next turn after it. A pending approval is never re-evaluated against a newer version's configuration.

***

## Surface 2: Group Conversations

### Configuration

```json
{
  "hitlConfig": {
    "granularity": "TASK",
    "approvalTimeout": "PT10M",
    "timeoutPolicy": "AUTO_APPROVE",
    "onTaskRejection": "RETRY"
  },
  "phases": [
    { "name": "Execution", "type": "EXECUTE", "requiresApproval": true, "...": "..." }
  ]
}
```

| Field                               | Type                              | Default             | Description                                                                                                                                                                                                                                                                                                                                                                        |
| ----------------------------------- | --------------------------------- | ------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `granularity`                       | `PHASE` \| `TASK`                 | `PHASE`             | See [Granularity](#granularity-group-only)                                                                                                                                                                                                                                                                                                                                         |
| `approvalTimeout` / `timeoutPolicy` | as above                          | `WAIT_INDEFINITELY` | Validated at save time                                                                                                                                                                                                                                                                                                                                                             |
| `onTaskRejection`                   | `FAIL` \| `RETRY`                 | `FAIL`              | `FAIL`: rejected task is terminal. `RETRY`: task is re-queued (ASSIGNED) with the reviewer's note as feedback — the agent re-executes it addressing the rejection reason.                                                                                                                                                                                                          |
| `approvalCompletesBacklogTask`      | boolean                           | `false`             | Standing teams only: a backlog task a person approved at a `TASK` gate stays done at cadence writeback (`COMPLETED`, counted in `tasksApproved`) instead of returning to `PENDING` and running again. Timeout auto-approvals (`system:timeout`) do not count. See [Standing Teams](https://docs.labs.ai/conversations-and-orchestration/group-conversations.md#standing-teams-i13) |
| `phases[n].requiresApproval`        | boolean                           | `false`             | Per-phase approval gate                                                                                                                                                                                                                                                                                                                                                            |
| `phases[n].onApproved`              | object                            | `null`              | `TASK` granularity, EXECUTE phase: one httpcalls call per approved task, with the approved result — see [Group Approved-Result Actions](https://docs.labs.ai/conversations-and-orchestration/group-conversations/group-approved-result-actions.md)                                                                                                                                 |
| `review`                            | object                            | absent              | Result and synthesis edits on approval, reason codes, phase categories — see [HITL Review & Audit](https://docs.labs.ai/conversations-and-orchestration/hitl/hitl-review-and-audit.md#groups--hitlconfigreview)                                                                                                                                                                    |
| `approvalContext`                   | list of context blocks, at most 8 | absent              | What the approval card shows — see [HITL Approval Card Context](https://docs.labs.ai/conversations-and-orchestration/hitl/hitl-approval-context.md)                                                                                                                                                                                                                                |
| `requirePlanHash`                   | boolean                           | `false`             | Strict [plan binding](#plan-binding-planhash) for the group's approvals                                                                                                                                                                                                                                                                                                            |

### REST API

| Method | Path                                                          | Description                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  |
| ------ | ------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `POST` | `/groups/{groupId}/conversations/{gcId}/approve`              | Approve/reject (optionally per-task). The owner and admins get the conversation back; an approver-only caller gets only `{"state": …}` — the conversation is re-read after the resume is enqueued and can already hold member turns from after the approval (the MCP `approve_group_phase` returns the same)                                                                                                                                                                                                                                                                                                                 |
| `POST` | `/groups/{groupId}/conversations/{gcId}/approve/stream`       | Same, with SSE progress events. The owner and admins follow the resumed discussion to its end; an approver-only caller (`eddi-approver`, neither owner nor admin) gets the outcome of their decision — `hitl_resume` once the resumed run is enqueued (a resume that cannot be enqueued keeps the pause and sends `group_error` instead), or for a rejection `group_complete` without the synthesized answer — and the stream then closes, because the member turns that run after the resume are outside the approver's review window                                                                                       |
| `GET`  | `/groups/{groupId}/conversations/{gcId}/approval-status`      | Pause summary (state, pausedAt, pauseId, phase, pauseType, reason, timeoutPolicy, awaiting task ids; for a HUMAN-member turn `pendingMemberId`, `pendingMemberDisplayName` and `pendingHumanPrompt`); `?detail=full` returns the whole conversation incl. transcript — approver-only callers get `full` only while paused, `403` otherwise. `pendingHumanPrompt` is built from the discussion, so it goes only to the pending member, the owner, admins, and an approver while the conversation awaits approval; other approvers see who is up but not the prompt. The MCP `get_group_approval_status` applies the same rule |
| `GET`  | `/groups/{groupId}/conversations/pending-approvals?limit=100` | This group's paused conversations as summaries (bounded, max 1000)                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           |
| `GET`  | `/groups/pending-approvals?limit=100`                         | **Global approval inbox** across all groups (bounded, max 1000): admins/approvers see everything, other callers their own conversations                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      |
| `POST` | `/groups/{groupId}/conversations/{gcId}/cancel`               | Cancel the discussion — `409` if it is already in a terminal state. An approver-only caller may cancel only a paused discussion (`AWAITING_APPROVAL` or `AWAITING_HUMAN_INPUT`), receives `{"state": "CANCELLED"}` rather than the conversation, and gets `403` on a running one — see [Who May Decide](#who-may-decide)                                                                                                                                                                                                                                                                                                     |

The `{groupId}` path segment is validated: a conversation that does not belong to the given group returns `404` on read/delete/cancel/approve/approval-status. A discussion deleted concurrently with an approve/cancel also returns `404` (never a misleading `409` state conflict).

**Approval bodies:**

```json
// Phase-level
{ "decision": { "verdict": "APPROVED", "note": "Proceed" } }

// Task-level (selective; values are case-insensitive)
{ "decision": { "verdict": "APPROVED" },
  "taskApprovals": { "task-abc": "APPROVED", "task-def": "REJECTED" } }

// Task-level shortcut: verdict APPROVED with no taskApprovals approves ALL pending tasks
```

Unknown task IDs, tasks not awaiting approval, and unknown decision values (anything other than case-insensitive `APPROVED`/`REJECTED`) are rejected with `400` **before anything is applied** — the pause and its timeout schedule survive a bad request. An explicit empty `taskApprovals` map (`{}`) behaves like the approve-all shortcut. Resume-vs-resume and cancel-vs-approve races are arbitrated by a DB-level compare-and-set; the loser gets `409`. For group discussions that compare-and-set covers **state and pause together**: the group conversation persists a `pauseId` (the same value `approval-status` reports) and approve, reject, cancel of a paused discussion and the human-turn timeout skip each write with *state AND pauseId* in one atomic conditional update (MongoDB filter / PostgreSQL `UPDATE ... WHERE`). A decision that was read against one pause therefore cannot land on a later pause of the same state — a resume followed by a re-pause between the read and the write makes it conflict (`409`, or a no-op for a timeout) instead of acting on a request the decider never saw. Discussions persisted before the field existed carry no `pauseId`; their write matches it as absent, which stays state-bound until the next write stamps the id.

**SSE events:** `awaiting_approval` (stream closes; re-attach via `/approve/stream`), `hitl_resume` (emitted once the approve commits — for the owner and admins the stream stays open for the resumed discussion's events; an approver-only caller's stream sends it once the resumed run is enqueued and then closes, see the `approve/stream` row above), `cancelled` and `group_complete`/`group_error` (stream closes), plus the standard discussion events. Every terminal outcome — including REJECTED verdicts, config-drift aborts, and resume failures — emits a closing event, so `/approve/stream` clients never hang.

### Config drift protection

Pauses can last days. On resume, the bookmarked phase (index + name) is verified against the **current** group config; if phases were added, removed, or reordered in between, the resume is aborted and the **pause is restored** (state back to `AWAITING_APPROVAL`, timeout schedule re-armed, `group_error` emitted with the mismatch details) — fix the config and approve again, or cancel. Transient failures before the resumed execution starts restore the pause the same way instead of failing the discussion terminally.

### No-progress protection (TASK granularity)

A TASK-gate pause caused by turn-budget exhaustion could previously loop forever under `AUTO_APPROVE` (approve → zero work → identical re-pause). Resumes now fingerprint the pause (phase + non-terminal task states): an **explicit human APPROVED grants a fresh turn budget**; if a resumed leg re-pauses with an identical fingerprint (no progress), the discussion **fails with an actionable error** instead of pausing again — guaranteed termination. Automated (`system:*`) approvals never grant fresh budget, so a timeout policy cannot sustain the loop.

***

## Tool-Level Approval Gating

The two surfaces above pause **turns** (a behavior-rule `PAUSE_CONVERSATION`) or **phases** (`requiresApproval`). Tool-level HITL is a third, finer gate: it pauses when the LLM **invokes a matching tool**, before that tool executes. It works for **all eight tool sources** — built-in `@Tool`, `http` (httpcall), `mcp`, `a2a`, `dynamic` (dynamic agents), `memory`, `recall`, and `team` (the cross-team [`handoff_to_team`](https://docs.labs.ai/conversations-and-orchestration/group-conversations/team-handoff.md) tool).

The gate lives in the tool-execution loop (`AgentOrchestrator`), so it is **fail-safe**: a gated call is intercepted *before* execution. It reuses the existing pause machinery — same `AWAITING_HUMAN` state, same `POST /agents/{id}/resume` endpoint, same timeout/audit/Slack/crash-recovery paths — with `hitlPauseType = "TOOL_CALL"` distinguishing it from a `RULE` pause. A single resume verdict resolves either pause type.

**Tool quotas (**[**`toolQuotas`**](https://docs.labs.ai/agent-configuration/langchain.md#per-subject-tool-quotas-toolquotas)**).** A gated call whose per-subject quota is **already exhausted** is refused immediately — the model gets a final `NOT_EXECUTED` result and the conversation does not pause — so a human is never asked to approve a call that would then be refused. The check is a read; nothing is counted while a call waits. The quota is applied again, and the call counted, when the approved call actually runs on resume, through the same execution pipeline as a live call; a call approved after the allowance was spent elsewhere is refused then. A rejected call is never counted.

### Configuration

`toolApprovals` has two homes, both optional:

* **Agent-level default** — `AgentConfiguration.hitlConfig.toolApprovals` (applies to every LLM task in the agent).
* **Per-task override** — `LlmConfiguration.task[n].toolApprovals` (a langchain task). How it combines with the agent-level block is decided by `eddi.hitl.tool.task-approvals.mode`: under the default **`strict`** the task block can only *strengthen* the agent gate (patterns are united, task-level `exempt` is ignored, task-level `AUTO_APPROVE` is demoted); under **`replace`** it is a full replace and the agent-level block is ignored for that task — the pre-6.3.0 behavior. See [Precedence](#precedence) for the per-field rules.

```json
{
  "hitlConfig": {
    "toolApprovals": {
      "requireApproval": ["mcp:*", "delete_*", "transfer_funds"],
      "exempt": ["mcp:read_*"],
      "maxPausesPerTurn": 3,
      "maxAutoApprovalsPerTurn": 2,
      "onNoProgress": "WAIT_FOR_HUMAN",
      "approvalTimeout": "PT30M",
      "timeoutPolicy": "AUTO_REJECT",
      "pauseReason": "Approval required for {toolNames}",
      "pendingMessage": "Waiting for a human to approve {toolNames}…",
      "inGroupTurns": "REJECT"
    }
  }
}
```

| Field                     | Type                                                              | Default                                                   | Description                                                                                                                                                                                                                 |
| ------------------------- | ----------------------------------------------------------------- | --------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `requireApproval`         | list of glob patterns                                             | absent/empty = **gate off**                               | Tools whose calls must be human-approved. An absent or empty list disables tool gating entirely (backward compatible).                                                                                                      |
| `exempt`                  | list of glob patterns                                             | `null`                                                    | Exemptions — **always beat** `requireApproval`. A pattern in `exempt` with no `requireApproval` is rejected at save time (no effect).                                                                                       |
| `maxPausesPerTurn`        | integer, `1`..`10`                                                | `3`                                                       | Max tool pauses in one turn. **Fail-closed at the cap**: once reached, the remaining gated calls in that turn are auto-error-resulted (`hitl_pause_cap`) rather than executed — never silently run.                         |
| `maxAutoApprovalsPerTurn` | integer, `0`..`10`                                                | `2`                                                       | Max consecutive `system:*` (timeout) auto-approvals per turn before the no-progress guard applies `onNoProgress`.                                                                                                           |
| `onNoProgress`            | `WAIT_FOR_HUMAN` \| `AUTO_REJECT` \| `ABORT`                      | `WAIT_FOR_HUMAN`                                          | What happens when a tool pause re-pauses with an identical fingerprint after a system decision (loop protection). `WAIT_FOR_HUMAN` demotes the re-pause to `WAIT_INDEFINITELY`; `AUTO_REJECT` reject-alls; `ABORT` cancels. |
| `approvalTimeout`         | ISO-8601 duration                                                 | inherits `hitlConfig.approvalTimeout`                     | Tool-pause timeout override. A finite policy requires a positive duration (validated at save time).                                                                                                                         |
| `timeoutPolicy`           | `AUTO_APPROVE` \| `AUTO_REJECT` \| `ABORT` \| `WAIT_INDEFINITELY` | see [Effective timeout policy](#effective-timeout-policy) | Tool-pause timeout policy override.                                                                                                                                                                                         |
| `pauseReason`             | string, ≤ 500 chars                                               | generic                                                   | Approver-facing reason; the literal `{toolNames}` placeholder is substituted with the gated tool names.                                                                                                                     |
| `pendingMessage`          | string, ≤ 500 chars                                               | `null`                                                    | End-user-facing message stored as **public output** at pause commit (so a chat UI shows the user *why* the turn stalled). `{toolNames}` is substituted.                                                                     |
| `inGroupTurns`            | `REJECT`                                                          | `REJECT`                                                  | Behavior when a member agent's tool call is gated inside a group turn. `INBOX` is **reserved** (rejected with a 400 in v1). See [Group members](#group-members).                                                            |
| `rules`                   | list of objects                                                   | `null`                                                    | Per-tool friction overrides. See [Per-tool approval rules](#per-tool-approval-rules).                                                                                                                                       |

All values are validated at **save time** and on ZIP import (`HitlConfigValidation.validateToolApprovals`): bad patterns (with the offending index), a pattern in both `requireApproval` and `exempt`, duplicates, `exempt` without `requireApproval`, out-of-range integers, a reserved `INBOX`, a finite policy without a valid `approvalTimeout`, and overlong reason/message all yield an actionable 400 — the gate never degrades silently at runtime.

### Per-tool approval rules

The fields above are single scalars for *every* gated tool, so "deploy an agent" and "create an agent" cannot differ in how long a reviewer has or what the approval card says. `rules` fixes that:

```json
{
  "requireApproval": ["http.post:*", "http.put:*", "http.patch:*", "http.delete:*"],
  "exempt": ["http.get:*"],
  "rules": [
    { "match": "http.post:/agentstore/agents",
      "timeoutPolicy": "WAIT_INDEFINITELY",
      "pauseReason": "Creating a new agent — review the whole config" },
    { "match": "http.post:/administration/{environment}/deploy/{agentId}",
      "timeoutPolicy": "AUTO_REJECT", "approvalTimeout": "PT5M" },
    { "match": "http.delete:*", "timeoutPolicy": "WAIT_INDEFINITELY" }
  ]
}
```

| Field              | Type                                                              | Description                                                                                                                                                                                                                                                           |
| ------------------ | ----------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `match`            | pattern                                                           | **Required.** Same [pattern language](#pattern-language) as `requireApproval` — bare name, `source:name`, or `source.method:path`.                                                                                                                                    |
| `timeoutPolicy`    | `AUTO_APPROVE` \| `AUTO_REJECT` \| `ABORT` \| `WAIT_INDEFINITELY` | Overrides `toolApprovals.timeoutPolicy` for this rule.                                                                                                                                                                                                                |
| `approvalTimeout`  | ISO-8601 duration                                                 | Overrides `toolApprovals.approvalTimeout`.                                                                                                                                                                                                                            |
| `pauseReason`      | string, ≤ 500 chars                                               | Overrides `toolApprovals.pauseReason`. `{toolNames}` is substituted.                                                                                                                                                                                                  |
| `pendingMessage`   | string, ≤ 500 chars                                               | Overrides `toolApprovals.pendingMessage`. `{toolNames}` is substituted.                                                                                                                                                                                               |
| `approvalCategory` | string                                                            | Category the calls this rule governs are recorded under in the audit ledger (absent: `tool:<pattern>`). See [HITL Review & Audit](https://docs.labs.ai/conversations-and-orchestration/hitl/hitl-review-and-audit.md#tool-rules--toolapprovalsrulesapprovalcategory). |
| `context`          | list of context blocks, at most 4                                 | Approval-card context for the calls this rule governs; `call.*` is available. See [HITL Approval Card Context](https://docs.labs.ai/conversations-and-orchestration/hitl/hitl-approval-context.md).                                                                   |

> **A rule tunes friction; it never gates or ungates.** Whether a call needs approval is decided *only* by `requireApproval`/`exempt`. This is deliberate: the gate allows an unmatched call, so it only survives by gating broadly and exempting narrowly — a rule able to ungate would let a config grant capability by adding an entry.

Resolution (`ToolApprovalRules`):

1. **Per call, most specific wins.** Rules are tried fewest-wildcards-first, then longest-pattern-first, so `http.post:/agentstore/agents` beats `http.post:*` **whatever order they are listed in**.
2. **Per batch, strictest wins.** A model can emit several gated calls in one message and they pause *together*, under one policy — so the matched rules are reduced to one: the rule assuming the least human authority on timeout, ordered `WAIT_INDEFINITELY` > `ABORT` > `AUTO_REJECT` > `AUTO_APPROVE` > (no policy stated). Bundling a lenient call into a batch can therefore never soften a stricter rule. Ties break on specificity. A gated call that **no** policy-stating rule covers counts too: it carries the policy it would inherit on its own (`toolApprovals.timeoutPolicy`, else the outer `hitlConfig.timeoutPolicy` with `AUTO_APPROVE` demoted to `WAIT_INDEFINITELY`), and that joins the comparison — so an `AUTO_APPROVE` rule for one endpoint never auto-approves an unrelated call bundled into the same message.
3. **Fields fall back individually** to the `toolApprovals` scalars, so a rule that sets only `pauseReason` keeps the configured timeout policy.

The governing rule is resolved **at gate time** and persisted on the pending batch (`PendingToolCallBatch.effectiveRule`), because the persisted batch keeps tool names and sources but no endpoints — an endpoint-addressed rule could not be re-matched after the pause. Each gated call also records the rule that tuned it (`matchedRule`), so an approver can tell which call brought the batch's policy.

Validation mirrors `requireApproval`: `match` goes through the same `ToolApprovalPatterns.validate`, duplicates are refused, `rules` without `requireApproval` is refused, a finite `timeoutPolicy` with no duration at either level is refused, and a `match` string-identical to an `exempt` pattern is refused — an exempt call is never gated, so such a rule could never apply. Only *exact* equality is refused: a broader rule may legitimately overlap an exemption (`http.*:*` alongside an exempt `http.get:*`) while still covering gated calls. The counter `eddi.hitl.rule.matched{match="<pattern>"}` records which rules actually fire (deduplicated per pause; the tag is the configured pattern, never a URL or argument).

### Pattern language

Patterns are matched by `ToolApprovalPatterns` / `ToolApprovalGate`:

* **`*` is the only wildcard** — it matches any run of characters (including empty). Every other character is a quoted literal, so compilation is **ReDoS-safe**.
* **Source-qualified or bare.** A pattern may carry a known source prefix (`mcp:read_*`, `http:*`) or match the bare tool name (`delete_account`). A call is tested against the endpoint-qualified form **first** (where one exists, see below), then `source:name`, then the bare dispatch name — a tool with an unknown source still matches bare-name patterns (fail-safe).
* **Endpoint-qualified** (`http` tools only). A pattern may also address *what a tool calls* rather than what it is named: `http.post:*` matches every POST, `http.post:/agentstore/agents` matches exactly one endpoint. This is the robust form for tools generated from an OpenAPI spec, whose names come from `operationId` or a slug and change when the spec does — `http.post:*` keeps gating every mutation even when a name changes or a new endpoint appears. The path is matched **as the httpcall config declares it**, normalised to a leading slash (an absolute URL contributes only its path).
* **Known sources** (the only accepted prefixes): `builtin`, `http`, `mcp`, `a2a`, `dynamic`, `memory`, `recall`, `team` (the cross-team [`handoff_to_team`](https://docs.labs.ai/conversations-and-orchestration/group-conversations/team-handoff.md) tool). An unknown prefix is rejected at save time with a typo suggestion (Levenshtein ≤ 2). Only `http` may carry a method qualifier: it is the only source whose tools record an endpoint, so `mcp.post:` is rejected rather than saved as a pattern nothing could match.
* **Allowed characters:** `A-Za-z0-9_-.:*` plus `/` `{` `}` for endpoint path templates. Braces are matched literally, not as regex quantifiers.
* **Case-sensitive.** Patterns match tool names exactly; `Delete_*` does not match `delete_account`. An endpoint path is matched as the httpcall config declares it, so its case must match too; the method half is normalised to lower case.
* Patterns may not start or end with `:`, and are capped at 256 characters.

### Precedence

| Rule                                                                  | Behavior                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            |
| --------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **Task combines with agent per `eddi.hitl.tool.task-approvals.mode`** | **`strict` (default):** the task block can only STRENGTHEN the agent gate — `requireApproval` is the union of both lists, task-level `exempt` entries are ignored (exempt beats require, so a task-added exemption is precisely the ungating vector), task-level `AUTO_APPROVE` (scalar or rule) is demoted to `WAIT_INDEFINITELY` unless the agent-level policy itself grants it, and `maxAutoApprovalsPerTurn` takes the minimum. **`replace` (legacy):** a present task block is a full replace of the agent-level block — the pre-6.3.0 behavior, for designs that deliberately loosen one task. See `TaskToolApprovalsResolver`.                                                                                                                                                                                               |
| **Exempt beats require**                                              | If a call matches any `exempt` pattern, it runs — even if it also matches `requireApproval`.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        |
| **Absent/empty `requireApproval` = gate off**                         | No `requireApproval` patterns → the gate is fully inactive; every call runs.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        |
| **Any match suffices**                                                | A call is gated if it matches *any* `requireApproval` pattern (and no `exempt` pattern).                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            |
| **An approval authorises one execution**                              | A call the human approved runs once. A model that reissues *that same call* in the continuation is asking to run it again, so the reissue pauses for a new decision, with the reason "repeat of an approved call that has already been executed" (it used to run a second time on the original approval). The match binds to the call id **and** the tool name **and** a canonical fingerprint of the arguments (key order and whitespace ignored), and it is used up by the first match. A different call that merely reuses the approved id — some OpenAI-compatible servers number calls `call_1` on every turn — is gated like any other. While the gate is active, an empty-string id is treated as missing and a repeated id within one model message is replaced, so per-call verdicts can never apply to two calls at once. |

### Effective timeout policy

Tool pauses resolve their effective timeout policy with a deliberate rule (`ConversationHitlService.applyEffectiveToolTimeoutPolicy`):

1. The **governing** [**rule**](#per-tool-approval-rules)'s `timeoutPolicy` wins — the most specific statement in the config, so it is honoured verbatim (`AUTO_APPROVE` included).
2. Otherwise an **explicit** `toolApprovals.timeoutPolicy` wins verbatim — including an explicit `AUTO_APPROVE` (the designer opted in at the tool level). Its `approvalTimeout` is used, falling back to the outer `hitlConfig.approvalTimeout`.
3. Otherwise the outer `hitlConfig.timeoutPolicy`/`approvalTimeout` is inherited, **except** an inherited `AUTO_APPROVE` is **demoted to `WAIT_INDEFINITELY`** — a silent timeout must never auto-execute a gated tool call (that is exactly what the gate exists to prevent).
4. Absent config on every level leaves the default `WAIT_INDEFINITELY`.

The duration resolves down the same chain independently (rule → `toolApprovals` → `hitlConfig`), so a rule that states only a policy still inherits a clock and actually fires.

> **Key rule:** `AUTO_APPROVE` applies to a **tool** pause **only when set explicitly on `toolApprovals`**. Agent-level `AUTO_APPROVE` covers RULE pauses but is demoted for tool pauses. Save-time emits a WARN (not a 400) when an agent sets `AUTO_APPROVE` and a `toolApprovals` block without its own `timeoutPolicy`.

### Resuming — per-call verdicts and amendments

A tool pause is resumed through the **same** `POST /agents/{conversationId}/resume` endpoint. The top-level verdict resolves the whole batch; the optional `toolDecisions` map (keyed by `callId`) lets a reviewer decide individual calls and amend an approved call's arguments before it runs. **Calls not listed in `toolDecisions` inherit the top-level verdict.**

```jsonc
// Approve everything (all-or-nothing — the common case)
{ "verdict": "APPROVED", "note": "looks fine" }

// Reject everything
{ "verdict": "REJECTED", "note": "not this time" }

// Mixed: approve one (with amended arguments), reject another, the rest inherit APPROVED
{
  "verdict": "APPROVED",
  "toolDecisions": {
    "call-1": { "verdict": "APPROVED", "amendedArguments": "{\"to\":\"ops@acme.com\"}" },
    "call-2": { "verdict": "REJECTED", "note": "wrong recipient" }
  }
}
```

Validation (all `400`, applied **before** any state changes, so a bad body never consumes the pause):

* `toolDecisions` is only valid for a `TOOL_CALL` pause.
* An unknown `callId` (not in the pending batch) is rejected (the body names the valid ids).
* Each listed call requires a `verdict`; per-call `note` ≤ **1024** chars (top-level `note` ≤ 4096).
* A listed call that is `REJECTED` and has no note of its own (absent or blank) uses the top-level `note`, so a client can send one note for the whole decision and still list the calls it rejects. An `APPROVED` call's note is never shown to the model.
* Top-level `REJECTED` combined with any per-call `APPROVED` is contradictory — set the top-level verdict to `APPROVED` to mix outcomes.
* `amendedArguments` is only valid on an `APPROVED` call, must be a **JSON object**, is size-capped, and cannot amend a call whose arguments were truncated at pause time (approve/reject it as-is).

A **REJECTED** call is not executed; instead the LLM receives a structured rejection tool-result (`status: REJECTED_BY_REVIEWER`, the tool name and the reviewer's note) — rejection feeds *back into* the model rather than aborting the turn. What the result tells the model to do depends on who decided and whether a note came with it (`hitlConfig.onRejection` does not change this: it applies to rule pauses only):

* **A person left a note.** The result says the user did not approve the call and left a note: if the note asks for changes, call the tool again with exactly those changes and nothing else changed; if it declines or asks for something else, do not call it again and reply briefly. A note is therefore a way to ask for a revision. The re-proposed call is a new call: it is gated like any other, pauses again (a new `pauseId` and its own timeout) and needs its own approval. Nothing a note says changes a call that was approved.
* **No note, or an automated decision.** The result keeps the plain "declined" text: do not retry this exact call, explain the situation and offer alternatives. An automated decision is one whose `decidedBy` starts with `system:` — the timeout auto-reject (`system:timeout`) and the group-conversation auto-reject (`system:group`, note "tool approval is not available during group discussions in this version"). The note on those is an explanation, not a request, and asking the model to revise would only make it retry a call that can never be approved.

Each re-proposal is another pause and counts toward `maxPausesPerTurn`. A deployment that expects notes to come back as revisions should raise it (the maximum is `10`); at the cap the remaining gated calls in the turn are refused.

### `pauseDetails` for a tool pause

`GET /agents/{id}/approval-status` returns a `TOOL_CALL` `pauseDetails` object (computed at read time; see the [`pauseDetails` shape](#pausedetails-shape) reference above for the full JSON). Its `calls[].arguments` is **always** the redacted, size-capped value (`argumentsRedacted`) — the raw arguments never appear. `executedUngatedCalls` names ungated calls in the same batch that already ran (see decision 4). `outcomeUnknown` lists callIds with an `EXECUTING` journal entry — a prior approval that crashed mid-execution — and is empty in the common case.

### Batching — several calls, one pause

The gate classifies **every tool call a model emits in one message** together (`ToolLoopRunner`, the `toolApprovalGate.classify` over the whole `toolExecutionRequests()` list). All the gated ones pause as **one batch**: one `AWAITING_HUMAN` state, one `pauseDetails.calls[]`, one decision (with a verdict per call if the reviewer wants one). Ungated calls in the same message execute immediately. Nothing is provider-specific here — the engine batches whatever the model emits; whether a given model emits several calls in one turn at all is up to the model, and a prompt that asks for it (the Platform Operator's does) is the lever.

Two consequences when you design for fewer approvals:

* **Independent calls can share a pause.** Writes that do not depend on each other's results can be issued together and approved in one sitting. One pause counts once toward `maxPausesPerTurn`, however many calls it holds, and the strictest governing rule applies to the whole batch (see [Per-tool approval rules](#per-tool-approval-rules)).
* **Dependent calls cannot.** Approval binds to the resolved request ([below](#request-pinning--approval-binds-to-a-request-not-a-tool-name)), so a call whose arguments depend on an earlier call's *result* — a version number or id it returns — can only be proposed once that result exists. Approved calls run in the order the model emitted them, so a batch is for independent work, not for pipelining.

The Platform Operator uses this for multi-step changes: it lists the whole plan first, sends the independent writes as parallel tool calls, and lands the edit with a single `POST /agentstore/agents/{id}/cascade` ([see](https://docs.labs.ai/conversations-and-orchestration/deployment-management-of-agents.md#landing-resource-changes-in-one-pass)) instead of separate repoint and deploy calls — connecting a knowledge base takes two approvals instead of five.

### Request pinning — approval binds to a request, not a tool name

For an `http`-sourced call, the tool name alone tells an approver little: it comes from the endpoint's `operationId` (or a generated slug) and says nothing about which resource is targeted or with what body. So at gate time each gated httpcall tool is **resolved** — `IApiCallExecutor.resolve` builds the method, URL, query, headers and body it would send, without sending it — and both a **redacted preview** and a **SHA-256 fingerprint** of that resolved request are persisted on the pause (`PendingToolCall.requestPreview`, `.requestFingerprint`). The preview is what an approver should actually look at, not the raw tool arguments.

`GET .../approval-status` surfaces this: each entry in `pauseDetails.calls[]` carries `requestPinned` (boolean) and, when the call could be resolved at all, `requestPreview` — `{method, uri, queryParams, headers, body, bodyTruncated}`, all already redacted. The raw fingerprint itself is never exposed; it is an internal comparison value with no meaning to a human.

**The two fields are independent, and a client must not infer one from the other.** `requestPinned` says whether a fingerprint will be *enforced* before execution — not whether a preview exists. An `http` call carrying `preRequest.propertyInstructions` is previewed best-effort but deliberately left unpinnable, so it arrives with `requestPinned: false` and a non-null `requestPreview`: show it, but do not present it as guaranteed to be what runs. `requestPreview: null` means there was nothing to resolve (every non-`http` tool), which is not a resolution failure a caller should treat as an error.

On resume, an **approved** call is re-resolved and its fingerprint re-compared immediately before execution. A mismatch refuses the call — a synthetic `{"status":"NOT_EXECUTED","reason":"the request changed after it was approved"}` result, an alertable log marker (`WARN hitl.tool.request_changed` — tool + callId + reason only, never the request itself; not an audit-ledger entry, for the same reason as `hitl.tool.outcome_unknown` below), and the rest of the batch proceeds normally. This is what makes the approval bind to *the request that runs*, not to the name of the tool that was called.

**An agent may not take its own approval gate away.** Two more checks run on every approved call immediately before it executes, in `ToolLoopResumer` — the one place the Manager, the Slack buttons, the MCP `resume_conversation` tool and REST `/resume` all funnel through. A **write to the acting agent itself** (any non-`GET` request whose URI names the agent the conversation is running — `PUT /agentstore/agents/{own}/updateResourceUri`, the hinge of a "repoint my own workflow and redeploy" loop, but also deploying, undeploying or starting a conversation with itself) and an **LLM-configuration write whose body carries `toolApprovals`** at any depth (or that cannot be parsed to show it does not) are refused with `{"status":"NOT_EXECUTED","reason":"…"}`, logged as `WARN hitl.tool.request_changed`, and the rest of the batch proceeds. A call without a resolvable request falls back to its raw arguments, erring toward refusal. Changing what gates an agent is a human's edit in the Manager, not an approval click. The Manager's own guards (`self-guard.ts`, `gate-guard.ts`) stay, so an approver is told before spending a decision on a call the engine will refuse.

Since 6.6.0 the same gate also covers what the agent id alone left open (security review 2026-10-15, L13). **The resources the agent runs on:** before the batch executes, `ToolLoopResumer` reads the acting agent's workflows and every extension document those workflows reference (its LLM configuration, rule sets, api calls…) from the stores, and a write to any of those ids — `PUT /llmstore/llms/{own-llm-id}` with a permissive document names the agent nowhere — is refused with `an agent may not modify the workflow or configuration resources it runs on`. If the stores cannot be read, every write to a configuration store in that batch is refused rather than guessed at. **Other agents' gates:** a write to another agent's document on the agent store is compared with what is stored — a full `PUT` that drops, loosens or adds `hitlConfig.toolApprovals`, and a `PATCH` naming `hitlConfig` or `toolApprovals` anywhere, are refused with `an agent may not remove or change another agent's tool-approval gate (hitlConfig)`; a faithful copy that keeps the gate as it is runs. Both rules apply to the request as finally sent (`ApprovedCallScope`), not only to the preview.

**Headers are fingerprinted redacted; the body is fingerprinted raw.** For **headers** the fingerprint deliberately covers the redacted form: `ApiCallExecutor` resolves `${caller:token}` into `Authorization` at execution time, and the approver is routinely a different person than whoever's turn raised the pause — fingerprinting the live header would mismatch on every cross-user approval (the normal case) and the check would have to be disabled. Redacting first makes the fingerprint answer what approval is actually about — *what the request does* — and leaves *whose credentials carry it* to authentication, which the fingerprint does not participate in.

The **body** has no such legitimate variance (`${caller:token}` is rejected outside headers, and a `${vault:…}` reference resolves identically at gate time and at execution), so it is hashed as resolved and only the *stored* copy is redacted. Redacting before hashing would collapse two different credentials to one marker and therefore to one fingerprint, letting a swapped secret pass the pre-execution re-check unnoticed.

The fingerprint is never returned through the client API — but it is a SHA-256 digest, not encryption, and it *is* persisted on the pause record. Treat the stored value as sensitive internal data: for a predictable body it supports offline guessing, and equal digests reveal that two requests were identical. It is excluded from every client-facing projection for that reason, not merely because it is meaningless to a human.

Query parameters get the same treatment as the body — hashed as resolved, redacted for display — because `?api_key=…` is a conventional way to pass a credential and the query string is shown to the approver too. A repeated parameter (`?tag=a&tag=b`) is canonicalised as one length-prefixed field *per value*, so a single value containing the display separator cannot impersonate two.

Body and query redaction are by **value shape**, not field name — a body is caller-defined JSON (or another format entirely) with no fixed key vocabulary to match on the way headers have. `SecretRedactionFilter` (the same filter behind `argumentsRedacted`) removes OpenAI/Anthropic-style keys, bearer tokens and vault references wherever they appear. A hand-rolled secret in a generically named field, matching none of those shapes, is not caught — the same limitation the redacted tool arguments already carry, and the reason a config write that must carry a credential belongs behind a vault reference rather than a literal.

**A call can be unpinned**, and that is a deliberate degrade, not a bug. A call is left unpinnable whenever `execute()` could legitimately build a request that `resolve()` did not — the guard is "never pin what cannot be honoured", so the set is defined by that property rather than by a list of features:

| Unpinnable when                                               | Why `execute()` can diverge from `resolve()`                                                                                                                                                                                       |
| ------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| The tool is not `http` (builtin/mcp/a2a)                      | There is no HTTP request on this side of the boundary to pin.                                                                                                                                                                      |
| `preRequest.propertyInstructions` is set                      | Those write to conversation memory, so resolving them ahead of execution would apply them twice.                                                                                                                                   |
| `fireAndForget` **and** `preRequest.batchRequests`            | The batch expands at execution time into N requests, none of them the single one that was previewed.                                                                                                                               |
| `postResponse.retryApiCallInstruction` with `maxRetries >= 1` | `buildRequest` sits inside the retry loop, and each attempt re-renders templates against a memory that the previous attempt wrote to (`{…Error}`, `{…HttpCode}`, `{responseObjectName}`). Attempt 2 is a request nobody previewed. |

The retry row is the easy one to trip over: `RetryApiCallInstruction.maxRetries` **defaults to 3**, so `"postResponse": {"retryApiCallInstruction": {}}` is by itself enough to unpin an otherwise-pinnable write — and a retry can fire on a **2xx** response when `responseValuePathMatchers` matches, not only on `retryOnHttpCodes`. Read `requestPinned` per call; do not infer it from the endpoint.

**A call that is certain to be refused is never put in front of a human.** Resolving a gated call runs the same request build as executing it, including the [credential-reference rule](https://docs.labs.ai/security-and-compliance/secrets-vault.md#where-vault-references-work) (a `${vault:…}`, `${connection:…}` or `${caller:…}` reference that came from conversation data, not from the configuration, refuses the call). That refusal is deterministic — the same arguments fail on every attempt — so gate time handles it before the pause: the gated call is dropped from the pending batch, the guard's message (it names the reference and the field, never a value) goes back to the model as that call's tool result, and the trace records `credential_reference_refused`. The rest of the batch is unaffected: ungated calls run, other gated calls still pause. Previously the resolve failure was swallowed as "approved unpinned", so the approver was shown a card for a call that was refused the instant they approved it — an approval spent on nothing. Only this one failure is treated as deterministic; any other failure to resolve, and a call that [can legitimately diverge](#request-pinning--approval-binds-to-a-request-not-a-tool-name) between resolve and execute (the unpinnable set below), still pauses and is approved unpinned. The task's [`toolCallGuardrails`](https://docs.labs.ai/agent-configuration/langchain/tool-call-guardrails.md) run even earlier, before the gate classifies the batch: a call they refuse never pauses, a call they redact pauses with the redacted arguments, and an approved or edited call is screened again, block-only, before it runs.

An unpinned call (`requestFingerprint == null`) is approved on name and arguments alone, exactly as before pinning existed — nothing is ever refused on a comparison that was never sound. An **amended** call (`amendedArguments` set) is likewise never fingerprint-checked: the approver rewrote the request themselves, so the pin describes the request they replaced.

Three situations fail **closed** instead — refused, not silently allowed — because "cannot verify" is a different answer than "unchanged": the tool disappeared from the workflow between pause and resume, re-resolution throws, or the call's config gained any of the unpinnable properties above mid-pause (a pinned call becoming unpinnable — adding `propertyInstructions`, or a `retryApiCallInstruction`, while a human is deciding). Treating any of these as "unchanged" would make reconfiguring an agent while a human is deciding the way around the guard.

### The execution journal (at-most-once)

Approved tool executions are protected by a write-ahead journal (`IHitlToolJournalStore`) so a human approval is executed **at most once**, across pod crashes and re-approvals:

1. Before running an approved tool, `tryClaim` inserts an `EXECUTING` entry keyed by `(conversationId, pauseEpoch, callId)`. The `pauseEpoch` is a per-pause UUID — providers may reuse tool-call ids across different pauses in one conversation, so the epoch keeps them distinct.
2. After the tool returns, `markExecuted` stores the capped result.
3. On resume, an `EXECUTED` entry **replays its stored result** — the tool is never re-run.
4. An `EXECUTING` entry (a crash *inside* the tool) yields an honest `EXECUTION_OUTCOME_UNKNOWN` result fed to the LLM: *"a previous execution attempt was interrupted; it may or may not have taken effect — verify externally before retrying."* This is logged with an alertable marker (`WARN hitl.tool.outcome_unknown`, not an audit-ledger entry — the orchestrator has no audit collector in scope here) and surfaced in `pauseDetails.outcomeUnknown`.

**Retention (MongoDB).** `eddi.hitl.tool.journal-retention` (default `30d`) is a TTL index on `claimedAt` that covers `EXECUTED` entries only (`idx_journal_ttl_completed`, a partial index), so a crash-orphaned `EXECUTING` claim is kept until its conversation is deleted. An older pod that is still running during a rolling update recreates the previous unfiltered index (`idx_journal_ttl_claimed`), which would expire those claims again. The store therefore reconciles at startup and every `eddi.hitl.tool.journal-reconcile-interval` (default `15m`): any unfiltered TTL index on `claimedAt` is dropped (one `WARN` per occurrence) and the partial index is re-created if missing. PostgreSQL keeps no such index.

> **Outcome-unknown contract:** the framework **never silently re-executes** a tool that may have already run. A crash between "claimed" and "executed" is reported as genuinely unknown, not retried — the human (or a downstream check) decides what to do.

### Slack

The Slack integration is tool-pause-aware. When `hitlApprovalChannel` is set, a `TOOL_CALL` pause posts an interactive approval card that additionally renders one context block per pending call — `toolName` plus its **redacted, 300-char-truncated arguments** (max 5 calls, then `+N more`) — so a reviewer sees *what* they are approving. The raw argument value is never accessed. The in-thread pause notice stays pause-reason-only. Slack buttons decide the whole batch; a single-call batch can also be **edited and approved** in a Slack modal ([HITL Review & Audit](https://docs.labs.ai/conversations-and-orchestration/hitl/hitl-review-and-audit.md#slack-edit-and-reject-modals)). Per-call verdicts for several calls require the REST resume body or the MCP `resume_conversation` tool's `toolDecisionsJson`. See [Slack Integration](#slack-integration).

### Group members

A group has no per-member human reviewer, so a member agent's gated tool call inside a group turn is resolved **gracefully, not stranded**: the framework issues a `system:group` **REJECTED** decision through the normal resume path (note: *"tool approval is not available during group discussions in this version"*), the member's LLM receives the rejection tool-result and produces a coherent tool-less contribution, and that becomes the turn's output. If the resume cannot complete in the member-turn budget (or the member re-pauses), it falls back to the existing member-pause handling (turn recorded SKIPPED, stranded pause auto-cancelled as `system:group`). The `inGroupTurns: "INBOX"` mode (routing member tool pauses to a human inbox instead) is reserved and rejected at save time in v1.

To have a group *act* on human-approved work — post an approved comment, publish an approved draft — gate the draft task instead (`granularity: TASK`, `requiresApproval` on the EXECUTE phase) and give that phase an `onApproved` action: on each approval the group makes one configured httpcalls call with the approved, possibly edited result, at most once. See [Group Approved-Result Actions](https://docs.labs.ai/conversations-and-orchestration/group-conversations/group-approved-result-actions.md).

### Frozen-transcript semantics

A tool pause serializes the **exact** in-flight langchain4j message list (the AiMessage + prior tool results of the current LLM loop) at pause time and persists it on the snapshot. On resume — even days later — the loop re-enters the **same** task index and replays that frozen transcript, then applies the verdicts and continues. The human therefore approves against, and the model resumes against, **pause-time prompt state** — not a transcript rebuilt from current memory. This is why the design persists the transcript rather than reconstructing it: a multi-iteration turn rebuilt from memory would lose intermediate tool results.

If the transcript exceeds `eddi.hitl.tool.transcript-max-bytes` (default 2,000,000) it is omitted, and resume falls back to rebuilding the history from memory — losing the turn's earlier iterations. That degraded path still replays the **assistant message that made the gated calls** unchanged, kept separately on the pause (`gatingAssistantMessageJson`, capped at 64 KB, written only when the transcript was omitted), because it carries provider-opaque fields the API demands back — Gemini 3.x's `thoughtSignature` among them. Its ungated calls, which were handled before the pause, are answered with an explicit "handled before the pause; result could not be restored" result, so they are neither left dangling nor blindly repeated — without claiming an outcome the degraded path cannot know.

### Rolling upgrade

The gate is guarded by a feature flag: `eddi.hitl.tool.enabled` (default `true`; injected into `LlmTask`). When `false`, the effective tool-approvals config resolves to `null` and the gate is inert.

* **Enabling on a cluster:** complete the rollout of the new version to **all** pods *before* enabling gates in agent configs. A pod running the previous version cannot read a `TOOL_CALL`-paused conversation (it does not understand the `AWAITING_HUMAN`/`TOOL_CALL` state), so mixed-version pods should not be producing tool pauses.
* **Downgrading:** set `eddi.hitl.tool.enabled=false` and **drain existing tool pauses** (resolve or cancel them) before rolling back to a version without this feature — otherwise those paused conversations are unreadable by the old code.

## Plan Binding (`planHash`)

An approval approves a **plan**, not "whatever is pending when the click arrives". Every pause gets a plan hash when it is committed, `approval-status` reports it, a decision can carry it back, and the resume refuses a decision for a different plan. The pattern is inspect → plan hash → apply only with that hash.

**What a plan is.** A SHA-256 over a canonical JSON document, reported as `v1:` followed by 64 lower-case hex digits (the prefix names the canonicalization, so a later version can still verify pauses committed under this one):

| Pause                  | The plan covers                                                                                                                                                                                                                                                                                                                                                                            |
| ---------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `TOOL_CALL`            | the conversation id, the agent id and version, the batch's `pauseEpoch`, a per-pause secret nonce, and for every pending call in batch order (the order approved calls run in): `callId`, `toolName`, `source`, `argsTruncated`, the **canonicalized raw arguments**, and the [request fingerprint](#request-pinning--approval-binds-to-a-request-not-a-tool-name) when the call is pinned |
| `RULE` (turn-level)    | there are no arguments, so the plan is what the rest of the turn acts on: the conversation id, the agent id and version, the `pauseId`, the paused workflow and task index, and the paused step's actions in order, without `PAUSE_CONVERSATION`                                                                                                                                           |
| Group `PHASE` / `TASK` | the group conversation and group ids, the `pauseId`, pause type and phase, the paused phase's transcript entries (speaker, type, content), the tasks awaiting approval (id, subject, assignee, result) and the synthesized answer                                                                                                                                                          |

**Canonicalization.** Object keys sorted by UTF-16 code unit (as RFC 8785 sorts them), arrays in order, no insignificant whitespace. Numbers by **value**: `1`, `1.0`, `1e0` and `1.00` are all `1`, `0.10` is `0.1`, `-0` is `0` — a store or a provider that re-serializes the arguments must not turn a pure re-encoding into a refused approval. Strings as parsed: `"\u00e9"` and `"é"` are the same string, but no Unicode normalization is applied (a precomposed and a decomposed character are different bytes to the tool, so different plans). Arguments that are not exactly one valid JSON document — they repeat a key, or carry anything after the first value — are hashed as their exact text.

**Why a nonce.** The tool-call plan covers the raw arguments and is served next to the redacted ones. Without a secret input it would be an offline guessing oracle — guess the redacted value, hash, compare — the reason the batch `fingerprint` and the per-call request fingerprint are never served. The nonce (128 random bits) is stored on the batch and never leaves the server: the approver projection nulls it, the names-only projection never copies it, and the summary read leaves it in the database. Rule and group plans contain nothing the approver is not shown, so they carry none.

**Where it is stored.** `hitlPlanHash` on the conversation, next to the bookmark (cleared with it), and for a tool pause also `planHash` on the pending batch, which the tool loop still holds once the bookmark is cleared. It is computed when the pause is committed, after the turn's secret scrub has rewritten the batch, so it covers exactly what the store keeps. A group plan is not stored: while a discussion is `AWAITING_APPROVAL` nothing it covers can change except through the approval, so it is derived from the stored discussion both when `approval-status` reports it and when the decision arrives.

**The checks.**

1. *Decision against the pause.* A decision whose `planHash` is not the pause's is refused with `409` before anything runs; the pause stays as it was (checked before the resume's compare-and-set, and again on the snapshot the resume actually runs, like `pauseId`).
2. *Plan against its hash.* The resume re-derives the hash from the plan it is about to run and refuses — `409`, `WARN hitl.plan.changed`, pause restored — when the stored plan no longer hashes to the value it was committed with. The tool loop does it once more immediately before an approved call executes: on a mismatch every approved call of the batch gets `{"status":"NOT_EXECUTED","reason":"the plan changed after it was approved"}` and a `hitl_plan_changed` trace entry. Whatever changed the stored plan after the pause, the approval was not given for it.

**Without a hash.** A decision that carries no `planHash` is, by default, accepted and logged (`WARN hitl.plan.not_presented`), so clients that predate plan hashing keep working. Under **strict binding** a human decision without one is refused with `400` and the pause is not consumed; send it again with the hash from `approval-status`. Automated decisions (`system:timeout`, `system:group`, other `system:*`) act on the pause they read themselves and are never refused for it. A pause committed **before plan hashing** has `planHash: ""` and is decided exactly as before — also in strict mode, since nothing can be bound to a plan that was never hashed (logged as `hitl.plan.legacy`); a decision that names a hash for such a pause is refused.

**When the hash cannot be computed.** Hashing never stops a pause from being committed. If computing the plan hash fails, the pause stores the marker `hitlPlanHash: "unavailable"` (and `planHash: "unavailable"` on the tool batch) in place of a hash, logged as `WARN hitl.plan.unavailable`, so it can never pass for a legacy pause. `approval-status` reports `planHash: ""` for it, since there is no plan a decision could name. Under **strict binding** a human decision on such a pause is refused with `409`, approvals and rejections alike, and the pause is restored as for a plan mismatch. Retrying cannot help, so cancel the conversation, or let its timeout policy decide: `system:*` decisions stay exempt. Without strict binding the decision is applied without binding and logged at WARN. Either way the audit records `planBinding: PLAN_HASH_UNAVAILABLE` and `planHash: "unavailable"`. A decision that names a hash for such a pause is refused, as it is for a legacy pause. Group plans are derived when the decision arrives rather than stored, so they have no such state: if the derivation fails, the approve fails and nothing is applied.

**Strict binding** is opt-in at two levels, and either one turns it on:

```json
{ "hitlConfig": { "requirePlanHash": true } }
```

* `hitlConfig.requirePlanHash` on an agent (read at the paused version) or a group — a designer protects the agents whose approvals matter most without breaking anyone else's clients;
* `eddi.hitl.plan-hash.strict=true` for the whole deployment — an operator turns it on once every client in use (Manager, Slack, MCP, their own) sends the hash.

If the paused version's configuration cannot be read when it is needed, the agent counts as strict (fail closed).

**Every surface carries it.** REST: `planHash` in `approval-status` (summary) and in the resume and group approve bodies. MCP: `planHash` in `get_approval_status` / `get_group_approval_status` and an optional `planHash` argument on `resume_conversation` / `approve_group_phase` (`errorCode: PLAN_CHANGED` for another plan, `PLAN_HASH_REQUIRED` under strict binding). Slack: the approval buttons carry the hash of the pause the card was posted for (`<integration>|<subject>|<cardId>|<planHash>`), and the edit and reject modals keep it, so Slack approvals work under strict binding. A click on a card whose plan is no longer the pending one runs nothing and leaves the pause waiting; the card is replaced by "Not applied: the request this card was posted for has changed since …" without buttons (its buttons carry the old plan and could only be refused again), and the request is decided in the Manager, over REST or MCP. Manager: the approvals inbox, the conversation and group pages and the operator's approval card send the plan they showed. Cards posted and pauses committed before plan hashing simply carry none.

**Audit.** The `hitl.approval` entry records `planHash` (the plan the decision applied to) and `planBinding` — `MATCHED`, `NOT_PRESENTED`, `SYSTEM`, `LEGACY_UNHASHED` or `PLAN_HASH_UNAVAILABLE` — and every task the resume runs records `input.hitlPlanHash`; an approved call's `hitl_approved` trace entry carries `planHash` too. See [HITL Review & Audit](https://docs.labs.ai/conversations-and-orchestration/hitl/hitl-review-and-audit.md#top-level-fields-auditentryoutput) and the [Audit Ledger](https://docs.labs.ai/security-and-compliance/audit-ledger.md#audit-entry-structure).

**Amended arguments.** `toolDecisions[callId].amendedArguments` replaces a call's arguments as part of the decision: the plan hash describes the plan the reviewer was shown, and the amendment is the reviewer's own change to it, recorded with the decision (`argsDigest`, edit metrics). It is not re-hashed.

**Rolling upgrade.** A pod that predates plan hashing ignores `planHash` in a body and stores no hash; its pauses are legacy pauses to a newer pod. Turn strict binding on only once every pod runs this version.

***

## Timeout Policies

| Policy              | On timeout                                                                                                   | Typical use case                        |
| ------------------- | ------------------------------------------------------------------------------------------------------------ | --------------------------------------- |
| `WAIT_INDEFINITELY` | Nothing is scheduled; waits forever                                                                          | Critical decisions (compliance, safety) |
| `AUTO_APPROVE`      | APPROVED decision (`decidedBy: system:timeout`), resumes                                                     | Progress monitoring, non-critical gates |
| `AUTO_REJECT`       | REJECTED decision → regular: turn skipped (never revised, even under `onRejection: REVISE`); group: `FAILED` | Strict SLA gates                        |
| `ABORT`             | Cancels the pending approval (regular surface: only the pause the timeout was armed for) / the discussion    | Safety-critical pipelines               |

Timeouts are one-shot schedules on EDDI's cluster-aware `ScheduleFireExecutor` — exactly one pod owns each claim, and they route through the **same** resume/cancel machinery as human decisions. Delivery is at-least-once (a lease-expired claim can be re-stolen after a pod crash), so a timeout must be safe to fire twice — and against the wrong pause:

* **A timeout decides only the pause it was armed for.** The schedule carries that pause's `pauseId`, and the `AUTO_APPROVE`/`AUTO_REJECT` decision names it, exactly like a reviewer's decision that passes `pauseId`. A fire that arrives after the conversation was resumed and paused again on a different request is refused as a pause mismatch and completes without deciding anything; the newer pause has its own timeout. (The resume/cancel state CAS alone did not cover this: a re-paused conversation is `AWAITING_HUMAN` again, so a stale fire's CAS succeeded and decided a request nobody had timed out on.) Timeouts armed by an older build carry no `pauseId` and decide whatever pause is current, as before. On the regular surface `ABORT` is bound the same way: it is the paused-only cancel, applied only while the conversation is still paused on the timeout's `pauseId` — a fire claimed just before an approver resumed neither stops the resumed turn nor aborts a newer pause. While that resume is still in flight the fire stays armed and is retried (the resume may yet fail and restore the pause, which only this fire would then abort); once the pause is decided or replaced, it completes without effect. (It used to be the full cancel, which also signals a running turn.) The group surface's `ABORT` still cancels the discussion as it stands.
* **A decision that cannot be applied yet keeps the timeout armed.** When the resume fails before anything runs — the conversation could not be loaded, the node is draining for shutdown, the agent cannot be resolved, or another decision on the same pause is still in flight (for `ABORT` and an expired human turn: the cancel or skip failed) — the pause is restored and the fire is recorded `FAILED` with the reason, and the schedule is re-armed after `eddi.schedule.hitl-timeout-retry-interval` (default `2m`). It is never dead-lettered: the usual cause is temporary and outside the schedule's control, and dropping it would turn a finite policy into wait-forever. A timeout whose conversation is gone, or no longer awaiting a decision, completes normally.

***

## Who May Decide

Approve/reject/cancel/status require, in order: the **conversation owner**, the **`eddi-admin`** role, or the dedicated **`eddi-approver`** role. Ownerless (legacy/internal) conversations fail **closed** for non-admin/non-approver callers. `decidedBy` is set server-side from the authenticated identity — with an authenticated caller it cannot be spoofed via the request body. The one exception is a deployment where nobody is authenticated: there a body `decidedBy` is recorded as `unverified:<value>` (see [Reply and approver on resume](#reply-and-approver-on-resume)). Approvers and admins see all entries in the pending-approvals listings; other users only their own.

**An owner's resume is a turn.** Under enforced workspaces an owner who is neither admin nor approver must still be allowed to `USE` the conversation's agent to resume it (REST and MCP alike), the check every `say` makes — a revoked share stops the resume too. Admins and approvers decide by their role.

**Approver cancel scope:** `POST /agents/{conversationId}/cancel` and the MCP `cancel_conversation` tool also stop a turn that is *executing*, and the approver role is not a licence to stop other users' running turns. An approver-only caller (not the owner, not an admin) may cancel a conversation only while it is `AWAITING_HUMAN` — the decision the role exists for. Their cancel is a single compare-and-set from that state, so the entitlement check and the cancel are one operation and a resume that lands in between cannot turn it into a stop of a running turn; on a conversation in any other state it is refused with `403` (`FORBIDDEN` over MCP), exactly as it would be without the role. The owner and admins are unchanged and can cancel an executing turn as before. Group discussions follow the same rule on `POST /groups/{groupId}/conversations/{gcId}/cancel` and the MCP `cancel_group_discussion` tool: an approver-only caller may cancel only a discussion that is `AWAITING_APPROVAL` or `AWAITING_HUMAN_INPUT` (one compare-and-set on that state), gets `403` / `FORBIDDEN` on a running one, and receives the resulting state rather than the transcript. The HITL timeouts of a group (approval `ABORT`, human-turn `ABORT` and `SKIP_TURN`) are bound the same way to the pause they were armed for: a late fire neither cancels a discussion that has moved on nor skips a newer human turn.

**Approver read scope:** the approver role exists to *decide* pending approvals, not as a universal read grant. Approver-only callers (not owner, not admin) may read `approval-status?detail=full` — the full memory snapshot / transcript — only while the conversation is actually awaiting approval; outside a pause they get `403` and can use the summary view. The full snapshot is also **sanitized** for every caller, on REST and on the MCP `get_approval_status` tool alike: the pending batch's `argumentsRaw`, frozen LLM transcript (`chatTranscriptJson`), running trace (`traceSoFar`) and batch-level `fingerprint` (an unsalted digest over the raw arguments) are removed, the per-call request fingerprint is replaced by a constant marker, and `argumentsRedacted` and the request preview are re-redacted with the current filter. Both surfaces call the same method (`ConversationMemoryUtilities.sanitizePendingToolCallsForApprover`), so they cannot serve different fields.

**Whose credentials a resumed turn carries.** When the approver *is* the conversation's owner, the resumed turn runs as them, exactly like a `say`. When somebody else decides — an admin or an `eddi-approver` — their identity covers only what they were shown: each tool call they explicitly approved in a `TOOL_CALL` pause runs with their caller identity (so a `${caller:token}` header on that call carries the approver's token), and the rest of the resumed turn runs with **no caller**. A `${caller:token}` / `${caller:userId}` reference elsewhere in that turn — including every call after a `RULE` pause, which previews nothing — therefore fails closed, as it does on a scheduled turn, instead of going out with the approver's credentials. A resumed group discussion follows the same rule: it runs as the approver only when the approver started the discussion. So does a discussion resumed by a HUMAN member's submission: it runs as the submitter only when the submitter started the discussion, otherwise with no caller. `PER_USER` connection credentials always resolve against the conversation's owner, never the approver.

**Group tie-breaks are human turns, not approvals.** A tied vote under `tiePolicy: HUMAN_DECIDES` pauses in `AWAITING_HUMAN_INPUT` and is answered on the human-input endpoint with a `choice`, by the configured decider or an admin when authentication is enabled (with authentication disabled the decider check does not run, so any client that passes the request guards can answer). An `eddi-approver` may submit only when their own principal is the configured decider; the role never lets anyone answer for another principal. See [Group Human Decisions](https://docs.labs.ai/conversations-and-orchestration/group-conversations/group-human-decisions.md).

## Auditing

Every HITL decision — human or automated — writes an immutable `hitl.approval` entry to the audit ledger (verdict, decider, automated flag, note, and `onRejection: REVISE` for a rule-pause rejection under that policy), and the resumed pipeline leg records its task entries like any other turn — a revision included. Cancelling a pending approval is a decision too: it writes an `hitl.approval` entry with verdict `CANCELLED`, the cancel mode, and the **cancelling actor** (`decidedBy`: the authenticated principal, or a `system:*` identifier such as `system:timeout` for ABORT policies and `system:group` for auto-cancelled member pauses). This is the EU AI Act human-oversight trail. Since 6.7 every entry also carries the typed decision contract — outcome per unit, approval category, reason code, channel, latency and edit metrics — see [HITL Review & Audit](https://docs.labs.ai/conversations-and-orchestration/hitl/hitl-review-and-audit.md#the-audit-contract). Analytics, a sampled audit of the calls nobody approved, and earned autonomy over these records: see [HITL Oversight](https://docs.labs.ai/conversations-and-orchestration/hitl/hitl-oversight.md).

## Crash Recovery

With `eddi.messaging.type=in-memory` (a single node), `HitlCrashRecoveryObserver` **repairs** HITL state on startup; it never destroys a legitimate pause. In NATS cluster mode there is no startup pass: a leader-elected `ClusterHitlRecovery` sweep does the same work periodically (`eddi.cluster.hitl-recovery.interval`, default `60s`, and `min-age`, default `3m`; see [clustering.md](https://docs.labs.ai/deployment-and-infrastructure/clustering.md)), which avoids the rolling-restart race a per-node startup pass has. The sweep runs on a background thread (application readiness does not block on it) and reads bounded projected summaries, not full conversation documents:

* Paused conversations with a **finite** policy get their one-shot timeout schedule idempotently re-armed at the original due time (or shortly after startup if overdue). After creating the schedule the pause state is re-checked — if a resume/cancel landed in the window, the schedule is withdrawn.
* `WAIT_INDEFINITELY` pauses are left untouched (and skipped without any further read).
* Regular conversations stuck `IN_PROGRESS` with an intact HITL bookmark (pod died mid-resume) are restored to `AWAITING_HUMAN` so the approval can be re-issued.
* **Group discussions** left `IN_PROGRESS` or `SYNTHESIZING` (startup pass only) are **cancelled** when they were last written before the process started. On a single node every leg the new process runs was started or resumed after it booted, and each of those writes stamps `lastModified`, so an older running discussion belongs to a leg that died. That includes one whose node crashed right after an approve: the approve clears the pause bookmark, so there is no pause to restore. It goes through the ordinary cancel (state CAS, timeout schedule removed); a standing team's next fire then returns its pulled backlog tasks to `PENDING`. Unlike a cancel that reaches a running leg, it does not release the discussion's ephemeral (dynamically created) agents — no leg is left to do that; they are released when the discussion is closed or deleted. The leader-elected cluster sweep does not do this: a group discussion holds no conversation lease that could prove its leg dead, so in cluster mode an interrupted discussion still waits for a manual cancel (or the standing-team claim TTL).

Config: `eddi.hitl.crash-recovery.enabled` (default `true`), `eddi.hitl.crash-recovery.recover-in-progress` (default `true`; applies to the single-node startup pass only, since cluster mode has none, and covers both the regular and the group recovery). EDDI does not support several in-memory replicas (the Helm chart refuses them, and both it and the Kustomize base replace the pod with `Recreate`). A deployment that nonetheless starts a new JVM while the old one still runs against the same database should set it to `false`: to the new process, a discussion the old one has been running since before the start looks interrupted and would be cancelled.

## Operations

* **Metrics** (`/q/metrics`; the full list, including the tool-pause counters and the `eddi_hitl_pending` gauges, is in [Metrics → HITL](https://docs.labs.ai/deployment-and-infrastructure/metrics.md#hitl-metrics)): `eddi_hitl_pause_count`, `eddi_hitl_resume_count`, `eddi_hitl_timeout_count`, each tagged `surface=regular|group`; `eddi_hitl_revision_total{outcome}` for rejections under `onRejection: REVISE`; `eddi_group_member_pause_skipped_count` for auto-cancelled member pauses inside groups; `eddi.operator.write.approval{decision=approved|rejected|timeout}`, one per gated call the instant its verdict is resolved (`timeout` is a distinct bucket from `approved`/`rejected` — see [Request pinning](#request-pinning--approval-binds-to-a-request-not-a-tool-name) above; not operator-specific despite the name, it fires for any gated call regardless of which agent).
* **Operator canary/gate metrics** (client-reported): the write canary and gate-installed check both run entirely client-side (there is no server-side notion of "the operator", just an agent with a particular `hitlConfig`), so the Manager reports outcomes via `POST /administration/operator/{canary-result,gate-status}` (`eddi-admin` only) purely so they show up on `/q/metrics` without a Manager tab open. This is a relay, not a verification — a report is trusted at face value. Produces `eddi.operator.canary{outcome=pass|fail|unknown}`, `eddi.operator.canary.duration`, and the gauge `eddi.operator.gate.verified` (1 only while every provisioned version last read back with a sound gate; defaults to 0, including on a deployment that has never activated an operator — that ambiguity is real and unresolved by this signal alone).
* **Operator self-URL** (`GET /administration/operator/self-url`, `eddi-admin`): answers the address this deployment can reach *itself* at, which is what the operator's generated tools must target. `eddi.self.base-url` when set, otherwise `http://${quarkus.http.host}:${quarkus.http.port}` when the listener binds one specific address (loopback ones such as `127.0.0.5` or `::1` included; an IPv6 literal is bracketed, e.g. `http://[::1]:7070`), and `http://127.0.0.1:${quarkus.http.port}` for a wildcard, empty or `localhost` bind; the response is `{baseUrl, source}` with `source` one of `configured`, `loopback` or `unresolved`. `unresolved` (with `baseUrl: null`) means a random HTTP port (`quarkus.http.port=0`) and no override — the Manager then refuses to guess and asks for the base URL explicitly. It exists because the only other candidate a provisioning client has is its own browser origin, and the two coincide only when nothing sits between the browser and EDDI — a tunnelled staging instance was provisioned with `localhost:7080` in front of a container on `:7070`, and the operator reported itself deployed and gate-verified while all 22 of its tools failed on connect. Deliberately a GET with no arguments: the answer must not depend on a `Host` header or an `X-Forwarded-*` chain a proxy can rewrite. Note that pointing the tools at that address makes them cross-origin to `${caller:token}`'s same-origin rule, which is why `CallerIdentityResolver` also releases the token when the target is this very process — the same argument `LoopbackCallerAuthFilter` makes for the internal hop; the value comes from deployment configuration alone. It is not narrower than same-origin: the self address bypasses whatever sits in front of EDDI, so what the token reaches is what EDDI's own authorization allows. A deployment that also relies on its proxy's rules sets `eddi.caller-identity.self-release.enabled=false`; a caller whose origin could not be captured never gets the self release.
* **Undeploy**: paused conversations do **not** count as active — an agent version with pending approvals can be undeployed. A resume must finish on the version that paused it, so it deploys that version on demand on the node that runs it — whatever its deployment record says. That is deliberate: the automatic old-version cleanup undeploys a previous version as soon as its only open conversations are paused, and so does retiring a version whose conversations can move to a compatible one; refusing there would strand every pending approval at the next deploy. If the version cannot be deployed (its configuration is gone, say), the resume returns `409 agent not deployed` and the pause is restored. Its approval timeouts stay armed through the undeploy (they are not among the schedules an undeploy disables) and fire at their due time; if the decision cannot be applied then, it is retried every `eddi.schedule.hitl-timeout-retry-interval` as described under timeouts. The idle-conversation cleanup sweep likewise **spares** `AWAITING_HUMAN` conversations — a pending approval is never silently force-ended by maintenance.
* **Cancel semantics (regular)**: cancels a paused conversation, or signals a turn executing on the same pod to stop at the next task boundary. `CANCEL_IMMEDIATE` currently degrades to graceful on the regular surface. Cancelling an idle conversation returns `409` (use `endConversation`) — unless it has a pending [self-continuation](https://docs.labs.ai/conversations-and-orchestration/long-jobs.md): a job between two of its turns is cancelled by withdrawing its next turn, and the answer is `200`. The full cancel withdraws a pending continuation in every case; the approver's paused-only cancel never does. An approver who is neither the owner nor an admin can only cancel a paused (`AWAITING_HUMAN`) conversation — see [Who May Decide](#who-may-decide).
* **Timeout schedules are not manually operable**: HITL timeout schedules live in the schedule store but the schedule REST surface refuses to fire them manually (`409`, use `/resume` or `/cancel` — manual firing would bypass the approval authz), restricts update/delete/enable/disable to `eddi-admin` (`403` otherwise, so an editor cannot disarm an ABORT/AUTO\_REJECT safety timeout), and redacts them from non-admin listings.
* **Pause retention (optional)**: `eddi.hitl.pending.max-age` (ISO-8601 duration, default **off**) auto-cancels pauses older than the threshold — audited, schedule-disarmed, via the paused-only cancel bound to the pause the sweep saw (a pause resumed in between is left running, a newer pause is not the expired one); `eddi.hitl.pending.sweep-interval` (default 6h) controls the sweep cadence. Under the default `WAIT_INDEFINITELY` policy, pauses otherwise accumulate until decided.
* **Mass-timeout drain**: due schedules are claimed in configurable batches (`eddi.schedule.poll-batch-size`, default 100) and fired concurrently on virtual threads with per-fire error isolation.

## Slack Integration

The Slack channel integration is HITL-aware end to end. Configuration lives in the Slack `ChannelIntegrationConfiguration.platformConfig` (both keys optional):

| Key                   | Description                                                                                                                                                                                                                                                                                                                                                                                                                           |
| --------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `hitlApprovalChannel` | Slack channel id that receives approval notifications when a conversation pauses.                                                                                                                                                                                                                                                                                                                                                     |
| `hitlApprovalContext` | `"true"` shows the agent's or group's [`approvalContext`](https://docs.labs.ai/conversations-and-orchestration/hitl/hitl-approval-context.md) — the draft, its sources, the claims — on the approval card, as plain text. Off by default: everyone in the approval channel sees the card, not only the approvers, so without it the card carries only "More context available in the Manager".                                        |
| `hitlApproverUserIds` | Comma-separated Slack user ids allowed to decide via buttons. A Slack user id is unique within one workspace only, so when the integration declares its workspace (`platformConfig.teamId`) a clicking user of another workspace — possible in a shared Slack Connect approval channel — is refused even if their id is listed. **Without this list, buttons are not rendered and interactive decisions are rejected — fail-closed.** |

Behavior:

* **In-thread pause notice** — when a turn pauses, the thread receives the output so far plus "⏸️ awaiting human approval" with the `pauseReason`. Messages sent while paused get "Still awaiting approval" instead of a generic error (the input is not consumed).
* **Approval inbox message** — if `hitlApprovalChannel` is set, an interactive Block Kit message is posted there (conversation, agent, reason, timeout deadline) with Approve/Reject buttons. For a **RULE** pause only the pause reason is shared — no conversation content (data minimization). For a **TOOL\_CALL** pause the approval channel additionally renders one context block per pending call — `toolName` plus its **redacted, size-capped arguments** truncated to 300 chars for display (max 5 calls, then a `+N more` line) — because a reviewer cannot responsibly approve `transfer_funds` without seeing the amount. The raw (unredacted) argument value is never accessed; this relaxation applies to the approval channel only, not the in-thread notice (which stays pause-reason-only). With `approvalContext` configured and `hitlApprovalContext` set, the card also shows the designer's context blocks as plain text ([HITL Approval Card Context](https://docs.labs.ai/conversations-and-orchestration/hitl/hitl-approval-context.md#slack)).
* **Edit & approve, Reject with reason** — modals on regular-conversation cards; see [HITL Review & Audit](https://docs.labs.ai/conversations-and-orchestration/hitl/hitl-review-and-audit.md#slack-edit-and-reject-modals) (`platformConfig.hitlShareRuleDrafts`).
* **Deciding from Slack** — buttons post to `POST /integrations/slack/interactive` (configure this as the Slack app's *Interactivity Request URL*; requests are signature-verified like the events webhook). The acting Slack user must be in `hitlApproverUserIds`; decisions are attributed `decidedBy: slack:<userId>` in the audit trail. Double-clicks and already-decided races update the message ("already resolved") without error spam. Group pauses work the same way (the button value carries `group:<conversationId>` and routes to the group approve machinery).
* **Decisions are bound to the card that was posted** — the signature and approver list prove *which integration* a decision came from, not that the conversation named in the button belongs to it. So every approval card is recorded when it is posted (`slack_hitl_approval_records`, MongoDB or PostgreSQL — persisted, so it survives restarts and also keeps "one card per pause" across them), keyed by integration, subject (conversation id or `group:<id>`) and pause identity (`hitlPausedAt` / the group's `pausedAt`). Each record also holds a random **card id** (128 bits), generated before the record is written and embedded in that card's buttons (`<integration>|<subject>|<cardId>`). A decision is accepted only if the owning integration has a record for that subject **whose card id matches the clicked button**, and that record is for the pause the subject is in now. So a card only ever resolves the pause it was posted for: an approver clicking an old card ("delete file A") while a newer pause of the same conversation or group is live ("delete everything") does not approve the newer action — the old card is marked "already resolved". A subject the integration never posted a card for, a card id no record holds, and a button without a card id (a card posted before card binding) are refused and logged (`SLACK_HITL_DECISION_REFUSED`); resolve such a pause through REST/MCP, or — for a conversation — have its own user send another message in the paused thread, which posts a fresh card (a message from anyone else opens that person's own conversation, and a reply in a group discussion's thread does not post the group's card again, so a group pause is resolved through REST/MCP). Records expire after `eddi.slack.hitl.approval-record-retention` (default `30d`); a decision on an older card is refused — resolve it through REST/MCP, or have the conversation's own user send another message in the paused thread, which posts a fresh card (groups: REST/MCP only). If a card cannot be recorded it is posted **without** buttons (fail-closed), and so is a card whose pause could not be read yet (the pause had not been persisted when the card was built): without its pause identity it could only be matched to *some* pause, possibly a later one it does not show. Nothing is recorded for it, and the card says so in place of the buttons: for a conversation, its own user sending another message in the paused thread posts a card with buttons; a group pause is resolved through REST/MCP. The pause check and the resume are two steps, so the decision carries the checked pause as its `pauseId` and the engine re-checks it under the resume CAS: a resume and re-pause landing between the two is refused there, and the card is marked "already resolved". Since 6.8 the buttons also carry the [plan hash](#plan-binding-planhash) of the pause the card was posted for (a fourth field, `<integration>|<subject>|<cardId>|<planHash>`), so a click binds to that exact plan and Slack approvals work under strict plan binding; cards posted earlier carry none.
* **Continuation push** — when the pause is resolved (human, Slack button, or `system:timeout`), the originating thread automatically receives the verdict and the resumed conversation's output — no polling. This works cross-pod: the resume fires an async CDI event (`HitlResumeCompletedEvent`) and the Slack observer resolves the thread from the persistent conversation mapping.
* **Group discussions** — Slack-driven group discussions post pause/resume/cancel notices (and `member_pause_skipped` explanations) into their thread.

**Delegated/managed conversations** (agent-to-agent tools, MCP `chat_managed`): when a nested conversation pauses, the calling tool receives a structured `PAUSED_FOR_APPROVAL` result naming the conversation and reason instead of hanging — the delegated approval stays pending (it is *not* auto-cancelled; a reviewer decides, then the tool can be re-invoked).

## Email notifications

An agent can name people to email when one of its conversations pauses for approval — whatever channel the conversation came from (Manager, REST, `/v1`, Slack, MCP). The mail says that something is waiting and links to the Manager's **Approvals** page; it decides nothing. Two settings, one per audience:

1. **The operator** configures the deployment's system mailer once (`eddi.mail.smtp.*`, see [configuration-reference.md → Email](https://docs.labs.ai/deployment-and-infrastructure/configuration-reference.md#email)). Without `eddi.mail.smtp.host` nothing is sent and the startup log says so.
2. **The agent designer** opts the agent in with `hitlConfig.notify.email`:

```json
{
  "hitlConfig": {
    "approvalTimeout": "PT4H",
    "timeoutPolicy": "AUTO_REJECT",
    "pauseReason": "Refunds over 500 EUR need a manager",
    "notify": {
      "email": {
        "recipients": ["refund-approvers@example.com", "ops-lead@example.com"]
      }
    }
  }
}
```

| Field                     | Default                              | Description                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              |
| ------------------------- | ------------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `notify`                  | absent — nobody is notified          | Who is told when this agent pauses. A config without it behaves exactly as before                                                                                                                                                                                                                                                                                                                                                                                                                                                        |
| `notify.email.recipients` | — (required when `email` is present) | 1–20 plain `local@domain` addresses (an ASCII local part; the domain may be written in Unicode and is converted to ASCII before it is checked, so the Unicode and punycode spellings of one domain count as duplicates; a domain with ß, ς or a zero-width joiner is refused: write it in punycode), no display names, no duplicates (compared case-insensitively), each in a domain the operator allows (below). Refused at save time (400) otherwise, naming the position, never the address. For more people, use a distribution list |

**Which addresses — the operator decides.** Anyone who may edit an agent can set its recipients, but the mail goes out through the operator's relay, from the operator's sender address, carrying text an author (agent name, pause reason) and an end user (tool arguments) can influence. So the operator bounds it with `eddi.mail.notify.allowed-recipient-domains` (exact domains, `*.domain` for subdomains, `*` for any); **unset, only the domain of `eddi.mail.smtp.from` and its subdomains are allowed.** With a mailer configured, a recipient outside is refused at save time; without one it is accepted with a WARN, since the operator may configure the mailer later. Either way it is checked again at every send and never mailed: its ledger row ends `SUPPRESSED`.

**Flood brake.** An end user can drive an agent into a pause every turn, or in many conversations at once. Each recipient gets at most `eddi.mail.notify.max-per-recipient-per-hour` (default 30) notifications in any hour, counted from the ledger across all instances; the rest are `SUPPRESSED` (`rate_limited`), and each instance logs one WARN per recipient per hour. Pending approvals stay on the Approvals page either way.

**One mail per pause and recipient**, across every pod: each recipient's notification is a row in the email ledger under a unique key derived from the conversation, the pause and the address, so a pause observed twice — or on two pods — mails once. A new pause of the same conversation is a new notification. A resume that restores a pause after a failed attempt is the same pause and is not mailed again.

**What the mail contains** follows the [Slack approval card](#slack-integration)'s data-minimisation rule: the agent's name, the pause type (approval rule or tool call), the designer's `pauseReason`, when it started, the deadline and what happens then, the conversation id, and for a `TOOL_CALL` pause each pending tool's name with its **redacted, 300-character-truncated** arguments (at most 5 calls, then `+N more`) — the same lines the Slack card shows, from the same code. Never anything a user or the model wrote: no input, no output, no transcript. The subject is `[EDDI] Approval needed: <agent name>`, and nothing else. Mails are `text/plain` and carry `Auto-Submitted: auto-generated` and `X-Auto-Response-Suppress: All`, so out-of-office replies stay quiet.

**What it does not do.** The link is `<public base URL>/manage/approvals` — no token, no conversation-specific action, nothing that happens on opening it (Safe Links and Proofpoint open every link in a mail). Replying does nothing either. Who may decide is unchanged: the Approvals page needs a sign-in, and the [rules above](#who-may-decide) apply. The base URL is the deployment's public origin, `eddi.connections.public-base-url` (the setting OAuth callbacks already use); without one the mail names the page instead of guessing a host.

**Delivery and retries.** The first attempt happens as soon as the pause is committed. A failure that may be transient (relay unreachable, TLS or login trouble, a 4xx deferral) is retried by a sweeper on every instance (`eddi.email.ledger.sweep-interval`, default 30 s) with exponential backoff (`eddi.email.outbound.retry-backoff`, default 1 min, doubling, capped at 1 h), up to `eddi.email.outbound.max-attempts` (default 6); a 5xx refusal fails it at once. Each retry re-reads the pause and re-renders the mail — the ledger stores no body — and a pause decided in the meantime ends `SUPPRESSED` instead of being mailed. Rows are kept for `eddi.email.ledger-retention` (default `30d`).

**Who is notified — recipients only, not "all approvers".** EDDI's approvers are the conversation's owner and holders of the `eddi-admin` / `eddi-approver` roles in the identity provider. The roles live in the identity provider, not in EDDI's user directory, so EDDI cannot list who holds them — and a list it built from past sign-ins would keep mailing a revoked approver forever. Name the approvers' shared mailbox or distribution list in `recipients` instead.

**Observability and audit.** `eddi_email_outbound_total{kind="notify",outcome="sent|retry|failed|suppressed|not_allowed|rate_limited"}` and the `eddi_email_ledger_pending` gauge ([metrics.md](https://docs.labs.ai/deployment-and-infrastructure/metrics.md#hitl-metrics)). Every sent or failed notification writes an `email.notify` audit-ledger entry with the conversation, the outcome, the Message-ID, the relay's reply and the recipient as `recipientPseudonym` (the GDPR pseudonym token: keyed with the audit ledger's key, or salted per deployment when the ledger has none, so it cannot be confirmed by hashing candidate addresses; only a deployment with neither a key nor a salt falls back to an unsalted hash) plus `recipientDomain` — the audit ledger is write-once, so the address itself is not written there. Ledger rows (which do hold the address) are erased and exported with the person's other data by `DELETE /admin/gdpr/{userId}` and the export, matched through the user id when it is an address and the email the user directory recorded for that principal.

**Not yet:** group conversations (`AWAITING_APPROVAL` discussions) are not notified by email; their approvals appear on the Approvals page and in Slack as before.

## Email conversations

A conversation that an [email integration in conversation mode](https://docs.labs.ai/protocols-and-integration/email-integration.md#conversation-mode) runs answers its correspondent in the mail thread, and that includes pauses — the counterpart of Slack's in-thread notice and continuation push:

* **In-thread pause notice.** When the turn of a mail pauses, the sender gets a reply in the thread: the agent's output so far, a fixed sentence that a person must approve the next step, and the agent's `pauseReason`. Never the tool's name or its arguments — the same data minimisation as Slack's in-thread notice; the approver sees those on the Approvals page or in their [notification](#email-notifications). It is sent from `HitlPauseCommittedEvent`, after the pause is durable, so it always carries the reason of the pause it is about.
* **Continuation.** `EmailHitlResumeObserver` listens for `HitlResumeCompletedEvent`, as `SlackHitlResumeObserver` does: after an approval the sender gets the resumed turn's output; after a rejection, a cancellation or a timeout a plain notice that the step was not carried out; after a resume that failed, that it could not be completed. Who decided is never named — approvers are staff, the correspondent is outside.
* **One row, any node.** Both are reply rows in the email ledger, keyed by conversation and pause (or by the continuation's verdict and text), retried like every reply and rebuilt from the conversation if a node dies; a second observer of the event sends nothing. The ledger deduplicates rows, not deliveries: a node that dies after the relay accepted a notice but before its row was marked `SENT` leaves a row whose lease runs out, and the retry sends it again (same Message-ID, so most mail clients show it once). A pause decided before its notice went out ends `SUPPRESSED`.
* Mail the sender writes while the conversation is paused waits in the mailbox until the decision, then runs.
* A pause in a new conversation's `CONVERSATION_START` turn, before the mail's own turn ran, sends no notice.

## MCP Surface

The HITL operations are also exposed over the MCP server (`McpHitlTools`), so an MCP client that drives a conversation (`talk_to_agent` / `chat_managed`) and receives a `PAUSED_FOR_APPROVAL` result can resolve the gate over the **same transport** instead of switching to REST. That paused payload names the tool to call next (`"suggestNextTool": "resume_conversation"`).

| MCP tool                           | Mirrors REST                                                 | Notes                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           |
| ---------------------------------- | ------------------------------------------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `list_pending_approvals`           | `GET /agents/pending-approvals`                              | Owner-scoped; includes RULE and TOOL\_CALL pauses                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               |
| `get_approval_status`              | `GET /agents/{id}/approval-status`                           | Summary reports `pauseType`; `detail=full` returns the snapshot (incl. any pending tool-call batch)                                                                                                                                                                                                                                                                                                                                                                                                                                             |
| `resume_conversation`              | `POST /agents/{id}/resume`                                   | A single verdict resolves both RULE and TOOL\_CALL pauses; optional `pauseId` and `planHash` from `get_approval_status` ([Plan Binding](#plan-binding-planhash)), `toolDecisionsJson` (per-call verdicts), `editedAnswer` and `reasonCode`                                                                                                                                                                                                                                                                                                      |
| `cancel_conversation`              | `POST /agents/{id}/cancel`                                   |                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                 |
| `list_group_pending_approvals`     | `GET /groups/{groupId}/conversations/pending-approvals`      | Owner-scoped                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    |
| `list_all_group_pending_approvals` | `GET /groups/pending-approvals`                              | Cross-group inbox                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               |
| `get_group_approval_status`        | `GET /groups/{groupId}/conversations/{gcId}/approval-status` | Summary only; `detail=full` returns the whole conversation                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      |
| `approve_group_phase`              | `POST /groups/{groupId}/conversations/{gcId}/approve`        | Optional `taskApprovalsJson` (or the richer `taskDecisionsJson`) for TASK granularity, `editedAnswer` and `reasonCode` (see [HITL Review & Audit](https://docs.labs.ai/conversations-and-orchestration/hitl/hitl-review-and-audit.md#surfaces)), optional `pauseId` (from `get_group_approval_status`; a changed pause answers `PAUSE_CHANGED`) and optional `planHash` (a different plan answers `PLAN_CHANGED`, a missing one under strict binding `PLAN_HASH_REQUIRED`); blocks and returns the resumed discussion (no SSE variant over MCP) |
| `cancel_group_discussion`          | `POST /groups/{groupId}/conversations/{gcId}/cancel`         |                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                 |

**Authority is identical to REST** — the tools first require one of `eddi-admin`, `eddi-editor`, `eddi-user`, `eddi-approver` (the `@RolesAllowed` of the REST HITL endpoints; `eddi-viewer` is refused as it is over REST), then the shared `HitlAccessGuard` enforces owner / `eddi-admin` / `eddi-approver` per conversation for every decision (fail-closed on a missing descriptor) — with the two group exceptions the REST surface has: `get_group_approval_status` also admits the pending HUMAN member of an `AWAITING_HUMAN_INPUT` discussion, and `submit_group_human_input` admits only that member or an admin, because it is the member speaking rather than an approval — and the decision is attributed **server-side** to the authenticated caller, prefixed `mcp:` (e.g. `mcp:alice`, mirroring the `system:timeout` convention) — never taken from a tool argument. Errors are structured JSON (`errorCode` ∈ `NOT_FOUND | WRONG_STATE | PAUSE_CHANGED | PLAN_CHANGED | PLAN_HASH_REQUIRED | FORBIDDEN | DISABLED | BAD_REQUEST | CONFLICT | INTERNAL`) so a programmatic client can branch on the failure kind — `PAUSE_CHANGED` when a `pauseId` names a pause that is no longer current, `PLAN_CHANGED` when a `planHash` names another plan, `PLAN_HASH_REQUIRED` when strict plan binding needs one.

**Kill-switch:** set `eddi.mcp.hitl.mutations.enabled=false` to make MCP a **read-only** HITL surface — `resume_conversation`, `cancel_conversation`, `approve_group_phase`, and `cancel_group_discussion` then return a `DISABLED` error while the read-only list/status tools keep working. MCP is a transport, not a new authority: no tool lets an agent approve its own gate.

## Known Limitations (v1)

* **Member-level HITL inside a group**: a member agent's own `PAUSE_CONVERSATION` rule firing during a group turn is not supported — the turn is recorded as SKIPPED with an explanatory note, the member's stranded pause is auto-cancelled (audited as `system:group`), and a `member_pause_skipped` SSE event is emitted. Use group-level HITL (`requiresApproval`) instead.
* **Nested groups**: `requiresApproval` inside a sub-group of a group-of-groups is not supported — the sub-pause is cancelled and the member turn is recorded as SKIPPED with an explanatory note.
* **Cross-pod cancel of an actively-running turn**: the cooperative cancel flag is per-pod; the DB CAS covers paused states cluster-wide, and a running group leg re-checks the persisted state at every phase boundary, so a cross-pod cancel takes effect at the next boundary.
* **Tool-level HITL** (pausing when the LLM invokes a gated tool) is **implemented** — see [Tool-Level Approval Gating](#tool-level-approval-gating). Group-member tool pauses are auto-rejected gracefully (they have no reviewer); the `inGroupTurns: "INBOX"` mode is reserved (rejected at save time in v1).
* **Managed REST conversations** (`RestAgentManagement`): a managed intent mapping stays pinned to a paused conversation until it is resumed or reset — a managed `say` against it answers `409` promptly, but the mapping is not automatically re-created while the approval is pending.
* **Upgrade notes**:
  * `DiscussionPhase.requiresApproval` existed before this feature as an inert placeholder. Stored group configs that set it to `true` will begin pausing for approval after this upgrade.
  * `PAUSE_CONVERSATION` is a **newly reserved action name**. A stored behavior-rule config that already emitted an action with this exact name will begin pausing conversations after this upgrade — rename such actions before upgrading.
  * During a rolling upgrade, pods running the previous version cannot read conversations paused by new pods (unknown `AWAITING_HUMAN` state) — schedule pause-heavy traffic after the rollout completes.
