Skip to content

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

TypeScript

fix(wrc): one Codex verdict per pass instead of convergent derivations

Alfredo Lopez974fc0c859f2
diff --git a/control-api/package-lock.json b/control-api/package-lock.json
index 50524b19b..74cbe884e 100644
--- a/control-api/package-lock.json
+++ b/control-api/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "clerum-control-api",
- "version": "0.1.542",
+ "version": "0.1.543",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "clerum-control-api",
- "version": "0.1.542",
+ "version": "0.1.543",
"dependencies": {
"@clerum/display-field": "file:../packages/display-field",
"@clerum/image-policy": "file:../packages/image-policy",
diff --git a/control-api/package.json b/control-api/package.json
index 20e5a7fea..0265e3e23 100644
--- a/control-api/package.json
+++ b/control-api/package.json
@@ -1,6 +1,6 @@
{
"name": "clerum-control-api",
- "version": "0.1.542",
+ "version": "0.1.543",
"description": "Internal Clerum control plane REST API + UI for managing CRDs and secrets",
"main": "dist/main.js",
"engines": {
diff --git a/control-api/src/routes/mcp-host/plugin-workload-sdk.routes.ts b/control-api/src/routes/mcp-host/plugin-workload-sdk.routes.ts
index 7010ae847..915dee85e 100644
--- a/control-api/src/routes/mcp-host/plugin-workload-sdk.routes.ts
+++ b/control-api/src/routes/mcp-host/plugin-workload-sdk.routes.ts
@@ -738,14 +738,6 @@ export function createMcpHostPluginWorkloadSdkRoutes(): Router {
// #533 acceptance criterion 2 ties the Codex binding to the catalog and
// credential revisions, but those live on the connection row and never
// reached the host, so `codexBindingReady` could not compare them. They
- // R4-M4: `codexBindingRevisions` is a STATIC capability of this binary —
- // "I know how to publish the revisions" — not a statement about any one
- // connection. Emitting it only alongside the numbers made a revoked or
- // missing connection look like an older control-api, so the host skipped
- // the freshness check exactly when the binding could not possibly be
- // backed. With the flag static, absent numbers take the host's
- // partial-deploy branch and fail closed, which is correct: a revoked
- // connection can never back a live binding.
// are advertised additively, gated by `codexBindingRevisions`, because
// the two rollout directions need opposite defaults: a host that
// predates the fields ignores them, and a host that postdates them must
@@ -754,6 +746,15 @@ export function createMcpHostPluginWorkloadSdkRoutes(): Router {
// which is the #540 failure shape. Omitting the comparison is a
// readiness gap, never an unfenced spend: llmProviderAttemptAuthorizer
// and llmProviderAttemptRedemption already reject a stale revision.
+ //
+ // R4-M4: `codexBindingRevisions` is a STATIC capability of this binary —
+ // "I know how to publish the revisions" — not a statement about any one
+ // connection. Emitting it only alongside the numbers made a revoked or
+ // missing connection look like an older control-api, so the host skipped
+ // the freshness check exactly when the binding could not possibly be
+ // backed. With the flag static, absent numbers take the host's
+ // partial-deploy branch and fail closed, which is correct: a revoked
+ // connection can never back a live binding.
const codexConnection =
reservationOnlyOauthBroker && typeof alignedPrimary?.connectionRef === 'string'
? await getSafeCodexSubscriptionConnection(pool, alignedPrimary.connectionRef)
diff --git a/control-api/src/services/pluginWorkloadSdkDb.ts b/control-api/src/services/pluginWorkloadSdkDb.ts
index bf8e6d311..c88dde3e5 100644
--- a/control-api/src/services/pluginWorkloadSdkDb.ts
+++ b/control-api/src/services/pluginWorkloadSdkDb.ts
@@ -173,7 +173,16 @@ export interface PluginWorkloadSdkQuotaLimits {
maxNotificationsPerRun?: number
maxInvocationsPerMinute?: number
maxNotificationsPerMinute?: number
- /** Deprecated (J8) — accepted and validated on the wire, never persisted. */
+ /**
+ * Per-grant output ceiling. PERSISTED and enforced: it lands as `max_tokens`
+ * on API-key providers; codex-subscription cannot bind it on the ChatGPT
+ * wire and is bounded there by the contract limit instead. See
+ * `AuthorizedPromptBridge.maxOutputTokens` (R4-H2).
+ *
+ * R5-M2: this said "never persisted" after R4-H2 had already reactivated the
+ * key. A reader trusting that comment would drop the persistence or the read
+ * and hand the regression straight back.
+ */
maxOutputTokens?: number
}
diff --git a/workflow-recipes/package-lock.json b/workflow-recipes/package-lock.json
index 73b6c46b0..32a88a9bb 100644
--- a/workflow-recipes/package-lock.json
+++ b/workflow-recipes/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "workload-recipes-controller",
- "version": "0.1.334",
+ "version": "0.1.335",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "workload-recipes-controller",
- "version": "0.1.334",
+ "version": "0.1.335",
"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 19ae9f239..9a1d3a85e 100644
--- a/workflow-recipes/package.json
+++ b/workflow-recipes/package.json
@@ -1,6 +1,6 @@
{
"name": "workload-recipes-controller",
- "version": "0.1.334",
+ "version": "0.1.335",
"description": "Workload Recipes Controller (WRC) - WorkloadRecipe lifecycle management and MCP server interface",
"main": "dist/main.js",
"engines": {
diff --git a/workflow-recipes/src/workflow/codexRecipeVerdict.test.ts b/workflow-recipes/src/workflow/codexRecipeVerdict.test.ts
new file mode 100644
index 000000000..f2615f4cc
--- /dev/null
+++ b/workflow-recipes/src/workflow/codexRecipeVerdict.test.ts
@@ -0,0 +1,216 @@
+import { describe, expect, it } from 'vitest'
+import { computeCodexPolicyHash } from '@clerum/llm-provider-attempt-contract'
+import type { WorkflowRecipeSpec } from '../types'
+import {
+ type CodexAllowlistView,
+ type CodexReconcileContext,
+ projectCodexRecipeVerdict,
+} from './codexRecipeVerdict'
+
+/*
+ * R5-B1. The Codex seam was fixed four times and each fix converged one more
+ * dimension: `readOk`, then `snapshotError`, while `provenance` stayed free to
+ * diverge. These tests pin the verdict as a whole, so a future dimension
+ * cannot be added on only one side.
+ *
+ * The last case in the file is the invariant sweep: it quantifies over every
+ * row rather than trusting that someone remembered to assert it per case.
+ */
+
+const MODEL = 'gpt-5.6-luna'
+const GRANT = 'team-plus'
+const RECIPE = 'notify-app'
+const UNASSIGNED = 'unassigned'
+
+const codexSpec = (): WorkflowRecipeSpec =>
+ ({ agent: { provider: 'codex-subscription', model: MODEL } }) as unknown as WorkflowRecipeSpec
+
+function eligibleConfigMap(overrides?: {
+ annotations?: Record<string, string>
+ models?: string[]
+}) {
+ 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(
+ (overrides?.models ?? [MODEL]).map(model => ({ model, stale: false }))
+ ),
+ },
+ }
+}
+
+const viewFrom = (
+ configMap: ReturnType<typeof eligibleConfigMap> | undefined
+): CodexAllowlistView =>
+ ({ configMap, snapshot: { flagEnabled: true } }) as unknown as CodexAllowlistView
+
+/** A view whose ConfigMap never arrived — the snapshot-error dimension. */
+const unreadableView = (): CodexAllowlistView =>
+ ({ snapshot: { flagEnabled: false, snapshotError: 'missing' } }) as unknown as CodexAllowlistView
+
+function context(overrides?: Partial<CodexReconcileContext>): CodexReconcileContext {
+ return {
+ recipeUid: 'uid-1',
+ recipeName: RECIPE,
+ runtimeScopeRecipeName: RECIPE,
+ claimedParent: false,
+ parentSpec: null,
+ connectionKey: GRANT,
+ ...overrides,
+ }
+}
+
+const verdict = (
+ ctx: CodexReconcileContext,
+ view: CodexAllowlistView,
+ hostAgent: { provider: string; model: string } | undefined = {
+ provider: 'codex-subscription',
+ model: MODEL,
+ }
+) => projectCodexRecipeVerdict({ ownSpec: codexSpec(), context: ctx, hostAgent, view })
+
+describe('projectCodexRecipeVerdict', () => {
+ it('reports an unreadable ConfigMap as uncertain and withholds the binding', () => {
+ const v = verdict(context(), unreadableView())
+ expect(v.projection.eligibility).toBe('uncertain')
+ expect(v.hostBinding).toBeNull()
+ })
+
+ it('reports a readable but malformed ConfigMap as uncertain, not as a decision', () => {
+ const cm = eligibleConfigMap({ annotations: { 'clerum.io/catalog-revision': 'not-a-number' } })
+ const v = verdict(context(), viewFrom(cm))
+ expect(v.projection.eligibility).toBe('uncertain')
+ expect(v.hostBinding).toBeNull()
+ })
+
+ // R5-B1 proper: the two provenance-uncertain states. Both were `ineligible`
+ // on the configure path while the scope path already called them uncertain,
+ // so a binding-less v3 configure wiped a live host binding over a transient
+ // condition.
+ it('reports an unavailable parent spec as uncertain even with an eligible own catalog', () => {
+ const v = verdict(
+ context({
+ runtimeScopeRecipeName: 'parent-recipe',
+ parentSpec: null,
+ connectionKey: UNASSIGNED,
+ }),
+ viewFrom(eligibleConfigMap())
+ )
+ expect(v.provenanceReason).toBe('parent_spec_unavailable')
+ expect(v.projection.eligibility).toBe('uncertain')
+ expect(v.hostBinding).toBeNull()
+ })
+
+ it('reports a rejected parent claim as uncertain even when the own grant is eligible', () => {
+ // The inverse divergence: the configure path used to MINT a binding here
+ // while the scope path withheld `llm:codex:execute` — an execution binding
+ // on a host whose freshly issued JWT lacks the scope.
+ const v = verdict(
+ context({ claimedParent: true, runtimeScopeRecipeName: RECIPE }),
+ viewFrom(eligibleConfigMap())
+ )
+ expect(v.provenanceReason).toBe('parent_provenance_rejected')
+ expect(v.projection.eligibility).toBe('uncertain')
+ expect(v.hostBinding).toBeNull()
+ })
+
+ it('treats an authoritative unassigned grant as a decision, not as uncertainty', () => {
+ // Not over-blocking: with authority established, "no grant assigned" is a
+ // real answer and a binding-less configure is the correct outcome.
+ const v = verdict(context({ connectionKey: UNASSIGNED }), viewFrom(eligibleConfigMap()))
+ expect(v.provenance).toBe('authoritative')
+ expect(v.projection.eligibility).not.toBe('uncertain')
+ expect(v.hostBinding).toBeNull()
+ })
+
+ it('mints the hashed five-field proof for an authoritative eligible catalog', () => {
+ const v = verdict(context(), viewFrom(eligibleConfigMap()))
+ expect(v.projection.eligibility).toBe('eligible')
+ expect(v.hostBinding).toEqual({
+ connectionKey: GRANT,
+ catalogRevision: 3,
+ credentialRevision: 1,
+ model: MODEL,
+ bindingHash: computeCodexPolicyHash({
+ model: MODEL,
+ catalogRevision: 3,
+ credentialRevision: 1,
+ connectionKey: GRANT,
+ }),
+ })
+ })
+
+ it('withholds the binding for a host agent on another model while keeping the scope', () => {
+ // The one remaining asymmetry: an eligible projection with no host binding
+ // is a decision about THIS pod's agent, not doubt about the catalog.
+ const v = verdict(context(), viewFrom(eligibleConfigMap()), {
+ provider: 'codex-subscription',
+ model: 'some-other-model',
+ })
+ expect(v.projection.eligibility).toBe('eligible')
+ expect(v.hostBinding).toBeNull()
+ })
+
+ it('withholds the binding for a non-Codex host agent', () => {
+ const v = verdict(context(), viewFrom(eligibleConfigMap()), {
+ provider: 'openai',
+ model: MODEL,
+ })
+ expect(v.hostBinding).toBeNull()
+ expect(v.hostBindingReason).toBe('host_agent_not_codex')
+ })
+
+ it('holds the binding/eligibility invariants across every case', () => {
+ const cases: Array<[string, ReturnType<typeof verdict>]> = [
+ ['unreadable', verdict(context(), unreadableView())],
+ [
+ 'malformed',
+ verdict(
+ context(),
+ viewFrom(eligibleConfigMap({ annotations: { 'clerum.io/catalog-revision': 'nope' } }))
+ ),
+ ],
+ [
+ 'parent-unavailable',
+ verdict(
+ context({
+ runtimeScopeRecipeName: 'parent',
+ parentSpec: null,
+ connectionKey: UNASSIGNED,
+ }),
+ viewFrom(eligibleConfigMap())
+ ),
+ ],
+ ['parent-rejected', verdict(context({ claimedParent: true }), viewFrom(eligibleConfigMap()))],
+ [
+ 'unassigned',
+ verdict(context({ connectionKey: UNASSIGNED }), viewFrom(eligibleConfigMap())),
+ ],
+ ['eligible', verdict(context(), viewFrom(eligibleConfigMap()))],
+ [
+ 'wrong-model',
+ verdict(context(), viewFrom(eligibleConfigMap()), {
+ provider: 'codex-subscription',
+ model: 'other',
+ }),
+ ],
+ ]
+ for (const [name, v] of cases) {
+ if (v.hostBinding !== null) {
+ expect(`${name}:${v.projection.eligibility}`).toBe(`${name}:eligible`)
+ expect(`${name}:${v.provenance}`).toBe(`${name}:authoritative`)
+ }
+ if (v.projection.eligibility === 'uncertain') {
+ expect(`${name}:${v.hostBinding === null}`).toBe(`${name}:true`)
+ }
+ }
+ })
+})
diff --git a/workflow-recipes/src/workflow/codexRecipeVerdict.ts b/workflow-recipes/src/workflow/codexRecipeVerdict.ts
new file mode 100644
index 000000000..3328d43b0
--- /dev/null
+++ b/workflow-recipes/src/workflow/codexRecipeVerdict.ts
@@ -0,0 +1,158 @@
+import {
+ CODEX_PROVIDER,
+ type CodexCatalogSnapshot,
+ type CodexConfigMapView,
+ type CodexExecutionProjection,
+ snapshotForAssignedCodexGrant,
+ toEligiblePolicyBinding,
+} from '@clerum/codex-catalog-projection'
+import type { WorkflowRecipeSpec } from '../types'
+import {
+ type CodexProvenance,
+ projectRecipeCodexExecution,
+ resolveCodexAuthoritativeSpec,
+} from './codexExecutionProjection'
+import {
+ type PluginWorkloadSdkCodexBindingProof,
+ mintSdkOnlyCodexBindingProof,
+} from './sdkOnlyCodexBinding'
+
+/*
+ * ONE Codex verdict per reconcile pass.
+ *
+ * This seam has been fixed four times — J4, N-08, R4-B1, R5-B1 — and every
+ * fix converged one more dimension while leaving another live. The shape of
+ * the bug never changed: two consumers answered the same question along
+ * different paths, so `readOk` disagreed with `eligibility`, and then
+ * `snapshotError` agreed while `provenance` did not.
+ *
+ * Converging one dimension at a time cannot end, because nothing forbids the
+ * next dimension. So this module does not converge dimensions: it removes the
+ * possibility of divergence. `projectCodexRecipeVerdict` computes the WHOLE
+ * verdict once, from one captured set of inputs, and every consumer — control
+ * scopes, scope uncertainty, the execution binding, the configure skip, the
+ * Codex-proxy egress decision — reads a FIELD of the returned object.
+ *
+ * There is deliberately no derived boolean anyone can force, no second
+ * projection, and no second read of the reconciler's live allowlist view
+ * inside the same pass. The provenance-blind entry points are deleted rather
+ * than deprecated, for the same reason `readOk` was deleted: a reachable
+ * blind path is an invitation for the sibling to come back.
+ */
+
+export type CodexReconcileContext = {
+ recipeUid: string
+ recipeName: string
+ runtimeScopeRecipeName: string
+ claimedParent: boolean
+ parentSpec: WorkflowRecipeSpec | null
+ /**
+ * Grant (connection key) the recipe is bound to via the
+ * `clerum.io/codex-connection-ref` annotation on the authoritative recipe
+ * (the runtime-scope parent when inherited). REQUIRED: an optional key with
+ * a `?? unassigned` default at the call site is a silent fallback, and the
+ * only producer (`bindCodexReconcileContext`) always fills it.
+ */
+ connectionKey: string
+}
+
+/**
+ * The allowlist refresh, captured once by the caller. Passing the view rather
+ * than reading `this.codexView` inside is what keeps a concurrently-refreshed
+ * snapshot from splitting one pass across two views (N-08, scope dimension).
+ */
+export type CodexAllowlistView = {
+ configMap?: CodexConfigMapView
+ snapshot: CodexCatalogSnapshot
+}
+
+export type CodexRecipeVerdict = {
+ readonly provenance: CodexProvenance
+ readonly provenanceReason: string
+ readonly connectionKey: string
+ /** Scope authority: eligibility, derivedScopes, egress, revisions. */
+ readonly projection: CodexExecutionProjection
+ /**
+ * v3 execution binding for the agent this pod runs.
+ *
+ * Non-null ONLY when `projection.eligibility === 'eligible'` AND
+ * `provenance === 'authoritative'`. A null under an eligible projection is a
+ * DECISION (the host agent is not Codex, its model is not the eligible one,
+ * or the revisions are out of range) — never uncertainty. That asymmetry is
+ * the one the type cannot express, so it is asserted in the verdict tests.
+ */
+ readonly hostBinding: PluginWorkloadSdkCodexBindingProof | null
+ readonly hostBindingReason: string
+}
+
+export function projectCodexRecipeVerdict(input: {
+ ownSpec: WorkflowRecipeSpec
+ context: CodexReconcileContext
+ hostAgent: { provider: string; model: string } | undefined
+ view: CodexAllowlistView
+ log?: {
+ warn(msg: string, fields?: Record<string, unknown>): void
+ debug(msg: string, fields?: Record<string, unknown>): void
+ }
+}): CodexRecipeVerdict {
+ const { context, view } = input
+ const resolved = resolveCodexAuthoritativeSpec({
+ recipeName: context.recipeName,
+ runtimeScopeRecipeName: context.runtimeScopeRecipeName,
+ claimedParent: context.claimedParent,
+ ownSpec: input.ownSpec,
+ parentSpec: context.parentSpec,
+ })
+ const snapshot = snapshotForAssignedCodexGrant(
+ context.connectionKey,
+ view.configMap,
+ view.snapshot
+ )
+ const projection = projectRecipeCodexExecution(resolved.spec, snapshot, resolved.provenance)
+
+ const base = {
+ provenance: resolved.provenance,
+ provenanceReason: resolved.reason,
+ connectionKey: context.connectionKey,
+ projection,
+ } as const
+
+ if (projection.eligibility !== 'eligible') {
+ if (projection.eligibility === 'uncertain') {
+ // A recipe stuck in awaiting_policy because of a stray parent label or an
+ // unreadable ConfigMap must be visible to an operator; this used to be a
+ // debug line, which is why the state was only ever found by reading code.
+ input.log?.warn('Codex verdict is undecidable; withholding scope and binding', {
+ recipeName: context.recipeName,
+ connectionKey: context.connectionKey,
+ provenanceReason: resolved.reason,
+ reason: projection.reason,
+ })
+ }
+ return { ...base, hostBinding: null, hostBindingReason: projection.reason }
+ }
+
+ if (!input.hostAgent || input.hostAgent.provider !== CODEX_PROVIDER) {
+ return { ...base, hostBinding: null, hostBindingReason: 'host_agent_not_codex' }
+ }
+
+ // Reached only past the provenance + eligibility gate above, and re-parsing
+ // the SAME captured ConfigMap deterministically: a derivation of this
+ // verdict, not a second source of truth.
+ const { binding, reason } = toEligiblePolicyBinding(
+ view.configMap,
+ context.connectionKey,
+ input.hostAgent.model
+ )
+ if (!binding || binding.catalogRevision < 1 || binding.credentialRevision < 1) {
+ const withheld = binding ? 'revision_out_of_range' : reason
+ input.log?.debug('Codex execution binding withheld', {
+ recipeName: context.recipeName,
+ model: input.hostAgent.model,
+ connectionKey: context.connectionKey,
+ reason: withheld,
+ })
+ return { ...base, hostBinding: null, hostBindingReason: withheld }
+ }
+ return { ...base, hostBinding: mintSdkOnlyCodexBindingProof(binding), hostBindingReason: reason }
+}
diff --git a/workflow-recipes/src/workflow/pluginWorkloadSdkProvisioner.codexPolicy.test.ts b/workflow-recipes/src/workflow/pluginWorkloadSdkProvisioner.codexPolicy.test.ts
index f892fe56a..e23e8da2c 100644
--- a/workflow-recipes/src/workflow/pluginWorkloadSdkProvisioner.codexPolicy.test.ts
+++ b/workflow-recipes/src/workflow/pluginWorkloadSdkProvisioner.codexPolicy.test.ts
@@ -1,6 +1,7 @@
import { describe, expect, it, vi } from 'vitest'
import { computeCodexPolicyHash } from '@clerum/llm-provider-attempt-contract'
import type { WorkflowRecipeSpec } from '../types'
+import type { CodexRecipeVerdict } from './codexRecipeVerdict'
import {
PluginWorkloadSdkProvisioner,
type PluginWorkloadSdkProvisionerDeps,
@@ -48,6 +49,34 @@ function codexBinding(
const MINTED = codexBinding()
+/** Build the one verdict the provisioner reads, from a case's intent. */
+function verdictFor(opts: {
+ codexBinding?: PluginWorkloadSdkCodexBindingProof | null
+ codexBindingUndecidable?: boolean
+}): CodexRecipeVerdict {
+ const undecidable = opts.codexBindingUndecidable === true
+ const binding = opts.codexBinding ?? null
+ return {
+ provenance: undecidable ? 'uncertain' : 'authoritative',
+ provenanceReason: undecidable ? 'parent_spec_unavailable' : 'standalone',
+ connectionKey: 'team-plus',
+ projection: {
+ targets: [],
+ eligibleTargets: [],
+ derivedScopes: [],
+ requiresCodexProxyEgress: false,
+ catalogContentHash: null,
+ catalogRevision: null,
+ connectionRevision: null,
+ eligibility: undecidable ? 'uncertain' : binding ? 'eligible' : 'ineligible',
+ reason: undecidable ? 'provenance_uncertain' : binding ? 'eligible' : 'unassigned',
+ driftHashInput: '{}',
+ },
+ hostBinding: binding,
+ hostBindingReason: binding ? 'eligible' : 'unassigned',
+ }
+}
+
/** A v3 bootstrap body that survives parseEagerSdkBootstrapProof as policy-ready. */
function readyBootstrapBody(binding: PluginWorkloadSdkCodexBindingProof | null) {
return {
@@ -125,6 +154,10 @@ function makeHarness(configureResult: unknown) {
} as unknown as PluginWorkloadSdkProvisionerDeps
const provisioner = new PluginWorkloadSdkProvisioner(deps)
+ // R5-B1: the provisioner now takes ONE verdict instead of a binding plus a
+ // derived boolean. These helpers keep each existing case's semantics: a
+ // minted binding means eligible+authoritative, and "undecidable" means the
+ // projection itself could not decide.
const reconcile = (opts: {
codexBinding?: PluginWorkloadSdkCodexBindingProof | null
codexBindingUndecidable?: boolean
@@ -138,7 +171,7 @@ function makeHarness(configureResult: unknown) {
RUNTIME,
{
mcpHostPhase: 'Running',
- ...opts,
+ codexVerdict: verdictFor(opts),
}
)
diff --git a/workflow-recipes/src/workflow/pluginWorkloadSdkProvisioner.imageDrift.test.ts b/workflow-recipes/src/workflow/pluginWorkloadSdkProvisioner.imageDrift.test.ts
index be39b61d8..61929e2ea 100644
--- a/workflow-recipes/src/workflow/pluginWorkloadSdkProvisioner.imageDrift.test.ts
+++ b/workflow-recipes/src/workflow/pluginWorkloadSdkProvisioner.imageDrift.test.ts
@@ -1,5 +1,6 @@
import { describe, expect, it, vi } from 'vitest'
import type { WorkflowRecipeSpec } from '../types'
+import type { CodexRecipeVerdict } from './codexRecipeVerdict'
import { PluginWorkloadSdkProvisioner } from './pluginWorkloadSdkProvisioner'
import type { PluginWorkloadSdkProvisionerDeps } from './pluginWorkloadSdkProvisioner'
import { buildMcpHostPod, pluginWorkloadSdkRuntimeContractHash } from './podFactory'
@@ -135,6 +136,31 @@ function desiredRuntimeContractHash(): string {
return pluginWorkloadSdkRuntimeContractHash(desiredPod)
}
+/**
+ * The one verdict the provisioner reads. These image-drift cases are about pod
+ * rolls, not Codex policy, so they use an authoritative-but-ineligible verdict:
+ * a real decision, never uncertainty (which would take the configure skip).
+ */
+const decidedVerdict: CodexRecipeVerdict = {
+ provenance: 'authoritative',
+ provenanceReason: 'standalone',
+ connectionKey: 'unassigned',
+ projection: {
+ targets: [],
+ eligibleTargets: [],
+ derivedScopes: [],
+ requiresCodexProxyEgress: false,
+ catalogContentHash: null,
+ catalogRevision: null,
+ connectionRevision: null,
+ eligibility: 'ineligible',
+ reason: 'unassigned',
+ driftHashInput: '{}',
+ },
+ hostBinding: null,
+ hostBindingReason: 'unassigned',
+}
+
describe('ensureEagerSdkMcpHost image-drift roll', () => {
it('rolls a healthy eager mcp-host pod when its image drifts from the platform image', async () => {
const { provisioner, deleteNamespacedPod, createNamespacedPod } = makeProvisioner(STALE_IMAGE)
@@ -146,7 +172,7 @@ describe('ensureEagerSdkMcpHost image-drift roll', () => {
RECIPE,
SPEC,
RUNTIME,
- { mcpHostPhase: 'Running' }
+ { mcpHostPhase: 'Running', codexVerdict: decidedVerdict }
)
// Pod deleted so the next reconcile recreates it from the platform image;
@@ -175,7 +201,7 @@ describe('ensureEagerSdkMcpHost image-drift roll', () => {
RECIPE,
SPEC,
RUNTIME,
- { mcpHostPhase: 'Running' }
+ { mcpHostPhase: 'Running', codexVerdict: decidedVerdict }
)
expect(deleteNamespacedPod).not.toHaveBeenCalled()
@@ -192,7 +218,7 @@ describe('ensureEagerSdkMcpHost image-drift roll', () => {
RECIPE,
SPEC,
RUNTIME,
- { mcpHostPhase: 'Running' }
+ { mcpHostPhase: 'Running', codexVerdict: decidedVerdict }
)
expect(status).toBe('deploying')
@@ -215,7 +241,7 @@ describe('ensureEagerSdkMcpHost image-drift roll', () => {
RECIPE,
SPEC,
RUNTIME,
- { mcpHostPhase: 'Pending' }
+ { mcpHostPhase: 'Pending', codexVerdict: decidedVerdict }
)
expect(status).toBe('deploying')
@@ -240,7 +266,7 @@ describe('ensureEagerSdkMcpHost image-drift roll', () => {
RECIPE,
SPEC,
RUNTIME,
- { mcpHostPhase: 'Running' }
+ { mcpHostPhase: 'Running', codexVerdict: decidedVerdict }
)
expect(status).toBe('deploying')
@@ -286,7 +312,7 @@ describe('ensureEagerSdkMcpHost image-drift roll', () => {
RECIPE,
SPEC,
RUNTIME,
- { mcpHostPhase: undefined }
+ { mcpHostPhase: undefined, codexVerdict: decidedVerdict }
)
expect(status).toBe('deploying')
@@ -351,7 +377,7 @@ describe('ensureEagerSdkMcpHost image-drift roll', () => {
RECIPE,
SPEC,
RUNTIME,
- { mcpHostPhase: 'Pending' }
+ { mcpHostPhase: 'Pending', codexVerdict: decidedVerdict }
)
expect(status).toBe('deploying')
@@ -416,7 +442,7 @@ describe('ensureEagerSdkMcpHost image-drift roll', () => {
RECIPE,
promptBridgeSpec,
RUNTIME,
- { mcpHostPhase: 'Running' }
+ { mcpHostPhase: 'Running', codexVerdict: decidedVerdict }
)
expect(status).toBe('deploying')
@@ -498,6 +524,7 @@ describe('ensureEagerSdkMcpHost image-drift roll', () => {
RUNTIME,
{
mcpHostPhase: 'Running',
+ codexVerdict: decidedVerdict,
}
)
@@ -534,7 +561,7 @@ describe('ensureEagerSdkMcpHost runtime token roll', () => {
RECIPE,
SPEC,
RUNTIME,
- { mcpHostPhase: 'Running' }
+ { mcpHostPhase: 'Running', codexVerdict: decidedVerdict }
)
expect(status).toBe('deploying')
@@ -558,7 +585,7 @@ describe('ensureEagerSdkMcpHost runtime token roll', () => {
RECIPE,
SPEC,
RUNTIME,
- { mcpHostPhase: 'Running' }
+ { mcpHostPhase: 'Running', codexVerdict: decidedVerdict }
)
expect(deleteNamespacedPod).not.toHaveBeenCalled()
@@ -582,7 +609,7 @@ describe('ensureEagerSdkMcpHost runtime token roll', () => {
RECIPE,
SPEC,
RUNTIME,
- { mcpHostPhase: 'Running' }
+ { mcpHostPhase: 'Running', codexVerdict: decidedVerdict }
)
expect(status).toBe('deploying')
@@ -607,7 +634,7 @@ describe('ensureEagerSdkMcpHost runtime token roll', () => {
RECIPE,
SPEC,
RUNTIME,
- { mcpHostPhase: 'Running' }
+ { mcpHostPhase: 'Running', codexVerdict: decidedVerdict }
)
expect(deleteNamespacedPod).not.toHaveBeenCalled()
@@ -682,7 +709,29 @@ describe('ensureEagerSdkMcpHost ConfigMap snapshot skip', () => {
RECIPE,
CODEX_SPEC,
RUNTIME,
- { mcpHostPhase: 'Running', codexBindingUndecidable: true }
+ {
+ mcpHostPhase: 'Running',
+ // R5-B1: undecidable is now a field of the one verdict.
+ codexVerdict: {
+ provenance: 'uncertain',
+ provenanceReason: 'parent_spec_unavailable',
+ connectionKey: 'team-plus',
+ projection: {
+ targets: [],
+ eligibleTargets: [],
+ derivedScopes: [],
+ requiresCodexProxyEgress: false,
+ catalogContentHash: null,
+ catalogRevision: null,
+ connectionRevision: null,
+ eligibility: 'uncertain',
+ reason: 'provenance_uncertain',
+ driftHashInput: '{}',
+ },
+ hostBinding: null,
+ hostBindingReason: 'provenance_uncertain',
+ } satisfies CodexRecipeVerdict,
+ }
)
).resolves.toBe('awaiting_policy')
expect(configure).not.toHaveBeenCalled()
diff --git a/workflow-recipes/src/workflow/pluginWorkloadSdkProvisioner.ts b/workflow-recipes/src/workflow/pluginWorkloadSdkProvisioner.ts
index 5ff884a5b..411c25a5f 100644
--- a/workflow-recipes/src/workflow/pluginWorkloadSdkProvisioner.ts
+++ b/workflow-recipes/src/workflow/pluginWorkloadSdkProvisioner.ts
@@ -5,6 +5,7 @@ import { getErrorCode } from '../reconciler/k8sErrors'
import { effectiveWorkflowContextRefForSpec } from '../reconciler/workflowContext'
import type { WorkflowRecipeSpec } from '../types'
import { resolveEagerSdkMcpHostAgent } from './agentResolution'
+import type { CodexRecipeVerdict } from './codexRecipeVerdict'
import {
deletePodIfExists,
getContainerWaitingReason,
@@ -123,7 +124,8 @@ export type PluginWorkloadSdkProvisionerDeps = {
recipeName: string,
runtimeScopeRecipeName: string,
spec: WorkflowRecipeSpec,
- recipeUid?: string
+ recipeUid: string | undefined,
+ codexVerdict: CodexRecipeVerdict
) => Promise<McpHostRuntimeTokenRefreshResult | void>
applyWorkflowNetworkPolicies: (
recipeName: string,
@@ -211,13 +213,14 @@ export class PluginWorkloadSdkProvisioner {
runtime: WorkflowRuntimePlan,
opts: {
mcpHostPhase: string | undefined
- codexBinding?: PluginWorkloadSdkCodexBindingProof | null
/**
- * ConfigMap read failed this reconcile. Grant decisions stay fail-closed.
- * Do not send a binding-less v3 configure that would clear a live host
- * binding.
+ * The caller's ONE Codex verdict for this pass (R5-B1). Required, and
+ * deliberately not a pair of optional derived fields: an optional
+ * `codexBindingUndecidable` defaulting to false is a flag a future
+ * caller can silently omit, which is precisely how a binding-less v3
+ * configure reached a live host.
*/
- codexBindingUndecidable?: boolean
+ codexVerdict: CodexRecipeVerdict
}
): Promise<EagerSdkMcpHostStatus> {
const log = createLogger('wrc', recipeName)
@@ -238,7 +241,8 @@ export class PluginWorkloadSdkProvisioner {
recipeName,
runtimeScopeRecipeName,
spec,
- recipeUid
+ recipeUid,
+ opts.codexVerdict
)
await this.deps.applyWorkflowNetworkPolicies(
@@ -387,7 +391,7 @@ export class PluginWorkloadSdkProvisioner {
if (promptBridge && !mcpHostAgent) return 'failed'
if (
- opts.codexBindingUndecidable === true &&
+ opts.codexVerdict.projection.eligibility === 'uncertain' &&
promptBridge &&
mcpHostAgent?.provider === 'codex-subscription'
) {
@@ -414,10 +418,10 @@ export class PluginWorkloadSdkProvisioner {
}
return 'ready'
}
- // The caller derives the binding from the same allowlist view it used for
- // `codexBindingUndecidable`; the provisioner never re-reads that state
- // after its own awaits (see the reconciler's `codexView`).
- const resolvedCodexBinding = opts.codexBinding ?? null
+ // Both the skip decision above and this binding are fields of the SAME
+ // verdict the caller computed once for this pass. The provisioner never
+ // re-derives either after its own awaits (R5-B1).
+ const resolvedCodexBinding = opts.codexVerdict.hostBinding
const capabilityFamily = promptBridge ? 'promptBridge' : 'clientNotifications'
const configureKey = `${readiness.uid}:${capabilityFamily}:${mcpHostAgent?.provider ?? 'none'}:${mcpHostAgent?.model ?? 'none'}:${resolvedCodexBinding?.bindingHash ?? 'none'}`
try {
diff --git a/workflow-recipes/src/workflow/sdkOnlyCodexBinding.test.ts b/workflow-recipes/src/workflow/sdkOnlyCodexBinding.test.ts
index 57c7de647..7b1633afb 100644
--- a/workflow-recipes/src/workflow/sdkOnlyCodexBinding.test.ts
+++ b/workflow-recipes/src/workflow/sdkOnlyCodexBinding.test.ts
@@ -1,10 +1,8 @@
import { describe, expect, it, vi } from 'vitest'
import { computeCodexPolicyHash } from '@clerum/llm-provider-attempt-contract'
import {
- deriveSdkOnlyCodexBinding,
isPluginWorkloadSdkCodexBindingProof,
readVerifiedSdkOnlyCodexBinding,
- resolveSdkOnlyCodexBinding,
verifySdkOnlyCodexBindingHash,
} from './sdkOnlyCodexBinding'
@@ -78,204 +76,10 @@ function eligibleMappedConfigMap(overrides?: {
}
}
-describe('deriveSdkOnlyCodexBinding', () => {
- it('returns a hashed v3 proof for an assigned executable catalog', () => {
- const binding = deriveSdkOnlyCodexBinding({
- provider: 'codex-subscription',
- model: MODEL,
- connectionKey: 'team-plus',
- configMap: eligibleLegacyConfigMap(),
- })
- expect(binding).toEqual({
- connectionKey: 'team-plus',
- catalogRevision: 3,
- credentialRevision: 1,
- 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: 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/catalog-revision': '3',
- 'clerum.io/connection-revision': '1',
- },
- },
- },
- })
- ).toBeNull()
- })
-
- it('returns null when the ConfigMap could not be read', () => {
- expect(
- deriveSdkOnlyCodexBinding({
- provider: 'codex-subscription',
- model: MODEL,
- connectionKey: 'team-plus',
- configMap: undefined,
- })
- ).toBeNull()
- })
-
- // R4-B1: the reconciler used to answer "was the catalog decidable?" from a
- // pure IO flag, which is true for a ConfigMap that reads fine and parses
- // badly. These pin the single verdict both paths now share: an unreadable
- // ConfigMap and a malformed one are equally `uncertain`, while a deliberate
- // "Codex is off" is `ineligible` — a decision, not a doubt.
- it('reports an unreadable ConfigMap as uncertain', () => {
- expect(
- resolveSdkOnlyCodexBinding({
- provider: 'codex-subscription',
- model: MODEL,
- connectionKey: 'team-plus',
- configMap: undefined,
- })
- ).toMatchObject({ binding: null, eligibility: 'uncertain' })
- })
-
- it('reports a readable but malformed ConfigMap as uncertain, not as a decision', () => {
- const malformed = eligibleLegacyConfigMap()
- malformed.metadata!.annotations!['clerum.io/catalog-revision'] = 'not-a-number'
-
- expect(
- resolveSdkOnlyCodexBinding({
- provider: 'codex-subscription',
- model: MODEL,
- connectionKey: 'team-plus',
- configMap: malformed,
- })
- ).toMatchObject({ binding: null, eligibility: 'uncertain' })
- })
-
- it('reports a non-Codex provider as ineligible rather than uncertain', () => {
- expect(
- resolveSdkOnlyCodexBinding({
- provider: 'openai',
- model: MODEL,
- connectionKey: 'team-plus',
- configMap: eligibleLegacyConfigMap(),
- })
- ).toMatchObject({ binding: null, eligibility: 'ineligible' })
- })
-
- it('returns null for non-Codex providers and unassigned grants', () => {
- expect(
- deriveSdkOnlyCodexBinding({
- provider: 'openai',
- model: 'gpt-5.4-mini',
- connectionKey: 'team-plus',
- configMap: eligibleLegacyConfigMap({ models: ['gpt-5.4-mini'] }),
- })
- ).toBeNull()
- expect(
- deriveSdkOnlyCodexBinding({
- provider: 'codex-subscription',
- model: MODEL,
- connectionKey: 'unassigned',
- 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' })
- )
- })
-
+describe('readVerifiedSdkOnlyCodexBinding', () => {
+ // The derive/resolve suite moved to codexRecipeVerdict.test.ts along with
+ // the functions themselves (R5-B1): those entry points were blind to
+ // provenance and are deleted, not deprecated.
it('rebuilds a five-field proof and drops extra keys', () => {
const proof = {
connectionKey: 'team-plus',
diff --git a/workflow-recipes/src/workflow/sdkOnlyCodexBinding.ts b/workflow-recipes/src/workflow/sdkOnlyCodexBinding.ts
index 2f3db27ff..f3b6e48c2 100644
--- a/workflow-recipes/src/workflow/sdkOnlyCodexBinding.ts
+++ b/workflow-recipes/src/workflow/sdkOnlyCodexBinding.ts
@@ -86,70 +86,17 @@ export function readVerifiedSdkOnlyCodexBinding(
}
/**
- * Derive the sanitized v3 Codex execution proof from one WRC snapshot.
+ * Mint the sanitized five-field v3 proof from an already-eligible binding.
*
- * 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.
+ * Deliberately NOT exported alongside a "derive from a ConfigMap" helper any
+ * more. Those helpers (`deriveSdkOnlyCodexBinding` / `resolveSdkOnlyCodexBinding`)
+ * were blind to provenance, so a caller could obtain a binding for a recipe
+ * whose Codex authority could not be established — the R5-B1 wipe. The only
+ * caller is `projectCodexRecipeVerdict`, which gates on provenance and
+ * eligibility first. Removed rather than deprecated, for the same reason
+ * `readOk` was removed: a reachable blind path invites the sibling back.
*/
-export type SdkOnlyCodexBindingResolution = {
- binding: PluginWorkloadSdkCodexBindingProof | null
- eligibility: 'eligible' | 'ineligible' | 'uncertain'
- reason: string
-}
-
-/**
- * R4-B1: the same call must answer both "which binding?" and "was the catalog
- * decidable at all?". The reconciler previously derived the second from
- * `readOk`, a pure IO signal that is `true` for a ConfigMap that reads fine
- * but parses badly — so a malformed `catalog-revision` produced `uncertain`
- * on the scope path while the configure path saw a decidable catalog and sent
- * a binding-less v3 configure, wiping the live execution binding.
- * `uncertain` strictly subsumes `!readOk`: an unreadable ConfigMap is
- * `missing`, which is also `uncertain`.
- */
-export function resolveSdkOnlyCodexBinding(input: {
- provider: string
- model: string
- connectionKey: string | undefined
- configMap: CodexConfigMapView | undefined
- log?: { debug(msg: string, fields?: Record<string, unknown>): void }
-}): SdkOnlyCodexBindingResolution {
- if (input.provider !== CODEX_PROVIDER) {
- return { binding: null, eligibility: 'ineligible', reason: 'provider_not_codex' }
- }
- const { binding, eligibility, reason } = toEligiblePolicyBinding(
- input.configMap,
- input.connectionKey,
- input.model
- )
- if (!binding || binding.catalogRevision < 1 || binding.credentialRevision < 1) {
- const withheldReason = binding ? 'revision_out_of_range' : reason
- input.log?.debug('Codex execution binding withheld', {
- model: input.model,
- connectionKey: input.connectionKey ?? CODEX_UNASSIGNED_CONNECTION_KEY,
- eligibility,
- reason: withheldReason,
- })
- return { binding: null, eligibility, reason: withheldReason }
- }
- return { binding: toProof(binding), eligibility, reason }
-}
-
-export function deriveSdkOnlyCodexBinding(input: {
- provider: string
- model: string
- connectionKey: string | undefined
- configMap: CodexConfigMapView | undefined
- log?: { debug(msg: string, fields?: Record<string, unknown>): void }
-}): PluginWorkloadSdkCodexBindingProof | null {
- return resolveSdkOnlyCodexBinding(input).binding
-}
-
-function toProof(binding: {
+export function mintSdkOnlyCodexBindingProof(binding: {
connectionKey: string
catalogRevision: number
credentialRevision: number
diff --git a/workflow-recipes/src/workflow/workflowReconciler.codexUncertainScope.test.ts b/workflow-recipes/src/workflow/workflowReconciler.codexUncertainScope.test.ts
index bd66edacf..95701234b 100644
--- a/workflow-recipes/src/workflow/workflowReconciler.codexUncertainScope.test.ts
+++ b/workflow-recipes/src/workflow/workflowReconciler.codexUncertainScope.test.ts
@@ -454,4 +454,98 @@ describe('Codex allowlist view across interleaved recipes', () => {
bindingHash: EXPECTED_BINDING_HASH,
})
})
+
+ // ── R5-M1 / R5-B1 ───────────────────────────────────────────────────────
+ // The previous round fixed the wiring but tested only its two ends: the
+ // helper (malformed -> uncertain) and the provisioner (given the flag as an
+ // input). Nothing drove the reconciler, so forcing the flag to `false` at
+ // the wiring reintroduced the wipe with every test still green.
+ //
+ // These assert the OBSERVABLE outcome — no binding-less configure is ever
+ // sent — and each one first proves the reconcile actually reached the pod,
+ // because "configure was not called" is also true of a reconcile that died
+ // on line one.
+ describe('a binding-less configure is never sent under an undecidable verdict', () => {
+ it('withholds configure when the allowlist ConfigMap is readable but malformed', async () => {
+ const { reconciler, coreApi, configure } = createHarness()
+ bindGrant(reconciler)
+ const malformed = codexConfigMap()
+ malformed.metadata!.annotations!['clerum.io/catalog-revision'] = 'not-a-number'
+ coreApi.readNamespacedConfigMap.mockResolvedValue(malformed)
+
+ await reconcileRecipe(reconciler, codexSdkSpec())
+
+ expect(builtMcpHostPodFrom(coreApi)).toBeDefined()
+ expect(configure).not.toHaveBeenCalled()
+ })
+
+ it('withholds configure when the runtime-scope parent spec is unavailable', async () => {
+ // R5-B1 proper. The scope path already called this uncertain and kept the
+ // live JWT scope; the configure path called it `ineligible` and shipped a
+ // null binding, wiping the live execution binding over a transient read.
+ const { reconciler, coreApi, configure } = createHarness()
+ reconciler.setCodexReconcileContext({
+ recipeUid: `uid-${RECIPE}`,
+ recipeName: RECIPE,
+ runtimeScopeRecipeName: 'parent-recipe',
+ claimedParent: true,
+ parentSpec: null,
+ connectionKey: 'unassigned',
+ })
+
+ await reconcileRecipe(reconciler, codexSdkSpec())
+
+ expect(builtMcpHostPodFrom(coreApi)).toBeDefined()
+ expect(configure).not.toHaveBeenCalled()
+ })
+
+ it('withholds configure AND the scope when the parent claim is rejected', async () => {
+ // The inverse divergence: an eligible own grant used to mint a binding
+ // here while the scope path withheld `llm:codex:execute`, leaving an
+ // execution binding on a host whose fresh JWT lacks the scope.
+ const { reconciler, coreApi, configure } = createHarness()
+ reconciler.setCodexReconcileContext({
+ recipeUid: `uid-${RECIPE}`,
+ recipeName: RECIPE,
+ runtimeScopeRecipeName: RECIPE,
+ claimedParent: true,
+ parentSpec: null,
+ connectionKey: GRANT,
+ })
+
+ await reconcileRecipe(reconciler, codexSdkSpec())
+
+ expect(builtMcpHostPodFrom(coreApi)).toBeDefined()
+ expect(configure).not.toHaveBeenCalled()
+ expect(issuedScopes()).not.toContain(CODEX_SCOPE)
+ })
+
+ it('does configure with a null binding when an authoritative grant is unassigned', async () => {
+ // Control case: with authority established, "no grant" is a DECISION and
+ // clearing the binding is correct. Without this, the three tests above
+ // would also pass if the guard simply blocked every configure.
+ const { reconciler, coreApi, configure } = createHarness()
+ bindGrant(reconciler, RECIPE, 'unassigned')
+
+ await reconcileRecipe(reconciler, codexSdkSpec())
+
+ expect(builtMcpHostPodFrom(coreApi)).toBeDefined()
+ expect(configure).toHaveBeenCalledTimes(1)
+ expect(configure.mock.calls[0]?.[5] ?? null).toBeNull()
+ })
+
+ it('agrees on binding and scope in the eligible case', async () => {
+ // R5-B1's real invariant, asserted as a biconditional rather than as two
+ // independent facts: a configure that carries a binding must come with
+ // the scope, and vice versa.
+ const { reconciler, coreApi, configure } = createHarness()
+ bindGrant(reconciler)
+
+ await reconcileRecipe(reconciler, codexSdkSpec())
+
+ expect(builtMcpHostPodFrom(coreApi)).toBeDefined()
+ const carriedBinding = (configure.mock.calls[0]?.[5] ?? null) !== null
+ expect(carriedBinding).toBe(issuedScopes().includes(CODEX_SCOPE))
+ })
+ })
})
diff --git a/workflow-recipes/src/workflow/workflowReconciler.ts b/workflow-recipes/src/workflow/workflowReconciler.ts
index edd29cfcd..1c7d76bff 100644
--- a/workflow-recipes/src/workflow/workflowReconciler.ts
+++ b/workflow-recipes/src/workflow/workflowReconciler.ts
@@ -45,6 +45,12 @@ import {
projectRecipeCodexExecution,
resolveCodexAuthoritativeSpec,
} from './codexExecutionProjection'
+import {
+ type CodexAllowlistView,
+ type CodexRecipeVerdict,
+ type CodexReconcileContext,
+ projectCodexRecipeVerdict,
+} from './codexRecipeVerdict'
import {
type PodReadiness,
deletePodIfExists,
@@ -141,7 +147,6 @@ import {
deleteScheduling,
reconcileScheduling,
} from './schedulingHandler'
-import { resolveSdkOnlyCodexBinding } from './sdkOnlyCodexBinding'
import {
MCP_HOST_RUNTIME_TOKEN_GENERATION_ANNOTATION,
buildMcpHostRuntimeTokenSecret,
@@ -364,20 +369,7 @@ const EFFECTIVE_WORKFLOW_CONTROL_SCOPE_ORDER: EffectiveWorkflowControlScope[] =
'llm:codex:execute',
]
-export type CodexReconcileContext = {
- recipeUid: string
- recipeName: string
- runtimeScopeRecipeName: string
- claimedParent: boolean
- parentSpec: WorkflowRecipeSpec | null
- /**
- * Grant (connection key) the recipe is bound to via the
- * `clerum.io/codex-connection-ref` annotation on the authoritative recipe
- * (the runtime-scope parent when inherited). Missing/empty binds the
- * fail-closed `unassigned` sentinel, never the reserved grant.
- */
- connectionKey?: string
-}
+export type { CodexReconcileContext } from './codexRecipeVerdict'
function orderedScopesEqual<T extends string>(actual: T[], expected: T[]): boolean {
if (actual.length !== expected.length) return false
@@ -908,12 +900,11 @@ export class WorkflowReconciler {
* binding-less v3 configure that wipes a live mcp-host binding.
* Readers capture `this.codexView` once and use only that snapshot.
*
- * There is deliberately NO separate "was the read OK?" boolean here (R4-B1).
- * A ConfigMap that reads fine but parses badly is just as undecidable as one
- * that never arrived, and an IO-only flag said otherwise — so the scope path
- * withheld the grant while the configure path wiped the binding. The single
- * verdict is `resolveSdkOnlyCodexBinding(...).eligibility === 'uncertain'`,
- * which strictly subsumes the old flag.
+ * There is deliberately NO derived boolean here (R4-B1, R5-B1). Every
+ * consumer reads a field of the ONE `CodexRecipeVerdict` a pass computes
+ * with `projectCodexRecipeVerdict`. Converging one dimension at a time —
+ * first `readOk`, then `snapshotError` — always left the next one free to
+ * diverge; provenance was that next one.
*
* 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
@@ -934,8 +925,22 @@ export class WorkflowReconciler {
tokenFactory: deps.tokenFactory,
modelConfigHandler: deps.modelConfigHandler,
log: this.log,
- ensureMcpHostSecrets: (namespace, recipeName, runtimeScopeRecipeName, spec, recipeUid) =>
- this.ensureMcpHostSecrets(namespace, recipeName, runtimeScopeRecipeName, spec, recipeUid),
+ ensureMcpHostSecrets: (
+ namespace,
+ recipeName,
+ runtimeScopeRecipeName,
+ spec,
+ recipeUid,
+ codexVerdict
+ ) =>
+ this.ensureMcpHostSecrets(
+ namespace,
+ recipeName,
+ runtimeScopeRecipeName,
+ spec,
+ recipeUid,
+ codexVerdict
+ ),
applyWorkflowNetworkPolicies: (
recipeName,
recipeUid,
@@ -984,36 +989,33 @@ export class WorkflowReconciler {
}
}
- private projectCodex(
+ /**
+ * The single Codex verdict for one reconcile pass.
+ *
+ * `view` is a REQUIRED parameter and never defaults to `this.codexView`:
+ * the caller must capture the allowlist refresh once and hand the same
+ * object to every consumer. Reading the live field here is exactly how the
+ * scope path and the configure path ended up on two different snapshots
+ * within one pass (N-08, scope dimension).
+ */
+ private codexVerdictFor(
spec: WorkflowRecipeSpec,
recipeUid: string,
recipeName: string,
- runtimeScopeRecipeName: string
- ) {
+ runtimeScopeRecipeName: string,
+ view: CodexAllowlistView
+ ): CodexRecipeVerdict {
const context = this.resolveCodexContext(recipeUid, recipeName, runtimeScopeRecipeName)
- const resolved = resolveCodexAuthoritativeSpec({
- recipeName: context.recipeName,
- runtimeScopeRecipeName: context.runtimeScopeRecipeName,
- claimedParent: context.claimedParent,
+ return projectCodexRecipeVerdict({
ownSpec: spec,
- parentSpec: context.parentSpec,
+ context: {
+ ...context,
+ connectionKey: context.connectionKey ?? CODEX_UNASSIGNED_CONNECTION_KEY,
+ },
+ hostAgent: resolveEagerSdkMcpHostAgent(spec),
+ view,
+ log: this.log,
})
- return projectRecipeCodexExecution(
- resolved.spec,
- this.codexSnapshotFor(context.connectionKey ?? CODEX_UNASSIGNED_CONNECTION_KEY),
- resolved.provenance
- )
- }
-
- /**
- * Per-recipe snapshot: re-parse the last allowlist ConfigMap with the
- * recipe's assigned grant key. `unassigned` never inherits a mapped or
- * legacy catalog. A mapped miss fail-closes to an empty Codex snapshot.
- * Read failures keep the fail-closed error snapshot.
- */
- private codexSnapshotFor(connectionKey: string): CodexCatalogSnapshot {
- const view = this.codexView
- return snapshotForAssignedCodexGrant(connectionKey, view.configMap, view.snapshot)
}
/**
@@ -1030,20 +1032,17 @@ export class WorkflowReconciler {
*/
private resolveEffectiveControlScopes(
spec: WorkflowRecipeSpec,
- recipeUid: string,
- recipeName: string,
- runtimeScopeRecipeName: string
+ verdict: CodexRecipeVerdict
): { scopes: EffectiveWorkflowControlScope[]; codexScopeUncertain: boolean } {
const workflow = deriveWorkflowControlScopes(spec, {
pluginWorkloadSdkEnabled: this.deps.config.pluginWorkloadSdkEnabled,
})
- const projection = this.projectCodex(spec, recipeUid, recipeName, runtimeScopeRecipeName)
- const derived = projection.derivedScopes.filter(
+ const derived = verdict.projection.derivedScopes.filter(
scope => !workflow.includes(scope as WorkflowControlScope)
)
return {
scopes: [...workflow, ...derived] as EffectiveWorkflowControlScope[],
- codexScopeUncertain: projection.eligibility === 'uncertain',
+ codexScopeUncertain: verdict.projection.eligibility === 'uncertain',
}
}
@@ -1152,24 +1151,15 @@ export class WorkflowReconciler {
}
const codexView = await this.refreshCodexSnapshot()
- const agent = resolveEagerSdkMcpHostAgent(spec)
- const context = this.resolveCodexContext(recipeUid, recipeName, runtimeScopeRecipeName)
- // R4-B1: the binding and the "was this decidable?" signal come from the
- // same call. Deriving the second from `codexView.readOk` made a readable
- // but malformed ConfigMap look decidable here while the scope path called
- // it uncertain, and a binding-less v3 configure then wiped the live one.
- const codexResolution =
- agent?.provider && agent.model
- ? resolveSdkOnlyCodexBinding({
- provider: agent.provider,
- model: agent.model,
- connectionKey: context.connectionKey,
- configMap: codexView.configMap,
- log: this.log,
- })
- : null
- const codexBinding = codexResolution?.binding ?? null
- const codexBindingUndecidable = codexResolution?.eligibility === 'uncertain'
+ // One verdict per pass. Scope, binding and the configure skip are fields of
+ // this object, not three derivations that must be kept in agreement.
+ const codexVerdict = this.codexVerdictFor(
+ spec,
+ recipeUid,
+ recipeName,
+ runtimeScopeRecipeName,
+ codexView
+ )
const runtime = deriveWorkflowRuntimePlan(spec, {
recipeName,
@@ -1188,7 +1178,7 @@ export class WorkflowReconciler {
runtimeScopeRecipeName,
spec,
runtime,
- { mcpHostPhase, codexBinding, codexBindingUndecidable }
+ { mcpHostPhase, codexVerdict }
)
const bootstrapProof = this.pluginWorkloadSdkProvisioner.getBootstrapProof(recipeName)
switch (status) {
@@ -1635,33 +1625,18 @@ 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(
+ // R5-N1: one verdict, computed from the view this pass captured.
+ // Resolving the binding inside the provisioner (after its own awaits)
+ // let a concurrently-reconciled recipe's failed refresh hand over a
+ // null binding that read as decidable — a binding-less v3 configure
+ // that wipes the live host binding.
+ const eagerCodexVerdict = this.codexVerdictFor(
+ spec,
recipeUid,
recipeName,
- runtimeScopeRecipeName
+ runtimeScopeRecipeName,
+ this.codexView
)
- // R4-B1: see the sibling call above — one resolution answers both
- // "which binding?" and "was the catalog decidable?".
- const eagerCodexResolution =
- eagerAgent?.provider && eagerAgent.model
- ? resolveSdkOnlyCodexBinding({
- provider: eagerAgent.provider,
- model: eagerAgent.model,
- connectionKey: eagerCodexContext.connectionKey,
- configMap: eagerCodexView.configMap,
- log: this.log,
- })
- : null
- const eagerCodexBinding = eagerCodexResolution?.binding ?? null
- const eagerCodexBindingUndecidable = eagerCodexResolution?.eligibility === 'uncertain'
const eagerStatus = await this.pluginWorkloadSdkProvisioner.ensureEagerSdkMcpHost(
recipeName,
recipeUid,
@@ -1669,11 +1644,7 @@ export class WorkflowReconciler {
runtimeScopeRecipeName,
spec,
runtime,
- {
- mcpHostPhase,
- codexBinding: eagerCodexBinding,
- codexBindingUndecidable: eagerCodexBindingUndecidable,
- }
+ { mcpHostPhase, codexVerdict: eagerCodexVerdict }
)
const eagerBootstrapProof =
this.pluginWorkloadSdkProvisioner.getBootstrapProof(recipeName)
@@ -1912,7 +1883,8 @@ export class WorkflowReconciler {
recipeName,
runtimeScopeRecipeName,
spec,
- recipeUid
+ recipeUid,
+ this.codexVerdictFor(spec, recipeUid, recipeName, runtimeScopeRecipeName, this.codexView)
)
}
@@ -2713,13 +2685,14 @@ export class WorkflowReconciler {
pluginWorkloadSdkEnabled: this.deps.config.pluginWorkloadSdkEnabled,
})
if (!runtime.mcpHost.required) return
- await this.refreshCodexSnapshot()
+ const codexView = await this.refreshCodexSnapshot()
await this.ensureMcpHostSecrets(
recipeNamespace,
recipeName,
runtimeScopeRecipeName,
spec,
- recipeUid
+ recipeUid,
+ this.codexVerdictFor(spec, recipeUid ?? '', recipeName, runtimeScopeRecipeName, codexView)
)
}
@@ -2944,12 +2917,13 @@ export class WorkflowReconciler {
// triggered. The artifact-reader/snippet-runner stay run-only.
const mcpHostLaneLive = !awaitsTriggeredRun || eagerSdkMcpHost
const includeMcpHost = runtime.network.includeMcpHost && mcpHostLaneLive
- const codexProjection = this.projectCodex(
+ const codexProjection = this.codexVerdictFor(
spec,
recipeUid,
recipeName,
- this.resolveCodexContext(recipeUid, recipeName, recipeName).runtimeScopeRecipeName
- )
+ this.resolveCodexContext(recipeUid, recipeName, recipeName).runtimeScopeRecipeName,
+ this.codexView
+ ).projection
const npConfig: NetworkPolicyConfig = {
recipeName,
sandboxNamespace: this.deps.config.sandboxNamespace,
@@ -3067,12 +3041,13 @@ export class WorkflowReconciler {
}
const policyNames = new Set(policies.map(policy => policy.metadata?.name))
const codexProxyPolicyName = `${recipeName}-mcp-host-to-codex-proxy`
- const codexProjection = this.projectCodex(
+ const codexProjection = this.codexVerdictFor(
spec,
recipeUid,
recipeName,
- this.resolveCodexContext(recipeUid, recipeName, recipeName).runtimeScopeRecipeName
- )
+ this.resolveCodexContext(recipeUid, recipeName, recipeName).runtimeScopeRecipeName,
+ this.codexView
+ ).projection
if (!policyNames.has(codexProxyPolicyName) && codexProjection.eligibility !== 'uncertain') {
await this.safeDelete(() =>
this.deps.networkingApi.deleteNamespacedNetworkPolicy({
@@ -3782,14 +3757,13 @@ export class WorkflowReconciler {
recipeName: string,
runtimeScopeRecipeName: string,
spec: WorkflowRecipeSpec,
- recipeUid?: string
+ recipeUid: string | undefined,
+ // R5-B1: the SAME verdict the caller used for the configure decision.
+ // Recomputing it here read `this.codexView` live, so a concurrent refresh
+ // could give the binding one snapshot and the scopes another.
+ codexVerdict: CodexRecipeVerdict
): Promise<McpHostRuntimeTokenRefreshResult> {
- const effectiveScopes = this.resolveEffectiveControlScopes(
- spec,
- recipeUid ?? '',
- recipeName,
- runtimeScopeRecipeName
- )
+ const effectiveScopes = this.resolveEffectiveControlScopes(spec, codexVerdict)
const tokenRefresh = await this.ensureMcpHostRuntimeTokenSecret(
namespace,
recipeName,