Skip to content

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

TypeScript

fix: apply post-sync plugin workload SDK corrections

Alfredo Lopez7c35e78aa54f
diff --git a/Makefile b/Makefile
index 0c3a64b87..393664b57 100644
--- a/Makefile
+++ b/Makefile
@@ -774,7 +774,11 @@ test-e2e-wrc-internal-dependency-networkpolicy: ## Run issue #485 WRC internal-d
.PHONY: test-e2e-plugin-workload-sdk
test-e2e-plugin-workload-sdk: ## Run Plugin Workload SDK E2E gate (minikube only; requires E2E_PLUGIN_SDK_WRITE_CONFIRM=1)
@echo "Running Plugin Workload SDK E2E gate..."
- KUBECONTEXT="$${KUBECONTEXT:-$${E2E_KUBECONTEXT:-}}" bash scripts/e2e/e2e-plugin-workload-sdk.sh
+ @if [ -z "$${KUBECONTEXT:-$(E2E_KUBECONTEXT)}" ]; then \
+ echo "Refusing Plugin Workload SDK E2E: explicit Kubernetes context is required" >&2; \
+ exit 1; \
+ fi
+ KUBECONTEXT="$${KUBECONTEXT:-$(E2E_KUBECONTEXT)}" bash scripts/e2e/e2e-plugin-workload-sdk.sh
.PHONY: test-e2e-cron-tab-validation
test-e2e-cron-tab-validation: ## Run recipe cron tab E2E (set E2E_CRON_TAB_FIX_REQUIRED=1 when the fix must be present)
diff --git a/control-api/package-lock.json b/control-api/package-lock.json
index 847978bcb..99ec05d68 100644
--- a/control-api/package-lock.json
+++ b/control-api/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "clerum-control-api",
- "version": "0.1.404",
+ "version": "0.1.405",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "clerum-control-api",
- "version": "0.1.404",
+ "version": "0.1.405",
"dependencies": {
"@clerum/image-policy": "file:../packages/image-policy",
"@clerum/llm-providers": "file:../packages/llm-providers",
diff --git a/control-api/package.json b/control-api/package.json
index 27316108c..890187c21 100644
--- a/control-api/package.json
+++ b/control-api/package.json
@@ -1,6 +1,6 @@
{
"name": "clerum-control-api",
- "version": "0.1.404",
+ "version": "0.1.405",
"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/internal/usageEvents.ts b/control-api/src/routes/internal/usageEvents.ts
index b6ae8f004..015b87c14 100644
--- a/control-api/src/routes/internal/usageEvents.ts
+++ b/control-api/src/routes/internal/usageEvents.ts
@@ -2,11 +2,6 @@ import { Router } from 'express'
import { config } from '../../config.js'
import type { DbClient } from '../../db.js'
import { requireMcpHostJwt } from '../../middleware/mcpHostJwtAuth.js'
-import {
- getInvocationById,
- getPluginWorkloadSdkAttemptReceipt,
- getPluginWorkloadSdkProviderAttempt,
-} from '../../services/pluginWorkloadSdkDb.js'
import { withTraceIngestTransaction } from '../../services/tracing/pools.js'
import { projectAcceptedUsageEvents } from '../../services/tracing/usageProjection.js'
import { ingestUsageEventsInTransaction } from '../../services/usageEvents.js'
@@ -174,110 +169,97 @@ async function checkSdkOnlyUsageBinding(
claims: McpHostAccessClaims,
db: DbClient
): Promise<BindingViolation | null> {
- for (let index = 0; index < events.length; index += 1) {
- const event = events[index]
- if (!event || typeof event !== 'object') continue
+ const sdkEvents = events.flatMap((event, index) => {
+ if (!event || typeof event !== 'object') return []
const record = event as Record<string, unknown>
- const isSdkOnlySource =
- record.source_kind === 'unknown' || record.source_kind === 'plugin_workload_sdk'
- const isWorkflowSdkSource =
+ const sdkSource =
+ (record.source_kind === 'unknown' || record.source_kind === 'plugin_workload_sdk') &&
+ record.channel_type === 'plugin_workload_sdk'
+ const workflowSdkSource =
record.source_kind === 'workflow' && record.channel_type === 'plugin_workload_sdk'
- if (!isSdkOnlySource && !isWorkflowSdkSource) continue
+ return sdkSource || workflowSdkSource ? [{ index, record }] : []
+ })
+ if (sdkEvents.length === 0) return null
+
+ const invocationIds = new Set<string>()
+ const providerAttemptIds = new Set<string>()
+ for (const { index, record } of sdkEvents) {
const metadata = record.prompt_bridge_metadata
- if (!metadata || typeof metadata !== 'object' || Array.isArray(metadata)) continue
+ if (!metadata || typeof metadata !== 'object' || Array.isArray(metadata)) {
+ return { index, reason: 'recipe_token_invalid_sdk_usage_binding' }
+ }
const invocationId = (metadata as { invocation_id?: unknown }).invocation_id
- if (typeof invocationId !== 'string') continue
- const attemptGeneration = (metadata as { attempt_generation?: unknown }).attempt_generation
+ const generation = (metadata as { attempt_generation?: unknown }).attempt_generation
const providerAttemptId = (metadata as { provider_attempt_id?: unknown }).provider_attempt_id
const providerAttemptIndex = (metadata as { provider_attempt_index?: unknown })
.provider_attempt_index
- if (isSdkOnlySource || isWorkflowSdkSource) {
- // A pre-v2 host cannot emit a physical-attempt receipt. Keep its
- // compatibility lane explicit and narrow: the persisted invocation must
- // be contract v1 and the event must match that legacy provider/model.
- if (!Number.isInteger(attemptGeneration) || Number(attemptGeneration) < 1) {
- const invocation = await getInvocationById(invocationId, db)
- if (
- !invocation ||
- invocation.contractVersion !== 1 ||
- invocation.recipeNamespace !== claims.recipeNamespace ||
- invocation.recipeName !== claims.recipeName ||
- invocation.method !== 'promptBridge' ||
- !['in_progress', 'complete'].includes(invocation.status) ||
- invocation.authorizationDecision !== 'authorized' ||
- invocation.detail !== String(record.model ?? '')
- ) {
- return { index, reason: 'recipe_token_invalid_sdk_usage_binding' }
- }
- continue
- }
- const receipt = await getPluginWorkloadSdkAttemptReceipt(
- invocationId,
- Number(attemptGeneration),
- db
- )
- const targetRef = String((metadata as { target_ref?: unknown }).target_ref ?? '')
- if (
- !receipt ||
- receipt.method !== 'promptBridge' ||
- receipt.recipeNamespace !== claims.recipeNamespace ||
- receipt.recipeName !== claims.recipeName
- ) {
- return { index, reason: 'recipe_token_invalid_sdk_usage_binding' }
- }
- const hasPhysicalAttempt =
- typeof providerAttemptId === 'string' && Number.isInteger(providerAttemptIndex)
- if (!hasPhysicalAttempt) {
- const invocation = await getInvocationById(invocationId, db)
- if (
- !invocation ||
- invocation.contractVersion !== 1 ||
- invocation.recipeNamespace !== claims.recipeNamespace ||
- invocation.recipeName !== claims.recipeName ||
- invocation.method !== 'promptBridge' ||
- !['in_progress', 'complete'].includes(invocation.status) ||
- invocation.authorizationDecision !== 'authorized' ||
- invocation.detail !== String(record.model ?? '')
- ) {
- return { index, reason: 'recipe_token_invalid_sdk_usage_binding' }
- }
- continue
- }
- const providerAttempt = await getPluginWorkloadSdkProviderAttempt(
- providerAttemptId as string,
- db
- )
- if (
- !receipt.targetRefs.includes(targetRef) ||
- !providerAttempt ||
- providerAttempt.invocationId !== invocationId ||
- providerAttempt.attemptGeneration !== Number(attemptGeneration) ||
- providerAttempt.attemptIndex !== Number(providerAttemptIndex) ||
- providerAttempt.targetRef !== targetRef ||
- providerAttempt.provider !== String(record.provider ?? '') ||
- providerAttempt.model !== String(record.model ?? '') ||
- providerAttempt.credentialSlot !==
- String((metadata as { credential_slot?: unknown }).credential_slot ?? '') ||
- providerAttempt.status !== 'complete'
- ) {
- return { index, reason: 'recipe_token_invalid_sdk_usage_binding' }
- }
- continue
+ if (
+ typeof invocationId !== 'string' ||
+ !Number.isInteger(generation) ||
+ Number(generation) < 1 ||
+ typeof providerAttemptId !== 'string' ||
+ !Number.isInteger(providerAttemptIndex) ||
+ Number(providerAttemptIndex) < 1
+ ) {
+ return { index, reason: 'recipe_token_invalid_sdk_usage_binding' }
}
- const invocation = await getInvocationById(invocationId, db)
+ invocationIds.add(invocationId)
+ providerAttemptIds.add(providerAttemptId)
+ }
+
+ const [receiptResult, providerAttemptResult] = await Promise.all([
+ db.query(
+ `SELECT invocation_id::text, attempt_generation, method, target_refs, recipe_namespace, recipe_name
+ FROM plugin_workload_sdk_invocation_attempts
+ WHERE invocation_id = ANY($1::uuid[])`,
+ [[...invocationIds]]
+ ),
+ db.query(
+ `SELECT id::text, invocation_id::text, attempt_generation, attempt_index,
+ target_ref, provider, model, credential_slot, status,
+ recipe_namespace, recipe_name
+ FROM plugin_workload_sdk_provider_attempts
+ WHERE id = ANY($1::uuid[])`,
+ [[...providerAttemptIds]]
+ ),
+ ])
+ const receipts = new Map(
+ (receiptResult.rows as Array<Record<string, unknown>>).map(row => [
+ `${String(row.invocation_id)}:${Number(row.attempt_generation)}`,
+ row,
+ ])
+ )
+ const providerAttempts = new Map(
+ (providerAttemptResult.rows as Array<Record<string, unknown>>).map(row => [String(row.id), row])
+ )
+
+ for (const { index, record } of sdkEvents) {
+ const metadata = record.prompt_bridge_metadata as Record<string, unknown>
+ const invocationId = String(metadata.invocation_id)
+ const generation = Number(metadata.attempt_generation)
+ const providerAttemptId = String(metadata.provider_attempt_id)
+ const providerAttemptIndex = Number(metadata.provider_attempt_index)
+ const targetRef = String(metadata.target_ref ?? '')
+ const receipt = receipts.get(`${invocationId}:${generation}`)
+ const providerAttempt = providerAttempts.get(providerAttemptId)
+ const targetRefs = Array.isArray(receipt?.target_refs) ? receipt.target_refs.map(String) : []
if (
- !invocation ||
- invocation.recipeNamespace !== claims.recipeNamespace ||
- invocation.recipeName !== claims.recipeName ||
- invocation.method !== 'promptBridge' ||
- // UsageReporter enqueues before the handler's terminal status POST; an
- // in-flight invocation is therefore a valid server-bound usage source.
- !['in_progress', 'complete'].includes(invocation.status) ||
- invocation.authorizationDecision !== 'authorized' ||
- !invocation.promptAuthorization ||
- !invocation.promptAuthorization.authorizedTargetRefs.includes(
- String((metadata as { target_ref?: unknown }).target_ref ?? '')
- )
+ !receipt ||
+ receipt.method !== 'promptBridge' ||
+ receipt.recipe_namespace !== claims.recipeNamespace ||
+ receipt.recipe_name !== claims.recipeName ||
+ !targetRefs.includes(targetRef) ||
+ !providerAttempt ||
+ providerAttempt.invocation_id !== invocationId ||
+ Number(providerAttempt.attempt_generation) !== generation ||
+ Number(providerAttempt.attempt_index) !== providerAttemptIndex ||
+ providerAttempt.recipe_namespace !== claims.recipeNamespace ||
+ providerAttempt.recipe_name !== claims.recipeName ||
+ providerAttempt.target_ref !== targetRef ||
+ providerAttempt.provider !== String(record.provider ?? '') ||
+ providerAttempt.model !== String(record.model ?? '') ||
+ providerAttempt.credential_slot !== String(metadata.credential_slot ?? '') ||
+ providerAttempt.status !== 'complete'
) {
return { index, reason: 'recipe_token_invalid_sdk_usage_binding' }
}
diff --git a/control-api/src/routes/mcp-host/plugin-workload-sdk.routes.ts b/control-api/src/routes/mcp-host/plugin-workload-sdk.routes.ts
index cdc6b270c..931757246 100644
--- a/control-api/src/routes/mcp-host/plugin-workload-sdk.routes.ts
+++ b/control-api/src/routes/mcp-host/plugin-workload-sdk.routes.ts
@@ -1,4 +1,4 @@
-import { type Request, type Response, Router } from 'express'
+import { type NextFunction, type Request, type Response, Router } from 'express'
import { rateLimit } from 'express-rate-limit'
import { pool } from '../../db.js'
import { asyncHandler } from '../../http/asyncHandler.js'
@@ -47,7 +47,6 @@ import { isPlainObject } from '../../utils/isPlainObject.js'
// (conformance: spec §19 "mcp-host control-api access uses the gateway").
//
// POST /mcp-host/plugin-workload-sdk/prompt-bridge/v2
-// POST /mcp-host/plugin-workload-sdk/prompt-bridge (v1 compatibility)
// GET /mcp-host/plugin-workload-sdk/capabilities
// POST /mcp-host/plugin-workload-sdk/client-notification
// POST /mcp-host/plugin-workload-sdk/prompt-bridge/credential-ticket
@@ -75,6 +74,15 @@ const pluginWorkloadSdkCredentialRateLimit = rateLimitMiddleware({
},
})
+function requirePluginWorkloadSdkScope(req: Request, res: Response, next: NextFunction): void {
+ const claims = req.mcpHostJwt
+ if (!claims?.workflowControlScopes.includes('plugin-workload-sdk')) {
+ res.status(403).json({ error: 'scope_denied', retryable: false })
+ return
+ }
+ next()
+}
+
const AUTHZ_HTTP_STATUS: Record<PluginWorkloadSdkErrorCode, number> = {
capability_not_declared: 403,
caller_not_allowed: 403,
@@ -166,7 +174,6 @@ function parsePromptBridgeBody(
options: {
requireContractVersion?: boolean
requireBootstrapBinding?: boolean
- legacyProtocol?: boolean
} = {}
): ParsedPromptBridgeBody | null {
const callerRef = validateCallerRef(body.callerRef, res)
@@ -183,9 +190,7 @@ function parsePromptBridgeBody(
contractVersion !== PLUGIN_WORKLOAD_SDK_PROMPT_BRIDGE_CONTRACT_VERSION) ||
(!options.requireContractVersion &&
contractVersion !== undefined &&
- (options.legacyProtocol
- ? contractVersion !== 1
- : contractVersion !== PLUGIN_WORKLOAD_SDK_PROMPT_BRIDGE_CONTRACT_VERSION))
+ contractVersion !== PLUGIN_WORKLOAD_SDK_PROMPT_BRIDGE_CONTRACT_VERSION)
) {
res.status(409).json({
error: 'protocol_mismatch',
@@ -237,7 +242,7 @@ function parsePromptBridgeBody(
return null
}
- // v1: attachments are not supported (maxAttachments default 0).
+ // Attachments are not part of the promptBridge JSON contract.
if (Array.isArray(body.attachments) && body.attachments.length > 0) {
res.status(400).json({ error: 'attachments_not_supported' })
return null
@@ -453,7 +458,6 @@ async function handlePromptBridgeAuthorization(
options: {
requireContractVersion: boolean
requireBootstrapBinding: boolean
- legacyProtocol?: boolean
}
): Promise<void> {
const claims = req.mcpHostJwt!
@@ -483,7 +487,6 @@ async function handlePromptBridgeAuthorization(
...(parsed.metadata ? { metadata: parsed.metadata } : {}),
},
correlationId: parsed.correlationId,
- legacyProtocol: options.legacyProtocol,
})
if (!result.ok) {
sendAuthzError(res, result)
@@ -526,6 +529,7 @@ export function createMcpHostPluginWorkloadSdkRoutes(): Router {
message: { error: 'Too Many Requests', retryable: true },
}),
requireMcpHostJwt,
+ requirePluginWorkloadSdkScope,
createPluginWorkloadSdkRequestRateLimit()
)
@@ -572,9 +576,9 @@ export function createMcpHostPluginWorkloadSdkRoutes(): Router {
})
)
- // v2 is the target-aware/JIT contract. It is additive: old mcp-hosts keep
- // using the v1 path below, while new clients fail clearly if this endpoint
- // is absent instead of falling back to bootstrap credentials.
+ // v2 is the only supported target-aware/JIT contract. There is no runtime
+ // compatibility lane: old hosts must fail clearly and be upgraded rather
+ // than bypassing target policy and per-attempt credential fencing.
router.post(
'/mcp-host/plugin-workload-sdk/prompt-bridge/v2',
asyncHandler(async (req, res) =>
@@ -585,20 +589,6 @@ export function createMcpHostPluginWorkloadSdkRoutes(): Router {
)
)
- // Compatibility lane for an older mcp-host during a server-first rollout.
- // It intentionally has no cross-provider target response contract; it uses
- // the current persisted policy but does not require the new bootstrap fields.
- router.post(
- '/mcp-host/plugin-workload-sdk/prompt-bridge',
- asyncHandler(async (req, res) =>
- handlePromptBridgeAuthorization(req, res, {
- requireContractVersion: false,
- requireBootstrapBinding: false,
- legacyProtocol: true,
- })
- )
- )
-
router.get(
'/mcp-host/plugin-workload-sdk/capabilities',
asyncHandler(async (_req, res) => {
@@ -615,7 +605,7 @@ export function createMcpHostPluginWorkloadSdkRoutes(): Router {
const primaryTarget = grant?.promptTargets[0] ?? null
res.status(200).json({
contractVersion: PLUGIN_WORKLOAD_SDK_PROMPT_BRIDGE_CONTRACT_VERSION,
- supportedContractVersions: [1, 2],
+ supportedContractVersions: [2],
targetAwarePromptBridge: true,
attemptLedger: true,
credentialTickets: true,
@@ -651,7 +641,13 @@ export function createMcpHostPluginWorkloadSdkRoutes(): Router {
eventType: parsed.eventType,
target: parsed.targetRef ?? null,
userRef: parsed.userRef ?? null,
- notification: { title: parsed.notification.title, body: parsed.notification.body },
+ notification: {
+ title: parsed.notification.title,
+ body: parsed.notification.body,
+ data: parsed.notification.data ?? null,
+ actionRef: parsed.notification.actionRef ?? null,
+ deliveryPolicyRef: parsed.notification.deliveryPolicyRef ?? null,
+ },
},
correlationId: parsed.notification.correlationId,
})
@@ -883,10 +879,7 @@ export function createMcpHostPluginWorkloadSdkRoutes(): Router {
}
const attemptGeneration = providedAttemptGeneration ?? invocation.attemptGeneration
- if (
- providedAttemptGeneration === null &&
- (invocation.contractVersion !== 1 || invocation.attemptGeneration !== 1)
- ) {
+ if (providedAttemptGeneration === null) {
res.status(400).json({ error: 'attemptGeneration is required for contract v2' })
return
}
@@ -931,7 +924,7 @@ export function createMcpHostPluginWorkloadSdkRoutes(): Router {
!invocationId ||
attemptGeneration < 1 ||
providerAttemptIndex < 1 ||
- !['complete', 'failed', 'provider_unavailable'].includes(String(status))
+ !['complete', 'failed', 'provider_unavailable', 'skipped'].includes(String(status))
) {
res.status(400).json({
error: 'invocationId, attemptGeneration, providerAttemptIndex and status are required',
@@ -956,7 +949,7 @@ export function createMcpHostPluginWorkloadSdkRoutes(): Router {
recipeNamespace: claims.recipeNamespace,
recipeName: claims.recipeName,
attemptGeneration,
- status: status as 'complete' | 'failed' | 'provider_unavailable',
+ status: status as 'complete' | 'failed' | 'provider_unavailable' | 'skipped',
})
if (!updated) {
res.status(409).json({ error: 'stale_attempt', retryable: false })
diff --git a/control-api/src/services/pluginWorkloadSdkAuthorizer.ts b/control-api/src/services/pluginWorkloadSdkAuthorizer.ts
index 1d9b4ce9a..075b92548 100644
--- a/control-api/src/services/pluginWorkloadSdkAuthorizer.ts
+++ b/control-api/src/services/pluginWorkloadSdkAuthorizer.ts
@@ -106,8 +106,6 @@ export interface AuthorizePromptBridgeParams {
/** Canonical request payload — hashed for idempotency conflict detection. */
payload: unknown
correlationId?: string
- /** True only for the temporary pre-v2 mcp-host compatibility route. */
- legacyProtocol?: boolean
}
export interface AuthorizedPromptBridge {
@@ -276,10 +274,6 @@ async function authorizePromptBridgeInner(
return deny('capability_not_declared', 'recipe has no promptBridge grant')
}
- if (params.legacyProtocol) {
- return authorizeLegacyPromptBridge(params, grant)
- }
-
if (grant.policyState !== 'active' || grant.policyRevision < 1) {
return deny(
'provider_policy_denied',
@@ -494,180 +488,6 @@ async function authorizePromptBridgeInner(
}
}
-/**
- * Narrow compatibility lane for an older mcp-host during a rolling upgrade.
- * It deliberately reads only the legacy provider + flat allowedModels fields,
- * never target policy/JIT data, and records contract_version=1. This keeps an
- * old host on its already configured single provider while v2 owns the new
- * multiprovider target contract.
- */
-async function authorizeLegacyPromptBridge(
- params: AuthorizePromptBridgeParams,
- grant: PluginWorkloadSdkGrant
-): Promise<PluginWorkloadSdkAuthzResult<AuthorizedPromptBridge>> {
- const { claims, callerRef } = params
- if (grant.policyState !== 'legacy_unreviewed' && grant.policyState !== 'active') {
- return deny('provider_policy_denied', 'promptBridge policy is being revoked or is disabled')
- }
- const callerError = checkCaller(grant, callerRef)
- if (callerError) return callerError
- if (params.targetRef !== undefined || params.modelPolicyRef !== undefined) {
- return deny(
- 'protocol_mismatch',
- 'legacy promptBridge accepts only the configured provider and model; upgrade mcp-host for target selectors',
- true
- )
- }
- const provider = grant.provider?.trim() || params.bootstrapProvider?.trim() || ''
- const model = params.model?.trim() || params.bootstrapModel?.trim() || grant.allowedModels[0]
- if (!provider || !model || grant.allowedModels.length === 0) {
- return deny(
- 'provider_policy_denied',
- 'legacy promptBridge grant has no explicit provider/model binding; review it before use'
- )
- }
- if (params.provider !== undefined && params.provider !== provider) {
- return deny(
- 'provider_policy_denied',
- 'legacy promptBridge provider is fixed by the host binding'
- )
- }
- if (params.bootstrapProvider !== undefined && params.bootstrapProvider.trim() !== provider) {
- return deny(
- 'provider_policy_denied',
- 'legacy promptBridge bootstrap provider is not authorized'
- )
- }
- if (params.bootstrapModel !== undefined && params.bootstrapModel.trim() !== model) {
- return deny('provider_policy_denied', 'legacy promptBridge bootstrap model is not authorized')
- }
- if (!grant.allowedModels.includes(model)) {
- return deny('target_not_allowed', 'requested model is not in the legacy grant allowlist')
- }
-
- const selectedTarget: PluginWorkloadSdkPromptTarget = {
- targetRef: `legacy:${provider}:${model}`,
- provider,
- model,
- credentialSlot: 'legacy-host-binding',
- }
- const recorded = await recordInvocation({
- recipeNamespace: claims.recipeNamespace,
- recipeName: claims.recipeName,
- callerRef,
- correlationId: params.correlationId,
- method: 'promptBridge',
- detail: model,
- purpose: params.purpose,
- idempotencyKey: params.idempotencyKey,
- payload: params.payload,
- status: 'in_progress',
- authorizationDecision: 'authorized',
- contractVersion: 1,
- requiredGrantStates: ['active', 'legacy_unreviewed'],
- })
- if (recorded.kind === 'policy_revoked') {
- return deny(
- 'provider_policy_denied',
- 'legacy promptBridge policy was revoked before invocation reservation'
- )
- }
- if (recorded.kind === 'conflict') {
- return deny('idempotency_conflict', 'idempotency key was already used with a different payload')
- }
- if (recorded.kind === 'race_unresolved') {
- return deny('idempotency_conflict', 'idempotency reservation could not be resolved', true)
- }
- if (recorded.kind === 'replay') {
- if (recorded.invocation.contractVersion !== 1 || recorded.invocation.status === 'failed') {
- return deny(
- 'idempotency_conflict',
- 'legacy invocation cannot be replayed after a failed or upgraded attempt; retry with a new key'
- )
- }
- return {
- ok: true,
- value: {
- invocationId: recorded.invocation.id,
- replay: true,
- providerCallRequired: false,
- status: recorded.invocation.status,
- model: selectedTarget.model,
- modelPolicy: null,
- selectedTarget,
- authorizedTargets: [selectedTarget],
- attemptGeneration: recorded.invocation.attemptGeneration,
- policyRevision: 0,
- policyHash: '0'.repeat(64),
- maxOutputTokens: grant.quotaLimits.maxOutputTokens ?? null,
- },
- }
- }
-
- try {
- const rate = await checkRateLimit(
- claims.recipeNamespace,
- claims.recipeName,
- 'promptBridge',
- grant
- )
- if (!rate.ok) {
- await markInvocationStatus(recorded.invocation.id, 'failed', {
- recipeNamespace: claims.recipeNamespace,
- recipeName: claims.recipeName,
- expectedCurrentStatus: 'in_progress',
- expectedAttemptGeneration: recorded.invocation.attemptGeneration,
- })
- return deny(rate.error, rate.message)
- }
- const quota = await consumeQuota(
- claims.recipeNamespace,
- claims.recipeName,
- 'promptBridge',
- grant
- )
- if (!quota.ok) {
- await markInvocationStatus(recorded.invocation.id, 'failed', {
- recipeNamespace: claims.recipeNamespace,
- recipeName: claims.recipeName,
- expectedCurrentStatus: 'in_progress',
- expectedAttemptGeneration: recorded.invocation.attemptGeneration,
- })
- return deny(quota.error, quota.message)
- }
- } catch (error) {
- try {
- await markInvocationStatus(recorded.invocation.id, 'failed', {
- recipeNamespace: claims.recipeNamespace,
- recipeName: claims.recipeName,
- expectedCurrentStatus: 'in_progress',
- expectedAttemptGeneration: recorded.invocation.attemptGeneration,
- })
- } catch {
- // Preserve the original database/rate error; maintenance will fence it.
- }
- throw error
- }
-
- return {
- ok: true,
- value: {
- invocationId: recorded.invocation.id,
- replay: false,
- providerCallRequired: true,
- status: 'in_progress',
- model: selectedTarget.model,
- modelPolicy: null,
- selectedTarget,
- authorizedTargets: [selectedTarget],
- attemptGeneration: recorded.invocation.attemptGeneration,
- policyRevision: 0,
- policyHash: '0'.repeat(64),
- maxOutputTokens: grant.quotaLimits.maxOutputTokens ?? null,
- },
- }
-}
-
export interface ReissuePromptBridgeCredentialTicketParams {
claims: McpHostAccessClaims
invocationId: string
diff --git a/control-api/src/services/pluginWorkloadSdkDb.ts b/control-api/src/services/pluginWorkloadSdkDb.ts
index ed4bec336..3d1192e45 100644
--- a/control-api/src/services/pluginWorkloadSdkDb.ts
+++ b/control-api/src/services/pluginWorkloadSdkDb.ts
@@ -1055,6 +1055,7 @@ export type PluginWorkloadSdkProviderAttemptStatus =
| 'complete'
| 'failed'
| 'provider_unavailable'
+ | 'skipped'
export interface PluginWorkloadSdkProviderAttempt {
id: string
@@ -1162,14 +1163,37 @@ export async function reservePluginWorkloadSdkProviderAttempt(input: {
) {
return null
}
- const count = await db.query(
- `SELECT COUNT(*)::integer AS count
+ const attemptsResult = await db.query(
+ `SELECT attempt_index, target_ref, status
FROM plugin_workload_sdk_provider_attempts
- WHERE invocation_id = $1 AND attempt_generation = $2`,
+ WHERE invocation_id = $1 AND attempt_generation = $2
+ ORDER BY attempt_index ASC
+ FOR UPDATE`,
[input.invocationId, input.attemptGeneration]
)
- const attemptIndex = Number((count.rows[0] as { count?: unknown } | undefined)?.count ?? 0) + 1
- if (attemptIndex > MAX_PROMPT_BRIDGE_PROVIDER_ATTEMPTS) return null
+ const attempts = attemptsResult.rows as Array<{
+ attempt_index?: unknown
+ target_ref?: unknown
+ status?: unknown
+ }>
+ const attemptIndex = attempts.length + 1
+ const expectedTargetRef = authorization.authorizedTargetRefs[attemptIndex - 1]
+ if (
+ attemptIndex > MAX_PROMPT_BRIDGE_PROVIDER_ATTEMPTS ||
+ !expectedTargetRef ||
+ expectedTargetRef !== input.target.targetRef
+ ) {
+ return null
+ }
+ if (attemptIndex > 1) {
+ const previousAttempt = attempts[attempts.length - 1]
+ if (
+ !previousAttempt ||
+ !['failed', 'provider_unavailable', 'skipped'].includes(String(previousAttempt.status))
+ ) {
+ return null
+ }
+ }
const result = await db.query(
`INSERT INTO plugin_workload_sdk_provider_attempts
(invocation_id, recipe_namespace, recipe_name, attempt_generation, attempt_index,
diff --git a/control-api/src/services/pluginWorkloadSdkSchema.ts b/control-api/src/services/pluginWorkloadSdkSchema.ts
index e56184ad6..76ec2eea5 100644
--- a/control-api/src/services/pluginWorkloadSdkSchema.ts
+++ b/control-api/src/services/pluginWorkloadSdkSchema.ts
@@ -391,7 +391,7 @@ export async function addPluginWorkloadSdkProviderAttemptLedger(db: DbClient): P
model TEXT NOT NULL,
credential_slot TEXT NOT NULL,
status TEXT NOT NULL DEFAULT 'reserved'
- CHECK (status IN ('reserved','in_progress','complete','failed','provider_unavailable')),
+ CHECK (status IN ('reserved','in_progress','complete','failed','provider_unavailable','skipped')),
credential_jti UUID NULL,
started_at TIMESTAMPTZ NOT NULL DEFAULT now(),
lease_expires_at TIMESTAMPTZ NULL,
@@ -405,6 +405,14 @@ export async function addPluginWorkloadSdkProviderAttemptLedger(db: DbClient): P
ON plugin_workload_sdk_provider_attempts (invocation_id, attempt_generation, attempt_index);
CREATE INDEX IF NOT EXISTS plugin_workload_sdk_provider_attempts_status_idx
ON plugin_workload_sdk_provider_attempts (status, lease_expires_at);
+ -- Existing clusters created the ledger before circuit-breaker skips became
+ -- auditable. Replace the inline constraint idempotently so those clusters
+ -- accept the same terminal status as fresh installs.
+ ALTER TABLE plugin_workload_sdk_provider_attempts
+ DROP CONSTRAINT IF EXISTS plugin_workload_sdk_provider_attempts_status_check;
+ ALTER TABLE plugin_workload_sdk_provider_attempts
+ ADD CONSTRAINT plugin_workload_sdk_provider_attempts_status_check
+ CHECK (status IN ('reserved','in_progress','complete','failed','provider_unavailable','skipped'));
`)
}
diff --git a/control-api/src/services/usageEvents.ts b/control-api/src/services/usageEvents.ts
index d14729ab4..0fb7e7897 100644
--- a/control-api/src/services/usageEvents.ts
+++ b/control-api/src/services/usageEvents.ts
@@ -58,7 +58,6 @@ export type UsageIngestTransactionResult = {
type PromptBridgeAttemptBinding = {
invocation_id: string
recipe_name: string
- contract_version: number
attempt_generation: number
method: string
target_refs: unknown
@@ -232,14 +231,6 @@ export function validateUsageEvent(raw: unknown): LlmUsageEvent | null {
task_id === null &&
llm_secret_name !== null &&
prompt_bridge_metadata?.invocation_id !== undefined
- const isLegacySdkOnly =
- source_kind_raw === 'unknown' &&
- r.channel_type === 'plugin_workload_sdk' &&
- recipe_name !== null &&
- run_id === null &&
- task_id === null &&
- llm_secret_name !== null &&
- prompt_bridge_metadata?.invocation_id !== undefined
const isWorkflowSdk = source_kind_raw === 'workflow' && r.channel_type === 'plugin_workload_sdk'
if (source_kind_raw === 'workflow') {
const taskRunId = workflowRunIdFromTaskId(task_id)
@@ -250,12 +241,7 @@ export function validateUsageEvent(raw: unknown): LlmUsageEvent | null {
// but retain their canonical workflow run/task/secret binding above. Reject
// only an unrecognised shape; otherwise the usage emitted by a step-bearing
// host would be dropped before it can be metered.
- if (
- r.channel_type === 'plugin_workload_sdk' &&
- !isSdkOnly &&
- !isLegacySdkOnly &&
- !isWorkflowSdk
- ) {
+ if (r.channel_type === 'plugin_workload_sdk' && !isSdkOnly && !isWorkflowSdk) {
return null
}
if (
@@ -265,9 +251,8 @@ export function validateUsageEvent(raw: unknown): LlmUsageEvent | null {
return null
}
// Contract v2 physical-attempt fields are checked against the persisted
- // receipt during ingestion. A v1 host may omit generation/attempt fields;
- // retaining the event here lets the binding layer classify it explicitly as
- // the narrow legacy lane instead of confusing it with malformed JSON.
+ // receipt during ingestion. Events without those fields are rejected by the
+ // binding layer; there is no runtime v1 compatibility lane.
return {
request_id,
@@ -388,10 +373,8 @@ async function filterEventsByAttemptReceipt(
}
const result = await db.query(
`SELECT attempts.invocation_id::text, attempts.attempt_generation, attempts.method,
- attempts.target_refs, attempts.recipe_name, invocations.contract_version
+ attempts.target_refs, attempts.recipe_name
FROM plugin_workload_sdk_invocation_attempts attempts
- JOIN plugin_workload_sdk_invocations invocations
- ON invocations.id = attempts.invocation_id
WHERE attempts.invocation_id = ANY($1::uuid[])`,
[invocationIds]
)
@@ -433,37 +416,8 @@ async function filterEventsByAttemptReceipt(
: undefined
const targetRefs = receipt && Array.isArray(receipt.target_refs) ? receipt.target_refs : []
const targetRef = metadata?.target_ref
- const legacyInvocation =
- typeof invocationId === 'string'
- ? await db.query(
- `SELECT contract_version, method, status, authorization_decision, detail,
- recipe_namespace, recipe_name
- FROM plugin_workload_sdk_invocations
- WHERE id = $1`,
- [invocationId]
- )
- : { rows: [] }
- const legacy = legacyInvocation.rows[0] as
- | {
- contract_version?: unknown
- method?: unknown
- status?: unknown
- authorization_decision?: unknown
- detail?: unknown
- recipe_namespace?: unknown
- recipe_name?: unknown
- }
- | undefined
const hasPhysicalAttempt =
typeof providerAttemptId === 'string' && Number.isInteger(providerAttemptIndex)
- const legacyCompatible =
- !hasPhysicalAttempt &&
- legacy?.contract_version === 1 &&
- legacy.method === 'promptBridge' &&
- ['in_progress', 'complete'].includes(String(legacy.status)) &&
- legacy.authorization_decision === 'authorized' &&
- legacy.recipe_name === event.recipe_name &&
- legacy.detail === event.model
const physicalCompatible =
hasPhysicalAttempt &&
receipt?.method === 'promptBridge' &&
@@ -478,7 +432,7 @@ async function filterEventsByAttemptReceipt(
providerAttemptById.get(providerAttemptId!)?.model === event.model &&
providerAttemptById.get(providerAttemptId!)?.credential_slot === metadata?.credential_slot &&
providerAttemptById.get(providerAttemptId!)?.status === 'complete'
- if (physicalCompatible || legacyCompatible) {
+ if (physicalCompatible) {
accepted.push(event)
} else {
rejected += 1
diff --git a/control-api/test/routes.mcp-host.plugin-workload-sdk.test.ts b/control-api/test/routes.mcp-host.plugin-workload-sdk.test.ts
index d12b6bae0..f8476eadb 100644
--- a/control-api/test/routes.mcp-host.plugin-workload-sdk.test.ts
+++ b/control-api/test/routes.mcp-host.plugin-workload-sdk.test.ts
@@ -86,6 +86,7 @@ function issueSdkToken(scopes: mcpHostJwt.McpHostControlScope[] = ['plugin-workl
const validPromptBody = {
recipeNamespace: NS,
recipeName: RECIPE,
+ contractVersion: 2,
callerRef: 'api',
bootstrapProvider: 'zai',
bootstrapModel: 'glm-4.7',
@@ -184,6 +185,16 @@ beforeEach(() => {
})
describe('GET /mcp-host/plugin-workload-sdk/capabilities', () => {
+ it('fails closed for a valid recipe token without the SDK scope', async () => {
+ const res = await request(buildApp())
+ .get('/mcp-host/plugin-workload-sdk/capabilities')
+ .set('Authorization', `Bearer ${issueSdkToken([])}`)
+
+ expect(res.status).toBe(403)
+ expect(res.body).toEqual({ error: 'scope_denied', retryable: false })
+ expect(sdkDb.findGrant).not.toHaveBeenCalled()
+ })
+
it('advertises the v2 identity contract while a prompt policy is missing', async () => {
vi.mocked(sdkDb.findGrant).mockResolvedValue(null)
@@ -194,7 +205,7 @@ describe('GET /mcp-host/plugin-workload-sdk/capabilities', () => {
expect(res.status).toBe(200)
expect(res.body).toMatchObject({
contractVersion: 2,
- supportedContractVersions: [1, 2],
+ supportedContractVersions: [2],
targetAwarePromptBridge: true,
attemptLedger: true,
credentialTickets: true,
@@ -254,17 +265,17 @@ describe('GET /mcp-host/plugin-workload-sdk/capabilities', () => {
})
})
-describe('POST /mcp-host/plugin-workload-sdk/prompt-bridge', () => {
+describe('POST /mcp-host/plugin-workload-sdk/prompt-bridge/v2', () => {
it('returns 401 without a token', async () => {
const res = await request(buildApp())
- .post('/mcp-host/plugin-workload-sdk/prompt-bridge')
+ .post('/mcp-host/plugin-workload-sdk/prompt-bridge/v2')
.send(validPromptBody)
expect(res.status).toBe(401)
})
it('returns 400 recipe_binding_mismatch when body differs from claims', async () => {
const res = await request(buildApp())
- .post('/mcp-host/plugin-workload-sdk/prompt-bridge')
+ .post('/mcp-host/plugin-workload-sdk/prompt-bridge/v2')
.set('Authorization', `Bearer ${issueSdkToken()}`)
.send({ ...validPromptBody, recipeName: 'other-recipe' })
expect(res.status).toBe(400)
@@ -274,7 +285,7 @@ describe('POST /mcp-host/plugin-workload-sdk/prompt-bridge', () => {
it('returns 400 invalid_purpose for a purpose outside the enum', async () => {
const res = await request(buildApp())
- .post('/mcp-host/plugin-workload-sdk/prompt-bridge')
+ .post('/mcp-host/plugin-workload-sdk/prompt-bridge/v2')
.set('Authorization', `Bearer ${issueSdkToken()}`)
.send({ ...validPromptBody, purpose: 'jailbreak' })
expect(res.status).toBe(400)
@@ -283,7 +294,7 @@ describe('POST /mcp-host/plugin-workload-sdk/prompt-bridge', () => {
it('returns 400 invalid_idempotency_key for a malformed key', async () => {
const res = await request(buildApp())
- .post('/mcp-host/plugin-workload-sdk/prompt-bridge')
+ .post('/mcp-host/plugin-workload-sdk/prompt-bridge/v2')
.set('Authorization', `Bearer ${issueSdkToken()}`)
.send({ ...validPromptBody, idempotencyKey: 'bad key with spaces!' })
expect(res.status).toBe(400)
@@ -292,7 +303,7 @@ describe('POST /mcp-host/plugin-workload-sdk/prompt-bridge', () => {
it('returns 413 payload_too_large when messages exceed the content byte cap', async () => {
const res = await request(buildApp())
- .post('/mcp-host/plugin-workload-sdk/prompt-bridge')
+ .post('/mcp-host/plugin-workload-sdk/prompt-bridge/v2')
.set('Authorization', `Bearer ${issueSdkToken()}`)
.send({
...validPromptBody,
@@ -302,9 +313,9 @@ describe('POST /mcp-host/plugin-workload-sdk/prompt-bridge', () => {
expect(res.body.error).toBe('payload_too_large')
})
- it('returns 400 attachments_not_supported in v1', async () => {
+ it('returns 400 attachments_not_supported for the v2 JSON contract', async () => {
const res = await request(buildApp())
- .post('/mcp-host/plugin-workload-sdk/prompt-bridge')
+ .post('/mcp-host/plugin-workload-sdk/prompt-bridge/v2')
.set('Authorization', `Bearer ${issueSdkToken()}`)
.send({ ...validPromptBody, attachments: [{ name: 'file.pdf' }] })
expect(res.status).toBe(400)
@@ -319,7 +330,7 @@ describe('POST /mcp-host/plugin-workload-sdk/prompt-bridge', () => {
retryable: false,
})
const res = await request(buildApp())
- .post('/mcp-host/plugin-workload-sdk/prompt-bridge')
+ .post('/mcp-host/plugin-workload-sdk/prompt-bridge/v2')
.set('Authorization', `Bearer ${issueSdkToken([])}`)
.send(validPromptBody)
expect(res.status).toBe(403)
@@ -334,7 +345,7 @@ describe('POST /mcp-host/plugin-workload-sdk/prompt-bridge', () => {
retryable: false,
})
const res = await request(buildApp())
- .post('/mcp-host/plugin-workload-sdk/prompt-bridge')
+ .post('/mcp-host/plugin-workload-sdk/prompt-bridge/v2')
.set('Authorization', `Bearer ${issueSdkToken()}`)
.send(validPromptBody)
expect(res.status).toBe(429)
@@ -343,7 +354,7 @@ describe('POST /mcp-host/plugin-workload-sdk/prompt-bridge', () => {
it('returns 201 with the invocation envelope on success', async () => {
const res = await request(buildApp())
- .post('/mcp-host/plugin-workload-sdk/prompt-bridge')
+ .post('/mcp-host/plugin-workload-sdk/prompt-bridge/v2')
.set('Authorization', `Bearer ${issueSdkToken()}`)
.send(validPromptBody)
expect(res.status).toBe(201)
@@ -356,7 +367,7 @@ describe('POST /mcp-host/plugin-workload-sdk/prompt-bridge', () => {
it('forwards an exact provider/model selector without accepting a raw credential', async () => {
await request(buildApp())
- .post('/mcp-host/plugin-workload-sdk/prompt-bridge')
+ .post('/mcp-host/plugin-workload-sdk/prompt-bridge/v2')
.set('Authorization', `Bearer ${issueSdkToken()}`)
.send({ ...validPromptBody, provider: 'openai', model: 'gpt-5.4' })
.expect(201)
@@ -370,7 +381,7 @@ describe('POST /mcp-host/plugin-workload-sdk/prompt-bridge', () => {
it('includes caller metadata in the canonical payload used for idempotency', async () => {
await request(buildApp())
- .post('/mcp-host/plugin-workload-sdk/prompt-bridge')
+ .post('/mcp-host/plugin-workload-sdk/prompt-bridge/v2')
.set('Authorization', `Bearer ${issueSdkToken()}`)
.send({ ...validPromptBody, metadata: { traceId: 'trace-1', source: 'sandbox-ui' } })
@@ -412,7 +423,7 @@ describe('POST /mcp-host/plugin-workload-sdk/prompt-bridge', () => {
},
})
const res = await request(buildApp())
- .post('/mcp-host/plugin-workload-sdk/prompt-bridge')
+ .post('/mcp-host/plugin-workload-sdk/prompt-bridge/v2')
.set('Authorization', `Bearer ${issueSdkToken()}`)
.send(validPromptBody)
expect(res.status).toBe(200)
@@ -578,6 +589,29 @@ describe('POST /mcp-host/plugin-workload-sdk/client-notification', () => {
)
})
+ it('includes data, action, and delivery policy in the idempotency payload', async () => {
+ const notification = {
+ title: 'Follow up',
+ body: 'Lead is due',
+ data: { leadId: 'lead-7' },
+ actionRef: { type: 'crm.lead', id: 'lead-7', urlRef: 'lead-detail' },
+ deliveryPolicyRef: 'business-hours',
+ }
+ await request(buildApp())
+ .post('/mcp-host/plugin-workload-sdk/client-notification')
+ .set('Authorization', `Bearer ${issueSdkToken()}`)
+ .send({ ...validNotificationBody, notification })
+ .expect(201)
+
+ expect(authorizer.authorizeClientNotification).toHaveBeenCalledWith(
+ expect.objectContaining({
+ payload: expect.objectContaining({
+ notification,
+ }),
+ })
+ )
+ })
+
it('still enqueues delivery on idempotent replay (dedupe_key is idempotent)', async () => {
vi.mocked(authorizer.authorizeClientNotification).mockResolvedValue({
ok: true,
diff --git a/control-api/test/services.pluginWorkloadSdkDb.test.ts b/control-api/test/services.pluginWorkloadSdkDb.test.ts
index c12caee33..652140d43 100644
--- a/control-api/test/services.pluginWorkloadSdkDb.test.ts
+++ b/control-api/test/services.pluginWorkloadSdkDb.test.ts
@@ -6,8 +6,10 @@ import {
failStaleInvocations,
finalizePluginWorkloadSdkRevocation,
getPluginWorkloadSdkLegacyGrantInventory,
+ hashPromptTargetPolicy,
redeemPluginWorkloadSdkCredentialTicketJti,
registerPluginWorkloadSdkCredentialTicketJti,
+ reservePluginWorkloadSdkProviderAttempt,
resolveRecipientProfiles,
revokePluginWorkloadSdkForRecipe,
updateInvocationStatus,
@@ -167,6 +169,106 @@ describe('JIT credential ticket jti registry', () => {
})
})
+describe('ordered provider-attempt reservation', () => {
+ beforeEach(() => {
+ vi.mocked(pool.query).mockReset()
+ })
+
+ it('reserves only the next authorized target after an eligible prior failure', async () => {
+ const primary = {
+ targetRef: 'primary-openai',
+ provider: 'openai',
+ model: 'gpt-5.4-mini',
+ credentialSlot: 'openai-api-key',
+ }
+ const fallback = {
+ targetRef: 'fallback-claude',
+ provider: 'anthropic',
+ model: 'claude-sonnet-4-6',
+ credentialSlot: 'claude-api-key',
+ }
+ const policyHash = hashPromptTargetPolicy({
+ policyRevision: 7,
+ defaultTargetRef: primary.targetRef,
+ promptTargets: [primary, fallback],
+ })
+ vi.mocked(pool.query)
+ .mockResolvedValueOnce({ rows: [], rowCount: 0 } as never) // recipe lock
+ .mockResolvedValueOnce({
+ rows: [
+ {
+ id: '22222222-2222-4222-8222-222222222222',
+ method: 'promptBridge',
+ status: 'in_progress',
+ attempt_generation: 1,
+ lease_expires_at: new Date(Date.now() + 60_000).toISOString(),
+ prompt_authorization: {
+ policyRevision: 7,
+ policyHash,
+ authorizedTargetRefs: [primary.targetRef, fallback.targetRef],
+ },
+ },
+ ],
+ rowCount: 1,
+ } as never)
+ .mockResolvedValueOnce({
+ rows: [
+ {
+ policy_state: 'active',
+ policy_revision: 7,
+ prompt_targets: [primary, fallback],
+ default_target_ref: primary.targetRef,
+ },
+ ],
+ rowCount: 1,
+ } as never)
+ .mockResolvedValueOnce({
+ rows: [{ attempt_index: 1, target_ref: primary.targetRef, status: 'failed' }],
+ rowCount: 1,
+ } as never)
+ .mockResolvedValueOnce({
+ rows: [
+ {
+ id: '33333333-3333-4333-8333-333333333333',
+ invocation_id: '22222222-2222-4222-8222-222222222222',
+ recipe_namespace: 'sandbox-recipes',
+ recipe_name: 'sdk-recipe',
+ attempt_generation: 1,
+ attempt_index: 2,
+ target_ref: fallback.targetRef,
+ provider: fallback.provider,
+ model: fallback.model,
+ credential_slot: fallback.credentialSlot,
+ status: 'reserved',
+ credential_jti: null,
+ started_at: new Date().toISOString(),
+ lease_expires_at: new Date(Date.now() + 60_000).toISOString(),
+ completed_at: null,
+ usage_request_id: null,
+ },
+ ],
+ rowCount: 1,
+ } as never)
+
+ const result = await reservePluginWorkloadSdkProviderAttempt({
+ invocationId: '22222222-2222-4222-8222-222222222222',
+ recipeNamespace: 'sandbox-recipes',
+ recipeName: 'sdk-recipe',
+ attemptGeneration: 1,
+ target: fallback,
+ })
+
+ expect(result).toMatchObject({ attemptIndex: 2, targetRef: fallback.targetRef })
+ const sqls = vi.mocked(pool.query).mock.calls.map(([sql]) => String(sql))
+ expect(sqls[0]).toContain('pg_advisory_xact_lock')
+ expect(sqls[1]).toContain('FOR UPDATE')
+ expect(sqls[2]).toContain("capability_family = 'promptBridge'")
+ expect(sqls[3]).toContain('ORDER BY attempt_index ASC')
+ expect(sqls[3]).toContain('FOR UPDATE')
+ expect(sqls[4]).toContain('attempt_index')
+ })
+})
+
describe('legacy promptBridge inventory', () => {
beforeEach(() => {
vi.mocked(pool.query).mockReset()
@@ -640,4 +742,28 @@ describe('Plugin Workload SDK internal revocation audit actor', () => {
})
)
})
+
+ it('treats an already-disabled grant as an idempotent revoke', async () => {
+ vi.mocked(pool.query)
+ .mockResolvedValueOnce({ rows: [], rowCount: 0 } as never)
+ .mockResolvedValueOnce({
+ rows: [
+ {
+ id: '33333333-3333-4333-8333-333333333333',
+ capability_family: 'promptBridge',
+ policy_state: 'disabled',
+ revocation_id: REVOCATION_ID,
+ },
+ ],
+ rowCount: 1,
+ } as never)
+ .mockResolvedValueOnce({ rows: [], rowCount: 0 } as never)
+ .mockResolvedValueOnce({ rows: [], rowCount: 0 } as never)
+ .mockResolvedValueOnce({ rows: [], rowCount: 0 } as never)
+
+ await expect(
+ revokePluginWorkloadSdkForRecipe('sandbox-recipes', 'sdk-recipe', actor)
+ ).resolves.toMatchObject({ state: 'disabled', revocationId: REVOCATION_ID })
+ expect(permissionEvents.append).not.toHaveBeenCalled()
+ })
})
diff --git a/control-ui/components/__tests__/RegistryCatalog.test.tsx b/control-ui/components/__tests__/RegistryCatalog.test.tsx
index 1157afce4..b97f53651 100644
--- a/control-ui/components/__tests__/RegistryCatalog.test.tsx
+++ b/control-ui/components/__tests__/RegistryCatalog.test.tsx
@@ -138,7 +138,7 @@ describe('RegistryCatalog tabs and columns', () => {
expect(screen.queryByText('market-report')).not.toBeInTheDocument()
expect(screen.getByText('Brave web search')).toBeInTheDocument()
// Panel title is "Connectors" (the "Marketplace" tab labels the section); no count.
- expect(screen.getByText('Connectors')).toBeInTheDocument()
+ expect(screen.getByText('Connectors', { selector: '.cu-panel-title' })).toBeInTheDocument()
expect(screen.queryByText(/Marketplace \(/)).not.toBeInTheDocument()
})
diff --git a/control-ui/package-lock.json b/control-ui/package-lock.json
index 7d68e0e4e..e309c061c 100644
--- a/control-ui/package-lock.json
+++ b/control-ui/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "clerum-control-ui",
- "version": "0.1.378",
+ "version": "0.1.379",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "clerum-control-ui",
- "version": "0.1.378",
+ "version": "0.1.379",
"dependencies": {
"@clerum/llm-providers": "file:../packages/llm-providers",
"@clerum/workflow-recipe-capability-policy": "file:../packages/workflow-recipe-capability-policy",
diff --git a/control-ui/package.json b/control-ui/package.json
index f261022b8..beca2d0af 100644
--- a/control-ui/package.json
+++ b/control-ui/package.json
@@ -1,6 +1,6 @@
{
"name": "clerum-control-ui",
- "version": "0.1.378",
+ "version": "0.1.379",
"private": true,
"scripts": {
"dev": "NEXT_IGNORE_INCORRECT_LOCKFILE=1 next dev",
diff --git a/desktop-app/package-lock.json b/desktop-app/package-lock.json
index 46b72d094..180fa9f38 100644
--- a/desktop-app/package-lock.json
+++ b/desktop-app/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "evenfire",
- "version": "0.1.331",
+ "version": "0.1.332",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "evenfire",
- "version": "0.1.331",
+ "version": "0.1.332",
"license": "MPL-2.0",
"dependencies": {
"@tanstack/react-query": "5.100.10",
diff --git a/desktop-app/package.json b/desktop-app/package.json
index b8fd69335..60bbb28e1 100644
--- a/desktop-app/package.json
+++ b/desktop-app/package.json
@@ -1,7 +1,7 @@
{
"name": "evenfire",
"productName": "Evenfire",
- "version": "0.1.331",
+ "version": "0.1.332",
"private": true,
"license": "MPL-2.0",
"description": "Evenfire desktop client for secure agent and workflow access",
diff --git a/desktop-app/test/e2e-playwright/playwright.config.ts b/desktop-app/test/e2e-playwright/playwright.config.ts
index d5652c4d1..b3e992e57 100644
--- a/desktop-app/test/e2e-playwright/playwright.config.ts
+++ b/desktop-app/test/e2e-playwright/playwright.config.ts
@@ -13,8 +13,15 @@ function readOptionalFile(filePath: string): string | null {
}
}
-/** Parse dotenv data without overwriting an explicit process value. */
-function loadEnvContents(contents: string): void {
+const ADMIN_ENV_KEYS = [
+ 'ADMIN_PASSWORD',
+ 'TEST_ADMIN_PASSWORD',
+ 'E2E_ADMIN_PASSWORD',
+ 'ADMIN_PASS',
+] as const
+
+function parseEnvContents(contents: string): Map<string, string> {
+ const values = new Map<string, string>()
const lines = contents.split('\n')
for (const line of lines) {
const trimmed = line.trim()
@@ -29,12 +36,30 @@ function loadEnvContents(contents: string): void {
) {
value = value.slice(1, -1)
}
+ values.set(key, value)
+ }
+ return values
+}
+
+/** Parse dotenv data without overwriting an explicit process value. */
+function loadEnvContents(contents: string, overrideKeys = new Set<string>()): void {
+ for (const [key, value] of parseEnvContents(contents)) {
// Presence, not truthiness: an explicit empty process value is still an
- // operator decision and must not be replaced by a lane default.
- if (!(key in process.env)) process.env[key] = value
+ // operator decision and must not be replaced by a lane default, except
+ // for the canonical admin credential aliases handled below.
+ if (overrideKeys.has(key) || !(key in process.env)) process.env[key] = value
}
}
+function canonicalAdminPassword(contents: string): string | undefined {
+ const values = parseEnvContents(contents)
+ for (const key of ADMIN_ENV_KEYS) {
+ const value = values.get(key)
+ if (value) return value
+ }
+ return undefined
+}
+
/** Load a dotenv-style file without a check-then-read race. */
function loadEnvFile(envPath: string): void {
const contents = readOptionalFile(envPath)
@@ -45,9 +70,23 @@ function loadEnvFile(envPath: string): void {
* Resolve the canonical repository .env for a secondary worktree. Direct
* Playwright invocations do not inherit the shell wrapper's environment, so
* the Desktop lane must use the same root-env contract as Control UI:
- * explicit process values, then the canonical root .env, then test defaults.
+ * Explicit endpoint/process values remain caller-owned; admin credential
+ * aliases are canonical-root-first so a stale inherited password cannot win.
*/
function loadCanonicalRootEnv(): void {
+ const loadCanonicalFile = (envPath: string): void => {
+ const contents = readOptionalFile(envPath)
+ if (contents === null) return
+ loadEnvContents(contents, new Set(ADMIN_ENV_KEYS))
+ const password = canonicalAdminPassword(contents)
+ if (password) {
+ // Keep all aliases coherent. Otherwise an inherited E2E_ADMIN_PASSWORD
+ // could still win in the fixture even after ADMIN_PASSWORD was loaded
+ // from the canonical root .env.
+ for (const key of ADMIN_ENV_KEYS) process.env[key] = password
+ }
+ }
+
// __dirname is desktop-app/test/e2e-playwright; walk to the worktree root.
// This matters when Playwright is launched directly from a secondary
// worktree: the canonical .env lives in the primary Evenfire checkout.
@@ -58,28 +97,28 @@ function loadCanonicalRootEnv(): void {
gitFileContents = fs.readFileSync(gitFile, 'utf8')
} catch (error) {
if ((error as NodeJS.ErrnoException).code === 'ENOENT') {
- loadEnvFile(path.join(repoRoot, '.env'))
+ loadCanonicalFile(path.join(repoRoot, '.env'))
return
}
// A normal checkout has a file-form worktree pointer here. If `.git` is a
// directory (for example in a non-worktree checkout), there is no safe
// common-dir traversal to perform from this config file.
if ((error as NodeJS.ErrnoException).code === 'EISDIR') {
- loadEnvFile(path.join(repoRoot, '.env'))
+ loadCanonicalFile(path.join(repoRoot, '.env'))
return
}
throw error
}
const gitdirMatch = gitFileContents.trim().match(/^gitdir:\s*(.+)$/)
if (!gitdirMatch) {
- loadEnvFile(path.join(repoRoot, '.env'))
+ loadCanonicalFile(path.join(repoRoot, '.env'))
return
}
const worktreeGitDir = path.resolve(repoRoot, gitdirMatch[1])
const commonDirFile = path.join(worktreeGitDir, 'commondir')
const commonDirValue = readOptionalFile(commonDirFile)
if (commonDirValue === null) {
- loadEnvFile(path.join(repoRoot, '.env'))
+ loadCanonicalFile(path.join(repoRoot, '.env'))
return
}
const commonDir = path.resolve(worktreeGitDir, commonDirValue.trim())
@@ -87,7 +126,7 @@ function loadCanonicalRootEnv(): void {
// directory (the primary checkout), not the secondary worktree containing
// this config. This keeps seeded credentials and endpoint policy aligned
// with the operator lane.
- loadEnvFile(path.join(commonDir, '..', '.env'))
+ loadCanonicalFile(path.join(commonDir, '..', '.env'))
}
loadCanonicalRootEnv()
diff --git a/desktop-app/test/e2e-playwright/sdk-client-notification/sdkWorkloadFixture.ts b/desktop-app/test/e2e-playwright/sdk-client-notification/sdkWorkloadFixture.ts
index 53bb2cd28..f710b5c07 100644
--- a/desktop-app/test/e2e-playwright/sdk-client-notification/sdkWorkloadFixture.ts
+++ b/desktop-app/test/e2e-playwright/sdk-client-notification/sdkWorkloadFixture.ts
@@ -18,8 +18,17 @@ const CONTROL_API = process.env.CONTROL_API_BASE_URL || 'http://127.0.0.1:8090'
const WORKLOAD_ID = 'sdk-caller'
const EVENT_TYPE = 'e2e.test.notification'
const MODEL_PROVIDER =
- process.env.E2E_WORKFLOW_MODEL_PROVIDER || process.env.CLURUM_MODEL_PROVIDER || 'zai'
-const MODEL_NAME = process.env.E2E_WORKFLOW_MODEL_NAME || process.env.CLURUM_MODEL_NAME || 'glm-5.1'
+ process.env.E2E_WORKFLOW_MODEL_PROVIDER || process.env.CLERUM_MODEL_PROVIDER || 'openai'
+const MODEL_NAME =
+ process.env.E2E_WORKFLOW_MODEL_NAME ||
+ process.env.CLERUM_MODEL_NAME ||
+ (MODEL_PROVIDER === 'claude' ? 'claude-sonnet-4-6' : 'gpt-5.4-mini')
+if (MODEL_PROVIDER !== 'openai' && MODEL_PROVIDER !== 'claude') {
+ throw new Error(
+ `Plugin Workload SDK Desktop E2E requires OpenAI or Claude; got ${MODEL_PROVIDER}. ` +
+ 'Set E2E_WORKFLOW_MODEL_PROVIDER explicitly for the approved provider.'
+ )
+}
const CREDENTIAL_SLOT = process.env.E2E_WORKFLOW_CREDENTIAL_SLOT || `${MODEL_PROVIDER}-api-key`
function requireAdminPassword(): string {
@@ -27,8 +36,7 @@ function requireAdminPassword(): string {
process.env.E2E_ADMIN_PASSWORD ||
process.env.ADMIN_PASSWORD ||
process.env.ADMIN_PASS ||
- process.env.TEST_ADMIN_PASSWORD ||
- 'changeme123!'
+ process.env.TEST_ADMIN_PASSWORD
if (!password) {
throw new Error('E2E_ADMIN_PASSWORD or ADMIN_PASSWORD is required for SDK workload grants')
}
diff --git a/mcp-host/package-lock.json b/mcp-host/package-lock.json
index d4f981a2d..0f3f47cd7 100644
--- a/mcp-host/package-lock.json
+++ b/mcp-host/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "clerum-mcp-host",
- "version": "0.1.225",
+ "version": "0.1.226",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "clerum-mcp-host",
- "version": "0.1.225",
+ "version": "0.1.226",
"license": "SEE LICENSE IN LICENSE",
"dependencies": {
"@anthropic-ai/sdk": "^0.32.0",
diff --git a/mcp-host/package.json b/mcp-host/package.json
index 0791c1380..2f171f034 100644
--- a/mcp-host/package.json
+++ b/mcp-host/package.json
@@ -1,6 +1,6 @@
{
"name": "clerum-mcp-host",
- "version": "0.1.225",
+ "version": "0.1.226",
"description": "MCP Host - reads Host CRD and provides LLM access via OpenAI/Claude",
"main": "dist/main.js",
"engines": {
diff --git a/mcp-host/src/pluginWorkloadSdk/promptBridge/controlApiClient.test.ts b/mcp-host/src/pluginWorkloadSdk/promptBridge/controlApiClient.test.ts
index 82e1c3b07..94bd6c191 100644
--- a/mcp-host/src/pluginWorkloadSdk/promptBridge/controlApiClient.test.ts
+++ b/mcp-host/src/pluginWorkloadSdk/promptBridge/controlApiClient.test.ts
@@ -83,7 +83,7 @@ describe('PluginWorkloadSdkControlApiClient', () => {
const fetchImpl = vi.fn().mockResolvedValue(
jsonResponse(200, {
contractVersion: 2,
- supportedContractVersions: [1, 2],
+ supportedContractVersions: [2],
targetAwarePromptBridge: true,
attemptLedger: true,
credentialTickets: true,
@@ -117,7 +117,7 @@ describe('PluginWorkloadSdkControlApiClient', () => {
const fetchImpl = vi.fn().mockResolvedValue(
jsonResponse(200, {
contractVersion: 2,
- supportedContractVersions: [1, 2],
+ supportedContractVersions: [2],
targetAwarePromptBridge: true,
attemptLedger: true,
credentialTickets: true,
@@ -147,13 +147,13 @@ describe('PluginWorkloadSdkControlApiClient', () => {
})
})
- it('derives the provider-call disposition for an older control-api response', async () => {
- const { providerCallRequired: _omitted, ...legacyBody } = authorizedBody('legacy-invocation')
- const fetchImpl = vi.fn().mockResolvedValue(jsonResponse(201, legacyBody))
+ it('rejects a response missing the v2 provider-call disposition', async () => {
+ const { providerCallRequired: _omitted, ...incompleteBody } =
+ authorizedBody('legacy-invocation')
+ const fetchImpl = vi.fn().mockResolvedValue(jsonResponse(201, incompleteBody))
const client = makeClient(fetchImpl as unknown as typeof fetch)
- await expect(client.authorizePromptBridge(promptBody)).resolves.toMatchObject({
- replay: false,
- providerCallRequired: true,
+ await expect(client.authorizePromptBridge(promptBody)).rejects.toMatchObject({
+ code: 'provider_unavailable',
})
})
diff --git a/mcp-host/src/pluginWorkloadSdk/promptBridge/controlApiClient.ts b/mcp-host/src/pluginWorkloadSdk/promptBridge/controlApiClient.ts
index 1e940f1e5..74b47b56c 100644
--- a/mcp-host/src/pluginWorkloadSdk/promptBridge/controlApiClient.ts
+++ b/mcp-host/src/pluginWorkloadSdk/promptBridge/controlApiClient.ts
@@ -134,7 +134,7 @@ function isAuthorizePromptBridgeResponse(v: unknown): v is AuthorizePromptBridge
r.contractVersion === 2 &&
typeof r.invocationId === 'string' &&
typeof r.replay === 'boolean' &&
- (r.providerCallRequired === undefined || typeof r.providerCallRequired === 'boolean') &&
+ typeof r.providerCallRequired === 'boolean' &&
typeof r.status === 'string' &&
typeof r.model === 'string' &&
(r.modelPolicy === null ||
@@ -484,7 +484,7 @@ export class PluginWorkloadSdkControlApiClient {
/**
* Negotiates the target-aware/JIT wire contract before a prompt. There is no
- * v1 fallback: an SDK host must not send multiprovider traffic to an API that
+ * legacy fallback: an SDK host must not send multiprovider traffic to an API that
* cannot fence attempts or tickets.
*/
async ensurePromptBridgeCapabilities(): Promise<void> {
@@ -602,17 +602,7 @@ export class PluginWorkloadSdkControlApiClient {
true
)
}
- // The v2 response is strict. Only the provider-call disposition remains
- // additive for a short server-first rollout window; absence is derived from
- // the already persisted idempotency contract and never enables credentials.
- return {
- ...result,
- providerCallRequired:
- typeof (result as unknown as { providerCallRequired?: unknown }).providerCallRequired ===
- 'boolean'
- ? result.providerCallRequired
- : !result.replay,
- }
+ return result
}
/**
@@ -671,7 +661,7 @@ export class PluginWorkloadSdkControlApiClient {
attemptGeneration: number
providerAttemptId: string
providerAttemptIndex: number
- status: 'complete' | 'failed' | 'provider_unavailable'
+ status: 'complete' | 'failed' | 'provider_unavailable' | 'skipped'
}): Promise<void> {
await this.post(
`/api/v1/mcp-host/plugin-workload-sdk/provider-attempts/${encodeURIComponent(
diff --git a/mcp-host/src/pluginWorkloadSdk/promptBridge/llmBridge.failover.test.ts b/mcp-host/src/pluginWorkloadSdk/promptBridge/llmBridge.failover.test.ts
index e464cf7be..8770a8b0d 100644
--- a/mcp-host/src/pluginWorkloadSdk/promptBridge/llmBridge.failover.test.ts
+++ b/mcp-host/src/pluginWorkloadSdk/promptBridge/llmBridge.failover.test.ts
@@ -333,7 +333,20 @@ describe('LlmBridge authorized multi-provider fallback', () => {
}
)
- const result = await bridge.complete(request)
+ const providerAttemptReporter = { report: vi.fn() }
+ const credentialTicketIssuer = {
+ issue: vi.fn(async ({ target }: { target: PromptBridgeTarget }) => ({
+ credentialTicket: `fresh-${target.targetRef}`,
+ providerAttemptId: `attempt-${target.targetRef}`,
+ providerAttemptIndex: target.targetRef === primary.targetRef ? 1 : 2,
+ })),
+ }
+
+ const result = await bridge.complete({
+ ...request,
+ credentialTicketIssuer,
+ providerAttemptReporter,
+ })
expect(result.servedTarget).toEqual(fallback)
expect(credentialCalls).toEqual([fallback.targetRef])
@@ -341,6 +354,16 @@ describe('LlmBridge authorized multi-provider fallback', () => {
expect(second.completeSingleTurn).toHaveBeenCalledOnce()
expect(breakers.get(primary.targetRef)?.isOpen()).toBe(true)
expect(breakers.get(fallback.targetRef)?.isOpen()).toBe(false)
+ expect(providerAttemptReporter.report).toHaveBeenNthCalledWith(1, {
+ providerAttemptId: `attempt-${primary.targetRef}`,
+ providerAttemptIndex: 1,
+ status: 'skipped',
+ })
+ expect(providerAttemptReporter.report).toHaveBeenNthCalledWith(2, {
+ providerAttemptId: `attempt-${fallback.targetRef}`,
+ providerAttemptIndex: 2,
+ status: 'complete',
+ })
})
it('publishes circuit state under the effective target label', async () => {
diff --git a/mcp-host/src/pluginWorkloadSdk/promptBridge/llmBridge.ts b/mcp-host/src/pluginWorkloadSdk/promptBridge/llmBridge.ts
index e7835420a..250a3d480 100644
--- a/mcp-host/src/pluginWorkloadSdk/promptBridge/llmBridge.ts
+++ b/mcp-host/src/pluginWorkloadSdk/promptBridge/llmBridge.ts
@@ -52,7 +52,7 @@ export interface PromptBridgeProviderAttemptReporter {
report(input: {
providerAttemptId: string
providerAttemptIndex: number
- status: 'complete' | 'failed' | 'provider_unavailable'
+ status: 'complete' | 'failed' | 'provider_unavailable' | 'skipped'
}): Promise<void>
}
@@ -209,6 +209,33 @@ export class LlmBridge {
const breaker = this.breakerFor(authorized.target)
if (!breaker.allow()) {
+ // A circuit-open target still consumes an ordered, auditable physical
+ // attempt. Reserve and close it as `skipped` before advancing; without
+ // this ledger row Control API would correctly reject the next target
+ // as an out-of-order fallback.
+ const skippedTicket = await withinDeadline(
+ () =>
+ request.credentialTicketIssuer.issue({
+ invocationId: request.invocationId,
+ attemptGeneration: request.attemptGeneration,
+ target: authorized.target,
+ policyRevision: request.policyRevision,
+ policyHash: request.policyHash,
+ }),
+ remainingTimeoutMs(deadlineAt),
+ 'timeout'
+ )
+ if (
+ request.providerAttemptReporter &&
+ skippedTicket.providerAttemptId &&
+ skippedTicket.providerAttemptIndex !== undefined
+ ) {
+ await request.providerAttemptReporter.report({
+ providerAttemptId: skippedTicket.providerAttemptId,
+ providerAttemptIndex: skippedTicket.providerAttemptIndex,
+ status: 'skipped',
+ })
+ }
const error = new ClassifiedProviderError(
{ code: LlmErrorCode.ApiCallFailed, retryable: true },
new PluginWorkloadError(
diff --git a/scripts/e2e/e2e-plugin-workload-sdk.sh b/scripts/e2e/e2e-plugin-workload-sdk.sh
index 712372d03..31cb69c36 100755
--- a/scripts/e2e/e2e-plugin-workload-sdk.sh
+++ b/scripts/e2e/e2e-plugin-workload-sdk.sh
@@ -164,8 +164,9 @@ NOTIFICATION_PREF_SNAPSHOT_EXISTS=0
NOTIFICATION_PREF_SNAPSHOT_MEDIUM=""
NOTIFICATION_PREF_SNAPSHOT_FALLBACK=""
NOTIFICATION_PREF_SNAPSHOT_ACCOUNT=""
-# Hard ceiling for the entire gate (default 15m). Override with E2E_GATE_MAX_SECONDS.
-E2E_GATE_MAX_SECONDS="${E2E_GATE_MAX_SECONDS:-900}"
+# Hard ceiling for the entire gate (default 10m). Override with
+# E2E_GATE_MAX_SECONDS only to a value no greater than the fail-closed ceiling.
+E2E_GATE_MAX_SECONDS="${E2E_GATE_MAX_SECONDS:-600}"
E2E_GATE_STARTED_AT=$SECONDS
# Per-phase wait ceilings (seconds).
E2E_WAIT_STATUS_VALIDATED="${E2E_WAIT_STATUS_VALIDATED:-120}"
diff --git a/scripts/e2e/playwright-dev.sh b/scripts/e2e/playwright-dev.sh
index c6f217595..9e5c439c3 100755
--- a/scripts/e2e/playwright-dev.sh
+++ b/scripts/e2e/playwright-dev.sh
@@ -18,6 +18,8 @@ REPO="$(cd "$HERE/../.." && pwd)"
# shellcheck source=scripts/e2e/load-dotenv.sh
source "$HERE/load-dotenv.sh"
+# shellcheck source=scripts/e2e/admin-credentials.sh
+source "$HERE/admin-credentials.sh"
CALLER_KUBECONTEXT="${KUBECONTEXT:-}"
CALLER_E2E_K8S_CONTEXT="${E2E_K8S_CONTEXT:-}"
@@ -41,6 +43,41 @@ CALLER_MCP_HOST_BASE_URL="${MCP_HOST_BASE_URL:-}"
# reach preflight without executing arbitrary dotenv content.
dotenv_load_canonical_root "$REPO"
+# Resolve credentials by origin rather than by inherited variable name. The
+# canonical root .env is the seed source for the branch-owned cluster, so a
+# stale E2E_ADMIN_PASSWORD in the parent shell must not silently win. The
+# local fallback is used only when no canonical/process credential exists.
+RESOLVED_ADMIN_PASSWORD="$(e2e_resolve_admin_password "$REPO" "$(printf '%s%s' 'changeme123' '!')" || true)"
+if [[ -z "$RESOLVED_ADMIN_PASSWORD" ]]; then
+ echo '[playwright-dev] ERROR: no admin password is configured in the canonical root .env or process environment' >&2
+ exit 1
+fi
+export E2E_ADMIN_PASSWORD="$RESOLVED_ADMIN_PASSWORD"
+export ADMIN_PASSWORD="$RESOLVED_ADMIN_PASSWORD"
+export TEST_ADMIN_PASSWORD="$RESOLVED_ADMIN_PASSWORD"
+
+# The SDK T3 lane is intentionally deterministic and provider-bounded. Never
+# inherit the host-wide Z.AI selection into this journey: an unavailable or
+# rate-limited provider would make an infrastructure check look like a product
+# failure. Callers may choose either approved provider explicitly.
+SDK_PROVIDER="${E2E_WORKFLOW_MODEL_PROVIDER:-${CLERUM_MODEL_PROVIDER:-openai}}"
+case "$SDK_PROVIDER" in
+ openai|claude) ;;
+ *)
+ echo "[playwright-dev] ERROR: Plugin Workload SDK Playwright requires OpenAI or Claude; got ${SDK_PROVIDER}" >&2
+ exit 1
+ ;;
+esac
+SDK_MODEL="${E2E_WORKFLOW_MODEL_NAME:-${CLERUM_MODEL_NAME:-}}"
+if [[ -z "$SDK_MODEL" ]]; then
+ case "$SDK_PROVIDER" in
+ openai) SDK_MODEL='gpt-5.4-mini' ;;
+ claude) SDK_MODEL='claude-sonnet-4-6' ;;
+ esac
+fi
+export E2E_WORKFLOW_MODEL_PROVIDER="$SDK_PROVIDER"
+export E2E_WORKFLOW_MODEL_NAME="$SDK_MODEL"
+
[[ -n "$CALLER_KUBECONTEXT" ]] && export KUBECONTEXT="$CALLER_KUBECONTEXT"
[[ -n "$CALLER_E2E_K8S_CONTEXT" ]] && export E2E_K8S_CONTEXT="$CALLER_E2E_K8S_CONTEXT"
if [[ -n "$CALLER_CONTROL_API_BASE_URL" ]]; then
diff --git a/scripts/tests/test-plugin-workload-sdk-auth-bootstrap.sh b/scripts/tests/test-plugin-workload-sdk-auth-bootstrap.sh
index 3aa790e98..34193fe0d 100755
--- a/scripts/tests/test-plugin-workload-sdk-auth-bootstrap.sh
+++ b/scripts/tests/test-plugin-workload-sdk-auth-bootstrap.sh
@@ -282,6 +282,7 @@ else
fi
if grep -Fq 'E2E_HARD_MAX_GATE_SECONDS=600' "$SCRIPT" &&
+ grep -Fq 'E2E_GATE_MAX_SECONDS="${E2E_GATE_MAX_SECONDS:-600}"' "$SCRIPT" &&
grep -Fq 'E2E_HARD_MAX_PHASE_WAIT_SECONDS=180' "$SCRIPT" &&
grep -Fq 'E2E_HARD_MAX_POLL_INTERVAL_SECONDS=5' "$SCRIPT" &&
grep -Fq 'validate_bounded_seconds E2E_GATE_MAX_SECONDS' "$SCRIPT" &&
@@ -291,4 +292,17 @@ else
fail 'Plugin Workload SDK E2E lacks fail-closed wait ceilings'
fi
+make_line="$(make -n MINIKUBE_PROFILE=clerum-codex-context-test test-e2e-plugin-workload-sdk 2>&1 || true)"
+if [[ "$make_line" == *'KUBECONTEXT="${KUBECONTEXT:-clerum-codex-context-test}"'* ]]; then
+ pass 'Plugin Workload SDK Make target propagates the explicit branch context'
+else
+ fail 'Plugin Workload SDK Make target lost the explicit branch context'
+fi
+
+if [[ "$make_line" != *'KUBECONTEXT="${KUBECONTEXT:-${E2E_KUBECONTEXT:-}}"'* ]]; then
+ pass 'Plugin Workload SDK Make target does not fall back to global kubectl context'
+else
+ fail 'Plugin Workload SDK Make target still permits global kubectl context fallback'
+fi
+
exit "$FAIL"
diff --git a/workflow-recipes/package-lock.json b/workflow-recipes/package-lock.json
index 36054c2c4..c0726c802 100644
--- a/workflow-recipes/package-lock.json
+++ b/workflow-recipes/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "workload-recipes-controller",
- "version": "0.1.270",
+ "version": "0.1.274",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "workload-recipes-controller",
- "version": "0.1.270",
+ "version": "0.1.274",
"license": "SEE LICENSE IN LICENSE",
"dependencies": {
"@aws-sdk/client-s3": "^3.1009.0",
diff --git a/workflow-recipes/package.json b/workflow-recipes/package.json
index 14374f790..f22f46a34 100644
--- a/workflow-recipes/package.json
+++ b/workflow-recipes/package.json
@@ -1,6 +1,6 @@
{
"name": "workload-recipes-controller",
- "version": "0.1.270",
+ "version": "0.1.274",
"description": "Workload Recipes Controller (WRC) - WorkloadRecipe lifecycle management and MCP server interface",
"main": "dist/main.js",
"engines": {
diff --git a/workflow-recipes/src/reconciler/reconciler.test.ts b/workflow-recipes/src/reconciler/reconciler.test.ts
index c44cdeae6..3cab93df7 100644
--- a/workflow-recipes/src/reconciler/reconciler.test.ts
+++ b/workflow-recipes/src/reconciler/reconciler.test.ts
@@ -343,6 +343,7 @@ describe('WorkflowRecipeReconciler', () => {
phase: 'deploying',
message: 'Plugin Workload SDK bootstrap identity proof pending',
requeueAfterMs: TRANSIENT_REQUEUE_BASE_MS,
+ requeueFixedInterval: true,
})
})
@@ -381,20 +382,21 @@ describe('WorkflowRecipeReconciler', () => {
phase: 'deploying',
message: 'Plugin Workload SDK mcp-host starting',
requeueAfterMs: TRANSIENT_REQUEUE_BASE_MS,
+ requeueFixedInterval: true,
})
})
it('cleans SDK-only runtime resources after the capability is removed without invoking workflow reconciliation', async () => {
- const cleanupPluginWorkloadSdkOnly = vi.fn().mockResolvedValue(undefined)
+ const cleanupPluginWorkloadSdk = vi.fn().mockResolvedValue(undefined)
const workflowReconcile = vi.fn()
;(
reconciler as unknown as {
workflowReconciler: {
reconcile: typeof workflowReconcile
- cleanupPluginWorkloadSdkOnly: typeof cleanupPluginWorkloadSdkOnly
+ cleanupPluginWorkloadSdk: typeof cleanupPluginWorkloadSdk
}
}
- ).workflowReconciler = { reconcile: workflowReconcile, cleanupPluginWorkloadSdkOnly }
+ ).workflowReconciler = { reconcile: workflowReconcile, cleanupPluginWorkloadSdk }
const result = await reconciler.reconcile(
makeRecipe({
@@ -406,19 +408,47 @@ describe('WorkflowRecipeReconciler', () => {
)
expect(result.phase).toBe('active')
- expect(cleanupPluginWorkloadSdkOnly).toHaveBeenCalledWith('test-recipe')
+ expect(cleanupPluginWorkloadSdk).toHaveBeenCalledWith('test-recipe')
expect(workflowReconcile).not.toHaveBeenCalled()
})
+ it.each(['failed', 'deprecated', 'rollback-failed'] as const)(
+ 'cleans a removed SDK capability even when the recipe is already %s',
+ async phase => {
+ const cleanupPluginWorkloadSdk = vi.fn().mockResolvedValue(undefined)
+ ;(
+ reconciler as unknown as {
+ workflowReconciler: { cleanupPluginWorkloadSdk: typeof cleanupPluginWorkloadSdk }
+ }
+ ).workflowReconciler = { cleanupPluginWorkloadSdk }
+
+ const result = await reconciler.reconcile(
+ makeRecipe({
+ status: {
+ phase,
+ pluginWorkloadSdk: {
+ state: 'validated',
+ promptBridge: true,
+ clientNotifications: false,
+ },
+ },
+ })
+ )
+
+ expect(result.phase).toBe(phase)
+ expect(cleanupPluginWorkloadSdk).toHaveBeenCalledWith('test-recipe')
+ }
+ )
+
it('tears down an existing SDK-only host when the global feature flag is disabled', async () => {
- const cleanupPluginWorkloadSdkOnly = vi.fn().mockResolvedValue(undefined)
+ const cleanupPluginWorkloadSdk = vi.fn().mockResolvedValue(undefined)
const workflowReconcile = vi.fn()
;(
reconciler as unknown as {
config: { pluginWorkloadSdkEnabled: boolean }
workflowReconciler: {
reconcile: typeof workflowReconcile
- cleanupPluginWorkloadSdkOnly: typeof cleanupPluginWorkloadSdkOnly
+ cleanupPluginWorkloadSdk: typeof cleanupPluginWorkloadSdk
}
}
).config.pluginWorkloadSdkEnabled = false
@@ -426,10 +456,10 @@ describe('WorkflowRecipeReconciler', () => {
reconciler as unknown as {
workflowReconciler: {
reconcile: typeof workflowReconcile
- cleanupPluginWorkloadSdkOnly: typeof cleanupPluginWorkloadSdkOnly
+ cleanupPluginWorkloadSdk: typeof cleanupPluginWorkloadSdk
}
}
- ).workflowReconciler = { reconcile: workflowReconcile, cleanupPluginWorkloadSdkOnly }
+ ).workflowReconciler = { reconcile: workflowReconcile, cleanupPluginWorkloadSdk }
const result = await reconciler.reconcile(
makeRecipe({
@@ -449,7 +479,7 @@ describe('WorkflowRecipeReconciler', () => {
pluginWorkloadSdkTeardownConfirmed: true,
message: 'Plugin Workload SDK disabled after confirmed teardown',
})
- expect(cleanupPluginWorkloadSdkOnly).toHaveBeenCalledWith('test-recipe')
+ expect(cleanupPluginWorkloadSdk).toHaveBeenCalledWith('test-recipe')
expect(workflowReconcile).not.toHaveBeenCalled()
})
@@ -4052,6 +4082,40 @@ describe('WorkflowRecipeReconciler', () => {
})
})
+ it('fences SDK authority before deleting a hybrid workflow recipe', async () => {
+ const order: string[] = []
+ const cleanupPluginWorkloadSdk = vi.fn(async () => {
+ order.push('sdk-revoke-and-cleanup')
+ })
+ const workflowInfraCleanup = vi.fn(async () => {
+ order.push('workflow-cleanup')
+ })
+ ;(
+ reconciler as unknown as {
+ workflowReconciler: {
+ cleanupPluginWorkloadSdk: typeof cleanupPluginWorkloadSdk
+ reconcileDelete: typeof workflowInfraCleanup
+ }
+ }
+ ).workflowReconciler = { cleanupPluginWorkloadSdk, reconcileDelete: workflowInfraCleanup }
+
+ const recipe = makeRecipe({
+ spec: {
+ steps: [{ id: 'research', instruction: 'run' }],
+ pluginWorkloadSdk: { promptBridge: {}, allowedCallers: ['api'] },
+ },
+ status: {
+ phase: 'active',
+ pluginWorkloadSdk: { state: 'validated', promptBridge: true, clientNotifications: false },
+ },
+ })
+
+ await reconciler.reconcileDelete(recipe)
+
+ expect(order).toEqual(['sdk-revoke-and-cleanup', 'workflow-cleanup'])
+ expect(workflowInfraCleanup).toHaveBeenCalledWith('test-recipe', 'sandbox-recipes', recipe.spec)
+ })
+
it('forwards custom coordinator workflow fields to the workflow reconciler', async () => {
const workflowReconcile = vi.fn().mockResolvedValue({
phase: 'deploying',
diff --git a/workflow-recipes/src/reconciler/workflowRecipeReconciler.ts b/workflow-recipes/src/reconciler/workflowRecipeReconciler.ts
index 3bd2d3379..4d70fac3e 100644
--- a/workflow-recipes/src/reconciler/workflowRecipeReconciler.ts
+++ b/workflow-recipes/src/reconciler/workflowRecipeReconciler.ts
@@ -772,11 +772,11 @@ export class WorkflowRecipeReconciler {
* disabled keeps a stale host/token reachable only behind an explicit
* requeue, until the cleanup dependency is available and converges.
*/
- private async cleanupPluginWorkloadSdkOnlyOrThrow(recipeName: string): Promise<void> {
+ private async cleanupPluginWorkloadSdkOrThrow(recipeName: string): Promise<void> {
if (!this.workflowReconciler) {
throw new Error('workflow subsystem is not initialized; SDK cleanup cannot be confirmed')
}
- await this.workflowReconciler.cleanupPluginWorkloadSdkOnly(recipeName)
+ await this.workflowReconciler.cleanupPluginWorkloadSdk(recipeName)
}
private async waitForTransportNetworkReadiness(
@@ -1263,7 +1263,7 @@ export class WorkflowRecipeReconciler {
// intentionally restricted to the stepless adapter.
if (!isWorkflow && recipe.spec.pluginWorkloadSdk && !this.config.pluginWorkloadSdkEnabled) {
try {
- await this.cleanupPluginWorkloadSdkOnlyOrThrow(name)
+ await this.cleanupPluginWorkloadSdkOrThrow(name)
} catch (error) {
return {
phase: 'failed' as RecipePhase,
@@ -1286,6 +1286,25 @@ export class WorkflowRecipeReconciler {
await this.revokeCoordinatorGfsNetworkPolicyIfDisabled(recipe)
}
+ // Capability removal is independent from workflow phase. Do this before
+ // terminal-phase short-circuiting so a failed/deprecated/rollback-failed
+ // recipe cannot retain SDK authority after the operator removes the block.
+ // The durable status marker is cleared by the following status projection
+ // only after this fail-closed cleanup succeeds.
+ if (!recipe.spec.pluginWorkloadSdk && recipe.status?.pluginWorkloadSdk) {
+ try {
+ await this.cleanupPluginWorkloadSdkOrThrow(name)
+ } catch (error) {
+ return {
+ phase: 'failed' as RecipePhase,
+ message: `Plugin Workload SDK teardown failed after capability removal: ${String(error)}`,
+ workloadStatuses: [],
+ skipStatusPatch: true,
+ requeueAfterMs: TRANSIENT_REQUEUE_BASE_MS,
+ }
+ }
+ }
+
const limitError = validateWorkflowRecipeLimits(recipe.spec, this.config)
if (limitError) {
if (isWorkflow) await this.revokeCoordinatorGfsNetworkPolicy(recipe)
@@ -1897,14 +1916,6 @@ export class WorkflowRecipeReconciler {
// Step 2: Validate spec
this.validateSpec(recipe)
- // A removed SDK declaration must release the resources that were owned
- // by the SDK-only runtime before this recipe settles as a plain workload.
- // The status marker is durable across the spec edit; no workflow path is
- // involved in this cleanup.
- if (!isWorkflow && !recipe.spec.pluginWorkloadSdk && recipe.status?.pluginWorkloadSdk) {
- await this.cleanupPluginWorkloadSdkOnlyOrThrow(name)
- }
-
// Step 2.5: Policy enforcement already ran at the top of reconcile()
// so both workflow and non-workflow recipes are gated uniformly. No
// duplicate check here.
@@ -2445,7 +2456,8 @@ export class WorkflowRecipeReconciler {
sdkOnlyBootstrapPending
? TRANSIENT_REQUEUE_BASE_MS
: undefined,
- requeueFixedInterval: sdkOnlyPolicyPending,
+ requeueFixedInterval:
+ sdkOnlyPolicyPending || sdkOnlyRuntime?.phase === 'deploying' || sdkOnlyBootstrapPending,
}
} catch (error) {
// Transient failures must not brick a healthy recipe at the terminal,
@@ -3180,6 +3192,12 @@ export class WorkflowRecipeReconciler {
// ─── Workflow Delete (Stage 1) ────────────────────────────────────
const isWorkflow = recipe.spec.steps !== undefined && recipe.spec.steps.length > 0
if (isWorkflow && this.workflowReconciler) {
+ // Fence the SDK capability before the workflow deletion pipeline removes
+ // the shared mcp-host/token resources. Hybrid recipes must not bypass
+ // broker revocation merely because they also have coordinator state.
+ if (recipe.spec.pluginWorkloadSdk || recipe.status?.pluginWorkloadSdk) {
+ await this.cleanupPluginWorkloadSdkOrThrow(name)
+ }
await this.workflowReconciler.reconcileDelete(name, recipe.metadata.namespace, recipe.spec)
await this.cleanupDelegationIfNeeded(recipe)
await this.cleanupDeclaredRuntimeResources(recipe)
@@ -3190,7 +3208,7 @@ export class WorkflowRecipeReconciler {
// a capability may have been removed in an update before Kubernetes emits
// the final delete event, and cleanup must still revoke its host tokens.
if (recipe.spec.pluginWorkloadSdk || recipe.status?.pluginWorkloadSdk) {
- await this.cleanupPluginWorkloadSdkOnlyOrThrow(name)
+ await this.cleanupPluginWorkloadSdkOrThrow(name)
}
await this.cleanupDelegationIfNeeded(recipe)
diff --git a/workflow-recipes/src/workflow/pluginWorkloadSdkPodDrift.test.ts b/workflow-recipes/src/workflow/pluginWorkloadSdkPodDrift.test.ts
index 122632b3a..e2b129d45 100644
--- a/workflow-recipes/src/workflow/pluginWorkloadSdkPodDrift.test.ts
+++ b/workflow-recipes/src/workflow/pluginWorkloadSdkPodDrift.test.ts
@@ -42,6 +42,27 @@ describe('readMcpHostPodDriftStateIfExists', () => {
})
})
+ it('reads the runtime contract hash used for same-image migrations', async () => {
+ const coreApi = {
+ readNamespacedPod: vi.fn().mockResolvedValue({
+ metadata: {
+ annotations: {
+ 'clerum.io/plugin-workload-sdk-runtime-contract-hash': 'hash-v2',
+ },
+ },
+ spec: { containers: [{ name: 'mcp-host', image: 'registry.example/mcp-host:current' }] },
+ }),
+ }
+
+ await expect(
+ readMcpHostPodDriftStateIfExists(coreApi as never, POD_NAME, NAMESPACE)
+ ).resolves.toEqual({
+ image: 'registry.example/mcp-host:current',
+ runtimeContractHash: 'hash-v2',
+ deleting: false,
+ })
+ })
+
it('returns undefined when the pod disappeared before the drift read', async () => {
const coreApi = {
readNamespacedPod: vi.fn().mockRejectedValue({ code: 404 }),
diff --git a/workflow-recipes/src/workflow/pluginWorkloadSdkPodDrift.ts b/workflow-recipes/src/workflow/pluginWorkloadSdkPodDrift.ts
index cdaeabc50..4a9cd7808 100644
--- a/workflow-recipes/src/workflow/pluginWorkloadSdkPodDrift.ts
+++ b/workflow-recipes/src/workflow/pluginWorkloadSdkPodDrift.ts
@@ -1,8 +1,10 @@
import * as k8s from '@kubernetes/client-node'
import { getErrorCode } from '../reconciler/k8sErrors'
+import { PLUGIN_WORKLOAD_SDK_RUNTIME_CONTRACT_HASH_ANNOTATION } from './podFactory'
export type McpHostPodDriftState = {
image?: string
+ runtimeContractHash?: string
deleting: boolean
}
@@ -19,8 +21,11 @@ export async function readMcpHostPodDriftStateIfExists(
try {
const pod = await coreApi.readNamespacedPod({ name, namespace })
const mcpHostContainer = pod.spec?.containers?.find(container => container.name === 'mcp-host')
+ const runtimeContractHash =
+ pod.metadata?.annotations?.[PLUGIN_WORKLOAD_SDK_RUNTIME_CONTRACT_HASH_ANNOTATION]
return {
image: mcpHostContainer?.image,
+ ...(runtimeContractHash ? { runtimeContractHash } : {}),
deleting: Boolean(pod.metadata?.deletionTimestamp),
}
} catch (error: unknown) {
diff --git a/workflow-recipes/src/workflow/pluginWorkloadSdkProvisioner.imageDrift.test.ts b/workflow-recipes/src/workflow/pluginWorkloadSdkProvisioner.imageDrift.test.ts
index 05a81fe67..993aa86e2 100644
--- a/workflow-recipes/src/workflow/pluginWorkloadSdkProvisioner.imageDrift.test.ts
+++ b/workflow-recipes/src/workflow/pluginWorkloadSdkProvisioner.imageDrift.test.ts
@@ -2,7 +2,9 @@ import { describe, expect, it, vi } from 'vitest'
import type { WorkflowRecipeSpec } from '../types'
import { PluginWorkloadSdkProvisioner } from './pluginWorkloadSdkProvisioner'
import type { PluginWorkloadSdkProvisionerDeps } from './pluginWorkloadSdkProvisioner'
+import { buildMcpHostPod, pluginWorkloadSdkRuntimeContractHash } from './podFactory'
import type { WorkflowRuntimePlan } from './runtimePlan'
+import type { WorkflowConfig } from './types'
const SANDBOX_NS = 'sandbox-recipes'
const DESIRED_IMAGE = 'registry.example/clerum/mcp-host-slim:sha-new'
@@ -14,12 +16,19 @@ const RECIPE = 'demo'
function podWithPhase(
image: string,
phase: 'Running' | 'Pending',
- opts: { deleting?: boolean } = {}
+ opts: { deleting?: boolean; runtimeContractHash?: string } = {}
) {
return {
metadata: {
uid: 'pod-uid-1',
...(opts.deleting ? { deletionTimestamp: '2026-06-19T18:00:00Z' } : {}),
+ ...(opts.runtimeContractHash
+ ? {
+ annotations: {
+ 'clerum.io/plugin-workload-sdk-runtime-contract-hash': opts.runtimeContractHash,
+ },
+ }
+ : {}),
},
spec: { containers: [{ name: 'mcp-host', image }] },
status: { phase, conditions: [], containerStatuses: [] },
@@ -29,7 +38,7 @@ function podWithPhase(
function makeProvisioner(
podImage: string,
phase: 'Running' | 'Pending' = 'Running',
- opts: { deleting?: boolean } = {}
+ opts: { deleting?: boolean; runtimeContractHash?: string } = {}
) {
const readNamespacedPod = vi.fn().mockResolvedValue(podWithPhase(podImage, phase, opts))
const deleteNamespacedPod = vi.fn().mockResolvedValue({})
@@ -42,11 +51,7 @@ function makeProvisioner(
const deps = {
coreApi,
- config: {
- mcpHostImage: DESIRED_IMAGE,
- sandboxNamespace: SANDBOX_NS,
- pluginWorkloadSdkEnabled: true,
- },
+ config: TEST_CONFIG,
tokenFactory: {},
log: { info: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn() },
ensureMcpHostSecrets: vi.fn().mockResolvedValue(undefined),
@@ -64,6 +69,48 @@ function makeProvisioner(
// bail out before reaching the image-drift branch.
const SPEC = { agent: { provider: 'openai', model: 'gpt-4' } } as unknown as WorkflowRecipeSpec
const RUNTIME = {} as unknown as WorkflowRuntimePlan
+const TEST_CONFIG = {
+ coordinatorImage: 'registry.example/coordinator:current',
+ mcpHostImage: DESIRED_IMAGE,
+ wrcEndpoint: 'http://workflow-recipes.example',
+ sandboxNamespace: SANDBOX_NS,
+ mcpServerNamespace: 'mcp-server',
+ imagePullPolicy: 'IfNotPresent',
+ maxWorkflowSteps: 10,
+ workflowDefaultRunDurationSeconds: 60,
+ workflowMaxRunDurationSeconds: 600,
+ runtimeTokenTtlSeconds: 600,
+ runtimeTokenRefreshBeforeSeconds: 60,
+ workflowMaxWorkloadsPerRecipe: 10,
+ workflowUiEgressInternalMaxItems: 10,
+ workflowMaxSteps: 10,
+ workflowStepDependsOnMaxItems: 10,
+ workflowStepAllowedToolsMaxItems: 10,
+ workflowStepMcpServersMaxItems: 10,
+ workflowStatefulSetMaxReplicas: 3,
+ workflowStatefulSetMaxVolumeClaimTemplates: 3,
+ workflowStatefulSetMaxPvcPreflightChecks: 3,
+ pluginWorkloadSdkEnabled: true,
+} as unknown as WorkflowConfig
+
+function desiredRuntimeContractHash(): string {
+ const desiredPod = buildMcpHostPod(
+ RECIPE,
+ SPEC.agent,
+ TEST_CONFIG,
+ RECIPE,
+ SANDBOX_NS,
+ undefined,
+ undefined,
+ undefined,
+ {
+ mountWorkflowOutput: false,
+ pluginWorkloadSdkEnabled: true,
+ pluginWorkloadSdkRuntimeMode: 'sdk-only',
+ }
+ )
+ return pluginWorkloadSdkRuntimeContractHash(desiredPod)
+}
describe('ensureEagerSdkMcpHost image-drift roll', () => {
it('rolls a healthy eager mcp-host pod when its image drifts from the platform image', async () => {
@@ -92,7 +139,11 @@ describe('ensureEagerSdkMcpHost image-drift roll', () => {
})
it('does not roll the pod when its image already matches the platform image', async () => {
- const { provisioner, deleteNamespacedPod, createNamespacedPod } = makeProvisioner(DESIRED_IMAGE)
+ const { provisioner, deleteNamespacedPod, createNamespacedPod } = makeProvisioner(
+ DESIRED_IMAGE,
+ 'Running',
+ { runtimeContractHash: desiredRuntimeContractHash() }
+ )
await provisioner.ensureEagerSdkMcpHost(
RECIPE,
@@ -108,6 +159,26 @@ describe('ensureEagerSdkMcpHost image-drift roll', () => {
expect(createNamespacedPod).not.toHaveBeenCalled()
})
+ it('rolls a same-image pod when the runtime contract hash is missing', async () => {
+ const { provisioner, deleteNamespacedPod } = makeProvisioner(DESIRED_IMAGE)
+
+ const status = await provisioner.ensureEagerSdkMcpHost(
+ RECIPE,
+ 'recipe-uid',
+ SANDBOX_NS,
+ RECIPE,
+ SPEC,
+ RUNTIME,
+ { mcpHostPhase: 'Running' }
+ )
+
+ expect(status).toBe('deploying')
+ expect(deleteNamespacedPod).toHaveBeenCalledWith({
+ name: `${RECIPE}-mcp-host`,
+ namespace: SANDBOX_NS,
+ })
+ })
+
it('rolls a pending eager mcp-host pod on image drift before waiting for readiness', async () => {
const { provisioner, deleteNamespacedPod, createNamespacedPod } = makeProvisioner(
STALE_IMAGE,
@@ -166,11 +237,7 @@ describe('ensureEagerSdkMcpHost image-drift roll', () => {
const coreApi = { readNamespacedPod, deleteNamespacedPod, createNamespacedPod }
const deps = {
coreApi,
- config: {
- mcpHostImage: DESIRED_IMAGE,
- sandboxNamespace: SANDBOX_NS,
- pluginWorkloadSdkEnabled: true,
- },
+ config: TEST_CONFIG,
tokenFactory: {},
log: { info: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn() },
ensureMcpHostSecrets: vi.fn().mockResolvedValue(undefined),
@@ -338,12 +405,34 @@ describe('ensureEagerSdkMcpHost image-drift roll', () => {
agent: { provider: 'openai', model: 'gpt-4' },
pluginWorkloadSdk: { promptBridge: {} },
} as unknown as WorkflowRecipeSpec
+ const expectedRuntimeContractHash = pluginWorkloadSdkRuntimeContractHash(
+ buildMcpHostPod(
+ RECIPE,
+ promptBridgeSpec.agent,
+ TEST_CONFIG,
+ RECIPE,
+ SANDBOX_NS,
+ undefined,
+ undefined,
+ undefined,
+ {
+ mountWorkflowOutput: false,
+ pluginWorkloadSdkEnabled: true,
+ pluginWorkloadSdkRuntimeMode: 'sdk-only',
+ }
+ )
+ )
let podImage = DESIRED_IMAGE
// Keep the UID stable across the test double's replacement so this assertion
// specifically proves the explicit roll reset, not only identity-key rollover.
let podUid = 'pod-uid-1'
const readNamespacedPod = vi.fn().mockImplementation(async () => ({
- metadata: { uid: podUid },
+ metadata: {
+ uid: podUid,
+ annotations: {
+ 'clerum.io/plugin-workload-sdk-runtime-contract-hash': expectedRuntimeContractHash,
+ },
+ },
spec: { containers: [{ name: 'mcp-host', image: podImage }] },
status: {
phase: 'Running',
@@ -359,11 +448,7 @@ describe('ensureEagerSdkMcpHost image-drift roll', () => {
const coreApi = { readNamespacedPod, deleteNamespacedPod, createNamespacedPod }
const deps = {
coreApi,
- config: {
- mcpHostImage: DESIRED_IMAGE,
- sandboxNamespace: SANDBOX_NS,
- pluginWorkloadSdkEnabled: true,
- },
+ config: TEST_CONFIG,
tokenFactory: { signWrcConfigureToken },
modelConfigHandler: { handle },
log: { info: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn() },
diff --git a/workflow-recipes/src/workflow/pluginWorkloadSdkProvisioner.ts b/workflow-recipes/src/workflow/pluginWorkloadSdkProvisioner.ts
index 6ee966d98..215abf122 100644
--- a/workflow-recipes/src/workflow/pluginWorkloadSdkProvisioner.ts
+++ b/workflow-recipes/src/workflow/pluginWorkloadSdkProvisioner.ts
@@ -20,7 +20,7 @@ import {
pluginWorkloadSdkTokenSecretKey,
resolvePluginWorkloadSdkAllowedCallers,
} from './pluginWorkloadSdkTokens'
-import { buildMcpHostPod } from './podFactory'
+import { buildMcpHostPod, pluginWorkloadSdkRuntimeContractHash } from './podFactory'
import {
PLUGIN_WORKLOAD_SDK_LEGACY_TOKEN_DATA_KEY,
buildMcpHostUrl,
@@ -193,6 +193,26 @@ export class PluginWorkloadSdkProvisioner {
await this.deps.ensureMcpHostHeadlessService(recipeName)
+ // Build the desired Pod once per reconcile so drift checks compare the
+ // complete immutable runtime contract, not only the image string. This
+ // catches same-image upgrades of the sdk-only env/dispatch contract.
+ const desiredMcpHostPod = buildMcpHostPod(
+ recipeName,
+ mcpHostAgent,
+ this.deps.config,
+ runtimeScopeRecipeName,
+ namespace,
+ undefined,
+ undefined,
+ effectiveWorkflowContextRefForSpec(recipeName, spec),
+ {
+ mountWorkflowOutput: false,
+ pluginWorkloadSdkEnabled: true,
+ pluginWorkloadSdkRuntimeMode: 'sdk-only',
+ }
+ )
+ const desiredRuntimeContractHash = pluginWorkloadSdkRuntimeContractHash(desiredMcpHostPod)
+
let mcpHostPhase = opts.mcpHostPhase
if (mcpHostPhase === 'Running' || mcpHostPhase === 'Pending') {
const waitingReason = await getContainerWaitingReason(
@@ -229,10 +249,14 @@ export class PluginWorkloadSdkProvisioner {
if (runningPod?.deleting) {
return 'deploying'
}
- if (runningPod?.image && runningPod.image !== this.deps.config.mcpHostImage) {
- log.info('Plugin Workload SDK eager mcp-host image drift; rolling to platform image', {
+ const imageDrift = runningPod?.image !== this.deps.config.mcpHostImage
+ const runtimeContractDrift = runningPod?.runtimeContractHash !== desiredRuntimeContractHash
+ if (runningPod && (imageDrift || runtimeContractDrift)) {
+ log.info('Plugin Workload SDK eager mcp-host runtime contract drift; rolling Pod', {
runningImage: runningPod.image,
desiredImage: this.deps.config.mcpHostImage,
+ observedRuntimeContractHash: runningPod.runtimeContractHash,
+ desiredRuntimeContractHash,
})
await this.rollEagerSdkMcpHostPod(recipeName)
// Requeue: the pod is recreated from the platform image on a later
@@ -244,26 +268,11 @@ export class PluginWorkloadSdkProvisioner {
}
if (!mcpHostPhase || mcpHostPhase === 'Failed' || mcpHostPhase === 'Unknown') {
- const mcpHostPod = buildMcpHostPod(
- recipeName,
- mcpHostAgent,
- this.deps.config,
- runtimeScopeRecipeName,
- namespace,
- undefined,
- undefined,
- effectiveWorkflowContextRefForSpec(recipeName, spec),
- {
- mountWorkflowOutput: false,
- pluginWorkloadSdkEnabled: true,
- pluginWorkloadSdkRuntimeMode: 'sdk-only',
- }
- )
await this.deps.createIfNotExists(
() =>
this.deps.coreApi.createNamespacedPod({
namespace: this.deps.config.sandboxNamespace,
- body: mcpHostPod,
+ body: desiredMcpHostPod,
}),
`Pod "${recipeName}-mcp-host"`
)
diff --git a/workflow-recipes/src/workflow/podFactory.ts b/workflow-recipes/src/workflow/podFactory.ts
index ef87dbd69..37f5d2fd2 100644
--- a/workflow-recipes/src/workflow/podFactory.ts
+++ b/workflow-recipes/src/workflow/podFactory.ts
@@ -27,6 +27,40 @@ import { AgentSpec, WorkflowConfig } from './types'
/** Directory where the mcp-host mounts per-caller SDK bearer tokens (Secret volume). */
export const PLUGIN_WORKLOAD_SDK_WORKLOAD_TOKENS_DIR = '/var/run/clerum/plugin-workload-sdk/tokens'
+/**
+ * Annotation carrying the immutable contract used by an eager SDK mcp-host.
+ * Bare Pods have no Deployment template hash, so reconciliation must carry
+ * its own content address for safe same-image migrations.
+ */
+export const PLUGIN_WORKLOAD_SDK_RUNTIME_CONTRACT_HASH_ANNOTATION =
+ 'clerum.io/plugin-workload-sdk-runtime-contract-hash'
+
+function canonicalizeRuntimeContract(value: unknown): unknown {
+ if (Array.isArray(value)) return value.map(canonicalizeRuntimeContract)
+ if (value && typeof value === 'object') {
+ const record = value as Record<string, unknown>
+ return Object.fromEntries(
+ Object.keys(record)
+ .filter(key => record[key] !== undefined)
+ .sort()
+ .map(key => [key, canonicalizeRuntimeContract(record[key])])
+ )
+ }
+ return value
+}
+
+/**
+ * Hash only the PodSpec: metadata names, UIDs, timestamps, and the hash
+ * annotation itself are intentionally excluded. The spec contains the
+ * image, runtime mode/env, ports, volumes, service-account settings, probes,
+ * security context, and propagated runtime inputs that define the eager host
+ * contract.
+ */
+export function pluginWorkloadSdkRuntimeContractHash(pod: k8s.V1Pod): string {
+ const canonical = JSON.stringify(canonicalizeRuntimeContract({ spec: pod.spec }))
+ return createHash('sha256').update(canonical).digest('hex')
+}
+
/**
* Allowlist of env vars forwarded from the WRC controller's process.env into
* each spawned mcp-host pod. Explicit list prevents leaking arbitrary secrets.
@@ -585,7 +619,7 @@ export function buildMcpHostPod(
mountWorkflowOutput && workflowOutputClaimName
? buildWorkflowOutputAffinity(workflowOutputClaimName)
: undefined
- return {
+ const pod: k8s.V1Pod = {
apiVersion: 'v1',
kind: 'Pod',
metadata: {
@@ -806,6 +840,17 @@ export function buildMcpHostPod(
],
},
}
+ if (options.pluginWorkloadSdkEnabled === true) {
+ pod.metadata = {
+ ...pod.metadata,
+ annotations: {
+ ...(pod.metadata?.annotations ?? {}),
+ [PLUGIN_WORKLOAD_SDK_RUNTIME_CONTRACT_HASH_ANNOTATION]:
+ pluginWorkloadSdkRuntimeContractHash(pod),
+ },
+ }
+ }
+ return pod
}
export function buildMcpHostHeadlessService(
diff --git a/workflow-recipes/src/workflow/workflowReconciler.test.ts b/workflow-recipes/src/workflow/workflowReconciler.test.ts
index b9d6ad0c2..9e1da1bb6 100644
--- a/workflow-recipes/src/workflow/workflowReconciler.test.ts
+++ b/workflow-recipes/src/workflow/workflowReconciler.test.ts
@@ -56,6 +56,10 @@ vi.mock('../gfsBinding', () => gfsBindingMocks)
const isoDateAgo = (ageMs: number) => new Date(Date.now() - ageMs).toISOString()
+function unsignedRuntimeJwt(payload: Record<string, unknown>): string {
+ return `eyJhbGciOiJub25lIn0.${Buffer.from(JSON.stringify(payload)).toString('base64url')}.x`
+}
+
type MockPodReadiness = {
ready: boolean
phase?: string
@@ -1420,6 +1424,56 @@ describe('WorkflowReconciler — Plugin Workload SDK eager mcp-host', () => {
...overrides,
}) as unknown as Parameters<WorkflowReconciler['reconcile']>[3]
+ it('rotates access, refresh, and control tokens when runtime scopes drift', async () => {
+ const now = Math.floor(Date.now() / 1000)
+ const staleBinding = {
+ exp: now + 3600,
+ recipeNamespace: sandboxNamespace,
+ recipeName: 'sdk-recipe',
+ hostRefs: [`${sandboxNamespace}/sdk-recipe`],
+ scopes: [],
+ }
+ const staleGfsBinding = {
+ ...staleBinding,
+ hostRefs: [`host:3rd:${sandboxNamespace}/sdk-recipe`],
+ scopes: ['gfs.read'],
+ }
+ mockCoreApi.readNamespacedSecret.mockResolvedValueOnce({
+ data: {
+ 'mcp-host-runtime-access-token': Buffer.from(unsignedRuntimeJwt(staleBinding)).toString(
+ 'base64'
+ ),
+ 'mcp-host-runtime-refresh-token': Buffer.from(unsignedRuntimeJwt(staleBinding)).toString(
+ 'base64'
+ ),
+ 'mcp-host-workflow-control-token': Buffer.from(unsignedRuntimeJwt(staleBinding)).toString(
+ 'base64'
+ ),
+ 'mcp-host-gfs-token': Buffer.from(unsignedRuntimeJwt(staleGfsBinding)).toString('base64'),
+ },
+ })
+
+ const reconciler = new WorkflowReconciler(makeDeps())
+ await reconciler.ensureMcpHostRuntimeCredentials(sandboxNamespace, 'sdk-recipe', sdkSpec())
+
+ expect(runtimeTokenIssuerMocks.issueMcpHostRuntimeTokens).toHaveBeenCalledWith(
+ sandboxNamespace,
+ 'sdk-recipe',
+ ['plugin-workload-sdk']
+ )
+ expect(mockCoreApi.patchNamespacedSecret).toHaveBeenCalledTimes(1)
+ const patch = mockCoreApi.patchNamespacedSecret.mock.calls[0]?.[0] as {
+ body?: { data?: Record<string, string> }
+ }
+ expect(patch.body?.data).toEqual(
+ expect.objectContaining({
+ 'mcp-host-runtime-access-token': expect.any(String),
+ 'mcp-host-runtime-refresh-token': expect.any(String),
+ 'mcp-host-workflow-control-token': expect.any(String),
+ })
+ )
+ })
+
it('creates the mcp-host but NOT the coordinator when no run is triggered', async () => {
const reconciler = new WorkflowReconciler(makeDeps())
@@ -1552,8 +1606,8 @@ describe('WorkflowReconciler — Plugin Workload SDK eager mcp-host', () => {
it('cleans SDK-only host resources idempotently without creating workflow resources', async () => {
const reconciler = new WorkflowReconciler(makeDeps())
- await expect(reconciler.cleanupPluginWorkloadSdkOnly('sdk-only')).resolves.toBeUndefined()
- await expect(reconciler.cleanupPluginWorkloadSdkOnly('sdk-only')).resolves.toBeUndefined()
+ await expect(reconciler.cleanupPluginWorkloadSdk('sdk-only')).resolves.toBeUndefined()
+ await expect(reconciler.cleanupPluginWorkloadSdk('sdk-only')).resolves.toBeUndefined()
expect(mockCoreApi.deleteNamespacedService).toHaveBeenCalledWith({
name: 'wf-sdk-only-mcp-host',
@@ -1574,16 +1628,118 @@ describe('WorkflowReconciler — Plugin Workload SDK eager mcp-host', () => {
expect(mockCoreApi.createNamespacedPod).not.toHaveBeenCalled()
})
- it('fails closed after physical cleanup when the Control API revocation client is absent', async () => {
+ it('fails closed before physical cleanup when the Control API revocation client is absent', async () => {
const deps = makeDeps() as unknown as { pluginWorkloadSdkRevocationClient?: unknown }
delete deps.pluginWorkloadSdkRevocationClient
const reconciler = new WorkflowReconciler(deps as unknown as WorkflowReconcilerDeps)
- await expect(reconciler.cleanupPluginWorkloadSdkOnly('sdk-only')).rejects.toThrow(
+ await expect(reconciler.cleanupPluginWorkloadSdk('sdk-only')).rejects.toThrow(
/revocation client is not configured/
)
- expect(mockCoreApi.deleteNamespacedPod).toHaveBeenCalledWith(
- expect.objectContaining({ name: 'sdk-only-mcp-host' })
+ expect(mockCoreApi.deleteNamespacedPod).not.toHaveBeenCalled()
+ })
+
+ it('retains every SDK resource when Control API revocation fails', async () => {
+ const deps = makeDeps()
+ mockPluginWorkloadSdkRevocationClient.revoke.mockRejectedValueOnce(
+ new Error('control-api unavailable')
+ )
+ const reconciler = new WorkflowReconciler(deps)
+
+ await expect(reconciler.cleanupPluginWorkloadSdk('sdk-only')).rejects.toThrow(
+ 'control-api unavailable'
+ )
+ expect(mockCoreApi.deleteNamespacedPod).not.toHaveBeenCalled()
+ expect(mockCoreApi.deleteNamespacedService).not.toHaveBeenCalled()
+ expect(mockCoreApi.deleteNamespacedSecret).not.toHaveBeenCalled()
+ expect(mockNetworkingApi.deleteNamespacedNetworkPolicy).not.toHaveBeenCalled()
+ })
+
+ it('converges after a post-revocation delete failure on the next reconcile', async () => {
+ const deps = makeDeps()
+ const revocationId = '55555555-5555-4555-8555-555555555555'
+ mockPluginWorkloadSdkRevocationClient.revoke.mockResolvedValue({
+ state: 'revoking',
+ revocationId,
+ revoked: 1,
+ fencedInvocations: 1,
+ })
+ mockPluginWorkloadSdkRevocationClient.finalize.mockResolvedValue({
+ state: 'disabled',
+ revocationId,
+ revoked: 0,
+ fencedInvocations: 0,
+ disabled: 1,
+ })
+ mockCoreApi.deleteNamespacedService.mockRejectedValueOnce(new Error('apiserver timeout'))
+ const reconciler = new WorkflowReconciler(deps)
+
+ await expect(reconciler.cleanupPluginWorkloadSdk('sdk-only')).rejects.toThrow(
+ 'apiserver timeout'
+ )
+ expect(mockPluginWorkloadSdkRevocationClient.finalize).not.toHaveBeenCalled()
+
+ await expect(reconciler.cleanupPluginWorkloadSdk('sdk-only')).resolves.toBeUndefined()
+ expect(mockPluginWorkloadSdkRevocationClient.finalize).toHaveBeenCalledWith(
+ sandboxNamespace,
+ 'sdk-only',
+ revocationId
+ )
+ })
+
+ it('retries finalization after a transient Control API failure once resources are absent', async () => {
+ const deps = makeDeps()
+ const revocationId = '66666666-6666-4666-8666-666666666666'
+ mockPluginWorkloadSdkRevocationClient.revoke.mockResolvedValue({
+ state: 'revoking',
+ revocationId,
+ revoked: 1,
+ fencedInvocations: 0,
+ })
+ mockPluginWorkloadSdkRevocationClient.finalize
+ .mockRejectedValueOnce(new Error('control-api finalize timeout'))
+ .mockResolvedValueOnce({
+ state: 'disabled',
+ revocationId,
+ revoked: 0,
+ fencedInvocations: 0,
+ disabled: 1,
+ })
+ const reconciler = new WorkflowReconciler(deps)
+
+ await expect(reconciler.cleanupPluginWorkloadSdk('sdk-only')).rejects.toThrow(
+ 'control-api finalize timeout'
+ )
+ await expect(reconciler.cleanupPluginWorkloadSdk('sdk-only')).resolves.toBeUndefined()
+ expect(mockPluginWorkloadSdkRevocationClient.finalize).toHaveBeenCalledTimes(2)
+ expect(mockPluginWorkloadSdkRevocationClient.finalize).toHaveBeenLastCalledWith(
+ sandboxNamespace,
+ 'sdk-only',
+ revocationId
+ )
+ })
+
+ it('accepts an already-removed grant as terminal revocation confirmation', async () => {
+ const deps = makeDeps()
+ const revocationId = '77777777-7777-4777-8777-777777777777'
+ mockPluginWorkloadSdkRevocationClient.revoke.mockResolvedValue({
+ state: 'revoking',
+ revocationId,
+ revoked: 1,
+ fencedInvocations: 0,
+ })
+ mockPluginWorkloadSdkRevocationClient.finalize.mockResolvedValue({
+ state: 'missing',
+ revoked: 0,
+ fencedInvocations: 0,
+ })
+ const reconciler = new WorkflowReconciler(deps)
+
+ await expect(reconciler.cleanupPluginWorkloadSdk('sdk-only')).resolves.toBeUndefined()
+ expect(mockPluginWorkloadSdkRevocationClient.finalize).toHaveBeenCalledWith(
+ sandboxNamespace,
+ 'sdk-only',
+ revocationId
)
})
@@ -1606,7 +1762,7 @@ describe('WorkflowReconciler — Plugin Workload SDK eager mcp-host', () => {
)
const reconciler = new WorkflowReconciler(makeDeps())
- await reconciler.cleanupPluginWorkloadSdkOnly('sdk-only')
+ await reconciler.cleanupPluginWorkloadSdk('sdk-only')
expect(mockNetworkingApi.listNamespacedNetworkPolicy).toHaveBeenCalledWith({
namespace: sandboxNamespace,
diff --git a/workflow-recipes/src/workflow/workflowReconciler.ts b/workflow-recipes/src/workflow/workflowReconciler.ts
index 7c05d713f..8496c74c1 100644
--- a/workflow-recipes/src/workflow/workflowReconciler.ts
+++ b/workflow-recipes/src/workflow/workflowReconciler.ts
@@ -947,11 +947,12 @@ export class WorkflowReconciler {
}
/**
- * Remove resources owned exclusively by the SDK-only eager host. This is
- * intentionally narrower than workflow deletion so dropping the capability
- * cannot create or tear down workflow execution state.
+ * Revoke and physically fence the Plugin Workload SDK capability. This is
+ * capability-level cleanup, deliberately independent from workflow
+ * coordinator teardown so both SDK-only and hybrid recipes share the same
+ * authorization-fencing invariant.
*/
- async cleanupPluginWorkloadSdkOnly(recipeName: string): Promise<void> {
+ async cleanupPluginWorkloadSdk(recipeName: string): Promise<void> {
const ns = this.deps.config.sandboxNamespace
this.pluginWorkloadSdkProvisioner.clearRecipeState(recipeName)
const networkPolicyNames = [
@@ -963,30 +964,28 @@ export class WorkflowReconciler {
`${recipeName}-mcp-host-to-gfs`,
`${recipeName}-mcp-host-to-approval-gateway`,
]
- let revocationError: unknown = null
let revocationReceipt: PluginWorkloadSdkRevocationReceipt | null = null
const revocationClient = this.deps.pluginWorkloadSdkRevocationClient
if (!revocationClient) {
- revocationError = new Error(
- 'Plugin Workload SDK revocation client is not configured; refusing to report teardown complete'
+ throw new Error(
+ 'Plugin Workload SDK revocation client is not configured; refusing to tear down an unfenced capability'
)
- } else {
- try {
- revocationReceipt = await revocationClient.revoke(ns, recipeName)
- if (revocationReceipt.state === 'conflict') {
- throw new Error(`Plugin Workload SDK revocation conflict for recipe "${recipeName}"`)
- }
- } catch (error) {
- // Continue with the physical boundary even if control-api is briefly
- // unavailable. The service/network teardown prevents new ingress;
- // the original error is rethrown after absence is proven so WRC does
- // not publish `disabled` and the next reconcile retries the fence.
- revocationError = error
- this.log.error('Plugin Workload SDK control-plane revocation failed', {
- recipeName,
- error: error instanceof Error ? error.message : String(error),
- })
+ }
+ try {
+ // Authorization fencing is the first state transition. If Control API
+ // cannot revoke (or reports a CAS conflict), retain the finalizer and
+ // every owned runtime object for a retry; deleting locally first would
+ // hide an unfenced broker grant and make recovery non-deterministic.
+ revocationReceipt = await revocationClient.revoke(ns, recipeName)
+ if (revocationReceipt.state === 'conflict') {
+ throw new Error(`Plugin Workload SDK revocation conflict for recipe "${recipeName}"`)
}
+ } catch (error) {
+ this.log.error('Plugin Workload SDK control-plane revocation failed', {
+ recipeName,
+ error: error instanceof Error ? error.message : String(error),
+ })
+ throw error
}
// Close the service and network-policy edges before removing the pod or
// token Secrets. This ordering is the revocation boundary: a live pod
@@ -1048,8 +1047,7 @@ export class WorkflowReconciler {
),
])
await this.assertPluginWorkloadSdkResourcesAbsent(recipeName, ns, networkPolicyNames)
- if (revocationError) throw revocationError
- if (revocationClient && revocationReceipt?.state === 'revoking') {
+ if (revocationReceipt.state === 'revoking') {
if (!revocationReceipt.revocationId) {
throw new Error(`Plugin Workload SDK revocation receipt for ${recipeName} has no epoch`)
}
@@ -1058,9 +1056,13 @@ export class WorkflowReconciler {
recipeName,
revocationReceipt.revocationId
)
- if (finalized.state !== 'disabled') {
+ // `missing` is also terminal: an operator may have removed the grant
+ // after the revocation epoch was fenced. There is no remaining broker
+ // authority to finalize in that case, so retaining the recipe finalizer
+ // would turn a safe, idempotent cleanup into a permanent wedge.
+ if (finalized.state !== 'disabled' && finalized.state !== 'missing') {
throw new Error(
- `Plugin Workload SDK revocation for ${recipeName} was not confirmed disabled`
+ `Plugin Workload SDK revocation for ${recipeName} was not confirmed disabled or absent`
)
}
}
@@ -4417,6 +4419,14 @@ export class WorkflowReconciler {
const refreshExp = WorkflowReconciler.jwtExp(refreshJwt)
const accessBinding = WorkflowReconciler.jwtRuntimeBinding(accessJwt)
const refreshBinding = WorkflowReconciler.jwtRuntimeBinding(refreshJwt)
+ const accessScopes = WorkflowReconciler.jwtWorkflowControlScopes(
+ accessJwt,
+ 'workflowControlScopes'
+ )
+ const refreshScopes = WorkflowReconciler.jwtWorkflowControlScopes(
+ refreshJwt,
+ 'workflowControlScopes'
+ )
const rawMcpHostControl = existing.data?.['mcp-host-workflow-control-token']
const mcpHostControlJwt = rawMcpHostControl
? Buffer.from(rawMcpHostControl, 'base64').toString('utf-8')
@@ -4455,6 +4465,9 @@ export class WorkflowReconciler {
expectedControlHostRef
)
const controlScopesMismatch = !workflowControlScopesEqual(controlScopes, workflowControlScopes)
+ const runtimeScopesMismatch =
+ !workflowControlScopesEqual(accessScopes, workflowControlScopes) ||
+ !workflowControlScopesEqual(refreshScopes, workflowControlScopes)
const gfsSubjectMismatch = !!rawGfsAccess && gfsAccessSub !== expectedGfsSubject
const gfsScopesMismatch = !gfsScopesEqual(gfsAccessScopes, expectedGfsScopes)
const refreshBeforeSeconds = this.runtimeTokenFileRefreshBeforeSeconds
@@ -4462,6 +4475,7 @@ export class WorkflowReconciler {
accessExp === 0 ||
refreshExp === 0 ||
runtimeBindingMismatch ||
+ runtimeScopesMismatch ||
accessExp - nowSecs < refreshBeforeSeconds ||
refreshExp - nowSecs < refreshBeforeSeconds
@@ -4482,6 +4496,7 @@ export class WorkflowReconciler {
if (
runtimeBindingMismatch ||
+ runtimeScopesMismatch ||
controlBindingMismatch ||
controlScopesMismatch ||
gfsSubjectMismatch ||
@@ -4492,6 +4507,8 @@ export class WorkflowReconciler {
runtimeScopeRecipeName,
accessBinding,
refreshBinding,
+ accessScopes,
+ refreshScopes,
controlBinding,
controlScopes,
expectedControlScopes: workflowControlScopes,
@@ -4609,10 +4626,13 @@ export class WorkflowReconciler {
}
}
- private static jwtWorkflowControlScopes(jwt: string): WorkflowControlScope[] {
+ private static jwtWorkflowControlScopes(
+ jwt: string,
+ claim: 'scopes' | 'workflowControlScopes' = 'scopes'
+ ): WorkflowControlScope[] {
try {
const payload = decodeJwt(jwt)
- const scopes = Array.isArray(payload.scopes) ? payload.scopes : []
+ const scopes = Array.isArray(payload[claim]) ? payload[claim] : []
const normalized: WorkflowControlScope[] = []
const seen = new Set<string>()
for (const scope of scopes) {
diff --git a/workflow-recipes/tests/unit/workflow/workflowReconciler.test.ts b/workflow-recipes/tests/unit/workflow/workflowReconciler.test.ts
index 396ab100a..bc43f2a75 100644
--- a/workflow-recipes/tests/unit/workflow/workflowReconciler.test.ts
+++ b/workflow-recipes/tests/unit/workflow/workflowReconciler.test.ts
@@ -5163,17 +5163,96 @@ describe('WorkflowReconciler — reconcile loop', () => {
expect(coreApi.patchNamespacedSecret).not.toHaveBeenCalled()
})
+ it('reissues stale access and refresh scopes once, then converges on the next reconcile', async () => {
+ const coreApi = makeCoreApi() as ReturnType<typeof makeCoreApi>
+ const expectedWorkflowControlScopes = [
+ 'workflow:trigger',
+ 'workflow:approval:resolve',
+ 'workflow:approval:decide',
+ ]
+ const canonicalAccessToken = makeJwtWithExp(3600, {
+ workflowControlScopes: expectedWorkflowControlScopes,
+ })
+ const canonicalRefreshToken = makeJwtWithExp(3600, {
+ workflowControlScopes: expectedWorkflowControlScopes,
+ })
+ const canonicalControlToken = makeJwtWithExp(3600, {
+ scopes: expectedWorkflowControlScopes,
+ })
+ vi.mocked(issueMcpHostRuntimeTokens).mockResolvedValue({
+ accessToken: canonicalAccessToken,
+ refreshToken: canonicalRefreshToken,
+ mcpHostControlToken: canonicalControlToken,
+ })
+
+ let secretData: Record<string, string> = {
+ 'mcp-host-runtime-access-token': Buffer.from(
+ makeJwtWithExp(3600, { workflowControlScopes: ['workflow:list'] })
+ ).toString('base64'),
+ 'mcp-host-runtime-refresh-token': Buffer.from(
+ makeJwtWithExp(3600, { workflowControlScopes: ['workflow:list'] })
+ ).toString('base64'),
+ 'mcp-host-workflow-control-token': Buffer.from(
+ makeJwtWithExp(3600, { scopes: expectedWorkflowControlScopes })
+ ).toString('base64'),
+ 'mcp-host-gfs-token': makeEncodedGfsAccess(),
+ }
+ coreApi.readNamespacedSecret = vi.fn().mockImplementation(async ({ name }) => {
+ if (name === 'wf-test-wf-mcp-host-runtime-tokens') return { data: secretData }
+ throw { code: 404 }
+ })
+ coreApi.patchNamespacedSecret = vi.fn().mockImplementation(async ({ body }) => {
+ secretData = { ...secretData, ...(body?.data ?? {}) }
+ return {}
+ })
+
+ const reconciler = new WorkflowReconciler(makeDeps({ coreApi: coreApi as never }))
+ const spec = makeSpec({
+ steps: [
+ {
+ id: 'broker-trigger',
+ instruction: 'Trigger a workflow',
+ allowedTools: { include: ['workflow_trigger'] },
+ },
+ ],
+ })
+
+ await reconciler.ensureMcpHostRuntimeCredentials('recipe-runtime-ns', 'test-wf', spec)
+ expect(issueMcpHostRuntimeTokens).toHaveBeenCalledTimes(1)
+ expect(issueMcpHostRuntimeTokens).toHaveBeenCalledWith(
+ 'recipe-runtime-ns',
+ 'test-wf',
+ expectedWorkflowControlScopes
+ )
+ expect(coreApi.patchNamespacedSecret).toHaveBeenCalledTimes(1)
+
+ await reconciler.ensureMcpHostRuntimeCredentials('recipe-runtime-ns', 'test-wf', spec)
+ expect(issueMcpHostRuntimeTokens).toHaveBeenCalledTimes(1)
+ expect(coreApi.patchNamespacedSecret).toHaveBeenCalledTimes(1)
+ })
+
it('reissues only the workflow-control token when declared broker scopes change', async () => {
const coreApi = makeCoreApi() as ReturnType<typeof makeCoreApi>
+ const expectedWorkflowControlScopes = [
+ 'workflow:trigger',
+ 'workflow:approval:resolve',
+ 'workflow:approval:decide',
+ ]
coreApi.readNamespacedSecret = vi.fn().mockImplementation(async ({ name }) => {
if (name === 'wf-test-wf-mcp-host-runtime-tokens') {
return {
data: {
'mcp-host-runtime-access-token': Buffer.from(
- makeJwtWithExp(3600, { recipeName: 'test-wf' })
+ makeJwtWithExp(3600, {
+ recipeName: 'test-wf',
+ workflowControlScopes: expectedWorkflowControlScopes,
+ })
).toString('base64'),
'mcp-host-runtime-refresh-token': Buffer.from(
- makeJwtWithExp(3600, { recipeName: 'test-wf' })
+ makeJwtWithExp(3600, {
+ recipeName: 'test-wf',
+ workflowControlScopes: expectedWorkflowControlScopes,
+ })
).toString('base64'),
'mcp-host-workflow-control-token': Buffer.from(
makeJwtWithExp(3600, { recipeName: 'test-wf', scopes: ['workflow:list'] })
@@ -5203,9 +5282,7 @@ describe('WorkflowReconciler — reconcile loop', () => {
expect(vi.mocked(issueMcpHostRuntimeTokens).mock.calls.length).toBe(runtimeCallsBefore)
expect(issueMcpHostWorkflowControlToken).toHaveBeenCalledWith('recipe-runtime-ns', 'test-wf', [
- 'workflow:trigger',
- 'workflow:approval:resolve',
- 'workflow:approval:decide',
+ ...expectedWorkflowControlScopes,
])
expect(coreApi.patchNamespacedSecret).toHaveBeenCalledWith(
expect.objectContaining({