Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure
TypeScript
feat(hcc): add llmhook reconciler with digest-dedup + reverse-index netpol (bucket b slice e)
Andy Paviad57711d12cf7
diff --git a/deploy/base/kustomization.yaml b/deploy/base/kustomization.yamlindex 0b1e244e4..8beb8009a 100644--- a/deploy/base/kustomization.yaml+++ b/deploy/base/kustomization.yaml@@ -7,6 +7,7 @@ resources:- control-plane- mcp-host- mcp-server+ - llm-hooks- channels- profiles- rpc-proxydiff --git a/deploy/base/llm-hooks/kustomization.yaml b/deploy/base/llm-hooks/kustomization.yamlnew file mode 100644index 000000000..b5633ece3--- /dev/null+++ b/deploy/base/llm-hooks/kustomization.yaml@@ -0,0 +1,4 @@+apiVersion: kustomize.config.k8s.io/v1beta1+kind: Kustomization+resources:+ - rbac.yamldiff --git a/deploy/base/llm-hooks/rbac.yaml b/deploy/base/llm-hooks/rbac.yamlnew file mode 100644index 000000000..d6c0a6a2e--- /dev/null+++ b/deploy/base/llm-hooks/rbac.yaml@@ -0,0 +1,58 @@+# --- Role: host-context-controller (llm-hooks namespace) ---+# Namespace-scoped grant for the HCC ServiceAccount to reconcile LlmHook CRDs+# into shared Deployment+Service+NetworkPolicy workloads (guardrails phase-4).+# Modeled on deploy/base/mcp-server/rbac.yaml, plus `pods` get/list which the+# McpServer Role does NOT grant — HCC needs it to read the LIVE pod's container+# image for status.observedDigest (mirrors the workflow-recipes Role).+apiVersion: rbac.authorization.k8s.io/v1+kind: Role+metadata:+ name: host-context-controller+ namespace: llm-hooks+rules:+ # Watch LlmHook CRDs+ - apiGroups: ["clerum.io"]+ resources: ["llmhooks"]+ verbs: ["get", "list", "watch", "patch"]+ # Read + write LlmHook status conditions / observedDigest / readyReplicas+ - apiGroups: ["clerum.io"]+ resources: ["llmhooks/status"]+ verbs: ["get", "patch"]+ # Manage the shared hook Deployments (digest-dedup: one Deployment per pod key)+ - apiGroups: ["apps"]+ resources: ["deployments"]+ verbs: ["get", "list", "create", "update", "delete"]+ # Manage the shared hook Services+ - apiGroups: [""]+ resources: ["services"]+ verbs: ["get", "list", "create", "update", "delete"]+ # ConfigMaps (forward-compat for hook config materialization)+ - apiGroups: [""]+ resources: ["configmaps"]+ verbs: ["get", "list", "create", "update", "delete"]+ # Read hook envSecret content for the credentials-revision digest+ - apiGroups: [""]+ resources: ["secrets"]+ verbs: ["get", "list", "watch"]+ # Manage the per-pod-key NetworkPolicies (reverse-index ingress + egress)+ - apiGroups: ["networking.k8s.io"]+ resources: ["networkpolicies"]+ verbs: ["get", "list", "create", "update", "delete"]+ # Read the LIVE hook pod's container status for status.observedDigest+ - apiGroups: [""]+ resources: ["pods"]+ verbs: ["get", "list"]+---+apiVersion: rbac.authorization.k8s.io/v1+kind: RoleBinding+metadata:+ name: host-context-controller+ namespace: llm-hooks+roleRef:+ apiGroup: rbac.authorization.k8s.io+ kind: Role+ name: host-context-controller+subjects:+ - kind: ServiceAccount+ name: host-context-controller+ namespace: control-planediff --git a/deploy/base/namespaces.yaml b/deploy/base/namespaces.yamlindex d76d77e9b..b5fde9dba 100644--- a/deploy/base/namespaces.yaml+++ b/deploy/base/namespaces.yaml@@ -43,6 +43,24 @@ metadata:---apiVersion: v1kind: Namespace+metadata:+ name: llm-hooks+ labels:+ app.kubernetes.io/name: clerum+ app.kubernetes.io/part-of: clerum+ kubernetes.io/metadata.name: llm-hooks+ # Guardrail hook pods run vendor/third-party images; baseline enforce is the+ # floor (blocks privileged / hostPath / hostNetwork), restricted warn/audit+ # surfaces drift. Mirrors mcp-server / sandbox-recipes.+ pod-security.kubernetes.io/enforce: baseline+ pod-security.kubernetes.io/enforce-version: latest+ pod-security.kubernetes.io/warn: restricted+ pod-security.kubernetes.io/warn-version: latest+ pod-security.kubernetes.io/audit: restricted+ pod-security.kubernetes.io/audit-version: latest+---+apiVersion: v1+kind: Namespacemetadata:name: profileslabels:diff --git a/host-context-controller/package-lock.json b/host-context-controller/package-lock.jsonindex c672234da..7ed85b211 100644--- a/host-context-controller/package-lock.json+++ b/host-context-controller/package-lock.json@@ -1,12 +1,12 @@{"name": "clerum-host-context-controller",- "version": "0.1.163",+ "version": "0.1.164","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "clerum-host-context-controller",- "version": "0.1.163",+ "version": "0.1.164","license": "SEE LICENSE IN LICENSE","dependencies": {"@clerum/image-policy": "file:../packages/image-policy",diff --git a/host-context-controller/package.json b/host-context-controller/package.jsonindex 85b46b7c4..9bf751897 100644--- a/host-context-controller/package.json+++ b/host-context-controller/package.json@@ -1,6 +1,6 @@{"name": "clerum-host-context-controller",- "version": "0.1.163",+ "version": "0.1.164","description": "Host Context Controller - provides McpServer CRDs to mcp-host via REST API","main": "dist/main.js","engines": {diff --git a/host-context-controller/src/config.ts b/host-context-controller/src/config.tsindex fb5c805ea..fdb94dcb6 100644--- a/host-context-controller/src/config.ts+++ b/host-context-controller/src/config.ts@@ -32,6 +32,15 @@ export interface Config {// Kubernetes namespace where per-Host channel-reader Deployments livechannelsNamespace: string+ // Kubernetes namespace where LlmHook image workloads (guardrail hook pods)+ // live and where the LlmHook CRDs are watched.+ llmHooksNamespace: string++ // Periodic LlmHook fullReconcile interval (seconds). Drives the reference-+ // counted orphan sweep (guardrails phase-4 §3) and readiness convergence when+ // a watch drops events. 0 disables.+ llmHookResyncIntervalSec: number+// Container image used for per-Host channel-reader DeploymentschannelReaderImage: string@@ -391,6 +400,12 @@ export const config: Config = {// Per-Host channel-reader Deployments namespacechannelsNamespace: getEnv('CONTEXT_MAPPER_CHANNELS_NAMESPACE', 'channels')!,+ // LlmHook image-workload / CRD-watch namespace (guardrails phase-4).+ llmHooksNamespace: getEnv('CONTEXT_MAPPER_LLM_HOOKS_NAMESPACE', 'llm-hooks')!,++ // Periodic LlmHook resync (default 5 min, matching hostResyncIntervalSec).+ llmHookResyncIntervalSec: getEnvInt('CONTEXT_MAPPER_LLM_HOOK_RESYNC_SEC', 300),+// Per-Host channel-reader Deployment image (matches deploy/base/channels/channel-reader.yaml)channelReaderImage: getEnv('CONTEXT_MAPPER_CHANNEL_READER_IMAGE', 'clerum/channel-reader:0.9.5')!,@@ -427,7 +442,9 @@ export const config: Config = {// Runtime namespaces where L0 deny-all + L1 infrastructure policies applyruntimeNamespaces: getEnv('CONTEXT_MAPPER_RUNTIME_NAMESPACES',- 'mcp-server,mcp-host,sandbox-recipes,rpc-proxy'+ // llm-hooks is included so ensureDefaultPolicies lays down default-deny ++ // infra (DNS/HCC API/K8s API) egress for guardrail hook pods (§5).+ 'mcp-server,mcp-host,sandbox-recipes,rpc-proxy,llm-hooks')!.split(','),// DNS infrastructure CIDR for GKE NodeLocal DNSCache / kube-dns. Emptydiff --git a/host-context-controller/src/constants.ts b/host-context-controller/src/constants.tsindex 9e18c3a61..c23b3c468 100644--- a/host-context-controller/src/constants.ts+++ b/host-context-controller/src/constants.ts@@ -4,6 +4,12 @@ export const MANAGED_BY_VALUE = 'host-context-controller'// WRC-labeled runtimes from unlabeled/user-owned resources.export const WRC_MANAGED_BY_VALUE = 'workflow-recipes'export const MCPSERVER_LABEL = 'clerum.io/mcpserver'+// Per-CR label stamped on the LlmHook workload's NetworkPolicy for traceability.+export const LLMHOOK_LABEL = 'clerum.io/llmhook'+// Pod-key label on the shared LlmHook Deployment/Service/NetworkPolicy. All+// hooks that hash to the same pod key co-locate on the pod named from this key+// and are reference-counted by it for label-owned GC (guardrails phase-4 §3).+export const HOOK_PODKEY_LABEL = 'clerum.io/hook-pod-key'export const POLICY_TYPE_LABEL = 'clerum.io/policy-type'export const RECIPE_LABEL = 'clerum.io/recipe'export const HOST_LABEL = 'clerum.io/host'diff --git a/host-context-controller/src/k8sClient.ts b/host-context-controller/src/k8sClient.tsindex ea754b7b5..c1b0eef09 100644--- a/host-context-controller/src/k8sClient.ts+++ b/host-context-controller/src/k8sClient.ts@@ -30,6 +30,7 @@ import {import { K8sGfsApi } from './k8s/gfsK8sApi'import { makeHostK8sApiClient } from './k8s/hostK8sApiClient'import { pvcName as sfsPvcName } from './k8s/sharedFileSystemFactory'+import { LlmHookReconciler, computePodKey, referencedHookIds } from './llmHookReconciler'import { hostDeleteCleanupTotal, hostFleetRequestsTotal, hostWatchRecoverySeconds } from './metrics'import { NetworkPolicyReconciler } from './networkPolicyReconciler'import { McpServerReconciler } from './reconciler'@@ -42,6 +43,8 @@ import {GlobalFileSystemSpec,HostCRD,HostSpec,+ LlmHookCRD,+ LlmHookSpec,McpServerCRD,McpServerInfo,McpServerSpec,@@ -83,6 +86,7 @@ const PLURAL_HOSTS = 'hosts'const PLURAL_SHAREDFILESYSTEMS = 'sharedfilesystems'const PLURAL_GLOBALFILESYSTEMS = 'globalfilesystems'const PLURAL_COMMUNICATIONCHANNELS = 'communicationchannels'+const PLURAL_LLMHOOKS = 'llmhooks'const EXTERNAL_EGRESS_RETRY_DELAYS_MS = [5000, 15000, 30000]const EXTERNAL_EGRESS_RESYNC_MAX_CONCURRENCY = 10const EXTERNAL_EGRESS_RESYNC_JITTER_MS = 5000@@ -494,6 +498,53 @@ async function listCommunicationChannelSnapshot(): Promise<CommunicationChannelS}}+/**+ * List all LlmHook CRDs in the llm-hooks namespace.+ */+export async function listAllLlmHooks(): Promise<LlmHookCRD[]> {+ if (!customObjectsApi) {+ throw new Error('K8s client not initialized - are you in dev mode?')+ }+ try {+ console.log(`[K8s] Listing all LlmHooks in namespace ${config.llmHooksNamespace}`)+ const response = await customObjectsApi.listNamespacedCustomObject({+ group: GROUP,+ version: VERSION,+ namespace: config.llmHooksNamespace,+ plural: PLURAL_LLMHOOKS,+ })+ const list = response as {+ items: Array<{+ metadata: {+ name: string+ namespace?: string+ uid?: string+ generation?: number+ annotations?: Record<string, string>+ labels?: Record<string, string>+ }+ spec: LlmHookSpec+ status?: LlmHookCRD['status']+ }>+ }+ const hooks = list.items.map(item => ({+ name: item.metadata.name,+ namespace: item.metadata.namespace || config.llmHooksNamespace,+ uid: item.metadata.uid,+ generation: item.metadata.generation,+ annotations: item.metadata.annotations,+ labels: item.metadata.labels,+ spec: item.spec,+ status: item.status,+ }))+ console.log(`[K8s] Found ${hooks.length} LlmHook(s)`)+ return hooks+ } catch (error) {+ console.error('[K8s] Failed to list LlmHooks:', error)+ throw error+ }+}+/*** Read a Context CRD by contextId.* Returns the allowed McpServer names, or null if not found.@@ -549,11 +600,13 @@ export class McpServerWatcher implements McpServerProvider {private sfsWatchRequest: { abort: () => void } | null = nullprivate gfsWatchRequest: { abort: () => void } | null = nullprivate ccWatchRequest: { abort: () => void } | null = null+ private llmHookWatchRequest: { abort: () => void } | null = nullprivate servers: Map<string, McpServerCRD> = new Map()private hosts: Map<string, HostCRD> = new Map()private contexts: Map<string, ContextCRD> = new Map()private sharedFileSystems: Map<string, SharedFileSystemCRD> = new Map()private communicationChannels: Map<string, CommunicationChannelCRD> = new Map()+ private llmHooks: Map<string, LlmHookCRD> = new Map()// A watch callback can still settle after its stream reports completion.// Host reconciles change the mcp-host pod template, so stale callbacks must// never replay an older Host spec after a replacement watch is active.@@ -594,6 +647,7 @@ export class McpServerWatcher implements McpServerProvider {private reconciler: McpServerReconcilerprivate hostReconciler: HostReconcilerprivate netPolReconciler: NetworkPolicyReconciler+ private llmHookReconciler: LlmHookReconcilerprivate bindingReconciler: BindingPolicyReconcilerprivate sharedFileSystemReconciler: SharedFileSystemReconcilerprivate gfsReconciler: GfsReconciler@@ -613,6 +667,9 @@ export class McpServerWatcher implements McpServerProvider {// reported Initializing/Degraded needs a periodic re-reconcile to converge to a// truthful Ready. Disabled when interval <= 0 (tests).private sfsResyncTimer: ReturnType<typeof setInterval> | null = null+ // Periodic LlmHook resync: drives the reference-counted orphan sweep and+ // readiness convergence when the watch drops events (guardrails phase-4 §3).+ private llmHookResyncTimer: ReturnType<typeof setInterval> | null = null// Periodic GlobalFileSystem resync: like SFS, the gfs watch fires only on the// CRD changing — not on the gfsc writer Deployment becoming Available — so a// GlobalFileSystem stuck at Initializing converges to Ready (and seeds its@@ -642,6 +699,9 @@ export class McpServerWatcher implements McpServerProvider {administrativeOutcomeReporter: this.administrativeOutcomeReporter,})this.netPolReconciler = new NetworkPolicyReconciler(kc, this.servers)+ // LlmHook reconciler shares the live hook + host caches so it can recompute+ // pod-key member sets and the Host→LlmHook reverse index on every reconcile.+ this.llmHookReconciler = new LlmHookReconciler(kc, this.llmHooks, this.hosts)this.bindingReconciler = new BindingPolicyReconciler(kc, config.namespace)this.sharedFileSystemReconciler = new SharedFileSystemReconciler(kc)// gfs (Global File System) — DISTINCT from SharedFileSystem. The reconcile@@ -1785,10 +1845,28 @@ export class McpServerWatcher implements McpServerProvider {)}+ // ── LlmHook initial load + reconciliation (guardrails phase-4) ──+ // Runs AFTER the Host cache is populated so the shared hook pods' NetworkPolicy+ // ingress reflects the current Host→LlmHook reverse index on the first pass.+ try {+ const initialHooks = await listAllLlmHooks()+ for (const hook of initialHooks) {+ this.llmHooks.set(hook.name, hook)+ }+ console.log('[K8s] Running initial LlmHook reconciliation...')+ await this.llmHookReconciler.fullReconcile(initialHooks)+ } catch (error) {+ console.error(+ '[K8s] Skipping initial LlmHook reconciliation because discovery failed:',+ error+ )+ }+await this.startMcpServerWatch()await this.startContextWatch()await this.startSharedFileSystemWatch()await this.startGlobalFileSystemWatch()+ await this.startLlmHookWatch()const resyncSec = config.hostResyncIntervalSecif (resyncSec > 0) {@@ -1814,6 +1892,18 @@ export class McpServerWatcher implements McpServerProvider {)}+ const llmHookResyncSec = config.llmHookResyncIntervalSec+ if (llmHookResyncSec > 0) {+ this.llmHookResyncTimer = setInterval(() => {+ void this.runLlmHookResync()+ }, llmHookResyncSec * 1000)+ console.log(`[K8s] LlmHook periodic resync enabled (every ${llmHookResyncSec}s)`)+ } else {+ console.warn(+ '[K8s] LlmHook periodic resync disabled; label-orphaned hook workloads will not be swept until another LlmHook event triggers reconciliation.'+ )+ }+const gfsResyncSec = config.gfsResyncIntervalSecif (gfsResyncSec > 0) {this.gfsResyncTimer = setInterval(() => {@@ -2506,6 +2596,90 @@ export class McpServerWatcher implements McpServerProvider {}}+ private getLlmHookWatchCallback(): (+ type: string,+ apiObj: {+ metadata: {+ name: string+ namespace?: string+ uid?: string+ generation?: number+ annotations?: Record<string, string>+ labels?: Record<string, string>+ }+ spec: LlmHookSpec+ status?: LlmHookCRD['status']+ }+ ) => Promise<void> {+ return async (type, apiObj) => {+ const hook: LlmHookCRD = {+ name: apiObj.metadata.name,+ namespace: apiObj.metadata.namespace || config.llmHooksNamespace,+ uid: apiObj.metadata.uid,+ generation: apiObj.metadata.generation,+ annotations: apiObj.metadata.annotations,+ labels: apiObj.metadata.labels,+ spec: apiObj.spec,+ status: apiObj.status,+ }++ console.log(`[K8s] LlmHook watch event: ${type} for ${hook.name}`)++ // Compute the pod key the CR had BEFORE this event so an image bump can+ // chain teardown of the old pod key with ensure of the new one (§4), and+ // a delete can GC the workload the CR was a member of.+ const previous = this.llmHooks.get(hook.name)+ const previousPodKey = previous ? computePodKey(previous) : null++ if (type === 'ADDED' || type === 'MODIFIED') {+ this.llmHooks.set(hook.name, hook)+ } else if (type === 'DELETED') {+ this.llmHooks.delete(hook.name)+ }++ try {+ if (type === 'ADDED' || type === 'MODIFIED') {+ await this.llmHookReconciler.reconcile(hook, previousPodKey)+ } else if (type === 'DELETED') {+ await this.llmHookReconciler.reconcileDelete(hook.name, previousPodKey)+ }+ } catch (error) {+ console.error(`[K8s] LlmHook reconciliation failed for ${hook.name}:`, error)+ }+ }+ }++ /**+ * Start watching LlmHook CRDs in the llm-hooks namespace.+ */+ private async startLlmHookWatch(): Promise<void> {+ const path = `/apis/${GROUP}/${VERSION}/namespaces/${config.llmHooksNamespace}/${PLURAL_LLMHOOKS}`+ console.log(`[K8s] Starting LlmHook watch`)++ const watchCallback = this.getLlmHookWatchCallback()++ const doneCallback = (err: Error | null) => {+ if (this.stopped) return+ if (err) {+ console.error('[K8s] LlmHook watch error:', err)+ }+ console.log('[K8s] LlmHook watch ended, restarting...')+ setTimeout(() => this.startLlmHookWatch(), err ? 5000 : 1000)+ }++ this.llmHookWatchRequest = await this.watch.watch(path, {}, watchCallback, doneCallback)+ }++ /** Periodic LlmHook resync: full reconcile drives the orphan sweep (§3). */+ private async runLlmHookResync(): Promise<void> {+ if (this.stopped) return+ try {+ await this.llmHookReconciler.fullReconcile([...this.llmHooks.values()])+ } catch (error) {+ console.error('[K8s] LlmHook periodic resync failed:', error)+ }+ }+/*** Start watching Context CRDs for NetworkPolicy reconciliation.*/@@ -2632,6 +2806,10 @@ export class McpServerWatcher implements McpServerProvider {this.clearHostWatchRetry(host.name)const eventRevision = ++this.hostWatchRevisionthis.latestHostWatchEventRevisions.set(host.name, eventRevision)+ // Capture the guardrail hook ids the Host referenced BEFORE this event so+ // a removed reference re-reconciles the (now smaller) NetworkPolicy+ // ingress set for the affected hook pod keys (Host→LlmHook reverse index).+ const previousHostForHooks = this.hosts.get(host.name)if (eventType === 'ADDED' || eventType === 'MODIFIED') {this.hosts.set(host.name, host)} else {@@ -2648,6 +2826,24 @@ export class McpServerWatcher implements McpServerProvider {console.error(`[K8s] Host reconciliation failed for ${host.name}:`, error)this.scheduleHostWatchReconcileRetry(eventType, host, eventRevision)}++ // Fan out to the LlmHook NetworkPolicy ingress (§5): re-reconcile the hook+ // pod keys this Host references now (or referenced before), so ingress+ // admits exactly the current set of mcp-hosts.+ const affectedHookIds = new Set<string>([+ ...referencedHookIds(previousHostForHooks),+ ...(eventType === 'DELETED' ? [] : referencedHookIds(host)),+ ])+ if (affectedHookIds.size > 0) {+ try {+ await this.llmHookReconciler.reconcileNetworkPoliciesForHooks([...affectedHookIds])+ } catch (error) {+ console.error(+ `[K8s] LlmHook NetworkPolicy fan-out after Host "${host.name}" change failed:`,+ error+ )+ }+ }}const doneCallback = (err: Error | null) => {@@ -2709,6 +2905,10 @@ export class McpServerWatcher implements McpServerProvider {clearInterval(this.sfsResyncTimer)this.sfsResyncTimer = null}+ if (this.llmHookResyncTimer) {+ clearInterval(this.llmHookResyncTimer)+ this.llmHookResyncTimer = null+ }if (this.gfsResyncTimer) {clearInterval(this.gfsResyncTimer)this.gfsResyncTimer = null@@ -2753,6 +2953,11 @@ export class McpServerWatcher implements McpServerProvider {this.ccWatchRequest.abort()this.ccWatchRequest = null}+ if (this.llmHookWatchRequest) {+ console.log('[K8s] Stopping LlmHook watch')+ this.llmHookWatchRequest.abort()+ this.llmHookWatchRequest = null+ }await Promise.allSettled([this.infrastructureTelemetryReporter?.stop(),this.administrativeOutcomeReporter?.stop(),diff --git a/host-context-controller/src/llmHookReconciler.test.ts b/host-context-controller/src/llmHookReconciler.test.tsnew file mode 100644index 000000000..c5f31c175--- /dev/null+++ b/host-context-controller/src/llmHookReconciler.test.ts@@ -0,0 +1,693 @@+import { beforeEach, describe, expect, it, vi } from 'vitest'+import * as k8s from '@kubernetes/client-node'+import {+ type MockAppsApi,+ type MockCoreApi,+ type MockCustomApi,+ type MockNetworkingApi,+ asAppsApi,+ asCoreApi,+ asCustomApi,+ asNetworkingApi,+ createMockAppsApi,+ createMockCoreApi,+ createMockCustomApi,+ createMockNetworkingApi,+} from '../test/__fixtures__/testMocks'+import { HOOK_PODKEY_LABEL, HOST_LABEL, MANAGED_BY_LABEL, MANAGED_BY_VALUE } from './constants'+import {+ LlmHookReconciler,+ computePodKey,+ podKeyResourceName,+ referencedHookIds,+} from './llmHookReconciler'+import { HostCRD, LlmHookCRD } from './types'++vi.mock('./config', () => ({+ config: {+ devMode: false,+ port: 8081,+ namespace: 'mcp-server',+ controlPlaneNamespace: 'control-plane',+ hostNamespace: 'mcp-host',+ llmHooksNamespace: 'llm-hooks',+ mcpServerImagePullPolicy: 'IfNotPresent',+ runtimeNamespaces: ['mcp-server', 'mcp-host', 'llm-hooks'],+ minimalInfraNamespaces: [],+ },+}))++const IMG = 'registry.example.com/hook@sha256:' + 'a'.repeat(64)++function makeHook(overrides: Partial<LlmHookCRD> & { name: string }): LlmHookCRD {+ const { name, spec, ...rest } = overrides+ return {+ name,+ namespace: 'llm-hooks',+ generation: 1,+ spec: {+ target: { image: { ref: IMG, port: 8080 } },+ path: '/',+ lifecyclePoints: ['preCall'],+ ...spec,+ },+ ...rest,+ }+}++function makeHostRef(name: string, hookIds: string[]): HostCRD {+ return {+ name,+ namespace: 'mcp-host',+ spec: {+ host: name,+ contextRef: 'ctx',+ secretRef: 'secret',+ guardrails: { hooks: { preCall: hookIds.map(id => ({ id })) } },+ },+ }+}++/** Extract the Ready condition from the patchNamespacedCustomObjectStatus calls for a hook. */+function readyConditionFor(customApi: MockCustomApi, name: string) {+ for (let i = customApi.patchNamespacedCustomObjectStatus.mock.calls.length - 1; i >= 0; i--) {+ const arg = customApi.patchNamespacedCustomObjectStatus.mock.calls[i][0] as {+ name: string+ body: Array<{ op: string; path: string; value: unknown }>+ }+ if (arg.name !== name) continue+ const op = arg.body.find(o => o.path === '/status/conditions' || o.path === '/status')+ if (!op) continue+ const conditions = (+ op.path === '/status'+ ? (op.value as { conditions?: Array<Record<string, unknown>> }).conditions+ : (op.value as Array<Record<string, unknown>>)+ ) as Array<Record<string, unknown>> | undefined+ const ready = conditions?.find(c => c.type === 'Ready')+ if (ready) return ready+ }+ return undefined+}++function deploymentNames(appsApi: MockAppsApi): string[] {+ return appsApi.createNamespacedDeployment.mock.calls.map(+ c => (c[0] as { body: k8s.V1Deployment }).body.metadata?.name as string+ )+}++describe('LlmHookReconciler', () => {+ let appsApi: MockAppsApi+ let coreApi: MockCoreApi+ let customApi: MockCustomApi+ let networkingApi: MockNetworkingApi+ let hooks: Map<string, LlmHookCRD>+ let hosts: Map<string, HostCRD>+ let reconciler: LlmHookReconciler++ function build(): LlmHookReconciler {+ return new LlmHookReconciler({} as k8s.KubeConfig, hooks, hosts, {+ appsApi: asAppsApi(appsApi),+ coreApi: asCoreApi(coreApi),+ customApi: asCustomApi(customApi),+ networkingApi: asNetworkingApi(networkingApi),+ })+ }++ beforeEach(() => {+ vi.clearAllMocks()+ appsApi = createMockAppsApi()+ coreApi = createMockCoreApi()+ customApi = createMockCustomApi()+ networkingApi = createMockNetworkingApi()+ // Status reads start with an empty conditions object (hasStatusObject true).+ customApi.getNamespacedCustomObjectStatus.mockResolvedValue({+ metadata: { resourceVersion: '1' },+ status: { conditions: [] },+ })+ hooks = new Map()+ hosts = new Map()+ reconciler = build()+ })++ // ─── Pod-key hashing (§10) ─────────────────────────────────────────++ describe('computePodKey', () => {+ it('is identical for identical pod-level fields', () => {+ const a = makeHook({+ name: 'a',+ spec: {+ target: { image: { ref: IMG, port: 8080 } },+ path: '/a',+ lifecyclePoints: ['preCall'],+ },+ })+ const b = makeHook({+ name: 'b',+ spec: {+ target: { image: { ref: IMG, port: 8080 } },+ path: '/b',+ lifecyclePoints: ['moderate'],+ },+ })+ expect(computePodKey(a)).toBe(computePodKey(b))+ })++ it('does NOT depend on path, order, capabilities, failMode', () => {+ const base = makeHook({ name: 'base' })+ const other = makeHook({+ name: 'other',+ spec: {+ target: { image: { ref: IMG, port: 8080 } },+ path: '/deep/path',+ lifecyclePoints: ['onError'],+ order: 5,+ failMode: 'open',+ capabilities: ['may_deny'],+ config: { anything: true },+ },+ })+ expect(computePodKey(other)).toBe(computePodKey(base))+ })++ it('differs on envSecret, egressBindings, and addCapabilities', () => {+ const base = makeHook({ name: 'base' })+ const key = computePodKey(base)+ const diffSecret = makeHook({+ name: 's',+ spec: {+ target: { image: { ref: IMG, port: 8080, envSecret: 'creds' } },+ lifecyclePoints: ['preCall'],+ },+ })+ const diffEgress = makeHook({+ name: 'e',+ spec: {+ target: { image: { ref: IMG, port: 8080, egressBindings: [{ cidr: '8.8.8.8/32' }] } },+ lifecyclePoints: ['preCall'],+ },+ })+ const diffCaps = makeHook({+ name: 'c',+ spec: {+ target: {+ image: { ref: IMG, port: 8080, security: { addCapabilities: ['NET_BIND_SERVICE'] } },+ },+ lifecyclePoints: ['preCall'],+ },+ })+ expect(computePodKey(diffSecret)).not.toBe(key)+ expect(computePodKey(diffEgress)).not.toBe(key)+ expect(computePodKey(diffCaps)).not.toBe(key)+ })++ it('is null for service/remote targets', () => {+ const svc = makeHook({+ name: 'svc',+ spec: {+ target: { service: { name: 'x', namespace: 'y', port: 1 } },+ lifecyclePoints: ['preCall'],+ },+ })+ expect(computePodKey(svc)).toBeNull()+ })++ it('is stable regardless of egressBindings ordering', () => {+ const a = makeHook({+ name: 'a',+ spec: {+ target: {+ image: {+ ref: IMG,+ port: 8080,+ egressBindings: [{ cidr: '8.8.8.8/32' }, { cidr: '1.1.1.1/32' }],+ },+ },+ lifecyclePoints: ['preCall'],+ },+ })+ const b = makeHook({+ name: 'b',+ spec: {+ target: {+ image: {+ ref: IMG,+ port: 8080,+ egressBindings: [{ cidr: '1.1.1.1/32' }, { cidr: '8.8.8.8/32' }],+ },+ },+ lifecyclePoints: ['preCall'],+ },+ })+ expect(computePodKey(a)).toBe(computePodKey(b))+ })+ })++ // ─── Dedup (§10) ───────────────────────────────────────────────────++ it('co-locates two same-pod-key hooks on ONE Deployment/Service', async () => {+ const a = makeHook({+ name: 'a',+ spec: {+ target: { image: { ref: IMG, port: 8080 } },+ path: '/a',+ lifecyclePoints: ['preCall'],+ },+ })+ const b = makeHook({+ name: 'b',+ spec: {+ target: { image: { ref: IMG, port: 8080 } },+ path: '/b',+ lifecyclePoints: ['preCall'],+ },+ })+ hooks.set('a', a)+ hooks.set('b', b)+ await reconciler.reconcile(a)+ await reconciler.reconcile(b)++ const uniqueNames = new Set(deploymentNames(appsApi))+ expect(uniqueNames.size).toBe(1)+ expect([...uniqueNames][0]).toBe(podKeyResourceName(computePodKey(a)!))+ })++ it('distinct pod keys → two Deployments', async () => {+ const a = makeHook({+ name: 'a',+ spec: { target: { image: { ref: IMG, port: 8080 } }, lifecyclePoints: ['preCall'] },+ })+ const b = makeHook({+ name: 'b',+ spec: { target: { image: { ref: IMG, port: 9090 } }, lifecyclePoints: ['preCall'] },+ })+ hooks.set('a', a)+ hooks.set('b', b)+ await reconciler.reconcile(a)+ await reconciler.reconcile(b)+ expect(new Set(deploymentNames(appsApi)).size).toBe(2)+ })++ // ─── Path collision (§10) ──────────────────────────────────────────++ it('fails the path-collision loser closed while serving the winner', async () => {+ const a = makeHook({+ name: 'a',+ spec: {+ target: { image: { ref: IMG, port: 8080 } },+ path: '/dup',+ lifecyclePoints: ['preCall'],+ },+ })+ const b = makeHook({+ name: 'b',+ spec: {+ target: { image: { ref: IMG, port: 8080 } },+ path: '/dup',+ lifecyclePoints: ['preCall'],+ },+ })+ hooks.set('a', a)+ hooks.set('b', b)+ await reconciler.reconcile(a)++ // 'a' (first by sorted name) wins; 'b' loses.+ expect(readyConditionFor(customApi, 'a')?.reason).toBe('Ready')+ expect(readyConditionFor(customApi, 'b')?.status).toBe('False')+ expect(readyConditionFor(customApi, 'b')?.reason).toBe('DuplicatePath')+ // Workload still created for the winner.+ expect(appsApi.createNamespacedDeployment).toHaveBeenCalled()+ })++ // ─── Reference-counted GC (§10) ────────────────────────────────────++ it('keeps the workload when one of two co-tenants is deleted', async () => {+ const a = makeHook({+ name: 'a',+ spec: {+ target: { image: { ref: IMG, port: 8080 } },+ path: '/a',+ lifecyclePoints: ['preCall'],+ },+ })+ const b = makeHook({+ name: 'b',+ spec: {+ target: { image: { ref: IMG, port: 8080 } },+ path: '/b',+ lifecyclePoints: ['preCall'],+ },+ })+ hooks.set('a', a)+ hooks.set('b', b)+ const podKey = computePodKey(a)!++ // Delete 'a' — the watcher evicts it from the cache first.+ hooks.delete('a')+ await reconciler.reconcileDelete('a', podKey)++ expect(appsApi.deleteNamespacedDeployment).not.toHaveBeenCalled()+ })++ it('deletes the workload when the last co-tenant is deleted (label-owned)', async () => {+ const a = makeHook({+ name: 'a',+ spec: { target: { image: { ref: IMG, port: 8080 } }, lifecyclePoints: ['preCall'] },+ })+ const podKey = computePodKey(a)!+ const name = podKeyResourceName(podKey)+ // Read returns HCC-owned labels for this pod key so the delete is authorized.+ const owned = {+ metadata: {+ resourceVersion: '1',+ labels: { [MANAGED_BY_LABEL]: MANAGED_BY_VALUE, [HOOK_PODKEY_LABEL]: podKey },+ },+ }+ appsApi.readNamespacedDeployment.mockResolvedValue(owned)+ coreApi.readNamespacedService.mockResolvedValue(owned)+ networkingApi.readNamespacedNetworkPolicy.mockResolvedValue(owned)++ // Last member gone.+ await reconciler.reconcileDelete('a', podKey)++ expect(appsApi.deleteNamespacedDeployment).toHaveBeenCalledWith(+ expect.objectContaining({ name, namespace: 'llm-hooks' })+ )+ expect(coreApi.deleteNamespacedService).toHaveBeenCalledWith(expect.objectContaining({ name }))+ expect(networkingApi.deleteNamespacedNetworkPolicy).toHaveBeenCalledWith(+ expect.objectContaining({ name })+ )+ })++ it('does NOT delete a workload whose labels are not HCC-owned', async () => {+ const a = makeHook({+ name: 'a',+ spec: { target: { image: { ref: IMG, port: 8080 } }, lifecyclePoints: ['preCall'] },+ })+ const podKey = computePodKey(a)!+ appsApi.readNamespacedDeployment.mockResolvedValue({+ metadata: { resourceVersion: '1', labels: { [HOOK_PODKEY_LABEL]: 'other-key' } },+ })+ await reconciler.reconcileDelete('a', podKey)+ expect(appsApi.deleteNamespacedDeployment).not.toHaveBeenCalled()+ })++ it('sweeps a label-orphaned workload with 0 members on full reconcile', async () => {+ const orphanKey = 'deadbeefdeadbeef'+ const orphanName = podKeyResourceName(orphanKey)+ appsApi.listNamespacedDeployment.mockResolvedValue({+ items: [+ {+ metadata: {+ name: orphanName,+ labels: { [MANAGED_BY_LABEL]: MANAGED_BY_VALUE, [HOOK_PODKEY_LABEL]: orphanKey },+ },+ },+ ],+ })+ const owned = {+ metadata: {+ resourceVersion: '1',+ labels: { [MANAGED_BY_LABEL]: MANAGED_BY_VALUE, [HOOK_PODKEY_LABEL]: orphanKey },+ },+ }+ appsApi.readNamespacedDeployment.mockResolvedValue(owned)+ coreApi.readNamespacedService.mockResolvedValue(owned)+ networkingApi.readNamespacedNetworkPolicy.mockResolvedValue(owned)++ await reconciler.fullReconcile([]) // no live hooks → orphan has 0 members++ expect(appsApi.deleteNamespacedDeployment).toHaveBeenCalledWith(+ expect.objectContaining({ name: orphanName })+ )+ })++ // ─── Concurrency (§10) ─────────────────────────────────────────────++ it('serializes concurrent reconciles of two CRs sharing a pod key', async () => {+ let inFlight = 0+ let maxInFlight = 0+ appsApi.createNamespacedDeployment.mockImplementation(async () => {+ inFlight+++ maxInFlight = Math.max(maxInFlight, inFlight)+ await new Promise(r => setTimeout(r, 5))+ inFlight--+ return {}+ })+ const a = makeHook({+ name: 'a',+ spec: {+ target: { image: { ref: IMG, port: 8080 } },+ path: '/a',+ lifecyclePoints: ['preCall'],+ },+ })+ const b = makeHook({+ name: 'b',+ spec: {+ target: { image: { ref: IMG, port: 8080 } },+ path: '/b',+ lifecyclePoints: ['preCall'],+ },+ })+ hooks.set('a', a)+ hooks.set('b', b)+ await Promise.all([reconciler.reconcile(a), reconciler.reconcile(b)])+ expect(maxInFlight).toBe(1)+ })++ it('image bump chains teardown of the old pod key and ensure of the new', async () => {+ const oldHook = makeHook({+ name: 'a',+ spec: { target: { image: { ref: IMG, port: 8080 } }, lifecyclePoints: ['preCall'] },+ })+ const oldKey = computePodKey(oldHook)!+ const newHook = makeHook({+ name: 'a',+ spec: { target: { image: { ref: IMG, port: 9090 } }, lifecyclePoints: ['preCall'] },+ })+ const newKey = computePodKey(newHook)!+ // Cache holds only the NEW hook after the MODIFIED event; old key has 0 members.+ hooks.set('a', newHook)+ const ownedOld = {+ metadata: {+ resourceVersion: '1',+ labels: { [MANAGED_BY_LABEL]: MANAGED_BY_VALUE, [HOOK_PODKEY_LABEL]: oldKey },+ },+ }+ appsApi.readNamespacedDeployment.mockResolvedValue(ownedOld)+ coreApi.readNamespacedService.mockResolvedValue(ownedOld)+ networkingApi.readNamespacedNetworkPolicy.mockResolvedValue(ownedOld)++ await reconciler.reconcile(newHook, oldKey)++ // Old pod key torn down…+ expect(appsApi.deleteNamespacedDeployment).toHaveBeenCalledWith(+ expect.objectContaining({ name: podKeyResourceName(oldKey) })+ )+ // …new pod key created.+ expect(deploymentNames(appsApi)).toContain(podKeyResourceName(newKey))+ })++ // ─── NetworkPolicy ingress reverse-index (§10) ─────────────────────++ it('NetworkPolicy ingress admits exactly the referencing Hosts', async () => {+ const a = makeHook({+ name: 'a',+ spec: { target: { image: { ref: IMG, port: 8080 } }, lifecyclePoints: ['preCall'] },+ })+ hooks.set('a', a)+ hosts.set('host-1', makeHostRef('host-1', ['a']))+ hosts.set('host-2', makeHostRef('host-2', ['other-hook'])) // does NOT reference 'a'++ await reconciler.reconcile(a)++ const npCall = networkingApi.createNamespacedNetworkPolicy.mock.calls.at(-1)![0] as {+ body: k8s.V1NetworkPolicy+ }+ const ingress = npCall.body.spec?.ingress ?? []+ const peers = (ingress[0]?._from ?? []) as Array<{+ podSelector?: { matchLabels?: Record<string, string> }+ }>+ const hostSelectors = peers.map(p => p.podSelector?.matchLabels?.[HOST_LABEL])+ expect(hostSelectors).toContain('host-1')+ expect(hostSelectors).not.toContain('host-2')+ })++ it('co-located members: NetworkPolicy label values are comma-free (member list is an annotation)', async () => {+ // Two hooks with the SAME image target share one pod key → one shared NP.+ const a = makeHook({+ name: 'a',+ spec: {+ target: { image: { ref: IMG, port: 8080 } },+ path: '/a',+ lifecyclePoints: ['preCall'],+ },+ })+ const b = makeHook({+ name: 'b',+ spec: {+ target: { image: { ref: IMG, port: 8080 } },+ path: '/b',+ lifecyclePoints: ['preCall'],+ },+ })+ hooks.set('a', a)+ hooks.set('b', b)+ await reconciler.reconcile(a)++ const npCall = networkingApi.createNamespacedNetworkPolicy.mock.calls.at(-1)![0] as {+ body: k8s.V1NetworkPolicy+ }+ // K8s label values may not contain commas; a comma-joined multi-member value+ // would 422 at the apiserver — the exact digest-dedup case.+ for (const value of Object.values(npCall.body.metadata?.labels ?? {})) {+ expect(value).not.toContain(',')+ }+ // The member list belongs in an annotation, where commas are valid.+ expect(npCall.body.metadata?.annotations?.['clerum.io/llmhook-members']).toBe('a,b')+ })++ it('re-reconciles NetworkPolicy ingress on a Host reference change (fan-out)', async () => {+ const a = makeHook({+ name: 'a',+ spec: { target: { image: { ref: IMG, port: 8080 } }, lifecyclePoints: ['preCall'] },+ })+ hooks.set('a', a)+ // Host newly references 'a'.+ hosts.set('host-1', makeHostRef('host-1', ['a']))++ await reconciler.reconcileNetworkPoliciesForHooks(['a'])++ expect(networkingApi.createNamespacedNetworkPolicy).toHaveBeenCalled()+ const npCall = networkingApi.createNamespacedNetworkPolicy.mock.calls.at(-1)![0] as {+ body: k8s.V1NetworkPolicy+ }+ const peers = (npCall.body.spec?.ingress?.[0]?._from ?? []) as Array<{+ podSelector?: { matchLabels?: Record<string, string> }+ }>+ expect(peers.map(p => p.podSelector?.matchLabels?.[HOST_LABEL])).toContain('host-1')+ })++ it('rejects an invalid (private-range) egress binding without exposing the workload', async () => {+ const a = makeHook({+ name: 'a',+ spec: {+ target: {+ image: { ref: IMG, port: 8080, egressBindings: [{ cidr: '10.0.0.0/8', ports: [443] }] },+ },+ lifecyclePoints: ['preCall'],+ },+ })+ hooks.set('a', a)+ await reconciler.reconcile(a)++ expect(readyConditionFor(customApi, 'a')?.status).toBe('False')+ expect(readyConditionFor(customApi, 'a')?.reason).toBe('InvalidEgress')+ expect(appsApi.createNamespacedDeployment).not.toHaveBeenCalled()+ })++ it('allows a valid public-CIDR egress binding as an Egress NetworkPolicy rule', async () => {+ const a = makeHook({+ name: 'a',+ spec: {+ target: {+ image: { ref: IMG, port: 8080, egressBindings: [{ cidr: '8.8.8.8/32', ports: [443] }] },+ },+ lifecyclePoints: ['preCall'],+ },+ })+ hooks.set('a', a)+ await reconciler.reconcile(a)++ const npCall = networkingApi.createNamespacedNetworkPolicy.mock.calls.at(-1)![0] as {+ body: k8s.V1NetworkPolicy+ }+ expect(npCall.body.spec?.egress?.[0]?.to?.[0]?.ipBlock?.cidr).toBe('8.8.8.8/32')+ expect(appsApi.createNamespacedDeployment).toHaveBeenCalled()+ })++ // ─── Secret gate ───────────────────────────────────────────────────++ it('fails closed with SecretNotFound when envSecret is missing', async () => {+ const a = makeHook({+ name: 'a',+ spec: {+ target: { image: { ref: IMG, port: 8080, envSecret: 'missing' } },+ lifecyclePoints: ['preCall'],+ },+ })+ hooks.set('a', a)+ coreApi.readNamespacedSecret.mockRejectedValue({ code: 404 })+ await reconciler.reconcile(a)++ expect(readyConditionFor(customApi, 'a')?.reason).toBe('SecretNotFound')+ expect(appsApi.createNamespacedDeployment).not.toHaveBeenCalled()+ })++ // ─── Status shape (§10) ────────────────────────────────────────────++ it('writes NoWorkload Ready=True for service/remote targets (nothing deployed)', async () => {+ const svc = makeHook({+ name: 'svc',+ spec: {+ target: { service: { name: 'x', namespace: 'y', port: 1 } },+ lifecyclePoints: ['preCall'],+ },+ })+ hooks.set('svc', svc)+ await reconciler.reconcile(svc)++ expect(readyConditionFor(customApi, 'svc')?.status).toBe('True')+ expect(readyConditionFor(customApi, 'svc')?.reason).toBe('NoWorkload')+ expect(appsApi.createNamespacedDeployment).not.toHaveBeenCalled()+ })++ it('writes conditions[] + observedDigest + readyReplicas for a ready image hook', async () => {+ const digest = 'sha256:' + 'b'.repeat(64)+ coreApi.listNamespacedPod.mockResolvedValue({+ items: [+ { status: { containerStatuses: [{ imageID: `docker.io/x@${digest}`, image: IMG }] } },+ ],+ })+ const a = makeHook({+ name: 'a',+ spec: { target: { image: { ref: IMG, port: 8080 } }, lifecyclePoints: ['preCall'] },+ })+ hooks.set('a', a)+ await reconciler.reconcile(a)++ const patch = customApi.patchNamespacedCustomObjectStatus.mock.calls.at(-1)![0] as {+ body: Array<{ op: string; path: string; value: unknown }>+ }+ const paths = patch.body.map(o => o.path)+ expect(paths).toContain('/status/conditions')+ expect(paths).toContain('/status/observedDigest')+ expect(paths).toContain('/status/readyReplicas')+ const digestOp = patch.body.find(o => o.path === '/status/observedDigest')+ expect(digestOp?.value).toBe(digest)+ expect(readyConditionFor(customApi, 'a')?.reason).toBe('Ready')+ })++ // ─── referencedHookIds helper ──────────────────────────────────────++ it('referencedHookIds collects ids across all guardrail phases', () => {+ const host: HostCRD = {+ name: 'h',+ namespace: 'mcp-host',+ spec: {+ host: 'h',+ contextRef: 'ctx',+ secretRef: 's',+ guardrails: {+ hooks: {+ preCall: [{ id: 'x' }],+ postCallSuccess: [{ id: 'y', digest: 'sha256:...' }],+ moderate: [{ id: 'x' }],+ },+ },+ },+ }+ expect(new Set(referencedHookIds(host))).toEqual(new Set(['x', 'y', 'x']))+ expect(referencedHookIds(undefined)).toEqual([])+ })+})diff --git a/host-context-controller/src/llmHookReconciler.ts b/host-context-controller/src/llmHookReconciler.tsnew file mode 100644index 000000000..7f0c365d7--- /dev/null+++ b/host-context-controller/src/llmHookReconciler.ts@@ -0,0 +1,1018 @@+/**+ * LlmHook Reconciler — turns `image`-target LlmHook CRs into a shared+ * Deployment + Service + NetworkPolicy in the llm-hooks namespace, and writes+ * LlmHook.status. `service` and `remote` targets deploy nothing (status-only).+ *+ * The one hard divergence from every other HCC reconciler is digest-dedup:+ * this is N-CRs → 1-workload. Multiple `image` hooks that share a POD KEY+ * (image ref + port + envSecret + egressBindings + addCapabilities) co-locate+ * on a single pod and are addressed by distinct spec.path. Three mechanisms+ * replace the single-owner-ref cascade every other reconciler relies on:+ * 1. reference-counted, label-owned workloads (delete when the last member+ * for a pod key is gone; startup/periodic sweep for orphans);+ * 2. per-pod-key serialization (not per-CR-name — two CRs mutating the same+ * pod key would otherwise race on the same Deployment/Service/NP);+ * 3. a Host→LlmHook reverse index for the NetworkPolicy ingress set.+ *+ * Mirrors McpServerReconciler (hardened securityContext, credentials-revision+ * annotation, create-then-409 replaceWithConflictRetry, ownership-verifying+ * deletes, status-subresource JSON-Patch writer) and NetworkPolicyReconciler+ * (default-deny + infra baseline, L2 reverse-index ingress, L3 egress + SSRF+ * validators).+ */+import * as k8s from '@kubernetes/client-node'+import { IntOrString } from '@kubernetes/client-node/dist/types.js'+import { createHash } from 'crypto'+import * as dns from 'node:dns/promises'+import { isIP } from 'node:net'+import { isWorkflowRecipeDefaultAllowedCapability } from '@clerum/workflow-recipe-capability-policy'+import { config } from './config'+import { HOOK_PODKEY_LABEL, HOST_LABEL, MANAGED_BY_LABEL, MANAGED_BY_VALUE } from './constants'+import { isAllowedExternalEgressCidr, isPublicDnsHostname } from './networkPolicyReconciler'+import { HostCRD, LlmHookCRD, LlmHookCondition, LlmHookImageTarget, LlmHookStatus } from './types'+import {+ getErrorCode,+ preserveDeploymentAnnotations,+ preserveObjectAnnotations,+ preserveServiceAssignedFields,+ replaceWithConflictRetry,+} from './utils'++const GROUP = 'clerum.io'+const VERSION = 'v1alpha1'+const PLURAL_LLMHOOKS = 'llmhooks'+const CREDENTIALS_REVISION_ANNOTATION = 'clerum.io/credentials-revision'+const LOG = '[LlmHook]'++/** Machine-readable Ready condition reasons (bounded enum, §6). */+export type LlmHookReadyReason =+ | 'NoWorkload'+ | 'Deploying'+ | 'Ready'+ | 'DuplicatePath'+ | 'SecretNotFound'+ | 'InvalidEgress'+ | 'ReconcileError'++type LlmHookReconcilerDeps = {+ appsApi?: k8s.AppsV1Api+ coreApi?: k8s.CoreV1Api+ customApi?: k8s.CustomObjectsApi+ networkingApi?: k8s.NetworkingV1Api+}++type SecretValidation = { ok: true; revision: string } | { ok: false; message: string }++type EgressBuild = { rules: k8s.V1NetworkPolicyEgressRule[]; failures: string[] }++type StatusExtras = {+ observedDigest?: string+ readyReplicas?: number+ lastReconciled?: string+}++/**+ * Collect every installed-hook id a Host references across all guardrail+ * lifecycle phases. This is the Host side of the Host→LlmHook reverse index+ * that drives the shared pod's NetworkPolicy ingress set (§5).+ */+export function referencedHookIds(host: HostCRD | undefined): string[] {+ const hooks = host?.spec.guardrails?.hooks+ if (!hooks) return []+ const ids: string[] = []+ for (const phase of Object.values(hooks)) {+ if (!Array.isArray(phase)) continue+ for (const ref of phase) {+ if (ref && typeof ref.id === 'string' && ref.id) ids.push(ref.id)+ }+ }+ return ids+}++/**+ * Stable pod key over the POD-LEVEL fields of an image target (§1.1). Two+ * hooks with the same key safely share a pod; a different envSecret or+ * egressBindings gets its own key → its own pod (a different trust/egress+ * boundary). path/order/capabilities/failMode/config are NOT in the key.+ * Returns null for non-image (service/remote) targets.+ */+export function computePodKey(hook: LlmHookCRD): string | null {+ const img = hook.spec.target?.image+ if (!img) return null+ const canonical = {+ imageRef: img.ref,+ port: img.port,+ envSecret: img.envSecret ?? '',+ egressBindings: normalizeEgressBindings(img.egressBindings),+ addCapabilities: [...(img.security?.addCapabilities ?? [])].sort(),+ }+ return createHash('sha256').update(JSON.stringify(canonical)).digest('hex').slice(0, 16)+}++/** Canonicalize egressBindings into a stable, order-independent form. */+function normalizeEgressBindings(+ bindings: LlmHookImageTarget['egressBindings']+): Array<{ cidr: string | null; toFQDN: string | null; ports: number[] }> {+ return (bindings ?? [])+ .map(b => ({+ cidr: b.cidr ?? null,+ toFQDN: b.toFQDN ?? null,+ ports: [...(b.ports ?? [])].sort((a, z) => a - z),+ }))+ .sort((a, z) => JSON.stringify(a).localeCompare(JSON.stringify(z)))+}++export function podKeyResourceName(podKey: string): string {+ return `llmhook-${podKey}`+}++type TargetKind = 'image' | 'service' | 'remote' | 'invalid'++function classifyTarget(hook: LlmHookCRD): TargetKind {+ const t = hook.spec.target ?? {}+ if (t.image) return 'image'+ if (t.service) return 'service'+ if (t.remote) return 'remote'+ return 'invalid'+}++export class LlmHookReconciler {+ private readonly appsApi: k8s.AppsV1Api+ private readonly coreApi: k8s.CoreV1Api+ private readonly customApi: k8s.CustomObjectsApi+ private readonly networkingApi: k8s.NetworkingV1Api++ /** Cache of LlmHook CRs by name (owned by the watcher). */+ private readonly hooks: Map<string, LlmHookCRD>+ /** Cache of Host CRs by name (owned by the watcher) — reverse-index source. */+ private readonly hosts: Map<string, HostCRD>++ /**+ * Tail promise of the in-flight work per SERIALIZATION KEY. Image targets+ * serialize by pod key so all work touching one shared workload runs strictly+ * sequentially while different pod keys run concurrently (§4); service/remote+ * targets serialize by `name:<crName>`.+ */+ private readonly inFlight: Map<string, Promise<void>> = new Map()++ constructor(+ kc: k8s.KubeConfig,+ hookCache: Map<string, LlmHookCRD>,+ hostCache: Map<string, HostCRD>,+ deps?: LlmHookReconcilerDeps+ ) {+ this.appsApi = deps?.appsApi ?? kc.makeApiClient(k8s.AppsV1Api)+ this.coreApi = deps?.coreApi ?? kc.makeApiClient(k8s.CoreV1Api)+ this.customApi = deps?.customApi ?? kc.makeApiClient(k8s.CustomObjectsApi)+ this.networkingApi = deps?.networkingApi ?? kc.makeApiClient(k8s.NetworkingV1Api)+ this.hooks = hookCache+ this.hosts = hostCache+ }++ // ─── Serialization ──────────────────────────────────────────────────++ private runSerialized(key: string, fn: () => Promise<void>): Promise<void> {+ const prev = this.inFlight.get(key) ?? Promise.resolve()+ const next = prev.catch(() => undefined).then(fn)+ this.inFlight.set(key, next)+ return (async () => {+ try {+ await next+ } finally {+ if (this.inFlight.get(key) === next) this.inFlight.delete(key)+ }+ })()+ }++ // ─── Public API ─────────────────────────────────────────────────────++ /**+ * Reconcile a created or modified LlmHook. `previousPodKey` (the pod key the+ * CR had before this event, computed from the cached object) lets an image+ * bump chain teardown of the old workload on the old key AND ensure the new+ * one on the new key (§4), so neither interleaves with the other.+ */+ async reconcile(hook: LlmHookCRD, previousPodKey?: string | null): Promise<void> {+ const kind = classifyTarget(hook)+ if (kind !== 'image') {+ await this.runSerialized(`name:${hook.name}`, () => this.reconcileNonImage(hook, kind))+ return+ }+ const podKey = computePodKey(hook)!+ if (previousPodKey && previousPodKey !== podKey) {+ // The image target changed pod keys: tear down the stale one (if it now+ // has zero members) before/while ensuring the new one.+ await this.runSerialized(previousPodKey, () => this.reconcilePodKey(previousPodKey))+ }+ await this.runSerialized(podKey, () => this.reconcilePodKey(podKey))+ }++ /**+ * Reconcile a deleted LlmHook. The cached object was already evicted by the+ * watcher; `formerPodKey` is its pod key (computed before eviction). Running+ * the pod-key reconcile now sees a smaller (possibly empty) member set and+ * GCs the workload when the last member is gone (§3).+ */+ async reconcileDelete(name: string, formerPodKey?: string | null): Promise<void> {+ if (!formerPodKey) {+ // service/remote (or unknown) — nothing was deployed.+ await this.runSerialized(`name:${name}`, async () => {})+ return+ }+ await this.runSerialized(formerPodKey, () => this.reconcilePodKey(formerPodKey))+ }++ /**+ * Re-reconcile only the NetworkPolicy ingress for the pod keys referenced by+ * the given hook ids. Called from the Host-watch fan-out so adding/removing a+ * Host reference re-computes which mcp-hosts the shared pod admits (§5).+ */+ async reconcileNetworkPoliciesForHooks(hookNames: string[]): Promise<void> {+ const podKeys = new Set<string>()+ for (const name of hookNames) {+ const hook = this.hooks.get(name)+ if (!hook) continue+ const key = computePodKey(hook)+ if (key) podKeys.add(key)+ }+ for (const podKey of podKeys) {+ await this.runSerialized(podKey, async () => {+ const members = this.membersForPodKey(podKey)+ if (members.length === 0) return+ const img = members[0].spec.target.image!+ const egress = await this.buildEgressRules(img)+ // A now-invalid egress binding must not silently re-open the pod; the+ // ingress refresh still applies (fail-closed egress on the next full+ // reconcile). Apply ingress with whatever egress currently validates.+ await this.ensureNetworkPolicy(podKey, members, egress.failures.length ? [] : egress.rules)+ })+ }+ }++ /**+ * Full reconciliation pass (startup + periodic resync). Reconciles every+ * distinct pod key once, every non-image hook, then sweeps label-orphaned+ * `llmhook-*` workloads whose pod key has zero live members (§3).+ */+ async fullReconcile(hooks: LlmHookCRD[]): Promise<void> {+ console.log(`${LOG} Running full reconciliation for ${hooks.length} LlmHook(s)`)+ const imagePodKeys = new Set<string>()+ for (const hook of hooks) {+ const kind = classifyTarget(hook)+ if (kind === 'image') {+ const key = computePodKey(hook)+ if (key) imagePodKeys.add(key)+ } else {+ await this.reconcile(hook)+ }+ }+ for (const podKey of imagePodKeys) {+ await this.runSerialized(podKey, () => this.reconcilePodKey(podKey))+ }+ await this.sweepOrphanedWorkloads()+ console.log(`${LOG} Full reconciliation complete`)+ }++ // ─── Members / reverse index ────────────────────────────────────────++ /** All cached image-target LlmHooks whose pod key equals `podKey`. */+ private membersForPodKey(podKey: string): LlmHookCRD[] {+ return [...this.hooks.values()]+ .filter(h => classifyTarget(h) === 'image' && computePodKey(h) === podKey)+ .sort((a, b) => a.name.localeCompare(b.name))+ }++ /** Hosts whose guardrails reference any of the given member hooks (§5). */+ private referencingHosts(members: LlmHookCRD[]): HostCRD[] {+ const memberNames = new Set(members.map(m => m.name))+ return [...this.hosts.values()]+ .filter(h => referencedHookIds(h).some(id => memberNames.has(id)))+ .sort((a, b) => a.name.localeCompare(b.name))+ }++ // ─── Core pod-key reconcile ─────────────────────────────────────────++ private async reconcilePodKey(podKey: string): Promise<void> {+ const members = this.membersForPodKey(podKey)++ // Reference count == live members. Zero → tear the workload down (§3).+ if (members.length === 0) {+ await this.gcPodKey(podKey)+ return+ }++ const rep = members[0]+ const img = rep.spec.target.image!++ // Path uniqueness within the pod key (§1.2): losers fail closed, winners+ // are still served.+ const duplicatePathNames = this.duplicatePathMembers(members)++ // Secret gate (mirror McpServer secret gate).+ const secret = await this.validateSecret(img)+ if (!secret.ok) {+ for (const m of members) {+ await this.writeStatus(m, condition('False', 'SecretNotFound', secret.message))+ }+ return+ }++ // Egress hardening (§5 caveat): apply McpServer-grade SSRF/private-range+ // validation to the looser LlmHook.egressBindings; a rejected binding fails+ // the whole pod key closed (egress is a pod-level boundary).+ const egress = await this.buildEgressRules(img)+ if (egress.failures.length > 0) {+ const message = egress.failures.join('; ')+ for (const m of members) {+ await this.writeStatus(m, condition('False', 'InvalidEgress', message))+ }+ return+ }++ // Ensure the shared workload (idempotent create-then-409 replace).+ try {+ await this.ensureDeployment(podKey, members, secret.revision)+ await this.ensureService(podKey, img.port)+ await this.ensureNetworkPolicy(podKey, members, egress.rules)+ } catch (err) {+ const message = `Resource sync failed: ${errMsg(err)}`+ for (const m of members) {+ await this.writeStatus(m, condition('False', 'ReconcileError', message))+ }+ return+ }++ // Readiness + observedDigest → per-member status (each member is a distinct+ // CR and gets its own status even though they share a pod, §6).+ const name = podKeyResourceName(podKey)+ const rollout = await this.readDeploymentRollout(name)+ const observedDigest = await this.readObservedDigest(podKey)+ const nowIso = new Date().toISOString()+ const extras: StatusExtras = {+ observedDigest,+ readyReplicas: rollout.readyReplicas,+ ...(rollout.ready ? { lastReconciled: nowIso } : {}),+ }++ for (const m of members) {+ if (duplicatePathNames.has(m.name)) {+ await this.writeStatus(+ m,+ condition(+ 'False',+ 'DuplicatePath',+ `spec.path "${m.spec.path ?? '/'}" collides with another co-located hook sharing this pod`+ ),+ extras+ )+ continue+ }+ await this.writeStatus(+ m,+ rollout.ready+ ? condition('True', 'Ready', 'Hook deployment ready')+ : condition('Unknown', 'Deploying', `Waiting for hook pod: ${rollout.detail}`),+ extras+ )+ }+ }++ private async reconcileNonImage(hook: LlmHookCRD, kind: TargetKind): Promise<void> {+ // service / remote targets deploy nothing: mcp-host dials them directly.+ if (kind === 'invalid') {+ await this.writeStatus(+ hook,+ condition('False', 'ReconcileError', 'target must be exactly one of image, service, remote')+ )+ return+ }+ await this.writeStatus(+ hook,+ condition('True', 'NoWorkload', 'No workload deployed for service/remote target'),+ { lastReconciled: new Date().toISOString() }+ )+ }++ /**+ * Names of members that lose a path collision. The first member (by sorted+ * name) to claim a path wins; later members claiming the same path are+ * flagged DuplicatePath and not routed.+ */+ private duplicatePathMembers(members: LlmHookCRD[]): Set<string> {+ const seen = new Map<string, string>()+ const losers = new Set<string>()+ for (const m of members) {+ const path = m.spec.path ?? '/'+ if (seen.has(path)) {+ losers.add(m.name)+ } else {+ seen.set(path, m.name)+ }+ }+ return losers+ }++ // ─── Secret validation (mirror validateSecret, credentials revision) ──++ private async validateSecret(img: LlmHookImageTarget): Promise<SecretValidation> {+ if (!img.envSecret) return { ok: true, revision: '' }+ try {+ const secret = await this.coreApi.readNamespacedSecret({+ name: img.envSecret,+ namespace: config.llmHooksNamespace,+ })+ const data = secret.data || {}+ const revision = createHash('sha256')+ .update(+ JSON.stringify(+ Object.keys(data)+ .sort()+ .map(k => [k, data[k]])+ )+ )+ .digest('hex')+ return { ok: true, revision }+ } catch (error) {+ const code = getErrorCode(error)+ if (code === 404) {+ return {+ ok: false,+ message: `Secret "${img.envSecret}" not found in namespace "${config.llmHooksNamespace}"`,+ }+ }+ return {+ ok: false,+ message: `Failed to read Secret "${img.envSecret}": ${errMsg(error)}`,+ }+ }+ }++ // ─── Egress builder (reuse NP reconciler's SSRF/private-range validators) ──++ private async buildEgressRules(img: LlmHookImageTarget): Promise<EgressBuild> {+ const rules: k8s.V1NetworkPolicyEgressRule[] = []+ const failures: string[] = []+ for (const binding of img.egressBindings ?? []) {+ const ports: k8s.V1NetworkPolicyPort[] =+ binding.ports && binding.ports.length > 0+ ? binding.ports.map(p => ({ port: p, protocol: 'TCP' as const }))+ : [+ { port: 443, protocol: 'TCP' },+ { port: 80, protocol: 'TCP' },+ ]++ if (binding.cidr) {+ if (!isAllowedExternalEgressCidr(binding.cidr)) {+ failures.push(+ `CIDR "${binding.cidr}" overlaps private, metadata, link-local, multicast, documentation, or reserved ranges`+ )+ continue+ }+ rules.push({ to: [{ ipBlock: { cidr: binding.cidr } }], ports })+ continue+ }++ if (binding.toFQDN) {+ if (!isPublicDnsHostname(binding.toFQDN)) {+ failures.push(+ `hostname "${binding.toFQDN}" is private, internal, metadata, local, or otherwise disallowed`+ )+ continue+ }+ try {+ const ips = [...new Set(await dns.resolve4(binding.toFQDN))].sort()+ if (ips.length === 0) {+ failures.push(`hostname "${binding.toFQDN}" resolved to no IPv4 addresses`)+ continue+ }+ const cidrs = ips.map(ip => `${ip}/32`)+ const disallowed = cidrs.filter(+ c => isIP(c.split('/')[0]) !== 4 || !isAllowedExternalEgressCidr(c)+ )+ if (disallowed.length > 0) {+ failures.push(+ `hostname "${binding.toFQDN}" resolved disallowed address(es): ${disallowed.join(', ')}`+ )+ continue+ }+ for (const cidr of cidrs) rules.push({ to: [{ ipBlock: { cidr } }], ports })+ } catch (err) {+ failures.push(`failed to resolve hostname "${binding.toFQDN}": ${errMsg(err)}`)+ }+ continue+ }++ failures.push('egress binding must declare toFQDN or cidr')+ }+ return { rules, failures }+ }++ // ─── Resource builders ──────────────────────────────────────────────++ private podKeyLabels(podKey: string): Record<string, string> {+ return {+ app: podKeyResourceName(podKey),+ [MANAGED_BY_LABEL]: MANAGED_BY_VALUE,+ [HOOK_PODKEY_LABEL]: podKey,+ }+ }++ private buildDeployment(+ podKey: string,+ members: LlmHookCRD[],+ credentialsRevision: string+ ): k8s.V1Deployment {+ const img = members[0].spec.target.image!+ const name = podKeyResourceName(podKey)+ const labels = this.podKeyLabels(podKey)++ // Defense in depth: the CRD enum already bounds addCapabilities to the+ // workflow-recipe allowlist, but strip anything outside it at reconcile too.+ const addCapabilities = (img.security?.addCapabilities ?? []).filter(cap => {+ if (isWorkflowRecipeDefaultAllowedCapability(cap)) return true+ console.warn(`${LOG} pod key ${podKey}: capability "${cap}" stripped (forbidden)`)+ return false+ })++ const hardenedContainerSecurityContext: k8s.V1SecurityContext = {+ allowPrivilegeEscalation: false,+ runAsNonRoot: true,+ runAsUser: 1000,+ runAsGroup: 1000,+ capabilities: {+ drop: ['ALL'],+ ...(addCapabilities.length ? { add: addCapabilities } : {}),+ },+ seccompProfile: { type: 'RuntimeDefault' },+ }++ return {+ apiVersion: 'apps/v1',+ kind: 'Deployment',+ metadata: { name, namespace: config.llmHooksNamespace, labels },+ spec: {+ replicas: 1,+ selector: { matchLabels: { app: name } },+ template: {+ metadata: {+ labels,+ // Rotating the hook's envSecret changes this digest → pod template+ // → rolling restart (mirror McpServer credentials-revision).+ ...(credentialsRevision && {+ annotations: { [CREDENTIALS_REVISION_ANNOTATION]: credentialsRevision },+ }),+ },+ spec: {+ automountServiceAccountToken: false,+ enableServiceLinks: false,+ securityContext: {+ runAsNonRoot: true,+ runAsUser: 1000,+ runAsGroup: 1000,+ seccompProfile: { type: 'RuntimeDefault' },+ },+ ...(img.imagePullSecrets?.length+ ? { imagePullSecrets: img.imagePullSecrets.map(n => ({ name: n })) }+ : {}),+ containers: [+ {+ name: 'hook',+ image: img.ref,+ imagePullPolicy: config.mcpServerImagePullPolicy,+ ports: [{ name: 'http', containerPort: img.port, protocol: 'TCP' }],+ // envSecret injects the hook's OWN credentials (whole Secret).+ ...(img.envSecret ? { envFrom: [{ secretRef: { name: img.envSecret } }] } : {}),+ securityContext: hardenedContainerSecurityContext,+ livenessProbe: {+ tcpSocket: { port: 'http' as unknown as IntOrString },+ initialDelaySeconds: 10,+ periodSeconds: 15,+ },+ readinessProbe: {+ tcpSocket: { port: 'http' as unknown as IntOrString },+ initialDelaySeconds: 5,+ periodSeconds: 10,+ },+ resources: {+ requests: { memory: '64Mi', cpu: '50m' },+ limits: { memory: '256Mi', cpu: '500m' },+ },+ },+ ],+ },+ },+ },+ }+ }++ private buildService(podKey: string, port: number): k8s.V1Service {+ const name = podKeyResourceName(podKey)+ return {+ apiVersion: 'v1',+ kind: 'Service',+ metadata: { name, namespace: config.llmHooksNamespace, labels: this.podKeyLabels(podKey) },+ spec: {+ type: 'ClusterIP',+ ports: [{ port, targetPort: 'http' as IntOrString, protocol: 'TCP', name: 'http' }],+ selector: { app: name },+ },+ }+ }++ private buildNetworkPolicy(+ podKey: string,+ members: LlmHookCRD[],+ egressRules: k8s.V1NetworkPolicyEgressRule[]+ ): k8s.V1NetworkPolicy {+ const name = podKeyResourceName(podKey)+ const port = members[0].spec.target.image!.port+ const hosts = this.referencingHosts(members)++ // Ingress admits EXACTLY the mcp-hosts whose Host CR references any+ // co-located member (Host→LlmHook reverse index, §5). No referencing host+ // ⇒ empty ingress ⇒ deny all (fail-closed until a Host references it).+ const ingress: k8s.V1NetworkPolicyIngressRule[] =+ hosts.length > 0+ ? [+ {+ _from: hosts.map(h => ({+ namespaceSelector: {+ matchLabels: { 'kubernetes.io/metadata.name': config.hostNamespace },+ },+ podSelector: { matchLabels: { [HOST_LABEL]: h.name } },+ })),+ ports: [{ port, protocol: 'TCP' }],+ },+ ]+ : []++ const policyTypes: Array<'Ingress' | 'Egress'> = ['Ingress']+ if (egressRules.length > 0) policyTypes.push('Egress')++ return {+ apiVersion: 'networking.k8s.io/v1',+ kind: 'NetworkPolicy',+ metadata: {+ name,+ namespace: config.llmHooksNamespace,+ labels: this.podKeyLabels(podKey),+ // Member CR names are recorded as an ANNOTATION, not a label: co-located+ // members are comma-joined, and commas are invalid in a label value (the+ // apiserver 422s), which would break exactly the multi-member digest-dedup+ // case. Annotations allow commas and long values.+ annotations: { 'clerum.io/llmhook-members': members.map(m => m.name).join(',') },+ },+ spec: {+ podSelector: { matchLabels: { [HOOK_PODKEY_LABEL]: podKey } },+ policyTypes,+ ingress,+ ...(egressRules.length > 0 ? { egress: egressRules } : {}),+ },+ }+ }++ // ─── Apply helpers (create-then-409 replaceWithConflictRetry) ─────────++ private async ensureDeployment(+ podKey: string,+ members: LlmHookCRD[],+ credentialsRevision: string+ ): Promise<void> {+ const deployment = this.buildDeployment(podKey, members, credentialsRevision)+ const name = deployment.metadata!.name!+ try {+ await this.appsApi.createNamespacedDeployment({+ namespace: config.llmHooksNamespace,+ body: deployment,+ })+ console.log(`${LOG} Created Deployment "${name}"`)+ return+ } catch (error) {+ if (getErrorCode(error) !== 409) throw error+ }+ await replaceWithConflictRetry({+ description: `Deployment "${name}"`,+ logPrefix: LOG,+ body: deployment,+ mergeExisting: preserveDeploymentAnnotations,+ read: () =>+ this.appsApi.readNamespacedDeployment({ name, namespace: config.llmHooksNamespace }),+ replace: body =>+ this.appsApi.replaceNamespacedDeployment({+ name,+ namespace: config.llmHooksNamespace,+ body,+ }),+ })+ }++ private async ensureService(podKey: string, port: number): Promise<void> {+ const service = this.buildService(podKey, port)+ const name = service.metadata!.name!+ try {+ await this.coreApi.createNamespacedService({+ namespace: config.llmHooksNamespace,+ body: service,+ })+ console.log(`${LOG} Created Service "${name}"`)+ return+ } catch (error) {+ if (getErrorCode(error) !== 409) throw error+ }+ await replaceWithConflictRetry({+ description: `Service "${name}"`,+ logPrefix: LOG,+ body: service,+ mergeExisting: preserveServiceAssignedFields,+ read: () => this.coreApi.readNamespacedService({ name, namespace: config.llmHooksNamespace }),+ replace: body =>+ this.coreApi.replaceNamespacedService({ name, namespace: config.llmHooksNamespace, body }),+ })+ }++ private async ensureNetworkPolicy(+ podKey: string,+ members: LlmHookCRD[],+ egressRules: k8s.V1NetworkPolicyEgressRule[]+ ): Promise<void> {+ const policy = this.buildNetworkPolicy(podKey, members, egressRules)+ const name = policy.metadata!.name!+ try {+ await this.networkingApi.createNamespacedNetworkPolicy({+ namespace: config.llmHooksNamespace,+ body: policy,+ })+ console.log(`${LOG} Created NetworkPolicy "${name}"`)+ return+ } catch (error) {+ if (getErrorCode(error) !== 409) throw error+ }+ await replaceWithConflictRetry({+ description: `NetworkPolicy "${name}"`,+ logPrefix: LOG,+ body: policy,+ mergeExisting: preserveObjectAnnotations,+ read: () =>+ this.networkingApi.readNamespacedNetworkPolicy({+ name,+ namespace: config.llmHooksNamespace,+ }),+ replace: body =>+ this.networkingApi.replaceNamespacedNetworkPolicy({+ name,+ namespace: config.llmHooksNamespace,+ body,+ }),+ })+ }++ // ─── Reference-counted, label-owned GC (§3) ─────────────────────────++ private isHccOwned(+ resource: { metadata?: { labels?: Record<string, string> } },+ podKey: string+ ): boolean {+ const labels = resource.metadata?.labels ?? {}+ return labels[MANAGED_BY_LABEL] === MANAGED_BY_VALUE && labels[HOOK_PODKEY_LABEL] === podKey+ }++ private async gcPodKey(podKey: string): Promise<void> {+ const name = podKeyResourceName(podKey)+ const ns = config.llmHooksNamespace+ // Deployment+ try {+ const dep = await this.appsApi.readNamespacedDeployment({ name, namespace: ns })+ if (this.isHccOwned(dep, podKey)) {+ await this.appsApi.deleteNamespacedDeployment({ name, namespace: ns })+ console.log(`${LOG} Deleted Deployment "${name}" (0 members)`)+ } else {+ console.warn(`${LOG} Skipping Deployment "${name}" delete — not HCC-owned`)+ }+ } catch (error) {+ if (getErrorCode(error) !== 404) throw error+ }+ // Service+ try {+ const svc = await this.coreApi.readNamespacedService({ name, namespace: ns })+ if (this.isHccOwned(svc, podKey)) {+ await this.coreApi.deleteNamespacedService({ name, namespace: ns })+ console.log(`${LOG} Deleted Service "${name}" (0 members)`)+ } else {+ console.warn(`${LOG} Skipping Service "${name}" delete — not HCC-owned`)+ }+ } catch (error) {+ if (getErrorCode(error) !== 404) throw error+ }+ // NetworkPolicy+ try {+ const np = await this.networkingApi.readNamespacedNetworkPolicy({ name, namespace: ns })+ if (this.isHccOwned(np, podKey)) {+ await this.networkingApi.deleteNamespacedNetworkPolicy({ name, namespace: ns })+ console.log(`${LOG} Deleted NetworkPolicy "${name}" (0 members)`)+ } else {+ console.warn(`${LOG} Skipping NetworkPolicy "${name}" delete — not HCC-owned`)+ }+ } catch (error) {+ if (getErrorCode(error) !== 404) throw error+ }+ }++ /**+ * Startup / periodic orphan GC (§3): list all `llmhook-*` Deployments by+ * label and delete any whose hook-pod-key has zero live members — covers pods+ * orphaned by a missed delete event or a crash between CR-delete and+ * workload-delete. Mandatory (no owner-ref cascade to rely on).+ */+ private async sweepOrphanedWorkloads(): Promise<void> {+ let deployments: k8s.V1Deployment[]+ try {+ const resp = await this.appsApi.listNamespacedDeployment({+ namespace: config.llmHooksNamespace,+ labelSelector: `${MANAGED_BY_LABEL}=${MANAGED_BY_VALUE}`,+ })+ deployments = resp.items ?? []+ } catch (error) {+ console.error(`${LOG} Orphan sweep: failed to list Deployments:`, error)+ return+ }+ for (const dep of deployments) {+ const podKey = dep.metadata?.labels?.[HOOK_PODKEY_LABEL]+ if (!podKey) continue+ if (this.membersForPodKey(podKey).length > 0) continue+ console.log(`${LOG} Orphan sweep: pod key ${podKey} has 0 members — deleting workload`)+ await this.runSerialized(podKey, () => this.gcPodKey(podKey))+ }+ }++ // ─── Readiness + observedDigest ─────────────────────────────────────++ private async readDeploymentRollout(+ name: string+ ): Promise<{ ready: boolean; readyReplicas: number; detail: string }> {+ try {+ const dep = await this.appsApi.readNamespacedDeployment({+ name,+ namespace: config.llmHooksNamespace,+ })+ const desired = dep.spec?.replicas ?? 1+ const readyReplicas = dep.status?.readyReplicas ?? 0+ return {+ ready: readyReplicas >= desired,+ readyReplicas,+ detail: `ready ${readyReplicas}/${desired}`,+ }+ } catch (error) {+ return { ready: false, readyReplicas: 0, detail: `Deployment read failed: ${errMsg(error)}` }+ }+ }++ /**+ * observedDigest from the LIVE pod's container status (§6). Reflects the+ * digest ACTUALLY running (not merely the intended one), which is what+ * mcp-host binds Host.spec.guardrails.hooks[].digest against and fails closed+ * on. Needs `pods` get/list RBAC in llm-hooks. Empty string when unresolved.+ */+ private async readObservedDigest(podKey: string): Promise<string> {+ try {+ const pods = await this.coreApi.listNamespacedPod({+ namespace: config.llmHooksNamespace,+ labelSelector: `${HOOK_PODKEY_LABEL}=${podKey}`,+ })+ for (const pod of pods.items ?? []) {+ for (const cs of pod.status?.containerStatuses ?? []) {+ const digest = extractSha256(cs.imageID) ?? extractSha256(cs.image)+ if (digest) return digest+ }+ }+ } catch (error) {+ console.warn(`${LOG} Failed to read observedDigest for pod key ${podKey}:`, error)+ }+ return ''+ }++ // ─── Status subresource writer (mirror writeStatusCondition) ──────────++ /**+ * Write (merge) the `Ready` condition plus flat observedDigest/readyReplicas/+ * lastReconciled on an LlmHook, fenced by a resourceVersion `test` op with+ * retry-on-409/422 so a concurrent writer never clobbers the other's fields.+ * Short-circuits when nothing changed (prevents a status→watch→reconcile loop).+ */+ private async writeStatus(+ hook: LlmHookCRD,+ condition: Omit<LlmHookCondition, 'lastTransitionTime'>,+ extras: StatusExtras = {}+ ): Promise<void> {+ const MAX_ATTEMPTS = 4+ for (let attempt = 1; attempt <= MAX_ATTEMPTS; attempt++) {+ const now = new Date().toISOString()+ let current: { metadata?: { resourceVersion?: string }; status?: LlmHookStatus }+ try {+ current = (await this.customApi.getNamespacedCustomObjectStatus({+ group: GROUP,+ version: VERSION,+ namespace: hook.namespace,+ plural: PLURAL_LLMHOOKS,+ name: hook.name,+ })) as { metadata?: { resourceVersion?: string }; status?: LlmHookStatus }+ } catch (error) {+ if (getErrorCode(error) === 404) return+ console.warn(`${LOG} Failed to read status for "${hook.name}":`, error)+ return+ }++ const resourceVersion = current.metadata?.resourceVersion+ const hasStatusObject = typeof current.status === 'object' && current.status !== null+ const existing = current.status ?? {}+ const existingConditions = existing.conditions ?? []++ const prior = existingConditions.find(c => c.type === condition.type)+ const lastTransitionTime =+ prior && prior.status === condition.status ? (prior.lastTransitionTime ?? now) : now+ const merged: LlmHookCondition = {+ type: condition.type,+ status: condition.status,+ reason: condition.reason,+ message: condition.message,+ lastTransitionTime,+ ...(hook.generation !== undefined && { observedGeneration: hook.generation }),+ }+ const nextConditions = [...existingConditions.filter(c => c.type !== condition.type), merged]++ const nextStatus: LlmHookStatus = {+ ...existing,+ conditions: nextConditions,+ ...(extras.observedDigest !== undefined && { observedDigest: extras.observedDigest }),+ ...(extras.readyReplicas !== undefined && { readyReplicas: extras.readyReplicas }),+ ...(extras.lastReconciled !== undefined && { lastReconciled: extras.lastReconciled }),+ }++ // No-op gate: skip the patch when nothing meaningful changed, so a status+ // write does not self-trigger an endless reconcile loop.+ const conditionUnchanged =+ prior !== undefined &&+ prior.status === condition.status &&+ prior.reason === condition.reason &&+ prior.message === condition.message+ const digestUnchanged =+ extras.observedDigest === undefined || existing.observedDigest === extras.observedDigest+ const replicasUnchanged =+ extras.readyReplicas === undefined || existing.readyReplicas === extras.readyReplicas+ if (conditionUnchanged && digestUnchanged && replicasUnchanged) return++ const statusPatch = [+ ...(resourceVersion+ ? [{ op: 'test', path: '/metadata/resourceVersion', value: resourceVersion }]+ : []),+ hasStatusObject+ ? { op: 'add', path: '/status/conditions', value: nextConditions }+ : { op: 'add', path: '/status', value: nextStatus },+ ...(hasStatusObject && extras.observedDigest !== undefined+ ? [{ op: 'add', path: '/status/observedDigest', value: extras.observedDigest }]+ : []),+ ...(hasStatusObject && extras.readyReplicas !== undefined+ ? [{ op: 'add', path: '/status/readyReplicas', value: extras.readyReplicas }]+ : []),+ ...(hasStatusObject && extras.lastReconciled !== undefined+ ? [{ op: 'add', path: '/status/lastReconciled', value: extras.lastReconciled }]+ : []),+ ]++ try {+ await this.customApi.patchNamespacedCustomObjectStatus({+ group: GROUP,+ version: VERSION,+ namespace: hook.namespace,+ plural: PLURAL_LLMHOOKS,+ name: hook.name,+ body: statusPatch,+ })+ return+ } catch (error) {+ if (getErrorCode(error) === 404) return+ const code = getErrorCode(error)+ if ((code === 409 || code === 422) && attempt < MAX_ATTEMPTS) continue+ console.warn(`${LOG} Failed to write status on "${hook.name}":`, error)+ return+ }+ }+ }+}++function condition(+ status: 'True' | 'False' | 'Unknown',+ reason: LlmHookReadyReason,+ message: string+): Omit<LlmHookCondition, 'lastTransitionTime'> {+ return { type: 'Ready', status, reason, message }+}++function extractSha256(ref: string | undefined): string | undefined {+ if (!ref) return undefined+ const m = ref.match(/sha256:[a-f0-9]{64}/)+ return m ? m[0] : undefined+}++function errMsg(error: unknown): string {+ return error instanceof Error ? error.message : String(error)+}diff --git a/host-context-controller/src/networkPolicyReconciler.ts b/host-context-controller/src/networkPolicyReconciler.tsindex aa19d54ca..b1a180b32 100644--- a/host-context-controller/src/networkPolicyReconciler.ts+++ b/host-context-controller/src/networkPolicyReconciler.ts@@ -103,12 +103,12 @@ function cidrOverlaps(left: string, right: string): boolean {return a.start <= b.end && b.start <= a.end}-function isAllowedExternalEgressCidr(cidr: string): boolean {+export function isAllowedExternalEgressCidr(cidr: string): boolean {if (!cidrRange(cidr)) return falsereturn !PUBLIC_EGRESS_EXCEPT_CIDRS.some(blocked => cidrOverlaps(cidr, blocked))}-function isPublicDnsHostname(host: string): boolean {+export function isPublicDnsHostname(host: string): boolean {if (host !== host.trim()) return falseif (host !== host.toLowerCase()) return falseif (host.includes('*') || host.includes('/') || host.includes(':')) return falsediff --git a/host-context-controller/src/rbacManifest.test.ts b/host-context-controller/src/rbacManifest.test.tsindex 9c775ee5a..1abfab085 100644--- a/host-context-controller/src/rbacManifest.test.ts+++ b/host-context-controller/src/rbacManifest.test.ts@@ -19,6 +19,42 @@ describe('host-context-controller RBAC manifest', () => {expect(mcpServerRule?.[1]).toContain('"patch"')})+ it('can reconcile LlmHook workloads and read pods in the llm-hooks namespace', () => {+ const manifest = readFileSync(+ path.join(__dirname, '../../deploy/base/llm-hooks/rbac.yaml'),+ 'utf8'+ )++ const role = manifest+ .split('name: host-context-controller\n namespace: llm-hooks\nrules:')[1]+ ?.split('---')[0]++ expect(role).toBeTruthy()++ // llmhooks: watch + patch (status write-back path)+ const llmhooksRule = role?.match(/resources: \["llmhooks"\]\n\s+verbs: \[([^\]]+)\]/)+ expect(llmhooksRule?.[1]).toContain('"watch"')+ expect(llmhooksRule?.[1]).toContain('"patch"')++ // llmhooks/status: patch+ const statusRule = role?.match(/resources: \["llmhooks\/status"\]\n\s+verbs: \[([^\]]+)\]/)+ expect(statusRule?.[1]).toContain('"patch"')++ // pods get/list — required for status.observedDigest (live pod image)+ const podsRule = role?.match(/resources: \["pods"\]\n\s+verbs: \[([^\]]+)\]/)+ expect(podsRule?.[1]).toContain('"get"')+ expect(podsRule?.[1]).toContain('"list"')++ // networkpolicies + deployments + services managed by HCC+ expect(role).toContain('resources: ["networkpolicies"]')+ expect(role).toContain('resources: ["deployments"]')+ expect(role).toContain('resources: ["services"]')++ // Bound to the HCC ServiceAccount in control-plane+ expect(manifest).toContain('kind: ServiceAccount')+ expect(manifest).toMatch(/name: host-context-controller\n\s+namespace: control-plane/)+ })+it('can reconcile GFS writer PodDisruptionBudgets in the gfs namespace', () => {const manifest = readFileSync(path.join(__dirname, '../../deploy/base/gfs/rbac.yaml'), 'utf8')diff --git a/host-context-controller/src/types.ts b/host-context-controller/src/types.tsindex a7488dc7d..dba6a5044 100644--- a/host-context-controller/src/types.ts+++ b/host-context-controller/src/types.ts@@ -386,6 +386,45 @@ export interface HostWorkflowControlSpec {scopes?: HostWorkflowControlScope[]}+/**+ * A single installed-hook reference inside Host.spec.guardrails.hooks[phase].+ * `id` is the LlmHook CR name (llm-hooks namespace); `digest` is the expected+ * image digest mcp-host binds against status.observedDigest (§8.2).+ */+export interface HostGuardrailHookRef {+ id: string+ digest?: string+}++/**+ * Host.spec.guardrails.hooks — installed LlmHook references grouped by+ * lifecycle phase. Only the hook `id`s matter to HCC: they form the+ * Host→LlmHook reverse index that drives the shared hook pod's NetworkPolicy+ * ingress set (guardrails phase-4 design §5).+ */+export interface HostGuardrailHooks {+ preToolUse?: HostGuardrailHookRef[]+ postToolUse?: HostGuardrailHookRef[]+ preCall?: HostGuardrailHookRef[]+ moderate?: HostGuardrailHookRef[]+ postCallSuccess?: HostGuardrailHookRef[]+ onError?: HostGuardrailHookRef[]+}++/**+ * Host.spec.guardrails — additive, opt-in guardrail policy (guardrails spec+ * §5). HCC only reads `hooks` (for the reverse index); the loosely-typed+ * `rules`/`builtins`/ceiling fields are owned by mcp-host/control-api.+ */+export interface HostGuardrailsSpec {+ hooks?: HostGuardrailHooks+ rules?: unknown[]+ builtins?: unknown[]+ minInstalledHookTrustLevel?: 'low' | 'mid' | 'high'+ approvalPolicies?: string[]+ capabilityCeiling?: string[]+}+export interface HostSpec {host: stringcontextRef: string@@ -396,6 +435,7 @@ export interface HostSpec {desktop?: HostDesktopSpeclifecycle?: HostLifecycleSpecworkflowControl?: HostWorkflowControlSpec+ guardrails?: HostGuardrailsSpec}export type HostLifecycleState = 'active' | 'draining' | 'suspended'@@ -542,3 +582,103 @@ export interface ErrorResponse {error: stringmessage: string}++// ─── LlmHook CRD ─────────────────────────────────────────────────────────────+//+// An installed guardrail hook mcp-host calls over the /v1 protocol (guardrails+// spec §8). host-context-controller reconciles `image`-target hooks into a+// shared Deployment+Service+NetworkPolicy in the llm-hooks namespace+// (digest-dedup: hooks sharing a pod key co-locate on one pod, routed by+// spec.path). `service` and `remote` targets deploy no workload (status-only).++/** External egress a hook pod is permitted (looser CRD shape than McpServer). */+export interface LlmHookEgressBinding {+ toFQDN?: string+ cidr?: string+ ports?: number[]+}++/** Security context overrides for a hook pod. */+export interface LlmHookSecurity {+ addCapabilities?: string[]+}++/** In-cluster image hook target — the only target HCC deploys a workload for. */+export interface LlmHookImageTarget {+ ref: string+ port: number+ imagePullSecrets?: string[]+ envSecret?: string+ egressBindings?: LlmHookEgressBinding[]+ security?: LlmHookSecurity+}++/** Existing in-cluster Service target — status-only, nothing deployed. */+export interface LlmHookServiceTarget {+ name: string+ namespace: string+ port: number+}++/** External HTTPS endpoint target — status-only, nothing deployed. */+export interface LlmHookRemoteTarget {+ baseUrl: string+ authHeadersSecret?: string+}++export interface LlmHookTarget {+ image?: LlmHookImageTarget+ service?: LlmHookServiceTarget+ remote?: LlmHookRemoteTarget+}++export type LlmHookLifecyclePoint = 'preCall' | 'moderate' | 'postCallSuccess' | 'onError'++export type LlmHookCapability =+ | 'may_deny'+ | 'may_rewrite'+ | 'may_substitute_result'+ | 'may_add_context'++export interface LlmHookSpec {+ target: LlmHookTarget+ path?: string+ lifecyclePoints: LlmHookLifecyclePoint[]+ order?: number+ failMode?: 'open' | 'closed'+ timeoutMs?: number+ onUnavailable?: {+ mode?: 'strict' | 'breaker'+ failureThreshold?: number+ cooldownMs?: number+ }+ capabilities?: LlmHookCapability[]+ config?: Record<string, unknown>+}++export interface LlmHookCondition {+ type: string+ status: 'True' | 'False' | 'Unknown'+ reason?: string+ message?: string+ lastTransitionTime?: string+ observedGeneration?: number+}++export interface LlmHookStatus {+ observedDigest?: string+ readyReplicas?: number+ lastReconciled?: string+ conditions?: LlmHookCondition[]+}++export interface LlmHookCRD {+ name: string+ namespace: string+ uid?: string+ generation?: number+ annotations?: Record<string, string>+ labels?: Record<string, string>+ spec: LlmHookSpec+ status?: LlmHookStatus+}