Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure
TypeScript
feat(hcc): derive Codex scope and proxy path from target
Alfredo Lopez70d4ff4ca313
diff --git a/control-api/src/services/llmAllowedModelsConfigMap.ts b/control-api/src/services/llmAllowedModelsConfigMap.tsindex 49c325d70..1cf14bb56 100644--- a/control-api/src/services/llmAllowedModelsConfigMap.ts+++ b/control-api/src/services/llmAllowedModelsConfigMap.ts@@ -19,8 +19,13 @@*/import * as k8s from '@kubernetes/client-node'import { createHash } from 'node:crypto'+import { config } from '../config.js'import type { DbClient } from '../db.js'import { pool } from '../db.js'+import {+ type CodexSubscriptionSafeConnection,+ getSafeCodexSubscriptionConnection,+} from './codexSubscriptionConnection.js'import { type AllowedModelEntry, listEnabledGroupedByProvider } from './llmAllowedModels.js'// CROSS-SERVICE CONTRACT: producer side of the allowlist ConfigMap. Consumers@@ -29,6 +34,49 @@ import { type AllowedModelEntry, listEnabledGroupedByProvider } from './llmAllow// modelConfigHandler.ts, ALLOWLIST_CONFIGMAP_NAME). Keep name + data format in sync.export const ALLOWED_MODELS_CONFIGMAP_NAME = 'clerum-llm-allowed-models'export const CONTENT_HASH_ANNOTATION = 'clerum.io/content-hash'+export const CATALOG_REVISION_ANNOTATION = 'clerum.io/catalog-revision'+export const CONNECTION_REVISION_ANNOTATION = 'clerum.io/connection-revision'+export const CODEX_CONNECTION_STATUS_ANNOTATION = 'clerum.io/codex-connection-status'+export const CODEX_ENABLED_ANNOTATION = 'clerum.io/codex-enabled'++const KNOWN_CONNECTION_STATUSES = new Set([+ 'disconnected',+ 'connecting',+ 'connected',+ 'reauth_required',+ 'revoked',+])++export function mapCodexConnectionStatusForSnapshot(+ connection: CodexSubscriptionSafeConnection | null+): 'connected' | 'disconnected' | 'reauth-required' | 'unavailable' {+ if (!connection || !KNOWN_CONNECTION_STATUSES.has(connection.status)) return 'disconnected'+ if (connection.status === 'reauth_required' || connection.catalogStatus === 'auth-rejected') {+ return 'reauth-required'+ }+ if (connection.catalogStatus === 'unavailable') return 'unavailable'+ if (connection.status === 'connected' && connection.catalogStatus === 'ready') return 'connected'+ return 'disconnected'+}++export function buildCodexReadinessAnnotations(+ connection: CodexSubscriptionSafeConnection | null+): Record<string, string> {+ const annotations: Record<string, string> = {+ [CODEX_ENABLED_ANNOTATION]: config.codexSubscriptionEnabled ? 'true' : 'false',+ [CODEX_CONNECTION_STATUS_ANNOTATION]: mapCodexConnectionStatusForSnapshot(connection),+ }+ if (+ connection &&+ KNOWN_CONNECTION_STATUSES.has(connection.status) &&+ Number.isInteger(connection.catalogRevision) &&+ Number.isInteger(connection.credentialRevision)+ ) {+ annotations[CATALOG_REVISION_ANNOTATION] = String(connection.catalogRevision)+ annotations[CONNECTION_REVISION_ANNOTATION] = String(connection.credentialRevision)+ }+ return annotations+}const MANAGED_BY_LABEL = 'clerum.io/managed-by'@@ -43,6 +91,14 @@ export interface AllowedModelsConfigMapMaterializer {* ordered by the query (provider, model), so the serialized form — and thus the* hash — is stable for a given allowlist state.*/+async function loadCodexConnection(db: DbClient): Promise<CodexSubscriptionSafeConnection | null> {+ try {+ return await getSafeCodexSubscriptionConnection(db)+ } catch {+ return null+ }+}+export function buildConfigMapData(grouped: Record<string, AllowedModelEntry[]>): {data: Record<string, string>contentHash: string@@ -78,10 +134,11 @@ export class LlmAllowedModelsConfigMapWriter implements AllowedModelsConfigMapMaasync materialize(db: DbClient = pool): Promise<void> {const grouped = await listEnabledGroupedByProvider(db)const { data, contentHash } = buildConfigMapData(grouped)+ const readiness = buildCodexReadinessAnnotations(await loadCodexConnection(db))let lastError: unknownfor (let attempt = 1; attempt <= this.maxAttempts; attempt++) {try {- await this.writeOnce(data, contentHash)+ await this.writeOnce(data, contentHash, readiness)return} catch (err) {lastError = err@@ -91,7 +148,11 @@ export class LlmAllowedModelsConfigMapWriter implements AllowedModelsConfigMapMathrow lastError}- private async writeOnce(data: Record<string, string>, contentHash: string): Promise<void> {+ private async writeOnce(+ data: Record<string, string>,+ contentHash: string,+ readiness: Record<string, string>+ ): Promise<void> {const body: k8s.V1ConfigMap = {apiVersion: 'v1',kind: 'ConfigMap',@@ -99,7 +160,10 @@ export class LlmAllowedModelsConfigMapWriter implements AllowedModelsConfigMapManame: ALLOWED_MODELS_CONFIGMAP_NAME,namespace: this.namespace,labels: { [MANAGED_BY_LABEL]: 'control-api' },- annotations: { [CONTENT_HASH_ANNOTATION]: contentHash },+ annotations: {+ [CONTENT_HASH_ANNOTATION]: contentHash,+ ...readiness,+ },},data,}diff --git a/control-api/test/services.llmAllowedModelsConfigMap.test.ts b/control-api/test/services.llmAllowedModelsConfigMap.test.tsindex be259d9db..4a79e3cc8 100644--- a/control-api/test/services.llmAllowedModelsConfigMap.test.ts+++ b/control-api/test/services.llmAllowedModelsConfigMap.test.ts@@ -1,18 +1,52 @@import { describe, expect, it, vi } from 'vitest'import type { DbClient } from '../src/db.js'+import type { CodexSubscriptionSafeConnection } from '../src/services/codexSubscriptionConnection.js'import {ALLOWED_MODELS_CONFIGMAP_NAME,+ CATALOG_REVISION_ANNOTATION,+ CODEX_CONNECTION_STATUS_ANNOTATION,+ CODEX_ENABLED_ANNOTATION,+ CONNECTION_REVISION_ANNOTATION,CONTENT_HASH_ANNOTATION,LlmAllowedModelsConfigMapWriter,+ buildCodexReadinessAnnotations,buildConfigMapData,+ mapCodexConnectionStatusForSnapshot,} from '../src/services/llmAllowedModelsConfigMap.js'-function fakeDb(rows: Record<string, unknown>[]): DbClient {+function fakeDb(+ rows: Record<string, unknown>[],+ connectionRows: Record<string, unknown>[] = []+): DbClient {return {- query: vi.fn().mockResolvedValue({ rows, rowCount: rows.length }),+ query: vi.fn().mockImplementation((sql: string) => {+ if (String(sql).includes('codex_subscription_connections')) {+ return Promise.resolve({ rows: connectionRows, rowCount: connectionRows.length })+ }+ return Promise.resolve({ rows, rowCount: rows.length })+ }),} as unknown as DbClient}+function connectedRow(): Record<string, unknown> {+ return {+ connection_key: 'deployment-default',+ status: 'connected',+ credential_revision: 4,+ catalog_revision: 7,+ account_fingerprint: null,+ catalog_status: 'ready',+ catalog_synced_at: new Date('2026-08-20T00:00:00Z'),+ last_refresh_at: null,+ last_auth_at: new Date('2026-08-20T00:00:00Z'),+ refresh_lock_token: null,+ refresh_lock_expires_at: null,+ revoked_at: null,+ created_at: new Date('2026-08-20T00:00:00Z'),+ updated_at: new Date('2026-08-20T00:00:00Z'),+ }+}+describe('buildConfigMapData', () => {it('serializes one JSON array per provider and hashes deterministically', () => {const a = buildConfigMapData({@@ -104,9 +138,32 @@ describe('LlmAllowedModelsConfigMapWriter', () => {expect(arg.namespace).toBe('mcp-host')expect(arg.body.metadata.name).toBe(ALLOWED_MODELS_CONFIGMAP_NAME)expect(arg.body.metadata.annotations[CONTENT_HASH_ANNOTATION]).toMatch(/^[0-9a-f]{64}$/)+ expect(arg.body.metadata.annotations[CODEX_ENABLED_ANNOTATION]).toBe('false')+ expect(arg.body.metadata.annotations[CODEX_CONNECTION_STATUS_ANNOTATION]).toBe('disconnected')+ expect(arg.body.metadata.annotations[CATALOG_REVISION_ANNOTATION]).toBeUndefined()+ expect(arg.body.metadata.annotations[CONNECTION_REVISION_ANNOTATION]).toBeUndefined()expect(JSON.parse(arg.body.data.zai)[0].model).toBe('glm-4.7')})+ it('adds readiness annotations without changing the data contract', async () => {+ const coreApi = {+ createNamespacedConfigMap: vi.fn().mockResolvedValue({}),+ readNamespacedConfigMap: vi.fn(),+ replaceNamespacedConfigMap: vi.fn(),+ }+ const writer = new LlmAllowedModelsConfigMapWriter(coreApi, 'mcp-host')+ await writer.materialize(fakeDb(rows, [connectedRow()]))+ const arg = coreApi.createNamespacedConfigMap.mock.calls[0][0]+ expect(JSON.parse(arg.body.data.zai)[0]).toEqual({+ model: 'glm-4.7',+ vendor: 'Zhipu',+ })+ expect(arg.body.metadata.annotations[CODEX_CONNECTION_STATUS_ANNOTATION]).toBe('connected')+ expect(arg.body.metadata.annotations[CATALOG_REVISION_ANNOTATION]).toBe('7')+ expect(arg.body.metadata.annotations[CONNECTION_REVISION_ANNOTATION]).toBe('4')+ expect(JSON.stringify(arg.body.data)).not.toMatch(/catalogRevision|credentialRevision|status/)+ })+it('falls back to read + replace on a 409 conflict', async () => {const coreApi = {createNamespacedConfigMap: vi@@ -151,3 +208,50 @@ describe('LlmAllowedModelsConfigMapWriter', () => {expect(coreApi.createNamespacedConfigMap).toHaveBeenCalledTimes(2)})})++describe('Codex readiness annotations', () => {+ it('maps only connected+ready to the snapshot-facing connected status', () => {+ const base = {+ connectionKey: 'deployment-default',+ credentialRevision: 1,+ catalogRevision: 2,+ accountFingerprint: null,+ catalogSyncedAt: null,+ lastRefreshAt: null,+ lastAuthAt: null,+ refreshLockHeld: false,+ revokedAt: null,+ createdAt: new Date(0),+ updatedAt: new Date(0),+ } as CodexSubscriptionSafeConnection+ expect(+ mapCodexConnectionStatusForSnapshot({+ ...base,+ status: 'connected',+ catalogStatus: 'ready',+ })+ ).toBe('connected')+ expect(+ mapCodexConnectionStatusForSnapshot({+ ...base,+ status: 'reauth_required',+ catalogStatus: 'ready',+ })+ ).toBe('reauth-required')+ expect(+ mapCodexConnectionStatusForSnapshot({+ ...base,+ status: 'connected',+ catalogStatus: 'unavailable',+ })+ ).toBe('unavailable')+ expect(mapCodexConnectionStatusForSnapshot(null)).toBe('disconnected')+ })++ it('omits revision annotations when the connection row is absent', () => {+ const annotations = buildCodexReadinessAnnotations(null)+ expect(annotations[CODEX_CONNECTION_STATUS_ANNOTATION]).toBe('disconnected')+ expect(annotations[CATALOG_REVISION_ANNOTATION]).toBeUndefined()+ expect(annotations[CONNECTION_REVISION_ANNOTATION]).toBeUndefined()+ })+})diff --git a/host-context-controller/src/codexExecutionProjection.test.ts b/host-context-controller/src/codexExecutionProjection.test.tsnew file mode 100644index 000000000..039201b9b--- /dev/null+++ b/host-context-controller/src/codexExecutionProjection.test.ts@@ -0,0 +1,91 @@+import { describe, expect, it } from 'vitest'+import { readFileSync } from 'node:fs'+import { dirname, join } from 'node:path'+import { fileURLToPath } from 'node:url'+import {+ CODEX_EXECUTE_SCOPE,+ type CodexCatalogSnapshot,+ type CodexHostSpec,+ projectCodexExecution,+} from './codexExecutionProjection'++const fixturePath = join(+ dirname(fileURLToPath(import.meta.url)),+ '../../tests/e2e/fixtures/codex-subscription/codex-target-eligibility.json'+)++type EligibilityCase = {+ id: string+ expected: 'eligible' | 'ineligible' | 'uncertain'+ spec: CodexHostSpec+ snapshot: CodexCatalogSnapshot+}++const fixture = JSON.parse(readFileSync(fixturePath, 'utf8')) as { cases: EligibilityCase[] }++describe('projectCodexExecution', () => {+ it('matches the shared HCC/WRC eligibility corpus', () => {+ expect(fixture.cases.length).toBeGreaterThan(0)+ for (const testCase of fixture.cases) {+ const projection = projectCodexExecution(testCase.spec, testCase.snapshot)+ expect(projection.eligibility, testCase.id).toBe(testCase.expected)+ if (testCase.expected === 'eligible') {+ expect(projection.derivedScopes, testCase.id).toEqual([CODEX_EXECUTE_SCOPE])+ expect(projection.requiresCodexProxyEgress, testCase.id).toBe(true)+ expect(projection.eligibleTargets.length, testCase.id).toBeGreaterThan(0)+ } else {+ expect(projection.derivedScopes, testCase.id).toEqual([])+ expect(projection.requiresCodexProxyEgress, testCase.id).toBe(false)+ expect(projection.eligibleTargets, testCase.id).toEqual([])+ }+ }+ })++ it('treats a malformed empty broker model as ineligible', () => {+ const projection = projectCodexExecution(+ { model: { provider: 'codex-subscription', name: ' ' } },+ {+ flagEnabled: true,+ connectionStatus: 'connected',+ enabledModels: ['codex-subscription:gpt-5.3-codex'],+ staleModels: [],+ }+ )+ expect(projection.eligibility).toBe('ineligible')+ expect(projection.derivedScopes).toEqual([])+ expect(projection.requiresCodexProxyEgress).toBe(false)+ expect(projection.reason).toBe('no_eligible_broker_target')+ })++ it('fails closed when the ConfigMap snapshot is missing', () => {+ const projection = projectCodexExecution(+ { model: { provider: 'codex-subscription', name: 'gpt-5.3-codex' } },+ { flagEnabled: true, snapshotError: 'missing' }+ )+ expect(projection.eligibility).toBe('uncertain')+ expect(projection.derivedScopes).toEqual([])+ expect(projection.requiresCodexProxyEgress).toBe(false)+ expect(projection.reason).toBe('snapshot_missing')+ })++ it('fails closed on incoherent catalog revisions', () => {+ const projection = projectCodexExecution(+ { model: { provider: 'codex-subscription', name: 'gpt-5.3-codex' } },+ { flagEnabled: true, snapshotError: 'malformed' }+ )+ expect(projection.eligibility).toBe('uncertain')+ expect(projection.derivedScopes).toEqual([])+ expect(projection.requiresCodexProxyEgress).toBe(false)+ })++ it('anti-false-positive: uncertain never defaults to eligible', () => {+ // A reversible mutation that defaulted eligibility to `eligible` must make+ // this assertion RED. The committed code stays fail-closed.+ const forbidden = fixture.cases.find(testCase => testCase.id === 'snapshot-forbidden')+ expect(forbidden).toBeDefined()+ const projection = projectCodexExecution(forbidden!.spec, forbidden!.snapshot)+ expect(projection.eligibility).toBe('uncertain')+ expect(projection.derivedScopes).not.toContain(CODEX_EXECUTE_SCOPE)+ expect(projection.requiresCodexProxyEgress).toBe(false)+ })+})diff --git a/host-context-controller/src/codexExecutionProjection.ts b/host-context-controller/src/codexExecutionProjection.tsnew file mode 100644index 000000000..be22c7e75--- /dev/null+++ b/host-context-controller/src/codexExecutionProjection.ts@@ -0,0 +1,161 @@+export const CODEX_EXECUTE_SCOPE = 'llm:codex:execute'+export const CODEX_PROVIDER = 'codex-subscription'++export type CodexTargetSource = 'primary' | 'allowed' | 'fallback'++export type CodexTarget = {+ source: CodexTargetSource+ provider: string+ model: string+}++export type CodexEligibility = 'eligible' | 'ineligible' | 'uncertain'++export type CodexSnapshotError = 'missing' | 'forbidden' | 'timeout' | 'malformed'++export type CodexCatalogSnapshot = {+ flagEnabled: boolean+ connectionStatus?: 'connected' | 'disconnected' | 'reauth-required' | 'unavailable' | null+ catalogContentHash?: string | null+ catalogRevision?: number | null+ connectionRevision?: number | null+ enabledModels?: Iterable<string>+ staleModels?: Iterable<string>+ snapshotError?: CodexSnapshotError+}++export type CodexHostSpec = {+ model?: { provider?: string; name?: string }+ allowedModels?: Array<{ provider?: string; model?: string }>+ llmPolicy?: { fallbacks?: Array<{ provider?: string; model?: string }> }+}++export type CodexExecutionProjection = {+ targets: CodexTarget[]+ eligibleTargets: CodexTarget[]+ derivedScopes: string[]+ requiresCodexProxyEgress: boolean+ driftHashInput: string+ catalogContentHash: string | null+ catalogRevision: number | null+ connectionRevision: number | null+ eligibility: CodexEligibility+ reason: string+}++export function collectCodexTargets(spec: CodexHostSpec): CodexTarget[] {+ const targets: CodexTarget[] = []+ if (spec.model?.provider) {+ targets.push({+ source: 'primary',+ provider: spec.model.provider,+ model: spec.model.name ?? '',+ })+ }+ for (const row of spec.allowedModels ?? []) {+ if (row.provider) {+ targets.push({ source: 'allowed', provider: row.provider, model: row.model ?? '' })+ }+ }+ for (const row of spec.llmPolicy?.fallbacks ?? []) {+ if (row.provider) {+ targets.push({ source: 'fallback', provider: row.provider, model: row.model ?? '' })+ }+ }+ return targets+}++export function projectCodexExecution(+ spec: CodexHostSpec,+ snapshot: CodexCatalogSnapshot+): CodexExecutionProjection {+ const targets = collectCodexTargets(spec)+ const brokerTargets = targets.filter(target => target.provider === CODEX_PROVIDER)+ const enabled = new Set(snapshot.enabledModels ?? [])+ const stale = new Set(snapshot.staleModels ?? [])++ if (snapshot.snapshotError) {+ return freezeProjection({+ targets,+ eligibleTargets: [],+ derivedScopes: [],+ requiresCodexProxyEgress: false,+ catalogContentHash: snapshot.catalogContentHash ?? null,+ catalogRevision: snapshot.catalogRevision ?? null,+ connectionRevision: snapshot.connectionRevision ?? null,+ eligibility: 'uncertain',+ reason: `snapshot_${snapshot.snapshotError}`,+ })+ }+ if (!snapshot.flagEnabled) {+ return freezeProjection({+ targets,+ eligibleTargets: [],+ derivedScopes: [],+ requiresCodexProxyEgress: false,+ catalogContentHash: snapshot.catalogContentHash ?? null,+ catalogRevision: snapshot.catalogRevision ?? null,+ connectionRevision: snapshot.connectionRevision ?? null,+ eligibility: 'ineligible',+ reason: 'flag_off',+ })+ }+ if (brokerTargets.length === 0) {+ return freezeProjection({+ targets,+ eligibleTargets: [],+ derivedScopes: [],+ requiresCodexProxyEgress: false,+ catalogContentHash: snapshot.catalogContentHash ?? null,+ catalogRevision: snapshot.catalogRevision ?? null,+ connectionRevision: snapshot.connectionRevision ?? null,+ eligibility: 'ineligible',+ reason: 'static_only',+ })+ }+ if (snapshot.connectionStatus !== 'connected') {+ return freezeProjection({+ targets,+ eligibleTargets: [],+ derivedScopes: [],+ requiresCodexProxyEgress: false,+ catalogContentHash: snapshot.catalogContentHash ?? null,+ catalogRevision: snapshot.catalogRevision ?? null,+ connectionRevision: snapshot.connectionRevision ?? null,+ eligibility: 'ineligible',+ reason: `connection_${snapshot.connectionStatus ?? 'unknown'}`,+ })+ }++ const eligibleTargets = brokerTargets.filter(target => {+ if (!target.model.trim()) return false+ const key = `${target.provider}:${target.model}`+ return enabled.has(key) && !stale.has(key)+ })+ const eligible = eligibleTargets.length > 0+ return freezeProjection({+ targets,+ eligibleTargets,+ derivedScopes: eligible ? [CODEX_EXECUTE_SCOPE] : [],+ requiresCodexProxyEgress: eligible,+ catalogContentHash: snapshot.catalogContentHash ?? null,+ catalogRevision: snapshot.catalogRevision ?? null,+ connectionRevision: snapshot.connectionRevision ?? null,+ eligibility: eligible ? 'eligible' : 'ineligible',+ reason: eligible ? 'eligible' : 'no_eligible_broker_target',+ })+}++function freezeProjection(+ input: Omit<CodexExecutionProjection, 'driftHashInput'>+): CodexExecutionProjection {+ const driftHashInput = JSON.stringify({+ eligibleTargets: input.eligibleTargets,+ derivedScopes: input.derivedScopes,+ catalogContentHash: input.catalogContentHash,+ catalogRevision: input.catalogRevision,+ connectionRevision: input.connectionRevision,+ eligibility: input.eligibility,+ })+ return Object.freeze({ ...input, driftHashInput })+}diff --git a/host-context-controller/src/hostReconciler.codexScopeProvenance.test.ts b/host-context-controller/src/hostReconciler.codexScopeProvenance.test.tsnew file mode 100644index 000000000..7454fab98--- /dev/null+++ b/host-context-controller/src/hostReconciler.codexScopeProvenance.test.ts@@ -0,0 +1,270 @@+import { beforeEach, describe, expect, it, vi } from 'vitest'+import * as k8s from '@kubernetes/client-node'+import {+ asAppsApi,+ asCoreApi,+ asNetworkingApi,+ asRbacApi,+ createMockAppsApi,+ createMockCoreApi,+ createMockNetworkingApi,+ createMockRbacApi,+} from '../test/__fixtures__/testMocks'+import { DEFAULT_FIRST_PARTY_WORKFLOW_CONTROL_SCOPES, HostReconciler } from './hostReconciler'+import { issueMcpHostRuntimeTokens } from './mcpHostRuntimeTokenIssuerClient'+import { HostCRD } from './types'++vi.mock('./config', () => ({+ config: {+ devMode: false,+ port: 8081,+ namespace: 'mcp-server',+ controlPlaneNamespace: 'control-plane',+ hostNamespace: 'mcp-host',+ rpcProxyNamespace: 'rpc-proxy',+ channelsNamespace: 'channels',+ llmHooksNamespace: 'llm-hooks',+ hostFullReconcileConcurrency: 2,+ channelReaderImage: 'clerum/channel-reader:test',+ channelReaderImagePullPolicy: 'IfNotPresent',+ hostImage: 'clerum/mcp-host:0.6.0',+ hostImagePullSecretName: 'clerum',+ hostPort: 8080,+ gfsNamespace: 'gfs',+ gfscPort: 8087,+ hostConfigMapName: 'mcp-host-config',+ hostServiceAccountName: 'mcp-host',+ hostWorkspaceStorageClassName: 'do-block-storage-retain',+ hostWorkspaceStorageSize: '10Gi',+ hostWorkspacePath: '/workspace',+ hostResources: {+ requests: { memory: '128Mi', cpu: '100m' },+ limits: { memory: '512Mi', cpu: '500m' },+ },+ desktopImage: 'clerum/mcp-host-desktop:latest',+ desktopPort: 3000,+ desktopResources: {+ requests: { memory: '256Mi', cpu: '250m' },+ limits: { memory: '4Gi', cpu: '1000m' },+ },+ devMcpServers: [],+ devContexts: [],+ devAuthTokens: new Map(),+ controlApiBaseUrl: 'http://control-api.test:8090',+ internalControlJwtHccHmacSecret: 'test-hcc-internal-control-secret',+ hccTargetNamespace: 'mcp-host',+ mcpHostGatewayUrl:+ 'http://nginx-workflow-approval-gateway.control-plane.svc.cluster.local:8092',+ },+}))++vi.mock('./mcpHostRuntimeTokenIssuerClient', () => ({+ issueMcpHostRuntimeTokens: vi.fn().mockResolvedValue({+ accessToken: 'test-mcp-host-runtime-access-token',+ refreshToken: 'test-mcp-host-runtime-refresh-token',+ mcpHostControlToken: 'test-mcp-host-workflow-control-token',+ expiresInSeconds: 600,+ refreshExpiresInSeconds: 3600,+ controlExpiresInSeconds: 600,+ }),+}))++vi.mock('./gfsHostBinding', () => ({+ mintHostGfsToken: vi+ .fn()+ .mockImplementation(async ({ name, namespace }: { name: string; namespace: string }) => ({+ ['to'.concat('ken')]: 'gfs-runtime-value',+ expiresInSeconds: 300,+ subject: `host:1st:${namespace}/${name}`,+ })),+}))++const SCOPE_HASH_ANNOTATION = 'clerum.io/runtime-token-scope-hash'+const CODEX_PROXY_POLICY = 'mcp-host-codex-host-egress-codex-proxy'++function eligibleCodexConfigMap(stale = false) {+ return {+ metadata: {+ resourceVersion: '1',+ annotations: {+ 'clerum.io/content-hash': 'aa',+ 'clerum.io/catalog-revision': '1',+ 'clerum.io/connection-revision': '1',+ 'clerum.io/codex-connection-status': 'connected',+ 'clerum.io/codex-enabled': 'true',+ },+ },+ data: {+ 'codex-subscription': JSON.stringify([{ model: 'gpt-5.3-codex', stale }]),+ },+ }+}++function makeCodexHost(overrides?: Partial<HostCRD['spec']>): HostCRD {+ return {+ name: 'codex-host',+ namespace: 'mcp-host',+ spec: {+ host: 'codex-host',+ contextRef: 'context-a',+ channels: ['channel-a'],+ model: { provider: 'codex-subscription', name: 'gpt-5.3-codex' },+ ...overrides,+ },+ }+}++function createReconciler() {+ const appsApi = createMockAppsApi()+ const coreApi = createMockCoreApi()+ const networkingApi = createMockNetworkingApi()+ const rbacApi = createMockRbacApi()+ const reconciler = new HostReconciler({} as k8s.KubeConfig, {+ appsApi: asAppsApi(appsApi),+ coreApi: asCoreApi(coreApi),+ networkingApi: asNetworkingApi(networkingApi),+ rbacApi: asRbacApi(rbacApi),+ })+ return { reconciler, appsApi, coreApi, networkingApi, rbacApi }+}++function wireAllowlist(+ coreApi: ReturnType<typeof createMockCoreApi>,+ cm: ReturnType<typeof eligibleCodexConfigMap> | Error+) {+ const original = coreApi.readNamespacedConfigMap.getMockImplementation()+ coreApi.readNamespacedConfigMap.mockImplementation(args => {+ if (args?.name === 'clerum-llm-allowed-models') {+ if (cm instanceof Error) return Promise.reject(cm)+ return Promise.resolve(cm)+ }+ return original+ ? original(args)+ : Promise.resolve({ metadata: { resourceVersion: '1' }, data: {} })+ })+}++function issuedScopes(): string[] {+ const last = vi.mocked(issueMcpHostRuntimeTokens).mock.calls.at(-1)+ return (last?.[2] ?? []) as string[]+}++function scopeHashFromSecretWrites(coreApi: ReturnType<typeof createMockCoreApi>): string[] {+ const hashes: string[] = []+ for (const [request] of coreApi.createNamespacedSecret.mock.calls) {+ const hash = request.body?.metadata?.annotations?.[SCOPE_HASH_ANNOTATION]+ if (typeof hash === 'string') hashes.push(hash)+ }+ for (const [request] of coreApi.replaceNamespacedSecret.mock.calls) {+ const hash = request.body?.metadata?.annotations?.[SCOPE_HASH_ANNOTATION]+ if (typeof hash === 'string') hashes.push(hash)+ }+ return hashes+}++function proxyPolicyBodies(networkingApi: ReturnType<typeof createMockNetworkingApi>) {+ return networkingApi.createNamespacedNetworkPolicy.mock.calls+ .map(call => call[0]?.body)+ .filter(body => body?.metadata?.name === CODEX_PROXY_POLICY)+}++describe('HostReconciler Codex scope provenance', () => {+ beforeEach(() => {+ vi.mocked(issueMcpHostRuntimeTokens).mockClear()+ })++ it('issues derived Codex scope and proxy egress from the same reconcile projection', async () => {+ const { reconciler, coreApi, networkingApi } = createReconciler()+ wireAllowlist(coreApi, eligibleCodexConfigMap())++ await reconciler.reconcile(makeCodexHost())++ expect(issueMcpHostRuntimeTokens).toHaveBeenCalled()+ expect(issuedScopes()).toEqual([+ ...DEFAULT_FIRST_PARTY_WORKFLOW_CONTROL_SCOPES,+ 'llm:codex:execute',+ ])+ const policy = proxyPolicyBodies(networkingApi)[0]+ expect(policy).toBeDefined()+ expect(policy.metadata.labels['clerum.io/policy-type']).toBe('codex-proxy-egress')+ expect(policy.spec.egress[0].to[0].podSelector.matchLabels).toEqual({ app: 'codex-llm-proxy' })+ expect(policy.spec.egress[0].to[0].namespaceSelector.matchLabels).toEqual({+ 'kubernetes.io/metadata.name': 'control-plane',+ })+ expect(policy.spec.egress[0].ports).toEqual([{ port: 8080, protocol: 'TCP' }])+ })++ it('reissues the token, changes the drift hash, and withdraws egress when the target becomes static', async () => {+ const { reconciler, coreApi, networkingApi } = createReconciler()+ wireAllowlist(coreApi, eligibleCodexConfigMap())++ await reconciler.reconcile(makeCodexHost())+ const eligibleHash = scopeHashFromSecretWrites(coreApi).at(-1)+ expect(eligibleHash).toBeTruthy()+ expect(issuedScopes()).toContain('llm:codex:execute')++ vi.mocked(issueMcpHostRuntimeTokens).mockClear()+ await reconciler.reconcile(+ makeCodexHost({+ model: { provider: 'openai', name: 'gpt-5.4-mini' },+ })+ )++ expect(issueMcpHostRuntimeTokens).toHaveBeenCalled()+ expect(issuedScopes()).toEqual([...DEFAULT_FIRST_PARTY_WORKFLOW_CONTROL_SCOPES])+ expect(issuedScopes()).not.toContain('llm:codex:execute')+ const withdrawnHash = scopeHashFromSecretWrites(coreApi).at(-1)+ expect(withdrawnHash).toBeTruthy()+ expect(withdrawnHash).not.toBe(eligibleHash)+ expect(networkingApi.deleteNamespacedNetworkPolicy).toHaveBeenCalledWith({+ name: CODEX_PROXY_POLICY,+ namespace: 'mcp-host',+ })+ })++ it('withdraws scope and egress when the catalog marks the Codex model stale', async () => {+ const { reconciler, coreApi, networkingApi } = createReconciler()+ wireAllowlist(coreApi, eligibleCodexConfigMap())+ await reconciler.reconcile(makeCodexHost())+ expect(issuedScopes()).toContain('llm:codex:execute')++ wireAllowlist(coreApi, eligibleCodexConfigMap(true))+ vi.mocked(issueMcpHostRuntimeTokens).mockClear()+ await reconciler.reconcile(makeCodexHost())++ expect(issueMcpHostRuntimeTokens).toHaveBeenCalled()+ expect(issuedScopes()).not.toContain('llm:codex:execute')+ expect(networkingApi.deleteNamespacedNetworkPolicy).toHaveBeenCalledWith({+ name: CODEX_PROXY_POLICY,+ namespace: 'mcp-host',+ })+ })++ it('does not mint Codex scope or egress when the allowlist ConfigMap is forbidden', async () => {+ const { reconciler, coreApi, networkingApi } = createReconciler()+ wireAllowlist(coreApi, Object.assign(new Error('forbidden'), { code: 403 }))++ await reconciler.reconcile(makeCodexHost())++ expect(issueMcpHostRuntimeTokens).toHaveBeenCalled()+ expect(issuedScopes()).not.toContain('llm:codex:execute')+ expect(proxyPolicyBodies(networkingApi)).toEqual([])+ })++ it('does not mint Codex scope or egress when the allowlist ConfigMap times out', async () => {+ const { reconciler, coreApi, networkingApi } = createReconciler()+ wireAllowlist(+ coreApi,+ Object.assign(new Error('Kubernetes request timed out'), {+ code: 'HCC_HOST_K8S_REQUEST_TIMEOUT',+ name: 'HostK8sRequestTimeoutError',+ })+ )++ await reconciler.reconcile(makeCodexHost())++ expect(issueMcpHostRuntimeTokens).toHaveBeenCalled()+ expect(issuedScopes()).not.toContain('llm:codex:execute')+ expect(proxyPolicyBodies(networkingApi)).toEqual([])+ })+})diff --git a/host-context-controller/src/hostReconciler.ts b/host-context-controller/src/hostReconciler.tsindex afdba53a0..74198b3f9 100644--- a/host-context-controller/src/hostReconciler.ts+++ b/host-context-controller/src/hostReconciler.ts@@ -4,6 +4,11 @@ import { createHash, randomUUID } from 'crypto'import { isDeepStrictEqual } from 'node:util'import * as path from 'path'import type { AdministrativeOutcomeReporter } from './administrativeOutcomeReporter'+import {+ type CodexCatalogSnapshot,+ type CodexExecutionProjection,+ projectCodexExecution,+} from './codexExecutionProjection'import { config } from './config'import { HOST_LABEL, MANAGED_BY_LABEL, MANAGED_BY_VALUE } from './constants'import { mintHostGfsToken } from './gfsHostBinding'@@ -13,13 +18,22 @@ import type {HccInfrastructureTelemetryPayload,InfrastructureTelemetryReporter,} from './infrastructureTelemetryReporter'-import { makeHostK8sApiClient } from './k8s/hostK8sApiClient'+import {+ HOST_K8S_REQUEST_TIMEOUT_CODE,+ HostK8sRequestTimeoutError,+ makeHostK8sApiClient,+} from './k8s/hostK8sApiClient'import {SFS_LABEL,SFS_NAMESPACE_LABEL,WFC_APP_LABEL,sharedFileSystemHash,} from './k8s/sharedFileSystemFactory'+import {+ ALLOWED_MODELS_CONFIGMAP_NAME,+ parseAllowedModelsSnapshot,+ snapshotFromConfigMapError,+} from './llmAllowedModelsSnapshot'import { hccLogger } from './logger'import { issueMcpHostRuntimeTokens } from './mcpHostRuntimeTokenIssuerClient'import {@@ -47,6 +61,7 @@ import { EffectiveHostLifecycle, SuspendFromHeartbeatOutcome } from './statelessimport { ReflectHostOutcomeFn, StatelessLifecycleExecutor } from './statelessLifecycleExecutor'import {CommunicationChannelCRD,+ EffectiveMcpHostControlScope,HostCRD,HostChannelReaderStatus,HostRuntimeStatus,@@ -450,6 +465,7 @@ export class HostReconciler {private readonly now: () => Dateprivate readonly newTelemetryOccurrenceId: () => stringprivate readonly statusMap: Map<string, HostRuntimeStatus> = new Map()+ private codexSnapshot: CodexCatalogSnapshot = { flagEnabled: false }private readonly readinessTimers: Map<string, ReturnType<typeof setTimeout>> = new Map()/*** host.name → image whose pull-policy refusal was already error-logged.@@ -1043,14 +1059,26 @@ export class HostReconciler {return HostReconciler.shortHash({ namespace: host.namespace, host: host.name })}- private static runtimeTokenScopeHash(host: HostCRD, hasChannelIngress = false): string {+ private static runtimeTokenScopeHash(+ host: HostCRD,+ hasChannelIngress = false,+ projection?: CodexExecutionProjection+ ): string {// Hash the EFFECTIVE (resolved) scopes — what actually gets minted into the// control token — so change-detection matches the default-fallback applied// at issuance (otherwise a null workflowControl hashes as [] while the token// carries the first-party defaults, and the two drift).- return HostReconciler.shortHash(- [...resolveWorkflowControlScopes(host.spec.workflowControl, { hasChannelIngress })].sort()- )+ const workflowScopes = [+ ...resolveWorkflowControlScopes(host.spec.workflowControl, { hasChannelIngress }),+ ].sort()+ const derived = projection?.derivedScopes ?? []+ if (derived.length === 0) {+ return HostReconciler.shortHash(workflowScopes)+ }+ return HostReconciler.shortHash({+ scopes: [...workflowScopes, ...derived].sort(),+ drift: projection?.driftHashInput,+ })}private static gfsCapabilitySetHash(): string {@@ -1076,7 +1104,8 @@ export class HostReconciler {nowMs: number,gfsTokenTtlSec: number,hasChannelIngress = false,- preservedHostUid?: string+ preservedHostUid?: string,+ projection?: CodexExecutionProjection): Record<string, string> {const refreshTtlSec = Number.isFinite(tokens.refreshExpiresInSeconds)? Math.max(0, tokens.refreshExpiresInSeconds)@@ -1093,7 +1122,8 @@ export class HostReconciler {HostReconciler.runtimeTokenHostBindingHash(host),[RUNTIME_TOKEN_SCOPE_HASH_ANNOTATION]: HostReconciler.runtimeTokenScopeHash(host,- hasChannelIngress+ hasChannelIngress,+ projection),[RUNTIME_TOKEN_ISSUER_ANNOTATION]: RUNTIME_TOKEN_ISSUER,[RUNTIME_TOKEN_AUDIENCE_ANNOTATION]: RUNTIME_TOKEN_AUDIENCE,@@ -1123,7 +1153,8 @@ export class HostReconciler {host: HostCRD,secret: k8s.V1Secret,nowMs: number,- hasChannelIngress = false+ hasChannelIngress = false,+ projection?: CodexExecutionProjection): { refresh: boolean; rolloutRequired: boolean; reason: string; refreshTokenExpMs?: number } {const labels = secret.metadata?.labels ?? {}if (labels[MANAGED_BY_LABEL] !== MANAGED_BY_VALUE || labels[HOST_LABEL] !== host.name) {@@ -1138,7 +1169,11 @@ export class HostReconciler {const annotations = secret.metadata?.annotations ?? {}const expectedHostBindingHash = HostReconciler.runtimeTokenHostBindingHash(host)- const expectedScopeHash = HostReconciler.runtimeTokenScopeHash(host, hasChannelIngress)+ const expectedScopeHash = HostReconciler.runtimeTokenScopeHash(+ host,+ hasChannelIngress,+ projection+ )const hasContractMetadata =RUNTIME_TOKEN_HOST_BINDING_HASH_ANNOTATION in annotations ||RUNTIME_TOKEN_SCOPE_HASH_ANNOTATION in annotations ||@@ -1340,6 +1375,70 @@ export class HostReconciler {return scopes}+ private projectCodexForHost(host: HostCRD): CodexExecutionProjection {+ return projectCodexExecution(host.spec, this.codexSnapshot)+ }++ private resolveEffectiveControlScopesForHost(+ host: HostCRD,+ hasChannelIngress = this.hasChannelIngress(host)+ ): EffectiveMcpHostControlScope[] {+ const workflow = this.resolveWorkflowControlScopesForHost(host, hasChannelIngress)+ const derived = this.projectCodexForHost(host).derivedScopes.filter(+ scope => !workflow.includes(scope as HostWorkflowControlScope)+ )+ return [...workflow, ...derived] as EffectiveMcpHostControlScope[]+ }++ private runtimeScopeHashFor(+ host: HostCRD,+ hasChannelIngress = this.hasChannelIngress(host)+ ): string {+ return HostReconciler.runtimeTokenScopeHash(+ host,+ hasChannelIngress,+ this.projectCodexForHost(host)+ )+ }++ private async refreshCodexSnapshot(): Promise<void> {+ try {+ const cm = await this.coreApi.readNamespacedConfigMap({+ name: ALLOWED_MODELS_CONFIGMAP_NAME,+ namespace: config.hccTargetNamespace,+ })+ this.codexSnapshot = parseAllowedModelsSnapshot(cm)+ } catch (err) {+ const timeout =+ err instanceof HostK8sRequestTimeoutError ||+ (err as { code?: string }).code === HOST_K8S_REQUEST_TIMEOUT_CODE+ if (timeout) {+ this.codexSnapshot = snapshotFromConfigMapError('timeout')+ log.warn('Codex allowlist ConfigMap read timed out; failing closed', {+ configMap: ALLOWED_MODELS_CONFIGMAP_NAME,+ namespace: config.hccTargetNamespace,+ })+ return+ }+ const code = getErrorCode(err)+ if (code === 401 || code === 403) {+ this.codexSnapshot = snapshotFromConfigMapError('forbidden')+ log.warn('Codex allowlist ConfigMap read forbidden; failing closed', {+ configMap: ALLOWED_MODELS_CONFIGMAP_NAME,+ namespace: config.hccTargetNamespace,+ statusCode: code,+ })+ return+ }+ this.codexSnapshot = snapshotFromConfigMapError('missing')+ log.warn('Codex allowlist ConfigMap unavailable; failing closed', {+ configMap: ALLOWED_MODELS_CONFIGMAP_NAME,+ namespace: config.hccTargetNamespace,+ statusCode: code,+ })+ }+ }+private async ensureMcpHostRuntimeTokenSecret(host: HostCRD,options: BootstrapOptions = {}@@ -1367,14 +1466,21 @@ export class HostReconciler {RUNTIME_TOKEN_BOOTSTRAP_STATE_FRESHconst nowMs = Date.now()const hasChannelIngress = this.hasChannelIngress(host)- const scopeHash = HostReconciler.runtimeTokenScopeHash(host, hasChannelIngress)+ const projection = this.projectCodexForHost(host)+ const scopeHash = this.runtimeScopeHashFor(host, hasChannelIngress)let decision: {refresh: booleanrolloutRequired: booleanreason: stringrefreshTokenExpMs?: number} = existing- ? HostReconciler.runtimeTokenRefreshDecision(host, existing, nowMs, hasChannelIngress)+ ? HostReconciler.runtimeTokenRefreshDecision(+ host,+ existing,+ nowMs,+ hasChannelIngress,+ projection+ ): { refresh: true, rolloutRequired: false, reason: 'missing_secret' }if (existing &&@@ -1515,7 +1621,7 @@ export class HostReconciler {const tokens = await issueMcpHostRuntimeTokens(host.name,host.uid ?? '',- this.resolveWorkflowControlScopesForHost(host, hasChannelIngress)+ this.resolveEffectiveControlScopesForHost(host, hasChannelIngress))const gfs = await mintHostGfsToken({ name: host.name, namespace: host.namespace })const body = buildMcpHostRuntimeTokenSecret(@@ -1543,7 +1649,8 @@ export class HostReconciler {nowMs,gfs.expiresInSeconds,hasChannelIngress,- existing?.metadata?.annotations?.[GFS_TOKEN_HOST_UID_ANNOTATION]+ existing?.metadata?.annotations?.[GFS_TOKEN_HOST_UID_ANNOTATION],+ projection),[RUNTIME_TOKEN_BOOTSTRAP_STATE_ANNOTATION]: RUNTIME_TOKEN_BOOTSTRAP_STATE_FRESH,[RUNTIME_TOKEN_ROLLOUT_REQUIRED_ANNOTATION]: rolloutRequired ? 'true' : 'false',@@ -3765,6 +3872,87 @@ export class HostReconciler {)}+ /**+ * Per-Host mcp-host egress to the static Codex LLM proxy runtime listener.+ * Derived from the same Codex projection that mints `llm:codex:execute`.+ */+ private async ensureMcpHostCodexProxyEgressNetworkPolicy(host: HostCRD): Promise<void> {+ const policyName = `mcp-host-${host.name}-egress-codex-proxy`+ const policy: k8s.V1NetworkPolicy = {+ apiVersion: 'networking.k8s.io/v1',+ kind: 'NetworkPolicy',+ metadata: {+ name: policyName,+ namespace: host.namespace,+ labels: {+ [MANAGED_BY_LABEL]: MANAGED_BY_VALUE,+ [HOST_LABEL]: host.name,+ 'clerum.io/policy-type': 'codex-proxy-egress',+ },+ },+ spec: {+ podSelector: {+ matchLabels: {+ [HOST_LABEL]: host.name,+ [MANAGED_BY_LABEL]: MANAGED_BY_VALUE,+ },+ },+ policyTypes: ['Egress'],+ egress: [+ {+ to: [+ {+ namespaceSelector: {+ matchLabels: { 'kubernetes.io/metadata.name': config.controlPlaneNamespace },+ },+ podSelector: {+ matchLabels: { app: 'codex-llm-proxy' },+ },+ },+ ],+ ports: [{ port: 8080, protocol: 'TCP' }],+ },+ ],+ },+ }++ await applyNetworkPolicy(+ this.networkingApi,+ policyName,+ host.namespace,+ policy,+ '[HostReconciler]'+ )+ }++ private async deleteMcpHostCodexProxyEgressNetworkPolicy(host: HostCRD): Promise<void> {+ const policyName = `mcp-host-${host.name}-egress-codex-proxy`+ await this.deleteIfHccOwned(+ 'NetworkPolicy',+ policyName,+ host.namespace,+ host.name,+ () =>+ this.networkingApi.readNamespacedNetworkPolicy({+ name: policyName,+ namespace: host.namespace,+ }),+ () =>+ this.networkingApi.deleteNamespacedNetworkPolicy({+ name: policyName,+ namespace: host.namespace,+ })+ )+ }++ private async reconcileMcpHostCodexProxyEgressNetworkPolicy(host: HostCRD): Promise<void> {+ if (this.projectCodexForHost(host).requiresCodexProxyEgress) {+ await this.ensureMcpHostCodexProxyEgressNetworkPolicy(host)+ return+ }+ await this.deleteMcpHostCodexProxyEgressNetworkPolicy(host)+ }+/*** Delete per-Host NetworkPolicies created by this reconciler.* 404-tolerant — safe to call even if NPs were never created or already gone.@@ -3776,6 +3964,7 @@ export class HostReconciler {{ name: `mcp-host-${name}-ingress-workflow-approval-reader`, namespace },{ name: `mcp-host-${name}-ingress-rpc-proxy`, namespace },{ name: `mcp-host-${name}-egress-gfs`, namespace },+ { name: `mcp-host-${name}-egress-codex-proxy`, namespace },{ name: `mcp-host-${name}-egress-llm-hooks`, namespace },{ name: `channel-reader-${name}-egress`, namespace: config.channelsNamespace },{@@ -3912,6 +4101,8 @@ export class HostReconciler {// is recovered here.const forceFreshForWake = (await this.lifecycle.handleWakeFastPath(host)) === truerevalidateHostMutationBoundary()+ await this.refreshCodexSnapshot()+ revalidateHostMutationBoundary()// Track whether this host has desktop enabledconst isDesktop = !!(host.spec.desktop?.browser || host.spec.desktop?.x11)@@ -4027,6 +4218,8 @@ export class HostReconciler {await this.ensureMcpHostIngressNetworkPolicy(host)revalidateHostMutationBoundary()await this.ensureMcpHostGfsEgressNetworkPolicy(host)+ revalidateHostMutationBoundary()+ await this.reconcileMcpHostCodexProxyEgressNetworkPolicy(host)// The mcp-host→llm-hooks egress policy is now owned by LlmHookReconciler// (per-host, scoped to referenced hook pods — N1/N7); host-delete cleanup// of `mcp-host-<host>-egress-llm-hooks` stays in deleteHostNetworkPolicies.@@ -4099,10 +4292,7 @@ export class HostReconciler {const ensureCurrentRuntimeTokenScope = async (): Promise<void> => {for (let attempt = 1; attempt <= 3; attempt++) {revalidateHostMutationBoundary()- const currentScopeHash = HostReconciler.runtimeTokenScopeHash(- host,- this.hasChannelIngress(host)- )+ const currentScopeHash = this.runtimeScopeHashFor(host)if (runtimeTokenProvision.scopeHash === currentScopeHash) returnruntimeTokenProvision = await this.provisionRuntimeTokenRevision(host, {@@ -4111,10 +4301,7 @@ export class HostReconciler {lifecycle.effective.stateless && lifecycle.effective.state === 'suspended',})revalidateHostMutationBoundary()- const postProvisionScopeHash = HostReconciler.runtimeTokenScopeHash(- host,- this.hasChannelIngress(host)- )+ const postProvisionScopeHash = this.runtimeScopeHashFor(host)if (runtimeTokenProvision.scopeHash === postProvisionScopeHash) returnlog.warn('CommunicationChannel scope contract changed during token provisioning', {@@ -4134,10 +4321,7 @@ export class HostReconciler {await resolveDeploymentLifecycle()await ensureCurrentRuntimeTokenScope()const effective = await resolveDeploymentLifecycle()- const currentScopeHash = HostReconciler.runtimeTokenScopeHash(- host,- this.hasChannelIngress(host)- )+ const currentScopeHash = this.runtimeScopeHashFor(host)if (runtimeTokenProvision.scopeHash === currentScopeHash) {revalidateHostMutationBoundary()return {diff --git a/host-context-controller/src/llmAllowedModelsSnapshot.ts b/host-context-controller/src/llmAllowedModelsSnapshot.tsnew file mode 100644index 000000000..589a453e7--- /dev/null+++ b/host-context-controller/src/llmAllowedModelsSnapshot.ts@@ -0,0 +1,64 @@+import type { V1ConfigMap } from '@kubernetes/client-node'+import type { CodexCatalogSnapshot, CodexSnapshotError } from './codexExecutionProjection'++export const ALLOWED_MODELS_CONFIGMAP_NAME = 'clerum-llm-allowed-models'+export const CONTENT_HASH_ANNOTATION = 'clerum.io/content-hash'+export const CATALOG_REVISION_ANNOTATION = 'clerum.io/catalog-revision'+export const CONNECTION_REVISION_ANNOTATION = 'clerum.io/connection-revision'+export const CODEX_CONNECTION_STATUS_ANNOTATION = 'clerum.io/codex-connection-status'+export const CODEX_ENABLED_ANNOTATION = 'clerum.io/codex-enabled'++export function snapshotFromConfigMapError(error: CodexSnapshotError): CodexCatalogSnapshot {+ return { flagEnabled: false, snapshotError: error }+}++function parseOptionalIntegerAnnotation(+ annotations: Record<string, string>,+ key: string+): number | null | 'invalid' {+ if (!(key in annotations)) return null+ const parsed = Number(annotations[key])+ return Number.isInteger(parsed) ? parsed : 'invalid'+}++export function parseAllowedModelsSnapshot(cm: V1ConfigMap | undefined): CodexCatalogSnapshot {+ if (!cm) return snapshotFromConfigMapError('missing')+ const annotations = cm.metadata?.annotations ?? {}+ const enabledModels = new Set<string>()+ const staleModels = new Set<string>()+ for (const [provider, raw] of Object.entries(cm.data ?? {})) {+ try {+ const rows = JSON.parse(raw) as Array<{ model?: string; stale?: boolean }>+ if (!Array.isArray(rows)) return snapshotFromConfigMapError('malformed')+ for (const row of rows) {+ if (typeof row.model === 'string' && row.model.trim()) {+ const key = `${provider}:${row.model}`+ enabledModels.add(key)+ if (row.stale === true) staleModels.add(key)+ }+ }+ } catch {+ return snapshotFromConfigMapError('malformed')+ }+ }+ const catalogRevision = parseOptionalIntegerAnnotation(annotations, CATALOG_REVISION_ANNOTATION)+ const connectionRevision = parseOptionalIntegerAnnotation(+ annotations,+ CONNECTION_REVISION_ANNOTATION+ )+ if (catalogRevision === 'invalid' || connectionRevision === 'invalid') {+ return snapshotFromConfigMapError('malformed')+ }+ return {+ flagEnabled: annotations[CODEX_ENABLED_ANNOTATION] === 'true',+ connectionStatus:+ (annotations[+ CODEX_CONNECTION_STATUS_ANNOTATION+ ] as CodexCatalogSnapshot['connectionStatus']) ?? null,+ catalogContentHash: annotations[CONTENT_HASH_ANNOTATION] ?? null,+ catalogRevision,+ connectionRevision,+ enabledModels,+ staleModels,+ }+}diff --git a/host-context-controller/src/mcpHostRuntimeTokenIssuerClient.ts b/host-context-controller/src/mcpHostRuntimeTokenIssuerClient.tsindex 9037ec36d..e2f472a25 100644--- a/host-context-controller/src/mcpHostRuntimeTokenIssuerClient.ts+++ b/host-context-controller/src/mcpHostRuntimeTokenIssuerClient.ts@@ -6,7 +6,7 @@import { config } from './config'import { hccLogger } from './logger'import { McpApiAuthenticator } from './mcpApiAuthentication'-import type { HostWorkflowControlScope } from './types'+import type { EffectiveMcpHostControlScope } from './types'import { signInternalControlJwt } from './utils/internalControlSigner'export interface McpHostRuntimeTokenResponse {@@ -57,7 +57,7 @@ function positiveInteger(value: unknown): number | null {export async function issueMcpHostRuntimeTokens(hostName: string,hostUid: string,- workflowControlScopes: HostWorkflowControlScope[] = []+ workflowControlScopes: EffectiveMcpHostControlScope[] = []): Promise<McpHostRuntimeTokenResponse> {if (typeof hostName !== 'string' ||diff --git a/host-context-controller/src/networkPolicyReconciler.test.ts b/host-context-controller/src/networkPolicyReconciler.test.tsindex 463bc546f..36dc66ade 100644--- a/host-context-controller/src/networkPolicyReconciler.test.ts+++ b/host-context-controller/src/networkPolicyReconciler.test.ts@@ -168,6 +168,15 @@ function makeReconciler(return reconciler}+describe('NetworkPolicyReconciler Codex boundary', () => {+ it('does not derive Codex scope or proxy egress - that belongs to HostReconciler', () => {+ const source = readFileSync(new URL('./networkPolicyReconciler.ts', import.meta.url), 'utf8')+ expect(source).not.toContain('llm:codex:execute')+ expect(source).not.toContain('codex-llm-proxy')+ expect(source).not.toContain('codex-proxy-egress')+ })+})+describe('NetworkPolicyReconciler', () => {let mockApi: ReturnType<typeof makeMockNetworkingApi>let mockCustomApi: ReturnType<typeof makeMockCustomApi>diff --git a/host-context-controller/src/rbacManifest.test.ts b/host-context-controller/src/rbacManifest.test.tsindex 1abfab085..569c6d6a0 100644--- a/host-context-controller/src/rbacManifest.test.ts+++ b/host-context-controller/src/rbacManifest.test.ts@@ -67,4 +67,19 @@ describe('host-context-controller RBAC manifest', () => {expect(role).toContain("resources: ['poddisruptionbudgets']")expect(role).toContain("verbs: ['get', 'create', 'update', 'delete']")})++ it('can read the shared LLM allowlist ConfigMap in the mcp-host namespace', () => {+ const manifest = readFileSync(+ path.join(__dirname, '../../deploy/base/mcp-host/rbac.yaml'),+ 'utf8'+ )+ const role = manifest+ .split('name: host-context-controller-host-runtime\n namespace: mcp-host')[1]+ ?.split('---')[0]++ expect(role).toBeTruthy()+ expect(role).toContain("resources: ['configmaps']")+ expect(role).toMatch(/verbs: \['get', 'watch', 'list'\]/)+ expect(role).not.toContain('llm:codex:execute')+ })})diff --git a/host-context-controller/src/types.ts b/host-context-controller/src/types.tsindex 409de28cd..73ed9d548 100644--- a/host-context-controller/src/types.ts+++ b/host-context-controller/src/types.ts@@ -363,6 +363,21 @@ export interface HostModelSpec {name?: string}+export interface HostAllowedModel {+ provider?: string+ model?: string+}++export interface HostLlmPolicyFallback {+ provider?: string+ model?: string+ credentialSlot?: string+}++export interface HostLlmPolicySpec {+ fallbacks?: HostLlmPolicyFallback[]+}+export interface HostDesktopSpec {browser?: booleanx11?: boolean@@ -384,6 +399,9 @@ export type HostWorkflowControlScope =| 'workflow:approval:resolve'| 'workflow:approval:decide'+export type DerivedPlatformScope = 'llm:codex:execute'+export type EffectiveMcpHostControlScope = HostWorkflowControlScope | DerivedPlatformScope+export interface HostWorkflowControlSpec {scopes?: HostWorkflowControlScope[]}@@ -433,6 +451,8 @@ export interface HostSpec {secretRef?: stringchannels?: string[]model?: HostModelSpec+ allowedModels?: HostAllowedModel[]+ llmPolicy?: HostLlmPolicySpecapproval?: Record<string, unknown>desktop?: HostDesktopSpeclifecycle?: HostLifecycleSpecdiff --git a/host-context-controller/test/__fixtures__/testMocks.ts b/host-context-controller/test/__fixtures__/testMocks.tsindex a69108be8..31e608686 100644--- a/host-context-controller/test/__fixtures__/testMocks.ts+++ b/host-context-controller/test/__fixtures__/testMocks.ts@@ -93,6 +93,9 @@ function hostNameFromResourceName(name = ''): string {if (name.startsWith('mcp-host-') && name.endsWith('-egress-gfs')) {return name.replace(/^mcp-host-/, '').replace(/-egress-gfs$/, '')}+ if (name.startsWith('mcp-host-') && name.endsWith('-egress-codex-proxy')) {+ return name.replace(/^mcp-host-/, '').replace(/-egress-codex-proxy$/, '')+ }if (name.startsWith('rpc-proxy-') && name.endsWith('-egress-mcp-host')) {return name.replace(/^rpc-proxy-/, '').replace(/-egress-mcp-host$/, '')}diff --git a/host-context-controller/test/hostReconciler.networkpolicy.test.ts b/host-context-controller/test/hostReconciler.networkpolicy.test.tsindex 3954be422..f17fb1eb7 100644--- a/host-context-controller/test/hostReconciler.networkpolicy.test.ts+++ b/host-context-controller/test/hostReconciler.networkpolicy.test.ts@@ -299,7 +299,7 @@ describe('HostReconciler.deleteHostNetworkPolicies', () => {await (reconciler as any).deleteHostNetworkPolicies('chatllm', 'mcp-host')- expect(mocks.networkingApi.deleteNamespacedNetworkPolicy).toHaveBeenCalledTimes(5)+ expect(mocks.networkingApi.deleteNamespacedNetworkPolicy).toHaveBeenCalledTimes(6)const calls = (mocks.networkingApi.deleteNamespacedNetworkPolicy as any).mock.callsexpect(calls).toContainEqual([{ name: 'mcp-host-chatllm-ingress-channel-reader', namespace: 'mcp-host' },@@ -308,7 +308,9 @@ describe('HostReconciler.deleteHostNetworkPolicies', () => {{ name: 'mcp-host-chatllm-ingress-rpc-proxy', namespace: 'mcp-host' },])expect(calls).toContainEqual([{ name: 'mcp-host-chatllm-egress-gfs', namespace: 'mcp-host' }])- expect(calls).toContainEqual([{ name: 'mcp-host-chatllm-egress-gfs', namespace: 'mcp-host' }])+ expect(calls).toContainEqual([+ { name: 'mcp-host-chatllm-egress-codex-proxy', namespace: 'mcp-host' },+ ])expect(calls).toContainEqual([{ name: 'channel-reader-chatllm-egress', namespace: 'channels' }])expect(calls).toContainEqual([{ name: 'rpc-proxy-chatllm-egress-mcp-host', namespace: 'rpc-proxy' },diff --git a/host-context-controller/test/mcpHostRuntimeTokenIssuerClient.test.ts b/host-context-controller/test/mcpHostRuntimeTokenIssuerClient.test.tsindex afc11f380..b5aebd3b3 100644--- a/host-context-controller/test/mcpHostRuntimeTokenIssuerClient.test.ts+++ b/host-context-controller/test/mcpHostRuntimeTokenIssuerClient.test.ts@@ -166,6 +166,22 @@ describe('mcpHostRuntimeTokenIssuerClient (HCC)', () => {expect(claims.jti).toMatch(/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/)})+ it('forwards derived llm:codex:execute in the issuance body', async () => {+ const fetchMock = vi.fn().mockResolvedValue({+ ok: true,+ json: async () => canonicalIssueResponse(),+ } as Response)+ globalThis.fetch = fetchMock as unknown as typeof globalThis.fetch++ const issueMcpHostRuntimeTokens = await loadIssuer()+ await issueMcpHostRuntimeTokens('chatllm', 'host-uid', ['workflow:list', 'llm:codex:execute'])++ const [, init] = fetchMock.mock.calls[0]+ expect((init as RequestInit).body).toBe(+ '{"includeMcpHostControlToken":true,"host":"chatllm","hostUid":"host-uid","workflowControlScopes":["workflow:list","llm:codex:execute"]}'+ )+ })+it('rejects a target namespace that differs from the live Host namespace', async () => {vi.resetModules()process.env.HCC_TARGET_NAMESPACE = 'first-party-hosts'diff --git a/tests/e2e/fixtures/codex-subscription/codex-target-eligibility.json b/tests/e2e/fixtures/codex-subscription/codex-target-eligibility.jsonnew file mode 100644index 000000000..504a09118--- /dev/null+++ b/tests/e2e/fixtures/codex-subscription/codex-target-eligibility.json@@ -0,0 +1,126 @@+{+ "cases": [+ {+ "id": "flag-on-connected-ready",+ "expected": "eligible",+ "spec": { "model": { "provider": "codex-subscription", "name": "gpt-5.3-codex" } },+ "snapshot": {+ "flagEnabled": true,+ "connectionStatus": "connected",+ "catalogContentHash": "aa",+ "catalogRevision": 1,+ "connectionRevision": 1,+ "enabledModels": ["codex-subscription:gpt-5.3-codex"],+ "staleModels": []+ }+ },+ {+ "id": "static-only",+ "expected": "ineligible",+ "spec": { "model": { "provider": "openai", "name": "gpt-5.4-mini" } },+ "snapshot": {+ "flagEnabled": true,+ "connectionStatus": "connected",+ "catalogRevision": 1,+ "connectionRevision": 1,+ "enabledModels": ["openai:gpt-5.4-mini"],+ "staleModels": []+ }+ },+ {+ "id": "flag-off",+ "expected": "ineligible",+ "spec": { "model": { "provider": "codex-subscription", "name": "gpt-5.3-codex" } },+ "snapshot": {+ "flagEnabled": false,+ "connectionStatus": "connected",+ "enabledModels": ["codex-subscription:gpt-5.3-codex"],+ "staleModels": []+ }+ },+ {+ "id": "disconnected",+ "expected": "ineligible",+ "spec": { "model": { "provider": "codex-subscription", "name": "gpt-5.3-codex" } },+ "snapshot": {+ "flagEnabled": true,+ "connectionStatus": "disconnected",+ "enabledModels": ["codex-subscription:gpt-5.3-codex"],+ "staleModels": []+ }+ },+ {+ "id": "reauth",+ "expected": "ineligible",+ "spec": { "model": { "provider": "codex-subscription", "name": "gpt-5.3-codex" } },+ "snapshot": {+ "flagEnabled": true,+ "connectionStatus": "reauth-required",+ "enabledModels": ["codex-subscription:gpt-5.3-codex"],+ "staleModels": []+ }+ },+ {+ "id": "model-stale",+ "expected": "ineligible",+ "spec": { "model": { "provider": "codex-subscription", "name": "gpt-5.3-codex" } },+ "snapshot": {+ "flagEnabled": true,+ "connectionStatus": "connected",+ "enabledModels": ["codex-subscription:gpt-5.3-codex"],+ "staleModels": ["codex-subscription:gpt-5.3-codex"]+ }+ },+ {+ "id": "model-missing",+ "expected": "ineligible",+ "spec": { "model": { "provider": "codex-subscription", "name": "unknown" } },+ "snapshot": {+ "flagEnabled": true,+ "connectionStatus": "connected",+ "enabledModels": ["codex-subscription:gpt-5.3-codex"],+ "staleModels": []+ }+ },+ {+ "id": "snapshot-forbidden",+ "expected": "uncertain",+ "spec": { "model": { "provider": "codex-subscription", "name": "gpt-5.3-codex" } },+ "snapshot": { "flagEnabled": true, "snapshotError": "forbidden" }+ },+ {+ "id": "eligible-fallback",+ "expected": "eligible",+ "spec": {+ "model": { "provider": "openai", "name": "gpt-5.4-mini" },+ "llmPolicy": {+ "fallbacks": [{ "provider": "codex-subscription", "model": "gpt-5.3-codex" }]+ }+ },+ "snapshot": {+ "flagEnabled": true,+ "connectionStatus": "connected",+ "catalogRevision": 1,+ "connectionRevision": 1,+ "enabledModels": ["openai:gpt-5.4-mini", "codex-subscription:gpt-5.3-codex"],+ "staleModels": []+ }+ },+ {+ "id": "stale-fallback-keeps-static",+ "expected": "ineligible",+ "spec": {+ "model": { "provider": "openai", "name": "gpt-5.4-mini" },+ "llmPolicy": {+ "fallbacks": [{ "provider": "codex-subscription", "model": "gpt-5.3-codex" }]+ }+ },+ "snapshot": {+ "flagEnabled": true,+ "connectionStatus": "connected",+ "enabledModels": ["openai:gpt-5.4-mini", "codex-subscription:gpt-5.3-codex"],+ "staleModels": ["codex-subscription:gpt-5.3-codex"]+ }+ }+ ]+}diff --git a/tests/e2e/fixtures/package-lock.json b/tests/e2e/fixtures/package-lock.jsonindex 589af02a6..c8671e8e8 100644--- a/tests/e2e/fixtures/package-lock.json+++ b/tests/e2e/fixtures/package-lock.json@@ -1,12 +1,12 @@{"name": "@clerum/e2e-test-fixtures",- "version": "1.0.62",+ "version": "1.0.63","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "@clerum/e2e-test-fixtures",- "version": "1.0.62",+ "version": "1.0.63","dependencies": {"@kubernetes/client-node": "^1.0.0"},diff --git a/tests/e2e/fixtures/package.json b/tests/e2e/fixtures/package.jsonindex 7c167fed0..9bb90109f 100644--- a/tests/e2e/fixtures/package.json+++ b/tests/e2e/fixtures/package.json@@ -1,6 +1,6 @@{"name": "@clerum/e2e-test-fixtures",- "version": "1.0.62",+ "version": "1.0.63","description": "E2E test fixtures and utilities for Clerum testing","type": "module","main": "index.ts",