Skip to content

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

TypeScript

fix(mcp-host): align tool-lane hooks with LLM-lane guards and scope hooks to Host phases

Jose Gabriel Ramirez Encinasf3371e355dfc
diff --git a/mcp-host/package-lock.json b/mcp-host/package-lock.json
index d589c42bd..1928bc87d 100644
--- a/mcp-host/package-lock.json
+++ b/mcp-host/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "clerum-mcp-host",
- "version": "0.1.556",
+ "version": "0.1.557",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "clerum-mcp-host",
- "version": "0.1.556",
+ "version": "0.1.557",
"license": "SEE LICENSE IN LICENSE",
"dependencies": {
"@anthropic-ai/sdk": "^0.32.0",
diff --git a/mcp-host/package.json b/mcp-host/package.json
index 4ea1e8ea3..2e9f5111a 100644
--- a/mcp-host/package.json
+++ b/mcp-host/package.json
@@ -1,6 +1,6 @@
{
"name": "clerum-mcp-host",
- "version": "0.1.556",
+ "version": "0.1.557",
"description": "MCP Host - reads Host CRD and provides LLM access via OpenAI/Claude",
"main": "dist/main.js",
"engines": {
diff --git a/mcp-host/src/__tests__/guardrailHookResolver.test.ts b/mcp-host/src/__tests__/guardrailHookResolver.test.ts
index 581e0f710..fe565bfa0 100644
--- a/mcp-host/src/__tests__/guardrailHookResolver.test.ts
+++ b/mcp-host/src/__tests__/guardrailHookResolver.test.ts
@@ -202,6 +202,49 @@ describe('resolveGuardrailHookDescriptors', () => {
})
})
+describe('resolveGuardrailHookDescriptors — Host phase scoping', () => {
+ const multiPoint: LlmHookCR = {
+ spec: {
+ target: { service: { name: 's', namespace: NS, port: 80 } },
+ lifecyclePoints: ['preCall', 'moderate', 'preToolUse'],
+ capabilities: ['may_deny'],
+ },
+ }
+
+ it('runs a hook only at the phases the Host references it under', async () => {
+ const out = await resolveGuardrailHookDescriptors(
+ guardrails({ moderate: [{ id: 'mp' }] }),
+ deps({ mp: multiPoint })
+ )
+ expect(out).toHaveLength(1)
+ expect(out[0].lifecyclePoints).toEqual(['moderate'])
+ })
+
+ it('unions the phases across Host keys, keeping CR declaration order', async () => {
+ const out = await resolveGuardrailHookDescriptors(
+ guardrails({ preToolUse: [{ id: 'mp' }], preCall: [{ id: 'mp' }] }),
+ deps({ mp: multiPoint })
+ )
+ expect(out[0].lifecyclePoints).toEqual(['pre_call', 'pre_tool_use'])
+ })
+
+ it('ignores a Host phase the hook does not declare', async () => {
+ const out = await resolveGuardrailHookDescriptors(
+ guardrails({ moderate: [{ id: 'mp' }], postToolUse: [{ id: 'mp' }] }),
+ deps({ mp: multiPoint })
+ )
+ expect(out[0].lifecyclePoints).toEqual(['moderate'])
+ })
+
+ it('skips a hook whose Host phases do not overlap its lifecyclePoints', async () => {
+ const out = await resolveGuardrailHookDescriptors(
+ guardrails({ postToolUse: [{ id: 'mp' }], onError: [{ id: 'mp' }] }),
+ deps({ mp: multiPoint })
+ )
+ expect(out).toHaveLength(0)
+ })
+})
+
describe('withResolvedHookDescriptors', () => {
it('merges resolved descriptors while preserving inline descriptors and other blocks', () => {
const inline = {
diff --git a/mcp-host/src/core/guardrails/hooks/__tests__/remoteToolHook.test.ts b/mcp-host/src/core/guardrails/hooks/__tests__/remoteToolHook.test.ts
index a98ea7d8b..cedb49d88 100644
--- a/mcp-host/src/core/guardrails/hooks/__tests__/remoteToolHook.test.ts
+++ b/mcp-host/src/core/guardrails/hooks/__tests__/remoteToolHook.test.ts
@@ -4,6 +4,7 @@
*/
import { describe, expect, it } from 'vitest'
import type { ToolIdentity } from '../../tool/provenance'
+import { HookBreakerRegistry } from '../hookBreaker'
import { RemoteToolHook } from '../remoteToolHook'
import type { HookDescriptor, HookFetcher, HookHttpResult } from '../types'
@@ -147,3 +148,149 @@ describe('RemoteToolHook.postToolUse', () => {
expect(await h.postToolUse(id, {}, result)).toBeNull()
})
})
+
+/** A fetcher that counts its dials and returns whatever `getResult` yields. */
+function countingFetcher(getResult: () => HookHttpResult) {
+ let calls = 0
+ const fetch: HookFetcher = async () => {
+ calls += 1
+ return getResult()
+ }
+ return { fetch, calls: () => calls }
+}
+
+const ok: HookHttpResult = { status: 200, body: {}, unavailable: false }
+const unavailable: HookHttpResult = { status: 0, body: undefined, unavailable: true }
+const toolResult = { content: 'secret=abc123', isError: false }
+
+describe('quarantine (§8.2) — tool lane matches the LLM lane', () => {
+ it('quarantined may_deny + fail-closed pre_tool_use → deny hook_unavailable, never dialed', async () => {
+ const cf = countingFetcher(() => ok)
+ const h = new RemoteToolHook(
+ desc({ capabilities: ['may_deny'], failMode: 'closed', quarantined: true }),
+ cf.fetch
+ )
+ const c = await h.preToolUse(id, {})
+ expect(c?.decision).toBe('deny')
+ expect(c?.reasonCode).toBe('hook_unavailable')
+ expect(cf.calls()).toBe(0)
+ })
+
+ it('quarantined advisory pre_tool_use → no contribution, never dialed', async () => {
+ const cf = countingFetcher(() => ({
+ status: 200,
+ body: { updatedInput: { command: ['ls'] } },
+ unavailable: false,
+ }))
+ const h = new RemoteToolHook(
+ desc({ capabilities: ['may_rewrite'], failMode: 'open', quarantined: true }),
+ cf.fetch
+ )
+ expect(await h.preToolUse(id, { command: ['pwd'] })).toBeNull()
+ expect(cf.calls()).toBe(0)
+ })
+
+ it('quarantined fail-closed post_tool_use redactor → withholds content, never dialed', async () => {
+ const cf = countingFetcher(() => ok)
+ const h = new RemoteToolHook(
+ desc({
+ lifecyclePoints: ['post_tool_use'],
+ capabilities: ['may_rewrite'],
+ failMode: 'closed',
+ quarantined: true,
+ }),
+ cf.fetch
+ )
+ const v = await h.postToolUse(id, {}, toolResult)
+ expect(v?.content).not.toContain('abc123')
+ expect(v?.isError).toBe(false)
+ expect(cf.calls()).toBe(0)
+ })
+
+ it('quarantined fail-open post_tool_use → no change, never dialed', async () => {
+ const cf = countingFetcher(() => ({
+ status: 200,
+ body: { updatedResult: { content: 'x' } },
+ unavailable: false,
+ }))
+ const h = new RemoteToolHook(
+ desc({
+ lifecyclePoints: ['post_tool_use'],
+ capabilities: ['may_rewrite'],
+ failMode: 'open',
+ quarantined: true,
+ }),
+ cf.fetch
+ )
+ expect(await h.postToolUse(id, {}, toolResult)).toBeNull()
+ expect(cf.calls()).toBe(0)
+ })
+})
+
+describe('circuit breaker (§8.6) — tool lane', () => {
+ const advisory = (over: Partial<HookDescriptor> = {}): HookDescriptor =>
+ desc({
+ capabilities: ['may_rewrite'],
+ failMode: 'open',
+ lifecyclePoints: ['pre_tool_use', 'post_tool_use'],
+ onUnavailable: { mode: 'breaker', failureThreshold: 2, cooldownMs: 1000 },
+ ...over,
+ })
+
+ it('advisory breaker-mode hook trips and stops dialing during cooldown', async () => {
+ const reg = new HookBreakerRegistry()
+ const cf = countingFetcher(() => unavailable)
+ const h = new RemoteToolHook(advisory(), cf.fetch, reg, () => 0)
+ expect(await h.preToolUse(id, {})).toBeNull()
+ expect(await h.postToolUse(id, {}, toolResult)).toBeNull()
+ expect(cf.calls()).toBe(2) // tripped
+ expect(await h.preToolUse(id, {})).toBeNull()
+ expect(await h.postToolUse(id, {}, toolResult)).toBeNull()
+ expect(cf.calls()).toBe(2) // short-circuited
+ })
+
+ it('re-probes after cooldown and closes on success', async () => {
+ const reg = new HookBreakerRegistry()
+ let t = 0
+ let healthy = false
+ const cf = countingFetcher(() => (healthy ? ok : unavailable))
+ const h = new RemoteToolHook(advisory(), cf.fetch, reg, () => t)
+ await h.preToolUse(id, {})
+ await h.preToolUse(id, {})
+ await h.preToolUse(id, {}) // open → no dial
+ expect(cf.calls()).toBe(2)
+ t = 1000
+ healthy = true
+ await h.preToolUse(id, {})
+ await h.preToolUse(id, {})
+ expect(cf.calls()).toBe(4)
+ })
+
+ it('may_deny hook ignores breaker mode — always dials and fails closed', async () => {
+ const reg = new HookBreakerRegistry()
+ const cf = countingFetcher(() => unavailable)
+ const h = new RemoteToolHook(
+ advisory({ capabilities: ['may_deny'], failMode: 'closed' }),
+ cf.fetch,
+ reg,
+ () => 0
+ )
+ for (let i = 0; i < 5; i++) {
+ expect((await h.preToolUse(id, {}))?.decision).toBe('deny')
+ }
+ expect(cf.calls()).toBe(5)
+ })
+
+ it('strict mode never trips', async () => {
+ const reg = new HookBreakerRegistry()
+ const cf = countingFetcher(() => unavailable)
+ const h = new RemoteToolHook(
+ advisory({ onUnavailable: { mode: 'strict', failureThreshold: 2, cooldownMs: 1000 } }),
+ cf.fetch,
+ reg,
+ () => 0
+ )
+ for (let i = 0; i < 5; i++) await h.preToolUse(id, {})
+ expect(cf.calls()).toBe(5)
+ })
+})
diff --git a/mcp-host/src/core/guardrails/hooks/guardedFetch.ts b/mcp-host/src/core/guardrails/hooks/guardedFetch.ts
new file mode 100644
index 000000000..58b889b11
--- /dev/null
+++ b/mcp-host/src/core/guardrails/hooks/guardedFetch.ts
@@ -0,0 +1,117 @@
+/**
+ * Guarded hook transport (spec §8.2 / §8.6), shared by the LLM lane
+ * (`RemoteLlmHook`) and the tool lane (`RemoteToolHook`) so both lanes apply the
+ * same quarantine gate, circuit breaker and hard deadline to every `/v1` dial.
+ *
+ * - Quarantine (§8.2): a quarantined hook (e.g. digest mismatch, DuplicatePath
+ * loser) never reaches the network — every call reports `unavailable`, so the
+ * calling point's §8.6 fail-posture applies (a `may_deny` fail-closed hook
+ * denies; an advisory hook contributes nothing).
+ * - Circuit breaker (§8.6): honored only for an advisory hook that opted into
+ * `breaker` mode. While tripped, calls short-circuit to `unavailable` WITHOUT
+ * dialing for the cooldown window. A deny-authoritative (`may_deny`) hook
+ * always dials strict so it can never be tripped into failing open.
+ * - Hard deadline: an absolute ceiling on every dial, independent of the
+ * transport's own timeout, so a dial that never settles still resolves to
+ * `unavailable` and the awaiting turn cannot hang.
+ *
+ * Every branch reports `unavailable` — never a silent allow.
+ */
+import { logger } from '../../../logger'
+import { type HookBreakerRegistry, defaultBreakerRegistry } from './hookBreaker'
+import type { HookDescriptor, HookFetcher, HookHttpResult } from './types'
+
+export interface GuardHookFetcherOptions {
+ descriptor: HookDescriptor
+ fetch: HookFetcher
+ /** Shared so a trip survives the per-task rebuild of hook instances (§8.6). */
+ breakers?: HookBreakerRegistry
+ /** Injectable clock for deterministic breaker tests. */
+ now?: () => number
+ /** Absolute per-dial ceiling; set well above the transport timeout. */
+ hardDeadlineMs?: number
+}
+
+export const DEFAULT_HOOK_HARD_DEADLINE_MS = 15000
+
+const UNAVAILABLE: HookHttpResult = { status: 0, body: undefined, unavailable: true }
+
+/** Identity of the breaker state (per hook pod+path), shared across tasks and lanes (§8.6). */
+export function hookBreakerKey(descriptor: HookDescriptor): string {
+ return `${descriptor.endpoint}${descriptor.path}`
+}
+
+/** The breaker is honored only for an advisory hook that opted into `breaker` mode (§8.6). */
+export function hookBreakerEngaged(descriptor: HookDescriptor): boolean {
+ return (
+ descriptor.onUnavailable?.mode === 'breaker' && !descriptor.capabilities.includes('may_deny')
+ )
+}
+
+/**
+ * Race the transport against an absolute deadline. Promise.race attaches a
+ * handler to the loser, so a late transport rejection is not an unhandled
+ * rejection.
+ */
+function withDeadline(
+ fetch: HookFetcher,
+ args: Parameters<HookFetcher>[0],
+ hardDeadlineMs: number
+): Promise<HookHttpResult> {
+ let timer: ReturnType<typeof setTimeout> | undefined
+ const deadline = new Promise<HookHttpResult>(resolve => {
+ timer = setTimeout(() => resolve(UNAVAILABLE), hardDeadlineMs)
+ // Don't let the backstop timer keep the event loop alive.
+ ;(timer as { unref?: () => void }).unref?.()
+ })
+ return Promise.race([fetch(args), deadline]).finally(() => {
+ if (timer) clearTimeout(timer)
+ })
+}
+
+/** Wrap a raw `HookFetcher` with the quarantine gate, §8.6 breaker and hard deadline. */
+export function guardHookFetcher(opts: GuardHookFetcherOptions): HookFetcher {
+ const { descriptor, fetch } = opts
+ const breakers = opts.breakers ?? defaultBreakerRegistry
+ const now = opts.now ?? (() => Date.now())
+ const hardDeadlineMs = opts.hardDeadlineMs ?? DEFAULT_HOOK_HARD_DEADLINE_MS
+ const key = hookBreakerKey(descriptor)
+
+ return async args => {
+ if (descriptor.quarantined) return UNAVAILABLE
+ const engaged = hookBreakerEngaged(descriptor)
+ // Breaker open: skip the dial (and its timeout); report unavailable.
+ if (engaged && breakers.isOpen(key, now())) return UNAVAILABLE
+
+ const res = await withDeadline(fetch, args, hardDeadlineMs)
+ if (engaged) {
+ const policy = descriptor.onUnavailable!
+ // "Response too big" (oversized) is NOT a hook-down failure — leave breaker
+ // state unchanged so small payloads that fit are still dialed. Only a real
+ // transport failure counts, and a reachable response resets it.
+ if (res.oversized) {
+ // no-op on breaker state
+ } else if (res.unavailable) {
+ const tripped = breakers.recordFailure(
+ key,
+ policy.failureThreshold,
+ policy.cooldownMs,
+ now()
+ )
+ if (tripped) {
+ logger.warn(
+ {
+ hookId: descriptor.id,
+ failureThreshold: policy.failureThreshold,
+ cooldownMs: policy.cooldownMs,
+ },
+ '[Guardrails] hook breaker tripped; failing open for cooldown'
+ )
+ }
+ } else {
+ breakers.recordSuccess(key)
+ }
+ }
+ return res
+ }
+}
diff --git a/mcp-host/src/core/guardrails/hooks/remoteLlmHook.ts b/mcp-host/src/core/guardrails/hooks/remoteLlmHook.ts
index d73071df5..53de50fe0 100644
--- a/mcp-host/src/core/guardrails/hooks/remoteLlmHook.ts
+++ b/mcp-host/src/core/guardrails/hooks/remoteLlmHook.ts
@@ -26,6 +26,7 @@ import type {
ToolCompletionResponse,
} from '../../types'
import type { Capability, Contributor } from '../types'
+import { DEFAULT_HOOK_HARD_DEADLINE_MS, guardHookFetcher } from './guardedFetch'
import { type HookBreakerRegistry, defaultBreakerRegistry } from './hookBreaker'
import { projectForHook } from './hookProjection'
import type { HookDescriptor, HookFetcher, HookHttpResult, LifecyclePoint } from './types'
@@ -71,11 +72,11 @@ function filteredPostResponse(usage: ToolCompletionResponse['usage']): ToolCompl
export class RemoteLlmHook {
constructor(
private readonly descriptor: HookDescriptor,
- private readonly fetch: HookFetcher,
+ fetch: HookFetcher,
/** Shared so a trip survives the per-task rebuild of this instance (§8.6). */
- private readonly breakers: HookBreakerRegistry = defaultBreakerRegistry,
+ breakers: HookBreakerRegistry = defaultBreakerRegistry,
/** Injectable clock for deterministic breaker tests. */
- private readonly now: () => number = () => Date.now(),
+ now: () => number = () => Date.now(),
/**
* Belt-and-braces hard deadline (§8.6): an ABSOLUTE ceiling on every hook
* dial, independent of the transport's own timeout. If the transport ever
@@ -84,8 +85,12 @@ export class RemoteLlmHook {
* so the §8.6 fail-posture always applies and the await can never hang. Set
* well above the transport timeout so normal timeouts settle there first.
*/
- private readonly hardDeadlineMs: number = 15000
- ) {}
+ hardDeadlineMs: number = DEFAULT_HOOK_HARD_DEADLINE_MS
+ ) {
+ this.guarded = guardHookFetcher({ descriptor, fetch, breakers, now, hardDeadlineMs })
+ }
+
+ private readonly guarded: HookFetcher
/** Stable hook id (the descriptor's id) — for diagnostics/logging only. */
get id(): string {
@@ -96,95 +101,17 @@ export class RemoteLlmHook {
return this.descriptor.capabilities.includes(cap)
}
- /** Identity of the breaker state (per hook pod+path), shared across tasks (§8.6). */
- private breakerKey(): string {
- return `${this.descriptor.endpoint}${this.descriptor.path}`
- }
-
- /**
- * The circuit breaker is honored only for an advisory hook that opted into
- * `breaker` mode (§8.6): a deny-authoritative (`may_deny`) hook always dials
- * strict so it can never be tripped into failing open.
- */
- private breakerEngaged(): boolean {
- return this.descriptor.onUnavailable?.mode === 'breaker' && !this.has('may_deny')
- }
-
/**
- * Transport with the quarantine gate (§8.2) and the §8.6 circuit breaker.
- *
- * A quarantined hook (e.g. digest mismatch) never reaches the network — every
- * call reports `unavailable`, so each point's §8.6 fail-posture applies. When a
- * `breaker`-mode advisory hook has tripped, calls likewise short-circuit to
- * `unavailable` WITHOUT dialing for the cooldown window, so a down hook is not
- * re-dialed (and re-timed-out) on every request. Every branch reports
- * `unavailable` — never a silent allow.
+ * Transport with the quarantine gate (§8.2), the §8.6 circuit breaker and the
+ * hard deadline — shared with the tool lane (`guardHookFetcher`). Every
+ * short-circuit reports `unavailable`, so each point's fail-posture applies.
*/
- private async fetchGuarded(args: {
+ private fetchGuarded(args: {
point: LifecyclePoint
descriptor: HookDescriptor
body: unknown
}): Promise<HookHttpResult> {
- if (this.descriptor.quarantined) {
- return { status: 0, body: undefined, unavailable: true }
- }
- const engaged = this.breakerEngaged()
- if (engaged && this.breakers.isOpen(this.breakerKey(), this.now())) {
- // Breaker open: skip the dial (and its timeout); report unavailable.
- return { status: 0, body: undefined, unavailable: true }
- }
- const res = await this.fetchWithDeadline(args)
- if (engaged) {
- const policy = this.descriptor.onUnavailable!
- // "Response too big" (oversized) is NOT a hook-down failure — it must not
- // trip the breaker (which would then skip small payloads that would fit).
- // Leave breaker state unchanged for oversized; only a real transport failure
- // counts, and a reachable response resets it.
- if (res.oversized) {
- // no-op on breaker state
- } else if (res.unavailable) {
- const tripped = this.breakers.recordFailure(
- this.breakerKey(),
- policy.failureThreshold,
- policy.cooldownMs,
- this.now()
- )
- if (tripped) {
- console.warn(
- `[Guardrails] hook ${this.descriptor.id} breaker tripped after ${policy.failureThreshold} failures; ` +
- `failing open for ${policy.cooldownMs}ms`
- )
- }
- } else {
- this.breakers.recordSuccess(this.breakerKey())
- }
- }
- return res
- }
-
- /**
- * Race the transport against an absolute deadline so a dial that never settles
- * (buggy/unhonored transport timeout) still yields `unavailable` rather than
- * hanging the awaiting turn. Promise.race attaches a handler to the loser, so a
- * late transport rejection is not an unhandled rejection.
- */
- private fetchWithDeadline(args: {
- point: LifecyclePoint
- descriptor: HookDescriptor
- body: unknown
- }): Promise<HookHttpResult> {
- let timer: ReturnType<typeof setTimeout> | undefined
- const deadline = new Promise<HookHttpResult>(resolve => {
- timer = setTimeout(
- () => resolve({ status: 0, body: undefined, unavailable: true }),
- this.hardDeadlineMs
- )
- // Don't let the backstop timer keep the event loop alive.
- ;(timer as { unref?: () => void }).unref?.()
- })
- return Promise.race([this.fetch(args), deadline]).finally(() => {
- if (timer) clearTimeout(timer)
- })
+ return this.guarded(args)
}
private handles(point: LifecyclePoint): boolean {
diff --git a/mcp-host/src/core/guardrails/hooks/remoteToolHook.ts b/mcp-host/src/core/guardrails/hooks/remoteToolHook.ts
index c7762963f..b90371abd 100644
--- a/mcp-host/src/core/guardrails/hooks/remoteToolHook.ts
+++ b/mcp-host/src/core/guardrails/hooks/remoteToolHook.ts
@@ -7,11 +7,14 @@
*
* `pre_tool_use` request body = `{ tool, arguments }` (the resolved identity +
* args); response = `{ decision?, reasonCode?, updatedInput?, additionalContext? }`.
- * Phase 3 increment: PreToolUse; PostToolUse (post-execution result transform)
- * is a later increment.
+ * Every dial goes through the shared guarded transport (`guardHookFetcher`), so
+ * the tool lane honours quarantine (§8.2), the §8.6 circuit breaker and the hard
+ * deadline exactly like the LLM lane.
*/
import type { ToolIdentity } from '../tool/provenance'
import type { Capability, Contributor } from '../types'
+import { DEFAULT_HOOK_HARD_DEADLINE_MS, guardHookFetcher } from './guardedFetch'
+import { type HookBreakerRegistry, defaultBreakerRegistry } from './hookBreaker'
import type { HookDescriptor, HookFetcher } from './types'
type ToolContributor = Contributor<Record<string, unknown>, string>
@@ -27,10 +30,19 @@ function isRecord(v: unknown): v is Record<string, unknown> {
}
export class RemoteToolHook {
+ private readonly fetch: HookFetcher
+
constructor(
private readonly descriptor: HookDescriptor,
- private readonly fetch: HookFetcher
- ) {}
+ fetch: HookFetcher,
+ /** Shared with the LLM lane so a trip is per-hook, not per-lane (§8.6). */
+ breakers: HookBreakerRegistry = defaultBreakerRegistry,
+ /** Injectable clock for deterministic breaker tests. */
+ now: () => number = () => Date.now(),
+ hardDeadlineMs: number = DEFAULT_HOOK_HARD_DEADLINE_MS
+ ) {
+ this.fetch = guardHookFetcher({ descriptor, fetch, breakers, now, hardDeadlineMs })
+ }
private has(cap: Capability): boolean {
return this.descriptor.capabilities.includes(cap)
diff --git a/mcp-host/src/guardrailHookResolver.ts b/mcp-host/src/guardrailHookResolver.ts
index 6a5e09807..9c7705214 100644
--- a/mcp-host/src/guardrailHookResolver.ts
+++ b/mcp-host/src/guardrailHookResolver.ts
@@ -8,7 +8,11 @@
* - endpoint — image target: the digest-dedup Service DNS the controller
* deploys (`llmhook-<podKey>.<ns>.svc`); service target: the
* referenced Service DNS; remote target: the external baseUrl.
- * - path / lifecyclePoints / capabilities / failMode / order from the CR spec.
+ * - path / capabilities / failMode / order from the CR spec.
+ * - lifecyclePoints — the INTERSECTION of the CR's declared points and the
+ * Host phase keys the hook is referenced under, so a hook runs
+ * only where the Host admin placed it (removing it from one
+ * phase stops it there even if the CR still declares it).
*
* The pod-key derivation MUST byte-match host-context-controller's
* `computePodKey` (llmHookReconciler.ts) or the Service DNS won't resolve.
@@ -20,6 +24,7 @@ import type { GuardrailsConfig } from './core/guardrails/config'
import type { HookDescriptor, LifecyclePoint } from './core/guardrails/hooks/types'
import type { Capability } from './core/guardrails/types'
import type { LlmHookCR } from './k8sClient'
+import { logger } from './logger'
/** Host phase key (CRD/Host naming) → engine lifecycle point. */
const PHASE_TO_POINT: Record<string, LifecyclePoint> = {
@@ -50,16 +55,34 @@ export interface ResolveHookDeps {
llmHooksNamespace: string
}
-/** Unique referenced hook ids (across all phases) → the first digest seen for each. */
-function collectRefs(guardrails: GuardrailsConfig | undefined): Map<string, string | undefined> {
- const out = new Map<string, string | undefined>()
+interface CollectedRef {
+ /** First digest seen for this id across phases. */
+ digest: string | undefined
+ /** Engine lifecycle points this id is referenced under on the Host. */
+ points: Set<LifecyclePoint>
+}
+
+/**
+ * Unique referenced hook ids (across all phases) → the first digest seen for
+ * each, plus the set of Host phases (as engine points) the id appears under.
+ * Unknown phase keys contribute no point.
+ */
+function collectRefs(guardrails: GuardrailsConfig | undefined): Map<string, CollectedRef> {
+ const out = new Map<string, CollectedRef>()
const hooks = guardrails?.hooks as Record<string, unknown> | undefined
if (!hooks) return out
for (const phase of Object.keys(hooks)) {
const refs = hooks[phase]
if (!Array.isArray(refs)) continue
+ const point = PHASE_TO_POINT[phase] as LifecyclePoint | undefined
for (const r of refs as HookRef[]) {
- if (r && typeof r.id === 'string' && !out.has(r.id)) out.set(r.id, r.digest)
+ if (!r || typeof r.id !== 'string') continue
+ let entry = out.get(r.id)
+ if (!entry) {
+ entry = { digest: r.digest, points: new Set() }
+ out.set(r.id, entry)
+ }
+ if (point) entry.points.add(point)
}
}
return out
@@ -147,27 +170,45 @@ export async function resolveGuardrailHookDescriptors(
const refs = collectRefs(guardrails)
const out: HookDescriptor[] = []
- for (const [id, refDigest] of refs) {
+ for (const [id, ref] of refs) {
+ const refDigest = ref.digest
let cr: LlmHookCR | null
try {
cr = await deps.getLlmHook(id)
} catch (err) {
- console.error(`[Guardrails] failed reading LlmHook ${id}:`, err)
+ logger.error(
+ { hookId: id, error: err instanceof Error ? err.message : String(err) },
+ '[Guardrails] failed reading LlmHook'
+ )
continue
}
if (!cr) continue // dangling reference → skip
const ep = endpointFor(cr, deps.llmHooksNamespace)
if (!ep) {
- console.warn(`[Guardrails] LlmHook ${id} has no resolvable target; skipping`)
+ logger.warn({ hookId: id }, '[Guardrails] LlmHook has no resolvable target; skipping')
continue
}
- const points = (cr.spec?.lifecyclePoints ?? [])
+ const declared = (cr.spec?.lifecyclePoints ?? [])
.map(p => PHASE_TO_POINT[p])
.filter((p): p is LifecyclePoint => !!p)
+ if (declared.length === 0) {
+ logger.warn(
+ { hookId: id },
+ '[Guardrails] LlmHook declares no known lifecycle points; skipping'
+ )
+ continue
+ }
+ // Run the hook only at the phases the Host references it under (§8.2): the
+ // Host phase key is the admin's placement, the CR's points are what the hook
+ // supports. A Host phase the hook does not declare is ignored.
+ const points = declared.filter(p => ref.points.has(p))
if (points.length === 0) {
- console.warn(`[Guardrails] LlmHook ${id} declares no known lifecycle points; skipping`)
+ logger.warn(
+ { hookId: id, declared, referenced: [...ref.points] },
+ '[Guardrails] LlmHook is not referenced under any phase it declares; skipping'
+ )
continue
}
@@ -222,13 +263,15 @@ export async function resolveGuardrailHookDescriptors(
const duplicatePathLoser = isDuplicatePathLoser(cr)
const quarantined = digestMismatch || duplicatePathLoser
if (digestMismatch) {
- console.warn(
- `[Guardrails] LlmHook ${id} digest mismatch (ref=${refDigest} observed=${cr.status?.observedDigest}); quarantining (fail-closed for may_deny)`
+ logger.warn(
+ { hookId: id, refDigest, observedDigest: cr.status?.observedDigest },
+ '[Guardrails] LlmHook digest mismatch; quarantining (fail-closed for may_deny)'
)
}
if (duplicatePathLoser) {
- console.warn(
- `[Guardrails] LlmHook ${id} is a DuplicatePath collision loser (Ready=False); quarantining (fail-closed for may_deny)`
+ logger.warn(
+ { hookId: id },
+ '[Guardrails] LlmHook is a DuplicatePath collision loser (Ready=False); quarantining (fail-closed for may_deny)'
)
}
@@ -245,8 +288,20 @@ export async function resolveGuardrailHookDescriptors(
...(contentAccess ? { contentAccess } : {}),
...(quarantined ? { quarantined: true } : {}),
})
- console.log(
- `[Guardrails] resolved hook ${id} -> ${ep.endpoint}${path} points=[${points.join(',')}] caps=[${capabilities.join(',')}] failMode=${failMode}${external ? ' external=true(SSRF-guarded)' : ''}${quarantined ? ` quarantined=true(${duplicatePathLoser ? 'duplicate-path' : 'digest-mismatch'})` : ''}`
+ logger.info(
+ {
+ hookId: id,
+ endpointKind: ep.kind,
+ path,
+ points,
+ capabilities,
+ failMode,
+ external,
+ ...(quarantined
+ ? { quarantined: duplicatePathLoser ? 'duplicate-path' : 'digest-mismatch' }
+ : {}),
+ },
+ '[Guardrails] resolved hook'
)
}