Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure
TypeScript
fix(codex): publish recipe grant identity with a single CAS writer
Alfredo Lopez187cd2d7f763
diff --git a/control-api/package-lock.json b/control-api/package-lock.jsonindex 0bd1c2229..2389b310d 100644--- a/control-api/package-lock.json+++ b/control-api/package-lock.json@@ -1,12 +1,12 @@{"name": "clerum-control-api",- "version": "0.1.515",+ "version": "0.1.516","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "clerum-control-api",- "version": "0.1.515",+ "version": "0.1.516","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.jsonindex 6e966ea12..bb3181d90 100644--- a/control-api/package.json+++ b/control-api/package.json@@ -1,6 +1,6 @@{"name": "clerum-control-api",- "version": "0.1.515",+ "version": "0.1.516","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/admin/pluginWorkloadSdk.ts b/control-api/src/routes/admin/pluginWorkloadSdk.tsindex 5ebcf54e9..d1eb95ecf 100644--- a/control-api/src/routes/admin/pluginWorkloadSdk.ts+++ b/control-api/src/routes/admin/pluginWorkloadSdk.ts@@ -17,7 +17,6 @@ import { createPluginWorkloadSdkAdminRateLimit } from '../../middleware/pluginWoimport { rootLogger } from '../../observability/logger.js'import { isCodexAssignmentAllowed } from '../../services/codexSubscriptionCatalog.js'import {- CODEX_CONNECTION_REF_ANNOTATION,assertCodexConnectionKey,isCodexUnassignedConnectionKey,} from '../../services/codexSubscriptionConnection.js'@@ -41,6 +40,10 @@ import {listInvocations,upsertGrant,} from '../../services/pluginWorkloadSdkDb.js'+import {+ RecipeCodexGrantIdentityError,+ publishRecipeGrantIdentity,+} from '../../services/recipeCodexGrantIdentity.js'import { isPlainObject } from '../../utils/isPlainObject.js'import {type EmitHostSpecIncoherenceTolerated,@@ -364,11 +367,10 @@ export interface AdminPluginWorkloadSdkRouterDeps {*/emitIncoherenceTolerated?: EmitHostSpecIncoherenceTolerated/**- * Stamps `clerum.io/codex-connection-ref` on the WorkflowRecipe after a- * Codex promptBridge upsert. Authorize attests that annotation, not the- * Postgres grant row, so a successful choose must persist it.+ * Publishes `clerum.io/codex-connection-ref` on the WorkflowRecipe when an+ * SDK Codex choose changes. Authorize attests that annotation.*/- gateway?: Pick<K8sGateway, 'patchResourceAnnotations'>+ gateway?: Pick<K8sGateway, 'getResource' | 'updateResource'>}const log = rootLogger.child({ module: 'admin-plugin-workload-sdk' })@@ -546,6 +548,30 @@ export function createAdminPluginWorkloadSdkRouter(// before (serialization only, no accept/reject change): a disabled model// reachable solely through `allowed_models` (no promptTarget) is a// PRE-EXISTING gap, out of R1-H3 scope.+ const brokerConnectionRef =+ promptTargets.find(+ target =>+ isBrokerBackedProvider(target.provider) &&+ target.connectionRef &&+ !isCodexUnassignedConnectionKey(target.connectionRef)+ )?.connectionRef ?? ''+ if (capabilityFamily === 'promptBridge' && deps.gateway && brokerConnectionRef) {+ try {+ await publishRecipeGrantIdentity({+ gateway: deps.gateway,+ namespace: recipeNamespace,+ name: recipeName,+ next: brokerConnectionRef,+ })+ } catch (err) {+ if (err instanceof RecipeCodexGrantIdentityError) {+ res.status(err.status).json({ error: err.error })+ return+ }+ throw err+ }+ }+let grant: Awaited<ReturnType<typeof upsertGrant>>try {grant = await withTransaction(async db => {@@ -760,30 +786,6 @@ export function createAdminPluginWorkloadSdkRouter(// Grant PERSISTED: NOW emit any Pieza D tolerations (never before the upsert// lands, so a failed upsert leaves no audit record — mini-spec 01).for (const event of pendingGrantTolerations) emitIncoherenceTolerated(event)- const brokerConnectionRef =- promptTargets.find(- target =>- isBrokerBackedProvider(target.provider) &&- target.connectionRef &&- !isCodexUnassignedConnectionKey(target.connectionRef)- )?.connectionRef ?? ''- if (capabilityFamily === 'promptBridge' && deps.gateway) {- try {- await deps.gateway.patchResourceAnnotations(- 'workflowrecipes',- recipeName,- { [CODEX_CONNECTION_REF_ANNOTATION]: brokerConnectionRef },- recipeNamespace- )- } catch (err) {- log.error(- { err, recipeNamespace, recipeName },- 'failed to stamp Codex connection annotation on WorkflowRecipe'- )- res.status(503).json({ error: 'recipe_annotation_stamp_failed' })- return- }- }// Fase 6: attach any soft-quarantine warnings additively (older clients// ignore the field). Absent when there is nothing to warn about.res@@ -827,21 +829,42 @@ export function createAdminPluginWorkloadSdkRouter(target.connectionRef &&!isCodexUnassignedConnectionKey(target.connectionRef))?.connectionRef ?? ''+ let recipeAgent: string | undefinedtry {- await deps.gateway.patchResourceAnnotations(+ const recipe = (await deps.gateway.getResource('workflowrecipes',recipeName,- { [CODEX_CONNECTION_REF_ANNOTATION]: remainingRef },recipeNamespace- )+ )) as { spec?: { agent?: { provider?: string } } }+ recipeAgent =+ typeof recipe.spec?.agent?.provider === 'string'+ ? recipe.spec.agent.provider+ : undefined} catch (err) {log.error({ err, recipeNamespace, recipeName },- 'failed to clear Codex connection annotation after grant delete'+ 'failed to read WorkflowRecipe after grant delete')- res.status(503).json({ error: 'recipe_annotation_stamp_failed' })+ res.status(503).json({ error: 'recipe_annotation_publish_failed' })return}+ const shouldUnassign = !remainingRef && recipeAgent !== 'codex-subscription'+ if (remainingRef || shouldUnassign) {+ try {+ await publishRecipeGrantIdentity({+ gateway: deps.gateway,+ namespace: recipeNamespace,+ name: recipeName,+ next: remainingRef || 'unassigned',+ })+ } catch (err) {+ if (err instanceof RecipeCodexGrantIdentityError) {+ res.status(err.status).json({ error: err.error })+ return+ }+ throw err+ }+ }}res.status(200).json({ deleted: true })})diff --git a/control-api/src/routes/admin/recipes.ts b/control-api/src/routes/admin/recipes.tsindex 60cfca64d..92fac5937 100644--- a/control-api/src/routes/admin/recipes.ts+++ b/control-api/src/routes/admin/recipes.ts@@ -1261,8 +1261,12 @@ function readRequestedCodexRecipeGrant(body: RecipeBody): string {return readHostCodexConnectionRef(typeof raw === 'string' ? raw : '')}-function validateCodexRecipeGrant(body: RecipeBody): ValidationError[] {+function validateCodexRecipeGrant(+ body: RecipeBody,+ opts?: { allowOmittedGrant?: boolean }+): ValidationError[] {if (!recipeUsesCodexBroker(body.spec)) return []+ if (opts?.allowOmittedGrant && !bodyHasCodexGrantAnnotation(body)) return []const key = readRequestedCodexRecipeGrant(body)if (isCodexUnassignedConnectionKey(key)) {return [@@ -1287,38 +1291,44 @@ function validateCodexRecipeGrant(body: RecipeBody): ValidationError[] {return []}+function bodyHasCodexGrantAnnotation(body: RecipeBody): boolean {+ const annotations = body.metadata?.annotations+ return Boolean(+ annotations &&+ Object.prototype.hasOwnProperty.call(annotations, CODEX_CONNECTION_REF_ANNOTATION)+ )+}+function sanitizeRecipeCodexAnnotation(body: RecipeBody,- currentAnnotations?: Record<string, string>+ currentAnnotations?: Record<string, string>,+ currentSpec?: Record<string, unknown>): Record<string, string> {const incoming = readRequestedCodexRecipeGrant(body)if (recipeUsesCodexBroker(body.spec)) {+ if (!bodyHasCodexGrantAnnotation(body)) return {}return {[CODEX_CONNECTION_REF_ANNOTATION]: isCodexUnassignedConnectionKey(incoming) ? '' : incoming,}}- // SDK promptBridge stamps the same annotation regardless of spec.agent.- // Do not wipe a live grant when the author edits an unrelated field.- if (recipeHasPluginWorkloadSdk(body.spec)) {- if (!isCodexUnassignedConnectionKey(incoming)) {- return { [CODEX_CONNECTION_REF_ANNOTATION]: incoming }- }- const current = readHostCodexConnectionRef(- typeof currentAnnotations?.[CODEX_CONNECTION_REF_ANNOTATION] === 'string'- ? currentAnnotations[CODEX_CONNECTION_REF_ANNOTATION]- : ''- )+ const leavingCodex = recipeUsesCodexBroker(currentSpec) && !recipeHasPluginWorkloadSdk(body.spec)+ if (leavingCodex) {+ return { [CODEX_CONNECTION_REF_ANNOTATION]: '' }+ }+ if (bodyHasCodexGrantAnnotation(body)) {return {- [CODEX_CONNECTION_REF_ANNOTATION]: isCodexUnassignedConnectionKey(current) ? '' : current,+ [CODEX_CONNECTION_REF_ANNOTATION]: isCodexUnassignedConnectionKey(incoming) ? '' : incoming,}}- return { [CODEX_CONNECTION_REF_ANNOTATION]: '' }+ void currentAnnotations+ return {}}function sanitizeRecipeBody(body: RecipeBody,currentLabels?: Record<string, string>,- currentAnnotations?: Record<string, string>+ currentAnnotations?: Record<string, string>,+ currentSpec?: Record<string, unknown>): {metadata: { name: string; labels?: Record<string, string>; annotations: Record<string, string> }spec: Record<string, unknown>@@ -1342,7 +1352,7 @@ function sanitizeRecipeBody(...(sanitizedLabels ? { labels: sanitizedLabels } : {}),annotations: {...(currentAnnotations ?? {}),- ...sanitizeRecipeCodexAnnotation(body, currentAnnotations),+ ...sanitizeRecipeCodexAnnotation(body, currentAnnotations, currentSpec),},},spec: body.spec as Record<string, unknown>,@@ -1925,7 +1935,7 @@ export function createAdminRecipesRouter(gateway: K8sGateway): Router {res.status(422).json({ errors })return}- const grantErrors = validateCodexRecipeGrant(body)+ const grantErrors = validateCodexRecipeGrant(body, { allowOmittedGrant: true })if (grantErrors.length > 0) {res.status(422).json({ errors: grantErrors })return@@ -1978,7 +1988,9 @@ export function createAdminRecipesRouter(gateway: K8sGateway): Router {: undefinedconst currentLabels = stringLabels(currentMeta?.labels)const currentAnnotations = stringLabels(currentMeta?.annotations)- const sanitized = sanitizeRecipeBody(body, currentLabels, currentAnnotations)+ const currentSpec =+ isPlainObject(resource) && isPlainObject(resource.spec) ? resource.spec : undefined+ const sanitized = sanitizeRecipeBody(body, currentLabels, currentAnnotations, currentSpec)const updated = await updateRecipeWithConflictRetry(gateway, req.params.name, sanitized, ns)res.status(200)diff --git a/control-api/src/routes/mcp-host/llmProviderAttempts.routes.ts b/control-api/src/routes/mcp-host/llmProviderAttempts.routes.tsindex e8f949828..3695ea73e 100644--- a/control-api/src/routes/mcp-host/llmProviderAttempts.routes.ts+++ b/control-api/src/routes/mcp-host/llmProviderAttempts.routes.ts@@ -6,14 +6,12 @@ import { requireMcpHostJwt } from '../../middleware/mcpHostJwtAuth.js'import { rootLogger } from '../../observability/logger.js'import {CODEX_CONNECTION_REF_ANNOTATION,- CODEX_UNASSIGNED_CONNECTION_KEY,readHostCodexConnectionRef,} from '../../services/codexSubscriptionConnection.js'import {LlmProviderAttemptAuthorizeError,authorizeLlmProviderAttempt,} from '../../services/llmProviderAttemptAuthorizer.js'-import { listGrants } from '../../services/pluginWorkloadSdkDb.js'import { llmProviderAttemptAuthorizeRateLimits } from '../workflows/shared/rateLimit.js'const log = rootLogger.child({ module: 'mcp-host-llm-provider-attempts' })@@ -34,11 +32,6 @@ const ERROR_STATUS: Record<string, number> = {provider_unavailable: 503,}-function recipeHasPluginWorkloadSdk(spec?: Record<string, unknown>): boolean {- const sdk = spec?.pluginWorkloadSdk- return Boolean(sdk && typeof sdk === 'object' && !Array.isArray(sdk))-}-function sendAuthorizeError(res: Response, err: unknown): void {if (err instanceof LlmProviderAttemptAuthorizeError) {const status = ERROR_STATUS[err.code] ?? 400@@ -51,10 +44,7 @@ function sendAuthorizeError(res: Response, err: unknown): void {export async function resolveHostAssignedConnectionKey(gateway: Pick<K8sGateway, 'getResource'>,- hostRef: string,- opts?: {- listSdkCodexConnectionRefs?: (namespace: string, recipeName: string) => Promise<string[]>- }+ hostRef: string): Promise<string> {if (hostRef.includes('/')) {// Workflow callers attest as `namespace/recipeName`. The grant identity is@@ -74,37 +64,9 @@ export async function resolveHostAssignedConnectionKey(recipeName,recipeNamespace)) as { metadata?: { annotations?: Record<string, string> }; spec?: Record<string, unknown> }- const annotated = readHostCodexConnectionRef(+ return readHostCodexConnectionRef(recipe?.metadata?.annotations?.[CODEX_CONNECTION_REF_ANNOTATION])- if (opts?.listSdkCodexConnectionRefs) {- const grantRefs = [- ...new Set(- (await opts.listSdkCodexConnectionRefs(recipeNamespace, recipeName))- .map(ref => ref.trim())- .filter(Boolean)- ),- ]- // Recipes-only keep the annotation when grantRefs is empty. An SDK- // recipe with a leftover named annotation and no grant must not spend.- if (- recipeHasPluginWorkloadSdk(recipe.spec) &&- grantRefs.length === 0 &&- annotated !== CODEX_UNASSIGNED_CONNECTION_KEY- ) {- throw new LlmProviderAttemptAuthorizeError(- 'host_binding_mismatch',- 'SDK grant connectionRef does not match the recipe annotation'- )- }- if (grantRefs.length > 1 || (grantRefs.length === 1 && grantRefs[0] !== annotated)) {- throw new LlmProviderAttemptAuthorizeError(- 'host_binding_mismatch',- 'SDK grant connectionRef does not match the recipe annotation'- )- }- }- return annotated} catch (err) {if (err instanceof LlmProviderAttemptAuthorizeError) throw errthrow new LlmProviderAttemptAuthorizeError(@@ -140,17 +102,7 @@ export function createMcpHostLlmProviderAttemptRoutes(gateway: K8sGateway): Rout}try {const result = await authorizeLlmProviderAttempt(claims, req.body, {- resolveConnectionKey: hostRef =>- resolveHostAssignedConnectionKey(gateway, hostRef, {- listSdkCodexConnectionRefs: async (namespace, recipeName) => {- const grants = await listGrants({ recipeNamespace: namespace, recipeName })- return grants.flatMap(grant =>- grant.promptTargets- .map(target => target.connectionRef)- .filter((ref): ref is string => typeof ref === 'string' && ref.length > 0)- )- },- }),+ resolveConnectionKey: hostRef => resolveHostAssignedConnectionKey(gateway, hostRef),})res.status(200).json(result)} catch (err) {diff --git a/control-api/src/services/recipeCodexGrantIdentity.ts b/control-api/src/services/recipeCodexGrantIdentity.tsnew file mode 100644index 000000000..3a3bbc8fa--- /dev/null+++ b/control-api/src/services/recipeCodexGrantIdentity.ts@@ -0,0 +1,125 @@+import type { DbClient } from '../db.js'+import { pool } from '../db.js'+import type { K8sGateway } from '../k8s.js'+import {+ CODEX_CONNECTION_REF_ANNOTATION,+ CODEX_UNASSIGNED_CONNECTION_KEY,+ getSafeCodexSubscriptionConnection,+ isCodexUnassignedConnectionKey,+ readHostCodexConnectionRef,+} from './codexSubscriptionConnection.js'+import { K8sConflictError } from './resourceService.js'++export class RecipeCodexGrantIdentityError extends Error {+ constructor(+ readonly status: 409 | 422 | 503,+ readonly error: string,+ message: string+ ) {+ super(message)+ this.name = 'RecipeCodexGrantIdentityError'+ }+}++export function readRecipeGrantIdentity(annotations?: Record<string, string> | null): string {+ return readHostCodexConnectionRef(annotations?.[CODEX_CONNECTION_REF_ANNOTATION])+}++function asRecord(value: unknown): Record<string, unknown> | undefined {+ if (!value || typeof value !== 'object' || Array.isArray(value)) return undefined+ return value as Record<string, unknown>+}++function stringMap(value: unknown): Record<string, string> {+ const record = asRecord(value)+ if (!record) return {}+ const out: Record<string, string> = {}+ for (const [key, entry] of Object.entries(record)) {+ if (typeof entry === 'string') out[key] = entry+ }+ return out+}++export async function publishRecipeGrantIdentity(input: {+ gateway: Pick<K8sGateway, 'getResource' | 'updateResource'>+ namespace: string+ name: string+ next: string+ db?: DbClient+}): Promise<{ published: string; resourceVersion?: string; noop: boolean }> {+ const next = isCodexUnassignedConnectionKey(input.next)+ ? CODEX_UNASSIGNED_CONNECTION_KEY+ : input.next.trim()+ if (next !== CODEX_UNASSIGNED_CONNECTION_KEY) {+ const live = await getSafeCodexSubscriptionConnection(input.db ?? pool, next)+ if (!live) {+ throw new RecipeCodexGrantIdentityError(+ 422,+ 'codex_connection_not_allowed',+ 'Codex grant is not a live connection'+ )+ }+ }++ let current: {+ metadata?: { annotations?: unknown; resourceVersion?: string; labels?: unknown }+ spec?: unknown+ }+ try {+ current = (await input.gateway.getResource('workflowrecipes', input.name, input.namespace)) as {+ metadata?: { annotations?: unknown; resourceVersion?: string; labels?: unknown }+ spec?: unknown+ }+ } catch (err) {+ throw new RecipeCodexGrantIdentityError(+ 503,+ 'recipe_annotation_publish_failed',+ err instanceof Error ? err.message : 'failed to read WorkflowRecipe'+ )+ }++ const annotations = stringMap(current.metadata?.annotations)+ const previous = readRecipeGrantIdentity(annotations)+ if (previous === next) {+ return { published: next, resourceVersion: current.metadata?.resourceVersion, noop: true }+ }++ const nextAnnotations = {+ ...annotations,+ [CODEX_CONNECTION_REF_ANNOTATION]: next === CODEX_UNASSIGNED_CONNECTION_KEY ? '' : next,+ }+ const spec = asRecord(current.spec) ?? {}+ try {+ await input.gateway.updateResource(+ 'workflowrecipes',+ input.name,+ {+ metadata: {+ ...(stringMap(current.metadata?.labels)+ ? { labels: stringMap(current.metadata?.labels) }+ : {}),+ annotations: nextAnnotations,+ ...(current.metadata?.resourceVersion+ ? { resourceVersion: current.metadata.resourceVersion }+ : {}),+ },+ spec,+ },+ input.namespace+ )+ } catch (err) {+ if (err instanceof K8sConflictError) {+ throw new RecipeCodexGrantIdentityError(+ 409,+ 'conflict',+ 'WorkflowRecipe was modified while publishing the Codex grant'+ )+ }+ throw new RecipeCodexGrantIdentityError(+ 503,+ 'recipe_annotation_publish_failed',+ err instanceof Error ? err.message : 'failed to publish Codex grant annotation'+ )+ }+ return { published: next, resourceVersion: current.metadata?.resourceVersion, noop: false }+}diff --git a/control-api/test/routes.adminPluginWorkloadSdk.test.ts b/control-api/test/routes.adminPluginWorkloadSdk.test.tsindex a4efe2810..28c370188 100644--- a/control-api/test/routes.adminPluginWorkloadSdk.test.ts+++ b/control-api/test/routes.adminPluginWorkloadSdk.test.ts@@ -6,6 +6,10 @@ import { createAdminPluginWorkloadSdkRouter } from '../src/routes/admin/pluginWoimport { isCodexAssignmentAllowed } from '../src/services/codexSubscriptionCatalog.js'import * as sdkDb from '../src/services/pluginWorkloadSdkDb.js'import { checkAndIncrement } from '../src/services/rateLimiterService.js'+import {+ RecipeCodexGrantIdentityError,+ publishRecipeGrantIdentity,+} from '../src/services/recipeCodexGrantIdentity.js'vi.mock('../src/services/rateLimiterService.js', () => ({checkAndIncrement: vi.fn(),@@ -52,9 +56,20 @@ vi.mock('../src/services/codexSubscriptionCatalog.js', () => ({isCodexAssignmentAllowed: vi.fn(),}))+vi.mock('../src/services/recipeCodexGrantIdentity.js', async () => {+ const actual = await vi.importActual<+ typeof import('../src/services/recipeCodexGrantIdentity.js')+ >('../src/services/recipeCodexGrantIdentity.js')+ return {+ ...actual,+ publishRecipeGrantIdentity: vi.fn(),+ }+})+const DEFAULT_ADMIN_SUB = '11111111-1111-4111-8111-111111111111'-const patchResourceAnnotations = vi.fn().mockResolvedValue({})+const getResource = vi.fn().mockResolvedValue({ spec: { pluginWorkloadSdk: {} } })+const updateResource = vi.fn().mockResolvedValue({})function buildApp(sub: string | null = DEFAULT_ADMIN_SUB) {const app = express()@@ -63,7 +78,7 @@ function buildApp(sub: string | null = DEFAULT_ADMIN_SUB) {;(req as unknown as { adminAuth: { sub?: string } }).adminAuth = sub === null ? {} : { sub }next()})- app.use(createAdminPluginWorkloadSdkRouter({ gateway: { patchResourceAnnotations } }))+ app.use(createAdminPluginWorkloadSdkRouter({ gateway: { getResource, updateResource } }))return app}@@ -110,8 +125,15 @@ beforeEach(() => {vi.mocked(pool.query).mockResolvedValue({ rows: [{ model: 'glm-4.7' }], rowCount: 1 } as never)vi.mocked(isCodexAssignmentAllowed).mockReset()vi.mocked(isCodexAssignmentAllowed).mockResolvedValue(false)- patchResourceAnnotations.mockReset()- patchResourceAnnotations.mockResolvedValue({})+ getResource.mockReset()+ getResource.mockResolvedValue({ spec: { pluginWorkloadSdk: {} } })+ updateResource.mockReset()+ updateResource.mockResolvedValue({})+ vi.mocked(publishRecipeGrantIdentity).mockReset()+ vi.mocked(publishRecipeGrantIdentity).mockResolvedValue({+ published: 'team-plus',+ noop: false,+ })})describe('routes/admin/pluginWorkloadSdk — grants', () => {@@ -605,23 +627,58 @@ describe('routes/admin/pluginWorkloadSdk — grants', () => {'11111111-1111-4111-8111-111111111111',expect.anything() // carrier transaction client (R1-H3 fase 2))- expect(patchResourceAnnotations).toHaveBeenCalledWith(- 'workflowrecipes',- 'sdk-recipe',- { 'clerum.io/codex-connection-ref': 'team-plus' },- 'sandbox-recipes'+ expect(publishRecipeGrantIdentity).toHaveBeenCalledWith({+ gateway: { getResource, updateResource },+ namespace: 'sandbox-recipes',+ name: 'sdk-recipe',+ next: 'team-plus',+ })+ expect(publishRecipeGrantIdentity.mock.invocationCallOrder[0]).toBeLessThan(+ vi.mocked(sdkDb.upsertGrant).mock.invocationCallOrder[0]!)})- it('returns 503 when the recipe annotation cannot be stamped after a Codex upsert', async () => {- vi.mocked(sdkDb.upsertGrant).mockResolvedValue({ id: 'g-codex' } as never)+ it('returns 409 when publish conflicts and does not persist the grant echo', async () => {+ vi.mocked(isCodexAssignmentAllowed).mockResolvedValue(true)+ vi.mocked(publishRecipeGrantIdentity).mockRejectedValueOnce(+ new RecipeCodexGrantIdentityError(+ 409,+ 'conflict',+ 'WorkflowRecipe was modified while publishing the Codex grant'+ )+ )+ const res = await request(buildApp())+ .post('/admin/plugin-workload-sdk/grants')+ .send(codexGrantBody)+ expect(res.status).toBe(409)+ expect(res.body.error).toBe('conflict')+ expect(sdkDb.upsertGrant).not.toHaveBeenCalled()+ })++ it('returns 503 when publish fails before the grant echo is persisted', async () => {vi.mocked(isCodexAssignmentAllowed).mockResolvedValue(true)- patchResourceAnnotations.mockRejectedValueOnce(new Error('apiserver down'))+ vi.mocked(publishRecipeGrantIdentity).mockRejectedValueOnce(+ new RecipeCodexGrantIdentityError(503, 'recipe_annotation_publish_failed', 'apiserver down')+ )const res = await request(buildApp()).post('/admin/plugin-workload-sdk/grants').send(codexGrantBody)expect(res.status).toBe(503)- expect(res.body.error).toBe('recipe_annotation_stamp_failed')+ expect(res.body.error).toBe('recipe_annotation_publish_failed')+ expect(sdkDb.upsertGrant).not.toHaveBeenCalled()+ })++ it('does not unassign when persist fails after a successful publish', async () => {+ vi.mocked(isCodexAssignmentAllowed).mockResolvedValue(true)+ vi.mocked(sdkDb.upsertGrant).mockRejectedValueOnce(new Error('db down'))+ const res = await request(buildApp())+ .post('/admin/plugin-workload-sdk/grants')+ .send(codexGrantBody)+ expect(res.status).toBeGreaterThanOrEqual(500)+ expect(publishRecipeGrantIdentity).toHaveBeenCalledTimes(1)+ expect(publishRecipeGrantIdentity).toHaveBeenCalledWith(+ expect.objectContaining({ next: 'team-plus' })+ )})it('rejects two Codex targets that name different grants', async () => {@@ -669,12 +726,7 @@ describe('routes/admin/pluginWorkloadSdk — grants', () => {.send({ ...codexGrantBody, promptTargets: [targetWithoutConnection] })expect(res.status).toBe(200)expect(isCodexAssignmentAllowed).not.toHaveBeenCalled()- expect(patchResourceAnnotations).toHaveBeenCalledWith(- 'workflowrecipes',- 'sdk-recipe',- { 'clerum.io/codex-connection-ref': '' },- 'sandbox-recipes'- )+ expect(publishRecipeGrantIdentity).not.toHaveBeenCalled()expect(sdkDb.upsertGrant).toHaveBeenCalled()})@@ -688,12 +740,7 @@ describe('routes/admin/pluginWorkloadSdk — grants', () => {})expect(res.status).toBe(200)expect(isCodexAssignmentAllowed).not.toHaveBeenCalled()- expect(patchResourceAnnotations).toHaveBeenCalledWith(- 'workflowrecipes',- 'sdk-recipe',- { 'clerum.io/codex-connection-ref': '' },- 'sandbox-recipes'- )+ expect(publishRecipeGrantIdentity).not.toHaveBeenCalled()expect(sdkDb.upsertGrant).toHaveBeenCalled()})@@ -730,6 +777,7 @@ describe('routes/admin/pluginWorkloadSdk — grants', () => {.send(validGrantBody)expect(res.status).toBe(200)expect(isCodexAssignmentAllowed).not.toHaveBeenCalled()+ expect(publishRecipeGrantIdentity).not.toHaveBeenCalled()expect(sdkDb.upsertGrant).toHaveBeenCalledWith(expect.objectContaining({promptTargets: [@@ -1020,12 +1068,24 @@ describe('routes/admin/pluginWorkloadSdk — grants', () => {'sdk-recipe','11111111-1111-4111-8111-111111111111')- expect(patchResourceAnnotations).toHaveBeenCalledWith(- 'workflowrecipes',- 'sdk-recipe',- { 'clerum.io/codex-connection-ref': '' },- 'sandbox-recipes'- )+ expect(publishRecipeGrantIdentity).toHaveBeenCalledWith({+ gateway: { getResource, updateResource },+ namespace: 'sandbox-recipes',+ name: 'sdk-recipe',+ next: 'unassigned',+ })+ })++ it('does not unassign a Codex-agent recipe when the last SDK Codex grant is deleted', async () => {+ vi.mocked(sdkDb.deleteGrant).mockResolvedValue(true)+ getResource.mockResolvedValue({+ spec: { agent: { provider: 'codex-subscription', model: 'gpt-5.3-codex' } },+ })+ const res = await request(buildApp())+ .delete('/admin/plugin-workload-sdk/grants/g1')+ .query({ recipeNamespace: 'sandbox-recipes', recipeName: 'sdk-recipe' })+ expect(res.status).toBe(200)+ expect(publishRecipeGrantIdentity).not.toHaveBeenCalled()})})diff --git a/control-api/test/routes.adminRecipes.test.ts b/control-api/test/routes.adminRecipes.test.tsindex dc3f1f81e..079fe8ac1 100644--- a/control-api/test/routes.adminRecipes.test.ts+++ b/control-api/test/routes.adminRecipes.test.ts@@ -307,6 +307,27 @@ describe.sequential('routes/admin/recipes', () => {})})+ it('PUT /admin/recipes/:name — keeps a recipes-only Codex grant when the annotation is omitted', async () => {+ await api+ .post('/admin/recipes')+ .send(codexSubscriptionRecipe('codex-image-bump', 'team-plus'))+ .expect(201)+ const res = await api+ .put('/admin/recipes/codex-image-bump')+ .send({+ spec: {+ agent: { provider: 'codex-subscription', model: 'gpt-5.1' },+ triggers: { onDemand: { allowedActors: ['user'] } },+ steps: [{ id: 'draft', instruction: 'Write v2', timeoutSeconds: 600 }],+ },+ })+ .expect(200)+ expect(res.body.metadata.annotations).toEqual({+ 'clerum.io/codex-connection-ref': 'team-plus',+ })+ expect(res.body.spec.steps[0].instruction).toBe('Write v2')+ })+it('PUT /admin/recipes/:name — keeps an SDK Codex grant and last-applied annotations', async () => {await api.post('/admin/recipes')diff --git a/control-api/test/routes.mcp-host.llmProviderAttempts.test.ts b/control-api/test/routes.mcp-host.llmProviderAttempts.test.tsindex 2087cf60b..a95a4d53e 100644--- a/control-api/test/routes.mcp-host.llmProviderAttempts.test.ts+++ b/control-api/test/routes.mcp-host.llmProviderAttempts.test.ts@@ -231,44 +231,19 @@ describe('resolveHostAssignedConnectionKey', () => {})})- it('fails closed when the SDK grant connectionRef disagrees with the recipe annotation', async () => {- const gateway = {- getResource: vi.fn().mockResolvedValue({- metadata: { annotations: { 'clerum.io/codex-connection-ref': 'team-plus' } },- }),- }- await expect(- resolveHostAssignedConnectionKey(gateway, 'sandbox-recipes/codex-recipe', {- listSdkCodexConnectionRefs: async () => ['team-other'],- })- ).rejects.toMatchObject({ code: 'host_binding_mismatch' })- })-- it('fails closed when the recipe annotation is unassigned but the SDK grant chose a key', async () => {- const gateway = {- getResource: vi.fn().mockResolvedValue({ metadata: { annotations: {} } }),- }- await expect(- resolveHostAssignedConnectionKey(gateway, 'sandbox-recipes/codex-recipe', {- listSdkCodexConnectionRefs: async () => ['team-plus'],- })- ).rejects.toMatchObject({ code: 'host_binding_mismatch' })- })-- it('accepts a recipe whose SDK grant matches the stamped annotation', async () => {+ it('attests the recipe annotation even when an SDK grant would disagree', async () => {const gateway = {getResource: vi.fn().mockResolvedValue({metadata: { annotations: { 'clerum.io/codex-connection-ref': 'team-plus' } },+ spec: { pluginWorkloadSdk: { family: 'promptBridge' } },}),}await expect(- resolveHostAssignedConnectionKey(gateway, 'sandbox-recipes/codex-recipe', {- listSdkCodexConnectionRefs: async () => ['team-plus'],- })+ resolveHostAssignedConnectionKey(gateway, 'sandbox-recipes/codex-recipe')).resolves.toBe('team-plus')})- it('keeps a recipes-only annotation when grant listing is empty', async () => {+ it('keeps a recipes-only annotation as identity', async () => {const gateway = {getResource: vi.fn().mockResolvedValue({metadata: { annotations: { 'clerum.io/codex-connection-ref': 'team-plus' } },@@ -276,13 +251,11 @@ describe('resolveHostAssignedConnectionKey', () => {}),}await expect(- resolveHostAssignedConnectionKey(gateway, 'sandbox-recipes/codex-recipe', {- listSdkCodexConnectionRefs: async () => [],- })+ resolveHostAssignedConnectionKey(gateway, 'sandbox-recipes/codex-recipe')).resolves.toBe('team-plus')})- it('fails closed when an SDK recipe has a leftover annotation and no grant', async () => {+ it('attests a leftover SDK annotation as identity (spend still uses getLive)', async () => {const gateway = {getResource: vi.fn().mockResolvedValue({metadata: { annotations: { 'clerum.io/codex-connection-ref': 'team-plus' } },@@ -290,9 +263,7 @@ describe('resolveHostAssignedConnectionKey', () => {}),}await expect(- resolveHostAssignedConnectionKey(gateway, 'sandbox-recipes/codex-recipe', {- listSdkCodexConnectionRefs: async () => [],- })- ).rejects.toMatchObject({ code: 'host_binding_mismatch' })+ resolveHostAssignedConnectionKey(gateway, 'sandbox-recipes/codex-recipe')+ ).resolves.toBe('team-plus')})})diff --git a/control-api/test/services.recipeCodexGrantIdentity.test.ts b/control-api/test/services.recipeCodexGrantIdentity.test.tsnew file mode 100644index 000000000..63dfdc507--- /dev/null+++ b/control-api/test/services.recipeCodexGrantIdentity.test.ts@@ -0,0 +1,133 @@+import { beforeEach, describe, expect, it, vi } from 'vitest'+import { getSafeCodexSubscriptionConnection } from '../src/services/codexSubscriptionConnection.js'+import {+ publishRecipeGrantIdentity,+ readRecipeGrantIdentity,+} from '../src/services/recipeCodexGrantIdentity.js'+import { K8sConflictError } from '../src/services/resourceService.js'++vi.mock('../src/services/codexSubscriptionConnection.js', async () => {+ const actual = await vi.importActual<+ typeof import('../src/services/codexSubscriptionConnection.js')+ >('../src/services/codexSubscriptionConnection.js')+ return {+ ...actual,+ getSafeCodexSubscriptionConnection: vi.fn(),+ }+})++const liveGrant = {+ id: '11111111-1111-1111-1111-111111111111',+ connectionKey: 'team-plus',+ displayName: 'Team Plus',+ status: 'connected',+}++describe('recipe Codex grant identity', () => {+ const getResource = vi.fn()+ const updateResource = vi.fn()++ beforeEach(() => {+ getResource.mockReset()+ updateResource.mockReset()+ vi.mocked(getSafeCodexSubscriptionConnection).mockReset()+ vi.mocked(getSafeCodexSubscriptionConnection).mockResolvedValue(liveGrant as never)+ })++ it('reads empty and blank annotations as unassigned', () => {+ expect(readRecipeGrantIdentity(undefined)).toBe('unassigned')+ expect(readRecipeGrantIdentity({})).toBe('unassigned')+ expect(readRecipeGrantIdentity({ 'clerum.io/codex-connection-ref': '' })).toBe('unassigned')+ expect(readRecipeGrantIdentity({ 'clerum.io/codex-connection-ref': 'team-plus' })).toBe(+ 'team-plus'+ )+ })++ it('rejects a named publish when the grant is not live', async () => {+ vi.mocked(getSafeCodexSubscriptionConnection).mockResolvedValueOnce(null)+ await expect(+ publishRecipeGrantIdentity({+ gateway: { getResource, updateResource },+ namespace: 'sandbox-recipes',+ name: 'codex-recipe',+ next: 'team-plus',+ })+ ).rejects.toMatchObject({+ status: 422,+ error: 'codex_connection_not_allowed',+ })+ expect(getResource).not.toHaveBeenCalled()+ expect(updateResource).not.toHaveBeenCalled()+ })++ it('no-ops when the live annotation already matches', async () => {+ getResource.mockResolvedValue({+ metadata: {+ resourceVersion: '12',+ annotations: { 'clerum.io/codex-connection-ref': 'team-plus' },+ },+ spec: { agent: { provider: 'codex-subscription' } },+ })+ await expect(+ publishRecipeGrantIdentity({+ gateway: { getResource, updateResource },+ namespace: 'sandbox-recipes',+ name: 'codex-recipe',+ next: 'team-plus',+ })+ ).resolves.toEqual({ published: 'team-plus', resourceVersion: '12', noop: true })+ expect(updateResource).not.toHaveBeenCalled()+ })++ it('writes empty string for unassigned and requires resourceVersion', async () => {+ getResource.mockResolvedValue({+ metadata: {+ resourceVersion: '9',+ annotations: { 'clerum.io/codex-connection-ref': 'team-plus' },+ labels: { app: 'recipe' },+ },+ spec: { pluginWorkloadSdk: { family: 'promptBridge' } },+ })+ await expect(+ publishRecipeGrantIdentity({+ gateway: { getResource, updateResource },+ namespace: 'sandbox-recipes',+ name: 'sdk-recipe',+ next: 'unassigned',+ })+ ).resolves.toEqual({ published: 'unassigned', resourceVersion: '9', noop: false })+ expect(getSafeCodexSubscriptionConnection).not.toHaveBeenCalled()+ expect(updateResource).toHaveBeenCalledWith(+ 'workflowrecipes',+ 'sdk-recipe',+ {+ metadata: {+ labels: { app: 'recipe' },+ annotations: { 'clerum.io/codex-connection-ref': '' },+ resourceVersion: '9',+ },+ spec: { pluginWorkloadSdk: { family: 'promptBridge' } },+ },+ 'sandbox-recipes'+ )+ })++ it('surfaces a 409 when the recipe changed under the CAS write', async () => {+ getResource.mockResolvedValue({+ metadata: {+ resourceVersion: '3',+ annotations: {},+ },+ spec: {},+ })+ updateResource.mockRejectedValueOnce(new K8sConflictError('resource changed'))+ await expect(+ publishRecipeGrantIdentity({+ gateway: { getResource, updateResource },+ namespace: 'sandbox-recipes',+ name: 'codex-recipe',+ next: 'team-plus',+ })+ ).rejects.toMatchObject({ status: 409, error: 'conflict' })+ })+})diff --git a/scripts/tests/test-codex-subscription-t0.sh b/scripts/tests/test-codex-subscription-t0.shindex baece585f..9224e3e2d 100755--- a/scripts/tests/test-codex-subscription-t0.sh+++ b/scripts/tests/test-codex-subscription-t0.sh@@ -158,6 +158,9 @@ run_group "control-api" "control-api" \"test/routes.admin.codexSubscription.hostWrite.test.ts" \"test/routes.auth.codexSubscriptionCallback.test.ts" \"test/routes.mcp-host.llmProviderAttempts.test.ts" \+ "test/routes.adminRecipes.test.ts" \+ "test/routes.adminPluginWorkloadSdk.test.ts" \+ "test/services.recipeCodexGrantIdentity.test.ts" \"test/hostSpecValidation.codexSubscription.test.ts" \"test/llmProviders.test.ts" \"test/services.codexSubscriptionConnection.test.ts" \