Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure
TypeScript
fix: derive the Codex binding from the same eligibility as the scopes
Alfredo Lopez42a3914a32f2
diff --git a/packages/codex-catalog-projection/index.cjs b/packages/codex-catalog-projection/index.cjsindex 4f7834463..c911f2bf8 100644--- a/packages/codex-catalog-projection/index.cjs+++ b/packages/codex-catalog-projection/index.cjs@@ -302,6 +302,54 @@ function toPolicyBinding(cm, connectionKey) {return { catalogRevision, credentialRevision, connectionKey: key }}+/**+ * Mint an execution policy binding for one (grant, model) pair using the SAME+ * eligibility cascade that decides `llm:codex:execute`. It is deliberately a+ * caller of `projectCodexExecution` with a synthetic single-target spec, not a+ * second copy of the cascade: the invariant+ * `binding !== null ⇔ derivedScopes.includes(CODEX_EXECUTE_SCOPE)`+ * is what keeps the scope gate and the binding gate from drifting apart.+ *+ * Always returns an object so the caller can log `reason` (e.g.+ * `connection_reauth-required`) without projecting a second time.+ */+function toEligiblePolicyBinding(cm, connectionKey, model) {+ const key = assignedCodexConnectionKey(connectionKey)+ const trimmedModel = typeof model === 'string' ? model.trim() : ''+ if (key === CODEX_UNASSIGNED_CONNECTION_KEY) {+ return { binding: null, eligibility: 'ineligible', reason: 'unassigned' }+ }+ if (!trimmedModel) {+ return { binding: null, eligibility: 'ineligible', reason: 'model_missing' }+ }+ const snapshot = parseAllowedModelsSnapshot(cm, key)+ const projection = projectCodexExecution(+ { model: { provider: CODEX_PROVIDER, name: trimmedModel } },+ snapshot+ )+ if (projection.eligibility !== 'eligible') {+ return { binding: null, eligibility: projection.eligibility, reason: projection.reason }+ }+ // Revisions come from the normalized snapshot (assigned.* first, global+ // annotations as the legacy shape). The writer always emits both.+ if (+ !Number.isInteger(snapshot.catalogRevision) ||+ !Number.isInteger(snapshot.connectionRevision)+ ) {+ return { binding: null, eligibility: 'ineligible', reason: 'revision_missing' }+ }+ return {+ binding: {+ connectionKey: key,+ catalogRevision: snapshot.catalogRevision,+ credentialRevision: snapshot.connectionRevision,+ model: trimmedModel,+ },+ eligibility: 'eligible',+ reason: 'eligible',+ }+}+module.exports = {ALLOWED_MODELS_CONFIGMAP_NAME,CONTENT_HASH_ANNOTATION,@@ -322,4 +370,5 @@ module.exports = {collectCodexTargets,projectCodexExecution,toPolicyBinding,+ toEligiblePolicyBinding,}diff --git a/packages/codex-catalog-projection/index.d.ts b/packages/codex-catalog-projection/index.d.tsindex b92313950..f7be31004 100644--- a/packages/codex-catalog-projection/index.d.ts+++ b/packages/codex-catalog-projection/index.d.ts@@ -81,6 +81,24 @@ export type CodexPolicyBinding = {models?: string[]}+export type CodexEligiblePolicyBinding = {+ connectionKey: string+ catalogRevision: number+ credentialRevision: number+ model: string+}++export type CodexEligiblePolicyBindingProjection = {+ binding: CodexEligiblePolicyBinding | null+ eligibility: CodexEligibility+ /**+ * `eligible` | `unassigned` | `model_missing` | `revision_missing`, or the+ * `reason` of the underlying `projectCodexExecution` (`flag_off`,+ * `connection_<status>`, `no_eligible_broker_target`, `snapshot_<error>`).+ */+ reason: string+}+/** Empty or missing → `unassigned`. Never aliases `deployment-default`. */export declare function assignedCodexConnectionKey(value?: string | null): stringexport declare function isCodexUnassignedConnectionKey(value?: string | null): boolean@@ -99,7 +117,24 @@ export declare function projectCodexExecution(spec: CodexHostSpec,snapshot: CodexCatalogSnapshot): CodexExecutionProjection+/**+ * Structural revision view for the Host chat reader (`configStore`). It does+ * NOT decide eligibility: a transiently `unavailable`/`reauth-required`+ * connection still yields a binding here on purpose, so a live mcp-host+ * binding is not wiped by a degraded snapshot. To mint an *execution* binding+ * use `toEligiblePolicyBinding`.+ */export declare function toPolicyBinding(cm: CodexConfigMapView | undefined | null,connectionKey?: string): CodexPolicyBinding | null+/**+ * Execution-gate binding: `binding !== null` exactly when+ * `projectCodexExecution` derives `llm:codex:execute` for the same model and+ * grant. `reason` explains a null binding without a second projection.+ */+export declare function toEligiblePolicyBinding(+ cm: CodexConfigMapView | undefined | null,+ connectionKey: string | undefined,+ model: string+): CodexEligiblePolicyBindingProjectiondiff --git a/packages/codex-catalog-projection/index.test.cjs b/packages/codex-catalog-projection/index.test.cjsindex d79a99ec0..b987ef6eb 100644--- a/packages/codex-catalog-projection/index.test.cjs+++ b/packages/codex-catalog-projection/index.test.cjs@@ -113,9 +113,10 @@ test('revoked is a first-class connectionStatus and blocks execute', () => {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',- ])+ 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@@ -158,3 +159,239 @@ test('missing ConfigMap is an error snapshot and a null binding', () => {assert.equal(snapshot.snapshotError, 'missing')assert.equal(projection.toPolicyBinding(undefined, 'team-plus'), null)})++// ── toEligiblePolicyBinding: the execution gate ───────────────────────────++function withAnnotations(view, annotations) {+ return {+ metadata: {+ annotations: {+ ...view.metadata.annotations,+ ...annotations,+ ...(typeof view.metadata.annotations['clerum.io/codex-connections'] === 'object' &&+ view.metadata.annotations['clerum.io/codex-connections'] !== null+ ? {+ 'clerum.io/codex-connections': JSON.stringify(+ view.metadata.annotations['clerum.io/codex-connections']+ ),+ }+ : {}),+ },+ },+ data: view.data,+ }+}++/**+ * Every case below is also fed to the parity oracle at the bottom of the file.+ * `{ cm, key, model }` plus the expected `binding !== null` and `reason`.+ */+const ELIGIBILITY_MATRIX = [+ {+ name: 'mapped hit: connected, listed in the map and in the catalog',+ cm: () => mappedView(),+ key: 'personal-pro',+ model: 'gpt-5.1',+ binding: {+ connectionKey: 'personal-pro',+ catalogRevision: 4,+ credentialRevision: 2,+ model: 'gpt-5.1',+ },+ reason: 'eligible',+ },+ ...['disconnected', 'reauth-required', 'unavailable', 'revoked'].map(status => ({+ name: `mapped connection status ${status} withholds the binding`,+ cm: () =>+ withConnections(FIXTURE.mapped, parsed => {+ parsed['personal-pro'].status = status+ }),+ key: 'personal-pro',+ model: 'gpt-5.1',+ binding: null,+ reason: `connection_${status}`,+ })),+ {+ name: 'Codex feature flag off withholds the binding',+ cm: () => withAnnotations(FIXTURE.mapped, { 'clerum.io/codex-enabled': 'false' }),+ key: 'personal-pro',+ model: 'gpt-5.1',+ binding: null,+ reason: 'flag_off',+ },+ {+ name: 'a stale catalog row withholds the binding',+ cm: () => ({+ metadata: mappedView().metadata,+ data: {+ ...FIXTURE.mapped.data,+ 'codex-subscription': JSON.stringify([+ { model: 'gpt-5.3-codex', stale: false },+ { model: 'gpt-5.1', stale: true },+ ]),+ },+ }),+ key: 'personal-pro',+ model: 'gpt-5.1',+ binding: null,+ reason: 'no_eligible_broker_target',+ },+ {+ name: 'a model listed in the grant map but absent from the catalog withholds the binding',+ cm: () =>+ withConnections(FIXTURE.mapped, parsed => {+ parsed['personal-pro'].models.push('gpt-5.9-unpublished')+ }),+ key: 'personal-pro',+ model: 'gpt-5.9-unpublished',+ binding: null,+ reason: 'no_eligible_broker_target',+ },+ {+ name: 'a model in the catalog but outside the grant map withholds the binding',+ cm: () => mappedView(),+ key: 'personal-pro',+ model: 'gpt-5.3-codex',+ binding: null,+ reason: 'no_eligible_broker_target',+ },+ {+ name: 'legacy without a map keeps the flat catalog for a real key',+ cm: () => FIXTURE.legacy,+ key: 'team-plus',+ model: 'gpt-5.3-codex',+ binding: {+ connectionKey: 'team-plus',+ catalogRevision: 4,+ credentialRevision: 2,+ model: 'gpt-5.3-codex',+ },+ reason: 'eligible',+ },+ {+ name: 'legacy that does not list the model withholds the binding',+ cm: () => FIXTURE.legacy,+ key: 'team-plus',+ model: 'gpt-5.9-unpublished',+ binding: null,+ reason: 'no_eligible_broker_target',+ },+ {+ name: 'an unreadable ConfigMap is uncertain, never ineligible',+ cm: () => undefined,+ key: 'team-plus',+ model: 'gpt-5.3-codex',+ binding: null,+ reason: 'snapshot_missing',+ eligibility: 'uncertain',+ },+ {+ name: 'malformed catalog data is uncertain, never ineligible',+ cm: () => ({+ metadata: mappedView().metadata,+ data: { 'codex-subscription': 'not json' },+ }),+ key: 'personal-pro',+ model: 'gpt-5.1',+ binding: null,+ reason: 'snapshot_malformed',+ eligibility: 'uncertain',+ },+ {+ name: 'an unassigned grant never mints a binding',+ cm: () => mappedView(),+ key: 'unassigned',+ model: 'gpt-5.3-codex',+ binding: null,+ reason: 'unassigned',+ },+ {+ name: 'an empty model never mints a binding',+ cm: () => mappedView(),+ key: 'personal-pro',+ model: ' ',+ binding: null,+ reason: 'model_missing',+ },+]++for (const entry of ELIGIBILITY_MATRIX) {+ test(`toEligiblePolicyBinding — ${entry.name}`, () => {+ const result = projection.toEligiblePolicyBinding(entry.cm(), entry.key, entry.model)+ assert.deepEqual(result.binding, entry.binding)+ assert.equal(result.reason, entry.reason)+ assert.equal(+ result.eligibility,+ entry.eligibility ?? (entry.binding ? 'eligible' : 'ineligible')+ )+ })+}++test('toEligiblePolicyBinding withholds the binding when the catalog carries no revisions', () => {+ // Strictly stronger than the scope gate: the execution binding hashes the+ // revisions, so it cannot be minted without them. This is the ONE direction+ // in which the two gates are allowed to differ, and it fails closed — the+ // recipe gets the scope but no binding, so mcp-host stays awaiting_policy.+ const cm = {+ metadata: {+ annotations: {+ 'clerum.io/codex-connection-status': 'connected',+ 'clerum.io/codex-enabled': 'true',+ },+ },+ data: { 'codex-subscription': JSON.stringify([{ model: 'gpt-5.1', stale: false }]) },+ }+ const result = projection.toEligiblePolicyBinding(cm, 'team-plus', 'gpt-5.1')+ assert.equal(result.binding, null)+ assert.equal(result.reason, 'revision_missing')+ const scoped = projection.projectCodexExecution(+ { model: { provider: projection.CODEX_PROVIDER, name: 'gpt-5.1' } },+ projection.parseAllowedModelsSnapshot(cm, 'team-plus')+ )+ assert.ok(scoped.derivedScopes.includes(projection.CODEX_EXECUTE_SCOPE))+})++test('parity oracle: the execution binding and the execute scope never disagree', () => {+ // The invariant behind unifying the two gates (N-03). A binding minted where+ // the scope gate says no is the dangerous direction — the recipe would hold+ // an execution policy the reconciler refuses to authorize — so it is+ // asserted unconditionally. The converse holds for every ConfigMap that+ // carries revisions, which is every ConfigMap the writer emits.+ let checked = 0+ for (const entry of ELIGIBILITY_MATRIX) {+ const cm = entry.cm()+ const { binding } = projection.toEligiblePolicyBinding(cm, entry.key, entry.model)+ const snapshot = projection.parseAllowedModelsSnapshot(cm, entry.key)+ const scoped = projection+ .projectCodexExecution(+ { model: { provider: projection.CODEX_PROVIDER, name: entry.model } },+ snapshot+ )+ .derivedScopes.includes(projection.CODEX_EXECUTE_SCOPE)+ assert.equal(+ binding !== null,+ scoped,+ `${entry.name}: binding=${binding !== null} scope=${scoped}`+ )+ checked += 1+ }+ assert.ok(checked >= ELIGIBILITY_MATRIX.length)+})++test('toPolicyBinding still serves Host chat through a degraded connection', () => {+ // Contract guard for mcp-host's configStore: hardening `toPolicyBinding` in+ // place would wipe a live Host binding on a transient `unavailable`, which is+ // exactly the regression J4 closed. The execution gate is a separate function.+ for (const status of ['reauth-required', 'unavailable', 'revoked', 'disconnected']) {+ const cm = withConnections(FIXTURE.mapped, parsed => {+ parsed['personal-pro'].status = status+ })+ assert.deepEqual(projection.toPolicyBinding(cm, 'personal-pro'), {+ catalogRevision: 4,+ credentialRevision: 2,+ connectionKey: 'personal-pro',+ models: ['gpt-5.1'],+ })+ assert.equal(projection.toEligiblePolicyBinding(cm, 'personal-pro', 'gpt-5.1').binding, null)+ }+})diff --git a/workflow-recipes/package-lock.json b/workflow-recipes/package-lock.jsonindex ce0c881ae..ec9ef2bdd 100644--- a/workflow-recipes/package-lock.json+++ b/workflow-recipes/package-lock.json@@ -1,12 +1,12 @@{"name": "workload-recipes-controller",- "version": "0.1.327",+ "version": "0.1.328","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "workload-recipes-controller",- "version": "0.1.327",+ "version": "0.1.328","license": "SEE LICENSE IN LICENSE","dependencies": {"@aws-sdk/client-s3": "^3.1009.0",diff --git a/workflow-recipes/package.json b/workflow-recipes/package.jsonindex 88fdfc8c8..a7a77cf17 100644--- a/workflow-recipes/package.json+++ b/workflow-recipes/package.json@@ -1,6 +1,6 @@{"name": "workload-recipes-controller",- "version": "0.1.327",+ "version": "0.1.328","description": "Workload Recipes Controller (WRC) - WorkloadRecipe lifecycle management and MCP server interface","main": "dist/main.js","engines": {diff --git a/workflow-recipes/src/workflow/modelConfigHandler.ts b/workflow-recipes/src/workflow/modelConfigHandler.tsindex 4e9474b84..b71e0de08 100644--- a/workflow-recipes/src/workflow/modelConfigHandler.ts+++ b/workflow-recipes/src/workflow/modelConfigHandler.ts@@ -21,10 +21,7 @@ import {isRunnableLlmModelId,} from '@clerum/llm-providers'import { createLogger } from '../observability/logger'-import {- isPluginWorkloadSdkCodexBindingProof,- sanitizePluginWorkloadSdkCodexBindingProof,-} from './sdkOnlyCodexBinding'+import { readVerifiedSdkOnlyCodexBinding } from './sdkOnlyCodexBinding'// ─── Types ──────────────────────────────────────────────────────────────@@ -293,6 +290,15 @@ export class ModelConfigHandler {(result.body.provider !== provider || result.body.model !== model)) ||!familyProofValid) {+ // A host that configured itself successfully but answered v2 to a+ // Codex bootstrap is running a pre-v3 image — a stale workload, not a+ // broker outage. Tag it so WRC can report `codex_bootstrap_contract_stale`+ // instead of burning the configure budget into "provider unavailable".+ const codexContractStale =+ expectedContractVersion === 3 &&+ result.body.configured === true &&+ result.body.ready === true &&+ result.body.contractVersion === 2return {status: 502,body: {@@ -300,10 +306,15 @@ export class ModelConfigHandler {expectedContractVersion === 3? 'mcp_host bootstrap identity is not Plugin Workload SDK v3': 'mcp_host bootstrap identity is not Plugin Workload SDK v2',+ ...(codexContractStale ? { policyReason: 'codex_bootstrap_contract_stale' } : {}),},}}const policyProof = capabilityFamily === 'promptBridge' && isBootstrapPolicyProof(result.body)+ // Shape alone is not proof: re-derive the policy hash and pin the model+ // so a host cannot echo a well-formed binding for another model or with+ // a hash that does not match its own five fields.+ const verifiedCodexBinding = readVerifiedSdkOnlyCodexBinding(result.body.codexBinding, model)return {status: 202,body: {@@ -313,9 +324,7 @@ export class ModelConfigHandler {model,contractVersion: expectedContractVersion,capabilityFamily,- ...(isPluginWorkloadSdkCodexBindingProof(result.body.codexBinding)- ? { codexBinding: sanitizePluginWorkloadSdkCodexBindingProof(result.body.codexBinding) }- : {}),+ ...(verifiedCodexBinding ? { codexBinding: verifiedCodexBinding } : {}),...(typeof result.body.policyReady === 'boolean'? { policyReady: result.body.policyReady }: {}),diff --git a/workflow-recipes/src/workflow/pluginWorkloadSdkProvisioner.codexPolicy.test.ts b/workflow-recipes/src/workflow/pluginWorkloadSdkProvisioner.codexPolicy.test.tsnew file mode 100644index 000000000..493dfca51--- /dev/null+++ b/workflow-recipes/src/workflow/pluginWorkloadSdkProvisioner.codexPolicy.test.ts@@ -0,0 +1,337 @@+import { describe, expect, it, vi } from 'vitest'+import { computeCodexPolicyHash } from '@clerum/llm-provider-attempt-contract'+import type { WorkflowRecipeSpec } from '../types'+import {+ PluginWorkloadSdkProvisioner,+ type PluginWorkloadSdkProvisionerDeps,+} from './pluginWorkloadSdkProvisioner'+import { buildMcpHostPod, pluginWorkloadSdkRuntimeContractHash } from './podFactory'+import type { WorkflowRuntimePlan } from './runtimePlan'+import type { PluginWorkloadSdkCodexBindingProof } from './sdkOnlyCodexBinding'+import type { WorkflowConfig } from './types'++const SANDBOX_NS = 'sandbox-recipes'+const IMAGE = 'registry.example/clerum/mcp-host-slim:sha-current'+const RECIPE = 'codex-sdk'+const MODEL = 'gpt-5.3-codex'++const RUNTIME = {} as unknown as WorkflowRuntimePlan++const TEST_CONFIG = {+ coordinatorImage: 'registry.example/coordinator:current',+ mcpHostImage: IMAGE,+ wrcEndpoint: 'http://workflow-recipes.example',+ sandboxNamespace: SANDBOX_NS,+ mcpServerNamespace: 'mcp-server',+ imagePullPolicy: 'IfNotPresent',+ maxWorkflowSteps: 10,+ pluginWorkloadSdkEnabled: true,+} as unknown as WorkflowConfig++const CODEX_SPEC = {+ agent: { provider: 'codex-subscription', model: MODEL },+ pluginWorkloadSdk: { promptBridge: {} },+} as unknown as WorkflowRecipeSpec++function codexBinding(+ overrides: Partial<Omit<PluginWorkloadSdkCodexBindingProof, 'bindingHash'>> = {}+): PluginWorkloadSdkCodexBindingProof {+ const fields = {+ connectionKey: 'team-plus',+ catalogRevision: 4,+ credentialRevision: 2,+ model: MODEL,+ ...overrides,+ }+ return { ...fields, bindingHash: computeCodexPolicyHash(fields) }+}++const MINTED = codexBinding()++/** A v3 bootstrap body that survives parseEagerSdkBootstrapProof as policy-ready. */+function readyBootstrapBody(binding: PluginWorkloadSdkCodexBindingProof | null) {+ return {+ status: 202,+ body: {+ configured: true,+ ready: true,+ provider: 'codex-subscription',+ model: MODEL,+ contractVersion: 3,+ policyReady: true,+ policyState: 'active',+ policyRevision: 7,+ policyHash: 'b'.repeat(64),+ defaultTargetRef: 'target/codex',+ defaultProvider: 'codex-subscription',+ defaultModel: MODEL,+ ...(binding ? { codexBinding: binding } : {}),+ },+ }+}++function desiredRuntimeContractHash(): string {+ return pluginWorkloadSdkRuntimeContractHash(+ buildMcpHostPod(+ RECIPE,+ CODEX_SPEC.agent,+ TEST_CONFIG,+ RECIPE,+ SANDBOX_NS,+ undefined,+ undefined,+ undefined,+ {+ mountWorkflowOutput: false,+ pluginWorkloadSdkCapabilities: ['promptBridge'],+ pluginWorkloadSdkRuntimeMode: 'sdk-only',+ }+ )+ )+}++function makeHarness(configureResult: unknown) {+ let podUid = 'pod-uid-1'+ const runtimeContractHash = desiredRuntimeContractHash()+ const readNamespacedPod = vi.fn().mockImplementation(async () => ({+ metadata: {+ uid: podUid,+ annotations: {+ 'clerum.io/plugin-workload-sdk-runtime-contract-hash': runtimeContractHash,+ },+ },+ spec: { containers: [{ name: 'mcp-host', image: IMAGE }] },+ status: {+ phase: 'Running',+ conditions: [{ type: 'Ready', status: 'True' }],+ containerStatuses: [],+ },+ }))+ const deleteNamespacedPod = vi.fn().mockResolvedValue({})+ const createNamespacedPod = vi.fn().mockResolvedValue({})+ const configure = vi.fn().mockResolvedValue(configureResult)+ const signWrcConfigureToken = vi.fn().mockResolvedValue('configure-token')+ const deps = {+ coreApi: { readNamespacedPod, deleteNamespacedPod, createNamespacedPod },+ config: TEST_CONFIG,+ tokenFactory: { signWrcConfigureToken },+ modelConfigHandler: { configurePluginWorkloadSdkBootstrap: configure },+ log: { info: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn() },+ ensureMcpHostSecrets: vi.fn().mockResolvedValue(undefined),+ applyWorkflowNetworkPolicies: vi.fn().mockResolvedValue(undefined),+ ensureMcpHostHeadlessService: vi.fn().mockResolvedValue(undefined),+ createIfNotExists: vi.fn().mockResolvedValue(true),+ safeDelete: vi.fn().mockResolvedValue(undefined),+ } as unknown as PluginWorkloadSdkProvisionerDeps+ const provisioner = new PluginWorkloadSdkProvisioner(deps)++ const reconcile = (opts: {+ codexBinding?: PluginWorkloadSdkCodexBindingProof | null+ codexSnapshotUnavailable?: boolean+ }) =>+ provisioner.ensureEagerSdkMcpHost(+ RECIPE,+ 'recipe-uid',+ SANDBOX_NS,+ RECIPE,+ CODEX_SPEC,+ RUNTIME,+ {+ mcpHostPhase: 'Running',+ ...opts,+ }+ )++ return {+ provisioner,+ reconcile,+ configure,+ deleteNamespacedPod,+ signWrcConfigureToken,+ setPodUid: (uid: string) => {+ podUid = uid+ },+ }+}++describe('eager Codex policy gate', () => {+ it('reports ready from a cached proof of the SAME pod when the snapshot goes unavailable', async () => {+ // The early-return's `ready` arm. It is only reachable with a proof already+ // cached from a readable-snapshot pass, so the proof is seeded by a real+ // configure round rather than reached into.+ const harness = makeHarness(readyBootstrapBody(MINTED))++ expect(await harness.reconcile({ codexBinding: MINTED })).toBe('ready')+ expect(harness.configure).toHaveBeenCalledTimes(1)+ expect(harness.provisioner.getBootstrapProof(RECIPE)).toMatchObject({+ contractVersion: 3,+ podUid: 'pod-uid-1',+ policyReady: true,+ codexBinding: MINTED,+ })++ // ConfigMap read fails on the next pass: the live host still holds the+ // binding this same pod was configured with, so the recipe stays ready and+ // WRC must NOT re-broker with a binding it can no longer justify.+ expect(await harness.reconcile({ codexSnapshotUnavailable: true })).toBe('ready')+ expect(harness.configure).toHaveBeenCalledTimes(1)+ })++ it('discards a cached proof whose pod was replaced instead of reporting ready', async () => {+ // N-06: the proof is the pod's, not the recipe's. A replacement pod has+ // never been configured, so a snapshot outage must not let its predecessor's+ // proof stand in for it.+ const harness = makeHarness(readyBootstrapBody(MINTED))+ expect(await harness.reconcile({ codexBinding: MINTED })).toBe('ready')++ harness.setPodUid('pod-uid-2')+ // Both spies carry the seeding round's call; clear so the assertions below+ // speak only about the pass that saw the replaced pod.+ harness.configure.mockClear()+ harness.signWrcConfigureToken.mockClear()++ expect(await harness.reconcile({ codexSnapshotUnavailable: true })).toBe('awaiting_policy')+ expect(harness.provisioner.getBootstrapProof(RECIPE)).toBeUndefined()+ expect(harness.configure).not.toHaveBeenCalled()+ expect(harness.signWrcConfigureToken).not.toHaveBeenCalled()+ })++ it('rejects a bootstrap that echoes a Codex binding other than the minted one', async () => {+ // N-14: a host answering with a different policy than the one WRC minted is+ // a broken host, not a pending policy. Three consecutive rounds exhaust the+ // configure budget and surface provider_unavailable.+ const harness = makeHarness(+ readyBootstrapBody(codexBinding({ credentialRevision: 99, connectionKey: 'team-plus' }))+ )++ expect(await harness.reconcile({ codexBinding: MINTED })).toBe('deploying')+ expect(harness.provisioner.getBootstrapProof(RECIPE)).toBeUndefined()+ expect(await harness.reconcile({ codexBinding: MINTED })).toBe('deploying')+ expect(await harness.reconcile({ codexBinding: MINTED })).toBe('provider_unavailable')+ expect(harness.configure).toHaveBeenCalledTimes(3)+ })++ it('rejects a bootstrap that drops the binding while WRC minted one', async () => {+ // Same defect from the other side: the host reports binding_missing for a+ // binding WRC did send. Accepting it would leave the recipe reporting a+ // pending policy forever while the real fault is the host.+ const harness = makeHarness({+ status: 202,+ body: {+ configured: true,+ ready: true,+ provider: 'codex-subscription',+ model: MODEL,+ contractVersion: 3,+ policyState: 'binding_missing',+ policyReason: 'codex_execution_binding_missing',+ },+ })++ expect(await harness.reconcile({ codexBinding: MINTED })).toBe('deploying')+ expect(harness.provisioner.getBootstrapProof(RECIPE)).toBeUndefined()+ })++ it('accepts binding_missing as awaiting_policy when the grant really was revoked', async () => {+ // The revocation path must keep working: with a readable ConfigMap that+ // denies the grant, WRC configures WITHOUT a binding, the host clears its+ // own, and the recipe reports awaiting_policy — not a configure failure.+ const harness = makeHarness({+ status: 202,+ body: {+ configured: true,+ ready: true,+ provider: 'codex-subscription',+ model: MODEL,+ contractVersion: 3,+ policyState: 'binding_missing',+ policyReason: 'codex_execution_binding_missing',+ },+ })++ expect(await harness.reconcile({ codexBinding: null, codexSnapshotUnavailable: false })).toBe(+ 'awaiting_policy'+ )+ expect(harness.configure).toHaveBeenCalledWith(+ 'codex-subscription',+ MODEL,+ expect.any(String),+ 'configure-token',+ 'promptBridge',+ null+ )+ expect(harness.provisioner.getBootstrapProof(RECIPE)).toMatchObject({+ policyReady: false,+ policyReason: 'codex_execution_binding_missing',+ })+ })++ it('reports a pre-v3 mcp-host as a stale contract, not as an unavailable provider', async () => {+ // A host on an old image answers the Codex bootstrap with a v2 identity.+ // Charging that to the configure budget renders as "the configured provider+ // is unavailable" and sends the operator hunting a broker outage; the real+ // fix is an image bump.+ const harness = makeHarness({+ status: 502,+ body: {+ error: 'mcp_host bootstrap identity is not Plugin Workload SDK v3',+ policyReason: 'codex_bootstrap_contract_stale',+ },+ })++ for (let round = 0; round < 4; round += 1) {+ expect(await harness.reconcile({ codexBinding: MINTED })).toBe('awaiting_policy')+ }+ expect(harness.provisioner.getBootstrapProof(RECIPE)).toMatchObject({+ contractVersion: 2,+ provider: 'codex-subscription',+ policyReady: false,+ policyReason: 'codex_bootstrap_contract_stale',+ })+ })++ it('never lets a cached stale-contract proof answer ready when the snapshot goes unavailable', async () => {+ // The stale-contract arm caches a proof so the CR can name the reason. That+ // proof then sits in exactly the slot the snapshot-outage early-return reads+ // to answer 'ready'. If it ever satisfied that check, a recipe on a pre-v3+ // image would report Validated the moment the ConfigMap blinked — issue+ // #533 with extra steps. Two independent fields keep it out (policyReady is+ // false AND contractVersion is not 3); this pins the outcome, not the path.+ const harness = makeHarness({+ status: 502,+ body: {+ error: 'mcp_host bootstrap identity is not Plugin Workload SDK v3',+ policyReason: 'codex_bootstrap_contract_stale',+ },+ })++ expect(await harness.reconcile({ codexBinding: MINTED })).toBe('awaiting_policy')+ expect(harness.provisioner.getBootstrapProof(RECIPE)).toMatchObject({ contractVersion: 2 })++ harness.configure.mockClear()+ expect(await harness.reconcile({ codexSnapshotUnavailable: true })).toBe('awaiting_policy')+ // The early-return short-circuits before configure either way, so the+ // status above is the whole assertion: 'ready' would be the regression.+ expect(harness.configure).not.toHaveBeenCalled()+ })++ it('still charges an ordinary bootstrap error to the configure budget', async () => {+ // Guard for the branch above: only the tagged stale-contract answer is+ // exempt. A plain 502 must keep converging on provider_unavailable.+ const harness = makeHarness({ status: 502, body: { error: 'mcp_host bootstrap failed' } })++ expect(await harness.reconcile({ codexBinding: MINTED })).toBe('deploying')+ expect(await harness.reconcile({ codexBinding: MINTED })).toBe('deploying')+ expect(await harness.reconcile({ codexBinding: MINTED })).toBe('provider_unavailable')+ })++ it('rejects a bootstrap whose binding is minted for a different model', async () => {+ // The echoed binding is well-formed and self-consistent, just not ours.+ // Without pinning the model, the five-field hash would verify and the proof+ // would be accepted for a model this host was never bootstrapped with.+ const harness = makeHarness(readyBootstrapBody(codexBinding({ model: 'gpt-5.1' })))++ expect(await harness.reconcile({ codexBinding: MINTED })).toBe('deploying')+ expect(harness.provisioner.getBootstrapProof(RECIPE)).toBeUndefined()+ })+})diff --git a/workflow-recipes/src/workflow/pluginWorkloadSdkProvisioner.ts b/workflow-recipes/src/workflow/pluginWorkloadSdkProvisioner.tsindex 803cb60af..f13816e2e 100644--- a/workflow-recipes/src/workflow/pluginWorkloadSdkProvisioner.ts+++ b/workflow-recipes/src/workflow/pluginWorkloadSdkProvisioner.ts@@ -136,13 +136,6 @@ export type PluginWorkloadSdkProvisionerDeps = {ensureMcpHostHeadlessService: (recipeName: string) => Promise<void>createIfNotExists: (createFn: () => Promise<unknown>, label: string) => Promise<boolean>safeDelete: (deleteFn: () => Promise<unknown>) => Promise<void>- resolveCodexBinding?: (input: {- provider: string- model: string- recipeName: string- recipeUid: string- runtimeScopeRecipeName: string- }) => PluginWorkloadSdkCodexBindingProof | null}/**@@ -399,6 +392,17 @@ export class PluginWorkloadSdkProvisioner {mcpHostAgent?.provider === 'codex-subscription') {const existing = this.eagerSdkBootstrapProofByRecipe.get(recipeName)+ if (existing && existing.podUid !== readiness.uid) {+ // Proof of a pod that has since been replaced. The new pod has never+ // been configured, so its cached predecessor's proof must not be read+ // as "this host already holds a Codex binding".+ log.info('Plugin Workload SDK bootstrap proof belongs to a replaced pod; discarding', {+ proofPodUid: existing.podUid,+ podUid: readiness.uid,+ })+ this.eagerSdkBootstrapProofByRecipe.delete(recipeName)+ return 'awaiting_policy'+ }if (!existing ||existing.policyReady === false ||@@ -410,17 +414,10 @@ export class PluginWorkloadSdkProvisioner {}return 'ready'}- const resolvedCodexBinding =- opts.codexBinding ??- (mcpHostAgent- ? (this.deps.resolveCodexBinding?.({- provider: mcpHostAgent.provider,- model: mcpHostAgent.model,- recipeName,- recipeUid,- runtimeScopeRecipeName,- }) ?? null)- : null)+ // The caller derives the binding from the same allowlist view it used for+ // `codexSnapshotUnavailable`; the provisioner never re-reads that state+ // after its own awaits (see the reconciler's `codexView`).+ const resolvedCodexBinding = opts.codexBinding ?? nullconst capabilityFamily = promptBridge ? 'promptBridge' : 'clientNotifications'const configureKey = `${readiness.uid}:${capabilityFamily}:${mcpHostAgent?.provider ?? 'none'}:${mcpHostAgent?.model ?? 'none'}:${resolvedCodexBinding?.bindingHash ?? 'none'}`try {@@ -447,13 +444,41 @@ export class PluginWorkloadSdkProvisioner {'clientNotifications')if (result.status >= 400) {+ // A pre-v3 mcp-host image answers the Codex bootstrap with a v2+ // identity, which the broker rejects. That is a stale workload image,+ // not a broker outage: charging it to the configure budget renders as+ // "the configured provider is unavailable" and sends the operator+ // looking for a credential problem. Record the stale contract as the+ // pending policy reason instead.+ if (+ promptBridge &&+ mcpHostAgent?.provider === 'codex-subscription' &&+ result.body?.policyReason === 'codex_bootstrap_contract_stale'+ ) {+ log.warn(+ 'Plugin Workload SDK eager mcp-host answered the Codex bootstrap with a pre-v3 contract',+ { status: result.status, podUid: readiness.uid }+ )+ this.eagerSdkBootstrapProofByRecipe.set(recipeName, {+ ready: true,+ contractVersion: 2,+ podUid: readiness.uid,+ provider: mcpHostAgent.provider,+ model: mcpHostAgent.model,+ policyReady: false,+ policyState: 'contract_stale',+ policyReason: 'codex_bootstrap_contract_stale',+ verifiedAt: new Date().toISOString(),+ })+ return 'awaiting_policy'+ }this.eagerSdkBootstrapProofByRecipe.delete(recipeName)return this.recordEagerConfigureFailure(recipeName, configureKey, log, {reason: 'Plugin Workload SDK eager mcp-host bootstrap returned an error',detail: { status: result.status },})}- const proof = parseEagerSdkBootstrapProof(result.body, readiness.uid)+ const proof = parseEagerSdkBootstrapProof(result.body, readiness.uid, mcpHostAgent?.model)if (!proof) {this.eagerSdkBootstrapProofByRecipe.delete(recipeName)return this.recordEagerConfigureFailure(recipeName, configureKey, log, {@@ -461,6 +486,34 @@ export class PluginWorkloadSdkProvisioner {detail: { status: result.status },})}+ // The host must echo back exactly the binding WRC minted. A different+ // binding is a broken host (or a mixed-up pod), not a pending policy:+ // accepting it would let the recipe execute under a policy WRC never+ // authorized. The hash covers all five binding fields.+ //+ // ORDER IS LOAD-BEARING: this check must stay BELOW the stale-contract+ // arm in the `status >= 400` branch above. A pre-v3 host answers with no+ // codexBinding at all, so against a non-null minted binding it compares+ // `null !== <hash>` and would be charged here as a mismatched echo —+ // converging on `provider_unavailable` and burying the stale-image reason+ // under the very symptom that arm exists to replace. Moving this earlier+ // silently reopens that.+ if (+ promptBridge &&+ mcpHostAgent?.provider === 'codex-subscription' &&+ (proof.codexBinding?.bindingHash ?? null) !== (resolvedCodexBinding?.bindingHash ?? null)+ ) {+ this.eagerSdkBootstrapProofByRecipe.delete(recipeName)+ return this.recordEagerConfigureFailure(recipeName, configureKey, log, {+ reason:+ 'Plugin Workload SDK bootstrap echoed a Codex binding that does not match the minted binding',+ detail: {+ status: result.status,+ mintedBindingHash: resolvedCodexBinding?.bindingHash ?? null,+ echoedBindingHash: proof.codexBinding?.bindingHash ?? null,+ },+ })+ }this.eagerSdkBootstrapProofByRecipe.set(recipeName, proof)this.eagerSdkConfigureFailuresByRecipe.delete(recipeName)if (promptBridge && proof.policyReady === false) {@@ -639,7 +692,9 @@ export class PluginWorkloadSdkProvisioner {function parseEagerSdkBootstrapProof(body: Record<string, unknown>,- podUid: string+ podUid: string,+ /** Agent model WRC bootstrapped; a binding for another model is not ours. */+ expectedModel?: string): EagerSdkBootstrapProof | null {if (body.capabilityFamily === 'clientNotifications') {if (@@ -678,7 +733,7 @@ function parseEagerSdkBootstrapProof(if (body.provider === 'codex-subscription' && body.contractVersion !== 3) {return null}- const codexBinding = parseCodexBindingProof(body.codexBinding)+ const codexBinding = parseCodexBindingProof(body.codexBinding, expectedModel)if (body.provider === 'codex-subscription' &&body.policyReason === 'codex_execution_binding_missing'@@ -744,6 +799,9 @@ function parseEagerSdkBootstrapProof(}}-function parseCodexBindingProof(value: unknown): PluginWorkloadSdkCodexBindingProof | undefined {- return readVerifiedSdkOnlyCodexBinding(value) ?? undefined+function parseCodexBindingProof(+ value: unknown,+ expectedModel?: string+): PluginWorkloadSdkCodexBindingProof | undefined {+ return readVerifiedSdkOnlyCodexBinding(value, expectedModel) ?? undefined}diff --git a/workflow-recipes/src/workflow/sdkOnlyCodexBinding.test.ts b/workflow-recipes/src/workflow/sdkOnlyCodexBinding.test.tsindex 2c834ba76..a71e47a39 100644--- a/workflow-recipes/src/workflow/sdkOnlyCodexBinding.test.ts+++ b/workflow-recipes/src/workflow/sdkOnlyCodexBinding.test.ts@@ -1,4 +1,4 @@-import { describe, expect, it } from 'vitest'+import { describe, expect, it, vi } from 'vitest'import { computeCodexPolicyHash } from '@clerum/llm-provider-attempt-contract'import {deriveSdkOnlyCodexBinding,@@ -7,55 +7,179 @@ import {verifySdkOnlyCodexBindingHash,} from './sdkOnlyCodexBinding'+const MODEL = 'gpt-5.6-luna'+const HASH = computeCodexPolicyHash({- model: 'gpt-5.6-luna',+ model: MODEL,catalogRevision: 3,credentialRevision: 1,connectionKey: 'team-plus',})+/**+ * An executable allowlist ConfigMap in the legacy (map-less) shape: the Codex+ * flag is on, the connection is `connected`, and the catalog actually lists the+ * model. Every one of those is load-bearing — the binding gate is the same+ * cascade that derives `llm:codex:execute`, so dropping any of them must drop+ * the binding too.+ */+function eligibleLegacyConfigMap(overrides?: {+ annotations?: Record<string, string>+ stale?: boolean+ models?: string[]+}) {+ const models = overrides?.models ?? [MODEL]+ return {+ metadata: {+ annotations: {+ 'clerum.io/catalog-revision': '3',+ 'clerum.io/connection-revision': '1',+ 'clerum.io/codex-connection-status': 'connected',+ 'clerum.io/codex-enabled': 'true',+ ...overrides?.annotations,+ },+ },+ data: {+ 'codex-subscription': JSON.stringify(+ models.map(model => ({ model, stale: overrides?.stale === true }))+ ),+ },+ }+}++/** The same grant expressed through the per-connection map. */+function eligibleMappedConfigMap(overrides?: {+ status?: string+ models?: string[]+ catalogModels?: string[]+}) {+ return {+ metadata: {+ annotations: {+ 'clerum.io/catalog-revision': '9',+ 'clerum.io/connection-revision': '9',+ 'clerum.io/codex-enabled': 'true',+ 'clerum.io/codex-connections': JSON.stringify({+ 'team-plus': {+ status: overrides?.status ?? 'connected',+ catalogRevision: 3,+ connectionRevision: 1,+ models: overrides?.models ?? [MODEL],+ },+ }),+ },+ },+ data: {+ 'codex-subscription': JSON.stringify(+ (overrides?.catalogModels ?? [MODEL]).map(model => ({ model, stale: false }))+ ),+ },+ }+}+describe('deriveSdkOnlyCodexBinding', () => {it('returns a hashed v3 proof for an assigned executable catalog', () => {const binding = deriveSdkOnlyCodexBinding({provider: 'codex-subscription',- model: 'gpt-5.6-luna',+ model: MODEL,connectionKey: 'team-plus',- configMap: {- metadata: {- annotations: {- 'clerum.io/catalog-revision': '3',- 'clerum.io/connection-revision': '1',- },- },- },+ configMap: eligibleLegacyConfigMap(),})expect(binding).toEqual({connectionKey: 'team-plus',catalogRevision: 3,credentialRevision: 1,- model: 'gpt-5.6-luna',+ model: MODEL,bindingHash: HASH,})expect(verifySdkOnlyCodexBindingHash(binding!)).toBe(true)expect(isPluginWorkloadSdkCodexBindingProof(binding)).toBe(true)})+ it('prefers the assigned connection revisions over the global annotations', () => {+ expect(+ deriveSdkOnlyCodexBinding({+ provider: 'codex-subscription',+ model: MODEL,+ connectionKey: 'team-plus',+ configMap: eligibleMappedConfigMap(),+ })+ ).toEqual({+ connectionKey: 'team-plus',+ catalogRevision: 3,+ credentialRevision: 1,+ model: MODEL,+ bindingHash: HASH,+ })+ })+it('returns null when the assigned catalog excludes the requested model', () => {expect(deriveSdkOnlyCodexBinding({provider: 'codex-subscription',- model: 'gpt-5.6-luna',+ model: MODEL,+ connectionKey: 'team-plus',+ configMap: eligibleMappedConfigMap({ models: ['gpt-5.1'], catalogModels: ['gpt-5.1'] }),+ })+ ).toBeNull()+ })++ it('returns null when the connection is not connected', () => {+ // The revocation path: revisions and catalog are intact, only the status+ // degraded. Reading revisions structurally (the Host-chat `toPolicyBinding`+ // contract) would still mint here — the execution gate must not.+ for (const status of ['reauth-required', 'unavailable', 'revoked', 'disconnected']) {+ expect(+ deriveSdkOnlyCodexBinding({+ provider: 'codex-subscription',+ model: MODEL,+ connectionKey: 'team-plus',+ configMap: eligibleLegacyConfigMap({+ annotations: { 'clerum.io/codex-connection-status': status },+ }),+ })+ ).toBeNull()+ }+ })++ it('returns null when the Codex feature flag is off', () => {+ expect(+ deriveSdkOnlyCodexBinding({+ provider: 'codex-subscription',+ model: MODEL,+ connectionKey: 'team-plus',+ configMap: eligibleLegacyConfigMap({+ annotations: { 'clerum.io/codex-enabled': 'false' },+ }),+ })+ ).toBeNull()+ })++ it('returns null when the catalog row is stale', () => {+ expect(+ deriveSdkOnlyCodexBinding({+ provider: 'codex-subscription',+ model: MODEL,+ connectionKey: 'team-plus',+ configMap: eligibleLegacyConfigMap({ stale: true }),+ })+ ).toBeNull()+ })++ it('returns null for a revisions-only ConfigMap that lists no catalog', () => {+ // Divergence #5: a legacy ConfigMap carrying nothing but revision+ // annotations used to mint a live execution binding while the reconciler+ // withheld `llm:codex:execute` for the very same ConfigMap.+ expect(+ deriveSdkOnlyCodexBinding({+ provider: 'codex-subscription',+ model: MODEL,connectionKey: 'team-plus',configMap: {metadata: {annotations: {- 'clerum.io/codex-connections': JSON.stringify({- 'team-plus': {- models: ['gpt-5.1'],- catalogRevision: 3,- connectionRevision: 1,- },- }),+ 'clerum.io/catalog-revision': '3',+ 'clerum.io/connection-revision': '1',},},},@@ -63,31 +187,59 @@ describe('deriveSdkOnlyCodexBinding', () => {).toBeNull()})+ it('returns null when the ConfigMap could not be read', () => {+ expect(+ deriveSdkOnlyCodexBinding({+ provider: 'codex-subscription',+ model: MODEL,+ connectionKey: 'team-plus',+ configMap: undefined,+ })+ ).toBeNull()+ })+it('returns null for non-Codex providers and unassigned grants', () => {expect(deriveSdkOnlyCodexBinding({provider: 'openai',model: 'gpt-5.4-mini',connectionKey: 'team-plus',- configMap: undefined,+ configMap: eligibleLegacyConfigMap({ models: ['gpt-5.4-mini'] }),})).toBeNull()expect(deriveSdkOnlyCodexBinding({provider: 'codex-subscription',- model: 'gpt-5.6-luna',+ model: MODEL,connectionKey: 'unassigned',- configMap: undefined,+ configMap: eligibleLegacyConfigMap(),})).toBeNull()})+ it('logs the withholding reason so an operator sees why the binding vanished', () => {+ const debug = vi.fn()+ deriveSdkOnlyCodexBinding({+ provider: 'codex-subscription',+ model: MODEL,+ connectionKey: 'team-plus',+ configMap: eligibleLegacyConfigMap({+ annotations: { 'clerum.io/codex-connection-status': 'reauth-required' },+ }),+ log: { debug },+ })+ expect(debug).toHaveBeenCalledWith(+ 'Codex execution binding withheld',+ expect.objectContaining({ reason: 'connection_reauth-required', eligibility: 'ineligible' })+ )+ })+it('rebuilds a five-field proof and drops extra keys', () => {const proof = {connectionKey: 'team-plus',catalogRevision: 3,credentialRevision: 1,- model: 'gpt-5.6-luna',+ model: MODEL,bindingHash: HASH,extra: true,}@@ -95,8 +247,20 @@ describe('deriveSdkOnlyCodexBinding', () => {connectionKey: 'team-plus',catalogRevision: 3,credentialRevision: 1,- model: 'gpt-5.6-luna',+ model: MODEL,bindingHash: HASH,})})++ it('rejects a well-formed proof minted for another model', () => {+ const proof = {+ connectionKey: 'team-plus',+ catalogRevision: 3,+ credentialRevision: 1,+ model: MODEL,+ bindingHash: HASH,+ }+ expect(readVerifiedSdkOnlyCodexBinding(proof, 'gpt-5.1')).toBeNull()+ expect(readVerifiedSdkOnlyCodexBinding(proof, MODEL)).toEqual(proof)+ })})diff --git a/workflow-recipes/src/workflow/sdkOnlyCodexBinding.ts b/workflow-recipes/src/workflow/sdkOnlyCodexBinding.tsindex 6187c65f9..4b0cce4ab 100644--- a/workflow-recipes/src/workflow/sdkOnlyCodexBinding.ts+++ b/workflow-recipes/src/workflow/sdkOnlyCodexBinding.ts@@ -2,7 +2,7 @@ import {CODEX_PROVIDER,CODEX_UNASSIGNED_CONNECTION_KEY,type CodexConfigMapView,- toPolicyBinding,+ toEligiblePolicyBinding,} from '@clerum/codex-catalog-projection'import { computeCodexPolicyHash } from '@clerum/llm-provider-attempt-contract'@@ -78,41 +78,46 @@ export function readVerifiedSdkOnlyCodexBinding(/*** Derive the sanitized v3 Codex execution proof from one WRC snapshot.- * Returns null when the grant is unassigned, the catalog is not executable,- * or the selected model is not in the assigned connection's model list.+ *+ * Eligibility is decided by `toEligiblePolicyBinding`, the same cascade that+ * derives `llm:codex:execute`, so a recipe can never be handed an execution+ * binding for a grant whose scope the reconciler withholds (and vice versa).+ * Returns null when the grant is unassigned, the Codex flag is off, the+ * connection is not `connected`, the catalog is stale, or the selected model+ * is not in the assigned connection's catalog.*/export function deriveSdkOnlyCodexBinding(input: {provider: stringmodel: stringconnectionKey: string | undefinedconfigMap: CodexConfigMapView | undefined+ log?: { debug(msg: string, fields?: Record<string, unknown>): void }}): PluginWorkloadSdkCodexBindingProof | null {if (input.provider !== CODEX_PROVIDER) return null- const policy = toPolicyBinding(input.configMap, input.connectionKey)- if (- !policy ||- !policy.connectionKey ||- policy.connectionKey === CODEX_UNASSIGNED_CONNECTION_KEY ||- !Number.isInteger(policy.catalogRevision) ||- policy.catalogRevision < 1 ||- !Number.isInteger(policy.credentialRevision) ||- policy.credentialRevision < 0- ) {- return null- }- if (Array.isArray(policy.models) && !policy.models.includes(input.model)) {+ const { binding, eligibility, reason } = toEligiblePolicyBinding(+ input.configMap,+ input.connectionKey,+ input.model+ )+ if (!binding || binding.catalogRevision < 1 || binding.credentialRevision < 0) {+ input.log?.debug('Codex execution binding withheld', {+ model: input.model,+ connectionKey: input.connectionKey ?? CODEX_UNASSIGNED_CONNECTION_KEY,+ eligibility,+ reason: binding ? 'revision_out_of_range' : reason,+ })return null}return {- connectionKey: policy.connectionKey,- catalogRevision: policy.catalogRevision,- credentialRevision: policy.credentialRevision,- model: input.model,+ connectionKey: binding.connectionKey,+ catalogRevision: binding.catalogRevision,+ credentialRevision: binding.credentialRevision,+ model: binding.model,bindingHash: computeCodexPolicyHash({- model: input.model,- catalogRevision: policy.catalogRevision,- credentialRevision: policy.credentialRevision,- connectionKey: policy.connectionKey,+ model: binding.model,+ catalogRevision: binding.catalogRevision,+ credentialRevision: binding.credentialRevision,+ connectionKey: binding.connectionKey,}),}}diff --git a/workflow-recipes/src/workflow/workflowReconciler.codexUncertainScope.test.ts b/workflow-recipes/src/workflow/workflowReconciler.codexUncertainScope.test.tsnew file mode 100644index 000000000..0d05f660e--- /dev/null+++ b/workflow-recipes/src/workflow/workflowReconciler.codexUncertainScope.test.ts@@ -0,0 +1,457 @@+import { beforeEach, describe, expect, it, vi } from 'vitest'+import { computeCodexPolicyHash } from '@clerum/llm-provider-attempt-contract'+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: 'none',+ message: 'healthy',+ newPhase: 'running',+ newAttempt: 0,+ }),+ 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 RECIPE = 'codex-recipe'+const MODEL = 'gpt-5.3-codex'+const GRANT = 'team-plus'+const CODEX_SCOPE = 'llm:codex:execute'++const EXPECTED_BINDING_HASH = computeCodexPolicyHash({+ model: MODEL,+ catalogRevision: 1,+ credentialRevision: 1,+ connectionKey: GRANT,+})++function unsignedRuntimeJwt(payload: Record<string, unknown>): string {+ return `eyJhbGciOiJub25lIn0.${Buffer.from(JSON.stringify(payload)).toString('base64url')}.x`+}++function codexConfigMap(status = 'connected') {+ 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': status,+ 'clerum.io/codex-enabled': 'true',+ },+ },+ data: { 'codex-subscription': JSON.stringify([{ model: MODEL, stale: false }]) },+ }+}++/**+ * A live runtime-token Secret whose JWTs already carry the Codex scope and are+ * far from expiry, so nothing but a scope decision can trigger a remint.+ */+function liveSecretWith(scopes: string[], recipeName = RECIPE) {+ const binding = {+ exp: Math.floor(Date.now() / 1000) + 3600,+ recipeNamespace: sandboxNamespace,+ recipeName,+ hostRefs: [`${sandboxNamespace}/${recipeName}`],+ workflowControlScopes: scopes,+ scopes: [...scopes, 'gfs.read'],+ }+ const jwt = Buffer.from(unsignedRuntimeJwt(binding)).toString('base64')+ return {+ data: {+ 'mcp-host-runtime-access-token': jwt,+ 'mcp-host-runtime-refresh-token': jwt,+ 'mcp-host-workflow-control-token': jwt,+ 'mcp-host-gfs-token': Buffer.from(+ unsignedRuntimeJwt({+ ...binding,+ sub: `host:3rd:${sandboxNamespace}/${recipeName}`,+ scopes: ['gfs.read'],+ })+ ).toString('base64'),+ },+ }+}++function codexSdkSpec(overrides: Partial<WorkflowRecipeSpec> = {}): WorkflowRecipeSpec {+ return {+ agent: { provider: 'codex-subscription', model: MODEL },+ steps: [{ id: 'brief', instruction: 'write the brief' }],+ workloads: [{ id: 'sdk-caller', type: 'deployment', image: 'caller:test' }],+ pluginWorkloadSdk: { promptBridge: {}, allowedCallers: ['sdk-caller'] },+ ...overrides,+ } as unknown as WorkflowRecipeSpec+}++function createHarness() {+ const coreApi = {+ readNamespacedPod: vi.fn().mockResolvedValue({}),+ readNamespacedSecret: vi.fn().mockRejectedValue({ code: 404 }),+ readNamespacedService: vi.fn().mockRejectedValue({ code: 404 }),+ readNamespacedEndpoints: vi.fn().mockRejectedValue({ code: 404 }),+ readNamespacedConfigMap: vi.fn().mockResolvedValue(codexConfigMap()),+ createNamespacedSecret: vi.fn().mockResolvedValue({}),+ replaceNamespacedSecret: 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({}),+ deleteNamespacedPod: 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 networkingApi = {+ createNamespacedNetworkPolicy: vi.fn().mockResolvedValue({}),+ readNamespacedNetworkPolicy: vi.fn().mockRejectedValue({ code: 404 }),+ replaceNamespacedNetworkPolicy: vi.fn().mockResolvedValue({}),+ deleteNamespacedNetworkPolicy: vi.fn().mockResolvedValue({}),+ listNamespacedNetworkPolicy: vi.fn().mockResolvedValue({ items: [] }),+ }+ const customApi = {+ patchNamespacedCustomObject: vi.fn().mockResolvedValue({}),+ patchNamespacedCustomObjectStatus: vi.fn().mockResolvedValue({}),+ }+ const configure = vi.fn().mockResolvedValue({+ status: 202,+ body: {+ configured: true,+ ready: true,+ provider: 'codex-subscription',+ model: MODEL,+ contractVersion: 3,+ policyReady: true,+ policyState: 'active',+ policyRevision: 1,+ policyHash: 'a'.repeat(64),+ defaultTargetRef: 'primary-codex',+ defaultProvider: 'codex-subscription',+ defaultModel: MODEL,+ codexBinding: {+ connectionKey: GRANT,+ catalogRevision: 1,+ credentialRevision: 1,+ model: MODEL,+ bindingHash: EXPECTED_BINDING_HASH,+ },+ },+ })+ const deps = {+ coreApi,+ customApi,+ networkingApi,+ 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,+ pluginWorkloadSdkEnabled: true,+ },+ tokenFactory: {+ signWrcConfigureToken: vi.fn().mockResolvedValue('wrc-configure-token'),+ signWrcArtifactDeleteToken: vi.fn().mockResolvedValue('stub-token'),+ signCoordinatorToMcpHostToken: vi.fn().mockResolvedValue('coordinator-mcp-host-token'),+ signCoordinatorToWrcToken: vi.fn().mockResolvedValue('coordinator-wrc-token'),+ signCustomCoordinatorToWrcToken: vi.fn().mockResolvedValue('custom-coordinator-wrc-token'),+ },+ modelConfigHandler: { configurePluginWorkloadSdkBootstrap: configure },+ pluginWorkloadSdkRevocationClient: {+ revoke: vi.fn().mockResolvedValue({ state: 'missing', revoked: 0, fencedInvocations: 0 }),+ finalize: vi.fn(),+ },+ } as unknown as WorkflowReconcilerDeps++ const reconciler = new WorkflowReconciler(deps)+ return { reconciler, coreApi, networkingApi, configure }+}++function bindGrant(reconciler: WorkflowReconciler, recipeName = RECIPE, connectionKey = GRANT) {+ reconciler.setCodexReconcileContext({+ recipeUid: `uid-${recipeName}`,+ recipeName,+ runtimeScopeRecipeName: recipeName,+ claimedParent: false,+ parentSpec: null,+ connectionKey,+ })+}++function reconcileRecipe(+ reconciler: WorkflowReconciler,+ spec: WorkflowRecipeSpec,+ recipeName = RECIPE+) {+ return reconciler.reconcile(+ recipeName,+ `uid-${recipeName}`,+ sandboxNamespace,+ spec,+ { workflowExecution: { phase: 'initializing' } },+ undefined,+ recipeName,+ undefined+ )+}++function issuedScopes(): string[] {+ const last = runtimeTokenIssuerMocks.issueMcpHostRuntimeTokens.mock.calls.at(-1)+ return (last?.[2] ?? []) as string[]+}++/**+ * The eager mcp-host Pod body WRC actually built, or undefined if the reconcile+ * never got that far. Every test below asserts on it before its own subject:+ * a reconcile that dies early satisfies "did not remint" and "did not roll"+ * for entirely the wrong reason.+ */+function builtMcpHostPodFrom(coreApi: {+ createNamespacedPod: { mock: { calls: Array<[{ body?: { metadata?: { name?: string } } }]> } }+}) {+ return coreApi.createNamespacedPod.mock.calls+ .map(call => call[0]?.body)+ .find(body => body?.metadata?.name === `${RECIPE}-mcp-host`)+}++describe('Codex scope under an undecidable catalog', () => {+ beforeEach(() => {+ vi.clearAllMocks()+ crashRecoveryMocks.getPodPhase.mockResolvedValue(undefined)+ crashRecoveryMocks.getPodReadiness.mockResolvedValue({+ ready: true,+ phase: 'Running',+ uid: 'pod-uid-1',+ })+ crashRecoveryMocks.isRecoverableContainerWaitingReason.mockReturnValue(false)+ runtimeTokenIssuerMocks.issueMcpHostRuntimeTokens.mockResolvedValue({+ accessToken: 'runtime-access-token',+ refreshToken: 'runtime-refresh-token',+ mcpHostControlToken: 'mcp-host-control-token',+ })+ vi.stubGlobal(+ 'fetch',+ vi.fn().mockResolvedValue({ ok: true, status: 204 } as unknown as Response)+ )+ })++ it('does not remint or roll when the allowlist read fails and the JWT already holds the scope', async () => {+ // N-04. An unreadable ConfigMap yields an empty derivedScopes, which is+ // indistinguishable from a revocation. Treating it as one remints with+ // reason 'scope', which rolls the eager pod and drops its bootstrap proof —+ // then rolls it a SECOND time when the ConfigMap comes back. No policy+ // changed, so nothing may change.+ const { reconciler, coreApi } = createHarness()+ bindGrant(reconciler)+ coreApi.readNamespacedSecret.mockResolvedValue(+ liveSecretWith(['plugin-workload-sdk', CODEX_SCOPE])+ )+ coreApi.readNamespacedConfigMap.mockRejectedValue(+ Object.assign(new Error('Kubernetes request timed out'), { code: 'ETIMEDOUT' })+ )++ await reconcileRecipe(reconciler, codexSdkSpec())++ // Positive evidence first: the reconcile really reached eager provisioning,+ // so the negative assertions below mean "chose not to", not "never got there".+ expect(builtMcpHostPodFrom(coreApi)).toBeDefined()+ expect(issueMcpHostRuntimeTokens).not.toHaveBeenCalled()+ expect(coreApi.patchNamespacedSecret).not.toHaveBeenCalled()+ expect(crashRecoveryMocks.deletePodIfExists).not.toHaveBeenCalledWith(+ expect.anything(),+ `${RECIPE}-mcp-host`,+ sandboxNamespace+ )+ })++ it('still withdraws the scope and rolls the pod when a readable catalog revokes the grant', async () => {+ // The other half of the same rule: `uncertain` preserves, but a decision+ // decides. If this ever stops rolling, N-04's fix has swallowed the+ // revocation path it was explicitly required not to mask.+ //+ // The steady-state pass in the middle is the control: it runs against the+ // very pod WRC built, so it drifts on nothing. A delete appearing only+ // after the grant is revoked can therefore only come from the scope remint.+ const { reconciler, coreApi } = createHarness()+ bindGrant(reconciler)+ coreApi.readNamespacedSecret.mockResolvedValue(+ liveSecretWith(['plugin-workload-sdk', CODEX_SCOPE])+ )++ await reconcileRecipe(reconciler, codexSdkSpec())+ const builtMcpHostPod = builtMcpHostPodFrom(coreApi)++ coreApi.readNamespacedPod.mockImplementation(async (params: { name?: string }) =>+ params.name === `${RECIPE}-mcp-host` ? builtMcpHostPod : {}+ )+ crashRecoveryMocks.getPodPhase.mockImplementation(async (_api: unknown, name: string) =>+ name === `${RECIPE}-mcp-host` ? 'Running' : undefined+ )++ // Control: the catalog still grants, the pod is the one WRC built.+ crashRecoveryMocks.deletePodIfExists.mockClear()+ await reconcileRecipe(reconciler, codexSdkSpec())+ expect(crashRecoveryMocks.deletePodIfExists).not.toHaveBeenCalledWith(+ expect.anything(),+ `${RECIPE}-mcp-host`,+ sandboxNamespace+ )++ // Revocation: readable ConfigMap, connection degraded.+ coreApi.readNamespacedConfigMap.mockResolvedValue(codexConfigMap('reauth-required'))+ runtimeTokenIssuerMocks.issueMcpHostRuntimeTokens.mockClear()+ coreApi.patchNamespacedSecret.mockClear()++ await reconcileRecipe(reconciler, codexSdkSpec())++ expect(issueMcpHostRuntimeTokens).toHaveBeenCalled()+ expect(issuedScopes()).not.toContain(CODEX_SCOPE)+ const patch = coreApi.patchNamespacedSecret.mock.calls.at(-1)?.[0] as {+ body?: { metadata?: { annotations?: Record<string, string> } }+ }+ expect(+ patch?.body?.metadata?.annotations?.['clerum.io/mcp-host-runtime-token-generation']+ ).toBe('1')+ expect(crashRecoveryMocks.deletePodIfExists).toHaveBeenCalledWith(+ expect.anything(),+ `${RECIPE}-mcp-host`,+ sandboxNamespace+ )+ })++ it('preserves only the Codex scope, never an unrelated one', async () => {+ // The preservation is surgical. A JWT carrying a workflow scope the spec no+ // longer declares must still be reminted while the catalog is unreadable.+ const { reconciler, coreApi } = createHarness()+ bindGrant(reconciler)+ coreApi.readNamespacedSecret.mockResolvedValue(+ liveSecretWith(['plugin-workload-sdk', 'workflow:list', CODEX_SCOPE])+ )+ coreApi.readNamespacedConfigMap.mockRejectedValue(+ Object.assign(new Error('forbidden'), { code: 403 })+ )++ await reconcileRecipe(reconciler, codexSdkSpec())++ expect(issueMcpHostRuntimeTokens).toHaveBeenCalled()+ expect(issuedScopes()).toContain(CODEX_SCOPE)+ expect(issuedScopes()).not.toContain('workflow:list')+ })++ it('mints without the Codex scope on the first mint under an unreadable catalog', async () => {+ // Nothing to preserve on a 404: fail closed. The scope arrives on the first+ // reconcile that can actually read the catalog.+ const { reconciler, coreApi } = createHarness()+ bindGrant(reconciler)+ coreApi.readNamespacedConfigMap.mockRejectedValue(+ Object.assign(new Error('Kubernetes request timed out'), { code: 'ETIMEDOUT' })+ )++ await reconcileRecipe(reconciler, codexSdkSpec())++ expect(issueMcpHostRuntimeTokens).toHaveBeenCalled()+ expect(issuedScopes()).not.toContain(CODEX_SCOPE)+ })+})++describe('Codex allowlist view across interleaved recipes', () => {+ beforeEach(() => {+ vi.clearAllMocks()+ crashRecoveryMocks.getPodPhase.mockResolvedValue(undefined)+ crashRecoveryMocks.getPodReadiness.mockResolvedValue({+ ready: true,+ phase: 'Running',+ uid: 'pod-uid-1',+ })+ crashRecoveryMocks.isRecoverableContainerWaitingReason.mockReturnValue(false)+ vi.stubGlobal(+ 'fetch',+ vi.fn().mockResolvedValue({ ok: true, status: 204 } as unknown as Response)+ )+ })++ it('configures with its OWN binding when another recipe wipes the shared view mid-reconcile', async () => {+ // N-08. Recipe B captured a readable catalog; while B is inside+ // ensureEagerSdkMcpHost, recipe A's refresh fails and clears the shared+ // state. Resolving the binding from that shared state after the awaits gave+ // B a null binding while `codexSnapshotUnavailable` still said false — a+ // binding-less v3 configure that wipes the live host binding. B must+ // configure from the view it captured, or not configure at all.+ const { reconciler, coreApi, configure } = createHarness()+ bindGrant(reconciler, RECIPE)+ bindGrant(reconciler, 'other-recipe', 'personal-pro')++ let interleaved = false+ coreApi.createNamespacedService.mockImplementation(async () => {+ if (!interleaved) {+ interleaved = true+ // Recipe A reconciles on the same controller and its ConfigMap read+ // fails, clearing the shared allowlist state under B's feet.+ coreApi.readNamespacedConfigMap.mockRejectedValue(+ Object.assign(new Error('Kubernetes request timed out'), { code: 'ETIMEDOUT' })+ )+ await reconciler.reconcilePluginWorkloadSdkOnly(+ 'other-recipe',+ 'uid-other-recipe',+ sandboxNamespace,+ codexSdkSpec({ steps: undefined }),+ 'other-recipe'+ )+ }+ return {}+ })++ await reconcileRecipe(reconciler, codexSdkSpec())++ expect(interleaved).toBe(true)+ const codexRecipeConfigure = configure.mock.calls.filter(call =>+ String(call[2]).includes(RECIPE)+ )+ expect(codexRecipeConfigure).toHaveLength(1)+ expect(codexRecipeConfigure[0][5]).toEqual({+ connectionKey: GRANT,+ catalogRevision: 1,+ credentialRevision: 1,+ model: MODEL,+ bindingHash: EXPECTED_BINDING_HASH,+ })+ })+})diff --git a/workflow-recipes/src/workflow/workflowReconciler.ts b/workflow-recipes/src/workflow/workflowReconciler.tsindex b3913ecff..ed5887c6e 100644--- a/workflow-recipes/src/workflow/workflowReconciler.ts+++ b/workflow-recipes/src/workflow/workflowReconciler.ts@@ -40,6 +40,7 @@ import type {} from '../types'import { resolveEagerSdkMcpHostAgent, resolveMcpHostAgent } from './agentResolution'import {+ CODEX_EXECUTE_SCOPE,type CodexCatalogSnapshot,projectRecipeCodexExecution,resolveCodexAuthoritativeSpec,@@ -897,16 +898,27 @@ export interface WorkflowReconcilerDeps {export class WorkflowReconciler {private readonly log = createLogger('wrc', 'reconciler')private readonly pluginWorkloadSdkProvisioner: PluginWorkloadSdkProvisioner- private codexSnapshot: CodexCatalogSnapshot = { flagEnabled: false }/**- * Raw allowlist ConfigMap from the last refresh, kept so each recipe's- * projection can re-parse it with that recipe's assigned grant key (HCC- * keeps the same shape for Hosts). Cleared on a failed read so grant- * decisions stay fail-closed. Do not send a binding-less v3 configure in- * that window — skip configure so mcp-host keeps a live binding.+ * The last allowlist refresh as ONE value. `configMap` is kept raw so each+ * recipe's projection can re-parse it with that recipe's assigned grant key+ * (HCC keeps the same shape for Hosts); `readOk` says whether the triple+ * comes from a successful read. They are a single field because they must be+ * read together: a `configMap` from one refresh combined with a `readOk`+ * from another is how a concurrently-reconciled recipe turns a failed read+ * into a binding-less v3 configure that wipes a live mcp-host binding.+ * Readers capture `this.codexView` once and use only that snapshot.+ *+ * Cleared on a failed read so grant decisions stay fail-closed. Do not send+ * a binding-less v3 configure in that window — skip configure so mcp-host+ * keeps a live binding. Symmetrically (see `resolveEffectiveControlScopes`),+ * an unreadable ConfigMap must not revoke the Codex scope either: with no+ * data there is no policy decision to apply in either direction.*/- private lastCodexConfigMap: k8s.V1ConfigMap | undefined- private lastCodexSnapshotReadOk = true+ private codexView: {+ configMap?: k8s.V1ConfigMap+ snapshot: CodexCatalogSnapshot+ readOk: boolean+ } = { snapshot: { flagEnabled: false }, readOk: true }private readonly codexContexts = new Map<string, CodexReconcileContext>()constructor(private readonly deps: WorkflowReconcilerDeps) {@@ -937,15 +949,6 @@ export class WorkflowReconciler {ensureMcpHostHeadlessService: recipeName => this.ensureMcpHostHeadlessService(recipeName),createIfNotExists: (createFn, label) => this.createIfNotExists(createFn, label),safeDelete: deleteFn => this.safeDelete(deleteFn),- resolveCodexBinding: ({ provider, model, recipeName, recipeUid, runtimeScopeRecipeName }) => {- const context = this.resolveCodexContext(recipeUid, recipeName, runtimeScopeRecipeName)- return deriveSdkOnlyCodexBinding({- provider,- model,- connectionKey: context.connectionKey,- configMap: this.lastCodexConfigMap,- })- },})}@@ -1003,65 +1006,79 @@ export class WorkflowReconciler {* Read failures keep the fail-closed error snapshot.*/private codexSnapshotFor(connectionKey: string): CodexCatalogSnapshot {- return snapshotForAssignedCodexGrant(connectionKey, this.lastCodexConfigMap, this.codexSnapshot)+ const view = this.codexView+ return snapshotForAssignedCodexGrant(connectionKey, view.configMap, view.snapshot)}+ /**+ * Effective control scopes plus whether the Codex decision rests on data.+ *+ * `codexScopeUncertain` is true when the projection could not decide —+ * an unreadable allowlist ConfigMap, or a spec whose Codex provenance could+ * not be established. In that state `derivedScopes` is empty, which is+ * indistinguishable from a real revocation; the token refresh uses the flag+ * to preserve whatever the live JWT already carries instead of reminting+ * (and rolling the pod) over a transient read failure. A readable ConfigMap+ * that says `reauth-required` is a decision, not uncertainty: it still+ * withdraws the scope.+ */private resolveEffectiveControlScopes(spec: WorkflowRecipeSpec,recipeUid: string,recipeName: string,runtimeScopeRecipeName: string- ): EffectiveWorkflowControlScope[] {+ ): { scopes: EffectiveWorkflowControlScope[]; codexScopeUncertain: boolean } {const workflow = deriveWorkflowControlScopes(spec, {pluginWorkloadSdkEnabled: this.deps.config.pluginWorkloadSdkEnabled,})- const derived = this.projectCodex(- spec,- recipeUid,- recipeName,- runtimeScopeRecipeName- ).derivedScopes.filter(scope => !workflow.includes(scope as WorkflowControlScope))- return [...workflow, ...derived] as EffectiveWorkflowControlScope[]+ const projection = this.projectCodex(spec, recipeUid, recipeName, runtimeScopeRecipeName)+ const derived = projection.derivedScopes.filter(+ scope => !workflow.includes(scope as WorkflowControlScope)+ )+ return {+ scopes: [...workflow, ...derived] as EffectiveWorkflowControlScope[],+ codexScopeUncertain: projection.eligibility === 'uncertain',+ }}- private async refreshCodexSnapshot(): Promise<boolean> {+ private async refreshCodexSnapshot(): Promise<{+ configMap?: k8s.V1ConfigMap+ snapshot: CodexCatalogSnapshot+ readOk: boolean+ }> {try {const cm = await this.deps.coreApi.readNamespacedConfigMap({name: ALLOWED_MODELS_CONFIGMAP_NAME,namespace: ALLOWLIST_CONFIGMAP_NAMESPACE,})- this.lastCodexConfigMap = cm- this.codexSnapshot = parseAllowedModelsSnapshot(cm)- this.lastCodexSnapshotReadOk = true- return true+ this.codexView = { configMap: cm, snapshot: parseAllowedModelsSnapshot(cm), readOk: true }+ return this.codexView} catch (err) {- this.lastCodexConfigMap = undefined- this.lastCodexSnapshotReadOk = falseif (isCodexSnapshotTimeout(err)) {- this.codexSnapshot = snapshotFromConfigMapError('timeout')+ this.codexView = { snapshot: snapshotFromConfigMapError('timeout'), readOk: false }this.log.warn('Codex allowlist ConfigMap read timed out; failing closed', {configMap: ALLOWED_MODELS_CONFIGMAP_NAME,namespace: ALLOWLIST_CONFIGMAP_NAMESPACE,})- return false+ return this.codexView}const code = getErrorCode(err)if (code === 401 || code === 403) {- this.codexSnapshot = snapshotFromConfigMapError('forbidden')+ this.codexView = { snapshot: snapshotFromConfigMapError('forbidden'), readOk: false }this.log.warn('Codex allowlist ConfigMap read forbidden; failing closed', {configMap: ALLOWED_MODELS_CONFIGMAP_NAME,namespace: ALLOWLIST_CONFIGMAP_NAMESPACE,statusCode: code,})- return false+ return this.codexView}- this.codexSnapshot = snapshotFromConfigMapError('missing')+ this.codexView = { snapshot: snapshotFromConfigMapError('missing'), readOk: false }this.log.warn('Codex allowlist ConfigMap unavailable; failing closed', {configMap: ALLOWED_MODELS_CONFIGMAP_NAME,namespace: ALLOWLIST_CONFIGMAP_NAMESPACE,statusCode: code,})- return false+ return this.codexView}}@@ -1129,7 +1146,7 @@ export class WorkflowReconciler {throw new Error('SDK-only runtime requires spec.steps to be absent or empty')}- const codexSnapshotAvailable = await this.refreshCodexSnapshot()+ const codexView = await this.refreshCodexSnapshot()const agent = resolveEagerSdkMcpHostAgent(spec)const context = this.resolveCodexContext(recipeUid, recipeName, runtimeScopeRecipeName)const codexBinding =@@ -1138,7 +1155,8 @@ export class WorkflowReconciler {provider: agent.provider,model: agent.model,connectionKey: context.connectionKey,- configMap: this.lastCodexConfigMap,+ configMap: codexView.configMap,+ log: this.log,}): null@@ -1159,7 +1177,7 @@ export class WorkflowReconciler {runtimeScopeRecipeName,spec,runtime,- { mcpHostPhase, codexBinding, codexSnapshotUnavailable: !codexSnapshotAvailable }+ { mcpHostPhase, codexBinding, codexSnapshotUnavailable: !codexView.readOk })const bootstrapProof = this.pluginWorkloadSdkProvisioner.getBootstrapProof(recipeName)switch (status) {@@ -1606,6 +1624,29 @@ export class WorkflowReconciler {// (that PVC is provisioned by the triggered-run path). Mounting it// here would wedge the pod in Pending — the PVC does not exist until a// run starts. The triggered run later recreates the pod with the mount.+ // Capture the allowlist view ONCE and derive the binding from it, so+ // the ConfigMap and the read-ok flag handed to the provisioner come+ // from the same refresh. Resolving the binding inside the provisioner+ // (after its own awaits) let a concurrently-reconciled recipe's failed+ // refresh produce a null binding with `codexSnapshotUnavailable:false`+ // — a binding-less v3 configure that wipes the live host binding.+ const eagerCodexView = this.codexView+ const eagerAgent = resolveEagerSdkMcpHostAgent(spec)+ const eagerCodexContext = this.resolveCodexContext(+ recipeUid,+ recipeName,+ runtimeScopeRecipeName+ )+ const eagerCodexBinding =+ eagerAgent?.provider && eagerAgent.model+ ? deriveSdkOnlyCodexBinding({+ provider: eagerAgent.provider,+ model: eagerAgent.model,+ connectionKey: eagerCodexContext.connectionKey,+ configMap: eagerCodexView.configMap,+ log: this.log,+ })+ : nullconst eagerStatus = await this.pluginWorkloadSdkProvisioner.ensureEagerSdkMcpHost(recipeName,recipeUid,@@ -1615,7 +1656,8 @@ export class WorkflowReconciler {runtime,{mcpHostPhase,- codexSnapshotUnavailable: !this.lastCodexSnapshotReadOk,+ codexBinding: eagerCodexBinding,+ codexSnapshotUnavailable: !eagerCodexView.readOk,})const eagerBootstrapProof =@@ -3727,12 +3769,19 @@ export class WorkflowReconciler {spec: WorkflowRecipeSpec,recipeUid?: string): Promise<McpHostRuntimeTokenRefreshResult> {+ const effectiveScopes = this.resolveEffectiveControlScopes(+ spec,+ recipeUid ?? '',+ recipeName,+ runtimeScopeRecipeName+ )const tokenRefresh = await this.ensureMcpHostRuntimeTokenSecret(namespace,recipeName,runtimeScopeRecipeName,- this.resolveEffectiveControlScopes(spec, recipeUid ?? '', recipeName, runtimeScopeRecipeName),- deriveRecipeHostGfsScopes(spec)+ effectiveScopes.scopes,+ deriveRecipeHostGfsScopes(spec),+ effectiveScopes.codexScopeUncertain)if (this.deps.config.pluginWorkloadSdkEnabled && spec.pluginWorkloadSdk) {await this.pluginWorkloadSdkProvisioner.ensurePluginWorkloadSdkTokenSecret(recipeName, spec)@@ -4667,7 +4716,8 @@ export class WorkflowReconciler {recipeName: string,runtimeScopeRecipeName = recipeName,workflowControlScopes: EffectiveWorkflowControlScope[] = [],- gfsScopes: WorkflowRecipeGfsScope[] = ['gfs.read']+ gfsScopes: WorkflowRecipeGfsScope[] = ['gfs.read'],+ codexScopeUncertain = false): Promise<McpHostRuntimeTokenRefreshResult> {const secretName = `wf-${recipeName}-mcp-host-runtime-tokens`const sandboxNamespace = this.deps.config.sandboxNamespace@@ -4683,12 +4733,16 @@ export class WorkflowReconciler {runtimeScopeRecipeName,workflowControlScopes,gfsScopes,- existing+ existing,+ codexScopeUncertain)} catch (err) {if (getErrorCode(err) !== 404) throw err}+ // First mint: there is no live JWT whose Codex decision could be preserved,+ // so an uncertain snapshot mints without the scope (fail-closed). The real+ // remint happens once the ConfigMap is readable again.const mcpHostRuntimeTokens = await issueMcpHostRuntimeTokens(recipeNamespace,runtimeScopeRecipeName,@@ -4726,7 +4780,8 @@ export class WorkflowReconciler {runtimeScopeRecipeName,workflowControlScopes,gfsScopes,- existing+ existing,+ codexScopeUncertain)this.log.info(`Secret "${secretName}" already exists (skip)`)return tokenRefresh@@ -4737,14 +4792,24 @@ export class WorkflowReconciler {* Refreshes the mcp-host-runtime-token Secret if either stored JWT is missing or will expire* within the configured runtime refresh window. Refresh failures are fatal to reconcile so the* mounted Secret never silently drifts stale after a pod restart.+ *+ * `codexScopeUncertain` marks a projection that had no data to decide on (see+ * `resolveEffectiveControlScopes`). In that state the expected scope set+ * inherits `llm:codex:execute` from the live JWT instead of dropping it: a+ * transient ConfigMap read failure otherwise looks exactly like a revocation+ * and remints with reason `scope`, which rolls the eager pod, discards its+ * bootstrap proof, and rolls it a second time when the ConfigMap returns.+ * Every other scope is still compared, and a readable ConfigMap that denies+ * the grant still withdraws the scope and rolls the pod.*/private async refreshMcpHostRuntimeTokensIfExpiring(recipeNamespace: string,recipeName: string,runtimeScopeRecipeName: string,- workflowControlScopes: EffectiveWorkflowControlScope[],+ requestedWorkflowControlScopes: EffectiveWorkflowControlScope[],expectedGfsScopes: WorkflowRecipeGfsScope[],- existing: k8s.V1Secret+ existing: k8s.V1Secret,+ codexScopeUncertain = false): Promise<McpHostRuntimeTokenRefreshResult> {const rawAccess = existing.data?.['mcp-host-runtime-access-token']const rawRefresh = existing.data?.['mcp-host-runtime-refresh-token']@@ -4762,6 +4827,25 @@ export class WorkflowReconciler {refreshJwt,'workflowControlScopes')+ // Uncertain neither grants nor revokes: with no readable catalog the Codex+ // decision already in the live access JWT is carried forward, so a failed+ // ConfigMap read cannot masquerade as a revocation. Applies to the issued+ // tokens as well — expecting a scope the mint would drop would remint on+ // every pass.+ const preservedCodexScope =+ codexScopeUncertain &&+ accessScopes.includes(CODEX_EXECUTE_SCOPE) &&+ !requestedWorkflowControlScopes.includes(CODEX_EXECUTE_SCOPE)+ if (preservedCodexScope) {+ this.log.warn('Codex catalog is undecidable; preserving the live Codex scope', {+ recipeName,+ runtimeScopeRecipeName,+ scope: CODEX_EXECUTE_SCOPE,+ })+ }+ const workflowControlScopes: EffectiveWorkflowControlScope[] = preservedCodexScope+ ? [...requestedWorkflowControlScopes, CODEX_EXECUTE_SCOPE]+ : requestedWorkflowControlScopesconst rawMcpHostControl = existing.data?.['mcp-host-workflow-control-token']const mcpHostControlJwt = rawMcpHostControl? Buffer.from(rawMcpHostControl, 'base64').toString('utf-8')diff --git a/workflow-recipes/tests/unit/workflow/modelConfigHandler.pluginSdkBroker.test.ts b/workflow-recipes/tests/unit/workflow/modelConfigHandler.pluginSdkBroker.test.tsindex d52bf034e..208c0b4ad 100644--- a/workflow-recipes/tests/unit/workflow/modelConfigHandler.pluginSdkBroker.test.ts+++ b/workflow-recipes/tests/unit/workflow/modelConfigHandler.pluginSdkBroker.test.ts@@ -1,4 +1,5 @@import { describe, expect, it, vi } from 'vitest'+import { computeCodexPolicyHash } from '@clerum/llm-provider-attempt-contract'import {type K8sSecretReader,type McpHostClient,@@ -202,12 +203,19 @@ describe('ModelConfigHandler Plugin SDK per-attempt credential broker', () => {})it('publishes Codex SDK bootstrap as v3 without reading ConfigMaps or Secrets', async () => {+ // The hash is re-derived from the five fields on the way back, so a+ // placeholder digest is not a valid echo — it must be the real one.const binding = {connectionKey: 'team-plus',catalogRevision: 4,credentialRevision: 1,model: 'gpt-5.1',- bindingHash: 'a'.repeat(64),+ bindingHash: computeCodexPolicyHash({+ model: 'gpt-5.1',+ catalogRevision: 4,+ credentialRevision: 1,+ connectionKey: 'team-plus',+ }),}const mcpHost: McpHostClient = {configure: vi.fn(async () => ({ status: 500, body: {} })),@@ -257,4 +265,157 @@ describe('ModelConfigHandler Plugin SDK per-attempt credential broker', () => {expect(k8s.readConfigMapWithPresence).not.toHaveBeenCalled()expect(k8s.readSecret).not.toHaveBeenCalled()})++ it('drops an echoed Codex binding whose hash does not verify', async () => {+ // Shape validation alone would republish this binding to WRC. The hash is+ // the only thing tying the five fields to the policy WRC minted, so an+ // unverifiable digest must not survive the broker.+ const minted = {+ connectionKey: 'team-plus',+ catalogRevision: 4,+ credentialRevision: 1,+ model: 'gpt-5.1',+ bindingHash: computeCodexPolicyHash({+ model: 'gpt-5.1',+ catalogRevision: 4,+ credentialRevision: 1,+ connectionKey: 'team-plus',+ }),+ }+ const mcpHost: McpHostClient = {+ configure: vi.fn(async () => ({ status: 500, body: {} })),+ configurePluginWorkloadSdkBootstrap: vi.fn(async () => ({+ status: 200,+ body: {+ configured: true,+ ready: true,+ provider: 'codex-subscription',+ model: 'gpt-5.1',+ contractVersion: 3,+ policyReady: true,+ policyState: 'active',+ // Same shape, tampered revision: the digest no longer matches.+ codexBinding: { ...minted, credentialRevision: 99 },+ },+ })),+ }+ const handler = new ModelConfigHandler(reader(), mcpHost)++ const result = await handler.configurePluginWorkloadSdkBootstrap(+ 'codex-subscription',+ 'gpt-5.1',+ 'http://mcp-host:8090',+ 'wrc-token',+ 'promptBridge',+ minted+ )++ expect(result.status).toBe(202)+ expect(result.body).not.toHaveProperty('codexBinding')+ })++ it('drops an echoed Codex binding minted for another model', async () => {+ const otherModel = {+ connectionKey: 'team-plus',+ catalogRevision: 4,+ credentialRevision: 1,+ model: 'gpt-5.3-codex',+ bindingHash: computeCodexPolicyHash({+ model: 'gpt-5.3-codex',+ catalogRevision: 4,+ credentialRevision: 1,+ connectionKey: 'team-plus',+ }),+ }+ const mcpHost: McpHostClient = {+ configure: vi.fn(async () => ({ status: 500, body: {} })),+ configurePluginWorkloadSdkBootstrap: vi.fn(async () => ({+ status: 200,+ body: {+ configured: true,+ ready: true,+ provider: 'codex-subscription',+ model: 'gpt-5.1',+ contractVersion: 3,+ policyReady: true,+ policyState: 'active',+ codexBinding: otherModel,+ },+ })),+ }+ const handler = new ModelConfigHandler(reader(), mcpHost)++ const result = await handler.configurePluginWorkloadSdkBootstrap(+ 'codex-subscription',+ 'gpt-5.1',+ 'http://mcp-host:8090',+ 'wrc-token',+ 'promptBridge'+ )++ expect(result.status).toBe(202)+ expect(result.body).not.toHaveProperty('codexBinding')+ })++ it('tags a pre-v3 Codex bootstrap answer as a stale contract, not a generic failure', async () => {+ // A host running an old image answers the v3 Codex bootstrap with a v2+ // identity. WRC needs to tell that apart from a broker outage, otherwise+ // the CR reports "the configured provider is unavailable" for what is+ // really a stale workload image.+ const mcpHost: McpHostClient = {+ configure: vi.fn(async () => ({ status: 500, body: {} })),+ configurePluginWorkloadSdkBootstrap: vi.fn(async () => ({+ status: 200,+ body: {+ configured: true,+ ready: true,+ provider: 'codex-subscription',+ model: 'gpt-5.1',+ contractVersion: 2,+ policyReady: true,+ policyState: 'active',+ },+ })),+ }+ const handler = new ModelConfigHandler(reader(), mcpHost)++ const result = await handler.configurePluginWorkloadSdkBootstrap(+ 'codex-subscription',+ 'gpt-5.1',+ 'http://mcp-host:8090',+ 'wrc-token',+ 'promptBridge'+ )++ expect(result.status).toBe(502)+ expect(result.body.policyReason).toBe('codex_bootstrap_contract_stale')+ })++ it('does not tag an unrelated v3 bootstrap rejection as a stale contract', async () => {+ const mcpHost: McpHostClient = {+ configure: vi.fn(async () => ({ status: 500, body: {} })),+ configurePluginWorkloadSdkBootstrap: vi.fn(async () => ({+ status: 200,+ body: {+ configured: true,+ ready: false,+ provider: 'codex-subscription',+ model: 'gpt-5.1',+ contractVersion: 3,+ },+ })),+ }+ const handler = new ModelConfigHandler(reader(), mcpHost)++ const result = await handler.configurePluginWorkloadSdkBootstrap(+ 'codex-subscription',+ 'gpt-5.1',+ 'http://mcp-host:8090',+ 'wrc-token',+ 'promptBridge'+ )++ expect(result.status).toBe(502)+ expect(result.body).not.toHaveProperty('policyReason')+ })})