Skip to content

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

TypeScript

fix: close jozer Codex ledger and configure wedges

Alfredo Lopezfff2000c863f
diff --git a/codex-llm-proxy/src/codexTransport.ts b/codex-llm-proxy/src/codexTransport.ts
index 806605d8a..27688dc43 100644
--- a/codex-llm-proxy/src/codexTransport.ts
+++ b/codex-llm-proxy/src/codexTransport.ts
@@ -290,7 +290,9 @@ function toUpstreamPayload(request: CodexCompletionRequestV1): Record<string, un
// ChatGPT `/codex/responses` rejects sampling fields that Chat Completions
// treats as portable. Keep them on CodexCompletionRequestV1 (authorize hash)
// and omit them on the upstream wire. The CLI Codex client also omits
- // max_output_tokens / temperature.
+ // max_output_tokens / temperature. The authorize hash still carries
+ // generation.maxOutputTokens as request identity; this wire cannot enforce
+ // that cap. Do not restore the fields here.
if (request.generation?.toolChoice) {
payload.tool_choice = request.generation.toolChoice
}
diff --git a/control-api/package-lock.json b/control-api/package-lock.json
index 49592ae27..f33b73361 100644
--- a/control-api/package-lock.json
+++ b/control-api/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "clerum-control-api",
- "version": "0.1.533",
+ "version": "0.1.534",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "clerum-control-api",
- "version": "0.1.533",
+ "version": "0.1.534",
"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 4e36c1aca..61aa2e9fb 100644
--- a/control-api/package.json
+++ b/control-api/package.json
@@ -1,6 +1,6 @@
{
"name": "clerum-control-api",
- "version": "0.1.533",
+ "version": "0.1.534",
"description": "Internal Clerum control plane REST API + UI for managing CRDs and secrets",
"main": "dist/main.js",
"engines": {
diff --git a/control-api/src/services/llmProviderAttemptAuthorizer.ts b/control-api/src/services/llmProviderAttemptAuthorizer.ts
index d78223358..0eeaaa287 100644
--- a/control-api/src/services/llmProviderAttemptAuthorizer.ts
+++ b/control-api/src/services/llmProviderAttemptAuthorizer.ts
@@ -321,6 +321,38 @@ export async function authorizeLlmProviderAttempt(
)
}
+ const pluginWorkloadSdkProviderAttemptId =
+ typeof body.pluginWorkloadSdkProviderAttemptId === 'string'
+ ? body.pluginWorkloadSdkProviderAttemptId.trim()
+ : ''
+ if (pluginWorkloadSdkProviderAttemptId) {
+ if (!UUID_RE.test(pluginWorkloadSdkProviderAttemptId)) {
+ throw new LlmProviderAttemptAuthorizeError(
+ 'invalid_request',
+ 'pluginWorkloadSdkProviderAttemptId must be a UUID'
+ )
+ }
+ if (caller.callerKind === 'host') {
+ throw new LlmProviderAttemptAuthorizeError(
+ 'no_grant',
+ 'host Codex chat cannot bind a Plugin Workload SDK provider attempt'
+ )
+ }
+ if (!caller.recipeNamespace || !caller.recipeName) {
+ throw new LlmProviderAttemptAuthorizeError(
+ 'no_grant',
+ 'pluginWorkloadSdkProviderAttemptId does not match the reserved SDK attempt'
+ )
+ }
+ }
+
+ // 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)
+ }
+
const presentedReservationId =
typeof body.budgetReservationId === 'string' ? body.budgetReservationId.trim() : ''
let budgetReservationId = presentedReservationId || 'unbudgeted'
@@ -365,10 +397,6 @@ export async function authorizeLlmProviderAttempt(
budgetReservationId = budget.reservationIds?.[0] ?? 'unbudgeted'
}
- const pluginWorkloadSdkProviderAttemptId =
- typeof body.pluginWorkloadSdkProviderAttemptId === 'string'
- ? body.pluginWorkloadSdkProviderAttemptId.trim()
- : ''
const presentedTargetRef = typeof body.targetRef === 'string' ? body.targetRef.trim() : ''
let reservedSdkAttemptToPromote: {
id: string
@@ -381,25 +409,6 @@ export async function authorizeLlmProviderAttempt(
targetRef: string
} | null = null
if (pluginWorkloadSdkProviderAttemptId) {
- if (!UUID_RE.test(pluginWorkloadSdkProviderAttemptId)) {
- throw new LlmProviderAttemptAuthorizeError(
- 'invalid_request',
- 'pluginWorkloadSdkProviderAttemptId must be a UUID'
- )
- }
- if (caller.callerKind === 'host') {
- throw new LlmProviderAttemptAuthorizeError(
- 'no_grant',
- 'host Codex chat cannot bind a Plugin Workload SDK provider attempt'
- )
- }
- if (!caller.recipeNamespace || !caller.recipeName) {
- throw new LlmProviderAttemptAuthorizeError(
- 'no_grant',
- 'pluginWorkloadSdkProviderAttemptId does not match the reserved SDK attempt'
- )
- }
- await lockPluginWorkloadSdkRecipe(db, caller.recipeNamespace, caller.recipeName)
const sdkAttempt = await getPluginWorkloadSdkProviderAttemptForUpdate(
pluginWorkloadSdkProviderAttemptId,
db
diff --git a/control-api/src/services/llmProviderAttemptStore.ts b/control-api/src/services/llmProviderAttemptStore.ts
index 326701aa6..fa31f04c5 100644
--- a/control-api/src/services/llmProviderAttemptStore.ts
+++ b/control-api/src/services/llmProviderAttemptStore.ts
@@ -41,16 +41,38 @@ export function isLinkedCodexUsageReady(
return row.outcome === 'success' && row.usageInputTokens != null && row.usageOutputTokens != null
}
+/**
+ * How long an authorized/redeemed Codex row may block SDK spend freeze.
+ * After this, usage is treated as never arriving so the sweeper can close
+ * the invocation. `finalized` is always terminal: ingest will not add tokens.
+ */
+export const CODEX_IN_FLIGHT_USAGE_GRACE_MS = 15 * 60 * 1000
+
/** Linked Codex still owns exact usage; sweepers must not freeze SDK spend. */
export function isLinkedCodexInFlightWithoutUsage(
- row: Pick<LlmProviderAttemptRow, 'status' | 'outcome' | 'usageInputTokens' | 'usageOutputTokens'>
+ row: Pick<
+ LlmProviderAttemptRow,
+ 'status' | 'outcome' | 'usageInputTokens' | 'usageOutputTokens'
+ > & {
+ createdAt?: Date | string | null
+ },
+ nowMs = Date.now()
): boolean {
if (isLinkedCodexUsageReady(row)) return false
- return (
- row.status === 'authorized' ||
- row.status === 'redeemed' ||
- (row.status === 'finalized' && row.outcome === 'success')
- )
+ // Finalized rows never receive a later usage frame. Treating usage-less
+ // success as in-flight wedges complete behind ledger_pending forever.
+ if (row.status === 'finalized') return false
+ if (row.status !== 'authorized' && row.status !== 'redeemed') return false
+ const created =
+ row.createdAt instanceof Date
+ ? row.createdAt.getTime()
+ : row.createdAt
+ ? Date.parse(String(row.createdAt))
+ : Number.NaN
+ if (Number.isFinite(created) && nowMs - created > CODEX_IN_FLIGHT_USAGE_GRACE_MS) {
+ return false
+ }
+ return true
}
export async function applyLlmProviderAttemptSchema(db: DbClient): Promise<void> {
diff --git a/control-api/src/services/pluginWorkloadSdkDb.ts b/control-api/src/services/pluginWorkloadSdkDb.ts
index dc51b0dde..4f8d97f27 100644
--- a/control-api/src/services/pluginWorkloadSdkDb.ts
+++ b/control-api/src/services/pluginWorkloadSdkDb.ts
@@ -2174,8 +2174,9 @@ export async function failStaleInvocationsInTransaction(
break
}
}
- // Codex still owns exact usage. Leave the invocation leased so finalize
- // can 409 ledger_pending instead of freezing an unknown spend row.
+ // Codex still owns exact usage within the in-flight grace. Leave the
+ // invocation leased so finalize can 409 ledger_pending. After the grace,
+ // or once Codex finalizes without tokens, unknown spend is the honest close.
if (linkedCodexInFlight) continue
const marked = await db.query(
diff --git a/control-api/src/services/pluginWorkloadSdkFinalization.ts b/control-api/src/services/pluginWorkloadSdkFinalization.ts
index 9534a9ef6..fa3281a60 100644
--- a/control-api/src/services/pluginWorkloadSdkFinalization.ts
+++ b/control-api/src/services/pluginWorkloadSdkFinalization.ts
@@ -216,24 +216,81 @@ type SpendOutcomeRow = {
output_tokens: number | string | null
}
+function spendBindingMatches(row: SpendOutcomeRow, input: PromptBridgeFinalizationInput): boolean {
+ return (
+ row.invocation_id === input.invocationId &&
+ row.recipe_namespace === input.recipeNamespace &&
+ row.recipe_name === input.recipeName &&
+ Number(row.attempt_generation) === input.attemptGeneration &&
+ Number(row.attempt_index) === input.providerAttemptIndex &&
+ row.target_ref === input.target.targetRef &&
+ (row.host_ref === null || row.host_ref === input.hostRef) &&
+ row.provider === input.target.provider &&
+ row.model === input.target.model &&
+ row.credential_slot === input.target.credentialSlot
+ )
+}
+
+async function upgradeUnknownOauthSpendToExact(
+ db: DbClient,
+ existing: SpendOutcomeRow,
+ input: PromptBridgeFinalizationInput,
+ linked: Pick<LlmProviderAttemptRow, 'usageInputTokens' | 'usageOutputTokens'>
+): Promise<PromptBridgeFinalizationResult> {
+ assertPersistedAuthModeCredentialRules(existing.provider, input)
+ if (!spendBindingMatches(existing, input)) {
+ throw new PromptBridgeFinalizationError(
+ 'conflict',
+ 'provider attempt was finalized with a different immutable outcome',
+ 409
+ )
+ }
+ const updated = await db.query(
+ `UPDATE plugin_workload_sdk_spend_outcomes
+ SET outcome = 'exact',
+ input_tokens = $2,
+ output_tokens = $3,
+ usage_request_id = COALESCE(usage_request_id, $1)
+ WHERE provider_attempt_id = $1
+ AND outcome = 'unknown'
+ RETURNING provider_attempt_id`,
+ [input.providerAttemptId, linked.usageInputTokens, linked.usageOutputTokens]
+ )
+ if ((updated.rowCount ?? updated.rows.length) !== 1) {
+ const raced = await db.query(
+ `SELECT provider_attempt_id, invocation_id, recipe_namespace, recipe_name,
+ attempt_generation, attempt_index, target_ref, host_ref, provider,
+ model, credential_slot, outcome, input_tokens, output_tokens
+ FROM plugin_workload_sdk_spend_outcomes
+ WHERE provider_attempt_id = $1`,
+ [input.providerAttemptId]
+ )
+ const existingOutcome = raced.rows[0] as SpendOutcomeRow | undefined
+ if (!existingOutcome) {
+ throw new PromptBridgeFinalizationError(
+ 'conflict',
+ 'provider attempt outcome was concurrently finalized but is not readable',
+ 409
+ )
+ }
+ return mapExistingOutcome(existingOutcome, input)
+ }
+ return {
+ invocationId: input.invocationId,
+ providerAttemptId: input.providerAttemptId,
+ status: input.status,
+ outcome: 'exact',
+ idempotent: false,
+ usageAccepted: false,
+ }
+}
+
function mapExistingOutcome(
row: SpendOutcomeRow,
input: PromptBridgeFinalizationInput
): PromptBridgeFinalizationResult {
assertPersistedAuthModeCredentialRules(row.provider, input)
- if (
- row.invocation_id !== input.invocationId ||
- row.recipe_namespace !== input.recipeNamespace ||
- row.recipe_name !== input.recipeName ||
- Number(row.attempt_generation) !== input.attemptGeneration ||
- Number(row.attempt_index) !== input.providerAttemptIndex ||
- row.target_ref !== input.target.targetRef ||
- (row.host_ref !== null && row.host_ref !== input.hostRef) ||
- row.provider !== input.target.provider ||
- row.model !== input.target.model ||
- row.credential_slot !== input.target.credentialSlot ||
- !replayOutcomeCompatible(input, row)
- ) {
+ if (!spendBindingMatches(row, input) || !replayOutcomeCompatible(input, row)) {
throw new PromptBridgeFinalizationError(
'conflict',
'provider attempt was finalized with a different immutable outcome',
@@ -283,11 +340,7 @@ export async function finalizePromptBridgeInTransaction(
)
const existing = existingResult.rows[0] as SpendOutcomeRow | undefined
if (existing) {
- if (
- isOauthBrokerProvider(existing.provider) &&
- input.status === 'complete' &&
- existing.outcome === 'unknown'
- ) {
+ if (isOauthBrokerProvider(existing.provider) && input.status === 'complete') {
const linkedCodex = await loadLlmProviderAttemptBySdkAttemptId(db, input.providerAttemptId)
if (linkedCodex && isLinkedCodexInFlightWithoutUsage(linkedCodex)) {
throw new PromptBridgeFinalizationError(
@@ -297,6 +350,22 @@ export async function finalizePromptBridgeInTransaction(
true
)
}
+ if (existing.outcome === 'unknown' && linkedCodex && isLinkedCodexUsageReady(linkedCodex)) {
+ return upgradeUnknownOauthSpendToExact(db, existing, input, linkedCodex)
+ }
+ if (
+ existing.outcome === 'exact' &&
+ linkedCodex &&
+ isLinkedCodexUsageReady(linkedCodex) &&
+ (Number(existing.input_tokens) !== Number(linkedCodex.usageInputTokens) ||
+ Number(existing.output_tokens) !== Number(linkedCodex.usageOutputTokens))
+ ) {
+ throw new PromptBridgeFinalizationError(
+ 'conflict',
+ 'provider attempt was finalized with a different immutable outcome',
+ 409
+ )
+ }
}
return mapExistingOutcome(existing, input)
}
diff --git a/control-api/test/services.llmProviderAttemptAuthorizer.test.ts b/control-api/test/services.llmProviderAttemptAuthorizer.test.ts
index 5e9010e06..c631ea10d 100644
--- a/control-api/test/services.llmProviderAttemptAuthorizer.test.ts
+++ b/control-api/test/services.llmProviderAttemptAuthorizer.test.ts
@@ -265,6 +265,9 @@ describe('authorizeLlmProviderAttempt', () => {
expect(promoteReservedOauthBrokerProviderAttempt.mock.invocationCallOrder[0]).toBeGreaterThan(
current.insertAttempt.mock.invocationCallOrder[0]!
)
+ expect(lockPluginWorkloadSdkRecipe.mock.invocationCallOrder[0]).toBeLessThan(
+ vi.mocked(current.evaluateBudget).mock.invocationCallOrder[0]!
+ )
})
it('rejects a Plugin Workload SDK attempt that does not match the reserved receipt', async () => {
diff --git a/control-api/test/services.llmProviderAttemptStore.helpers.test.ts b/control-api/test/services.llmProviderAttemptStore.helpers.test.ts
index 61c46467e..c80cde6b8 100644
--- a/control-api/test/services.llmProviderAttemptStore.helpers.test.ts
+++ b/control-api/test/services.llmProviderAttemptStore.helpers.test.ts
@@ -1,9 +1,13 @@
import { describe, expect, it } from 'vitest'
import {
+ CODEX_IN_FLIGHT_USAGE_GRACE_MS,
isLinkedCodexInFlightWithoutUsage,
isLinkedCodexUsageReady,
} from '../src/services/llmProviderAttemptStore.js'
+const recentCreatedAt = new Date('2026-09-02T07:40:00.000Z')
+const nowMs = recentCreatedAt.getTime() + 60_000
+
describe('linked Codex usage predicates', () => {
it('treats success plus both token counts as usage-ready', () => {
expect(
@@ -29,46 +33,97 @@ describe('linked Codex usage predicates', () => {
).toBe(false)
})
- it('keeps authorized, redeemed, and usage-less success finalized in flight', () => {
+ it('keeps recent authorized and redeemed rows in flight', () => {
expect(
- isLinkedCodexInFlightWithoutUsage({
- status: 'authorized',
- outcome: null,
- usageInputTokens: null,
- usageOutputTokens: null,
- })
+ isLinkedCodexInFlightWithoutUsage(
+ {
+ status: 'authorized',
+ outcome: null,
+ usageInputTokens: null,
+ usageOutputTokens: null,
+ createdAt: recentCreatedAt,
+ },
+ nowMs
+ )
).toBe(true)
expect(
- isLinkedCodexInFlightWithoutUsage({
- status: 'redeemed',
- outcome: null,
- usageInputTokens: null,
- usageOutputTokens: null,
- })
+ isLinkedCodexInFlightWithoutUsage(
+ {
+ status: 'redeemed',
+ outcome: null,
+ usageInputTokens: null,
+ usageOutputTokens: null,
+ createdAt: recentCreatedAt,
+ },
+ nowMs
+ )
).toBe(true)
+ })
+
+ it('treats finalized rows as terminal even when usage never arrived', () => {
expect(
- isLinkedCodexInFlightWithoutUsage({
- status: 'finalized',
- outcome: 'success',
- usageInputTokens: null,
- usageOutputTokens: null,
- })
- ).toBe(true)
+ isLinkedCodexInFlightWithoutUsage(
+ {
+ status: 'finalized',
+ outcome: 'success',
+ usageInputTokens: null,
+ usageOutputTokens: null,
+ createdAt: recentCreatedAt,
+ },
+ nowMs
+ )
+ ).toBe(false)
expect(
- isLinkedCodexInFlightWithoutUsage({
- status: 'finalized',
- outcome: 'success',
- usageInputTokens: 3,
- usageOutputTokens: 2,
- })
+ isLinkedCodexInFlightWithoutUsage(
+ {
+ status: 'finalized',
+ outcome: 'success',
+ usageInputTokens: 3,
+ usageOutputTokens: 2,
+ createdAt: recentCreatedAt,
+ },
+ nowMs
+ )
).toBe(false)
expect(
- isLinkedCodexInFlightWithoutUsage({
- status: 'finalized',
- outcome: 'error',
- usageInputTokens: null,
- usageOutputTokens: null,
- })
+ isLinkedCodexInFlightWithoutUsage(
+ {
+ status: 'finalized',
+ outcome: 'error',
+ usageInputTokens: null,
+ usageOutputTokens: null,
+ createdAt: recentCreatedAt,
+ },
+ nowMs
+ )
+ ).toBe(false)
+ })
+
+ it('ages out authorized and redeemed rows after the usage grace', () => {
+ const stale = new Date(nowMs - CODEX_IN_FLIGHT_USAGE_GRACE_MS - 1)
+ expect(
+ isLinkedCodexInFlightWithoutUsage(
+ {
+ status: 'authorized',
+ outcome: null,
+ usageInputTokens: null,
+ usageOutputTokens: null,
+ createdAt: stale,
+ },
+ nowMs
+ )
+ ).toBe(false)
+ expect(
+ isLinkedCodexInFlightWithoutUsage(
+ {
+ status: 'redeemed',
+ outcome: null,
+ usageInputTokens: null,
+ usageOutputTokens: null,
+ createdAt: stale,
+ },
+ nowMs
+ )
).toBe(false)
})
})
diff --git a/control-api/test/services.pluginWorkloadSdkDb.test.ts b/control-api/test/services.pluginWorkloadSdkDb.test.ts
index 11f70ea8a..a131cc4e3 100644
--- a/control-api/test/services.pluginWorkloadSdkDb.test.ts
+++ b/control-api/test/services.pluginWorkloadSdkDb.test.ts
@@ -509,7 +509,7 @@ describe('invocation retry lifecycle timestamps', () => {
outcome: null,
usage_input_tokens: null,
usage_output_tokens: null,
- created_at: new Date('2026-09-01T00:00:00.000Z'),
+ created_at: new Date(),
},
],
rowCount: 1,
@@ -528,6 +528,74 @@ describe('invocation retry lifecycle timestamps', () => {
.mock.calls.some(([sql]: [string]) => sql.includes("SET status = 'provider_unavailable'"))
).toBe(false)
})
+
+ it('freezes oauth spend after the linked Codex in-flight grace expires', async () => {
+ vi.mocked(pool.query)
+ .mockResolvedValueOnce({
+ rows: [
+ {
+ id: 'inv-codex-stale',
+ attempt_generation: 1,
+ recipe_namespace: 'sandbox-recipes',
+ recipe_name: 'sdk-recipe',
+ },
+ ],
+ rowCount: 1,
+ } as never)
+ .mockResolvedValueOnce({
+ rows: [
+ {
+ id: 'attempt-codex-stale',
+ recipe_namespace: 'sandbox-recipes',
+ recipe_name: 'sdk-recipe',
+ attempt_generation: 1,
+ attempt_index: 1,
+ target_ref: 'primary-codex',
+ provider: 'codex-subscription',
+ model: 'gpt-5.1',
+ credential_slot: '',
+ },
+ ],
+ rowCount: 1,
+ } as never)
+ .mockResolvedValueOnce({
+ rows: [
+ {
+ id: 'codex-stale',
+ caller_kind: 'recipe',
+ host_ref: 'sandbox-recipes/sdk-recipe',
+ recipe_namespace: 'sandbox-recipes',
+ recipe_name: 'sdk-recipe',
+ invocation_id: 'inv-codex-stale',
+ attempt_generation: 1,
+ provider_attempt_index: 1,
+ provider: 'codex-subscription',
+ model: 'gpt-5.1',
+ request_hash: 'hash',
+ policy_revision: 1,
+ policy_hash: 'a'.repeat(64),
+ budget_reservation_id: 'budget-1',
+ connection_revision: 1,
+ plugin_workload_sdk_provider_attempt_id: 'attempt-codex-stale',
+ status: 'authorized',
+ outcome: null,
+ usage_input_tokens: null,
+ usage_output_tokens: null,
+ created_at: new Date(Date.now() - 16 * 60 * 1000),
+ },
+ ],
+ rowCount: 1,
+ } as never)
+ .mockResolvedValue({ rows: [{ id: 'inv-codex-stale' }], rowCount: 1 } as never)
+ await expect(failStaleInvocations(150)).resolves.toBe(1)
+ expect(
+ vi
+ .mocked(pool.query)
+ .mock.calls.some(([sql]: [string]) =>
+ sql.includes('INSERT INTO plugin_workload_sdk_spend_outcomes')
+ )
+ ).toBe(true)
+ })
})
describe('upsertGrant — provider column (R1)', () => {
diff --git a/control-api/test/services.pluginWorkloadSdkFinalization.test.ts b/control-api/test/services.pluginWorkloadSdkFinalization.test.ts
index 5898921d3..13129c6e7 100644
--- a/control-api/test/services.pluginWorkloadSdkFinalization.test.ts
+++ b/control-api/test/services.pluginWorkloadSdkFinalization.test.ts
@@ -554,7 +554,7 @@ describe('Plugin Workload SDK promptBridge finalization', () => {
outcome: null,
usage_input_tokens: null,
usage_output_tokens: null,
- created_at: new Date('2026-08-03T00:00:00.000Z'),
+ created_at: new Date(),
}
)
@@ -686,6 +686,104 @@ describe('Plugin Workload SDK promptBridge finalization', () => {
])
})
+ it('records Codex complete as unknown when linked success finalized without usage', async () => {
+ ingest.mockReset()
+ project.mockReset()
+ const db = dbWithRows(
+ [],
+ [],
+ {
+ id: IDS.invocation,
+ recipe_namespace: inputBase.recipeNamespace,
+ recipe_name: inputBase.recipeName,
+ method: 'promptBridge',
+ status: 'in_progress',
+ attempt_generation: 1,
+ },
+ {
+ invocation_id: IDS.invocation,
+ recipe_namespace: inputBase.recipeNamespace,
+ recipe_name: inputBase.recipeName,
+ attempt_generation: 1,
+ method: 'promptBridge',
+ status: 'in_progress',
+ },
+ {
+ id: IDS.providerAttempt,
+ invocation_id: IDS.invocation,
+ recipe_namespace: inputBase.recipeNamespace,
+ recipe_name: inputBase.recipeName,
+ attempt_generation: 1,
+ attempt_index: 1,
+ target_ref: 'codex-primary',
+ host_ref: inputBase.hostRef,
+ provider: 'codex-subscription',
+ model: 'gpt-5.1',
+ credential_slot: '',
+ status: 'in_progress',
+ },
+ {
+ id: '33333333-3333-4333-8333-333333333333',
+ caller_kind: 'recipe',
+ host_ref: inputBase.hostRef,
+ recipe_namespace: inputBase.recipeNamespace,
+ recipe_name: inputBase.recipeName,
+ invocation_id: IDS.invocation,
+ attempt_generation: 1,
+ provider_attempt_index: 1,
+ provider: 'codex-subscription',
+ model: 'gpt-5.1',
+ request_hash: 'hash',
+ policy_revision: 1,
+ policy_hash: 'a'.repeat(64),
+ budget_reservation_id: 'budget-1',
+ connection_revision: 1,
+ status: 'finalized',
+ outcome: 'success',
+ usage_input_tokens: null,
+ usage_output_tokens: null,
+ created_at: new Date(),
+ },
+ { rows: [], rowCount: 1 },
+ { rows: [], rowCount: 1 },
+ { rows: [], rowCount: 1 },
+ { rows: [], rowCount: 1 }
+ )
+
+ const result = await finalizePromptBridgeInTransaction(
+ {
+ ...inputBase,
+ target: {
+ targetRef: 'codex-primary',
+ provider: 'codex-subscription',
+ model: 'gpt-5.1',
+ credentialSlot: '',
+ },
+ status: 'complete',
+ usage: {
+ llmSecretName: '',
+ callerRef: 'scanner',
+ fallbackUsed: false,
+ attemptCount: 1,
+ inputTokens: 4,
+ outputTokens: 2,
+ },
+ },
+ db as never
+ )
+
+ expect(result).toMatchObject({
+ status: 'complete',
+ outcome: 'unknown',
+ usageAccepted: false,
+ })
+ expect(
+ db.query.mock.calls.some(([statement]: [string]) =>
+ statement.includes('INSERT INTO plugin_workload_sdk_spend_outcomes')
+ )
+ ).toBe(true)
+ })
+
it('replays a Codex unknown complete finalization idempotently', async () => {
const row = {
provider_attempt_id: IDS.providerAttempt,
@@ -732,6 +830,83 @@ describe('Plugin Workload SDK promptBridge finalization', () => {
})
})
+ it('upgrades a Codex unknown spend row to exact when linked usage becomes ready', async () => {
+ const row = {
+ provider_attempt_id: IDS.providerAttempt,
+ invocation_id: IDS.invocation,
+ recipe_namespace: inputBase.recipeNamespace,
+ recipe_name: inputBase.recipeName,
+ attempt_generation: 1,
+ attempt_index: 1,
+ target_ref: 'codex-primary',
+ host_ref: inputBase.hostRef,
+ provider: 'codex-subscription',
+ model: 'gpt-5.1',
+ credential_slot: '',
+ outcome: 'unknown',
+ input_tokens: null,
+ output_tokens: null,
+ }
+ const db = dbWithRows(
+ [],
+ row,
+ {
+ id: '33333333-3333-4333-8333-333333333333',
+ caller_kind: 'recipe',
+ host_ref: inputBase.hostRef,
+ recipe_namespace: inputBase.recipeNamespace,
+ recipe_name: inputBase.recipeName,
+ invocation_id: IDS.invocation,
+ attempt_generation: 1,
+ provider_attempt_index: 1,
+ provider: 'codex-subscription',
+ model: 'gpt-5.1',
+ request_hash: 'hash',
+ policy_revision: 1,
+ policy_hash: 'a'.repeat(64),
+ budget_reservation_id: 'budget-1',
+ connection_revision: 1,
+ status: 'finalized',
+ outcome: 'success',
+ usage_input_tokens: 12,
+ usage_output_tokens: 7,
+ created_at: new Date(),
+ },
+ { rows: [{ provider_attempt_id: IDS.providerAttempt }], rowCount: 1 }
+ )
+ await expect(
+ finalizePromptBridgeInTransaction(
+ {
+ ...inputBase,
+ target: {
+ targetRef: 'codex-primary',
+ provider: 'codex-subscription',
+ model: 'gpt-5.1',
+ credentialSlot: '',
+ },
+ status: 'complete',
+ usage: {
+ llmSecretName: '',
+ callerRef: 'scanner',
+ fallbackUsed: false,
+ attemptCount: 1,
+ inputTokens: 4,
+ outputTokens: 2,
+ },
+ },
+ db as never
+ )
+ ).resolves.toMatchObject({
+ idempotent: false,
+ outcome: 'exact',
+ usageAccepted: false,
+ })
+ const upgrade = db.query.mock.calls.find(([statement]: [string]) =>
+ statement.includes("SET outcome = 'exact'")
+ )
+ expect(upgrade?.[1]).toEqual([IDS.providerAttempt, 12, 7])
+ })
+
it('refuses to replay a sweeper unknown while the linked Codex attempt is still in flight', async () => {
const row = {
provider_attempt_id: IDS.providerAttempt,
@@ -789,7 +964,7 @@ describe('Plugin Workload SDK promptBridge finalization', () => {
outcome: null,
usage_input_tokens: null,
usage_output_tokens: null,
- created_at: new Date('2026-08-03T00:00:00.000Z'),
+ created_at: new Date(),
}) as never
)
).rejects.toMatchObject({
diff --git a/mcp-host/package-lock.json b/mcp-host/package-lock.json
index d4ac7c746..9aced9b84 100644
--- a/mcp-host/package-lock.json
+++ b/mcp-host/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "clerum-mcp-host",
- "version": "0.1.309",
+ "version": "0.1.310",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "clerum-mcp-host",
- "version": "0.1.309",
+ "version": "0.1.310",
"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 39bb36d85..548b1b092 100644
--- a/mcp-host/package.json
+++ b/mcp-host/package.json
@@ -1,6 +1,6 @@
{
"name": "clerum-mcp-host",
- "version": "0.1.309",
+ "version": "0.1.310",
"description": "MCP Host - reads Host CRD and provides LLM access via OpenAI/Claude",
"main": "dist/main.js",
"engines": {
diff --git a/mcp-host/src/pluginWorkloadSdk/promptBridge/handler.test.ts b/mcp-host/src/pluginWorkloadSdk/promptBridge/handler.test.ts
index ca536da8c..78a6f98a8 100644
--- a/mcp-host/src/pluginWorkloadSdk/promptBridge/handler.test.ts
+++ b/mcp-host/src/pluginWorkloadSdk/promptBridge/handler.test.ts
@@ -2,7 +2,11 @@ import { describe, expect, it, vi } from 'vitest'
import { PluginWorkloadError } from '../domain/errors'
import type { PromptBridgeTarget } from '../domain/types'
import type { PluginWorkloadSdkControlApiClient } from './controlApiClient'
-import { PromptBridgeHandler, type PromptBridgeHandlerDeps } from './handler'
+import {
+ PromptBridgeHandler,
+ type PromptBridgeHandlerDeps,
+ finalizeLedgerRetryDelayMs,
+} from './handler'
import type { LlmBridge } from './llmBridge'
const validBody = {
@@ -445,6 +449,13 @@ describe('PromptBridgeHandler', () => {
expect(report).not.toHaveBeenCalled()
})
+ it('uses seconds-scale backoff for ledger_pending retries', () => {
+ expect(finalizeLedgerRetryDelayMs(0)).toBe(500)
+ expect(finalizeLedgerRetryDelayMs(1)).toBe(1000)
+ expect(finalizeLedgerRetryDelayMs(2)).toBe(2000)
+ expect(finalizeLedgerRetryDelayMs(3)).toBe(4000)
+ })
+
it('retries a retryable complete finalization before treating the outcome as unknown', async () => {
const finalize = vi
.fn<FinalizePromptBridge>()
@@ -478,10 +489,17 @@ describe('PromptBridgeHandler', () => {
})
const { handler, report } = makeDeps({ complete, finalize })
- await expect(handler.handle(validBody, 'api')).resolves.toMatchObject({
- invocationId: 'inv-1',
- content: 'summary text',
- })
+ vi.useFakeTimers()
+ try {
+ const pending = handler.handle(validBody, 'api')
+ await vi.runAllTimersAsync()
+ await expect(pending).resolves.toMatchObject({
+ invocationId: 'inv-1',
+ content: 'summary text',
+ })
+ } finally {
+ vi.useRealTimers()
+ }
expect(finalize).toHaveBeenCalledTimes(2)
expect(finalize).toHaveBeenNthCalledWith(1, expect.objectContaining({ status: 'complete' }))
expect(finalize).toHaveBeenNthCalledWith(2, expect.objectContaining({ status: 'complete' }))
diff --git a/mcp-host/src/pluginWorkloadSdk/promptBridge/handler.ts b/mcp-host/src/pluginWorkloadSdk/promptBridge/handler.ts
index 1214fe0da..b78dbde30 100644
--- a/mcp-host/src/pluginWorkloadSdk/promptBridge/handler.ts
+++ b/mcp-host/src/pluginWorkloadSdk/promptBridge/handler.ts
@@ -37,7 +37,11 @@ const IDEMPOTENCY_KEY_RE = new RegExp(DEFAULT_IDEMPOTENCY_KEY_PATTERN)
const PURPOSE_SET = new Set<string>(PLUGIN_WORKLOAD_SDK_PURPOSES)
const MAX_METADATA_BYTES = 16 * 1024
const FINALIZE_LEDGER_RETRIES = 4
-const FINALIZE_LEDGER_DELAY_MS = 50
+
+/** Seconds-scale backoff so a Codex usage frame can land before ledger_pending expires. */
+export function finalizeLedgerRetryDelayMs(attempt: number): number {
+ return Math.min(4_000, 500 * 2 ** attempt)
+}
async function finalizeCompleteWithLedgerRetry(
finalize: NonNullable<PromptBridgeHandlerDeps['finalizePromptBridge']>,
@@ -57,7 +61,7 @@ async function finalizeCompleteWithLedgerRetry(
) {
throw error
}
- await new Promise(resolve => setTimeout(resolve, FINALIZE_LEDGER_DELAY_MS))
+ await new Promise(resolve => setTimeout(resolve, finalizeLedgerRetryDelayMs(attempt)))
}
}
throw lastError
@@ -588,6 +592,12 @@ function unexpectedAuthorizationResponse(): PluginWorkloadError {
)
}
+/**
+ * Grant-advertised output cap for providers that honor max_tokens on the wire.
+ * Codex ChatGPT `/codex/responses` rejects max_output_tokens; the proxy omits
+ * it. This clamp still bounds the host request used for authorize hashing. It
+ * is not ChatGPT enforcement.
+ */
function clampMaxTokens(
requested: number | undefined,
grantCap: number | null
diff --git a/mcp-host/src/pluginWorkloadSdk/sdkOnlyCodexBinding.ts b/mcp-host/src/pluginWorkloadSdk/sdkOnlyCodexBinding.ts
index 3e3d2f8f5..3b6e8e0e5 100644
--- a/mcp-host/src/pluginWorkloadSdk/sdkOnlyCodexBinding.ts
+++ b/mcp-host/src/pluginWorkloadSdk/sdkOnlyCodexBinding.ts
@@ -76,9 +76,8 @@ export function verifySdkOnlyCodexBindingHash(
}
/**
- * Integrity-check a caller-supplied Codex binding against the expected model.
- * This must run for every bootstrap request that carries a binding object;
- * the request provider/version must not decide whether the hash is verified.
+ * Return a public-field copy of an already-typed Codex binding.
+ * Hash and model checks live on `readVerifiedSdkOnlyCodexBinding`.
*/
export function sanitizePluginWorkloadSdkCodexBindingProof(
binding: PluginWorkloadSdkCodexBindingProof
@@ -92,6 +91,11 @@ export function sanitizePluginWorkloadSdkCodexBindingProof(
}
}
+/**
+ * Integrity-check a caller-supplied Codex binding against the expected model.
+ * This must run for every bootstrap request that carries a binding object;
+ * the request provider/version must not decide whether the hash is verified.
+ */
export function readVerifiedSdkOnlyCodexBinding(
value: unknown,
model: string
diff --git a/workflow-recipes/package-lock.json b/workflow-recipes/package-lock.json
index 75bbafc0f..ce0c881ae 100644
--- a/workflow-recipes/package-lock.json
+++ b/workflow-recipes/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "workload-recipes-controller",
- "version": "0.1.326",
+ "version": "0.1.327",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "workload-recipes-controller",
- "version": "0.1.326",
+ "version": "0.1.327",
"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 7decfa20a..88fdfc8c8 100644
--- a/workflow-recipes/package.json
+++ b/workflow-recipes/package.json
@@ -1,6 +1,6 @@
{
"name": "workload-recipes-controller",
- "version": "0.1.326",
+ "version": "0.1.327",
"description": "Workload Recipes Controller (WRC) - WorkloadRecipe lifecycle management and MCP server interface",
"main": "dist/main.js",
"engines": {
diff --git a/workflow-recipes/src/reconciler/pluginWorkloadSdkValidator.test.ts b/workflow-recipes/src/reconciler/pluginWorkloadSdkValidator.test.ts
index 29b9184d0..b7281d38b 100644
--- a/workflow-recipes/src/reconciler/pluginWorkloadSdkValidator.test.ts
+++ b/workflow-recipes/src/reconciler/pluginWorkloadSdkValidator.test.ts
@@ -631,6 +631,40 @@ describe('buildPluginWorkloadSdkStatus', () => {
)
})
+ it('does not hide a stale Codex contract behind a default policyState', () => {
+ const projection = buildPluginWorkloadSdkStatus({
+ spec: baseSpec(
+ { promptBridge: {} },
+ { agent: { provider: 'codex-subscription', model: 'gpt-5.6-luna' } }
+ ),
+ existingConditions: undefined,
+ phase: 'active',
+ featureFlagEnabled: true,
+ bootstrapProof: {
+ ready: true,
+ contractVersion: 2,
+ podUid: 'pod-uid-1',
+ provider: 'codex-subscription',
+ model: 'gpt-5.6-luna',
+ policyReady: true,
+ policyState: 'active',
+ verifiedAt: NOW,
+ },
+ now: NOW,
+ })
+ expect(projection.conditions).toEqual(
+ expect.arrayContaining([
+ expect.objectContaining({
+ type: PLUGIN_WORKLOAD_SDK_POLICY_PENDING_CONDITION_TYPE,
+ status: 'True',
+ reason: 'codex_bootstrap_contract_stale',
+ message:
+ 'Plugin Workload SDK promptBridge policy is not ready (codex_bootstrap_contract_stale)',
+ }),
+ ])
+ )
+ })
+
it('does not validate a clientNotifications-only recipe before its grant is proven', () => {
const projection = buildPluginWorkloadSdkStatus({
spec: baseSpec(
diff --git a/workflow-recipes/src/reconciler/pluginWorkloadSdkValidator.ts b/workflow-recipes/src/reconciler/pluginWorkloadSdkValidator.ts
index e67b7ad28..3d869d7fd 100644
--- a/workflow-recipes/src/reconciler/pluginWorkloadSdkValidator.ts
+++ b/workflow-recipes/src/reconciler/pluginWorkloadSdkValidator.ts
@@ -209,6 +209,21 @@ export interface PluginWorkloadSdkBootstrapProofInput {
verifiedAt: string
}
+/**
+ * parseEagerSdkBootstrapProof always sets policyState (default `unknown`).
+ * A stale v2 Codex image or a missing binding must not render as `(active)`.
+ */
+function promptBridgePolicyPendingReason(
+ bootstrapProof: PluginWorkloadSdkBootstrapProofInput | undefined,
+ codexBindingPending: boolean
+): string {
+ if (codexBindingPending) {
+ if (bootstrapProof?.contractVersion !== 3) return 'codex_bootstrap_contract_stale'
+ return bootstrapProof.policyReason ?? 'codex_execution_binding_missing'
+ }
+ return bootstrapProof?.policyReason ?? bootstrapProof?.policyState ?? 'unknown'
+}
+
/**
* JSON merge-patch preserves omitted object members. Keep the status
* projection's derived metadata explicit so a validated record cannot leave
@@ -361,13 +376,7 @@ export function buildPluginWorkloadSdkStatus(args: {
? (bootstrapProof?.clientNotificationsPolicyReason ??
bootstrapProof?.clientNotificationsPolicyState ??
'unknown')
- : (bootstrapProof?.policyReason ??
- bootstrapProof?.policyState ??
- (codexBindingPending
- ? bootstrapProof?.contractVersion !== 3
- ? 'codex_bootstrap_contract_stale'
- : 'codex_execution_binding_missing'
- : 'unknown'))
+ : promptBridgePolicyPendingReason(bootstrapProof, codexBindingPending)
const message =
policyReason === 'grant_missing'
? `Plugin Workload SDK ${family} is awaiting an operator grant`
diff --git a/workflow-recipes/src/workflow/pluginWorkloadSdkProvisioner.imageDrift.test.ts b/workflow-recipes/src/workflow/pluginWorkloadSdkProvisioner.imageDrift.test.ts
index 5dbc713e4..48ceeacee 100644
--- a/workflow-recipes/src/workflow/pluginWorkloadSdkProvisioner.imageDrift.test.ts
+++ b/workflow-recipes/src/workflow/pluginWorkloadSdkProvisioner.imageDrift.test.ts
@@ -613,3 +613,79 @@ describe('ensureEagerSdkMcpHost runtime token roll', () => {
expect(deleteNamespacedPod).not.toHaveBeenCalled()
})
})
+
+describe('ensureEagerSdkMcpHost ConfigMap snapshot skip', () => {
+ const CODEX_SPEC = {
+ agent: { provider: 'codex-subscription', model: 'gpt-5.6-luna' },
+ pluginWorkloadSdk: { promptBridge: {} },
+ } as unknown as WorkflowRecipeSpec
+
+ function desiredCodexRuntimeContractHash(): string {
+ const desiredPod = buildMcpHostPod(
+ RECIPE,
+ CODEX_SPEC.agent,
+ TEST_CONFIG,
+ RECIPE,
+ SANDBOX_NS,
+ undefined,
+ undefined,
+ undefined,
+ {
+ mountWorkflowOutput: false,
+ pluginWorkloadSdkCapabilities: ['promptBridge'],
+ pluginWorkloadSdkRuntimeMode: 'sdk-only',
+ }
+ )
+ return pluginWorkloadSdkRuntimeContractHash(desiredPod)
+ }
+
+ it('does not send a binding-less Codex configure when the allowlist snapshot is unavailable', async () => {
+ const configure = vi.fn()
+ const signWrcConfigureToken = vi.fn()
+ const readNamespacedPod = vi.fn().mockResolvedValue({
+ metadata: {
+ uid: 'pod-uid-1',
+ annotations: {
+ 'clerum.io/plugin-workload-sdk-runtime-contract-hash': desiredCodexRuntimeContractHash(),
+ },
+ },
+ spec: { containers: [{ name: 'mcp-host', image: DESIRED_IMAGE }] },
+ status: {
+ phase: 'Running',
+ conditions: [{ type: 'Ready', status: 'True' }],
+ containerStatuses: [],
+ },
+ })
+ const deps = {
+ coreApi: {
+ readNamespacedPod,
+ deleteNamespacedPod: vi.fn(),
+ createNamespacedPod: vi.fn(),
+ },
+ config: TEST_CONFIG,
+ tokenFactory: { signWrcConfigureToken },
+ log: { info: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn() },
+ ensureMcpHostSecrets: vi.fn().mockResolvedValue(undefined),
+ applyWorkflowNetworkPolicies: vi.fn().mockResolvedValue(undefined),
+ ensureMcpHostHeadlessService: vi.fn().mockResolvedValue(undefined),
+ modelConfigHandler: { configurePluginWorkloadSdkBootstrap: configure },
+ createIfNotExists: vi.fn().mockResolvedValue(true),
+ safeDelete: vi.fn().mockResolvedValue(undefined),
+ } as unknown as PluginWorkloadSdkProvisionerDeps
+ const provisioner = new PluginWorkloadSdkProvisioner(deps)
+
+ await expect(
+ provisioner.ensureEagerSdkMcpHost(
+ RECIPE,
+ 'recipe-uid',
+ SANDBOX_NS,
+ RECIPE,
+ CODEX_SPEC,
+ RUNTIME,
+ { mcpHostPhase: 'Running', codexSnapshotUnavailable: true }
+ )
+ ).resolves.toBe('awaiting_policy')
+ expect(configure).not.toHaveBeenCalled()
+ expect(deps.tokenFactory.signWrcConfigureToken).not.toHaveBeenCalled()
+ })
+})
diff --git a/workflow-recipes/src/workflow/pluginWorkloadSdkProvisioner.ts b/workflow-recipes/src/workflow/pluginWorkloadSdkProvisioner.ts
index 00543a548..803cb60af 100644
--- a/workflow-recipes/src/workflow/pluginWorkloadSdkProvisioner.ts
+++ b/workflow-recipes/src/workflow/pluginWorkloadSdkProvisioner.ts
@@ -219,6 +219,12 @@ export class PluginWorkloadSdkProvisioner {
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.
+ */
+ codexSnapshotUnavailable?: boolean
}
): Promise<EagerSdkMcpHostStatus> {
const log = createLogger('wrc', recipeName)
@@ -387,6 +393,23 @@ export class PluginWorkloadSdkProvisioner {
}
if (promptBridge && !mcpHostAgent) return 'failed'
+ if (
+ opts.codexSnapshotUnavailable === true &&
+ promptBridge &&
+ mcpHostAgent?.provider === 'codex-subscription'
+ ) {
+ const existing = this.eagerSdkBootstrapProofByRecipe.get(recipeName)
+ if (
+ !existing ||
+ existing.policyReady === false ||
+ existing.contractVersion !== 3 ||
+ !existing.codexBinding ||
+ existing.policyReason === 'codex_execution_binding_missing'
+ ) {
+ return 'awaiting_policy'
+ }
+ return 'ready'
+ }
const resolvedCodexBinding =
opts.codexBinding ??
(mcpHostAgent
diff --git a/workflow-recipes/src/workflow/sdkOnlyCodexBinding.ts b/workflow-recipes/src/workflow/sdkOnlyCodexBinding.ts
index 5e84f998e..6187c65f9 100644
--- a/workflow-recipes/src/workflow/sdkOnlyCodexBinding.ts
+++ b/workflow-recipes/src/workflow/sdkOnlyCodexBinding.ts
@@ -50,6 +50,10 @@ export function verifySdkOnlyCodexBindingHash(
)
}
+/**
+ * Return a public-field copy of an already-typed Codex binding.
+ * Hash and model checks live on `readVerifiedSdkOnlyCodexBinding`.
+ */
export function sanitizePluginWorkloadSdkCodexBindingProof(
binding: PluginWorkloadSdkCodexBindingProof
): PluginWorkloadSdkCodexBindingProof {
diff --git a/workflow-recipes/src/workflow/workflowReconciler.ts b/workflow-recipes/src/workflow/workflowReconciler.ts
index 1dd970072..b3913ecff 100644
--- a/workflow-recipes/src/workflow/workflowReconciler.ts
+++ b/workflow-recipes/src/workflow/workflowReconciler.ts
@@ -901,10 +901,12 @@ export class WorkflowReconciler {
/**
* Raw allowlist ConfigMap from the last refresh, kept so each recipe's
* projection can re-parse it with that recipe's assigned grant key (HCC
- * keeps the same shape for Hosts). Undefined while the read is failing —
- * `codexSnapshot` then carries the fail-closed snapshot error.
+ * keeps the same shape for Hosts). Cleared on a failed read so grant
+ * decisions stay fail-closed. Do not send a binding-less v3 configure in
+ * that window — skip configure so mcp-host keeps a live binding.
*/
private lastCodexConfigMap: k8s.V1ConfigMap | undefined
+ private lastCodexSnapshotReadOk = true
private readonly codexContexts = new Map<string, CodexReconcileContext>()
constructor(private readonly deps: WorkflowReconcilerDeps) {
@@ -1022,7 +1024,7 @@ export class WorkflowReconciler {
return [...workflow, ...derived] as EffectiveWorkflowControlScope[]
}
- private async refreshCodexSnapshot(): Promise<void> {
+ private async refreshCodexSnapshot(): Promise<boolean> {
try {
const cm = await this.deps.coreApi.readNamespacedConfigMap({
name: ALLOWED_MODELS_CONFIGMAP_NAME,
@@ -1030,15 +1032,18 @@ export class WorkflowReconciler {
})
this.lastCodexConfigMap = cm
this.codexSnapshot = parseAllowedModelsSnapshot(cm)
+ this.lastCodexSnapshotReadOk = true
+ return true
} catch (err) {
this.lastCodexConfigMap = undefined
+ this.lastCodexSnapshotReadOk = false
if (isCodexSnapshotTimeout(err)) {
this.codexSnapshot = snapshotFromConfigMapError('timeout')
this.log.warn('Codex allowlist ConfigMap read timed out; failing closed', {
configMap: ALLOWED_MODELS_CONFIGMAP_NAME,
namespace: ALLOWLIST_CONFIGMAP_NAMESPACE,
})
- return
+ return false
}
const code = getErrorCode(err)
if (code === 401 || code === 403) {
@@ -1048,7 +1053,7 @@ export class WorkflowReconciler {
namespace: ALLOWLIST_CONFIGMAP_NAMESPACE,
statusCode: code,
})
- return
+ return false
}
this.codexSnapshot = snapshotFromConfigMapError('missing')
this.log.warn('Codex allowlist ConfigMap unavailable; failing closed', {
@@ -1056,6 +1061,7 @@ export class WorkflowReconciler {
namespace: ALLOWLIST_CONFIGMAP_NAMESPACE,
statusCode: code,
})
+ return false
}
}
@@ -1123,7 +1129,7 @@ export class WorkflowReconciler {
throw new Error('SDK-only runtime requires spec.steps to be absent or empty')
}
- await this.refreshCodexSnapshot()
+ const codexSnapshotAvailable = await this.refreshCodexSnapshot()
const agent = resolveEagerSdkMcpHostAgent(spec)
const context = this.resolveCodexContext(recipeUid, recipeName, runtimeScopeRecipeName)
const codexBinding =
@@ -1153,7 +1159,7 @@ export class WorkflowReconciler {
runtimeScopeRecipeName,
spec,
runtime,
- { mcpHostPhase, codexBinding }
+ { mcpHostPhase, codexBinding, codexSnapshotUnavailable: !codexSnapshotAvailable }
)
const bootstrapProof = this.pluginWorkloadSdkProvisioner.getBootstrapProof(recipeName)
switch (status) {
@@ -1607,7 +1613,10 @@ export class WorkflowReconciler {
runtimeScopeRecipeName,
spec,
runtime,
- { mcpHostPhase }
+ {
+ mcpHostPhase,
+ codexSnapshotUnavailable: !this.lastCodexSnapshotReadOk,
+ }
)
const eagerBootstrapProof =
this.pluginWorkloadSdkProvisioner.getBootstrapProof(recipeName)