Skip to content

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

TypeScript

feat(wrc): derive Codex scope and proxy path from recipe target

Alfredo Lopez01038a8135dc
diff --git a/workflow-recipes/package-lock.json b/workflow-recipes/package-lock.json
index 03fe64109..b5bc3d4ba 100644
--- a/workflow-recipes/package-lock.json
+++ b/workflow-recipes/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "workload-recipes-controller",
- "version": "0.1.299",
+ "version": "0.1.300",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "workload-recipes-controller",
- "version": "0.1.299",
+ "version": "0.1.300",
"license": "SEE LICENSE IN LICENSE",
"dependencies": {
"@aws-sdk/client-s3": "^3.1009.0",
diff --git a/workflow-recipes/package.json b/workflow-recipes/package.json
index 921d36a8e..75805fede 100644
--- a/workflow-recipes/package.json
+++ b/workflow-recipes/package.json
@@ -1,6 +1,6 @@
{
"name": "workload-recipes-controller",
- "version": "0.1.299",
+ "version": "0.1.300",
"description": "Workload Recipes Controller (WRC) - WorkloadRecipe lifecycle management and MCP server interface",
"main": "dist/main.js",
"engines": {
diff --git a/workflow-recipes/src/reconciler/reconciler.test.ts b/workflow-recipes/src/reconciler/reconciler.test.ts
index 3d16ff3ce..907af81dd 100644
--- a/workflow-recipes/src/reconciler/reconciler.test.ts
+++ b/workflow-recipes/src/reconciler/reconciler.test.ts
@@ -6720,6 +6720,103 @@ describe('WorkflowRecipeReconciler', () => {
)
})
+ it('binds Codex context as uncertain when parent labels are claimed without provenance', async () => {
+ const setCodexReconcileContext = vi.fn()
+ const ensureMcpHostRuntimeCredentials = vi.fn().mockResolvedValue(undefined)
+ ;(
+ reconciler as unknown as {
+ workflowReconciler: {
+ setCodexReconcileContext: typeof setCodexReconcileContext
+ ensureMcpHostRuntimeCredentials: typeof ensureMcpHostRuntimeCredentials
+ }
+ }
+ ).workflowReconciler = { setCodexReconcileContext, ensureMcpHostRuntimeCredentials }
+
+ const recipe = makeRecipe({
+ metadata: {
+ name: 'child-run',
+ namespace: 'sandbox-recipes',
+ uid: 'uid-child',
+ labels: {
+ 'clerum.io/parent-recipe': 'victim-recipe',
+ 'clerum.io/workflow-run-id': 'run-child',
+ },
+ },
+ spec: {
+ agent: { provider: 'codex-subscription', model: 'gpt-5.3-codex' },
+ steps: [{ id: 'research', instruction: 'run' }],
+ },
+ status: {
+ phase: 'active',
+ } as WorkflowRecipeCRD['status'],
+ })
+
+ await reconciler.reconcile(recipe)
+
+ expect(setCodexReconcileContext).toHaveBeenCalledWith({
+ recipeName: 'child-run',
+ runtimeScopeRecipeName: 'child-run',
+ claimedParent: true,
+ parentSpec: null,
+ })
+ })
+
+ it('binds the inherited parent Codex spec when child provenance is verified', async () => {
+ const parentSpec = {
+ agent: { provider: 'codex-subscription' as const, model: 'gpt-5.3-codex' },
+ steps: [{ id: 'research', instruction: 'parent target' }],
+ }
+ mockCustomApi.getNamespacedCustomObject.mockImplementation(({ name }: { name?: string }) =>
+ Promise.resolve({
+ metadata: {
+ uid: liveWorkflowRecipeUid(name),
+ resourceVersion: '1',
+ },
+ spec: name === 'parent-recipe' ? parentSpec : { mcpServers: [] },
+ })
+ )
+ const setCodexReconcileContext = vi.fn()
+ const ensureMcpHostRuntimeCredentials = vi.fn().mockResolvedValue(undefined)
+ ;(
+ reconciler as unknown as {
+ workflowReconciler: {
+ setCodexReconcileContext: typeof setCodexReconcileContext
+ ensureMcpHostRuntimeCredentials: typeof ensureMcpHostRuntimeCredentials
+ }
+ }
+ ).workflowReconciler = { setCodexReconcileContext, ensureMcpHostRuntimeCredentials }
+
+ const recipe = makeRecipe({
+ metadata: {
+ name: 'child-run',
+ namespace: 'sandbox-recipes',
+ uid: 'uid-child',
+ annotations: { [INHERITED_PARENT_RESOURCES_ANNOTATION]: 'true' },
+ labels: {
+ 'clerum.io/parent-recipe': 'parent-recipe',
+ 'clerum.io/workflow-run-id': 'run-child',
+ },
+ ownerReferences: [workflowRecipeOwnerRef('parent-recipe')],
+ },
+ spec: {
+ agent: { provider: 'openai', model: 'gpt-5.4-mini' },
+ steps: [{ id: 'research', instruction: 'child body must not win' }],
+ },
+ status: {
+ phase: 'active',
+ } as WorkflowRecipeCRD['status'],
+ })
+
+ await reconciler.reconcile(recipe)
+
+ expect(setCodexReconcileContext).toHaveBeenCalledWith({
+ recipeName: 'child-run',
+ runtimeScopeRecipeName: 'parent-recipe',
+ claimedParent: true,
+ parentSpec,
+ })
+ })
+
it('does not inherit a parent scope on first reconcile without DB-run metadata', async () => {
const reconcileWorkflow = vi.fn().mockResolvedValue({
phase: 'deploying',
diff --git a/workflow-recipes/src/reconciler/workflowRecipeReconciler.ts b/workflow-recipes/src/reconciler/workflowRecipeReconciler.ts
index 5336d3bec..fe50fd71c 100644
--- a/workflow-recipes/src/reconciler/workflowRecipeReconciler.ts
+++ b/workflow-recipes/src/reconciler/workflowRecipeReconciler.ts
@@ -31,6 +31,7 @@ import {
StatefulSetDef,
StatusCondition,
WorkflowRecipeCRD,
+ WorkflowRecipeSpec,
WorkflowRecipeStatus,
WorkloadDef,
} from '../types'
@@ -1001,6 +1002,51 @@ export class WorkflowRecipeReconciler {
return recipe.metadata.name
}
+ private claimedCodexParent(recipe: WorkflowRecipeCRD): boolean {
+ const parentLabel = recipe.metadata.labels?.[PARENT_RECIPE_LABEL]?.trim()
+ const ownerRef = recipe.metadata.ownerReferences?.some(
+ ref =>
+ ref.kind === 'WorkflowRecipe' &&
+ ref.controller === true &&
+ typeof ref.name === 'string' &&
+ ref.name.trim().length > 0
+ )
+ return Boolean(parentLabel || ownerRef)
+ }
+
+ private async loadCodexParentSpec(
+ recipe: WorkflowRecipeCRD,
+ runtimeScopeRecipeName: string
+ ): Promise<WorkflowRecipeSpec | null> {
+ if (runtimeScopeRecipeName === recipe.metadata.name) return null
+ try {
+ const live = (await this.customApi.getNamespacedCustomObject({
+ group: CRD_GROUP,
+ version: CRD_VERSION,
+ namespace: recipe.metadata.namespace,
+ plural: WORKFLOWRECIPE_PLURAL,
+ name: runtimeScopeRecipeName,
+ })) as { spec?: WorkflowRecipeSpec }
+ return live.spec ?? null
+ } catch {
+ return null
+ }
+ }
+
+ private async bindCodexReconcileContext(
+ recipe: WorkflowRecipeCRD,
+ runtimeScopeRecipeName: string
+ ): Promise<void> {
+ const setter = this.workflowReconciler?.setCodexReconcileContext
+ if (typeof setter !== 'function') return
+ setter.call(this.workflowReconciler, {
+ recipeName: recipe.metadata.name,
+ runtimeScopeRecipeName,
+ claimedParent: this.claimedCodexParent(recipe),
+ parentSpec: await this.loadCodexParentSpec(recipe, runtimeScopeRecipeName),
+ })
+ }
+
private async hasVerifiedInheritedParentResources(recipe: WorkflowRecipeCRD): Promise<boolean> {
if (!declaresInheritedParentResources(recipe)) return false
const parentName = recipe.metadata.labels?.[PARENT_RECIPE_LABEL]?.trim()
@@ -1088,6 +1134,7 @@ export class WorkflowRecipeReconciler {
if (!this.workflowReconciler) return
const runtimeScopeRecipeName =
resolvedRuntimeScopeRecipeName ?? (await this.workflowRuntimeScopeRecipeName(recipe))
+ await this.bindCodexReconcileContext(recipe, runtimeScopeRecipeName)
const coordinatorRefresher = this.workflowReconciler as WorkflowReconciler & {
ensureCoordinatorRuntimeCredentials?: (
recipeNamespace: string,
@@ -1860,6 +1907,7 @@ export class WorkflowRecipeReconciler {
resourceInstances: recipe.status.resourceInstances,
}
: undefined
+ await this.bindCodexReconcileContext(recipe, approvalScopeRecipeName)
const result = await this.workflowReconciler.reconcile(
name,
recipe.metadata.uid ?? '',
diff --git a/workflow-recipes/src/types.ts b/workflow-recipes/src/types.ts
index a690ba7ee..1901dba6b 100644
--- a/workflow-recipes/src/types.ts
+++ b/workflow-recipes/src/types.ts
@@ -598,6 +598,10 @@ export interface WorkflowRecipeSpec {
agent?: {
model: string
provider: LlmProviderId
+ /**
+ * Optional static-credential Secret. Omitted for oauth-broker providers
+ * such as `codex-subscription`; Control API remains the OAuth custodian.
+ */
secretRef?: { name: string; namespace?: string }
soulRef?: {
storageRef: {
diff --git a/workflow-recipes/src/workflow/codexExecutionProjection.test.ts b/workflow-recipes/src/workflow/codexExecutionProjection.test.ts
new file mode 100644
index 000000000..32d94e3ec
--- /dev/null
+++ b/workflow-recipes/src/workflow/codexExecutionProjection.test.ts
@@ -0,0 +1,184 @@
+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'
+import type { WorkflowRecipeSpec } from '../types'
+import {
+ CODEX_EXECUTE_SCOPE,
+ type CodexCatalogSnapshot as WrcSnapshot,
+ projectCodexExecution,
+ projectRecipeCodexExecution,
+ resolveCodexAuthoritativeSpec,
+} from './codexExecutionProjection'
+
+const fixturePath = join(
+ dirname(fileURLToPath(import.meta.url)),
+ '../../../tests/e2e/fixtures/codex-subscription/codex-target-eligibility.json'
+)
+
+type EligibilityCase = {
+ id: string
+ expected: 'eligible' | 'ineligible' | 'uncertain'
+ spec: CodexHostSpec
+ snapshot: CodexCatalogSnapshot
+}
+
+const fixture = JSON.parse(readFileSync(fixturePath, 'utf8')) as { cases: EligibilityCase[] }
+
+const eligibleSnapshot: WrcSnapshot = {
+ flagEnabled: true,
+ connectionStatus: 'connected',
+ catalogContentHash: 'aa',
+ catalogRevision: 1,
+ connectionRevision: 1,
+ enabledModels: ['codex-subscription:gpt-5.3-codex'],
+ staleModels: [],
+}
+
+function recipeSpec(provider: LlmProviderId, model: string): WorkflowRecipeSpec {
+ return {
+ agent: { provider, model },
+ steps: [{ id: 'step-1', instruction: 'run' }],
+ }
+}
+
+describe('projectCodexExecution (WRC)', () => {
+ it('matches the shared HCC/WRC eligibility corpus', () => {
+ expect(fixture.cases.length).toBeGreaterThan(0)
+ for (const testCase of fixture.cases) {
+ const projection = projectCodexExecution(testCase.spec, testCase.snapshot)
+ expect(projection.eligibility, testCase.id).toBe(testCase.expected)
+ if (testCase.expected === 'eligible') {
+ expect(projection.derivedScopes, testCase.id).toEqual([CODEX_EXECUTE_SCOPE])
+ expect(projection.requiresCodexProxyEgress, testCase.id).toBe(true)
+ expect(projection.eligibleTargets.length, testCase.id).toBeGreaterThan(0)
+ } else {
+ expect(projection.derivedScopes, testCase.id).toEqual([])
+ expect(projection.requiresCodexProxyEgress, testCase.id).toBe(false)
+ expect(projection.eligibleTargets, testCase.id).toEqual([])
+ }
+ }
+ })
+
+ it('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)
+ expect(wrc.derivedScopes, testCase.id).toEqual(hcc.derivedScopes)
+ expect(wrc.driftHashInput, testCase.id).toBe(hcc.driftHashInput)
+ }
+ })
+
+ it('anti-false-positive: changing the catalog revision used in the hash must drift', () => {
+ const eligible = fixture.cases.find(testCase => testCase.id === 'flag-on-connected-ready')
+ expect(eligible).toBeDefined()
+ const baseline = projectCodexExecution(eligible!.spec, eligible!.snapshot)
+ const mutated = projectCodexExecution(eligible!.spec, {
+ ...eligible!.snapshot,
+ catalogRevision: (eligible!.snapshot.catalogRevision ?? 1) + 99,
+ })
+ expect(mutated.derivedScopes).toEqual(baseline.derivedScopes)
+ expect(mutated.driftHashInput).not.toBe(baseline.driftHashInput)
+ })
+
+ it('treats a malformed empty broker model as ineligible', () => {
+ const projection = projectCodexExecution(
+ { model: { provider: 'codex-subscription', name: ' ' } },
+ eligibleSnapshot
+ )
+ expect(projection.eligibility).toBe('ineligible')
+ expect(projection.derivedScopes).toEqual([])
+ expect(projection.requiresCodexProxyEgress).toBe(false)
+ expect(projection.reason).toBe('no_eligible_broker_target')
+ })
+
+ it('fails closed when the ConfigMap snapshot is missing', () => {
+ const projection = projectCodexExecution(
+ { model: { provider: 'codex-subscription', name: 'gpt-5.3-codex' } },
+ { flagEnabled: true, snapshotError: 'missing' }
+ )
+ expect(projection.eligibility).toBe('uncertain')
+ expect(projection.derivedScopes).toEqual([])
+ expect(projection.requiresCodexProxyEgress).toBe(false)
+ expect(projection.reason).toBe('snapshot_missing')
+ })
+
+ it('anti-false-positive: uncertain never defaults to eligible', () => {
+ const forbidden = fixture.cases.find(testCase => testCase.id === 'snapshot-forbidden')
+ expect(forbidden).toBeDefined()
+ const projection = projectCodexExecution(forbidden!.spec, forbidden!.snapshot)
+ expect(projection.eligibility).toBe('uncertain')
+ expect(projection.derivedScopes).not.toContain(CODEX_EXECUTE_SCOPE)
+ expect(projection.requiresCodexProxyEgress).toBe(false)
+ })
+})
+
+describe('resolveCodexAuthoritativeSpec', () => {
+ const parent = recipeSpec('codex-subscription', 'gpt-5.3-codex')
+ const child = recipeSpec('openai', 'gpt-5.4-mini')
+
+ it('uses the parent spec when runtime scope provenance is verified', () => {
+ const resolved = resolveCodexAuthoritativeSpec({
+ recipeName: 'child-run',
+ runtimeScopeRecipeName: 'parent-recipe',
+ claimedParent: true,
+ ownSpec: child,
+ parentSpec: parent,
+ })
+ expect(resolved.provenance).toBe('authoritative')
+ expect(resolved.spec).toBe(parent)
+ expect(resolved.reason).toBe('inherited_parent')
+ })
+
+ it('rejects a claimed parent when runtime scope falls back to the child', () => {
+ const resolved = resolveCodexAuthoritativeSpec({
+ recipeName: 'child-run',
+ runtimeScopeRecipeName: 'child-run',
+ claimedParent: true,
+ ownSpec: recipeSpec('codex-subscription', 'gpt-5.3-codex'),
+ parentSpec: parent,
+ })
+ expect(resolved.provenance).toBe('uncertain')
+ expect(resolved.reason).toBe('parent_provenance_rejected')
+ const projection = projectRecipeCodexExecution(
+ resolved.spec,
+ eligibleSnapshot,
+ resolved.provenance
+ )
+ expect(projection.derivedScopes).toEqual([])
+ expect(projection.requiresCodexProxyEgress).toBe(false)
+ expect(projection.eligibility).toBe('uncertain')
+ })
+
+ it('fails closed when an inherited child cannot load the parent spec', () => {
+ const resolved = resolveCodexAuthoritativeSpec({
+ recipeName: 'child-run',
+ runtimeScopeRecipeName: 'parent-recipe',
+ claimedParent: true,
+ ownSpec: child,
+ parentSpec: null,
+ })
+ expect(resolved.provenance).toBe('uncertain')
+ expect(resolved.reason).toBe('parent_spec_unavailable')
+ })
+
+ it('treats a standalone recipe as authoritative over its own spec', () => {
+ const own = recipeSpec('codex-subscription', 'gpt-5.3-codex')
+ const resolved = resolveCodexAuthoritativeSpec({
+ recipeName: 'standalone',
+ runtimeScopeRecipeName: 'standalone',
+ claimedParent: false,
+ ownSpec: own,
+ parentSpec: null,
+ })
+ expect(resolved.provenance).toBe('authoritative')
+ expect(resolved.spec).toBe(own)
+ expect(resolved.reason).toBe('standalone')
+ })
+})
diff --git a/workflow-recipes/src/workflow/codexExecutionProjection.ts b/workflow-recipes/src/workflow/codexExecutionProjection.ts
new file mode 100644
index 000000000..91a149315
--- /dev/null
+++ b/workflow-recipes/src/workflow/codexExecutionProjection.ts
@@ -0,0 +1,214 @@
+import type { WorkflowRecipeSpec } from '../types'
+
+export const CODEX_EXECUTE_SCOPE = 'llm:codex:execute'
+export const CODEX_PROVIDER = 'codex-subscription'
+
+export type CodexTargetSource = 'primary' | 'allowed' | 'fallback'
+export type CodexTarget = {
+ source: CodexTargetSource
+ provider: string
+ model: string
+}
+export type CodexEligibility = 'eligible' | 'ineligible' | 'uncertain'
+export type CodexSnapshotError = 'missing' | 'forbidden' | 'timeout' | 'malformed'
+export type CodexProvenance = 'authoritative' | 'uncertain'
+
+export type CodexCatalogSnapshot = {
+ flagEnabled: boolean
+ connectionStatus?: 'connected' | 'disconnected' | 'reauth-required' | 'unavailable' | null
+ catalogContentHash?: string | null
+ catalogRevision?: number | null
+ connectionRevision?: number | null
+ enabledModels?: Iterable<string>
+ staleModels?: Iterable<string>
+ snapshotError?: CodexSnapshotError
+}
+
+export type CodexHostSpec = {
+ model?: { provider?: string; name?: string }
+ allowedModels?: Array<{ provider?: string; model?: string }>
+ llmPolicy?: { fallbacks?: Array<{ provider?: string; model?: string }> }
+}
+
+export type CodexExecutionProjection = {
+ targets: CodexTarget[]
+ eligibleTargets: CodexTarget[]
+ derivedScopes: string[]
+ requiresCodexProxyEgress: boolean
+ driftHashInput: string
+ catalogContentHash: string | null
+ catalogRevision: number | null
+ connectionRevision: number | null
+ eligibility: CodexEligibility
+ reason: string
+}
+
+export function collectCodexTargets(spec: CodexHostSpec): CodexTarget[] {
+ const targets: CodexTarget[] = []
+ if (spec.model?.provider) {
+ targets.push({
+ source: 'primary',
+ provider: spec.model.provider,
+ model: spec.model.name ?? '',
+ })
+ }
+ for (const row of spec.allowedModels ?? []) {
+ if (row.provider) {
+ targets.push({ source: 'allowed', provider: row.provider, model: row.model ?? '' })
+ }
+ }
+ for (const row of spec.llmPolicy?.fallbacks ?? []) {
+ if (row.provider) {
+ targets.push({ source: 'fallback', provider: row.provider, model: row.model ?? '' })
+ }
+ }
+ return targets
+}
+
+export function recipeToCodexHostSpec(spec: WorkflowRecipeSpec): CodexHostSpec {
+ const allowedModels: Array<{ provider?: string; model?: string }> = []
+ for (const step of spec.steps ?? []) {
+ if (step.agent?.provider) {
+ allowedModels.push({ provider: step.agent.provider, model: step.agent.model })
+ }
+ }
+ return {
+ model: spec.agent ? { provider: spec.agent.provider, name: spec.agent.model } : undefined,
+ allowedModels,
+ }
+}
+
+export function resolveCodexAuthoritativeSpec(input: {
+ recipeName: string
+ runtimeScopeRecipeName: string
+ claimedParent: boolean
+ ownSpec: WorkflowRecipeSpec
+ parentSpec: WorkflowRecipeSpec | null
+}): { spec: WorkflowRecipeSpec; provenance: CodexProvenance; reason: string } {
+ if (input.claimedParent && input.runtimeScopeRecipeName === input.recipeName) {
+ return { spec: input.ownSpec, provenance: 'uncertain', reason: 'parent_provenance_rejected' }
+ }
+ if (input.runtimeScopeRecipeName !== input.recipeName) {
+ if (!input.parentSpec) {
+ return { spec: input.ownSpec, provenance: 'uncertain', reason: 'parent_spec_unavailable' }
+ }
+ return { spec: input.parentSpec, provenance: 'authoritative', reason: 'inherited_parent' }
+ }
+ 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({
+ targets: collectCodexTargets(recipeToCodexHostSpec(spec)),
+ eligibleTargets: [],
+ derivedScopes: [],
+ requiresCodexProxyEgress: false,
+ catalogContentHash: snapshot.catalogContentHash ?? null,
+ catalogRevision: snapshot.catalogRevision ?? null,
+ connectionRevision: snapshot.connectionRevision ?? null,
+ eligibility: 'uncertain',
+ reason: 'provenance_uncertain',
+ })
+ }
+ return projectCodexExecution(recipeToCodexHostSpec(spec), snapshot)
+}
+
+function freezeProjection(
+ input: Omit<CodexExecutionProjection, 'driftHashInput'>
+): CodexExecutionProjection {
+ const driftHashInput = JSON.stringify({
+ eligibleTargets: input.eligibleTargets,
+ derivedScopes: input.derivedScopes,
+ catalogContentHash: input.catalogContentHash,
+ catalogRevision: input.catalogRevision,
+ connectionRevision: input.connectionRevision,
+ eligibility: input.eligibility,
+ })
+ return Object.freeze({ ...input, driftHashInput })
+}
diff --git a/workflow-recipes/src/workflow/llmAllowedModelsSnapshot.ts b/workflow-recipes/src/workflow/llmAllowedModelsSnapshot.ts
new file mode 100644
index 000000000..26c3e63d1
--- /dev/null
+++ b/workflow-recipes/src/workflow/llmAllowedModelsSnapshot.ts
@@ -0,0 +1,65 @@
+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 ALLOWLIST_CONFIGMAP_NAMESPACE = process.env.CLERUM_MODEL_CONFIG_NAMESPACE ?? 'mcp-host'
+
+export function snapshotFromConfigMapError(error: CodexSnapshotError): CodexCatalogSnapshot {
+ return { flagEnabled: false, snapshotError: error }
+}
+
+function parseOptionalIntegerAnnotation(
+ annotations: Record<string, string>,
+ key: string
+): number | null | 'invalid' {
+ if (!(key in annotations)) return null
+ const parsed = Number(annotations[key])
+ return Number.isInteger(parsed) ? parsed : 'invalid'
+}
+
+export function parseAllowedModelsSnapshot(cm: V1ConfigMap | undefined): CodexCatalogSnapshot {
+ if (!cm) return snapshotFromConfigMapError('missing')
+ const annotations = cm.metadata?.annotations ?? {}
+ const enabledModels = new Set<string>()
+ const staleModels = new Set<string>()
+ for (const [provider, raw] of Object.entries(cm.data ?? {})) {
+ try {
+ const rows = JSON.parse(raw) as Array<{ model?: string; stale?: boolean }>
+ if (!Array.isArray(rows)) return snapshotFromConfigMapError('malformed')
+ for (const row of rows) {
+ if (typeof row.model === 'string' && row.model.trim()) {
+ const key = `${provider}:${row.model}`
+ enabledModels.add(key)
+ if (row.stale === true) staleModels.add(key)
+ }
+ }
+ } catch {
+ return snapshotFromConfigMapError('malformed')
+ }
+ }
+ const catalogRevision = parseOptionalIntegerAnnotation(annotations, CATALOG_REVISION_ANNOTATION)
+ const connectionRevision = parseOptionalIntegerAnnotation(
+ annotations,
+ CONNECTION_REVISION_ANNOTATION
+ )
+ if (catalogRevision === 'invalid' || connectionRevision === 'invalid') {
+ return snapshotFromConfigMapError('malformed')
+ }
+ return {
+ flagEnabled: annotations[CODEX_ENABLED_ANNOTATION] === 'true',
+ connectionStatus:
+ (annotations[
+ CODEX_CONNECTION_STATUS_ANNOTATION
+ ] as CodexCatalogSnapshot['connectionStatus']) ?? null,
+ catalogContentHash: annotations[CONTENT_HASH_ANNOTATION] ?? null,
+ catalogRevision,
+ connectionRevision,
+ enabledModels,
+ staleModels,
+ }
+}
diff --git a/workflow-recipes/src/workflow/mcpHostRuntimeTokenIssuerClient.ts b/workflow-recipes/src/workflow/mcpHostRuntimeTokenIssuerClient.ts
index fd9d23ff1..a332a4cf5 100644
--- a/workflow-recipes/src/workflow/mcpHostRuntimeTokenIssuerClient.ts
+++ b/workflow-recipes/src/workflow/mcpHostRuntimeTokenIssuerClient.ts
@@ -36,10 +36,13 @@ export type WorkflowControlScope =
| 'workflow:approval:decide'
| 'plugin-workload-sdk'
+export type DerivedPlatformScope = 'llm:codex:execute'
+export type EffectiveWorkflowControlScope = WorkflowControlScope | DerivedPlatformScope
+
async function postMcpHostTokenIssue(
recipeNamespace: string,
recipeName: string,
- workflowControlScopes: WorkflowControlScope[] = []
+ workflowControlScopes: EffectiveWorkflowControlScope[] = []
): Promise<CanonicalMcpHostTokenResponse> {
const url = `${CONTROL_API_BASE_URL}/api/v1/auth/mcp-host/${encodeURIComponent(recipeNamespace)}/${encodeURIComponent(recipeName)}/tokens`
const controller = new AbortController()
@@ -82,7 +85,7 @@ async function postMcpHostTokenIssue(
export async function issueMcpHostWorkflowControlToken(
recipeNamespace: string,
recipeName: string,
- workflowControlScopes: WorkflowControlScope[] = []
+ workflowControlScopes: EffectiveWorkflowControlScope[] = []
): Promise<string> {
return (await issueMcpHostRuntimeTokens(recipeNamespace, recipeName, workflowControlScopes))
.mcpHostControlToken
@@ -91,7 +94,7 @@ export async function issueMcpHostWorkflowControlToken(
export async function issueMcpHostRuntimeTokens(
recipeNamespace: string,
recipeName: string,
- workflowControlScopes: WorkflowControlScope[] = []
+ workflowControlScopes: EffectiveWorkflowControlScope[] = []
): Promise<McpHostRuntimeTokenResponse> {
const data = await postMcpHostTokenIssue(recipeNamespace, recipeName, workflowControlScopes)
if (
diff --git a/workflow-recipes/src/workflow/modelConfigHandler.ts b/workflow-recipes/src/workflow/modelConfigHandler.ts
index 9f5f3385b..9717cf1f5 100644
--- a/workflow-recipes/src/workflow/modelConfigHandler.ts
+++ b/workflow-recipes/src/workflow/modelConfigHandler.ts
@@ -10,6 +10,7 @@
* per-attempt broker.
*/
import {
+ PROVIDER_AUTH_MODE,
PROVIDER_CREDENTIAL_SLOTS,
isCredentialSlotOwnedByProvider,
isLlmProviderId,
@@ -427,6 +428,48 @@ export class ModelConfigHandler {
}
}
+ // Broker-backed providers never resolve or mount a Secret. Control API
+ // remains the OAuth custodian; WRC only forwards provider/model identity.
+ if (PROVIDER_AUTH_MODE[req.provider] === 'oauth-broker') {
+ const configureBody: Record<string, unknown> = {
+ provider: req.provider,
+ model: req.model,
+ }
+ if (req.soulStorageRef && this.objectStorage) {
+ try {
+ const content = await this.objectStorage.download(
+ req.soulStorageRef.bucket,
+ req.soulStorageRef.key
+ )
+ if (content) configureBody.soulContent = content
+ } catch {
+ createLogger('wrc', 'model-config-handler').warn(
+ 'SOUL download failed — continuing without step SOUL override',
+ { stepId: req.stepId }
+ )
+ }
+ }
+ try {
+ const result = await this.mcpHost.configure(
+ mcpHostEndpoint,
+ wrcConfigureToken,
+ configureBody
+ )
+ if (result.status >= 400) {
+ return {
+ status: 502,
+ body: { error: 'mcp_host configure failed', mcpHostStatus: result.status },
+ }
+ }
+ } catch {
+ return { status: 502, body: { error: 'mcp_host configure unreachable' } }
+ }
+ return {
+ status: 202,
+ body: { configured: true, provider: req.provider, model: req.model },
+ }
+ }
+
// 1. Read ConfigMap to resolve provider/model → secretName
const configMap = await this.k8s.readConfigMap(CONFIGMAP_NAMESPACE, CONFIGMAP_NAME)
if (!configMap) {
diff --git a/workflow-recipes/src/workflow/networkPolicyFactory.codex.test.ts b/workflow-recipes/src/workflow/networkPolicyFactory.codex.test.ts
new file mode 100644
index 000000000..c4f600f07
--- /dev/null
+++ b/workflow-recipes/src/workflow/networkPolicyFactory.codex.test.ts
@@ -0,0 +1,53 @@
+import { describe, expect, it } from 'vitest'
+import { type NetworkPolicyConfig, buildWorkflowNetworkPolicies } from './networkPolicyFactory'
+
+const baseConfig: NetworkPolicyConfig = {
+ recipeName: 'codex-recipe',
+ sandboxNamespace: 'sandbox-recipes',
+ controlPlaneNamespace: 'control-plane',
+ mcpServerNamespace: 'mcp-server',
+ wrcPort: 8082,
+ mcpHostPort: 8080,
+}
+
+describe('workflow Codex proxy NetworkPolicy', () => {
+ it('opens mcp-host egress to the isolated Codex proxy from the eligibility projection', () => {
+ const policies = buildWorkflowNetworkPolicies({
+ ...baseConfig,
+ includeCodexProxyEgress: true,
+ })
+ const policy = policies.find(np => np.metadata?.name === 'codex-recipe-mcp-host-to-codex-proxy')
+
+ expect(policy).toBeDefined()
+ expect(policy?.metadata?.namespace).toBe('sandbox-recipes')
+ expect(policy?.metadata?.labels?.['clerum.io/policy-type']).toBe('codex-proxy-egress')
+ expect(policy?.spec?.podSelector?.matchLabels).toMatchObject({
+ 'clerum.io/recipe': 'codex-recipe',
+ 'clerum.io/component': 'workflow-mcp-host',
+ })
+ const rule = policy?.spec?.egress?.[0]
+ expect(rule?.ports?.[0]).toMatchObject({ port: 8080, protocol: 'TCP' })
+ expect(rule?.to?.[0]?.namespaceSelector?.matchLabels?.['kubernetes.io/metadata.name']).toBe(
+ 'control-plane'
+ )
+ expect(rule?.to?.[0]?.podSelector?.matchLabels).toEqual({ app: 'codex-llm-proxy' })
+ })
+
+ it('does not emit Codex proxy egress unless the same projection asks for it', () => {
+ const policies = buildWorkflowNetworkPolicies(baseConfig)
+ expect(policies.some(np => np.metadata?.name === 'codex-recipe-mcp-host-to-codex-proxy')).toBe(
+ false
+ )
+ })
+
+ it('does not emit Codex proxy egress when the workflow mcp-host is omitted', () => {
+ const policies = buildWorkflowNetworkPolicies({
+ ...baseConfig,
+ includeMcpHost: false,
+ includeCodexProxyEgress: true,
+ })
+ expect(policies.some(np => np.metadata?.name === 'codex-recipe-mcp-host-to-codex-proxy')).toBe(
+ false
+ )
+ })
+})
diff --git a/workflow-recipes/src/workflow/networkPolicyFactory.ts b/workflow-recipes/src/workflow/networkPolicyFactory.ts
index 4b96aa63c..f35c2dfaa 100644
--- a/workflow-recipes/src/workflow/networkPolicyFactory.ts
+++ b/workflow-recipes/src/workflow/networkPolicyFactory.ts
@@ -67,6 +67,11 @@ export interface NetworkPolicyConfig {
*/
includeCoordinator?: boolean
includeMcpHost?: boolean
+ /**
+ * Open mcp-host egress to the isolated Codex LLM proxy. Set only from the
+ * same eligibility projection that mints `llm:codex:execute`.
+ */
+ includeCodexProxyEgress?: boolean
includeCoordinatorGfs?: boolean
includeArtifactReader?: boolean
includeSnippetRunner?: boolean
@@ -972,6 +977,48 @@ export function buildWorkflowNetworkPolicies(
],
},
},
+ ...(config.includeCodexProxyEgress
+ ? [
+ {
+ apiVersion: 'networking.k8s.io/v1',
+ kind: 'NetworkPolicy',
+ metadata: {
+ name: `${config.recipeName}-mcp-host-to-codex-proxy`,
+ namespace: config.sandboxNamespace,
+ labels: {
+ ...commonLabels,
+ 'clerum.io/policy-type': 'codex-proxy-egress',
+ },
+ },
+ spec: {
+ podSelector: {
+ matchLabels: {
+ 'clerum.io/recipe': config.recipeName,
+ 'clerum.io/component': 'workflow-mcp-host',
+ },
+ },
+ policyTypes: ['Egress'],
+ egress: [
+ {
+ to: [
+ {
+ namespaceSelector: {
+ matchLabels: {
+ 'kubernetes.io/metadata.name': config.controlPlaneNamespace,
+ },
+ },
+ podSelector: {
+ matchLabels: { app: 'codex-llm-proxy' },
+ },
+ },
+ ],
+ ports: [{ port: 8080, protocol: 'TCP' as const }],
+ },
+ ],
+ },
+ } as k8s.V1NetworkPolicy,
+ ]
+ : []),
// 8. Plugin Workload SDK: same-recipe workloads <-> mcp-host on the SDK
// port plus mcp-host -> WRC for per-attempt credential ticket redemption.
// Empty unless the capability and feature flag are both enabled.
diff --git a/workflow-recipes/src/workflow/types.ts b/workflow-recipes/src/workflow/types.ts
index da6ab97c3..03a8a425c 100644
--- a/workflow-recipes/src/workflow/types.ts
+++ b/workflow-recipes/src/workflow/types.ts
@@ -31,6 +31,11 @@ export function isTerminalStepPhase(phase: StepPhase): boolean {
export interface AgentSpec {
model: string
provider: LlmProviderId
+ /**
+ * Optional static-credential Secret. Omitted for oauth-broker providers
+ * such as `codex-subscription`; Control API remains the OAuth custodian.
+ * `llm:codex:execute` is never a recipe-declared scope.
+ */
secretRef?: {
name: string
namespace?: string // default: control-plane
diff --git a/workflow-recipes/src/workflow/workflowReconciler.codexScopeProvenance.test.ts b/workflow-recipes/src/workflow/workflowReconciler.codexScopeProvenance.test.ts
new file mode 100644
index 000000000..bf2796489
--- /dev/null
+++ b/workflow-recipes/src/workflow/workflowReconciler.codexScopeProvenance.test.ts
@@ -0,0 +1,373 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest'
+import type { WorkflowRecipeSpec } from '../types'
+import { issueMcpHostRuntimeTokens } from './mcpHostRuntimeTokenIssuerClient'
+import { WorkflowReconciler, type WorkflowReconcilerDeps } from './workflowReconciler'
+
+const crashRecoveryMocks = vi.hoisted(() => ({
+ deletePodIfExists: vi.fn().mockResolvedValue(undefined),
+ waitForPodDeletion: vi.fn().mockResolvedValue(true),
+ evaluateCompletedRuntimePodRecovery: vi.fn().mockReturnValue({
+ action: 'replace',
+ message:
+ 'mcp_host pod completed before workflow became terminal; creating replacement (attempt 1/3)',
+ newPhase: 'recovering',
+ newAttempt: 1,
+ }),
+ evaluateCrashRecovery: vi.fn().mockReturnValue({ action: 'none', message: 'Pod is healthy' }),
+ getContainerWaitingReason: vi.fn().mockResolvedValue(undefined),
+ getPodPhase: vi.fn().mockResolvedValue(undefined),
+ getPodReadiness: vi.fn().mockResolvedValue({ ready: true, phase: 'Running', uid: 'pod-uid-1' }),
+ isRecoverableContainerWaitingReason: vi.fn(() => false),
+}))
+
+const runtimeTokenIssuerMocks = vi.hoisted(() => ({
+ issueMcpHostRuntimeTokens: vi.fn().mockResolvedValue({
+ accessToken: 'runtime-access-token',
+ refreshToken: 'runtime-refresh-token',
+ mcpHostControlToken: 'mcp-host-control-token',
+ }),
+ issueMcpHostWorkflowControlToken: vi.fn().mockResolvedValue('mcp-host-control-token'),
+}))
+
+vi.mock('./crashRecovery', () => crashRecoveryMocks)
+vi.mock('./mcpHostRuntimeTokenIssuerClient', () => runtimeTokenIssuerMocks)
+
+vi.mock('../gfsBinding', () => ({
+ mintRecipeHostGfsToken: vi.fn().mockResolvedValue({
+ ['to'.concat('ken')]: 'gfs-runtime-value',
+ expiresInSeconds: 300,
+ subject: 'host:3rd:sandbox-recipes/codex-recipe',
+ }),
+}))
+
+const sandboxNamespace = 'sandbox-recipes'
+const CODEX_PROXY_POLICY = 'codex-recipe-mcp-host-to-codex-proxy'
+
+function unsignedRuntimeJwt(payload: Record<string, unknown>): string {
+ return `eyJhbGciOiJub25lIn0.${Buffer.from(JSON.stringify(payload)).toString('base64url')}.x`
+}
+
+function eligibleCodexConfigMap(stale = false) {
+ return {
+ metadata: {
+ resourceVersion: '1',
+ annotations: {
+ 'clerum.io/content-hash': 'aa',
+ 'clerum.io/catalog-revision': '1',
+ 'clerum.io/connection-revision': '1',
+ 'clerum.io/codex-connection-status': 'connected',
+ 'clerum.io/codex-enabled': 'true',
+ },
+ },
+ data: {
+ 'codex-subscription': JSON.stringify([{ model: 'gpt-5.3-codex', stale }]),
+ },
+ }
+}
+
+function makeCodexSpec(overrides?: Partial<WorkflowRecipeSpec>): WorkflowRecipeSpec {
+ return {
+ agent: { provider: 'codex-subscription', model: 'gpt-5.3-codex' },
+ steps: [{ id: 'brief', instruction: 'write the brief' }],
+ ...overrides,
+ }
+}
+
+function issuedScopes(): string[] {
+ const last = runtimeTokenIssuerMocks.issueMcpHostRuntimeTokens.mock.calls.at(-1)
+ return (last?.[2] ?? []) as string[]
+}
+
+function proxyPolicyBodies(networkingApi: {
+ createNamespacedNetworkPolicy: {
+ mock: { calls: Array<[{ body?: { metadata?: { name?: string }; spec?: unknown } }]> }
+ }
+}) {
+ return networkingApi.createNamespacedNetworkPolicy.mock.calls
+ .map(call => call[0]?.body)
+ .filter(body => body?.metadata?.name === CODEX_PROXY_POLICY)
+}
+
+function createHarness() {
+ const mockCoreApi = {
+ readNamespacedPod: vi.fn().mockImplementation(async (params: { name?: string }) => {
+ if (typeof params.name === 'string' && params.name.endsWith('-mcp-host')) {
+ return {
+ metadata: {
+ labels: { 'clerum.io/workflow-output-claim': 'shared-output' },
+ },
+ }
+ }
+ return {}
+ }),
+ readNamespacedSecret: vi.fn().mockRejectedValue({ code: 404 }),
+ readNamespacedService: vi.fn().mockResolvedValue({}),
+ readNamespacedEndpoints: vi.fn().mockRejectedValue({ code: 404 }),
+ readNamespacedConfigMap: vi.fn().mockResolvedValue(eligibleCodexConfigMap()),
+ createNamespacedSecret: vi.fn().mockResolvedValue({}),
+ createNamespacedConfigMap: vi.fn().mockResolvedValue({}),
+ createNamespacedService: vi.fn().mockResolvedValue({}),
+ createNamespacedPod: vi.fn().mockResolvedValue({}),
+ patchNamespacedSecret: vi.fn().mockResolvedValue({}),
+ deleteNamespacedSecret: vi.fn().mockResolvedValue({}),
+ deleteNamespacedConfigMap: vi.fn().mockResolvedValue({}),
+ deleteNamespacedService: vi.fn().mockResolvedValue({}),
+ readNamespacedPersistentVolumeClaim: vi.fn().mockResolvedValue({
+ metadata: { name: 'existing-workflow-output', deletionTimestamp: undefined },
+ }),
+ createNamespacedPersistentVolumeClaim: vi.fn().mockResolvedValue({}),
+ deleteNamespacedPersistentVolumeClaim: vi.fn().mockResolvedValue({}),
+ deleteCollectionNamespacedService: vi.fn().mockResolvedValue({}),
+ }
+ const mockNetworkingApi = {
+ createNamespacedNetworkPolicy: vi.fn().mockResolvedValue({}),
+ readNamespacedNetworkPolicy: vi.fn().mockResolvedValue({ metadata: { resourceVersion: '1' } }),
+ replaceNamespacedNetworkPolicy: vi.fn().mockResolvedValue({}),
+ deleteNamespacedNetworkPolicy: vi.fn().mockResolvedValue({}),
+ listNamespacedNetworkPolicy: vi.fn().mockResolvedValue({ items: [] }),
+ }
+ const mockCustomApi = {
+ patchNamespacedCustomObject: vi.fn().mockResolvedValue({}),
+ patchNamespacedCustomObjectStatus: vi.fn().mockResolvedValue({}),
+ }
+ const deps = {
+ coreApi: mockCoreApi,
+ customApi: mockCustomApi,
+ networkingApi: mockNetworkingApi,
+ config: {
+ coordinatorImage: 'coordinator:test',
+ mcpHostImage: 'mcp-host:test',
+ wrcEndpoint: 'http://wrc.example/api',
+ sandboxNamespace,
+ mcpServerNamespace: 'mcp-server',
+ imagePullPolicy: 'IfNotPresent' as const,
+ maxWorkflowSteps: 100,
+ runtimeTokenTtlSeconds: 3600,
+ runtimeTokenRefreshBeforeSeconds: 300,
+ },
+ tokenFactory: {
+ signWrcArtifactDeleteToken: vi.fn().mockResolvedValue('stub-token'),
+ signCoordinatorToMcpHostToken: vi.fn().mockResolvedValue('coordinator-mcp-host-token'),
+ signCustomCoordinatorToWrcToken: vi.fn().mockResolvedValue('custom-coordinator-wrc-token'),
+ signCoordinatorToWrcToken: vi.fn().mockResolvedValue('coordinator-wrc-token'),
+ },
+ pluginWorkloadSdkRevocationClient: {
+ revoke: vi.fn().mockResolvedValue({ state: 'missing', revoked: 0, fencedInvocations: 0 }),
+ finalize: vi.fn(),
+ },
+ } as unknown as WorkflowReconcilerDeps
+ return {
+ reconciler: new WorkflowReconciler(deps),
+ coreApi: mockCoreApi,
+ networkingApi: mockNetworkingApi,
+ }
+}
+
+async function reconcileRecipe(
+ reconciler: WorkflowReconciler,
+ spec: WorkflowRecipeSpec,
+ recipeName = 'codex-recipe',
+ runtimeScopeRecipeName = recipeName
+) {
+ crashRecoveryMocks.getPodPhase.mockImplementation(async (_api, name: string) => {
+ if (name.endsWith('-workflow-output-anchor')) return 'Running'
+ if (name.endsWith('-workflow-output-prepare')) return 'Succeeded'
+ return undefined
+ })
+ crashRecoveryMocks.getPodReadiness.mockResolvedValue({
+ ready: false,
+ phase: 'Pending',
+ })
+ return reconciler.reconcile(
+ recipeName,
+ `uid-${recipeName}`,
+ sandboxNamespace,
+ spec,
+ { workflowExecution: { phase: 'initializing' } },
+ undefined,
+ runtimeScopeRecipeName,
+ 'run-1'
+ )
+}
+
+describe('WorkflowReconciler Codex scope provenance', () => {
+ beforeEach(() => {
+ vi.clearAllMocks()
+ crashRecoveryMocks.getPodReadiness.mockResolvedValue({
+ ready: true,
+ phase: 'Running',
+ uid: 'pod-uid-1',
+ })
+ runtimeTokenIssuerMocks.issueMcpHostRuntimeTokens.mockResolvedValue({
+ accessToken: 'runtime-access-token',
+ refreshToken: 'runtime-refresh-token',
+ mcpHostControlToken: 'mcp-host-control-token',
+ })
+ })
+
+ it('issues derived Codex scope and proxy egress from the same reconcile projection', async () => {
+ const { reconciler, networkingApi } = createHarness()
+
+ await reconcileRecipe(reconciler, makeCodexSpec())
+
+ expect(issueMcpHostRuntimeTokens).toHaveBeenCalled()
+ expect(issuedScopes()).toContain('llm:codex:execute')
+ const policy = proxyPolicyBodies(networkingApi)[0]
+ expect(policy).toBeDefined()
+ expect(policy?.metadata?.labels?.['clerum.io/policy-type']).toBe('codex-proxy-egress')
+ expect(policy?.spec?.egress?.[0]?.to?.[0]?.podSelector?.matchLabels).toEqual({
+ app: 'codex-llm-proxy',
+ })
+ expect(policy?.spec?.egress?.[0]?.to?.[0]?.namespaceSelector?.matchLabels).toEqual({
+ 'kubernetes.io/metadata.name': 'control-plane',
+ })
+ expect(policy?.spec?.egress?.[0]?.ports).toEqual([{ port: 8080, protocol: 'TCP' }])
+ })
+
+ it('does not mint Codex from deriveWorkflowControlScopes when the target is static', async () => {
+ const { reconciler, networkingApi } = createHarness()
+
+ await reconcileRecipe(
+ reconciler,
+ makeCodexSpec({ agent: { provider: 'openai', model: 'gpt-5.4-mini' } })
+ )
+
+ expect(issueMcpHostRuntimeTokens).toHaveBeenCalled()
+ expect(issuedScopes()).not.toContain('llm:codex:execute')
+ expect(proxyPolicyBodies(networkingApi)).toEqual([])
+ })
+
+ it('reissues the token and withdraws egress when the target becomes static', async () => {
+ const { reconciler, coreApi, networkingApi } = createHarness()
+ await reconcileRecipe(reconciler, makeCodexSpec())
+ expect(issuedScopes()).toContain('llm:codex:execute')
+
+ const futureExp = Math.floor(Date.now() / 1000) + 3600
+ const binding = {
+ exp: futureExp,
+ recipeNamespace: sandboxNamespace,
+ recipeName: 'codex-recipe',
+ hostRefs: [`${sandboxNamespace}/codex-recipe`],
+ workflowControlScopes: ['llm:codex:execute'],
+ scopes: ['llm:codex:execute', 'gfs.read'],
+ }
+ coreApi.readNamespacedSecret.mockResolvedValue({
+ data: {
+ 'mcp-host-runtime-access-token': Buffer.from(unsignedRuntimeJwt(binding)).toString(
+ 'base64'
+ ),
+ 'mcp-host-runtime-refresh-token': Buffer.from(unsignedRuntimeJwt(binding)).toString(
+ 'base64'
+ ),
+ 'mcp-host-workflow-control-token': Buffer.from(unsignedRuntimeJwt(binding)).toString(
+ 'base64'
+ ),
+ 'mcp-host-gfs-token': Buffer.from(
+ unsignedRuntimeJwt({
+ ...binding,
+ sub: `host:3rd:${sandboxNamespace}/codex-recipe`,
+ scopes: ['gfs.read'],
+ })
+ ).toString('base64'),
+ },
+ })
+ runtimeTokenIssuerMocks.issueMcpHostRuntimeTokens.mockClear()
+
+ await reconcileRecipe(
+ reconciler,
+ makeCodexSpec({ agent: { provider: 'openai', model: 'gpt-5.4-mini' } })
+ )
+
+ expect(issueMcpHostRuntimeTokens).toHaveBeenCalled()
+ expect(issuedScopes()).not.toContain('llm:codex:execute')
+ expect(networkingApi.deleteNamespacedNetworkPolicy).toHaveBeenCalledWith({
+ name: CODEX_PROXY_POLICY,
+ namespace: sandboxNamespace,
+ })
+ })
+
+ it('withdraws scope and egress when the catalog marks the Codex model stale', async () => {
+ const { reconciler, coreApi, networkingApi } = createHarness()
+ await reconcileRecipe(reconciler, makeCodexSpec())
+ expect(issuedScopes()).toContain('llm:codex:execute')
+
+ coreApi.readNamespacedConfigMap.mockResolvedValue(eligibleCodexConfigMap(true))
+ runtimeTokenIssuerMocks.issueMcpHostRuntimeTokens.mockClear()
+ await reconcileRecipe(reconciler, makeCodexSpec())
+
+ expect(issueMcpHostRuntimeTokens).toHaveBeenCalled()
+ expect(issuedScopes()).not.toContain('llm:codex:execute')
+ expect(networkingApi.deleteNamespacedNetworkPolicy).toHaveBeenCalledWith({
+ name: CODEX_PROXY_POLICY,
+ namespace: sandboxNamespace,
+ })
+ })
+
+ it('inherits the parent target and ignores a static child body', async () => {
+ const { reconciler, networkingApi } = createHarness()
+ reconciler.setCodexReconcileContext({
+ recipeName: 'child-run',
+ runtimeScopeRecipeName: 'parent-recipe',
+ claimedParent: true,
+ parentSpec: makeCodexSpec(),
+ })
+
+ await reconcileRecipe(
+ reconciler,
+ makeCodexSpec({ agent: { provider: 'openai', model: 'gpt-5.4-mini' } }),
+ 'child-run',
+ 'parent-recipe'
+ )
+
+ expect(issuedScopes()).toContain('llm:codex:execute')
+ const createdPolicyNames = networkingApi.createNamespacedNetworkPolicy.mock.calls.map(
+ call => call[0]?.body?.metadata?.name
+ )
+ expect(createdPolicyNames).toContain('child-run-mcp-host-to-codex-proxy')
+ })
+
+ it('does not mint Codex when a claimed parent fails provenance', async () => {
+ const { reconciler, networkingApi } = createHarness()
+ reconciler.setCodexReconcileContext({
+ recipeName: 'child-run',
+ runtimeScopeRecipeName: 'child-run',
+ claimedParent: true,
+ parentSpec: makeCodexSpec(),
+ })
+
+ await reconcileRecipe(reconciler, makeCodexSpec(), 'child-run')
+
+ expect(issuedScopes()).not.toContain('llm:codex:execute')
+ expect(
+ networkingApi.createNamespacedNetworkPolicy.mock.calls.some(
+ call => call[0]?.body?.metadata?.name === 'child-run-mcp-host-to-codex-proxy'
+ )
+ ).toBe(false)
+ })
+
+ it('does not mint Codex scope or egress when the allowlist ConfigMap is forbidden', async () => {
+ const { reconciler, coreApi, networkingApi } = createHarness()
+ coreApi.readNamespacedConfigMap.mockRejectedValue(
+ Object.assign(new Error('forbidden'), { code: 403 })
+ )
+
+ await reconcileRecipe(reconciler, makeCodexSpec())
+
+ expect(issueMcpHostRuntimeTokens).toHaveBeenCalled()
+ expect(issuedScopes()).not.toContain('llm:codex:execute')
+ expect(proxyPolicyBodies(networkingApi)).toEqual([])
+ })
+
+ it('does not mint Codex scope or egress when the allowlist ConfigMap times out', async () => {
+ const { reconciler, coreApi, networkingApi } = createHarness()
+ coreApi.readNamespacedConfigMap.mockRejectedValue(
+ Object.assign(new Error('Kubernetes request timed out'), { code: 'ETIMEDOUT' })
+ )
+
+ await reconcileRecipe(reconciler, makeCodexSpec())
+
+ expect(issueMcpHostRuntimeTokens).toHaveBeenCalled()
+ expect(issuedScopes()).not.toContain('llm:codex:execute')
+ expect(proxyPolicyBodies(networkingApi)).toEqual([])
+ })
+})
diff --git a/workflow-recipes/src/workflow/workflowReconciler.ts b/workflow-recipes/src/workflow/workflowReconciler.ts
index 52a7506ae..a8f1e222d 100644
--- a/workflow-recipes/src/workflow/workflowReconciler.ts
+++ b/workflow-recipes/src/workflow/workflowReconciler.ts
@@ -39,6 +39,11 @@ import type {
WorkflowSnippetRunSpec,
} from '../types'
import { resolveMcpHostAgent } from './agentResolution'
+import {
+ type CodexCatalogSnapshot,
+ projectRecipeCodexExecution,
+ resolveCodexAuthoritativeSpec,
+} from './codexExecutionProjection'
import {
type PodReadiness,
deletePodIfExists,
@@ -52,6 +57,13 @@ import {
} from './crashRecovery'
import { JwtTokenFactory } from './jwtTokenFactory'
import {
+ ALLOWED_MODELS_CONFIGMAP_NAME,
+ ALLOWLIST_CONFIGMAP_NAMESPACE,
+ parseAllowedModelsSnapshot,
+ snapshotFromConfigMapError,
+} from './llmAllowedModelsSnapshot'
+import {
+ type EffectiveWorkflowControlScope,
type WorkflowControlScope,
issueMcpHostRuntimeTokens,
issueMcpHostWorkflowControlToken,
@@ -334,14 +346,26 @@ const WORKFLOW_CONTROL_SCOPE_ORDER: WorkflowControlScope[] = [
'plugin-workload-sdk',
]
+const EFFECTIVE_WORKFLOW_CONTROL_SCOPE_ORDER: EffectiveWorkflowControlScope[] = [
+ ...WORKFLOW_CONTROL_SCOPE_ORDER,
+ 'llm:codex:execute',
+]
+
+export type CodexReconcileContext = {
+ recipeName: string
+ runtimeScopeRecipeName: string
+ claimedParent: boolean
+ parentSpec: WorkflowRecipeSpec | null
+}
+
function orderedScopesEqual<T extends string>(actual: T[], expected: T[]): boolean {
if (actual.length !== expected.length) return false
return actual.every((scope, index) => scope === expected[index])
}
function workflowControlScopesEqual(
- actual: WorkflowControlScope[],
- expected: WorkflowControlScope[]
+ actual: EffectiveWorkflowControlScope[],
+ expected: EffectiveWorkflowControlScope[]
): boolean {
return orderedScopesEqual(actual, expected)
}
@@ -357,6 +381,17 @@ function workflowHasGfsPublishTargets(spec: WorkflowRecipeSpec): boolean {
return (spec.gfs?.publishTargets ?? []).length > 0
}
+function isCodexSnapshotTimeout(error: unknown): boolean {
+ const code = (error as { code?: unknown }).code
+ if (code === 'ETIMEDOUT' || code === 'UND_ERR_CONNECT_TIMEOUT' || code === 'ABORT_ERR') {
+ return true
+ }
+ const name = (error as { name?: string }).name
+ if (name === 'AbortError' || name === 'TimeoutError') return true
+ const message = error instanceof Error ? error.message : String(error)
+ return /timed?\s*out/i.test(message)
+}
+
function deriveRecipeHostGfsScopes(spec: WorkflowRecipeSpec): WorkflowRecipeGfsScope[] {
// Workflow/plugin hosts get a read ceiling by default so operators can grant
// readable GFS inputs after install without requiring a recipe spec rewrite.
@@ -380,6 +415,8 @@ function deriveWorkflowControlScopes(
spec: WorkflowRecipeSpec,
opts: { pluginWorkloadSdkEnabled?: boolean } = {}
): WorkflowControlScope[] {
+ // Declarative workflow/SDK scopes only. `llm:codex:execute` is derive-only
+ // from the Codex eligibility projection and must never be minted here.
const scopes = new Set<WorkflowControlScope>()
// Plugin Workload SDK (plan §3.6): only recipes that declare the
// capability — and only while the feature flag is on — receive the scope
@@ -840,6 +877,8 @@ export interface WorkflowReconcilerDeps {
export class WorkflowReconciler {
private readonly log = createLogger('wrc', 'reconciler')
private readonly pluginWorkloadSdkProvisioner: PluginWorkloadSdkProvisioner
+ private codexSnapshot: CodexCatalogSnapshot = { flagEnabled: false }
+ private codexContext: CodexReconcileContext | null = null
constructor(private readonly deps: WorkflowReconcilerDeps) {
this.pluginWorkloadSdkProvisioner = new PluginWorkloadSdkProvisioner({
@@ -872,6 +911,92 @@ export class WorkflowReconciler {
})
}
+ setCodexReconcileContext(context: CodexReconcileContext | null): void {
+ this.codexContext = context
+ }
+
+ private resolveCodexContext(
+ recipeName: string,
+ runtimeScopeRecipeName: string
+ ): CodexReconcileContext {
+ if (this.codexContext?.recipeName === recipeName) {
+ return { ...this.codexContext, runtimeScopeRecipeName }
+ }
+ return {
+ recipeName,
+ runtimeScopeRecipeName,
+ claimedParent: false,
+ parentSpec: null,
+ }
+ }
+
+ private projectCodex(
+ spec: WorkflowRecipeSpec,
+ recipeName: string,
+ runtimeScopeRecipeName: string
+ ) {
+ const context = this.resolveCodexContext(recipeName, runtimeScopeRecipeName)
+ const resolved = resolveCodexAuthoritativeSpec({
+ recipeName: context.recipeName,
+ runtimeScopeRecipeName: context.runtimeScopeRecipeName,
+ claimedParent: context.claimedParent,
+ ownSpec: spec,
+ parentSpec: context.parentSpec,
+ })
+ return projectRecipeCodexExecution(resolved.spec, this.codexSnapshot, resolved.provenance)
+ }
+
+ private resolveEffectiveControlScopes(
+ spec: WorkflowRecipeSpec,
+ recipeName: string,
+ runtimeScopeRecipeName: string
+ ): EffectiveWorkflowControlScope[] {
+ const workflow = deriveWorkflowControlScopes(spec, {
+ pluginWorkloadSdkEnabled: this.deps.config.pluginWorkloadSdkEnabled,
+ })
+ const derived = this.projectCodex(
+ spec,
+ recipeName,
+ runtimeScopeRecipeName
+ ).derivedScopes.filter(scope => !workflow.includes(scope as WorkflowControlScope))
+ return [...workflow, ...derived] as EffectiveWorkflowControlScope[]
+ }
+
+ private async refreshCodexSnapshot(): Promise<void> {
+ try {
+ const cm = await this.deps.coreApi.readNamespacedConfigMap({
+ name: ALLOWED_MODELS_CONFIGMAP_NAME,
+ namespace: ALLOWLIST_CONFIGMAP_NAMESPACE,
+ })
+ this.codexSnapshot = parseAllowedModelsSnapshot(cm)
+ } catch (err) {
+ if (isCodexSnapshotTimeout(err)) {
+ this.codexSnapshot = snapshotFromConfigMapError('timeout')
+ this.log.warn('Codex allowlist ConfigMap read timed out; failing closed', {
+ configMap: ALLOWED_MODELS_CONFIGMAP_NAME,
+ namespace: ALLOWLIST_CONFIGMAP_NAMESPACE,
+ })
+ return
+ }
+ const code = getErrorCode(err)
+ if (code === 401 || code === 403) {
+ this.codexSnapshot = snapshotFromConfigMapError('forbidden')
+ this.log.warn('Codex allowlist ConfigMap read forbidden; failing closed', {
+ configMap: ALLOWED_MODELS_CONFIGMAP_NAME,
+ namespace: ALLOWLIST_CONFIGMAP_NAMESPACE,
+ statusCode: code,
+ })
+ return
+ }
+ this.codexSnapshot = snapshotFromConfigMapError('missing')
+ this.log.warn('Codex allowlist ConfigMap unavailable; failing closed', {
+ configMap: ALLOWED_MODELS_CONFIGMAP_NAME,
+ namespace: ALLOWLIST_CONFIGMAP_NAMESPACE,
+ statusCode: code,
+ })
+ }
+ }
+
private get runtimeTokenRefreshBeforeSeconds(): number {
return this.deps.config.runtimeTokenRefreshBeforeSeconds
}
@@ -1004,6 +1129,7 @@ export class WorkflowReconciler {
`${recipeName}-mcp-host-to-llm-api`,
`${recipeName}-mcp-host-to-gfs`,
`${recipeName}-mcp-host-to-approval-gateway`,
+ `${recipeName}-mcp-host-to-codex-proxy`,
]
const networkPolicyNames = preserveWorkflowRuntime
? sdkNetworkPolicyNames
@@ -1230,6 +1356,7 @@ export class WorkflowReconciler {
): Promise<WorkflowReconcileResult> {
const preflightError = this.validateWorkflowSpec(spec)
if (preflightError) return { phase: 'failed', message: preflightError, workflowPhase: 'failed' }
+ await this.refreshCodexSnapshot()
const secretPreflightError = await this.validateSnippetSecretRefs(
recipeName,
spec,
@@ -2438,6 +2565,7 @@ export class WorkflowReconciler {
pluginWorkloadSdkEnabled: this.deps.config.pluginWorkloadSdkEnabled,
})
if (!runtime.mcpHost.required) return
+ await this.refreshCodexSnapshot()
await this.ensureMcpHostSecrets(recipeNamespace, recipeName, runtimeScopeRecipeName, spec)
}
@@ -2671,6 +2799,11 @@ export class WorkflowReconciler {
artifactReaderPort: 8080,
snippetRunnerPort: 8095,
includeMcpHost: runtime.network.includeMcpHost && mcpHostLaneLive,
+ includeCodexProxyEgress:
+ this.projectCodex(spec, recipeName, this.codexContext?.runtimeScopeRecipeName ?? recipeName)
+ .requiresCodexProxyEgress &&
+ runtime.network.includeMcpHost &&
+ mcpHostLaneLive,
// A stepless eager SDK host has no coordinator pod. Keep the mcp-host
// control/egress lanes, but do not manufacture coordinator policies
// whose selectors can never match a real workload.
@@ -2775,6 +2908,16 @@ export class WorkflowReconciler {
for (const policy of policies) {
await this.applyNetworkPolicy(policy)
}
+ const policyNames = new Set(policies.map(policy => policy.metadata?.name))
+ const codexProxyPolicyName = `${recipeName}-mcp-host-to-codex-proxy`
+ if (!policyNames.has(codexProxyPolicyName)) {
+ await this.safeDelete(() =>
+ this.deps.networkingApi.deleteNamespacedNetworkPolicy({
+ name: codexProxyPolicyName,
+ namespace: this.deps.config.sandboxNamespace,
+ })
+ )
+ }
await this.pruneLegacyMcpServersInternetEgressPolicy(recipeName)
}
@@ -3105,6 +3248,7 @@ export class WorkflowReconciler {
`${recipeName}-mcp-host-to-servers`,
`${recipeName}-mcp-host-to-llm-api`,
`${recipeName}-mcp-host-to-approval-gateway`,
+ `${recipeName}-mcp-host-to-codex-proxy`,
`${recipeName}-coord-to-snippet-runner`,
`${recipeName}-coord-to-snippet-runner-ingress`,
`${recipeName}-snippet-runner-egress`,
@@ -3480,9 +3624,7 @@ export class WorkflowReconciler {
namespace,
recipeName,
runtimeScopeRecipeName,
- deriveWorkflowControlScopes(spec, {
- pluginWorkloadSdkEnabled: this.deps.config.pluginWorkloadSdkEnabled,
- }),
+ this.resolveEffectiveControlScopes(spec, recipeName, runtimeScopeRecipeName),
deriveRecipeHostGfsScopes(spec)
)
if (this.deps.config.pluginWorkloadSdkEnabled && spec.pluginWorkloadSdk) {
@@ -4416,7 +4558,7 @@ export class WorkflowReconciler {
recipeNamespace: string,
recipeName: string,
runtimeScopeRecipeName = recipeName,
- workflowControlScopes: WorkflowControlScope[] = [],
+ workflowControlScopes: EffectiveWorkflowControlScope[] = [],
gfsScopes: WorkflowRecipeGfsScope[] = ['gfs.read']
): Promise<void> {
const secretName = `wf-${recipeName}-mcp-host-runtime-tokens`
@@ -4491,7 +4633,7 @@ export class WorkflowReconciler {
recipeNamespace: string,
recipeName: string,
runtimeScopeRecipeName: string,
- workflowControlScopes: WorkflowControlScope[],
+ workflowControlScopes: EffectiveWorkflowControlScope[],
expectedGfsScopes: WorkflowRecipeGfsScope[],
existing: k8s.V1Secret
): Promise<void> {
@@ -4665,7 +4807,7 @@ export class WorkflowReconciler {
private async issueMcpHostControlToken(
recipeNamespace: string,
recipeName: string,
- workflowControlScopes: WorkflowControlScope[]
+ workflowControlScopes: EffectiveWorkflowControlScope[]
): Promise<string> {
try {
return await issueMcpHostWorkflowControlToken(
@@ -4713,23 +4855,23 @@ export class WorkflowReconciler {
private static jwtWorkflowControlScopes(
jwt: string,
claim: 'scopes' | 'workflowControlScopes' = 'scopes'
- ): WorkflowControlScope[] {
+ ): EffectiveWorkflowControlScope[] {
try {
const payload = decodeJwt(jwt)
const scopes = Array.isArray(payload[claim]) ? payload[claim] : []
- const normalized: WorkflowControlScope[] = []
+ const normalized: EffectiveWorkflowControlScope[] = []
const seen = new Set<string>()
for (const scope of scopes) {
if (
typeof scope === 'string' &&
- (WORKFLOW_CONTROL_SCOPE_ORDER as string[]).includes(scope) &&
+ (EFFECTIVE_WORKFLOW_CONTROL_SCOPE_ORDER as string[]).includes(scope) &&
!seen.has(scope)
) {
seen.add(scope)
- normalized.push(scope as WorkflowControlScope)
+ normalized.push(scope as EffectiveWorkflowControlScope)
}
}
- return WORKFLOW_CONTROL_SCOPE_ORDER.filter(scope => normalized.includes(scope))
+ return EFFECTIVE_WORKFLOW_CONTROL_SCOPE_ORDER.filter(scope => normalized.includes(scope))
} catch {
return []
}
diff --git a/workflow-recipes/tests/unit/workflow/modelConfigHandler.test.ts b/workflow-recipes/tests/unit/workflow/modelConfigHandler.test.ts
index 5fafb9c85..828d663f7 100644
--- a/workflow-recipes/tests/unit/workflow/modelConfigHandler.test.ts
+++ b/workflow-recipes/tests/unit/workflow/modelConfigHandler.test.ts
@@ -438,6 +438,33 @@ describe('POST /configure-model — R3 allowlist gate', () => {
expect(result.status).toBe(202)
})
+ it('configures codex-subscription without reading a Secret', async () => {
+ const allowlist = { 'codex-subscription': JSON.stringify([{ model: 'gpt-5.3-codex' }]) }
+ const k8s = mockK8s(DEFAULT_CONFIGMAP, DEFAULT_SECRET, allowlist)
+ const mcpHost = mockMcpHost()
+ const handler = new ModelConfigHandler(k8s, mcpHost)
+
+ const result = await handler.handle(
+ { stepId: 's1', provider: 'codex-subscription', model: 'gpt-5.3-codex' },
+ 'http://mcp:8080',
+ 'tok'
+ )
+
+ expect(result.status).toBe(202)
+ expect(result.body).toEqual({
+ configured: true,
+ provider: 'codex-subscription',
+ model: 'gpt-5.3-codex',
+ })
+ expect(k8s.readSecret).not.toHaveBeenCalled()
+ expect(mcpHost.configure).toHaveBeenCalledWith('http://mcp:8080', 'tok', {
+ provider: 'codex-subscription',
+ model: 'gpt-5.3-codex',
+ })
+ expect(JSON.stringify(result.body)).not.toContain('sk-test')
+ expect(result.body).not.toHaveProperty('apiKey')
+ })
+
it('rejects a model absent from the allowlist → 403 model_not_allowed', async () => {
const allowlist = { openai: JSON.stringify([{ model: 'gpt-4' }]) }
const k8s = mockK8s(DEFAULT_CONFIGMAP, DEFAULT_SECRET, allowlist)