Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure
TypeScript
fix: close stepless SDK release blockers
Alfredo Lopezcd55aa92f802
diff --git a/control-api/package-lock.json b/control-api/package-lock.jsonindex bee10c909..c004271a5 100644--- a/control-api/package-lock.json+++ b/control-api/package-lock.json@@ -1,12 +1,12 @@{"name": "clerum-control-api",- "version": "0.1.418",+ "version": "0.1.419","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "clerum-control-api",- "version": "0.1.418",+ "version": "0.1.419","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.jsonindex cea300089..5dbf72a70 100644--- a/control-api/package.json+++ b/control-api/package.json@@ -1,6 +1,6 @@{"name": "clerum-control-api",- "version": "0.1.418",+ "version": "0.1.419","description": "Internal Clerum control plane REST API + UI for managing CRDs and secrets","main": "dist/main.js","engines": {diff --git a/control-api/src/db.ts b/control-api/src/db.tsindex 0ffaf5bea..9d7c6f908 100644--- a/control-api/src/db.ts+++ b/control-api/src/db.ts@@ -10,6 +10,7 @@ import {addPluginWorkloadSdkAttemptLedgerColumns,addPluginWorkloadSdkJitCredentialTicketColumns,addPluginWorkloadSdkNotExecutedSpendOutcome,+ addPluginWorkloadSdkPolicyReviewProvenance,addPluginWorkloadSdkPromptTargetPolicyColumns,addPluginWorkloadSdkProtocolAndRevocation,addPluginWorkloadSdkProviderAttemptLedger,@@ -5134,6 +5135,10 @@ export const CONTROL_API_MIGRATIONS: DbMigration[] = [version: '0087_plugin_workload_sdk_not_executed_spend_outcome',apply: addPluginWorkloadSdkNotExecutedSpendOutcome,},+ {+ version: '0088_plugin_workload_sdk_policy_review_provenance',+ apply: addPluginWorkloadSdkPolicyReviewProvenance,+ },]async function consolidateWorkflowAllowedUsersToTriggers(db: DbClient): Promise<void> {diff --git a/control-api/src/routes/admin/pluginWorkloadSdk.ts b/control-api/src/routes/admin/pluginWorkloadSdk.tsindex c2500aece..2800dd4f6 100644--- a/control-api/src/routes/admin/pluginWorkloadSdk.ts+++ b/control-api/src/routes/admin/pluginWorkloadSdk.ts@@ -22,6 +22,7 @@ import {deleteGrant,getPluginWorkloadSdkLegacyGrantInventory,getQuotaCounters,+ hasUsableClientNotificationRecipients,listGrants,listInvocations,upsertGrant,@@ -325,6 +326,26 @@ export function createAdminPluginWorkloadSdkRouter(): Router {.json({ error: 'allowedEventTypes must be non-empty for clientNotifications grants' })return}+ if (+ capabilityFamily === 'clientNotifications' &&+ allowedTargetRefs.length + allowedUserRefs.length === 0+ ) {+ res.status(400).json({+ error:+ 'clientNotifications grants require at least one allowedTargetRefs or allowedUserRefs entry',+ })+ return+ }+ if (+ capabilityFamily === 'clientNotifications' &&+ !(await hasUsableClientNotificationRecipients({ allowedTargetRefs, allowedUserRefs }))+ ) {+ res.status(400).json({+ error:+ 'clientNotifications grants require at least one existing user or verified notification target',+ })+ return+ }const promptTargets =capabilityFamily === 'promptBridge' ? parsePromptTargets(body.promptTargets, res) : []if (promptTargets === null) returndiff --git a/control-api/src/routes/mcp-host/plugin-workload-sdk.routes.ts b/control-api/src/routes/mcp-host/plugin-workload-sdk.routes.tsindex 22ea99e9a..8ccbe28d3 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@@ -31,7 +31,9 @@ import {getInvocationById,getPluginWorkloadSdkAttemptReceipt,getPluginWorkloadSdkProviderAttempt,+ hasUsableClientNotificationRecipients,hashPromptTargetPolicy,+ isClientNotificationsPolicyReady,listInvocations,markPluginWorkloadSdkProviderAttemptStatus,redeemPluginWorkloadSdkCredentialTicketJti,@@ -704,15 +706,15 @@ export function createMcpHostPluginWorkloadSdkRoutes(): Router {grant &&grant.policyState === 'active' &&grant.policyRevision >= 1 &&+ grant.policyReviewProvenancePresent !== false &&grant.promptTargets.length > 0 &&grant.defaultTargetRef !== null &&grant.promptTargets[0]?.targetRef === grant.defaultTargetRef)const clientNotificationsReady = Boolean(clientNotificationsGrant &&- clientNotificationsGrant.policyState === 'active' &&- clientNotificationsGrant.allowedCallers.length > 0 &&- clientNotificationsGrant.allowedEventTypes.length > 0+ isClientNotificationsPolicyReady(clientNotificationsGrant) &&+ (await hasUsableClientNotificationRecipients(clientNotificationsGrant)))const primaryTarget = grant?.promptTargets[0] ?? nullres.status(200).json({diff --git a/control-api/src/services/pluginWorkloadSdkAuthorizer.ts b/control-api/src/services/pluginWorkloadSdkAuthorizer.tsindex 5d860e46d..1ee5e2e90 100644--- a/control-api/src/services/pluginWorkloadSdkAuthorizer.ts+++ b/control-api/src/services/pluginWorkloadSdkAuthorizer.ts@@ -13,7 +13,9 @@ import {findGrant,getInvocationById,getPluginWorkloadSdkAttemptReceipt,+ hasUsableClientNotificationRecipients,hashPromptTargetPolicy,+ isClientNotificationsPolicyReady,markPluginWorkloadSdkProviderAttemptStatus,registerPluginWorkloadSdkCredentialTicketJti,reservePluginWorkloadSdkProviderAttempt,@@ -293,7 +295,11 @@ async function authorizePromptBridgeInner(return deny('capability_not_declared', 'recipe has no promptBridge grant')}- if (grant.policyState !== 'active' || grant.policyRevision < 1) {+ if (+ grant.policyState !== 'active' ||+ grant.policyRevision < 1 ||+ grant.policyReviewProvenancePresent === false+ ) {return deny('provider_policy_denied','promptBridge grant requires an explicit operator-reviewed target policy'@@ -577,7 +583,13 @@ export async function reissuePromptBridgeCredentialTicket('promptBridge')const callerError = grant ? checkCaller(grant, invocation.callerRef) : null- if (!grant || grant.policyState !== 'active' || grant.policyRevision < 1 || callerError) {+ if (+ !grant ||+ grant.policyState !== 'active' ||+ grant.policyRevision < 1 ||+ grant.policyReviewProvenancePresent === false ||+ callerError+ ) {return deny('provider_policy_denied','promptBridge policy no longer authorizes this invocation'@@ -709,6 +721,15 @@ async function authorizeClientNotificationInner(if (!grant) {return deny('capability_not_declared', 'recipe has no clientNotifications grant')}+ if (+ !isClientNotificationsPolicyReady(grant) ||+ !(await hasUsableClientNotificationRecipients(grant))+ ) {+ return deny(+ 'provider_policy_denied',+ 'clientNotifications policy is not active or has no authorized recipient'+ )+ }const callerError = checkCaller(grant, callerRef)if (callerError) return callerError@@ -868,6 +889,15 @@ async function authorizeListRecipientsInner(if (!grant) {return deny('capability_not_declared', 'recipe has no clientNotifications grant')}+ if (+ !isClientNotificationsPolicyReady(grant) ||+ !(await hasUsableClientNotificationRecipients(grant))+ ) {+ return deny(+ 'provider_policy_denied',+ 'clientNotifications policy is not active or has no authorized recipient'+ )+ }const callerError = checkCaller(grant, callerRef)if (callerError) return callerErrordiff --git a/control-api/src/services/pluginWorkloadSdkDb.ts b/control-api/src/services/pluginWorkloadSdkDb.tsindex 6e1aa4bd7..b376e3fb2 100644--- a/control-api/src/services/pluginWorkloadSdkDb.ts+++ b/control-api/src/services/pluginWorkloadSdkDb.ts@@ -161,12 +161,78 @@ export interface PluginWorkloadSdkGrant {defaultTargetRef: string | nullpolicyState: 'active' | 'legacy_unreviewed' | 'revoking' | 'disabled'policyRevision: number+ /** Durable proof that an operator explicitly saved the current policy. */+ policyReviewProvenancePresent?: boolean/** Kill-switch epoch. Non-null while a recipe is revoking or disabled. */revocationId: string | nullcreatedAt: stringupdatedAt: string}+/**+ * Single readiness predicate for the provider-free notification capability.+ * An active grant without a usable recipient allowlist cannot deliver a+ * notification, so it must never be advertised as validated or admitted by+ * the authorizer.+ */+export function isClientNotificationsPolicyReady(+ grant: Pick<+ PluginWorkloadSdkGrant,+ 'policyState' | 'allowedCallers' | 'allowedEventTypes' | 'allowedTargetRefs' | 'allowedUserRefs'+ >+): boolean {+ return (+ grant.policyState === 'active' &&+ grant.allowedCallers.length > 0 &&+ grant.allowedEventTypes.length > 0 &&+ grant.allowedTargetRefs.length + grant.allowedUserRefs.length > 0+ )+}++const CONTROL_PLANE_USER_UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i++/**+ * Resolve the destination half of the notification contract against the same+ * tables used by delivery. A non-empty JSON allowlist is not sufficient:+ * deleted users and disabled medium identities must not make a recipe appear+ * validated when every send would remain queued or be dropped. A transaction+ * client may be supplied so an admin upsert and its readiness check share one+ * database boundary.+ */+export async function hasUsableClientNotificationRecipients(+ grant: Pick<PluginWorkloadSdkGrant, 'allowedTargetRefs' | 'allowedUserRefs'>,+ db: Pick<DbClient, 'query'> = pool+): Promise<boolean> {+ const userRefs = grant.allowedUserRefs.filter(ref => CONTROL_PLANE_USER_UUID_RE.test(ref))+ if (userRefs.length > 0) {+ const users = await db.query(+ `SELECT id+ FROM users+ WHERE id = ANY($1::uuid[])+ AND email IS NOT NULL+ AND btrim(email) <> ''+ LIMIT 1`,+ [userRefs]+ )+ if (users.rows.length > 0) return true+ }++ const targetRefs = grant.allowedTargetRefs.filter(ref => ref.trim().length > 0)+ if (targetRefs.length === 0) return false++ // Opaque targetRef delivery is backed by verified, non-disabled medium+ // identities; arbitrary strings are intentionally not treated as usable.+ const mediumAccounts = await db.query(+ `SELECT 1+ FROM workflow_approval_medium_accounts+ WHERE provider_user_id = ANY($1::text[])+ AND disabled_at IS NULL+ LIMIT 1`,+ [targetRefs]+ )+ return mediumAccounts.rows.length > 0+}+export interface PluginWorkloadSdkInvocationRecord {id: stringrecipeNamespace: string@@ -298,6 +364,10 @@ function mapGrantRow(row: Record<string, unknown>): PluginWorkloadSdkGrant {typeof row.policy_revision === 'number' && Number.isInteger(row.policy_revision)? row.policy_revision: 0,+ policyReviewProvenancePresent:+ row.policy_reviewed_at != null &&+ typeof row.policy_reviewed_by === 'string' &&+ row.policy_reviewed_by.trim().length > 0,revocationId: row.revocation_id == null ? null : String(row.revocation_id),createdAt: new Date(row.created_at as string).toISOString(),updatedAt: new Date(row.updated_at as string).toISOString(),@@ -430,12 +500,27 @@ export async function upsertGrant(const previousUserRefs = Array.isArray(previousRow?.allowed_user_refs)? previousRow.allowed_user_refs.map(String): []+ if (+ params.capabilityFamily === 'clientNotifications' &&+ !(await hasUsableClientNotificationRecipients(+ {+ allowedTargetRefs: params.allowedTargetRefs ?? [],+ allowedUserRefs: params.allowedUserRefs ?? [],+ },+ db+ ))+ ) {+ throw new Error(+ 'clientNotifications policy requires at least one existing user or verified notification target'+ )+ }const result = await db.query(`INSERT INTO plugin_workload_sdk_grants(recipe_namespace, recipe_name, capability_family, provider, allowed_models,allowed_event_types, allowed_target_refs, allowed_user_refs, allowed_callers,- quota_limits, model_policies, prompt_targets, default_target_ref)- VALUES ($1, $2, $3, $4, $5::jsonb, $6::jsonb, $7::jsonb, $8::jsonb, $9::jsonb, $10::jsonb, $11::jsonb, $12::jsonb, $13)+ quota_limits, model_policies, prompt_targets, default_target_ref,+ policy_reviewed_at, policy_reviewed_by)+ VALUES ($1, $2, $3, $4, $5::jsonb, $6::jsonb, $7::jsonb, $8::jsonb, $9::jsonb, $10::jsonb, $11::jsonb, $12::jsonb, $13, now(), $14)ON CONFLICT (recipe_namespace, recipe_name, capability_family)DO UPDATE SETprovider = EXCLUDED.provider,@@ -462,6 +547,8 @@ export async function upsertGrant(ELSE NULLEND,policy_revision = plugin_workload_sdk_grants.policy_revision + 1,+ policy_reviewed_at = now(),+ policy_reviewed_by = EXCLUDED.policy_reviewed_by,updated_at = now()RETURNING *`,[@@ -478,6 +565,7 @@ export async function upsertGrant(JSON.stringify(params.modelPolicies ?? {}),JSON.stringify(params.promptTargets ?? []),params.defaultTargetRef ?? null,+ operatorSub,])const grant = mapGrantRow(result.rows[0] as Record<string, unknown>)@@ -565,6 +653,7 @@ export interface PluginWorkloadSdkLegacyGrantInventoryItem {policyState: stringpolicyRevision: numberproviderPresent: boolean+ policyReviewProvenancePresent: booleanpromptTargetsCount: numberdefaultTargetRefPresent: booleanreasons: string[]@@ -593,7 +682,8 @@ export async function getPluginWorkloadSdkLegacyGrantInventory(filter?: {}const result = await pool.query(`SELECT id, recipe_namespace, recipe_name, policy_state, policy_revision,- provider, prompt_targets, default_target_ref+ provider, prompt_targets, default_target_ref, policy_reviewed_at,+ policy_reviewed_byFROM plugin_workload_sdk_grantsWHERE ${clauses.join(' AND ')}ORDER BY recipe_namespace, recipe_name`,@@ -609,10 +699,15 @@ export async function getPluginWorkloadSdkLegacyGrantInventory(filter?: {? row.policy_revision: Number(row.policy_revision ?? 0)const providerPresent = typeof row.provider === 'string' && row.provider.trim().length > 0+ const policyReviewProvenancePresent =+ row.policy_reviewed_at != null &&+ typeof row.policy_reviewed_by === 'string' &&+ row.policy_reviewed_by.trim().length > 0const defaultTargetRefPresent =typeof row.default_target_ref === 'string' && row.default_target_ref.trim().length > 0const reasons: string[] = []if (policyState === 'legacy_unreviewed') reasons.push('legacy_policy_state')+ if (!policyReviewProvenancePresent) reasons.push('missing_operator_review_provenance')if (!providerPresent) reasons.push('missing_provider')if (rawTargets.length !== targets.length) reasons.push('invalid_prompt_targets')if (targets.length === 0) reasons.push('empty_prompt_targets')@@ -632,6 +727,7 @@ export async function getPluginWorkloadSdkLegacyGrantInventory(filter?: {policyState,policyRevision: Number.isFinite(policyRevision) ? policyRevision : 0,providerPresent,+ policyReviewProvenancePresent,promptTargetsCount: targets.length,defaultTargetRefPresent,reasons,@@ -1768,10 +1864,22 @@ export async function reviveFailedInvocation(input: {* Returns the number of rows transitioned.*/export async function failStaleInvocations(olderThanSeconds: number): Promise<number> {+ return withTransaction(db => failStaleInvocationsInTransaction(olderThanSeconds, db))+}++/**+ * Transaction-scoped stale recovery primitive. Keeping the transaction+ * injectable makes the row-lock/ledger race testable against a real database+ * and lets callers that already own a control-plane transaction preserve the+ * same atomic fencing boundary as the scheduled sweeper.+ */+export async function failStaleInvocationsInTransaction(+ olderThanSeconds: number,+ db: DbClient+): Promise<number> {const timeoutSeconds = Math.max(1, Math.floor(olderThanSeconds))- return withTransaction(async db => {- const result = await db.query(- `UPDATE plugin_workload_sdk_invocations+ const result = await db.query(+ `UPDATE plugin_workload_sdk_invocationsSET status = 'provider_unavailable', updated_at = now(), completed_at = now()WHERE status = 'in_progress'AND (@@ -1782,62 +1890,61 @@ export async function failStaleInvocations(olderThanSeconds: number): Promise<nu))RETURNING id, attempt_generation`,- [timeoutSeconds]- )- for (const row of result.rows as Array<{ id: string; attempt_generation: number }>) {- const physicalAttempts = await db.query(- `SELECT id, recipe_namespace, recipe_name, attempt_generation,+ [timeoutSeconds]+ )+ for (const row of result.rows as Array<{ id: string; attempt_generation: number }>) {+ const physicalAttempts = await db.query(+ `SELECT id, recipe_namespace, recipe_name, attempt_generation,attempt_index, target_ref, provider, model, credential_slotFROM plugin_workload_sdk_provider_attemptsWHERE invocation_id = $1AND attempt_generation = $2AND status IN ('reserved', 'in_progress', 'complete', 'failed')FOR UPDATE`,- [row.id, row.attempt_generation]- )- for (const attempt of physicalAttempts.rows as Array<Record<string, unknown>>) {- // The host has disappeared, so no current JWT can prove a host_ref.- // Persist an unattributed unknown outcome instead of inventing one- // from recipe names; the physical-attempt PK makes this idempotent.- await db.query(- `INSERT INTO plugin_workload_sdk_spend_outcomes+ [row.id, row.attempt_generation]+ )+ for (const attempt of physicalAttempts.rows as Array<Record<string, unknown>>) {+ // The host has disappeared, so no current JWT can prove a host_ref.+ // Persist an unattributed unknown outcome instead of inventing one+ // from recipe names; the physical-attempt PK makes this idempotent.+ await db.query(+ `INSERT INTO plugin_workload_sdk_spend_outcomes(provider_attempt_id, invocation_id, recipe_namespace, recipe_name,attempt_generation, attempt_index, target_ref, host_ref, provider, model,credential_slot, outcome, reason, input_tokens, output_tokens, usage_request_id)VALUES ($1, $2, $3, $4, $5, $6, $7, NULL, $8, $9, $10, 'unknown','stale_lease', NULL, NULL, NULL)ON CONFLICT (provider_attempt_id) DO NOTHING`,- [- String(attempt.id),- row.id,- String(attempt.recipe_namespace),- String(attempt.recipe_name),- Number(attempt.attempt_generation),- Number(attempt.attempt_index),- String(attempt.target_ref),- String(attempt.provider),- String(attempt.model),- String(attempt.credential_slot),- ]- )- }- await db.query(- `UPDATE plugin_workload_sdk_invocation_attempts+ [+ String(attempt.id),+ row.id,+ String(attempt.recipe_namespace),+ String(attempt.recipe_name),+ Number(attempt.attempt_generation),+ Number(attempt.attempt_index),+ String(attempt.target_ref),+ String(attempt.provider),+ String(attempt.model),+ String(attempt.credential_slot),+ ]+ )+ }+ await db.query(+ `UPDATE plugin_workload_sdk_invocation_attemptsSET status = 'provider_unavailable', lease_expires_at = NULL, completed_at = now()WHERE invocation_id = $1 AND attempt_generation = $2`,- [row.id, row.attempt_generation]- )- await db.query(- `UPDATE plugin_workload_sdk_provider_attempts+ [row.id, row.attempt_generation]+ )+ await db.query(+ `UPDATE plugin_workload_sdk_provider_attemptsSET status = 'provider_unavailable', lease_expires_at = NULL, completed_at = now()WHERE invocation_id = $1AND attempt_generation = $2AND status IN ('reserved', 'in_progress')`,- [row.id, row.attempt_generation]- )- }- return result.rowCount ?? 0- })+ [row.id, row.attempt_generation]+ )+ }+ return result.rowCount ?? 0}export interface ListInvocationsFilter {diff --git a/control-api/src/services/pluginWorkloadSdkFinalization.ts b/control-api/src/services/pluginWorkloadSdkFinalization.tsindex 6f11f766b..e15bb652f 100644--- a/control-api/src/services/pluginWorkloadSdkFinalization.ts+++ b/control-api/src/services/pluginWorkloadSdkFinalization.ts@@ -412,12 +412,16 @@ export async function finalizePromptBridgeInTransaction(WHERE id = $1 AND attempt_generation = $3`,[input.invocationId, expectedStatus, input.attemptGeneration])- await db.query(+ const spendOutcomeInsert = await db.query(`INSERT INTO plugin_workload_sdk_spend_outcomes(provider_attempt_id, invocation_id, recipe_namespace, recipe_name,attempt_generation, attempt_index, target_ref, host_ref, provider, model,credential_slot, outcome, reason, input_tokens, output_tokens, usage_request_id)- VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16)`,+ VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16)+ ON CONFLICT (provider_attempt_id) DO NOTHING+ RETURNING provider_attempt_id, invocation_id, recipe_namespace, recipe_name,+ attempt_generation, attempt_index, target_ref, host_ref, provider,+ model, credential_slot, outcome, input_tokens, output_tokens`,[input.providerAttemptId,input.invocationId,@@ -438,6 +442,30 @@ export async function finalizePromptBridgeInTransaction(])+ // The stale-lease sweeper can win the physical-attempt race between our+ // initial ledger lookup and this insert. Treat an identical existing outcome+ // as an idempotent replay and surface a stable conflict for incompatible+ // accounting, never a raw unique_violation/500.+ if ((spendOutcomeInsert.rowCount ?? spendOutcomeInsert.rows.length) === 0) {+ const raced = await db.query(+ `SELECT provider_attempt_id, invocation_id, recipe_namespace, recipe_name,+ attempt_generation, attempt_index, target_ref, host_ref, provider,+ model, credential_slot, outcome, input_tokens, output_tokens+ FROM plugin_workload_sdk_spend_outcomes+ WHERE provider_attempt_id = $1`,+ [input.providerAttemptId]+ )+ const existingOutcome = raced.rows[0] as SpendOutcomeRow | undefined+ if (!existingOutcome) {+ throw new PromptBridgeFinalizationError(+ 'conflict',+ 'provider attempt outcome was concurrently finalized but is not readable',+ 409+ )+ }+ return mapExistingOutcome(existingOutcome, input)+ }+return {invocationId: input.invocationId,providerAttemptId: input.providerAttemptId,diff --git a/control-api/src/services/pluginWorkloadSdkSchema.ts b/control-api/src/services/pluginWorkloadSdkSchema.tsindex beb32b006..6fddb1fe8 100644--- a/control-api/src/services/pluginWorkloadSdkSchema.ts+++ b/control-api/src/services/pluginWorkloadSdkSchema.ts@@ -32,6 +32,11 @@ export async function applyPluginWorkloadSdkSchema(db: DbClient): Promise<void>policy_revision INTEGER NOT NULL DEFAULT 1,policy_state TEXT NOT NULL DEFAULT 'active'CHECK (policy_state IN ('active', 'legacy_unreviewed', 'revoking', 'disabled')),+ -- A routable policy must carry durable proof that an operator explicitly+ -- reviewed and saved the ordered contract. Shape alone is never+ -- provenance: rows without this pair remain fail-closed.+ policy_reviewed_at TIMESTAMPTZ NULL,+ policy_reviewed_by TEXT NULL,created_at TIMESTAMPTZ NOT NULL DEFAULT now(),updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),UNIQUE (recipe_namespace, recipe_name, capability_family)@@ -349,51 +354,40 @@ export async function addPluginWorkloadSdkAttemptLedgerColumns(db: DbClient): Pr}/**- * Repairs databases that recorded the original 0078 migration before the- * non-degrading predicate shipped. The ordered target policy is retained and- * explicitly re-activated at revision 1; malformed rows remain- * legacy_unreviewed. The operation is idempotent and never touches- * clientNotifications or a policy already fenced as revoking/disabled.+ * Migration 0086 is intentionally a no-op for policy authority. A complete+ * JSON shape is not provenance of an operator decision, so a legacy row must+ * never be reactivated automatically. The forward provenance migration below+ * fences rows on clusters that already ran the original unsafe implementation.*/export async function repairPluginWorkloadSdkLegacyGrantPolicies(db: DbClient): Promise<void> {+ // Keep the migration registered so already-applied version history remains+ // monotonic. No UPDATE is intentionally executed here.+ void db+}++/**+ * Adds explicit operator-review provenance and re-fences every promptBridge+ * row that lacks it. This is forward-only and safe for clusters where 0086+ * already auto-reactivated a structurally complete legacy row: the row is+ * quarantined again and must be explicitly saved through the admin API.+ */+export async function addPluginWorkloadSdkPolicyReviewProvenance(db: DbClient): Promise<void> {await db.query(`+ ALTER TABLE plugin_workload_sdk_grants+ ADD COLUMN IF NOT EXISTS policy_reviewed_at TIMESTAMPTZ NULL,+ ADD COLUMN IF NOT EXISTS policy_reviewed_by TEXT NULL;+UPDATE plugin_workload_sdk_grants- SET policy_state = 'active',- policy_revision = 1,+ SET policy_state = 'legacy_unreviewed',+ policy_revision = 0,updated_at = now()WHERE capability_family = 'promptBridge'- AND policy_state = 'legacy_unreviewed'- AND policy_revision = 0- AND provider IS NOT NULL- AND btrim(provider) <> ''- AND default_target_ref IS NOT NULL- AND btrim(default_target_ref) <> ''- AND CASE WHEN jsonb_typeof(prompt_targets) = 'array'- THEN jsonb_array_length(prompt_targets) > 0 ELSE false END- AND CASE WHEN jsonb_typeof(allowed_callers) = 'array'- THEN jsonb_array_length(allowed_callers) > 0 ELSE false END- AND (prompt_targets -> 0 ->> 'targetRef') = default_target_ref- AND (prompt_targets -> 0 ->> 'provider') = provider- AND NOT EXISTS (- SELECT 1- FROM jsonb_array_elements(- CASE WHEN jsonb_typeof(prompt_targets) = 'array'- THEN prompt_targets ELSE '[]'::jsonb END- ) AS target- WHERE jsonb_typeof(target) <> 'object'- OR btrim(COALESCE(target ->> 'targetRef', '')) = ''- OR btrim(COALESCE(target ->> 'provider', '')) = ''- OR btrim(COALESCE(target ->> 'model', '')) = ''- OR btrim(COALESCE(target ->> 'credentialSlot', '')) = ''- )- AND (- SELECT COUNT(DISTINCT target ->> 'targetRef')- FROM jsonb_array_elements(- CASE WHEN jsonb_typeof(prompt_targets) = 'array'- THEN prompt_targets ELSE '[]'::jsonb END- ) AS target- ) = CASE WHEN jsonb_typeof(prompt_targets) = 'array'- THEN jsonb_array_length(prompt_targets) ELSE 0 END;+ AND policy_state = 'active'+ AND policy_reviewed_at IS NULL;++ CREATE INDEX IF NOT EXISTS plugin_workload_sdk_grants_review_provenance_idx+ ON plugin_workload_sdk_grants (policy_reviewed_at)+ WHERE capability_family = 'promptBridge' AND policy_reviewed_at IS NULL;`)}diff --git a/control-api/test/db.pluginWorkloadSdkProtocolMigration.test.ts b/control-api/test/db.pluginWorkloadSdkProtocolMigration.test.tsindex 3f717a2d2..977502ff9 100644--- a/control-api/test/db.pluginWorkloadSdkProtocolMigration.test.ts+++ b/control-api/test/db.pluginWorkloadSdkProtocolMigration.test.ts@@ -2,6 +2,7 @@ import { describe, expect, it, vi } from 'vitest'import {addPluginWorkloadSdkAttemptLedgerColumns,addPluginWorkloadSdkNotExecutedSpendOutcome,+ addPluginWorkloadSdkPolicyReviewProvenance,addPluginWorkloadSdkProtocolAndRevocation,addPluginWorkloadSdkRuntimeAccess,repairPluginWorkloadSdkLegacyGrantPolicies,@@ -49,18 +50,26 @@ describe('plugin workload SDK protocol migration', () => {expect(migrationSql).toContain("policy_state = 'active'")})- it('provides an idempotent forward repair for valid policies already marked legacy', async () => {+ it('keeps the legacy policy repair migration fail-closed', async () => {const query = vi.fn().mockResolvedValue({ rows: [], rowCount: 0 })await repairPluginWorkloadSdkLegacyGrantPolicies({ query } as never)+ expect(query).not.toHaveBeenCalled()+ })++ it('adds durable review provenance and re-fences ambiguous active rows', async () => {+ const query = vi.fn().mockResolvedValue({ rows: [], rowCount: 0 })++ await addPluginWorkloadSdkPolicyReviewProvenance({ query } as never)+const migrationSql = String(query.mock.calls[0]?.[0])- expect(migrationSql).toContain("SET policy_state = 'active'")- expect(migrationSql).toContain('policy_revision = 1')- expect(migrationSql).toContain("policy_state = 'legacy_unreviewed'")+ expect(migrationSql).toContain('policy_reviewed_at TIMESTAMPTZ NULL')+ expect(migrationSql).toContain('policy_reviewed_by TEXT NULL')+ expect(migrationSql).toContain("SET policy_state = 'legacy_unreviewed'")+ expect(migrationSql).toContain('policy_reviewed_at IS NULL')expect(migrationSql).toContain('policy_revision = 0')- expect(migrationSql).toContain("capability_family = 'promptBridge'")- expect(migrationSql).not.toContain('clientNotifications')+ expect(migrationSql).not.toContain("SET policy_state = 'active'")})it('keeps no-execution receipts distinct from unknown provider spend', async () => {diff --git a/control-api/test/pluginWorkloadSdkPolicyReview.realPostgres.integration.test.ts b/control-api/test/pluginWorkloadSdkPolicyReview.realPostgres.integration.test.tsnew file mode 100644index 000000000..31129675c--- /dev/null+++ b/control-api/test/pluginWorkloadSdkPolicyReview.realPostgres.integration.test.ts@@ -0,0 +1,137 @@+import { afterAll, beforeAll, describe, expect, it } from 'vitest'+import { randomBytes } from 'node:crypto'+import { Pool } from 'pg'+import { initDb } from '../src/db.js'+import {+ addPluginWorkloadSdkPolicyReviewProvenance,+ repairPluginWorkloadSdkLegacyGrantPolicies,+} from '../src/services/pluginWorkloadSdkSchema.js'++const adminUrl = process.env.CONTROL_API_REAL_PG_ADMIN_URL+const describeRealPostgres = adminUrl ? describe : describe.skip++function databaseUrl(baseUrl: string, database: string): string {+ const url = new URL(baseUrl)+ url.pathname = `/${database}`+ return url.toString()+}++describeRealPostgres('Plugin Workload SDK policy review provenance on real PostgreSQL', () => {+ const database = `control_api_sdk_policy_${randomBytes(6).toString('hex')}`+ const connectionString = databaseUrl(+ adminUrl ?? 'postgresql://[email protected]/postgres',+ database+ )+ let adminPool: Pool+ let dbPool: Pool++ beforeAll(async () => {+ adminPool = new Pool({ connectionString: adminUrl })+ await adminPool.query(`CREATE DATABASE "${database.replace(/"/g, '""')}"`)+ dbPool = new Pool({ connectionString })+ await initDb({ connect: () => dbPool.connect() })+ })++ afterAll(async () => {+ await dbPool?.end()+ if (!adminPool) return+ await adminPool.query(+ `SELECT pg_terminate_backend(pid)+ FROM pg_stat_activity+ WHERE datname = $1+ AND pid <> pg_backend_pid()`,+ [database]+ )+ await adminPool.query(`DROP DATABASE IF EXISTS "${database.replace(/"/g, '""')}"`)+ await adminPool.end()+ })++ it('re-fences complete-looking active rows without provenance and never reactivates them', async () => {+ const client = await dbPool.connect()+ try {+ const inserted = await client.query<{ id: string }>(+ `INSERT INTO plugin_workload_sdk_grants+ (recipe_namespace, recipe_name, capability_family, provider,+ allowed_callers, prompt_targets, default_target_ref, policy_revision,+ policy_state, policy_reviewed_at, policy_reviewed_by)+ VALUES ('sandbox-recipes', 'legacy-complete-looking', 'promptBridge', 'openai',+ '["worker"]'::jsonb,+ '[{"targetRef":"primary","provider":"openai","model":"gpt-4o-mini","credentialSlot":"openai-api-key"}]'::jsonb,+ 'primary', 1, 'active', NULL, NULL)+ RETURNING id`+ )+ const grantId = inserted.rows[0]!.id++ await repairPluginWorkloadSdkLegacyGrantPolicies({+ query: client.query.bind(client),+ } as never)+ const repairState = await client.query(+ `SELECT policy_state, policy_revision+ FROM plugin_workload_sdk_grants+ WHERE id = $1`,+ [grantId]+ )+ expect(repairState.rows[0]).toEqual({ policy_state: 'active', policy_revision: 1 })++ await addPluginWorkloadSdkPolicyReviewProvenance({+ query: client.query.bind(client),+ } as never)+ const fencedState = await client.query(+ `SELECT policy_state, policy_revision, policy_reviewed_at, policy_reviewed_by+ FROM plugin_workload_sdk_grants+ WHERE id = $1`,+ [grantId]+ )+ expect(fencedState.rows[0]).toMatchObject({+ policy_state: 'legacy_unreviewed',+ policy_revision: 0,+ policy_reviewed_at: null,+ policy_reviewed_by: null,+ })++ await client.query(+ `UPDATE plugin_workload_sdk_grants+ SET policy_state = 'active', policy_revision = 2,+ policy_reviewed_at = now(), policy_reviewed_by = 'operator-1'+ WHERE id = $1`,+ [grantId]+ )+ await addPluginWorkloadSdkPolicyReviewProvenance({+ query: client.query.bind(client),+ } as never)+ const reviewedState = await client.query(+ `SELECT policy_state, policy_revision, policy_reviewed_by+ FROM plugin_workload_sdk_grants+ WHERE id = $1`,+ [grantId]+ )+ expect(reviewedState.rows[0]).toMatchObject({+ policy_state: 'active',+ policy_revision: 2,+ policy_reviewed_by: 'operator-1',+ })+ } finally {+ client.release()+ }+ })++ it('keeps the SDK attempt and spend ledgers writable only by control_api_runtime', async () => {+ const result = await dbPool.query(`+ SELECT+ has_table_privilege('control_api_runtime', 'plugin_workload_sdk_provider_attempts', 'SELECT,INSERT,UPDATE,DELETE') AS control_attempt_rw,+ has_table_privilege('workflow_recipes_runtime', 'plugin_workload_sdk_provider_attempts', 'SELECT') AS wrc_attempt_read,+ has_table_privilege('trace_maintenance_runtime', 'plugin_workload_sdk_provider_attempts', 'SELECT') AS trace_attempt_read,+ has_table_privilege('control_api_runtime', 'plugin_workload_sdk_spend_outcomes', 'SELECT,INSERT') AS control_spend_write,+ has_table_privilege('workflow_recipes_runtime', 'plugin_workload_sdk_spend_outcomes', 'SELECT') AS wrc_spend_read,+ has_table_privilege('trace_maintenance_runtime', 'plugin_workload_sdk_spend_outcomes', 'SELECT') AS trace_spend_read+ `)+ expect(result.rows[0]).toEqual({+ control_attempt_rw: true,+ wrc_attempt_read: false,+ trace_attempt_read: false,+ control_spend_write: true,+ wrc_spend_read: false,+ trace_spend_read: false,+ })+ })+})diff --git a/control-api/test/routes.adminPluginWorkloadSdk.test.ts b/control-api/test/routes.adminPluginWorkloadSdk.test.tsindex e545f53d4..74c7ba2e1 100644--- a/control-api/test/routes.adminPluginWorkloadSdk.test.ts+++ b/control-api/test/routes.adminPluginWorkloadSdk.test.ts@@ -29,6 +29,7 @@ vi.mock('../src/services/pluginWorkloadSdkDb.js', async () => {deleteGrant: vi.fn(),getQuotaCounters: vi.fn(),getPluginWorkloadSdkLegacyGrantInventory: vi.fn(),+ hasUsableClientNotificationRecipients: vi.fn(),listInvocations: vi.fn(),}})@@ -70,7 +71,9 @@ beforeEach(() => {vi.mocked(sdkDb.deleteGrant).mockReset()vi.mocked(sdkDb.getQuotaCounters).mockReset()vi.mocked(sdkDb.getPluginWorkloadSdkLegacyGrantInventory).mockReset()+ vi.mocked(sdkDb.hasUsableClientNotificationRecipients).mockReset()vi.mocked(sdkDb.listInvocations).mockReset()+ vi.mocked(sdkDb.hasUsableClientNotificationRecipients).mockResolvedValue(true)vi.mocked(checkAndIncrement).mockReset()vi.mocked(checkAndIncrement).mockResolvedValue({allowed: true,@@ -402,6 +405,7 @@ describe('routes/admin/pluginWorkloadSdk — grants', () => {capabilityFamily: 'clientNotifications',allowedEventTypes: ['lead.followup.due'],allowedCallers: ['api'],+ allowedUserRefs: ['11111111-1111-4111-8111-111111111111'],})expect(res.status).toBe(200)expect(sdkDb.upsertGrant).toHaveBeenCalledWith(@@ -410,6 +414,21 @@ describe('routes/admin/pluginWorkloadSdk — grants', () => {)})+ it('rejects clientNotifications grants without an authorized destination', async () => {+ const res = await request(buildApp())+ .post('/admin/plugin-workload-sdk/grants')+ .send({+ recipeNamespace: 'sandbox-recipes',+ recipeName: 'r1',+ capabilityFamily: 'clientNotifications',+ allowedEventTypes: ['lead.followup.due'],+ allowedCallers: ['api'],+ })+ expect(res.status).toBe(400)+ expect(res.body.error).toContain('allowedTargetRefs or allowedUserRefs')+ expect(sdkDb.upsertGrant).not.toHaveBeenCalled()+ })+it('rejects empty allowedCallers', async () => {const res = await request(buildApp()).post('/admin/plugin-workload-sdk/grants')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.tsindex d7af530f3..f4459cb37 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@@ -35,6 +35,7 @@ vi.mock('../src/services/pluginWorkloadSdkDb.js', async () => {getInvocationById: vi.fn(),getPluginWorkloadSdkAttemptReceipt: vi.fn(),getPluginWorkloadSdkProviderAttempt: vi.fn(),+ hasUsableClientNotificationRecipients: vi.fn(),findGrant: vi.fn(),listInvocations: vi.fn(),redeemPluginWorkloadSdkCredentialTicketJti: vi.fn(),@@ -123,6 +124,7 @@ beforeEach(() => {vi.mocked(sdkDb.getInvocationById).mockReset()vi.mocked(sdkDb.getPluginWorkloadSdkAttemptReceipt).mockReset()vi.mocked(sdkDb.getPluginWorkloadSdkProviderAttempt).mockReset()+ vi.mocked(sdkDb.hasUsableClientNotificationRecipients).mockReset()vi.mocked(sdkDb.findGrant).mockReset()vi.mocked(sdkDb.redeemPluginWorkloadSdkCredentialTicketJti).mockReset()vi.mocked(sdkDb.markPluginWorkloadSdkProviderAttemptStatus).mockReset()@@ -132,6 +134,7 @@ beforeEach(() => {vi.mocked(sdkDb.redeemPluginWorkloadSdkCredentialTicketJti).mockResolvedValue(true)vi.mocked(sdkDb.getPluginWorkloadSdkAttemptReceipt).mockResolvedValue(null)vi.mocked(sdkDb.getPluginWorkloadSdkProviderAttempt).mockResolvedValue(null)+ vi.mocked(sdkDb.hasUsableClientNotificationRecipients).mockResolvedValue(true)vi.mocked(sdkDb.markPluginWorkloadSdkProviderAttemptStatus).mockResolvedValue(true)vi.mocked(authorizer.authorizePromptBridge).mockResolvedValue({ok: true,diff --git a/control-api/test/services.pluginWorkloadSdkAuthorizer.test.ts b/control-api/test/services.pluginWorkloadSdkAuthorizer.test.tsindex 6a20cb4b7..1c4f4b09a 100644--- a/control-api/test/services.pluginWorkloadSdkAuthorizer.test.ts+++ b/control-api/test/services.pluginWorkloadSdkAuthorizer.test.ts@@ -31,6 +31,7 @@ vi.mock('../src/services/pluginWorkloadSdkDb.js', async () => {countRecentInvocations: vi.fn(),getInvocationById: vi.fn(),getPluginWorkloadSdkAttemptReceipt: vi.fn(),+ hasUsableClientNotificationRecipients: vi.fn(),reservePluginWorkloadSdkProviderAttempt: vi.fn(),markPluginWorkloadSdkProviderAttemptStatus: vi.fn(),registerPluginWorkloadSdkCredentialTicketJti: vi.fn(),@@ -141,11 +142,13 @@ beforeEach(() => {vi.mocked(sdkDb.countRecentInvocations).mockReset()vi.mocked(sdkDb.getInvocationById).mockReset()vi.mocked(sdkDb.getPluginWorkloadSdkAttemptReceipt).mockReset()+ vi.mocked(sdkDb.hasUsableClientNotificationRecipients).mockReset()vi.mocked(sdkDb.reservePluginWorkloadSdkProviderAttempt).mockReset()vi.mocked(sdkDb.markPluginWorkloadSdkProviderAttemptStatus).mockReset()vi.mocked(sdkDb.registerPluginWorkloadSdkCredentialTicketJti).mockReset()vi.mocked(sdkDb.countRecentInvocations).mockResolvedValue(0)vi.mocked(sdkDb.consumePeriodQuota).mockResolvedValue(true)+ vi.mocked(sdkDb.hasUsableClientNotificationRecipients).mockResolvedValue(true)vi.mocked(sdkDb.registerPluginWorkloadSdkCredentialTicketJti).mockResolvedValue(true)vi.mocked(sdkDb.getPluginWorkloadSdkAttemptReceipt).mockResolvedValue({invocationId: 'inv-1',@@ -231,6 +234,13 @@ describe('authorizePromptBridge', () => {expect(sdkDb.insertInvocation).not.toHaveBeenCalled()})+ it('fails closed when an active promptBridge grant lacks review provenance', async () => {+ vi.mocked(sdkDb.findGrant).mockResolvedValue(grant({ policyReviewProvenancePresent: false }))+ const result = await authorizePromptBridge({ claims: claims(), ...basePromptParams })+ expect(result).toMatchObject({ ok: false, error: 'provider_policy_denied' })+ expect(sdkDb.insertInvocation).not.toHaveBeenCalled()+ })+it('uses the ordered default when the request omits a selector', async () => {const paramsWithoutModel = {callerRef: basePromptParams.callerRef,@@ -920,6 +930,7 @@ describe('authorizeListRecipients', () => {grant({capabilityFamily: 'clientNotifications',allowedEventTypes: ['lead.followup.due'],+ allowedUserRefs: ['11111111-1111-4111-8111-111111111111'],...overrides,})@@ -951,4 +962,18 @@ describe('authorizeListRecipients', () => {expect(sdkDb.insertInvocation).not.toHaveBeenCalled()expect(sdkDb.consumePeriodQuota).not.toHaveBeenCalled()})++ it.each(['revoking', 'disabled'] as const)(+ 'denies recipient listing while policy is %s',+ async policyState => {+ vi.mocked(sdkDb.findGrant).mockResolvedValue(+ notificationGrant({+ policyState,+ allowedUserRefs: ['11111111-1111-4111-8111-111111111111'],+ })+ )+ const result = await authorizeListRecipients({ claims: claims(), callerRef: 'api' })+ expect(result).toMatchObject({ ok: false, error: 'provider_policy_denied' })+ }+ )})diff --git a/control-api/test/services.pluginWorkloadSdkDb.test.ts b/control-api/test/services.pluginWorkloadSdkDb.test.tsindex 988ecb1d2..e2a302cc9 100644--- a/control-api/test/services.pluginWorkloadSdkDb.test.ts+++ b/control-api/test/services.pluginWorkloadSdkDb.test.ts@@ -6,6 +6,7 @@ import {failStaleInvocations,finalizePluginWorkloadSdkRevocation,getPluginWorkloadSdkLegacyGrantInventory,+ hasUsableClientNotificationRecipients,hashPromptTargetPolicy,markPluginWorkloadSdkProviderAttemptStatus,redeemPluginWorkloadSdkCredentialTicketJti,@@ -45,11 +46,23 @@ function maxPlaceholder(sql: string): number {function mockUpsertGrantQueries(row: Record<string, unknown>): void {// recipe advisory lock → family row → recipe kill-switch guard → upsert.- vi.mocked(pool.query)- .mockResolvedValueOnce({ rows: [], rowCount: 0 } as never)- .mockResolvedValueOnce({ rows: [], rowCount: 0 } as never)- .mockResolvedValueOnce({ rows: [], rowCount: 0 } as never)- .mockResolvedValueOnce({ rows: [row], rowCount: 1 } as never)+ const responses = [+ { rows: [], rowCount: 0 },+ { rows: [], rowCount: 0 },+ { rows: [], rowCount: 0 },+ ] as Array<{ rows: unknown[]; rowCount: number }>+ if (row.capability_family === 'clientNotifications') {+ responses.push({ rows: [{ id: '11111111-1111-4111-8111-111111111111' }], rowCount: 1 })+ }+ responses.push({ rows: [row], rowCount: 1 })+ if (row.capability_family === 'clientNotifications') {+ // Permission-event materialization resolves newly added control-plane+ // users after the upsert has returned its row.+ responses.push({ rows: [{ id: '11111111-1111-4111-8111-111111111111' }], rowCount: 1 })+ }+ for (const response of responses) {+ vi.mocked(pool.query).mockResolvedValueOnce(response as never)+ }}describe('consumePeriodQuota — SQL bind parameter contract', () => {@@ -287,6 +300,8 @@ describe('legacy promptBridge inventory', () => {provider: null,prompt_targets: [],default_target_ref: null,+ policy_reviewed_at: null,+ policy_reviewed_by: null,},{id: 'grant-active',@@ -304,6 +319,8 @@ describe('legacy promptBridge inventory', () => {},],default_target_ref: 'primary-openai',+ policy_reviewed_at: '2026-08-05T00:00:00.000Z',+ policy_reviewed_by: 'operator-1',},],rowCount: 2,@@ -507,6 +524,7 @@ describe('upsertGrant — provider column (R1)', () => {...grantRow,capability_family: 'clientNotifications',provider: null,+ allowed_user_refs: ['11111111-1111-4111-8111-111111111111'],})const grant = await upsertGrant({@@ -514,6 +532,7 @@ describe('upsertGrant — provider column (R1)', () => {recipeName: 'sdk-recipe',capabilityFamily: 'clientNotifications',allowedCallers: ['api'],+ allowedUserRefs: ['11111111-1111-4111-8111-111111111111'],},'operator-1')@@ -649,6 +668,47 @@ describe('resolveRecipientProfiles', () => {})})+describe('hasUsableClientNotificationRecipients', () => {+ const U1 = '11111111-1111-4111-8111-111111111111'++ it('accepts an existing user with a deliverable email address', async () => {+ const db = { query: vi.fn().mockResolvedValue({ rows: [{ id: U1 }], rowCount: 1 }) }+ await expect(+ hasUsableClientNotificationRecipients({ allowedUserRefs: [U1], allowedTargetRefs: [] }, db)+ ).resolves.toBe(true)+ expect(db.query).toHaveBeenCalledTimes(1)+ expect(String(db.query.mock.calls[0]?.[0])).toContain('email IS NOT NULL')+ })++ it('accepts a verified non-disabled medium target when no user is selected', async () => {+ const db = { query: vi.fn().mockResolvedValue({ rows: [{ '?column?': 1 }], rowCount: 1 }) }+ await expect(+ hasUsableClientNotificationRecipients(+ { allowedUserRefs: [], allowedTargetRefs: ['telegram-user-1'] },+ db+ )+ ).resolves.toBe(true)+ expect(db.query).toHaveBeenCalledTimes(1)+ expect(String(db.query.mock.calls[0]?.[0])).toContain('FROM workflow_approval_medium_accounts')+ })++ it('rejects deleted users and disabled/unknown targets instead of treating a non-empty list as ready', async () => {+ const db = {+ query: vi+ .fn()+ .mockResolvedValueOnce({ rows: [], rowCount: 0 })+ .mockResolvedValueOnce({ rows: [], rowCount: 0 }),+ }+ await expect(+ hasUsableClientNotificationRecipients(+ { allowedUserRefs: [U1], allowedTargetRefs: ['unknown-target'] },+ db+ )+ ).resolves.toBe(false)+ expect(db.query).toHaveBeenCalledTimes(2)+ })+})+describe('Plugin Workload SDK governed permission events', () => {const U1 = '11111111-1111-4111-8111-111111111111'const U2 = '22222222-2222-4222-8222-222222222222'diff --git a/control-api/test/services.pluginWorkloadSdkFinalization.realPostgres.integration.test.ts b/control-api/test/services.pluginWorkloadSdkFinalization.realPostgres.integration.test.tsnew file mode 100644index 000000000..2cfa5d8ad--- /dev/null+++ b/control-api/test/services.pluginWorkloadSdkFinalization.realPostgres.integration.test.ts@@ -0,0 +1,373 @@+import { afterAll, beforeAll, describe, expect, it } from 'vitest'+import { randomBytes, randomUUID } from 'node:crypto'+import { Pool, type PoolClient } from 'pg'+import { initDb } from '../src/db.js'+import { failStaleInvocationsInTransaction } from '../src/services/pluginWorkloadSdkDb.js'+import {+ PromptBridgeFinalizationError,+ type PromptBridgeFinalizationInput,+ finalizePromptBridgeInTransaction,+} from '../src/services/pluginWorkloadSdkFinalization.js'++const adminUrl = process.env.CONTROL_API_REAL_PG_ADMIN_URL+const describeRealPostgres = adminUrl ? describe : describe.skip++function databaseUrl(baseUrl: string, database: string): string {+ const url = new URL(baseUrl)+ url.pathname = `/${database}`+ return url.toString()+}++async function begin(client: PoolClient): Promise<void> {+ await client.query('BEGIN')+}++async function commit(client: PoolClient): Promise<void> {+ await client.query('COMMIT')+}++describeRealPostgres('Plugin Workload SDK finalization on real PostgreSQL', () => {+ const database = `control_api_sdk_finalization_${randomBytes(6).toString('hex')}`+ const connectionString = databaseUrl(+ adminUrl ?? 'postgresql://[email protected]/postgres',+ database+ )+ let adminPool: Pool+ let dbPool: Pool++ beforeAll(async () => {+ adminPool = new Pool({ connectionString: adminUrl })+ await adminPool.query(`CREATE DATABASE "${database.replace(/"/g, '""')}"`)+ dbPool = new Pool({ connectionString })+ await initDb({ connect: () => dbPool.connect() })+ })++ afterAll(async () => {+ await dbPool?.end()+ if (adminPool) {+ await adminPool.query(+ `SELECT pg_terminate_backend(pid)+ FROM pg_stat_activity+ WHERE datname = $1+ AND pid <> pg_backend_pid()`,+ [database]+ )+ await adminPool.query(`DROP DATABASE IF EXISTS "${database.replace(/"/g, '""')}"`)+ await adminPool.end()+ }+ })++ async function seedAttempt(+ client: PoolClient,+ options: {+ status?: PromptBridgeFinalizationInput['status']+ leaseExpired?: boolean+ } = {}+ ): Promise<PromptBridgeFinalizationInput> {+ const invocationId = randomUUID()+ const providerAttemptId = randomUUID()+ const recipeNamespace = 'sandbox-recipes'+ const recipeName = `real-finalization-${invocationId}`+ const status = options.status ?? 'provider_unavailable'+ const leaseExpression = options.leaseExpired+ ? "now() - interval '5 minutes'"+ : "now() + interval '5 minutes'"+ const target = {+ targetRef: 'primary-openai',+ provider: 'openai',+ model: 'gpt-4o-mini',+ credentialSlot: 'openai-api-key',+ }+ await client.query(+ `INSERT INTO plugin_workload_sdk_invocations+ (id, recipe_namespace, recipe_name, caller_ref, method, detail,+ idempotency_key_hash, payload_hash, status, authorization_decision,+ contract_version, attempt_generation, lease_expires_at)+ VALUES ($1, $2, $3, 'integration-test', 'promptBridge', '{}',+ $4, $5, 'in_progress', 'allowed', 2, 1, ${leaseExpression})`,+ [invocationId, recipeNamespace, recipeName, randomUUID(), randomUUID()]+ )+ await client.query(+ `INSERT INTO plugin_workload_sdk_invocation_attempts+ (invocation_id, recipe_namespace, recipe_name, attempt_generation,+ method, target_refs, status, lease_expires_at)+ VALUES ($1, $2, $3, 1, 'promptBridge', $4::jsonb, 'in_progress',+ ${leaseExpression})`,+ [invocationId, recipeNamespace, recipeName, JSON.stringify([target.targetRef])]+ )+ await client.query(+ `INSERT INTO plugin_workload_sdk_provider_attempts+ (id, invocation_id, recipe_namespace, recipe_name, attempt_generation,+ attempt_index, target_ref, provider, model, credential_slot, status,+ lease_expires_at)+ VALUES ($1, $2, $3, $4, 1, 1, $5, $6, $7, $8, 'in_progress',+ now() + interval '5 minutes')`,+ [+ providerAttemptId,+ invocationId,+ recipeNamespace,+ recipeName,+ target.targetRef,+ target.provider,+ target.model,+ target.credentialSlot,+ ]+ )+ return {+ invocationId,+ recipeNamespace,+ recipeName,+ hostRef: 'mcp-host/integration',+ attemptGeneration: 1,+ providerAttemptId,+ providerAttemptIndex: 1,+ status,+ target,+ reason: 'integration_provider_unavailable',+ ...(status === 'complete'+ ? {+ usage: {+ llmSecretName: 'openai-api-key',+ callerRef: 'integration-test',+ fallbackUsed: false,+ attemptCount: 1,+ inputTokens: 23,+ outputTokens: 11,+ },+ }+ : {}),+ }+ }++ it('writes one immutable unknown outcome and makes an identical replay idempotent', async () => {+ const client = await dbPool.connect()+ try {+ await begin(client)+ const input = await seedAttempt(client)+ const first = await finalizePromptBridgeInTransaction(input, client)+ await commit(client)++ expect(first).toMatchObject({+ status: 'provider_unavailable',+ outcome: 'unknown',+ idempotent: false,+ })++ const replayClient = await dbPool.connect()+ try {+ await begin(replayClient)+ const replay = await finalizePromptBridgeInTransaction(input, replayClient)+ await commit(replayClient)+ expect(replay).toMatchObject({+ status: 'provider_unavailable',+ outcome: 'unknown',+ idempotent: true,+ })+ } finally {+ replayClient.release()+ }++ const count = await dbPool.query(+ `SELECT count(*)::int AS count+ FROM plugin_workload_sdk_spend_outcomes+ WHERE provider_attempt_id = $1`,+ [input.providerAttemptId]+ )+ expect(count.rows[0]?.count).toBe(1)+ } finally {+ await client.query('ROLLBACK').catch(() => undefined)+ client.release()+ }+ })++ it('serializes concurrent identical finalizers without a unique-violation response', async () => {+ const seedClient = await dbPool.connect()+ const firstClient = await dbPool.connect()+ const secondClient = await dbPool.connect()+ try {+ await begin(seedClient)+ const input = await seedAttempt(seedClient)+ await commit(seedClient)+ await Promise.all([begin(firstClient), begin(secondClient)])+ const firstPromise = finalizePromptBridgeInTransaction(input, firstClient)+ const secondPromise = finalizePromptBridgeInTransaction(input, secondClient)+ const winner = await Promise.race([+ firstPromise.then(result => ({ slot: 'first' as const, result })),+ secondPromise.then(result => ({ slot: 'second' as const, result })),+ ])+ if (winner.slot === 'first') {+ await commit(firstClient)+ } else {+ await commit(secondClient)+ }+ const first = winner.slot === 'first' ? winner.result : await firstPromise+ const second = winner.slot === 'second' ? winner.result : await secondPromise+ if (winner.slot === 'first') await commit(secondClient)+ else await commit(firstClient)+ const results = [first, second]+ expect(results.map(result => result.outcome)).toEqual(['unknown', 'unknown'])+ expect(results.filter(result => result.idempotent)).toHaveLength(1)+ } finally {+ await Promise.all([+ firstClient.query('ROLLBACK').catch(() => undefined),+ secondClient.query('ROLLBACK').catch(() => undefined),+ ])+ seedClient.release()+ firstClient.release()+ secondClient.release()+ }+ })++ it('records exact usage and projects it once; an identical replay does not bill twice', async () => {+ const client = await dbPool.connect()+ try {+ await begin(client)+ const input = await seedAttempt(client, { status: 'complete' })+ const first = await finalizePromptBridgeInTransaction(input, client)+ await commit(client)++ expect(first).toMatchObject({+ status: 'complete',+ outcome: 'exact',+ idempotent: false,+ usageAccepted: true,+ })++ const replayClient = await dbPool.connect()+ try {+ await begin(replayClient)+ const replay = await finalizePromptBridgeInTransaction(input, replayClient)+ await commit(replayClient)+ expect(replay).toMatchObject({+ status: 'complete',+ outcome: 'exact',+ idempotent: true,+ usageAccepted: true,+ })+ } finally {+ replayClient.release()+ }++ const counts = await dbPool.query(+ `SELECT+ (SELECT count(*) FROM plugin_workload_sdk_spend_outcomes WHERE provider_attempt_id = $1)::int AS spend_count,+ (SELECT count(*) FROM usage_events WHERE request_id = $1)::int AS usage_count,+ (SELECT count(*) FROM agent_run_events WHERE source_event_id = $1)::int AS trace_count,+ (SELECT count(*) FROM governed_event_stream stream+ JOIN agent_run_events event ON event.event_id = stream.event_id+ WHERE event.source_event_id = $1)::int AS stream_count`,+ [input.providerAttemptId]+ )+ expect(counts.rows[0]).toEqual({+ spend_count: 1,+ usage_count: 1,+ trace_count: 1,+ stream_count: 1,+ })+ } finally {+ await client.query('ROLLBACK').catch(() => undefined)+ client.release()+ }+ })++ it('records a proven pre-provider failure as not_executed and keeps it idempotent', async () => {+ const client = await dbPool.connect()+ try {+ await begin(client)+ const input = await seedAttempt(client, { status: 'failed' })+ input.reason = 'integration_credential_resolution_failed'+ const first = await finalizePromptBridgeInTransaction(input, client)+ await commit(client)+ expect(first).toMatchObject({ status: 'failed', outcome: 'not_executed', idempotent: false })++ const state = await dbPool.query(+ `SELECT inv.status AS invocation_status,+ receipt.status AS receipt_status,+ attempt.status AS provider_status,+ outcome.outcome+ FROM plugin_workload_sdk_invocations inv+ JOIN plugin_workload_sdk_invocation_attempts receipt ON receipt.invocation_id = inv.id+ JOIN plugin_workload_sdk_provider_attempts attempt ON attempt.id = $1+ JOIN plugin_workload_sdk_spend_outcomes outcome ON outcome.provider_attempt_id = $1+ WHERE inv.id = $2`,+ [input.providerAttemptId, input.invocationId]+ )+ expect(state.rows[0]).toEqual({+ invocation_status: 'failed',+ receipt_status: 'failed',+ provider_status: 'failed',+ outcome: 'not_executed',+ })+ } finally {+ await client.query('ROLLBACK').catch(() => undefined)+ client.release()+ }+ })++ it('contains stale-sweeper/finalizer interleaving without a raw 500 or duplicate spend row', async () => {+ const seedClient = await dbPool.connect()+ const finalizerClient = await dbPool.connect()+ const sweeperClient = await dbPool.connect()+ try {+ await begin(seedClient)+ const input = await seedAttempt(seedClient, {+ status: 'provider_unavailable',+ leaseExpired: true,+ })+ await commit(seedClient)+ await Promise.all([begin(finalizerClient), begin(sweeperClient)])++ // Both operations contend on the invocation row lock. Do not await both+ // before committing: the loser cannot finish until the winner releases+ // its lock, so Promise.allSettled followed by two commits deadlocks the+ // test itself. Commit/rollback the first completed transaction, then+ // await the contender and release its transaction as well.+ const finalizerPromise = finalizePromptBridgeInTransaction(input, finalizerClient)+ .then(result => ({ kind: 'finalizer' as const, status: 'fulfilled' as const, result }))+ .catch(reason => ({ kind: 'finalizer' as const, status: 'rejected' as const, reason }))+ const sweeperPromise = failStaleInvocationsInTransaction(1, sweeperClient)+ .then(result => ({ kind: 'sweeper' as const, status: 'fulfilled' as const, result }))+ .catch(reason => ({ kind: 'sweeper' as const, status: 'rejected' as const, reason }))++ const first = await Promise.race([finalizerPromise, sweeperPromise])+ const release = async (winner: typeof first, client: PoolClient): Promise<void> => {+ if (winner.status === 'fulfilled') await commit(client)+ else await client.query('ROLLBACK')+ }+ if (first.kind === 'finalizer') await release(first, finalizerClient)+ else await release(first, sweeperClient)++ const second = first.kind === 'finalizer' ? await sweeperPromise : await finalizerPromise+ if (second.kind === 'finalizer') await release(second, finalizerClient)+ else await release(second, sweeperClient)++ const results = [first, second]+ expect(results.some(result => result.status === 'fulfilled')).toBe(true)+ const sweeperResult = results.find(result => result.kind === 'sweeper')!+ expect(sweeperResult.status).toBe('fulfilled')+ if (sweeperResult.status === 'rejected') throw sweeperResult.reason+ for (const result of results) {+ if (result.status === 'rejected' && result.kind === 'finalizer') {+ expect(result.reason).toBeInstanceOf(PromptBridgeFinalizationError)+ expect((result.reason as PromptBridgeFinalizationError).httpStatus).toBe(409)+ }+ }++ const count = await dbPool.query(+ `SELECT count(*)::int AS count+ FROM plugin_workload_sdk_spend_outcomes+ WHERE provider_attempt_id = $1`,+ [input.providerAttemptId]+ )+ expect(count.rows[0]?.count).toBe(1)+ } finally {+ await Promise.all([+ finalizerClient.query('ROLLBACK').catch(() => undefined),+ sweeperClient.query('ROLLBACK').catch(() => undefined),+ ])+ seedClient.release()+ finalizerClient.release()+ sweeperClient.release()+ }+ })+})diff --git a/control-api/test/services.pluginWorkloadSdkFinalization.test.ts b/control-api/test/services.pluginWorkloadSdkFinalization.test.tsindex 68c16a8ea..9efdfda6a 100644--- a/control-api/test/services.pluginWorkloadSdkFinalization.test.ts+++ b/control-api/test/services.pluginWorkloadSdkFinalization.test.ts@@ -168,6 +168,7 @@ describe('Plugin Workload SDK promptBridge finalization', () => {},{ rows: [], rowCount: 1 },{ rows: [], rowCount: 1 },+ { rows: [], rowCount: 1 },{ rows: [], rowCount: 1 })@@ -318,6 +319,7 @@ describe('Plugin Workload SDK promptBridge finalization', () => {},{ rows: [], rowCount: 1 },{ rows: [], rowCount: 1 },+ { rows: [], rowCount: 1 },{ rows: [], rowCount: 1 })diff --git a/control-ui/app/plugin-workload-sdk/Views.tsx b/control-ui/app/plugin-workload-sdk/Views.tsxindex 736bfd790..331836c36 100644--- a/control-ui/app/plugin-workload-sdk/Views.tsx+++ b/control-ui/app/plugin-workload-sdk/Views.tsx@@ -56,6 +56,8 @@ export function GrantsView({deletingId,userMap,legacyInventory,+ legacyInventoryLoading,+ legacyInventoryError,onEdit,onDelete,}: {@@ -65,6 +67,8 @@ export function GrantsView({deletingId: string | nulluserMap: Map<string, string>legacyInventory: PluginWorkloadSdkLegacyGrantInventory | null+ legacyInventoryLoading: boolean+ legacyInventoryError: stringonEdit: (grant: PluginWorkloadSdkGrant) => voidonDelete: (grant: PluginWorkloadSdkGrant) => void}) {@@ -75,6 +79,23 @@ export function GrantsView({</div>)}+ if (legacyInventoryError) {+ return (+ <div className="cu-card__body">+ <div className="cu-banner cu-banner--error">+ SDK migration inventory is unavailable. Grant activation is blocked until it can be+ verified: {legacyInventoryError}+ </div>+ </div>+ )+ }+ if (legacyInventoryLoading) {+ return (+ <div className="cu-card__body">+ <div className="cu-empty">Loading SDK migration inventory…</div>+ </div>+ )+ }if (grants.length === 0 && !loading && !legacyInventory?.legacyPromptBridgeGrants) {return (<div className="cu-card__body">diff --git a/control-ui/app/plugin-workload-sdk/page.tsx b/control-ui/app/plugin-workload-sdk/page.tsxindex 4e9a00736..bacaf88cb 100644--- a/control-ui/app/plugin-workload-sdk/page.tsx+++ b/control-ui/app/plugin-workload-sdk/page.tsx@@ -40,6 +40,7 @@ import {getProviderLabel,normalizeProvider,} from '@lib/llm'+import { shouldApplyRecipePrefill } from '@lib/pluginWorkloadSdkPrefill'import { GrantsView, InvocationsView } from './Views'type SdkView = 'grants' | 'invocations'@@ -129,6 +130,8 @@ export default function PluginWorkloadSdkPage() {const [legacyInventory, setLegacyInventory] = useState<Awaited<ReturnType<typeof getPluginWorkloadSdkLegacyInventory>> | null>(null)+ const [legacyInventoryLoading, setLegacyInventoryLoading] = useState(true)+ const [legacyInventoryError, setLegacyInventoryError] = useState('')const [grantSearch, setGrantSearch] = useState('')const [deletingId, setDeletingId] = useState<string | null>(null)const [editing, setEditing] = useState<PluginWorkloadSdkGrant | 'new' | null>(null)@@ -181,22 +184,46 @@ export default function PluginWorkloadSdkPage() {const loadGrants = useCallback(async () => {setGrantsLoading(true)setGrantsError('')+ setLegacyInventoryLoading(true)+ setLegacyInventoryError('')try {const r = await listPluginWorkloadSdkGrants()const items = (r.items || []) as PluginWorkloadSdkGrant[]setGrants(items)- void getPluginWorkloadSdkLegacyInventory()- .then(setLegacyInventory)- .catch(() => setLegacyInventory(null))+ try {+ const inventory = await getPluginWorkloadSdkLegacyInventory()+ setLegacyInventory(inventory)+ } catch (e) {+ setLegacyInventory(null)+ setLegacyInventoryError(+ isSilentApiError(e)+ ? 'SDK migration inventory could not be verified; refresh after signing in again.'+ : e instanceof Error+ ? e.message+ : 'Failed to load SDK migration inventory'+ )+ } finally {+ setLegacyInventoryLoading(false)+ }const userRefs = items.flatMap(grant => grant.allowedUserRefs)void fetchUsersByRefs(userRefs).then(mergeLoadedUsers).catch(() => undefined)} catch (e) {- if (isSilentApiError(e)) return- setGrantsError(e instanceof Error ? e.message : 'Failed to load grants')+ setGrantsError(+ isSilentApiError(e)+ ? 'SDK grants could not be verified; refresh after signing in again.'+ : e instanceof Error+ ? e.message+ : 'Failed to load grants'+ )+ setLegacyInventoryLoading(false)} finally {setGrantsLoading(false)+ // Inventory is a safety prerequisite independent of the grants request;+ // never leave the page in an apparently loading-but-editable state when+ // the inventory request failed or the grants request short-circuited.+ setLegacyInventoryLoading(false)}}, [mergeLoadedUsers])@@ -284,7 +311,12 @@ export default function PluginWorkloadSdkPage() {onChange={setGrantSearch}placeholder="Search grants"ariaLabel="Search grants"- disabled={grantsInitialLoad}+ disabled={+ grantsInitialLoad ||+ legacyInventoryLoading ||+ Boolean(legacyInventoryError) ||+ Boolean(grantsError)+ }/><Buttontype="button"@@ -312,7 +344,12 @@ export default function PluginWorkloadSdkPage() {variant="primary"size="sm"onClick={() => setEditing('new')}- disabled={grantsInitialLoad}+ disabled={+ grantsInitialLoad ||+ legacyInventoryLoading ||+ Boolean(legacyInventoryError) ||+ Boolean(grantsError)+ }>New grant</Button>@@ -344,6 +381,8 @@ export default function PluginWorkloadSdkPage() {deletingId={deletingId}userMap={userMap}legacyInventory={legacyInventory}+ legacyInventoryLoading={legacyInventoryLoading}+ legacyInventoryError={legacyInventoryError}onEdit={setEditing}onDelete={handleDelete}/>@@ -524,7 +563,14 @@ function GrantFormModal({// A later recipe selection invalidates this response. Once the operator// edits the picker, preserve that explicit decision instead of applying// a stale/default access grant over it.- if (requestId !== recipePrefillRequest.current || allowedUserRefsEdited.current) return+ if (+ !shouldApplyRecipePrefill(+ requestId,+ recipePrefillRequest.current,+ allowedUserRefsEdited.current+ )+ )+ returnsetAllowedUserRefs((res.items ?? []).map(u => u.id))} catch {// Best-effort: leave users empty if the access grant can't be read.diff --git a/control-ui/components/LlmCredentialFields/index.tsx b/control-ui/components/LlmCredentialFields/index.tsxindex 1ca819d92..f328a8a39 100644--- a/control-ui/components/LlmCredentialFields/index.tsx+++ b/control-ui/components/LlmCredentialFields/index.tsx@@ -479,7 +479,7 @@ export function LlmCredentialFields({monospacevalue={slot.nameInput}onChange={event => commitExtraSlot(slot, event.target.value, slot.value)}- placeholder={`${group.provider}-api-key-fb1`}+ placeholder={`${group.slots[0]?.dataKey ?? group.provider}-fb1`}aria-label="Extra credential slot key name"invalid={Boolean(error)}disabled={disabled}diff --git a/control-ui/components/__tests__/LlmCredentialFields.test.tsx b/control-ui/components/__tests__/LlmCredentialFields.test.tsxindex 49e655f1a..c59221a7d 100644--- a/control-ui/components/__tests__/LlmCredentialFields.test.tsx+++ b/control-ui/components/__tests__/LlmCredentialFields.test.tsx@@ -509,7 +509,7 @@ describe('LlmCredentialFields — retiring stored extra slots', () => {})})-describe('providerForDataKey (B1, prefix-aware)', () => {+describe('providerForDataKey (B1, canonical-slot-prefix aware)', () => {it('resolves canonical slot keys to their provider', () => {expect(providerForDataKey('openai-api-key')).toBe('openai')expect(providerForDataKey('claude-api-key')).toBe('claude')@@ -518,11 +518,11 @@ describe('providerForDataKey (B1, prefix-aware)', () => {expect(providerForDataKey('vertex-service-account-json')).toBe('vertex')})- it('resolves extra-slot keys by provider prefix or canonical-slot prefix', () => {+ it('resolves extra-slot keys only by canonical-slot prefix', () => {expect(providerForDataKey('claude-api-key-fb1')).toBe('claude')expect(providerForDataKey('openai-api-key-fb2')).toBe('openai')- expect(providerForDataKey('zai-secondary-key')).toBe('zai')- expect(providerForDataKey('bedrock-api-key-fb1')).toBe('bedrock')+ expect(providerForDataKey('zai-secondary-key')).toBeNull()+ expect(providerForDataKey('bedrock-api-key-fb1')).toBeNull()// Bedrock extras minted from the canonical slot name carry no `bedrock-`// prefix — the canonical-slot-prefix rule must still claim them.expect(providerForDataKey('aws-access-key-id-fb1')).toBe('bedrock')@@ -530,6 +530,7 @@ describe('providerForDataKey (B1, prefix-aware)', () => {it('returns null for keys owned by no provider', () => {expect(providerForDataKey('random-key')).toBeNull()+ expect(providerForDataKey('openai-project')).toBeNull()expect(providerForDataKey('SOME_ENV_VAR')).toBeNull()expect(providerForDataKey('')).toBeNull()})diff --git a/control-ui/components/__tests__/PluginWorkloadSdkPage.test.tsx b/control-ui/components/__tests__/PluginWorkloadSdkPage.test.tsxnew file mode 100644index 000000000..96f7aaa18--- /dev/null+++ b/control-ui/components/__tests__/PluginWorkloadSdkPage.test.tsx@@ -0,0 +1,138 @@+import React from 'react'+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'+import { act, cleanup, fireEvent, render, screen, waitFor, within } from '@testing-library/react'+import {+ getAdminUsers,+ getPluginWorkloadSdkLegacyInventory,+ getRecipes,+ listLlmHostSecrets,+ listPluginWorkloadSdkGrants,+ listWorkflowGrants,+ searchPluginWorkloadSdkInvocations,+} from '@lib/api'+import PluginWorkloadSdkPage from '../../app/plugin-workload-sdk/page'++const mocks = vi.hoisted(() => ({+ confirm: vi.fn(),+ showToast: vi.fn(),+ routerPush: vi.fn(),+}))++vi.mock('next/navigation', () => ({+ useRouter: () => ({ push: mocks.routerPush }),+ usePathname: () => '/plugins/sdk',+}))++vi.mock('@components/DashboardLayout', () => ({+ DashboardLayout: ({ children }: { children: React.ReactNode }) => <>{children}</>,+}))++vi.mock('@components/ConfirmDialog', () => ({+ useConfirmDialog: () => ({ confirm: mocks.confirm, confirmDialog: null }),+}))++vi.mock('@components/Toast', () => ({+ useToast: () => ({ showToast: mocks.showToast, dismissToast: vi.fn() }),+}))++vi.mock('@lib/hooks/useLlmAllowedModels', () => ({+ useLlmAllowedModels: () => ({ models: [], loading: false, error: '', reload: vi.fn() }),+}))++vi.mock('@lib/api', async importOriginal => {+ const actual = await importOriginal<typeof import('@lib/api')>()+ return {+ ...actual,+ getAdminUsers: vi.fn(),+ getPluginWorkloadSdkLegacyInventory: vi.fn(),+ getRecipes: vi.fn(),+ listLlmHostSecrets: vi.fn(),+ listPluginWorkloadSdkGrants: vi.fn(),+ listWorkflowGrants: vi.fn(),+ searchPluginWorkloadSdkInvocations: vi.fn(),+ }+})++function createDeferred<T>() {+ let resolve!: (value: T) => void+ const promise = new Promise<T>(res => {+ resolve = res+ })+ return { promise, resolve }+}++const manualUser = {+ id: 'manual-user',+ email: '[email protected]',+ name: 'Manual user',+ displayName: null,+ picture: null,+ activeTeamCount: 0,+}++const prefilledUser = {+ id: 'prefilled-user',+ email: '[email protected]',+ name: 'Prefilled user',+ displayName: null,+}++beforeEach(() => {+ vi.mocked(getAdminUsers).mockResolvedValue({ items: [manualUser] })+ vi.mocked(getPluginWorkloadSdkLegacyInventory).mockResolvedValue({+ totalPromptBridgeGrants: 0,+ legacyPromptBridgeGrants: 0,+ activationReady: true,+ items: [],+ })+ vi.mocked(getRecipes).mockResolvedValue({+ items: [+ {+ metadata: { namespace: 'sandbox-recipes', name: 'notify-recipe' },+ spec: {+ pluginWorkloadSdk: {+ allowedCallers: ['scanner'],+ clientNotifications: { allowedEventTypes: ['scan.complete'] },+ },+ },+ },+ ],+ } as never)+ vi.mocked(listLlmHostSecrets).mockResolvedValue({ items: [] })+ vi.mocked(listPluginWorkloadSdkGrants).mockResolvedValue({ items: [] })+ vi.mocked(searchPluginWorkloadSdkInvocations).mockResolvedValue({ items: [] })+ mocks.confirm.mockResolvedValue(false)+})++afterEach(() => {+ cleanup()+ vi.clearAllMocks()+})++describe('Plugin Workload SDK operator page', () => {+ it('does not let a late recipe-grant response overwrite an explicit recipient selection', async () => {+ const prefill = createDeferred<{ items: (typeof prefilledUser)[] }>()+ vi.mocked(listWorkflowGrants).mockReturnValue(prefill.promise)++ render(<PluginWorkloadSdkPage />)+ const newGrant = await screen.findByRole('button', { name: 'New grant' })+ await waitFor(() => expect(newGrant).toBeEnabled())+ fireEvent.click(newGrant)++ const recipePicker = await screen.findByLabelText('Recipe (declares the SDK)')+ fireEvent.change(recipePicker, { target: { value: 'sandbox-recipes/notify-recipe' } })++ const usersPicker = await screen.findByLabelText('Allowed users')+ fireEvent.click(usersPicker)+ fireEvent.click(await screen.findByRole('option', { name: 'Manual user' }))++ await act(async () => {+ prefill.resolve({ items: [prefilledUser] })+ await prefill.promise+ })++ const selected = screen.getByLabelText('Selected users')+ expect(within(selected).getByText('Manual user')).toBeInTheDocument()+ expect(within(selected).queryByText('Prefilled user')).not.toBeInTheDocument()+ })+})diff --git a/control-ui/lib/__tests__/llmPolicy.test.ts b/control-ui/lib/__tests__/llmPolicy.test.tsindex b12563b26..976daa47c 100644--- a/control-ui/lib/__tests__/llmPolicy.test.ts+++ b/control-ui/lib/__tests__/llmPolicy.test.ts@@ -49,11 +49,13 @@ describe('getCredentialSlotOptions (spec R4.5.6)', () => {'claude-api-key-fb1','openai-api-key','openai-api-key-fb1',+ 'claude-project',])expect(opts).toEqual(['claude-api-key', 'claude-api-key-fb1', 'claude-api-key-fb2'])// Another provider's keys never leak in.expect(opts).not.toContain('openai-api-key')expect(opts).not.toContain('openai-api-key-fb1')+ expect(opts).not.toContain('claude-project')})})@@ -71,6 +73,7 @@ describe('getPromptBridgeCredentialSlotOptions', () => {getPromptBridgeCredentialSlotOptions('claude', ['claude-api-key','claude-api-key-fb1',+ 'claude-project','vertex-service-account-json-fb1',])).toEqual(['claude-api-key', 'claude-api-key-fb1'])diff --git a/control-ui/lib/__tests__/pluginWorkloadSdkPrefill.test.ts b/control-ui/lib/__tests__/pluginWorkloadSdkPrefill.test.tsnew file mode 100644index 000000000..e881dfabe--- /dev/null+++ b/control-ui/lib/__tests__/pluginWorkloadSdkPrefill.test.ts@@ -0,0 +1,16 @@+import { describe, expect, it } from 'vitest'+import { shouldApplyRecipePrefill } from '../pluginWorkloadSdkPrefill'++describe('shouldApplyRecipePrefill', () => {+ it('applies the response for the current recipe when the operator has not edited recipients', () => {+ expect(shouldApplyRecipePrefill(2, 2, false)).toBe(true)+ })++ it('preserves an explicit recipient edit made while the request was pending', () => {+ expect(shouldApplyRecipePrefill(2, 2, true)).toBe(false)+ })++ it('drops a late response from a previously selected recipe', () => {+ expect(shouldApplyRecipePrefill(1, 2, false)).toBe(false)+ })+})diff --git a/control-ui/lib/llm.ts b/control-ui/lib/llm.tsindex 44d42668b..20cc3d865 100644--- a/control-ui/lib/llm.ts+++ b/control-ui/lib/llm.ts@@ -587,9 +587,10 @@ export function providerSupportsFallbackCredentialSlot(provider: LlmProvider): b// Dropdown options for a fallback entry's `credentialSlot` (spec R4.5.6): the// provider's canonical registry slots first, then any EXTRA keys already present// in the LLM Secret that belong to this provider (e.g. `claude-api-key-fb1`).-// Extra keys are matched by the `<provider>-` prefix or a registry slot prefix-// (the suggested `<slot>-fb1` naming), excluding keys that are canonical slots of-// another provider. The empty option ('') means "use the provider's normal slot".+// Extra keys are matched only by a canonical registry slot prefix (the+// suggested `<slot>-fb1` naming), excluding keys that are canonical slots of+// another provider. A provider-name prefix alone (for example+// `openai-project`) is not a credential slot and must not be offered.// Providers that can't express a single-key slot (Bedrock/Vertex) offer NOTHING —// their fallbacks reuse the primary credentials (mirrors the backend gate).export function getCredentialSlotOptions(@@ -598,7 +599,7 @@ export function getCredentialSlotOptions(): string[] {if (!providerSupportsFallbackCredentialSlot(provider)) return []const registrySlots = PROVIDER_CREDENTIAL_SLOTS[provider].map(slot => slot.dataKey)- const prefixes = [...registrySlots, `${provider}-`]+ const prefixes = registrySlotsconst extras = secretKeys.filter(key => !ALL_REGISTRY_SLOT_KEYS.has(key)).filter(key => prefixes.some(prefix => key.startsWith(prefix)))@@ -622,7 +623,7 @@ export function getPromptBridgeCredentialSlotOptions(if (registrySlots.length === 0) return []if (slots.length !== 1 || slots[0].multiline === true) return registrySlots- const prefixes = [...registrySlots, `${provider}-`]+ const prefixes = registrySlotsconst extras = secretKeys.filter(key => !ALL_REGISTRY_SLOT_KEYS.has(key)).filter(key => prefixes.some(prefix => key.startsWith(prefix)))@@ -648,7 +649,7 @@ export function providerForDataKey(dataKey: string): LlmProvider | null {if (group.slots.some(slot => slot.dataKey === dataKey)) return group.provider}for (const group of LLM_CREDENTIAL_GROUPS) {- const prefixes = [...group.slots.map(slot => slot.dataKey), `${group.provider}-`]+ const prefixes = group.slots.map(slot => slot.dataKey)if (prefixes.some(prefix => dataKey.startsWith(prefix))) return group.provider}return nulldiff --git a/control-ui/lib/pluginWorkloadSdkPrefill.ts b/control-ui/lib/pluginWorkloadSdkPrefill.tsnew file mode 100644index 000000000..e469f5ee0--- /dev/null+++ b/control-ui/lib/pluginWorkloadSdkPrefill.ts@@ -0,0 +1,13 @@+/**+ * Decide whether an asynchronous recipe-prefill response may update the+ * operator's recipient selection. A response is stale when a newer recipe+ * selection has been made, and it is never allowed to overwrite an explicit+ * recipient edit made while the request was pending.+ */+export function shouldApplyRecipePrefill(+ requestId: number,+ currentRequestId: number,+ recipientsEdited: boolean+): boolean {+ return requestId === currentRequestId && !recipientsEdited+}diff --git a/control-ui/package-lock.json b/control-ui/package-lock.jsonindex ddc127427..0b9fd11ea 100644--- a/control-ui/package-lock.json+++ b/control-ui/package-lock.json@@ -1,12 +1,12 @@{"name": "clerum-control-ui",- "version": "0.1.385",+ "version": "0.1.386","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "clerum-control-ui",- "version": "0.1.385",+ "version": "0.1.386","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.jsonindex b8c20a4bb..484e2610e 100644--- a/control-ui/package.json+++ b/control-ui/package.json@@ -1,6 +1,6 @@{"name": "clerum-control-ui",- "version": "0.1.385",+ "version": "0.1.386","private": true,"scripts": {"dev": "NEXT_IGNORE_INCORRECT_LOCKFILE=1 next dev",diff --git a/deploy/base/control-plane/control-api.yaml b/deploy/base/control-plane/control-api.yamlindex 37c3f7613..ce429b99c 100644--- a/deploy/base/control-plane/control-api.yaml+++ b/deploy/base/control-plane/control-api.yaml@@ -13,6 +13,11 @@ metadata:app: control-apispec:replicas: 1+ # Control API writes the SDK policy/attempt ledger. Recreate prevents an old+ # and a new writer from serving concurrently during an image or config+ # rollout; schema-first pre-gate sync also fences replicas before migrations.+ strategy:+ type: Recreateselector:matchLabels:app: control-apidiff --git a/desktop-app/src/main.ts b/desktop-app/src/main.tsindex 9705ec6e5..d190f540e 100644--- a/desktop-app/src/main.ts+++ b/desktop-app/src/main.ts@@ -115,8 +115,6 @@ function wireWindowVisibility(win: BrowserWindow): void {win.on('hide', emit)win.on('minimize', emit)win.on('restore', emit)- win.on('focus', emit)- win.on('blur', emit)}/**diff --git a/desktop-app/test/e2e-playwright/playwright.config.ts b/desktop-app/test/e2e-playwright/playwright.config.tsindex b3e992e57..33fc4c896 100644--- a/desktop-app/test/e2e-playwright/playwright.config.ts+++ b/desktop-app/test/e2e-playwright/playwright.config.ts@@ -63,7 +63,10 @@ function canonicalAdminPassword(contents: string): string | undefined {/** Load a dotenv-style file without a check-then-read race. */function loadEnvFile(envPath: string): void {const contents = readOptionalFile(envPath)- if (contents !== null) loadEnvContents(contents)+ if (contents !== null) {+ process.env.EVENFIRE_ENV_FILE_PRESENT = '1'+ loadEnvContents(contents)+ }}/**@@ -77,6 +80,7 @@ function loadCanonicalRootEnv(): void {const loadCanonicalFile = (envPath: string): void => {const contents = readOptionalFile(envPath)if (contents === null) return+ process.env.EVENFIRE_ENV_FILE_PRESENT = '1'loadEnvContents(contents, new Set(ADMIN_ENV_KEYS))const password = canonicalAdminPassword(contents)if (password) {@@ -134,6 +138,7 @@ loadCanonicalRootEnv()// from the canonical root env. Do not read a second root-level `.env.e2e`: that// file belongs to another lane and previously masked desktop-app/.env.e2e.loadEnvFile(path.resolve(__dirname, '../../.env.e2e'))+if (!process.env.EVENFIRE_ENV_FILE_PRESENT) process.env.EVENFIRE_ENV_FILE_PRESENT = '0'export default defineConfig({testDir: '.',diff --git a/desktop-app/test/e2e-playwright/qa-recorder-helpers.ts b/desktop-app/test/e2e-playwright/qa-recorder-helpers.tsindex e5a2d7b0a..dc8ea515f 100644--- a/desktop-app/test/e2e-playwright/qa-recorder-helpers.ts+++ b/desktop-app/test/e2e-playwright/qa-recorder-helpers.ts@@ -91,6 +91,16 @@ function configuredValue(candidates: Array<string | undefined>): string | undefi}export function desktopCredentials(): { email: string; password: string } {+ const password = configuredValue([+ process.env.E2E_DESKTOP_PASSWORD,+ process.env.E2E_TEST_PASSWORD,+ process.env.ADMIN_PASSWORD,+ ])+ if (!password && process.env.EVENFIRE_ENV_FILE_PRESENT === '1') {+ throw new Error(+ 'Desktop QA password is missing from the canonical repository .env (or the explicitly selected lane env file). Refusing to use changeme123! when an env file exists.'+ )+ }return {// The canonical repository .env is loaded by playwright.config.ts before// this helper is imported. Keep explicit process/root-env values first;@@ -98,12 +108,7 @@ export function desktopCredentials(): { email: string; password: string } {email:configuredValue([process.env.E2E_DEV_LOGIN_EMAIL, process.env.TEST_USER_EMAIL]) ||DEFAULT_DESKTOP_EMAIL,- password:- configuredValue([- process.env.E2E_DESKTOP_PASSWORD,- process.env.E2E_TEST_PASSWORD,- process.env.ADMIN_PASSWORD,- ]) || DEFAULT_DESKTOP_PASSWORD,+ password: password || DEFAULT_DESKTOP_PASSWORD,}}diff --git a/desktop-app/test/qaRecorderHelpers.test.ts b/desktop-app/test/qaRecorderHelpers.test.tsindex 17942bd18..2cdf29494 100644--- a/desktop-app/test/qaRecorderHelpers.test.ts+++ b/desktop-app/test/qaRecorderHelpers.test.ts@@ -1,13 +1,25 @@import { afterEach, describe, expect, it, vi } from 'vitest'-import { assertAllowedTarget } from './e2e-playwright/qa-recorder-helpers'+import { assertAllowedTarget, desktopCredentials } from './e2e-playwright/qa-recorder-helpers'describe('QA recorder target guard', () => {const previousRemoteOptIn = process.env.QA_RECORDER_ALLOW_REMOTE+ const previousEnvFilePresent = process.env.EVENFIRE_ENV_FILE_PRESENT+ const previousDesktopPassword = process.env.E2E_DESKTOP_PASSWORD+ const previousTestPassword = process.env.E2E_TEST_PASSWORD+ const previousAdminPassword = process.env.ADMIN_PASSWORDafterEach(() => {vi.unstubAllGlobals()if (previousRemoteOptIn === undefined) delete process.env.QA_RECORDER_ALLOW_REMOTEelse process.env.QA_RECORDER_ALLOW_REMOTE = previousRemoteOptIn+ if (previousEnvFilePresent === undefined) delete process.env.EVENFIRE_ENV_FILE_PRESENT+ else process.env.EVENFIRE_ENV_FILE_PRESENT = previousEnvFilePresent+ if (previousDesktopPassword === undefined) delete process.env.E2E_DESKTOP_PASSWORD+ else process.env.E2E_DESKTOP_PASSWORD = previousDesktopPassword+ if (previousTestPassword === undefined) delete process.env.E2E_TEST_PASSWORD+ else process.env.E2E_TEST_PASSWORD = previousTestPassword+ if (previousAdminPassword === undefined) delete process.env.ADMIN_PASSWORD+ else process.env.ADMIN_PASSWORD = previousAdminPassword})it('awaits loopback health and fails before the journey when it is unavailable', async () => {@@ -31,4 +43,22 @@ describe('QA recorder target guard', () => {).resolves.toBeUndefined()expect(fetchMock).toHaveBeenCalledWith('http://127.0.0.1:36238/health')})++ it('allows the seeded default only when no env file exists', () => {+ process.env.EVENFIRE_ENV_FILE_PRESENT = '0'+ delete process.env.E2E_DESKTOP_PASSWORD+ delete process.env.E2E_TEST_PASSWORD+ delete process.env.ADMIN_PASSWORD+ expect(desktopCredentials().password).toBe('changeme123!')+ })++ it('fails closed when an env file exists without a password', () => {+ process.env.EVENFIRE_ENV_FILE_PRESENT = '1'+ delete process.env.E2E_DESKTOP_PASSWORD+ delete process.env.E2E_TEST_PASSWORD+ delete process.env.ADMIN_PASSWORD+ expect(() => desktopCredentials()).toThrow(+ /password is missing from the canonical repository \.env/i+ )+ })})diff --git a/docs/deploy/plugin-workload-sdk-upgrade.md b/docs/deploy/plugin-workload-sdk-upgrade.mdindex f360a3e0a..252a611a7 100644--- a/docs/deploy/plugin-workload-sdk-upgrade.md+++ b/docs/deploy/plugin-workload-sdk-upgrade.md@@ -14,18 +14,23 @@ not run beside the new policy/ledger contract.report.3. Apply the compatible CRDs and deploy the new Control API migration image.4. Stop old SDK writers before allowing the new Control API to accept writes.-5. Run the migrations, including the forward-only legacy policy repair. The- repair preserves a complete ordered policy and leaves malformed or legacy- rows in `legacy_unreviewed`.+ `pre-gate-sync` fences both `workflow-recipes` and `control-api` at zero+ replicas, and the Control API Deployment uses `strategy: Recreate`; this is+ an enforced no-overlap invariant, not a runbook-only coordination hint.+5. Run the migrations, including the no-op legacy repair and the forward-only+ policy-review-provenance migration. A complete-looking JSON row is not+ provenance: every active promptBridge row without a durable operator review+ is re-fenced as `legacy_unreviewed` and remains unusable.6. Start the new Control API and verify the read-only`/api/v1/admin/plugin-workload-sdk/legacy-inventory` endpoint. A recipe can- be enabled only when its inventory is `activationReady=true`.+ be enabled only when its inventory is `activationReady=true` and every+ declared policy has review provenance.7. Deploy the matching gateway, Control UI, WRC, and mcp-host images. Thecapabilities probe must report readiness independently for promptBridge andclientNotifications.8. Have an operator review every `legacy_unreviewed` row in Control UI andexplicitly save its ordered targets. The UI never activates a legacy row on- page load.+ page load, and no migration infers provider, model, slot, default, or order.9. Enable the feature for a canary recipe, reconcile it, and verify:- the eager host is Ready with a stable pod UID;- every declared family has an active grant;@@ -50,7 +55,11 @@ Use the branch-owned profile and generated random ports, then run:make minikube-pre-gate-sync GATE=plugin-workload-sdk-review```-The pre-gate fails when a `legacy_unreviewed` promptBridge policy remains. It-does not fail merely because an operator intentionally disabled or revoked a-grant; those states are fenced at authorization time and are reported by the-inventory for operational review.+The pre-gate fences the workflow reconciler and Control API before database+migration, restores their prior replica counts on success or failure, and+restores the Control API only after the schema-first deployment has converged.+It fails when a+`legacy_unreviewed` promptBridge policy remains. It does not fail merely+because an operator intentionally disabled or revoked a grant; those states+are fenced at authorization time and are reported by the inventory for+operational review.diff --git a/mcp-host/package-lock.json b/mcp-host/package-lock.jsonindex 6752d711f..38a2229fa 100644--- a/mcp-host/package-lock.json+++ b/mcp-host/package-lock.json@@ -1,12 +1,12 @@{"name": "clerum-mcp-host",- "version": "0.1.229",+ "version": "0.1.230","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "clerum-mcp-host",- "version": "0.1.229",+ "version": "0.1.230","license": "SEE LICENSE IN LICENSE","dependencies": {"@anthropic-ai/sdk": "^0.32.0",diff --git a/mcp-host/package.json b/mcp-host/package.jsonindex 17e8ccd74..1c0102af4 100644--- a/mcp-host/package.json+++ b/mcp-host/package.json@@ -1,6 +1,6 @@{"name": "clerum-mcp-host",- "version": "0.1.229",+ "version": "0.1.230","description": "MCP Host - reads Host CRD and provides LLM access via OpenAI/Claude","main": "dist/main.js","engines": {diff --git a/mcp-host/src/config.ts b/mcp-host/src/config.tsindex 6dd2fa209..d918e2148 100644--- a/mcp-host/src/config.ts+++ b/mcp-host/src/config.ts@@ -6,6 +6,33 @@ import { NativeToolConfig } from './core/interfaces'import { ALL_PROVIDERS, type LlmProvider, descriptorFor, isLlmProvider } from './llm/registryCore'import { HostSpec, McpServerInfo, MemoryConfig, ModelConfig, PersonalizationConfig } from './types'+/** Route families projected by WRC into a recipe-bound mcp-host. */+export const PLUGIN_WORKLOAD_SDK_CAPABILITIES = ['promptBridge', 'clientNotifications'] as const+export type PluginWorkloadSdkCapability = (typeof PLUGIN_WORKLOAD_SDK_CAPABILITIES)[number]++/**+ * Parse the WRC capability projection without silently accepting typos. An+ * empty/missing value is intentionally an empty set so the SDK activation gate+ * fails closed rather than exposing a broader route surface than the recipe.+ */+export function parsePluginWorkloadSdkCapabilities(+ raw: string | undefined+): PluginWorkloadSdkCapability[] {+ if (!raw?.trim()) return []+ const declared = raw+ .split(',')+ .map(value => value.trim())+ .filter(Boolean)+ const known = new Set<string>(PLUGIN_WORKLOAD_SDK_CAPABILITIES)+ const unknown = declared.filter(value => !known.has(value))+ if (unknown.length > 0) {+ throw new Error(+ `PLUGIN_WORKLOAD_SDK_CAPABILITIES contains unsupported value(s): ${unknown.join(', ')}`+ )+ }+ return PLUGIN_WORKLOAD_SDK_CAPABILITIES.filter(capability => declared.includes(capability))+}+export interface Config {// Dev mode - if true, reads config from env vars instead of K8sdevMode: boolean@@ -219,6 +246,8 @@ export interface Config {// (flag + runtime JWT recipeNamespace + downward-API pod namespace, all// fail-closed — see pluginWorkloadSdk/server/sdkServer.ts).pluginWorkloadSdkEnabled: boolean+ /** Exact capability families declared by WRC for this recipe-bound host. */+ pluginWorkloadSdkCapabilities: PluginWorkloadSdkCapability[]pluginWorkloadSdkRuntimeMode: 'workflow' | 'sdk-only'pluginWorkloadSdkPort: number/** Pod namespace via Kubernetes downward API (defense-in-depth). */@@ -791,6 +820,9 @@ export const config: Config = {// Plugin Workload SDK (plan §3.5 config table)pluginWorkloadSdkEnabled: getEnvBool('PLUGIN_WORKLOAD_SDK_ENABLED', false),+ pluginWorkloadSdkCapabilities: parsePluginWorkloadSdkCapabilities(+ getEnv('PLUGIN_WORKLOAD_SDK_CAPABILITIES', '')+ ),// Workflow is the backwards-compatible SDK mode for workflow/standalone// processes; WRC explicitly sets sdk-only on the stepless adapter.pluginWorkloadSdkRuntimeMode: configuredRuntimeKind === 'sdk-only' ? 'sdk-only' : 'workflow',diff --git a/mcp-host/src/llm/__tests__/openai.singleTurn.test.ts b/mcp-host/src/llm/__tests__/openai.singleTurn.test.tsindex 37f1d0249..7827e34ed 100644--- a/mcp-host/src/llm/__tests__/openai.singleTurn.test.ts+++ b/mcp-host/src/llm/__tests__/openai.singleTurn.test.ts@@ -305,6 +305,22 @@ describe('OpenAI token limit parameter compatibility', () => {expect(callArgs.max_tokens).toBe(8)expect(callArgs).not.toHaveProperty('max_completion_tokens')})++ it('uses max_completion_tokens for GPT-5 tool calls', async () => {+ const mockClient = createMockOpenAIClient()+ mockClient.chat.completions.create.mockResolvedValue(openAITextResponse('OK'))+ const provider = new OpenAIProvider(mockClient as any, 'gpt-5.4-mini')++ await provider.completeSingleTurnWithTools(+ [{ role: 'user', content: 'Use the tool' }],+ [{ name: 'search', description: 'Search docs', parameters: {} }],+ { max_tokens: 8 }+ )++ const callArgs = mockClient.chat.completions.create.mock.calls[0][0]+ expect(callArgs.max_completion_tokens).toBe(8)+ expect(callArgs).not.toHaveProperty('max_tokens')+ })})describe('OpenAI token usage mapping', () => {diff --git a/mcp-host/src/pluginWorkloadSdk/bootstrapServer.test.ts b/mcp-host/src/pluginWorkloadSdk/bootstrapServer.test.tsindex 867adc2c1..1cafc5611 100644--- a/mcp-host/src/pluginWorkloadSdk/bootstrapServer.test.ts+++ b/mcp-host/src/pluginWorkloadSdk/bootstrapServer.test.ts@@ -68,8 +68,16 @@ describe('PluginWorkloadSdkBootstrapServer', () => {it('exposes readiness and projects bootstrap input to public identity only', async () => {const { baseUrl, configure } = await start()const health = await fetch(`${baseUrl}/v1/runtime/health`)- expect(health.status).toBe(200)- await expect(health.json()).resolves.toMatchObject({ mode: 'sdk-only', ready: true })+ expect(health.status).toBe(503)+ await expect(health.json()).resolves.toMatchObject({ mode: 'sdk-only', ready: false })++ const bootstrapReady = await fetch(`${baseUrl}/v1/runtime/bootstrap-ready`)+ expect(bootstrapReady.status).toBe(200)+ await expect(bootstrapReady.json()).resolves.toMatchObject({+ status: 'bootstrap_ready',+ mode: 'sdk-only',+ identityReady: false,+ })const response = await fetch(`${baseUrl}/api/v1/workflow/plugin-workload-sdk/bootstrap`, {method: 'POST',@@ -82,6 +90,17 @@ describe('PluginWorkloadSdkBootstrapServer', () => {})expect(response.status).toBe(200)expect(configure).toHaveBeenCalledWith({ provider: 'openai', model: 'gpt-5.4-mini' })+ const ready = await fetch(`${baseUrl}/v1/runtime/health`)+ expect(ready.status).toBe(200)+ await expect(ready.json()).resolves.toMatchObject({ mode: 'sdk-only', ready: true })++ const bootstrapReadyAfterConfigure = await fetch(`${baseUrl}/v1/runtime/bootstrap-ready`)+ expect(bootstrapReadyAfterConfigure.status).toBe(200)+ await expect(bootstrapReadyAfterConfigure.json()).resolves.toMatchObject({+ status: 'bootstrap_ready',+ mode: 'sdk-only',+ identityReady: true,+ })})it('requires a configure-scoped WRC token bound to the Pod recipe', async () => {diff --git a/mcp-host/src/pluginWorkloadSdk/bootstrapServer.ts b/mcp-host/src/pluginWorkloadSdk/bootstrapServer.tsindex 6b82815be..5eb6ad5e1 100644--- a/mcp-host/src/pluginWorkloadSdk/bootstrapServer.ts+++ b/mcp-host/src/pluginWorkloadSdk/bootstrapServer.ts@@ -29,6 +29,7 @@ export interface PluginWorkloadSdkBootstrapServerOptions {export class PluginWorkloadSdkBootstrapServer {private readonly app = express()private readonly rateLimitBuckets = new Map<string, { windowStart: number; count: number }>()+ private identityReady = falseprivate server: http.Server | null = nullconstructor(private readonly opts: PluginWorkloadSdkBootstrapServerOptions) {@@ -48,7 +49,25 @@ export class PluginWorkloadSdkBootstrapServer {)this.app.use(express.json({ limit: '16kb' }))this.app.get('/v1/runtime/health', (_req, res) => {- res.status(200).json({ status: 'healthy', mode: 'sdk-only', ready: true })+ const ready = this.identityReady+ res.status(ready ? 200 : 503).json({+ status: ready ? 'healthy' : 'not_ready',+ mode: 'sdk-only',+ ready,+ })+ })+ // Kubernetes must be able to mark the Pod reachable before WRC can POST+ // the identity bootstrap. This probe proves that the bootstrap listener is+ // bound, not that the provider/policy identity has already been installed.+ // WRC uses the Ready transition to discover the Service endpoint and then+ // performs the authenticated bootstrap; `/health` remains the operational+ // post-bootstrap readiness signal for callers and diagnostics.+ this.app.get('/v1/runtime/bootstrap-ready', (_req, res) => {+ res.status(200).json({+ status: 'bootstrap_ready',+ mode: 'sdk-only',+ identityReady: this.identityReady,+ })})this.app.get('/v1/runtime/live', (_req, res) => {res.status(200).json({ status: 'alive', mode: 'sdk-only' })@@ -69,8 +88,10 @@ export class PluginWorkloadSdkBootstrapServer {}try {const result = await this.opts.configure(request)+ this.identityReady = result.configured === true && result.ready !== falseres.status(result.configured ? 200 : result.ready === false ? 503 : 400).json(result)} catch {+ this.identityReady = falseres.status(503).json({configured: false,ready: false,diff --git a/mcp-host/src/pluginWorkloadSdk/promptBridge/handler.test.ts b/mcp-host/src/pluginWorkloadSdk/promptBridge/handler.test.tsindex e9ebb3fe0..d723542b7 100644--- a/mcp-host/src/pluginWorkloadSdk/promptBridge/handler.test.ts+++ b/mcp-host/src/pluginWorkloadSdk/promptBridge/handler.test.ts@@ -228,7 +228,7 @@ describe('PromptBridgeHandler', () => {content: 'summary text',usage: { inputTokens: 10, outputTokens: 5 },finishReason: 'complete',- providerAttemptAcknowledged: false,+ providerAttemptAcknowledgement: 'failed',})const onUsage = vi.fn()const { handler } = makeDeps({ complete, report, onUsage })diff --git a/mcp-host/src/pluginWorkloadSdk/promptBridge/handler.ts b/mcp-host/src/pluginWorkloadSdk/promptBridge/handler.tsindex cd8366893..358d3669f 100644--- a/mcp-host/src/pluginWorkloadSdk/promptBridge/handler.ts+++ b/mcp-host/src/pluginWorkloadSdk/promptBridge/handler.ts@@ -350,13 +350,17 @@ export class PromptBridgeHandler {status: input.status,}),},- deferSuccessfulAttemptAcknowledgement: Boolean(this.deps.finalizePromptBridge),+ acknowledgementMode: this.deps.finalizePromptBridge+ ? 'atomic_terminal_finalization'+ : 'per_attempt',maxTokens: clampMaxTokens(request.maxTokens, authorized.maxOutputTokens),temperature: request.temperature ?? authorized.modelPolicy?.temperature,timeoutMs: this.deps.promptTimeoutMs,})- const providerAttemptAcknowledged = completion.providerAttemptAcknowledged !== false+ const providerAttemptAcknowledgement =+ completion.providerAttemptAcknowledgement ?? 'confirmed'+ const providerAttemptAcknowledged = providerAttemptAcknowledgement === 'confirmed'const providerAttemptId = completion.providerAttemptIdconst providerAttemptIndex = completion.providerAttemptIndexif (@@ -387,9 +391,10 @@ export class PromptBridgeHandler {providerAttemptId,providerAttemptIndex,status: 'complete',- reason: providerAttemptAcknowledged- ? 'provider_completed'- : 'provider_completion_acknowledgement_recovered',+ reason:+ providerAttemptAcknowledgement === 'failed'+ ? 'provider_completion_acknowledgement_failed'+ : 'provider_completed',target: completion.servedTarget,usage: {llmSecretName: completion.llmSecretName,@@ -403,6 +408,22 @@ export class PromptBridgeHandler {} catch {// Returning provider content before durable finalization would hide// a possible spend. Surface an explicit unknown outcome instead.+ try {+ await this.deps.controlApiClient.reportProviderAttemptStatus({+ invocationId: authorized.invocationId,+ recipeNamespace: this.deps.recipeNamespace,+ recipeName: this.deps.recipeName,+ attemptGeneration: authorized.attemptGeneration,+ providerAttemptId,+ providerAttemptIndex,+ status: 'provider_unavailable',+ })+ } catch {+ // The finalizer remains the source of truth. This best-effort+ // physical close only prevents a failed finalizer from leaving a+ // receipt open until the lease sweeper.+ console.warn('[PluginWorkloadSdk] provider attempt recovery failed')+ }throw new PluginWorkloadError('provider_unavailable','provider result could not be durably finalized; retry with a new idempotency key after investigation',diff --git a/mcp-host/src/pluginWorkloadSdk/promptBridge/llmBridge.failover.test.ts b/mcp-host/src/pluginWorkloadSdk/promptBridge/llmBridge.failover.test.tsindex d3efdfe27..c6dad89c1 100644--- a/mcp-host/src/pluginWorkloadSdk/promptBridge/llmBridge.failover.test.ts+++ b/mcp-host/src/pluginWorkloadSdk/promptBridge/llmBridge.failover.test.ts@@ -206,7 +206,7 @@ describe('LlmBridge authorized multi-provider fallback', () => {await expect(bridge.complete({...request,- deferSuccessfulAttemptAcknowledgement: true,+ acknowledgementMode: 'atomic_terminal_finalization',credentialTicketIssuer,providerAttemptReporter,})@@ -218,6 +218,43 @@ describe('LlmBridge authorized multi-provider fallback', () => {expect(providerAttemptReporter.report).toHaveBeenCalledTimes(2)})+ it('defers only the successful terminal ACK in atomic finalization mode', async () => {+ const provider = new FakeProvider(() => Promise.resolve(OK))+ const { bridge } = makeBridge({ [primary.model]: provider })+ const providerAttemptReporter = { report: vi.fn().mockResolvedValue(undefined) }+ const credentialTicketIssuer = {+ issue: vi.fn(async () => ({+ credentialTicket: 'fresh-primary',+ providerAttemptId: 'attempt-primary',+ providerAttemptIndex: 1,+ })),+ }++ const atomic = await bridge.complete({+ ...request,+ targets: [{ target: primary }],+ acknowledgementMode: 'atomic_terminal_finalization',+ credentialTicketIssuer,+ providerAttemptReporter,+ })+ expect(atomic.providerAttemptAcknowledgement).toBe('owned_by_finalizer')+ expect(providerAttemptReporter.report).not.toHaveBeenCalled()++ const perAttempt = await bridge.complete({+ ...request,+ targets: [{ target: primary }],+ acknowledgementMode: 'per_attempt',+ credentialTicketIssuer,+ providerAttemptReporter,+ })+ expect(perAttempt.providerAttemptAcknowledgement).toBe('confirmed')+ expect(providerAttemptReporter.report).toHaveBeenCalledWith({+ providerAttemptId: 'attempt-primary',+ providerAttemptIndex: 1,+ status: 'complete',+ })+ })+it('reissues a fresh target-bound ticket immediately before each credential resolution', async () => {const first = new FakeProvider(() => Promise.reject(new Error('provider response')))const second = new FakeProvider(() => Promise.resolve(OK))@@ -455,7 +492,7 @@ describe('LlmBridge authorized multi-provider fallback', () => {servedTarget: primary,content: OK.content,usage: { inputTokens: 3, outputTokens: 4 },- providerAttemptAcknowledged: false,+ providerAttemptAcknowledgement: 'failed',})expect(provider.completeSingleTurn).toHaveBeenCalledOnce()expect(providerAttemptReporter.report).toHaveBeenCalledWith({diff --git a/mcp-host/src/pluginWorkloadSdk/promptBridge/llmBridge.ts b/mcp-host/src/pluginWorkloadSdk/promptBridge/llmBridge.tsindex 7a82a6ebd..2438f34bb 100644--- a/mcp-host/src/pluginWorkloadSdk/promptBridge/llmBridge.ts+++ b/mcp-host/src/pluginWorkloadSdk/promptBridge/llmBridge.ts@@ -69,7 +69,11 @@ export interface LlmBridgeRequest {credentialTicketIssuer: PromptBridgeCredentialTicketIssuerproviderAttemptReporter?: PromptBridgeProviderAttemptReporter/** SDK-only lane finalizes a successful physical attempt atomically in the handler. */- deferSuccessfulAttemptAcknowledgement?: boolean+ /**+ * Physical-attempt acknowledgement ownership. SDK-only finalization owns+ * the served terminal receipt; workflow mode reports each attempt here.+ */+ acknowledgementMode?: 'per_attempt' | 'atomic_terminal_finalization'messages: Array<{ role: 'system' | 'user' | 'assistant'; content: string }>maxTokens?: numbertemperature?: number@@ -85,8 +89,12 @@ export interface LlmBridgeResult {llmSecretName: stringproviderAttemptId?: stringproviderAttemptIndex?: number- /** False means the provider result is real but its terminal receipt is not. */- providerAttemptAcknowledged?: boolean+ /**+ * Explicit physical-receipt ownership. `owned_by_finalizer` is a successful+ * SDK-only path, not a missing acknowledgement; `failed` means the receipt+ * transport failed after provider execution and must be fenced unknown.+ */+ providerAttemptAcknowledgement?: 'confirmed' | 'owned_by_finalizer' | 'failed'content: stringusage: { inputTokens: number; outputTokens: number }finishReason: 'complete' | 'length' | 'content_filter'@@ -366,18 +374,20 @@ export class LlmBridge {// rejects the Secret read; close it before surfacing the terminal// credential/configuration failure to the caller.if (ticket.providerAttemptId && ticket.providerAttemptIndex !== undefined) {- // `deferSuccessfulAttemptAcknowledgement` applies only to the- // successful SDK-only terminal ACK. A ticket has already reserved a- // physical attempt, so every pre-provider credential/configuration- // failure must close that attempt as `failed`, regardless of the- // logical finalizer mode. Otherwise the logical invocation closes- // while the physical ledger remains reserved/in_progress forever.+ // A ticket has already reserved a physical attempt, so every+ // pre-provider credential/configuration failure must close that+ // attempt as `failed`, regardless of the logical finalizer mode.+ // Otherwise the logical invocation closes while the physical ledger+ // remains reserved/in_progress forever.await reportProviderAttemptBestEffort(request.providerAttemptReporter, {providerAttemptId: ticket.providerAttemptId,providerAttemptIndex: ticket.providerAttemptIndex,status: 'failed',})}+ // Preserve the reserved receipt in every mode. Atomic SDK-only+ // finalization owns the logical/spend outcome, so dropping this+ // context would close only the physical row and lose `not_executed`.if (ticket.providerAttemptId && ticket.providerAttemptIndex !== undefined) {throw withProviderAttemptContext(error, {providerAttemptId: ticket.providerAttemptId,@@ -396,9 +406,14 @@ export class LlmBridge {{ ...request, timeoutMs: remainingTimeoutMs(deadlineAt) },breaker)- let providerAttemptAcknowledged = true- if (ticket.providerAttemptId && ticket.providerAttemptIndex !== undefined) {- providerAttemptAcknowledged = await reportProviderAttemptBestEffort(+ let providerAttemptAcknowledgement: 'confirmed' | 'owned_by_finalizer' | 'failed' =+ 'confirmed'+ if (+ request.acknowledgementMode !== 'atomic_terminal_finalization' &&+ ticket.providerAttemptId &&+ ticket.providerAttemptIndex !== undefined+ ) {+ const acknowledged = await reportProviderAttemptBestEffort(request.providerAttemptReporter,{providerAttemptId: ticket.providerAttemptId,@@ -406,6 +421,12 @@ export class LlmBridge {status: 'complete',})+ providerAttemptAcknowledgement = acknowledged ? 'confirmed' : 'failed'+ } else if (request.acknowledgementMode === 'atomic_terminal_finalization') {+ // The handler's atomic finalizer is the sole owner of the served+ // terminal receipt. Reporting `complete` here would double-close+ // the same physical attempt and can double-apply usage.+ providerAttemptAcknowledgement = 'owned_by_finalizer'}return {...completion,@@ -417,15 +438,16 @@ export class LlmBridge {...(ticket.providerAttemptIndex !== undefined? { providerAttemptIndex: ticket.providerAttemptIndex }: {}),- providerAttemptAcknowledged,+ providerAttemptAcknowledgement,}} catch (error) {const providerMayHaveExecuted =(error instanceof PluginWorkloadError && error.providerMayHaveExecuted) ||(error instanceof ClassifiedProviderError && error.providerMayHaveExecuted)- let providerAttemptAcknowledged = true+ let providerAttemptAcknowledgement: 'confirmed' | 'owned_by_finalizer' | 'failed' =+ 'confirmed'if (ticket.providerAttemptId && ticket.providerAttemptIndex !== undefined) {- providerAttemptAcknowledged = await reportProviderAttemptBestEffort(+ const acknowledged = await reportProviderAttemptBestEffort(request.providerAttemptReporter,{providerAttemptId: ticket.providerAttemptId,@@ -436,6 +458,7 @@ export class LlmBridge {: 'failed',})+ providerAttemptAcknowledgement = acknowledged ? 'confirmed' : 'failed'}const providerAttemptContext =ticket.providerAttemptId && ticket.providerAttemptIndex !== undefined@@ -448,7 +471,7 @@ export class LlmBridge {llmSecretName: credential.llmSecretName,}: undefined- if (!providerAttemptAcknowledged) {+ if (providerAttemptAcknowledgement === 'failed') {// Once execution may have started, a failed receipt is not a safe// failover signal. Closing the logical invocation as terminal// provider_unavailable prevents the same idempotency key fromdiff --git a/mcp-host/src/pluginWorkloadSdk/promptBridge/runtime-http.test.ts b/mcp-host/src/pluginWorkloadSdk/promptBridge/runtime-http.test.tsindex 425d04497..0a0592cc2 100644--- a/mcp-host/src/pluginWorkloadSdk/promptBridge/runtime-http.test.ts+++ b/mcp-host/src/pluginWorkloadSdk/promptBridge/runtime-http.test.ts@@ -195,9 +195,16 @@ function makeHarness(scenario: Scenario): RuntimeHarness {const server = new PluginWorkloadSdkServer({port: 0,recipeName: 'runtime-http',+ capabilities: ['promptBridge'],workloadTokens: new Map([[TOKEN, CALLER_REF]]),promptBridgeHandler,clientNotificationsHandler: clientNotificationsHandler as never,+ readiness: () => ({ ready: true }),+ getRuntimeBinding: () => ({+ hostRef: 'sandbox-recipes/runtime-http',+ recipeNamespace: 'sandbox-recipes',+ recipeName: 'runtime-http',+ }),})return {diff --git a/mcp-host/src/pluginWorkloadSdk/server/index.ts b/mcp-host/src/pluginWorkloadSdk/server/index.tsindex b473f29f9..6794aecde 100644--- a/mcp-host/src/pluginWorkloadSdk/server/index.ts+++ b/mcp-host/src/pluginWorkloadSdk/server/index.ts@@ -10,7 +10,11 @@ import { PluginWorkloadSdkControlApiClient } from '../promptBridge/controlApiCliimport { PluginWorkloadSdkCredentialBrokerClient } from '../promptBridge/credentialBrokerClient'import { PromptBridgeHandler } from '../promptBridge/handler'import { LlmBridge } from '../promptBridge/llmBridge'-import { PluginWorkloadSdkServer, shouldStartPluginWorkloadSdk } from './sdkServer'+import {+ PluginWorkloadSdkServer,+ checkLiveRuntimeBinding,+ shouldStartPluginWorkloadSdk,+} from './sdkServer'import {loadWorkloadTokenRegistryFromDir,loadWorkloadTokenRegistryFromPair,@@ -243,6 +247,7 @@ export function maybeCreatePluginWorkloadSdkServer(): PluginWorkloadSdkServer | null {const gate = shouldStartPluginWorkloadSdk({pluginWorkloadSdkEnabled: config.pluginWorkloadSdkEnabled,+ pluginWorkloadSdkCapabilities: config.pluginWorkloadSdkCapabilities,mcpHostRuntimeAccessToken: runtimeAuth?.accessToken ?? config.mcpHostRuntimeAccessToken ?? '',podNamespace: config.podNamespace ?? '',pluginWorkloadSdkCredentialBrokerUrl: config.pluginWorkloadSdkCredentialBrokerUrl,@@ -311,85 +316,117 @@ export function maybeCreatePluginWorkloadSdkServer(})recordCircuitBreakerState('control-api', false)- const credentialBroker = new PluginWorkloadSdkCredentialBrokerClient({- baseUrl: config.pluginWorkloadSdkCredentialBrokerUrl,- recipeNamespace: binding.recipeNamespace,- recipeName: binding.recipeName,- getAccessToken: () => runtimeAuth?.accessToken ?? config.mcpHostRuntimeAccessToken ?? '',- })- const llmBridge = new LlmBridge(credentialBroker, {- maxResponseBytes: config.pluginWorkloadSdkMaxLlmResponseBytes,- createBreaker: target =>- new CircuitBreaker({- onStateChange: open => recordCircuitBreakerState(`llm-provider:${target.targetRef}`, open),- }),- })+ const capabilities = new Set(config.pluginWorkloadSdkCapabilities)+ let promptBridgeHandler: PromptBridgeHandler | undefined+ if (capabilities.has('promptBridge')) {+ // The provider broker is a promptBridge dependency only. A notification-+ // only recipe must be able to start without CLERUM_WRC_URL or any LLM+ // client, while promptBridge remains fail-closed when the broker is absent.+ if (!config.pluginWorkloadSdkCredentialBrokerUrl.trim()) {+ console.error(+ '[PluginWorkloadSdk] SDK server NOT started: CLERUM_WRC_URL is required for promptBridge'+ )+ return null+ }+ const credentialBroker = new PluginWorkloadSdkCredentialBrokerClient({+ baseUrl: config.pluginWorkloadSdkCredentialBrokerUrl,+ recipeNamespace: binding.recipeNamespace,+ recipeName: binding.recipeName,+ getAccessToken: () => runtimeAuth?.accessToken ?? config.mcpHostRuntimeAccessToken ?? '',+ })+ const llmBridge = new LlmBridge(credentialBroker, {+ maxResponseBytes: config.pluginWorkloadSdkMaxLlmResponseBytes,+ createBreaker: target =>+ new CircuitBreaker({+ onStateChange: open =>+ recordCircuitBreakerState(`llm-provider:${target.targetRef}`, open),+ }),+ })- const usageReporter = opts.usageReporter ?? null- const promptBridgeHandler = new PromptBridgeHandler({- controlApiClient,- llmBridge,- recipeNamespace: binding.recipeNamespace,- recipeName: binding.recipeName,- promptTimeoutMs: config.pluginWorkloadSdkPromptTimeoutSeconds * 1000,- getBootstrapTarget: opts.getLlmContext- ? () => {- const context = opts.getLlmContext?.()- if (!context) return null- return { provider: context.provider, model: context.defaultModel }- }- : undefined,- finalizePromptBridge:- config.pluginWorkloadSdkRuntimeMode === 'sdk-only'- ? input =>- controlApiClient.finalizePromptBridge({- recipeNamespace: binding.recipeNamespace,- recipeName: binding.recipeName,- ...input,- })+ const usageReporter = opts.usageReporter ?? null+ promptBridgeHandler = new PromptBridgeHandler({+ controlApiClient,+ llmBridge,+ recipeNamespace: binding.recipeNamespace,+ recipeName: binding.recipeName,+ promptTimeoutMs: config.pluginWorkloadSdkPromptTimeoutSeconds * 1000,+ getBootstrapTarget: opts.getLlmContext+ ? () => {+ const context = opts.getLlmContext?.()+ if (!context) return null+ return { provider: context.provider, model: context.defaultModel }+ }: undefined,- onUsage: usage => {- if (!usageReporter) return- const event = buildPromptBridgeUsageEvent({- binding: {- hostRef: runtimeAuth?.hostRef ?? binding.hostRef,- recipeNamespace: binding.recipeNamespace,- recipeName: binding.recipeName,- },- provider: usage.provider,- model: usage.model,- inputTokens: usage.inputTokens,- outputTokens: usage.outputTokens,- callerRef: usage.callerRef,- promptBridgeMetadata: {- targetRef: usage.servedTarget.targetRef,- credentialSlot: usage.servedTarget.credentialSlot,- fallbackUsed: usage.fallbackUsed,- attemptCount: usage.attemptCount,- attemptGeneration: usage.attemptGeneration,- providerAttemptId: usage.providerAttemptId,- providerAttemptIndex: usage.providerAttemptIndex,- },- runtimeMode: config.pluginWorkloadSdkRuntimeMode === 'sdk-only' ? 'sdk-only' : 'workflow',- invocationId: usage.invocationId,- metadata: { ...usage.metadata, llmSecretName: usage.llmSecretName },+ finalizePromptBridge:+ config.pluginWorkloadSdkRuntimeMode === 'sdk-only'+ ? input =>+ controlApiClient.finalizePromptBridge({+ recipeNamespace: binding.recipeNamespace,+ recipeName: binding.recipeName,+ ...input,+ })+ : undefined,+ onUsage: usage => {+ if (!usageReporter) return+ const event = buildPromptBridgeUsageEvent({+ binding: {+ hostRef: runtimeAuth?.hostRef ?? binding.hostRef,+ recipeNamespace: binding.recipeNamespace,+ recipeName: binding.recipeName,+ },+ provider: usage.provider,+ model: usage.model,+ inputTokens: usage.inputTokens,+ outputTokens: usage.outputTokens,+ callerRef: usage.callerRef,+ promptBridgeMetadata: {+ targetRef: usage.servedTarget.targetRef,+ credentialSlot: usage.servedTarget.credentialSlot,+ fallbackUsed: usage.fallbackUsed,+ attemptCount: usage.attemptCount,+ attemptGeneration: usage.attemptGeneration,+ providerAttemptId: usage.providerAttemptId,+ providerAttemptIndex: usage.providerAttemptIndex,+ },+ runtimeMode: config.pluginWorkloadSdkRuntimeMode === 'sdk-only' ? 'sdk-only' : 'workflow',+ invocationId: usage.invocationId,+ metadata: { ...usage.metadata, llmSecretName: usage.llmSecretName },+ })+ if (event) usageReporter.enqueue(event)+ },+ })+ }++ const clientNotificationsHandler = capabilities.has('clientNotifications')+ ? new ClientNotificationsHandler({+ controlApiClient,+ recipeNamespace: binding.recipeNamespace,+ recipeName: binding.recipeName,})- if (event) usageReporter.enqueue(event)- },- })+ : undefined- const clientNotificationsHandler = new ClientNotificationsHandler({- controlApiClient,- recipeNamespace: binding.recipeNamespace,- recipeName: binding.recipeName,- })+ const getRuntimeBinding = () =>+ getJwtRuntimeBinding(runtimeAuth?.accessToken ?? config.mcpHostRuntimeAccessToken ?? '')+ const readiness = () => {+ const liveBinding = getRuntimeBinding()+ const reason = liveBinding+ ? checkLiveRuntimeBinding(liveBinding, binding.recipeName)+ : 'runtime token has no decodable recipe binding'+ if (reason) return { ready: false, reason }+ if (capabilities.has('promptBridge') && !opts.getLlmContext?.()) {+ return { ready: false, reason: 'promptBridge provider identity has not been brokered' }+ }+ return { ready: true }+ }return new PluginWorkloadSdkServer({port: config.pluginWorkloadSdkPort,recipeName: binding.recipeName,+ capabilities: config.pluginWorkloadSdkCapabilities,workloadTokens,promptBridgeHandler,clientNotificationsHandler,+ readiness,maxConnections: config.pluginWorkloadSdkMaxConnections,maxRequestsPerMinutePerWorkload: config.pluginWorkloadSdkMaxRpmPerWorkload,maxConcurrentPerWorkload: config.pluginWorkloadSdkMaxConnectionsPerWorkload,@@ -397,7 +434,6 @@ export function maybeCreatePluginWorkloadSdkServer(// Re-validate the rotating runtime token on every request: the boot-time// gate is one-shot, but refreshed tokens could in theory carry a drifted// binding. Fail closed instead of trusting the boot decision forever.- getRuntimeBinding: () =>- getJwtRuntimeBinding(runtimeAuth?.accessToken ?? config.mcpHostRuntimeAccessToken ?? ''),+ getRuntimeBinding,})}diff --git a/mcp-host/src/pluginWorkloadSdk/server/routes.test.ts b/mcp-host/src/pluginWorkloadSdk/server/routes.test.tsindex c5f695530..c6c945ea9 100644--- a/mcp-host/src/pluginWorkloadSdk/server/routes.test.ts+++ b/mcp-host/src/pluginWorkloadSdk/server/routes.test.ts@@ -27,12 +27,14 @@ describe('SDK routes — workload auth + rate limiting', () => {const app = express()app.use(express.json({ limit: '1mb' }))registerSdkRoutes(app, {+ capabilities: ['promptBridge', 'clientNotifications'],workloadTokens,promptBridgeHandler: { handle: promptHandle } as unknown as PromptBridgeHandler,clientNotificationsHandler: {handle: notifyHandle,listRecipients,} as unknown as ClientNotificationsHandler,+ readiness: () => ({ ready: true }),maxRequestsPerMinutePerWorkload: 3,maxConcurrentPerWorkload: 10,})@@ -61,6 +63,15 @@ describe('SDK routes — workload auth + rate limiting', () => {expect(res.status).toBe(200)})+ it('GET /health is readiness and /live is liveness', async () => {+ const health = await fetch(`${baseUrl}/health`)+ const live = await fetch(`${baseUrl}/live`)+ expect(health.status).toBe(200)+ expect(live.status).toBe(200)+ expect(await health.json()).toMatchObject({ status: 'ready' })+ expect(await live.json()).toEqual({ status: 'live' })+ })+it('rejects requests without a workload token', async () => {const res = await post('/sdk/v1/prompt-bridge', { 'x-clerum-caller-ref': 'api' })expect(res.status).toBe(401)@@ -154,4 +165,40 @@ describe('SDK routes — workload auth + rate limiting', () => {expect(limited.status).toBe(429)expect(((await limited.json()) as { error: string }).error).toBe('quota_exceeded')})++ it('does not expose an undeclared route family', async () => {+ const app = express()+ app.use(express.json({ limit: '1mb' }))+ registerSdkRoutes(app, {+ capabilities: ['clientNotifications'],+ workloadTokens,+ clientNotificationsHandler: {+ handle: notifyHandle,+ listRecipients,+ } as unknown as ClientNotificationsHandler,+ readiness: () => ({ ready: true }),+ maxRequestsPerMinutePerWorkload: 3,+ maxConcurrentPerWorkload: 10,+ })+ const scopedServer = await new Promise<http.Server>(resolve => {+ const listener = app.listen(0, '127.0.0.1', () => resolve(listener))+ })+ try {+ const response = await fetch(+ `http://127.0.0.1:${(scopedServer.address() as AddressInfo).port}/sdk/v1/prompt-bridge`,+ {+ method: 'POST',+ headers: {+ Authorization: `Bearer ${API_TOKEN}`,+ 'Content-Type': 'application/json',+ },+ body: '{}',+ }+ )+ expect(response.status).toBe(404)+ expect(promptHandle).not.toHaveBeenCalled()+ } finally {+ await new Promise<void>(resolve => scopedServer.close(() => resolve()))+ }+ })})diff --git a/mcp-host/src/pluginWorkloadSdk/server/routes.ts b/mcp-host/src/pluginWorkloadSdk/server/routes.tsindex c07cde50f..804df72bc 100644--- a/mcp-host/src/pluginWorkloadSdk/server/routes.ts+++ b/mcp-host/src/pluginWorkloadSdk/server/routes.ts@@ -1,4 +1,5 @@import type { Express, NextFunction, Request, Response } from 'express'+import type { PluginWorkloadSdkCapability } from '../../config'import type { ClientNotificationsHandler } from '../clientNotifications/handler'import { PluginWorkloadError } from '../domain/errors'import type { PromptBridgeHandler } from '../promptBridge/handler'@@ -11,13 +12,25 @@ import { createWorkloadAuthMiddleware } from './middleware/workloadAuth'* POST /sdk/v1/prompt-bridge — one-shot LLM call* POST /sdk/v1/client-notifications — notification intent* GET /sdk/v1/client-notifications/recipients — list allowed recipients- * GET /healthz — unauthenticated liveness+ * GET /live — unauthenticated liveness+ * GET /health — unauthenticated readiness+ *+ * Route families are projected by WRC. A host never exposes a capability that+ * is absent from that projection, even when the caller has a valid workload+ * token for another family.*/+export interface PluginWorkloadSdkReadiness {+ ready: boolean+ reason?: string+}+export interface SdkRoutesOptions {+ capabilities: readonly PluginWorkloadSdkCapability[]workloadTokens: ReadonlyMap<string, string>- promptBridgeHandler: PromptBridgeHandler- clientNotificationsHandler: ClientNotificationsHandler+ promptBridgeHandler?: PromptBridgeHandler+ clientNotificationsHandler?: ClientNotificationsHandler+ readiness: () => PluginWorkloadSdkReadinessmaxRequestsPerMinutePerWorkload: numbermaxConcurrentPerWorkload: number}@@ -39,8 +52,20 @@ function sendError(res: Response, err: unknown): void {}export function registerSdkRoutes(app: Express, opts: SdkRoutesOptions): void {+ app.get('/live', (_req, res) => {+ res.status(200).json({ status: 'live' })+ })+ // Keep the old probe spelling as an observability alias only; it does not+ // restore any legacy workload route or authorization behavior.app.get('/healthz', (_req, res) => {- res.status(200).json({ ok: true })+ res.status(200).json({ status: 'live' })+ })+ app.get('/health', (_req, res) => {+ const readiness = opts.readiness()+ res.status(readiness.ready ? 200 : 503).json({+ status: readiness.ready ? 'ready' : 'not_ready',+ ...(readiness.reason ? { reason: readiness.reason } : {}),+ })})const auth = createWorkloadAuthMiddleware(opts.workloadTokens)@@ -49,39 +74,52 @@ export function registerSdkRoutes(app: Express, opts: SdkRoutesOptions): void {maxConcurrent: opts.maxConcurrentPerWorkload,})- app.post(- '/sdk/v1/prompt-bridge',- auth,- rateLimit,- (req: Request, res: Response, _next: NextFunction) => {- void opts.promptBridgeHandler- .handle(req.body, req.pluginWorkloadCallerRef!)- .then(result => res.status(200).json(result))- .catch(err => sendError(res, err))+ const capabilities = new Set(opts.capabilities)+ if (capabilities.has('promptBridge')) {+ if (!opts.promptBridgeHandler) {+ throw new Error('promptBridge route declared without a promptBridge handler')}- )+ const promptBridgeHandler = opts.promptBridgeHandler+ app.post(+ '/sdk/v1/prompt-bridge',+ auth,+ rateLimit,+ (req: Request, res: Response, _next: NextFunction) => {+ void promptBridgeHandler+ .handle(req.body, req.pluginWorkloadCallerRef!)+ .then(result => res.status(200).json(result))+ .catch(err => sendError(res, err))+ }+ )+ }- app.post(- '/sdk/v1/client-notifications',- auth,- rateLimit,- (req: Request, res: Response, _next: NextFunction) => {- void opts.clientNotificationsHandler- .handle(req.body, req.pluginWorkloadCallerRef!)- .then(result => res.status(200).json(result))- .catch(err => sendError(res, err))+ if (capabilities.has('clientNotifications')) {+ if (!opts.clientNotificationsHandler) {+ throw new Error('clientNotifications routes declared without a notifications handler')}- )+ const notificationsHandler = opts.clientNotificationsHandler+ app.post(+ '/sdk/v1/client-notifications',+ auth,+ rateLimit,+ (req: Request, res: Response, _next: NextFunction) => {+ void notificationsHandler+ .handle(req.body, req.pluginWorkloadCallerRef!)+ .then(result => res.status(200).json(result))+ .catch(err => sendError(res, err))+ }+ )- app.get(- '/sdk/v1/client-notifications/recipients',- auth,- rateLimit,- (req: Request, res: Response, _next: NextFunction) => {- void opts.clientNotificationsHandler- .listRecipients(req.pluginWorkloadCallerRef!)- .then(recipients => res.status(200).json({ recipients }))- .catch(err => sendError(res, err))- }- )+ app.get(+ '/sdk/v1/client-notifications/recipients',+ auth,+ rateLimit,+ (req: Request, res: Response, _next: NextFunction) => {+ void notificationsHandler+ .listRecipients(req.pluginWorkloadCallerRef!)+ .then(recipients => res.status(200).json({ recipients }))+ .catch(err => sendError(res, err))+ }+ )+ }}diff --git a/mcp-host/src/pluginWorkloadSdk/server/sdkServer.test.ts b/mcp-host/src/pluginWorkloadSdk/server/sdkServer.test.tsindex ebde33bd1..5d44da9a4 100644--- a/mcp-host/src/pluginWorkloadSdk/server/sdkServer.test.ts+++ b/mcp-host/src/pluginWorkloadSdk/server/sdkServer.test.ts@@ -111,6 +111,7 @@ describe('shouldStartPluginWorkloadSdk — behavior matrix', () => {it(c.name, () => {const result = shouldStartPluginWorkloadSdk({pluginWorkloadSdkEnabled: c.enabled,+ pluginWorkloadSdkCapabilities: c.enabled ? ['promptBridge'] : [],mcpHostRuntimeAccessToken: c.token,podNamespace: c.podNamespace,pluginWorkloadSdkCredentialBrokerUrl: c.enabled ? BROKER_URL : '',@@ -124,6 +125,7 @@ describe('shouldStartPluginWorkloadSdk — behavior matrix', () => {expect(shouldStartPluginWorkloadSdk({pluginWorkloadSdkEnabled: false,+ pluginWorkloadSdkCapabilities: [],mcpHostRuntimeAccessToken: SANDBOX_TOKEN,podNamespace: 'sandbox-recipes',pluginWorkloadSdkCredentialBrokerUrl: '',@@ -132,6 +134,7 @@ describe('shouldStartPluginWorkloadSdk — behavior matrix', () => {expect(shouldStartPluginWorkloadSdk({pluginWorkloadSdkEnabled: true,+ pluginWorkloadSdkCapabilities: ['promptBridge'],mcpHostRuntimeAccessToken: HOST_NS_TOKEN,podNamespace: 'sandbox-recipes',pluginWorkloadSdkCredentialBrokerUrl: BROKER_URL,@@ -140,12 +143,48 @@ describe('shouldStartPluginWorkloadSdk — behavior matrix', () => {expect(shouldStartPluginWorkloadSdk({pluginWorkloadSdkEnabled: true,+ pluginWorkloadSdkCapabilities: ['promptBridge'],mcpHostRuntimeAccessToken: SANDBOX_TOKEN,podNamespace: '',pluginWorkloadSdkCredentialBrokerUrl: BROKER_URL,}).reason).toContain('(empty)')})++ it('fails closed when WRC did not declare a capability family', () => {+ const result = shouldStartPluginWorkloadSdk({+ pluginWorkloadSdkEnabled: true,+ pluginWorkloadSdkCapabilities: [],+ mcpHostRuntimeAccessToken: SANDBOX_TOKEN,+ podNamespace: 'sandbox-recipes',+ pluginWorkloadSdkCredentialBrokerUrl: BROKER_URL,+ })+ expect(result.start).toBe(false)+ expect(result.reason).toContain('PLUGIN_WORKLOAD_SDK_CAPABILITIES')+ })++ it('starts a notification-only host without a promptBridge broker URL', () => {+ const result = shouldStartPluginWorkloadSdk({+ pluginWorkloadSdkEnabled: true,+ pluginWorkloadSdkCapabilities: ['clientNotifications'],+ mcpHostRuntimeAccessToken: SANDBOX_TOKEN,+ podNamespace: 'sandbox-recipes',+ pluginWorkloadSdkCredentialBrokerUrl: '',+ })+ expect(result).toEqual({ start: true, reason: 'all three gate conditions satisfied' })+ })++ it('requires the broker only when promptBridge is declared', () => {+ const result = shouldStartPluginWorkloadSdk({+ pluginWorkloadSdkEnabled: true,+ pluginWorkloadSdkCapabilities: ['promptBridge'],+ mcpHostRuntimeAccessToken: SANDBOX_TOKEN,+ podNamespace: 'sandbox-recipes',+ pluginWorkloadSdkCredentialBrokerUrl: '',+ })+ expect(result.start).toBe(false)+ expect(result.reason).toContain('CLERUM_WRC_URL')+ })})describe('validatePluginWorkloadSdkCredentialBrokerUrl', () => {diff --git a/mcp-host/src/pluginWorkloadSdk/server/sdkServer.ts b/mcp-host/src/pluginWorkloadSdk/server/sdkServer.tsindex b5228f6c2..e2bf5e02f 100644--- a/mcp-host/src/pluginWorkloadSdk/server/sdkServer.ts+++ b/mcp-host/src/pluginWorkloadSdk/server/sdkServer.ts@@ -1,5 +1,6 @@import express, { type Express } from 'express'import type http from 'http'+import type { PluginWorkloadSdkCapability } from '../../config'import { type RuntimeJwtBinding, getJwtRuntimeBinding } from '../../workflow/mcpHostRuntimeJwt'import type { ClientNotificationsHandler } from '../clientNotifications/handler'import type {@@ -7,7 +8,7 @@ import type {PluginWorkloadSdkClientNotificationsBootstrapProof,} from '../promptBridge/controlApiClient'import type { PromptBridgeHandler } from '../promptBridge/handler'-import { registerSdkRoutes } from './routes'+import { type PluginWorkloadSdkReadiness, registerSdkRoutes } from './routes'// ─── Namespace-bound activation gate (plan §3.5 / §6.3) ──────────────────// The SDK server starts if and only if ALL three conditions hold:@@ -46,6 +47,7 @@ export function validatePluginWorkloadSdkCredentialBrokerUrl(value: string): strexport function shouldStartPluginWorkloadSdk(config: {pluginWorkloadSdkEnabled: boolean+ pluginWorkloadSdkCapabilities: readonly PluginWorkloadSdkCapability[]mcpHostRuntimeAccessToken: stringpodNamespace: stringpluginWorkloadSdkCredentialBrokerUrl?: string@@ -54,10 +56,16 @@ export function shouldStartPluginWorkloadSdk(config: {return { start: false, reason: 'PLUGIN_WORKLOAD_SDK_ENABLED is not set' }}- const brokerUrlError = validatePluginWorkloadSdkCredentialBrokerUrl(- config.pluginWorkloadSdkCredentialBrokerUrl ?? ''- )- if (brokerUrlError) return { start: false, reason: brokerUrlError }+ if (config.pluginWorkloadSdkCapabilities.length === 0) {+ return { start: false, reason: 'PLUGIN_WORKLOAD_SDK_CAPABILITIES is empty' }+ }++ if (config.pluginWorkloadSdkCapabilities.includes('promptBridge')) {+ const brokerUrlError = validatePluginWorkloadSdkCredentialBrokerUrl(+ config.pluginWorkloadSdkCredentialBrokerUrl ?? ''+ )+ if (brokerUrlError) return { start: false, reason: brokerUrlError }+ }const runtimeBinding = getJwtRuntimeBinding(config.mcpHostRuntimeAccessToken)if (runtimeBinding?.recipeNamespace !== PLUGIN_WORKLOAD_SDK_REQUIRED_NAMESPACE) {@@ -83,9 +91,11 @@ export function shouldStartPluginWorkloadSdk(config: {export interface SdkServerOptions {port: numberrecipeName: string+ capabilities: readonly PluginWorkloadSdkCapability[]workloadTokens: ReadonlyMap<string, string>- promptBridgeHandler: PromptBridgeHandler- clientNotificationsHandler: ClientNotificationsHandler+ promptBridgeHandler?: PromptBridgeHandler+ clientNotificationsHandler?: ClientNotificationsHandler+ readiness: () => PluginWorkloadSdkReadinessmaxConnections?: numbermaxRequestsPerMinutePerWorkload?: numbermaxConcurrentPerWorkload?: number@@ -127,7 +137,7 @@ export class PluginWorkloadSdkServer {this.app.use(express.json({ limit: '1mb' }))if (opts.getRuntimeBinding) {this.app.use((req, res, next) => {- if (req.path === '/healthz') return next()+ if (req.path === '/health' || req.path === '/live' || req.path === '/healthz') return next()const reason = checkLiveRuntimeBinding(opts.getRuntimeBinding!(), opts.recipeName)if (reason) {console.error(`[PluginWorkloadSdk] request refused (binding drift): ${reason}`)@@ -139,9 +149,11 @@ export class PluginWorkloadSdkServer {})}registerSdkRoutes(this.app, {+ capabilities: opts.capabilities,workloadTokens: opts.workloadTokens,promptBridgeHandler: opts.promptBridgeHandler,clientNotificationsHandler: opts.clientNotificationsHandler,+ readiness: opts.readiness,maxRequestsPerMinutePerWorkload: opts.maxRequestsPerMinutePerWorkload ?? 100,maxConcurrentPerWorkload: opts.maxConcurrentPerWorkload ?? 10,})@@ -151,6 +163,9 @@ export class PluginWorkloadSdkServer {expectedProvider: string,expectedModel: string): Promise<PluginWorkloadSdkBootstrapProof> {+ if (!this.opts.promptBridgeHandler) {+ return Promise.reject(new Error('promptBridge bootstrap verifier is not configured'))+ }return this.opts.promptBridgeHandler.verifyBootstrapV2(expectedProvider, expectedModel)}diff --git a/scripts/minikube/pre-gate-sync.sh b/scripts/minikube/pre-gate-sync.shindex ba752ed3d..82c2efbd3 100755--- a/scripts/minikube/pre-gate-sync.sh+++ b/scripts/minikube/pre-gate-sync.sh@@ -52,6 +52,86 @@ source "${SCRIPT_DIR}/pre-gate-runtime.sh"# shellcheck source=scripts/minikube/pre-gate-incremental.shsource "${SCRIPT_DIR}/pre-gate-incremental.sh"+# A database/schema migration must not race the eager workflow reconciler. Keep+# the existing replica count so a failed gate restores the branch-owned+# control-plane shape instead of silently leaving reconciliation disabled.+WRC_FENCED=false+WRC_REPLICAS=1+CONTROL_API_FENCED=false+CONTROL_API_REPLICAS=1++fence_workflow_reconciler() {+ if ! ${KC} get deployment/workflow-recipes -n control-plane >/dev/null 2>&1; then+ log "Workflow reconciler is not present; no rollout fence is required"+ return 0+ fi+ WRC_REPLICAS="$(${KC} get deployment/workflow-recipes -n control-plane -o jsonpath='{.spec.replicas}')"+ WRC_REPLICAS="${WRC_REPLICAS:-1}"+ log "Fencing workflow reconciler at ${WRC_REPLICAS} replica(s) before schema migration"+ WRC_FENCED=true+ ${KC} scale deployment/workflow-recipes -n control-plane --replicas=0 >/dev/null+ ${KC} rollout status deployment/workflow-recipes -n control-plane --timeout=60s >/dev/null+}++restore_workflow_reconciler() {+ if [[ "${WRC_FENCED}" != "true" ]]; then+ return 0+ fi+ set +e+ log "Restoring workflow reconciler to ${WRC_REPLICAS} replica(s)"+ ${KC} scale deployment/workflow-recipes -n control-plane --replicas="${WRC_REPLICAS}" >/dev/null+ ${KC} rollout status deployment/workflow-recipes -n control-plane --timeout=120s >/dev/null+ local restore_rc=$?+ set -e+ if [[ "${restore_rc}" -ne 0 ]]; then+ log "WARNING: workflow reconciler did not become Ready during pre-gate cleanup"+ fi+ WRC_FENCED=false+}++fence_control_api() {+ if ! ${KC} get deployment/control-api -n control-plane >/dev/null 2>&1; then+ log "Control API is not present; no writer fence is required"+ return 0+ fi+ CONTROL_API_REPLICAS="$(${KC} get deployment/control-api -n control-plane -o jsonpath='{.spec.replicas}')"+ CONTROL_API_REPLICAS="${CONTROL_API_REPLICAS:-1}"+ if [[ ! "${CONTROL_API_REPLICAS}" =~ ^[0-9]+$ ]]; then+ log "ERROR: unable to determine control-api replica count; refusing schema-first sync"+ return 1+ fi+ log "Fencing Control API writers at ${CONTROL_API_REPLICAS} replica(s) before schema migration"+ CONTROL_API_FENCED=true+ ${KC} scale deployment/control-api -n control-plane --replicas=0 >/dev/null+ ${KC} rollout status deployment/control-api -n control-plane --timeout=60s >/dev/null+}++restore_control_api() {+ if [[ "${CONTROL_API_FENCED}" != "true" ]]; then+ return 0+ fi+ set +e+ log "Restoring Control API to ${CONTROL_API_REPLICAS} replica(s)"+ ${KC} scale deployment/control-api -n control-plane --replicas="${CONTROL_API_REPLICAS}" >/dev/null+ ${KC} rollout status deployment/control-api -n control-plane --timeout=120s >/dev/null+ local restore_rc=$?+ set -e+ if [[ "${restore_rc}" -ne 0 ]]; then+ log "WARNING: Control API did not become Ready during pre-gate cleanup"+ fi+ CONTROL_API_FENCED=false+}++restore_pre_gate_writers() {+ # Restore Control API first so it can serve the final readiness checks; WRC+ # remains last because it is the consumer that must stay stopped until every+ # migration, writer restart, and legacy-policy gate has completed.+ restore_control_api+ restore_workflow_reconciler+}++trap restore_pre_gate_writers EXIT+fingerprint_dir() {local dir="$1"@@ -312,20 +392,13 @@ if [[ "${cluster_changed}" == "true" ]]; thenfifi- incremental_build_images-- if [[ "${INCREMENTAL_FULL_IMAGE_BUILD}" == "true" ||- "${INCREMENTAL_FULL_DEPLOYMENT}" == "true" ]]; then- (- cd "${PROJECT_DIR}"- make minikube-apply-secrets- make minikube-deploy-all- if [[ "${FORCE_RESTART}" == "true" || "${INCREMENTAL_FULL_IMAGE_BUILD}" == "true" ]]; then- make minikube-restart-all- fi- )+ if incremental_requires_database_reconcile; then+ fence_workflow_reconciler+ fence_control_apifi+ incremental_build_images+if incremental_requires_database_reconcile; thenrollout_if_present control-plane control-postgresCONTEXT="${PROFILE}" ALLOWED_CONTEXTS="${PROFILE}" \@@ -333,7 +406,6 @@ if [[ "${cluster_changed}" == "true" ]]; then--overlay "${PROJECT_DIR}/deploy/overlays/minikube"CONTEXT="${PROFILE}" ALLOWED_CONTEXTS="${PROFILE}" \bash "${PROJECT_DIR}/deploy/scripts/provision-control-api-runtime-roles.sh"- rollout_if_present control-plane control-api# The base manifest no longer declares connection-string (provisioning-owned# key), so deploy-all cannot clobber it. Provisioning must still run AFTER# control-api migrations (0048 creates the least-privilege gfs_controller@@ -342,6 +414,27 @@ if [[ "${cluster_changed}" == "true" ]]; thenprovision_gfs_servingfi+ # Schema/control-plane first: only after migrations, runtime roles, and+ # inventory gates have converged may the new consumer workloads be applied or+ # restarted. The workflow reconciler is fenced above for this window.+ if [[ "${INCREMENTAL_FULL_IMAGE_BUILD}" == "true" ||+ "${INCREMENTAL_FULL_DEPLOYMENT}" == "true" ]]; then+ (+ cd "${PROJECT_DIR}"+ make minikube-apply-secrets+ make minikube-deploy-all+ if [[ "${FORCE_RESTART}" == "true" || "${INCREMENTAL_FULL_IMAGE_BUILD}" == "true" ]]; then+ make minikube-restart-all+ fi+ )+ fi++ # The schema-first window is over: all desired manifests/images are now in+ # place, so restore the old replica count only after the old writer was fully+ # stopped and migrations completed. Recreate strategy on the Deployment makes+ # ordinary image/config rollouts obey the same no-overlap contract.+ restore_control_api+# Release invariant: every path that can restart/serve mcp-host proves that# no legacy grant is routable, not only the migration path.assert_no_legacy_prompt_bridge_grantsdiff --git a/scripts/tests/test-gfs-deploy-contract.sh b/scripts/tests/test-gfs-deploy-contract.shindex c738c1871..7660f3041 100755--- a/scripts/tests/test-gfs-deploy-contract.sh+++ b/scripts/tests/test-gfs-deploy-contract.sh@@ -22,7 +22,7 @@ provision_contract="$(sed -n '/verify_role_contract()/,/^}/p' deploy/scripts/pro[[ "$provision_contract" == *"has_column_privilege(:'role_name', 'control_admin_users', 'id', 'SELECT')"* && "$provision_contract" == *"has_column_privilege(:'role_name', 'team_members', 'status', 'SELECT')"* && "$provision_contract" == *"column_name NOT IN ('id', 'status')"* && "$provision_contract" == *"column_name NOT IN ('team_id', 'user_id', 'status')"* ]] || fail 'provisioner does not verify the exact subject-column contract'writer_case="$(sed -n '/rotate-writer)/,/;;/p' deploy/scripts/provision-gfs-db.sh)"[[ "$writer_case" == *'reconcile_credential gfs_controller writer "$WRITER_SECRET" gfsc-writer true'* && "$writer_case" != *'gfsc-reader'* ]] || fail 'writer rollout scope'-runtime_script="$(cat deploy/scripts/provision-gfs-runtime.sh)"+runtime_script="$(sed '/^[[:space:]]*#/d' deploy/scripts/provision-gfs-runtime.sh)"[[ "$runtime_script" == *'reconcile-gfs-deploy-credentials.sh'* ]] \|| fail 'post-overlay runtime path does not reconcile staged credentials'[[ "$runtime_script" == *'rollout status deployment/gfsc-writer'* && \@@ -115,9 +115,11 @@ reset_full_overlay="$(grep -n 'kubectl kustomize .* | .* apply -f -' <<<"$full_spre_gate_crds="$(grep -n 'make minikube-deploy-crds' scripts/minikube/pre-gate-sync.sh | cut -d: -f1)"pre_gate_writer="$(grep -n 'apply-gfs-writer-secret.sh' scripts/minikube/pre-gate-sync.sh | head -1 | cut -d: -f1)"pre_gate_overlay="$(grep -n 'make minikube-deploy-all' scripts/minikube/pre-gate-sync.sh | head -1 | cut -d: -f1)"+pre_gate_migration="$(grep -n 'run-control-api-db-migration.sh' scripts/minikube/pre-gate-sync.sh | head -1 | cut -d: -f1)"[[ "$(wc -l <<<"$pre_gate_crds" | tr -d ' ')" -eq 1 ]] || fail 'pre-gate must apply CRDs exactly once'-[[ "$pre_gate_crds" -lt "$pre_gate_writer" && "$pre_gate_writer" -lt "$pre_gate_overlay" ]] \- || fail 'pre-gate must apply namespaces/CRDs before GFS Secrets and overlay'+[[ "$pre_gate_crds" -lt "$pre_gate_writer" && "$pre_gate_writer" -lt "$pre_gate_migration" && \+ "$pre_gate_migration" -lt "$pre_gate_overlay" ]] \+ || fail 'pre-gate must apply CRDs, secrets, and schema migration before the consumer overlay'# The GFS writer Secret must never be applied into a missing namespace. In the# OSS deploy model, namespaces are applied by the prior deploy-crds/pre-gate step# (asserted above for pre-gate-sync: CRDs -> writer Secret -> overlay), anddiff --git a/scripts/tests/test-minikube-pre-gate-sync-state.sh b/scripts/tests/test-minikube-pre-gate-sync-state.shindex ae8d7a90e..00fc7700b 100755--- a/scripts/tests/test-minikube-pre-gate-sync-state.sh+++ b/scripts/tests/test-minikube-pre-gate-sync-state.sh@@ -143,14 +143,25 @@ elsefail "pre-gate sync does not build workflow-runtime-core before dependent package tests"fi-control_api_rollout_line="$(grep -nF 'rollout_if_present control-plane control-api' "$SCRIPT" | head -n 1 | cut -d: -f1)"+control_api_restore_line="$(grep -nF 'restore_control_api' "$SCRIPT" | tail -n 1 | cut -d: -f1)"gfs_provision_line="$(grep -nF 'provision_gfs_serving' "$SCRIPT" | tail -n 1 | cut -d: -f1)"-if [[ -n "$control_api_rollout_line" &&+if [[ -n "$control_api_restore_line" &&-n "$gfs_provision_line" &&- "$control_api_rollout_line" -lt "$gfs_provision_line" ]]; then- pass "pre-gate sync waits for control-api migrations before gfs provisioning"+ "$gfs_provision_line" -lt "$control_api_restore_line" ]]; then+ pass "pre-gate sync waits for control-api migrations and gfs provisioning before writer restore"else- fail "pre-gate sync can provision gfs before control-api migrations"+ fail "pre-gate sync can restore control-api before migrations or gfs provisioning"+fi++if contains 'fence_control_api()' &&+ contains 'restore_control_api()' &&+ contains 'fence_workflow_reconciler' &&+ contains 'fence_control_api' &&+ contains 'trap restore_pre_gate_writers EXIT' &&+ grep -Fq 'type: Recreate' deploy/base/control-plane/control-api.yaml; then+ pass "pre-gate and Deployment enforce a no-overlap Control API writer window"+else+ fail "Control API writer overlap is not fail-closed during migration/rollout"fiif grep -Fq 'MINIKUBE_MULTI_NODE=true' "$REGISTRY_SCRIPT" &&@@ -186,4 +197,22 @@ elsefail "legacy grant inventory can execute psql on the host instead of PostgreSQL"fi+if contains 'fence_workflow_reconciler()' &&+ contains 'restore_workflow_reconciler()' &&+ contains 'trap restore_pre_gate_writers EXIT' &&+ contains 'fence_workflow_reconciler' &&+ contains 'run-control-api-db-migration.sh' &&+ contains 'make minikube-deploy-all'; then+ fence_line="$(grep -n 'fence_workflow_reconciler$' "$SCRIPT" | tail -1 | cut -d: -f1)"+ migration_line="$(grep -n 'run-control-api-db-migration.sh' "$SCRIPT" | head -1 | cut -d: -f1)"+ overlay_line="$(grep -n 'make minikube-deploy-all' "$SCRIPT" | head -1 | cut -d: -f1)"+ if [[ "$fence_line" -lt "$migration_line" && "$migration_line" -lt "$overlay_line" ]]; then+ pass "pre-gate fences workflow reconciliation before schema-first migration"+ else+ fail "pre-gate rollout order can expose consumers before schema migration"+ fi+else+ fail "pre-gate sync lacks an explicit workflow reconciliation fence"+fi+exit "$FAIL"diff --git a/workflow-recipes/package-lock.json b/workflow-recipes/package-lock.jsonindex cec272f40..fa166d2f2 100644--- a/workflow-recipes/package-lock.json+++ b/workflow-recipes/package-lock.json@@ -1,6 +1,6 @@{"name": "workload-recipes-controller",- "version": "0.1.278",+ "version": "0.1.279","lockfileVersion": 3,"requires": true,"packages": {@@ -34,7 +34,7 @@"engines": {"node": ">=24"},- "version": "0.1.278"+ "version": "0.1.279"},"../packages/image-policy": {"name": "@clerum/image-policy",diff --git a/workflow-recipes/package.json b/workflow-recipes/package.jsonindex d1bf60f5f..7bc08787f 100644--- a/workflow-recipes/package.json+++ b/workflow-recipes/package.json@@ -1,6 +1,6 @@{"name": "workload-recipes-controller",- "version": "0.1.278",+ "version": "0.1.279","description": "Workload Recipes Controller (WRC) - WorkloadRecipe lifecycle management and MCP server interface","main": "dist/main.js","engines": {diff --git a/workflow-recipes/src/workflow/pluginWorkloadSdkProvisioner.imageDrift.test.ts b/workflow-recipes/src/workflow/pluginWorkloadSdkProvisioner.imageDrift.test.tsindex 993aa86e2..870c53b65 100644--- a/workflow-recipes/src/workflow/pluginWorkloadSdkProvisioner.imageDrift.test.ts+++ b/workflow-recipes/src/workflow/pluginWorkloadSdkProvisioner.imageDrift.test.ts@@ -57,6 +57,9 @@ function makeProvisioner(ensureMcpHostSecrets: vi.fn().mockResolvedValue(undefined),applyWorkflowNetworkPolicies: vi.fn().mockResolvedValue(undefined),ensureMcpHostHeadlessService: vi.fn().mockResolvedValue(undefined),+ modelConfigHandler: {+ configurePluginWorkloadSdkBootstrap: vi.fn().mockResolvedValue({ status: 503 }),+ },createIfNotExists: vi.fn().mockResolvedValue(true),safeDelete: vi.fn().mockResolvedValue(undefined),} as unknown as PluginWorkloadSdkProvisionerDeps@@ -67,7 +70,10 @@ function makeProvisioner(// spec.agent resolves to a complete agent so ensureEagerSdkMcpHost does not// bail out before reaching the image-drift branch.-const SPEC = { agent: { provider: 'openai', model: 'gpt-4' } } as unknown as WorkflowRecipeSpec+const SPEC = {+ agent: { provider: 'openai', model: 'gpt-4' },+ pluginWorkloadSdk: { promptBridge: {} },+} as unknown as WorkflowRecipeSpecconst RUNTIME = {} as unknown as WorkflowRuntimePlanconst TEST_CONFIG = {coordinatorImage: 'registry.example/coordinator:current',@@ -105,7 +111,7 @@ function desiredRuntimeContractHash(): string {undefined,{mountWorkflowOutput: false,- pluginWorkloadSdkEnabled: true,+ pluginWorkloadSdkCapabilities: ['promptBridge'],pluginWorkloadSdkRuntimeMode: 'sdk-only',})@@ -239,6 +245,9 @@ describe('ensureEagerSdkMcpHost image-drift roll', () => {coreApi,config: TEST_CONFIG,tokenFactory: {},+ modelConfigHandler: {+ configurePluginWorkloadSdkBootstrap: vi.fn().mockResolvedValue({ status: 503 }),+ },log: { info: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn() },ensureMcpHostSecrets: vi.fn().mockResolvedValue(undefined),applyWorkflowNetworkPolicies: vi.fn().mockResolvedValue(undefined),@@ -303,6 +312,9 @@ describe('ensureEagerSdkMcpHost image-drift roll', () => {pluginWorkloadSdkEnabled: true,},tokenFactory: {},+ modelConfigHandler: {+ configurePluginWorkloadSdkBootstrap: vi.fn().mockResolvedValue({ status: 503 }),+ },log: { info: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn() },ensureMcpHostSecrets: vi.fn().mockResolvedValue(undefined),applyWorkflowNetworkPolicies: vi.fn().mockResolvedValue(undefined),@@ -417,7 +429,7 @@ describe('ensureEagerSdkMcpHost image-drift roll', () => {undefined,{mountWorkflowOutput: false,- pluginWorkloadSdkEnabled: true,+ pluginWorkloadSdkCapabilities: ['promptBridge'],pluginWorkloadSdkRuntimeMode: 'sdk-only',})diff --git a/workflow-recipes/src/workflow/pluginWorkloadSdkProvisioner.ts b/workflow-recipes/src/workflow/pluginWorkloadSdkProvisioner.tsindex cf4e14eb5..6e585fcf1 100644--- a/workflow-recipes/src/workflow/pluginWorkloadSdkProvisioner.ts+++ b/workflow-recipes/src/workflow/pluginWorkloadSdkProvisioner.ts@@ -20,7 +20,11 @@ import {pluginWorkloadSdkTokenSecretKey,resolvePluginWorkloadSdkAllowedCallers,} from './pluginWorkloadSdkTokens'-import { buildMcpHostPod, pluginWorkloadSdkRuntimeContractHash } from './podFactory'+import {+ buildMcpHostPod,+ declaredPluginWorkloadSdkCapabilities,+ pluginWorkloadSdkRuntimeContractHash,+} from './podFactory'import {PLUGIN_WORKLOAD_SDK_LEGACY_TOKEN_DATA_KEY,buildMcpHostUrl,@@ -173,9 +177,11 @@ export class PluginWorkloadSdkProvisioner {}): Promise<EagerSdkMcpHostStatus> {const log = createLogger('wrc', recipeName)+ const capabilities = declaredPluginWorkloadSdkCapabilities(spec.pluginWorkloadSdk)+ const requiresPromptBridge = capabilities.includes('promptBridge')const mcpHostAgent = resolveEagerSdkMcpHostAgent(spec)- if (!mcpHostAgent && spec.pluginWorkloadSdk?.promptBridge) {+ if (!mcpHostAgent && requiresPromptBridge) {log.warn('Plugin Workload SDK promptBridge declared but no agent is resolvable; ' +'declare spec.agent with provider+model to bind the eager mcp-host'@@ -210,7 +216,7 @@ export class PluginWorkloadSdkProvisioner {effectiveWorkflowContextRefForSpec(recipeName, spec),{mountWorkflowOutput: false,- pluginWorkloadSdkEnabled: true,+ pluginWorkloadSdkCapabilities: capabilities,pluginWorkloadSdkRuntimeMode: 'sdk-only',})@@ -282,21 +288,33 @@ export class PluginWorkloadSdkProvisioner {}const readiness = await this.readinessForEagerSdkMcpHost(recipeName)- const promptBridge = spec.pluginWorkloadSdk?.promptBridge !== undefined- const clientNotifications = spec.pluginWorkloadSdk?.clientNotifications !== undefined+ const promptBridge = capabilities.includes('promptBridge')+ const clientNotifications = capabilities.includes('clientNotifications')if (!promptBridge && !clientNotifications) {this.eagerSdkBootstrapProofByRecipe.delete(recipeName)return readiness.status}- if (!this.deps.modelConfigHandler) {+ const modelConfigHandler = this.deps.modelConfigHandler+ if (requiresPromptBridge && !modelConfigHandler) {this.eagerSdkBootstrapProofByRecipe.delete(recipeName)- return 'failed'+ return 'provider_unavailable'}if (readiness.status !== 'ready') {this.eagerSdkBootstrapProofByRecipe.delete(recipeName)return readiness.status}+ // A provider-free notification host can expose its route once the+ // namespace-bound runtime is Ready; there is no LLM identity to broker.+ // Production normally supplies the modelConfigHandler for a policy proof,+ // but absence must not turn a valid notification-only recipe into a fake+ // provider failure.+ if (!requiresPromptBridge && !modelConfigHandler) {+ this.eagerSdkBootstrapProofByRecipe.delete(recipeName)+ return readiness.status+ }+ if (!modelConfigHandler) return 'provider_unavailable'+if (!readiness.uid) {log.warn('Plugin Workload SDK eager mcp-host reported Ready without a pod UID; waiting for stable bootstrap identity'@@ -315,13 +333,13 @@ export class PluginWorkloadSdkProvisioner {const mcpHostEndpoint = buildMcpHostUrl(recipeName, this.deps.config.sandboxNamespace)const result =capabilityFamily === 'promptBridge'- ? await this.deps.modelConfigHandler.configurePluginWorkloadSdkBootstrap(+ ? await modelConfigHandler.configurePluginWorkloadSdkBootstrap(mcpHostAgent!.provider,mcpHostAgent!.model,mcpHostEndpoint,wrcConfigureToken)- : await this.deps.modelConfigHandler.configurePluginWorkloadSdkBootstrap(+ : await modelConfigHandler.configurePluginWorkloadSdkBootstrap(undefined,undefined,mcpHostEndpoint,diff --git a/workflow-recipes/src/workflow/podFactory.ts b/workflow-recipes/src/workflow/podFactory.tsindex 37f5d2fd2..7a688fb9d 100644--- a/workflow-recipes/src/workflow/podFactory.ts+++ b/workflow-recipes/src/workflow/podFactory.ts@@ -6,7 +6,7 @@import * as k8s from '@kubernetes/client-node'import { createHash } from 'node:crypto'import { privateWorkflowContextName } from '../reconciler/workflowContext'-import type { WorkflowRecipeGfsScope } from '../types'+import type { PluginWorkloadSdkSpec, WorkflowRecipeGfsScope } from '../types'import { truncateRfc1123WithHash } from './networkPolicyFactory'import {PLUGIN_WORKLOAD_SDK_PORT,@@ -26,6 +26,15 @@ 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'+export const PLUGIN_WORKLOAD_SDK_CAPABILITIES = ['promptBridge', 'clientNotifications'] as const+export type PluginWorkloadSdkCapability = (typeof PLUGIN_WORKLOAD_SDK_CAPABILITIES)[number]++export function declaredPluginWorkloadSdkCapabilities(+ spec: PluginWorkloadSdkSpec | undefined+): PluginWorkloadSdkCapability[] {+ if (!spec) return []+ return PLUGIN_WORKLOAD_SDK_CAPABILITIES.filter(capability => spec[capability] !== undefined)+}/*** Annotation carrying the immutable contract used by an eager SDK mcp-host.@@ -585,6 +594,9 @@ export interface McpHostPodOptions {* mcp-host). MCP_HOST_POD_NAMESPACE is injected unconditionally — the* downward API leg of the gate must exist even when the flag is off.*/+ /** Exact SDK families projected from the reviewed WorkflowRecipe. */+ pluginWorkloadSdkCapabilities?: readonly PluginWorkloadSdkCapability[]+ /** Compatibility input for existing workflow mcp-host callers. */pluginWorkloadSdkEnabled?: boolean/** Runtime contract used by mcp-host usage attribution. */pluginWorkloadSdkRuntimeMode?: 'workflow' | 'sdk-only'@@ -603,7 +615,11 @@ export function buildMcpHostPod(): k8s.V1Pod {const mountWorkflowOutput = options.mountWorkflowOutputconst runtimeMode = options.pluginWorkloadSdkRuntimeMode ?? 'workflow'- if (runtimeMode === 'sdk-only' && options.pluginWorkloadSdkEnabled !== true) {+ const pluginWorkloadSdkCapabilities =+ options.pluginWorkloadSdkCapabilities ??+ (options.pluginWorkloadSdkEnabled ? PLUGIN_WORKLOAD_SDK_CAPABILITIES : [])+ const pluginWorkloadSdkEnabled = pluginWorkloadSdkCapabilities.length > 0+ if (runtimeMode === 'sdk-only' && !pluginWorkloadSdkEnabled) {throw new Error('sdk-only mcp-host runtime requires pluginWorkloadSdkEnabled=true')}if (mountWorkflowOutput && !workflowOutputClaimName) {@@ -730,8 +746,11 @@ export function buildMcpHostPod(value: 'http://nginx-workflow-approval-gateway.control-plane.svc.cluster.local:8092',},// PromptBridge resolves exactly one signed target credential per- // attempt through WRC; no provider key is preloaded for this lane.- { name: 'CLERUM_WRC_URL', value: config.wrcEndpoint },+ // attempt through WRC. Notification-only hosts are provider-free+ // and deliberately receive no broker URL.+ ...(pluginWorkloadSdkCapabilities.includes('promptBridge')+ ? [{ name: 'CLERUM_WRC_URL', value: config.wrcEndpoint }]+ : []),{name: 'MCP_HOST_WORKFLOW_CONTROL_TOKEN_FILE',value: MCP_HOST_WORKFLOW_CONTROL_TOKEN_FILE_PATH,@@ -750,9 +769,13 @@ export function buildMcpHostPod(name: 'MCP_HOST_POD_NAMESPACE',valueFrom: { fieldRef: { fieldPath: 'metadata.namespace' } },},- ...(options.pluginWorkloadSdkEnabled+ ...(pluginWorkloadSdkEnabled? [{ name: 'PLUGIN_WORKLOAD_SDK_ENABLED', value: 'true' },+ {+ name: 'PLUGIN_WORKLOAD_SDK_CAPABILITIES',+ value: pluginWorkloadSdkCapabilities.join(','),+ },{name: 'PLUGIN_WORKLOAD_SDK_RUNTIME_MODE',value: runtimeMode,@@ -788,7 +811,7 @@ export function buildMcpHostPod(},]: []),- ...(options.pluginWorkloadSdkEnabled+ ...(pluginWorkloadSdkEnabled? [{name: 'plugin-workload-sdk-tokens',@@ -803,13 +826,21 @@ export function buildMcpHostPod(limits: { cpu: '2000m', memory: '2Gi' },},readinessProbe: {- httpGet: { path: '/v1/runtime/health', port: 8080 },+ // SDK-only mcp-hosts are bootstrapped by WRC after the Pod becomes+ // a Service endpoint. `/health` intentionally remains 503 until+ // that identity handshake completes, so probing it here would+ // create a permanent Ready -> bootstrap -> Ready deadlock.+ httpGet: {+ path:+ runtimeMode === 'sdk-only' ? '/v1/runtime/bootstrap-ready' : '/v1/runtime/health',+ port: 8080,+ },initialDelaySeconds: 5,periodSeconds: 10,failureThreshold: 6,},livenessProbe: {- httpGet: { path: '/v1/runtime/health', port: 8080 },+ httpGet: { path: '/v1/runtime/live', port: 8080 },initialDelaySeconds: 15,periodSeconds: 30,},@@ -829,7 +860,7 @@ export function buildMcpHostPod(},]: []),- ...(options.pluginWorkloadSdkEnabled+ ...(pluginWorkloadSdkEnabled? [{name: 'plugin-workload-sdk-tokens',@@ -840,7 +871,7 @@ export function buildMcpHostPod(],},}- if (options.pluginWorkloadSdkEnabled === true) {+ if (pluginWorkloadSdkEnabled) {pod.metadata = {...pod.metadata,annotations: {diff --git a/workflow-recipes/src/workflow/workflowReconciler.ts b/workflow-recipes/src/workflow/workflowReconciler.tsindex de1012d46..27ec4bef8 100644--- a/workflow-recipes/src/workflow/workflowReconciler.ts+++ b/workflow-recipes/src/workflow/workflowReconciler.ts@@ -83,6 +83,7 @@ import {buildWorkflowOutputAnchorPodName,buildWorkflowOutputPreparePod,buildWorkflowOutputPreparePodName,+ declaredPluginWorkloadSdkCapabilities,workflowOutputLabelValue,} from './podFactory'import {@@ -1430,10 +1431,13 @@ export class WorkflowReconciler {const pluginWorkloadSdkDeclared =spec.pluginWorkloadSdk?.promptBridge !== undefined ||spec.pluginWorkloadSdk?.clientNotifications !== undefined+ const promptBridgeDeclared = spec.pluginWorkloadSdk?.promptBridge !== undefinedconst eagerReady =(eagerStatus === 'ready' || eagerPolicyPending) &&- (!pluginWorkloadSdkDeclared || eagerBootstrapProof !== undefined)- if (eagerStatus === 'ready' && pluginWorkloadSdkDeclared && !eagerBootstrapProof) {+ (!pluginWorkloadSdkDeclared ||+ !promptBridgeDeclared ||+ eagerBootstrapProof !== undefined)+ if (eagerStatus === 'ready' && promptBridgeDeclared && !eagerBootstrapProof) {return withWorkflowConditions({phase: 'deploying',message: `Plugin Workload SDK bootstrap policy proof pending (${classification})`,@@ -1936,8 +1940,9 @@ export class WorkflowReconciler {gfsScopes: coordinatorGfsScopes,mountWorkflowOutput: runtime.pods.mcpHost!.mountWorkflowOutput,workflowOutputScope: runtime.pods.mcpHost!.workflowOutputScope,- pluginWorkloadSdkEnabled:- this.deps.config.pluginWorkloadSdkEnabled && Boolean(spec.pluginWorkloadSdk),+ pluginWorkloadSdkCapabilities: this.deps.config.pluginWorkloadSdkEnabled+ ? declaredPluginWorkloadSdkCapabilities(spec.pluginWorkloadSdk)+ : [],})await this.createIfNotExists(