Skip to content

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

TypeScript

fix(sdk): close the R4 ledger, lock and capabilities regressions

Alfredo Lopeze5c859ac56e1
diff --git a/control-api/package-lock.json b/control-api/package-lock.json
index 2bae35174..4d43f93f6 100644
--- a/control-api/package-lock.json
+++ b/control-api/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "clerum-control-api",
- "version": "0.1.538",
+ "version": "0.1.541",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "clerum-control-api",
- "version": "0.1.538",
+ "version": "0.1.541",
"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 239e4d542..7a1f768c4 100644
--- a/control-api/package.json
+++ b/control-api/package.json
@@ -1,6 +1,6 @@
{
"name": "clerum-control-api",
- "version": "0.1.538",
+ "version": "0.1.541",
"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 66f5cfca1..7010ae847 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
@@ -612,6 +612,7 @@ async function handlePromptBridgeAuthorization(
attemptGeneration: result.value.attemptGeneration,
policyRevision: result.value.policyRevision,
policyHash: result.value.policyHash,
+ maxOutputTokens: result.value.maxOutputTokens,
})
}
@@ -737,6 +738,14 @@ 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
@@ -765,10 +774,11 @@ export function createMcpHostPluginWorkloadSdkRoutes(): Router {
defaultModel: alignedPrimary?.model ?? null,
defaultConnectionRef: alignedPrimary?.connectionRef ?? null,
v2Ready,
- ...(reservationOnlyOauthBroker ? { reservationOnlyOauthBroker: true } : {}),
+ ...(reservationOnlyOauthBroker
+ ? { reservationOnlyOauthBroker: true, codexBindingRevisions: true }
+ : {}),
...(codexConnection
? {
- codexBindingRevisions: true,
defaultCatalogRevision: codexConnection.catalogRevision,
defaultCredentialRevision: codexConnection.credentialRevision,
}
diff --git a/control-api/src/services/llmProviderAttemptAuthorizer.ts b/control-api/src/services/llmProviderAttemptAuthorizer.ts
index 0eeaaa287..57c9ff148 100644
--- a/control-api/src/services/llmProviderAttemptAuthorizer.ts
+++ b/control-api/src/services/llmProviderAttemptAuthorizer.ts
@@ -325,6 +325,7 @@ export async function authorizeLlmProviderAttempt(
typeof body.pluginWorkloadSdkProviderAttemptId === 'string'
? body.pluginWorkloadSdkProviderAttemptId.trim()
: ''
+ let sdkLinkRecipe: { namespace: string; name: string } | null = null
if (pluginWorkloadSdkProviderAttemptId) {
if (!UUID_RE.test(pluginWorkloadSdkProviderAttemptId)) {
throw new LlmProviderAttemptAuthorizeError(
@@ -344,13 +345,19 @@ export async function authorizeLlmProviderAttempt(
'pluginWorkloadSdkProviderAttemptId does not match the reserved SDK attempt'
)
}
+ sdkLinkRecipe = { namespace: caller.recipeNamespace, name: caller.recipeName }
}
// Recipe authorize and promptBridge finalize share this advisory. Take it
// before budget reservation work so concurrent Codex + fallback cannot
// deadlock (budget rows then advisory vs advisory then spend/invocation).
- if (caller.callerKind === 'recipe' && caller.recipeNamespace && caller.recipeName) {
- await lockPluginWorkloadSdkRecipe(db, caller.recipeNamespace, caller.recipeName)
+ //
+ // R4-M3: only an SDK-linked authorize goes on to take plugin_workload_sdk_*
+ // rows FOR UPDATE, which is the order finalize follows after this advisory.
+ // The workflow lane touches neither, so taking it for every recipe caller
+ // serialized that lane per recipe for no ordering benefit.
+ if (sdkLinkRecipe) {
+ await lockPluginWorkloadSdkRecipe(db, sdkLinkRecipe.namespace, sdkLinkRecipe.name)
}
const presentedReservationId =
diff --git a/control-api/src/services/pluginWorkloadSdkFinalization.ts b/control-api/src/services/pluginWorkloadSdkFinalization.ts
index fbc5d281d..1ba843e13 100644
--- a/control-api/src/services/pluginWorkloadSdkFinalization.ts
+++ b/control-api/src/services/pluginWorkloadSdkFinalization.ts
@@ -478,28 +478,34 @@ export async function finalizePromptBridgeInTransaction(
const linkedCodex = oauthBroker
? await loadLlmProviderAttemptBySdkAttemptId(db, input.providerAttemptId)
: null
- if (oauthBroker && input.status === 'complete' && linkedCodex) {
- if (isLinkedCodexInFlightWithoutUsage(linkedCodex)) {
- throw new PromptBridgeFinalizationError(
- 'ledger_pending',
- 'linked Codex attempt has not finalized usage yet',
- 409,
- true
- )
- }
+ // R4-H1: decided from the linked Codex row, never from the caller-chosen
+ // status. Gating this on `complete` let a `failed` close through while the
+ // Codex call was still inside its usage grace and could bill afterwards.
+ // The replay path (`:314`) and the sweeper already read the linked row
+ // this way; only the fresh path was narrower.
+ if (oauthBroker && linkedCodex && isLinkedCodexInFlightWithoutUsage(linkedCodex)) {
+ throw new PromptBridgeFinalizationError(
+ 'ledger_pending',
+ 'linked Codex attempt has not finalized usage yet',
+ 409,
+ true
+ )
}
const spend = resolvePersistableSpend(input.status, oauthBroker, linkedCodex, input.usage)
// N-17: only point a usage_request_id at a usage_events row that is really
// written. Codex spend is ingested by the proxy finalize, not here.
const willIngestUsage = input.status === 'complete' && !oauthBroker
- // Codex already billed this attempt, so closing the invocation `failed`
- // would leave it revivable (reviveFailedInvocation gates only on
- // status = 'failed') and the same idempotency key could launch a second
- // billable Codex call. provider_unavailable is the non-revivable terminal
- // state for exactly this situation. The RESULT still echoes input.status:
- // mcp-host's controlApiClient requires result.status === body.status.
+ // Closing the invocation `failed` leaves it revivable (reviveFailedInvocation
+ // gates only on status = 'failed'), so the same idempotency key could launch
+ // a second billable Codex call. Only a spend proved `not_executed` — no
+ // linked Codex row at all — is safe to leave revivable. `exact` obviously
+ // billed; `unknown` means we cannot prove it did not, which is the same
+ // hazard (R4-H1, and the invariant pluginWorkloadSdkDb.ts:2118-2122 states).
+ // provider_unavailable is the non-revivable terminal state for both. The
+ // RESULT still echoes input.status: mcp-host's controlApiClient requires
+ // result.status === body.status.
const expectedStatus: PromptBridgeFinalizationStatus =
- oauthBroker && spend.outcome === 'exact' && input.status === 'failed'
+ oauthBroker && input.status === 'failed' && spend.outcome !== 'not_executed'
? 'provider_unavailable'
: input.status
let usageAccepted = false
diff --git a/control-api/src/services/pluginWorkloadSdkSpendLedger.ts b/control-api/src/services/pluginWorkloadSdkSpendLedger.ts
index 8526d8fd7..6123b2b96 100644
--- a/control-api/src/services/pluginWorkloadSdkSpendLedger.ts
+++ b/control-api/src/services/pluginWorkloadSdkSpendLedger.ts
@@ -150,8 +150,15 @@ async function resolvePriorAttemptSpend(
)
}
if (isOauthBrokerProvider(provider)) {
- const exact = linkedCodexExactUsage(await loadLlmProviderAttemptBySdkAttemptId(db, attemptId))
+ const linked = await loadLlmProviderAttemptBySdkAttemptId(db, attemptId)
+ const exact = linkedCodexExactUsage(linked)
if (exact) return { outcome: 'exact', ...exact }
+ // R4-M1: a linked row exists only if authorize-link ran, which means the
+ // host already asked the broker for a ticket — that call may still bill.
+ // `not_executed` is terminal (deriveEffectiveSpend only lifts unknown to
+ // exact), so freezing it here would lose that spend permanently. Same rule
+ // the winner already applies in resolvePersistableSpend.
+ if (linked) return spendFloor('unknown')
}
return spendFloor(status === 'provider_unavailable' ? 'unknown' : 'not_executed')
}
diff --git a/control-api/test/routes.mcp-host.plugin-workload-sdk.test.ts b/control-api/test/routes.mcp-host.plugin-workload-sdk.test.ts
index 737ac09f4..85602f0b1 100644
--- a/control-api/test/routes.mcp-host.plugin-workload-sdk.test.ts
+++ b/control-api/test/routes.mcp-host.plugin-workload-sdk.test.ts
@@ -405,10 +405,13 @@ describe('GET /mcp-host/plugin-workload-sdk/capabilities', () => {
)
})
- it('omits the revision flag entirely when the Codex connection does not resolve', async () => {
- // The flag is a promise to send both values. A revoked or missing
- // connection must drop all three together, never advertise the flag over
- // absent numbers — a host that trusted it would fail closed forever.
+ it('advertises the revision flag without numbers when the Codex connection does not resolve', async () => {
+ // R4-M4. The flag states what this binary can publish, not what this
+ // connection has. Dropping it alongside the numbers made a revoked
+ // connection indistinguishable from an older control-api, so the host
+ // skipped the freshness check precisely when no live connection could back
+ // the binding. Flag present + numbers absent is the host's fail-closed
+ // branch, and failing closed is correct here.
vi.mocked(sdkDb.findGrant).mockResolvedValue(codexGrant())
vi.mocked(codexConnection.getSafeCodexSubscriptionConnection).mockResolvedValue(null)
@@ -418,11 +421,45 @@ describe('GET /mcp-host/plugin-workload-sdk/capabilities', () => {
expect(res.status).toBe(200)
expect(res.body.reservationOnlyOauthBroker).toBe(true)
- expect(res.body.codexBindingRevisions).toBeUndefined()
+ expect(res.body.codexBindingRevisions).toBe(true)
expect(res.body.defaultCatalogRevision).toBeUndefined()
expect(res.body.defaultCredentialRevision).toBeUndefined()
})
+ it('publishes catalog revision 0 for a connected but never-synced connection', async () => {
+ // R4-H3 contract pin. 0 is the schema DEFAULT for catalog_revision, so it
+ // must survive the wire untouched; the host decides readiness from it.
+ vi.mocked(sdkDb.findGrant).mockResolvedValue(codexGrant())
+ vi.mocked(codexConnection.getSafeCodexSubscriptionConnection).mockResolvedValue({
+ id: 'conn-never-synced',
+ connectionKey: 'team-plus',
+ displayName: 'Team Plus',
+ defaultModel: 'gpt-5.1',
+ createdBy: null,
+ status: 'connected',
+ credentialRevision: 1,
+ catalogRevision: 0,
+ accountFingerprint: null,
+ catalogStatus: 'never_synced',
+ catalogSyncedAt: null,
+ lastRefreshAt: null,
+ lastAuthAt: null,
+ refreshLockHeld: false,
+ revokedAt: null,
+ createdAt: new Date('2026-08-03T00:00:00.000Z'),
+ updatedAt: new Date('2026-08-03T00:00:00.000Z'),
+ })
+
+ const res = await request(buildApp())
+ .get('/mcp-host/plugin-workload-sdk/capabilities')
+ .set('Authorization', `Bearer ${issueSdkToken()}`)
+
+ expect(res.status).toBe(200)
+ expect(res.body.codexBindingRevisions).toBe(true)
+ expect(res.body.defaultCatalogRevision).toBe(0)
+ expect(res.body.defaultCredentialRevision).toBe(1)
+ })
+
it('does not advertise oauth-broker v3 when promptTargets[0] is not the default', async () => {
vi.mocked(sdkDb.findGrant).mockResolvedValue({
id: 'grant-misaligned-capabilities',
diff --git a/control-api/test/services.llmProviderAttemptAuthorizer.test.ts b/control-api/test/services.llmProviderAttemptAuthorizer.test.ts
index c631ea10d..74d7343f9 100644
--- a/control-api/test/services.llmProviderAttemptAuthorizer.test.ts
+++ b/control-api/test/services.llmProviderAttemptAuthorizer.test.ts
@@ -223,6 +223,23 @@ describe('authorizeLlmProviderAttempt', () => {
expect(current.insertAttempt).not.toHaveBeenCalled()
})
+ it('does not take the recipe advisory lock for a recipe caller without an SDK attempt link', async () => {
+ // R4-M3. Only an SDK-linked authorize goes on to take plugin_workload_sdk_*
+ // rows FOR UPDATE, which is the order finalize follows after this advisory.
+ // Taking it for every recipe caller serialized the workflow lane per recipe
+ // for no ordering benefit.
+ await authorizeLlmProviderAttempt(
+ claims({
+ recipeNamespace: 'sandbox-recipes',
+ recipeName: 'prompt-notify',
+ hostRefs: ['sandbox-recipes/prompt-notify'],
+ }),
+ body(),
+ current
+ )
+ expect(lockPluginWorkloadSdkRecipe).not.toHaveBeenCalled()
+ })
+
it('binds a reserved Plugin Workload SDK attempt onto the Codex ledger row', async () => {
const sdkAttemptId = '44444444-4444-4444-8444-444444444444'
getPluginWorkloadSdkProviderAttemptForUpdate.mockResolvedValue(
diff --git a/control-api/test/services.pluginWorkloadSdkFinalization.test.ts b/control-api/test/services.pluginWorkloadSdkFinalization.test.ts
index b506e9b99..c6f2c1239 100644
--- a/control-api/test/services.pluginWorkloadSdkFinalization.test.ts
+++ b/control-api/test/services.pluginWorkloadSdkFinalization.test.ts
@@ -1361,6 +1361,66 @@ describe('spend floor writers (Addendum A.4 "best-floor")', () => {
expect(updateParams(db, 'plugin_workload_sdk_invocations')?.[1]).toBe('failed')
})
+ // R4-H1. The ledger_pending gate was keyed on `input.status === 'complete'`,
+ // so a host closing `failed` walked past a Codex call still inside its usage
+ // grace. `failed` is what reviveFailedInvocation reopens, so the same
+ // idempotency key could launch a second billable Codex call while the first
+ // was still able to bill.
+ const codexInFlight = {
+ status: 'authorized',
+ outcome: null,
+ usage_input_tokens: null,
+ usage_output_tokens: null,
+ } as const
+
+ it('refuses a Codex failed close while the linked attempt is still in flight', async () => {
+ ingest.mockReset()
+ project.mockReset()
+ const db = dbWithRows(
+ [],
+ [],
+ ...codexFence('in_progress'),
+ linkedCodexRow({ ...codexInFlight, created_at: new Date() })
+ )
+
+ await expect(
+ finalizePromptBridgeInTransaction(
+ { ...codexInput, status: 'failed', reason: 'provider_error' },
+ db as never
+ )
+ ).rejects.toMatchObject({ code: 'ledger_pending', httpStatus: 409, retryable: true })
+ expect(updateParams(db, 'plugin_workload_sdk_invocations')).toBeUndefined()
+ })
+
+ it('closes a Codex failed attempt whose linked row aged out without usage as provider_unavailable', async () => {
+ // Past the grace window there is no ledger_pending left to raise, but the
+ // call may still have billed. Only a spend proved `not_executed` — no
+ // linked Codex row at all — is safe to leave revivable.
+ ingest.mockReset()
+ project.mockReset()
+ const db = dbWithRows(
+ [],
+ [],
+ ...codexFence('in_progress'),
+ linkedCodexRow({ ...codexInFlight, created_at: new Date(Date.now() - 20 * 60_000) }),
+ { rows: [], rowCount: 1 },
+ { rows: [], rowCount: 1 },
+ { rows: [], rowCount: 1 },
+ codexSpendRow({ outcome: 'unknown' })
+ )
+
+ const result = await finalizePromptBridgeInTransaction(
+ { ...codexInput, status: 'failed', reason: 'provider_error' },
+ db as never
+ )
+
+ // The RESULT still echoes the caller's status — mcp-host asserts
+ // result.status === body.status — while the persisted invocation state is
+ // the non-revivable one.
+ expect(result).toMatchObject({ status: 'failed', outcome: 'unknown' })
+ expect(updateParams(db, 'plugin_workload_sdk_invocations')?.[1]).toBe('provider_unavailable')
+ })
+
it('refuses to promote a Codex row that errored with usage or reported a partial token pair', async () => {
for (const linked of [
linkedCodexRow({ outcome: 'error' }),
@@ -1728,6 +1788,60 @@ describe('prior provider attempt settlement (RP-539-003)', () => {
])
})
+ it('freezes unknown for a displaced Codex attempt whose linked row carries no usage yet', async () => {
+ // R4-M1. `not_executed` is terminal — deriveEffectiveSpend only lifts
+ // `unknown` to `exact` — so freezing it over a linked row that can still
+ // bill loses that spend permanently. A linked row exists only if
+ // authorize-link ran, which is already "asked the broker for a ticket".
+ const db = dbWithRows(
+ [],
+ [],
+ ...fenceRows({
+ attempt_index: 2,
+ target_ref: CODEX_TARGET.targetRef,
+ provider: CODEX_TARGET.provider,
+ model: CODEX_TARGET.model,
+ credential_slot: CODEX_TARGET.credentialSlot,
+ }),
+ linkedCodexRow(),
+ { rows: [], rowCount: 1 },
+ { rows: [], rowCount: 1 },
+ { rows: [], rowCount: 1 },
+ codexSpendRow({ attempt_index: 2, outcome: 'exact', input_tokens: 12, output_tokens: 7 }),
+ [
+ {
+ ...priorAttemptRow('failed'),
+ target_ref: CODEX_TARGET.targetRef,
+ provider: CODEX_TARGET.provider,
+ model: CODEX_TARGET.model,
+ credential_slot: CODEX_TARGET.credentialSlot,
+ },
+ ],
+ linkedCodexRow({
+ id: '55555555-5555-4555-8555-555555555555',
+ plugin_workload_sdk_provider_attempt_id: PRIOR_ATTEMPT_ID,
+ status: 'authorized',
+ outcome: null,
+ usage_input_tokens: null,
+ usage_output_tokens: null,
+ }),
+ spendRow({ provider_attempt_id: PRIOR_ATTEMPT_ID, outcome: 'unknown' })
+ )
+
+ await finalizePromptBridgeInTransaction(winner, db as never)
+
+ const inserts = db.query.mock.calls.filter(([statement]: [string]) =>
+ statement.includes('INSERT INTO plugin_workload_sdk_spend_outcomes')
+ )
+ expect((inserts[1]?.[1] as unknown[])?.slice(11, 16)).toEqual([
+ 'unknown',
+ 'prior_attempt_failed',
+ null,
+ null,
+ null,
+ ])
+ })
+
it('fails loudly when a displaced attempt is not terminal', async () => {
// reservePluginWorkloadSdkProviderAttempt cannot hand out index 2 over a
// non-terminal index 1, so this is a broken fence, not a tolerable case.
diff --git a/mcp-host/package-lock.json b/mcp-host/package-lock.json
index 006bedfb5..152eba93b 100644
--- a/mcp-host/package-lock.json
+++ b/mcp-host/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "clerum-mcp-host",
- "version": "0.1.313",
+ "version": "0.1.315",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "clerum-mcp-host",
- "version": "0.1.313",
+ "version": "0.1.315",
"license": "SEE LICENSE IN LICENSE",
"dependencies": {
"@anthropic-ai/sdk": "^0.32.0",
diff --git a/mcp-host/package.json b/mcp-host/package.json
index f174fb25d..f3b8b5f24 100644
--- a/mcp-host/package.json
+++ b/mcp-host/package.json
@@ -1,6 +1,6 @@
{
"name": "clerum-mcp-host",
- "version": "0.1.313",
+ "version": "0.1.315",
"description": "MCP Host - reads Host CRD and provides LLM access via OpenAI/Claude",
"main": "dist/main.js",
"engines": {
diff --git a/mcp-host/src/llm/codexPolicyBinding.ts b/mcp-host/src/llm/codexPolicyBinding.ts
index 520f731c0..46d755f16 100644
--- a/mcp-host/src/llm/codexPolicyBinding.ts
+++ b/mcp-host/src/llm/codexPolicyBinding.ts
@@ -50,7 +50,9 @@ export function resolveCodexAttemptPolicy(input: {
!Number.isInteger(binding.catalogRevision) ||
binding.catalogRevision < 1 ||
!Number.isInteger(binding.credentialRevision) ||
- binding.credentialRevision < 0
+ // CHECK (credential_revision >= 1) in codex_subscription_connections.
+ // catalogRevision >= 1 above is a binding invariant, not a row one.
+ binding.credentialRevision < 1
) {
return null
}
diff --git a/mcp-host/src/pluginWorkloadSdk/promptBridge/controlApiClient.test.ts b/mcp-host/src/pluginWorkloadSdk/promptBridge/controlApiClient.test.ts
index 722b6353a..b9b8dc7ff 100644
--- a/mcp-host/src/pluginWorkloadSdk/promptBridge/controlApiClient.test.ts
+++ b/mcp-host/src/pluginWorkloadSdk/promptBridge/controlApiClient.test.ts
@@ -34,6 +34,9 @@ function authorizedBody(invocationId: string) {
attemptGeneration: 1,
policyRevision: 2,
policyHash: 'a'.repeat(64),
+ // R4-H2: the field is required on the wire again. `null` is "this grant
+ // sets no ceiling", which is the default these fixtures describe.
+ maxOutputTokens: null,
}
}
@@ -338,6 +341,73 @@ describe('PluginWorkloadSdkControlApiClient', () => {
).resolves.toMatchObject({ policyReady: true, codexBindingReady: true })
})
+ // R4-H3 / R4-M5: the hand-built fixtures only ever used catalog revisions
+ // {4,5,7,999} and never 0 — which is the schema DEFAULT for a never-synced
+ // catalog and exactly the value the inverted bounds rejected. These pin the
+ // real CHECK constraints of codex_subscription_connections:
+ // catalog_revision BIGINT NOT NULL DEFAULT 0 CHECK (>= 0)
+ // credential_revision BIGINT NOT NULL DEFAULT 1 CHECK (>= 1)
+ it('accepts a never-synced peer publishing catalog revision 0 and reports the binding not ready', async () => {
+ installCodexBinding()
+ const fetchImpl = vi.fn().mockResolvedValue(
+ jsonResponse(
+ 200,
+ codexCapabilities({
+ codexBindingRevisions: true,
+ defaultCatalogRevision: 0,
+ defaultCredentialRevision: 1,
+ })
+ )
+ )
+ const client = makeClient(fetchImpl as unknown as typeof fetch)
+
+ await expect(
+ client.verifyPromptBridgeBootstrapV2('codex-subscription', 'gpt-5.1')
+ ).resolves.toMatchObject({
+ policyReady: false,
+ policyReason: 'codex_execution_binding_missing',
+ codexBindingReady: false,
+ })
+ })
+
+ it('rejects a credential revision below the schema floor as a protocol mismatch', async () => {
+ installCodexBinding()
+ const fetchImpl = vi.fn().mockResolvedValue(
+ jsonResponse(
+ 200,
+ codexCapabilities({
+ codexBindingRevisions: true,
+ defaultCatalogRevision: 4,
+ defaultCredentialRevision: 0,
+ })
+ )
+ )
+ const client = makeClient(fetchImpl as unknown as typeof fetch)
+
+ await expect(
+ client.verifyPromptBridgeBootstrapV2('codex-subscription', 'gpt-5.1')
+ ).rejects.toMatchObject({ code: 'protocol_mismatch' })
+ })
+
+ it('refuses the binding when the peer claims revisions but omits both', async () => {
+ // R4-M4: a revoked or absent connection now keeps the flag and drops only
+ // the numbers, so this is the branch a live control-api takes for a
+ // connection that cannot back any binding.
+ installCodexBinding()
+ const fetchImpl = vi
+ .fn()
+ .mockResolvedValue(jsonResponse(200, codexCapabilities({ codexBindingRevisions: true })))
+ const client = makeClient(fetchImpl as unknown as typeof fetch)
+
+ await expect(
+ client.verifyPromptBridgeBootstrapV2('codex-subscription', 'gpt-5.1')
+ ).resolves.toMatchObject({
+ policyReady: false,
+ policyReason: 'codex_execution_binding_missing',
+ codexBindingReady: false,
+ })
+ })
+
it('keeps request-time policy readiness separate from identity bootstrap', async () => {
const fetchImpl = vi.fn().mockResolvedValue(
jsonResponse(200, {
diff --git a/mcp-host/src/pluginWorkloadSdk/promptBridge/controlApiClient.ts b/mcp-host/src/pluginWorkloadSdk/promptBridge/controlApiClient.ts
index dac54c986..13a45354a 100644
--- a/mcp-host/src/pluginWorkloadSdk/promptBridge/controlApiClient.ts
+++ b/mcp-host/src/pluginWorkloadSdk/promptBridge/controlApiClient.ts
@@ -51,6 +51,13 @@ export interface AuthorizePromptBridgeResponse {
attemptGeneration: number
policyRevision: number
policyHash: string
+ /**
+ * Per-grant output ceiling, or null when the grant sets none. Enforced as
+ * `max_tokens` on API-key providers; codex-subscription cannot bind it on
+ * the ChatGPT wire, where the contract's LIMITS.maxOutputTokens is the only
+ * bound (R4-H2).
+ */
+ maxOutputTokens: number | null
}
export interface PluginWorkloadSdkCapabilities {
@@ -193,7 +200,12 @@ function isAuthorizePromptBridgeResponse(v: unknown): v is AuthorizePromptBridge
Number.isInteger(r.policyRevision) &&
(r.policyRevision as number) >= 1 &&
typeof r.policyHash === 'string' &&
- /^[a-f0-9]{64}$/.test(r.policyHash)
+ /^[a-f0-9]{64}$/.test(r.policyHash) &&
+ // R4-H2: a grant cap of 0 is not "no cap" — it would clamp every response
+ // to nothing. Reject it here rather than let Math.min silently zero the
+ // request.
+ (r.maxOutputTokens === null ||
+ (Number.isInteger(r.maxOutputTokens) && Number(r.maxOutputTokens) >= 1))
)
}
@@ -220,12 +232,18 @@ function isPluginWorkloadSdkCapabilities(v: unknown): v is PluginWorkloadSdkCapa
typeof value.v2Ready === 'boolean' &&
(value.reservationOnlyOauthBroker === undefined || value.reservationOnlyOauthBroker === true) &&
(value.codexBindingRevisions === undefined || value.codexBindingRevisions === true) &&
+ // R4-H3: bounds mirror the codex_subscription_connections CHECKs —
+ // `catalog_revision BIGINT NOT NULL DEFAULT 0 CHECK (>= 0)` and
+ // `credential_revision BIGINT NOT NULL DEFAULT 1 CHECK (>= 1)`. These were
+ // inverted, so a connection whose catalog was never synced (revision 0,
+ // the DEFAULT) failed the whole capabilities contract with
+ // protocol_mismatch instead of resolving to codexBindingReady: false.
(value.defaultCatalogRevision === undefined ||
(Number.isInteger(value.defaultCatalogRevision) &&
- Number(value.defaultCatalogRevision) >= 1)) &&
+ Number(value.defaultCatalogRevision) >= 0)) &&
(value.defaultCredentialRevision === undefined ||
(Number.isInteger(value.defaultCredentialRevision) &&
- Number(value.defaultCredentialRevision) >= 0)) &&
+ Number(value.defaultCredentialRevision) >= 1)) &&
typeof value.clientNotificationsPolicyState === 'string' &&
typeof value.clientNotificationsReady === 'boolean'
)
diff --git a/mcp-host/src/pluginWorkloadSdk/promptBridge/llmBridge.failover.test.ts b/mcp-host/src/pluginWorkloadSdk/promptBridge/llmBridge.failover.test.ts
index c5b95924d..0b1db788b 100644
--- a/mcp-host/src/pluginWorkloadSdk/promptBridge/llmBridge.failover.test.ts
+++ b/mcp-host/src/pluginWorkloadSdk/promptBridge/llmBridge.failover.test.ts
@@ -597,12 +597,12 @@ describe('LlmBridge authorized multi-provider fallback', () => {
replaceSdkOnlyCodexBinding({
connectionKey: 'team-plus',
catalogRevision: 1,
- credentialRevision: 0,
+ credentialRevision: 1,
model: 'gpt-5.1',
bindingHash: computeCodexPolicyHash({
model: 'gpt-5.1',
catalogRevision: 1,
- credentialRevision: 0,
+ credentialRevision: 1,
connectionKey: 'team-plus',
}),
})
@@ -692,12 +692,12 @@ describe('LlmBridge authorized multi-provider fallback', () => {
replaceSdkOnlyCodexBinding({
connectionKey: 'team-plus',
catalogRevision: 1,
- credentialRevision: 0,
+ credentialRevision: 1,
model: 'gpt-5.1',
bindingHash: computeCodexPolicyHash({
model: 'gpt-5.1',
catalogRevision: 1,
- credentialRevision: 0,
+ credentialRevision: 1,
connectionKey: 'team-plus',
}),
})
@@ -800,12 +800,12 @@ function installCodexBinding(): void {
replaceSdkOnlyCodexBinding({
connectionKey: 'team-plus',
catalogRevision: 1,
- credentialRevision: 0,
+ credentialRevision: 1,
model: codexTarget.model,
bindingHash: computeCodexPolicyHash({
model: codexTarget.model,
catalogRevision: 1,
- credentialRevision: 0,
+ credentialRevision: 1,
connectionKey: 'team-plus',
}),
})
diff --git a/mcp-host/src/pluginWorkloadSdk/sdkOnlyCodexBinding.ts b/mcp-host/src/pluginWorkloadSdk/sdkOnlyCodexBinding.ts
index 3b6e8e0e5..b93886885 100644
--- a/mcp-host/src/pluginWorkloadSdk/sdkOnlyCodexBinding.ts
+++ b/mcp-host/src/pluginWorkloadSdk/sdkOnlyCodexBinding.ts
@@ -53,7 +53,11 @@ export function isPluginWorkloadSdkCodexBindingProof(
Number.isInteger(candidate.catalogRevision) &&
Number(candidate.catalogRevision) >= 1 &&
Number.isInteger(candidate.credentialRevision) &&
- Number(candidate.credentialRevision) >= 0 &&
+ // `credential_revision` is CHECK (>= 1) in codex_subscription_connections.
+ // `catalogRevision >= 1` above is a binding invariant rather than a row
+ // one: a proof is only minted for an eligible catalog, and the sole writer
+ // of catalog_status='ready' bumps catalog_revision in the same UPDATE.
+ Number(candidate.credentialRevision) >= 1 &&
typeof candidate.model === 'string' &&
candidate.model.trim().length > 0 &&
typeof candidate.bindingHash === 'string' &&
diff --git a/workflow-recipes/package-lock.json b/workflow-recipes/package-lock.json
index 0d2273a9f..94d2451be 100644
--- a/workflow-recipes/package-lock.json
+++ b/workflow-recipes/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "workload-recipes-controller",
- "version": "0.1.329",
+ "version": "0.1.332",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "workload-recipes-controller",
- "version": "0.1.329",
+ "version": "0.1.332",
"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 83f779fea..acce42898 100644
--- a/workflow-recipes/package.json
+++ b/workflow-recipes/package.json
@@ -1,6 +1,6 @@
{
"name": "workload-recipes-controller",
- "version": "0.1.329",
+ "version": "0.1.332",
"description": "Workload Recipes Controller (WRC) - WorkloadRecipe lifecycle management and MCP server interface",
"main": "dist/main.js",
"engines": {
diff --git a/workflow-recipes/src/workflow/sdkOnlyCodexBinding.ts b/workflow-recipes/src/workflow/sdkOnlyCodexBinding.ts
index 4b0cce4ab..2f3db27ff 100644
--- a/workflow-recipes/src/workflow/sdkOnlyCodexBinding.ts
+++ b/workflow-recipes/src/workflow/sdkOnlyCodexBinding.ts
@@ -28,7 +28,11 @@ export function isPluginWorkloadSdkCodexBindingProof(
Number.isInteger(candidate.catalogRevision) &&
Number(candidate.catalogRevision) >= 1 &&
Number.isInteger(candidate.credentialRevision) &&
- Number(candidate.credentialRevision) >= 0 &&
+ // `credential_revision` is CHECK (>= 1) in codex_subscription_connections.
+ // `catalogRevision >= 1` above is a binding invariant rather than a row
+ // one: a proof is only minted for an eligible catalog, and the sole writer
+ // of catalog_status='ready' bumps catalog_revision in the same UPDATE.
+ Number(candidate.credentialRevision) >= 1 &&
typeof candidate.model === 'string' &&
candidate.model.trim().length > 0 &&
typeof candidate.bindingHash === 'string' &&
@@ -66,12 +70,17 @@ export function sanitizePluginWorkloadSdkCodexBindingProof(
}
}
+/**
+ * R4-L1: `model` is REQUIRED. It used to be optional and the model pin was
+ * skipped when omitted, so a caller that forgot it would accept a binding for
+ * another model. mcp-host's twin has always required it; the two now agree.
+ */
export function readVerifiedSdkOnlyCodexBinding(
value: unknown,
- model?: string
+ model: string
): PluginWorkloadSdkCodexBindingProof | null {
if (!isPluginWorkloadSdkCodexBindingProof(value)) return null
- if (model !== undefined && value.model !== model) return null
+ if (value.model !== model) return null
if (!verifySdkOnlyCodexBindingHash(value)) return null
return sanitizePluginWorkloadSdkCodexBindingProof(value)
}
@@ -86,28 +95,66 @@ export function readVerifiedSdkOnlyCodexBinding(
* connection is not `connected`, the catalog is stale, or the selected model
* is not in the assigned connection's catalog.
*/
-export function deriveSdkOnlyCodexBinding(input: {
+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 }
-}): PluginWorkloadSdkCodexBindingProof | null {
- if (input.provider !== CODEX_PROVIDER) return null
+}): 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 < 0) {
+ 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: binding ? 'revision_out_of_range' : reason,
+ reason: withheldReason,
})
- return null
+ 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: {
+ connectionKey: string
+ catalogRevision: number
+ credentialRevision: number
+ model: string
+}): PluginWorkloadSdkCodexBindingProof {
return {
connectionKey: binding.connectionKey,
catalogRevision: binding.catalogRevision,