Skip to content

Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure

TypeScript

docs(guardrails): add unified mcp-host guardrails spec suite

Andy Pavia641ba77c3335
diff --git a/docs/features/llm-hooks-spec.md b/docs/features/llm-hooks-spec.md
deleted file mode 100644
index a9f25b19b..000000000
--- a/docs/features/llm-hooks-spec.md
+++ /dev/null
@@ -1,353 +0,0 @@
-# Spec · LLM hooks — implementation & marketplace install (v2)
-
-**Type:** design spec (implementable) · **Date:** 2026-08-10 · **Status:** draft for approval
-**Code head:** `evenfire` @ `dev`
-**Model:** a request-lifecycle hook chain (`pre_call` / `moderation` / `post_call_success` /
-`post_call_failure`) realized **in-process** at the mcp-host `LlmPort` seam, with a second class of
-hook that is an **installable marketplace artifact running in its own pod**.
-
-> v2 supersedes the conceptual v1: two hook classes, dedicated `LlmHook` CRD, and a
-> `/admin/registry/install-hook` saga. This doc is implementation-first.
-
----
-
-## 0 · The two hook classes
-
-| Class | Runs where | Examples | Distribution | Trust |
-|---|---|---|---|---|
-| **Built-in** | inside mcp-host (`HookedLlmPort` + `core/extensions/prePrune.ts`) | `prompt-shaping`, `token-trim` | compiled into mcp-host, enabled by config | first-party |
-| **Remote** | its own pod/image (Deployment+Service+NetworkPolicy) | `guardrail`, `pii-redact` (3rd-party) | **marketplace** → `LlmHook` CRD | image-allowlist + sha256 digest + egress policy + trust_level |
-
-Both classes implement the **same `LlmHook` interface** and run in the **same ordered chain** at the
-same seam. A remote hook is just an `LlmHook` whose methods make an HTTP call to its pod. Third-party
-code never runs inside the mcp-host process (which holds LLM credentials + conversation state).
-
----
-
-## 1 · Runtime seam (shared by both classes)
-
-Every completion funnels through `LlmPort.completeWithTools` (`mcp-host/src/core/interfaces.ts:33`);
-`LlmPortAdapter` (`core/adapters/llmPortAdapter.ts:93`) is the one implementation, sitting under an
-optional `FailoverLlmPort` (`core/adapters/failoverLlmPort.ts:56`). We insert a decorator **above
-failover** so each hook fires **once per logical request**.
-
-### 1.1 · `LlmHook` interface · `mcp-host/src/llm/hooks/types.ts` (new)
-```ts
-export interface LlmHookContext {
- readonly callType: 'complete' | 'completeWithTools'
- readonly model: string
- readonly provider: LlmProvider
- readonly host: { hostRef?: string; contextRef?: string } // NOT llmSecretName — see §6
- readonly usage?: UsageContext // user_id, team_id, recipe_name, task_id, traceContext
- readonly signal?: AbortSignal
- readonly state: Record<string, unknown> // mutable, shared across ONE request's hooks
-}
-export type PreCallOutcome =
- | { action: 'continue'; request?: ToolCompletionRequest } // optionally-mutated request
- | { action: 'reject'; error: LlmError } // veto before any tokens spent
-export interface LlmHook {
- readonly name: string
- readonly failMode: 'open' | 'closed'
- readonly timeoutMs: number
- preCall?(req: ToolCompletionRequest, ctx: LlmHookContext): Promise<PreCallOutcome>
- moderate?(req: ToolCompletionRequest, ctx: LlmHookContext): Promise<void> // throw = fail
- postCallSuccess?(req: ToolCompletionRequest, res: ToolCompletionResponse, ctx: LlmHookContext): Promise<ToolCompletionResponse>
- onError?(req: ToolCompletionRequest, err: LlmError, ctx: LlmHookContext): Promise<LlmError>
-}
-```
-
-### 1.2 · `HookedLlmPort` decorator · `mcp-host/src/core/adapters/hookedLlmPort.ts` (new)
-Implements `LlmPort`, wraps an inner `LlmPort`, holds `readonly hooks: LlmHook[]` (built-ins first,
-then remote hooks by `order`). Behavior:
-- **preCall** in order; thread the mutated request forward; `reject` → throw immediately (no
- dispatch). Thrown/timed-out hook obeys `failMode` (closed → reject, open → skip + warn metric).
-- **moderate ‖ dispatch**: `linkedAbort` chained to `req.signal`; `Promise.all([inner.completeWithTools(req), ...moderate()])`.
- A rejected `moderate` calls `linkedAbort.abort()` and throws a `ContentFiltered` `LlmError`
- (`core/errors.ts`). Succeeds only when the call **and** every moderation resolve.
-- **postCallSuccess** folds in **reverse** order (onion). **onError** folds inner throw (after
- failover) in reverse order. `modelName()`/`getTokenCounter?()` delegate to inner.
-- Per-hook calls wrapped in `withTimeout(hook.timeoutMs)`.
-
-### 1.3 · Lifecycle state machine
-
-```mermaid
-stateDiagram-v2
- [*] --> BuildContext : completeWithTools(request)
- BuildContext --> PreCall : ctx = usage + model + state{}
-
- state PreCall {
- [*] --> RunHooks
- RunHooks --> RunHooks : continue — mutate request, next hook
- RunHooks --> [*] : all hooks approved
- }
-
- PreCall --> Rejected : a hook rejects (or fail-closed error/timeout)
- PreCall --> Dispatch : approved (request possibly mutated)
-
- state Dispatch {
- [*] --> UpstreamCall
- UpstreamCall --> CallSucceeded : response
- UpstreamCall --> CallFailed : throws (after failover)
- --
- [*] --> Moderation
- Moderation --> ModerationPassed : all moderate() resolve
- Moderation --> ModerationFailed : a moderate() rejects
- }
-
- Dispatch --> Blocked : ModerationFailed → abort in-flight call
- Dispatch --> OnError : CallFailed
- Dispatch --> PostCall : CallSucceeded and ModerationPassed
-
- state PostCall {
- [*] --> Transform
- Transform --> Transform : redact / transform (reverse order)
- Transform --> [*] : chain done
- }
- PostCall --> Success
-
- state OnError {
- [*] --> Reshape
- Reshape --> Reshape : reshape error (reverse order)
- Reshape --> [*] : chain done
- }
- OnError --> Failed
-
- Rejected --> [*] : throw LlmError — no tokens spent
- Blocked --> [*] : throw ContentFiltered LlmError
- Success --> [*] : return ToolCompletionResponse
- Failed --> [*] : throw reshaped LlmError
-```
-
-### 1.4 · Wiring · `mcp-host/src/agent/taskExecutor.ts`
-In `buildLoopConfig` (`taskExecutor.ts:1057`), after `effectiveLlmPort` is built (primary or
-failover-wrapped, `:1017–1055`): `effectiveLlmPort = new HookedLlmPort(effectiveLlmPort, chain)`.
-Build `LlmHookContext.usage` from the existing `buildDefaultUsageContext()` (`:1436`). The compaction
-lane (`stateMachine.ts:821`) gets only built-in trim/observability hooks (flag on the chain builder).
-
----
-
-## 2 · Built-in hooks (in-process, first-party)
-
-Implement as `LlmHook`s compiled into mcp-host, under `mcp-host/src/llm/hooks/builtins/`:
-| type | method(s) | implementation notes |
-|---|---|---|
-| `prompt-shaping` | `preCall` | inject a system `systemPromptParts` entry; force `temperature`/`max_tokens`/`tool_choice`. |
-| `token-trim` | `preCall` | reduce **input** tokens to a budget; **reuse the existing `core/extensions/prePrune.ts` passes** internally (they already do toggleable pre-LLM context pruning) — the hook is a thin `LlmHook` wrapper so ordering/config are uniform with the chain. |
-
-Registered in a `Map<type, (config)=>LlmHook>` (`mcp-host/src/llm/hooks/builtins/registry.ts`),
-enabled/ordered via config (§4). No marketplace, no network hop.
-
-```mermaid
-flowchart TB
- subgraph CFG["Host CRD · spec.llmHooks (config)"]
- C1["prompt-shaping<br/>(order, failMode, config)"]
- C2["token-trim<br/>(budget, config)"]
- end
-
- CFG --> REG["builtins/registry.ts<br/>Map&lt;type, factory&gt;"]
- REG --> PS["prompt-shaping : LlmHook"]
- REG --> TT["token-trim : LlmHook"]
-
- subgraph CHAIN["HookedLlmPort · built-ins run first (preCall only)"]
- direction TB
- PS --> PSA["force temperature / max_tokens / tool_choice<br/>append systemPromptParts"]
- TT --> Q{"input tokens &gt; budget?"}
- Q -->|no| PASS["pass through unchanged"]
- Q -->|yes| PP["reuse core/extensions/prePrune.ts passes<br/>drop / compact oldest messages"]
- PP --> Q2{"under budget?"}
- Q2 -->|no| PP
- Q2 -->|yes| TRIM["trimmed request"]
- end
-
- PSA --> OUT["mutated ToolCompletionRequest<br/>→ next hook / dispatch"]
- PASS --> OUT
- TRIM --> OUT
-```
-
-Both built-ins are `preCall`-only (no `moderate`/`postCall`); they mutate the request and hand it to
-the next hook. Remote marketplace hooks (§3) run **after** the built-ins, by `order`.
-
----
-
-## 3 · Remote hooks (installable, own pod)
-
-### 3.1 · `RemoteLlmHook` adapter · `mcp-host/src/llm/hooks/remoteHook.ts` (new)
-An `LlmHook` whose methods POST to the hook pod's in-cluster `Service`. Constructed from an `LlmHook`
-CRD (§3.3). Only the lifecycle methods the CRD's `lifecyclePoints` declare are wired; others are
-`undefined` (skipped by the chain).
-
-### 3.2 · Hook protocol (HTTP/JSON, `mcp-host → hook Service`)
-Versioned under `/v1`. mcp-host authenticates with a short-lived RS256 token (reuse the broker-token
-signer pattern, `control-api/src/utils/auth/*`) and the connection is confined by NetworkPolicy.
-| Endpoint | Request body (redacted projection — §6) | Response |
-|---|---|---|
-| `POST /v1/pre_call` | `{ messages, tools?, model, params, usage, state, config }` | `{ action:'continue', patch?:{messages?,params?,systemPromptParts?} } \| { action:'reject', code, message }` |
-| `POST /v1/moderate` | `{ messages, model, usage, config }` | `200 {}` = pass · `4xx { code, message }` = fail |
-| `POST /v1/post_call` | `{ response:{content,tool_calls,finish_reason}, usage, state, config }` | `{ response }` (possibly redacted) |
-| `POST /v1/on_error` | `{ error:{code,message,retryable}, usage, state, config }` | `{ error:{code,message} }` |
-
-`RemoteLlmHook` maps a `pre_call` `patch` onto the local `ToolCompletionRequest` (mcp-host applies the
-patch — the hook never gets the raw request object), and maps `reject`/moderation-4xx onto an
-`LlmError`. `timeoutMs`/`failMode` come from the CRD.
-
-### 3.3 · `LlmHook` CRD · `charts/clerum-crds/crds/llmhook.yaml` (new)
-Namespaced `clerum.io/v1alpha1`, **modeled field-for-field on `mcpserver.yaml`** so it reuses the
-same image-trust + egress machinery. Reconciled by the **host-context-controller** into
-Deployment+Service+NetworkPolicy (new `host-context-controller/src/llmHookReconciler.ts`, mirroring
-the McpServer reconcile).
-```yaml
-spec:
- image: registry.evenfire.ai/hooks/pii-redact:1.2.0 # required; image-allowlist enforced
- imagePullSecrets: [ ... ] # reuse evenfire-registry-pull
- port: 8080
- lifecyclePoints: [preCall, moderate, postCallSuccess, onError] # which /v1 endpoints it serves
- order: 100 # chain position (built-ins run before)
- scope: context # global | context (see §3.4) — DECIDED: both supported
- failMode: closed # closed = a hook failure rejects the request
- timeoutMs: 5000
- onUnavailable: # per-hook down-behavior (DECIDED)
- mode: breaker # breaker | strict
- failureThreshold: 5 # trips after N consecutive failures
- cooldownMs: 30000 # fail-open + alert while tripped; re-probe after
- appliesTo: # which requests this intercepts
- models: ['*']
- sourceKinds: ['channel','desktop','workflow']
- config: { ... } # opaque, passed to the hook
- envSecret: pii-redact-creds # hook's OWN credentials (not the LLM secret)
- egressBindings: [ { toFQDN: moderation.vendor.com, ports:[443] } ] # hook's outbound allowlist
- security: { addCapabilities: [] }
- managed: true # owned by HCC vs authored directly
-```
-- **`scope`** (DECIDED — both): `global` hooks live in the operator namespace and apply to every Host;
- `context` hooks live in the Context/team namespace and apply only there. mcp-host merges both (§3.4).
-- **`onUnavailable`** (DECIDED — per-hook): `strict` = a down fail-closed hook blocks every call;
- `breaker` = after `failureThreshold` consecutive failures the hook trips to fail-open (loud
- metric/alert) for `cooldownMs`, then re-probes. `RemoteLlmHook` owns the breaker state.
-
-**NetworkPolicy** (generated): ingress **only** from mcp-host pods on `port`; egress **only** per
-`egressBindings`. **Capability floor** reuses `@clerum/workflow-recipe-capability-policy`.
-
-### 3.4 · mcp-host discovery + hot reload · `mcp-host/src/llm/hooks/hookChainProvider.ts` (new)
-mcp-host **watches `LlmHook` CRDs** in **two scopes** (DECIDED — both global + per-Context): the
-operator namespace (`scope: global`) and its own Context namespace (`scope: context`). It filters by
-`appliesTo`, builds `RemoteLlmHook`s, and orders the chain as: **built-ins → global remote (by
-`order`) → context remote (by `order`)**. Rebuild on CRD add/update/delete in either scope and hand
-to the loop (hot reload, mirroring `main.ts` `refreshFailoverPolicy:406`). Each `RemoteLlmHook` owns
-its `onUnavailable` breaker state so a down hook degrades per its declared mode, not globally.
-
----
-
-## 4 · Config (built-ins) · Host CRD + `mcp-host/src/config.ts`
-Built-in hook selection/order stays on the Host CRD (`spec.llmHooks`, parsed by
-`mcp-host/src/llm/hooks/parseLlmHooks.ts`, hot-reloaded like `spec.llmPolicy`). Remote hooks are
-**not** listed here — their presence is the `LlmHook` CRD itself. `CLERUM_LLM_HOOK_TIMEOUT_MS` default.
-
----
-
-## 5 · Marketplace registration & install (answering "how do they get into the registry")
-
-Clone the connector path end-to-end. Nothing new in the trust model.
-
-### 5.1 · Registry entry type · `control-api/src/services/registryClient.ts`
-Add `'llm_hook'` to `RegistryEntry.entry_type` (`registryClient.ts:198`) with a `hook_meta`:
-`{ image, lifecyclePoints[], credential_schema, defaultConfig, requiredEgress[], appliesToDefaults }`.
-`getEntryVersion` / `credential-schema` / `bundle` / `digest` already generic — reused as-is.
-
-### 5.2 · Install saga · `control-api/src/routes/admin/registry.ts`
-New `POST /admin/registry/install-hook`, cloned from `install-recipe` (`:1360+`) / `install` (`:961`):
-1. `getEntryVersion` → **verify bundle `sha256` digest** (tamper check, cf. `:999`).
-2. Fetch + validate `credential_schema`; create a K8s `Secret` from user creds (cf. `:1214`).
-3. Build the `LlmHook` spec from `hook_meta` (image, port, lifecyclePoints, egress, envSecret ref).
-4. **Image-allowlist preflight** via `@clerum/image-policy` `classifyPluginImage` (cf. `:1174`).
-5. Stamp `clerum.io/catalog-id` + `catalog-version` annotations (`catalogAnnotations`, `:102`).
-6. Create the `LlmHook` CRD; **rollback saga** on any failure (delete CRD + Secret).
-7. Fire-and-forget `reportInstall` (`:1331`).
-
-### 5.3 · Installed-state + catalog · `registry.ts:658`
-Extend `getInstalledRegistryState` to list `LlmHook` CRDs and match by `catalog-id`, so
-`GET /admin/registry/catalog` (`:718`) shows hooks as "installed."
-
-### 5.4 · control-ui
-Add a **"Guardrails / Hooks"** tab to `components/MarketplaceTabs.tsx`; an install form cloned from
-`components/RegistryInstallForm/` (credential-schema-driven); surface `trust_level`/`quality_tier`
-(already on the entry). Route alias `/marketplace/hooks → /registry`.
-
-### 5.5 · Trust — 100% reuse
-Image allowlist (`@clerum/image-policy`, `config.allowedPluginImagePrefixes`), sha256 bundle digest,
-per-org pull secret (`registryPullSecretService`), capability whitelist
-(`@clerum/workflow-recipe-capability-policy`), `trust_level`/`quality_tier`, install-time credential
-`Secret`, per-workload egress NetworkPolicy. **No new trust primitives.**
-
-### 5.6 · Publish/author path
-A hook author ships a container image implementing the `/v1` protocol + a registry manifest
-(`entry_type: llm_hook`, `hook_meta`). Publish via `POST /admin/registry/entries` (`publishEntry`,
-`:764`) with org scoping. A reference hook image + template lives under `mcp-servers/`-style samples.
-
----
-
-## 6 · Security invariants
-- **No third-party code in the mcp-host pod** — remote hooks run in their own pod; mcp-host only makes
- an authenticated HTTP call.
-- **Hooks never receive LLM provider credentials.** `LlmHookContext.host` omits `llmSecretName`.
-- **Content exposure is need-based + trust-gated** (DECIDED). A remote hook receives message/response
- **content** only for the lifecycle points that require it — `moderate`/`postCallSuccess` get content,
- `preCall` param-shaping gets model+params+metadata but not message bodies — **and** only if the
- entry's `trust_level` clears a configurable bar (`config.minHookTrustLevel`); below the bar, install
- is refused or the hook is content-starved. Every content-bearing hook call is audit-logged
- (hook name, lifecycle point, request id — not the content).
-- Hook's **own** credentials live in its **own** `Secret` (`envSecret`), never the LLM secret.
-- NetworkPolicy: hook ingress **only** from mcp-host; egress **only** per `egressBindings`.
-- **Fail-closed** default for `guardrail`/`pii-redact`; `token-trim`/observability fail-open. Per-hook.
-- Bounded per-hook `timeoutMs`; a slow/hung hook cannot stall the reasoning loop; a rejected
- `moderate` **aborts** the in-flight call so no tokens are wasted.
-- `postCallSuccess` redaction runs **before** the response reaches the caller; telemetry stays in the
- adapter below on raw counts (redacted content never re-serialized to logs/billing).
-- Install-time: image allowlist + sha256 digest + trust_level surfaced for consent.
-
----
-
-## 7 · Sequencing / PRs
-1. **PR1 (runtime core):** `LlmHook` types + `HookedLlmPort` + built-ins (`prompt-shaping`,
- `token-trim` on prePrune) + `taskExecutor` wiring. Remote chain empty. Unit tests. No marketplace.
-2. **PR2 (remote plumbing):** hook `/v1` protocol + `RemoteLlmHook` + `LlmHook` CRD + HCC
- `llmHookReconciler` + mcp-host watch/`hookChainProvider` + hot reload.
-3. **PR3 (control-api marketplace):** `entry_type: llm_hook`, `install-hook` saga, installed-state,
- trust reuse.
-4. **PR4 (control-ui):** marketplace Hooks tab + install form + installed badges.
-5. **PR5:** metrics, docs (`docs/llm-providers/llm-hooks.md`), reference hook image.
-
-## 8 · Decisions (resolved) / risks
-1. **Dedicated `LlmHook` CRD** (not a WorkflowRecipe capability block) → independent lifecycle + its
- own marketplace `entry_type`; recipe-bundled hooks can be a later fast-follow. *(decided)*
-2. **Two classes:** built-ins in-process (no hop) vs remote (marketplace). *(decided)*
-3. **Install scope = both** `global` (operator ns, all Hosts) **and** `context` (team ns); merge order
- built-ins → global → context. *(decided, §3.3/§3.4)*
-4. **Down-behavior = per-hook** `onUnavailable: strict | breaker`; breaker trips to fail-open with
- alerting after N failures, re-probes after cooldown. *(decided, §3.3)*
-5. **Block UX = hard block:** a rejected `moderate`/pre-call surfaces a `ContentFiltered` `LlmError` to
- the caller (no advisory or canned-response mode in v1). *(decided)*
-6. **Content exposure = need-based + trust-gated** (§6): content only to lifecycle points that need it,
- gated by `trust_level`, audit-logged. *(decided)*
-7. **`onError` is reshape-only** in v1 (no canned-response recovery). *(open — confirm)*
-8. **Latency:** each remote hook is a round-trip; mitigations — moderation runs in parallel, built-ins
- in-proc, per-hook timeout, `appliesTo` scoping. **Streaming** stays out (single-shot lane).
-9. **Protocol versioning:** `/v1` prefix; CRD `lifecyclePoints` must match what the image serves
- (declared in `hook_meta`, probed at install).
-10. **Registry dependency:** `entry_type: 'llm_hook'` + `hook_meta` require the external
- `evenfire-registry` service to add the type. *(open — coordination)*
-
-## 9 · Verification
-1. **HookedLlmPort unit tests** (mock inner + fake hooks): preCall order/mutation/reject-no-dispatch;
- parallel moderation fail aborts the call; postCall reverse fold; onError reshape; per-hook
- timeout + `failMode`; empty chain = pass-through.
-2. **Built-in tests:** `token-trim` brings an over-budget message set under budget via the real token
- counter; `prompt-shaping` forces params + injects a system part.
-3. **RemoteLlmHook tests** (mock hook server): each `/v1` endpoint mapped correctly; reject/4xx →
- `LlmError`; patch application; timeout → `failMode`.
-4. **CRD/reconciler tests:** HCC materializes Deployment+Service+NetworkPolicy; ingress-from-mcp-host
- only; egress per `egressBindings`; capability floor.
-5. **Install saga tests** (mock registry): digest mismatch rejects; credential Secret created; CRD
- stamped with catalog-id; rollback on failure; installed-state reflects the hook.
-6. **Integration:** install a reference `pii-redact` hook from a mock registry → it appears installed
- → a reasoning turn's response is redacted by the remote hook, fired once across a failover.
-7. Confirm no LLM secret ever appears in a hook request body or hook logs.
diff --git a/docs/features/mcp-host-guardrails/00-unified-architecture.md b/docs/features/mcp-host-guardrails/00-unified-architecture.md
new file mode 100644
index 000000000..d26533261
--- /dev/null
+++ b/docs/features/mcp-host-guardrails/00-unified-architecture.md
@@ -0,0 +1,112 @@
+# S0 · MCP Host Guardrails — Unified Architecture
+
+| | |
+|---|---|
+| **Type** | architecture / umbrella spec |
+| **Status** | draft for discussion |
+| **Suite** | S1 [core](./01-guardrail-core.md) · S2 [tool-lane](./02-tool-lane-adapter.md) · S3 [llm-lane](./03-llm-lane-adapter.md) · S4 [trust & delivery](./04-hook-trust-and-delivery.md) |
+| **Scope** | specification only — no runtime/CRD/deployment change is authorized here |
+
+---
+
+## 0 · Thesis
+
+The MCP Host applies guardrails on two lanes — the **LLM completion** and **tool execution** — and both
+are the same machine: *intercept a call → run an ordered chain of policy contributors → aggregate to a
+decision → execute at-most-once → emit bounded audit.* They differ only in **what** they intercept and
+in the **trust model of their hooks**.
+
+So this suite is a **shared spine + two lane adapters + a shared trust substrate**, not one merged
+document:
+
+- **S1 · Guardrail Core** — the common decision/policy/audit machine.
+- **S2 / S3 · Lane adapters** — tool lane and LLM lane, each specialized over S1.
+- **S4 · Hook trust & delivery** — the substrate that lets a *local, digest-verified* hook and a
+ *remote, marketplace* hook coexist as explicit tiers.
+
+```mermaid
+flowchart TB
+ REQ["task / user request"] --> S3B["S3 · LLM-lane boundary<br/>HookedLlmPort (pre / moderate / post / on_error)"]
+ S3B --> MODEL["model completion"]
+ MODEL --> TC["model emits a tool call"]
+ TC --> S2B["S2 · Tool-lane boundary<br/>rules + PreToolUse → execute → PostToolUse"]
+ S2B --> EXEC["tool executes (at-most-once)"]
+ S3B -. decision algebra · admin policy · at-most-once · audit .-> CORE["S1 · Guardrail Core"]
+ S2B -. .-> CORE
+ S3B -. hooks delivered by .-> SUB["S4 · Hook trust &amp; delivery<br/>Tier A local · Tier B remote"]
+ S2B -. .-> SUB
+```
+
+---
+
+## 1 · The unifying abstraction — one `GuardrailBoundary`
+
+Each lane instantiates one boundary over its own call/result types (defined fully in S1):
+
+| Stage | Shared contract (S1) | LLM lane (S3) | Tool lane (S2) |
+|---|---|---|---|
+| Intercept | a call reaches a mandatory boundary | `HookedLlmPort` at `LlmPort` | resolved tool call before execution |
+| Contributors | ordered chain of **rules + hooks + validators** | moderation, prompt-shaping, token-trim, PII | permission rules, Pre hooks, hard validators |
+| Decision | `allow / ask / deny / no_decision`, strict aggregation `deny > ask > allow > no_decision` | reject→`deny`, moderation-fail→`deny`, continue→`allow` | as authored |
+| Rewrite | full input replacement, canonicalize + revalidate | `pre_call` patch | Pre-hook `updatedInput` |
+| Execute | **at-most-once**, snapshot-safe | one completion per logical request (above failover) | `executeSingleTool`, batch/resume |
+| Post | transform the model-visible result; never alter the authoritative outcome | `post_call`; `on_error` recover (gated) | `PostToolUse` |
+| Evidence | bounded-enum metrics + redacted, digest-based audit | S3 audit | S2 audit |
+
+A **contributor** is the shared unit: `{ phase: pre|post, source: admin_rule|host_rule|hook|validator,
+decision, reasonCode, rewrite?, capabilities? }`. Rules are declarative contributors; hooks are
+executable contributors delivered per S4.
+
+---
+
+## 2 · How the lanes' differences reconcile
+
+The two lanes independently agree on the trust primitives (universal mediation, no-secrets-in-hooks,
+digest/allowlist trust, HCC-delivered admin policy, at-most-once, bounded audit). Where they diverge,
+the resolution lives at the spine:
+
+| Divergence | Resolution | Home |
+|---|---|---|
+| Hook runs **local** vs **remote** | not either/or — **two tiers**; a hook declares its tier, admin policy admits tiers per lane/Context | S4 |
+| Hook **network/side-effects** | derived from tier: Tier A none/deterministic; Tier B egress-allowlisted | S4 |
+| Who **installs** | one **non-overridable Context admin policy** governs both tiers | S1 + S4 |
+| **Fail-open vs fail-closed** on hook-down | fail-closed is mandatory for any deny-authoritative hook; a `breaker` fail-open is allowed only for advisory hooks the admin opts in | S1 + S4 |
+| Hook **fabricating the outcome** | a named, admin-granted, audited `may_substitute_result` capability that never alters the stored outcome | S1 + S4 |
+| **Decision expressiveness** | the 4-valued algebra + strict aggregation for both lanes | S1 |
+
+The load-bearing move is the **tiered hook model** (S4): **Tier A** (trusted local, digest-verified,
+no-network, may be deny-authoritative) and **Tier B** (remote/marketplace, network-permitted,
+`trust_level`-gated, advisory unless strongly gated). Admin policy declares, per Context and lane, which
+tiers and which capabilities (`may_deny`, `may_rewrite`, `may_substitute_result`) are admissible — so the
+two specs' opposite instincts become expressible policy instead of contradiction.
+
+---
+
+## 3 · Sequencing
+
+1. **S1 (Core)** — lift the decision algebra, contributor contract, at-most-once/resume, admin-policy
+ model, and audit out of the lane specifics into a lane-neutral core.
+2. **S4 (Trust substrate)** — define Tier A + Tier B and the admin-policy tier/capability grants.
+3. **S2 / S3 (adapters, in parallel)** — each conforms to S1 and consumes S4; keeps its lane depth.
+
+Dependencies: S1 → {S4, S2, S3}; S4 → {S2, S3}. The open decisions in §4 gate S1's scope.
+
+---
+
+## 4 · Open decisions
+
+1. Does the **LLM lane need `ask`** (human approval before a model call)? If not, `ask` is tool-lane-only.
+2. May **tool-lane guardrails ever be Tier B** (remote), or local-only?
+3. Is **`may_substitute_result`** allowed on the tool lane, or LLM-only?
+4. Is **Guardrail Core** an in-process shared library (both lanes run in mcp-host) or a separate module?
+5. **Unify the reason-code registries**, or keep per-lane with a shared bounded-label discipline?
+6. Minimal **capability set** — is `{may_deny, may_rewrite, may_substitute_result}` enough, or also
+ `may_ask` / `may_add_context`?
+
+---
+
+## 5 · Out of scope for the spine
+
+The spine must not absorb lane mechanics: the tool lane's typed argument predicates, provenance, doom-loop,
+and persistence scanner (S2); and the LLM lane's `token-trim`/`prompt-shaping` built-ins and
+`HookedLlmPort` placement (S3). Those stay in the adapters.
diff --git a/docs/features/mcp-host-guardrails/01-guardrail-core.md b/docs/features/mcp-host-guardrails/01-guardrail-core.md
new file mode 100644
index 000000000..04276c7c6
--- /dev/null
+++ b/docs/features/mcp-host-guardrails/01-guardrail-core.md
@@ -0,0 +1,158 @@
+# S1 · Guardrail Core (lane-neutral)
+
+| | |
+|---|---|
+| **Type** | design spec |
+| **Status** | draft for discussion |
+| **Consumed by** | S2 [tool-lane](./02-tool-lane-adapter.md), S3 [llm-lane](./03-llm-lane-adapter.md) |
+| **Depends on** | S4 [trust & delivery](./04-hook-trust-and-delivery.md) for how hook contributors are invoked |
+
+The lane-neutral machine every guarded call passes through. A lane supplies the concrete **input** and
+**result** types; this core supplies the decision algebra, the contributor contract, execution safety,
+admin policy, and evidence.
+
+---
+
+## 1 · The `GuardrailBoundary`
+
+One mandatory boundary per guarded call: `Intake → Contributors → Aggregate → (Approve) → Execute → Post
+→ Evidence`. It is universal — native, remote, bridged, first-run, resumed, interactive, and unattended
+calls all pass the same boundary before execution.
+
+Lane-supplied types: `Input` (e.g. tool arguments / an LLM request), `Result` (tool result / LLM
+response), `ResolvedIdentity` (the *real* target after any bridge resolution — never inferred from a name
+pattern).
+
+```mermaid
+flowchart LR
+ IN["Intake<br/>resolve identity + input"] --> C["Contributors (pre)<br/>rules + hooks + validators"]
+ C --> AGG{"Aggregate<br/>deny &gt; ask &gt; allow &gt; no_decision"}
+ AGG -->|deny| DENY["Denied<br/>bounded result + audit"]
+ AGG -->|ask| APPR{"Approve<br/>exact-call resolver?"}
+ AGG -->|allow / no_decision| EXEC["Execute<br/>at-most-once"]
+ APPR -->|approved| EXEC
+ APPR -->|no resolver / denied| DENY
+ EXEC --> POST["Post contributors<br/>transform model-visible result"]
+ POST --> EV["Evidence<br/>bounded metrics + redacted audit"]
+ DENY --> EV
+```
+
+## 2 · Contributor contract
+
+A **contributor** is the unit every source produces:
+
+```
+Contributor = {
+ phase: 'pre' | 'post'
+ source: 'admin_rule' | 'host_rule' | 'hook' | 'validator' | 'current' // 'current' = the existing approval path
+ sourceId: string // stable configured id
+ decision: 'allow' | 'ask' | 'deny' | 'no_decision'
+ reasonCode: <bounded enum>
+ rewrite?: Input // full replacement of the input (pre only)
+ substitute?: Result // only if granted may_substitute_result (§6)
+ audit: { modelReason?, userReason?, details? } // redacted, bounded; not copied across surfaces
+}
+```
+
+- **Rules** are declarative contributors (the lane defines their match language). **Hooks** are executable
+ contributors; *how* a hook is executed (local child-process vs remote call) is S4's concern, not the
+ algebra's.
+- `modelReason` / `userReason` / `details` serve different consumers and MUST NOT be copied between
+ surfaces without explicit redaction.
+
+## 3 · Decision algebra & aggregation
+
+- **Strictness order:** `deny > ask > allow > no_decision`. The boundary outcome is the **strictest**
+ contribution across all matching sources; every contribution is retained in audit.
+- **`no_decision`** means "no guardrail source decided" → the lane's *defer* behavior (the existing approval path).
+- **Unmatched default is explicit:** when a lane has a non-empty rule set, an unmatched call contributes
+ `ask` (not silently `allow`); when it has no guardrail config at all, absence contributes `no_decision`.
+ A default is never synthesized when guardrails are absent (no-config compatibility, §7).
+- **Tie-break for presentation only:** when one bounded reason must be chosen for a metric or a
+ model-facing result, break ties deterministically (admin_rule → hook order → host_rule → lexical
+ sourceId). This selects *presentation*, never severity.
+- **Malformed input fails closed:** an unknown decision value or an out-of-range predicate is rejected at
+ admission; it never aggregates as permissive.
+
+## 4 · Rewrite safety
+
+A `pre` contributor's `rewrite` **replaces the entire `Input`**, which is then canonicalized and
+**re-validated** before the next contributor sees it. A contributor can never *weaken* an earlier
+stricter decision. Rewrites are re-evaluated, so an earlier `allow` on the original input is never reused.
+
+## 5 · Execution safety — at-most-once, snapshot, resume
+
+- **At-most-once:** an approved call executes exactly once; suspension, restart, retry, and batch resume
+ never execute a call more than once.
+- **Snapshot:** a suspended call persists an immutable snapshot — resolved identity, original + effective
+ input digests, matched rule/hook ids + decisions + rewrite digests, admin-policy digest, execution
+ mode, and state (`pending | approved | denied | executing | executed | post_complete`).
+- **Resume:** load the snapshot, verify identity + effective-input digest, verify hook artifacts still
+ match stored digests **without re-running pre hooks**, **re-load current admin policy and deny if it is
+ now stricter or missing**, atomically claim `executing`, run once, then run post hooks under a stable
+ idempotency key. An approval for a different digest/identity/expired request is invalid.
+
+## 6 · Capabilities
+
+Contributor powers beyond `allow/deny` are **explicit, admin-granted** capabilities (§ admin policy):
+`may_rewrite`, `may_ask`, `may_substitute_result`, `may_add_context`. In particular **`substitute` never
+alters the stored authoritative outcome** — it changes only the *caller-visible* result, is clearly
+tagged as contributor-originated, and is audited.
+
+## 7 · Administrative policy
+
+- **Shape** — `Context.spec.guardrails.adminPolicy`, an additive field on the Context CRD (rendered into
+ its `openAPIV3Schema`):
+
+```yaml
+adminPolicy:
+ type: object
+ properties:
+ denyRules: { type: array, items: { type: object } } # host-rule shape, action fixed = deny (S2 §2)
+ allowedHooks: # id + phase + expected digest
+ type: array
+ items:
+ type: object
+ required: [id, phase, digest]
+ properties:
+ id: { type: string }
+ phase: { type: string, enum: [preToolUse, postToolUse, preCall, moderate, postCallSuccess, onError] }
+ digest: { type: string }
+ allowedHookTiers: { type: array, items: { type: string, enum: [A, B] } }
+ allowedApprovalPolicies: { type: array, items: { type: string, enum: [cli_only, channel_users, designated_approvers] } }
+ allowedCapabilities: { type: array, items: { type: string, enum: [may_deny, may_rewrite, may_substitute_result, may_add_context] } }
+ limits:
+ type: object
+ properties:
+ maxRules: { type: integer, default: 100 }
+ maxHooksPerPhase: { type: integer, default: 8 }
+ maxHookTimeoutMs: { type: integer, default: 5000 }
+ maxHookOutputBytes: { type: integer, default: 65536 }
+```
+- **Admin cannot be weakened:** host rules, hooks, approvals, and wildcards can only *tighten*, never
+ override, an administrative `deny` or limit.
+- **Delivery:** the Host Context Controller reads the authorized Context policy, validates schema/digests/
+ limits, normalizes it, and **atomically materializes a read-only, digest-checked artifact** in the Host
+ namespace. The Host reads that artifact and gains no general Context RBAC. If policy is declared but no
+ valid artifact exists, the Host is **not Ready** and guarded execution **fails closed**; a malformed
+ update never replaces the last valid artifact; a policy-digest mismatch never falls back to Host-only
+ policy.
+- **No-config compatibility:** with no admin policy, host rules, or hooks, behavior is identical to
+ current — absence contributes `no_decision`.
+
+## 8 · Evidence — metrics & audit
+
+- **Metrics** use **fixed-enum labels only** (`decision`, `source`, `execution_mode`, `phase`, `outcome`,
+ `reason_code`, plus lane-supplied bounded dimensions). Ids, paths, args, free-form reasons, and digests
+ are **forbidden** as labels.
+- **Audit** events carry timestamps, identity linkage, original + resolved identities, decision + source
+ ids, bounded reason codes, original/effective **input digests**, policy/rule/hook digests, execution
+ state, and redaction status. Raw sensitive inputs, hook stdout/stderr, and credentials are excluded
+ unless a separate protected-trace contract permits a redacted form.
+- **Reason-code registry** is a single bounded enum (see §4/§8 open decision in S0 on per-lane vs unified).
+
+## 9 · Invariants (lane-neutral)
+
+Universal mediation · resolved-identity evaluation · strict aggregation · rewrite-then-revalidate ·
+at-most-once · authoritative-outcome-immutable · admin-cannot-be-weakened · authoritative-delivery
+(atomic, digest-checked) · bounded/redacted evidence · no-config compatibility.
diff --git a/docs/features/mcp-host-guardrails/02-tool-lane-adapter.md b/docs/features/mcp-host-guardrails/02-tool-lane-adapter.md
new file mode 100644
index 000000000..82fe49652
--- /dev/null
+++ b/docs/features/mcp-host-guardrails/02-tool-lane-adapter.md
@@ -0,0 +1,142 @@
+# S2 · Tool-lane adapter
+
+| | |
+|---|---|
+| **Type** | design spec (lane adapter) |
+| **Status** | draft for discussion |
+| **Conforms to** | S1 [core](./01-guardrail-core.md) · **Consumes** S4 [trust & delivery](./04-hook-trust-and-delivery.md) (Tier A) |
+| **Source of record** | the colleague's draft *MCP Host Guardrails — Permission Rules, Hooks & Admin Policy* (full tool-lane detail); this adapter re-homes it on S1/S4 |
+
+Specializes the `GuardrailBoundary` over **tool execution** (native + MCP tools). Everything not below —
+the decision algebra, aggregation, at-most-once/resume, admin policy, audit — comes from S1; hook
+execution (Tier A local child-processes) comes from S4.
+
+---
+
+## 1 · Lane types
+
+- **`Input`** = resolved-tool arguments; **`Result`** = the tool result; **`ResolvedIdentity`** = the real
+ tool after dynamic-bridge resolution.
+- **Provenance** (`native` vs `mcp`, server + name) comes from the **registry**, never inferred from a
+ `__` name pattern. A `clerum__tool_call` bridge rule evaluates the *resolved* target; it MAY additionally
+ constrain the original bridge identity but never instead of the resolved target.
+
+```mermaid
+flowchart TB
+ T["resolved tool call<br/>(provenance from registry)"] --> R["permission rules<br/>(typed predicates)"]
+ T --> P["PreToolUse hooks (Tier A)<br/>sequential · may rewrite"]
+ R --> A{"aggregate (S1)<br/>+ doom-loop guard"}
+ P --> A
+ A -->|deny| D["Denied<br/>bounded result + audit"]
+ A -->|ask| AP{"approval resolver?"}
+ A -->|allow / no_decision| HV["hard validators + containment"]
+ AP -->|approved / interactive| HV
+ AP -->|unattended · none| D
+ HV --> X["execute at-most-once"]
+ X --> PT["PostToolUse (once)<br/>redact model-visible result"]
+```
+
+## 2 · Permission rules (declarative contributors)
+
+`Host.spec.guardrails.rules[]` with `action: allow | ask | deny`, matched on provenance + **typed
+argument predicates**. Schema — `Host.spec.guardrails`, additive on the Host CRD:
+
+```yaml
+guardrails:
+ type: object
+ properties:
+ rules:
+ type: array
+ items:
+ type: object
+ required: [id, action, match]
+ properties:
+ id: { type: string }
+ action: { type: string, enum: [allow, ask, deny] }
+ reasonCode: { type: string }
+ match:
+ type: object
+ required: [tool]
+ properties:
+ tool:
+ type: object
+ required: [provenance]
+ properties:
+ provenance: { type: string, enum: [native, mcp] }
+ server: { type: string }
+ name: { type: string }
+ arguments:
+ type: array
+ items:
+ type: object
+ required: [type, pointer, op]
+ properties:
+ type: { type: string, enum: [path, url, command, json] }
+ pointer: { type: string } # constrained RFC 6901 JSON Pointer
+ op: { type: string } # per type — see the predicate list below
+ value: { x-kubernetes-preserve-unknown-fields: true }
+ hooks:
+ type: object
+ properties:
+ preToolUse: { type: array, items: { type: string } } # hook ids — must be in adminPolicy.allowedHooks
+ postToolUse: { type: array, items: { type: string } }
+```
+
+Predicate `op` values by `type`:
+
+- **`path`** — `equals | under | outside`; normalized, symlink-aware, boundary-safe containment; prefix
+ strings are forbidden.
+- **`url`** — `scheme_in | host_in | port_in | path_under`; parsed + normalized; credentials-in-URL rejected.
+- **`command`** — `executable_is | argv_prefix`; a structured executable + argv, not a parsed shell string.
+- **`json`** — `exists | equals | one_of | contains`; size- and depth-bounded; object-key order canonicalized.
+
+Predicates name constrained RFC-6901 JSON Pointers; invalid pointers / excess depth / excess count / over-
+limit values are **rejected at admission**. Wildcards support only `*` and `?`, anchored, bounded length
+— no regex. Array order is never security precedence (all matching rules contribute; S1 aggregates).
+
+Unmatched default follows S1: non-empty rules → `ask`; absent → `no_decision` (defer to the existing approval path).
+
+## 3 · Pre/PostToolUse hooks (Tier A)
+
+Executable contributors, delivered as **Tier A** local hooks (S4): admin-allowlisted, digest-verified,
+least-privilege child processes, no shell, no secrets, bounded stdio.
+
+- **PreToolUse** — runs sequentially **before** approval; returns `{decision, reasonCode, updatedInput,
+ additionalContext}`. `updatedInput` (only with `allow`/`ask`) is a full input replacement, canonicalized
+ + revalidated (S1 §4). Failure/timeout/digest-mismatch → declared fail-mode (decision-making pre hooks
+ default **closed**).
+- **PostToolUse** — runs **once** after the single execution attempt; may redact/replace the *model-visible*
+ result, add bounded context, or recommend stop. It **cannot** undo side effects, mark the execution
+ denied, or alter the stored outcome (S1 §5/§6).
+
+## 4 · Approvals — interactive & unattended
+
+Execution mode is set by the **availability of an exact-call approval resolver**, not by cron origin.
+
+- **Interactive** (`ask`/`force_ask`): one pending request bound to the resolved tool + effective-input
+ digest + rule/hook digests; choices are `approve_once | deny`. A broad wildcard/prior approval **cannot** satisfy
+ an explicit `ask`. This creates no persistent rule.
+- **Unattended:** explicit `deny` → deny; `ask` with no resolver → **deny** (`approval_unavailable`); `allow`
+ → proceed through hard validators + containment; `no_decision` → preserve current unattended behavior.
+- The existing `*`, exact-tool, and MCP-server approvals apply **only** inside `no_decision`/defer.
+
+Snapshot/resume for suspended calls uses S1 §5; batches are left-to-right with earlier denied/completed
+results preserved.
+
+## 5 · Doom-loop guard
+
+Within one task, three consecutive identical `(resolved tool, effective-input digest)` calls →
+`deny (repeated_identical_call)`. Any intervening different tool or input resets the counter; the counter
+is persisted with task state.
+
+## 6 · Persistence / prompt-injection hardening
+
+Rules and hooks evaluate memory and file tools including canonical paths after rewrites, but **path denial
+is not a substitute for content scanning**: raw `file_write` MUST route through the `WorkspaceService`
+scanner, and `daily/*` memory is treated as prompt-affecting persistent state.
+
+## 7 · Hard validators & containment (unchanged)
+
+Existing structural validators, MCP scoping, token restrictions, NetworkPolicy, and the stateless
+cron-manage containment remain authoritative and independent of guardrail outcome — a guardrail `allow`
+never bypasses them.
diff --git a/docs/features/mcp-host-guardrails/03-llm-lane-adapter.md b/docs/features/mcp-host-guardrails/03-llm-lane-adapter.md
new file mode 100644
index 000000000..6572c2af4
--- /dev/null
+++ b/docs/features/mcp-host-guardrails/03-llm-lane-adapter.md
@@ -0,0 +1,130 @@
+# S3 · LLM-lane adapter
+
+| | |
+|---|---|
+| **Type** | design spec (lane adapter) |
+| **Status** | draft for discussion |
+| **Conforms to** | S1 [core](./01-guardrail-core.md) · **Consumes** S4 [trust & delivery](./04-hook-trust-and-delivery.md) (Tier A built-ins + Tier B remote) |
+
+Specializes the `GuardrailBoundary` over the **LLM completion call**. Decision algebra, aggregation,
+at-most-once, admin policy, and audit come from S1; hook delivery (in-process built-ins and remote hooks)
+comes from S4.
+
+---
+
+## 1 · Lane types & placement
+
+- **`Input`** = the `ToolCompletionRequest` (messages, tools, params, `usageContext`); **`Result`** =
+ the `ToolCompletionResponse`; **`ResolvedIdentity`** = model + provider.
+- The boundary is a **`HookedLlmPort`** decorator (`mcp-host/src/core/adapters/hookedLlmPort.ts`) wrapping
+ the effective `LlmPort` **above failover**, so contributors fire **once per logical request**, not per
+ fallback attempt. Wired in `taskExecutor.buildLoopConfig`.
+
+## 2 · Lifecycle → S1 contributor mapping
+
+| LLM-lane point | S1 contributor |
+|---|---|
+| `pre_call` (mutate) | `pre` contributor with `rewrite` (`may_rewrite`) |
+| `pre_call` (reject) / `moderation` fail | `pre` contributor `decision: deny` (`ContentFiltered`) |
+| `post_call_success` | `post` contributor transforming the model-visible `Result` |
+| `on_error` recover | `post`/error contributor with `substitute` (`may_substitute_result`, S4-gated) |
+| `token-trim` / `prompt-shaping` | `pre` contributors with `rewrite` |
+
+**Moderation runs concurrently** with the upstream call (`Promise.all([call, ...moderate()])`); a
+moderation `deny` aborts the in-flight call via a linked `AbortSignal` so no tokens are wasted. The happy
+path (call ok **and** all moderation pass) proceeds to `post`. A `pre` reject, a moderation block, and a
+call failure all converge on the `on_error` contributor chain, where a gated hook may `substitute` a safe
+`Result` (bypassing `post`, never model output) or the aggregated error surfaces.
+
+### 2.1 · Lifecycle state machine
+
+```mermaid
+stateDiagram-v2
+ [*] --> PreCall : completeWithTools(request)
+ state PreCall {
+ [*] --> RunHooks
+ RunHooks --> RunHooks : continue — rewrite, next
+ RunHooks --> [*] : all approved
+ }
+ PreCall --> OnError : a hook rejects (deny) — no dispatch
+ PreCall --> Dispatch : approved (possibly rewritten)
+
+ state Dispatch {
+ [*] --> Call
+ Call --> CallOk : response
+ Call --> CallFail : throws (after failover)
+ --
+ [*] --> Moderation
+ Moderation --> ModPass : all moderate() resolve
+ Moderation --> ModFail : a moderate() rejects → abort call
+ }
+
+ Dispatch --> OnError : CallFail or ModFail (seeds the error)
+ Dispatch --> PostCall : CallOk and ModPass
+ PostCall --> Success
+
+ state OnError {
+ [*] --> Handle
+ Handle --> Handle : reshape (reverse order)
+ Handle --> [*] : chain done or a hook recovers
+ }
+ OnError --> Recovered : a hook substitutes (may_substitute_result)
+ OnError --> Failed : no recover — aggregated error
+
+ Recovered --> [*] : return substitute response
+ Success --> [*] : return response
+ Failed --> [*] : throw aggregated error
+```
+
+`OnError` is the single convergence point for a `pre` reject, a moderation block, and a call failure; any
+gated hook may `recover` (return a safe response) instead of surfacing the error.
+
+## 3 · Built-in hooks (in-process, Tier A)
+
+First-party, compiled into mcp-host, no network — Tier-A-equivalent (S4):
+
+- **`prompt-shaping`** — inject a system prompt part; force `temperature`/`max_tokens`/`tool_choice`.
+- **`token-trim`** — reduce input tokens to a budget, reusing the existing `core/extensions/prePrune.ts`
+ passes; exposed as an `LlmHook` so ordering/config are uniform with the chain.
+
+Both are `pre`-only rewrite contributors. Registered in `mcp-host/src/llm/hooks/builtins/registry.ts`,
+selected/ordered by `Host.spec.llmHooks`.
+
+## 4 · Remote hooks (Tier B)
+
+Guardrail / PII-redaction and other third-party contributors run as **Tier B** hooks (S4): remote
+services reached over the `/v1` protocol, declared by an `LlmHook` CR, `trust_level`-gated, and delivered
+by any of the three modes (self-hosted pod / in-cluster Service / direct external egress). Their content
+exposure is need-based + trust-gated (S4); mcp-host discovers them by watching the CRs and orders the
+chain **built-ins → global remote → context remote**.
+
+## 5 · Aux/compaction lane
+
+The internal summarization/compaction calls (`stateMachine.ts`) run only **`token-trim` + observability**
+contributors — no guardrail/PII on internal calls — via an explicit per-lane flag on the chain builder.
+
+## 6 · Config — `Host.spec.llmHooks` (additive field on the Host CRD)
+
+Built-in selection/order lives on `Host.spec.llmHooks`, parsed by `mcp-host/src/llm/hooks/parseLlmHooks.ts`
+and hot-reloaded like `spec.llmPolicy`. Remote hooks are declared by their `LlmHook` CR (S4), not here.
+Schema (rendered into the Host CRD `openAPIV3Schema`):
+
+```yaml
+llmHooks:
+ type: array
+ items:
+ type: object
+ required: [type]
+ properties:
+ type: { type: string, enum: [prompt-shaping, token-trim] }
+ order: { type: integer, default: 100 }
+ failMode: { type: string, enum: [open, closed] }
+ timeoutMs: { type: integer, minimum: 1 }
+ config: { type: object, x-kubernetes-preserve-unknown-fields: true }
+```
+
+## 7 · Lane-specific notes
+
+`ask`/human approval is generally **unused** on this lane (S0 open decision 1) — the LLM adapter typically
+uses only `allow`/`deny`/`no_decision`. `HookedLlmPort` placement above failover and the built-ins are
+lane mechanics that stay here, not in S1.
diff --git a/docs/features/mcp-host-guardrails/04-hook-trust-and-delivery.md b/docs/features/mcp-host-guardrails/04-hook-trust-and-delivery.md
new file mode 100644
index 000000000..bd7ce7cc9
--- /dev/null
+++ b/docs/features/mcp-host-guardrails/04-hook-trust-and-delivery.md
@@ -0,0 +1,219 @@
+# S4 · Hook trust & delivery substrate
+
+| | |
+|---|---|
+| **Type** | design spec |
+| **Status** | draft for discussion |
+| **Consumed by** | S2 [tool-lane](./02-tool-lane-adapter.md) (Tier A), S3 [llm-lane](./03-llm-lane-adapter.md) (Tier A built-ins + Tier B) |
+| **Governed by** | S1 [core](./01-guardrail-core.md) admin policy (which tiers/capabilities are admissible) |
+
+How an *executable* contributor (a hook, per S1 §2) is trusted, delivered, and invoked. Both lanes' hooks
+resolve to one of **two tiers**; admin policy (S1 §7) declares which tiers and capabilities a given
+Context/lane may use.
+
+---
+
+## 1 · The two tiers
+
+| | **Tier A — trusted local** | **Tier B — remote / marketplace** |
+|---|---|---|
+| Runs as | least-privilege child process in the workload | own pod / in-cluster Service / external endpoint |
+| Network | none (deterministic transform) | permitted, egress-scoped |
+| Trust | admin-allowlisted, **digest-pinned** | image-allowlist + sha256 digest + `trust_level` |
+| Author | first-party / operator-vetted | third-party marketplace |
+| Fail-mode | fail-closed (may be **deny-authoritative**) | fail-closed if deny-authoritative; `breaker` fail-open only if advisory + admin-opted-in |
+| Typical use | tool-lane permission checks; LLM built-ins | LLM moderation/PII calling vendor services |
+
+**Capabilities are admin-granted per hook** (S1 §6): `may_deny`, `may_rewrite`, `may_substitute_result`,
+`may_add_context`. A lane can require Tier A for anything deny-authoritative and admit Tier B only for
+advisory contributions.
+
+## 2 · Tier A — local execution
+
+- **Config references hook IDs, never commands.** Each installed hook: `{id, phase, executable, args,
+ digest, timeoutMs, failureMode}`. Admin policy lists the allowed hook ids + expected digests.
+- **Verified before every launch:** canonical immutable realpath under the configured hook root; regular
+ file, expected owner, non-writable, no symlink escape; content digest equals administrative policy.
+- **Process boundary:** minimal allowlisted env; read-only cwd; **no LLM keys / K8s creds / secret-bearing
+ env**; bounded JSON stdin + bounded stdout/stderr; deadline + grace; least UID/groups/caps; **no
+ network**. `sh -c` / `bash -c` / `eval` / mutable paths / env-var command expansion are forbidden.
+- Hooks are **deterministic transforms over their JSON input** — no independent side effects or
+ notifications. Each invocation gets a stable idempotency key so a recovery can dedupe the result.
+
+## 3 · Tier B — remote invocation
+
+### 3.1 · The `/v1` protocol
+mcp-host POSTs the contributor call to the hook endpoint. **Auth:** a short-lived RS256 bearer token
+(broker-token signer) over a NetworkPolicy-confined connection; no mTLS. **Bodies** are a redacted,
+need-based projection (§5). Only the endpoints a hook's `lifecyclePoints` declares are called.
+
+| Endpoint | Request body (redacted projection — §5) | Response |
+|---|---|---|
+| `POST /v1/pre_call` | `{ messages, tools?, model, params, usage, state, config }` | `{ action:'continue', patch?:{messages?,params?,systemPromptParts?} } \| { action:'reject', code, message }` |
+| `POST /v1/moderate` | `{ messages, model, usage, config }` | `200 {}` = pass · `4xx { code, message }` = fail |
+| `POST /v1/post_call` | `{ response:{content,tool_calls,finish_reason}, usage, state, config }` | `{ response }` (possibly redacted) |
+| `POST /v1/on_error` | `{ error:{code,message,retryable}, messages, model, usage, state, config }` | `{ action:'reshape', error:{code,message} } \| { action:'recover', response:{content,tool_calls?} }` |
+
+`RemoteLlmHook` applies a `pre_call` `patch` onto the local request (the hook never gets the raw request
+object), maps `reject`/`moderate`-4xx onto a `deny` contributor, and maps `on_error` `recover` onto a
+`substitute` contributor (gated by `may_substitute_result`, §5/S1 §6).
+
+### 3.2 · The `LlmHook` CRD (declaration)
+Namespaced `clerum.io/v1alpha1`, reconciled by the **host-context-controller** (`llmHookReconciler.ts`).
+Full schema (rendered as the k8s CRD `openAPIV3Schema` under `charts/clerum-crds/crds/llmhook.yaml`):
+
+```yaml
+apiVersion: apiextensions.k8s.io/v1
+kind: CustomResourceDefinition
+metadata: { name: llmhooks.clerum.io }
+spec:
+ group: clerum.io
+ scope: Namespaced
+ names: { kind: LlmHook, listKind: LlmHookList, plural: llmhooks, singular: llmhook, shortNames: [llmhook] }
+ versions:
+ - name: v1alpha1
+ served: true
+ storage: true
+ schema:
+ openAPIV3Schema:
+ type: object
+ required: [spec]
+ properties:
+ spec:
+ type: object
+ required: [target, lifecyclePoints]
+ properties:
+ target: # exactly one of image | service | remote
+ type: object
+ oneOf: [{required: [image]}, {required: [service]}, {required: [remote]}]
+ properties:
+ image:
+ type: object
+ required: [ref, port]
+ properties:
+ ref: { type: string } # image-allowlist enforced at install
+ port: { type: integer, minimum: 1, maximum: 65535 }
+ imagePullSecrets: { type: array, items: { type: string } }
+ envSecret: { type: string } # hook's OWN creds (never the LLM secret)
+ egressBindings: { type: array, items: { type: object,
+ properties: { toFQDN: {type: string}, cidr: {type: string},
+ ports: {type: array, items: {type: integer}} } } }
+ security:
+ type: object
+ properties: { addCapabilities: { type: array, items: { type: string } } }
+ service:
+ type: object
+ required: [name, namespace, port]
+ properties:
+ name: { type: string }
+ namespace: { type: string }
+ port: { type: integer, minimum: 1, maximum: 65535 }
+ remote:
+ type: object
+ required: [baseUrl]
+ properties:
+ baseUrl: { type: string, pattern: '^https://' } # §4 SSRF-validated at dial
+ authHeadersSecret: { type: string }
+ lifecyclePoints:
+ type: array
+ minItems: 1
+ items: { type: string, enum: [preCall, moderate, postCallSuccess, onError] }
+ order: { type: integer, default: 100 }
+ scope: { type: string, enum: [global, context], default: context }
+ failMode: { type: string, enum: [open, closed], default: closed }
+ timeoutMs: { type: integer, default: 5000, minimum: 1 }
+ onUnavailable:
+ type: object
+ properties:
+ mode: { type: string, enum: [strict, breaker], default: strict }
+ failureThreshold: { type: integer, default: 5, minimum: 1 }
+ cooldownMs: { type: integer, default: 30000, minimum: 0 }
+ capabilities: # subset admin-granted (S1 §6); enforced ⊆ adminPolicy
+ type: array
+ items: { type: string, enum: [may_deny, may_rewrite, may_substitute_result, may_add_context] }
+ appliesTo:
+ type: object
+ properties:
+ models: { type: array, items: { type: string } }
+ sourceKinds: { type: array, items: { type: string,
+ enum: [channel, desktop, workflow, cron, plugin_workload_sdk] } }
+ config: { type: object, x-kubernetes-preserve-unknown-fields: true }
+ managed: { type: boolean, default: true }
+ x-kubernetes-validations: # CEL
+ - rule: "!has(self.target.remote) || self.target.remote.baseUrl.startsWith('https://')"
+ message: "remote.baseUrl must be https://"
+ - rule: "!(has(self.capabilities) && self.capabilities.exists(c, c == 'may_deny')) || self.failMode == 'closed'"
+ message: "a deny-authoritative hook (may_deny) must fail closed"
+```
+
+### 3.3 · Delivery modes & reconcile flow
+Exactly one `target`: **`image`** — HCC deploys a Deployment+Service+NetworkPolicy in the **`llm-hooks`**
+namespace (`CONTROL_API_LLM_HOOKS_NAMESPACE`), ingress only from mcp-host, egress per `egressBindings`;
+**`service`** — an existing in-cluster Service, nothing deployed; **`remote`** — an external HTTPS endpoint
+mcp-host dials directly (§4), no proxy pod.
+
+```mermaid
+flowchart LR
+ subgraph CP["control plane"]
+ UI["control-ui<br/>marketplace"] --> SAGA["control-api<br/>install-hook saga"]
+ SAGA -->|writes| CR["LlmHook CR<br/>(+ credential Secret)"]
+ SAGA -->|digest + image-allowlist + trust_level| SAGA
+ end
+ CR --> HCC["host-context-controller<br/>llmHookReconciler"]
+ HCC -->|image| DEP["Deployment + Service + NetworkPolicy<br/>(llm-hooks ns)"]
+ HCC -->|service / remote| NOP["no workload deployed"]
+ CR -. watch .-> MH["mcp-host<br/>hookChainProvider"]
+ MH --> RH["RemoteLlmHook"]
+ RH -->|image / service| DEP
+ RH -->|remote: direct egress + SSRF §4| EXT["external endpoint"]
+```
+
+control-api's saga only **writes** the CR + Secret; **HCC** reconciles it to workloads; **mcp-host** only
+**watches** the CRs (global + context) to build `RemoteLlmHook`s — it deploys nothing.
+
+## 4 · `remote`-mode egress (direct, matching the status quo)
+
+mcp-host dials a `remote` endpoint directly over its existing broad public-egress lane — the same way it
+already reaches external LLM providers (`deploy/base/mcp-host/networkpolicies.yaml:108-121` — `443 →
+0.0.0.0/0`; `llm/claude.ts` calls `api.anthropic.com` directly). No per-hook proxy pod: the proxy pattern
+exists to fence *untrusted connector pods*, which does not apply to the trusted mcp-host reaching out.
+
+**Destination safety is app-layer (the primary control):**
+1. **Config-only provenance** — the target comes only from the admin-vetted, `trust_level`-gated `LlmHook`
+ CR, never from model/tool/user/hook data.
+2. **Reuse the existing SSRF guard** (`core/tools/httpRequest.ts` + `core/safety/safety.ts`): `https` only;
+ block RFC-1918 / loopback / link-local / metadata `169.254.169.254` / `*.cluster.local`; resolve A+AAAA
+ and reject if any is private (fail-closed on DNS failure); **DNS-pin** to the validated IP; **no
+ redirects**.
+3. **Payload** stays governed by the content projection (§5).
+
+**L3 is a backstop only.** The broad lane is the pre-existing LLM-call posture; hooks add no new class of
+egress. Optional: a Calico `destination.domains` policy scoped to the admin-declared hook hosts, programmed
+by HCC per `remote` hook — per-host precision without a proxy pod.
+
+## 5 · Content exposure (Tier B)
+
+A remote hook receives message/response **content** only for the lifecycle points that need it
+(`moderate`/`post_call` get content; `pre_call` shaping gets model+params+metadata, not bodies) **and** only
+if the entry's `trust_level` clears `config.minHookTrustLevel`. Below the bar, install is refused or the hook
+is content-starved. Every content-bearing call is audit-logged (hook + phase + request id, not the content).
+`LlmHookContext.host` omits `llmSecretName`; the hook's own credentials live in its own Secret.
+
+## 6 · Marketplace (Tier B distribution)
+
+- Registry `entry_type: 'llm_hook'` with `hook_meta { target(image|service|remote), lifecyclePoints[],
+ credential_schema, defaultConfig, requiredEgress[], appliesToDefaults }`. Extending the `evenfire-registry`
+ schema is a prerequisite we own.
+- `POST /admin/registry/install-hook` saga (cloned from `install-recipe`): verify sha256 bundle digest →
+ validate + store credential Secret → build the `LlmHook` `target` → image-allowlist preflight → stamp
+ `catalog-id/version` → create CR → rollback on failure → `reportInstall`. Installed-state derived from CRs.
+- **Trust reuse (no new primitives):** `@clerum/image-policy` allowlist, sha256 digest, per-org pull secret,
+ `@clerum/workflow-recipe-capability-policy`, `trust_level`/`quality_tier`, install-time credential Secret,
+ per-workload egress NetworkPolicy.
+
+## 7 · Fail-posture
+
+Fail-closed is the default and **mandatory for any deny-authoritative hook** (either tier). A `breaker`
+(trip to fail-open after N failures, alert, re-probe) is permitted **only** for non-authoritative
+(advisory/observability) hooks and **only** when admin policy opts in. `RemoteLlmHook` owns per-hook breaker
+state so a down hook degrades per its declared mode, not globally.
diff --git a/docs/features/mcp-host-guardrails/README.md b/docs/features/mcp-host-guardrails/README.md
new file mode 100644
index 000000000..0148048f2
--- /dev/null
+++ b/docs/features/mcp-host-guardrails/README.md
@@ -0,0 +1,27 @@
+# MCP Host Guardrails — spec suite
+
+One guardrail/policy framework for the MCP Host, spanning **two lanes**:
+
+- **LLM lane** — guardrails on the model *completion* call (mutate/moderate the request, transform the
+ response, recover on failure).
+- **Tool lane** — guardrails on *tool execution* (permission rules + `Pre/PostToolUse` hooks + admin
+ policy + approvals).
+
+The two lanes share one decision/policy/audit machine (**S1**) and one hook trust/delivery substrate
+(**S4**); each lane is an adapter (**S2**, **S3**) over that shared foundation.
+
+## Suite
+
+| Spec | Scope |
+|---|---|
+| [`00-unified-architecture.md`](./00-unified-architecture.md) | **S0** — the umbrella: the shared abstraction, the suite map, and how the lanes' differences reconcile |
+| [`01-guardrail-core.md`](./01-guardrail-core.md) | **S1** — lane-neutral core: decision algebra + aggregation, contributor contract, at-most-once/resume, admin policy + HCC delivery, bounded audit |
+| [`02-tool-lane-adapter.md`](./02-tool-lane-adapter.md) | **S2** — tool lane: permission rules + typed predicates, `Pre/PostToolUse`, provenance, approvals, doom-loop, persistence |
+| [`03-llm-lane-adapter.md`](./03-llm-lane-adapter.md) | **S3** — LLM lane: `HookedLlmPort`, `pre_call`/`moderation`/`post_call`/`on_error`, built-ins |
+| [`04-hook-trust-and-delivery.md`](./04-hook-trust-and-delivery.md) | **S4** — hook tiers (local digest-verified vs remote/marketplace), invocation, install, egress, credential isolation |
+
+## Status
+
+All documents are **drafts for discussion**. No runtime, CRD, or deployment change is authorized by this
+suite — it is a specification. Each spec is self-contained; cross-references stay within the suite
+(S0–S4).
diff --git a/docs/features/mcp-host-guardrails/legacy/README.md b/docs/features/mcp-host-guardrails/legacy/README.md
new file mode 100644
index 000000000..2bd2a5aa4
--- /dev/null
+++ b/docs/features/mcp-host-guardrails/legacy/README.md
@@ -0,0 +1,28 @@
+# MCP Host Guardrails — spec suite
+
+Guardrail / policy specs for the MCP Host, across **two lanes**:
+
+- **LLM lane** — hooks on the model *completion* call (mutate/moderate the request, transform the
+ response).
+- **Tool lane** — permission rules + `Pre/PostToolUse` hooks + admin policy over *tool execution*
+ (a colleague's draft, tracked externally as a Notion/PDF; not committed here).
+
+## Documents
+
+| Doc | Role |
+|---|---|
+| [`mcp-host-guardrails-unified-architecture.md`](./mcp-host-guardrails-unified-architecture.md) | **S0 · umbrella** — the shared spine + trust substrate that unifies the two lanes, and how the disagreements resolve |
+| [`guardrails-vs-llm-hooks-comparison.md`](./guardrails-vs-llm-hooks-comparison.md) | analysis — where the two lanes **agree**, what each **emphasizes**, and where they **disagree** |
+| [`llm-hooks-spec.md`](./llm-hooks-spec.md) | **S3 · LLM-lane adapter** — pre/post-call hooks (guardrail/PII/prompt-shaping/token-trim) + the marketplace/remote-hook substrate |
+
+## Planned (not yet written)
+
+Per the umbrella §2, the full suite is:
+
+- **S1 · Guardrail Core** — decision algebra + aggregation, contributor contract, at-most-once/resume,
+ admin-policy model + HCC delivery, bounded audit. *(new; mostly lifted from the tool-lane spec.)*
+- **S2 · Tool-lane adapter** — the colleague's spec, re-homed on S1.
+- **S4 · Hook trust & delivery substrate** — Tier A (local, digest-verified) + Tier B
+ (remote/marketplace) and their governance. *(new; the main reconciliation work.)*
+
+Status: all drafts, for discussion — no runtime/CRD/deployment change is authorized by these documents.
diff --git a/docs/features/mcp-host-guardrails/legacy/guardrails-vs-llm-hooks-comparison.md b/docs/features/mcp-host-guardrails/legacy/guardrails-vs-llm-hooks-comparison.md
new file mode 100644
index 000000000..0e7e8b8b2
--- /dev/null
+++ b/docs/features/mcp-host-guardrails/legacy/guardrails-vs-llm-hooks-comparison.md
@@ -0,0 +1,123 @@
+# Comparison · Guardrails spec vs LLM-hooks spec — where they agree & what each emphasizes
+
+| | |
+|---|---|
+| **Colleague's doc** | *(DRAFT) MCP Host Guardrails — Permission Rules, Hooks & Admin Policy Specification* (draft target contract; not implemented) |
+| **Our doc** | [`llm-hooks-spec.md`](./llm-hooks-spec.md) — LLM pre/post-call hooks + marketplace |
+| **This doc** | where the two align (§2), what each emphasizes (§3–4), and where they genuinely disagree (§5) |
+
+---
+
+## 1 · They govern different lanes (so "agree" = shared principles, not same scope)
+
+Before the comparison: the two specs sit on **different lanes** and both are needed.
+
+- **Colleague's — the tool lane.** Guardrails on *tool execution* (native + MCP): `PreToolUse`/
+ `PostToolUse` hooks, host permission rules (`allow`/`ask`/`deny`), Context admin policy, approvals.
+- **Ours — the LLM lane.** Hooks on *the model completion call*: `pre_call`/`moderation`/`post_call`/
+ `on_error` for guardrail/PII/prompt-shaping/token-trim, plus a marketplace for remote hooks.
+
+A request runs **our lane** (mutate/moderate the model call → the model emits a tool call) then **his
+lane** (authorize/execute that tool call). They **stack**; neither replaces the other. So the
+agreements below are shared *principles*, applied to two different boundaries.
+
+---
+
+## 2 · Where you agree (shared design principles)
+
+Strong alignment — both specs independently landed on the same guardrail philosophy:
+
+| Shared principle | Colleague (Guardrails) | Ours (LLM-hooks) |
+|---|---|---|
+| **One mandatory mediation boundary; fail-closed** | G1 universal mediation; decision-making hooks default closed | `HookedLlmPort` single funnel; fail-closed default for guardrail/PII |
+| **Hooks never hold credentials/secrets** | G10 + §9.2: no LLM keys, K8s creds, or secret env in the hook | §6: hooks never receive the LLM provider credential |
+| **Hook trust via allowlist + content digest** | G10: preinstalled, admin-allowlisted, digest-verified | image-allowlist + sha256 bundle digest + `trust_level` |
+| **Admin/policy delivered by HCC as an atomic artifact; Host can't weaken it** | G4/G13: HCC materializes a read-only, digest-checked policy artifact | HCC reconciles `LlmHook` CRs; `global`/`context` scope, mcp-host only reads |
+| **Pre = mutate/reject; Post = redact/transform; Post can't undo side effects** | §9.3/§9.4 | `pre_call` continue/reject; `post_call_success` transforms the response |
+| **Rewrite safety: a rewrite replaces the whole input and is revalidated** | G7 | `pre_call` `patch` applied by mcp-host, request re-validated before dispatch |
+| **Fire/execute at-most-once, safe across retries** | G11/G12 (at-most-once execution; Post once) | `HookedLlmPort` fires once per logical request, **above** failover |
+| **Bounded, redacted observability** | §13/G15: fixed-enum metric labels; audit uses digests, not raw args | §6: audit-logged; telemetry on raw counts; redacted content projection |
+| **No-config compatibility (unconfigured = current behavior)** | G8 | PR1 lands an empty chain — pass-through, zero behavior change |
+| **Bounded hook execution (timeout + failure mode)** | `timeoutMs` + `failureMode` | per-hook `timeoutMs` + `failMode` + `onUnavailable` breaker |
+| **Evaluate the real resolved identity, not a guessed one** | G2 resolved identity; provenance from the registry | `ctx` carries the real model/provider + `usageContext` |
+
+Net: on **trust model primitives** (digests, allowlists, no-secrets, HCC-delivered admin artifact,
+bounded audit) and **hook lifecycle** (pre-mutate/reject, post-transform, at-most-once, revalidation,
+no-config safety) you are aligned.
+
+---
+
+## 3 · What your colleague focused more on
+
+Areas his spec develops in depth that ours barely touches (mostly because they're tool-lane concerns):
+
+- **A declarative permission-rule engine.** Host rules with `allow`/`ask`/`deny`, **typed argument
+ predicates** (`path`/`url`/`command`/`json` with RFC-6901 pointers, symlink-aware path containment,
+ URL credential rejection, no-regex bounded wildcards), provenance-aware matching, and **strict
+ aggregation** (`deny > force_ask > allow > no_decision`). Ours has *no* declarative rule layer — our
+ hooks are code/services, not argument-level allow/ask/deny rules.
+- **Human approval / interactive consent.** `force_ask` bound to the exact tool-call id + effective-input
+ digest, interactive vs unattended by resolver availability, and a full **approval snapshot / batch /
+ resume** state machine. Ours has no human-in-the-loop concept at the LLM lane.
+- **Exactly-once execution + resumability.** Suspended snapshots, resume re-checking admin policy without
+ rerunning Pre hooks, idempotency keys, and a **doom-loop guard** (3 identical resolved-tool+input →
+ deny). Ours treats the model call as a single completion — far less execution state.
+- **A non-overridable admin hierarchy.** "Admin cannot be weakened" (G4) as a first-class invariant —
+ Context policy strictly dominates Host rules/hooks/approvals. Ours has `global`/`context` scope but not
+ a strict *dominance* rule.
+- **Local sandboxed hook execution.** He solves the *trusted local executable* problem — least-privilege
+ child processes, per-launch digest/owner/realpath verification, no shell, bounded stdio. (Ours sidesteps
+ this by pushing hooks **out of process** instead — see §4.)
+- **Persistence / prompt-injection hardening.** Routing raw `file_write` through the `WorkspaceService`
+ scanner and treating `daily/*` memory as prompt-affecting. Not in our scope.
+- **Heavy formal apparatus.** 15 invariants, a 17-row **threat model** (T1–T17 with preventive +
+ detective controls and residual owners), 30 **acceptance scenarios** (A1–A30), a compatibility matrix,
+ a work-package dependency graph, and an **external-semantics survey** (OpenAI/Claude/Cursor/OpenCode
+ hook contracts). Ours is lighter on threat matrix / acceptance scenarios.
+
+---
+
+## 4 · What your spec focuses more on (the mirror)
+
+The inverse — areas ours develops that his doesn't address (his spec never touches the model call):
+
+- **Intercepting the LLM completion itself** — parallel `moderation`, PII redaction of model
+ input/output, `prompt-shaping`, `token-trim`, and `on_error` **recover** (substituting a safe response).
+ His hooks act only *after* the model has chosen a tool.
+- **Remote + marketplace distribution.** Installable third-party hooks: a registry `entry_type:
+ 'llm_hook'`, an `install-hook` saga, image-allowlist/digest/egress trust, and **three delivery modes**
+ (self-hosted pod, in-cluster Service, external endpoint) with a `llm-hooks` namespace. His hooks are
+ **local-only, admin-allowlisted** — explicitly *not* a marketplace/sidecar/WASM.
+- **Content-exposure governance for third-party code** — need-based + trust-gated message/response access.
+ Not a concern for his local, no-network hooks.
+
+---
+
+## 5 · Where you disagree
+
+The disagreements cluster in the **hook execution & trust model** — where, on the *same* question, the
+two specs make opposing choices. The first five are fundamental (a single "hook" mechanism cannot
+satisfy both); the last two are expressiveness gaps rather than contradictions.
+
+| Question | Colleague (Guardrails) | Ours (LLM-hooks) | |
+|---|---|---|---|
+| **Where a hook runs** | a local child process inside the Host workload; non-goals **exclude** sidecar / WASM / remote | a **remote** service (own pod / in-cluster Service / external endpoint) | fundamental |
+| **Network & side-effects** | **forbidden** — a deterministic JSON transform, "no independent external side effects," network stays outside the hook contract | **required** — guardrail/moderation/PII hooks call external services (e.g. `egressBindings` to a vendor API) | fundamental |
+| **Who may author / install** | admin-**allowlisted**, digest-pinned; "no arbitrary user scripts" | **third-party marketplace** installs, gated by `trust_level` tiers | fundamental |
+| **When a hook is down** | strict **fail-closed** — declared-but-unavailable policy ⇒ Host not Ready; digest mismatch never falls back | a per-hook **`onUnavailable: breaker`** may trip **fail-open** (with alerting) after N failures | fundamental (safety posture) |
+| **May a hook fabricate the outcome?** | **no** — Post redacts the *model-visible view* only; it can't alter the stored outcome, and a deny yields a bounded error | **yes** — `on_error` **`recover`** substitutes a full safe response for a blocked/failed call | fundamental |
+| **Decision expressiveness** | 4-valued `allow / force_ask / deny / no_decision`, **human `force_ask`**, and strict multi-source aggregation with precedence | `continue`/`reject` + moderation pass/fail + hard block; **no** human `ask`, no `defer`/`no_decision`, no aggregation | gap |
+| **Config authority** | a **non-overridable** Context allowlist of hook id+phase+**digest** the Host can't exceed | scope (`global`/`context`) on a CRD; no per-digest allowlist the Host is bound to | gap |
+
+**Reading it:** several of these are *lane-justified* — a tool guardrail genuinely should be a
+deterministic local check, and an LLM moderation genuinely needs to call a service — so they're not
+"someone is wrong." But they are the exact points that **collide if anyone tries to unify the two into
+one "hook" mechanism**, and two stand out as posture disagreements worth an explicit decision even while
+the specs stay separate:
+
+1. **local-no-network vs remote-network** hooks (the trust boundary is inverted), and
+2. **strict fail-closed vs fail-open breaker** when a hook is unavailable.
+
+Everything *else* composes cleanly (shared digest/allowlist/no-secrets/HCC-artifact/bounded-audit
+primitives on two stacked lanes) — so the recommendation stands: keep them as **two separate mechanisms**
+and say so in both docs, but align deliberately on those two posture questions.
diff --git a/docs/features/mcp-host-guardrails/legacy/llm-hooks-spec.md b/docs/features/mcp-host-guardrails/legacy/llm-hooks-spec.md
new file mode 100644
index 000000000..be5b6e83c
--- /dev/null
+++ b/docs/features/mcp-host-guardrails/legacy/llm-hooks-spec.md
@@ -0,0 +1,473 @@
+# Spec · LLM hooks — implementation & marketplace install
+
+| | |
+|---|---|
+| **Type** | design spec (implementable) |
+| **Date** | 2026-08-10 |
+| **Status** | draft for approval |
+| **Code head** | `evenfire` @ `dev` |
+| **Model** | a request-lifecycle hook chain (`pre_call` / `moderation` / `post_call_success` / `post_call_failure`) realized **in-process** at the mcp-host `LlmPort` seam, plus a second class of hook that is an **installable marketplace artifact running out-of-process** (a self-hosted pod, an in-cluster Service, or an external endpoint) |
+
+---
+
+## 0 · The two hook classes
+
+| Class | Runs where | Examples | Distribution | Trust |
+|---|---|---|---|---|
+| **Built-in** | inside mcp-host (`HookedLlmPort` + `core/extensions/prePrune.ts`) | `prompt-shaping`, `token-trim` | compiled into mcp-host, enabled by config | first-party |
+| **Remote** | out-of-process: self-hosted pod, in-cluster Service, or external endpoint (§3) | `guardrail`, `pii-redact` (3rd-party) | **marketplace** → `LlmHook` CRD | image-allowlist + sha256 digest + egress policy + trust_level |
+
+Both classes implement the **same `LlmHook` interface** and run in the **same ordered chain** at the
+same seam. A remote hook is just an `LlmHook` whose methods make an HTTP call to its pod. Third-party
+code never runs inside the mcp-host process (which holds LLM credentials + conversation state).
+
+---
+
+## 1 · Runtime seam (shared by both classes)
+
+Every completion funnels through `LlmPort.completeWithTools` (`mcp-host/src/core/interfaces.ts:33`);
+`LlmPortAdapter` (`core/adapters/llmPortAdapter.ts:93`) is the one implementation, sitting under an
+optional `FailoverLlmPort` (`core/adapters/failoverLlmPort.ts:56`). We insert a decorator **above
+failover** so each hook fires **once per logical request**.
+
+### 1.1 · `LlmHook` interface · `mcp-host/src/llm/hooks/types.ts` (new)
+```ts
+export interface LlmHookContext {
+ readonly callType: 'complete' | 'completeWithTools'
+ readonly model: string
+ readonly provider: LlmProvider
+ readonly host: { hostRef?: string; contextRef?: string } // NOT llmSecretName — see §6
+ readonly usage?: UsageContext // user_id, team_id, recipe_name, task_id, traceContext
+ readonly signal?: AbortSignal
+ readonly state: Record<string, unknown> // mutable, shared across ONE request's hooks
+}
+export type PreCallOutcome =
+ | { action: 'continue'; request?: ToolCompletionRequest } // optionally-mutated request
+ | { action: 'reject'; error: LlmError } // veto before any tokens spent
+export type OnErrorOutcome =
+ | { action: 'reshape'; error: LlmError } // transform the surfaced error
+ | { action: 'recover'; response: ToolCompletionResponse } // substitute a safe response
+export interface LlmHook {
+ readonly name: string
+ readonly failMode: 'open' | 'closed'
+ readonly timeoutMs: number
+ preCall?(req: ToolCompletionRequest, ctx: LlmHookContext): Promise<PreCallOutcome>
+ moderate?(req: ToolCompletionRequest, ctx: LlmHookContext): Promise<void> // throw = fail
+ postCallSuccess?(req: ToolCompletionRequest, res: ToolCompletionResponse, ctx: LlmHookContext): Promise<ToolCompletionResponse>
+ // Invoked whenever the request fails to produce a model response — a preCall
+ // reject, a moderation block, or a call failure (after failover). May reshape
+ // the surfaced error OR RECOVER with a substitute response. `recover` is
+ // trust-gated + audited (§6).
+ onError?(req: ToolCompletionRequest, err: LlmError, ctx: LlmHookContext): Promise<OnErrorOutcome>
+}
+```
+
+### 1.2 · `HookedLlmPort` decorator · `mcp-host/src/core/adapters/hookedLlmPort.ts` (new)
+Implements `LlmPort`, wraps an inner `LlmPort`, holds `readonly hooks: LlmHook[]` (built-ins first,
+then remote hooks by `order`). Behavior:
+- **preCall** in order; thread the mutated request forward. A `reject` (or a fail-closed
+ error/timeout, per `failMode`) does **not** dispatch — it seeds an `error` and jumps straight to
+ the onError chain (so a recovery hook can substitute a safe response with zero tokens spent).
+- **moderate ‖ dispatch**: `linkedAbort` chained to `req.signal`; `Promise.all([inner.completeWithTools(req), ...moderate()])`.
+ A rejected `moderate` calls `linkedAbort.abort()` and seeds a `ContentFiltered` `LlmError`
+ (`core/errors.ts`); a call failure (after failover) seeds its `LlmError`. Either routes to onError.
+ The happy path (call ok **and** every moderation passes) goes to postCallSuccess.
+- **postCallSuccess** folds in **reverse** order (onion) and returns the response.
+- **onError** — the single convergence point for preCall-reject, moderation-block, and call-failure.
+ Folds hooks in **reverse** order; each returns `reshape` (update the error, continue) or `recover`
+ (short-circuit: return the substitute response immediately — remaining onError hooks are skipped
+ and postCallSuccess is **not** re-run, since a recovered response is synthesized, not model output).
+ If the chain ends with no `recover`, throw the final reshaped error.
+- `modelName()`/`getTokenCounter?()` delegate to inner. Per-hook calls wrapped in `withTimeout(hook.timeoutMs)`.
+
+### 1.3 · Lifecycle state machine
+
+```mermaid
+stateDiagram-v2
+ [*] --> BuildContext : completeWithTools(request)
+ BuildContext --> PreCall : ctx = usage + model + state{}
+
+ state PreCall {
+ [*] --> RunHooks
+ RunHooks --> RunHooks : continue — mutate request, next hook
+ RunHooks --> [*] : all hooks approved
+ }
+
+ PreCall --> OnError : a hook rejects (or fail-closed error/timeout) — no dispatch
+ PreCall --> Dispatch : approved (request possibly mutated)
+
+ state Dispatch {
+ [*] --> UpstreamCall
+ UpstreamCall --> CallSucceeded : response
+ UpstreamCall --> CallFailed : throws (after failover)
+ --
+ [*] --> Moderation
+ Moderation --> ModerationPassed : all moderate() resolve
+ Moderation --> ModerationFailed : a moderate() rejects → abort call
+ }
+
+ Dispatch --> OnError : CallFailed or ModerationFailed (seeds the error)
+ Dispatch --> PostCall : CallSucceeded and ModerationPassed
+
+ state PostCall {
+ [*] --> Transform
+ Transform --> Transform : redact / transform (reverse order)
+ Transform --> [*] : chain done
+ }
+ PostCall --> Success
+
+ state OnError {
+ [*] --> Handle
+ Handle --> Handle : reshape error (reverse order)
+ Handle --> [*] : chain done or a hook recovers
+ }
+ OnError --> Recovered : a hook returns recover
+ OnError --> Failed : no recover — final reshaped error
+
+ Recovered --> [*] : return substitute ToolCompletionResponse
+ Success --> [*] : return ToolCompletionResponse
+ Failed --> [*] : throw reshaped LlmError
+```
+
+`OnError` is the single convergence point: a preCall reject, a moderation block, and a call failure
+all seed an error into it, and any hook may **recover** (return a safe response) instead of the error.
+
+### 1.4 · Wiring · `mcp-host/src/agent/taskExecutor.ts`
+In `buildLoopConfig` (`taskExecutor.ts:1057`), after `effectiveLlmPort` is built (primary or
+failover-wrapped, `:1017–1055`): `effectiveLlmPort = new HookedLlmPort(effectiveLlmPort, chain)`.
+Build `LlmHookContext.usage` from the existing `buildDefaultUsageContext()` (`:1436`). The compaction
+lane (`stateMachine.ts:821`) gets only built-in trim/observability hooks (flag on the chain builder).
+
+---
+
+## 2 · Built-in hooks (in-process, first-party)
+
+Implement as `LlmHook`s compiled into mcp-host, under `mcp-host/src/llm/hooks/builtins/`:
+| type | method(s) | implementation notes |
+|---|---|---|
+| `prompt-shaping` | `preCall` | inject a system `systemPromptParts` entry; force `temperature`/`max_tokens`/`tool_choice`. |
+| `token-trim` | `preCall` | reduce **input** tokens to a budget; **reuse the existing `core/extensions/prePrune.ts` passes** internally (they already do toggleable pre-LLM context pruning) — the hook is a thin `LlmHook` wrapper so ordering/config are uniform with the chain. |
+
+Registered in a `Map<type, (config)=>LlmHook>` (`mcp-host/src/llm/hooks/builtins/registry.ts`),
+enabled/ordered via config (§4). No marketplace, no network hop.
+
+```mermaid
+flowchart TB
+ subgraph CFG["Host CRD · spec.llmHooks (config)"]
+ C1["prompt-shaping<br/>(order, failMode, config)"]
+ C2["token-trim<br/>(budget, config)"]
+ end
+
+ CFG --> REG["builtins/registry.ts<br/>Map&lt;type, factory&gt;"]
+ REG --> PS["prompt-shaping : LlmHook"]
+ REG --> TT["token-trim : LlmHook"]
+
+ subgraph CHAIN["HookedLlmPort · built-ins run first (preCall only)"]
+ direction TB
+ PS --> PSA["force temperature / max_tokens / tool_choice<br/>append systemPromptParts"]
+ TT --> Q{"input tokens &gt; budget?"}
+ Q -->|no| PASS["pass through unchanged"]
+ Q -->|yes| PP["reuse core/extensions/prePrune.ts passes<br/>drop / compact oldest messages"]
+ PP --> Q2{"under budget?"}
+ Q2 -->|no| PP
+ Q2 -->|yes| TRIM["trimmed request"]
+ end
+
+ PSA --> OUT["mutated ToolCompletionRequest<br/>→ next hook / dispatch"]
+ PASS --> OUT
+ TRIM --> OUT
+```
+
+Both built-ins are `preCall`-only (no `moderate`/`postCall`); they mutate the request and hand it to
+the next hook. Remote marketplace hooks (§3) run **after** the built-ins, by `order`.
+
+---
+
+## 3 · Remote hooks (installable, out-of-process)
+
+### 3.1 · `RemoteLlmHook` adapter · `mcp-host/src/llm/hooks/remoteHook.ts` (new)
+An `LlmHook` whose methods POST to the hook's endpoint — its in-cluster `Service` (`image`/`service`
+modes) or an external URL dialed directly with SSRF validation (`remote` mode, §3.5), resolved from the
+`LlmHook` CRD (§3.3). Only the lifecycle methods the CRD's `lifecyclePoints` declare are wired; others
+are `undefined` (skipped by the chain).
+
+### 3.2 · Hook protocol (HTTP/JSON, `mcp-host → hook Service`)
+Versioned under `/v1`. **Auth: a short-lived RS256 bearer token** (reuse the broker-token signer,
+`control-api/src/utils/auth/*`) over a connection confined by NetworkPolicy (ingress-from-mcp-host-only).
+No mTLS.
+| Endpoint | Request body (redacted projection — §6) | Response |
+|---|---|---|
+| `POST /v1/pre_call` | `{ messages, tools?, model, params, usage, state, config }` | `{ action:'continue', patch?:{messages?,params?,systemPromptParts?} } \| { action:'reject', code, message }` |
+| `POST /v1/moderate` | `{ messages, model, usage, config }` | `200 {}` = pass · `4xx { code, message }` = fail |
+| `POST /v1/post_call` | `{ response:{content,tool_calls,finish_reason}, usage, state, config }` | `{ response }` (possibly redacted) |
+| `POST /v1/on_error` | `{ error:{code,message,retryable}, messages, model, usage, state, config }` | `{ action:'reshape', error:{code,message} } \| { action:'recover', response:{content,tool_calls?} }` |
+
+`RemoteLlmHook` maps a `pre_call` `patch` onto the local `ToolCompletionRequest` (mcp-host applies the
+patch — the hook never gets the raw request object), maps `reject`/moderation-4xx onto an `LlmError`,
+and maps an `on_error` `recover` onto a substitute `ToolCompletionResponse` (trust-gated + audited, §6).
+`timeoutMs`/`failMode` come from the CRD.
+
+### 3.3 · `LlmHook` CRD · `charts/clerum-crds/crds/llmhook.yaml` (new)
+Namespaced `clerum.io/v1alpha1`, **modeled field-for-field on `mcpserver.yaml`** (including its
+`image`-vs-`remote` split) so it reuses the same image-trust + egress machinery. Reconciled by the
+**host-context-controller** (new `host-context-controller/src/llmHookReconciler.ts`, mirroring the
+McpServer reconcile): `image` mode materializes a Deployment+Service+NetworkPolicy in `llm-hooks`;
+`service` and `remote` modes deploy nothing — `service` wires an in-cluster Service reference, and
+`remote` is dialed **directly** by mcp-host over its existing public-egress lane (§3.5).
+```yaml
+spec:
+ # Delivery — exactly ONE of image | service | remote (mirrors McpServer's image vs remote):
+ target:
+ image: # SELF-HOSTED: HCC deploys a Deployment + Service
+ ref: registry.evenfire.ai/hooks/pii-redact:1.2.0 # image-allowlist enforced
+ port: 8080
+ imagePullSecrets: [ ... ] # reuse evenfire-registry-pull
+ envSecret: pii-redact-creds # hook's OWN credentials (never the LLM secret)
+ egressBindings: [ { toFQDN: moderation.vendor.com, ports: [443] } ]
+ security: { addCapabilities: [] }
+ # service: # INTERNAL: an existing in-cluster Service — no pod deployed
+ # name: shared-guardrail; namespace: platform; port: 8080
+ # remote: # EXTERNAL: HTTPS endpoint mcp-host dials DIRECTLY (no proxy pod; §3.5)
+ # baseUrl: https://guardrail.vendor.com; authHeadersSecret: guardrail-creds
+ lifecyclePoints: [preCall, moderate, postCallSuccess, onError] # which /v1 endpoints it serves
+ order: 100 # chain position (built-ins run before)
+ scope: context # global | context (see §3.4)
+ failMode: closed # closed = a hook failure rejects the request
+ timeoutMs: 5000
+ onUnavailable: # per-hook down-behavior
+ mode: breaker # breaker | strict
+ failureThreshold: 5 # trips after N consecutive failures
+ cooldownMs: 30000 # fail-open + alert while tripped; re-probe after
+ appliesTo: # which requests this intercepts
+ models: ['*']
+ sourceKinds: ['channel','desktop','workflow']
+ config: { ... } # opaque, passed to the hook
+ managed: true # owned by HCC vs authored directly
+```
+- **Delivery modes** (three): `image` = HCC deploys a Deployment+Service and manages its lifecycle;
+ `service` = mcp-host calls an **existing in-cluster Service** (name/ns/port), nothing is deployed;
+ `remote` = an **external HTTPS endpoint mcp-host dials directly** (no proxy pod — §3.5), so no
+ third-party image runs in-cluster. The `image`-only fields (`imagePullSecrets`/`envSecret`/
+ `egressBindings`/`security`) apply solely to that mode.
+- **Namespace:** `image`-mode hook workloads deploy into a dedicated platform namespace
+ **`llm-hooks`** (env `CONTROL_API_LLM_HOOKS_NAMESPACE`, default `llm-hooks`) — parallel to
+ `mcp-server` / `sandbox-recipes` / `sandbox-ui`. **Both** `global` and `context` scopes live in it;
+ context-scoping is enforced by a `context` label + `appliesTo` + NetworkPolicy (ingress only from the
+ matching mcp-host), **not** by per-context namespaces — keeping the egress lane a single
+ `mcp-host` → `llm-hooks` hop. On per-tenant managed clusters (where Host namespaces are
+ `mcp-host-<slug>`), the hooks namespace follows the same per-tenant override.
+- **`scope`:** `global` applies to every Host in the deployment; `context` only to its Context/team.
+ mcp-host merges both (§3.4).
+- **`onUnavailable`** (per-hook): `strict` = a down fail-closed hook blocks every call;
+ `breaker` = after `failureThreshold` consecutive failures the hook trips to fail-open (loud
+ metric/alert) for `cooldownMs`, then re-probes. `RemoteLlmHook` owns the breaker state.
+
+**NetworkPolicy** (generated, `image` mode): the hook Service in `llm-hooks` accepts ingress **only**
+from mcp-host pods on `port`; egress **only** per `egressBindings`; **capability floor** reuses
+`@clerum/workflow-recipe-capability-policy`. `service` mode adds an egress lane to the referenced
+Service; `remote` mode uses mcp-host's existing public-egress lane, validated app-layer (§3.5) — no
+in-cluster hook pod and no proxy.
+
+**Ownership (who reconciles what):** the marketplace install saga (§5.2) only writes the `LlmHook` CR
+(+ its credential Secret). The **host-context-controller** reconciles that CR to the live
+Deployment/Service/NetworkPolicy on every add/update/delete (`image` mode) — the same actor that
+reconciles `McpServer`. mcp-host merely **watches** the CRs to build its hook chain (§3.4); it never
+deploys anything.
+
+### 3.4 · mcp-host discovery + hot reload · `mcp-host/src/llm/hooks/hookChainProvider.ts` (new)
+mcp-host **watches `LlmHook` CRDs** in **two scopes** (global + per-Context): the
+operator namespace (`scope: global`) and its own Context namespace (`scope: context`). It filters by
+`appliesTo`, builds `RemoteLlmHook`s, and orders the chain as: **built-ins → global remote (by
+`order`) → context remote (by `order`)**. Rebuild on CRD add/update/delete in either scope and hand
+to the loop (hot reload, mirroring `main.ts` `refreshFailoverPolicy:406`). Each `RemoteLlmHook` owns
+its `onUnavailable` breaker state so a down hook degrades per its declared mode, not globally.
+
+### 3.5 · `remote`-mode egress — direct, matching the status quo
+
+A `remote` hook is reached by **mcp-host dialing the external endpoint directly** — **not** through a
+per-hook egress-proxy pod (the `McpServer.spec.remote` nginx pattern). This is a deliberate
+simplification, and it adds **no new network-exposure class**, because it is exactly how mcp-host
+already reaches external LLM providers today.
+
+**Why it matches the status quo (current code):**
+- mcp-host's namespace is default-deny (`deploy/base/mcp-host/networkpolicies.yaml:6-17`), with one
+ **broad external lane**: `443/TCP → 0.0.0.0/0` (and `80`), `except: []`
+ (`networkpolicies.yaml:108-121`). No per-host allowlist, no FQDN policy, no proxy.
+- **LLM completions already ride that lane directly** — `new Anthropic({apiKey})` → `api.anthropic.com`
+ (`llm/claude.ts:30`), OpenAI-compatible providers use compiled-in baseURL constants
+ (`llm/registryCore.ts`). The provider baseURL set is a *functional table, not a network allowlist*.
+- So a `remote` hook endpoint is the **same shape of call** as an LLM completion. Routing it through a
+ proxy while the LLM call goes direct would be inconsistent for no security gain — the proxy pattern
+ exists to fence *untrusted connector pods*, not the trusted mcp-host reaching out.
+
+**Why the proxy's job is unnecessary here.** The nginx egress proxy on the MCP path does two things —
+(a) fence an untrusted vendor pod's egress, and (b) hide the upstream credential from that pod. Neither
+applies: mcp-host is first-party trusted code (there is no untrusted pod to fence), and it already holds
+credentials (LLM secrets), so holding one hook's outbound auth is not a new trust-boundary crossing.
+
+**Destination safety is enforced app-layer (primary control):**
+1. **Config-only provenance.** The dial target comes *only* from the reconciled, admin-vetted,
+ `trust_level`-gated `LlmHook` CR — never from a model output, tool result, user input, or a hook's
+ own response. The destination is a control-plane fact, not a data-plane input.
+2. **Reuse the existing SSRF guard.** The hook dial routes through the **same validation the
+ `http_request` tool already uses** (`core/tools/httpRequest.ts` + `core/safety/safety.ts`):
+ `https://` only, reject IP literals, **block RFC-1918 / loopback / link-local / metadata
+ `169.254.169.254` / `*.cluster.local`**, resolve A+AAAA and reject if any is private (fail-closed on
+ DNS failure), **DNS-pin** (connect to the validated IP with the original Host/SNI), and **do not
+ follow redirects**. This is a reuse, not new code, and it is what actually stops the one
+ high-severity threat — an admin-configured `baseUrl` pointing back at the cluster or metadata.
+3. **Payload minimization** stays governed by the need-based/`trust_level` content projection (§6);
+ egress governs *destination*, the projection governs *payload*.
+
+**L3 is the backstop, not the control.** The broad `0.0.0.0/0:443` lane bounds a *compromised* mcp-host
+only weakly — but that is the **pre-existing posture for LLM calls**, so hooks do not regress it. Teams
+that want network-level containment can add a Calico domain policy (`destination.domains`) scoped to the
+admin-declared hook hosts + provider hosts, ideally programmed by HCC per `remote` hook — no proxy pod,
+per-host precision, kept in sync with the CR. Note the current mcp-host external lane does **not**
+exclude private/metadata ranges at L3 (`except: []`) — which is exactly why control (2) is load-bearing
+rather than optional.
+
+---
+
+## 4 · Config (built-ins) · Host CRD + `mcp-host/src/config.ts`
+Built-in hook selection/order stays on the Host CRD (`spec.llmHooks`, parsed by
+`mcp-host/src/llm/hooks/parseLlmHooks.ts`, hot-reloaded like `spec.llmPolicy`). Remote hooks are
+**not** listed here — their presence is the `LlmHook` CRD itself. `CLERUM_LLM_HOOK_TIMEOUT_MS` default.
+
+---
+
+## 5 · Marketplace registration & install (answering "how do they get into the registry")
+
+Clone the connector path end-to-end. Nothing new in the trust model.
+
+### 5.1 · Registry entry type · `evenfire-registry` (PR0) + `control-api/src/services/registryClient.ts`
+Add `'llm_hook'` to `RegistryEntry.entry_type` (`registryClient.ts:198`) with a `hook_meta`:
+`{ target: image|service|remote, lifecyclePoints[], credential_schema, defaultConfig, requiredEgress[], appliesToDefaults }`.
+The `evenfire-registry` schema is **ours to extend** — the entry-type + `hook_meta` addition is **PR0**
+(§7), a prerequisite we own, not an external coordination. `getEntryVersion` / `credential-schema` /
+`bundle` / `digest` are already generic — reused as-is.
+
+### 5.2 · Install saga · `control-api/src/routes/admin/registry.ts`
+New `POST /admin/registry/install-hook`, cloned from `install-recipe` (`:1360+`) / `install` (`:961`):
+1. `getEntryVersion` → **verify bundle `sha256` digest** (tamper check, cf. `:999`).
+2. Fetch + validate `credential_schema`; create a K8s `Secret` from user creds (cf. `:1214`).
+3. Build the `LlmHook` spec's `target` from `hook_meta` (`image` | `service` | `remote`), plus
+ lifecyclePoints, egress, envSecret ref.
+4. **Image-allowlist preflight** via `@clerum/image-policy` `classifyPluginImage` (cf. `:1174`).
+5. Stamp `clerum.io/catalog-id` + `catalog-version` annotations (`catalogAnnotations`, `:102`).
+6. Create the `LlmHook` CRD; **rollback saga** on any failure (delete CRD + Secret).
+7. Fire-and-forget `reportInstall` (`:1331`).
+
+### 5.3 · Installed-state + catalog · `registry.ts:658`
+Extend `getInstalledRegistryState` to list `LlmHook` CRDs and match by `catalog-id`, so
+`GET /admin/registry/catalog` (`:718`) shows hooks as "installed."
+
+### 5.4 · control-ui
+Add a **"Guardrails / Hooks"** tab to `components/MarketplaceTabs.tsx`; an install form cloned from
+`components/RegistryInstallForm/` (credential-schema-driven); surface `trust_level`/`quality_tier`
+(already on the entry). Route alias `/marketplace/hooks → /registry`.
+
+### 5.5 · Trust — 100% reuse
+Image allowlist (`@clerum/image-policy`, `config.allowedPluginImagePrefixes`), sha256 bundle digest,
+per-org pull secret (`registryPullSecretService`), capability whitelist
+(`@clerum/workflow-recipe-capability-policy`), `trust_level`/`quality_tier`, install-time credential
+`Secret`, per-workload egress NetworkPolicy. **No new trust primitives.**
+
+### 5.6 · Publish/author path
+A hook author ships a container image implementing the `/v1` protocol + a registry manifest
+(`entry_type: llm_hook`, `hook_meta`). Publish via `POST /admin/registry/entries` (`publishEntry`,
+`:764`) with org scoping. A reference hook image + template lives under `mcp-servers/`-style samples.
+
+---
+
+## 6 · Security invariants
+- **No third-party code in the mcp-host pod** — remote hooks run out-of-process (self-hosted pod in
+ `llm-hooks`, an existing in-cluster Service, or an external endpoint mcp-host dials directly — §3.5);
+ mcp-host only makes an authenticated HTTP call.
+- **`remote`-mode destination safety** (§3.5): the dial target is **config-only** (the admin-vetted,
+ `trust_level`-gated `LlmHook` CR — never data-derived), validated by the reused `http_request` SSRF
+ guard (`https`-only, block private/loopback/link-local/metadata/`*.cluster.local`, DNS-pin,
+ no-redirect, fail-closed). The broad `0.0.0.0/0:443` NetworkPolicy is only an L3 backstop.
+- **Hooks never receive LLM provider credentials.** `LlmHookContext.host` omits `llmSecretName`.
+- **Content exposure is need-based + trust-gated.** A remote hook receives message/response
+ **content** only for the lifecycle points that require it — `moderate`/`postCallSuccess` get content,
+ `preCall` param-shaping gets model+params+metadata but not message bodies — **and** only if the
+ entry's `trust_level` clears a configurable bar (`config.minHookTrustLevel`); below the bar, install
+ is refused or the hook is content-starved. Every content-bearing hook call is audit-logged
+ (hook name, lifecycle point, request id — not the content).
+- Hook's **own** credentials live in its **own** `Secret` (`envSecret`), never the LLM secret.
+- NetworkPolicy: hook ingress **only** from mcp-host; egress **only** per `egressBindings`.
+- **Fail-closed** default for `guardrail`/`pii-redact`; `token-trim`/observability fail-open. Per-hook.
+- **`onError` `recover` fabricates the assistant's response**, so it is as powerful as content access:
+ only a hook whose `trust_level` clears the bar may recover, every recovery is audit-logged (hook
+ name + request id), and the substitute response is tagged **hook-originated** in telemetry — never
+ attributed to the model. A recovered response bypasses `postCallSuccess` (it is not model output).
+- Bounded per-hook `timeoutMs`; a slow/hung hook cannot stall the reasoning loop; a rejected
+ `moderate` **aborts** the in-flight call so no tokens are wasted.
+- `postCallSuccess` redaction runs **before** the response reaches the caller; telemetry stays in the
+ adapter below on raw counts (redacted content never re-serialized to logs/billing).
+- Install-time: image allowlist + sha256 digest + trust_level surfaced for consent.
+
+---
+
+## 7 · Sequencing / PRs
+0. **PR0 (registry schema — prerequisite, we own it):** add `entry_type: 'llm_hook'` + `hook_meta` to
+ `evenfire-registry`. Gates PR3's install saga; no runtime effect on its own.
+1. **PR1 (runtime core):** `LlmHook` types (incl. `onError` reshape/recover) + `HookedLlmPort` +
+ built-ins (`prompt-shaping`, `token-trim` on prePrune) + `taskExecutor` wiring (main lane + aux
+ lane restricted to trim/observability). Remote chain empty. Unit tests. No marketplace.
+2. **PR2 (remote plumbing):** hook `/v1` protocol + `RemoteLlmHook` + `LlmHook` CRD + HCC
+ `llmHookReconciler` + mcp-host watch/`hookChainProvider` + hot reload.
+3. **PR3 (control-api marketplace):** `entry_type: llm_hook`, `install-hook` saga, installed-state,
+ trust reuse.
+4. **PR4 (control-ui):** marketplace Hooks tab + install form + installed badges.
+5. **PR5:** metrics, docs (`docs/llm-providers/llm-hooks.md`), reference hook image.
+
+## 8 · Design decisions
+1. **Dedicated `LlmHook` CRD** (not a WorkflowRecipe capability block) → independent lifecycle + its own
+ marketplace `entry_type`. Recipe-bundled hooks are a possible later addition.
+2. **Two classes:** built-ins in-process (no hop) vs remote (marketplace).
+3. **Install scope = both** `global` (operator ns, all Hosts) **and** `context` (team ns); merge order
+ built-ins → global → context (§3.3/§3.4).
+4. **Down-behavior = per-hook** `onUnavailable: strict | breaker`; breaker trips to fail-open with
+ alerting after N failures, then re-probes after cooldown (§3.3).
+5. **`onError` may reshape OR recover:** a trust-gated, audited hook can substitute a safe response for
+ a preCall-reject / moderation-block / call-failure; otherwise the error surfaces (a block is a
+ `ContentFiltered` `LlmError`). Recovery bypasses `postCallSuccess` and is tagged hook-originated
+ (§1 / §6).
+6. **Content exposure = need-based + trust-gated** (§6): content only to lifecycle points that need it,
+ gated by `trust_level`, audit-logged.
+7. **Aux/compaction lane** runs only built-in `token-trim` + observability — no guardrail/PII on
+ internal summarization calls (§1.4).
+8. **Protocol auth = short-lived RS256 token + NetworkPolicy** (ingress-from-mcp-host-only); no mTLS
+ (§3.2).
+9. **Registry entry type** `entry_type: 'llm_hook'` + `hook_meta` is added in **PR0** (§7).
+
+**Risks / out of scope:**
+- **Streaming** is out of scope for the initial version (single-shot lane); `postCall`/`onError` take a
+ full response, so a future `postCallStreaming` chunk hook slots onto the same interface.
+- **Latency:** each remote hook is a round-trip; mitigated by parallel moderation, in-process
+ built-ins, per-hook timeout, and `appliesTo` scoping.
+- **Protocol versioning:** the `/v1` prefix; a CRD's `lifecyclePoints` must match what the image serves
+ (declared in `hook_meta`, probed at install).
+
+## 9 · Verification
+1. **HookedLlmPort unit tests** (mock inner + fake hooks): preCall order/mutation; a preCall reject, a
+ moderation block, and a call failure all route to the onError chain; parallel moderation fail aborts
+ the call; postCall reverse fold; onError **reshape** and **recover** (recover short-circuits, skips
+ remaining onError + postCall, returns the substitute response); per-hook timeout + `failMode`; empty
+ chain = pass-through.
+2. **Built-in tests:** `token-trim` brings an over-budget message set under budget via the real token
+ counter; `prompt-shaping` forces params + injects a system part.
+3. **RemoteLlmHook tests** (mock hook server): each `/v1` endpoint mapped correctly; reject/4xx →
+ `LlmError`; patch application; timeout → `failMode`.
+4. **CRD/reconciler tests:** HCC materializes Deployment+Service+NetworkPolicy; ingress-from-mcp-host
+ only; egress per `egressBindings`; capability floor.
+5. **Install saga tests** (mock registry): digest mismatch rejects; credential Secret created; CRD
+ stamped with catalog-id; rollback on failure; installed-state reflects the hook.
+6. **Integration:** install a reference `pii-redact` hook from a mock registry → it appears installed
+ → a reasoning turn's response is redacted by the remote hook, fired once across a failover.
+7. **Recovery gating:** an `on_error` `recover` from a below-bar `trust_level` hook is refused (the
+ error surfaces); an allowed recovery returns the substitute response, bypasses `postCallSuccess`,
+ and is tagged hook-originated in telemetry + audit-logged.
+8. Confirm no LLM secret ever appears in a hook request body or hook logs.
diff --git a/docs/features/mcp-host-guardrails/legacy/mcp-host-guardrails-unified-architecture.md b/docs/features/mcp-host-guardrails/legacy/mcp-host-guardrails-unified-architecture.md
new file mode 100644
index 000000000..c7db9d7ac
--- /dev/null
+++ b/docs/features/mcp-host-guardrails/legacy/mcp-host-guardrails-unified-architecture.md
@@ -0,0 +1,157 @@
+# Spec · MCP Host Guardrails — Unified Architecture (umbrella)
+
+| | |
+|---|---|
+| **Type** | architecture / umbrella spec — decomposes into the suite in §2 |
+| **Status** | draft for discussion |
+| **Combines** | *(DRAFT) MCP Host Guardrails — Permission Rules, Hooks & Admin Policy* (tool lane) + [`llm-hooks-spec.md`](./llm-hooks-spec.md) (LLM lane) |
+| **Companion** | [`guardrails-vs-llm-hooks-comparison.md`](./guardrails-vs-llm-hooks-comparison.md) — the agree / emphasize / disagree analysis this design resolves |
+
+---
+
+## 0 · Thesis
+
+The two specs are the same machine on two lanes: **intercept a call → run an ordered chain of policy
+contributors → aggregate to a decision → execute at-most-once → emit bounded audit.** They differ in
+*what* they intercept (an LLM completion vs a resolved tool call) and in the *trust model of their
+hooks* (remote/marketplace vs local/digest-verified).
+
+So the combination is **not** one merged document. It is:
+
+1. a **shared guardrail spine** (the common decision/policy/audit machine),
+2. **two lane adapters** (the two existing specs, re-homed on that spine), and
+3. a **shared hook trust & delivery substrate** that makes the two hook models coexist as explicit tiers.
+
+Everything the two specs *agree* on (comparison §2) becomes the spine; everything they *disagree* on
+(comparison §5) is resolved once, at the spine (§3 below).
+
+---
+
+## 1 · The unifying abstraction — one `GuardrailBoundary`
+
+Define the boundary once; each lane instantiates it over its own call/result types.
+
+| Stage | Shared contract | LLM lane (`llm-hooks`) | Tool lane (Guardrails) |
+|---|---|---|---|
+| **Intercept** | a call reaches a mandatory boundary (G1) | `LlmPort.completeWithTools` (`HookedLlmPort`) | resolved tool call before execution |
+| **Context** | identity + resolved target + original/effective input | model, `usageContext` | resolved tool, provenance, args |
+| **Contributors** | ordered chain of *rules* + *hooks* + *validators*, each emitting a decision | moderation, prompt-shaping, token-trim, PII hooks | permission rules, Pre hooks, hard validators |
+| **Decision** | `allow / ask / deny / no_decision`, strict aggregation `deny > ask > allow > no_decision` | reject→`deny`, moderation-fail→`deny`, continue→`allow` | as authored |
+| **Rewrite** | full input replacement, canonicalize + **revalidate** (G7) | `pre_call` `patch` | Pre-hook `updatedInput` |
+| **Approve** | if `ask`: exact-call resolver, else fail-closed | (usually N/A — see §6) | `force_ask` snapshot/resume |
+| **Execute** | **at-most-once**, snapshot-safe across resume (G11/G12) | one completion per logical request (above failover) | `executeSingleTool`, batch/resume |
+| **Post** | transform the *model-visible* result; never alter the authoritative outcome | `post_call_success`; `on_error` recover (gated, §3) | `PostToolUse` |
+| **Evidence** | bounded-enum metrics + redacted, digest-based audit (G15) | §6 audit | §13 audit |
+
+A **contributor** is the shared unit: `{ phase: pre|post, source: admin_rule|host_rule|hook|validator,
+decision, reasonCode, rewrite?, capabilities? }`. Rules are declarative contributors; hooks are executable
+contributors. The lane supplies the input/result types; the spine supplies the algebra.
+
+---
+
+## 2 · Spec suite (thinking in multiple specs)
+
+| Spec | Owns | Sourced from |
+|---|---|---|
+| **S0 — this doc** | the umbrella: shared abstraction, reconciliation, spec map, migration | new |
+| **S1 — Guardrail Core** | decision algebra + strict aggregation, the contributor contract, at-most-once + snapshot/resume, admin-policy model + **HCC atomic-artifact delivery**, bounded metrics/audit, reason-code registry | shared parts of both (Guardrails §3–6, §10, §11, §13; llm-hooks §1.2–1.3, §6) |
+| **S2 — Tool-lane adapter** | permission **rules** + typed argument predicates, provenance, `Pre/PostToolUse`, approvals/`force_ask`, doom-loop, persistence/scanner hardening | the colleague's spec, re-homed |
+| **S3 — LLM-lane adapter** | `pre_call`/`moderation`/`post_call`/`on_error`, built-ins (`prompt-shaping`/`token-trim`/PII), `HookedLlmPort` placement above failover | `llm-hooks-spec.md`, re-homed |
+| **S4 — Hook trust & delivery substrate** | the **two hook tiers** (§3.1), digest/allowlist verification (Tier A), marketplace registry + `install` saga + image-allowlist + `trust_level` (Tier B), egress policy, credential isolation | Guardrails §9 + llm-hooks §3/§5, unified |
+
+S1 and S4 are the new work; S2 and S3 are the existing specs demoted to **adapters** that conform to S1
+and consume S4. Neither existing doc is thrown away — each keeps its lane-specific depth.
+
+---
+
+## 3 · Reconciling the disagreements (resolved at the spine)
+
+The comparison's §5 conflicts, decided once:
+
+| Disagreement | Unified resolution | Why it holds |
+|---|---|---|
+| **Where a hook runs** (local vs remote) | Not either/or — **two tiers** (§3.1). A hook declares its tier; the spine + admin policy decide which tiers a given lane/Context may use. | A deterministic tool check and a network moderation call are both legitimate; the tier makes the trust rules explicit rather than global. |
+| **Network & side-effects** | Derived from tier: **Tier A = no network / deterministic**; **Tier B = network-permitted, egress-allowlisted**. | Preserves the colleague's determinism guarantee where it matters and our vendor-call capability where it's needed. |
+| **Who authors/installs** | **Admin policy governs both tiers.** Tier A = admin-allowlisted digests. Tier B = marketplace install that must satisfy a Context allowlist + `trust_level` floor. | Adopts his non-overridable Context authority as the single governance model for both. |
+| **When a hook is down** | **Fail-closed is the default and is mandatory for any decision-authoritative (deny-capable) hook.** A `breaker`/fail-open is permitted **only** for non-authoritative (advisory/observability) hooks and **only** when admin policy opts in. | Keeps his strict posture for anything that can block; allows our availability trade-off exactly where it's safe. |
+| **May a hook fabricate the outcome?** | Recovery/substitution is a **named capability** (`may_substitute_result`) an admin must grant; the substitute is **clearly hook-originated + audited** and **never alters the stored authoritative outcome** (his G12 holds). | Our `on_error recover` survives, but as a gated, auditable exception rather than a default power. |
+| **Decision expressiveness** | Adopt the **4-valued algebra + strict aggregation for both lanes**. The LLM lane gains `ask`/`no_decision` (used rarely — §6). | One decision model; the LLM lane's simpler cases are just the subset it uses. |
+| **Config authority** | The **non-overridable Context admin policy** governs rules, allowed hook tiers, allowed hook digests/entries, allowed approval policies, and limits — for **both** lanes. | Single governance surface; marketplace installs and local hooks both bind to it. |
+
+### 3.1 · The tiered hook model (the load-bearing move)
+
+| | **Tier A — trusted local** | **Tier B — remote / marketplace** |
+|---|---|---|
+| Runs as | least-privilege child process in the workload | own pod / in-cluster Service / external endpoint |
+| Network | none (deterministic transform) | permitted, egress-allowlisted |
+| Trust | admin-allowlisted, digest-pinned | image-allowlist + sha256 digest + `trust_level` |
+| Author | first-party / operator-vetted | third-party marketplace |
+| Fail-mode | fail-closed (may be deny-authoritative) | fail-closed if deny-authoritative; `breaker` only if advisory + admin-opted-in |
+| Typical use | tool-lane permission checks, high-assurance guardrails | LLM moderation/PII that call vendor services |
+
+**Rule:** admin policy declares, per Context and per lane, which tiers are admissible and which
+capabilities (`may_deny`, `may_rewrite`, `may_substitute_result`) each hook is granted. A lane can require
+Tier A for anything decision-authoritative and allow Tier B only for advisory contributions — which is
+exactly how the two specs' instincts differ, now expressible instead of contradictory.
+
+---
+
+## 4 · How the existing specs slot in (no rework of their depth)
+
+- **Tool lane (S2)** already speaks the spine's language: its `allow/ask/deny/no_decision`, strict
+ aggregation, `Pre/PostToolUse`, at-most-once/resume, and admin policy **are** the spine's canonical
+ forms. It contributes almost all of S1. Its hooks are **Tier A**.
+- **LLM lane (S3)** maps on cleanly: `pre_call`→pre contributor (rewrite/deny), `moderation`→pre
+ contributor (deny/ask), `post_call_success`→post contributor, `on_error recover`→post with
+ `may_substitute_result`, `token-trim`/`prompt-shaping`→rewrite contributors. Its remote hooks are
+ **Tier B**; its built-ins are in-process **Tier A**-equivalent (first-party, no network).
+
+Net: the tool-lane spec is ~the spine already; the LLM-lane spec is the same machine specialized to the
+model call plus the Tier-B substrate.
+
+---
+
+## 5 · Sequencing / migration
+
+1. **S1 — Guardrail Core** first: lift the decision algebra, contributor contract, at-most-once/resume,
+ admin-policy model, and audit/metrics out of the tool-lane spec into a lane-neutral core.
+2. **S4 — Trust substrate**: define Tier A (local digest-verified execution) + Tier B (marketplace/remote)
+ and the admin-policy tier/capability grants.
+3. **S2 / S3 — adapters**: re-home each existing spec as an adapter that *conforms to* S1 and *consumes*
+ S4. Most of their text is unchanged; the delta is pointing shared concepts at S1/S4 instead of
+ redefining them.
+4. Both existing docs get a one-line header: "Lane adapter of the unified guardrail architecture (S0);
+ shared model in S1, trust substrate in S4."
+
+No production code, CRD, or deployment change is authorized by this document (consistent with both
+source specs); this is a specification decomposition.
+
+---
+
+## 6 · Open decisions for the authors
+
+Genuine forks the unification surfaces — worth an explicit call before S1 is written:
+
+1. **Does the LLM lane need `ask` (human approval before a model call)?** Likely rare (cost/risk gating on
+ an expensive model, or a jailbreak-suspected turn). If never needed, the LLM adapter uses only
+ `allow`/`deny`/`no_decision` and `ask` is a tool-lane-only feature of the shared algebra.
+2. **May tool-lane guardrails ever be Tier B (remote)?** The colleague's spec says local-only. Holding
+ that line is safest; allowing a remote tool guardrail (strongly gated) would let teams reuse a shared
+ policy service across lanes. Decide whether Tier B is admissible on the tool lane at all.
+3. **Is `may_substitute_result` allowed on the tool lane** (substitute a tool result), or LLM-only?
+ His model forbids altering a tool outcome; keeping substitution LLM-only preserves that.
+4. **Where does Guardrail Core live** — an in-process mcp-host library, or a shared module both the tool
+ and LLM lanes import? (Both lanes already run inside mcp-host, so a shared library is the likely form.)
+5. **Unify the reason-code registries** into one enum, or keep per-lane registries that share a bounded-label
+ discipline? A single registry eases cross-lane dashboards.
+6. **Capability granularity** — is `{may_deny, may_rewrite, may_substitute_result}` the right minimal set,
+ or do we also need `may_ask` and `may_add_context` as separately grantable?
+
+---
+
+## 7 · Explicitly out of scope (stays lane-specific)
+
+The spine must **not** absorb lane mechanics that don't generalize: the tool lane's typed argument
+predicates (`path`/`url`/`command`/`json`), provenance-from-registry, doom-loop guard, and persistence
+scanner; and the LLM lane's `token-trim`/`prompt-shaping` built-ins, model-context projection, and
+`HookedLlmPort` placement above failover. These live in S2/S3, not S1.