Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure
TypeScript
fix(control-api): make recipe grant provider transitions explicit
Jose Gabriel Ramirez Encinas0d69ae25dd97
diff --git a/control-api/package-lock.json b/control-api/package-lock.jsonindex df5c2fd8b..730825a43 100644--- a/control-api/package-lock.json+++ b/control-api/package-lock.json@@ -1,12 +1,12 @@{"name": "clerum-control-api",- "version": "0.1.572",+ "version": "0.1.573","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "clerum-control-api",- "version": "0.1.572",+ "version": "0.1.573","dependencies": {"@clerum/display-field": "file:../packages/display-field","@clerum/grok-provider-attempt-contract": "file:../packages/grok-provider-attempt-contract",diff --git a/control-api/package.json b/control-api/package.jsonindex a9ca5d154..861b15295 100644--- a/control-api/package.json+++ b/control-api/package.json@@ -1,6 +1,6 @@{"name": "clerum-control-api",- "version": "0.1.572",+ "version": "0.1.573","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/codexSubscription.ts b/control-api/src/routes/admin/codexSubscription.tsindex 27e00aa7d..af4f12e82 100644--- a/control-api/src/routes/admin/codexSubscription.ts+++ b/control-api/src/routes/admin/codexSubscription.ts@@ -1017,7 +1017,15 @@ export function createAdminCodexSubscriptionRouter(res.status(404).json({ error: 'no_grant' })return}- res.status(200).json(await withAssignedHosts(updated))+ res+ .status(200)+ .json(+ await withAssignedHosts(+ updated,+ undefined,+ grok ? 'grok-subscription' : 'codex-subscription'+ )+ )}))diff --git a/control-api/src/routes/admin/pluginWorkloadSdk.ts b/control-api/src/routes/admin/pluginWorkloadSdk.tsindex f18f474e2..7b29df4b7 100644--- a/control-api/src/routes/admin/pluginWorkloadSdk.ts+++ b/control-api/src/routes/admin/pluginWorkloadSdk.ts@@ -49,6 +49,7 @@ import {RecipeCodexGrantIdentityError,publishRecipeGrantIdentity,} from '../../services/recipeCodexGrantIdentity.js'+import { collectRecipeOauthBrokerProviders } from '../../services/subscriptionGrantIdentity.js'import { isPlainObject } from '../../utils/isPlainObject.js'import {type EmitHostSpecIncoherenceTolerated,@@ -409,28 +410,38 @@ async function publishPromptBridgeGrantIdentity(input: {recipeName: stringnextRef: stringprovider?: string+ /**+ * Upsert rejects a broker target whose provider differs from the recipe's+ * agent / step-agent broker. Delete skips the publish instead: the grant row+ * is already gone and the agent owns the annotation.+ */+ onProviderConflict: 'reject' | 'skip'}): Promise<{ error?: { status: number; error: string } }> {+ let recipeBrokers: string[]+ try {+ const recipe = (await input.gateway.getResource(+ 'workflowrecipes',+ input.recipeName,+ input.recipeNamespace+ )) as { spec?: unknown } | null+ recipeBrokers = collectRecipeOauthBrokerProviders(+ isPlainObject(recipe?.spec) ? recipe.spec : {}+ )+ } catch (err) {+ log.error(+ { err, recipeNamespace: input.recipeNamespace, recipeName: input.recipeName },+ 'failed to read WorkflowRecipe before publishing grant identity'+ )+ return { error: { status: 503, error: 'recipe_annotation_publish_failed' } }+ }+ if (input.provider && recipeBrokers.length > 0 && !recipeBrokers.includes(input.provider)) {+ if (input.onProviderConflict === 'skip') return {}+ return { error: { status: 400, error: 'oauth_broker_provider_conflict' } }+ }let next = input.nextRefif (!next) {- let recipeAgent: string | undefined- try {- const recipe = (await input.gateway.getResource(- 'workflowrecipes',- input.recipeName,- input.recipeNamespace- )) as { spec?: { agent?: { provider?: string } } }- recipeAgent =- typeof recipe.spec?.agent?.provider === 'string' ? recipe.spec.agent.provider : undefined- } catch (err) {- log.error(- { err, recipeNamespace: input.recipeNamespace, recipeName: input.recipeName },- 'failed to read WorkflowRecipe before publishing grant identity'- )- return { error: { status: 503, error: 'recipe_annotation_publish_failed' } }- }- if (recipeAgent === 'codex-subscription' || recipeAgent === 'grok-subscription') {- return {}- }+ // Do not unassign a recipe whose agent (or any step agent) owns the grant.+ if (recipeBrokers.length > 0) return {}next = 'unassigned'}try {@@ -641,6 +652,7 @@ export function createAdminPluginWorkloadSdkRouter(recipeName,nextRef: brokerConnectionRef,provider: brokerTarget?.provider ?? brokerProviders[0],+ onProviderConflict: 'reject',})if (published.error) {res.status(published.error.status).json({ error: published.error.error })@@ -922,6 +934,7 @@ export function createAdminPluginWorkloadSdkRouter(recipeName,nextRef: remainingTarget?.connectionRef ?? '',provider: remainingTarget?.provider,+ onProviderConflict: 'skip',})if (published.error) {res.status(published.error.status).json({ error: published.error.error })diff --git a/control-api/src/routes/admin/recipes.ts b/control-api/src/routes/admin/recipes.tsindex a252a0c2d..6f6d74d12 100644--- a/control-api/src/routes/admin/recipes.ts+++ b/control-api/src/routes/admin/recipes.ts@@ -15,28 +15,14 @@ import {type SecretOwnership,parseSecretOwnership,} from '../../secretOwnership.js'-import {- CODEX_CONNECTION_REF_ANNOTATION,- CODEX_UNASSIGNED_CONNECTION_KEY,- assertCodexConnectionKey,- isCodexUnassignedConnectionKey,-} from '../../services/codexSubscriptionConnection.js'-import {- GROK_UNASSIGNED_CONNECTION_KEY,- assertGrokConnectionKey,- isGrokUnassignedConnectionKey,-} from '../../services/grokSubscriptionConnection.js'+import { resolveRecipeGrantTransition } from '../../services/recipeGrantTransition.js'import {ensureRegistryPullSecrets,platformWorkloadNamespaces,} from '../../services/registryPullSecretService.js'import { K8sNotFoundError } from '../../services/resourceService.js'import { invalidSecretDataKeyReason } from '../../services/secretKeys.js'-import {- SUBSCRIPTION_CONNECTION_REF_ANNOTATION,- collectRecipeOauthBrokerProviders,- readSubscriptionConnectionRef,-} from '../../services/subscriptionGrantIdentity.js'+import { collectRecipeOauthBrokerProviders } from '../../services/subscriptionGrantIdentity.js'import {validateWorkflowRecipeEgressPreflight,validateWorkflowRecipeLimits,@@ -1263,218 +1249,11 @@ function validateRecipeBody(body: RecipeBody): ValidationError[] {return errors}-function recipeUsesCodexBroker(spec?: Record<string, unknown>): boolean {- if (!spec) return false- return collectRecipeOauthBrokerProviders(spec).includes('codex-subscription')-}--function recipeUsesGrokBroker(spec?: Record<string, unknown>): boolean {- if (!spec) return false- return collectRecipeOauthBrokerProviders(spec).includes('grok-subscription')-}--function recipeHasPluginWorkloadSdk(spec?: Record<string, unknown>): boolean {- const sdk = spec?.pluginWorkloadSdk- return Boolean(sdk && typeof sdk === 'object' && !Array.isArray(sdk))-}--function recipeAnnotationStrings(- annotations: Record<string, unknown> | undefined-): Record<string, string> | undefined {- if (!annotations) return undefined- const out: Record<string, string> = Object.create(null)- const alias = annotations[CODEX_CONNECTION_REF_ANNOTATION]- const canonical = annotations[SUBSCRIPTION_CONNECTION_REF_ANNOTATION]- if (typeof alias === 'string') out[CODEX_CONNECTION_REF_ANNOTATION] = alias- if (typeof canonical === 'string') out[SUBSCRIPTION_CONNECTION_REF_ANNOTATION] = canonical- return out-}--function readRequestedCodexRecipeGrant(body: RecipeBody): string {- const result = readSubscriptionConnectionRef({- provider: 'codex-subscription',- annotations: recipeAnnotationStrings(body.metadata?.annotations),- })- if (!result.ok) {- throw new RecipeGrantAnnotationDisagreeError(result.message)- }- return result.connectionKey-}--class RecipeGrantAnnotationDisagreeError extends Error {- constructor(message: string) {- super(message)- this.name = 'RecipeGrantAnnotationDisagreeError'- }-}--function validateCodexRecipeGrant(- body: RecipeBody,- opts?: { allowOmittedGrant?: boolean }-): ValidationError[] {- if (!recipeUsesCodexBroker(body.spec)) return []- if (opts?.allowOmittedGrant && !bodyHasCodexGrantAnnotation(body)) return []- let key: string- try {- key = readRequestedCodexRecipeGrant(body)- } catch (err) {- if (err instanceof RecipeGrantAnnotationDisagreeError) {- return [- {- field: `metadata.annotations.${CODEX_CONNECTION_REF_ANNOTATION}`,- rule: 'subscriptionAnnotationsDisagree',- message: err.message,- },- ]- }- throw err- }- if (isCodexUnassignedConnectionKey(key)) {- return [- {- field: `metadata.annotations.${CODEX_CONNECTION_REF_ANNOTATION}`,- rule: 'codexRecipeGrantRequired',- message: 'Codex subscription recipes must choose an existing ChatGPT grant',- },- ]- }- try {- assertCodexConnectionKey(key)- } catch {- return [- {- field: `metadata.annotations.${CODEX_CONNECTION_REF_ANNOTATION}`,- rule: 'codexRecipeGrantInvalid',- message: 'clerum.io/codex-connection-ref is not a valid connection key',- },- ]- }- return []-}--function bodyHasCodexGrantAnnotation(body: RecipeBody): boolean {- const annotations = body.metadata?.annotations- if (!annotations) return false- return (- Object.prototype.hasOwnProperty.call(annotations, CODEX_CONNECTION_REF_ANNOTATION) ||- Object.prototype.hasOwnProperty.call(annotations, SUBSCRIPTION_CONNECTION_REF_ANNOTATION)- )-}--function readRequestedGrokRecipeGrant(body: RecipeBody): string {- const result = readSubscriptionConnectionRef({- provider: 'grok-subscription',- annotations: recipeAnnotationStrings(body.metadata?.annotations),- })- if (!result.ok) {- throw new RecipeGrantAnnotationDisagreeError(result.message)- }- return result.connectionKey-}--function validateGrokRecipeGrant(- body: RecipeBody,- opts?: { allowOmittedGrant?: boolean }-): ValidationError[] {- if (!recipeUsesGrokBroker(body.spec)) return []- if (opts?.allowOmittedGrant && !bodyHasCodexGrantAnnotation(body)) return []- let key: string- try {- key = readRequestedGrokRecipeGrant(body)- } catch (err) {- if (err instanceof RecipeGrantAnnotationDisagreeError) {- return [- {- field: `metadata.annotations.${SUBSCRIPTION_CONNECTION_REF_ANNOTATION}`,- rule: 'subscriptionAnnotationsDisagree',- message: err.message,- },- ]- }- throw err- }- if (isGrokUnassignedConnectionKey(key) || key === GROK_UNASSIGNED_CONNECTION_KEY) {- return [- {- field: `metadata.annotations.${SUBSCRIPTION_CONNECTION_REF_ANNOTATION}`,- rule: 'grokRecipeGrantRequired',- message: 'Grok subscription recipes must choose an existing Grok grant',- },- ]- }- try {- assertGrokConnectionKey(key)- } catch {- return [- {- field: `metadata.annotations.${SUBSCRIPTION_CONNECTION_REF_ANNOTATION}`,- rule: 'grokRecipeGrantInvalid',- message: 'clerum.io/subscription-connection-ref is not a valid connection key',- },- ]- }- return []-}--function sanitizeRecipeCodexAnnotation(- body: RecipeBody,- currentAnnotations?: Record<string, string>,- currentSpec?: Record<string, unknown>-): Record<string, string> {- const grokMirrored = (key: string) => ({- [CODEX_CONNECTION_REF_ANNOTATION]: '',- [SUBSCRIPTION_CONNECTION_REF_ANNOTATION]: key,- })- if (recipeUsesGrokBroker(body.spec)) {- if (!bodyHasCodexGrantAnnotation(body)) return {}- const incoming = readRequestedGrokRecipeGrant(body)- return grokMirrored(isGrokUnassignedConnectionKey(incoming) ? '' : incoming)- }- const mirrored = (key: string) => ({- [CODEX_CONNECTION_REF_ANNOTATION]: key,- [SUBSCRIPTION_CONNECTION_REF_ANNOTATION]: key,- })- if (recipeUsesCodexBroker(body.spec)) {- if (!bodyHasCodexGrantAnnotation(body)) {- if (recipeUsesGrokBroker(currentSpec)) return mirrored('')- return {}- }- const annotations = recipeAnnotationStrings(body.metadata?.annotations) ?? {}- const alias = (annotations[CODEX_CONNECTION_REF_ANNOTATION] ?? '').trim()- const canonical = (annotations[SUBSCRIPTION_CONNECTION_REF_ANNOTATION] ?? '').trim()- if (canonical && alias && canonical !== alias) {- throw new RecipeGrantAnnotationDisagreeError('subscription connection annotations disagree')- }- // Grok writers emit canonical only. A missing Codex alias is leftover only- // when the previous spec was Grok — not when a Codex writer sent the- // canonical key alone.- if (recipeUsesGrokBroker(currentSpec) && !alias) return mirrored('')- const incoming = readRequestedCodexRecipeGrant(body)- return mirrored(isCodexUnassignedConnectionKey(incoming) ? '' : incoming)- }- const leavingCodex = recipeUsesCodexBroker(currentSpec) && !recipeHasPluginWorkloadSdk(body.spec)- const leavingGrok = recipeUsesGrokBroker(currentSpec) && !recipeHasPluginWorkloadSdk(body.spec)- if (leavingCodex || leavingGrok) {- return mirrored('')- }- if (bodyHasCodexGrantAnnotation(body)) {- const annotations = recipeAnnotationStrings(body.metadata?.annotations) ?? {}- const alias = (annotations[CODEX_CONNECTION_REF_ANNOTATION] ?? '').trim()- // This path is not a Codex recipe. Missing alias must not promote a- // canonical leftover onto the Codex alias.- if (!alias) return mirrored('')- const incoming = readRequestedCodexRecipeGrant(body)- return mirrored(isCodexUnassignedConnectionKey(incoming) ? '' : incoming)- }- void currentAnnotations- return {}-}-function sanitizeRecipeBody(body: RecipeBody,+ grantAnnotations: Record<string, string>,currentLabels?: Record<string, string>,- currentAnnotations?: Record<string, string>,- currentSpec?: Record<string, unknown>+ currentAnnotations?: Record<string, string>): {metadata: { name: string; labels?: Record<string, string>; annotations: Record<string, string> }spec: Record<string, unknown>@@ -1498,7 +1277,7 @@ function sanitizeRecipeBody(...(sanitizedLabels ? { labels: sanitizedLabels } : {}),annotations: {...(currentAnnotations ?? {}),- ...sanitizeRecipeCodexAnnotation(body, currentAnnotations, currentSpec),+ ...grantAnnotations,},},spec: body.spec as Record<string, unknown>,@@ -1785,9 +1564,9 @@ export function createAdminRecipesRouter(gateway: K8sGateway): Router {res.status(422).json({ valid: false, errors })return}- const grantErrors = [...validateCodexRecipeGrant(body), ...validateGrokRecipeGrant(body)]- if (grantErrors.length > 0) {- res.status(422).json({ valid: false, errors: grantErrors })+ const grant = resolveRecipeGrantTransition({ body })+ if (!grant.ok) {+ res.status(422).json({ valid: false, errors: grant.errors })return}const egressErrors = await validateWorkflowRecipeEgressPreflight(body.spec)@@ -1971,9 +1750,9 @@ export function createAdminRecipesRouter(gateway: K8sGateway): Router {res.status(422).json({ errors })return}- const grantErrors = [...validateCodexRecipeGrant(body), ...validateGrokRecipeGrant(body)]- if (grantErrors.length > 0) {- res.status(422).json({ errors: grantErrors })+ const grant = resolveRecipeGrantTransition({ body })+ if (!grant.ok) {+ res.status(422).json({ errors: grant.errors })return}const egressErrors = await validateWorkflowRecipeEgressPreflight(body.spec)@@ -2033,7 +1812,7 @@ export function createAdminRecipesRouter(gateway: K8sGateway): Router {// The reconciler still independently splits the rendered resources:// - MCP workloads (transport) → mcp-server// - non-MCP workloads + PVCs → sandbox-recipes- const sanitized = sanitizeRecipeBody(body)+ const sanitized = sanitizeRecipeBody(body, grant.annotations)const created = await gateway.createResource(PLURAL, sanitized, RECIPE_CRD_NAMESPACE)res.status(201)@@ -2081,14 +1860,6 @@ export function createAdminRecipesRouter(gateway: K8sGateway): Router {res.status(422).json({ errors })return}- const grantErrors = [- ...validateCodexRecipeGrant(body, { allowOmittedGrant: true }),- ...validateGrokRecipeGrant(body, { allowOmittedGrant: true }),- ]- if (grantErrors.length > 0) {- res.status(422).json({ errors: grantErrors })- return- }const egressErrors = await validateWorkflowRecipeEgressPreflight(body.spec)if (egressErrors.length > 0) {res.status(422).json({ errors: egressErrors })@@ -2115,6 +1886,25 @@ export function createAdminRecipesRouter(gateway: K8sGateway): Router {// Discover the canonical recipe resource and update it in sandbox-recipes.try {const { ns, resource } = await findRecipeNamespace(req.params.name)+ const currentMeta =+ isPlainObject(resource) && isPlainObject(resource.metadata)+ ? resource.metadata+ : undefined+ const currentLabels = stringLabels(currentMeta?.labels)+ const currentAnnotations = stringLabels(currentMeta?.annotations)+ const currentSpec =+ isPlainObject(resource) && isPlainObject(resource.spec) ? resource.spec : undefined+ // Grant identity transitions depend on the stored recipe (provider+ // change, broker→static). Resolve before any pull-secret mint so a 422+ // leaves no side effect.+ const grant = resolveRecipeGrantTransition({+ body,+ current: { spec: currentSpec, annotations: currentAnnotations },+ })+ if (!grant.ok) {+ res.status(422).json({ errors: grant.errors })+ return+ }// Same guard as create: an update is how a recipe FIRST acquires a platform image// (edit the workload's image, keep the name), and the stored CRD is what WRC// reconciles. Provision AFTER the existence lookup, so a PUT naming a recipe that@@ -2131,15 +1921,12 @@ export function createAdminRecipesRouter(gateway: K8sGateway): Router {return}}- const currentMeta =- isPlainObject(resource) && isPlainObject(resource.metadata)- ? resource.metadata- : undefined- const currentLabels = stringLabels(currentMeta?.labels)- const currentAnnotations = stringLabels(currentMeta?.annotations)- const currentSpec =- isPlainObject(resource) && isPlainObject(resource.spec) ? resource.spec : undefined- const sanitized = sanitizeRecipeBody(body, currentLabels, currentAnnotations, currentSpec)+ const sanitized = sanitizeRecipeBody(+ body,+ grant.annotations,+ currentLabels,+ currentAnnotations+ )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 b6f6610bb..265519e1c 100644--- a/control-api/src/routes/mcp-host/llmProviderAttempts.routes.ts+++ b/control-api/src/routes/mcp-host/llmProviderAttempts.routes.ts@@ -15,7 +15,6 @@ import {import {collectHostOauthBrokerProviders,collectRecipeOauthBrokerProviders,- readSubscriptionConnectionRef,} from '../../services/subscriptionGrantIdentity.js'import { llmProviderAttemptAuthorizeRateLimits } from '../workflows/shared/rateLimit.js'@@ -53,13 +52,6 @@ export type LiveBrokerAssignment = {annotations?: Record<string, string>}-function throwAttestError(result: { ok: false; code: string; message: string }): never {- throw new LlmProviderAttemptAuthorizeError(- result.code as 'host_binding_mismatch' | 'unassigned_connection',- result.message- )-}-export async function resolveHostAssignedAssignment(gateway: Pick<K8sGateway, 'getResource'>,hostRef: string@@ -116,20 +108,6 @@ export async function resolveHostAssignedAssignment(}}-export async function resolveHostAssignedConnectionKey(- gateway: Pick<K8sGateway, 'getResource'>,- hostRef: string-): Promise<string> {- const assignment = await resolveHostAssignedAssignment(gateway, hostRef)- if (!assignment.annotations) return assignment.liveConnectionRef- const read = readSubscriptionConnectionRef({- provider: assignment.liveBrokerProviders[0] ?? 'codex-subscription',- annotations: assignment.annotations,- })- if (!read.ok) throwAttestError(read)- return read.connectionKey-}-export function createMcpHostLlmProviderAttemptRoutes(gateway: K8sGateway): Router {const router = Router()router.post(@@ -144,7 +122,6 @@ export function createMcpHostLlmProviderAttemptRoutes(gateway: K8sGateway): Rout}try {const result = await authorizeLlmProviderAttempt(claims, req.body, {- resolveConnectionKey: hostRef => resolveHostAssignedConnectionKey(gateway, hostRef),resolveAssignment: hostRef => resolveHostAssignedAssignment(gateway, hostRef),})res.status(200).json(result)diff --git a/control-api/src/services/llmProviderAttemptAuthorizer.ts b/control-api/src/services/llmProviderAttemptAuthorizer.tsindex cc208ddb0..c88d7ba99 100644--- a/control-api/src/services/llmProviderAttemptAuthorizer.ts+++ b/control-api/src/services/llmProviderAttemptAuthorizer.ts@@ -110,7 +110,6 @@ export type LlmProviderAttemptAuthorizerDeps = {withTransaction: typeof withTransactiongetConnection: typeof getSafeCodexSubscriptionConnectiongetModelState: typeof getCodexCatalogModelState- resolveConnectionKey: (hostRef: string) => Promise<string>/*** Live oauth-broker targets on the Host/recipe. Required: a missing* assignment must not fall back to `request.provider` (that made D6 a no-op).@@ -133,7 +132,6 @@ const defaultDeps = (): LlmProviderAttemptAuthorizerDeps => ({withTransaction,getConnection: getSafeCodexSubscriptionConnection,getModelState: getCodexCatalogModelState,- resolveConnectionKey: async () => CODEX_UNASSIGNED_CONNECTION_KEY,resolveAssignment: async () => ({liveBrokerProviders: [],liveConnectionRef: CODEX_UNASSIGNED_CONNECTION_KEY,diff --git a/control-api/src/services/recipeCodexGrantIdentity.ts b/control-api/src/services/recipeCodexGrantIdentity.tsindex 7ff807696..8a388e7b9 100644--- a/control-api/src/services/recipeCodexGrantIdentity.ts+++ b/control-api/src/services/recipeCodexGrantIdentity.ts@@ -15,6 +15,7 @@ import {import { K8sConflictError } from './resourceService.js'import {SUBSCRIPTION_CONNECTION_REF_ANNOTATION,+ collectRecipeOauthBrokerProviders,readSubscriptionConnectionRef,} from './subscriptionGrantIdentity.js'@@ -106,11 +107,21 @@ export async function publishRecipeGrantIdentity(input: {)}+ const provider = grok ? 'grok-subscription' : 'codex-subscription'+ // The recipe's agent / step agents own the grant annotations when they name+ // an oauth-broker. Publishing another broker's identity would rewrite the+ // agent grant (e.g. a Grok SDK key read back as the Codex agent's key).+ const agentBrokers = collectRecipeOauthBrokerProviders(asRecord(current.spec) ?? {})+ if (agentBrokers.length > 0 && !agentBrokers.includes(provider)) {+ throw new RecipeCodexGrantIdentityError(+ 409,+ 'oauth_broker_provider_conflict',+ `WorkflowRecipe agent uses ${agentBrokers.join(', ')}; cannot publish a ${provider} grant`+ )+ }+const annotations = stringMap(current.metadata?.annotations)- const previous = readSubscriptionConnectionRef({- provider: grok ? 'grok-subscription' : 'codex-subscription',- annotations,- })+ const previous = readSubscriptionConnectionRef({ provider, annotations })if (previous.ok && previous.connectionKey === next) {return { published: next, resourceVersion: current.metadata?.resourceVersion, noop: true }}diff --git a/control-api/src/services/recipeGrantTransition.ts b/control-api/src/services/recipeGrantTransition.tsnew file mode 100644index 000000000..79c247e83--- /dev/null+++ b/control-api/src/services/recipeGrantTransition.ts@@ -0,0 +1,201 @@+import {+ CODEX_CONNECTION_REF_ANNOTATION,+ assertCodexConnectionKey,+ isCodexUnassignedConnectionKey,+} from './codexSubscriptionConnection.js'+import {+ assertGrokConnectionKey,+ isGrokUnassignedConnectionKey,+} from './grokSubscriptionConnection.js'+import {+ SUBSCRIPTION_CONNECTION_REF_ANNOTATION,+ collectRecipeOauthBrokerProviders,+} from './subscriptionGrantIdentity.js'++/**+ * Server authority for WorkflowRecipe oauth-broker grant annotations.+ *+ * Write shapes:+ * - codex-subscription: `{codex-connection-ref: k, subscription-connection-ref: k}`+ * - any other broker (grok-subscription): `{codex-connection-ref: '', subscription-connection-ref: k}`+ *+ * Transition table (explicit = either annotation key present in the body):+ * - alias and canonical both non-empty and unequal → 422 on any spec+ * - create / static→broker: omitted → grant required; explicit → validate, write shape+ * - same broker: omitted → keep stored; explicit → validate, write shape+ * - broker change: omitted → 422 providerChangeRequiresGrant; explicit → validate, write shape+ * - broker→static: clear both unless the recipe declares pluginWorkloadSdk (SDK route owns it)+ * - static→static / static create: keep (the SDK route owns static-recipe identity)+ *+ * Pure and total: every input maps to a result or 422 errors, never a throw.+ */++export interface RecipeGrantValidationError {+ field: string+ message: string+ rule?: string+}++export type RecipeGrantTransitionResult =+ | {+ ok: true+ /** Annotation patch merged over the stored annotations. `{}` keeps them. */+ annotations: Record<string, string>+ }+ | { ok: false; errors: RecipeGrantValidationError[] }++export interface RecipeGrantTransitionInput {+ body: {+ spec?: Record<string, unknown>+ metadata?: { annotations?: Record<string, unknown> }+ }+ /** Stored recipe on update; omitted for create and /validate. */+ current?: {+ spec?: Record<string, unknown>+ annotations?: Record<string, string>+ } | null+}++const ALIAS_FIELD = `metadata.annotations.${CODEX_CONNECTION_REF_ANNOTATION}`+const CANONICAL_FIELD = `metadata.annotations.${SUBSCRIPTION_CONNECTION_REF_ANNOTATION}`++type BrokerRules = {+ field: string+ requiredRule: string+ requiredMessage: string+ invalidRule: string+ invalidMessage: string+ isUnassigned: (key: string) => boolean+ assertKey: (key: string) => string+ shape: (key: string) => Record<string, string>+}++const CODEX_RULES: BrokerRules = {+ field: ALIAS_FIELD,+ requiredRule: 'codexRecipeGrantRequired',+ requiredMessage: 'Codex subscription recipes must choose an existing ChatGPT grant',+ invalidRule: 'codexRecipeGrantInvalid',+ invalidMessage: 'clerum.io/codex-connection-ref is not a valid connection key',+ isUnassigned: isCodexUnassignedConnectionKey,+ assertKey: assertCodexConnectionKey,+ shape: key => ({+ [CODEX_CONNECTION_REF_ANNOTATION]: key,+ [SUBSCRIPTION_CONNECTION_REF_ANNOTATION]: key,+ }),+}++const GROK_RULES: BrokerRules = {+ field: CANONICAL_FIELD,+ requiredRule: 'grokRecipeGrantRequired',+ requiredMessage: 'Grok subscription recipes must choose an existing Grok grant',+ invalidRule: 'grokRecipeGrantInvalid',+ invalidMessage: 'clerum.io/subscription-connection-ref is not a valid connection key',+ isUnassigned: isGrokUnassignedConnectionKey,+ assertKey: assertGrokConnectionKey,+ shape: key => ({+ [CODEX_CONNECTION_REF_ANNOTATION]: '',+ [SUBSCRIPTION_CONNECTION_REF_ANNOTATION]: key,+ }),+}++function brokerRules(provider: string): BrokerRules {+ return provider === 'codex-subscription' ? CODEX_RULES : GROK_RULES+}++function isRecord(value: unknown): value is Record<string, unknown> {+ return Boolean(value) && typeof value === 'object' && !Array.isArray(value)+}++function recipeBroker(spec: unknown): string | undefined {+ if (!isRecord(spec)) return undefined+ return collectRecipeOauthBrokerProviders(spec)[0]+}++function hasPluginWorkloadSdk(spec: unknown): boolean {+ return isRecord(spec) && isRecord(spec.pluginWorkloadSdk)+}++function stringAnnotation(annotations: Record<string, unknown>, key: string): string {+ const value = annotations[key]+ return typeof value === 'string' ? value.trim() : ''+}++function error(field: string, rule: string, message: string): RecipeGrantTransitionResult {+ return { ok: false, errors: [{ field, rule, message }] }+}++const CLEARED = {+ [CODEX_CONNECTION_REF_ANNOTATION]: '',+ [SUBSCRIPTION_CONNECTION_REF_ANNOTATION]: '',+}++export function resolveRecipeGrantTransition(+ input: RecipeGrantTransitionInput+): RecipeGrantTransitionResult {+ const rawAnnotations = isRecord(input.body.metadata?.annotations)+ ? input.body.metadata.annotations+ : {}+ const explicit =+ Object.prototype.hasOwnProperty.call(rawAnnotations, CODEX_CONNECTION_REF_ANNOTATION) ||+ Object.prototype.hasOwnProperty.call(rawAnnotations, SUBSCRIPTION_CONNECTION_REF_ANNOTATION)+ const alias = stringAnnotation(rawAnnotations, CODEX_CONNECTION_REF_ANNOTATION)+ const canonical = stringAnnotation(rawAnnotations, SUBSCRIPTION_CONNECTION_REF_ANNOTATION)+ const nextBroker = recipeBroker(input.body.spec)++ if (explicit && alias && canonical && alias !== canonical) {+ return error(+ nextBroker && nextBroker !== 'codex-subscription' ? CANONICAL_FIELD : ALIAS_FIELD,+ 'subscriptionAnnotationsDisagree',+ 'subscription connection annotations disagree'+ )+ }++ const current = input.current ?? undefined+ const previousBroker = current ? recipeBroker(current.spec) : undefined++ if (!nextBroker) {+ // Leaving a broker without an SDK: the agent grant no longer has an owner.+ if (previousBroker && !hasPluginWorkloadSdk(input.body.spec)) {+ return { ok: true, annotations: { ...CLEARED } }+ }+ // Static recipes (and SDK recipes leaving a broker) keep whatever the+ // plugin-workload-sdk grant route published.+ return { ok: true, annotations: {} }+ }++ const rules = brokerRules(nextBroker)+ if (!explicit) {+ if (previousBroker === nextBroker) return { ok: true, annotations: {} }+ if (previousBroker) {+ return error(+ rules.field,+ 'providerChangeRequiresGrant',+ `Changing the recipe oauth-broker provider from ${previousBroker} to ${nextBroker} requires choosing a ${nextBroker} grant`+ )+ }+ return error(rules.field, rules.requiredRule, rules.requiredMessage)+ }++ let key: string+ if (nextBroker === 'codex-subscription') {+ key = canonical || alias+ } else {+ if (alias) {+ return error(+ CANONICAL_FIELD,+ 'subscriptionAnnotationsDisagree',+ 'Codex connection annotation is not valid for this oauth-broker provider'+ )+ }+ key = canonical+ }+ if (!key || rules.isUnassigned(key)) {+ return error(rules.field, rules.requiredRule, rules.requiredMessage)+ }+ try {+ rules.assertKey(key)+ } catch {+ return error(rules.field, rules.invalidRule, rules.invalidMessage)+ }+ return { ok: true, annotations: rules.shape(key) }+}diff --git a/control-api/test/pluginWorkloadSdkCodexDualLedger.realPostgres.integration.test.ts b/control-api/test/pluginWorkloadSdkCodexDualLedger.realPostgres.integration.test.tsindex 463f2086b..ce5157e49 100644--- a/control-api/test/pluginWorkloadSdkCodexDualLedger.realPostgres.integration.test.ts+++ b/control-api/test/pluginWorkloadSdkCodexDualLedger.realPostgres.integration.test.ts@@ -145,7 +145,6 @@ describeRealPostgres('Plugin Workload SDK Codex dual ledger on real PostgreSQL',},getConnection: getSafeCodexSubscriptionConnection,getModelState: getCodexCatalogModelState,- resolveConnectionKey: async () => 'deployment-default',resolveAssignment: async () => ({liveBrokerProviders: ['codex-subscription'],liveConnectionRef: 'deployment-default',diff --git a/control-api/test/pluginWorkloadSdkGrokDualLedger.realPostgres.integration.test.ts b/control-api/test/pluginWorkloadSdkGrokDualLedger.realPostgres.integration.test.tsindex d001e4d30..a52001d73 100644--- a/control-api/test/pluginWorkloadSdkGrokDualLedger.realPostgres.integration.test.ts+++ b/control-api/test/pluginWorkloadSdkGrokDualLedger.realPostgres.integration.test.ts@@ -192,7 +192,6 @@ describeRealPostgres('Plugin Workload SDK Grok dual ledger on real PostgreSQL',},getConnection: async () => current,getModelState: async () => ({ enabled: true, stale: false }),- resolveConnectionKey: async () => CONNECTION_KEY,resolveAssignment: async () => ({liveBrokerProviders: ['grok-subscription'],liveConnectionRef: CONNECTION_KEY,diff --git a/control-api/test/routes.admin.codexSubscription.test.ts b/control-api/test/routes.admin.codexSubscription.test.tsindex 7d3d57686..e8a6e9e34 100644--- a/control-api/test/routes.admin.codexSubscription.test.ts+++ b/control-api/test/routes.admin.codexSubscription.test.ts@@ -962,6 +962,35 @@ describe('admin Codex subscription routes', () => {expect(res.body).toEqual({ error: 'no_grant' })})+ it('Grok metadata PATCH reports only Grok Hosts assigned to a same-named key', async () => {+ config.grokSubscriptionEnabled = true+ vi.mocked(pool.query).mockResolvedValueOnce({+ rows: [safeCreatedRow('team-shared', 'Shared')],+ rowCount: 1,+ })+ const gateway = makeGateway()+ gateway.listResource.mockResolvedValue([+ {+ metadata: { name: 'codex-host-a' },+ spec: {+ model: { provider: 'codex-subscription', name: 'gpt-5.1', connectionRef: 'team-shared' },+ },+ },+ {+ metadata: { name: 'grok-host-b' },+ spec: {+ model: { provider: 'grok-subscription', name: 'grok-4.6', connectionRef: 'team-shared' },+ },+ },+ ])+ const res = await request(makeAuthedApp(gateway))+ .patch('/admin/llm/providers/grok-subscription/connections/team-shared')+ .send({ displayName: 'Shared' })+ expect(res.status).toBe(200)+ expect(res.body.assignedHosts).toEqual([{ name: 'grok-host-b' }])+ assertNoLeak(res.body)+ })+it('lists grant models and toggles enabled', async () => {oauth.getConnection.mockResolvedValue({id: 'id-codex-aaa',diff --git a/control-api/test/routes.adminPluginWorkloadSdk.test.ts b/control-api/test/routes.adminPluginWorkloadSdk.test.tsindex db31268c8..76c29e31a 100644--- a/control-api/test/routes.adminPluginWorkloadSdk.test.ts+++ b/control-api/test/routes.adminPluginWorkloadSdk.test.ts@@ -885,6 +885,54 @@ describe('routes/admin/pluginWorkloadSdk — grants', () => {})})+ it.each([+ ['spec.agent', { agent: { provider: 'codex-subscription', model: 'gpt-5.3-codex' } }],+ [+ 'a step agent',+ {+ agent: { provider: 'openai', model: 'gpt-5.1' },+ steps: [{ id: 's', agent: { provider: 'codex-subscription', model: 'gpt-5.3-codex' } }],+ },+ ],+ ])(+ 'rejects a Grok target when %s is Codex (oauth_broker_provider_conflict)',+ async (_label, spec) => {+ vi.mocked(isGrokAssignmentAllowed).mockResolvedValue(true)+ getResource.mockResolvedValue({+ metadata: {+ annotations: {+ 'clerum.io/codex-connection-ref': 'team-plus',+ 'clerum.io/subscription-connection-ref': 'team-plus',+ },+ },+ spec,+ })+ const res = await request(buildApp())+ .post('/admin/plugin-workload-sdk/grants')+ .send(grokGrantBody)+ expect(res.status).toBe(400)+ expect(res.body).toEqual({ error: 'oauth_broker_provider_conflict' })+ expect(publishRecipeGrantIdentity).not.toHaveBeenCalled()+ expect(updateResource).not.toHaveBeenCalled()+ expect(sdkDb.upsertGrant).not.toHaveBeenCalled()+ }+ )++ it('accepts a Grok target on a Grok-agent recipe', async () => {+ vi.mocked(sdkDb.upsertGrant).mockResolvedValue({ id: 'g-grok' } as never)+ vi.mocked(isGrokAssignmentAllowed).mockResolvedValue(true)+ getResource.mockResolvedValue({+ spec: { agent: { provider: 'grok-subscription', model: 'grok-4.6' } },+ })+ const res = await request(buildApp())+ .post('/admin/plugin-workload-sdk/grants')+ .send(grokGrantBody)+ expect(res.status).toBe(200)+ expect(publishRecipeGrantIdentity).toHaveBeenCalledWith(+ expect.objectContaining({ next: 'team-grok', provider: 'grok-subscription' })+ )+ })+it('fails closed when the Grok grant is unknown or does not offer the model', async () => {vi.mocked(isGrokAssignmentAllowed).mockResolvedValue(false)const res = await request(buildApp())@@ -1218,6 +1266,21 @@ describe('routes/admin/pluginWorkloadSdk — grants', () => {})})+ it('does not unassign a recipe whose step agent is Codex when the last SDK grant is deleted', async () => {+ vi.mocked(sdkDb.deleteGrant).mockResolvedValue(true)+ getResource.mockResolvedValue({+ spec: {+ agent: { provider: 'openai', model: 'gpt-5.1' },+ steps: [{ id: 's', 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()+ })+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({diff --git a/control-api/test/routes.adminRecipes.test.ts b/control-api/test/routes.adminRecipes.test.tsindex 05cd1108d..52ca20911 100644--- a/control-api/test/routes.adminRecipes.test.ts+++ b/control-api/test/routes.adminRecipes.test.ts@@ -296,71 +296,164 @@ describe.sequential('routes/admin/recipes', () => {})})- it('PUT /admin/recipes/:name — does not promote a leftover Grok canonical key onto Codex', async () => {+ const ALIAS = 'clerum.io/codex-connection-ref'+ const CANONICAL = 'clerum.io/subscription-connection-ref'++ function brokerSpec(provider: 'codex-subscription' | 'grok-subscription') {+ return {+ agent: {+ provider,+ model: provider === 'grok-subscription' ? 'grok-4.6' : 'gpt-5.1',+ },+ triggers: { onDemand: { allowedActors: ['user'] } },+ steps: [{ id: 'draft', instruction: 'Write', timeoutSeconds: 600 }],+ }+ }++ const SDK_STATIC_SPEC = {+ pluginWorkloadSdk: { promptBridge: { allowedModels: ['grok-4.6'] } },+ workloads: [{ id: 'svc', type: 'deployment', image: 'my-image:latest' }],+ }++ async function createGrokRecipe(name: string) {await api.post('/admin/recipes').send({- metadata: {- name: 'grok-then-codex',- annotations: { 'clerum.io/subscription-connection-ref': 'team-grok' },- },- spec: {- agent: { provider: 'grok-subscription', model: 'grok-4.6' },- triggers: { onDemand: { allowedActors: ['user'] } },- steps: [{ id: 'draft', instruction: 'Write', timeoutSeconds: 600 }],- },+ metadata: { name, annotations: { [ALIAS]: '', [CANONICAL]: 'team-grok' } },+ spec: brokerSpec('grok-subscription'),}).expect(201)+ }++ // Grok→Codex with the canonical-only writer shape used to validate the key+ // and then silently persist both annotations empty. The server now treats+ // an explicit key as the Codex choice and writes the Codex shape.+ it('PUT /admin/recipes/:name — Grok→Codex canonical-only writes the Codex shape (no silent clear)', async () => {+ await createGrokRecipe('grok-then-codex')const res = await api.put('/admin/recipes/grok-then-codex').send({- metadata: {- annotations: { 'clerum.io/subscription-connection-ref': 'team-grok' },- },- spec: {- agent: { provider: 'codex-subscription', model: 'gpt-5.1' },- triggers: { onDemand: { allowedActors: ['user'] } },- steps: [{ id: 'draft', instruction: 'Write', timeoutSeconds: 600 }],- },+ metadata: { annotations: { [CANONICAL]: 'team-codex' } },+ spec: brokerSpec('codex-subscription'),}).expect(200)expect(res.body.metadata.annotations).toEqual({- 'clerum.io/codex-connection-ref': '',- 'clerum.io/subscription-connection-ref': '',+ [ALIAS]: 'team-codex',+ [CANONICAL]: 'team-codex',})})- it('PUT /admin/recipes/:name — clears leftover Grok when switching to Codex without annotations', async () => {+ // Omitted annotations across a broker change used to clear (Grok→Codex) or+ // retain the old broker's key (Codex→Grok). Both now fail closed.+ it('PUT /admin/recipes/:name — Grok→Codex without annotations is 422 providerChangeRequiresGrant', async () => {+ await createGrokRecipe('grok-then-codex-omit')+ const res = await api+ .put('/admin/recipes/grok-then-codex-omit')+ .send({ spec: brokerSpec('codex-subscription') })+ .expect(422)+ expect(res.body.errors[0].rule).toBe('providerChangeRequiresGrant')+ const stored = await gateway.getResource('workflowrecipes', 'grok-then-codex-omit', SANDBOX_NS)+ expect((stored as { metadata: { annotations: unknown } }).metadata.annotations).toEqual({+ [ALIAS]: '',+ [CANONICAL]: 'team-grok',+ })+ })++ it('PUT /admin/recipes/:name — Codex→Grok without annotations is 422 providerChangeRequiresGrant', async () => {+ await api+ .post('/admin/recipes')+ .send(codexSubscriptionRecipe('codex-then-grok-omit', 'team-plus'))+ .expect(201)+ const res = await api+ .put('/admin/recipes/codex-then-grok-omit')+ .send({ spec: brokerSpec('grok-subscription') })+ .expect(422)+ expect(res.body.errors[0].rule).toBe('providerChangeRequiresGrant')+ })++ it('PUT /admin/recipes/:name — Codex→Grok explicit canonical writes the Grok shape', async () => {await api.post('/admin/recipes')+ .send(codexSubscriptionRecipe('codex-then-grok', 'team-plus'))+ .expect(201)+ const res = await api+ .put('/admin/recipes/codex-then-grok').send({- metadata: {- name: 'grok-then-codex-omit',- annotations: { 'clerum.io/subscription-connection-ref': 'team-grok' },- },- spec: {- agent: { provider: 'grok-subscription', model: 'grok-4.6' },- triggers: { onDemand: { allowedActors: ['user'] } },- steps: [{ id: 'draft', instruction: 'Write', timeoutSeconds: 600 }],- },+ metadata: { annotations: { [CANONICAL]: 'team-grok' } },+ spec: brokerSpec('grok-subscription'),+ })+ .expect(200)+ expect(res.body.metadata.annotations).toEqual({ [ALIAS]: '', [CANONICAL]: 'team-grok' })+ })++ it('PUT /admin/recipes/:name — static→Codex without annotations requires a grant', async () => {+ await api.post('/admin/recipes').send(VALID_RECIPE).expect(201)+ const res = await api+ .put('/admin/recipes/my-recipe')+ .send({ spec: brokerSpec('codex-subscription') })+ .expect(422)+ expect(res.body.errors[0].rule).toBe('codexRecipeGrantRequired')+ })++ it.each([+ ['POST /admin/recipes', 'post', '/admin/recipes'],+ ['POST /admin/recipes/validate', 'post', '/admin/recipes/validate'],+ ['PUT /admin/recipes/:name', 'put', '/admin/recipes/my-recipe'],+ ] as const)(+ '%s — static recipe with disagreeing annotations is 422, not 500',+ async (_label, method, path) => {+ if (method === 'put') await api.post('/admin/recipes').send(VALID_RECIPE).expect(201)+ const res = await api[method](path).send({+ metadata: { name: 'my-recipe', annotations: { [ALIAS]: 'a', [CANONICAL]: 'b' } },+ spec: VALID_RECIPE.spec,})+ expect(res.status).toBe(422)+ expect(res.body.errors[0].rule).toBe('subscriptionAnnotationsDisagree')+ }+ )++ it('PUT /admin/recipes/:name — Codex→static with SDK keeps the SDK-owned identity', async () => {+ await api+ .post('/admin/recipes')+ .send(codexSubscriptionRecipe('codex-then-sdk', 'team-plus')).expect(201)const res = await api- .put('/admin/recipes/grok-then-codex-omit')+ .put('/admin/recipes/codex-then-sdk').send({- spec: {- agent: { provider: 'codex-subscription', model: 'gpt-5.1' },- triggers: { onDemand: { allowedActors: ['user'] } },- steps: [{ id: 'draft', instruction: 'Write', timeoutSeconds: 600 }],- },+ metadata: { annotations: { [ALIAS]: '', [CANONICAL]: '' } },+ spec: SDK_STATIC_SPEC,}).expect(200)expect(res.body.metadata.annotations).toEqual({- 'clerum.io/codex-connection-ref': '',- 'clerum.io/subscription-connection-ref': '',+ [ALIAS]: 'team-plus',+ [CANONICAL]: 'team-plus',})})+ it('PUT /admin/recipes/:name — static SDK recipe keeps a Grok SDK identity when the editor sends empty annotations', async () => {+ await api+ .post('/admin/recipes')+ .send({ metadata: { name: 'sdk-grok' }, spec: SDK_STATIC_SPEC })+ .expect(201)+ await gateway.updateResource(+ 'workflowrecipes',+ 'sdk-grok',+ {+ metadata: { annotations: { [ALIAS]: '', [CANONICAL]: 'team-grok' } },+ spec: SDK_STATIC_SPEC,+ },+ SANDBOX_NS+ )+ const res = await api+ .put('/admin/recipes/sdk-grok')+ .send({+ metadata: { annotations: { [ALIAS]: '', [CANONICAL]: '' } },+ spec: SDK_STATIC_SPEC,+ })+ .expect(200)+ expect(res.body.metadata.annotations).toEqual({ [ALIAS]: '', [CANONICAL]: 'team-grok' })+ })+it('POST /admin/recipes — rejects mixed oauth-broker providers on agent and steps', async () => {const res = await api.post('/admin/recipes').send({metadata: { name: 'mixed-broker' },diff --git a/control-api/test/routes.mcp-host.llmProviderAttempts.test.ts b/control-api/test/routes.mcp-host.llmProviderAttempts.test.tsindex c9ffa3a56..43fc9bd22 100644--- a/control-api/test/routes.mcp-host.llmProviderAttempts.test.ts+++ b/control-api/test/routes.mcp-host.llmProviderAttempts.test.ts@@ -4,7 +4,6 @@ import request from 'supertest'import {createMcpHostLlmProviderAttemptRoutes,resolveHostAssignedAssignment,- resolveHostAssignedConnectionKey,} from '../src/routes/mcp-host/llmProviderAttempts.routes.js'import { LlmProviderAttemptAuthorizeError } from '../src/services/llmProviderAttemptAuthorizer.js'import * as authorizer from '../src/services/llmProviderAttemptAuthorizer.js'@@ -175,7 +174,7 @@ describe('POST /api/v1/mcp-host/llm/provider-attempts/authorize', () => {})})-describe('resolveHostAssignedConnectionKey', () => {+describe('resolveHostAssignedAssignment', () => {it('reads connectionRef from a static primary with a Codex fallback', async () => {const gateway = {getResource: vi.fn().mockResolvedValue({@@ -206,58 +205,42 @@ describe('resolveHostAssignedConnectionKey', () => {})})- it('fails closed when recipe subscription annotations disagree', async () => {- const gateway = {- getResource: vi.fn().mockResolvedValue({- metadata: {- annotations: {- 'clerum.io/codex-connection-ref': 'team-plus',- 'clerum.io/subscription-connection-ref': 'other-key',- },- },- spec: { agent: { provider: 'codex-subscription' } },- }),- }- await expect(- resolveHostAssignedConnectionKey(gateway, 'sandbox-recipes/codex-recipe')- ).rejects.toMatchObject({ code: 'host_binding_mismatch' })- })-it('reads the Host connectionRef and treats a missing field as unassigned', async () => {const gateway = {getResource: vi.fn().mockResolvedValue({spec: { model: { provider: 'codex-subscription', connectionRef: 'team-plus' } },}),}- await expect(resolveHostAssignedConnectionKey(gateway, 'agent-a')).resolves.toBe('team-plus')-- gateway.getResource.mockResolvedValueOnce({- spec: { model: { provider: 'codex-subscription' } },+ await expect(resolveHostAssignedAssignment(gateway, 'agent-a')).resolves.toMatchObject({+ liveConnectionRef: 'team-plus',})- await expect(resolveHostAssignedConnectionKey(gateway, 'agent-b')).resolves.toBe('unassigned')gateway.getResource.mockResolvedValueOnce({- spec: { model: { provider: 'codex-subscription', connectionRef: 'unassigned' } },+ spec: { model: { provider: 'codex-subscription' } },})- await expect(resolveHostAssignedConnectionKey(gateway, 'agent-c')).resolves.toBe('unassigned')-- gateway.getResource.mockResolvedValueOnce({- spec: { model: { provider: 'codex-subscription', connectionRef: 'deployment-default' } },+ await expect(resolveHostAssignedAssignment(gateway, 'agent-b')).resolves.toMatchObject({+ liveConnectionRef: 'unassigned',})- await expect(resolveHostAssignedConnectionKey(gateway, 'agent-d')).resolves.toBe(- 'deployment-default'- )})- it('attests a recipe caller from the codex-connection-ref annotation', async () => {+ it('returns recipe broker targets and raw annotations for the authorizer to attest', async () => {+ const annotations = {+ 'clerum.io/codex-connection-ref': 'team-plus',+ 'clerum.io/subscription-connection-ref': 'other-key',+ }const gateway = {getResource: vi.fn().mockResolvedValue({- metadata: { annotations: { 'clerum.io/codex-connection-ref': 'team-plus' } },+ metadata: { annotations },+ spec: { agent: { provider: 'codex-subscription' } },}),}await expect(- resolveHostAssignedConnectionKey(gateway, 'sandbox-recipes/codex-recipe')- ).resolves.toBe('team-plus')+ resolveHostAssignedAssignment(gateway, 'sandbox-recipes/codex-recipe')+ ).resolves.toEqual({+ liveBrokerProviders: ['codex-subscription'],+ liveConnectionRef: 'unassigned',+ annotations,+ })expect(gateway.getResource).toHaveBeenCalledWith('workflowrecipes','codex-recipe',@@ -265,37 +248,16 @@ describe('resolveHostAssignedConnectionKey', () => {)})- it('treats a recipe without the grant annotation as unassigned', async () => {- const gateway = {- getResource: vi.fn().mockResolvedValue({ metadata: { annotations: {} } }),- }- await expect(- resolveHostAssignedConnectionKey(gateway, 'sandbox-recipes/codex-recipe')- ).resolves.toBe('unassigned')-- gateway.getResource.mockResolvedValueOnce({- metadata: { annotations: { 'clerum.io/codex-connection-ref': ' ' } },- })- await expect(- resolveHostAssignedConnectionKey(gateway, 'sandbox-recipes/blank-annotation')- ).resolves.toBe('unassigned')-- gateway.getResource.mockResolvedValueOnce({})- await expect(- resolveHostAssignedConnectionKey(gateway, 'sandbox-recipes/no-metadata')- ).resolves.toBe('unassigned')- })-it('fails closed when the recipe cannot be attested', async () => {const gateway = {getResource: vi.fn().mockRejectedValue(Object.assign(new Error('nf'), { code: 404 })),}await expect(- resolveHostAssignedConnectionKey(gateway, 'sandbox-recipes/ghost-recipe')+ resolveHostAssignedAssignment(gateway, 'sandbox-recipes/ghost-recipe')).rejects.toMatchObject({ code: 'host_binding_mismatch' })// Malformed multi-segment refs never reach the gateway.- await expect(resolveHostAssignedConnectionKey(gateway, 'ns/name/extra')).rejects.toMatchObject({+ await expect(resolveHostAssignedAssignment(gateway, 'ns/name/extra')).rejects.toMatchObject({code: 'host_binding_mismatch',})})@@ -304,44 +266,8 @@ describe('resolveHostAssignedConnectionKey', () => {const gateway = {getResource: vi.fn().mockRejectedValue(Object.assign(new Error('nf'), { code: 404 })),}- await expect(resolveHostAssignedConnectionKey(gateway, 'ghost')).rejects.toMatchObject({+ await expect(resolveHostAssignedAssignment(gateway, 'ghost')).rejects.toMatchObject({code: 'host_binding_mismatch',})})-- 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')- ).resolves.toBe('team-plus')- })-- it('keeps a recipes-only annotation as identity', async () => {- const gateway = {- getResource: vi.fn().mockResolvedValue({- metadata: { annotations: { 'clerum.io/codex-connection-ref': 'team-plus' } },- spec: { agent: { provider: 'codex-subscription', model: 'gpt-5.3-codex' } },- }),- }- await expect(- resolveHostAssignedConnectionKey(gateway, 'sandbox-recipes/codex-recipe')- ).resolves.toBe('team-plus')- })-- 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' } },- spec: { pluginWorkloadSdk: { family: 'promptBridge' } },- }),- }- await expect(- resolveHostAssignedConnectionKey(gateway, 'sandbox-recipes/codex-recipe')- ).resolves.toBe('team-plus')- })})diff --git a/control-api/test/services.llmProviderAttemptAuthorization.realPostgres.integration.test.ts b/control-api/test/services.llmProviderAttemptAuthorization.realPostgres.integration.test.tsindex def692584..93b13e66f 100644--- a/control-api/test/services.llmProviderAttemptAuthorization.realPostgres.integration.test.ts+++ b/control-api/test/services.llmProviderAttemptAuthorization.realPostgres.integration.test.ts@@ -101,7 +101,6 @@ describeRealPostgres('Codex provider-attempt authorization on real PostgreSQL',},getConnection: getSafeCodexSubscriptionConnection,getModelState: getCodexCatalogModelState,- resolveConnectionKey: async () => 'deployment-default',resolveAssignment: async () => ({liveBrokerProviders: ['codex-subscription'],liveConnectionRef: 'deployment-default',diff --git a/control-api/test/services.llmProviderAttemptAuthorizer.grok.test.ts b/control-api/test/services.llmProviderAttemptAuthorizer.grok.test.tsindex f3f4fb192..a4a51a402 100644--- a/control-api/test/services.llmProviderAttemptAuthorizer.grok.test.ts+++ b/control-api/test/services.llmProviderAttemptAuthorizer.grok.test.ts@@ -151,12 +151,17 @@ function body(overrides: Record<string, unknown> = {}) {}}-function deps(- overrides: Partial<LlmProviderAttemptAuthorizerDeps> = {}-): LlmProviderAttemptAuthorizerDeps {+// `resolveConnectionKey` is a test-only convenience that feeds the default+// `resolveAssignment`; the authorizer itself only consumes `resolveAssignment`.+function deps({+ resolveConnectionKey: resolveConnectionKeyOverride,+ ...overrides+}: Partial<LlmProviderAttemptAuthorizerDeps> & {+ resolveConnectionKey?: (hostRef: string) => Promise<string>+} = {}): LlmProviderAttemptAuthorizerDeps {const db = { query: vi.fn() }const resolveConnectionKey =- overrides.resolveConnectionKey ?? vi.fn().mockResolvedValue('team-grok')+ resolveConnectionKeyOverride ?? vi.fn().mockResolvedValue('team-grok')const resolveAssignment =overrides.resolveAssignment ??(async (hostRef: string) => ({@@ -178,7 +183,6 @@ function deps(}),issueTicket: vi.fn(),...overrides,- resolveConnectionKey,resolveAssignment,}}diff --git a/control-api/test/services.llmProviderAttemptAuthorizer.test.ts b/control-api/test/services.llmProviderAttemptAuthorizer.test.tsindex 057805ad6..d2a2fd559 100644--- a/control-api/test/services.llmProviderAttemptAuthorizer.test.ts+++ b/control-api/test/services.llmProviderAttemptAuthorizer.test.ts@@ -112,12 +112,17 @@ function body(overrides: Record<string, unknown> = {}) {}}-function deps(- overrides: Partial<LlmProviderAttemptAuthorizerDeps> = {}-): LlmProviderAttemptAuthorizerDeps {+// `resolveConnectionKey` is a test-only convenience that feeds the default+// `resolveAssignment`; the authorizer itself only consumes `resolveAssignment`.+function deps({+ resolveConnectionKey: resolveConnectionKeyOverride,+ ...overrides+}: Partial<LlmProviderAttemptAuthorizerDeps> & {+ resolveConnectionKey?: (hostRef: string) => Promise<string>+} = {}): LlmProviderAttemptAuthorizerDeps {const db = { query: vi.fn() }const resolveConnectionKey =- overrides.resolveConnectionKey ?? vi.fn().mockResolvedValue('deployment-default')+ resolveConnectionKeyOverride ?? vi.fn().mockResolvedValue('deployment-default')const resolveAssignment =overrides.resolveAssignment ??(async (hostRef: string) => ({@@ -143,7 +148,6 @@ function deps(claims: { jti: 'jti-ticket' },}),...overrides,- resolveConnectionKey,resolveAssignment,}}@@ -569,6 +573,34 @@ describe('authorizeLlmProviderAttempt', () => {expect(resolveConnectionKey).toHaveBeenCalledWith('agent-c')})+ it('attests recipe grant annotations and fails closed when alias and canonical disagree', async () => {+ const disagree = deps({+ resolveAssignment: async () => ({+ liveBrokerProviders: ['codex-subscription'],+ liveConnectionRef: 'unassigned',+ annotations: {+ 'clerum.io/codex-connection-ref': 'team-plus',+ 'clerum.io/subscription-connection-ref': 'other-key',+ },+ }),+ })+ await expect(authorizeLlmProviderAttempt(claims(), body(), disagree)).rejects.toMatchObject({+ code: 'host_binding_mismatch',+ })+ expect(disagree.getConnection).not.toHaveBeenCalled()++ const aliasOnly = deps({+ resolveAssignment: async () => ({+ liveBrokerProviders: ['codex-subscription'],+ liveConnectionRef: 'unassigned',+ annotations: { 'clerum.io/codex-connection-ref': 'deployment-default' },+ }),+ })+ const result = await authorizeLlmProviderAttempt(claims(), body(), aliasOnly)+ expect(result.executionTicket).toBe('ticket.jwt')+ expect(aliasOnly.getConnection).toHaveBeenCalledWith(expect.anything(), 'deployment-default')+ })+it('evaluates budget with a null user_id even when claims.sub is present', async () => {const result = await authorizeLlmProviderAttempt(claims({ sub: 'default/research-host' }),diff --git a/control-api/test/services.recipeCodexGrantIdentity.test.ts b/control-api/test/services.recipeCodexGrantIdentity.test.tsindex f64e4971b..3392549dc 100644--- a/control-api/test/services.recipeCodexGrantIdentity.test.ts+++ b/control-api/test/services.recipeCodexGrantIdentity.test.ts@@ -196,6 +196,80 @@ describe('recipe Codex grant identity', () => {)})+ it.each([+ ['agent', { agent: { provider: 'codex-subscription' } }],+ [+ 'step agent',+ {+ agent: { provider: 'openai' },+ steps: [{ id: 's', agent: { provider: 'codex-subscription' } }],+ },+ ],+ ])(+ 'refuses (409) to publish a Grok identity on a recipe whose %s is Codex',+ async (_label, spec) => {+ getResource.mockResolvedValue({+ metadata: {+ resourceVersion: '5',+ annotations: {+ 'clerum.io/codex-connection-ref': 'team-plus',+ 'clerum.io/subscription-connection-ref': 'team-plus',+ },+ },+ spec,+ })+ await expect(+ publishRecipeGrantIdentity({+ gateway: { getResource, updateResource },+ namespace: 'sandbox-recipes',+ name: 'codex-recipe',+ next: 'team-grok',+ provider: 'grok-subscription',+ })+ ).rejects.toMatchObject({ status: 409, error: 'oauth_broker_provider_conflict' })+ expect(updateResource).not.toHaveBeenCalled()+ }+ )++ it('refuses (409) to publish a Codex identity on a Grok-agent recipe', async () => {+ getResource.mockResolvedValue({+ metadata: {+ resourceVersion: '6',+ annotations: {+ 'clerum.io/codex-connection-ref': '',+ 'clerum.io/subscription-connection-ref': 'team-grok',+ },+ },+ spec: { agent: { provider: 'grok-subscription' } },+ })+ await expect(+ publishRecipeGrantIdentity({+ gateway: { getResource, updateResource },+ namespace: 'sandbox-recipes',+ name: 'grok-recipe',+ next: 'team-plus',+ })+ ).rejects.toMatchObject({ status: 409, error: 'oauth_broker_provider_conflict' })+ expect(updateResource).not.toHaveBeenCalled()+ })++ it('publishes a Grok identity on an SDK-only recipe with a static agent', async () => {+ getResource.mockResolvedValue({+ metadata: { resourceVersion: '7', annotations: {} },+ spec: { agent: { provider: 'openai' }, pluginWorkloadSdk: { family: 'promptBridge' } },+ })+ await expect(+ publishRecipeGrantIdentity({+ gateway: { getResource, updateResource },+ namespace: 'sandbox-recipes',+ name: 'sdk-recipe',+ next: 'team-grok',+ provider: 'grok-subscription',+ })+ ).resolves.toMatchObject({ published: 'team-grok', noop: false })+ expect(updateResource).toHaveBeenCalledTimes(1)+ })+it('rejects a named Grok publish when the Grok grant is not live', async () => {vi.mocked(getSafeGrokSubscriptionConnection).mockResolvedValueOnce(null)await expect(diff --git a/control-api/test/services.recipeGrantTransition.test.ts b/control-api/test/services.recipeGrantTransition.test.tsnew file mode 100644index 000000000..447b19bb0--- /dev/null+++ b/control-api/test/services.recipeGrantTransition.test.ts@@ -0,0 +1,317 @@+import { describe, expect, it } from 'vitest'+import { resolveRecipeGrantTransition } from '../src/services/recipeGrantTransition.js'++const ALIAS = 'clerum.io/codex-connection-ref'+const CANONICAL = 'clerum.io/subscription-connection-ref'++const CODEX_SPEC = { agent: { provider: 'codex-subscription', model: 'gpt-5.1' } }+const GROK_SPEC = { agent: { provider: 'grok-subscription', model: 'grok-4.6' } }+const GROK_STEP_SPEC = {+ agent: { provider: 'openai', model: 'gpt-5.1' },+ steps: [{ id: 's', agent: { provider: 'grok-subscription', model: 'grok-4.6' } }],+}+const STATIC_SPEC = { agent: { provider: 'openai', model: 'gpt-5.1' } }+const SDK_STATIC_SPEC = {+ pluginWorkloadSdk: { promptBridge: { allowedModels: ['gpt-5.3-codex'] } },+ workloads: [{ id: 'svc', type: 'deployment', image: 'svc:latest' }],+}++function body(spec: Record<string, unknown>, annotations?: Record<string, unknown>) {+ return { spec, ...(annotations ? { metadata: { annotations } } : {}) }+}++function rules(result: ReturnType<typeof resolveRecipeGrantTransition>): string[] {+ return result.ok ? [] : result.errors.map(error => error.rule ?? '')+}++describe('resolveRecipeGrantTransition', () => {+ describe('alias/canonical disagreement', () => {+ it.each([+ ['Codex', CODEX_SPEC],+ ['Grok', GROK_SPEC],+ ['static', STATIC_SPEC],+ ['SDK static', SDK_STATIC_SPEC],+ ])('rejects non-empty unequal annotations on a %s spec without throwing', (_label, spec) => {+ const input = body(spec, { [ALIAS]: 'a', [CANONICAL]: 'b' })+ expect(() => resolveRecipeGrantTransition({ body: input })).not.toThrow()+ expect(rules(resolveRecipeGrantTransition({ body: input }))).toEqual([+ 'subscriptionAnnotationsDisagree',+ ])+ expect(+ rules(+ resolveRecipeGrantTransition({+ body: input,+ current: { spec: STATIC_SPEC, annotations: {} },+ })+ )+ ).toEqual(['subscriptionAnnotationsDisagree'])+ })+ })++ describe('create / validate (no stored recipe)', () => {+ it('requires a grant when a broker recipe omits annotations', () => {+ expect(rules(resolveRecipeGrantTransition({ body: body(CODEX_SPEC) }))).toEqual([+ 'codexRecipeGrantRequired',+ ])+ expect(rules(resolveRecipeGrantTransition({ body: body(GROK_STEP_SPEC) }))).toEqual([+ 'grokRecipeGrantRequired',+ ])+ })++ it('writes the Codex shape for alias-only and canonical-only Codex writers', () => {+ expect(+ resolveRecipeGrantTransition({ body: body(CODEX_SPEC, { [ALIAS]: 'team-plus' }) })+ ).toEqual({ ok: true, annotations: { [ALIAS]: 'team-plus', [CANONICAL]: 'team-plus' } })+ expect(+ resolveRecipeGrantTransition({ body: body(CODEX_SPEC, { [CANONICAL]: 'team-a' }) })+ ).toEqual({ ok: true, annotations: { [ALIAS]: 'team-a', [CANONICAL]: 'team-a' } })+ })++ it('writes the Grok shape and rejects a Codex alias on a Grok recipe', () => {+ expect(+ resolveRecipeGrantTransition({+ body: body(GROK_SPEC, { [ALIAS]: '', [CANONICAL]: 'team-grok' }),+ })+ ).toEqual({ ok: true, annotations: { [ALIAS]: '', [CANONICAL]: 'team-grok' } })+ expect(+ rules(+ resolveRecipeGrantTransition({+ body: body(GROK_SPEC, { [ALIAS]: 'team-grok', [CANONICAL]: 'team-grok' }),+ })+ )+ ).toEqual(['subscriptionAnnotationsDisagree'])+ })++ it('rejects explicit unassigned and malformed keys', () => {+ expect(+ rules(resolveRecipeGrantTransition({ body: body(CODEX_SPEC, { [ALIAS]: 'unassigned' }) }))+ ).toEqual(['codexRecipeGrantRequired'])+ expect(+ rules(+ resolveRecipeGrantTransition({ body: body(CODEX_SPEC, { [ALIAS]: '', [CANONICAL]: '' }) })+ )+ ).toEqual(['codexRecipeGrantRequired'])+ expect(+ rules(resolveRecipeGrantTransition({ body: body(CODEX_SPEC, { [ALIAS]: 'Bad_Key' }) }))+ ).toEqual(['codexRecipeGrantInvalid'])+ expect(+ rules(resolveRecipeGrantTransition({ body: body(GROK_SPEC, { [CANONICAL]: '' }) }))+ ).toEqual(['grokRecipeGrantRequired'])+ expect(+ rules(resolveRecipeGrantTransition({ body: body(GROK_SPEC, { [CANONICAL]: 'Bad_Key' }) }))+ ).toEqual(['grokRecipeGrantInvalid'])+ })++ it('never writes grant annotations for a static recipe', () => {+ expect(+ resolveRecipeGrantTransition({ body: body(STATIC_SPEC, { [ALIAS]: '', [CANONICAL]: '' }) })+ ).toEqual({ ok: true, annotations: {} })+ expect(+ resolveRecipeGrantTransition({ body: body(SDK_STATIC_SPEC, { [ALIAS]: 'team-plus' }) })+ ).toEqual({ ok: true, annotations: {} })+ })+ })++ describe('same broker update', () => {+ const codexStored = { [ALIAS]: 'team-plus', [CANONICAL]: 'team-plus' }+ const grokStored = { [ALIAS]: '', [CANONICAL]: 'team-grok' }++ it('keeps the stored grant when annotations are omitted', () => {+ expect(+ resolveRecipeGrantTransition({+ body: body(CODEX_SPEC),+ current: { spec: CODEX_SPEC, annotations: codexStored },+ })+ ).toEqual({ ok: true, annotations: {} })+ expect(+ resolveRecipeGrantTransition({+ body: body(GROK_SPEC),+ current: { spec: GROK_SPEC, annotations: grokStored },+ })+ ).toEqual({ ok: true, annotations: {} })+ })++ it('rewrites an explicit same-broker grant in that broker shape', () => {+ expect(+ resolveRecipeGrantTransition({+ body: body(CODEX_SPEC, { [ALIAS]: 'personal-pro', [CANONICAL]: 'personal-pro' }),+ current: { spec: CODEX_SPEC, annotations: codexStored },+ })+ ).toEqual({ ok: true, annotations: { [ALIAS]: 'personal-pro', [CANONICAL]: 'personal-pro' } })+ expect(+ resolveRecipeGrantTransition({+ body: body(GROK_SPEC, { [CANONICAL]: 'other-grok' }),+ current: { spec: GROK_SPEC, annotations: grokStored },+ })+ ).toEqual({ ok: true, annotations: { [ALIAS]: '', [CANONICAL]: 'other-grok' } })+ })++ it('rejects an explicit same-broker clear', () => {+ expect(+ rules(+ resolveRecipeGrantTransition({+ body: body(CODEX_SPEC, { [ALIAS]: '', [CANONICAL]: '' }),+ current: { spec: CODEX_SPEC, annotations: codexStored },+ })+ )+ ).toEqual(['codexRecipeGrantRequired'])+ })+ })++ describe('broker change', () => {+ it('Codex→Grok with omitted annotations requires an explicit grant', () => {+ expect(+ rules(+ resolveRecipeGrantTransition({+ body: body(GROK_SPEC),+ current: {+ spec: CODEX_SPEC,+ annotations: { [ALIAS]: 'team-plus', [CANONICAL]: 'team-plus' },+ },+ })+ )+ ).toEqual(['providerChangeRequiresGrant'])+ })++ it('Codex→Grok explicit canonical writes the Grok shape (alias cleared)', () => {+ expect(+ resolveRecipeGrantTransition({+ body: body(GROK_SPEC, { [CANONICAL]: 'team-grok' }),+ current: {+ spec: CODEX_SPEC,+ annotations: { [ALIAS]: 'team-plus', [CANONICAL]: 'team-plus' },+ },+ })+ ).toEqual({ ok: true, annotations: { [ALIAS]: '', [CANONICAL]: 'team-grok' } })+ })++ it('Codex→Grok explicit non-empty alias is rejected', () => {+ expect(+ rules(+ resolveRecipeGrantTransition({+ body: body(GROK_SPEC, { [ALIAS]: 'team-plus' }),+ current: {+ spec: CODEX_SPEC,+ annotations: { [ALIAS]: 'team-plus', [CANONICAL]: 'team-plus' },+ },+ })+ )+ ).toEqual(['subscriptionAnnotationsDisagree'])+ })++ it('Grok→Codex with omitted annotations requires an explicit grant', () => {+ expect(+ rules(+ resolveRecipeGrantTransition({+ body: body(CODEX_SPEC),+ current: { spec: GROK_SPEC, annotations: { [ALIAS]: '', [CANONICAL]: 'team-grok' } },+ })+ )+ ).toEqual(['providerChangeRequiresGrant'])+ })++ it('Grok→Codex canonical-only writes the Codex shape instead of clearing', () => {+ expect(+ resolveRecipeGrantTransition({+ body: body(CODEX_SPEC, { [CANONICAL]: 'team-codex' }),+ current: { spec: GROK_SPEC, annotations: { [ALIAS]: '', [CANONICAL]: 'team-grok' } },+ })+ ).toEqual({ ok: true, annotations: { [ALIAS]: 'team-codex', [CANONICAL]: 'team-codex' } })+ })++ it('Grok→Codex explicit empty grant is rejected, never silently cleared', () => {+ expect(+ rules(+ resolveRecipeGrantTransition({+ body: body(CODEX_SPEC, { [ALIAS]: '', [CANONICAL]: '' }),+ current: { spec: GROK_SPEC, annotations: { [ALIAS]: '', [CANONICAL]: 'team-grok' } },+ })+ )+ ).toEqual(['codexRecipeGrantRequired'])+ })++ it('static→broker with omitted annotations requires a grant', () => {+ expect(+ rules(+ resolveRecipeGrantTransition({+ body: body(CODEX_SPEC),+ current: {+ spec: SDK_STATIC_SPEC,+ annotations: { [ALIAS]: '', [CANONICAL]: 'sdk-grok' },+ },+ })+ )+ ).toEqual(['codexRecipeGrantRequired'])+ })++ it('static→broker explicit grant writes the broker shape', () => {+ expect(+ resolveRecipeGrantTransition({+ body: body(GROK_SPEC, { [ALIAS]: '', [CANONICAL]: 'team-grok' }),+ current: { spec: STATIC_SPEC, annotations: {} },+ })+ ).toEqual({ ok: true, annotations: { [ALIAS]: '', [CANONICAL]: 'team-grok' } })+ })+ })++ describe('leaving a broker', () => {+ it.each([+ ['omitted', undefined],+ ['explicit empty', { [ALIAS]: '', [CANONICAL]: '' }],+ ])('broker→static without SDK clears both annotations (%s)', (_label, annotations) => {+ for (const prev of [+ { spec: CODEX_SPEC, annotations: { [ALIAS]: 'team-plus', [CANONICAL]: 'team-plus' } },+ { spec: GROK_SPEC, annotations: { [ALIAS]: '', [CANONICAL]: 'team-grok' } },+ ]) {+ expect(+ resolveRecipeGrantTransition({ body: body(STATIC_SPEC, annotations), current: prev })+ ).toEqual({ ok: true, annotations: { [ALIAS]: '', [CANONICAL]: '' } })+ }+ })++ it.each([+ ['omitted', undefined],+ ['explicit empty', { [ALIAS]: '', [CANONICAL]: '' }],+ ])('broker→static with SDK keeps the SDK-owned identity (%s)', (_label, annotations) => {+ expect(+ resolveRecipeGrantTransition({+ body: body(SDK_STATIC_SPEC, annotations),+ current: {+ spec: CODEX_SPEC,+ annotations: { [ALIAS]: 'team-plus', [CANONICAL]: 'team-plus' },+ },+ })+ ).toEqual({ ok: true, annotations: {} })+ })++ it('static→static keeps the stored identity even when the editor sends empty annotations', () => {+ expect(+ resolveRecipeGrantTransition({+ body: body(SDK_STATIC_SPEC, { [ALIAS]: '', [CANONICAL]: '' }),+ current: { spec: SDK_STATIC_SPEC, annotations: { [ALIAS]: '', [CANONICAL]: 'sdk-grok' } },+ })+ ).toEqual({ ok: true, annotations: {} })+ })+ })++ it('ignores non-string annotation values and never throws on malformed input', () => {+ expect(() =>+ resolveRecipeGrantTransition({+ body: { spec: CODEX_SPEC, metadata: { annotations: { [ALIAS]: 42, [CANONICAL]: null } } },+ })+ ).not.toThrow()+ expect(+ rules(+ resolveRecipeGrantTransition({+ body: { spec: CODEX_SPEC, metadata: { annotations: { [ALIAS]: 42 } } },+ })+ )+ ).toEqual(['codexRecipeGrantRequired'])+ expect(() =>+ resolveRecipeGrantTransition({+ body: { metadata: { annotations: { [ALIAS]: 'a', [CANONICAL]: 'b' } } },+ current: { spec: undefined, annotations: undefined },+ })+ ).not.toThrow()+ })+})