Skip to content

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

TypeScript

fix(codex): share one grant snapshot module across HCC, WRC, and mcp-host

Alfredo Lopez4f1f4d68c8bb
diff --git a/.github/workflows/ci-public.yml b/.github/workflows/ci-public.yml
index 19b3d30db..e14f61192 100644
--- a/.github/workflows/ci-public.yml
+++ b/.github/workflows/ci-public.yml
@@ -68,6 +68,7 @@ jobs:
- packages/workflow-sdk
- packages/network-policy-core
- packages/llm-provider-attempt-contract
+ - packages/codex-catalog-projection
- codex-llm-proxy
steps:
@@ -127,10 +128,11 @@ jobs:
# network-policy-core is a hand-authored .cjs + .d.ts with no tsconfig, so
# `tsc --noEmit` resolves no project (like mcp-servers). Its .d.ts is kept
# aligned with the runtime by the "runtime exports stay aligned" node:test.
- # llm-provider-attempt-contract is the same shape: hand-authored .cjs + .d.ts,
- # no tsconfig; node --test keeps the types aligned with the runtime.
+ # llm-provider-attempt-contract and codex-catalog-projection are the same
+ # shape: hand-authored .cjs + .d.ts, no tsconfig; node --test keeps the
+ # types aligned with the runtime.
- name: Typecheck (tsc --noEmit)
- if: matrix.service != 'mcp-servers' && matrix.service != 'packages/desktop-app-links' && matrix.service != 'packages/network-policy-core' && matrix.service != 'packages/llm-provider-attempt-contract'
+ if: matrix.service != 'mcp-servers' && matrix.service != 'packages/desktop-app-links' && matrix.service != 'packages/network-policy-core' && matrix.service != 'packages/llm-provider-attempt-contract' && matrix.service != 'packages/codex-catalog-projection'
working-directory: ${{ matrix.service }}
run: npx tsc --noEmit
diff --git a/control-api/package-lock.json b/control-api/package-lock.json
index 2389b310d..4e7e7446e 100644
--- a/control-api/package-lock.json
+++ b/control-api/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "clerum-control-api",
- "version": "0.1.516",
+ "version": "0.1.517",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "clerum-control-api",
- "version": "0.1.516",
+ "version": "0.1.517",
"dependencies": {
"@clerum/display-field": "file:../packages/display-field",
"@clerum/image-policy": "file:../packages/image-policy",
diff --git a/control-api/package.json b/control-api/package.json
index bb3181d90..f90191797 100644
--- a/control-api/package.json
+++ b/control-api/package.json
@@ -1,6 +1,6 @@
{
"name": "clerum-control-api",
- "version": "0.1.516",
+ "version": "0.1.517",
"description": "Internal Clerum control plane REST API + UI for managing CRDs and secrets",
"main": "dist/main.js",
"engines": {
diff --git a/control-api/test/crd.llmProviderEnums.test.ts b/control-api/test/crd.llmProviderEnums.test.ts
index 54a2b889a..23b883ef9 100644
--- a/control-api/test/crd.llmProviderEnums.test.ts
+++ b/control-api/test/crd.llmProviderEnums.test.ts
@@ -3,6 +3,7 @@ import { readFileSync } from 'node:fs'
import { dirname, resolve } from 'node:path'
import { fileURLToPath } from 'node:url'
import { parse } from 'yaml'
+import { PROVIDER_AUTH_MODE, PROVIDER_IDS } from '@clerum/llm-providers'
// These are CRD-enum (K8s admission) invariants, not control-api code paths:
// a provider missing from a CRD enum is rejected by the apiserver on write. We
@@ -83,4 +84,15 @@ describe('LLM provider CRD enums', () => {
expect(e).not.toContain('bedrock')
}
})
+
+ it('Host and WorkflowRecipe CEL mention every oauth-broker provider', () => {
+ const host = readFileSync(resolve(crdsDir, 'host.yaml'), 'utf8')
+ const recipe = readFileSync(resolve(crdsDir, 'workflowrecipe.yaml'), 'utf8')
+ const brokers = PROVIDER_IDS.filter(id => PROVIDER_AUTH_MODE[id] === 'oauth-broker')
+ expect(brokers.length).toBeGreaterThan(0)
+ for (const id of brokers) {
+ expect(host).toMatch(new RegExp(`provider == '${id}'`))
+ expect(recipe).toMatch(new RegExp(`provider (==|!=) '${id}'`))
+ }
+ })
})
diff --git a/host-context-controller/Dockerfile b/host-context-controller/Dockerfile
index 5ef684218..8cae96d18 100644
--- a/host-context-controller/Dockerfile
+++ b/host-context-controller/Dockerfile
@@ -12,6 +12,7 @@ COPY packages/network-policy-core ./packages/network-policy-core
# host-context-controller's npm ci because it resolves the provider set from it
# (R4).
COPY packages/llm-providers ./packages/llm-providers
+COPY packages/codex-catalog-projection ./packages/codex-catalog-projection
COPY host-context-controller/package*.json ./host-context-controller/
WORKDIR /app/host-context-controller
@@ -39,6 +40,7 @@ COPY packages/network-policy-core ./packages/network-policy-core
# Shared prebuilt data-only providers package (no build step) — same file:
# dependency the production npm ci below resolves against (R4).
COPY packages/llm-providers ./packages/llm-providers
+COPY packages/codex-catalog-projection ./packages/codex-catalog-projection
COPY host-context-controller/package*.json ./host-context-controller/
WORKDIR /app/host-context-controller
RUN npm ci --omit=dev
diff --git a/host-context-controller/Dockerfile.dockerignore b/host-context-controller/Dockerfile.dockerignore
index 2337c390c..957be02ff 100644
--- a/host-context-controller/Dockerfile.dockerignore
+++ b/host-context-controller/Dockerfile.dockerignore
@@ -1,5 +1,7 @@
**
!packages/
+!packages/codex-catalog-projection/
+!packages/codex-catalog-projection/**
!packages/network-policy-core/
!packages/network-policy-core/**
!packages/workflow-recipe-capability-policy/
diff --git a/host-context-controller/package-lock.json b/host-context-controller/package-lock.json
index 4a7a1abf2..6e6ebbfe7 100644
--- a/host-context-controller/package-lock.json
+++ b/host-context-controller/package-lock.json
@@ -1,14 +1,15 @@
{
"name": "clerum-host-context-controller",
- "version": "0.1.261",
+ "version": "0.1.262",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "clerum-host-context-controller",
- "version": "0.1.261",
+ "version": "0.1.262",
"license": "SEE LICENSE IN LICENSE",
"dependencies": {
+ "@clerum/codex-catalog-projection": "file:../packages/codex-catalog-projection",
"@clerum/image-policy": "file:../packages/image-policy",
"@clerum/llm-providers": "file:../packages/llm-providers",
"@clerum/network-policy-core": "file:../packages/network-policy-core",
@@ -29,6 +30,11 @@
"node": ">=24"
}
},
+ "../packages/codex-catalog-projection": {
+ "name": "@clerum/codex-catalog-projection",
+ "version": "0.1.0",
+ "license": "MIT"
+ },
"../packages/image-policy": {
"name": "@clerum/image-policy",
"version": "0.1.0",
@@ -49,6 +55,10 @@
"version": "0.1.0",
"license": "SEE LICENSE IN LICENSE"
},
+ "node_modules/@clerum/codex-catalog-projection": {
+ "resolved": "../packages/codex-catalog-projection",
+ "link": true
+ },
"node_modules/@clerum/image-policy": {
"resolved": "../packages/image-policy",
"link": true
diff --git a/host-context-controller/package.json b/host-context-controller/package.json
index c880b3031..f0176cad1 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.261",
+ "version": "0.1.262",
"description": "Host Context Controller - provides McpServer CRDs to mcp-host via REST API",
"main": "dist/main.js",
"engines": {
@@ -22,6 +22,7 @@
],
"license": "SEE LICENSE IN LICENSE",
"dependencies": {
+ "@clerum/codex-catalog-projection": "file:../packages/codex-catalog-projection",
"@clerum/image-policy": "file:../packages/image-policy",
"@clerum/llm-providers": "file:../packages/llm-providers",
"@clerum/network-policy-core": "file:../packages/network-policy-core",
diff --git a/host-context-controller/src/codexExecutionProjection.ts b/host-context-controller/src/codexExecutionProjection.ts
index 8b65bec9e..a151c6462 100644
--- a/host-context-controller/src/codexExecutionProjection.ts
+++ b/host-context-controller/src/codexExecutionProjection.ts
@@ -1,175 +1,18 @@
-export const CODEX_EXECUTE_SCOPE = 'llm:codex:execute'
-export const CODEX_PROVIDER = 'codex-subscription'
-/** Fail-closed Host sentinel. Empty/missing is not the reserved grant. */
-export const CODEX_UNASSIGNED_CONNECTION_KEY = 'unassigned' as const
-
-export function assignedHostCodexConnectionRef(value?: string | null): string {
- const trimmed = typeof value === 'string' ? value.trim() : ''
- return trimmed || CODEX_UNASSIGNED_CONNECTION_KEY
-}
-
-export function isCodexUnassignedConnectionRef(value?: string | null): boolean {
- return assignedHostCodexConnectionRef(value) === CODEX_UNASSIGNED_CONNECTION_KEY
-}
-
-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'
- | 'revoked'
- | 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; connectionRef?: 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,
- eligibility: input.eligibility,
- })
- return Object.freeze({ ...input, driftHashInput })
-}
+export {
+ CODEX_EXECUTE_SCOPE,
+ CODEX_PROVIDER,
+ CODEX_UNASSIGNED_CONNECTION_KEY,
+ assignedCodexConnectionKey as assignedHostCodexConnectionRef,
+ collectCodexTargets,
+ isCodexUnassignedConnectionKey as isCodexUnassignedConnectionRef,
+ projectCodexExecution,
+} from '@clerum/codex-catalog-projection'
+export type {
+ CodexCatalogSnapshot,
+ CodexEligibility,
+ CodexExecutionProjection,
+ CodexHostSpec,
+ CodexSnapshotError,
+ CodexTarget,
+ CodexTargetSource,
+} from '@clerum/codex-catalog-projection'
diff --git a/host-context-controller/src/hostReconciler.ts b/host-context-controller/src/hostReconciler.ts
index da3047fad..fc44ec5c5 100644
--- a/host-context-controller/src/hostReconciler.ts
+++ b/host-context-controller/src/hostReconciler.ts
@@ -8,7 +8,6 @@ import {
type CodexCatalogSnapshot,
type CodexExecutionProjection,
assignedHostCodexConnectionRef,
- isCodexUnassignedConnectionRef,
projectCodexExecution,
} from './codexExecutionProjection'
import { config } from './config'
@@ -34,6 +33,7 @@ import {
import {
ALLOWED_MODELS_CONFIGMAP_NAME,
parseAllowedModelsSnapshot,
+ snapshotForAssignedCodexGrant,
snapshotFromConfigMapError,
} from './llmAllowedModelsSnapshot'
import { hccLogger } from './logger'
@@ -1381,19 +1381,11 @@ export class HostReconciler {
private projectCodexForHost(host: HostCRD): CodexExecutionProjection {
const connectionKey = assignedHostCodexConnectionRef(host.spec.model?.connectionRef)
- if (isCodexUnassignedConnectionRef(connectionKey)) {
- // Missing/empty is not the reserved grant. Do not project execute scope
- // or proxy egress from deployment-default just because the field was omitted.
- return projectCodexExecution(host.spec, {
- flagEnabled: this.codexSnapshot.flagEnabled,
- connectionStatus: 'disconnected',
- enabledModels: [],
- staleModels: [],
- })
- }
- const snapshot = this.lastCodexConfigMap
- ? parseAllowedModelsSnapshot(this.lastCodexConfigMap, connectionKey)
- : this.codexSnapshot
+ const snapshot = snapshotForAssignedCodexGrant(
+ connectionKey,
+ this.lastCodexConfigMap,
+ this.codexSnapshot
+ )
return projectCodexExecution(host.spec, snapshot)
}
diff --git a/host-context-controller/src/llmAllowedModelsSnapshot.ts b/host-context-controller/src/llmAllowedModelsSnapshot.ts
index 78e6ef5e0..3dcfd4f33 100644
--- a/host-context-controller/src/llmAllowedModelsSnapshot.ts
+++ b/host-context-controller/src/llmAllowedModelsSnapshot.ts
@@ -1,133 +1,12 @@
-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 const CODEX_CONNECTIONS_ANNOTATION = 'clerum.io/codex-connections'
-
-export function snapshotFromConfigMapError(error: CodexSnapshotError): CodexCatalogSnapshot {
- return { flagEnabled: false, snapshotError: error }
-}
-
-const CODEX_PROVIDER_PREFIX = 'codex-subscription:'
-
-function dropCodexModels(enabledModels: Set<string>, staleModels: Set<string>): void {
- for (const key of [...enabledModels]) {
- if (key.startsWith(CODEX_PROVIDER_PREFIX)) {
- enabledModels.delete(key)
- staleModels.delete(key)
- }
- }
-}
-
-function intersectCodexModels(
- enabledModels: Set<string>,
- staleModels: Set<string>,
- models: string[] | undefined,
- _connectionKey: string
-): void {
- if (!Array.isArray(models)) {
- dropCodexModels(enabledModels, staleModels)
- return
- }
- const allowed = new Set(models.filter(model => typeof model === 'string' && model.trim()))
- for (const key of [...enabledModels]) {
- if (!key.startsWith(CODEX_PROVIDER_PREFIX)) continue
- const model = key.slice(CODEX_PROVIDER_PREFIX.length)
- if (!allowed.has(model)) {
- enabledModels.delete(key)
- staleModels.delete(key)
- }
- }
-}
-
-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,
- connectionKey = 'unassigned'
-): 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')
- }
- }
- let catalogRevision = parseOptionalIntegerAnnotation(annotations, CATALOG_REVISION_ANNOTATION)
- let connectionRevision = parseOptionalIntegerAnnotation(
- annotations,
- CONNECTION_REVISION_ANNOTATION
- )
- if (catalogRevision === 'invalid' || connectionRevision === 'invalid') {
- return snapshotFromConfigMapError('malformed')
- }
- let connectionStatus =
- (annotations[CODEX_CONNECTION_STATUS_ANNOTATION] as CodexCatalogSnapshot['connectionStatus']) ??
- null
- const rawMap = annotations[CODEX_CONNECTIONS_ANNOTATION]
- if (rawMap) {
- try {
- const parsed = JSON.parse(rawMap) as Record<
- string,
- {
- status?: string
- catalogRevision?: number
- connectionRevision?: number
- models?: string[]
- }
- >
- const assigned = parsed[connectionKey]
- if (assigned) {
- connectionStatus =
- (assigned.status as CodexCatalogSnapshot['connectionStatus']) ?? connectionStatus
- if (Number.isInteger(assigned.catalogRevision)) {
- catalogRevision = assigned.catalogRevision as number
- }
- if (Number.isInteger(assigned.connectionRevision)) {
- connectionRevision = assigned.connectionRevision as number
- }
- intersectCodexModels(enabledModels, staleModels, assigned.models, connectionKey)
- } else {
- connectionStatus = 'disconnected'
- dropCodexModels(enabledModels, staleModels)
- }
- } catch {
- return snapshotFromConfigMapError('malformed')
- }
- }
- // No connections map: keep the flat catalog (legacy single-grant). Do not
- // invent deployment-default; a multi-grant map already fail-closed above.
- return {
- flagEnabled: annotations[CODEX_ENABLED_ANNOTATION] === 'true',
- connectionStatus,
- catalogContentHash: annotations[CONTENT_HASH_ANNOTATION] ?? null,
- catalogRevision,
- connectionRevision,
- enabledModels,
- staleModels,
- }
-}
+export {
+ ALLOWED_MODELS_CONFIGMAP_NAME,
+ CATALOG_REVISION_ANNOTATION,
+ CODEX_CONNECTIONS_ANNOTATION,
+ CODEX_CONNECTION_STATUS_ANNOTATION,
+ CODEX_ENABLED_ANNOTATION,
+ CONNECTION_REVISION_ANNOTATION,
+ CONTENT_HASH_ANNOTATION,
+ parseAllowedModelsSnapshot,
+ snapshotForAssignedCodexGrant,
+ snapshotFromConfigMapError,
+} from '@clerum/codex-catalog-projection'
diff --git a/mcp-host/Dockerfile b/mcp-host/Dockerfile
index 94f2ead19..5331cdff2 100644
--- a/mcp-host/Dockerfile
+++ b/mcp-host/Dockerfile
@@ -15,6 +15,7 @@ WORKDIR /app
# Shared prebuilt data-only package (no build step — ships index.cjs + .d.ts).
COPY packages/llm-providers ./packages/llm-providers
COPY packages/llm-provider-attempt-contract ./packages/llm-provider-attempt-contract
+COPY packages/codex-catalog-projection ./packages/codex-catalog-projection
# Install dependencies (file: deps resolve to ../packages/llm-providers and
# ../packages/llm-provider-attempt-contract)
@@ -37,6 +38,7 @@ WORKDIR /app
# Copy the shared package + package files, install production dependencies only
COPY packages/llm-providers ./packages/llm-providers
COPY packages/llm-provider-attempt-contract ./packages/llm-provider-attempt-contract
+COPY packages/codex-catalog-projection ./packages/codex-catalog-projection
COPY mcp-host/package*.json ./mcp-host/
WORKDIR /app/mcp-host
RUN npm ci --only=production
diff --git a/mcp-host/Dockerfile.desktop b/mcp-host/Dockerfile.desktop
index 7d120449c..c0efaeb13 100644
--- a/mcp-host/Dockerfile.desktop
+++ b/mcp-host/Dockerfile.desktop
@@ -6,6 +6,7 @@ FROM node:24.16.0-alpine@sha256:21f403ab171f2dc89bad4dd69d7721bfd15f084ccb46cdd2
WORKDIR /app
COPY packages/llm-providers ./packages/llm-providers
COPY packages/llm-provider-attempt-contract ./packages/llm-provider-attempt-contract
+COPY packages/codex-catalog-projection ./packages/codex-catalog-projection
COPY mcp-host/package*.json ./mcp-host/
WORKDIR /app/mcp-host
RUN npm ci
@@ -48,6 +49,7 @@ ENV PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD=1
WORKDIR /app
COPY packages/llm-providers ./packages/llm-providers
COPY packages/llm-provider-attempt-contract ./packages/llm-provider-attempt-contract
+COPY packages/codex-catalog-projection ./packages/codex-catalog-projection
COPY --from=builder /app/mcp-host/package*.json ./mcp-host/
WORKDIR /app/mcp-host
RUN npm ci --omit=dev
diff --git a/mcp-host/Dockerfile.full b/mcp-host/Dockerfile.full
index 65d8abee1..c90a6630b 100644
--- a/mcp-host/Dockerfile.full
+++ b/mcp-host/Dockerfile.full
@@ -13,6 +13,7 @@ WORKDIR /app
# Shared prebuilt data-only package (no build step — ships index.cjs + .d.ts).
COPY packages/llm-providers ./packages/llm-providers
COPY packages/llm-provider-attempt-contract ./packages/llm-provider-attempt-contract
+COPY packages/codex-catalog-projection ./packages/codex-catalog-projection
# Install dependencies (file: deps resolve to ../packages/llm-providers and
# ../packages/llm-provider-attempt-contract)
@@ -45,6 +46,7 @@ RUN apt-get update && apt-get install -y --no-install-recommends \
# Copy the shared package + package files, install production dependencies only
COPY packages/llm-providers ./packages/llm-providers
COPY packages/llm-provider-attempt-contract ./packages/llm-provider-attempt-contract
+COPY packages/codex-catalog-projection ./packages/codex-catalog-projection
COPY mcp-host/package*.json ./mcp-host/
WORKDIR /app/mcp-host
RUN npm ci --only=production
diff --git a/mcp-host/Dockerfile.slim b/mcp-host/Dockerfile.slim
index 21f70dc36..79feed2b6 100644
--- a/mcp-host/Dockerfile.slim
+++ b/mcp-host/Dockerfile.slim
@@ -13,6 +13,7 @@ WORKDIR /app
# Shared prebuilt data-only package (no build step — ships index.cjs + .d.ts).
COPY packages/llm-providers ./packages/llm-providers
COPY packages/llm-provider-attempt-contract ./packages/llm-provider-attempt-contract
+COPY packages/codex-catalog-projection ./packages/codex-catalog-projection
# Install dependencies (file: deps resolve to ../packages/llm-providers and
# ../packages/llm-provider-attempt-contract)
@@ -48,6 +49,7 @@ RUN apt-get update && apt-get install -y --no-install-recommends \
# Copy the shared package + package files, install production dependencies only
COPY packages/llm-providers ./packages/llm-providers
COPY packages/llm-provider-attempt-contract ./packages/llm-provider-attempt-contract
+COPY packages/codex-catalog-projection ./packages/codex-catalog-projection
COPY mcp-host/package*.json ./mcp-host/
WORKDIR /app/mcp-host
RUN npm ci --only=production
diff --git a/mcp-host/package-lock.json b/mcp-host/package-lock.json
index d1e8a65ee..42c30df1b 100644
--- a/mcp-host/package-lock.json
+++ b/mcp-host/package-lock.json
@@ -1,16 +1,17 @@
{
"name": "clerum-mcp-host",
- "version": "0.1.294",
+ "version": "0.1.295",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "clerum-mcp-host",
- "version": "0.1.294",
+ "version": "0.1.295",
"license": "SEE LICENSE IN LICENSE",
"dependencies": {
"@anthropic-ai/sdk": "^0.32.0",
"@aws-sdk/client-bedrock-runtime": "^3.895.0",
+ "@clerum/codex-catalog-projection": "file:../packages/codex-catalog-projection",
"@clerum/llm-provider-attempt-contract": "file:../packages/llm-provider-attempt-contract",
"@clerum/llm-providers": "file:../packages/llm-providers",
"@google/genai": "^2.10.0",
@@ -60,6 +61,11 @@
"node": ">=24"
}
},
+ "../packages/codex-catalog-projection": {
+ "name": "@clerum/codex-catalog-projection",
+ "version": "0.1.0",
+ "license": "MIT"
+ },
"../packages/llm-provider-attempt-contract": {
"name": "@clerum/llm-provider-attempt-contract",
"version": "0.1.0",
@@ -532,6 +538,10 @@
"node": ">=18.0.0"
}
},
+ "node_modules/@clerum/codex-catalog-projection": {
+ "resolved": "../packages/codex-catalog-projection",
+ "link": true
+ },
"node_modules/@clerum/llm-provider-attempt-contract": {
"resolved": "../packages/llm-provider-attempt-contract",
"link": true
diff --git a/mcp-host/package.json b/mcp-host/package.json
index c41892d9d..5a3c9292e 100644
--- a/mcp-host/package.json
+++ b/mcp-host/package.json
@@ -1,6 +1,6 @@
{
"name": "clerum-mcp-host",
- "version": "0.1.294",
+ "version": "0.1.295",
"description": "MCP Host - reads Host CRD and provides LLM access via OpenAI/Claude",
"main": "dist/main.js",
"engines": {
@@ -27,6 +27,7 @@
"dependencies": {
"@anthropic-ai/sdk": "^0.32.0",
"@aws-sdk/client-bedrock-runtime": "^3.895.0",
+ "@clerum/codex-catalog-projection": "file:../packages/codex-catalog-projection",
"@clerum/llm-provider-attempt-contract": "file:../packages/llm-provider-attempt-contract",
"@clerum/llm-providers": "file:../packages/llm-providers",
"@google/genai": "^2.10.0",
diff --git a/mcp-host/src/config/configStore.test.ts b/mcp-host/src/config/configStore.test.ts
index 799203fea..2d5dd7720 100644
--- a/mcp-host/src/config/configStore.test.ts
+++ b/mcp-host/src/config/configStore.test.ts
@@ -972,8 +972,7 @@ describe('ConfigStore — allowlist tier (R3)', () => {
})
store = built.store
await store.start()
- expect(store.codexPolicyBinding()?.connectionKey).toBe('personal-pro')
- expect(store.codexPolicyBinding()?.models).toEqual([])
+ expect(store.codexPolicyBinding()).toBeNull()
expect(store.allowedModels().get('codex-subscription')).toEqual([])
})
})
diff --git a/mcp-host/src/config/configStore.ts b/mcp-host/src/config/configStore.ts
index 1bbb8ede0..f19a8dde8 100644
--- a/mcp-host/src/config/configStore.ts
+++ b/mcp-host/src/config/configStore.ts
@@ -30,7 +30,14 @@
* backoff; on "too old" the watch falls back to a fresh list and resumes.
*/
import * as k8s from '@kubernetes/client-node'
-import { CODEX_UNASSIGNED_CONNECTION_KEY, assignedConnectionRef } from '../llm/hostLlmBinding'
+import {
+ CATALOG_REVISION_ANNOTATION,
+ CODEX_CONNECTIONS_ANNOTATION,
+ CONNECTION_REVISION_ANNOTATION,
+ type CodexPolicyBinding,
+ toPolicyBinding,
+} from '@clerum/codex-catalog-projection'
+import { assignedConnectionRef } from '../llm/hostLlmBinding'
import {
ALL_PROVIDERS,
ALL_PROVIDER_SLOT_ENV_NAMES,
@@ -114,16 +121,8 @@ export interface AllowedModelEntry {
* Codex attempt. Annotation names are a cross-service contract with
* control-api, HCC, and WRC.
*/
-export type CodexPolicyBinding = {
- catalogRevision: number
- credentialRevision: number
- connectionKey: string
- models?: string[]
-}
-
-export const CATALOG_REVISION_ANNOTATION = 'clerum.io/catalog-revision'
-export const CONNECTION_REVISION_ANNOTATION = 'clerum.io/connection-revision'
-export const CODEX_CONNECTIONS_ANNOTATION = 'clerum.io/codex-connections'
+export type { CodexPolicyBinding }
+export { CATALOG_REVISION_ANNOTATION, CONNECTION_REVISION_ANNOTATION, CODEX_CONNECTIONS_ANNOTATION }
export type ConfigStoreChangeHandler = (change: ConfigStoreChange) => void
@@ -560,10 +559,7 @@ export class ConfigStore {
data?: Record<string, string>
metadata?: { annotations?: Record<string, string> }
}): boolean {
- const nextBinding = parseCodexPolicyBinding(
- cm.metadata?.annotations,
- assignedConnectionRef(this.opts.connectionRef)
- )
+ const nextBinding = toPolicyBinding(cm, assignedConnectionRef(this.opts.connectionRef))
const modelsChanged = this.applyAllowlistData(cm.data ?? {}, nextBinding)
const bindingChanged = !codexBindingsEqual(this.codexBinding, nextBinding)
this.codexBinding = nextBinding
@@ -926,66 +922,6 @@ interface KubeObject {
data?: Record<string, string>
}
-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'
-}
-
-function parseCodexPolicyBinding(
- annotations: Record<string, string> | undefined,
- connectionKey: string = CODEX_UNASSIGNED_CONNECTION_KEY
-): CodexPolicyBinding | null {
- if (!annotations || connectionKey === CODEX_UNASSIGNED_CONNECTION_KEY) return null
- let catalogRevision = parseOptionalIntegerAnnotation(annotations, CATALOG_REVISION_ANNOTATION)
- let credentialRevision = parseOptionalIntegerAnnotation(
- annotations,
- CONNECTION_REVISION_ANNOTATION
- )
- const rawMap = annotations[CODEX_CONNECTIONS_ANNOTATION]
- if (rawMap) {
- try {
- const parsed = JSON.parse(rawMap) as Record<
- string,
- { catalogRevision?: number; connectionRevision?: number; models?: string[] }
- >
- const assigned = parsed[connectionKey]
- if (
- assigned &&
- Number.isInteger(assigned.catalogRevision) &&
- Number.isInteger(assigned.connectionRevision)
- ) {
- catalogRevision = assigned.catalogRevision as number
- credentialRevision = assigned.connectionRevision as number
- return {
- catalogRevision,
- credentialRevision,
- connectionKey,
- models: Array.isArray(assigned.models) ? assigned.models.filter(Boolean) : [],
- }
- }
- return null
- } catch {
- return null
- }
- }
- // No connections map: keep the flat catalog for any assigned grant (legacy
- // single-grant). Do not invent deployment-default for unassigned — that
- // already returned null above. Named keys must match HCC/WRC.
- if (
- catalogRevision === null ||
- catalogRevision === 'invalid' ||
- credentialRevision === null ||
- credentialRevision === 'invalid'
- ) {
- return null
- }
- return { catalogRevision, credentialRevision, connectionKey }
-}
-
function codexBindingsEqual(a: CodexPolicyBinding | null, b: CodexPolicyBinding | null): boolean {
if (a === b) return true
if (!a || !b) return false
diff --git a/mcp-host/src/llm/codexPolicyBinding.ts b/mcp-host/src/llm/codexPolicyBinding.ts
index 36a19d8bc..520f731c0 100644
--- a/mcp-host/src/llm/codexPolicyBinding.ts
+++ b/mcp-host/src/llm/codexPolicyBinding.ts
@@ -1,12 +1,9 @@
+import type { CodexPolicyBinding } from '@clerum/codex-catalog-projection'
import { computeCodexPolicyHash } from '@clerum/llm-provider-attempt-contract'
const POLICY_HASH_RE = /^[a-f0-9]{64}$/
-export type CodexPolicyBinding = {
- catalogRevision: number
- credentialRevision: number
- connectionKey?: string
-}
+export type { CodexPolicyBinding }
export type CodexAttemptPolicy = {
policyRevision: number
diff --git a/packages/codex-catalog-projection/fixtures/allowlist-views.json b/packages/codex-catalog-projection/fixtures/allowlist-views.json
new file mode 100644
index 000000000..f5b6cb6dc
--- /dev/null
+++ b/packages/codex-catalog-projection/fixtures/allowlist-views.json
@@ -0,0 +1,52 @@
+{
+ "mapped": {
+ "metadata": {
+ "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",
+ "clerum.io/codex-connections": {
+ "deployment-default": {
+ "status": "connected",
+ "catalogRevision": 1,
+ "connectionRevision": 1,
+ "models": ["gpt-5.3-codex"]
+ },
+ "team-plus": {
+ "status": "revoked",
+ "catalogRevision": 3,
+ "connectionRevision": 8,
+ "models": ["gpt-5.3-codex"]
+ },
+ "personal-pro": {
+ "status": "connected",
+ "catalogRevision": 4,
+ "connectionRevision": 2,
+ "models": ["gpt-5.1"]
+ }
+ }
+ }
+ },
+ "data": {
+ "codex-subscription": "[{\"model\":\"gpt-5.3-codex\",\"stale\":false},{\"model\":\"gpt-5.1\",\"stale\":false}]",
+ "openai": "[{\"model\":\"gpt-4\"}]"
+ }
+ },
+ "legacy": {
+ "metadata": {
+ "annotations": {
+ "clerum.io/content-hash": "bb",
+ "clerum.io/catalog-revision": "4",
+ "clerum.io/connection-revision": "2",
+ "clerum.io/codex-connection-status": "connected",
+ "clerum.io/codex-enabled": "true"
+ }
+ },
+ "data": {
+ "codex-subscription": "[{\"model\":\"gpt-5.3-codex\"},{\"model\":\"gpt-5.1\"}]",
+ "openai": "[{\"model\":\"gpt-4\"}]"
+ }
+ }
+}
diff --git a/packages/codex-catalog-projection/index.cjs b/packages/codex-catalog-projection/index.cjs
new file mode 100644
index 000000000..4f7834463
--- /dev/null
+++ b/packages/codex-catalog-projection/index.cjs
@@ -0,0 +1,325 @@
+'use strict'
+
+const ALLOWED_MODELS_CONFIGMAP_NAME = 'clerum-llm-allowed-models'
+const CONTENT_HASH_ANNOTATION = 'clerum.io/content-hash'
+const CATALOG_REVISION_ANNOTATION = 'clerum.io/catalog-revision'
+const CONNECTION_REVISION_ANNOTATION = 'clerum.io/connection-revision'
+const CODEX_CONNECTION_STATUS_ANNOTATION = 'clerum.io/codex-connection-status'
+const CODEX_ENABLED_ANNOTATION = 'clerum.io/codex-enabled'
+const CODEX_CONNECTIONS_ANNOTATION = 'clerum.io/codex-connections'
+const CODEX_CONNECTION_REF_ANNOTATION = 'clerum.io/codex-connection-ref'
+const CODEX_UNASSIGNED_CONNECTION_KEY = 'unassigned'
+const CODEX_PROVIDER = 'codex-subscription'
+const CODEX_EXECUTE_SCOPE = 'llm:codex:execute'
+const CODEX_PROVIDER_PREFIX = `${CODEX_PROVIDER}:`
+
+function assignedCodexConnectionKey(value) {
+ const trimmed = typeof value === 'string' ? value.trim() : ''
+ return trimmed || CODEX_UNASSIGNED_CONNECTION_KEY
+}
+
+function isCodexUnassignedConnectionKey(value) {
+ return assignedCodexConnectionKey(value) === CODEX_UNASSIGNED_CONNECTION_KEY
+}
+
+function snapshotFromConfigMapError(error) {
+ return { flagEnabled: false, snapshotError: error }
+}
+
+function parseOptionalIntegerAnnotation(annotations, key) {
+ if (!annotations || !Object.prototype.hasOwnProperty.call(annotations, key)) return null
+ const parsed = Number(annotations[key])
+ return Number.isInteger(parsed) ? parsed : 'invalid'
+}
+
+function dropCodexModels(enabledModels, staleModels) {
+ for (const key of [...enabledModels]) {
+ if (key.startsWith(CODEX_PROVIDER_PREFIX)) {
+ enabledModels.delete(key)
+ staleModels.delete(key)
+ }
+ }
+}
+
+function intersectCodexModels(enabledModels, staleModels, models) {
+ const allowed = new Set(models.filter(model => typeof model === 'string' && model.trim()))
+ for (const key of [...enabledModels]) {
+ if (!key.startsWith(CODEX_PROVIDER_PREFIX)) continue
+ const model = key.slice(CODEX_PROVIDER_PREFIX.length)
+ if (!allowed.has(model)) {
+ enabledModels.delete(key)
+ staleModels.delete(key)
+ }
+ }
+}
+
+function parseFlatCatalog(data) {
+ const enabledModels = new Set()
+ const staleModels = new Set()
+ for (const [provider, raw] of Object.entries(data ?? {})) {
+ let rows
+ try {
+ rows = JSON.parse(raw)
+ } catch {
+ return { error: 'malformed' }
+ }
+ if (!Array.isArray(rows)) return { error: 'malformed' }
+ for (const row of rows) {
+ if (row && typeof row.model === 'string' && row.model.trim()) {
+ const key = `${provider}:${row.model}`
+ enabledModels.add(key)
+ if (row.stale === true) staleModels.add(key)
+ }
+ }
+ }
+ return { enabledModels, staleModels }
+}
+
+function parseAllowedModelsSnapshot(cm, connectionKey) {
+ if (!cm) return snapshotFromConfigMapError('missing')
+ const annotations = (cm.metadata && cm.metadata.annotations) || {}
+ const catalog = parseFlatCatalog(cm.data)
+ if (catalog.error) return snapshotFromConfigMapError('malformed')
+ const enabledModels = catalog.enabledModels
+ const staleModels = catalog.staleModels
+ let catalogRevision = parseOptionalIntegerAnnotation(annotations, CATALOG_REVISION_ANNOTATION)
+ let connectionRevision = parseOptionalIntegerAnnotation(
+ annotations,
+ CONNECTION_REVISION_ANNOTATION
+ )
+ if (catalogRevision === 'invalid' || connectionRevision === 'invalid') {
+ return snapshotFromConfigMapError('malformed')
+ }
+ let connectionStatus = annotations[CODEX_CONNECTION_STATUS_ANNOTATION] || null
+ const assignedKey = assignedCodexConnectionKey(connectionKey)
+ const rawMap = annotations[CODEX_CONNECTIONS_ANNOTATION]
+ if (rawMap) {
+ let parsed
+ try {
+ parsed = JSON.parse(rawMap)
+ } catch {
+ return snapshotFromConfigMapError('malformed')
+ }
+ if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {
+ return snapshotFromConfigMapError('malformed')
+ }
+ const assigned = parsed[assignedKey]
+ // Mapped miss OR models[] omitted: disconnected, empty Codex, no rematch.
+ if (!assigned || !Array.isArray(assigned.models)) {
+ connectionStatus = 'disconnected'
+ dropCodexModels(enabledModels, staleModels)
+ } else {
+ connectionStatus = assigned.status || connectionStatus
+ if (Number.isInteger(assigned.catalogRevision)) {
+ catalogRevision = assigned.catalogRevision
+ }
+ if (Number.isInteger(assigned.connectionRevision)) {
+ connectionRevision = assigned.connectionRevision
+ }
+ intersectCodexModels(enabledModels, staleModels, assigned.models)
+ }
+ } else if (assignedKey === CODEX_UNASSIGNED_CONNECTION_KEY) {
+ // Unassigned never inherits a legacy flat catalog.
+ connectionStatus = 'disconnected'
+ dropCodexModels(enabledModels, staleModels)
+ }
+ return {
+ flagEnabled: annotations[CODEX_ENABLED_ANNOTATION] === 'true',
+ connectionStatus,
+ catalogContentHash: annotations[CONTENT_HASH_ANNOTATION] ?? null,
+ catalogRevision,
+ connectionRevision,
+ enabledModels,
+ staleModels,
+ }
+}
+
+function snapshotForAssignedCodexGrant(connectionKey, lastConfigMap, fallback) {
+ const key = assignedCodexConnectionKey(connectionKey)
+ if (key === CODEX_UNASSIGNED_CONNECTION_KEY) {
+ return {
+ flagEnabled: Boolean(fallback && fallback.flagEnabled),
+ connectionStatus: 'disconnected',
+ enabledModels: [],
+ staleModels: [],
+ }
+ }
+ if (!lastConfigMap) return fallback
+ return parseAllowedModelsSnapshot(lastConfigMap, key)
+}
+
+function collectCodexTargets(spec) {
+ const targets = []
+ if (spec && spec.model && spec.model.provider) {
+ targets.push({
+ source: 'primary',
+ provider: spec.model.provider,
+ model: spec.model.name ?? '',
+ })
+ }
+ for (const row of (spec && spec.allowedModels) || []) {
+ if (row && row.provider) {
+ targets.push({ source: 'allowed', provider: row.provider, model: row.model ?? '' })
+ }
+ }
+ for (const row of (spec && spec.llmPolicy && spec.llmPolicy.fallbacks) || []) {
+ if (row && row.provider) {
+ targets.push({ source: 'fallback', provider: row.provider, model: row.model ?? '' })
+ }
+ }
+ return targets
+}
+
+function freezeProjection(input) {
+ const driftHashInput = JSON.stringify({
+ eligibleTargets: input.eligibleTargets,
+ derivedScopes: input.derivedScopes,
+ eligibility: input.eligibility,
+ })
+ return Object.freeze({ ...input, driftHashInput })
+}
+
+function projectCodexExecution(spec, snapshot) {
+ 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 toPolicyBinding(cm, connectionKey) {
+ const key = assignedCodexConnectionKey(connectionKey)
+ if (!cm || key === CODEX_UNASSIGNED_CONNECTION_KEY) return null
+ const annotations = (cm.metadata && cm.metadata.annotations) || {}
+ let catalogRevision = parseOptionalIntegerAnnotation(annotations, CATALOG_REVISION_ANNOTATION)
+ let credentialRevision = parseOptionalIntegerAnnotation(
+ annotations,
+ CONNECTION_REVISION_ANNOTATION
+ )
+ const rawMap = annotations[CODEX_CONNECTIONS_ANNOTATION]
+ if (rawMap) {
+ let parsed
+ try {
+ parsed = JSON.parse(rawMap)
+ } catch {
+ return null
+ }
+ if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) return null
+ const assigned = parsed[key]
+ if (
+ !assigned ||
+ !Array.isArray(assigned.models) ||
+ !Number.isInteger(assigned.catalogRevision) ||
+ !Number.isInteger(assigned.connectionRevision)
+ ) {
+ return null
+ }
+ return {
+ catalogRevision: assigned.catalogRevision,
+ credentialRevision: assigned.connectionRevision,
+ connectionKey: key,
+ models: assigned.models.filter(model => typeof model === 'string' && model),
+ }
+ }
+ if (
+ catalogRevision === null ||
+ catalogRevision === 'invalid' ||
+ credentialRevision === null ||
+ credentialRevision === 'invalid'
+ ) {
+ return null
+ }
+ return { catalogRevision, credentialRevision, connectionKey: key }
+}
+
+module.exports = {
+ ALLOWED_MODELS_CONFIGMAP_NAME,
+ CONTENT_HASH_ANNOTATION,
+ CATALOG_REVISION_ANNOTATION,
+ CONNECTION_REVISION_ANNOTATION,
+ CODEX_CONNECTION_STATUS_ANNOTATION,
+ CODEX_ENABLED_ANNOTATION,
+ CODEX_CONNECTIONS_ANNOTATION,
+ CODEX_CONNECTION_REF_ANNOTATION,
+ CODEX_UNASSIGNED_CONNECTION_KEY,
+ CODEX_PROVIDER,
+ CODEX_EXECUTE_SCOPE,
+ assignedCodexConnectionKey,
+ isCodexUnassignedConnectionKey,
+ snapshotFromConfigMapError,
+ parseAllowedModelsSnapshot,
+ snapshotForAssignedCodexGrant,
+ collectCodexTargets,
+ projectCodexExecution,
+ toPolicyBinding,
+}
diff --git a/packages/codex-catalog-projection/index.d.ts b/packages/codex-catalog-projection/index.d.ts
new file mode 100644
index 000000000..b92313950
--- /dev/null
+++ b/packages/codex-catalog-projection/index.d.ts
@@ -0,0 +1,105 @@
+/**
+ * @clerum/codex-catalog-projection — shared grant snapshot and Codex
+ * execution projection for HCC, WRC, and mcp-host.
+ *
+ * Pure module: structural ConfigMap view only. No Kubernetes client, no
+ * network, no `normalizeCodexConnectionKey` (that alias is a control-api
+ * OAuth/DB reserved key, not a Host/recipe reader).
+ */
+
+export declare const ALLOWED_MODELS_CONFIGMAP_NAME: 'clerum-llm-allowed-models'
+export declare const CONTENT_HASH_ANNOTATION: 'clerum.io/content-hash'
+export declare const CATALOG_REVISION_ANNOTATION: 'clerum.io/catalog-revision'
+export declare const CONNECTION_REVISION_ANNOTATION: 'clerum.io/connection-revision'
+export declare const CODEX_CONNECTION_STATUS_ANNOTATION: 'clerum.io/codex-connection-status'
+export declare const CODEX_ENABLED_ANNOTATION: 'clerum.io/codex-enabled'
+export declare const CODEX_CONNECTIONS_ANNOTATION: 'clerum.io/codex-connections'
+export declare const CODEX_CONNECTION_REF_ANNOTATION: 'clerum.io/codex-connection-ref'
+export declare const CODEX_UNASSIGNED_CONNECTION_KEY: 'unassigned'
+export declare const CODEX_PROVIDER: 'codex-subscription'
+export declare const CODEX_EXECUTE_SCOPE: 'llm:codex:execute'
+
+export type CodexConfigMapView = {
+ metadata?: { annotations?: Record<string, string> | null } | null
+ data?: Record<string, string> | null
+}
+
+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 CodexConnectionStatus =
+ | 'connected'
+ | 'disconnected'
+ | 'reauth-required'
+ | 'unavailable'
+ | 'revoked'
+ | null
+
+export type CodexCatalogSnapshot = {
+ flagEnabled: boolean
+ connectionStatus?: CodexConnectionStatus
+ 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; connectionRef?: 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 type CodexPolicyBinding = {
+ catalogRevision: number
+ credentialRevision: number
+ connectionKey?: string
+ models?: string[]
+}
+
+/** Empty or missing → `unassigned`. Never aliases `deployment-default`. */
+export declare function assignedCodexConnectionKey(value?: string | null): string
+export declare function isCodexUnassignedConnectionKey(value?: string | null): boolean
+export declare function snapshotFromConfigMapError(error: CodexSnapshotError): CodexCatalogSnapshot
+export declare function parseAllowedModelsSnapshot(
+ cm: CodexConfigMapView | undefined | null,
+ connectionKey?: string
+): CodexCatalogSnapshot
+export declare function snapshotForAssignedCodexGrant(
+ connectionKey: string,
+ lastConfigMap: CodexConfigMapView | undefined | null,
+ fallback: CodexCatalogSnapshot
+): CodexCatalogSnapshot
+export declare function collectCodexTargets(spec: CodexHostSpec): CodexTarget[]
+export declare function projectCodexExecution(
+ spec: CodexHostSpec,
+ snapshot: CodexCatalogSnapshot
+): CodexExecutionProjection
+export declare function toPolicyBinding(
+ cm: CodexConfigMapView | undefined | null,
+ connectionKey?: string
+): CodexPolicyBinding | null
diff --git a/packages/codex-catalog-projection/index.test.cjs b/packages/codex-catalog-projection/index.test.cjs
new file mode 100644
index 000000000..d79a99ec0
--- /dev/null
+++ b/packages/codex-catalog-projection/index.test.cjs
@@ -0,0 +1,160 @@
+'use strict'
+
+const assert = require('node:assert/strict')
+const fs = require('node:fs')
+const path = require('node:path')
+const test = require('node:test')
+const projection = require('./index.cjs')
+
+const FIXTURE = JSON.parse(
+ fs.readFileSync(path.join(__dirname, 'fixtures/allowlist-views.json'), 'utf8')
+)
+
+function withConnections(view, rewrite) {
+ const parsed = JSON.parse(
+ typeof view.metadata.annotations['clerum.io/codex-connections'] === 'string'
+ ? view.metadata.annotations['clerum.io/codex-connections']
+ : JSON.stringify(view.metadata.annotations['clerum.io/codex-connections'])
+ )
+ rewrite(parsed)
+ return {
+ metadata: {
+ annotations: {
+ ...view.metadata.annotations,
+ 'clerum.io/codex-connections': JSON.stringify(parsed),
+ },
+ },
+ data: view.data,
+ }
+}
+
+function mappedView() {
+ return withConnections(FIXTURE.mapped, () => {})
+}
+
+test('runtime exports stay aligned with the declaration file', () => {
+ const declarations = fs.readFileSync(path.join(__dirname, 'index.d.ts'), 'utf8')
+ const declared = Array.from(
+ declarations.matchAll(/export declare (?:const|function)\s+([A-Za-z0-9_]+)/g),
+ m => m[1]
+ ).sort()
+ assert.deepEqual(Object.keys(projection).sort(), declared)
+})
+
+test('assignedCodexConnectionKey treats empty as unassigned and never invents deployment-default', () => {
+ assert.equal(projection.assignedCodexConnectionKey(undefined), 'unassigned')
+ assert.equal(projection.assignedCodexConnectionKey(''), 'unassigned')
+ assert.equal(projection.assignedCodexConnectionKey(' '), 'unassigned')
+ assert.equal(projection.assignedCodexConnectionKey('team-plus'), 'team-plus')
+ assert.equal(projection.assignedCodexConnectionKey('deployment-default'), 'deployment-default')
+ assert.equal(projection.isCodexUnassignedConnectionKey(''), true)
+})
+
+test('unassigned never inherits a mapped or legacy catalog', () => {
+ const mapped = projection.parseAllowedModelsSnapshot(mappedView(), 'unassigned')
+ assert.equal(mapped.connectionStatus, 'disconnected')
+ assert.ok(!Array.from(mapped.enabledModels).includes('codex-subscription:gpt-5.3-codex'))
+ assert.ok(Array.from(mapped.enabledModels).includes('openai:gpt-4'))
+ assert.equal(projection.toPolicyBinding(mappedView(), 'unassigned'), null)
+
+ const legacy = projection.parseAllowedModelsSnapshot(FIXTURE.legacy, 'unassigned')
+ assert.equal(legacy.connectionStatus, 'disconnected')
+ assert.ok(!Array.from(legacy.enabledModels).includes('codex-subscription:gpt-5.3-codex'))
+ assert.equal(projection.toPolicyBinding(FIXTURE.legacy, ''), null)
+
+ const spend = projection.snapshotForAssignedCodexGrant('unassigned', mappedView(), {
+ flagEnabled: true,
+ })
+ assert.equal(spend.connectionStatus, 'disconnected')
+ assert.deepEqual([...spend.enabledModels], [])
+})
+
+test('legacy without a map keeps the flat catalog for a real key', () => {
+ for (const key of ['team-plus', 'deployment-default']) {
+ const snapshot = projection.parseAllowedModelsSnapshot(FIXTURE.legacy, key)
+ assert.ok(Array.from(snapshot.enabledModels).includes('codex-subscription:gpt-5.3-codex'))
+ const binding = projection.toPolicyBinding(FIXTURE.legacy, key)
+ assert.deepEqual(binding, {
+ catalogRevision: 4,
+ credentialRevision: 2,
+ connectionKey: key,
+ })
+ assert.equal(binding.models, undefined)
+ }
+})
+
+test('mapped miss and omitted models[] empty Codex without rematch', () => {
+ const miss = projection.parseAllowedModelsSnapshot(mappedView(), 'ghost-grant')
+ assert.equal(miss.connectionStatus, 'disconnected')
+ assert.ok(!Array.from(miss.enabledModels).includes('codex-subscription:gpt-5.1'))
+ assert.equal(projection.toPolicyBinding(mappedView(), 'ghost-grant'), null)
+
+ const omitted = withConnections(FIXTURE.mapped, parsed => {
+ delete parsed['personal-pro'].models
+ })
+ const snapshot = projection.parseAllowedModelsSnapshot(omitted, 'personal-pro')
+ assert.equal(snapshot.connectionStatus, 'disconnected')
+ assert.ok(!Array.from(snapshot.enabledModels).includes('codex-subscription:gpt-5.1'))
+ assert.equal(projection.toPolicyBinding(omitted, 'personal-pro'), null)
+})
+
+test('revoked is a first-class connectionStatus and blocks execute', () => {
+ const revoked = projection.parseAllowedModelsSnapshot(mappedView(), 'team-plus')
+ assert.equal(revoked.connectionStatus, 'revoked')
+ assert.equal(revoked.connectionRevision, 8)
+ const projectionResult = projection.projectCodexExecution(
+ { model: { provider: 'codex-subscription', name: 'gpt-5.3-codex' } },
+ revoked
+ )
+ assert.equal(projectionResult.eligibility, 'ineligible')
+ assert.equal(projectionResult.reason, 'connection_revoked')
+})
+
+test('mapped hit intersects models and does not rematch another grant', () => {
+ const snapshot = projection.parseAllowedModelsSnapshot(mappedView(), 'personal-pro')
+ assert.equal(snapshot.connectionStatus, 'connected')
+ assert.deepEqual(Array.from(snapshot.enabledModels).filter(k => k.startsWith('codex-subscription:')), [
+ 'codex-subscription:gpt-5.1',
+ ])
+ const otherModel = projection.projectCodexExecution(
+ { model: { provider: 'codex-subscription', name: 'gpt-5.3-codex' } },
+ snapshot
+ )
+ assert.equal(otherModel.eligibility, 'ineligible')
+ assert.deepEqual(projection.toPolicyBinding(mappedView(), 'personal-pro'), {
+ catalogRevision: 4,
+ credentialRevision: 2,
+ connectionKey: 'personal-pro',
+ models: ['gpt-5.1'],
+ })
+})
+
+test('driftHashInput excludes catalog and connection revisions', () => {
+ const spec = { model: { provider: 'codex-subscription', name: 'gpt-5.1' } }
+ const baseline = projection.projectCodexExecution(spec, {
+ flagEnabled: true,
+ connectionStatus: 'connected',
+ catalogRevision: 1,
+ connectionRevision: 1,
+ enabledModels: ['codex-subscription:gpt-5.1'],
+ staleModels: [],
+ })
+ const bumped = projection.projectCodexExecution(spec, {
+ flagEnabled: true,
+ connectionStatus: 'connected',
+ catalogRevision: 99,
+ connectionRevision: 12,
+ catalogContentHash: 'other',
+ enabledModels: ['codex-subscription:gpt-5.1'],
+ staleModels: [],
+ })
+ assert.equal(baseline.driftHashInput, bumped.driftHashInput)
+ assert.ok(!baseline.driftHashInput.includes('99'))
+ assert.ok(!baseline.driftHashInput.includes('catalogRevision'))
+})
+
+test('missing ConfigMap is an error snapshot and a null binding', () => {
+ const snapshot = projection.parseAllowedModelsSnapshot(undefined, 'team-plus')
+ assert.equal(snapshot.snapshotError, 'missing')
+ assert.equal(projection.toPolicyBinding(undefined, 'team-plus'), null)
+})
diff --git a/packages/codex-catalog-projection/package-lock.json b/packages/codex-catalog-projection/package-lock.json
new file mode 100644
index 000000000..e89ccbf67
--- /dev/null
+++ b/packages/codex-catalog-projection/package-lock.json
@@ -0,0 +1,13 @@
+{
+ "name": "@clerum/codex-catalog-projection",
+ "version": "0.1.0",
+ "lockfileVersion": 3,
+ "requires": true,
+ "packages": {
+ "": {
+ "name": "@clerum/codex-catalog-projection",
+ "version": "0.1.0",
+ "license": "MIT"
+ }
+ }
+}
diff --git a/packages/codex-catalog-projection/package.json b/packages/codex-catalog-projection/package.json
new file mode 100644
index 000000000..b86f11423
--- /dev/null
+++ b/packages/codex-catalog-projection/package.json
@@ -0,0 +1,20 @@
+{
+ "name": "@clerum/codex-catalog-projection",
+ "version": "0.1.0",
+ "private": true,
+ "description": "Shared Codex allowlist snapshot and execution projection. Structural ConfigMap view only — no Kubernetes client, no normalizeCodexConnectionKey.",
+ "main": "index.cjs",
+ "types": "index.d.ts",
+ "exports": {
+ ".": {
+ "types": "./index.d.ts",
+ "require": "./index.cjs",
+ "default": "./index.cjs"
+ }
+ },
+ "scripts": {
+ "build": "node --check index.cjs",
+ "test": "node --test index.test.cjs"
+ },
+ "license": "MIT"
+}
diff --git a/scripts/tests/test-codex-subscription-t0.sh b/scripts/tests/test-codex-subscription-t0.sh
index 9224e3e2d..5c43ec9ab 100755
--- a/scripts/tests/test-codex-subscription-t0.sh
+++ b/scripts/tests/test-codex-subscription-t0.sh
@@ -149,8 +149,10 @@ fi
require_ci_matrix_entry "codex-llm-proxy"
require_ci_matrix_entry "packages/llm-provider-attempt-contract"
+require_ci_matrix_entry "packages/codex-catalog-projection"
run_group "shared-contract" "packages/llm-provider-attempt-contract" "index.test.cjs"
+run_group "codex-catalog-projection" "packages/codex-catalog-projection" "index.test.cjs"
run_group "control-api" "control-api" \
"test/codexSubscriptionRedirectUri.test.ts" \
@@ -161,6 +163,7 @@ run_group "control-api" "control-api" \
"test/routes.adminRecipes.test.ts" \
"test/routes.adminPluginWorkloadSdk.test.ts" \
"test/services.recipeCodexGrantIdentity.test.ts" \
+ "test/crd.llmProviderEnums.test.ts" \
"test/hostSpecValidation.codexSubscription.test.ts" \
"test/llmProviders.test.ts" \
"test/services.codexSubscriptionConnection.test.ts" \
@@ -198,7 +201,8 @@ run_group "workflow-recipes" "workflow-recipes" \
"src/workflow/codexExecutionProjection.test.ts" \
"src/workflow/workflowReconciler.codexScopeProvenance.test.ts" \
"src/workflow/llmAllowedModelsSnapshot.test.ts" \
- "src/workflow/networkPolicyFactory.codex.test.ts"
+ "src/workflow/networkPolicyFactory.codex.test.ts" \
+ "tests/unit/workflow/modelConfigHandler.test.ts"
run_group "control-ui" "control-ui" \
"components/__tests__/CodexSubscriptionHub.test.tsx" \
diff --git a/workflow-recipes/Dockerfile b/workflow-recipes/Dockerfile
index 8d49376dc..86a87bda1 100644
--- a/workflow-recipes/Dockerfile
+++ b/workflow-recipes/Dockerfile
@@ -7,6 +7,7 @@ WORKDIR /app
# @clerum/workflow-runtime-core depends on it (file:../llm-providers) and
# workflow-recipes consumes it directly.
COPY packages/llm-providers ./packages/llm-providers
+COPY packages/codex-catalog-projection ./packages/codex-catalog-projection
COPY packages/network-policy-core ./packages/network-policy-core
COPY packages/workflow-runtime-core/package.json packages/workflow-runtime-core/package-lock.json ./packages/workflow-runtime-core/
COPY packages/workflow-runtime-core/tsconfig.json ./packages/workflow-runtime-core/
@@ -30,6 +31,7 @@ FROM node:24-alpine
WORKDIR /app
COPY packages/llm-providers ./packages/llm-providers
+COPY packages/codex-catalog-projection ./packages/codex-catalog-projection
COPY packages/network-policy-core ./packages/network-policy-core
COPY packages/workflow-runtime-core/package.json packages/workflow-runtime-core/package-lock.json ./packages/workflow-runtime-core/
COPY --from=builder /app/packages/workflow-runtime-core/dist ./packages/workflow-runtime-core/dist
diff --git a/workflow-recipes/Dockerfile.coordinator b/workflow-recipes/Dockerfile.coordinator
index df17dc7ae..a55241bae 100644
--- a/workflow-recipes/Dockerfile.coordinator
+++ b/workflow-recipes/Dockerfile.coordinator
@@ -6,6 +6,7 @@ WORKDIR /app
# Shared prebuilt data-only package (no build step). @clerum/workflow-runtime-core
# depends on it (file:../llm-providers) and workflow-recipes consumes it directly.
COPY packages/llm-providers ./packages/llm-providers
+COPY packages/codex-catalog-projection ./packages/codex-catalog-projection
# Issue #299: workflow-recipes also imports the shared egress accumulator
# package through a local file dependency, so it must be present before npm ci.
COPY packages/network-policy-core ./packages/network-policy-core
@@ -31,6 +32,7 @@ FROM node:24-alpine
WORKDIR /app
COPY packages/llm-providers ./packages/llm-providers
+COPY packages/codex-catalog-projection ./packages/codex-catalog-projection
COPY packages/network-policy-core ./packages/network-policy-core
COPY packages/workflow-runtime-core/package.json packages/workflow-runtime-core/package-lock.json ./packages/workflow-runtime-core/
COPY --from=builder /app/packages/workflow-runtime-core/dist ./packages/workflow-runtime-core/dist
diff --git a/workflow-recipes/Dockerfile.coordinator.dockerignore b/workflow-recipes/Dockerfile.coordinator.dockerignore
index afa3a5066..53d4ec84b 100644
--- a/workflow-recipes/Dockerfile.coordinator.dockerignore
+++ b/workflow-recipes/Dockerfile.coordinator.dockerignore
@@ -1,5 +1,7 @@
**
!packages/
+!packages/codex-catalog-projection/
+!packages/codex-catalog-projection/**
!packages/network-policy-core/
!packages/network-policy-core/**
!packages/workflow-runtime-core/
diff --git a/workflow-recipes/Dockerfile.dockerignore b/workflow-recipes/Dockerfile.dockerignore
index afa3a5066..53d4ec84b 100644
--- a/workflow-recipes/Dockerfile.dockerignore
+++ b/workflow-recipes/Dockerfile.dockerignore
@@ -1,5 +1,7 @@
**
!packages/
+!packages/codex-catalog-projection/
+!packages/codex-catalog-projection/**
!packages/network-policy-core/
!packages/network-policy-core/**
!packages/workflow-runtime-core/
diff --git a/workflow-recipes/package-lock.json b/workflow-recipes/package-lock.json
index 534f9a340..5cb5c84f8 100644
--- a/workflow-recipes/package-lock.json
+++ b/workflow-recipes/package-lock.json
@@ -1,15 +1,16 @@
{
"name": "workload-recipes-controller",
- "version": "0.1.313",
+ "version": "0.1.314",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "workload-recipes-controller",
- "version": "0.1.313",
+ "version": "0.1.314",
"license": "SEE LICENSE IN LICENSE",
"dependencies": {
"@aws-sdk/client-s3": "^3.1009.0",
+ "@clerum/codex-catalog-projection": "file:../packages/codex-catalog-projection",
"@clerum/image-policy": "file:../packages/image-policy",
"@clerum/llm-providers": "file:../packages/llm-providers",
"@clerum/network-policy-core": "file:../packages/network-policy-core",
@@ -37,6 +38,11 @@
"node": ">=24"
}
},
+ "../packages/codex-catalog-projection": {
+ "name": "@clerum/codex-catalog-projection",
+ "version": "0.1.0",
+ "license": "MIT"
+ },
"../packages/image-policy": {
"name": "@clerum/image-policy",
"version": "0.1.0",
@@ -570,6 +576,10 @@
"node": ">=18.0.0"
}
},
+ "node_modules/@clerum/codex-catalog-projection": {
+ "resolved": "../packages/codex-catalog-projection",
+ "link": true
+ },
"node_modules/@clerum/image-policy": {
"resolved": "../packages/image-policy",
"link": true
diff --git a/workflow-recipes/package.json b/workflow-recipes/package.json
index 8c4307ca8..2cf833dc4 100644
--- a/workflow-recipes/package.json
+++ b/workflow-recipes/package.json
@@ -1,6 +1,6 @@
{
"name": "workload-recipes-controller",
- "version": "0.1.313",
+ "version": "0.1.314",
"description": "Workload Recipes Controller (WRC) - WorkloadRecipe lifecycle management and MCP server interface",
"main": "dist/main.js",
"engines": {
@@ -28,6 +28,7 @@
"license": "SEE LICENSE IN LICENSE",
"dependencies": {
"@aws-sdk/client-s3": "^3.1009.0",
+ "@clerum/codex-catalog-projection": "file:../packages/codex-catalog-projection",
"@clerum/image-policy": "file:../packages/image-policy",
"@clerum/llm-providers": "file:../packages/llm-providers",
"@clerum/network-policy-core": "file:../packages/network-policy-core",
diff --git a/workflow-recipes/src/workflow/codexExecutionProjection.test.ts b/workflow-recipes/src/workflow/codexExecutionProjection.test.ts
index 2ddcf9998..59894455b 100644
--- a/workflow-recipes/src/workflow/codexExecutionProjection.test.ts
+++ b/workflow-recipes/src/workflow/codexExecutionProjection.test.ts
@@ -2,12 +2,12 @@ import { describe, expect, it } from 'vitest'
import { readFileSync } from 'node:fs'
import { dirname, join } from 'node:path'
import { fileURLToPath } from 'node:url'
-import type { LlmProviderId } from '@clerum/llm-providers'
import {
type CodexCatalogSnapshot,
type CodexHostSpec,
- projectCodexExecution as projectHostCodexExecution,
-} from '../../../host-context-controller/src/codexExecutionProjection'
+ projectCodexExecution as projectSharedCodexExecution,
+} from '@clerum/codex-catalog-projection'
+import type { LlmProviderId } from '@clerum/llm-providers'
import type { WorkflowRecipeSpec } from '../types'
import {
CODEX_EXECUTE_SCOPE,
@@ -69,7 +69,7 @@ describe('projectCodexExecution (WRC)', () => {
it('keeps HCC/WRC derivedScopes and driftHashInput identical on the shared fixture', () => {
for (const testCase of fixture.cases) {
const wrc = projectCodexExecution(testCase.spec, testCase.snapshot)
- const hcc = projectHostCodexExecution(testCase.spec, testCase.snapshot)
+ const hcc = projectSharedCodexExecution(testCase.spec, testCase.snapshot)
expect(wrc.derivedScopes, testCase.id).toEqual(hcc.derivedScopes)
expect(wrc.driftHashInput, testCase.id).toBe(hcc.driftHashInput)
}
diff --git a/workflow-recipes/src/workflow/codexExecutionProjection.ts b/workflow-recipes/src/workflow/codexExecutionProjection.ts
index b420f2c2c..e0dcded8b 100644
--- a/workflow-recipes/src/workflow/codexExecutionProjection.ts
+++ b/workflow-recipes/src/workflow/codexExecutionProjection.ts
@@ -1,77 +1,32 @@
+import {
+ collectCodexTargets,
+ projectCodexExecution as projectSharedCodexExecution,
+} from '@clerum/codex-catalog-projection'
+import type {
+ CodexCatalogSnapshot,
+ CodexExecutionProjection,
+} from '@clerum/codex-catalog-projection'
import type { WorkflowRecipeSpec } from '../types'
-export const CODEX_EXECUTE_SCOPE = 'llm:codex:execute'
-export const CODEX_PROVIDER = 'codex-subscription'
+export {
+ CODEX_EXECUTE_SCOPE,
+ CODEX_PROVIDER,
+ collectCodexTargets,
+ projectCodexExecution,
+} from '@clerum/codex-catalog-projection'
+export type {
+ CodexCatalogSnapshot,
+ CodexEligibility,
+ CodexExecutionProjection,
+ CodexHostSpec,
+ CodexSnapshotError,
+ CodexTarget,
+ CodexTargetSource,
+} from '@clerum/codex-catalog-projection'
-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 CodexProvenance = 'authoritative' | 'uncertain'
-export type CodexCatalogSnapshot = {
- flagEnabled: boolean
- connectionStatus?:
- | 'connected'
- | 'disconnected'
- | 'reauth-required'
- | 'unavailable'
- | 'revoked'
- | 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 recipeToCodexHostSpec(spec: WorkflowRecipeSpec): CodexHostSpec {
+export function recipeToCodexHostSpec(spec: WorkflowRecipeSpec) {
const allowedModels: Array<{ provider?: string; model?: string }> = []
for (const step of spec.steps ?? []) {
if (step.agent?.provider) {
@@ -103,94 +58,13 @@ export function resolveCodexAuthoritativeSpec(input: {
return { spec: input.ownSpec, provenance: 'authoritative', reason: 'standalone' }
}
-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',
- })
-}
-
export function projectRecipeCodexExecution(
spec: WorkflowRecipeSpec,
snapshot: CodexCatalogSnapshot,
provenance: CodexProvenance = 'authoritative'
): CodexExecutionProjection {
if (provenance !== 'authoritative') {
- return freezeProjection({
+ return {
targets: collectCodexTargets(recipeToCodexHostSpec(spec)),
eligibleTargets: [],
derivedScopes: [],
@@ -200,18 +74,12 @@ export function projectRecipeCodexExecution(
connectionRevision: snapshot.connectionRevision ?? null,
eligibility: 'uncertain',
reason: 'provenance_uncertain',
- })
+ driftHashInput: JSON.stringify({
+ eligibleTargets: [],
+ derivedScopes: [],
+ eligibility: 'uncertain',
+ }),
+ }
}
- return projectCodexExecution(recipeToCodexHostSpec(spec), snapshot)
-}
-
-function freezeProjection(
- input: Omit<CodexExecutionProjection, 'driftHashInput'>
-): CodexExecutionProjection {
- const driftHashInput = JSON.stringify({
- eligibleTargets: input.eligibleTargets,
- derivedScopes: input.derivedScopes,
- eligibility: input.eligibility,
- })
- return Object.freeze({ ...input, driftHashInput })
+ return projectSharedCodexExecution(recipeToCodexHostSpec(spec), snapshot)
}
diff --git a/workflow-recipes/src/workflow/k8sSecretReaderImpl.ts b/workflow-recipes/src/workflow/k8sSecretReaderImpl.ts
index 14363d71e..46e4a1468 100644
--- a/workflow-recipes/src/workflow/k8sSecretReaderImpl.ts
+++ b/workflow-recipes/src/workflow/k8sSecretReaderImpl.ts
@@ -28,7 +28,11 @@ export class K8sSecretReaderImpl implements K8sSecretReader {
// The CM exists — even if `data` was omitted (kube-apiserver drops an
// empty `data: {}`), report it present with an empty map so the caller
// treats an empty allowlist as deny-all rather than absent (degraded).
- return { exists: true, data: cm.data ?? {} }
+ return {
+ exists: true,
+ data: cm.data ?? {},
+ annotations: cm.metadata?.annotations ?? {},
+ }
} catch (error: unknown) {
const code = getErrorCode(error)
if (code === 404) return { exists: false }
diff --git a/workflow-recipes/src/workflow/llmAllowedModelsSnapshot.ts b/workflow-recipes/src/workflow/llmAllowedModelsSnapshot.ts
index 24201cffd..f5d3c8e10 100644
--- a/workflow-recipes/src/workflow/llmAllowedModelsSnapshot.ts
+++ b/workflow-recipes/src/workflow/llmAllowedModelsSnapshot.ts
@@ -1,23 +1,23 @@
-import type { V1ConfigMap } from '@kubernetes/client-node'
-import type { CodexCatalogSnapshot, CodexSnapshotError } from './codexExecutionProjection'
+import {
+ CODEX_CONNECTION_REF_ANNOTATION,
+ assignedCodexConnectionKey,
+} from '@clerum/codex-catalog-projection'
+
+export {
+ ALLOWED_MODELS_CONFIGMAP_NAME,
+ CATALOG_REVISION_ANNOTATION,
+ CODEX_CONNECTION_REF_ANNOTATION,
+ CODEX_CONNECTIONS_ANNOTATION,
+ CODEX_CONNECTION_STATUS_ANNOTATION,
+ CODEX_ENABLED_ANNOTATION,
+ CODEX_UNASSIGNED_CONNECTION_KEY,
+ CONNECTION_REVISION_ANNOTATION,
+ CONTENT_HASH_ANNOTATION,
+ parseAllowedModelsSnapshot,
+ snapshotForAssignedCodexGrant,
+ snapshotFromConfigMapError,
+} from '@clerum/codex-catalog-projection'
-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 const CODEX_CONNECTIONS_ANNOTATION = 'clerum.io/codex-connections'
-/**
- * WorkflowRecipe metadata annotation naming the Codex grant (connection key)
- * the recipe executes against. Recipes have no Host `spec.model.connectionRef`
- * field by design: grants are created in Secrets and a recipe only *chooses*
- * an existing grant through this annotation. HCC (Hosts), WRC (recipes), the
- * control-api authorizer, and mcp-host must agree on the same key.
- */
-export const CODEX_CONNECTION_REF_ANNOTATION = 'clerum.io/codex-connection-ref'
-/** Fail-closed sentinel. Not a grant row; never aliases deployment-default. */
-export const CODEX_UNASSIGNED_CONNECTION_KEY = 'unassigned'
export const ALLOWLIST_CONFIGMAP_NAMESPACE = process.env.CLERUM_MODEL_CONFIG_NAMESPACE ?? 'mcp-host'
/**
@@ -27,152 +27,5 @@ export const ALLOWLIST_CONFIGMAP_NAMESPACE = process.env.CLERUM_MODEL_CONFIG_NAM
export function readRecipeCodexConnectionRef(
annotations: Record<string, string> | undefined
): string {
- const raw = annotations?.[CODEX_CONNECTION_REF_ANNOTATION]
- const trimmed = typeof raw === 'string' ? raw.trim() : ''
- if (!trimmed) return CODEX_UNASSIGNED_CONNECTION_KEY
- return trimmed
-}
-
-export function snapshotFromConfigMapError(error: CodexSnapshotError): CodexCatalogSnapshot {
- return { flagEnabled: false, snapshotError: error }
-}
-
-const CODEX_PROVIDER_PREFIX = 'codex-subscription:'
-
-function dropCodexModels(enabledModels: Set<string>, staleModels: Set<string>): void {
- for (const key of [...enabledModels]) {
- if (key.startsWith(CODEX_PROVIDER_PREFIX)) {
- enabledModels.delete(key)
- staleModels.delete(key)
- }
- }
-}
-
-function intersectCodexModels(
- enabledModels: Set<string>,
- staleModels: Set<string>,
- models: string[] | undefined,
- _connectionKey: string
-): void {
- if (!Array.isArray(models)) {
- dropCodexModels(enabledModels, staleModels)
- return
- }
- const allowed = new Set(models.filter(model => typeof model === 'string' && model.trim()))
- for (const key of [...enabledModels]) {
- if (!key.startsWith(CODEX_PROVIDER_PREFIX)) continue
- const model = key.slice(CODEX_PROVIDER_PREFIX.length)
- if (!allowed.has(model)) {
- enabledModels.delete(key)
- staleModels.delete(key)
- }
- }
-}
-
-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,
- connectionKey = 'unassigned'
-): 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')
- }
- }
- let catalogRevision = parseOptionalIntegerAnnotation(annotations, CATALOG_REVISION_ANNOTATION)
- let connectionRevision = parseOptionalIntegerAnnotation(
- annotations,
- CONNECTION_REVISION_ANNOTATION
- )
- if (catalogRevision === 'invalid' || connectionRevision === 'invalid') {
- return snapshotFromConfigMapError('malformed')
- }
- let connectionStatus =
- (annotations[CODEX_CONNECTION_STATUS_ANNOTATION] as CodexCatalogSnapshot['connectionStatus']) ??
- null
- const rawMap = annotations[CODEX_CONNECTIONS_ANNOTATION]
- if (rawMap) {
- try {
- const parsed = JSON.parse(rawMap) as Record<
- string,
- {
- status?: string
- catalogRevision?: number
- connectionRevision?: number
- models?: string[]
- }
- >
- const assigned = parsed[connectionKey]
- if (assigned) {
- connectionStatus =
- (assigned.status as CodexCatalogSnapshot['connectionStatus']) ?? connectionStatus
- if (Number.isInteger(assigned.catalogRevision)) {
- catalogRevision = assigned.catalogRevision as number
- }
- if (Number.isInteger(assigned.connectionRevision)) {
- connectionRevision = assigned.connectionRevision as number
- }
- intersectCodexModels(enabledModels, staleModels, assigned.models, connectionKey)
- } else {
- connectionStatus = 'disconnected'
- dropCodexModels(enabledModels, staleModels)
- }
- } catch {
- return snapshotFromConfigMapError('malformed')
- }
- }
- // No connections map: keep the flat catalog (legacy single-grant). Do not
- // invent deployment-default; a multi-grant map already fail-closed above.
- return {
- flagEnabled: annotations[CODEX_ENABLED_ANNOTATION] === 'true',
- connectionStatus,
- catalogContentHash: annotations[CONTENT_HASH_ANNOTATION] ?? null,
- catalogRevision,
- connectionRevision,
- enabledModels,
- staleModels,
- }
-}
-
-/**
- * Per-recipe snapshot. `unassigned` never inherits a legacy flat catalog —
- * that would let a recipe without a grant spend the cluster default.
- */
-export function snapshotForAssignedCodexGrant(
- connectionKey: string,
- lastConfigMap: V1ConfigMap | undefined | null,
- fallback: CodexCatalogSnapshot
-): CodexCatalogSnapshot {
- if (connectionKey === CODEX_UNASSIGNED_CONNECTION_KEY) {
- return {
- flagEnabled: fallback.flagEnabled,
- connectionStatus: 'disconnected',
- enabledModels: [],
- staleModels: [],
- }
- }
- if (!lastConfigMap) return fallback
- return parseAllowedModelsSnapshot(lastConfigMap, connectionKey)
+ return assignedCodexConnectionKey(annotations?.[CODEX_CONNECTION_REF_ANNOTATION])
}
diff --git a/workflow-recipes/src/workflow/modelConfigHandler.ts b/workflow-recipes/src/workflow/modelConfigHandler.ts
index 441d200bd..45699db8c 100644
--- a/workflow-recipes/src/workflow/modelConfigHandler.ts
+++ b/workflow-recipes/src/workflow/modelConfigHandler.ts
@@ -9,6 +9,10 @@
* SDK bootstrap is identity-only; its prompt credentials stay behind the
* per-attempt broker.
*/
+import {
+ assignedCodexConnectionKey,
+ snapshotForAssignedCodexGrant,
+} from '@clerum/codex-catalog-projection'
import {
PROVIDER_AUTH_MODE,
PROVIDER_CREDENTIAL_SLOTS,
@@ -71,7 +75,9 @@ export interface PluginSdkCredentialTarget {
* The allowlist gate needs it: an existing-but-empty CM must deny-all, whereas
* an absent CM drops into degraded mode. See {@link ModelConfigHandler.handle}.
*/
-export type ConfigMapPresence = { exists: false } | { exists: true; data: Record<string, string> }
+export type ConfigMapPresence =
+ | { exists: false }
+ | { exists: true; data: Record<string, string>; annotations?: Record<string, string> }
export interface K8sSecretReader {
readConfigMap(namespace: string, name: string): Promise<Record<string, string> | null>
@@ -118,6 +124,8 @@ export type DegradedModeValidator = () => Promise<ConfigureModelResult | null>
export interface HandleOptions {
/** Enforced only when the allowlist ConfigMap does not exist (see R3.5). */
validateDegraded?: DegradedModeValidator
+ /** Assigned Codex grant. Empty/missing is unassigned and never inherits. */
+ codexConnectionKey?: string
}
// ─── Handler ────────────────────────────────────────────────────────────
@@ -182,6 +190,26 @@ function parseAllowedModels(raw: string | undefined, provider: string): Set<stri
return allowed
}
+function isCodexModelAllowed(
+ provider: string,
+ model: string,
+ allowlistCm: { data: Record<string, string>; annotations?: Record<string, string> },
+ connectionKey?: string
+): boolean {
+ if (isLlmProviderId(provider) && PROVIDER_AUTH_MODE[provider] === 'oauth-broker') {
+ const snapshot = snapshotForAssignedCodexGrant(
+ assignedCodexConnectionKey(connectionKey),
+ { metadata: { annotations: allowlistCm.annotations ?? {} }, data: allowlistCm.data },
+ { flagEnabled: false }
+ )
+ const key = `${provider}:${model}`
+ const enabled = new Set(snapshot.enabledModels ?? [])
+ const stale = new Set(snapshot.staleModels ?? [])
+ return enabled.has(key) && !stale.has(key)
+ }
+ return parseAllowedModels(allowlistCm.data[provider], provider).has(model)
+}
+
export class ModelConfigHandler {
constructor(
private readonly k8s: K8sSecretReader,
@@ -324,8 +352,7 @@ export class ModelConfigHandler {
if (!allowlistCm.exists) {
return { status: 503, body: { error: 'Provider configuration unavailable' } }
}
- const allowed = parseAllowedModels(allowlistCm.data[target.provider], target.provider)
- if (!allowed.has(target.model)) {
+ if (!isCodexModelAllowed(target.provider, target.model, allowlistCm)) {
return { status: 403, body: { error: 'Provider target is not enabled' } }
}
@@ -405,8 +432,13 @@ export class ModelConfigHandler {
ALLOWLIST_CONFIGMAP_NAME
)
if (allowlistCm.exists) {
- const allowed = parseAllowedModels(allowlistCm.data[req.provider], req.provider)
- if (!allowed.has(req.model)) {
+ const allowed = isCodexModelAllowed(
+ req.provider,
+ req.model,
+ allowlistCm,
+ opts?.codexConnectionKey
+ )
+ if (!allowed) {
return {
status: 403,
body: {
@@ -490,7 +522,8 @@ export class ModelConfigHandler {
const resolvedFallbacks = await this.resolveFallbacks(
req,
configMap,
- allowlistCm.exists ? allowlistCm.data : null
+ allowlistCm.exists ? allowlistCm : null,
+ opts?.codexConnectionKey
)
// 3. Optional SOUL download
@@ -617,7 +650,8 @@ export class ModelConfigHandler {
private async resolveFallbacks(
req: ConfigureModelRequest,
configMap: Record<string, string>,
- allowlist: Record<string, string> | null
+ allowlist: { data: Record<string, string>; annotations?: Record<string, string> } | null,
+ codexConnectionKey?: string
): Promise<Array<{ provider: string; model: string; apiKey: string; llmSecretName: string }>> {
const fallbacks = req.fallbacks
if (!fallbacks || fallbacks.length === 0) return []
@@ -642,8 +676,13 @@ export class ModelConfigHandler {
log.warn('Skipping fallback with invalid provider/model', { stepId: req.stepId })
continue
}
- const allowed = parseAllowedModels(allowlist[entry.provider], entry.provider)
- if (!allowed.has(entry.model)) {
+ const allowed = isCodexModelAllowed(
+ entry.provider,
+ entry.model,
+ allowlist,
+ codexConnectionKey
+ )
+ if (!allowed) {
log.warn('Skipping fallback model not in allowlist', {
stepId: req.stepId,
provider: entry.provider,
diff --git a/workflow-recipes/src/workflow/restEndpoints.ts b/workflow-recipes/src/workflow/restEndpoints.ts
index 8a513d8d4..b3bafb6ba 100644
--- a/workflow-recipes/src/workflow/restEndpoints.ts
+++ b/workflow-recipes/src/workflow/restEndpoints.ts
@@ -2,6 +2,10 @@
* WRC REST endpoints for workflow status reporting and management.
*/
import * as k8s from '@kubernetes/client-node'
+import {
+ CODEX_CONNECTION_REF_ANNOTATION,
+ assignedCodexConnectionKey,
+} from '@clerum/codex-catalog-projection'
import { loadConfig } from '../config'
import type {
GovernedTraceReporter,
@@ -626,6 +630,21 @@ export function createWorkflowEndpointHandlers(
const statusOutputPreviewMaxChars = loadConfig().workflowStepOutputPreviewMaxChars
const traceReporter = options.traceReporter ?? null
+ async function readRecipe(recipeName: string, namespace: string): Promise<unknown | null> {
+ try {
+ return await customApi.getNamespacedCustomObject({
+ group: CRD_GROUP,
+ version: CRD_VERSION,
+ namespace,
+ plural: WORKFLOWRECIPE_PLURAL,
+ name: recipeName,
+ })
+ } catch (err) {
+ if (getErrorCode(err) === 404) return null
+ throw err
+ }
+ }
+
function validateWorkflowClaimBinding(
recipeName: string,
claims: AuthenticatedRequest['tokenClaims']
@@ -667,6 +686,15 @@ export function createWorkflowEndpointHandlers(
)
const mcpHostEndpoint = buildMcpHostUrl(recipeName, sandboxNamespace)
+ const recipe = (await readRecipe(recipeName, recipeNamespaceClaim)) as {
+ metadata?: { annotations?: Record<string, string> }
+ } | null
+ const handleOpts = {
+ ...(validateDegraded ? { validateDegraded } : {}),
+ codexConnectionKey: assignedCodexConnectionKey(
+ recipe?.metadata?.annotations?.[CODEX_CONNECTION_REF_ANNOTATION]
+ ),
+ }
// R5 F6 stop-point: `fallbacks`/`cooldownSeconds`/`triggerOn` are NOT
// forwarded yet — the broker request carries only the declared step tuple, so
// the mcp-host handler's fallback path is never reached from the coordinator.
@@ -676,7 +704,7 @@ export function createWorkflowEndpointHandlers(
{ stepId: body.stepId, provider: body.provider, model: body.model },
mcpHostEndpoint,
wrcConfigureToken,
- validateDegraded ? { validateDegraded } : undefined
+ handleOpts
)
return { status: result.status, body: result.body }
}
@@ -1558,18 +1586,7 @@ export function createWorkflowEndpointHandlers(
* Non-404 lookup errors rethrow.
*/
async getRecipe(recipeName: string, namespace: string): Promise<unknown | null> {
- try {
- return await customApi.getNamespacedCustomObject({
- group: CRD_GROUP,
- version: CRD_VERSION,
- namespace,
- plural: WORKFLOWRECIPE_PLURAL,
- name: recipeName,
- })
- } catch (err) {
- if (getErrorCode(err) === 404) return null
- throw err
- }
+ return readRecipe(recipeName, namespace)
},
}
}
diff --git a/workflow-recipes/tests/unit/workflow/modelConfigHandler.test.ts b/workflow-recipes/tests/unit/workflow/modelConfigHandler.test.ts
index 9eb14d153..0192dafa7 100644
--- a/workflow-recipes/tests/unit/workflow/modelConfigHandler.test.ts
+++ b/workflow-recipes/tests/unit/workflow/modelConfigHandler.test.ts
@@ -19,7 +19,8 @@ import {
function mockK8s(
configMap: Record<string, string> | null = null,
secret: Record<string, string> | null = null,
- allowlist: Record<string, string> | null = null
+ allowlist: Record<string, string> | null = null,
+ allowlistAnnotations: Record<string, string> = {}
): K8sSecretReader {
return {
readConfigMap: vi.fn(async (_namespace: string, name: string) =>
@@ -28,7 +29,7 @@ function mockK8s(
readConfigMapWithPresence: vi.fn(async () =>
allowlist === null
? ({ exists: false } as const)
- : ({ exists: true, data: allowlist } as const)
+ : ({ exists: true, data: allowlist, annotations: allowlistAnnotations } as const)
),
readSecret: vi.fn().mockResolvedValue(secret),
}
@@ -447,7 +448,8 @@ describe('POST /configure-model — R3 allowlist gate', () => {
const result = await handler.handle(
{ stepId: 's1', provider: 'codex-subscription', model: 'gpt-5.3-codex' },
'http://mcp:8080',
- 'tok'
+ 'tok',
+ { codexConnectionKey: 'team-plus' }
)
expect(result.status).toBe(202)
@@ -474,7 +476,8 @@ describe('POST /configure-model — R3 allowlist gate', () => {
const result = await handler.handle(
{ stepId: 's1', provider: 'codex-subscription', model: 'gpt-5.3-codex' },
'http://mcp:8080',
- 'tok'
+ 'tok',
+ { codexConnectionKey: 'team-plus' }
)
expect(result.status).toBe(502)
@@ -696,4 +699,60 @@ describe('POST /configure-model — security invariants', () => {
expect(bodyStr).not.toContain('apiKey')
expect(bodyStr).not.toContain('sk-test')
})
+
+ it('rejects a Codex model that only another grant offers', async () => {
+ const allowlist = {
+ 'codex-subscription': JSON.stringify([{ model: 'gpt-5.3-codex' }, { model: 'gpt-5.1' }]),
+ }
+ const annotations = {
+ 'clerum.io/codex-connections': JSON.stringify({
+ 'team-plus': {
+ status: 'connected',
+ catalogRevision: 3,
+ connectionRevision: 8,
+ models: ['gpt-5.3-codex'],
+ },
+ 'personal-pro': {
+ status: 'connected',
+ catalogRevision: 4,
+ connectionRevision: 2,
+ models: ['gpt-5.1'],
+ },
+ }),
+ }
+ const k8s = mockK8s({}, null, allowlist, annotations)
+ const handler = new ModelConfigHandler(k8s, mockMcpHost())
+ const denied = await handler.handle(
+ { stepId: 's1', provider: 'codex-subscription', model: 'gpt-5.3-codex' },
+ 'http://mcp:8080',
+ 'tok',
+ { codexConnectionKey: 'personal-pro' }
+ )
+ expect(denied.status).toBe(403)
+ expect(denied.body.code).toBe('model_not_allowed')
+
+ const allowed = await handler.handle(
+ { stepId: 's1', provider: 'codex-subscription', model: 'gpt-5.1' },
+ 'http://mcp:8080',
+ 'tok',
+ { codexConnectionKey: 'personal-pro' }
+ )
+ expect(allowed.status).toBe(202)
+ expect(allowed.body.configured).toBe(true)
+ })
+
+ it('does not let an unassigned recipe inherit the flat Codex catalog', async () => {
+ const allowlist = {
+ 'codex-subscription': JSON.stringify([{ model: 'gpt-5.3-codex' }]),
+ }
+ const k8s = mockK8s({}, null, allowlist)
+ const handler = new ModelConfigHandler(k8s, mockMcpHost())
+ const denied = await handler.handle(
+ { stepId: 's1', provider: 'codex-subscription', model: 'gpt-5.3-codex' },
+ 'http://mcp:8080',
+ 'tok'
+ )
+ expect(denied.status).toBe(403)
+ expect(denied.body.code).toBe('model_not_allowed')
+ })
})
diff --git a/workflow-recipes/tests/unit/workflow/restEndpoints.functional.test.ts b/workflow-recipes/tests/unit/workflow/restEndpoints.functional.test.ts
index 22af163d5..fd9a27845 100644
--- a/workflow-recipes/tests/unit/workflow/restEndpoints.functional.test.ts
+++ b/workflow-recipes/tests/unit/workflow/restEndpoints.functional.test.ts
@@ -1171,7 +1171,7 @@ describe('requestModelInjection', () => {
{ stepId: 'broker-review', provider: 'zai', model: 'glm-4.7' },
'http://wf-my-recipe-mcp-host.sandbox-recipes.svc.cluster.local:8080',
'wrc-configure-token',
- undefined
+ { codexConnectionKey: 'unassigned' }
)
})