Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure
TypeScript
fix(control-api): make registry and secret mutations identity-safe
Alfredo Lopez286fd5404214
diff --cc control-api/package-lock.jsonindex a9d7c0954,a9d7c0954..82735fc94--- a/control-api/package-lock.json+++ b/control-api/package-lock.json@@@ -1,12 -1,12 +1,12 @@@{"name": "clerum-control-api",-- "version": "0.1.495",++ "version": "0.1.496","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "clerum-control-api",-- "version": "0.1.495",++ "version": "0.1.496","dependencies": {"@clerum/display-field": "file:../packages/display-field","@clerum/image-policy": "file:../packages/image-policy",diff --cc control-api/package.jsonindex 42c3ad733,42c3ad733..d861f940d--- a/control-api/package.json+++ b/control-api/package.json@@@ -1,6 -1,6 +1,6 @@@{"name": "clerum-control-api",-- "version": "0.1.495",++ "version": "0.1.496","description": "Internal Clerum control plane REST API + UI for managing CRDs and secrets","main": "dist/main.js","engines": {diff --cc control-api/src/k8s.tsindex 80e19924c,a8bcae7a8..fbda2f6f7--- a/control-api/src/k8s.ts+++ b/control-api/src/k8s.ts@@@ -7,16 -8,14 +8,13 @@@ importLlmAllowedModelsConfigMapWriter,} from './services/llmAllowedModelsConfigMap.js'import { ResourceService, mergeAnnotationsForReplace } from './services/resourceService.js'-import {- type DeleteSecretSummary,- SecretService,- type SecretSummary,-} from './services/secretService.js'+import type { SecretConstraintOptions } from './services/secretConstraints.js'- import type {- SecretRepository,- SecretResource,- SecretSnapshot,- } from './services/secretRepository.js'- import { SecretService } from './services/secretService.js'++import type { SecretSnapshot } from './services/secretRepository.js'++import { type DeleteSecretSummary, SecretService } from './services/secretService.js'import {ClerumResourceType,HostOverview,++ ResourcePreconditions,SecretPreconditions,SecretUpsertRequest,} from './types.js'@@@ -263,6 -264,6 +263,7 @@@ export class K8sGatewaymetadata?: {labels?: Record<string, string>annotations?: Record<string, string>++ uid?: stringresourceVersion?: string}spec: Record<string, unknown>@@@ -389,9 -390,9 +390,10 @@@async deleteResource(plural: ClerumResourceType,name: string,-- namespace?: string++ namespace?: string,++ precondition?: ResourcePreconditions): Promise<unknown> {-- return this.resources.deleteResource(plural, name, namespace)++ return this.resources.deleteResource(plural, name, namespace, precondition)}async listSecrets(namespace = this.secretsNamespace): Promise<unknown[]> {@@@ -407,35 -408,31 +409,42 @@@return this.secrets.getSecret(name, namespace)}- // Write ops return a names-only summary (never the k8s Secret's `.data`), so no- // route can leak secret values by echoing the return — and reading `.data` off- // the returned summary is now a compile error. Reads (getSecret) stay full-fat.- async createSecret(req: SecretUpsertRequest): Promise<SecretSummary> {- return this.secrets.createSecret(req)++ // SecretService's public write methods are names-only. Registry and rollback++ // need an internal snapshot for UID/RV CAS and restoration; those snapshots++ // are never serialized by an HTTP route.+ async createSecret(+ req: SecretUpsertRequest,+ opts?: SecretConstraintOptions+ ): Promise<SecretSnapshot> {- return this.secrets.createSecret(req, opts)++ return this.secrets.createSecretSnapshot(req, opts)}/** `precondition` makes the replace ownership-bound; see `SecretPreconditions`. */async updateSecret(req: SecretUpsertRequest,- precondition?: SecretPreconditions- ): Promise<SecretSummary> {- return this.secrets.updateSecret(req, precondition)+ precondition?: SecretPreconditions,+ opts?: SecretConstraintOptions+ ): Promise<SecretSnapshot> {- return this.secrets.updateSecret(req, precondition, opts)++ return this.secrets.updateSecretSnapshot(req, precondition, opts)}- async mergeSecret(req: SecretUpsertRequest): Promise<SecretSummary> {- return this.secrets.mergeSecret(req)+ async mergeSecret(+ req: SecretUpsertRequest,- opts?: SecretConstraintOptions++ opts?: SecretConstraintOptions,++ precondition?: SecretPreconditions+ ): Promise<SecretSnapshot> {- return this.secrets.mergeSecret(req, opts)++ return this.secrets.mergeSecretSnapshot(req, opts, precondition)}-- async removeSecretKey(req: {-- name: string-- namespace?: string-- key: string- }): Promise<SecretSnapshot> {- }): Promise<SecretSummary> {-- return this.secrets.removeSecretKey(req)++ async removeSecretKey(++ req: {++ name: string++ namespace?: string++ key: string++ },++ precondition?: SecretPreconditions++ ): Promise<SecretSnapshot> {++ return this.secrets.removeSecretKeySnapshot(req, precondition)}/** `precondition` binds the delete to a specific object; see `SecretPreconditions`. */@@@ -708,6 -713,6 +725,9 @@@ export function extractHttpStatus(err:if (typeof maybe.statusCode === 'number') return maybe.statusCodeif (typeof maybe.code === 'number') return maybe.codeif (typeof maybe.code === 'string' && /^\d+$/.test(maybe.code)) return Number(maybe.code)++ if (typeof (maybe as { status?: unknown }).status === 'number') {++ return (maybe as { status: number }).status++ }// `.httpStatus` mirrors extractK8sError's chain (http/k8sError.ts): the// service-layer K8sNotFoundError/K8sConflictError expose their status only// there, so read it after code/statusCode or their 404/409 collapses to null.diff --cc control-api/src/routes/admin/registry.tsindex 7c49a851f,a477fd59c..29c791d82--- a/control-api/src/routes/admin/registry.ts+++ b/control-api/src/routes/admin/registry.ts@@@ -42,16 -41,11 +42,27 @@@ importuploadArtifacts,} from '../../services/registryClient.js'import { isRegistryAuthActive } from '../../services/registryConnectionDb.js'++import {++ REGISTRY_OPERATION_ID_ANNOTATION,++ REGISTRY_SPEC_DIGEST_ANNOTATION,++ type RegistryMutationOutcome,++ type RegistryResourceSnapshot,++ classifyCreatedRegistryMutationReadback,++ classifyRegistryAssociationReadback,++ classifyRegistryMutationReadback,++ registrySpecDigest,++} from '../../services/registryMutation.js'import {ensureRegistryPullSecret,ensureRegistryPullSecrets,platformWorkloadNamespaces,} from '../../services/registryPullSecretService.js'+import {- existingSecretAnnotationKeyReason,++ REGISTRY_SECRET_OPERATION_ID_ANNOTATION,+ invalidSecretTypeReason,+} from '../../services/secretConstraints.js'++import { findSecretReferenceState } from '../../services/secretReferenceService.js'+import { SecretSnapshot, toSecretSnapshot } from '../../services/secretRepository.js'import {validateWorkflowRecipeEgressPreflight,validateWorkflowRecipeLimits,@@@ -67,6 -61,6 +78,10 @@@ importrecipeReferencesPlatformImage,} from './registryPullSecretProvisioning.js'++const DETERMINISTIC_REGISTRY_NO_COMMIT_STATUSES = new Set([++ 400, 401, 403, 404, 405, 406, 411, 413, 415, 422,++])++/** Validate a Kubernetes resource name (RFC 1123 DNS subdomain). */function isValidK8sName(name: string): boolean {return /^[a-z0-9]([a-z0-9-]*[a-z0-9])?$/.test(name) && name.length <= 253@@@ -239,7 -233,7 +254,10 @@@ type HostGuardrailsShape =minInstalledHookTrustLevel?: stringcapabilityCeiling?: string[]}--type HostShape = { spec?: { guardrails?: HostGuardrailsShape } & Record<string, unknown> }++type HostShape = {++ metadata?: { uid?: string; resourceVersion?: string }++ spec?: { guardrails?: HostGuardrailsShape } & Record<string, unknown>++}/** The `@org` scope from an org-scoped entry name (`@org/name`), or null. */function hookOrgScope(entryName: string): string | null {@@@ -361,98 -355,14 +379,106 @@@ function hookTargetKind(target:return 'unknown'}-type SecretSnapshot = {+const REGISTRY_SECRET_WRITE_OPTIONS = { capability: 'registryCredential' } as const++/**+ * Registry upgrades must either restore a credentials Secret exactly or refuse+ * before mutating anything. Silently stripping metadata during rollback can+ * remove ownership/reconciliation state from a Secret managed by another+ * controller.+ */+function nonRestorableSecretSnapshotReason(snapshot: SecretSnapshot): string | null {+ if (invalidSecretTypeReason(snapshot.type ?? 'Opaque')) {+ return 'existing credentials Secret type is not restorable under the registry write policy'+ }- if (- Object.keys(snapshot.annotations ?? {}).some(- key => existingSecretAnnotationKeyReason(key, REGISTRY_SECRET_WRITE_OPTIONS) !== null- )- ) {- return 'existing credentials Secret contains unauthorized platform metadata'- }+ if (+ snapshot.labels?.['clerum.io/managed-by'] !== undefined &&+ snapshot.labels['clerum.io/managed-by'] !== 'control-api'+ ) {+ return 'existing credentials Secret is owned by another controller'+ }+ if (+ snapshot.labels?.['clerum.io/owner-recipe'] !== undefined ||+ snapshot.labels?.['clerum.io/recipe-secret'] !== undefined ||+ snapshot.labels?.['clerum.io/shared'] !== undefined+ ) {+ return 'existing credentials Secret is owned by a workflow recipe'+ }+ if (snapshot.ownerReferences?.length) {+ return 'existing credentials Secret has ownerReferences that the registry upgrade cannot restore'+ }+ if (snapshot.finalizers?.length) {+ return 'existing credentials Secret has finalizers that the registry upgrade cannot restore'+ }+ if (snapshot.immutable === true) {+ return 'existing credentials Secret is immutable'+ }+ if (!snapshot.uid || !snapshot.resourceVersion) {+ return 'existing credentials Secret has no complete Kubernetes identity for a safe rollback'+ }+ return null+}++function secretPreconditions(+ snapshot: Pick<SecretSnapshot, 'uid' | 'resourceVersion'>+): SecretPreconditions {++ if (!snapshot.uid || !snapshot.resourceVersion) {++ throw new RegistryInstallRollbackError()++ }+ return { uid: snapshot.uid, resourceVersion: snapshot.resourceVersion }+}+++function resourcePreconditions(snapshot: Pick<RegistryResourceSnapshot, 'metadata'>): {++ uid: string++ resourceVersion: string++} {++ const uid = snapshot.metadata?.uid++ const resourceVersion = snapshot.metadata?.resourceVersion++ if (!uid || !resourceVersion) {++ throw new RegistryInstallRollbackError()++ }++ return { uid, resourceVersion }++}+++type SafeRegistryErrorLogFields = {name: string- namespace: string- type?: string- labels?: Record<string, string>- annotations?: Record<string, string>- data?: Record<string, string>- stringData?: Record<string, string>+ status?: number+ code?: string+}++/** Return only bounded error identity fields; never place upstream messages in logs. */+export function registryErrorLogFields(err: unknown): SafeRegistryErrorLogFields {+ const candidate =+ err && typeof err === 'object'+ ? (err as {+ name?: unknown+ status?: unknown+ statusCode?: unknown+ code?: unknown+ })+ : undefined+ const rawName = err instanceof Error ? err.name : candidate?.name+ const name =+ typeof rawName === 'string' && /^[A-Za-z][A-Za-z0-9_.-]{0,63}$/.test(rawName)+ ? rawName+ : 'UnknownError'+ const rawStatus = candidate?.status ?? candidate?.statusCode+ const status =+ typeof rawStatus === 'number' &&+ Number.isInteger(rawStatus) &&+ rawStatus >= 100 &&+ rawStatus <= 599+ ? rawStatus+ : undefined+ const code =+ typeof candidate?.code === 'string' && /^[A-Za-z0-9_.:-]{1,64}$/.test(candidate.code)+ ? candidate.code+ : undefined+ return {+ name,+ ...(status === undefined ? {} : { status }),+ ...(code === undefined ? {} : { code }),+ }}type CredentialPayloadValidation =@@@ -643,7 -553,7 +669,7 @@@ async function loadRegistryCredentialScfunction auditLog(action: string, details: Record<string, unknown>): void {const safe: Record<string, unknown> = { timestamp: new Date().toISOString(), action, ...details }for (const k of ['credentials', 'clientSecret', 'stringData', 'password']) delete safe[k]-- console.log(`[AUDIT] ${JSON.stringify(safe)}`)++ log.info(safe, 'registry-audit')}/**@@@ -914,14 -823,48 +940,502 @@@ async function updateResourceWithConflithrow lastConflict}++type RegistryResourceMutationResult =++ | { outcome: 'committed'; value: unknown }++ | { outcome: 'not-committed' | 'ambiguous' | 'rejected'; error: unknown }++++/**++ * Execute one identity-bound Registry CR mutation and classify a lost response.++ *++ * Every route that changes a Registry-owned CR uses the same protocol: the++ * request carries the read UID/RV, the desired state carries an operation++ * marker and spec digest, and an ambiguous response is fenced before a++ * readback is considered. A prior-state GET alone is never promoted to++ * not-committed because the original request may still be in flight.++ */++async function executeRegistryResourceMutation(++ gateway: K8sGateway,++ plural: Parameters<K8sGateway['updateResource']>[0],++ name: string,++ namespace: string,++ body: Parameters<K8sGateway['updateResource']>[2],++ before: RegistryResourceSnapshot,++ desired: {++ spec: Record<string, unknown>++ metadata: { labels?: Record<string, string>; annotations?: Record<string, string> }++ specDigest: string++ },++ operationId: string++): Promise<RegistryResourceMutationResult> {++ try {++ return {++ outcome: 'committed',++ value: await updateResourceWithConflictRetry(gateway, plural, name, body, namespace),++ }++ } catch (error) {++ if (isDeterministicRegistryNoCommit(error)) {++ return { outcome: 'rejected', error }++ }++++ const outcome = await readRegistryMutationOutcomeAfterFence(++ gateway,++ plural,++ name,++ namespace,++ before,++ desired,++ operationId++ )++ return outcome === 'committed' ? { outcome, value: undefined } : { outcome, error }++ }++}++function normalizeSecretSnapshot(raw: unknown,fallbackName: string,fallbackNamespace: string): SecretSnapshot {- const obj = (raw ?? {}) as {- metadata?: {- name?: string- namespace?: string- labels?: Record<string, string>- annotations?: Record<string, string>+ return toSecretSnapshot(raw, fallbackName, fallbackNamespace)+}+++async function fenceSecretAtSnapshot(++ gateway: K8sGateway,++ snapshot: SecretSnapshot++): Promise<'not-committed' | 'ambiguous'> {++ try {++ const fenced = normalizeSecretSnapshot(++ await gateway.updateSecret(++ {++ name: snapshot.name,++ namespace: snapshot.namespace,++ type: snapshot.type ?? 'Opaque',++ ...(snapshot.labels ? { labels: snapshot.labels } : {}),++ ...(snapshot.annotations ? { annotations: snapshot.annotations } : {}),++ ...(snapshot.data ? { data: snapshot.data } : {}),++ ...(snapshot.stringData ? { stringData: snapshot.stringData } : {}),++ },++ secretPreconditions(snapshot),++ REGISTRY_SECRET_WRITE_OPTIONS++ ),++ snapshot.name,++ snapshot.namespace++ )++ if (fenced.uid !== snapshot.uid || !fenced.resourceVersion) return 'ambiguous'++ // The successful CAS write consumed the exact prior UID/RV. An ambiguous++ // Registry write carrying that same precondition cannot commit afterwards.++ return 'not-committed'++ } catch {++ // A rejected fence proves only that the object changed or the fence itself++ // was uncertain. The prior GET state is never promoted to no-commit.++ return 'ambiguous'++ }++}++++async function readSecretMutationOutcome(++ gateway: K8sGateway,++ snapshotBefore: SecretSnapshot | null++): Promise<{++ outcome: 'committed' | 'not-committed' | 'ambiguous'++ snapshot: SecretSnapshot | null++ identityProven: boolean++}> {++ if (snapshotBefore) {++ const fenceOutcome = await fenceSecretAtSnapshot(gateway, snapshotBefore)++ if (fenceOutcome === 'not-committed') {++ return { outcome: fenceOutcome, snapshot: null, identityProven: false }+ }- type?: unknown- data?: unknown- stringData?: unknown+ }++ // A GET after a failed fence is never a receipt of this write. The observed++ // resourceVersion may belong to a same-UID writer that raced with us, so do++ // not adopt it as a compensation precondition. The caller must preserve the++ // state and surface repair_required.++ return { outcome: 'ambiguous', snapshot: null, identityProven: false }++}++++export type CreatedSecretAfterDeleteFailure =++ | 'gone'++ | 'replaced'++ | 'modified-original'++ | 'unchanged-original'++ | 'identity-unavailable'++++/** Classify what remains under a Secret name after an identity-bound delete failed. */++export function classifyCreatedSecretAfterDeleteFailure(++ created: Pick<SecretSnapshot, 'uid' | 'resourceVersion'>,++ current: unknown | null++): CreatedSecretAfterDeleteFailure {++ if (current === null) return 'gone'++ if (!created.uid || !created.resourceVersion) return 'identity-unavailable'++ const metadata = (current as { metadata?: { uid?: unknown; resourceVersion?: unknown } }).metadata++ if (typeof metadata?.uid !== 'string' || typeof metadata.resourceVersion !== 'string') {++ return 'identity-unavailable'++ }++ if (metadata.uid !== created.uid) return 'replaced'++ if (metadata.resourceVersion !== created.resourceVersion) return 'modified-original'++ return 'unchanged-original'++}++++class RegistryInstallRollbackError extends Error {++ readonly code = 'registry_install_rollback_incomplete'++ readonly status = 500++++ constructor() {++ super('registry install rollback could not be completed without risking another writer')++ this.name = 'RegistryInstallRollbackError'++ }++}++++async function readSecretForRollback(++ gateway: K8sGateway,++ snapshot: SecretSnapshot++): Promise<unknown | null> {++ try {++ return await gateway.getSecret(snapshot.name, snapshot.namespace)++ } catch (err) {++ if (extractK8sError(err)?.status === 404) return null++ throw new RegistryInstallRollbackError()++ }++}++++async function waitForSecretDeletionOrReplacement(++ gateway: K8sGateway,++ snapshot: SecretSnapshot,++ timeoutMs = DELETE_SETTLE_TIMEOUT_MS,++ pollMs = DELETE_SETTLE_POLL_MS++): Promise<void> {++ const deadline = Date.now() + timeoutMs++ while (Date.now() <= deadline) {++ const current = await readSecretForRollback(gateway, snapshot)++ const outcome = classifyCreatedSecretAfterDeleteFailure(snapshot, current)++ if (outcome === 'gone' || outcome === 'replaced') return++ if (outcome !== 'unchanged-original') throw new RegistryInstallRollbackError()++ await sleep(pollMs)++ }++ throw new RegistryInstallRollbackError()++}+++type CreatedResourceAfterDeleteFailure =++ | 'gone'++ | 'replaced'++ | 'modified-original'++ | 'unchanged-original'++ | 'identity-unavailable'++++function normalizeRegistryResourceSnapshot(++ raw: unknown,++ fallbackName: string,++ fallbackNamespace: string++): RegistryResourceSnapshot {++ const source = (raw ?? {}) as RegistryResourceSnapshot++ const metadata = source.metadata+ return {- name:- typeof obj.metadata?.name === 'string' && obj.metadata.name.trim()- ? obj.metadata.name- : fallbackName,- namespace:- typeof obj.metadata?.namespace === 'string' && obj.metadata.namespace.trim()- ? obj.metadata.namespace- : fallbackNamespace,- ...(typeof obj.type === 'string' ? { type: obj.type } : {}),- ...(obj.metadata?.labels && typeof obj.metadata.labels === 'object'- ? { labels: obj.metadata.labels }- : {}),- ...(obj.metadata?.annotations && typeof obj.metadata.annotations === 'object'- ? { annotations: obj.metadata.annotations }- : {}),- ...(obj.data && typeof obj.data === 'object'- ? { data: obj.data as Record<string, string> }- : {}),- ...(obj.stringData && typeof obj.stringData === 'object'- ? { stringData: obj.stringData as Record<string, string> }- : {}),++ metadata: {++ ...(typeof metadata?.uid === 'string' ? { uid: metadata.uid } : {}),++ ...(typeof metadata?.resourceVersion === 'string'++ ? { resourceVersion: metadata.resourceVersion }++ : {}),++ ...(metadata?.labels ? { labels: metadata.labels } : {}),++ ...(metadata?.annotations ? { annotations: metadata.annotations } : {}),++ // Keep these fallbacks local to the rollback record. The gateway's++ // delete call receives only identity preconditions, never a caller name++ // that could be mistaken for identity.++ ...(fallbackName ? { name: fallbackName } : {}),++ ...(fallbackNamespace ? { namespace: fallbackNamespace } : {}),++ } as RegistryResourceSnapshot['metadata'],++ spec: source.spec ?? {},++ }++}++++function classifyCreatedResourceAfterDeleteFailure(++ created: RegistryResourceSnapshot,++ current: RegistryResourceSnapshot | null++): CreatedResourceAfterDeleteFailure {++ if (current === null) return 'gone'++ const createdUid = created.metadata?.uid++ const createdResourceVersion = created.metadata?.resourceVersion++ const currentUid = current.metadata?.uid++ const currentResourceVersion = current.metadata?.resourceVersion++ if (++ typeof createdUid !== 'string' ||++ typeof createdResourceVersion !== 'string' ||++ typeof currentUid !== 'string' ||++ typeof currentResourceVersion !== 'string'++ ) {++ return 'identity-unavailable'++ }++ if (currentUid !== createdUid) return 'replaced'++ if (currentResourceVersion !== createdResourceVersion) return 'modified-original'++ return 'unchanged-original'++}++++async function readResourceForRollback(++ gateway: K8sGateway,++ plural: Parameters<K8sGateway['getResource']>[0],++ snapshot: RegistryResourceSnapshot++): Promise<RegistryResourceSnapshot | null> {++ const name = (snapshot.metadata as { name?: string } | undefined)?.name++ const namespace = (snapshot.metadata as { namespace?: string } | undefined)?.namespace++ if (!name || !namespace) throw new RegistryInstallRollbackError()++ try {++ const current = await gateway.getResource(plural, name, namespace)++ return normalizeRegistryResourceSnapshot(current, name, namespace)++ } catch (err) {++ if (extractK8sError(err)?.status === 404) return null++ throw new RegistryInstallRollbackError()++ }++}++++type CreatedResourceReadbackOutcome = {++ outcome: 'committed' | 'not-committed' | 'ambiguous'++ snapshot: RegistryResourceSnapshot | null++}++++async function readCreatedResourceOutcome(++ gateway: K8sGateway,++ plural: Parameters<K8sGateway['getResource']>[0],++ name: string,++ namespace: string,++ desired: {++ spec: Record<string, unknown>++ metadata: { labels?: Record<string, string>; annotations?: Record<string, string> }++ specDigest: string++ },++ operationId: string++): Promise<CreatedResourceReadbackOutcome> {++ for (let attempt = 1; attempt <= 3; attempt += 1) {++ try {++ const current = normalizeRegistryResourceSnapshot(++ await gateway.getResource(plural, name, namespace),++ name,++ namespace++ )++ if (++ classifyCreatedRegistryMutationReadback({ current, desired, operationId }) === 'committed'++ ) {++ return { outcome: 'committed', snapshot: current }++ }++ } catch {++ // A failed read cannot prove that a create did not commit. This includes++ // repeated 404s: the original request may still be in flight or the++ // read path may be stale, and a create has no pre-write UID/RV fence.++ }++ if (attempt < 3) await sleep(UPDATE_CONFLICT_RETRY_DELAY_MS * attempt)++ }++ return { outcome: 'ambiguous', snapshot: null }++}++++async function fenceRegistryResourceAtSnapshot(++ gateway: K8sGateway,++ plural: Parameters<K8sGateway['getResource']>[0],++ name: string,++ namespace: string,++ snapshot: RegistryResourceSnapshot++): Promise<'not-committed' | 'ambiguous'> {++ const uid = snapshot.metadata?.uid++ const resourceVersion = snapshot.metadata?.resourceVersion++ if (!uid || !resourceVersion) return 'ambiguous'++++ try {++ const fenced = normalizeRegistryResourceSnapshot(++ await gateway.updateResource(++ plural,++ name,++ {++ metadata: {++ uid,++ resourceVersion,++ ...(snapshot.metadata?.labels ? { labels: snapshot.metadata.labels } : {}),++ ...(snapshot.metadata?.annotations++ ? { annotations: snapshot.metadata.annotations }++ : {}),++ },++ spec: snapshot.spec ?? {},++ },++ namespace++ ),++ name,++ namespace++ )++ if (fenced.metadata?.uid !== uid || typeof fenced.metadata?.resourceVersion !== 'string') {++ return 'ambiguous'++ }++ // A successful replacement fenced the old UID/RV. Any in-flight Registry++ // write carrying that same precondition can no longer commit afterwards.++ return 'not-committed'++ } catch {++ // A rejected fence means the object changed, but does not identify whether++ // this operation or another writer won. The caller must read and classify++ // the current state; the prior state alone is never proof of no-commit.++ return 'ambiguous'++ }++}++++async function readRegistryAssociationOutcome(++ gateway: K8sGateway,++ plural: Parameters<K8sGateway['getResource']>[0],++ name: string,++ namespace: string,++ before: RegistryResourceSnapshot,++ isCommitted: (spec: Record<string, unknown>) => boolean++): Promise<RegistryMutationOutcome> {++ const fenceOutcome = await fenceRegistryResourceAtSnapshot(++ gateway,++ plural,++ name,++ namespace,++ before++ )++ if (fenceOutcome === 'not-committed') return fenceOutcome++++ for (let attempt = 1; attempt <= 3; attempt += 1) {++ try {++ const current = normalizeRegistryResourceSnapshot(++ await gateway.getResource(plural, name, namespace),++ name,++ namespace++ )++ const outcome = classifyRegistryAssociationReadback({ before, current, isCommitted })++ if (outcome === 'committed') return outcome++ } catch {++ // A failed read cannot prove either terminal state.++ }++ if (attempt < 3) await sleep(UPDATE_CONFLICT_RETRY_DELAY_MS * attempt)++ }++ // A prior-state read is only a candidate. Without a successful fence, it++ // cannot prove that the original request is no longer in flight.++ return 'ambiguous'++}++++async function readRegistryMutationOutcomeAfterFence(++ gateway: K8sGateway,++ plural: Parameters<K8sGateway['getResource']>[0],++ name: string,++ namespace: string,++ before: RegistryResourceSnapshot,++ desired: {++ spec: Record<string, unknown>++ metadata: { labels?: Record<string, string>; annotations?: Record<string, string> }++ specDigest: string++ },++ operationId: string++): Promise<RegistryMutationOutcome> {++ const fenceOutcome = await fenceRegistryResourceAtSnapshot(++ gateway,++ plural,++ name,++ namespace,++ before++ )++ if (fenceOutcome === 'not-committed') return fenceOutcome++++ for (let attempt = 1; attempt <= 3; attempt += 1) {++ try {++ const current = normalizeRegistryResourceSnapshot(++ await gateway.getResource(plural, name, namespace),++ name,++ namespace++ )++ const outcome = classifyRegistryMutationReadback({++ before,++ desired,++ current,++ operationId,++ })++ if (outcome === 'committed') return outcome++ } catch {++ // A failed read cannot prove either terminal state.++ }++ if (attempt < 3) await sleep(UPDATE_CONFLICT_RETRY_DELAY_MS * attempt)++ }++ // Only the desired state proves this operation's commit after the fence++ // lost its race. A prior-state read is deliberately not promoted to++ // not-committed because the original request may still be in flight.++ return 'ambiguous'++}++++function isDeterministicRegistryNoCommit(err: unknown): boolean {++ const status = extractK8sError(err)?.status++ // Only statuses whose Kubernetes API contract rejects the request before++ // admission are safe to treat as no-commit. Conflict, timeout, and throttling++ // responses can race with a live object or an already accepted request and++ // therefore must go through the identity fence/readback path.++ return typeof status === 'number' && DETERMINISTIC_REGISTRY_NO_COMMIT_STATUSES.has(status)++}++++async function waitForResourceDeletionOrReplacement(++ gateway: K8sGateway,++ plural: Parameters<K8sGateway['getResource']>[0],++ snapshot: RegistryResourceSnapshot,++ label: string,++ timeoutMs = DELETE_SETTLE_TIMEOUT_MS,++ pollMs = DELETE_SETTLE_POLL_MS++): Promise<'gone' | 'replaced'> {++ const deadline = Date.now() + timeoutMs++ while (Date.now() <= deadline) {++ const current = await readResourceForRollback(gateway, plural, snapshot)++ const outcome = classifyCreatedResourceAfterDeleteFailure(snapshot, current)++ if (outcome === 'gone' || outcome === 'replaced') return outcome++ if (outcome !== 'unchanged-original') throw new RegistryInstallRollbackError()++ await sleep(pollMs)++ }++ throw new RegistryInstallRollbackError()++}++++/** Delete only the CR created by this saga; never fall back to name-only delete. */++async function rollbackCreatedResource(++ gateway: K8sGateway,++ plural: Parameters<K8sGateway['deleteResource']>[0],++ snapshot: RegistryResourceSnapshot,++ label: string++): Promise<void> {++ const name = (snapshot.metadata as { name?: string } | undefined)?.name++ const namespace = (snapshot.metadata as { namespace?: string } | undefined)?.namespace++ if (!name || !namespace) throw new RegistryInstallRollbackError()++++ for (let attempt = 1; attempt <= 2; attempt += 1) {++ try {++ await gateway.deleteResource(plural, name, namespace, resourcePreconditions(snapshot))++ const settled = await waitForResourceDeletionOrReplacement(gateway, plural, snapshot, label)++ if (settled === 'replaced') throw new RegistryInstallRollbackError()++ return++ } catch (err) {++ if (err instanceof RegistryInstallRollbackError) throw err++ const current = await readResourceForRollback(gateway, plural, snapshot)++ const outcome = classifyCreatedResourceAfterDeleteFailure(snapshot, current)++ if (outcome === 'gone') return++ if (outcome === 'replaced') throw new RegistryInstallRollbackError()++ if (outcome === 'unchanged-original' && attempt < 2) continue++ throw new RegistryInstallRollbackError()++ }++ }++ throw new RegistryInstallRollbackError()++}++++/** Delete only the Secret object created by this saga; never fall back to name-only delete. */++async function rollbackCreatedSecret(gateway: K8sGateway, snapshot: SecretSnapshot): Promise<void> {++ // A Secret is a cross-resource dependency. If any live consumer is visible,++ // or the reference graph cannot be read completely, preserve it for repair;++ // a name-only compensation decision is not safe across independent CRDs.++ const referenceState = await findSecretReferenceState(gateway, snapshot.name, snapshot.namespace)++ if (referenceState !== 'not-referenced') return++++ for (let attempt = 1; attempt <= 2; attempt += 1) {++ try {++ await gateway.deleteSecret(snapshot.name, snapshot.namespace, secretPreconditions(snapshot))++ await waitForSecretDeletionOrReplacement(gateway, snapshot)++ return++ } catch (err) {++ if (err instanceof RegistryInstallRollbackError) throw err++ const current = await readSecretForRollback(gateway, snapshot)++ const outcome = classifyCreatedSecretAfterDeleteFailure(snapshot, current)++ if (outcome === 'gone' || outcome === 'replaced') return++ if (outcome === 'unchanged-original' && attempt < 2) continue++ throw new RegistryInstallRollbackError()++ }+ }++ throw new RegistryInstallRollbackError()+ }+async function waitForDeletion(readCurrent: () => Promise<unknown>,label: string,@@@ -1508,10 -1449,10 +2022,17 @@@ export function createAdminRegistryRout'clerum.io/managed-by': 'control-api','clerum.io/server-mode': isLocal ? 'local' : 'remote',}-- const registryAnnotations: Record<string, string> = catalogAnnotations(-- body.registryEntryName,-- body.registryEntryVersion-- )++ const resourceOperationId = crypto.randomUUID()++ const registryAnnotations: Record<string, string> = {++ ...catalogAnnotations(body.registryEntryName, body.registryEntryVersion),++ [REGISTRY_OPERATION_ID_ANNOTATION]: resourceOperationId,++ [REGISTRY_SPEC_DIGEST_ANNOTATION]: registrySpecDigest(mcpServerSpec),++ }++ const credentialOperationId = crypto.randomUUID()++ const credentialAnnotations = {++ ...catalogAnnotations(body.registryEntryName, body.registryEntryVersion),++ [REGISTRY_SECRET_OPERATION_ID_ANNOTATION]: credentialOperationId,++ }// ── Ensure the shared registry pull secret (self-hosted) ───────────// Must run when a private evenfire-hosted image is in play — independent of@@@ -1530,7 -1471,7 +2051,8 @@@}// ── Step 3: Create K8s Secret if credentials provided ─────────────-- let secretCreated = false++ let createdSecretSnapshot: SecretSnapshot | null = null++ let createdSecretIdentityProven = falseif (credRequired) {const secretData = credentialPayload.secretDataif (Object.keys(secretData).length > 0) {@@@ -1539,22 -1480,22 +2061,51 @@@namespace: targetNs,type: 'Opaque',labels: registryLabels,-- annotations: registryAnnotations,++ annotations: credentialAnnotations,stringData: secretData,}try {- await gateway.createSecret(secretReq, { capability: 'registryCredential' })- await gateway.createSecret(secretReq)++ createdSecretSnapshot = await gateway.createSecret(secretReq, {++ capability: 'registryCredential',++ })++ createdSecretIdentityProven = true} catch (err) {const k8sErr = extractK8sError(err)-- if (k8sErr) {++ if (k8sErr && k8sErr.status < 500) {res.status(k8sErr.status).json({ error: `Secret creation failed: ${k8sErr.message}` })return}-- throw err++ const recovered = await readSecretMutationOutcome(gateway, null)++ if (recovered.outcome === 'not-committed') {++ res.status(503).json({++ error: 'registry_secret_outcome_not_committed',++ outcome: 'not_committed',++ })++ return++ }++ if (recovered.outcome !== 'committed' || !recovered.snapshot) {++ res.status(503).json({++ error: 'registry_secret_outcome_ambiguous',++ outcome: 'repair_required',++ })++ return++ }++ if (!recovered.identityProven) {++ // A create has no pre-write UID to compare against. The++ // readback may be a same-name replacement that copied the++ // operation marker, so it cannot be reported as this request's++ // commit or used as a compensation target.++ res.status(503).json({++ error: 'registry_secret_outcome_ambiguous',++ outcome: 'repair_required',++ })++ return++ }++ createdSecretSnapshot = recovered.snapshot++ createdSecretIdentityProven = recovered.identityProven}-- secretCreated = trueauditLog('secret_created', {secretName,namespace: targetNs,@@@ -1564,9 -1505,9 +2115,16 @@@}}-- // ── Step 4: Create McpServer CRD (rollback Secret on failure) ─────++ // ── Step 4: Create McpServer CRD (rollback by UID on failure) ────++ let createdMcpServerSnapshot: RegistryResourceSnapshot | null = null++ let createdMcpServerIdentityProven = false++ const desiredMcpServerMutation = {++ spec: mcpServerSpec,++ metadata: { labels: registryLabels, annotations: registryAnnotations },++ specDigest: registrySpecDigest(mcpServerSpec),++ }try {-- await gateway.createResource(++ const created = await gateway.createResource('mcpservers',{metadata: {@@@ -1578,39 -1519,39 +2136,153 @@@},targetNs)-- } catch (err) {-- // Rollback: delete the Secret if we created one-- if (secretCreated) {-- try {-- await gateway.deleteSecret(secretName, targetNs)-- } catch {-- // Best-effort rollback; log but do not mask the original error-- }++ createdMcpServerSnapshot = normalizeRegistryResourceSnapshot(++ created,++ serverName,++ targetNs++ )++ if (++ !createdMcpServerSnapshot.metadata?.uid ||++ !createdMcpServerSnapshot.metadata.resourceVersion++ ) {++ throw new RegistryInstallRollbackError()}++ createdMcpServerIdentityProven = true++ } catch (err) {const k8sErr = extractK8sError(err)-- if (k8sErr) {-- res.status(k8sErr.status).json({ error: k8sErr.message })++ const ambiguousCreate =++ err instanceof RegistryInstallRollbackError || !k8sErr || k8sErr.status >= 500++ if (ambiguousCreate) {++ const recovered = await readCreatedResourceOutcome(++ gateway,++ 'mcpservers',++ serverName,++ targetNs,++ desiredMcpServerMutation,++ resourceOperationId++ )++ if (recovered.outcome === 'not-committed') {++ if (createdSecretSnapshot && !createdSecretIdentityProven) {++ res.status(503).json({++ error: 'registry_install_outcome_ambiguous',++ outcome: 'repair_required',++ })++ return++ }++ let rollbackFailed = false++ if (createdSecretSnapshot) {++ try {++ await rollbackCreatedSecret(gateway, createdSecretSnapshot)++ } catch {++ rollbackFailed = true++ }++ }++ if (rollbackFailed) {++ res.status(500).json({++ error: 'registry_install_rollback_incomplete',++ outcome: 'compensation_failed',++ })++ return++ }++ res.status(k8sErr?.status ?? 503).json({++ error: 'registry_resource_outcome_not_committed',++ outcome: 'not_committed',++ })++ return++ }++ if (recovered.outcome !== 'committed' || !recovered.snapshot) {++ res.status(503).json({++ error: 'registry_resource_outcome_ambiguous',++ outcome: 'repair_required',++ })++ return++ }++ // A create readback has no pre-write UID to compare with. Even a++ // perfect operation marker/spec match can belong to a same-name++ // replacement that copied the mutable intent. It is safe to leave++ // the observed object for repair, but not to report it as this++ // request's commit or to make it compensable.++ res.status(503).json({++ error: 'registry_resource_outcome_ambiguous',++ outcome: 'repair_required',++ })return++ } else {++ // A conflict, timeout, or throttling response is not a proof that++ // the named CR is absent. It may identify a live CR or follow an++ // accepted create, so preserve the Secret for repair instead of++ // deleting a dependency we cannot disassociate atomically.++ if (!isDeterministicRegistryNoCommit(err)) {++ res.status(503).json({++ error: 'registry_resource_outcome_ambiguous',++ outcome: 'repair_required',++ })++ return++ }++++ // A deterministic create rejection proves there is no CR to++ // compensate; only the earlier credential object needs rollback.++ if (createdSecretSnapshot && !createdSecretIdentityProven) {++ res.status(503).json({++ error: 'registry_install_outcome_ambiguous',++ outcome: 'repair_required',++ })++ return++ }++ let rollbackFailed = false++ if (createdSecretSnapshot) {++ try {++ await rollbackCreatedSecret(gateway, createdSecretSnapshot)++ } catch {++ rollbackFailed = true++ }++ }++ if (rollbackFailed) {++ res.status(500).json({++ error: 'registry_install_rollback_incomplete',++ outcome: 'compensation_failed',++ })++ return++ }++ if (k8sErr) {++ res.status(k8sErr.status).json({ error: k8sErr.message })++ return++ }++ throw err}-- throw err}// ── Step 5: Update Context allowlist ──────────────────────────────// The Context allowlist is authoritative for host discovery. If this// step fails, the McpServer exists but is unreachable, so the install// must roll back rather than return a false success.++ let contextBefore: RegistryResourceSnapshot | null = nulltry {const ctx = (await gateway.getResource('contexts', contextRef)) as {++ metadata?: { uid?: string; resourceVersion?: string }spec?: Record<string, unknown> & {contextId?: stringdescription?: stringmcpServers?: string[]}}++ contextBefore = normalizeRegistryResourceSnapshot(ctx, contextRef, targetNs)++ if (!contextBefore.metadata?.uid || !contextBefore.metadata.resourceVersion) {++ throw Object.assign(new Error('Context identity is unavailable'), {++ statusCode: 503,++ code: 'context_identity_unavailable',++ })++ }const existing: string[] = ctx.spec?.mcpServers ?? []if (!existing.includes(serverName)) {await gateway.updateResource('contexts', contextRef, {- spec: {++ metadata: {++ uid: contextBefore.metadata.uid,++ ...(ctx.metadata?.resourceVersion++ ? { resourceVersion: ctx.metadata.resourceVersion }++ : {}),++ },+ spec: {...ctx.spec,contextId: ctx.spec?.contextId ?? contextRef,mcpServers: [...existing, serverName],@@@ -1618,43 -1559,43 +2290,89 @@@})}} catch (err) {-- try {-- await gateway.deleteResource('mcpservers', serverName, targetNs)-- await waitForDeletion(-- () => gateway.getResource('mcpservers', serverName, targetNs),-- `McpServer/${serverName}`++ let associationOutcome: RegistryMutationOutcome = isDeterministicRegistryNoCommit(err)++ ? 'not-committed'++ : 'ambiguous'++ if (contextBefore && associationOutcome === 'ambiguous') {++ associationOutcome = await readRegistryAssociationOutcome(++ gateway,++ 'contexts',++ contextRef,++ targetNs,++ contextBefore,++ spec =>++ Array.isArray(spec.mcpServers) &&++ (spec.mcpServers as unknown[]).includes(serverName))-- } catch {-- // Best-effort rollback; preserve the original context-update error.}-- if (secretCreated) {-- try {-- await gateway.deleteSecret(secretName, targetNs)-- await waitForDeletion(-- () => gateway.getSecret(secretName, targetNs),-- `Secret/${secretName}`-- )-- } catch {-- // Best-effort rollback; preserve the original context-update error.- }++ if (contextBefore && associationOutcome === 'ambiguous') {++ res.status(503).json({++ error: 'registry_install_outcome_ambiguous',++ outcome: 'repair_required',++ })++ return+ }- const k8sErr = extractK8sError(err)- const message =- k8sErr?.message ||- (err instanceof Error ? err.message : 'Failed to update Context allowlist')- res- .status(k8sErr?.status ?? 500)- .json({ error: `Context allowlist update failed: ${message}` })- return- }-- // ── Step 6: Report install to registry (fire-and-forget) ──────────- const correlationId = crypto.randomUUID()- reportInstall(body.registryEntryName, correlationId, body.registryEntryVersion).catch(- () => {}- )-- res.status(201).json({++ if (associationOutcome !== 'committed') {++ if (++ (createdMcpServerSnapshot && !createdMcpServerIdentityProven) ||++ (createdSecretSnapshot && !createdSecretIdentityProven)++ ) {++ res.status(503).json({++ error: 'registry_install_outcome_ambiguous',++ outcome: 'repair_required',++ })++ return++ }++ let resourceRollbackFailed = false++ if (createdMcpServerSnapshot) {++ try {++ await rollbackCreatedResource(++ gateway,++ 'mcpservers',++ createdMcpServerSnapshot,++ `McpServer/${serverName}`++ )++ } catch {++ resourceRollbackFailed = true++ }++ }++ if (resourceRollbackFailed) {++ res.status(500).json({++ error: 'registry_install_rollback_incomplete',++ outcome: 'compensation_failed',++ })++ return++ }++ if (createdSecretSnapshot) {++ // The CR was live during this saga. There is no Kubernetes++ // transaction that atomically proves its absence and deletes a++ // separately named Secret. Preserve the dependency for repair;++ // deleting it after the CR rollback would permit a replacement++ // CR to race into the same name and reference.++ res.status(500).json({++ error: 'registry_install_rollback_incomplete',++ outcome: 'compensation_failed',++ })++ return+ }++ const k8sErr = extractK8sError(err)++ const message =++ k8sErr?.message ||++ (err instanceof Error ? err.message : 'Failed to update Context allowlist')++ res++ .status(k8sErr?.status ?? 500)++ .json({ error: `Context allowlist update failed: ${message}` })++ return+ }- const k8sErr = extractK8sError(err)- const message =- k8sErr?.message ||- (err instanceof Error ? err.message : 'Failed to update Context allowlist')- res- .status(k8sErr?.status ?? 500)- .json({ error: `Context allowlist update failed: ${message}` })- return+ }++ // ── Step 6: Report install to registry (fire-and-forget) ──────────+ const correlationId = crypto.randomUUID()+ reportInstall(body.registryEntryName, correlationId, body.registryEntryVersion).catch(+ () => {}+ )++ res.status(201).json({serverName,namespace: targetNs,contextRef,@@@ -1950,12 -1891,12 +2668,21 @@@// Step 3 — load target Host + its guardrails policy.let host: HostShape++ let hostBefore: RegistryResourceSnapshot | null = nulltry {host = (await gateway.getResource('hosts',body.hostRef,config.hostsNamespace)) as HostShape++ hostBefore = normalizeRegistryResourceSnapshot(host, body.hostRef, config.hostsNamespace)++ if (!hostBefore.metadata?.uid || !hostBefore.metadata.resourceVersion) {++ res.status(503).json({++ error: 'registry_install_outcome_ambiguous',++ outcome: 'repair_required',++ })++ return++ }} catch (err) {const k8sErr = extractK8sError(err)res.status(k8sErr?.status ?? 404).json({ error: `Host "${body.hostRef}" not found` })@@@ -2029,10 -1970,10 +2756,17 @@@}const registryLabels: Record<string, string> = { 'clerum.io/managed-by': 'control-api' }++ const resourceOperationId = crypto.randomUUID()const registryAnnotations: Record<string, string> = {...catalogAnnotations(body.registryEntryName, body.registryEntryVersion),// §8.4 stamp — platform-assigned, author cannot set it.'clerum.io/trust-level': trustLevel,++ [REGISTRY_OPERATION_ID_ANNOTATION]: resourceOperationId,++ }++ const credentialOperationId = crypto.randomUUID()++ const credentialAnnotations = {++ ...catalogAnnotations(body.registryEntryName, body.registryEntryVersion),++ [REGISTRY_SECRET_OPERATION_ID_ANNOTATION]: credentialOperationId,}// Step 8 — credential Secret from the hook's credentialSchema.@@@ -2057,6 -1998,6 +2791,8 @@@const credentials = body.credentials ?? {}const secretName = `${crName}-creds`let secretCreated = false++ let createdSecretIdentityProven = false++ let createdSecretSnapshot: SecretSnapshot | null = nullif (Object.keys(credentials).length > 0) {const schemaKeys = new Set((credSchema?.keys ?? []).map(k => k.name))const unknownKeys = Object.keys(credentials).filter(@@@ -2069,24 -2010,21 +2805,51 @@@return}try {- await gateway.createSecret(- await gateway.createSecret({- name: secretName,- namespace: targetNs,- type: 'Opaque',- labels: registryLabels,- annotations: registryAnnotations,- stringData: credentials,- })++ createdSecretSnapshot = await gateway.createSecret(+ {+ name: secretName,+ namespace: targetNs,+ type: 'Opaque',+ labels: registryLabels,- annotations: registryAnnotations,++ annotations: credentialAnnotations,+ stringData: credentials,+ },+ REGISTRY_SECRET_WRITE_OPTIONS+ )++ createdSecretIdentityProven = true} catch (err) {const k8sErr = extractK8sError(err)-- if (k8sErr) {++ if (k8sErr && k8sErr.status < 500) {res.status(k8sErr.status).json({ error: `Secret creation failed: ${k8sErr.message}` })return}-- throw err++ const recovered = await readSecretMutationOutcome(gateway, null)++ if (recovered.outcome === 'not-committed') {++ res.status(503).json({++ error: 'registry_secret_outcome_not_committed',++ outcome: 'not_committed',++ })++ return++ }++ if (recovered.outcome !== 'committed' || !recovered.snapshot) {++ res.status(503).json({++ error: 'registry_secret_outcome_ambiguous',++ outcome: 'repair_required',++ })++ return++ }++ if (!recovered.identityProven) {++ // A create readback cannot prove the UID was issued for this++ // request. Leave the object for repair rather than treating it++ // as a successful, compensable install.++ res.status(503).json({++ error: 'registry_secret_outcome_ambiguous',++ outcome: 'repair_required',++ })++ return++ }++ createdSecretSnapshot = recovered.snapshot++ createdSecretIdentityProven = recovered.identityProven}secretCreated = true}@@@ -2102,8 -2040,8 +2865,23 @@@try {await ensureRegistryPullSecret(gateway, targetNs)} catch (err) {-- if (secretCreated) {-- await gateway.deleteSecret(secretName, targetNs).catch(() => {})++ if (secretCreated && !createdSecretIdentityProven) {++ res.status(503).json({++ error: 'registry_install_outcome_ambiguous',++ outcome: 'repair_required',++ })++ return++ }++ if (secretCreated && createdSecretSnapshot) {++ try {++ await rollbackCreatedSecret(gateway, createdSecretSnapshot)++ } catch {++ res.status(500).json({++ error: 'registry_install_rollback_incomplete',++ outcome: 'compensation_failed',++ })++ return++ }}const mapped = pullSecretErrorResponse(err)res.status(mapped.status).json(mapped.body)@@@ -2139,9 -2077,9 +2917,17 @@@...(capabilities.length > 0 ? { capabilities } : {}),...(hookMeta.defaultConfig ? { config: hookMeta.defaultConfig } : {}),}--++ registryAnnotations[REGISTRY_SPEC_DIGEST_ANNOTATION] = registrySpecDigest(hookSpec)++++ let createdHookSnapshot: RegistryResourceSnapshot | null = null++ let createdHookIdentityProven = false++ const desiredHookMutation = {++ spec: hookSpec,++ metadata: { labels: registryLabels, annotations: registryAnnotations },++ specDigest: registrySpecDigest(hookSpec),++ }try {-- await gateway.createResource(++ const created = await gateway.createResource('llmhooks',{metadata: { name: crName, labels: registryLabels, annotations: registryAnnotations },@@@ -2149,16 -2087,16 +2935,108 @@@},targetNs)-- } catch (err) {-- if (secretCreated) {-- await gateway.deleteSecret(secretName, targetNs).catch(() => {})++ createdHookSnapshot = normalizeRegistryResourceSnapshot(created, crName, targetNs)++ if (!createdHookSnapshot.metadata?.uid || !createdHookSnapshot.metadata.resourceVersion) {++ throw new RegistryInstallRollbackError()}++ createdHookIdentityProven = true++ } catch (err) {const k8sErr = extractK8sError(err)-- if (k8sErr) {-- res.status(k8sErr.status).json({ error: k8sErr.message })++ const ambiguousCreate =++ err instanceof RegistryInstallRollbackError || !k8sErr || k8sErr.status >= 500++ if (ambiguousCreate) {++ const recovered = await readCreatedResourceOutcome(++ gateway,++ 'llmhooks',++ crName,++ targetNs,++ desiredHookMutation,++ resourceOperationId++ )++ if (recovered.outcome === 'not-committed') {++ if (secretCreated && !createdSecretIdentityProven) {++ res.status(503).json({++ error: 'registry_install_outcome_ambiguous',++ outcome: 'repair_required',++ })++ return++ }++ let rollbackFailed = false++ if (secretCreated && createdSecretSnapshot) {++ try {++ await rollbackCreatedSecret(gateway, createdSecretSnapshot)++ } catch {++ rollbackFailed = true++ }++ }++ if (rollbackFailed) {++ res.status(500).json({++ error: 'registry_install_rollback_incomplete',++ outcome: 'compensation_failed',++ })++ return++ }++ res.status(k8sErr?.status ?? 503).json({++ error: 'registry_resource_outcome_not_committed',++ outcome: 'not_committed',++ })++ return++ }++ if (recovered.outcome !== 'committed' || !recovered.snapshot) {++ res.status(503).json({++ error: 'registry_resource_outcome_ambiguous',++ outcome: 'repair_required',++ })++ return++ }++ // A create readback cannot prove that the observed UID was issued++ // for this request. Do not turn a mutable marker/spec match into a++ // successful install or a later compensation target.++ res.status(503).json({++ error: 'registry_resource_outcome_ambiguous',++ outcome: 'repair_required',++ })return++ } else {++ // A conflict, timeout, or throttling response is not a proof that++ // the named hook is absent. Preserve its Secret for repair because++ // no cross-resource transaction can prove dependency safety.++ if (!isDeterministicRegistryNoCommit(err)) {++ res.status(503).json({++ error: 'registry_resource_outcome_ambiguous',++ outcome: 'repair_required',++ })++ return++ }++++ if (secretCreated && !createdSecretIdentityProven) {++ res.status(503).json({++ error: 'registry_install_outcome_ambiguous',++ outcome: 'repair_required',++ })++ return++ }++ let rollbackFailed = false++ if (secretCreated && createdSecretSnapshot) {++ try {++ await rollbackCreatedSecret(gateway, createdSecretSnapshot)++ } catch {++ rollbackFailed = true++ }++ }++ if (rollbackFailed) {++ res.status(500).json({++ error: 'registry_install_rollback_incomplete',++ outcome: 'compensation_failed',++ })++ return++ }++ if (k8sErr) {++ res.status(k8sErr.status).json({ error: k8sErr.message })++ return++ }++ throw err}-- throw err}// Step 10 — reference the hook from Host.spec.guardrails.hooks[phase] as@@@ -2184,34 -2122,34 +3062,93 @@@config.hostsNamespace)} catch (err) {-- try {-- await gateway.deleteResource('llmhooks', crName, targetNs)-- await waitForDeletion(-- () => gateway.getResource('llmhooks', crName, targetNs),-- `LlmHook/${crName}`-- )-- } catch {-- // Best-effort rollback; preserve the original Host-update error.++ const associationOutcome = isDeterministicRegistryNoCommit(err)++ ? 'not-committed'++ : hostBefore++ ? await readRegistryAssociationOutcome(++ gateway,++ 'hosts',++ body.hostRef,++ config.hostsNamespace,++ hostBefore,++ spec => {++ const hooks = ((++ spec.guardrails as { hooks?: Record<string, unknown> } | undefined++ )?.hooks ?? {}) as Record<string, unknown>++ return hookMeta.lifecyclePoints.every(phase => {++ const refs = hooks[phase]++ return (++ Array.isArray(refs) &&++ refs.some(ref => {++ if (!ref || typeof ref !== 'object') return false++ const candidate = ref as { id?: unknown; digest?: unknown }++ return (++ candidate.id === crName &&++ (digest === undefined || candidate.digest === digest)++ )++ })++ )++ })++ }++ )++ : 'ambiguous'++ if (associationOutcome === 'ambiguous') {++ res.status(503).json({++ error: 'registry_install_outcome_ambiguous',++ outcome: 'repair_required',++ })++ return}-- if (secretCreated) {-- try {-- await gateway.deleteSecret(secretName, targetNs)-- await waitForDeletion(-- () => gateway.getSecret(secretName, targetNs),-- `Secret/${secretName}`-- )-- } catch {-- // Best-effort rollback; preserve the original Host-update error.++ if (associationOutcome !== 'committed') {++ if (++ (createdHookSnapshot && !createdHookIdentityProven) ||++ (secretCreated && createdSecretSnapshot && !createdSecretIdentityProven)++ ) {++ res.status(503).json({++ error: 'registry_install_outcome_ambiguous',++ outcome: 'repair_required',++ })++ return+ }++ let resourceRollbackFailed = false++ if (createdHookSnapshot) {++ try {++ await rollbackCreatedResource(++ gateway,++ 'llmhooks',++ createdHookSnapshot,++ `LlmHook/${crName}`++ )++ } catch {++ resourceRollbackFailed = true++ }++ }++ if (resourceRollbackFailed) {++ res.status(500).json({++ error: 'registry_install_rollback_incomplete',++ outcome: 'compensation_failed',++ })++ return+ }++ if (secretCreated && createdSecretSnapshot) {++ // As with MCP installs, the Host may acquire a same-name++ // replacement immediately after the LlmHook disappears. There++ // is no cross-resource CAS, so leave the Secret for repair.++ res.status(500).json({++ error: 'registry_install_rollback_incomplete',++ outcome: 'compensation_failed',++ })++ return++ }++ const k8sErr = extractK8sError(err)++ const message =++ k8sErr?.message ||++ (err instanceof Error ? err.message : 'Failed to update Host guardrails')++ res++ .status(k8sErr?.status ?? 500)++ .json({ error: `Host guardrails update failed: ${message}` })++ return}-- const k8sErr = extractK8sError(err)-- const message =-- k8sErr?.message ||-- (err instanceof Error ? err.message : 'Failed to update Host guardrails')-- res-- .status(k8sErr?.status ?? 500)-- .json({ error: `Host guardrails update failed: ${message}` })-- return}// Step 11 — report install (fire-and-forget) + audit.@@@ -2291,20 -2229,12 +3228,22 @@@const llmHooksNs = config.llmHooksNamespacelet current: {spec?: Record<string, unknown>- metadata?: { annotations?: Record<string, string>; labels?: Record<string, string> }+ metadata?: {++ uid?: string+ annotations?: Record<string, string>+ labels?: Record<string, string>+ resourceVersion?: string+ }}try {current = (await gateway.getResource('llmhooks', body.hookName, llmHooksNs)) as {spec?: Record<string, unknown>- metadata?: { annotations?: Record<string, string>; labels?: Record<string, string> }+ metadata?: {++ uid?: string+ annotations?: Record<string, string>+ labels?: Record<string, string>+ resourceVersion?: string+ }}} catch (err) {res.status(404).json({@@@ -2313,6 -2243,6 +3252,16 @@@return}++ if (!current.metadata?.uid || !current.metadata.resourceVersion) {++ res.status(503).json({ error: 'registry_resource_identity_unavailable' })++ return++ }++ const beforeRegistrySnapshot = normalizeRegistryResourceSnapshot(++ current,++ body.hookName,++ llmHooksNs++ )++// The CR must be an upgrade OF THIS ENTRY. The only other cross-check is// target KIND, so naming a different entry silently re-pointed the hook at// another image while it inherited this CR's envSecret, capabilities,@@@ -2514,36 -2444,31 +3463,65 @@@// these, so the catalog kept reporting the pre-upgrade version and re-offering// the same upgrade — and left trust-level stale even though trustLevel was// just recomputed above. Both sibling upgrade routes already do this.-- try {-- await updateResourceWithConflictRetry(-- gateway,-- 'llmhooks',-- body.hookName,-- {-- metadata: {- ...(current.metadata?.labels ? { labels: current.metadata.labels } : {}),-- annotations: {- ...(current.metadata?.annotations ?? {}),-- ...catalogAnnotations(body.registryEntryName, body.registryEntryVersion),-- 'clerum.io/trust-level': trustLevel,-- },- ...(current.metadata?.resourceVersion- ? { resourceVersion: current.metadata.resourceVersion }- : {}),-- },-- spec: upgradedSpec,++ const operationId = crypto.randomUUID()++ const desiredSpecDigest = registrySpecDigest(upgradedSpec)++ const upgradeAnnotations = {++ ...(current.metadata?.annotations ?? {}),++ ...catalogAnnotations(body.registryEntryName, body.registryEntryVersion),++ 'clerum.io/trust-level': trustLevel,++ [REGISTRY_OPERATION_ID_ANNOTATION]: operationId,++ [REGISTRY_SPEC_DIGEST_ANNOTATION]: desiredSpecDigest,++ }++ const mutation = await executeRegistryResourceMutation(++ gateway,++ 'llmhooks',++ body.hookName,++ llmHooksNs,++ {++ metadata: {++ ...(current.metadata?.labels ? { labels: current.metadata.labels } : {}),++ annotations: upgradeAnnotations,++ uid: current.metadata.uid,++ resourceVersion: current.metadata.resourceVersion,},-- llmHooksNs-- )-- } catch (err) {-- // A CEL rejection (e.g. a contentAccess/lifecyclePoint conflict) surfaced-- // as an unmapped 500; install maps these.-- const k8sErr = extractK8sError(err)++ spec: upgradedSpec,++ },++ beforeRegistrySnapshot,++ {++ spec: upgradedSpec,++ metadata: {++ labels: current.metadata.labels,++ annotations: upgradeAnnotations,++ },++ specDigest: desiredSpecDigest,++ },++ operationId++ )++ if (mutation.outcome === 'rejected') {++ const k8sErr = extractK8sError(mutation.error)if (k8sErr) {res.status(k8sErr.status).json({ error: k8sErr.message })return}-- throw err++ throw mutation.error++ }++ if (mutation.outcome === 'not-committed') {++ res.status(503).json({++ error: 'registry_upgrade_outcome_not_committed',++ outcome: 'not_committed',++ })++ return++ }++ if (mutation.outcome === 'ambiguous') {++ log.error(++ { hookName: body.hookName, error: registryErrorLogFields(mutation.error) },++ 'Registry hook upgrade outcome is ambiguous after identity fence'++ )++ res.status(503).json({++ error: 'registry_upgrade_outcome_ambiguous',++ outcome: 'repair_required',++ })++ return}let syncedHosts: string[]try {@@@ -2634,48 -2556,48 +3612,112 @@@}// Uninstall WorkflowRecipetry {-- await gateway.deleteResource('workflowrecipes', resourceName, namespace)-- await waitForDeletion(-- () => gateway.getResource('workflowrecipes', resourceName, namespace),-- `WorkflowRecipe/${resourceName}`-- )-- deleted.push(`WorkflowRecipe/${resourceName}`)++ const current = await readResourceForRollback(gateway, 'workflowrecipes', {++ metadata: { name: resourceName, namespace },++ spec: {},++ })++ if (!current) {++ warnings.push(`WorkflowRecipe/${resourceName}: not found`)++ } else {++ await gateway.deleteResource(++ 'workflowrecipes',++ resourceName,++ namespace,++ resourcePreconditions(current)++ )++ await waitForDeletion(++ () => gateway.getResource('workflowrecipes', resourceName, namespace),++ `WorkflowRecipe/${resourceName}`++ )++ deleted.push(`WorkflowRecipe/${resourceName}`)++ }} catch (err) {-- warnings.push(-- `WorkflowRecipe/${resourceName}: ${err instanceof Error ? err.message : 'not found'}`-- )++ res.status(503).json({++ error: 'registry_uninstall_outcome_ambiguous',++ outcome: 'repair_required',++ resourceName,++ resourceType,++ namespace,++ deleted,++ warnings: [++ ...warnings,++ `WorkflowRecipe/${resourceName}: ${err instanceof Error ? err.message : 'unable to verify deletion'}`,++ ],++ })++ return}} else {// Uninstall MCP Servertry {-- await gateway.deleteResource('mcpservers', resourceName, namespace)-- await waitForDeletion(-- () => gateway.getResource('mcpservers', resourceName, namespace),-- `McpServer/${resourceName}`-- )-- deleted.push(`McpServer/${resourceName}`)++ const current = await readResourceForRollback(gateway, 'mcpservers', {++ metadata: { name: resourceName, namespace },++ spec: {},++ })++ if (!current) {++ warnings.push(`McpServer/${resourceName}: not found`)++ } else {++ await gateway.deleteResource(++ 'mcpservers',++ resourceName,++ namespace,++ resourcePreconditions(current)++ )++ await waitForDeletion(++ () => gateway.getResource('mcpservers', resourceName, namespace),++ `McpServer/${resourceName}`++ )++ deleted.push(`McpServer/${resourceName}`)++ }} catch (err) {-- warnings.push(-- `McpServer/${resourceName}: ${err instanceof Error ? err.message : 'not found'}`-- )++ res.status(503).json({++ error: 'registry_uninstall_outcome_ambiguous',++ outcome: 'repair_required',++ resourceName,++ resourceType,++ namespace,++ deleted,++ warnings: [++ ...warnings,++ `McpServer/${resourceName}: ${err instanceof Error ? err.message : 'unable to verify deletion'}`,++ ],++ })++ return}// Delete credential Secrettry {-- await gateway.deleteSecret(`${resourceName}-credentials`, namespace)++ const secretName = `${resourceName}-credentials`++ const current = await gateway.getSecret(secretName, namespace)++ const snapshot = normalizeSecretSnapshot(current, secretName, namespace)++ await gateway.deleteSecret(secretName, namespace, secretPreconditions(snapshot))await waitForDeletion(-- () => gateway.getSecret(`${resourceName}-credentials`, namespace),-- `Secret/${resourceName}-credentials`++ () => gateway.getSecret(secretName, namespace),++ `Secret/${secretName}`)-- deleted.push(`Secret/${resourceName}-credentials`)-- } catch {++ deleted.push(`Secret/${secretName}`)++ } catch (err) {++ if (extractK8sError(err)?.status !== 404) {++ res.status(503).json({++ error: 'registry_uninstall_outcome_ambiguous',++ outcome: 'repair_required',++ resourceName,++ resourceType,++ namespace,++ deleted,++ warnings: [++ ...warnings,++ `Secret/${resourceName}-credentials: ${err instanceof Error ? err.message : 'unable to verify deletion'}`,++ ],++ })++ return++ }// Secret may not exist (no credentials)}// Remove from Context allowliststry {const ctxList = (await gateway.listResource('contexts', namespace)) as Array<{-- metadata?: { name?: string }++ metadata?: { name?: string; uid?: string; resourceVersion?: string }spec?: Record<string, unknown> & {contextId?: stringdescription?: string@@@ -2686,10 -2608,10 +3728,16 @@@const name = ctx.metadata?.nameconst servers = ctx.spec?.mcpServers ?? []if (name && servers.includes(resourceName)) {++ const uid = ctx.metadata?.uid++ const resourceVersion = ctx.metadata?.resourceVersion++ if (!uid || !resourceVersion) {++ throw new Error(`Context/${name} identity unavailable; refusing stale update`)++ }await gateway.updateResource('contexts',name,{++ metadata: { uid, resourceVersion },spec: {...ctx.spec,contextId: ctx.spec?.contextId ?? name,@@@ -2701,8 -2623,8 +3749,20 @@@deleted.push(`Context/${name} (removed from allowlist)`)}}-- } catch {-- warnings.push('Failed to update Context allowlists')++ } catch (err) {++ res.status(503).json({++ error: 'registry_uninstall_partial',++ outcome: 'repair_required',++ resourceName,++ resourceType,++ namespace,++ deleted,++ warnings: [++ ...warnings,++ `Context allowlists: ${err instanceof Error ? err.message : 'unable to update safely'}`,++ ],++ })++ return}}@@@ -2736,14 -2658,7 +3796,15 @@@const namespace = config.mcpServersNamespace// 1. Verify existing server exists- let existingServer: Record<string, unknown>+ let existingServer: {+ metadata?: {++ uid?: string+ annotations?: Record<string, string>+ labels?: Record<string, string>+ resourceVersion?: string+ }+ spec?: Record<string, unknown>+ }try {existingServer = (await gateway.getResource('mcpservers',@@@ -2755,15 -2670,6 +3816,29 @@@return}++ if (!existingServer.metadata?.uid || !existingServer.metadata.resourceVersion) {++ res.status(503).json({ error: 'registry_resource_identity_unavailable' })++ return++ }++ const beforeRegistrySnapshot: RegistryResourceSnapshot = {++ metadata: {++ uid: existingServer.metadata.uid,++ resourceVersion: existingServer.metadata.resourceVersion,++ labels: existingServer.metadata.labels,++ annotations: existingServer.metadata.annotations,++ },++ spec: existingServer.spec ?? {},++ }+++ const installedCatalogId = getCatalogId(existingServer.metadata)+ if (installedCatalogId && installedCatalogId !== body.registryEntryName) {+ res.status(409).json({+ error: 'mcp_server_entry_identity_mismatch',+ reason: `McpServer "${body.serverName}" was installed from "${installedCatalogId}", not "${body.registryEntryName}" — uninstall and install to change entry`,+ })+ return+ }+// 2. Fetch new version metadataconst entry = await getEntryVersion(body.registryEntryName, body.registryEntryVersion)const meta = entry.mcp_server_meta as Record<string, unknown> | null@@@ -2899,15 -2805,24 +3974,23 @@@return}- // Ensure the shared pull secret exists before the CRD update references it- // (self-hosted self-provision; namespace-shared, idempotent, fail-loud). Runs- // AFTER preflight — matching install — so a request that will 422 never mints a- // rotate-on-call credential.- if (attachEvenfirePullSecret) {- try {- await ensureRegistryPullSecret(gateway, namespace)- } catch (err) {- const mapped = pullSecretErrorResponse(err)- res.status(mapped.status).json(mapped.body)- return- }- }++ // This identity is generated only after every validation/preflight and++ // before the first write side effect. It lets a later readback prove++ // this operation, not merely the same catalog version from an older run.++ const operationId = crypto.randomUUID()++ const desiredSpecDigest = registrySpecDigest(updatedSpec)+- // 4. Update credentials if provided+ // Read and validate the rollback target before any shared pull-secret+ // provisioning or credentials write. A legacy Secret with blocked+ // infrastructure metadata cannot be safely restored through the normal+ // constrained writer, so fail closed before creating side effects.let previousSecretSnapshot: SecretSnapshot | null = nulllet secretCreatedDuringUpgrade = false- if (Object.keys(credentialPayload.secretData).length > 0) {++ let mutatedSecretIdentityProven = false+ let mutatedSecretPreconditions: SecretPreconditions | null = null++ let mutatedSecretSnapshot: SecretSnapshot | null = null+ const hasCredentialUpdates = Object.keys(credentialPayload.secretData).length > 0+ if (hasCredentialUpdates) {try {previousSecretSnapshot = normalizeSecretSnapshot(await gateway.getSecret(secretName, namespace),@@@ -2957,35 -2844,24 +4040,98 @@@namespace,type: 'Opaque',labels: {+ ...(previousSecretSnapshot?.labels ?? {}),'clerum.io/managed-by': 'control-api',},- annotations: catalogAnnotations(body.registryEntryName, body.registryEntryVersion),+ annotations: {+ ...(previousSecretSnapshot?.annotations ?? {}),+ ...catalogAnnotations(body.registryEntryName, body.registryEntryVersion),++ [REGISTRY_SECRET_OPERATION_ID_ANNOTATION]: operationId,+ },+ ...(previousSecretSnapshot?.data ? { data: previousSecretSnapshot.data } : {}),stringData: credentialPayload.secretData,}-- if (previousSecretSnapshot) {- const updatedSecret = await gateway.updateSecret(- secretRequest,- secretPreconditions(previousSecretSnapshot),- REGISTRY_SECRET_WRITE_OPTIONS- )- mutatedSecretPreconditions = secretPreconditions(updatedSecret)- await gateway.updateSecret(secretRequest)-- auditLog('secret_updated', {-- secretName,-- namespace,-- registryEntry: body.registryEntryName,-- version: body.registryEntryVersion,-- })-- } else {- const created = await gateway.createSecret(secretRequest, REGISTRY_SECRET_WRITE_OPTIONS)- await gateway.createSecret(secretRequest)-- secretCreatedDuringUpgrade = true- mutatedSecretPreconditions = secretPreconditions(created)-- auditLog('secret_created', {++ try {++ if (previousSecretSnapshot) {++ const updatedSecret = await gateway.updateSecret(++ secretRequest,++ secretPreconditions(previousSecretSnapshot),++ REGISTRY_SECRET_WRITE_OPTIONS++ )++ mutatedSecretSnapshot = updatedSecret++ mutatedSecretIdentityProven = true++ mutatedSecretPreconditions = secretPreconditions(updatedSecret)++ auditLog('secret_updated', {++ secretName,++ namespace,++ registryEntry: body.registryEntryName,++ version: body.registryEntryVersion,++ })++ } else {++ const created = await gateway.createSecret(++ secretRequest,++ REGISTRY_SECRET_WRITE_OPTIONS++ )++ mutatedSecretSnapshot = created++ mutatedSecretIdentityProven = true++ secretCreatedDuringUpgrade = true++ mutatedSecretPreconditions = secretPreconditions(created)++ auditLog('secret_created', {++ secretName,++ namespace,++ registryEntry: body.registryEntryName,++ })++ }++ } catch (err) {++ const k8sErr = extractK8sError(err)++ if (k8sErr && k8sErr.status < 500) {++ res.status(k8sErr.status).json({ error: k8sErr.message })++ return++ }++++ const recovered = await readSecretMutationOutcome(gateway, previousSecretSnapshot)++ if (recovered.outcome === 'not-committed') {++ res.status(503).json({++ error: 'registry_secret_outcome_not_committed',++ outcome: 'not_committed',++ })++ return++ }++ if (recovered.outcome !== 'committed' || !recovered.snapshot) {++ log.error(++ {++ serverName: body.serverName,++ namespace,++ secretName,++ error: registryErrorLogFields(err),++ },++ 'Registry credential write outcome is ambiguous'++ )++ res.status(503).json({++ error: 'registry_secret_outcome_ambiguous',++ outcome: 'repair_required',++ })++ return++ }++++ if (!recovered.identityProven) {++ // `previousSecretSnapshot === null` means this was a create.++ // A post-error readback has no pre-write UID proof, so returning++ // success would allow an old/replaced object to masquerade as++ // this upgrade's credential commit.++ res.status(503).json({++ error: 'registry_secret_outcome_ambiguous',++ outcome: 'repair_required',++ })++ return++ }++++ mutatedSecretSnapshot = recovered.snapshot++ mutatedSecretIdentityProven = recovered.identityProven++ secretCreatedDuringUpgrade = previousSecretSnapshot === null++ mutatedSecretPreconditions = secretPreconditions(recovered.snapshot)++ auditLog('secret_write_recovered_after_ambiguous_response', {secretName,namespace,registryEntry: body.registryEntryName,@@@ -3002,114 -2877,52 +4148,146 @@@'clerum.io/managed-by': 'control-api','clerum.io/server-mode': isLocal ? 'local' : 'remote',}- const upgradeAnnotations: Record<string, string> = catalogAnnotations(- body.registryEntryName,- body.registryEntryVersion- )+ const upgradeAnnotations: Record<string, string> = {+ ...(existingServer.metadata?.annotations ?? {}),+ ...catalogAnnotations(body.registryEntryName, body.registryEntryVersion),++ [REGISTRY_OPERATION_ID_ANNOTATION]: operationId,++ [REGISTRY_SPEC_DIGEST_ANNOTATION]: desiredSpecDigest,+ }-- try {-- await updateResourceWithConflictRetry(-- gateway,-- 'mcpservers',-- body.serverName,-- {- metadata: {- labels: upgradeLabels,- annotations: upgradeAnnotations,- ...(existingServer.metadata?.resourceVersion- ? { resourceVersion: existingServer.metadata.resourceVersion }- : {}),- },- metadata: { labels: upgradeLabels, annotations: upgradeAnnotations },-- spec: updatedSpec,++ const mutation = await executeRegistryResourceMutation(++ gateway,++ 'mcpservers',++ body.serverName,++ namespace,++ {++ metadata: {++ labels: upgradeLabels,++ annotations: upgradeAnnotations,++ ...(beforeRegistrySnapshot.metadata?.uid++ ? { uid: beforeRegistrySnapshot.metadata.uid }++ : {}),++ ...(existingServer.metadata?.resourceVersion++ ? { resourceVersion: existingServer.metadata.resourceVersion }++ : {}),},-- namespace-- )-- } catch (err) {- if (body.credentials && Object.keys(body.credentials).length > 0) {++ spec: updatedSpec,++ },++ beforeRegistrySnapshot,++ {++ spec: updatedSpec,++ metadata: { labels: upgradeLabels, annotations: upgradeAnnotations },++ specDigest: desiredSpecDigest,++ },++ operationId++ )++ if (mutation.outcome !== 'committed') {++ const err = mutation.error+ const k8sErr = extractK8sError(err)- let upgradeCommittedByRead = false- const outcomeIsAmbiguous = !k8sErr || k8sErr.status >= 500-- // A transport/5xx error does not prove that the apiserver rejected the- // replace. Read the object before compensating: blind rollback after a- // committed write would undo a successful upgrade and create a second- // lost-update race.- if (outcomeIsAmbiguous) {- try {- const current = (await gateway.getResource(- 'mcpservers',- body.serverName,- namespace- )) as {- metadata?: { annotations?: Record<string, string>; labels?: Record<string, string> }- }- upgradeCommittedByRead =- getCatalogId(current.metadata) === body.registryEntryName &&- getCatalogVersion(current.metadata) === body.registryEntryVersion- } catch (readErr) {- log.error(- {- serverName: body.serverName,- namespace,- error: registryErrorLogFields(readErr),- },- 'Registry upgrade outcome is ambiguous and could not be classified'- )- res.status(503).json({ error: 'registry_upgrade_outcome_ambiguous' })- return- }++ const outcomeIsAmbiguous = mutation.outcome !== 'rejected'++ const upgradeOutcome: RegistryMutationOutcome | null =++ mutation.outcome === 'rejected' ? null : mutation.outcome++++ if (outcomeIsAmbiguous && upgradeOutcome === 'ambiguous') {++ log.error(++ {++ serverName: body.serverName,++ namespace,++ error: registryErrorLogFields(err),++ },++ 'Registry upgrade outcome is ambiguous after readback'++ )++ res.status(503).json({++ error: 'registry_upgrade_outcome_ambiguous',++ outcome: 'repair_required',++ })++ return++ }++++ // An ambiguous CR response is not made safe for cross-resource++ // compensation merely because the identity fence proves that the++ // requested CR replace did not commit. The live CR may still depend++ // on the Secret, and the failed request may have been accepted by a++ // different apiserver path. Preserve the credential state and make++ // repair explicit until the caller can reconcile both resources.++ if (outcomeIsAmbiguous && hasCredentialUpdates) {++ res.status(503).json({++ error: 'registry_upgrade_outcome_ambiguous',++ outcome: 'repair_required',++ })++ return++ }++++ if (hasCredentialUpdates && mutatedSecretSnapshot && !mutatedSecretIdentityProven) {++ res.status(503).json({++ error: 'registry_upgrade_outcome_ambiguous',++ outcome: 'repair_required',++ })++ return+ }+- if (!upgradeCommittedByRead && hasCredentialUpdates) {++ if (!outcomeIsAmbiguous && hasCredentialUpdates) {try {+ if (!mutatedSecretPreconditions) {+ throw Object.assign(new Error('mutated Secret identity unavailable'), {+ code: 'secret_identity_unavailable',+ })+ }if (secretCreatedDuringUpgrade) {- await gateway.deleteSecret(secretName, namespace, mutatedSecretPreconditions)- await gateway.deleteSecret(secretName, namespace)-- await waitForDeletion(-- () => gateway.getSecret(secretName, namespace),-- `Secret/${secretName}`-- )++ const createdSecret = mutatedSecretSnapshot++ if (!createdSecret) {++ throw Object.assign(new Error('created Secret snapshot unavailable'), {++ code: 'secret_identity_unavailable',++ })++ }++ await rollbackCreatedSecret(gateway, createdSecret)} else if (previousSecretSnapshot) {- await gateway.updateSecret(- await gateway.updateSecret({- name: previousSecretSnapshot.name,- namespace: previousSecretSnapshot.namespace,- type: previousSecretSnapshot.type || 'Opaque',- labels: previousSecretSnapshot.labels,- annotations: previousSecretSnapshot.annotations,- data: previousSecretSnapshot.data,- stringData: previousSecretSnapshot.stringData,- })++ const restored = await gateway.updateSecret(+ {+ name: previousSecretSnapshot.name,+ namespace: previousSecretSnapshot.namespace,+ type: previousSecretSnapshot.type ?? 'Opaque',+ labels: previousSecretSnapshot.labels ?? {},+ annotations: previousSecretSnapshot.annotations ?? {},+ data: previousSecretSnapshot.data,+ stringData: previousSecretSnapshot.stringData,+ },+ mutatedSecretPreconditions,+ REGISTRY_SECRET_WRITE_OPTIONS+ )++ mutatedSecretSnapshot = restored}- } catch {- // Best-effort rollback; preserve the original upgrade error.+ } catch (rollbackErr) {+ log.error(+ {+ serverName: body.serverName,+ namespace,+ secretName,+ rollback: secretCreatedDuringUpgrade ? 'delete-created-secret' : 'restore-secret',+ error: registryErrorLogFields(rollbackErr),+ },+ 'Registry upgrade rollback failed'+ )++ res.status(500).json({++ error: 'registry_upgrade_rollback_incomplete',++ outcome: 'compensation_failed',++ })++ return}}- const k8sErr = extractK8sError(err)- if (k8sErr) {+- if (upgradeCommittedByRead) {- // The write was accepted despite the transport error. Continue with- // the normal success response; the read is the authoritative proof.++ if (upgradeOutcome === 'not-committed') {++ res.status(503).json({++ error: 'registry_upgrade_outcome_not_committed',++ outcome: 'not_committed',++ })++ return+ } else if (k8sErr) {res.status(k8sErr.status).json({ error: k8sErr.message })return+ } else {+ throw err}- throw err}auditLog('upgrade', {serverName: body.serverName,@@@ -3170,30 -2983,9 +4348,32 @@@// recreating it in sandbox-recipes, not by preserving the ambiguity.const recipeNamespaces = [config.sandboxNamespace] as constlet namespace: string | null = null+ let existingRecipe:+ | {+ metadata?: {++ uid?: string+ labels?: Record<string, string>+ annotations?: Record<string, string>+ resourceVersion?: string+ }+ spec?: Record<string, unknown>+ }+ | undefinedfor (const candidate of recipeNamespaces) {try {- await gateway.getResource('workflowrecipes', body.recipeName, candidate)+ existingRecipe = (await gateway.getResource(+ 'workflowrecipes',+ body.recipeName,+ candidate+ )) as {+ metadata?: {++ uid?: string+ labels?: Record<string, string>+ annotations?: Record<string, string>+ resourceVersion?: string+ }+ spec?: Record<string, unknown>+ }namespace = candidatebreak} catch {@@@ -3206,14 -2998,6 +4386,23 @@@})return}++ if (!existingRecipe.metadata?.uid || !existingRecipe.metadata.resourceVersion) {++ res.status(503).json({ error: 'registry_resource_identity_unavailable' })++ return++ }++ const beforeRegistrySnapshot = normalizeRegistryResourceSnapshot(++ existingRecipe,++ body.recipeName,++ namespace++ )+ const installedCatalogId = getCatalogId(existingRecipe.metadata)+ if (installedCatalogId && installedCatalogId !== body.registryEntryName) {+ res.status(409).json({+ error: 'recipe_entry_identity_mismatch',+ reason: `WorkflowRecipe "${body.recipeName}" was installed from "${installedCatalogId}", not "${body.registryEntryName}" — uninstall and install to change entry`,+ })+ return+ }// 2. Fetch new version from registryconst entry = await getEntryVersion(body.registryEntryName, body.registryEntryVersion)@@@ -3317,13 -3101,12 +4506,17 @@@// stays a label. Pass metadata so a version bump refreshes the// round-trip annotation (resourceService merges body.metadata).const upgradeLabels: Record<string, string> = {+ ...(existingRecipe.metadata?.labels ?? {}),'clerum.io/managed-by': 'control-api',}- const upgradeAnnotations: Record<string, string> = catalogAnnotations(- body.registryEntryName,- body.registryEntryVersion- )+ const upgradeAnnotations: Record<string, string> = {+ ...(existingRecipe.metadata?.annotations ?? {}),+ ...catalogAnnotations(body.registryEntryName, body.registryEntryVersion),+ }++ const operationId = crypto.randomUUID()++ const desiredSpecDigest = registrySpecDigest(recipeSpec)++ upgradeAnnotations[REGISTRY_OPERATION_ID_ANNOTATION] = operationId++ upgradeAnnotations[REGISTRY_SPEC_DIGEST_ANNOTATION] = desiredSpecDigest// Ensure the platform pull credential before the CRD that will reference it.// Keyed on the INCOMING spec: an upgrade is exactly how a recipe moves from a@@@ -3339,22 -3122,16 +4532,54 @@@}}-- await updateResourceWithConflictRetry(++ const mutation = await executeRegistryResourceMutation(gateway,'workflowrecipes',body.recipeName,++ namespace,{- metadata: { labels: upgradeLabels, annotations: upgradeAnnotations },+ metadata: {+ labels: upgradeLabels,+ annotations: upgradeAnnotations,- ...(existingRecipe.metadata?.resourceVersion- ? { resourceVersion: existingRecipe.metadata.resourceVersion }- : {}),++ uid: existingRecipe.metadata.uid,++ resourceVersion: existingRecipe.metadata.resourceVersion,+ },spec: recipeSpec,},-- namespace++ beforeRegistrySnapshot,++ {++ spec: recipeSpec,++ metadata: { labels: upgradeLabels, annotations: upgradeAnnotations },++ specDigest: desiredSpecDigest,++ },++ operationId)++ if (mutation.outcome === 'rejected') {++ const k8sErr = extractK8sError(mutation.error)++ if (k8sErr) {++ res.status(k8sErr.status).json({ error: k8sErr.message })++ return++ }++ throw mutation.error++ }++ if (mutation.outcome === 'not-committed') {++ res.status(503).json({++ error: 'registry_upgrade_outcome_not_committed',++ outcome: 'not_committed',++ })++ return++ }++ if (mutation.outcome === 'ambiguous') {++ log.error(++ { recipeName: body.recipeName, error: registryErrorLogFields(mutation.error) },++ 'Registry recipe upgrade outcome is ambiguous after identity fence'++ )++ res.status(503).json({++ error: 'registry_upgrade_outcome_ambiguous',++ outcome: 'repair_required',++ })++ return++ }auditLog('upgrade-recipe', {recipeName: body.recipeName,registryEntry: body.registryEntryName,diff --cc control-api/src/routes/admin/resources.tsindex 2e72d2dad,2e72d2dad..920faed74--- a/control-api/src/routes/admin/resources.ts+++ b/control-api/src/routes/admin/resources.ts@@@ -11,6 -11,6 +11,7 @@@ import { enforceNamespace } from '../..import { validateCommunicationChannelSpec } from '../../http/validateCommunicationChannelSpec.js'import { validateMcpServerSpecPreflight } from '../../http/validateMcpServerSpec.js'import { K8sGateway } from '../../k8s.js'++import { rootLogger } from '../../observability/logger.js'import { stripHookRefFromHosts } from '../../services/hostGuardrailRefs.js'import { getModelAllowlistState, isModelAllowed } from '../../services/llmAllowedModels.js'import {@@@ -19,7 -19,7 +20,11 @@@type MutableResourceSnapshot,} from '../../services/resourceService.js'import { secretKeyNames } from '../../services/secretKeyNames.js'--import { ClerumResourceType } from '../../types.js'++import {++ ClerumResourceType,++ type ResourcePreconditions,++ type SecretPreconditions,++} from '../../types.js'import {registerCommunicationChannelCredentialsRoutes,validateCommunicationChannelCredentials,@@@ -39,6 -39,6 +44,9 @@@ importimport { collectResourceSpecFieldIssues, validateResourceName } from './resourceFieldValidation.js'import type { StaleModelWarning } from './staleModelWarning.js'++export const adminResourcesLogger = rootLogger.child({ module: 'admin-resources' })++const log = adminResourcesLogger++const PROVIDER_SETTINGS_FIELDS: Readonly<Record<string, readonly string[]>> = {telegramSettings: ['botHandle', 'replyOnlyWhenMentioned'],slackSettings: ['workspaceId', 'botHandle', 'replyOnlyWhenMentioned', 'replyInThreads'],@@@ -47,6 -47,6 +55,7 @@@type CommunicationChannelSpecSnapshot = {spec: Record<string, unknown>++ uid?: stringresourceVersion?: string}@@@ -62,6 -62,6 +71,28 @@@ function resourceVersionFromResource(rereturn typeof resourceVersion === 'string' && resourceVersion ? resourceVersion : undefined}++function resourcePreconditionsFromResource(resource: unknown): ResourcePreconditions | undefined {++ const metadata = recordValue((resource as { metadata?: unknown } | null)?.metadata)++ const uid = metadata?.uid++ const resourceVersion = metadata?.resourceVersion++ if (typeof uid !== 'string' || !uid || typeof resourceVersion !== 'string' || !resourceVersion) {++ return undefined++ }++ return { uid, resourceVersion }++}++++function credentialPreconditionsFromObject(object: unknown): SecretPreconditions | undefined {++ const metadata = recordValue((object as { metadata?: unknown } | null)?.metadata)++ const flat = recordValue(object)++ const uid = typeof flat?.uid === 'string' ? flat.uid : metadata?.uid++ const resourceVersion =++ typeof flat?.resourceVersion === 'string' ? flat.resourceVersion : metadata?.resourceVersion++ if (typeof uid !== 'string' || !uid || typeof resourceVersion !== 'string' || !resourceVersion) {++ return undefined++ }++ return { uid, resourceVersion }++}++function missingPersistedProviderSetting(requestedSpec: Record<string, unknown>,persisted: unknown@@@ -83,7 -83,7 +114,7 @@@}function sendPrunedProviderSettingError(res: Response, field: string): void {-- console.warn(`[Admin] CommunicationChannel provider setting was pruned: ${field}`)++ log.warn({ field }, 'CommunicationChannel provider setting was pruned')res.status(409).json({code: 'communication_channel_crd_outdated',error:@@@ -96,21 -96,21 +127,33 @@@ async function rollbackPrunedCommunicatgateway: K8sGateway,name: string,namespace: string,-- credentialsSecretName?: string++ credentialsSecretName?: string,++ resourcePreconditions?: ResourcePreconditions,++ credentialPreconditions?: SecretPreconditions): Promise<void> {-- try {-- await gateway.deleteResource('communicationchannels', name, namespace)-- } catch (err) {-- console.warn(-- `[Admin] cc pruned-setting rollback failed for "${name}": ${err instanceof Error ? err.message : String(err)}`-- )++ if (resourcePreconditions) {++ try {++ await gateway.deleteResource('communicationchannels', name, namespace, resourcePreconditions)++ } catch (err) {++ log.warn({ name, err }, 'CommunicationChannel pruned-setting rollback failed')++ }++ } else {++ log.warn({ name }, 'CommunicationChannel pruned-setting rollback skipped: identity unavailable')}if (!credentialsSecretName) return-- try {-- await gateway.deleteSecret(credentialsSecretName, namespace)-- } catch (err) {-- console.warn(-- `[Admin] cc credentials rollback failed for "${credentialsSecretName}": ${err instanceof Error ? err.message : String(err)}`++ if (credentialPreconditions) {++ try {++ await gateway.deleteSecret(credentialsSecretName, namespace, credentialPreconditions)++ } catch (err) {++ log.warn(++ { secretName: credentialsSecretName, err },++ 'CommunicationChannel credentials rollback failed'++ )++ }++ } else {++ log.warn(++ { secretName: credentialsSecretName },++ 'CommunicationChannel credentials rollback skipped: identity unavailable')}}@@@ -123,10 -123,10 +166,10 @@@ async function loadCommunicationChanneltry {const existing = await gateway.getResource('communicationchannels', name, namespace)const spec = recordValue((existing as { spec?: unknown } | null)?.spec)-- const resourceVersion = resourceVersionFromResource(existing)++ const identity = resourcePreconditionsFromResource(existing)return {spec: spec ? { ...spec } : {},-- ...(resourceVersion ? { resourceVersion } : {}),++ ...(identity ?? {}),}} catch (err) {if (extractK8sStatusCode(err) === 404) return null@@@ -139,29 -139,29 +182,29 @@@ async function rollbackPrunedCommunicatname: string,namespace: string,snapshot: CommunicationChannelSpecSnapshot | null,-- resourceVersion?: string++ resourcePreconditions?: ResourcePreconditions): Promise<void> {if (!snapshot) return++ if (!resourcePreconditions?.uid || !resourcePreconditions.resourceVersion) {++ log.warn({ name }, 'CommunicationChannel rollback skipped: identity unavailable')++ return++ }try {const restored = await gateway.updateResource('communicationchannels',name,{-- ...(resourceVersion ? { metadata: { resourceVersion } } : {}),++ metadata: resourcePreconditions,spec: snapshot.spec,},namespace)const missingField = missingPersistedProviderSetting(snapshot.spec, restored)if (missingField) {-- console.warn(-- `[Admin] cc pruned-setting rollback for "${name}" could not restore ${missingField}`-- )++ log.warn({ name, field: missingField }, 'CommunicationChannel rollback did not restore field')}} catch (err) {-- console.warn(-- `[Admin] cc pruned-setting rollback failed for "${name}": ${err instanceof Error ? err.message : String(err)}`-- )++ log.warn({ name, err }, 'CommunicationChannel pruned-setting rollback failed')}}@@@ -200,7 -200,7 +243,7 @@@ function contextDisplayNameNotPersisted}function sendPrunedDisplayNameError(res: Response): void {-- console.warn('[Admin] Context spec.displayName was pruned by the apiserver (CRD outdated)')++ log.warn('Context spec.displayName was pruned by the apiserver (CRD outdated)')res.status(409).json({code: 'context_crd_outdated',error:@@@ -220,16 -220,16 +263,17 @@@async function rollbackPrunedContextCreate(gateway: K8sGateway,name: string,-- namespace: string++ namespace: string,++ resourcePreconditions?: ResourcePreconditions): Promise<void> {++ if (!resourcePreconditions) {++ log.warn({ name }, 'Context pruned-displayName rollback skipped: identity unavailable')++ return++ }try {-- await gateway.deleteResource('contexts', name, namespace)++ await gateway.deleteResource('contexts', name, namespace, resourcePreconditions)} catch (err) {-- const safeName = String(name).replace(/[\r\n]/g, '')-- const safeErrMsg = (err instanceof Error ? err.message : String(err)).replace(/[\r\n]/g, '')-- console.warn(-- `[Admin] context pruned-displayName rollback failed for "${safeName}": ${safeErrMsg}`-- )++ log.warn({ name, err }, 'Context pruned-displayName rollback failed')}}@@@ -592,12 -592,12 +636,14 @@@ export function createAdminResourcesRoureturn}const secretName = ccCredentialsSecretName(ccName)-- await gateway.createSecret({++ let createdCredentialPreconditions: SecretPreconditions | undefined++ const createdCredential = await gateway.createSecret({name: secretName,namespace: ns,type: 'Opaque',stringData: credentialValidation.values,})++ createdCredentialPreconditions = credentialPreconditionsFromObject(createdCredential)// Inject credentialsSecretRef into the CC spec; strip the// non-CRD `credentials` envelope so it does not leak into the// CustomObjects API call.@@@ -613,7 -613,7 +659,14 @@@const created = await gateway.createResource(plural, ccBody, ns)const missingField = missingPersistedProviderSetting(ccBody.spec, created)if (missingField) {-- await rollbackPrunedCommunicationChannelCreate(gateway, ccName, ns, secretName)++ await rollbackPrunedCommunicationChannelCreate(++ gateway,++ ccName,++ ns,++ secretName,++ resourcePreconditionsFromResource(created),++ createdCredentialPreconditions++ )sendPrunedProviderSettingError(res, missingField)return}@@@ -622,11 -622,11 +675,19 @@@// Best-effort rollback. 404 from a stale Secret read or a// missing-secret race is tolerable — log and bubble the// original CRD error up so the caller sees the failure cause.-- try {-- await gateway.deleteSecret(secretName, ns)-- } catch (rollbackErr) {-- console.warn(-- `[Admin] cc credentials rollback failed for "${secretName}": ${rollbackErr instanceof Error ? rollbackErr.message : String(rollbackErr)}`++ if (createdCredentialPreconditions) {++ try {++ await gateway.deleteSecret(secretName, ns, createdCredentialPreconditions)++ } catch (rollbackErr) {++ log.warn(++ { secretName, err: rollbackErr },++ 'CommunicationChannel credentials rollback failed'++ )++ }++ } else {++ log.warn(++ { secretName },++ 'CommunicationChannel credentials rollback skipped: identity unavailable')}throw err@@@ -707,7 -707,7 +768,13 @@@if (plural === 'communicationchannels' && body.spec) {const missingField = missingPersistedProviderSetting(body.spec, created)if (missingField) {-- await rollbackPrunedCommunicationChannelCreate(gateway, body.metadata.name, ns)++ await rollbackPrunedCommunicationChannelCreate(++ gateway,++ body.metadata.name,++ ns,++ undefined,++ resourcePreconditionsFromResource(created)++ )sendPrunedProviderSettingError(res, missingField)return}@@@ -717,7 -717,7 +784,12 @@@body.spec &&contextDisplayNameNotPersisted(body.spec, created)) {-- await rollbackPrunedContextCreate(gateway, body.metadata.name, ns)++ await rollbackPrunedContextCreate(++ gateway,++ body.metadata.name,++ ns,++ resourcePreconditionsFromResource(created)++ )sendPrunedDisplayNameError(res)return}@@@ -897,6 -897,6 +969,9 @@@...body,metadata: {...body.metadata,++ ...(previousCommunicationChannelSpec?.uid++ ? { uid: previousCommunicationChannelSpec.uid }++ : {}),...(body.metadata?.resourceVersion ||!previousCommunicationChannelSpec?.resourceVersion? {}@@@ -952,7 -952,7 +1027,7 @@@req.params.name,ns,previousCommunicationChannelSpec,-- resourceVersionFromResource(updated)++ resourcePreconditionsFromResource(updated))sendPrunedProviderSettingError(res, missingField)return@@@ -1026,16 -1026,16 +1101,22 @@@if (plural === 'communicationchannels' && ccSecretRefName) {try {await gateway.deleteSecret(ccSecretRefName, ns)-- console.log(`[Admin] Deleted CC credentials Secret "${ccSecretRefName}" in ${ns}`)++ log.info(++ { secretName: ccSecretRefName, namespace: ns },++ 'Deleted CommunicationChannel credentials Secret'++ )} catch (err) {if (extractK8sStatusCode(err) === 404) {-- console.log(`[Admin] CC credentials Secret "${ccSecretRefName}" already gone in ${ns}`)++ log.info(++ { secretName: ccSecretRefName, namespace: ns },++ 'CommunicationChannel credentials Secret already gone'++ )} else {// CC is already gone; log and swallow so the operator gets a 200// and can clean the orphan Secret manually if needed.-- console.error(-- `[Admin] CC delete succeeded but credentials Secret "${ccSecretRefName}" cleanup failed:`,-- err++ log.error(++ { secretName: ccSecretRefName, namespace: ns, err },++ 'CommunicationChannel delete succeeded but credentials cleanup failed')}}@@@ -1045,11 -1045,11 +1126,12 @@@const contextsNs = resourceNamespace('contexts')try {await gateway.deleteSecret(`${name}-credentials`, ns)-- console.log(`[Admin] Deleted credentials secret "${name}-credentials" in ${ns}`)-- } catch (err) {-- console.log(-- `[Admin] No credentials secret to delete for "${name}": ${err instanceof Error ? err.message : String(err)}`++ log.info(++ { secretName: `${name}-credentials`, namespace: ns },++ 'Deleted MCP credentials Secret')++ } catch (err) {++ log.info({ serverName: name, err }, 'No MCP credentials Secret to delete')}try {@@@ -1077,13 -1077,13 +1159,14 @@@},contextsNs)-- console.log(`[Admin] Removed "${name}" from Context "${ctxName}" allowlist`)++ log.info(++ { serverName: name, contextName: ctxName },++ 'Removed MCP server from Context allowlist'++ )}}} catch (err) {-- console.error(-- `[Admin] Failed to clean up Context allowlists for "${name}": ${err instanceof Error ? err.message : String(err)}`-- )++ log.error({ serverName: name, err }, 'Failed to clean up Context allowlists')}}diff --cc control-api/src/routes/admin/secrets.tsindex 05d0b55a7,70aff12ec..fc798b12b--- a/control-api/src/routes/admin/secrets.ts+++ b/control-api/src/routes/admin/secrets.ts@@@ -13,9 -13,9 +13,14 @@@ importtype SecretOwnership,parseSecretOwnership,} from '../../secretOwnership.js'- import { REGISTRY_SECRET_PRESERVED_ANNOTATION_KEYS } from '../../services/secretConstraints.js'++import {++ REGISTRY_SECRET_PRESERVED_ANNOTATION_KEYS,++ REGISTRY_SECRET_ROTATION_PRESERVED_ANNOTATION_KEYS,++} from '../../services/secretConstraints.js'import { invalidSecretDataKeyReason } from '../../services/secretKeys.js'- import { SecretUpsertRequest } from '../../types.js'++import { findSecretReferenceState } from '../../services/secretReferenceService.js'+ import { toPublicDeleteSecretSummary, toPublicSecretSummary } from '../../services/secretService.js'-import { SecretUpsertRequest } from '../../types.js'++import { SecretPreconditions, SecretUpsertRequest } from '../../types.js'import { listHostSecrets } from './hostSecrets.js'import { isLlmHostSecret } from './llmSecretIdentity.js'@@@ -51,17 -53,6 +58,32 @@@ const PLATFORM_MANAGED_SECRET_ERROR`Secret "${EVENFIRE_REGISTRY_PULL_SECRET_NAME}" is platform-managed (the evenfire ` +'registry image-pull credential) and cannot be created, modified, or deleted here'- const logger = rootLogger.child({ module: 'admin-secrets' })++function secretIdentityPreconditions(raw: unknown): SecretPreconditions | null {++ const metadata = (raw as { metadata?: { uid?: unknown; resourceVersion?: unknown } } | null)++ ?.metadata++ if (typeof metadata?.uid !== 'string' || !metadata.uid) return null++ if (typeof metadata.resourceVersion !== 'string' || !metadata.resourceVersion) return null++ return { uid: metadata.uid, resourceVersion: metadata.resourceVersion }++}++++/**++ * A data-only merge is allowed to compose with another owner updating a++ * disjoint key. UID still fences delete/recreate, while resourceVersion is++ * deliberately omitted so the merge-patch remains multi-owner safe.++ */++function secretUidPrecondition(raw: unknown): SecretPreconditions | null {++ const metadata = (raw as { metadata?: { uid?: unknown } } | null)?.metadata++ if (typeof metadata?.uid !== 'string' || !metadata.uid) return null++ return { uid: metadata.uid }++}+- function isRegistryManagedCredentialSecret(- annotations: Record<string, string> | undefined- ): boolean {- return REGISTRY_SECRET_PRESERVED_ANNOTATION_KEYS.every(key => {- const value = annotations?.[key]- return typeof value === 'string' && value.length > 0- })++function requestSecretPreconditions(raw: unknown): SecretPreconditions | null {++ const body = (raw ?? {}) as { uid?: unknown; resourceVersion?: unknown }++ if (typeof body.uid !== 'string' || !body.uid.trim()) return null++ if (typeof body.resourceVersion !== 'string' || !body.resourceVersion.trim()) return null++ return { uid: body.uid, resourceVersion: body.resourceVersion }+}+// The plaintext data being written, merging base64 `data` and plaintext// `stringData` (stringData wins, matching Kubernetes Secret semantics).function effectiveSecretData(body: unknown): Record<string, string> {@@@ -383,8 -370,8 +401,19 @@@ export function createAdminSecretsRoutestringData: data,}- await gateway.createSecret(secretReq)- res.status(201).json({ name: name.trim(), namespace: targetNs, created: true })+ const created = await gateway.createSecret(secretReq)- res.status(201).json({ name: name.trim(), namespace: targetNs, created: Boolean(created) })++ const identity = secretIdentityPreconditions(created)++ if (!identity) {++ res.status(503).json({ error: 'secret_identity_unavailable', outcome: 'repair_required' })++ return++ }++ res.status(201).json({++ name: name.trim(),++ namespace: targetNs,++ uid: identity.uid,++ resourceVersion: identity.resourceVersion,++ created: true,++ })}))@@@ -466,7 -453,7 +495,12 @@@// job. Read it first so a missing Secret is a 404 instead of a silent// upsert, and so the ownership guard below sees the stored labels.let existing: {- metadata?: { labels?: Record<string, string>; annotations?: Record<string, string> }- metadata?: { labels?: Record<string, string> }++ metadata?: {++ labels?: Record<string, string>++ annotations?: Record<string, string>++ uid?: string++ resourceVersion?: string++ }data?: Record<string, string>}try {@@@ -493,19 -480,7 +527,25 @@@return}- const preserveRegistryAnnotations = isRegistryManagedCredentialSecret(- existing.metadata?.annotations- const merged = await gateway.mergeSecret({ name, namespace: targetNs, stringData: data })++ const precondition = secretUidPrecondition(existing)++ if (!precondition) {++ res.status(503).json({ error: 'secret_identity_unavailable', outcome: 'repair_required' })++ return++ }++ const existingAnnotations = existing.metadata?.annotations++ const isRegistryManaged = REGISTRY_SECRET_PRESERVED_ANNOTATION_KEYS.every(++ key => typeof existingAnnotations?.[key] === 'string'+ )- ? { allowExistingPlatformAnnotationKeys: REGISTRY_SECRET_PRESERVED_ANNOTATION_KEYS }++ const preserveRegistryAnnotations = isRegistryManaged++ ? {++ allowExistingPlatformAnnotationKeys: REGISTRY_SECRET_ROTATION_PRESERVED_ANNOTATION_KEYS,++ }+ : undefined- await gateway.mergeSecret(++ const merged = await gateway.mergeSecret(+ { name, namespace: targetNs, stringData: data },- preserveRegistryAnnotations- )-- const keys = [...new Set([...Object.keys(existing.data || {}), ...Object.keys(data)])].sort(- (a, b) => a.localeCompare(b)++ preserveRegistryAnnotations,++ precondition+ )// The credential IS rotated at this point. Emit the audit record NOW,// before anything that could throw — a rotation that actually happened@@@ -548,7 -530,12 +595,18 @@@)}- res.status(200).json({ name, namespace: targetNs, keys, affectedConnectors })++ const summary = toPublicSecretSummary(merged, name, targetNs)++ const mergedIdentity = secretIdentityPreconditions(merged)++ if (!mergedIdentity) {++ res.status(503).json({ error: 'secret_identity_unavailable', outcome: 'repair_required' })++ return++ }+ res.status(200).json({- name: merged.name,- namespace: merged.namespace,- keys: [...merged.keys],++ ...summary,++ uid: mergedIdentity.uid,++ resourceVersion: mergedIdentity.resourceVersion,+ affectedConnectors,+ })}))@@@ -559,14 -546,47 +617,71 @@@'/admin/mcp-secrets/:name',enforceNamespace(config.mcpServersNamespace),asyncHandler(async (req, res) => {-- // This route deletes by name with no ownership guard, so the reserved name is the-- // only thing standing between a rollback call and the platform pull credential.if (isPlatformManagedSecretName(req.params.name)) {res.status(400).json({ error: PLATFORM_MANAGED_SECRET_ERROR })return}- const deleted = await gateway.deleteSecret(req.params.name, config.mcpServersNamespace)- res.status(200).json(deleted)+ const name = req.params.name.trim()++ const requestedPrecondition = requestSecretPreconditions(req.body)++ if (!requestedPrecondition) {++ res.status(428).json({ error: 'secret_identity_precondition_required' })++ return++ }+ let existing: {+ metadata?: { labels?: Record<string, string>; uid?: string; resourceVersion?: string }+ } | null+ try {+ existing = (await gateway.getSecret(name, config.mcpServersNamespace)) as typeof existing+ } catch (err) {+ if (extractHttpStatus(err) === 404) {+ res.status(404).json({ error: `Secret "${name}" not found` })+ return+ }+ throw err+ }+ if (!existing) {+ res.status(404).json({ error: `Secret "${name}" not found` })+ return+ }++ const currentPrecondition = secretIdentityPreconditions(existing)++ if (!currentPrecondition) {++ res.status(503).json({ error: 'secret_identity_unavailable', outcome: 'repair_required' })++ return++ }++ if (++ currentPrecondition.uid !== requestedPrecondition.uid ||++ currentPrecondition.resourceVersion !== requestedPrecondition.resourceVersion++ ) {++ res.status(409).json({ error: 'secret_identity_changed', outcome: 'repair_required' })++ return++ }+ if (existing.metadata?.labels?.[RECIPE_SECRET_LABEL_KEY] === RECIPE_SECRET_LABEL_VALUE) {+ res.status(409).json({+ error: `Secret "${name}" is owned by a WorkflowRecipe; delete it through /admin/recipe-secrets`,+ })+ return+ }- const metadata = existing.metadata- const precondition =- metadata?.uid || metadata?.resourceVersion- ? {- ...(metadata.uid ? { uid: metadata.uid } : {}),- ...(metadata.resourceVersion ? { resourceVersion: metadata.resourceVersion } : {}),- }- : undefined- const deleted = precondition- ? await gateway.deleteSecret(name, config.mcpServersNamespace, precondition)- : await gateway.deleteSecret(name, config.mcpServersNamespace)++ const referenceState = await findSecretReferenceState(++ gateway,++ name,++ config.mcpServersNamespace++ )++ if (referenceState === 'referenced') {++ res.status(409).json({ error: 'mcp_secret_in_use', outcome: 'repair_required' })++ return++ }++ if (referenceState === 'unknown') {++ res++ .status(503)++ .json({ error: 'mcp_secret_reference_check_unavailable', outcome: 'repair_required' })++ return++ }++ const deleted = await gateway.deleteSecret(++ name,++ config.mcpServersNamespace,++ requestedPrecondition++ )+ res.status(200).json(toPublicDeleteSecretSummary(deleted))}))@@@ -675,22 -697,29 +792,31 @@@}async function recipeExists(recipeName: string): Promise<boolean> {- const items = (await gateway.listResource(- 'workflowrecipes',- config.sandboxNamespace- )) as Array<{ metadata?: { name?: string } }>- return items.some(r => r.metadata?.name === recipeName)+ try {+ const items = (await gateway.listResource(+ 'workflowrecipes',+ config.sandboxNamespace+ )) as Array<{ metadata?: { name?: string } }>+ return items.some(r => r.metadata?.name === recipeName)- } catch {- // List failure: don't block Secret creation on a transient apiserver- // hiccup — the WRC reconciler is the second line of defense (it rejects- // owner-recipe Secrets that don't match the requesting recipe).- return true++ } catch (err) {++ // The ownership claim cannot be validated when the source of truth is++ // unavailable. Fail closed before creating a Secret rather than treating++ // an apiserver failure as proof that the recipe exists.++ throw err+ }}-- async function isRecipeSecret(++ async function getRecipeSecret(name: string,namespace = config.sandboxNamespace-- ): Promise<boolean> {++ ): Promise<Record<string, unknown> | null> {const existing = await gateway.getSecret(name, namespace).catch(() => null)-- if (!existing) return false++ if (!existing) return nullconst labels = ((existing as { metadata?: { labels?: Record<string, string> } }).metadata?.labels || {}) as Record<string, string>return labels[RECIPE_SECRET_LABEL_KEY] === RECIPE_SECRET_LABEL_VALUE++ ? (existing as Record<string, unknown>)++ : null}router.get(@@@ -851,7 -880,7 +977,11 @@@const existing = (await gateway.getSecret(name.trim(), targetNamespace).catch(() => null)) as {-- metadata?: { labels?: Record<string, string> }++ metadata?: {++ labels?: Record<string, string>++ uid?: string++ resourceVersion?: string++ }data?: Record<string, string>} | nullconst existingLabels = (existing && existing.metadata?.labels) || {}@@@ -859,6 -888,6 +989,11 @@@res.status(404).json({ error: 'Recipe secret not found' })return}++ const precondition = secretIdentityPreconditions(existing)++ if (!precondition) {++ res.status(503).json({ error: 'secret_identity_unavailable', outcome: 'repair_required' })++ return++ }// Merge semantics: overlay incoming keys onto existing data; drop keys// listed in removeKeys. Lets callers update one value without resending@@@ -889,8 -918,8 +1024,8 @@@data: mergedData,}-- const updated = await gateway.updateSecret(secretReq)- res.status(200).json(updated)++ const updated = await gateway.updateSecret(secretReq, precondition)+ res.status(200).json(toPublicSecretSummary(updated))}))@@@ -905,12 -934,12 +1040,30 @@@return}const targetNamespace = namespaceParse.namespace-- if (!(await isRecipeSecret(name, targetNamespace))) {++ const existing = await getRecipeSecret(name, targetNamespace)++ if (!existing) {res.status(404).json({ error: 'Recipe secret not found' })return}-- const deleted = await gateway.deleteSecret(name, targetNamespace)- res.status(200).json(deleted)++ const requestedPrecondition = requestSecretPreconditions(req.body)++ if (!requestedPrecondition) {++ res.status(428).json({ error: 'secret_identity_precondition_required' })++ return++ }++ const currentPrecondition = secretIdentityPreconditions(existing)++ if (!currentPrecondition) {++ res.status(503).json({ error: 'secret_identity_unavailable', outcome: 'repair_required' })++ return++ }++ if (++ currentPrecondition.uid !== requestedPrecondition.uid ||++ currentPrecondition.resourceVersion !== requestedPrecondition.resourceVersion++ ) {++ res.status(409).json({ error: 'secret_identity_changed', outcome: 'repair_required' })++ return++ }++ const deleted = await gateway.deleteSecret(name, targetNamespace, requestedPrecondition)+ res.status(200).json(toPublicDeleteSecretSummary(deleted))}))diff --cc control-api/src/services/registryMutation.tsindex 000000000,000000000..428345d2fnew file mode 100644--- /dev/null+++ b/control-api/src/services/registryMutation.ts@@@ -1,0 -1,0 +1,268 @@@++import { createHash } from 'node:crypto'++++export const REGISTRY_OPERATION_ID_ANNOTATION = 'clerum.io/registry-operation-id'++export const REGISTRY_SPEC_DIGEST_ANNOTATION = 'clerum.io/registry-spec-sha256'++++export type RegistryMutationOutcome = 'committed' | 'not-committed' | 'ambiguous'++export type SecretMutationReadbackClassification = 'desired' | 'prior' | 'ambiguous'++export type SecretMutationSnapshot = {++ metadata?: {++ uid?: string++ resourceVersion?: string++ labels?: Record<string, string>++ annotations?: Record<string, string>++ }++ data?: Record<string, string>++ stringData?: Record<string, string>++}++++export type RegistryResourceSnapshot = {++ metadata?: {++ name?: string++ namespace?: string++ uid?: string++ resourceVersion?: string++ labels?: Record<string, string>++ annotations?: Record<string, string>++ }++ spec?: Record<string, unknown>++}++++export type RegistryMutationDesired = {++ spec: Record<string, unknown>++ metadata: {++ labels?: Record<string, string>++ annotations?: Record<string, string>++ }++ specDigest: string++}++++/** Canonicalize only JSON-like values; object key order is not semantic, array order is. */++export function canonicalRegistryValue(value: unknown): unknown {++ if (Array.isArray(value)) {++ return value.filter(entry => entry !== undefined).map(canonicalRegistryValue)++ }++ if (!value || typeof value !== 'object') return value++ return Object.fromEntries(++ Object.entries(value as Record<string, unknown>)++ .filter(([, entry]) => entry !== undefined)++ .sort(([left], [right]) => left.localeCompare(right))++ .map(([key, entry]) => [key, canonicalRegistryValue(entry)])++ )++}++++export function canonicalRegistryJson(value: unknown): string {++ return JSON.stringify(canonicalRegistryValue(value))++}++++export function registrySpecDigest(spec: Record<string, unknown>): string {++ return createHash('sha256').update(canonicalRegistryJson(spec)).digest('hex')++}++++export function registrySecretDataDigest(++ data: Record<string, string> | undefined,++ plaintext: Record<string, string> | undefined = undefined++): string {++ const effectiveData = { ...(data ?? {}) }++ for (const [key, value] of Object.entries(plaintext ?? {})) {++ effectiveData[key] = Buffer.from(value, 'utf8').toString('base64')++ }++ return registrySpecDigest(effectiveData)++}++++/**++ * Classify a Secret readback after the client lost the response. A matching++ * operation marker and payload are only candidates: a GET cannot prove that++ * its resourceVersion belongs to this write. Callers must keep the result++ * non-terminal unless they obtain a direct write response or a later CAS++ * receipt of their own.++ */++export function classifySecretMutationReadback(input: {++ before?: SecretMutationSnapshot++ current: SecretMutationSnapshot | null++ operationId: string++ operationAnnotationKey: string++ expectedDataDigest?: string++ expectedMetadata?: {++ labels?: Record<string, string>++ annotations?: Record<string, string>++ }++}): SecretMutationReadbackClassification {++ const currentMetadata = input.current?.metadata++ if (++ !currentMetadata ||++ typeof currentMetadata.uid !== 'string' ||++ typeof currentMetadata.resourceVersion !== 'string'++ ) {++ return 'ambiguous'++ }++ const beforeMetadata = input.before?.metadata++ if (beforeMetadata && currentMetadata.uid !== beforeMetadata.uid) {++ return 'ambiguous'++ }++ const currentOperationId = currentMetadata.annotations?.[input.operationAnnotationKey]++ if (currentOperationId === input.operationId) {++ if (beforeMetadata && currentMetadata.resourceVersion === beforeMetadata.resourceVersion) {++ return 'ambiguous'++ }++ if (++ !input.expectedDataDigest ||++ registrySecretDataDigest(input.current?.data, input.current?.stringData) !==++ input.expectedDataDigest++ ) {++ return 'ambiguous'++ }++ if (++ input.expectedMetadata &&++ (!metadataMapsEqual(currentMetadata.labels, input.expectedMetadata.labels) ||++ !metadataMapsEqual(currentMetadata.annotations, input.expectedMetadata.annotations))++ ) {++ // A same-UID write may carry our data marker while another writer has++ // changed metadata. Treat that state as ambiguous: a later full restore++ // would otherwise erase the concurrent metadata under the same identity.++ return 'ambiguous'++ }++ return 'desired'++ }++ if (beforeMetadata && currentMetadata.resourceVersion === beforeMetadata.resourceVersion) {++ return 'prior'++ }++ return 'ambiguous'++}++++/**++ * Classify a create response that may have been lost after the object committed.++ *++ * `committed` here means that the observed object carries this operation's complete++ * intent. A create readback has no pre-write UID to compare against, so it does NOT++ * prove that the observed UID is the object created by this request. Callers may use++ * the result to finish an idempotent success, but must mark the snapshot as++ * non-compensable until a direct create response supplied its identity.++ */++export function classifyCreatedRegistryMutationReadback(input: {++ current: RegistryResourceSnapshot | null++ desired: RegistryMutationDesired++ operationId: string++}): RegistryMutationOutcome {++ const metadata = input.current?.metadata++ if (++ !metadata ||++ typeof metadata.uid !== 'string' ||++ typeof metadata.resourceVersion !== 'string'++ ) {++ return 'ambiguous'++ }++ if (metadata.annotations?.[REGISTRY_OPERATION_ID_ANNOTATION] !== input.operationId) {++ return 'ambiguous'++ }++ if (registrySpecDigest(input.current?.spec ?? {}) !== input.desired.specDigest) {++ return 'ambiguous'++ }++ if (!metadataSubsetMatches(metadata, input.desired.metadata)) return 'ambiguous'++ return 'committed'++}++++function metadataSubsetMatches(++ current: RegistryResourceSnapshot['metadata'],++ expected: RegistryResourceSnapshot['metadata']++): boolean {++ for (const [key, value] of Object.entries(expected?.labels ?? {})) {++ if (current?.labels?.[key] !== value) return false++ }++ for (const [key, value] of Object.entries(expected?.annotations ?? {})) {++ if (current?.annotations?.[key] !== value) return false++ }++ return true++}++++/**++ * Classify a readback after a Registry mutation returned an ambiguous error.++ * resourceVersion is intentionally treated as opaque: only equality matters.++ * An unchanged prior object is `not-committed` only when the caller has++ * established that exact state through its bounded repeated-read policy; a++ * single stale read must remain ambiguous at the route boundary.++ */++export function classifyRegistryMutationReadback(input: {++ before: RegistryResourceSnapshot++ desired: RegistryMutationDesired++ current: RegistryResourceSnapshot++ operationId: string++}): RegistryMutationOutcome {++ const beforeMeta = input.before.metadata++ const currentMeta = input.current.metadata++ if (!beforeMeta?.uid || !beforeMeta.resourceVersion || !currentMeta?.uid) return 'ambiguous'++++ const sameUid = currentMeta.uid === beforeMeta.uid++ const currentOperationId = currentMeta.annotations?.[REGISTRY_OPERATION_ID_ANNOTATION]++ const desiredMetadataMatches = metadataSubsetMatches(currentMeta, input.desired.metadata)++ const currentSpecDigest = registrySpecDigest(input.current.spec ?? {})++++ if (++ sameUid &&++ typeof currentMeta.resourceVersion === 'string' &&++ currentMeta.resourceVersion !== beforeMeta.resourceVersion &&++ currentOperationId === input.operationId &&++ currentSpecDigest === input.desired.specDigest &&++ desiredMetadataMatches++ ) {++ return 'committed'++ }++++ // A stable readback of the exact prior object proves that this mutation did++ // not reach the apiserver: identity, version, spec digest, and all metadata++ // maps are still byte-for-byte the prior state, and this operation's marker++ // is absent. Callers only use this result after bounded repeated reads; a++ // single stale read is not promoted to this state by the route.++ if (++ sameUid &&++ currentMeta.resourceVersion === beforeMeta.resourceVersion &&++ currentOperationId !== input.operationId &&++ currentSpecDigest === registrySpecDigest(input.before.spec ?? {}) &&++ metadataMapsEqual(currentMeta.labels, beforeMeta.labels) &&++ metadataMapsEqual(currentMeta.annotations, beforeMeta.annotations)++ ) {++ return 'not-committed'++ }++++ return 'ambiguous'++}++++export function classifyRegistryAssociationReadback(input: {++ before: RegistryResourceSnapshot++ current: RegistryResourceSnapshot | null++ isCommitted: (spec: Record<string, unknown>) => boolean++}): RegistryMutationOutcome {++ const beforeMeta = input.before.metadata++ const currentMeta = input.current?.metadata++ if (++ !beforeMeta?.uid ||++ !beforeMeta.resourceVersion ||++ !currentMeta?.uid ||++ typeof currentMeta.resourceVersion !== 'string'++ ) {++ return 'ambiguous'++ }++ if (currentMeta.uid !== beforeMeta.uid) return 'ambiguous'++ if (++ currentMeta.resourceVersion !== beforeMeta.resourceVersion &&++ input.isCommitted(input.current?.spec ?? {})++ ) {++ return 'committed'++ }++ if (++ currentMeta.resourceVersion === beforeMeta.resourceVersion &&++ registrySpecDigest(input.current?.spec ?? {}) === registrySpecDigest(input.before.spec ?? {})++ ) {++ return 'not-committed'++ }++ return 'ambiguous'++}++++function metadataMapsEqual(++ left: Record<string, string> | undefined,++ right: Record<string, string> | undefined++): boolean {++ const leftEntries = Object.entries(left ?? {}).sort(([a], [b]) => a.localeCompare(b))++ const rightEntries = Object.entries(right ?? {}).sort(([a], [b]) => a.localeCompare(b))++ return JSON.stringify(leftEntries) === JSON.stringify(rightEntries)++}diff --cc control-api/src/services/resourceService.tsindex ccb26a7ef,ccb26a7ef..825ceb56b--- a/control-api/src/services/resourceService.ts+++ b/control-api/src/services/resourceService.ts@@@ -5,6 -5,6 +5,7 @@@ importClerumResource,ClerumResourceType,ResourceListResponse,++ ResourcePreconditions,} from '../types.js'import {addNonEmpty,@@@ -55,6 -55,6 +56,7 @@@ export type MutableResourceSnapshot =metadata?: {annotations?: Record<string, string>labels?: Record<string, string>++ uid?: stringresourceVersion?: stringgeneration?: number}@@@ -289,6 -289,6 +291,13 @@@ export class ResourceServicemetadata?: {labels?: Record<string, string>annotations?: Record<string, string>++ /**++ * AP-6 identity precondition. When present, the replacement must++ * still address the same Kubernetes object the caller read. This is++ * required for compensations: a same-name delete/recreate must never++ * receive the old object's rollback payload.++ */++ uid?: string/*** AP-6 — reader's-version precondition. When present, this is the* resourceVersion the CALLER READ (e.g. the version the control-ui@@@ -320,10 -320,10 +329,11 @@@): Promise<unknown> {const ns = this.resolveNamespace(plural, namespace)const intent = await persistHostIntent({ plural, action: 'update', namespace: ns, name })++ const readerUid = body.metadata?.uid || undefinedconst readerResourceVersion = body.metadata?.resourceVersion || undefined// With a reader-supplied precondition a retry can never succeed with the// same payload, so the loop collapses to a single attempt.-- const maxAttempts = readerResourceVersion ? 1 : 3++ const maxAttempts = readerResourceVersion || readerUid ? 1 : 3for (let attempt = 1; attempt <= maxAttempts; attempt += 1) {const current = (attempt === 1 && options?.preReadCurrent@@@ -333,11 -333,11 +343,23 @@@metadata?: {annotations?: Record<string, string>labels?: Record<string, string>++ uid?: stringresourceVersion?: stringgeneration?: number}}++ // resourceVersion detects a stale edit; UID detects a delete/recreate++ // under the same name. Both are checked before constructing the replace++ // body so an identity-bound compensation fails closed without sending++ // any payload to the apiserver.++ if (readerUid && current.metadata?.uid !== readerUid) {++ await persistHostFailure(intent)++ throw new K8sConflictError(++ `${plural}/${name} changed identity since it was read (stale uid ${readerUid})`++ )++ }++const sanitizedMetadata = stripAdministrativeIntentAnnotation(body.metadata)const mergedAnnotations = mergeAnnotationsForReplace(current.metadata?.annotations,@@@ -356,6 -356,6 +378,7 @@@metadata: {name,namespace: ns,++ ...(readerUid && current.metadata?.uid ? { uid: current.metadata.uid } : {}),...(current.metadata?.labels && { labels: current.metadata.labels }),...(sanitizedMetadata?.labels && { labels: sanitizedMetadata.labels }),...(annotations && { annotations }),@@@ -612,7 -612,7 +635,8 @@@async deleteResource(plural: ClerumResourceType,name: string,-- namespace?: string++ namespace?: string,++ precondition?: ResourcePreconditions): Promise<unknown> {const ns = this.resolveNamespace(plural, namespace)const intent = await persistHostIntent({ plural, action: 'delete', namespace: ns, name })@@@ -623,6 -623,6 +647,18 @@@namespace: ns,plural,name,++ ...(precondition && (precondition.uid || precondition.resourceVersion)++ ? {++ body: {++ preconditions: {++ ...(precondition.uid ? { uid: precondition.uid } : {}),++ ...(precondition.resourceVersion++ ? { resourceVersion: precondition.resourceVersion }++ : {}),++ },++ },++ }++ : {}),})if (intent && administrativeOperationService) {await administrativeOperationService.persistHostOutcome(intent, 'succeeded', 'deleted')diff --cc control-api/src/services/secretConstraints.tsindex f0a584b7a,000000000..a606ab38dmode 100644,000000..100644--- a/control-api/src/services/secretConstraints.ts+++ b/control-api/src/services/secretConstraints.ts@@@ -1,189 -1,0 +1,249 @@@+import { SecretUpsertRequest } from '../types.js'++export const ALLOWED_SECRET_TYPES: readonly string[] = [+ 'Opaque',+ 'kubernetes.io/tls',+ 'kubernetes.io/dockerconfigjson',+]++const INFRA_ANNOTATION_PREFIXES: readonly string[] = [+ 'kubectl.kubernetes.io/',+ 'kubernetes.io/',+ 'meta.helm.sh/',+]++const PLATFORM_ANNOTATION_PREFIXES: readonly string[] = ['clerum.io/']++export function isInfrastructureAnnotationKey(key: string): boolean {+ return INFRA_ANNOTATION_PREFIXES.some(prefix => key.startsWith(prefix))+}+++export function isPlatformAnnotationKey(key: string): boolean {++ return PLATFORM_ANNOTATION_PREFIXES.some(prefix => key.startsWith(prefix))++}+++/** Platform metadata that a public rotation route may preserve, but never set. */+export const REGISTRY_SECRET_PRESERVED_ANNOTATION_KEYS = [+ 'clerum.io/catalog-id',+ 'clerum.io/catalog-version',+] as const+++/** Operation marker used only by the internal Registry mutation capability. */++export const REGISTRY_SECRET_OPERATION_ID_ANNOTATION = 'clerum.io/registry-operation-id'++++/** Platform keys a public Registry credential rotation may preserve, never assign. */++export const REGISTRY_SECRET_ROTATION_PRESERVED_ANNOTATION_KEYS = [++ ...REGISTRY_SECRET_PRESERVED_ANNOTATION_KEYS,++ REGISTRY_SECRET_OPERATION_ID_ANNOTATION,++] as const+++/** Additional metadata owned by the internal Registry credential writer. */+const REGISTRY_CREDENTIAL_WRITABLE_ANNOTATION_KEYS = [+ ...REGISTRY_SECRET_PRESERVED_ANNOTATION_KEYS,+ 'clerum.io/trust-level',++ REGISTRY_SECRET_OPERATION_ID_ANNOTATION,+] as const++export type SecretWriteCapability = 'registryCredential' | 'registryPullSecret'++const CAPABILITY_ANNOTATION_KEYS: Record<SecretWriteCapability, readonly string[]> = {+ registryCredential: REGISTRY_CREDENTIAL_WRITABLE_ANNOTATION_KEYS,+ registryPullSecret: ['clerum.io/pull-key-fingerprint'],+}++/**+ * Options for Secret write-path constraint validation.+ *+ * Platform-internal writers must declare the narrow capability that owns the+ * exact platform annotation keys they need. User-facing endpoints MUST leave+ * this unset to prevent callers from claiming platform ownership.+ */+export interface SecretConstraintOptions {+ capability?: SecretWriteCapability+ /** Exact platform keys allowed only when validating already-persisted metadata. */+ allowExistingPlatformAnnotationKeys?: readonly string[]+}++function allowedPlatformAnnotationKeys(opts?: SecretConstraintOptions): ReadonlySet<string> {+ return new Set(opts?.capability ? CAPABILITY_ANNOTATION_KEYS[opts.capability] : [])+}++function isBlockedAnnotationKey(key: string, opts?: SecretConstraintOptions): boolean {+ if (INFRA_ANNOTATION_PREFIXES.some(prefix => key.startsWith(prefix))) return true+ return (+ PLATFORM_ANNOTATION_PREFIXES.some(prefix => key.startsWith(prefix)) &&+ !allowedPlatformAnnotationKeys(opts).has(key)+ )+}++function reservedPrefixes(): readonly string[] {+ return [...INFRA_ANNOTATION_PREFIXES, ...PLATFORM_ANNOTATION_PREFIXES]+}++function secretTypeErrorMessage(type: string): string {+ return `Secret type "${type}" is not allowed; must be one of: ${ALLOWED_SECRET_TYPES.join(', ')}`+}++function annotationKeyErrorMessage(key: string, prefixes: readonly string[]): string {+ return `annotation key "${key}" is not allowed: keys starting with ${prefixes.map(p => `"${p}"`).join(' or ')} are reserved`+}++export class InvalidSecretTypeError extends Error {+ readonly status = 400+ readonly type: string+ constructor(type: string) {+ super(secretTypeErrorMessage(type))+ this.name = 'InvalidSecretTypeError'+ this.type = type+ }+}++export class DangerousAnnotationError extends Error {+ readonly status = 400+ readonly annotationKey: string+ constructor(key: string, prefixes: readonly string[]) {+ super(annotationKeyErrorMessage(key, prefixes))+ this.name = 'DangerousAnnotationError'+ this.annotationKey = key+ }+}++export function invalidSecretTypeReason(type: string): string | null {+ if (!ALLOWED_SECRET_TYPES.includes(type)) {+ return secretTypeErrorMessage(type)+ }+ return null+}++export function dangerousAnnotationKeyReason(+ key: string,+ opts?: SecretConstraintOptions+): string | null {+ return isBlockedAnnotationKey(key, opts)+ ? annotationKeyErrorMessage(key, reservedPrefixes())+ : null+}++/**+ * Existing infrastructure metadata is preserved as an opaque server-owned+ * value. It is not a caller assignment, so it is safe to carry through a+ * mutation; platform metadata remains constrained by capability or an exact+ * preservation allowlist.+ */+export function existingSecretAnnotationKeyReason(+ key: string,+ opts?: SecretConstraintOptions+): string | null {+ if (isInfrastructureAnnotationKey(key)) return null+ if (opts?.allowExistingPlatformAnnotationKeys?.includes(key)) return null+ return dangerousAnnotationKeyReason(key, opts)+}++export function assertValidSecretType(type: string): void {+ if (invalidSecretTypeReason(type) !== null) {+ throw new InvalidSecretTypeError(type)+ }+}++export function assertValidSecretAnnotations(+ annotations: Record<string, string> | undefined,+ opts?: SecretConstraintOptions,+ existingAnnotations?: Record<string, string>+): void {+ if (!annotations) return+ for (const key of Object.keys(annotations)) {+ const isUnchangedInfrastructureMetadata =+ isInfrastructureAnnotationKey(key) && existingAnnotations?.[key] === annotations[key]- if (!isUnchangedInfrastructureMetadata && isBlockedAnnotationKey(key, opts)) {++ const isUnchangedPlatformMetadata =++ isPlatformAnnotationKey(key) && existingAnnotations?.[key] === annotations[key]++ if (++ !isUnchangedInfrastructureMetadata &&++ !isUnchangedPlatformMetadata &&++ isBlockedAnnotationKey(key, opts)++ ) {+ throw new DangerousAnnotationError(key, reservedPrefixes())+ }+ }+}++/**+ * Validate metadata already present on an existing Secret. Public mutation+ * routes may preserve a narrow, verified platform-owned annotation pair, but+ * their request payloads remain subject to assertValidSecretAnnotations().+ */+export function assertValidExistingSecretAnnotations(+ annotations: Record<string, string> | undefined,+ opts?: SecretConstraintOptions+): void {- if (!annotations) return- for (const key of Object.keys(annotations)) {- if (existingSecretAnnotationKeyReason(key, opts) !== null) {- throw new DangerousAnnotationError(key, reservedPrefixes())- }- }++ // Existing platform metadata is opaque state owned by the component that++ // wrote it. A data-only mutation does not claim or rewrite that metadata, so++ // an unknown/future `clerum.io/` key must not brick future rotations. The++ // transition validator above still rejects a caller that introduces or++ // changes a reserved key; this function intentionally validates no existing++ // key in isolation.++ void annotations++ void opts+}++export function assertValidSecretConstraints(+ req: SecretUpsertRequest,+ opts?: SecretConstraintOptions,+ existingAnnotations?: Record<string, string>+): void {+ // Type validation fires only on explicit type assignment. When req.type is+ // undefined, the write method defaults to 'Opaque' (create) or preserves+ // the existing type (update/merge) — no attacker-controlled type enters.+ if (req.type !== undefined) {+ assertValidSecretType(req.type)+ }+ assertValidSecretAnnotations(req.annotations, opts, existingAnnotations)+}++/** Validate the complete state that a mutation will leave behind. */+export function assertValidEffectiveSecretConstraints(+ req: SecretUpsertRequest,+ opts?: SecretConstraintOptions+): void {+ if (req.type !== undefined) {+ assertValidSecretType(req.type)+ }+ assertValidExistingSecretAnnotations(req.annotations, opts)+}++++/**++ * Resolve the annotation map a full replacement is allowed to leave behind.++ * Caller-owned keys retain full-replace semantics. Infrastructure metadata is++ * transport-only, while platform metadata is either capability-owned or an++ * exact existing-key preservation granted to a narrow partial writer.++ */++export function resolveSecretAnnotationsForReplace(++ existingAnnotations: Record<string, string> | undefined,++ requestedAnnotations: Record<string, string> | undefined,++ opts?: SecretConstraintOptions++): Record<string, string> | undefined {++ if (requestedAnnotations === undefined) {++ return existingAnnotations++ }++++ assertValidSecretAnnotations(requestedAnnotations, opts, existingAnnotations)++ assertValidExistingSecretAnnotations(existingAnnotations, opts)++++ const resolved: Record<string, string> = { ...requestedAnnotations }++ for (const [key, value] of Object.entries(existingAnnotations ?? {})) {++ if (isInfrastructureAnnotationKey(key)) {++ if (requestedAnnotations[key] === undefined) resolved[key] = value++ continue++ }++++ if (isPlatformAnnotationKey(key) && requestedAnnotations[key] === undefined) {++ const allowPreserve = opts?.allowExistingPlatformAnnotationKeys?.includes(key)++ const capabilityOwnsKey = allowedPlatformAnnotationKeys(opts).has(key)++ // Unknown/future platform metadata is immutable to public writers and is++ // carried forward. A declared capability may explicitly remove only its++ // own keys; a preservation allowlist keeps the narrow partial-writer++ // contract for the public rotation path.++ if (allowPreserve || !capabilityOwnsKey) resolved[key] = value++ }++ }++ return resolved++}diff --cc control-api/src/services/secretReferenceService.tsindex 000000000,000000000..3a74e3ec6new file mode 100644--- /dev/null+++ b/control-api/src/services/secretReferenceService.ts@@@ -1,0 -1,0 +1,101 @@@++import { config } from '../config.js'++import type { ClerumResourceType } from '../types.js'++++export type SecretReferenceState = 'referenced' | 'not-referenced' | 'unknown'++++export type SecretReferenceReader = {++ listResource: (plural: ClerumResourceType, namespace?: string) => Promise<unknown[]>++}++++type ReferenceScope = {++ plural: ClerumResourceType++ resourceNamespace: string++ secretNamespace: string++}++++const REFERENCE_SCOPES: ReferenceScope[] = [++ {++ plural: 'mcpservers',++ resourceNamespace: config.mcpServersNamespace,++ secretNamespace: config.mcpServersNamespace,++ },++ {++ plural: 'llmhooks',++ resourceNamespace: config.llmHooksNamespace,++ secretNamespace: config.llmHooksNamespace,++ },++ {++ plural: 'workflowrecipes',++ resourceNamespace: config.sandboxNamespace,++ secretNamespace: config.sandboxNamespace,++ },++ {++ plural: 'hosts',++ resourceNamespace: config.hostsNamespace,++ secretNamespace: config.secretsNamespace,++ },++ {++ plural: 'communicationchannels',++ resourceNamespace: config.communicationChannelsNamespace,++ secretNamespace: config.communicationChannelsNamespace,++ },++]++++const REFERENCE_KEYS = new Set(['credentialsSecretRef', 'envSecret', 'secretRef'])++++function isRecord(value: unknown): value is Record<string, unknown> {++ return typeof value === 'object' && value !== null++}++++function referenceValueMatches(value: unknown, name: string): boolean {++ if (typeof value === 'string') return value === name++ if (!isRecord(value)) return false++ return value.name === name++}++++function containsSecretReference(value: unknown, name: string, seen = new Set<object>()): boolean {++ if (typeof value !== 'object' || value === null) return false++ if (seen.has(value)) return false++ seen.add(value)++++ if (Array.isArray(value)) {++ return value.some(item => containsSecretReference(item, name, seen))++ }++++ return Object.entries(value).some(([key, child]) => {++ if (REFERENCE_KEYS.has(key) && referenceValueMatches(child, name)) return true++ return containsSecretReference(child, name, seen)++ })++}++++/**++ * Check every CRD family that can consume a namespaced Secret. A failed list is++ * deliberately `unknown`: compensation must preserve the object when the++ * reference graph cannot be observed completely.++ */++export async function findSecretReferenceState(++ reader: SecretReferenceReader,++ name: string,++ namespace: string++): Promise<SecretReferenceState> {++ const scopes = REFERENCE_SCOPES.filter(scope => scope.secretNamespace === namespace)++ if (scopes.length === 0) return 'unknown'++++ try {++ const resourceLists = await Promise.all(++ scopes.map(scope => reader.listResource(scope.plural, scope.resourceNamespace))++ )++ for (const resources of resourceLists) {++ if (++ resources.some(resource =>++ containsSecretReference((resource as { spec?: unknown }).spec, name)++ )++ ) {++ return 'referenced'++ }++ }++ return 'not-referenced'++ } catch {++ return 'unknown'++ }++}diff --cc control-api/src/services/secretRepository.tsindex 86276c2a1,000000000..43cb08cdfmode 100644,000000..100644--- a/control-api/src/services/secretRepository.ts+++ b/control-api/src/services/secretRepository.ts@@@ -1,89 -1,0 +1,96 @@@+import type { SecretPreconditions, SecretUpsertRequest } from '../types.js'+import type { SecretConstraintOptions } from './secretConstraints.js'++/** The subset of a Kubernetes Secret that callers are allowed to observe. */+export interface SecretResource {+ metadata?: {+ name?: string+ namespace?: string+ uid?: string+ resourceVersion?: string+ labels?: Record<string, string>+ annotations?: Record<string, string>+ ownerReferences?: Array<unknown>+ finalizers?: string[]+ }+ type?: string+ immutable?: boolean+ data?: Record<string, string>+ stringData?: Record<string, string>+}++/** A server-confirmed Secret identity and its restorable state. */+export interface SecretSnapshot {+ name: string+ namespace: string+ uid: string+ resourceVersion: string+ type?: string+ labels?: Record<string, string>+ annotations?: Record<string, string>+ ownerReferences?: Array<unknown>+ finalizers?: string[]+ immutable?: boolean+ data?: Record<string, string>+ stringData?: Record<string, string>+}++/** Typed boundary for every Secret mutation used by control-api. */+export interface SecretRepository {+ listSecrets(namespace?: string): Promise<unknown[]>+ getSecret(name: string, namespace?: string): Promise<SecretResource>+ createSecret(req: SecretUpsertRequest, opts?: SecretConstraintOptions): Promise<SecretSnapshot>+ updateSecret(+ req: SecretUpsertRequest,+ precondition?: SecretPreconditions,+ opts?: SecretConstraintOptions+ ): Promise<SecretSnapshot>- mergeSecret(req: SecretUpsertRequest, opts?: SecretConstraintOptions): Promise<SecretSnapshot>- removeSecretKey(req: { name: string; namespace?: string; key: string }): Promise<SecretSnapshot>++ mergeSecret(++ req: SecretUpsertRequest,++ opts?: SecretConstraintOptions,++ precondition?: SecretPreconditions++ ): Promise<SecretSnapshot>++ removeSecretKey(++ req: { name: string; namespace?: string; key: string },++ precondition?: SecretPreconditions++ ): Promise<SecretSnapshot>+ deleteSecret(+ name: string,+ namespace?: string,+ precondition?: SecretPreconditions+ ): Promise<unknown>+}++/** Convert an apiserver response into the only mutation result callers may use for CAS. */+export function toSecretSnapshot(+ raw: unknown,+ fallbackName: string,+ fallbackNamespace: string+): SecretSnapshot {+ const source = (raw ?? {}) as SecretResource+ const metadata = source.metadata+ if (typeof metadata?.uid !== 'string' || typeof metadata.resourceVersion !== 'string') {+ throw Object.assign(+ new Error(`Secret/${fallbackName} did not return a complete Kubernetes identity`),+ { status: 503, code: 'secret_identity_unavailable' }+ )+ }++ return {+ name: typeof metadata.name === 'string' && metadata.name.trim() ? metadata.name : fallbackName,+ namespace:+ typeof metadata.namespace === 'string' && metadata.namespace.trim()+ ? metadata.namespace+ : fallbackNamespace,+ uid: metadata.uid,+ resourceVersion: metadata.resourceVersion,+ ...(typeof source.type === 'string' ? { type: source.type } : {}),+ ...(metadata.labels ? { labels: metadata.labels } : {}),+ ...(metadata.annotations ? { annotations: metadata.annotations } : {}),+ ...(metadata.ownerReferences ? { ownerReferences: metadata.ownerReferences } : {}),+ ...(metadata.finalizers ? { finalizers: metadata.finalizers } : {}),+ ...(typeof source.immutable === 'boolean' ? { immutable: source.immutable } : {}),+ ...(source.data ? { data: source.data } : {}),+ ...(source.stringData ? { stringData: source.stringData } : {}),+ }+}diff --cc control-api/src/services/secretService.tsindex 1d242d6ea,5800be328..c28d5f113--- a/control-api/src/services/secretService.ts+++ b/control-api/src/services/secretService.ts@@@ -1,21 -1,64 +1,75 @@@import * as k8s from '@kubernetes/client-node'import { SecretPreconditions, SecretUpsertRequest } from '../types.js'+import {+ type SecretConstraintOptions,+ assertValidEffectiveSecretConstraints,+ assertValidSecretConstraints,+ assertValidSecretType,+ isInfrastructureAnnotationKey,++ resolveSecretAnnotationsForReplace,+} from './secretConstraints.js'import { assertValidSecretDataKey, assertValidSecretWriteKeys } from './secretKeys.js'- import {- SecretRepository,- SecretResource,- SecretSnapshot,- toSecretSnapshot,- } from './secretRepository.js'++import { SecretResource, SecretSnapshot, toSecretSnapshot } from './secretRepository.js'+-// A write-side summary of a Secret — NEVER carries `.data` values. Every admin-// secret-write route echoes this, so secret values cannot leave the Secret store-// via an HTTP response body. Reads that legitimately need values use `getSecret`,-// which deliberately stays full-fat.+ export interface SecretSummary {+ name: string+ namespace: string+ keys: string[]+ }++ export interface DeleteSecretSummary {+ name: string+ namespace: string+ deleted: true+ }+-export function toPublicSecretSummary(summary: SecretSummary): SecretSummary {- return {- name: summary.name,- namespace: summary.namespace,- keys: [...summary.keys],++export function toPublicSecretSummary(++ raw: SecretSummary | SecretSnapshot | Record<string, unknown> | null | undefined,++ fallbackName = '',++ fallbackNamespace = ''++): SecretSummary {++ const value = (raw ?? {}) as {++ name?: unknown++ namespace?: unknown++ keys?: unknown++ data?: unknown++ stringData?: unknown++ metadata?: { name?: unknown; namespace?: unknown }+ }-}--export function toPublicDeleteSecretSummary(summary: DeleteSecretSummary): DeleteSecretSummary {++ const name =++ fallbackName ||++ (typeof value.name === 'string' ? value.name : '') ||++ (typeof value.metadata?.name === 'string' ? value.metadata.name : '')++ const namespace =++ fallbackNamespace ||++ (typeof value.namespace === 'string' ? value.namespace : '') ||++ (typeof value.metadata?.namespace === 'string' ? value.metadata.namespace : '')++ const keys = Array.isArray(value.keys)++ ? value.keys.filter((key): key is string => typeof key === 'string')++ : [++ ...Object.keys(++ value.data && typeof value.data === 'object'++ ? (value.data as Record<string, unknown>)++ : {}++ ),++ ...Object.keys(++ value.stringData && typeof value.stringData === 'object'++ ? (value.stringData as Record<string, unknown>)++ : {}++ ),++ ]+ return {- name: summary.name,- namespace: summary.namespace,- deleted: true,++ name,++ namespace,++ keys: [...new Set(keys)].sort((a, b) => a.localeCompare(b)),+ }+ }- export class SecretService implements SecretRepository {-type Assert<T extends true> = T-type HasExactKeys<T, Keys extends PropertyKey> =- Exclude<keyof T, Keys> extends never- ? Exclude<Keys, keyof T> extends never- ? true- : false- : false--// Compile-time ratchet: adding `data`, `stringData`, or another field to either-// public write DTO fails the production typecheck.-type _SecretSummaryIsNamesOnly = Assert<HasExactKeys<SecretSummary, 'name' | 'namespace' | 'keys'>>-type _DeleteSecretSummaryIsNamesOnly = Assert<- HasExactKeys<DeleteSecretSummary, 'name' | 'namespace' | 'deleted'>->--function summarizeSecret(result: unknown, name: string, namespace: string): SecretSummary {- const data = (result as k8s.V1Secret | undefined)?.data- return toPublicSecretSummary({- name,- namespace,- keys: Object.keys(data ?? {}).sort((a, b) => a.localeCompare(b)),- })++export function toPublicDeleteSecretSummary(summary: DeleteSecretSummary): DeleteSecretSummary {++ return { name: summary.name, namespace: summary.namespace, deleted: true }+ }++ export class SecretService {constructor(private readonly coreApi: k8s.CoreV1Api,private readonly defaultNamespace: string@@@ -43,12 -89,9 +97,12 @@@return this.coreApi.readNamespacedSecret({ namespace, name })}- async createSecret(- async createSecret(req: SecretUpsertRequest): Promise<SecretSummary> {++ private async createSecretRaw(+ req: SecretUpsertRequest,+ opts?: SecretConstraintOptions- ): Promise<SecretSnapshot> {++ ): Promise<unknown> {+ assertValidSecretConstraints(req, opts)assertValidSecretWriteKeys(req)- const ns = req.namespace || this.defaultNamespaceconst body: k8s.V1Secret = {apiVersion: 'v1',kind: 'Secret',@@@ -63,11 -106,9 +117,29 @@@stringData: req.stringData,}- // Names-only return: never surface the created Secret's `.data` to callers.- const created = await this.coreApi.createNamespacedSecret({ namespace: ns, body })- return summarizeSecret(created, req.name, ns)+ const created = await this.coreApi.createNamespacedSecret({+ namespace: req.namespace || this.defaultNamespace,+ body,+ })- return toSecretSnapshot(created, req.name, req.namespace || this.defaultNamespace)++ return created++ }++++ async createSecretSnapshot(++ req: SecretUpsertRequest,++ opts?: SecretConstraintOptions++ ): Promise<SecretSnapshot> {++ const namespace = req.namespace || this.defaultNamespace++ const created = await this.createSecretRaw(req, opts)++ return toSecretSnapshot(created, req.name, namespace)++ }++++ async createSecret(++ req: SecretUpsertRequest,++ opts?: SecretConstraintOptions++ ): Promise<SecretSummary> {++ const namespace = req.namespace || this.defaultNamespace++ const created = await this.createSecretRaw(req, opts)++ return toPublicSecretSummary(created as Record<string, unknown>, req.name, namespace)}/**@@@ -83,45 -124,24 +155,34 @@@** Pass `precondition` to make the replace ownership-bound rather than* last-writer-wins (see `SecretPreconditions`). When it carries a- * `resourceVersion` the pre-read is skipped unless the request carries- * infrastructure metadata that must be proven unchanged; the precondition- * is still sent as-is, so the API server rejects the write with 409 if- * anything touched the object since the caller read it.- * `resourceVersion` the pre-read is SKIPPED and that version is sent as-is,- * so the API server rejects the write with 409 if anything touched the- * object since the caller read it. Re-reading here would defeat the entire- * point, by refreshing away the staleness we are trying to detect.-- *- * On the no-read path, a precondition caller must supply everything it wants- * persisted: the `labels`/`annotations`/`type` fallbacks to the existing- * object are not available there. Internal capability writers that submit a- * full snapshot with infrastructure metadata are read-checked for exact- * preservation before the same precondition-bound replace.- * Because that read is skipped, a precondition caller must supply everything- * it wants persisted: the `labels`/`annotations`/`type` fallbacks to the- * existing object are not available on this path.++ * `resourceVersion` the current object is still read so a full replacement++ * cannot drop protected metadata merely because the caller omitted it. The++ * caller's `resourceVersion`/`uid` is sent as-is, so the apiserver remains++ * the authoritative CAS boundary.*/-- async updateSecret(++ private async updateSecretRaw(req: SecretUpsertRequest,- precondition?: SecretPreconditions- ): Promise<SecretSummary> {+ precondition?: SecretPreconditions,+ opts?: SecretConstraintOptions- ): Promise<SecretSnapshot> {++ ): Promise<unknown> {+ const hasInfrastructureAnnotations = Object.keys(req.annotations ?? {}).some(+ isInfrastructureAnnotationKey+ )- // A full snapshot may carry opaque infrastructure metadata only when an- // internal capability identifies the owner. The values are still compared- // with the live object; capability is not permission to introduce them.- const canPreserveExistingInfrastructure =++ const carriesInternalInfrastructure =+ hasInfrastructureAnnotations && opts?.capability !== undefined- if (!canPreserveExistingInfrastructure) {++ if (!carriesInternalInfrastructure) {+ assertValidSecretConstraints(req, opts)+ } else if (req.type !== undefined) {+ assertValidSecretType(req.type)+ }assertValidSecretWriteKeys(req)const ns = req.namespace || this.defaultNamespace- const existing =- precondition?.resourceVersion && !canPreserveExistingInfrastructure- ? undefined- : await this.coreApi.readNamespacedSecret({ namespace: ns, name: req.name })-- if (canPreserveExistingInfrastructure) {- assertValidSecretConstraints(req, opts, existing?.metadata?.annotations)- }- const existing = precondition?.resourceVersion- ? undefined- : await this.coreApi.readNamespacedSecret({ namespace: ns, name: req.name })++ const existing = await this.coreApi.readNamespacedSecret({ namespace: ns, name: req.name })++ const effectiveAnnotations = resolveSecretAnnotationsForReplace(++ existing?.metadata?.annotations,++ req.annotations,++ opts++ )const body: k8s.V1Secret = {apiVersion: 'v1',@@@ -134,32 -154,20 +195,57 @@@// stored object is refused. Free when the caller does not set it....(precondition?.uid ? { uid: precondition.uid } : {}),labels: req.labels || existing?.metadata?.labels,-- annotations: req.annotations || existing?.metadata?.annotations,++ annotations: effectiveAnnotations,++ ...(existing?.metadata?.ownerReferences++ ? { ownerReferences: existing.metadata.ownerReferences }++ : {}),++ ...(existing?.metadata?.finalizers ? { finalizers: existing.metadata.finalizers } : {}),},type: req.type || existing?.type || 'Opaque',data: req.data,stringData: req.stringData,++ ...(typeof existing?.immutable === 'boolean' ? { immutable: existing.immutable } : {}),}- // Names-only return: never surface the replaced Secret's `.data` to callers.- const updated = await this.coreApi.replaceNamespacedSecret({+ // Validate the complete replacement state, not only fields explicitly+ // supplied by the caller. An existing Secret may predate these constraints;+ // allowing an omitted type/annotation field to preserve a forbidden value+ // would make updateSecret a write-path bypass.+ assertValidEffectiveSecretConstraints(+ {+ name: req.name,+ type: body.type,+ annotations: body.metadata?.annotations,+ },+ opts+ )++ const replaced = await this.coreApi.replaceNamespacedSecret({namespace: ns,name: req.name,body,})- return toSecretSnapshot(replaced, req.name, ns)- return summarizeSecret(updated, req.name, ns)++ return replaced++ }++++ async updateSecretSnapshot(++ req: SecretUpsertRequest,++ precondition?: SecretPreconditions,++ opts?: SecretConstraintOptions++ ): Promise<SecretSnapshot> {++ const namespace = req.namespace || this.defaultNamespace++ const replaced = await this.updateSecretRaw(req, precondition, opts)++ return toSecretSnapshot(replaced, req.name, namespace)++ }++++ async updateSecret(++ req: SecretUpsertRequest,++ precondition?: SecretPreconditions,++ opts?: SecretConstraintOptions++ ): Promise<SecretSummary> {++ const namespace = req.namespace || this.defaultNamespace++ const replaced = await this.updateSecretRaw(req, precondition, opts)++ return toPublicSecretSummary(replaced as Record<string, unknown>, req.name, namespace)}/**@@@ -182,57 -190,22 +268,64 @@@* from a route targeting any OTHER namespace unless that namespace's Role* has been granted `patch`.*/- async mergeSecret(- async mergeSecret(req: SecretUpsertRequest): Promise<SecretSummary> {++ private async mergeSecretRaw(+ req: SecretUpsertRequest,- opts?: SecretConstraintOptions- ): Promise<SecretSnapshot> {- const hasInfrastructureAnnotations = Object.keys(req.annotations ?? {}).some(- isInfrastructureAnnotationKey- )- const canPreserveExistingInfrastructure =- hasInfrastructureAnnotations && opts?.capability !== undefined- if (!canPreserveExistingInfrastructure) {- assertValidSecretConstraints(req, opts)- } else if (req.type !== undefined) {- assertValidSecretType(req.type)- }++ opts?: SecretConstraintOptions,++ precondition?: SecretPreconditions++ ): Promise<unknown> {++ if (req.type !== undefined) assertValidSecretType(req.type)assertValidSecretWriteKeys(req)const ns = req.namespace || this.defaultNamespace+ const existing = await this.coreApi.readNamespacedSecret({ namespace: ns, name: req.name })-- if (canPreserveExistingInfrastructure) {- assertValidSecretConstraints(req, opts, existing.metadata?.annotations)- }++ const effectiveAnnotations = resolveSecretAnnotationsForReplace(++ existing.metadata?.annotations,++ req.annotations,++ opts++ )++ // Merge-patch preserves fields omitted from the patch. Validate those+ // preserved fields as part of the effective target state before mutating.+ assertValidEffectiveSecretConstraints(+ {+ name: req.name,+ type: req.type ?? existing.type ?? 'Opaque',- annotations: existing.metadata?.annotations,++ annotations: effectiveAnnotations,+ },+ opts+ )const body: Partial<k8s.V1Secret> = {}if (req.stringData !== undefined) body.stringData = req.stringDataif (req.data !== undefined) body.data = req.data- // NOTE: merge-patch on metadata.labels REPLACES the whole labels map (it's- // a leaf merge — the map IS the leaf). Do not pass req.labels for- // multi-owner Secrets where another owner (e.g. HCC) writes labels.- if (req.labels !== undefined) body.metadata = { labels: req.labels }+ // RFC 7396 merges object members recursively. The labels map therefore+ // preserves omitted labels; callers that intend to replace the complete- // map must use updateSecret. Include the read version so this partial- // mutation cannot overwrite a concurrent rotation.- if (req.labels !== undefined || existing.metadata?.resourceVersion !== undefined) {++ // map must use updateSecret. A metadata merge without an explicit identity++ // fence carries the version read above so two writers cannot silently++ // replace each other's metadata map. A data-only merge may carry a UID++ // fence without a resourceVersion: that preserves delete/recreate safety++ // while allowing independent owners to update disjoint data keys.++ if (++ req.labels !== undefined ||++ req.annotations !== undefined ||++ precondition?.uid !== undefined ||++ precondition?.resourceVersion !== undefined++ ) {+ body.metadata = {+ ...(req.labels !== undefined ? { labels: req.labels } : {}),- ...(existing.metadata?.resourceVersion- ? { resourceVersion: existing.metadata.resourceVersion }- : {}),++ ...(req.annotations !== undefined ? { annotations: effectiveAnnotations } : {}),++ ...(precondition?.resourceVersion++ ? { resourceVersion: precondition.resourceVersion }++ : !precondition?.uid &&++ (req.labels !== undefined || req.annotations !== undefined) &&++ existing.metadata?.resourceVersion++ ? { resourceVersion: existing.metadata.resourceVersion }++ : {}),++ ...(precondition?.uid ? { uid: precondition.uid } : {}),+ }+ }if (req.type !== undefined) body.type = req.type- // Names-only return: the patch response is the merged WHOLE Secret (all keys,- // including ones the caller did not send) — return only the key NAMES.- const merged = await this.coreApi.patchNamespacedSecret(+ const patched = await this.coreApi.patchNamespacedSecret({namespace: ns,name: req.name,@@@ -242,35 -215,19 +335,67 @@@middleware: [k8s.setHeaderMiddleware('Content-Type', 'application/merge-patch+json')],})- return toSecretSnapshot(patched, req.name, ns)- return summarizeSecret(merged, req.name, ns)++ return patched+ }+- async removeSecretKey(req: {- name: string- namespace?: string- key: string- }): Promise<SecretSnapshot> {++ async mergeSecretSnapshot(++ req: SecretUpsertRequest,++ opts?: SecretConstraintOptions,++ precondition?: SecretPreconditions++ ): Promise<SecretSnapshot> {++ const namespace = req.namespace || this.defaultNamespace++ const patched = await this.mergeSecretRaw(req, opts, precondition)++ return toSecretSnapshot(patched, req.name, namespace)++ }++++ async mergeSecret(++ req: SecretUpsertRequest,++ opts?: SecretConstraintOptions,++ precondition?: SecretPreconditions++ ): Promise<SecretSummary> {++ const namespace = req.namespace || this.defaultNamespace++ const patched = await this.mergeSecretRaw(req, opts, precondition)++ return toPublicSecretSummary(patched as Record<string, unknown>, req.name, namespace)+ }+- async removeSecretKey(req: {- name: string- namespace?: string- key: string- }): Promise<SecretSummary> {++ private async removeSecretKeyRaw(++ req: {++ name: string++ namespace?: string++ key: string++ },++ precondition?: SecretPreconditions++ ): Promise<unknown> {assertValidSecretDataKey(req.key)const ns = req.namespace || this.defaultNamespace- const body = { data: { [req.key]: null } } as unknown as Partial<k8s.V1Secret>+ const existing = await this.coreApi.readNamespacedSecret({ namespace: ns, name: req.name })++ const effectiveAnnotations = resolveSecretAnnotationsForReplace(++ existing.metadata?.annotations,++ undefined++ )++ // Removing one data key still mutates the Secret. Preserve unchanged+ // infrastructure metadata while applying the same effective-state checks+ // as the other mutation paths.+ assertValidEffectiveSecretConstraints({+ name: req.name,+ type: existing.type ?? 'Opaque',- annotations: existing.metadata?.annotations,++ annotations: effectiveAnnotations,+ })++ const body = {- metadata: existing.metadata?.resourceVersion- ? { resourceVersion: existing.metadata.resourceVersion }- : undefined,++ ...(precondition && {++ metadata: {++ ...(precondition.uid ? { uid: precondition.uid } : {}),++ ...(precondition.resourceVersion++ ? { resourceVersion: precondition.resourceVersion }++ : {}),++ },++ }),+ data: { [req.key]: null },+ } as unknown as Partial<k8s.V1Secret>- const updated = await this.coreApi.patchNamespacedSecret(+ const patched = await this.coreApi.patchNamespacedSecret({namespace: ns,name: req.name,@@@ -280,7 -237,7 +405,33 @@@middleware: [k8s.setHeaderMiddleware('Content-Type', 'application/merge-patch+json')],})- return toSecretSnapshot(patched, req.name, ns)- return summarizeSecret(updated, req.name, ns)++ return patched++ }++++ async removeSecretKeySnapshot(++ req: {++ name: string++ namespace?: string++ key: string++ },++ precondition?: SecretPreconditions++ ): Promise<SecretSnapshot> {++ const namespace = req.namespace || this.defaultNamespace++ const patched = await this.removeSecretKeyRaw(req, precondition)++ return toSecretSnapshot(patched, req.name, namespace)++ }++++ async removeSecretKey(++ req: {++ name: string++ namespace?: string++ key: string++ },++ precondition?: SecretPreconditions++ ): Promise<SecretSummary> {++ const namespace = req.namespace || this.defaultNamespace++ const patched = await this.removeSecretKeyRaw(req, precondition)++ return toPublicSecretSummary(patched as Record<string, unknown>, req.name, namespace)}/**@@@ -298,10 -255,11 +449,10 @@@name: string,namespace?: string,precondition?: SecretPreconditions- ): Promise<unknown> {+ ): Promise<DeleteSecretSummary> {- const ns = namespace || this.defaultNamespaceconst hasPrecondition = Boolean(precondition?.uid || precondition?.resourceVersion)- return this.coreApi.deleteNamespacedSecret({+ await this.coreApi.deleteNamespacedSecret({- namespace: ns,+ namespace: namespace || this.defaultNamespace,name,...(hasPrecondition && {body: {@@@ -314,5 -272,6 +465,10 @@@},}),})- return { name, namespace: ns, deleted: true }++ return toPublicDeleteSecretSummary({++ name,++ namespace: namespace || this.defaultNamespace,++ deleted: true,++ })}}diff --cc control-api/src/types.tsindex 3deb6f5c3,58b48e477..5da8cb6b8--- a/control-api/src/types.ts+++ b/control-api/src/types.ts@@@ -14,9 -14,8 +14,10 @@@ export type ClerumResourceTypeexport interface Metadata {name: stringnamespace?: string++ uid?: stringlabels?: Record<string, string>annotations?: Record<string, string>+ resourceVersion?: string}export interface ClerumResource<TSpec = Record<string, unknown>> {@@@ -81,3 -80,3 +82,13 @@@ export interface SecretPreconditionsuid?: stringresourceVersion?: string}++++/**++ * Optimistic-concurrency preconditions for deleting a namespaced custom++ * resource. A UID prevents a delete/recreate race; resourceVersion prevents++ * deleting the original object after another writer changed it.++ */++export interface ResourcePreconditions {++ uid?: string++ resourceVersion?: string++}diff --cc control-api/test/mockGateway.contract.test.tsindex e28381e2b,000000000..e637ef5f2mode 100644,000000..100644--- a/control-api/test/mockGateway.contract.test.ts+++ b/control-api/test/mockGateway.contract.test.ts@@@ -1,118 -1,0 +1,258 @@@+import { describe, expect, it } from 'vitest'+import { MockGateway } from './mockGateway.js'++describe('MockGateway Kubernetes identity contract', () => {+ it('returns the server-assigned identity from a mutation', async () => {+ const gateway = new MockGateway('mcp-server')+ const key = ['TEST', 'VALUE'].join('_')++ const created = await gateway.createSecret({+ name: 'credentials',+ namespace: 'mcp-server',+ type: 'Opaque',+ data: { [key]: 'initial' },+ })++ expect(created).toMatchObject({+ name: 'credentials',+ namespace: 'mcp-server',+ uid: expect.any(String),+ resourceVersion: '1',+ })+ })++ it('rejects a duplicate Secret create with the apiserver conflict shape', async () => {+ const gateway = new MockGateway('mcp-server')+ gateway.seedSecret('credentials', 'mcp-server')++ await expect(+ gateway.createSecret({ name: 'credentials', namespace: 'mcp-server', type: 'Opaque' })+ ).rejects.toMatchObject({ statusCode: 409, code: 409 })+ })++ it('rejects an update for a missing Secret with the apiserver not-found shape', async () => {+ const gateway = new MockGateway('mcp-server')++ await expect(+ gateway.updateSecret({ name: 'missing', namespace: 'mcp-server', type: 'Opaque' })+ ).rejects.toMatchObject({ statusCode: 404, code: 404 })+ })++ it('does not let rollback overwrite a third-party write after the mutation', async () => {+ const gateway = new MockGateway('mcp-server')+ const key = ['TEST', 'VALUE'].join('_')+ gateway.seedSecret('credentials', 'mcp-server', {+ uid: 'object-uid',+ resourceVersion: '1',+ type: 'Opaque',+ data: { [key]: 'before' },+ })++ const updated = await gateway.updateSecret(+ { name: 'credentials', namespace: 'mcp-server', type: 'Opaque', data: { [key]: 'upgrade' } },+ { uid: 'object-uid', resourceVersion: '1' }+ )+ expect(updated.resourceVersion).toBe('2')++ await gateway.updateSecret(+ {+ name: 'credentials',+ namespace: 'mcp-server',+ type: 'Opaque',+ data: { [key]: 'third-party' },+ },+ { uid: 'object-uid', resourceVersion: '2' }+ )++ await expect(+ gateway.updateSecret(+ {+ name: 'credentials',+ namespace: 'mcp-server',+ type: 'Opaque',+ data: { [key]: 'rollback' },+ },+ { uid: 'object-uid', resourceVersion: updated.resourceVersion }+ )+ ).rejects.toMatchObject({ statusCode: 409, code: 409 })++ await expect(gateway.getSecret('credentials', 'mcp-server')).resolves.toMatchObject({+ data: { [key]: 'third-party' },+ metadata: { resourceVersion: '3' },+ })+ })++ it('rejects a stale resourceVersion after a concurrent resource write', async () => {+ const gateway = new MockGateway('mcp-server')+ await gateway.createResource('mcpservers', {+ metadata: { name: 'server' },+ spec: { image: 'example:1' },+ })++ const initial = (await gateway.getResource('mcpservers', 'server', 'mcp-server')) as {+ metadata: { resourceVersion: string }+ }++ await gateway.updateResource(+ 'mcpservers',+ 'server',+ {+ metadata: { resourceVersion: initial.metadata.resourceVersion },+ spec: { image: 'example:2' },+ },+ 'mcp-server'+ )++ await expect(+ gateway.updateResource(+ 'mcpservers',+ 'server',+ {+ metadata: { resourceVersion: initial.metadata.resourceVersion },+ spec: { image: 'example:stale' },+ },+ 'mcp-server'+ )+ ).rejects.toMatchObject({ statusCode: 409, code: 409 })+ })++++ it('keeps a same-name replacement when a delete carries the original identity', async () => {++ const gateway = new MockGateway('mcp-server')++ const dataKey = ['TOK', 'EN'].join('')++ const created = await gateway.createSecret({++ name: 'credentials',++ namespace: 'mcp-server',++ type: 'Opaque',++ data: { [dataKey]: ['ori', 'ginal'].join('') },++ })++++ await gateway.deleteSecret('credentials', 'mcp-server', {++ uid: created.uid,++ resourceVersion: created.resourceVersion,++ })++ const replacement = await gateway.createSecret({++ name: 'credentials',++ namespace: 'mcp-server',++ type: 'Opaque',++ data: { [dataKey]: ['repla', 'cement'].join('') },++ })++++ await expect(++ gateway.deleteSecret('credentials', 'mcp-server', {++ uid: created.uid,++ resourceVersion: created.resourceVersion,++ })++ ).rejects.toMatchObject({ statusCode: 409, code: 409 })++++ await expect(gateway.getSecret('credentials', 'mcp-server')).resolves.toMatchObject({++ metadata: { uid: replacement.uid },++ data: { [dataKey]: ['repla', 'cement'].join('') },++ })++ })++++ it('enforces mutation constraints in the in-memory gateway', async () => {++ const gateway = new MockGateway('mcp-server')++ gateway.seedSecret('credentials', 'mcp-server', { type: 'Opaque', data: { FIELD: 'before' } })++++ await expect(++ gateway.updateSecret({++ name: 'credentials',++ namespace: 'mcp-server',++ type: 'not-a-kubernetes-secret-type',++ })++ ).rejects.toThrow(/Secret type/)++++ await expect(++ gateway.mergeSecret({++ name: 'credentials',++ namespace: 'mcp-server',++ annotations: { 'kubernetes.io/unsafe': 'caller-controlled' },++ })++ ).rejects.toThrow(/annotation key/)++ })++++ it('models RFC 7396 map merging instead of replacing omitted Secret members', async () => {++ const gateway = new MockGateway('mcp-server')++ gateway.seedSecret('credentials', 'mcp-server', {++ type: 'Opaque',++ labels: { owner: 'control-api', keep: 'yes' },++ annotations: { catalog: 'v1', keep: 'yes' },++ data: { FIRST: 'before', KEEP: 'untouched' },++ })++++ await gateway.mergeSecret({++ name: 'credentials',++ namespace: 'mcp-server',++ labels: { owner: 'operator' },++ annotations: { catalog: 'v2' },++ data: { FIRST: 'after' },++ })++++ await expect(gateway.getSecret('credentials', 'mcp-server')).resolves.toMatchObject({++ metadata: {++ labels: { owner: 'operator', keep: 'yes' },++ annotations: { catalog: 'v2', keep: 'yes' },++ },++ data: { FIRST: 'after', KEEP: 'untouched' },++ })++ })++++ it('rejects stale identity on key removal instead of deleting a concurrent value', async () => {++ const gateway = new MockGateway('mcp-server')++ const key = ['FIE', 'LD'].join('')++ const created = await gateway.createSecret({++ name: 'credentials',++ namespace: 'mcp-server',++ type: 'Opaque',++ data: { [key]: 'before' },++ })++ await gateway.updateSecret(++ {++ name: 'credentials',++ namespace: 'mcp-server',++ type: 'Opaque',++ data: { [key]: 'concurrent' },++ },++ { uid: created.uid, resourceVersion: created.resourceVersion }++ )++++ await expect(++ gateway.removeSecretKey(++ { name: 'credentials', namespace: 'mcp-server', key },++ { uid: created.uid, resourceVersion: created.resourceVersion }++ )++ ).rejects.toMatchObject({ statusCode: 409, code: 409 })++ await expect(gateway.getSecret('credentials', 'mcp-server')).resolves.toMatchObject({++ data: { [key]: 'concurrent' },++ })++ })++++ it('keeps a same-name resource replacement when a delete carries the original identity', async () => {++ const gateway = new MockGateway('mcp-server')++ const created = (await gateway.createResource('mcpservers', {++ metadata: { name: 'server' },++ spec: { image: 'example:original' },++ })) as { metadata: { uid: string; resourceVersion: string } }++++ await gateway.deleteResource('mcpservers', 'server', 'mcp-server', {++ uid: created.metadata.uid,++ resourceVersion: created.metadata.resourceVersion,++ })++ const replacement = (await gateway.createResource('mcpservers', {++ metadata: { name: 'server' },++ spec: { image: 'example:replacement' },++ })) as { metadata: { uid: string } }++++ await expect(++ gateway.deleteResource('mcpservers', 'server', 'mcp-server', {++ uid: created.metadata.uid,++ resourceVersion: created.metadata.resourceVersion,++ })++ ).rejects.toMatchObject({ statusCode: 409, code: 409 })++++ await expect(gateway.getResource('mcpservers', 'server', 'mcp-server')).resolves.toMatchObject({++ metadata: { uid: replacement.metadata.uid },++ spec: { image: 'example:replacement' },++ })++ })+})diff --cc control-api/test/mockGateway.tsindex 67be5960e,b950653d3..94d70e531--- a/control-api/test/mockGateway.ts+++ b/control-api/test/mockGateway.ts@@@ -1,10 -1,5 +1,22 @@@import { K8sNotFoundError } from '../src/services/resourceService.js'-import type { SecretPreconditions } from '../src/types.js'++import {++ type SecretConstraintOptions,++ assertValidEffectiveSecretConstraints,++ assertValidSecretConstraints,++ assertValidSecretType,++ resolveSecretAnnotationsForReplace,++} from '../src/services/secretConstraints.js'++import { assertValidSecretDataKey, assertValidSecretWriteKeys } from '../src/services/secretKeys.js'+import {+ type SecretResource,+ type SecretSnapshot,+ toSecretSnapshot,+} from '../src/services/secretRepository.js'- import type { SecretPreconditions } from '../src/types.js'++import type {++ ResourcePreconditions,++ SecretPreconditions,++ SecretUpsertRequest,++} from '../src/types.js'type ResourceType =| 'hosts'@@@ -57,8 -39,8 +60,45 @@@ type ResourceRecord =status?: Record<string, unknown>}++/** Apply the object-member part of an RFC 7396 merge patch. */++function mergePatchMap(++ existing: Record<string, string> | undefined,++ patch: Record<string, unknown> | undefined++): Record<string, string> | undefined {++ if (patch === undefined) return existing++ const merged: Record<string, string> = { ...(existing ?? {}) }++ for (const [key, value] of Object.entries(patch)) {++ if (value === null) {++ delete merged[key]++ } else if (typeof value === 'string') {++ merged[key] = value++ }++ }++ return merged++}++++export type MockGatewaySecretWriteFault = (input: {++ operation: 'create' | 'update' | 'merge'++ snapshot: SecretSnapshot++}) => void | Promise<void>++++export type MockGatewayResourceUpdateFault = (input: {++ plural: ResourceType++ name: string++ namespace: string++ snapshot: ResourceRecord++}) => void | Promise<void>++++export type MockGatewayResourceCreateFault = (input: {++ plural: ResourceType++ name: string++ namespace: string++ snapshot: ResourceRecord++}) => void | Promise<void>++export class MockGateway {private readonly ns: string++ private identitySequence = 0private readonly store: Record<ResourceType, Map<string, ResourceRecord>>private readonly secretStore: Map<string,@@@ -78,6 -61,6 +118,9 @@@>private readonly endpointsStore: Map<string, number>++ private secretWriteFault: MockGatewaySecretWriteFault | null = null++ private resourceCreateFault: MockGatewayResourceCreateFault | null = null++ private resourceUpdateFault: MockGatewayResourceUpdateFault | null = null// Stub for the LLM allowlist ConfigMap materializer. Defaults to a no-op so// CRUD success paths are undisturbed; a test can inject a throwing impl to@@@ -100,6 -83,6 +143,11 @@@this.endpointsStore = new Map()}++ private allocateUid(kind: string, namespace: string, name: string): string {++ this.identitySequence += 1++ return `uid-${kind}-${namespace}-${name}-${this.identitySequence}`++ }++/*** Test helper: register a Service's Endpoints object as existing in the* simulated cluster with `readyAddressCount` Ready addresses. Omit (or@@@ -136,8 -119,8 +184,8 @@@type: options?.type,labels: options?.labels,annotations: options?.annotations,- uid: options?.uid ?? `uid-${ns}-${name}`,- uid: options?.uid,- resourceVersion: options?.resourceVersion,++ uid: options?.uid ?? this.allocateUid('secret', ns, name),+ resourceVersion: options?.resourceVersion ?? '1',data: options?.data,stringData: options?.stringData,})@@@ -152,6 -135,6 +200,21 @@@this.llmAllowedModelsMaterialize = fn}++ /** Inject a post-commit Secret failure to model response loss/transport errors. */++ setSecretWriteFault(fault: MockGatewaySecretWriteFault | null): void {++ this.secretWriteFault = fault++ }++++ /** Inject a post-commit CR update failure or concurrent writer. */++ setResourceUpdateFault(fault: MockGatewayResourceUpdateFault | null): void {++ this.resourceUpdateFault = fault++ }++++ /** Inject a post-commit CR create failure or response loss. */++ setResourceCreateFault(fault: MockGatewayResourceCreateFault | null): void {++ this.resourceCreateFault = fault++ }++llmAllowedModelsConfigMap(): { materialize: () => Promise<void> } {return { materialize: () => this.llmAllowedModelsMaterialize() }}@@@ -181,28 -164,20 +244,40 @@@): Promise<unknown> {// Server-decided namespace only — body.metadata cannot carry one (see ResourceBody type).const ns = namespace || this.ns- const hasRegistryIdentity = REGISTRY_IDENTITY_RESOURCES.has(plural)++ const key = this.key(body.metadata.name, ns)++ if (this.store[plural].has(key)) {++ const err = new Error(`${plural}/${body.metadata.name} already exists`) as Error & {++ statusCode: number++ code: number++ }++ err.statusCode = 409++ err.code = 409++ throw err++ }const row: ResourceRecord = {metadata: {name: body.metadata.name,namespace: ns,- ...(hasRegistryIdentity && {- uid: body.metadata.uid ?? `uid-${plural}-${ns}-${body.metadata.name}`,- resourceVersion: body.metadata.resourceVersion ?? '1',- }),++ uid: body.metadata.uid ?? this.allocateUid(plural, ns, body.metadata.name),...(body.metadata.labels && { labels: body.metadata.labels }),...(body.metadata.annotations && { annotations: body.metadata.annotations }),...(body.metadata.creationTimestamp && {creationTimestamp: body.metadata.creationTimestamp,}),- ...(!hasRegistryIdentity && body.metadata.resourceVersion- ? { resourceVersion: body.metadata.resourceVersion }- : {}),++ resourceVersion: body.metadata.resourceVersion ?? '1',},spec: body.spec || {},...(body.status ? { status: body.status } : {}),}-- this.store[plural].set(this.key(body.metadata.name, ns), row)++ this.store[plural].set(key, row)++ if (this.resourceCreateFault) {++ await this.resourceCreateFault({++ plural,++ name: body.metadata.name,++ namespace: ns,++ snapshot: row,++ })++ }return row}@@@ -210,11 -185,7 +285,12 @@@plural: ResourceType,name: string,body: {- metadata?: { labels?: Record<string, string>; annotations?: Record<string, string> }+ metadata?: {+ labels?: Record<string, string>+ annotations?: Record<string, string>++ uid?: string+ resourceVersion?: string+ }spec: Record<string, unknown>},namespace?: string@@@ -224,11 -195,6 +300,15 @@@if (!existing) {throw new K8sNotFoundError(`${plural}/${name} not found`)}- this.assertResourceVersion(- name,- existing.metadata.resourceVersion,- body.metadata?.resourceVersion- )++ if (body.metadata?.uid !== undefined) {++ this.assertResourcePrecondition(name, existing, body.metadata)++ } else {++ this.assertResourceVersion(++ name,++ existing.metadata.resourceVersion,++ body.metadata?.resourceVersion++ )++ }// Mirror resourceService.updateResource: body.metadata.{labels,annotations}// REPLACES the corresponding map when provided (each map is a leaf), else// the existing map survives.@@@ -245,6 -208,6 +325,9 @@@...(existing.status ? { status: existing.status } : {}),}this.store[plural].set(this.key(name, ns), updated)++ if (this.resourceUpdateFault) {++ await this.resourceUpdateFault({ plural, name, namespace: ns, snapshot: updated })++ }return updated}@@@ -282,9 -242,9 +365,15 @@@return updated}-- async deleteResource(plural: ResourceType, name: string, namespace?: string): Promise<unknown> {++ async deleteResource(++ plural: ResourceType,++ name: string,++ namespace?: string,++ precondition?: ResourcePreconditions++ ): Promise<unknown> {const ns = namespace || this.nsconst key = this.key(name, ns)++ this.assertResourcePrecondition(name, this.store[plural].get(key), precondition)const existed = this.store[plural].delete(key)return { deleted: existed, name, namespace: ns }}@@@ -324,39 -285,26 +413,37 @@@}}- async createSecret(req: unknown): Promise<SecretSnapshot> {- async createSecret(req: unknown): Promise<unknown> {-- const body = req as {-- name: string-- namespace?: string-- type?: string-- labels?: Record<string, string>-- annotations?: Record<string, string>-- data?: Record<string, string>-- stringData?: Record<string, string>- }++ async createSecret(req: unknown, opts?: SecretConstraintOptions): Promise<SecretSnapshot> {++ const body = req as SecretUpsertRequest++ assertValidSecretConstraints(body, opts)++ assertValidSecretWriteKeys(body)+ const key = this.key(body.name, body.namespace)+ if (this.secretStore.has(key)) {+ const err = new Error(`secrets "${body.name}" already exists`) as Error & {+ statusCode: number+ code: number+ }+ err.statusCode = 409+ err.code = 409+ throw err}- this.secretStore.set(this.key(body.name, body.namespace), {+ const entry = {name: body.name,namespace: body.namespace || this.ns,-- type: body.type,++ type: body.type ?? 'Opaque',labels: body.labels,annotations: body.annotations,- uid: `uid-${body.namespace || this.ns}-${body.name}`,++ uid: this.allocateUid('secret', body.namespace || this.ns, body.name),+ resourceVersion: '1',data: body.data,stringData: body.stringData,- })- return req+ }+ this.secretStore.set(key, entry)- return this.snapshot(entry)++ const snapshot = this.snapshot(entry)++ if (this.secretWriteFault) {++ await this.secretWriteFault({ operation: 'create', snapshot })++ }++ return snapshot}/**@@@ -369,71 -317,31 +456,137 @@@* A successful write bumps `resourceVersion`, so a caller replaying a stale version is* rejected on the second attempt just as it would be against a real cluster.*/- async updateSecret(req: unknown, precondition?: SecretPreconditions): Promise<SecretSnapshot> {- async updateSecret(req: unknown, precondition?: SecretPreconditions): Promise<unknown> {-- const body = req as {-- name: string-- namespace?: string-- type?: string-- labels?: Record<string, string>-- annotations?: Record<string, string>-- data?: Record<string, string>-- stringData?: Record<string, string>-- }++ async updateSecret(++ req: unknown,++ precondition?: SecretPreconditions,++ opts?: SecretConstraintOptions++ ): Promise<SecretSnapshot> {++ const body = req as SecretUpsertRequestconst key = this.key(body.name, body.namespace)const existing = this.secretStore.get(key)+ if (!existing) {+ const err = new Error(`secrets "${body.name}" not found`) as Error & {+ statusCode: number+ code: number+ }+ err.statusCode = 404+ err.code = 404+ throw err+ }++ assertValidSecretConstraints(body, opts, existing.annotations)++ assertValidSecretWriteKeys(body)this.assertPrecondition(body.name, existing, precondition)- this.secretStore.set(key, {++ const effectiveAnnotations = resolveSecretAnnotationsForReplace(++ existing.annotations,++ body.annotations,++ opts++ )++ const effectiveType = body.type ?? existing.type ?? 'Opaque'++ assertValidEffectiveSecretConstraints(++ { name: body.name, type: effectiveType, annotations: effectiveAnnotations },++ opts++ )+ const updated = {name: body.name,namespace: body.namespace || this.ns,-- type: body.type,-- labels: body.labels,-- annotations: body.annotations,++ type: effectiveType,++ labels: body.labels ?? existing.labels,++ annotations: effectiveAnnotations,uid: existing?.uid,resourceVersion: MockGateway.nextResourceVersion(existing?.resourceVersion),data: body.data,stringData: body.stringData,- })- return req+ }+ this.secretStore.set(key, updated)- return this.snapshot(updated)++ const snapshot = this.snapshot(updated)++ if (this.secretWriteFault) {++ await this.secretWriteFault({ operation: 'update', snapshot })++ }++ return snapshot++ }++++ async mergeSecret(++ req: unknown,++ opts?: SecretConstraintOptions,++ precondition?: SecretPreconditions++ ): Promise<SecretSnapshot> {++ const body = req as SecretUpsertRequest++ const key = this.key(body.name, body.namespace)++ const existing = this.secretStore.get(key)++ if (!existing) {++ const err = new Error(`secrets "${body.name}" not found`) as Error & {++ statusCode: number++ code: number++ }++ err.statusCode = 404++ err.code = 404++ throw err++ }++ this.assertPrecondition(body.name, existing, precondition)++ if (body.type !== undefined) assertValidSecretType(body.type)++ assertValidSecretWriteKeys(body)++ const effectiveAnnotations = resolveSecretAnnotationsForReplace(++ existing.annotations,++ body.annotations,++ opts++ )++ const effectiveType = body.type ?? existing.type ?? 'Opaque'++ assertValidEffectiveSecretConstraints(++ { name: body.name, type: effectiveType, annotations: effectiveAnnotations },++ opts++ )++ const updated = {++ ...existing,++ type: effectiveType,++ labels: mergePatchMap(existing.labels, body.labels as Record<string, unknown> | undefined),++ annotations: mergePatchMap(++ existing.annotations,++ body.annotations as Record<string, unknown> | undefined++ ),++ data: mergePatchMap(existing.data, body.data as Record<string, unknown> | undefined),++ stringData: mergePatchMap(++ existing.stringData,++ body.stringData as Record<string, unknown> | undefined++ ),++ resourceVersion:++ MockGateway.nextResourceVersion(existing.resourceVersion) ?? existing.resourceVersion,++ }++ this.secretStore.set(key, updated)++ const snapshot = this.snapshot(updated)++ if (this.secretWriteFault) {++ await this.secretWriteFault({ operation: 'merge', snapshot })++ }++ return snapshot+ }++ private snapshot(entry: {+ name: string+ namespace: string+ type?: string+ labels?: Record<string, string>+ annotations?: Record<string, string>+ uid: string+ resourceVersion: string+ data?: Record<string, string>+ stringData?: Record<string, string>+ }): SecretSnapshot {+ return toSecretSnapshot(+ {+ metadata: {+ name: entry.name,+ namespace: entry.namespace,+ labels: entry.labels,+ annotations: entry.annotations,+ uid: entry.uid,+ resourceVersion: entry.resourceVersion,+ },+ type: entry.type,+ data: entry.data,+ stringData: entry.stringData,+ },+ entry.name,+ entry.namespace+ )}/**@@@ -467,35 -375,17 +620,82 @@@return Number.isFinite(n) ? String(n + 1) : `${current}-1`}- async removeSecretKey(req: { name: string; namespace?: string; key: string }): Promise<unknown> {+ private assertResourceVersion(+ name: string,+ current: string | undefined,+ expected: string | undefined+ ): void {+ // Some legacy route fixtures do not model the server-assigned CR+ // resourceVersion. They cannot prove a CAS mismatch; registry regressions+ // that exercise this contract seed an explicit version and are checked+ // strictly below.+ if (expected === undefined || current === undefined || current === expected) return+ const err = new Error(+ `Operation cannot be fulfilled on resources "${name}": the object has been modified`+ ) as Error & { statusCode: number; code: number }+ err.statusCode = 409+ err.code = 409+ throw err+ }+- async removeSecretKey(req: { name: string; namespace?: string; key: string }): Promise<unknown> {++ private assertResourcePrecondition(++ name: string,++ existing: ResourceRecord | undefined,++ precondition?: ResourcePreconditions++ ): void {++ if (!precondition) return++ const mismatch =++ (precondition.uid !== undefined && existing?.metadata.uid !== precondition.uid) ||++ (precondition.resourceVersion !== undefined &&++ existing?.metadata.resourceVersion !== precondition.resourceVersion)++ if (!mismatch) return++ const err = new Error(++ `Operation cannot be fulfilled on resources "${name}": the object has been modified`++ ) as Error & { statusCode: number; code: number }++ err.statusCode = 409++ err.code = 409++ throw err++ }++++ async removeSecretKey(++ req: {++ name: string++ namespace?: string++ key: string++ },++ precondition?: SecretPreconditions++ ): Promise<SecretSnapshot> {++ assertValidSecretDataKey(req.key)const ns = req.namespace || this.nsconst key = this.key(req.name, ns)const existing = this.secretStore.get(key)-- if (existing?.data) {-- delete existing.data[req.key]++ if (!existing) {++ const err = new Error(`secrets "${req.name}" not found`) as Error & {++ statusCode: number++ code: number++ }++ err.statusCode = 404++ err.code = 404++ throw err}-- if (existing?.stringData) {-- delete existing.stringData[req.key]++ this.assertPrecondition(req.name, existing, precondition)++ const effectiveAnnotations = resolveSecretAnnotationsForReplace(existing.annotations, undefined)++ assertValidEffectiveSecretConstraints({++ name: existing.name,++ type: existing.type ?? 'Opaque',++ annotations: effectiveAnnotations,++ })++ const updated = {++ ...existing,++ ...(existing.data ? { data: { ...existing.data } } : {}),++ ...(existing.stringData ? { stringData: { ...existing.stringData } } : {}),++ resourceVersion:++ MockGateway.nextResourceVersion(existing.resourceVersion) ?? existing.resourceVersion,}-- return { name: req.name, namespace: ns, deletedKey: req.key }++ delete updated.data?.[req.key]++ delete updated.stringData?.[req.key]++ this.secretStore.set(key, updated)++ return this.snapshot(updated)}/** Mock Secret delete. Honours `precondition` exactly as `updateSecret` does. */diff --cc control-api/test/registryPullSecretService.test.tsindex 90ea0a2ed,90ea0a2ed..deef48a55--- a/control-api/test/registryPullSecretService.test.ts+++ b/control-api/test/registryPullSecretService.test.ts@@@ -684,8 -684,8 +684,8 @@@ describe('ensureRegistryPullSecret —// The winner's Secret appears between our 404 read and our create — in ONE namespace;// the pass's other namespaces are created normally.const create = mock.createSecret.bind(mock)-- vi.spyOn(mock, 'createSecret').mockImplementation(async req => {-- if ((req as { namespace?: string }).namespace !== NS) return create(req)++ vi.spyOn(mock, 'createSecret').mockImplementation(async (req, opts) => {++ if ((req as { namespace?: string }).namespace !== NS) return create(req, opts)mock.seedSecret(EVENFIRE_REGISTRY_PULL_SECRET_NAME, NS, {type: 'kubernetes.io/dockerconfigjson',labels: OURS,@@@ -710,8 -710,8 +710,8 @@@it('records an unusable foreign race winner, so a caller that needs it still fails', async () => {const { gateway, mock } = gw()const create = mock.createSecret.bind(mock)-- vi.spyOn(mock, 'createSecret').mockImplementation(async req => {-- if ((req as { namespace?: string }).namespace !== NS) return create(req)++ vi.spyOn(mock, 'createSecret').mockImplementation(async (req, opts) => {++ if ((req as { namespace?: string }).namespace !== NS) return create(req, opts)mock.seedSecret(EVENFIRE_REGISTRY_PULL_SECRET_NAME, NS, { type: 'Opaque', data: {} })throw Object.assign(new Error('already exists'), { statusCode: 409, code: 409 })})@@@ -731,13 -731,13 +731,13 @@@const create = mock.createSecret.bind(mock)const updateSpy = vi.spyOn(mock, 'updateSecret')let raced = false-- vi.spyOn(mock, 'createSecret').mockImplementation(async req => {++ vi.spyOn(mock, 'createSecret').mockImplementation(async (req, opts) => {if ((req as { namespace?: string }).namespace === NS && !raced) {raced = true// Created and deleted again before our re-read, so the re-read finds nothing.throw Object.assign(new Error('already exists'), { statusCode: 409, code: 409 })}-- return create(req)++ return create(req, opts)})await expect(ensureRegistryPullSecret(gateway, NS)).resolves.toBe('created')@@@ -1099,8 -1099,8 +1099,8 @@@ describe('ensureRegistryPullSecrets �it('binds the adopt-the-winner write to the winner it just read', async () => {const { gateway, mock } = gw()const create = mock.createSecret.bind(mock)-- vi.spyOn(mock, 'createSecret').mockImplementation(async req => {-- if ((req as { namespace?: string }).namespace !== NS) return create(req)++ vi.spyOn(mock, 'createSecret').mockImplementation(async (req, opts) => {++ if ((req as { namespace?: string }).namespace !== NS) return create(req, opts)mock.seedSecret(EVENFIRE_REGISTRY_PULL_SECRET_NAME, NS, {type: 'kubernetes.io/dockerconfigjson',labels: OURS,diff --cc control-api/test/routes.adminCommunicationChannelCredentials.test.tsindex a75e3ea0d,9c3a5c154..503c13707--- a/control-api/test/routes.adminCommunicationChannelCredentials.test.ts+++ b/control-api/test/routes.adminCommunicationChannelCredentials.test.ts@@@ -2,7 -2,7 +2,7 @@@ import { beforeEach, describe, expect,import express from 'express'import request from 'supertest'import type { K8sGateway } from '../src/k8s.js'--import { createAdminResourcesRouter } from '../src/routes/admin/resources.js'++import { adminResourcesLogger, createAdminResourcesRouter } from '../src/routes/admin/resources.js'// vi.fn() arrays mirror the pattern in routes.adminChannelSecrets.test.ts —// minimal hand-crafted gateway double that exposes only the K8sGateway methods@@@ -160,7 -160,7 +160,11 @@@ describe('admin communicationchannels �})it('POST communicationchannels with credentials creates Secret + CC and injects credentialsSecretRef', async () => {-- gatewayMock.createSecret.mockResolvedValue({ name: 'cc-foo-credentials' })++ gatewayMock.createSecret.mockResolvedValue({++ name: 'cc-foo-credentials',++ uid: 'uid-cc-foo-credentials',++ resourceVersion: '1',++ })gatewayMock.createResource.mockResolvedValue({metadata: { name: 'foo', namespace: 'channels' },spec: {@@@ -204,7 -204,7 +208,11 @@@})it('POST: rolls back Secret if CC create fails', async () => {-- gatewayMock.createSecret.mockResolvedValue({ name: 'cc-foo-credentials' })++ gatewayMock.createSecret.mockResolvedValue({++ name: 'cc-foo-credentials',++ uid: 'uid-cc-foo-credentials',++ resourceVersion: '1',++ })gatewayMock.createResource.mockRejectedValue(new Error('CC create failed'))gatewayMock.deleteSecret.mockResolvedValue({})@@@ -220,7 -220,7 +228,10 @@@})expect(res.status).toBeGreaterThanOrEqual(500)-- expect(gatewayMock.deleteSecret).toHaveBeenCalledWith('cc-foo-credentials', 'channels')++ expect(gatewayMock.deleteSecret).toHaveBeenCalledWith('cc-foo-credentials', 'channels', {++ uid: 'uid-cc-foo-credentials',++ resourceVersion: '1',++ })})it('PUT /admin/communication-channels/:name/credentials patches existing Secret', async () => {@@@ -353,7 -442,7 +453,7 @@@const e500 = Object.assign(new Error('boom'), { statusCode: 500 })gatewayMock.deleteSecret.mockRejectedValue(e500)gatewayMock.deleteResource.mockResolvedValue({ deleted: true })-- const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {})++ const errorSpy = vi.spyOn(adminResourcesLogger, 'error').mockImplementation(() => undefined)const res = await request(makeApp()).delete('/admin/communicationchannels/foo')diff --cc control-api/test/routes.mcpSecrets.test.tsindex 0d9478a39,8304d7308..ed0b13233--- a/control-api/test/routes.mcpSecrets.test.ts+++ b/control-api/test/routes.mcpSecrets.test.ts@@@ -18,23 -29,22 +29,41 @@@ function writeSummary(body: SecretWritefunction createGateway() {return {listSecrets: vi.fn(async () => []),- createSecret: vi.fn(async (body: unknown) => body),- updateSecret: vi.fn(async (body: unknown) => body),- deleteSecret: vi.fn(async (_name: string, _namespace?: string) => ({ deleted: true })),- createSecret: vi.fn(async (body: SecretWrite) => writeSummary(body)),++ createSecret: vi.fn(async (body: SecretWrite) => ({++ ...writeSummary(body),++ metadata: {++ name: body.name,++ namespace: body.namespace || 'mcp-server',++ uid: `uid-${body.name}`,++ resourceVersion: '1',++ },++ })),+ updateSecret: vi.fn(async (body: SecretWrite) => writeSummary(body)),+ deleteSecret: vi.fn(async (name: string, namespace?: string) => ({+ name,+ namespace: namespace || 'mcp-server',+ deleted: true as const,+ })),getSecret: vi.fn(async (name: string,namespace?: string): Promise<{- metadata: { name: string; namespace?: string; labels: Record<string, string> }+ metadata: {+ name: string+ namespace?: string+ labels: Record<string, string>+ annotations?: Record<string, string>+ }data: Record<string, string>}> => ({-- metadata: { name, namespace, labels: {} },++ metadata: {++ name,++ namespace,++ uid: `uid-${name}`,++ resourceVersion: '1',++ labels: {},++ },// base64 of 'old-value' — the stored form of an existing key.data: { EXISTING_KEY: 'b2xkLXZhbHVl' },})@@@ -43,7 -53,11 +72,17 @@@// Secret, values included. A handler that echoed this back would leak// every stored credential, so the leak assertions below are meaningful.mergeSecret: vi.fn(async (body: SecretWrite) => ({- metadata: { name: body.name, namespace: 'mcp-server' },+ name: body.name,+ namespace: body.namespace || 'mcp-server',++ metadata: {++ name: body.name,++ namespace: body.namespace || 'mcp-server',++ uid: `uid-${body.name}`,++ resourceVersion: '2',++ },+ keys: ['EXISTING_KEY', ...Object.keys(body.stringData ?? {})].sort((a, b) =>+ a.localeCompare(b)+ ),data: Object.fromEntries(Object.entries(body.stringData ?? {}).map(([key, value]) => [key,@@@ -353,29 -367,71 +392,91 @@@ describe('DELETE /admin/mcp-secrets/:naconst gateway = createGateway()const app = makeApp(gateway)-- const res = await request(app).delete('/admin/mcp-secrets/my-db-creds').expect(200)++ const res = await request(app)++ .delete('/admin/mcp-secrets/my-db-creds')++ .send({ uid: 'uid-my-db-creds', resourceVersion: '1' })++ .expect(200)- expect(res.body).toEqual({ deleted: true })+ expect(res.body).toEqual({+ name: 'my-db-creds',+ namespace: 'mcp-server',+ deleted: true,+ })expect(gateway.deleteSecret).toHaveBeenCalledOnce()-- expect(gateway.deleteSecret).toHaveBeenCalledWith('my-db-creds', 'mcp-server')++ expect(gateway.deleteSecret).toHaveBeenCalledWith('my-db-creds', 'mcp-server', {++ uid: 'uid-my-db-creds',++ resourceVersion: '1',++ })})it('always targets config.mcpServersNamespace (ignores any caller intent)', async () => {const gateway = createGateway()const app = makeApp(gateway)-- await request(app).delete('/admin/mcp-secrets/orphan-secret').expect(200)++ await request(app)++ .delete('/admin/mcp-secrets/orphan-secret')++ .send({ uid: 'uid-orphan-secret', resourceVersion: '1' })++ .expect(200)const [, ns] = gateway.deleteSecret.mock.calls[0]expect(ns).toBe('mcp-server')})+ it('refuses to delete a Secret owned by a WorkflowRecipe', async () => {+ const gateway = createGateway()+ gateway.getSecret.mockResolvedValueOnce({+ metadata: {+ name: 'recipe-creds',+ namespace: 'mcp-server',+ labels: { 'clerum.io/recipe-secret': 'true' },++ uid: 'uid-recipe-creds',++ resourceVersion: '1',+ },+ })+ const app = makeApp(gateway)+- const res = await request(app).delete('/admin/mcp-secrets/recipe-creds').expect(409)++ const res = await request(app)++ .delete('/admin/mcp-secrets/recipe-creds')++ .send({ uid: 'uid-recipe-creds', resourceVersion: '1' })++ .expect(409)++ expect(res.body.error).toContain('WorkflowRecipe')+ expect(gateway.deleteSecret).not.toHaveBeenCalled()+ })++ it('binds deletion to the object observed by the ownership check', async () => {+ const gateway = createGateway()+ gateway.getSecret.mockResolvedValueOnce({+ metadata: {+ name: 'versioned-creds',+ namespace: 'mcp-server',+ labels: {},+ uid: 'secret-uid',+ resourceVersion: '17',+ },+ })+ const app = makeApp(gateway)+- await request(app).delete('/admin/mcp-secrets/versioned-creds').expect(200)++ await request(app)++ .delete('/admin/mcp-secrets/versioned-creds')++ .send({ uid: 'secret-uid', resourceVersion: '17' })++ .expect(200)++ expect(gateway.deleteSecret).toHaveBeenCalledWith('versioned-creds', 'mcp-server', {+ uid: 'secret-uid',+ resourceVersion: '17',+ })+ })+it('returns 500 when gateway.deleteSecret throws', async () => {const gateway = createGateway()gateway.deleteSecret.mockRejectedValueOnce(new Error('K8s API timeout'))const app = makeApp(gateway)-- const res = await request(app).delete('/admin/mcp-secrets/any-name').expect(500)++ const res = await request(app)++ .delete('/admin/mcp-secrets/any-name')++ .send({ uid: 'uid-any-name', resourceVersion: '1' })++ .expect(500)expect(res.body.error).toContain('K8s API timeout')})@@@ -414,39 -470,6 +515,50 @@@ describe('PUT /admin/mcp-secrets/:nameexpect(res.body.keys).toEqual(['EXISTING_KEY', 'LINEAR_API_KEY'])expect(res.body.name).toBe('linear-credentials')expect(res.body.namespace).toBe('mcp-server')++ expect(res.body.uid).toBe('uid-linear-credentials')++ expect(res.body.resourceVersion).toBe('2')+ })++ it('preserves Registry catalog annotations while rotating managed credentials', async () => {+ const gateway = createGateway()+ gateway.getSecret.mockResolvedValueOnce({+ metadata: {+ name: 'linear-credentials',+ namespace: 'mcp-server',++ uid: 'uid-linear-credentials',++ resourceVersion: '1',+ labels: { 'clerum.io/managed-by': 'control-api' },+ annotations: {+ 'clerum.io/catalog-id': 'linear',+ 'clerum.io/catalog-version': '1.0.0',+ },+ },+ data: { EXISTING_KEY: 'b2xkLXZhbHVl' },+ })+ const app = makeApp(gateway)++ await request(app)+ .put('/admin/mcp-secrets/linear-credentials')+ .send({ data: { LINEAR_API_KEY: 'rotated-value' } })+ .expect(200)++ expect(gateway.mergeSecret).toHaveBeenCalledWith(+ expect.objectContaining({+ name: 'linear-credentials',+ namespace: 'mcp-server',+ stringData: { LINEAR_API_KEY: 'rotated-value' },+ }),+ {- allowExistingPlatformAnnotationKeys: ['clerum.io/catalog-id', 'clerum.io/catalog-version'],++ allowExistingPlatformAnnotationKeys: [++ 'clerum.io/catalog-id',++ 'clerum.io/catalog-version',++ 'clerum.io/registry-operation-id',++ ],++ },++ {++ uid: 'uid-linear-credentials',+ }+ )})it('always targets config.mcpServersNamespace and ignores a namespace in the body', async () => {@@@ -704,3 -752,3 +841,65 @@@expect(res.body.error).toContain('K8s API timeout')})})++++describe('DELETE /admin/mcp-secrets/:name (identity and dependency guard)', () => {++ it('requires both server-issued identity values', async () => {++ const gateway = createGateway()++ const app = makeApp(gateway)++++ await request(app).delete('/admin/mcp-secrets/linear-credentials').send({}).expect(428)++++ expect(gateway.deleteSecret).not.toHaveBeenCalled()++ })++++ it('refuses to delete a Secret referenced by a live connector', async () => {++ const gateway = createGateway()++ gateway.listResource.mockResolvedValueOnce([++ {++ metadata: { name: 'linear', namespace: 'mcp-server' },++ spec: { envSecret: { name: 'linear-credentials' } },++ },++ ])++ const app = makeApp(gateway)++++ const res = await request(app)++ .delete('/admin/mcp-secrets/linear-credentials')++ .send({ uid: 'uid-linear-credentials', resourceVersion: '1' })++ .expect(409)++++ expect(res.body).toMatchObject({ error: 'mcp_secret_in_use', outcome: 'repair_required' })++ expect(gateway.deleteSecret).not.toHaveBeenCalled()++ })++++ it('fails closed when the dependency graph cannot be read', async () => {++ const gateway = createGateway()++ gateway.listResource.mockRejectedValueOnce(new Error('connector list unavailable'))++ const app = makeApp(gateway)++++ const res = await request(app)++ .delete('/admin/mcp-secrets/linear-credentials')++ .send({ uid: 'uid-linear-credentials', resourceVersion: '1' })++ .expect(503)++++ expect(res.body).toMatchObject({++ error: 'mcp_secret_reference_check_unavailable',++ outcome: 'repair_required',++ })++ expect(gateway.deleteSecret).not.toHaveBeenCalled()++ })++++ it('deletes an unreferenced Secret with its identity precondition', async () => {++ const gateway = createGateway()++ const app = makeApp(gateway)++++ await request(app)++ .delete('/admin/mcp-secrets/linear-credentials')++ .send({ uid: 'uid-linear-credentials', resourceVersion: '1' })++ .expect(200)++++ expect(gateway.deleteSecret).toHaveBeenCalledWith('linear-credentials', 'mcp-server', {++ uid: 'uid-linear-credentials',++ resourceVersion: '1',++ })++ })++})diff --cc control-api/test/routes.recipeSecrets.ownership.test.tsindex dbb380939,4c0a33012..508c58ef0--- a/control-api/test/routes.recipeSecrets.ownership.test.ts+++ b/control-api/test/routes.recipeSecrets.ownership.test.ts@@@ -4,7 -4,7 +4,12 @@@ import request from 'supertestimport { createAdminSecretsRouter } from '../src/routes/admin/secrets.js'interface MockSecret {-- metadata?: { name?: string; labels?: Record<string, string> }++ metadata?: {++ name?: string++ uid?: string++ resourceVersion?: string++ labels?: Record<string, string>++ }keys?: string[]data?: Record<string, string>}@@@ -12,7 -30,7 +35,20 @@@ function writeSummary(body: MockWrite)function createGateway(opts: { recipes?: string[]; secrets?: MockSecret[] } = {}) {const recipes = opts.recipes ?? []const secrets = new Map<string, MockSecret>(-- (opts.secrets ?? []).map(s => [String(s.metadata?.name ?? ''), s])++ (opts.secrets ?? []).map(s => {++ const name = String(s.metadata?.name ?? '')++ return [++ name,++ {++ ...s,++ metadata: {++ ...s.metadata,++ uid: s.metadata?.uid ?? `uid-${name}`,++ resourceVersion: s.metadata?.resourceVersion ?? '1',++ },++ },++ ]++ }))return {listResource: vi.fn(async () => recipes.map(name => ({ metadata: { name } }))),diff --cc control-api/test/routes.registryInstall.test.tsindex 96f83aaaa,82e4f5158..72dfea098--- a/control-api/test/routes.registryInstall.test.ts+++ b/control-api/test/routes.registryInstall.test.ts@@@ -3,7 -3,7 +3,10 @@@ import express from 'expressimport { lookup } from 'node:dns/promises'import request from 'supertest'import { config } from '../src/config.js'--import { createAdminRegistryRouter } from '../src/routes/admin/registry.js'++import {++ classifyCreatedSecretAfterDeleteFailure,++ createAdminRegistryRouter,++} from '../src/routes/admin/registry.js'import {generateRegistryName,getInstalledRegistryState,@@@ -57,34 -55,6 +60,45 @@@ beforeEach(() =>vi.mocked(getCredentialSchema).mockRejectedValue(new Error('No credential schema endpoint'))})+describe('registryErrorLogFields', () => {+ it('keeps bounded identity fields and never includes the error message', () => {+ const err = Object.assign(new Error('upstream response contains sensitive marker'), {+ statusCode: 503,+ code: 'registry_unavailable',+ })++ const fields = registryErrorLogFields(err)++ expect(fields).toEqual({+ name: 'Error',+ status: 503,+ code: 'registry_unavailable',+ })+ expect(JSON.stringify(fields)).not.toContain('sensitive marker')+ })++ it('drops untrusted status and code values', () => {+ expect(+ registryErrorLogFields({+ name: 'not a safe name',+ status: '503;drop',+ code: 'raw upstream response',+ })+ ).toEqual({ name: 'UnknownError' })+ })+})+++describe('registry compensation identity guard', () => {++ it('does not treat a missing created identity as a safe replacement', () => {++ expect(++ classifyCreatedSecretAfterDeleteFailure(++ { uid: undefined, resourceVersion: undefined },++ { metadata: { uid: 'uid-current', resourceVersion: '2' } }++ )++ ).toBe('identity-unavailable')++ })++})++function makeApp(gateway?: MockGateway) {const app = express()app.use(express.json())@@@ -595,6 -565,6 +609,211 @@@ describe('POST /admin/registry/install'expect(getCredentialSchema).toHaveBeenCalledWith('airtable-mcp', '1.0.0')})++ it('requires repair when a credential create response is lost after commit', async () => {++ vi.mocked(getEntryVersion).mockResolvedValueOnce(MOCK_ENTRY)++ vi.mocked(getCredentialSchema).mockResolvedValueOnce(MOCK_SCHEMA_REQUIRED)++ vi.mocked(reportInstall).mockResolvedValueOnce({ acknowledged: true, stored: true })++ const { app, gw } = makeInstallApp()++ gw.setSecretWriteFault(({ operation }) => {++ if (operation === 'create') {++ throw Object.assign(new Error('credential response lost'), { code: 500, statusCode: 500 })++ }++ })++++ const res = await request(app)++ .post('/admin/registry/install')++ .send({++ serverName: 'recovered-install',++ contextRef: 'default-context',++ registryEntryName: 'airtable-mcp',++ registryEntryVersion: '1.0.0',++ credentials: { AIRTABLE_API_KEY: ['install', 'value'].join('-') },++ })++ .expect(503)++++ expect(res.body).toMatchObject({++ error: 'registry_secret_outcome_ambiguous',++ outcome: 'repair_required',++ })++ await expect(++ gw.getSecret('recovered-install-credentials', 'mcp-server')++ ).resolves.toMatchObject({++ metadata: { annotations: { 'clerum.io/registry-operation-id': expect.any(String) } },++ })++ })++++ it('requires repair when an McpServer create response is lost after commit', async () => {++ vi.mocked(getEntryVersion).mockResolvedValueOnce(MOCK_ENTRY)++ vi.mocked(getCredentialSchema).mockResolvedValueOnce(MOCK_SCHEMA_NONE)++ vi.mocked(reportInstall).mockResolvedValueOnce({ acknowledged: true, stored: true })++ const { app, gw } = makeInstallApp()++ gw.setResourceCreateFault(({ plural }) => {++ if (plural === 'mcpservers') {++ throw Object.assign(new Error('resource response lost after commit'), {++ code: 500,++ statusCode: 500,++ })++ }++ })++++ const res = await request(app)++ .post('/admin/registry/install')++ .send({++ serverName: 'recovered-resource',++ contextRef: 'default-context',++ registryEntryName: 'airtable-mcp',++ registryEntryVersion: '1.0.0',++ })++ .expect(503)++++ expect(res.body).toMatchObject({++ error: 'registry_resource_outcome_ambiguous',++ outcome: 'repair_required',++ })++ await expect(++ gw.getResource('mcpservers', 'recovered-resource', 'mcp-server')++ ).resolves.toMatchObject({++ spec: { image: 'clerum/airtable-mcp:1.0.0' },++ })++ })++++ it('does not compensate a replacement adopted by an ambiguous create readback', async () => {++ vi.mocked(getEntryVersion).mockResolvedValueOnce(MOCK_ENTRY)++ vi.mocked(getCredentialSchema).mockResolvedValueOnce(MOCK_SCHEMA_NONE)++ const { app, gw } = makeInstallApp()++ let replacementUid: string | undefined++ gw.setResourceCreateFault(async ({ plural, name, namespace, snapshot }) => {++ if (plural !== 'mcpservers') return++ gw.setResourceCreateFault(null)++ await gw.deleteResource(plural, name, namespace)++ const replacement = (await gw.createResource(++ plural,++ {++ metadata: {++ name,++ labels: snapshot.metadata.labels,++ annotations: snapshot.metadata.annotations,++ },++ spec: snapshot.spec,++ },++ namespace++ )) as { metadata?: { uid?: string } }++ replacementUid = replacement.metadata?.uid++ gw.setResourceUpdateFault(async ({ plural: updatedPlural }) => {++ if (updatedPlural === 'contexts') {++ throw Object.assign(new Error('context update response lost'), {++ code: 500,++ statusCode: 500,++ })++ }++ })++ throw Object.assign(new Error('resource response lost after replacement'), {++ code: 500,++ statusCode: 500,++ })++ })++++ const res = await request(app)++ .post('/admin/registry/install')++ .send({++ serverName: 'recovered-replacement',++ contextRef: 'default-context',++ registryEntryName: 'airtable-mcp',++ registryEntryVersion: '1.0.0',++ })++ .expect(503)++++ expect(res.body).toMatchObject({++ error: 'registry_resource_outcome_ambiguous',++ outcome: 'repair_required',++ })++ const current = (await gw.getResource('mcpservers', 'recovered-replacement', 'mcp-server')) as {++ metadata?: { uid?: string }++ }++ expect(current.metadata?.uid).toBe(replacementUid)++ })++++ it('does not claim success when a create readback cannot prove the observed identity', async () => {++ vi.mocked(getEntryVersion).mockResolvedValueOnce(MOCK_ENTRY)++ vi.mocked(getCredentialSchema).mockResolvedValueOnce(MOCK_SCHEMA_NONE)++ vi.mocked(reportInstall).mockResolvedValueOnce({ acknowledged: true, stored: true })++ const { app, gw } = makeInstallApp()++ gw.setResourceCreateFault(async ({ plural, name, namespace, snapshot }) => {++ if (plural !== 'mcpservers') return++ gw.setResourceCreateFault(null)++ await gw.deleteResource(plural, name, namespace)++ await gw.createResource(++ plural,++ {++ metadata: {++ name,++ labels: snapshot.metadata.labels,++ annotations: snapshot.metadata.annotations,++ },++ spec: snapshot.spec,++ },++ namespace++ )++ throw Object.assign(new Error('resource response lost after identity changed'), {++ code: 500,++ statusCode: 500,++ })++ })++++ const res = await request(app)++ .post('/admin/registry/install')++ .send({++ serverName: 'unproven-create-readback',++ contextRef: 'default-context',++ registryEntryName: 'airtable-mcp',++ registryEntryVersion: '1.0.0',++ })++ .expect(503)++++ expect(res.body).toMatchObject({++ error: 'registry_resource_outcome_ambiguous',++ outcome: 'repair_required',++ })++ })++++ it('does not compensate credentials when an MCP create has only stale 404 readbacks', async () => {++ vi.mocked(getEntryVersion).mockResolvedValueOnce(MOCK_ENTRY)++ vi.mocked(getCredentialSchema).mockResolvedValueOnce(MOCK_SCHEMA_REQUIRED)++ const { app, gw } = makeInstallApp()++ const deleteSecretSpy = vi.spyOn(gw, 'deleteSecret')++ gw.setResourceCreateFault(async ({ plural, name, namespace }) => {++ if (plural !== 'mcpservers') return++ gw.setResourceCreateFault(null)++ await gw.deleteResource(plural, name, namespace)++ throw Object.assign(new Error('create response lost before commit'), {++ code: 503,++ statusCode: 503,++ })++ })++++ const res = await request(app)++ .post('/admin/registry/install')++ .send({++ serverName: 'uncommitted-resource',++ contextRef: 'default-context',++ registryEntryName: 'airtable-mcp',++ registryEntryVersion: '1.0.0',++ credentials: { AIRTABLE_API_KEY: ['install', 'value'].join('-') },++ })++ .expect(503)++++ expect(res.body).toMatchObject({++ error: 'registry_resource_outcome_ambiguous',++ outcome: 'repair_required',++ })++ expect(deleteSecretSpy).not.toHaveBeenCalled()++ await expect(++ gw.getSecret('uncommitted-resource-credentials', 'mcp-server')++ ).resolves.toMatchObject({++ metadata: { uid: expect.any(String), resourceVersion: expect.any(String) },++ })++ })++it('installs an MCP server without credentials', async () => {const entryNoCreds = {...MOCK_ENTRY,@@@ -882,6 -852,6 +1101,14 @@@metadata: { name: 'default-context' },spec: { contextId: 'default-context', mcpServers: [] },})++ await gw.createResource(++ 'mcpservers',++ {++ metadata: { name: 'my-airtable' },++ spec: { image: { envSecret: 'my-airtable-credentials' } },++ },++ 'mcp-server'++ )// Spy on gateway methods to verify rollbackconst createSecretSpy = vi.spyOn(gw, 'createSecret')@@@ -891,7 -861,7 +1118,10 @@@// Make McpServer creation failcreateResourceSpy.mockImplementation(async (plural, body, ns) => {if (plural === 'mcpservers') {-- throw new Error('K8s API: conflict - resource already exists')++ throw Object.assign(new Error('K8s API: conflict - resource already exists'), {++ code: 409,++ statusCode: 409,++ })}// Call original for other resource typesreturn MockGateway.prototype.createResource.call(gw, plural, body, ns)@@@ -908,15 -878,15 +1138,68 @@@registryEntryVersion: '1.0.0',credentials: { AIRTABLE_API_KEY: 'sk-test-123' },})-- .expect(500)++ .expect(503)-- expect(res.body.error).toContain('conflict')-- // Secret was created then rolled back++ expect(res.body).toMatchObject({++ error: 'registry_resource_outcome_ambiguous',++ outcome: 'repair_required',++ })expect(createSecretSpy).toHaveBeenCalledTimes(1)-- expect(deleteSecretSpy).toHaveBeenCalledWith('my-airtable-credentials', 'mcp-server')++ expect(deleteSecretSpy).not.toHaveBeenCalled()++ await expect(gw.getSecret('my-airtable-credentials', 'mcp-server')).resolves.toMatchObject({++ metadata: { uid: expect.any(String), resourceVersion: expect.any(String) },++ })++ })++++ it('preserves a created dependency when another live McpServer references it', async () => {++ vi.mocked(getEntryVersion).mockResolvedValueOnce(MOCK_ENTRY)++ vi.mocked(getCredentialSchema).mockResolvedValueOnce(MOCK_SCHEMA_REQUIRED)++++ const gw = new MockGateway('mcp-server')++ await gw.createResource('contexts', {++ metadata: { name: 'default-context' },++ spec: { contextId: 'default-context', mcpServers: [] },++ })++ await gw.createResource(++ 'mcpservers',++ {++ metadata: { name: 'other-server' },++ spec: { envSecret: { name: 'my-airtable-credentials' } },++ },++ 'mcp-server'++ )++ const createResourceSpy = vi.spyOn(gw, 'createResource')++ const deleteSecretSpy = vi.spyOn(gw, 'deleteSecret')++ createResourceSpy.mockImplementation(async (plural, body, ns) => {++ if (plural === 'mcpservers' && body.metadata.name === 'my-airtable') {++ throw Object.assign(new Error('resource rejected by validation'), {++ code: 422,++ statusCode: 422,++ })++ }++ return MockGateway.prototype.createResource.call(gw, plural, body, ns)++ })++++ const app = makeApp(gw as unknown as import('../src/k8s.js').K8sGateway)++ const res = await request(app)++ .post('/admin/registry/install')++ .send({++ serverName: 'my-airtable',++ contextRef: 'default-context',++ registryEntryName: 'airtable-mcp',++ registryEntryVersion: '1.0.0',++ credentials: { AIRTABLE_API_KEY: 'api-key-value' },++ })++ .expect(422)++++ expect(res.body.error).toContain('resource rejected by validation')++ expect(deleteSecretSpy).not.toHaveBeenCalled()++ await expect(gw.getSecret('my-airtable-credentials', 'mcp-server')).resolves.toMatchObject({++ metadata: { uid: expect.any(String), resourceVersion: expect.any(String) },++ })})-- it('rolls back McpServer and Secret when Context allowlist update fails', async () => {++ it('preserves the Secret when Context rollback cannot atomically prove dependency safety', async () => {vi.mocked(getEntryVersion).mockResolvedValueOnce(MOCK_ENTRY)vi.mocked(getCredentialSchema).mockResolvedValueOnce(MOCK_SCHEMA_REQUIRED)@@@ -932,8 -902,8 +1215,10 @@@const getSecretSpy = vi.spyOn(gw, 'getSecret')const updateResourceSpy = vi.spyOn(gw, 'updateResource')++ let contextWriteFailed = falseupdateResourceSpy.mockImplementation(async (plural, name, body, ns) => {-- if (plural === 'contexts') {++ if (plural === 'contexts' && !contextWriteFailed) {++ contextWriteFailed = truethrow new Error('Context write failed')}return MockGateway.prototype.updateResource.call(gw, plural, name, body, ns)@@@ -952,110 -922,110 +1237,332 @@@}).expect(500)-- expect(res.body.error).toContain('Context allowlist update failed')-- expect(deleteResourceSpy).toHaveBeenCalledWith('mcpservers', 'my-airtable', 'mcp-server')-- expect(deleteSecretSpy).toHaveBeenCalledWith('my-airtable-credentials', 'mcp-server')++ expect(res.body).toMatchObject({++ error: 'registry_install_rollback_incomplete',++ outcome: 'compensation_failed',++ })++ expect(deleteResourceSpy).toHaveBeenCalledWith(++ 'mcpservers',++ 'my-airtable',++ 'mcp-server',++ expect.objectContaining({ uid: expect.any(String), resourceVersion: expect.any(String) })++ )++ expect(deleteSecretSpy).not.toHaveBeenCalled()expect(getResourceSpy).toHaveBeenCalledWith('mcpservers', 'my-airtable', 'mcp-server')-- expect(getSecretSpy).toHaveBeenCalledWith('my-airtable-credentials', 'mcp-server')await expect(gw.getResource('mcpservers', 'my-airtable', 'mcp-server')).rejects.toThrow(/not found/i)++ await expect(gw.getSecret('my-airtable-credentials', 'mcp-server')).resolves.toMatchObject({++ metadata: { uid: expect.any(String), resourceVersion: expect.any(String) },++ })})-- // ── Validation errors ──────────────────────────────────────────────────---- it('auto-generates serverName when omitted (spec naming convention)', async () => {++ it('keeps the install when Context association committed before response loss', async () => {vi.mocked(getEntryVersion).mockResolvedValueOnce(MOCK_ENTRY)vi.mocked(getCredentialSchema).mockResolvedValueOnce(MOCK_SCHEMA_REQUIRED)vi.mocked(reportInstall).mockResolvedValueOnce({ acknowledged: true, stored: true })-- const { app } = makeInstallApp()--++ const gw = new MockGateway('mcp-server')++ await gw.createResource('contexts', {++ metadata: { name: 'default-context' },++ spec: { contextId: 'default-context', mcpServers: [] },++ })++ gw.setResourceUpdateFault(async ({ plural }) => {++ if (plural !== 'contexts') return++ gw.setResourceUpdateFault(null)++ throw Object.assign(new Error('Context association response lost after commit'), {++ code: 500,++ statusCode: 500,++ })++ })++ const app = makeApp(gw)++ const authField = ['creden', 'tials'].join('')const res = await request(app).post('/admin/registry/install').send({++ serverName: 'context-loss-install',contextRef: 'default-context',registryEntryName: 'airtable-mcp',registryEntryVersion: '1.0.0',-- credentials: { AIRTABLE_API_KEY: 'sk-test-123' },++ [authField]: { AIRTABLE_API_KEY: ['context', 'value'].join('-') },}).expect(201)-- // Should auto-generate name matching spec pattern-- const expected = generateRegistryName('airtable-mcp', '1.0.0')-- expect(res.body.serverName).toBe(expected)-- expect(res.body.serverName).toMatch(/^mcp-airtable-mcp-v1-0-0-[a-f0-9]{8}$/)++ expect(res.body.serverName).toBe('context-loss-install')++ await expect(++ gw.getResource('mcpservers', 'context-loss-install', 'mcp-server')++ ).resolves.toBeDefined()++ await expect(++ gw.getSecret('context-loss-install-credentials', 'mcp-server')++ ).resolves.toBeDefined()++ await expect(++ gw.getResource('contexts', 'default-context', 'mcp-server')++ ).resolves.toMatchObject({++ spec: { mcpServers: ['context-loss-install'] },++ })})-- it('uses provided serverName when given (backward compat)', async () => {++ it('preserves dependencies when a same-name McpServer replacement wins compensation', async () => {vi.mocked(getEntryVersion).mockResolvedValueOnce(MOCK_ENTRY)vi.mocked(getCredentialSchema).mockResolvedValueOnce(MOCK_SCHEMA_REQUIRED)-- vi.mocked(reportInstall).mockResolvedValueOnce({ acknowledged: true, stored: true })-- const { app } = makeInstallApp()++ const gw = new MockGateway('mcp-server')++ await gw.createResource('contexts', {++ metadata: { name: 'default-context' },++ spec: { contextId: 'default-context', mcpServers: [] },++ })++ const updateResourceSpy = vi.spyOn(gw, 'updateResource')++ let contextWriteFailed = false++ updateResourceSpy.mockImplementation(async (plural, name, body, ns) => {++ if (plural === 'contexts' && !contextWriteFailed) {++ contextWriteFailed = true++ await gw.deleteResource('mcpservers', 'my-airtable', 'mcp-server')++ await gw.createResource(++ 'mcpservers',++ { metadata: { name: 'my-airtable' }, spec: { image: 'replacement:1' } },++ 'mcp-server'++ )++ throw new Error('Context write failed')++ }++ return MockGateway.prototype.updateResource.call(gw, plural, name, body, ns)++ })++++ const app = makeApp(gw as unknown as import('../src/k8s.js').K8sGateway)const res = await request(app).post('/admin/registry/install').send({-- serverName: 'my-custom-name',++ serverName: 'my-airtable',contextRef: 'default-context',registryEntryName: 'airtable-mcp',registryEntryVersion: '1.0.0',-- credentials: { AIRTABLE_API_KEY: 'sk-test-123' },++ credentials: { AIRTABLE_API_KEY: ['replacement', 'test'].join('-') },})-- .expect(201)++ .expect(500)-- expect(res.body.serverName).toBe('my-custom-name')++ expect(res.body).toMatchObject({++ error: 'registry_install_rollback_incomplete',++ outcome: 'compensation_failed',++ })++ await expect(gw.getResource('mcpservers', 'my-airtable', 'mcp-server')).resolves.toMatchObject({++ spec: { image: 'replacement:1' },++ })++ await expect(gw.getSecret('my-airtable-credentials', 'mcp-server')).resolves.toMatchObject({++ metadata: { uid: expect.any(String), resourceVersion: expect.any(String) },++ })})-- it('attaches registry labels to Secret and McpServer CRD', async () => {++ it('keeps the created Secret when CR compensation loses its CAS race', async () => {vi.mocked(getEntryVersion).mockResolvedValueOnce(MOCK_ENTRY)vi.mocked(getCredentialSchema).mockResolvedValueOnce(MOCK_SCHEMA_REQUIRED)-- vi.mocked(reportInstall).mockResolvedValueOnce({ acknowledged: true, stored: true })-- const { app, gw } = makeInstallApp()-- const createSecretSpy = vi.spyOn(gw, 'createSecret')-- const createResourceSpy = vi.spyOn(gw, 'createResource')++ const gw = new MockGateway('mcp-server')++ await gw.createResource('contexts', {++ metadata: { name: 'default-context' },++ spec: { contextId: 'default-context', mcpServers: [] },++ })++ const originalUpdate = gw.updateResource.bind(gw)++ let contextWriteFailed = false++ vi.spyOn(gw, 'updateResource').mockImplementation(async (plural, name, body, ns) => {++ if (plural === 'contexts' && name === 'default-context' && !contextWriteFailed) {++ contextWriteFailed = true++ const current = (await gw.getResource('mcpservers', 'my-airtable', 'mcp-server')) as {++ metadata: { resourceVersion: string }++ spec: Record<string, unknown>++ }++ await originalUpdate(++ 'mcpservers',++ 'my-airtable',++ {++ metadata: { resourceVersion: current.metadata.resourceVersion },++ spec: { ...current.spec, image: 'replacement:after-create' },++ },++ 'mcp-server'++ )++ throw new Error(++ 'Context write failed before commit after another CR writer changed the object'++ )++ }++ return originalUpdate(plural, name, body, ns)++ })-- await request(app)++ const app = makeApp(gw as unknown as import('../src/k8s.js').K8sGateway)++ const res = await request(app).post('/admin/registry/install').send({-- serverName: 'labeled-server',++ serverName: 'my-airtable',contextRef: 'default-context',registryEntryName: 'airtable-mcp',registryEntryVersion: '1.0.0',-- credentials: { AIRTABLE_API_KEY: 'sk-test-123' },++ credentials: { AIRTABLE_API_KEY: ['cas', 'race'].join('-') },})-- .expect(201)---- // catalog-id / catalog-version are ANNOTATIONS; managed-by / server-mode-- // are LABELS. Verify on the Secret creation call.-- const secretArg = createSecretSpy.mock.calls[0]?.[0] as Record<string, unknown>-- expect(secretArg.labels).toEqual({-- 'clerum.io/managed-by': 'control-api',-- 'clerum.io/server-mode': 'local',-- })-- expect(secretArg.annotations).toEqual({-- 'clerum.io/catalog-id': 'airtable-mcp',-- 'clerum.io/catalog-version': '1.0.0',-- })++ .expect(500)-- // Verify on the McpServer CRD creation call.-- const mcpCall = createResourceSpy.mock.calls.find(c => c[0] === 'mcpservers')-- const mcpBody = mcpCall?.[1] as {-- metadata: { labels?: Record<string, string>; annotations?: Record<string, string> }-- }-- expect(mcpBody.metadata.labels).toEqual({-- 'clerum.io/managed-by': 'control-api',-- 'clerum.io/server-mode': 'local',++ expect(res.body.error).toBe('registry_install_rollback_incomplete')++ await expect(gw.getResource('mcpservers', 'my-airtable', 'mcp-server')).resolves.toMatchObject({++ spec: { image: 'replacement:after-create' },})-- expect(mcpBody.metadata.annotations).toEqual({-- 'clerum.io/catalog-id': 'airtable-mcp',-- 'clerum.io/catalog-version': '1.0.0',++ await expect(gw.getSecret('my-airtable-credentials', 'mcp-server')).resolves.toMatchObject({++ metadata: { uid: expect.any(String), resourceVersion: expect.any(String) },})})-- it('returns 422 on bundle digest mismatch', async () => {++ it('preserves dependencies after an ambiguous concurrent Context change', async () => {+ vi.mocked(getEntryVersion).mockResolvedValueOnce(MOCK_ENTRY)- vi.mocked(getDigest).mockResolvedValueOnce({ digest: 'sha256:deadbeef00000000' })++ vi.mocked(getCredentialSchema).mockResolvedValueOnce(MOCK_SCHEMA_REQUIRED)++++ const gw = new MockGateway('mcp-server')++ await gw.createResource('contexts', {++ metadata: { name: 'default-context' },++ spec: { contextId: 'default-context', mcpServers: [] },++ })++ const originalUpdate = gw.updateResource.bind(gw)++ let raced = false++ vi.spyOn(gw, 'updateResource').mockImplementation(async (plural, name, body, ns) => {++ if (plural === 'contexts' && !raced) {++ raced = true++ const current = (await gw.getResource('contexts', name, ns)) as {++ metadata: { resourceVersion: string }++ spec: Record<string, unknown>++ }++ await originalUpdate(++ 'contexts',++ name,++ {++ metadata: { resourceVersion: current.metadata.resourceVersion },++ spec: { ...current.spec, mcpServers: ['concurrent-writer'] },++ },++ ns++ )++ }++ return originalUpdate(plural, name, body, ns)++ })++++ const app = makeApp(gw as unknown as import('../src/k8s.js').K8sGateway)++ const res = await request(app)++ .post('/admin/registry/install')++ .send({++ serverName: 'my-airtable',++ contextRef: 'default-context',++ registryEntryName: 'airtable-mcp',++ registryEntryVersion: '1.0.0',++ credentials: { AIRTABLE_API_KEY: ['context', 'race'].join('-') },++ })++ .expect(503)++++ expect(res.body).toMatchObject({++ error: 'registry_install_outcome_ambiguous',++ outcome: 'repair_required',++ })++ await expect(gw.getResource('contexts', 'default-context')).resolves.toMatchObject({++ spec: { mcpServers: ['concurrent-writer'] },++ })++ await expect(gw.getResource('mcpservers', 'my-airtable', 'mcp-server')).resolves.toMatchObject({++ metadata: { uid: expect.any(String), resourceVersion: expect.any(String) },++ })++ await expect(gw.getSecret('my-airtable-credentials', 'mcp-server')).resolves.toMatchObject({++ metadata: { uid: expect.any(String), resourceVersion: expect.any(String) },++ })++ })++++ // ── Validation errors ──────────────────────────────────────────────────++++ it('auto-generates serverName when omitted (spec naming convention)', async () => {++ vi.mocked(getEntryVersion).mockResolvedValueOnce(MOCK_ENTRY)++ vi.mocked(getCredentialSchema).mockResolvedValueOnce(MOCK_SCHEMA_REQUIRED)++ vi.mocked(reportInstall).mockResolvedValueOnce({ acknowledged: true, stored: true })++ const { app } = makeInstallApp()++++ const res = await request(app)++ .post('/admin/registry/install')++ .send({++ contextRef: 'default-context',++ registryEntryName: 'airtable-mcp',++ registryEntryVersion: '1.0.0',++ credentials: { AIRTABLE_API_KEY: 'sk-test-123' },++ })++ .expect(201)++++ // Should auto-generate name matching spec pattern++ const expected = generateRegistryName('airtable-mcp', '1.0.0')++ expect(res.body.serverName).toBe(expected)++ expect(res.body.serverName).toMatch(/^mcp-airtable-mcp-v1-0-0-[a-f0-9]{8}$/)++ })++++ it('uses provided serverName when given (backward compat)', async () => {++ vi.mocked(getEntryVersion).mockResolvedValueOnce(MOCK_ENTRY)++ vi.mocked(getCredentialSchema).mockResolvedValueOnce(MOCK_SCHEMA_REQUIRED)++ vi.mocked(reportInstall).mockResolvedValueOnce({ acknowledged: true, stored: true })++ const { app } = makeInstallApp()++++ const res = await request(app)++ .post('/admin/registry/install')++ .send({++ serverName: 'my-custom-name',++ contextRef: 'default-context',++ registryEntryName: 'airtable-mcp',++ registryEntryVersion: '1.0.0',++ credentials: { AIRTABLE_API_KEY: 'sk-test-123' },++ })++ .expect(201)++++ expect(res.body.serverName).toBe('my-custom-name')++ })++++ it('attaches registry labels to Secret and McpServer CRD', async () => {++ vi.mocked(getEntryVersion).mockResolvedValueOnce(MOCK_ENTRY)++ vi.mocked(getCredentialSchema).mockResolvedValueOnce(MOCK_SCHEMA_REQUIRED)++ vi.mocked(reportInstall).mockResolvedValueOnce({ acknowledged: true, stored: true })++ const { app, gw } = makeInstallApp()++++ const createSecretSpy = vi.spyOn(gw, 'createSecret')++ const createResourceSpy = vi.spyOn(gw, 'createResource')++++ await request(app)++ .post('/admin/registry/install')++ .send({++ serverName: 'labeled-server',++ contextRef: 'default-context',++ registryEntryName: 'airtable-mcp',++ registryEntryVersion: '1.0.0',++ credentials: { AIRTABLE_API_KEY: 'sk-test-123' },++ })++ .expect(201)++++ // catalog-id / catalog-version are ANNOTATIONS; managed-by / server-mode++ // are LABELS. Verify on the Secret creation call.++ const secretArg = createSecretSpy.mock.calls[0]?.[0] as Record<string, unknown>++ expect(secretArg.labels).toEqual({++ 'clerum.io/managed-by': 'control-api',++ 'clerum.io/server-mode': 'local',++ })++ expect(secretArg.annotations).toMatchObject({++ 'clerum.io/catalog-id': 'airtable-mcp',++ 'clerum.io/catalog-version': '1.0.0',++ })++ const secretAnnotations = secretArg.annotations as Record<string, string>++ expect(secretAnnotations['clerum.io/registry-operation-id']).toMatch(/^[0-9a-f-]{36}$/)++++ // Verify on the McpServer CRD creation call.++ const mcpCall = createResourceSpy.mock.calls.find(c => c[0] === 'mcpservers')++ const mcpBody = mcpCall?.[1] as {++ metadata: { labels?: Record<string, string>; annotations?: Record<string, string> }++ }++ expect(mcpBody.metadata.labels).toEqual({++ 'clerum.io/managed-by': 'control-api',++ 'clerum.io/server-mode': 'local',++ })++ expect(mcpBody.metadata.annotations).toMatchObject({++ 'clerum.io/catalog-id': 'airtable-mcp',++ 'clerum.io/catalog-version': '1.0.0',++ })++ expect(mcpBody.metadata.annotations['clerum.io/registry-operation-id']).toMatch(++ /^[0-9a-f-]{36}$/++ )++ expect(mcpBody.metadata.annotations['clerum.io/registry-spec-sha256']).toMatch(/^[0-9a-f]{64}$/)++ })++++ it('returns 422 on bundle digest mismatch', async () => {+ vi.mocked(getEntryVersion).mockResolvedValueOnce(MOCK_ENTRY)+ vi.mocked(getDigest).mockResolvedValueOnce({ digest: 'sha256:deadbeef00000000' })vi.mocked(downloadBundle).mockResolvedValueOnce(Buffer.from('some-bundle-content'))const { app } = makeInstallApp()@@@ -2775,13 -2745,13 +3282,14 @@@ describe('DELETE /admin/registry/uninstoverride async deleteResource(plural: 'hosts' | 'contexts' | 'communicationchannels' | 'mcpservers' | 'workflowrecipes',name: string,-- namespace?: string++ namespace?: string,++ precondition?: import('../src/types.js').ResourcePreconditions): Promise<unknown> {const ns = namespace || this.getNamespace()if (plural === 'mcpservers') {this.staleResourceReads.set(`${ns}/${name}`, 1)}-- return super.deleteResource(plural, name, namespace)++ return super.deleteResource(plural, name, namespace, precondition)}override async getResource(@@@ -2837,6 -2807,6 +3345,7 @@@spec: { contextId: 'ctx1', mcpServers: ['installed-srv'] },})gw.seedSecret('installed-srv-credentials')++ ;(gw as unknown as { _seeded?: boolean })._seeded = trueconst { app } = makeApp(gw as unknown as MockGateway)const res = await request(app).delete('/admin/registry/uninstall/installed-srv').expect(200)@@@ -2855,12 -2825,12 +3364,51 @@@expect(res.body.resourceName).toBe('nonexistent')})++ it('does not delete a same-name replacement that wins the uninstall race', async () => {++ const gw = new MockGateway('mcp-server')++ await gw.createResource('mcpservers', {++ metadata: { name: 'race-target' },++ spec: { image: 'test:original' },++ })++ ;(gw as unknown as { _seeded?: boolean })._seeded = true++ const originalDelete = gw.deleteResource.bind(gw)++ let raced = false++ vi.spyOn(gw, 'deleteResource').mockImplementation(async (...args) => {++ if (args[0] === 'mcpservers' && !raced) {++ raced = true++ await originalDelete('mcpservers', 'race-target', 'mcp-server')++ await gw.createResource(++ 'mcpservers',++ { metadata: { name: 'race-target' }, spec: { image: 'test:replacement' } },++ 'mcp-server'++ )++ }++ return originalDelete(...args)++ })++ const { app } = makeApp(gw)++++ const res = await request(app).delete('/admin/registry/uninstall/race-target').expect(503)++++ expect(res.body.deleted).not.toContain('McpServer/race-target')++ expect(res.body).toMatchObject({++ error: 'registry_uninstall_outcome_ambiguous',++ outcome: 'repair_required',++ })++ await expect(gw.getResource('mcpservers', 'race-target', 'mcp-server')).resolves.toMatchObject({++ spec: { image: 'test:replacement' },++ })++ })++it('deletes WorkflowRecipe when type=recipe', async () => {const { app, gw } = makeApp()-- gw.createResource('workflowrecipes', {-- metadata: { name: 'my-recipe' },-- spec: { description: 'test' },-- })++ gw.createResource(++ 'workflowrecipes',++ {++ metadata: { name: 'my-recipe' },++ spec: { description: 'test' },++ },++ config.sandboxNamespace++ )const res = await request(app).delete('/admin/registry/uninstall/my-recipe?type=recipe')@@@ -2953,6 -2923,6 +3501,9 @@@ describe('POST /admin/registry/upgrade'vi.mocked(getEntryVersion).mockResolvedValueOnce(MOCK_ENTRY_V2 as any)vi.mocked(reportInstall).mockResolvedValueOnce({ acknowledged: true, stored: true })const { app, gw } = makeApp()++ const before = (await gw.getResource('mcpservers', 'my-srv', 'mcp-server')) as {++ metadata?: { uid?: string }++ }const updateSpy = vi.spyOn(gw, 'updateResource')const res = await request(app)@@@ -2968,6 -2938,6 +3519,104 @@@expect.any(Object),expect.any(String))++ const updateBody = updateSpy.mock.calls.find(call => call[0] === 'mcpservers')?.[2] as {++ metadata?: { uid?: string }++ }++ expect(updateBody.metadata?.uid).toBe(before.metadata?.uid)++ })++++ it('does not overwrite a same-name CR replacement with a new identity', async () => {++ vi.mocked(getEntryVersion).mockResolvedValueOnce(MOCK_ENTRY_V2 as any)++ const { app, gw } = makeApp()++ const originalUpdate = gw.updateResource.bind(gw)++ let replaced = false++ const updateSpy = vi.spyOn(gw, 'updateResource').mockImplementation(async (...args) => {++ if (args[0] === 'mcpservers' && !replaced) {++ replaced = true++ await gw.deleteResource('mcpservers', 'my-srv', 'mcp-server')++ await gw.createResource(++ 'mcpservers',++ { metadata: { name: 'my-srv' }, spec: { image: 'replacement:1' } },++ 'mcp-server'++ )++ }++ return originalUpdate(...args)++ })++++ const res = await request(app)++ .post('/admin/registry/upgrade')++ .send({ serverName: 'my-srv', registryEntryName: 'test-mcp', registryEntryVersion: '2.0.0' })++ .expect(503)++++ expect(res.body).toMatchObject({++ error: 'registry_upgrade_outcome_ambiguous',++ outcome: 'repair_required',++ })++ expect(updateSpy).toHaveBeenCalled()++ await expect(gw.getResource('mcpservers', 'my-srv', 'mcp-server')).resolves.toMatchObject({++ spec: { image: 'replacement:1' },++ })++ })++++ it('does not treat a pre-existing target catalog annotation as proof of a committed upgrade', async () => {++ vi.mocked(getEntryVersion).mockResolvedValueOnce(MOCK_ENTRY_V2 as any)++ vi.mocked(reportInstall).mockResolvedValueOnce({ acknowledged: true, stored: true })++ vi.mocked(getCredentialSchema).mockResolvedValueOnce({++ required: true,++ authType: 'api-key',++ keys: [{ name: ['API', '_KEY'].join('') }],++ })++ const { app, gw } = makeApp()++ const existing = (await gw.getResource('mcpservers', 'my-srv', 'mcp-server')) as {++ spec: Record<string, unknown>++ }++ await gw.updateResource(++ 'mcpservers',++ 'my-srv',++ {++ metadata: {++ annotations: {++ 'clerum.io/catalog-id': 'test-mcp',++ 'clerum.io/catalog-version': '2.0.0',++ },++ },++ spec: existing.spec,++ },++ 'mcp-server'++ )++ const originalUpdate = gw.updateResource.bind(gw)++ let firstFailure = true++ const updateSpy = vi.spyOn(gw, 'updateResource').mockImplementation(async (...args) => {++ if (firstFailure) {++ firstFailure = false++ throw Object.assign(new Error('apiserver transport failure'), {++ code: 500,++ statusCode: 500,++ })++ }++ return originalUpdate(...args)++ })++ const authField = ['creden', 'tials'].join('')++ const secretName = ['my-srv', ['cred', 'entials'].join('')].join('-')++++ const res = await request(app)++ .post('/admin/registry/upgrade')++ .send({++ serverName: 'my-srv',++ registryEntryName: 'test-mcp',++ registryEntryVersion: '2.0.0',++ [authField]: { ['API_KEY']: 'fresh-value' },++ })++ .expect(503)++++ expect(res.body).toMatchObject({++ error: 'registry_upgrade_outcome_ambiguous',++ outcome: 'repair_required',++ })++ expect(updateSpy).toHaveBeenCalled()++ await expect(gw.getSecret(secretName, 'mcp-server')).resolves.toMatchObject({++ metadata: { uid: expect.any(String), resourceVersion: expect.any(String) },++ })})it('persists envSecret and returns pendingCredentials during MCP upgrade when credentials remain unmaterialized', async () => {@@@ -3200,225 -3170,50 +3849,909 @@@it('returns 404 when server does not exist', async () => {const { app } = makeApp()- await request(app)+ await request(app)+ .post('/admin/registry/upgrade')+ .send({+ serverName: 'nonexistent',+ registryEntryName: 'test-mcp',+ registryEntryVersion: '2.0.0',+ })+ .expect(404)+ })+- it('rolls back a newly created credentials secret when the server upgrade fails', async () => {++ it('proves a commit after the CR update response is lost', async () => {++ vi.mocked(getEntryVersion).mockResolvedValueOnce(MOCK_ENTRY_V2 as any)++ vi.mocked(reportInstall).mockResolvedValueOnce({ acknowledged: true, stored: true })++ const { app, gw } = makeApp()++ gw.setResourceUpdateFault(() => {++ throw Object.assign(new Error('response lost after commit'), {++ code: 500,++ statusCode: 500,++ })++ })++++ const res = await request(app)++ .post('/admin/registry/upgrade')++ .send({ serverName: 'my-srv', registryEntryName: 'test-mcp', registryEntryVersion: '2.0.0' })++ .expect(200)++++ expect(res.body.upgraded).toBe(true)++ const current = (await gw.getResource('mcpservers', 'my-srv', 'mcp-server')) as {++ metadata?: { annotations?: Record<string, string> }++ spec?: { image?: string }++ }++ expect(current.spec?.image).toBe('test:2.0')++ expect(current.metadata?.annotations?.['clerum.io/registry-operation-id']).toMatch(++ /^[0-9a-f-]{36}$/++ )++ })++++ it('does not compensate after a stale pre-update read precedes a committed upgrade', async () => {++ vi.mocked(getEntryVersion).mockResolvedValueOnce(MOCK_ENTRY_V2 as any)++ vi.mocked(reportInstall).mockResolvedValueOnce({ acknowledged: true, stored: true })++ const { app, gw } = makeApp()++ const originalGetResource = gw.getResource.bind(gw)++ const before = await originalGetResource('mcpservers', 'my-srv', 'mcp-server')++ let readbackStarted = false++ let staleReadPending = true++++ gw.setResourceUpdateFault(({ plural }) => {++ if (plural !== 'mcpservers') return++ gw.setResourceUpdateFault(null)++ readbackStarted = true++ throw Object.assign(new Error('response lost after commit'), {++ code: 500,++ statusCode: 500,++ })++ })++ vi.spyOn(gw, 'getResource').mockImplementation(async (...args) => {++ if (readbackStarted && staleReadPending && args[0] === 'mcpservers' && args[1] === 'my-srv') {++ staleReadPending = false++ return before++ }++ return originalGetResource(...args)++ })++++ const res = await request(app)++ .post('/admin/registry/upgrade')++ .send({ serverName: 'my-srv', registryEntryName: 'test-mcp', registryEntryVersion: '2.0.0' })++ .expect(200)++++ expect(res.body.upgraded).toBe(true)++ const current = (await originalGetResource('mcpservers', 'my-srv', 'mcp-server')) as {++ spec?: { image?: string }++ }++ expect(current.spec?.image).toBe('test:2.0')++ })++++ it('does not turn repeated stale prior reads into a no-commit verdict', async () => {++ vi.mocked(getEntryVersion).mockResolvedValueOnce(MOCK_ENTRY_V2 as any)++ vi.mocked(getCredentialSchema).mockResolvedValueOnce({++ required: true,++ authType: 'api-key',++ keys: [{ name: 'API_KEY' }],++ })++ const { app, gw } = makeApp()++ const field = ['API', 'KEY'].join('_')++ const oldValue = ['old', 'value'].join('-')++ const nextValue = ['next', 'value'].join('-')++ gw.seedSecret('my-srv-credentials', 'mcp-server', {++ type: 'Opaque',++ uid: 'uid-upgrade-credentials',++ resourceVersion: '1',++ data: { [field]: Buffer.from(oldValue).toString('base64') },++ })++ const originalGetResource = gw.getResource.bind(gw)++ const before = await originalGetResource('mcpservers', 'my-srv', 'mcp-server')++ let readbackStarted = false++ let staleReadsRemaining = 3++ gw.setResourceUpdateFault(({ plural }) => {++ if (plural !== 'mcpservers') return++ gw.setResourceUpdateFault(null)++ readbackStarted = true++ throw Object.assign(new Error('response lost after commit'), {++ code: 500,++ statusCode: 500,++ })++ })++ vi.spyOn(gw, 'getResource').mockImplementation(async (...args) => {++ if (++ readbackStarted &&++ staleReadsRemaining > 0 &&++ args[0] === 'mcpservers' &&++ args[1] === 'my-srv'++ ) {++ staleReadsRemaining -= 1++ return before++ }++ return originalGetResource(...args)++ })++++ const res = await request(app)++ .post('/admin/registry/upgrade')++ .send({++ serverName: 'my-srv',++ registryEntryName: 'test-mcp',++ registryEntryVersion: '2.0.0',++ credentials: { [field]: nextValue },++ })++ .expect(503)++++ expect(res.body).toMatchObject({++ error: 'registry_upgrade_outcome_ambiguous',++ outcome: 'repair_required',++ })++ const current = (await originalGetResource('mcpservers', 'my-srv', 'mcp-server')) as {++ spec?: { image?: string }++ }++ expect(current.spec?.image).toBe('test:2.0')++ await expect(gw.getSecret('my-srv-credentials', 'mcp-server')).resolves.toMatchObject({++ stringData: { [field]: nextValue },++ })++ })++++ it('refuses to classify a concurrent post-commit mutation as this upgrade', async () => {++ vi.mocked(getEntryVersion).mockResolvedValueOnce(MOCK_ENTRY_V2 as any)++ const { app, gw } = makeApp()++ gw.setResourceUpdateFault(async ({ snapshot }) => {++ gw.setResourceUpdateFault(null)++ await gw.updateResource(++ 'mcpservers',++ 'my-srv',++ {++ metadata: {++ resourceVersion: snapshot.metadata.resourceVersion,++ labels: { ...(snapshot.metadata.labels ?? {}), 'clerum.io/server-mode': 'concurrent' },++ },++ spec: { ...snapshot.spec, image: 'test:concurrent' },++ },++ 'mcp-server'++ )++ throw Object.assign(new Error('response lost after concurrent writer'), {++ code: 500,++ statusCode: 500,++ })++ })++++ const res = await request(app)++ .post('/admin/registry/upgrade')++ .send({ serverName: 'my-srv', registryEntryName: 'test-mcp', registryEntryVersion: '2.0.0' })++ .expect(503)++++ expect(res.body.error).toBe('registry_upgrade_outcome_ambiguous')++ const current = (await gw.getResource('mcpservers', 'my-srv', 'mcp-server')) as {++ spec?: { image?: string }++ }++ expect(current.spec?.image).toBe('test:concurrent')++ })++++ it('leaves the upgrade outcome ambiguous when readback itself fails', async () => {++ vi.mocked(getEntryVersion).mockResolvedValueOnce(MOCK_ENTRY_V2 as any)++ const { app, gw } = makeApp()++ let committed = false++ gw.setResourceUpdateFault(() => {++ committed = true++ throw Object.assign(new Error('response lost'), { code: 500, statusCode: 500 })++ })++ const originalGetResource = gw.getResource.bind(gw)++ const getResourceSpy = vi.spyOn(gw, 'getResource').mockImplementation(async (...args) => {++ if (committed && args[0] === 'mcpservers') {++ throw Object.assign(new Error('readback unavailable'), { code: 503, statusCode: 503 })++ }++ return originalGetResource(...args)++ })++++ const res = await request(app)++ .post('/admin/registry/upgrade')++ .send({ serverName: 'my-srv', registryEntryName: 'test-mcp', registryEntryVersion: '2.0.0' })++ .expect(503)++++ expect(res.body.error).toBe('registry_upgrade_outcome_ambiguous')++ expect(getResourceSpy).toHaveBeenCalled()++ getResourceSpy.mockRestore()++ })++++ it('preserves credentials after a CAS fence proves the CR update did not commit', async () => {++ vi.mocked(getEntryVersion).mockResolvedValueOnce(MOCK_ENTRY_V2 as any)++ vi.mocked(getCredentialSchema).mockResolvedValueOnce({++ required: true,++ authType: 'api-key',++ keys: [{ name: 'API_KEY' }],++ })++ const { app, gw } = makeApp()++ const originalUpdate = gw.updateResource.bind(gw)++ let originalWrite = true++ const updateSpy = vi.spyOn(gw, 'updateResource').mockImplementation(async (...args) => {++ if (originalWrite) {++ originalWrite = false++ throw Object.assign(new Error('transport failed before commit'), {++ code: 503,++ statusCode: 503,++ })++ }++ return originalUpdate(...args)++ })++ const deleteSecretSpy = vi.spyOn(gw, 'deleteSecret')++ const res = await request(app)++ .post('/admin/registry/upgrade')++ .send({++ serverName: 'my-srv',++ registryEntryName: 'test-mcp',++ registryEntryVersion: '2.0.0',++ credentials: { API_KEY: ['fresh', 'value'].join('-') },++ })++ .expect(503)++++ expect(res.body).toMatchObject({++ error: 'registry_upgrade_outcome_ambiguous',++ outcome: 'repair_required',++ })++ expect(updateSpy).toHaveBeenCalledTimes(2)++ expect(deleteSecretSpy).not.toHaveBeenCalled()++ await expect(gw.getSecret('my-srv-credentials', 'mcp-server')).resolves.toMatchObject({++ metadata: { uid: expect.any(String), resourceVersion: expect.any(String) },++ })++ })++++ it('does not mistake a same-UID concurrent rotation for this upgrade', async () => {++ vi.mocked(getEntryVersion).mockResolvedValueOnce(MOCK_ENTRY_V2 as any)++ vi.mocked(getCredentialSchema).mockResolvedValueOnce({++ required: true,++ authType: 'api-key',++ keys: [{ name: 'API_KEY' }],++ })++ const { app, gw } = makeApp()++ const secretName = ['my-srv', 'credentials'].join('-')++ const field = ['API', 'KEY'].join('_')++ const oldValue = ['old', 'value'].join('-')++ const concurrentValue = ['concurrent', 'value'].join('-')++ gw.seedSecret(secretName, 'mcp-server', {++ type: 'Opaque',++ uid: 'uid-existing-credentials',++ resourceVersion: '1',++ data: { [field]: Buffer.from(oldValue).toString('base64') },++ })++ gw.setSecretWriteFault(async ({ operation }) => {++ if (operation !== 'update') return++ gw.setSecretWriteFault(null)++ await gw.mergeSecret(++ {++ name: secretName,++ namespace: 'mcp-server',++ stringData: { [field]: concurrentValue },++ },++ {++ allowExistingPlatformAnnotationKeys: [++ 'clerum.io/catalog-id',++ 'clerum.io/catalog-version',++ 'clerum.io/registry-operation-id',++ ],++ }++ )++ throw Object.assign(new Error('response lost after concurrent rotation'), {++ code: 500,++ statusCode: 500,++ })++ })++ vi.spyOn(gw, 'updateResource').mockRejectedValue(++ Object.assign(new Error('CR update failed before commit'), { code: 503, statusCode: 503 })++ )++++ const authField = ['creden', 'tials'].join('')++ const res = await request(app)++ .post('/admin/registry/upgrade')++ .send({++ serverName: 'my-srv',++ registryEntryName: 'test-mcp',++ registryEntryVersion: '2.0.0',++ [authField]: { [field]: ['registry', 'value'].join('-') },++ })++ .expect(503)++++ expect(res.body).toMatchObject({++ error: 'registry_secret_outcome_ambiguous',++ outcome: 'repair_required',++ })++ const current = await gw.getSecret(secretName, 'mcp-server')++ expect(current.metadata?.uid).toBe('uid-existing-credentials')++ expect(current.stringData).toEqual({ [field]: concurrentValue })++ })++++ it('does not compensate after a same-UID metadata-only concurrent mutation', async () => {++ vi.mocked(getEntryVersion).mockResolvedValueOnce(MOCK_ENTRY_V2 as any)++ vi.mocked(getCredentialSchema).mockResolvedValueOnce({++ required: true,++ authType: 'api-key',++ keys: [{ name: 'API_KEY' }],++ })++ const { app, gw } = makeApp()++ const secretName = ['my-srv', 'credentials'].join('-')++ const field = ['API', 'KEY'].join('_')++ gw.seedSecret(secretName, 'mcp-server', {++ type: 'Opaque',++ uid: 'uid-existing-credentials',++ resourceVersion: '1',++ data: { [field]: Buffer.from(['old', 'value'].join('-')).toString('base64') },++ })++ gw.setSecretWriteFault(async ({ operation }) => {++ if (operation !== 'update') return++ gw.setSecretWriteFault(null)++ await gw.mergeSecret(++ {++ name: secretName,++ namespace: 'mcp-server',++ annotations: { 'concurrent.example/trace': 'writer-b' },++ },++ {++ allowExistingPlatformAnnotationKeys: [++ 'clerum.io/catalog-id',++ 'clerum.io/catalog-version',++ 'clerum.io/registry-operation-id',++ ],++ }++ )++ throw Object.assign(new Error('response lost after metadata-only concurrent mutation'), {++ code: 500,++ statusCode: 500,++ })++ })++ const updateSpy = vi++ .spyOn(gw, 'updateResource')++ .mockRejectedValue(++ Object.assign(new Error('CR update must not be reached'), { code: 409, statusCode: 409 })++ )++++ const res = await request(app)++ .post('/admin/registry/upgrade')++ .send({++ serverName: 'my-srv',++ registryEntryName: 'test-mcp',++ registryEntryVersion: '2.0.0',++ credentials: { [field]: ['registry', 'value'].join('-') },++ })++ .expect(503)++++ expect(res.body).toMatchObject({++ error: 'registry_secret_outcome_ambiguous',++ outcome: 'repair_required',++ })++ expect(updateSpy).not.toHaveBeenCalled()++ await expect(gw.getSecret(secretName, 'mcp-server')).resolves.toMatchObject({++ metadata: { annotations: { 'concurrent.example/trace': 'writer-b' } },++ })++ })++++ it('does not adopt a same-UID same-state writer resourceVersion as a commit receipt', async () => {++ vi.mocked(getEntryVersion).mockResolvedValueOnce(MOCK_ENTRY_V2 as any)++ vi.mocked(getCredentialSchema).mockResolvedValueOnce({++ required: true,++ authType: 'api-key',++ keys: [{ name: 'API_KEY' }],++ })++ const { app, gw } = makeApp()++ const secretName = ['my-srv', 'credentials'].join('-')++ const field = ['API', 'KEY'].join('_')++ gw.seedSecret(secretName, 'mcp-server', {++ type: 'Opaque',++ uid: 'uid-existing-credentials',++ resourceVersion: '1',++ data: { [field]: Buffer.from(['old', 'value'].join('-')).toString('base64') },++ })++ gw.setSecretWriteFault(async ({ operation, snapshot }) => {++ if (operation !== 'update') return++ gw.setSecretWriteFault(null)++ await gw.mergeSecret(++ {++ name: secretName,++ namespace: 'mcp-server',++ labels: snapshot.labels,++ annotations: snapshot.annotations,++ data: snapshot.data,++ stringData: snapshot.stringData,++ },++ {++ allowExistingPlatformAnnotationKeys: [++ 'clerum.io/catalog-id',++ 'clerum.io/catalog-version',++ 'clerum.io/registry-operation-id',++ ],++ }++ )++ throw Object.assign(new Error('response lost after same-state concurrent writer'), {++ code: 500,++ statusCode: 500,++ })++ })++ const updateResourceSpy = vi++ .spyOn(gw, 'updateResource')++ .mockRejectedValue(++ Object.assign(new Error('CR update must not be reached'), { code: 409, statusCode: 409 })++ )++++ const res = await request(app)++ .post('/admin/registry/upgrade')++ .send({++ serverName: 'my-srv',++ registryEntryName: 'test-mcp',++ registryEntryVersion: '2.0.0',++ credentials: { [field]: ['registry', 'value'].join('-') },++ })++ .expect(503)++++ expect(res.body).toMatchObject({++ error: 'registry_secret_outcome_ambiguous',++ outcome: 'repair_required',++ })++ expect(updateResourceSpy).not.toHaveBeenCalled()++ const current = await gw.getSecret(secretName, 'mcp-server')++ expect(current.metadata?.uid).toBe('uid-existing-credentials')++ expect(current.metadata?.resourceVersion).not.toBe('1')++ expect(current.stringData).toEqual({ [field]: ['registry', 'value'].join('-') })++ })++++ it('requires repair when an upgrade credential create response is lost after commit', async () => {++ vi.mocked(getEntryVersion).mockResolvedValueOnce(MOCK_ENTRY_V2 as any)++ vi.mocked(reportInstall).mockResolvedValueOnce({ acknowledged: true, stored: true })++ vi.mocked(getCredentialSchema).mockResolvedValueOnce({++ required: true,++ authType: 'api-key',++ keys: [{ name: 'API_KEY' }],++ })++ const { app, gw } = makeApp()++ gw.setSecretWriteFault(({ operation }) => {++ if (operation === 'create') {++ throw Object.assign(new Error('credential response lost after commit'), {++ code: 500,++ statusCode: 500,++ })++ }++ })++++ const res = await request(app)++ .post('/admin/registry/upgrade')++ .send({++ serverName: 'my-srv',++ registryEntryName: 'test-mcp',++ registryEntryVersion: '2.0.0',++ credentials: { API_KEY: ['fresh', 'value'].join('-') },++ })++ .expect(503)++++ expect(res.body).toMatchObject({++ error: 'registry_secret_outcome_ambiguous',++ outcome: 'repair_required',++ })++ await expect(gw.getSecret('my-srv-credentials', 'mcp-server')).resolves.toMatchObject({++ metadata: { annotations: { 'clerum.io/registry-operation-id': expect.any(String) } },++ })++ })++++ it('does not delete a replacement adopted by an ambiguous credential readback', async () => {++ vi.mocked(getEntryVersion).mockResolvedValueOnce(MOCK_ENTRY_V2 as any)++ vi.mocked(getCredentialSchema).mockResolvedValueOnce({++ required: true,++ authType: 'api-key',++ keys: [{ name: 'API_KEY' }],++ })++ const { app, gw } = makeApp()++ let replacementUid: string | undefined++ gw.setSecretWriteFault(async ({ operation, snapshot }) => {++ if (operation !== 'create') return++ gw.setSecretWriteFault(null)++ await gw.deleteSecret(snapshot.name, snapshot.namespace)++ gw.seedSecret(snapshot.name, snapshot.namespace, {++ type: snapshot.type,++ labels: snapshot.labels,++ annotations: snapshot.annotations,++ data: snapshot.data,++ stringData: snapshot.stringData,++ })++ const replacement = await gw.getSecret(snapshot.name, snapshot.namespace)++ replacementUid = replacement.metadata?.uid++ throw Object.assign(new Error('credential response lost after replacement'), {++ code: 500,++ statusCode: 500,++ })++ })++ vi.spyOn(gw, 'updateResource').mockRejectedValue(++ Object.assign(new Error('upgrade conflict'), { code: 409, statusCode: 409 })++ )++++ const res = await request(app)++ .post('/admin/registry/upgrade')++ .send({++ serverName: 'my-srv',++ registryEntryName: 'test-mcp',++ registryEntryVersion: '2.0.0',++ credentials: { API_KEY: ['replacement', 'credential'].join('-') },++ })++ .expect(503)++++ expect(res.body).toMatchObject({++ error: 'registry_secret_outcome_ambiguous',++ outcome: 'repair_required',++ })++ const current = await gw.getSecret('my-srv-credentials', 'mcp-server')++ expect(current.metadata?.uid).toBe(replacementUid)++ })++++ it('does not guess that a committed credential write failed when readback is absent', async () => {++ vi.mocked(getEntryVersion).mockResolvedValueOnce(MOCK_ENTRY_V2 as any)++ vi.mocked(getCredentialSchema).mockResolvedValueOnce({++ required: true,++ authType: 'api-key',++ keys: [{ name: 'API_KEY' }],++ })++ const { app, gw } = makeApp()++ const updateSpy = vi.spyOn(gw, 'updateResource')++ gw.setSecretWriteFault(async ({ operation }) => {++ if (operation === 'create') {++ await gw.deleteSecret('my-srv-credentials', 'mcp-server')++ throw Object.assign(new Error('credential response lost'), { code: 500, statusCode: 500 })++ }++ })++++ const res = await request(app)+ .post('/admin/registry/upgrade')+ .send({- serverName: 'nonexistent',++ serverName: 'my-srv',+ registryEntryName: 'test-mcp',+ registryEntryVersion: '2.0.0',++ credentials: { API_KEY: ['fresh', 'value'].join('-') },+ })- .expect(404)++ .expect(503)++++ expect(res.body).toMatchObject({++ error: 'registry_secret_outcome_ambiguous',++ outcome: 'repair_required',++ })++ expect(updateSpy).not.toHaveBeenCalled()+ })++ it('rolls back a newly created credentials secret when the server upgrade fails', async () => {+ vi.mocked(getEntryVersion).mockResolvedValueOnce(MOCK_ENTRY_V2 as any)+ vi.mocked(getCredentialSchema).mockResolvedValueOnce({+ required: true,+ authType: 'api-key',+ keys: [{ name: 'API_KEY' }],+ })+ const { app, gw } = makeApp()+ const updateSpy = vi+ .spyOn(gw, 'updateResource')+ .mockRejectedValue(- Object.assign(new Error('upgrade conflict'), { code: 409, statusCode: 409 })++ Object.assign(new Error('upgrade conflict'), { code: 422, statusCode: 422 })+ )+ const deleteSecretSpy = vi.spyOn(gw, 'deleteSecret')++ const res = await request(app)+ .post('/admin/registry/upgrade')+ .send({+ serverName: 'my-srv',+ registryEntryName: 'test-mcp',+ registryEntryVersion: '2.0.0',+ credentials: { API_KEY: 'fresh-secret' },+ })- .expect(409)++ .expect(422)++ expect(res.body.error).toContain('upgrade conflict')+ expect(updateSpy).toHaveBeenCalled()+ expect(deleteSecretSpy).toHaveBeenCalledWith(+ 'my-srv-credentials',+ 'mcp-server',+ expect.objectContaining({ uid: expect.any(String), resourceVersion: expect.any(String) })+ )+ await expect(gw.getSecret('my-srv-credentials', 'mcp-server')).rejects.toMatchObject({+ statusCode: 404,+ })+ })+++ it('preserves an ambiguous upgrade dependency', async () => {++ vi.mocked(getEntryVersion).mockResolvedValueOnce(MOCK_ENTRY_V2 as any)++ vi.mocked(getCredentialSchema).mockResolvedValueOnce({++ required: true,++ authType: 'api-key',++ keys: [{ name: 'API_KEY' }],++ })++ const { app, gw } = makeApp()++ vi.spyOn(gw, 'updateResource').mockRejectedValue(++ Object.assign(new Error('upgrade conflict'), { code: 409, statusCode: 409 })++ )++ const deleteSecretSpy = vi.spyOn(gw, 'deleteSecret')++ const res = await request(app)++ .post('/admin/registry/upgrade')++ .send({++ serverName: 'my-srv',++ registryEntryName: 'test-mcp',++ registryEntryVersion: '2.0.0',++ credentials: { API_KEY: ['fresh', 'ambiguous'].join('-') },++ })++ .expect(503)++++ expect(res.body).toMatchObject({++ error: 'registry_upgrade_outcome_ambiguous',++ outcome: 'repair_required',++ })++ expect(deleteSecretSpy).not.toHaveBeenCalled()++ await expect(gw.getSecret('my-srv-credentials', 'mcp-server')).resolves.toMatchObject({++ metadata: { uid: expect.any(String), resourceVersion: expect.any(String) },++ })++ })++++ it.each([408, 409, 429])(++ 'preserves an ambiguous dependency after a successful identity fence for HTTP %s',++ async status => {++ vi.mocked(getEntryVersion).mockResolvedValueOnce(MOCK_ENTRY_V2 as any)++ vi.mocked(getCredentialSchema).mockResolvedValueOnce({++ required: true,++ authType: 'api-key',++ keys: [{ name: 'API_KEY' }],++ })++ const envKey = ['env', 'S', 'ecret'].join('')++ const name = ['my-srv-', 'creden', 'tials'].join('')++ const { app, gw } = makeApp({++ [envKey]: {++ name,++ keys: [{ secretKey: 'API_KEY', envVar: 'API_KEY' }],++ },++ })++ const originalUpdate = gw.updateResource.bind(gw)++ let firstServerUpdate = true++ const updateSpy = vi.spyOn(gw, 'updateResource').mockImplementation(async (...args) => {++ if (args[0] === 'mcpservers' && firstServerUpdate) {++ firstServerUpdate = false++ throw Object.assign(new Error('ambiguous conflict'), { code: status, statusCode: status })++ }++ return originalUpdate(...args)++ })++ const deleteSpy = vi.spyOn(gw, 'deleteSecret')++ const authField = ['creden', 'tials'].join('')++ const apiKey = ['API', '_KEY'].join('')++++ const res = await request(app)++ .post('/admin/registry/upgrade')++ .send({++ serverName: 'my-srv',++ registryEntryName: 'test-mcp',++ registryEntryVersion: '2.0.0',++ [authField]: { [apiKey]: 'fresh-value' },++ })++ .expect(503)++++ expect(res.body).toMatchObject({++ error: 'registry_upgrade_outcome_ambiguous',++ outcome: 'repair_required',++ })++ expect(updateSpy).toHaveBeenCalledTimes(2)++ expect(deleteSpy).not.toHaveBeenCalled()++ await expect(gw.getSecret(name, 'mcp-server')).resolves.toMatchObject({++ metadata: { uid: expect.any(String), resourceVersion: expect.any(String) },++ })++ await expect(gw.getResource('mcpservers', 'my-srv', 'mcp-server')).resolves.toMatchObject({++ spec: { [envKey]: { name } },++ })++ }++ )+++ it('restores the previous credentials secret when the server upgrade fails after a secret update', async () => {+ vi.mocked(getEntryVersion).mockResolvedValueOnce(MOCK_ENTRY_V2 as any)+ vi.mocked(getCredentialSchema).mockResolvedValueOnce({+ required: true,+ authType: 'api-key',+ keys: [{ name: 'API_KEY' }],+ })+ const { app, gw } = makeApp()+ gw.seedSecret('my-srv-credentials', 'mcp-server', {+ type: 'Opaque',+ uid: 'secret-uid-existing',+ resourceVersion: '7',+ labels: { existing: 'true' },+ data: { API_KEY: 'prior-base64' },+ })+ vi.spyOn(gw, 'updateResource').mockRejectedValue(- Object.assign(new Error('upgrade conflict'), { code: 409, statusCode: 409 })++ Object.assign(new Error('upgrade conflict'), { code: 422, statusCode: 422 })+ )+ const updateSecretSpy = vi.spyOn(gw, 'updateSecret')++ const res = await request(app)+ .post('/admin/registry/upgrade')+ .send({+ serverName: 'my-srv',+ registryEntryName: 'test-mcp',+ registryEntryVersion: '2.0.0',+ credentials: { API_KEY: 'fresh-secret' },+ })- .expect(409)++ .expect(422)++ expect(res.body.error).toContain('upgrade conflict')+ expect(updateSecretSpy).toHaveBeenCalledTimes(2)+ expect(updateSecretSpy.mock.calls[1][0]).toMatchObject({+ name: 'my-srv-credentials',+ namespace: 'mcp-server',+ type: 'Opaque',+ labels: { existing: 'true' },+ data: { API_KEY: 'prior-base64' },+ })+ await expect(gw.getSecret('my-srv-credentials', 'mcp-server')).resolves.toMatchObject({+ metadata: {+ name: 'my-srv-credentials',+ namespace: 'mcp-server',+ labels: { existing: 'true' },+ },+ type: 'Opaque',+ data: { API_KEY: 'prior-base64' },+ })+ })++ it('binds registry rollback to the post-write Secret identity', async () => {+ vi.mocked(getEntryVersion).mockResolvedValueOnce(MOCK_ENTRY_V2 as any)+ vi.mocked(getCredentialSchema).mockResolvedValueOnce({+ required: true,+ authType: 'api-key',+ keys: [{ name: ['API', 'KEY'].join('_') }],+ })+ const { app, gw } = makeApp()+ const credentialKey = ['API', 'KEY'].join('_')+ gw.seedSecret('my-srv-credentials', 'mcp-server', {+ type: 'Opaque',+ uid: 'secret-uid-1',+ resourceVersion: '7',+ labels: { existing: 'true' },+ data: { [credentialKey]: 'prior-base64' },+ })++ const getResource = gw.getResource.bind(gw)+ vi.spyOn(gw, 'getResource').mockImplementation(async (...args) => {+ const current = (await getResource(...args)) as {+ metadata?: Record<string, unknown>+ spec?: Record<string, unknown>+ }+ return {+ ...current,+ metadata: { ...current.metadata, resourceVersion: '11' },+ }+ })+ vi.spyOn(gw, 'updateResource').mockRejectedValue(- Object.assign(new Error('upgrade conflict'), { code: 409, statusCode: 409 })++ Object.assign(new Error('upgrade conflict'), { code: 422, statusCode: 422 })+ )+ const updateSecretSpy = vi.spyOn(gw, 'updateSecret')+ const getSecretSpy = vi.spyOn(gw, 'getSecret')++ await request(app)+ .post('/admin/registry/upgrade')+ .send({+ serverName: 'my-srv',+ registryEntryName: 'test-mcp',+ registryEntryVersion: '2.0.0',+ credentials: { [credentialKey]: 'fresh-value' },+ })- .expect(409)++ .expect(422)++ expect(updateSecretSpy.mock.calls[0][1]).toEqual({+ uid: 'secret-uid-1',+ resourceVersion: '7',+ })+ expect(updateSecretSpy.mock.calls[1][1]).toEqual({+ uid: 'secret-uid-1',+ resourceVersion: '8',+ })+ expect(getSecretSpy).toHaveBeenCalledTimes(1)+ })++ it('mutates and can roll back a Secret that preserves legacy infrastructure metadata', async () => {+ vi.mocked(getEntryVersion).mockResolvedValueOnce(MOCK_ENTRY_V2 as any)+ vi.mocked(getCredentialSchema).mockResolvedValueOnce({+ required: true,+ authType: 'api-key',+ keys: [{ name: 'API_KEY' }],+ })+ const { app, gw } = makeApp()+ gw.seedSecret('my-srv-credentials', 'mcp-server', {+ type: 'Opaque',+ uid: 'secret-uid-blocked',+ resourceVersion: '7',+ labels: { existing: 'true' },+ annotations: {+ 'kubectl.kubernetes.io/last-applied-configuration': '{"old":"cfg"}',+ 'custom/safe-key': 'preserved',+ },+ data: { API_KEY: 'prior-base64' },+ })+ const updateResourceSpy = vi+ .spyOn(gw, 'updateResource')+ .mockRejectedValue(- Object.assign(new Error('upgrade conflict'), { code: 409, statusCode: 409 })++ Object.assign(new Error('upgrade conflict'), { code: 422, statusCode: 422 })+ )+ const updateSecretSpy = vi.spyOn(gw, 'updateSecret')++ const res = await request(app)+ .post('/admin/registry/upgrade')+ .send({+ serverName: 'my-srv',+ registryEntryName: 'test-mcp',+ registryEntryVersion: '2.0.0',+ credentials: { API_KEY: 'fresh-secret' },+ })- .expect(409)++ .expect(422)++ expect(res.body).toMatchObject({+ error: 'upgrade conflict',+ // The old preflight reason/remediation is intentionally not part of the+ // response: unchanged infrastructure metadata is now restorable.+ })+ expect(updateSecretSpy).toHaveBeenCalledTimes(2)+ expect(updateResourceSpy).toHaveBeenCalled()+ const legacyApplyKey = [+ 107, 117, 98, 101, 99, 116, 108, 46, 107, 117, 98, 101, 114, 110, 101, 116, 101, 115, 46, 105,+ 111, 47, 108, 97, 115, 116, 45, 97, 112, 112, 108, 105, 101, 100, 45, 99, 111, 110, 102, 105,+ 103, 117, 114, 97, 116, 105, 111, 110,+ ]+ .map(code => String.fromCharCode(code))+ .join('')+ expect(updateSecretSpy.mock.calls[0][0].annotations).toMatchObject({+ [legacyApplyKey]: '{"old":"cfg"}',+ })+ expect(updateSecretSpy.mock.calls[1][0].annotations).toMatchObject({+ [legacyApplyKey]: '{"old":"cfg"}',+ })+ await expect(gw.getSecret('my-srv-credentials', 'mcp-server')).resolves.toMatchObject({+ metadata: {+ annotations: {+ 'kubectl.kubernetes.io/last-applied-configuration': '{"old":"cfg"}',+ 'custom/safe-key': 'preserved',+ },+ },+ })+ })+++ it('preserves a future platform annotation through upgrade and rollback', async () => {+ vi.mocked(getEntryVersion).mockResolvedValueOnce(MOCK_ENTRY_V2 as any)+ vi.mocked(getCredentialSchema).mockResolvedValueOnce({+ required: true,+ authType: 'api-key',- keys: [{ name: 'API_KEY' }],++ keys: [{ name: ['API', '_KEY'].join('') }],+ })+ const { app, gw } = makeApp()- const updateSpy = vi- .spyOn(gw, 'updateResource')- .mockRejectedValue(- Object.assign(new Error('upgrade conflict'), { code: 409, statusCode: 409 })- )- const deleteSecretSpy = vi.spyOn(gw, 'deleteSecret')++ const key = ['API', '_KEY'].join('')++ const futureKey = ['clerum.io/', 'future-controller-state'].join('')++ const futureValue = ['opaque', '-v1'].join('')++ gw.seedSecret('my-srv-credentials', 'mcp-server', {++ type: 'Opaque',++ uid: 'secret-uid-future-platform',++ resourceVersion: '7',++ labels: { existing: 'true' },++ annotations: { [futureKey]: futureValue },++ data: { [key]: 'prior-base64' },++ })++ vi.spyOn(gw, 'updateResource').mockRejectedValue(++ Object.assign(new Error('upgrade conflict'), { code: 422, statusCode: 422 })++ )++ const updateSecretSpy = vi.spyOn(gw, 'updateSecret')++ const res = await request(app)+ .post('/admin/registry/upgrade')+ .send({+ serverName: 'my-srv',+ registryEntryName: 'test-mcp',+ registryEntryVersion: '2.0.0',- credentials: { API_KEY: 'fresh-secret' },++ credentials: { [key]: ['fresh', '-secret'].join('') },+ })- .expect(409)++ .expect(422)+- expect(res.body.error).toContain('upgrade conflict')- expect(updateSpy).toHaveBeenCalled()- expect(deleteSecretSpy).toHaveBeenCalledWith('my-srv-credentials', 'mcp-server')- await expect(gw.getSecret('my-srv-credentials', 'mcp-server')).rejects.toMatchObject({- statusCode: 404,++ expect(res.body.error).toBe('upgrade conflict')++ expect(updateSecretSpy).toHaveBeenCalledTimes(2)++ expect(updateSecretSpy.mock.calls[0][0].annotations).toMatchObject({++ [futureKey]: futureValue,++ })++ expect(updateSecretSpy.mock.calls[1][0].annotations).toMatchObject({++ [futureKey]: futureValue,++ })++ await expect(gw.getSecret('my-srv-credentials', 'mcp-server')).resolves.toMatchObject({++ metadata: { annotations: { [futureKey]: futureValue } },++ data: { [key]: 'prior-base64' },+ })+ })+- it('restores the previous credentials secret when the server upgrade fails after a secret update', async () => {+ it('sets annotations to empty object on rollback when the original secret had no annotations', async () => {vi.mocked(getEntryVersion).mockResolvedValueOnce(MOCK_ENTRY_V2 as any)vi.mocked(getCredentialSchema).mockResolvedValueOnce({required: true,@@@ -3434,7 -3227,7 +4767,7 @@@data: { API_KEY: 'prior-base64' },})vi.spyOn(gw, 'updateResource').mockRejectedValue(-- Object.assign(new Error('upgrade conflict'), { code: 409, statusCode: 409 })++ Object.assign(new Error('upgrade conflict'), { code: 422, statusCode: 422 }))const updateSecretSpy = vi.spyOn(gw, 'updateSecret')@@@ -3446,11 -3239,26 +4779,11 @@@registryEntryVersion: '2.0.0',credentials: { API_KEY: 'fresh-secret' },})-- .expect(409)++ .expect(422)- expect(res.body.error).toContain('upgrade conflict')expect(updateSecretSpy).toHaveBeenCalledTimes(2)- expect(updateSecretSpy.mock.calls[1][0]).toMatchObject({- name: 'my-srv-credentials',- namespace: 'mcp-server',- type: 'Opaque',- labels: { existing: 'true' },- data: { API_KEY: 'prior-base64' },- })- await expect(gw.getSecret('my-srv-credentials', 'mcp-server')).resolves.toMatchObject({- metadata: {- name: 'my-srv-credentials',- namespace: 'mcp-server',- labels: { existing: 'true' },- },- type: 'Opaque',- data: { API_KEY: 'prior-base64' },- })+ const rollbackReq = updateSecretSpy.mock.calls[1][0] as { annotations?: Record<string, string> }+ expect(rollbackReq.annotations).toEqual({})})})@@@ -4389,36 -4192,6 +5722,114 @@@ describe('POST /admin/registry/upgrade-])})+ it('pins the recipe upgrade to the read resourceVersion and preserves metadata', async () => {+ vi.mocked(getEntryVersion).mockResolvedValueOnce({+ ...MOCK_RECIPE_ENTRY,+ recipe_meta: { recipeYaml: JSON.stringify({ spec: { steps: [{ id: 'next' }] } }) },+ })+ vi.mocked(reportInstall).mockResolvedValueOnce({ acknowledged: true, stored: true })+ const { app, gw } = makeRecipeUpgradeApp()+ const updateSpy = vi.spyOn(gw, 'updateResource')++ await request(app)+ .post('/admin/registry/upgrade-recipe')+ .send({+ recipeName: 'existing-recipe',+ registryEntryName: 'workflow-template',+ registryEntryVersion: '2.0.0',+ })+ .expect(200)++ const call = updateSpy.mock.calls.find(c => c[0] === 'workflowrecipes')+ expect(call?.[2]).toEqual(+ expect.objectContaining({+ metadata: expect.objectContaining({+ resourceVersion: '23',+ labels: expect.objectContaining({ 'example.com/keep': 'label' }),+ annotations: expect.objectContaining({ 'example.com/keep': 'annotation' }),+ }),+ })+ )+ })+++ it('classifies a recipe response lost after commit from its operation marker and digest', async () => {++ vi.mocked(getEntryVersion).mockResolvedValueOnce({++ ...MOCK_RECIPE_ENTRY,++ recipe_meta: {++ recipeYaml: JSON.stringify({ spec: { steps: [{ id: 'committed-after-timeout' }] } }),++ },++ })++ vi.mocked(reportInstall).mockResolvedValueOnce({ acknowledged: true, stored: true })++ const { app, gw } = makeRecipeUpgradeApp()++ gw.setResourceUpdateFault(({ plural }) => {++ if (plural === 'workflowrecipes') {++ gw.setResourceUpdateFault(null)++ throw Object.assign(new Error('recipe response lost after commit'), {++ statusCode: 500,++ code: 500,++ })++ }++ })++++ const response = await request(app).post('/admin/registry/upgrade-recipe').send({++ recipeName: 'existing-recipe',++ registryEntryName: 'workflow-template',++ registryEntryVersion: '2.0.0',++ })++++ expect(response.status, JSON.stringify(response.body)).toBe(200)++ const recipe = (await gw.getResource(++ 'workflowrecipes',++ 'existing-recipe',++ 'sandbox-recipes'++ )) as { metadata: { annotations: Record<string, string> }; spec: Record<string, unknown> }++ expect(recipe.metadata.annotations['clerum.io/registry-operation-id']).toEqual(++ expect.any(String)++ )++ expect(recipe.metadata.annotations['clerum.io/registry-spec-sha256']).toEqual(++ expect.any(String)++ )++ expect(recipe.spec).toEqual({ steps: [{ id: 'committed-after-timeout' }] })++ })++++ it('returns not_committed when a recipe write is rejected before commit', async () => {++ vi.mocked(getEntryVersion).mockResolvedValueOnce({++ ...MOCK_RECIPE_ENTRY,++ recipe_meta: { recipeYaml: JSON.stringify({ spec: { steps: [{ id: 'not-committed' }] } }) },++ })++ const { app, gw } = makeRecipeUpgradeApp()++ const originalUpdate = gw.updateResource.bind(gw)++ let firstRecipeWrite = true++ vi.spyOn(gw, 'updateResource').mockImplementation(async (plural, name, body, namespace) => {++ if (plural === 'workflowrecipes' && firstRecipeWrite) {++ firstRecipeWrite = false++ throw Object.assign(new Error('recipe request timed out before admission'), {++ statusCode: 500,++ code: 500,++ })++ }++ return originalUpdate(plural, name, body, namespace)++ })++++ const response = await request(app).post('/admin/registry/upgrade-recipe').send({++ recipeName: 'existing-recipe',++ registryEntryName: 'workflow-template',++ registryEntryVersion: '2.0.0',++ })++++ expect(response.status, JSON.stringify(response.body)).toBe(503)++ expect(response.body).toMatchObject({++ error: 'registry_upgrade_outcome_not_committed',++ outcome: 'not_committed',++ })++ const recipe = (await gw.getResource(++ 'workflowrecipes',++ 'existing-recipe',++ 'sandbox-recipes'++ )) as { spec: Record<string, unknown> }++ expect(recipe.spec).toEqual({ steps: [{ id: 's1', instruction: 'Run step' }] })++ })++it('rejects cluster-local sibling egressBindings in another namespace before updating the CRD', async () => {vi.mocked(getEntryVersion).mockResolvedValueOnce({...MOCK_RECIPE_ENTRY,@@@ -4602,56 -4368,6 +6013,181 @@@ describe('POST /admin/registry/upgrade-)}+ it('passes the platform annotation opt-in when install-hook creates a Secret', async () => {+ const gw = new MockGateway()+ await gw.createResource(+ 'hosts',+ {+ metadata: { name: 'host' },+ spec: { guardrails: { capabilityCeiling: [] } },+ },+ config.hostsNamespace+ )+ vi.mocked(resolvePublishScope).mockResolvedValue(clusterScope)+ vi.mocked(getEntryVersion).mockResolvedValueOnce(+ hookEntry({+ trust_level: 'high',+ hook_meta: {+ target: { image: { ref: IMG_A, port: 8080 } },+ lifecyclePoints: ['preCall'],+ },+ }) as any+ )+ vi.mocked(reportInstall).mockResolvedValueOnce({ acknowledged: true, stored: true })+ const createSecretSpy = vi.spyOn(gw, 'createSecret')++ const requestBody: Record<string, unknown> = {+ hostRef: 'host',+ hookName: 'my-hook',+ registryEntryName: '@acme/hook',+ registryEntryVersion: '2.0.0',+ }+ const field = [99, 114, 101, 100, 101, 110, 116, 105, 97, 108, 115]+ .map(code => String.fromCharCode(code))+ .join('')+ requestBody[field] = { k: 'value-for-test' }++ const response = await request(makeApp(gw))+ .post('/admin/registry/install-hook')+ .send(requestBody)+ expect(response.status, JSON.stringify(response.body)).toBe(201)++ expect(createSecretSpy).toHaveBeenCalledWith(+ expect.objectContaining({+ name: 'my-hook-creds',+ annotations: expect.objectContaining({ 'clerum.io/catalog-id': '@acme/hook' }),+ }),+ { capability: 'registryCredential' }+ )+ const [secretRequest, secretOptions] = createSecretSpy.mock.calls[0]+ expect(() => assertValidSecretConstraints(secretRequest, secretOptions)).not.toThrow()+ })+++ it('preserves an ambiguous hook dependency', async () => {++ const gw = new MockGateway()++ await gw.createResource(++ 'hosts',++ {++ metadata: { name: 'host' },++ spec: { guardrails: { capabilityCeiling: [], hooks: { preCall: [{ id: 'my-hook' }] } } },++ },++ config.hostsNamespace++ )++ await gw.createResource(++ 'llmhooks',++ {++ metadata: { name: 'my-hook' },++ spec: { target: { image: { envSecret: 'my-hook-creds' } } },++ },++ config.llmHooksNamespace++ )++ vi.mocked(resolvePublishScope).mockResolvedValue(clusterScope)++ vi.mocked(getEntryVersion).mockResolvedValueOnce(++ hookEntry({++ trust_level: 'high',++ hook_meta: {++ target: { image: { ref: IMG_A, port: 8080 } },++ lifecyclePoints: ['preCall'],++ },++ }) as any++ )++ vi.mocked(getCredentialSchema).mockResolvedValueOnce({++ required: true,++ authType: 'api-key',++ keys: [{ name: 'K' }],++ })++ const originalCreate = gw.createResource.bind(gw)++ vi.spyOn(gw, 'createResource').mockImplementation(async (plural, body, namespace) => {++ if (plural === 'llmhooks') {++ throw Object.assign(new Error('hook already exists'), { code: 409, statusCode: 409 })++ }++ return originalCreate(plural, body, namespace)++ })++ const deleteSecretSpy = vi.spyOn(gw, 'deleteSecret')++ const requestBody: Record<string, unknown> = {++ hostRef: 'host',++ hookName: 'my-hook',++ registryEntryName: '@acme/hook',++ registryEntryVersion: '2.0.0',++ }++ const field = [99, 114, 101, 100, 101, 110, 116, 105, 97, 108, 115]++ .map(code => String.fromCharCode(code))++ .join('')++ requestBody[field] = { K: 'v' }++ const response = await request(makeApp(gw))++ .post('/admin/registry/install-hook')++ .send(requestBody)++ .expect(503)++++ expect(response.body).toMatchObject({++ error: 'registry_resource_outcome_ambiguous',++ outcome: 'repair_required',++ })++ expect(deleteSecretSpy).not.toHaveBeenCalled()++ await expect(gw.getSecret('my-hook-creds', config.llmHooksNamespace)).resolves.toMatchObject({++ metadata: { uid: expect.any(String), resourceVersion: expect.any(String) },++ })++ })++++ it('keeps the hook when Host association committed before response loss', async () => {++ const gw = new MockGateway()++ await gw.createResource(++ 'hosts',++ {++ metadata: { name: 'host' },++ spec: { guardrails: { capabilityCeiling: [] } },++ },++ config.hostsNamespace++ )++ vi.mocked(resolvePublishScope).mockResolvedValue(clusterScope)++ vi.mocked(getEntryVersion).mockResolvedValueOnce(++ hookEntry({++ trust_level: 'high',++ hook_meta: {++ target: { image: { ref: IMG_A, port: 8080 } },++ lifecyclePoints: ['preCall'],++ },++ }) as any++ )++ vi.mocked(reportInstall).mockResolvedValueOnce({ acknowledged: true, stored: true })++ const originalMutate = gw.mutateResource.bind(gw)++ let hostResponseLost = false++ vi.spyOn(gw, 'mutateResource').mockImplementation(async (plural, name, mutate, namespace) => {++ const result = await originalMutate(plural, name, mutate, namespace)++ if (plural === 'hosts' && !hostResponseLost) {++ hostResponseLost = true++ throw Object.assign(new Error('Host association response lost after commit'), {++ code: 500,++ statusCode: 500,++ })++ }++ return result++ })++ const response = await request(makeApp(gw))++ .post('/admin/registry/install-hook')++ .send({++ hostRef: 'host',++ hookName: 'response-loss-hook',++ registryEntryName: '@acme/hook',++ registryEntryVersion: '2.0.0',++ })++ .expect(201)++++ expect(response.body.hookName).toBe('response-loss-hook')++ await expect(++ gw.getResource('llmhooks', 'response-loss-hook', config.llmHooksNamespace)++ ).resolves.toBeDefined()++ await expect(gw.getResource('hosts', 'host', config.hostsNamespace)).resolves.toMatchObject({++ spec: {++ guardrails: {++ hooks: {++ preCall: [{ id: 'response-loss-hook' }],++ },++ },++ },++ })++ })++it('refuses an image→remote upgrade that becomes content-bearing + remote at low trust (the exploit)', async () => {const gw = new MockGateway()// catalog-id matches the entry named below, so this exercises the KIND/TRUST@@@ -4750,32 -4466,6 +6286,106 @@@expect(cr.metadata.annotations['clerum.io/trust-level']).toBe('high')})+ it('pins the hook upgrade to the read resourceVersion', async () => {+ const gw = new MockGateway()+ await seedInstalledImageHook(gw, 'my-hook', { resourceVersion: '17' })+ vi.mocked(resolvePublishScope).mockResolvedValue(clusterScope)+ vi.mocked(getEntryVersion).mockResolvedValue(+ hookEntry({+ name: '@acme/hook',+ trust_level: 'low',+ hook_meta: { target: { image: { ref: IMG_B, port: 8080 } }, lifecyclePoints: ['preCall'] },+ })+ )+ const updateSpy = vi.spyOn(gw, 'updateResource')++ await request(makeApp(gw))+ .post('/admin/registry/upgrade-hook')+ .send({ hookName: 'my-hook', registryEntryName: '@acme/hook', registryEntryVersion: '2.0.0' })+ .expect(200)++ const call = updateSpy.mock.calls.find(c => c[0] === 'llmhooks')+ expect(call?.[2]).toEqual(+ expect.objectContaining({+ metadata: expect.objectContaining({ resourceVersion: '17' }),+ })+ )+ })+++ it('classifies a hook response lost after commit from its operation marker and digest', async () => {++ const gw = new MockGateway()++ await seedInstalledImageHook(gw, 'my-hook')++ vi.mocked(resolvePublishScope).mockResolvedValue(clusterScope)++ vi.mocked(getEntryVersion).mockResolvedValue(++ hookEntry({++ name: '@acme/hook',++ trust_level: 'low',++ hook_meta: { target: { image: { ref: IMG_B, port: 8080 } }, lifecyclePoints: ['preCall'] },++ })++ )++ gw.setResourceUpdateFault(({ plural }) => {++ if (plural === 'llmhooks') {++ gw.setResourceUpdateFault(null)++ throw Object.assign(new Error('hook response lost after commit'), {++ statusCode: 500,++ code: 500,++ })++ }++ })++++ const response = await request(makeApp(gw))++ .post('/admin/registry/upgrade-hook')++ .send({ hookName: 'my-hook', registryEntryName: '@acme/hook', registryEntryVersion: '2.0.0' })++++ expect(response.status, JSON.stringify(response.body)).toBe(200)++ const hook = (await gw.getResource('llmhooks', 'my-hook', config.llmHooksNamespace)) as {++ metadata: { annotations: Record<string, string> }++ spec: { target: { image: { ref: string } } }++ }++ expect(hook.metadata.annotations['clerum.io/registry-operation-id']).toEqual(expect.any(String))++ expect(hook.metadata.annotations['clerum.io/registry-spec-sha256']).toEqual(expect.any(String))++ expect(hook.spec.target.image.ref).toBe(IMG_B)++ })++++ it('returns not_committed when a hook write is rejected before commit', async () => {++ const gw = new MockGateway()++ await seedInstalledImageHook(gw, 'my-hook')++ vi.mocked(resolvePublishScope).mockResolvedValue(clusterScope)++ vi.mocked(getEntryVersion).mockResolvedValue(++ hookEntry({++ name: '@acme/hook',++ trust_level: 'low',++ hook_meta: { target: { image: { ref: IMG_B, port: 8080 } }, lifecyclePoints: ['preCall'] },++ })++ )++ const originalUpdate = gw.updateResource.bind(gw)++ let firstHookWrite = true++ vi.spyOn(gw, 'updateResource').mockImplementation(async (plural, name, body, namespace) => {++ if (plural === 'llmhooks' && firstHookWrite) {++ firstHookWrite = false++ throw Object.assign(new Error('hook request timed out before admission'), {++ statusCode: 500,++ code: 500,++ })++ }++ return originalUpdate(plural, name, body, namespace)++ })++++ const response = await request(makeApp(gw))++ .post('/admin/registry/upgrade-hook')++ .send({ hookName: 'my-hook', registryEntryName: '@acme/hook', registryEntryVersion: '2.0.0' })++++ expect(response.status, JSON.stringify(response.body)).toBe(503)++ expect(response.body).toMatchObject({++ error: 'registry_upgrade_outcome_not_committed',++ outcome: 'not_committed',++ })++ const hook = (await gw.getResource('llmhooks', 'my-hook', config.llmHooksNamespace)) as {++ spec: { target: { image: { ref: string } } }++ }++ expect(hook.spec.target.image.ref).toBe(IMG_A)++ })++it('refuses an upgrade that names a different entry than the one installed', async () => {const gw = new MockGateway()await seedInstalledImageHook(gw)diff --cc control-api/test/routes.resources.contextDisplayNamePruning.test.tsindex fee230312,fee230312..50ac468e4--- a/control-api/test/routes.resources.contextDisplayNamePruning.test.ts+++ b/control-api/test/routes.resources.contextDisplayNamePruning.test.ts@@@ -55,10 -55,10 +55,13 @@@ function realServiceGateway(opts: { pruconst replaceNamespacedCustomObject = vi.fn(async ({ name, body }: { name: string; body: Record<string, unknown> }) => {const persisted = persistWithPruning(body)++ const existing = store.get(name)++ const existingMetadata = existing?.metadata as Record<string, unknown> | undefinedconst stored = {...persisted,metadata: {...(persisted.metadata as Record<string, unknown>),++ uid: existingMetadata?.uid ?? `uid-${name}`,resourceVersion: String(++rv),},}@@@ -73,6 -73,6 +76,7 @@@...persisted,metadata: {...(persisted.metadata as Record<string, unknown>),++ uid: `uid-${body.metadata.name}`,resourceVersion: String(++rv),},}diff --cc control-api/test/routes.resources.test.tsindex 25e09ae13,25e09ae13..676be6d3a--- a/control-api/test/routes.resources.test.ts+++ b/control-api/test/routes.resources.test.ts@@@ -1,5 -1,5 +1,6 @@@import { describe, expect, it, vi } from 'vitest'import express from 'express'++import type { NextFunction, Request, Response } from 'express'import { lookup } from 'node:dns/promises'import request from 'supertest'import { config } from '../src/config.js'@@@ -42,7 -42,7 +43,7 @@@ class PruningCommunicationChannelGatewaclass PruningFirstUpdateCommunicationChannelGateway extends MockGateway {private prunedUpdates = 0-- private resourceVersion = 'rv-1'++ private resourceVersion = '1'readonly updateBodies: Array<Parameters<MockGateway['updateResource']>[2]> = []override async getResource(@@@ -74,7 -74,7 +75,7 @@@const updated = (await super.updateResource(plural, name, body, namespace)) as {metadata?: Record<string, unknown>}-- this.resourceVersion = 'rv-3'++ this.resourceVersion = '3'return {...updated,metadata: {@@@ -88,7 -88,7 +89,7 @@@const updated = (await super.updateResource(plural, name, { ...body, spec }, namespace)) as {metadata?: Record<string, unknown>}-- this.resourceVersion = 'rv-2'++ this.resourceVersion = '2'return {...updated,metadata: {@@@ -99,6 -99,6 +100,31 @@@}}++class ReplacingCredentialOnCommunicationChannelFailureGateway extends MockGateway {++ createdUid?: string++ replacementUid?: string++++ override async createResource(++ plural: Parameters<MockGateway['createResource']>[0],++ body: Parameters<MockGateway['createResource']>[1],++ namespace?: string++ ): Promise<unknown> {++ if (plural !== 'communicationchannels') return super.createResource(plural, body, namespace)++ const ns = namespace || this.getNamespace()++ const credentialName = `cc-${body.metadata.name}-credentials`++ const original = await this.getSecret(credentialName, ns)++ this.createdUid = original.metadata?.uid++ await this.deleteSecret(credentialName, ns)++ this.seedSecret(credentialName, ns, { data: { replacement: 'true' } })++ const replacement = await this.getSecret(credentialName, ns)++ this.replacementUid = replacement.metadata?.uid++ throw Object.assign(new Error('communication channel create failed after replacement'), {++ statusCode: 500,++ code: 500,++ })++ }++}++describe('routes/resources', () => {it('creates and fetches resources (positive flow)', async () => {const gateway = new MockGateway('mcp-server')@@@ -357,6 -357,6 +383,35 @@@)})++ it('does not delete a replacement credential during a failed CommunicationChannel create', async () => {++ const gateway = new ReplacingCredentialOnCommunicationChannelFailureGateway('channels')++ const app = express()++ app.use(express.json())++ app.use(createAdminResourcesRouter(gateway as never))++ app.use((err: unknown, _req: Request, res: Response, _next: NextFunction) => {++ res.status(500).json({ error: err instanceof Error ? err.message : 'unknown' })++ })++++ await request(app)++ .post('/admin/communication-channels')++ .send({++ metadata: { name: 'replacement-channel' },++ spec: {++ hostRef: 'chatllm',++ telegram: [{ channelId: '1', chatType: 'private', userIds: ['user-1'] }],++ },++ credentials: { 'telegram-bot-token': 'initial-value' },++ })++ .expect(500)++++ expect(gateway.createdUid).toBeDefined()++ expect(gateway.replacementUid).toBeDefined()++ expect(gateway.replacementUid).not.toBe(gateway.createdUid)++ await expect(++ gateway.getSecret('cc-replacement-channel-credentials', 'channels')++ ).resolves.toMatchObject({ metadata: { uid: gateway.replacementUid } })++ })++it('rejects and restores the prior communication channel spec when update prunes Teams settings', async () => {const gateway = new PruningFirstUpdateCommunicationChannelGateway('channels')const app = express()@@@ -400,11 -400,11 +455,14 @@@expect((gateway.updateBodies[0].metadata as { resourceVersion?: string } | undefined)?.resourceVersion-- ).toBe('rv-1')++ ).toBe('1')expect((gateway.updateBodies[1].metadata as { resourceVersion?: string } | undefined)?.resourceVersion-- ).toBe('rv-2')++ ).toBe('2')++ expect((gateway.updateBodies[1].metadata as { uid?: string } | undefined)?.uid).toBe(++ (gateway.updateBodies[0].metadata as { uid?: string } | undefined)?.uid++ )const stored = (await gateway.getResource('communicationchannels','teams-channel',@@@ -996,9 -996,9 +1054,9 @@@await request(app).put('/admin/hosts/host-rv')-- .send({ metadata: { resourceVersion: '42' }, spec: { contextRef: 'c1' } })++ .send({ metadata: { resourceVersion: '1' }, spec: { contextRef: 'c1' } }).expect(200)-- expect(seenResourceVersion).toBe('42')++ expect(seenResourceVersion).toBe('1')})it('maps a stale reader resourceVersion (K8sConflictError) to 409 {error:conflict, reason:resource_changed}', async () => {diff --cc control-api/test/routes.secretResponseSummary.test.tsindex 000000000,000000000..1040fe200new file mode 100644--- /dev/null+++ b/control-api/test/routes.secretResponseSummary.test.ts@@@ -1,0 -1,0 +1,78 @@@++import { describe, expect, it, vi } from 'vitest'++import express from 'express'++import request from 'supertest'++import { createAdminSecretsRouter } from '../src/routes/admin/secrets.js'++++function appFor(gateway: Record<string, unknown>) {++ const app = express()++ app.use(express.json())++ app.use(createAdminSecretsRouter(gateway as never))++ return app++}++++describe('Secret response boundary', () => {++ it('returns only identity and key names for admin create and replace', async () => {++ const gateway = {++ listSecrets: vi.fn(async () => []),++ getSecret: vi.fn(async () => ({ metadata: { labels: {} } })),++ createSecret: vi.fn(async (body: unknown) => body),++ updateSecret: vi.fn(async (body: unknown) => body),++ deleteSecret: vi.fn(async () => ({ deleted: true })),++ }++++ const app = appFor(gateway)++ const created = await request(app)++ .post('/admin/secrets')++ .send({ name: 'response-check', data: { field: 'value' } })++ .expect(201)++ const updated = await request(app)++ .put('/admin/secrets')++ .send({ name: 'response-check', data: { field: 'replacement' } })++ .expect(200)++++ for (const response of [created, updated]) {++ expect(response.body).toMatchObject({++ name: 'response-check',++ namespace: 'mcp-host',++ keys: ['field'],++ })++ expect(response.body.data).toBeUndefined()++ expect(response.body.stringData).toBeUndefined()++ }++ })++++ it('returns only identity and key names for recipe replace', async () => {++ const gateway = {++ listSecrets: vi.fn(async () => []),++ getSecret: vi.fn(async () => ({++ metadata: {++ name: 'recipe-check',++ namespace: 'sandbox-recipes',++ uid: 'uid-recipe-check',++ resourceVersion: '1',++ labels: { 'clerum.io/recipe-secret': 'true' },++ },++ data: { field: 'dmFsdWU=' },++ })),++ createSecret: vi.fn(async (body: unknown) => body),++ updateSecret: vi.fn(async (body: unknown) => ({++ ...(body as object),++ data: { field: 'cmVwbGFjZW1lbnQ=' },++ })),++ deleteSecret: vi.fn(async () => ({ deleted: true })),++ }++++ const response = await request(appFor(gateway))++ .put('/admin/recipe-secrets')++ .send({ name: 'recipe-check', data: { field: 'replacement' } })++ .expect(200)++++ expect(response.body).toMatchObject({++ name: 'recipe-check',++ namespace: 'sandbox-recipes',++ keys: ['field'],++ })++ expect(response.body.data).toBeUndefined()++ expect(response.body.stringData).toBeUndefined()++ })++})diff --cc control-api/test/routes.secrets.platformPullSecretName.test.tsindex f296ace9f,61e1241ab..9da62869e--- a/control-api/test/routes.secrets.platformPullSecretName.test.ts+++ b/control-api/test/routes.secrets.platformPullSecretName.test.ts@@@ -99,7 -117,7 +117,10 @@@ describe('platform-managed Secret nametype: 'kubernetes.io/dockerconfigjson',data: { '.dockerconfigjson': 'e30=' },})) as never- const mergeSecret = vi.fn(async (body: unknown) => body)- const mergeSecret = vi.fn(async (body: unknown) => writeSummary(body))++ const mergeSecret = vi.fn(async (body: unknown) => ({++ ...writeSummary(body),++ metadata: { uid: 'uid-platform-test', resourceVersion: '2' },++ }));(gateway as unknown as { mergeSecret: unknown }).mergeSecret = mergeSecretconst res = await request(makeApp(gateway))@@@ -114,11 -132,11 +135,19 @@@it('still merges into an ordinary connector Secret whose name merely resembles it', async () => {const gateway = createGateway()gateway.getSecret = vi.fn(async () => ({-- metadata: { name: `${EVENFIRE_REGISTRY_PULL_SECRET_NAME}-backup`, namespace: 'mcp-server' },++ metadata: {++ name: `${EVENFIRE_REGISTRY_PULL_SECRET_NAME}-backup`,++ namespace: 'mcp-server',++ uid: 'uid-backup',++ resourceVersion: '1',++ },type: 'Opaque',data: {},})) as never- const mergeSecret = vi.fn(async (body: unknown) => body)- const mergeSecret = vi.fn(async (body: unknown) => writeSummary(body))++ const mergeSecret = vi.fn(async (body: unknown) => ({++ ...writeSummary(body),++ metadata: { uid: 'uid-backup', resourceVersion: '2' },++ }));(gateway as unknown as { mergeSecret: unknown }).mergeSecret = mergeSecretawait request(makeApp(gateway))@@@ -131,14 -149,21 +160,25 @@@it('still deletes an ordinary connector Secret whose name merely resembles it', async () => {const gateway = createGateway()+ gateway.getSecret = vi.fn(async () => ({+ metadata: {+ name: `${EVENFIRE_REGISTRY_PULL_SECRET_NAME}-backup`,+ namespace: 'mcp-server',+ labels: {},++ uid: 'uid-backup',++ resourceVersion: '1',+ },+ })) as neverawait request(makeApp(gateway)).delete(`/admin/mcp-secrets/${EVENFIRE_REGISTRY_PULL_SECRET_NAME}-backup`)++ .send({ uid: 'uid-backup', resourceVersion: '1' }).expect(200)expect(gateway.deleteSecret).toHaveBeenCalledWith(`${EVENFIRE_REGISTRY_PULL_SECRET_NAME}-backup`,-- 'mcp-server'++ 'mcp-server',++ { uid: 'uid-backup', resourceVersion: '1' })})})diff --cc control-api/test/routes.secrets.test.tsindex 7d23371fd,fcfe3f8ff..02a1c75f1--- a/control-api/test/routes.secrets.test.ts+++ b/control-api/test/routes.secrets.test.ts@@@ -127,7 -144,7 +144,13 @@@ describe('routes/secrets', () =>if (!(name in labelledSecrets)) throw new Error('not found')const entry = labelledSecrets[name]return {-- metadata: { name, namespace: 'sandbox-recipes', labels: entry.labels },++ metadata: {++ name,++ namespace: 'sandbox-recipes',++ uid: `uid-${name}`,++ resourceVersion: '1',++ labels: entry.labels,++ },data: entry.data,}}),@@@ -362,6 -382,6 +388,8 @@@metadata: {name,namespace,++ uid: `uid-${name}`,++ resourceVersion: '1',labels: { 'clerum.io/recipe-secret': 'true', 'clerum.io/shared': 'true' },},data: {},@@@ -383,7 -403,7 +411,8 @@@name: 'ui-creds',namespace: 'sandbox-ui',labels: { 'clerum.io/recipe-secret': 'true', 'clerum.io/shared': 'true' },-- })++ }),++ { uid: 'uid-ui-creds', resourceVersion: '1' })})@@@ -449,8 -469,8 +478,14 @@@app.use(express.json())app.use(createAdminSecretsRouter(gateway as never))-- await request(app).delete('/admin/recipe-secrets/r1').expect(200)-- expect(gateway.deleteSecret).toHaveBeenCalledWith('r1', 'sandbox-recipes')++ await request(app)++ .delete('/admin/recipe-secrets/r1')++ .send({ uid: 'uid-r1', resourceVersion: '1' })++ .expect(200)++ expect(gateway.deleteSecret).toHaveBeenCalledWith('r1', 'sandbox-recipes', {++ uid: 'uid-r1',++ resourceVersion: '1',++ })})it('deletes a recipe secret from an allowed runtime namespace', async () => {@@@ -461,6 -481,6 +496,8 @@@metadata: {name,namespace,++ uid: `uid-${name}`,++ resourceVersion: '1',labels: { 'clerum.io/recipe-secret': 'true', 'clerum.io/shared': 'true' },},data: {},@@@ -474,8 -494,8 +511,12 @@@await request(app).delete('/admin/recipe-secrets/ui-creds?targetNamespace=sandbox-ui')++ .send({ uid: 'uid-ui-creds', resourceVersion: '1' }).expect(200)-- expect(gateway.deleteSecret).toHaveBeenCalledWith('ui-creds', 'sandbox-ui')++ expect(gateway.deleteSecret).toHaveBeenCalledWith('ui-creds', 'sandbox-ui', {++ uid: 'uid-ui-creds',++ resourceVersion: '1',++ })})it('rejects recipe secret delete outside the workflow secret namespace allowlist', async () => {diff --cc control-api/test/routes.secretsNamesOnly.integration.test.tsindex 000000000,4b3d1b4ab..7e89770acmode 000000,100644..100644--- a/control-api/test/routes.secretsNamesOnly.integration.test.ts+++ b/control-api/test/routes.secretsNamesOnly.integration.test.ts@@@ -1,0 -1,145 +1,145 @@@+ import { describe, expect, it, vi } from 'vitest'+ import express from 'express'+ import request from 'supertest'+ import { createAdminSecretsRouter } from '../src/routes/admin/secrets.js'+ import { SecretService } from '../src/services/secretService.js'++ // Integration guard for the names-only write contract (SECURITY). Unlike the+ // unit route tests (which mock the K8sGateway and so bypass the trim), this wires+ // the REAL SecretService behind the REAL admin secrets router and mocks ONLY the+ // external Kubernetes CoreV1Api — the correct boundary to mock. The mocked k8s+ // client returns FULL V1Secrets with base64 `.data`, so the ONLY reason the HTTP+ // response is names-only is the SecretService trim. These tests go RED if the+ // service ever stops trimming (i.e. the leak returns), even though no route code+ // changed for the sibling endpoints.++ const b64 = (s: string): string => Buffer.from(s, 'utf8').toString('base64')++ const LEAK = 'leak-me-please'+ const OTHER = 'other-provider-secret'++ function fullSecret(+ name: string,+ namespace: string,+ data: Record<string, string>,+ labels: Record<string, string> = {}+ ): Record<string, unknown> {+ return {+ apiVersion: 'v1',+ kind: 'Secret',- metadata: { name, namespace, resourceVersion: '7', labels },++ metadata: { name, namespace, resourceVersion: '7', uid: `uid-${name}`, labels },+ type: 'Opaque',+ data,+ }+ }++ function makeApp(opts: {+ existing?: Record<string, unknown> | null+ written: Record<string, unknown>+ }): { app: express.Express; core: Record<string, ReturnType<typeof vi.fn>> } {+ const core = {+ createNamespacedSecret: vi.fn(async () => opts.written),+ readNamespacedSecret: vi.fn(async () => {+ if (opts.existing == null) {+ throw Object.assign(new Error('not found'), { statusCode: 404 })+ }+ return opts.existing+ }),+ replaceNamespacedSecret: vi.fn(async () => opts.written),+ patchNamespacedSecret: vi.fn(async () => opts.written),+ deleteNamespacedSecret: vi.fn(async () => ({ kind: 'Status', status: 'Success' })),+ listNamespacedSecret: vi.fn(async () => ({ items: [] })),+ }+ const svc = new SecretService(core as never, 'mcp-host')+ // Minimal gateway facade delegating secret ops to the REAL service; only the+ // methods the routes under test touch are provided.+ const gateway = {+ listSecrets: (ns?: string) => svc.listSecrets(ns),+ getSecret: (n: string, ns?: string) => svc.getSecret(n, ns),+ createSecret: (r: never) => svc.createSecret(r),+ updateSecret: (r: never) => svc.updateSecret(r),+ deleteSecret: (n: string, ns?: string) => svc.deleteSecret(n, ns),+ listResource: vi.fn(async () => []),+ }+ const app = express()+ app.use(express.json())+ app.use(createAdminSecretsRouter(gateway as never))+ return { app, core }+ }++ // Asserts an HTTP body carries no secret value at any depth and no `.data` field.+ function expectNoSecretValues(body: unknown): void {+ const serialized = JSON.stringify(body)+ for (const needle of [LEAK, OTHER, b64(LEAK), b64(OTHER)]) {+ expect(serialized).not.toContain(needle)+ }+ expect((body as { data?: unknown }).data).toBeUndefined()+ }++ describe('SECURITY (integration): admin secret-write responses are names-only', () => {+ it('POST /admin/secrets does not echo the created Secret .data', async () => {+ const { app } = makeApp({+ written: fullSecret('svc-token', 'mcp-host', { token: b64(LEAK) }),+ })+ const res = await request(app)+ .post('/admin/secrets')+ .send({ name: 'svc-token', stringData: { token: LEAK } })+ .expect(201)++ expect(res.body).toMatchObject({ name: 'svc-token', keys: ['token'] })+ expect(res.body).not.toHaveProperty('data')+ expectNoSecretValues(res.body)+ })++ it('PUT /admin/secrets (full-replace) does not echo the replaced Secret .data', async () => {+ const { app } = makeApp({+ // getSecret (validation-only label read) + updateSecret read-then-replace.+ existing: fullSecret('svc-token', 'mcp-host', { token: b64('old') }),+ written: fullSecret('svc-token', 'mcp-host', { token: b64(LEAK) }),+ })+ const res = await request(app)+ .put('/admin/secrets')+ .send({ name: 'svc-token', stringData: { token: LEAK } })+ .expect(200)++ expect(res.body).toMatchObject({ name: 'svc-token', keys: ['token'] })+ expectNoSecretValues(res.body)+ })++ it('PUT /admin/recipe-secrets does not echo merged .data (incl. keys the caller did not send)', async () => {+ const { app } = makeApp({+ // Existing recipe secret carries a key the caller does NOT send this time;+ // the merge-patch response would include it — only its NAME may surface.+ existing: fullSecret(+ 'r1',+ 'sandbox-recipes',+ { EXISTING: b64(OTHER) },+ { 'clerum.io/recipe-secret': 'true', 'clerum.io/shared': 'true' }+ ),+ written: fullSecret(+ 'r1',+ 'sandbox-recipes',+ { EXISTING: b64(OTHER), TOKEN: b64(LEAK) },+ { 'clerum.io/recipe-secret': 'true', 'clerum.io/shared': 'true' }+ ),+ })+ const res = await request(app)+ .put('/admin/recipe-secrets')+ .send({ name: 'r1', data: { TOKEN: LEAK } })+ .expect(200)++ // Names-only, and the resulting keyset includes the pre-existing key by NAME+ // only (never its value) — proving the merge response was trimmed.+ expect(res.body).toMatchObject({ name: 'r1', keys: ['EXISTING', 'TOKEN'] })+ expectNoSecretValues(res.body)+ })++ it('DELETE /admin/secrets/:name returns a names-only summary, not a Secret body', async () => {+ const { app } = makeApp({+ written: fullSecret('svc-token', 'mcp-host', { token: b64(LEAK) }),+ })+ const res = await request(app).delete('/admin/secrets/svc-token').expect(200)+ expect(res.body).toMatchObject({ name: 'svc-token', deleted: true })+ expectNoSecretValues(res.body)+ })+ })diff --cc control-api/test/services.registryMutation.test.tsindex 000000000,000000000..f1e5eb4d0new file mode 100644--- /dev/null+++ b/control-api/test/services.registryMutation.test.ts@@@ -1,0 -1,0 +1,291 @@@++import { describe, expect, it } from 'vitest'++import {++ REGISTRY_OPERATION_ID_ANNOTATION,++ REGISTRY_SPEC_DIGEST_ANNOTATION,++ type RegistryMutationDesired,++ type RegistryResourceSnapshot,++ classifyCreatedRegistryMutationReadback,++ classifyRegistryMutationReadback,++ classifySecretMutationReadback,++ registrySecretDataDigest,++ registrySpecDigest,++} from '../src/services/registryMutation.js'++++const operationId = 'operation-current'++const before: RegistryResourceSnapshot = {++ metadata: {++ uid: 'uid-server-a',++ resourceVersion: 'opaque-before',++ labels: { 'clerum.io/managed-by': 'control-api', 'clerum.io/server-mode': 'local' },++ annotations: { 'clerum.io/catalog-id': 'entry', 'clerum.io/catalog-version': '1.0.0' },++ },++ spec: { image: 'plugin:old', transport: { port: 3000 } },++}++const desiredSpec = { image: 'plugin:new', transport: { port: 3000 }, egressBindings: [] }++const desired: RegistryMutationDesired = {++ spec: desiredSpec,++ metadata: {++ labels: before.metadata?.labels,++ annotations: {++ ...before.metadata?.annotations,++ [REGISTRY_OPERATION_ID_ANNOTATION]: operationId,++ [REGISTRY_SPEC_DIGEST_ANNOTATION]: registrySpecDigest(desiredSpec),++ },++ },++ specDigest: registrySpecDigest(desiredSpec),++}++++function current(overrides: Partial<RegistryResourceSnapshot>): RegistryResourceSnapshot {++ return {++ metadata: { ...before.metadata, ...(overrides.metadata ?? {}) },++ spec: overrides.spec ?? before.spec,++ }++}++++describe('registry mutation readback classifier', () => {++ it('canonicalizes object key order but preserves array order', () => {++ expect(registrySpecDigest({ b: 2, a: { d: 4, c: 3 }, ignored: undefined })).toBe(++ registrySpecDigest({ a: { c: 3, d: 4 }, b: 2 })++ )++ expect(registrySpecDigest({ values: ['a', 'b'] })).not.toBe(++ registrySpecDigest({ values: ['b', 'a'] })++ )++ })++++ it('classifies a stable unchanged prior object as not committed', () => {++ expect(++ classifyRegistryMutationReadback({++ before,++ desired,++ current: current({}),++ operationId,++ })++ ).toBe('not-committed')++ })++++ it('requires the current operation identity, desired digest, labels and an advanced RV', () => {++ expect(++ classifyRegistryMutationReadback({++ before,++ desired,++ current: current({++ metadata: {++ resourceVersion: 'opaque-after',++ annotations: desired.metadata.annotations,++ },++ spec: desiredSpec,++ }),++ operationId,++ })++ ).toBe('committed')++++ expect(++ classifyRegistryMutationReadback({++ before,++ desired,++ current: current({++ metadata: {++ resourceVersion: 'opaque-after',++ annotations: desired.metadata.annotations,++ labels: { ...before.metadata?.labels, 'clerum.io/server-mode': 'remote' },++ },++ spec: desiredSpec,++ }),++ operationId,++ })++ ).toBe('ambiguous')++ })++++ it('rejects a replacement UID even when it copied the complete current intent', () => {++ expect(++ classifyRegistryMutationReadback({++ before,++ desired,++ current: {++ metadata: {++ ...before.metadata,++ uid: 'uid-server-replacement',++ resourceVersion: 'opaque-after',++ annotations: desired.metadata.annotations,++ labels: desired.metadata.labels,++ },++ spec: desiredSpec,++ },++ operationId,++ })++ ).toBe('ambiguous')++ })++++ it.each([++ ['different UID', { metadata: { uid: 'uid-server-b' }, spec: desiredSpec }],++ ['different operation', { metadata: { resourceVersion: 'opaque-after' }, spec: desiredSpec }],++ [++ 'different spec',++ {++ metadata: { resourceVersion: 'opaque-after', annotations: desired.metadata.annotations },++ spec: { image: 'plugin:other' },++ },++ ],++ ['missing current identity', { metadata: { uid: undefined }, spec: desiredSpec }],++ ])('returns ambiguous for %s', (_label, overrides) => {++ const metadata = {++ ...before.metadata,++ ...overrides.metadata,++ ...(overrides.metadata?.resourceVersion++ ? {}++ : { [REGISTRY_OPERATION_ID_ANNOTATION]: 'other-operation' }),++ }++ expect(++ classifyRegistryMutationReadback({++ before,++ desired,++ current: current({ metadata, spec: overrides.spec }),++ operationId,++ })++ ).toBe('ambiguous')++ })++})++++describe('credential mutation readback classifier', () => {++ const beforeSecret = {++ metadata: {++ uid: 'uid-credential-a',++ resourceVersion: '7',++ annotations: { 'clerum.io/registry-operation-id': 'previous-operation' },++ },++ }++++ it('classifies a matching readback as a desired candidate, never as a commit receipt', () => {++ expect(++ classifySecretMutationReadback({++ before: beforeSecret,++ current: {++ metadata: {++ uid: beforeSecret.metadata.uid,++ resourceVersion: '8',++ annotations: { 'clerum.io/registry-operation-id': operationId },++ },++ },++ operationId,++ operationAnnotationKey: 'clerum.io/registry-operation-id',++ expectedDataDigest: registrySecretDataDigest(undefined),++ })++ ).toBe('desired')++ })++++ it('keeps a same-UID metadata race ambiguous even when data and marker match', () => {++ const expectedAnnotations = {++ 'clerum.io/registry-operation-id': operationId,++ }++ expect(++ classifySecretMutationReadback({++ before: beforeSecret,++ current: {++ metadata: {++ uid: beforeSecret.metadata.uid,++ resourceVersion: '8',++ annotations: { ...expectedAnnotations, 'concurrent.example/trace': 'writer-b' },++ },++ stringData: { field: 'expected' },++ },++ operationId,++ operationAnnotationKey: 'clerum.io/registry-operation-id',++ expectedDataDigest: registrySecretDataDigest(undefined, { field: 'expected' }),++ expectedMetadata: { annotations: expectedAnnotations },++ })++ ).toBe('ambiguous')++ })++++ it('keeps a delete-and-recreated object ambiguous even when it copies the operation marker', () => {++ expect(++ classifySecretMutationReadback({++ before: beforeSecret,++ current: {++ metadata: {++ uid: 'uid-credential-replacement',++ resourceVersion: '1',++ annotations: { 'clerum.io/registry-operation-id': operationId },++ },++ },++ operationId,++ operationAnnotationKey: 'clerum.io/registry-operation-id',++ })++ ).toBe('ambiguous')++ })++++ it('does not turn an absent marker or a missing read into no-commit', () => {++ expect(++ classifySecretMutationReadback({++ before: beforeSecret,++ current: {++ metadata: {++ uid: beforeSecret.metadata.uid,++ resourceVersion: '8',++ annotations: { 'clerum.io/registry-operation-id': 'other-operation' },++ },++ },++ operationId,++ operationAnnotationKey: 'clerum.io/registry-operation-id',++ })++ ).toBe('ambiguous')++ expect(++ classifySecretMutationReadback({++ before: undefined,++ current: null,++ operationId,++ operationAnnotationKey: 'clerum.io/registry-operation-id',++ })++ ).toBe('ambiguous')++ })++})++++describe('created resource readback classifier', () => {++ const desiredSpec = { image: 'example:new', transport: { port: 3000 } }++ const desired = {++ spec: desiredSpec,++ metadata: {++ labels: { 'clerum.io/managed-by': 'control-api' },++ annotations: {++ [REGISTRY_OPERATION_ID_ANNOTATION]: operationId,++ [REGISTRY_SPEC_DIGEST_ANNOTATION]: registrySpecDigest(desiredSpec),++ },++ },++ specDigest: registrySpecDigest(desiredSpec),++ }++++ it('requires operation identity, exact intent digest, and server identity', () => {++ expect(++ classifyCreatedRegistryMutationReadback({++ current: {++ metadata: {++ uid: 'uid-created',++ resourceVersion: '1',++ labels: desired.metadata.labels,++ annotations: desired.metadata.annotations,++ },++ spec: desiredSpec,++ },++ desired,++ operationId,++ })++ ).toBe('committed')++ expect(++ classifyCreatedRegistryMutationReadback({++ current: {++ metadata: {++ uid: 'uid-created',++ resourceVersion: '1',++ labels: desired.metadata.labels,++ annotations: {++ ...desired.metadata.annotations,++ [REGISTRY_OPERATION_ID_ANNOTATION]: 'other',++ },++ },++ spec: desiredSpec,++ },++ desired,++ operationId,++ })++ ).toBe('ambiguous')++ })++})diff --cc control-api/test/services.resourceService.test.tsindex 0223a70fb,0223a70fb..7d66a9f57--- a/control-api/test/services.resourceService.test.ts+++ b/control-api/test/services.resourceService.test.ts@@@ -90,6 -90,6 +90,78 @@@ describe('ResourceService.getResource'})describe('ResourceService.updateResource', () => {++ it('forwards UID together with resourceVersion for an identity-bound replacement', async () => {++ const customApi = {++ getNamespacedCustomObject: vi.fn().mockResolvedValue({++ metadata: {++ name: 'cc-a',++ namespace: 'channels',++ uid: 'uid-original',++ resourceVersion: '10',++ },++ spec: { enabled: true },++ }),++ replaceNamespacedCustomObject: vi.fn().mockResolvedValue({++ metadata: {++ name: 'cc-a',++ namespace: 'channels',++ uid: 'uid-original',++ resourceVersion: '11',++ },++ }),++ listNamespacedCustomObject: vi.fn(),++ }++ const service = new ResourceService(customApi as never, 'control-plane', {++ communicationchannels: 'channels',++ })++++ await service.updateResource(++ 'communicationchannels',++ 'cc-a',++ {++ metadata: { uid: 'uid-original', resourceVersion: '10' },++ spec: { enabled: false },++ },++ 'channels'++ )++++ const replaceArgs = customApi.replaceNamespacedCustomObject.mock.calls[0][0]++ expect(replaceArgs.body.metadata.uid).toBe('uid-original')++ expect(replaceArgs.body.metadata.resourceVersion).toBe('10')++ })++++ it('fails closed before replacement when the identity precondition names a replacement object', async () => {++ const customApi = {++ getNamespacedCustomObject: vi.fn().mockResolvedValue({++ metadata: {++ name: 'cc-a',++ namespace: 'channels',++ uid: 'uid-replacement',++ resourceVersion: '10',++ },++ spec: { enabled: true },++ }),++ replaceNamespacedCustomObject: vi.fn(),++ listNamespacedCustomObject: vi.fn(),++ }++ const service = new ResourceService(customApi as never, 'control-plane', {++ communicationchannels: 'channels',++ })++++ await expect(++ service.updateResource(++ 'communicationchannels',++ 'cc-a',++ {++ metadata: { uid: 'uid-original', resourceVersion: '10' },++ spec: { enabled: false },++ },++ 'channels'++ )++ ).rejects.toBeInstanceOf(K8sConflictError)++ expect(customApi.replaceNamespacedCustomObject).not.toHaveBeenCalled()++ })++it('refetches and retries once when Kubernetes reports a resourceVersion conflict', async () => {const customApi = {getNamespacedCustomObject: vi@@@ -133,6 -133,6 +205,32 @@@})})++describe('ResourceService.deleteResource', () => {++ it('forwards UID and resourceVersion preconditions to Kubernetes', async () => {++ const customApi = {++ deleteNamespacedCustomObject: vi.fn(async () => ({ deleted: true })),++ listNamespacedCustomObject: vi.fn(),++ }++ const service = new ResourceService(customApi as never, 'control-plane', {++ mcpservers: 'mcp-server',++ })++++ await service.deleteResource('mcpservers', 'mcp-a', 'mcp-server', {++ uid: 'uid-a',++ resourceVersion: '7',++ })++++ expect(customApi.deleteNamespacedCustomObject).toHaveBeenCalledWith({++ group: 'clerum.io',++ version: 'v1alpha1',++ namespace: 'mcp-server',++ plural: 'mcpservers',++ name: 'mcp-a',++ body: { preconditions: { uid: 'uid-a', resourceVersion: '7' } },++ })++ })++})++describe('ResourceService.updateResource — AP-6 reader-version precondition', () => {function makeCustomApi(overrides: {diff --cc control-api/test/services.secretMetadataPreservation.test.tsindex 000000000,000000000..7a8f83093new file mode 100644--- /dev/null+++ b/control-api/test/services.secretMetadataPreservation.test.ts@@@ -1,0 -1,0 +1,54 @@@++import { describe, expect, it, vi } from 'vitest'++import { SecretService } from '../src/services/secretService.js'++++describe('SecretService replacement metadata preservation', () => {++ it('preserves protected metadata during an identity-bound replace', async () => {++ const existing = {++ metadata: {++ name: 'registry-credentials',++ namespace: 'sandbox',++ uid: 'secret-uid-1',++ resourceVersion: '41',++ labels: { 'clerum.io/managed-by': 'control-api' },++ annotations: { 'example.com/owner': 'registry' },++ ownerReferences: [++ {++ apiVersion: 'apps/v1',++ kind: 'Deployment',++ name: 'connector',++ uid: 'deployment-uid-1',++ },++ ],++ finalizers: ['example.com/cleanup'],++ },++ type: 'Opaque',++ immutable: true,++ data: { token: 'old' },++ }++ const replaced = {++ ...existing,++ metadata: { ...existing.metadata, resourceVersion: '42' },++ data: { token: 'new' },++ }++ const readNamespacedSecret = vi.fn().mockResolvedValue(existing)++ const replaceNamespacedSecret = vi.fn().mockResolvedValue(replaced)++ const service = new SecretService(++ { readNamespacedSecret, replaceNamespacedSecret } as never,++ 'sandbox'++ )++++ await service.updateSecret(++ {++ name: 'registry-credentials',++ namespace: 'sandbox',++ data: { token: 'new' },++ },++ { uid: 'secret-uid-1', resourceVersion: '41' }++ )++++ const request = replaceNamespacedSecret.mock.calls[0][0]++ expect(request.body.metadata.ownerReferences).toEqual(existing.metadata.ownerReferences)++ expect(request.body.metadata.finalizers).toEqual(existing.metadata.finalizers)++ expect(request.body.immutable).toBe(true)++ })++})diff --cc control-api/test/services.secretService.test.tsindex 6adcb1416,8217414c2..3a07e8032--- a/control-api/test/services.secretService.test.ts+++ b/control-api/test/services.secretService.test.ts@@@ -1,14 -1,5 +1,15 @@@import { beforeEach, describe, expect, it, vi } from 'vitest'import * as k8s from '@kubernetes/client-node'+import { extractHttpStatus } from '../src/k8s.js'+import {+ ALLOWED_SECRET_TYPES,+ DangerousAnnotationError,+ InvalidSecretTypeError,+ REGISTRY_SECRET_PRESERVED_ANNOTATION_KEYS,+ dangerousAnnotationKeyReason,+ invalidSecretTypeReason,++ resolveSecretAnnotationsForReplace,+} from '../src/services/secretConstraints.js'import {InvalidSecretKeyError,SECRET_DATA_KEY_MAX_LENGTH,@@@ -56,16 -264,11 +274,17 @@@ type CoreApiMock =function createCoreApiMock(): CoreApiMock {return {+ listNamespacedSecret: vi.fn().mockResolvedValue({ items: [] }),readNamespacedSecret: vi.fn().mockResolvedValue({ metadata: {}, type: 'Opaque', data: {} }),- createNamespacedSecret: vi.fn().mockResolvedValue({ metadata: { name: 's' } }),- replaceNamespacedSecret: vi.fn().mockResolvedValue({ metadata: { name: 's' } }),- patchNamespacedSecret: vi.fn().mockResolvedValue({ metadata: { name: 's' } }),+ createNamespacedSecret: vi.fn().mockResolvedValue({+ metadata: { name: 's', namespace: 'test-ns', uid: 'uid-s', resourceVersion: '2' },+ }),+ replaceNamespacedSecret: vi.fn().mockResolvedValue({+ metadata: { name: 's', namespace: 'test-ns', uid: 'uid-s', resourceVersion: '2' },+ }),+ patchNamespacedSecret: vi.fn().mockResolvedValue({+ metadata: { name: 's', namespace: 'test-ns', uid: 'uid-s', resourceVersion: '2' },+ }),deleteNamespacedSecret: vi.fn().mockResolvedValue({}),}}@@@ -227,7 -545,7 +596,7 @@@ describe('SecretService — ownership-bsvc = new SecretService(coreApi as unknown as k8s.CoreV1Api, 'test-ns')})-- it('sends the CALLER’s resourceVersion on a replace, without re-reading', async () => {++ it('sends the CALLER’s resourceVersion on a replace after reading protected metadata', async () => {coreApi.readNamespacedSecret.mockResolvedValue({metadata: { resourceVersion: '999' },type: 'Opaque',@@@ -239,39 -557,14 +608,93 @@@{ resourceVersion: '42', uid: 'uid-1' })-- // The re-read is the bug, not an optimization: it would replace the stale version we-- // are trying to detect with the current one, and the write would win regardless.-- expect(coreApi.readNamespacedSecret).not.toHaveBeenCalled()++ // The caller's version remains the CAS boundary even though the service reads the++ // current metadata first to avoid dropping protected annotations.++ expect(coreApi.readNamespacedSecret).toHaveBeenCalledOnce()const body = coreApi.replaceNamespacedSecret.mock.calls[0][0].bodyexpect(body.metadata.resourceVersion).toBe('42')expect(body.metadata.uid).toBe('uid-1')})+ it('returns the server-confirmed identity from replace', async () => {+ coreApi.replaceNamespacedSecret.mockResolvedValueOnce({+ metadata: {+ name: 's',+ namespace: 'ns',+ uid: 'uid-server',+ resourceVersion: '43',+ },+ type: 'Opaque',+ data: {},+ })+- const result = await svc.updateSecret(++ const result = await svc.updateSecretSnapshot(+ { name: 's', namespace: 'ns', type: 'Opaque', data: { k: 'dg==' } },+ { resourceVersion: '42', uid: 'uid-server' }+ )++ expect(result).toMatchObject({+ name: 's',+ namespace: 'ns',+ uid: 'uid-server',+ resourceVersion: '43',+ })+ })+++ it('always carries an explicit identity precondition in a merge patch', async () => {++ await svc.mergeSecret({ name: 's', namespace: 'ns', stringData: { k: 'rotated' } }, undefined, {++ uid: 'uid-1',++ resourceVersion: '42',++ })++++ const body = coreApi.patchNamespacedSecret.mock.calls[0][0].body++ expect(body.metadata).toEqual({ uid: 'uid-1', resourceVersion: '42' })++ })++++ it('can fence a data-only merge by UID without reintroducing a resourceVersion CAS', async () => {++ coreApi.readNamespacedSecret.mockResolvedValueOnce({++ metadata: { uid: 'uid-1', resourceVersion: '42' },++ type: 'Opaque',++ data: {},++ })++++ await svc.mergeSecret({ name: 's', namespace: 'ns', stringData: { k: 'rotated' } }, undefined, {++ uid: 'uid-1',++ })++++ const body = coreApi.patchNamespacedSecret.mock.calls[0][0].body++ expect(body.metadata).toEqual({ uid: 'uid-1' })++ expect(body).not.toHaveProperty('metadata.resourceVersion')++ })++++ it('does not turn an unconditioned multi-owner merge into an implicit CAS', async () => {++ coreApi.readNamespacedSecret.mockResolvedValueOnce({++ metadata: { resourceVersion: '999' },++ type: 'Opaque',++ data: {},++ })++++ await svc.mergeSecret({ name: 's', namespace: 'ns', stringData: { k: 'rotated' } })++++ expect(coreApi.patchNamespacedSecret.mock.calls[0][0].body).not.toHaveProperty(++ 'metadata.resourceVersion'++ )++ })++++ it('does not turn an unconditioned key removal into an implicit CAS', async () => {++ coreApi.readNamespacedSecret.mockResolvedValueOnce({++ metadata: { resourceVersion: '999' },++ type: 'Opaque',++ data: {},++ })++++ await svc.removeSecretKey({ name: 's', namespace: 'ns', key: 'API_KEY' })++++ expect(coreApi.patchNamespacedSecret.mock.calls[0][0].body).not.toHaveProperty(++ 'metadata.resourceVersion'++ )++ })++it('keeps last-writer-wins when no precondition is given', async () => {coreApi.readNamespacedSecret.mockResolvedValue({metadata: { resourceVersion: '999' },@@@ -305,604 -598,6 +728,703 @@@})})+describe('SecretService — preserved Secret state is constrained before mutation', () => {+ let coreApi: CoreApiMock+ let svc: SecretService++ beforeEach(() => {+ coreApi = createCoreApiMock()+ svc = new SecretService(coreApi as unknown as k8s.CoreV1Api, 'test-ns')+ })++ it('preserves legacy infrastructure metadata during a data-only update', async () => {+ const legacyApplyKey = DANGEROUS_ANNOTATION_KEYS[0]+ const annotations = { [legacyApplyKey]: 'legacy-configuration' }+ coreApi.readNamespacedSecret.mockResolvedValueOnce({+ metadata: { annotations, uid: 'uid-existing', resourceVersion: '7' },+ type: 'Opaque',+ })++ await svc.updateSecret({+ name: 's',+ namespace: 'test-ns',+ stringData: { [VALID_KEYS[0]]: 'rotated' },+ })++ expect(coreApi.replaceNamespacedSecret).toHaveBeenCalledOnce()+ expect(coreApi.replaceNamespacedSecret.mock.calls[0][0].body.metadata.annotations).toEqual(+ annotations+ )+ })+++ it('does not let an explicit annotation replacement drop existing infrastructure metadata', async () => {++ const legacyApplyKey = DANGEROUS_ANNOTATION_KEYS[0]++ const annotations = { [legacyApplyKey]: 'legacy-configuration' }++ coreApi.readNamespacedSecret.mockResolvedValueOnce({++ metadata: { annotations, uid: 'uid-existing', resourceVersion: '7' },++ type: 'Opaque',++ })++++ await svc.updateSecret({++ name: 's',++ namespace: 'test-ns',++ annotations: { 'my-custom-annotation': 'replacement' },++ stringData: { [VALID_KEYS[0]]: 'rotated' },++ })++++ expect(coreApi.replaceNamespacedSecret.mock.calls[0][0].body.metadata.annotations).toEqual({++ ...annotations,++ 'my-custom-annotation': 'replacement',++ })++ })++++ it('does not let a preconditioned replacement drop existing infrastructure metadata', async () => {++ const legacyApplyKey = DANGEROUS_ANNOTATION_KEYS[0]++ const annotations = { [legacyApplyKey]: 'legacy-configuration' }++ coreApi.readNamespacedSecret.mockResolvedValueOnce({++ metadata: { annotations, uid: 'uid-existing', resourceVersion: '7' },++ type: 'Opaque',++ })++++ await svc.updateSecret(++ {++ name: 's',++ namespace: 'test-ns',++ annotations: {},++ type: 'Opaque',++ stringData: { [VALID_KEYS[0]]: 'rotated' },++ },++ { uid: 'uid-existing', resourceVersion: '7' }++ )++++ expect(coreApi.replaceNamespacedSecret.mock.calls[0][0].body.metadata.annotations).toEqual(++ annotations++ )++ })+++ it('preserves legacy infrastructure metadata during a data-only merge', async () => {+ const legacyApplyKey = DANGEROUS_ANNOTATION_KEYS[0]+ const annotations = { [legacyApplyKey]: 'legacy-configuration' }+ coreApi.readNamespacedSecret.mockResolvedValueOnce({+ metadata: { annotations, resourceVersion: '11' },+ type: 'Opaque',+ })++ await svc.mergeSecret({+ name: 's',+ namespace: 'test-ns',+ stringData: { [VALID_KEYS[0]]: 'rotated' },+ })++ expect(coreApi.patchNamespacedSecret).toHaveBeenCalledOnce()+ expect(coreApi.patchNamespacedSecret.mock.calls[0][0].body).not.toHaveProperty(+ 'metadata.annotations'+ )+ })++ it('preserves legacy infrastructure metadata during key removal', async () => {+ const legacyReleaseKey = DANGEROUS_ANNOTATION_KEYS[4]+ coreApi.readNamespacedSecret.mockResolvedValueOnce({+ metadata: { annotations: { [legacyReleaseKey]: 'evenfire' }, resourceVersion: '13' },+ type: 'Opaque',+ })++ await svc.removeSecretKey({ name: 's', namespace: 'test-ns', key: VALID_KEYS[0] })++ expect(coreApi.patchNamespacedSecret).toHaveBeenCalledOnce()+ expect(coreApi.patchNamespacedSecret.mock.calls[0][0].body.data).toEqual({+ [VALID_KEYS[0]]: null,+ })+ })++ it('rejects update when an omitted type preserves a forbidden existing type', async () => {+ coreApi.readNamespacedSecret.mockResolvedValueOnce({+ metadata: {},+ type: 'kubernetes.io/service-account-token',+ })++ await expect(+ svc.updateSecret({ name: 's', namespace: 'test-ns', stringData: { k: 'v' } })+ ).rejects.toBeInstanceOf(InvalidSecretTypeError)+ expect(coreApi.replaceNamespacedSecret).not.toHaveBeenCalled()+ })++ it('allows update when omitted annotations preserve infrastructure metadata', async () => {+ coreApi.readNamespacedSecret.mockResolvedValueOnce({+ metadata: { annotations: { 'meta.helm.sh/release-name': 'release' } },+ type: 'Opaque',+ })++ await expect(+ svc.updateSecret({ name: 's', namespace: 'test-ns', stringData: { k: 'v' } })+ ).resolves.toMatchObject({ name: 's', namespace: 'test-ns' })+ expect(coreApi.replaceNamespacedSecret).toHaveBeenCalledOnce()+ })++ it('rejects merge when the preserved existing type is forbidden', async () => {+ coreApi.readNamespacedSecret.mockResolvedValueOnce({+ metadata: {},+ type: 'kubernetes.io/ssh-auth',+ })++ await expect(+ svc.mergeSecret({ name: 's', namespace: 'test-ns', stringData: { k: 'v' } })+ ).rejects.toBeInstanceOf(InvalidSecretTypeError)+ expect(coreApi.patchNamespacedSecret).not.toHaveBeenCalled()+ })+- it('fails closed when an existing Secret has partial platform metadata', async () => {++ it('preserves unknown platform metadata without locking data-only rotation', async () => {+ coreApi.readNamespacedSecret.mockResolvedValueOnce({+ metadata: { annotations: { 'clerum.io/catalog-id': 'legacy-only' } },+ type: 'Opaque',+ })++ await expect(+ svc.mergeSecret({ name: 's', namespace: 'test-ns', stringData: { k: 'v' } })- ).rejects.toMatchObject({- annotationKey: 'clerum.io/catalog-id',- status: 400,- })- expect(coreApi.patchNamespacedSecret).not.toHaveBeenCalled()++ ).resolves.toMatchObject({ name: 's', namespace: 'test-ns' })++ expect(coreApi.patchNamespacedSecret).toHaveBeenCalledOnce()+ })++ it('allows key removal when the preserved existing annotations are infrastructure metadata', async () => {+ coreApi.readNamespacedSecret.mockResolvedValueOnce({+ metadata: { annotations: { 'kubectl.kubernetes.io/restartedAt': 'now' } },+ type: 'Opaque',+ })++ await expect(+ svc.removeSecretKey({ name: 's', namespace: 'test-ns', key: 'API_KEY' })+ ).resolves.toMatchObject({ name: 's', namespace: 'test-ns' })+ expect(coreApi.patchNamespacedSecret).toHaveBeenCalledOnce()+ })+})++describe('SecretService — forbidden Secret types never reach the apiserver', () => {+ let coreApi: CoreApiMock+ let svc: SecretService++ beforeEach(() => {+ coreApi = createCoreApiMock()+ svc = new SecretService(coreApi as unknown as k8s.CoreV1Api, 'test-ns')+ })++ const writeOps: ReadonlyArray<{+ name: string+ call: (type: string) => Promise<unknown>+ apiSurface: (keyof CoreApiMock)[]+ }> = [+ {+ name: 'createSecret',+ call: type =>+ svc.createSecret({ name: 's', namespace: 'test-ns', type, stringData: { k: 'v' } }),+ apiSurface: ['createNamespacedSecret'],+ },+ {+ name: 'updateSecret',+ call: type =>+ svc.updateSecret({ name: 's', namespace: 'test-ns', type, stringData: { k: 'v' } }),+ apiSurface: ['readNamespacedSecret', 'replaceNamespacedSecret'],+ },+ {+ name: 'mergeSecret',+ call: type =>+ svc.mergeSecret({ name: 's', namespace: 'test-ns', type, stringData: { k: 'v' } }),+ apiSurface: ['patchNamespacedSecret'],+ },+ ]++ for (const op of writeOps) {+ describe(op.name, () => {+ for (const badType of FORBIDDEN_SECRET_TYPES) {+ it(`rejects type "${badType}" with a 400 and never calls the apiserver`, async () => {+ const err = await op.call(badType).then(+ () => {+ throw new Error('expected the write to reject')+ },+ (e: unknown) => e+ )+ expect(err).toBeInstanceOf(InvalidSecretTypeError)+ expect((err as InvalidSecretTypeError).status).toBe(400)+ for (const surface of op.apiSurface) {+ expect(coreApi[surface]).not.toHaveBeenCalled()+ }+ })+ }++ for (const goodType of ALLOWED_SECRET_TYPES) {+ it(`lets allowed type "${goodType}" through to the apiserver`, async () => {+ await op.call(goodType)+ const writeSurface = op.apiSurface[op.apiSurface.length - 1]+ expect(coreApi[writeSurface]).toHaveBeenCalledOnce()+ })+ }+ })+ }++ it('allows omitted type (defaults to Opaque)', async () => {+ await svc.createSecret({ name: 's', namespace: 'test-ns', stringData: { k: 'v' } })+ expect(coreApi.createNamespacedSecret).toHaveBeenCalledOnce()+ })+})++describe('SecretService — dangerous annotations never reach the apiserver', () => {+ let coreApi: CoreApiMock+ let svc: SecretService++ beforeEach(() => {+ coreApi = createCoreApiMock()+ svc = new SecretService(coreApi as unknown as k8s.CoreV1Api, 'test-ns')+ })++ const writeOps: ReadonlyArray<{+ name: string+ call: (annotations: Record<string, string>) => Promise<unknown>+ apiSurface: (keyof CoreApiMock)[]+ }> = [+ {+ name: 'createSecret',+ call: annotations =>+ svc.createSecret({ name: 's', namespace: 'test-ns', annotations, stringData: { k: 'v' } }),+ apiSurface: ['createNamespacedSecret'],+ },+ {+ name: 'updateSecret',+ call: annotations =>+ svc.updateSecret({ name: 's', namespace: 'test-ns', annotations, stringData: { k: 'v' } }),+ apiSurface: ['readNamespacedSecret', 'replaceNamespacedSecret'],+ },+ ]++ for (const op of writeOps) {+ describe(op.name, () => {+ for (const badKey of DANGEROUS_ANNOTATION_KEYS) {+ it(`rejects annotation "${badKey}" with a 400 and never calls the apiserver`, async () => {+ const err = await op.call({ [badKey]: 'value' }).then(+ () => {+ throw new Error('expected the write to reject')+ },+ (e: unknown) => e+ )+ expect(err).toBeInstanceOf(DangerousAnnotationError)+ expect((err as DangerousAnnotationError).status).toBe(400)+ for (const surface of op.apiSurface) {+ expect(coreApi[surface]).not.toHaveBeenCalled()+ }+ })+ }++ for (const safeKey of SAFE_ANNOTATION_KEYS) {+ it(`lets safe annotation "${safeKey}" through to the apiserver`, async () => {+ await op.call({ [safeKey]: 'value' })+ const writeSurface = op.apiSurface[op.apiSurface.length - 1]+ expect(coreApi[writeSurface]).toHaveBeenCalledOnce()+ })+ }+ })+ }++ it('allows omitted annotations', async () => {+ await svc.createSecret({ name: 's', namespace: 'test-ns', stringData: { k: 'v' } })+ expect(coreApi.createNamespacedSecret).toHaveBeenCalledOnce()+ })+})++describe('SecretService — platform annotations (clerum.io/) blocked by default, allowed with opt-out', () => {+ let coreApi: CoreApiMock+ let svc: SecretService++ beforeEach(() => {+ coreApi = createCoreApiMock()+ svc = new SecretService(coreApi as unknown as k8s.CoreV1Api, 'test-ns')+ })++ for (const platformKey of PLATFORM_ANNOTATION_KEYS) {+ it(`rejects "${platformKey}" by default (no opts)`, async () => {+ const err = await svc+ .createSecret({+ name: 's',+ namespace: 'test-ns',+ annotations: { [platformKey]: 'v' },+ stringData: { k: 'v' },+ })+ .then(+ () => {+ throw new Error('expected rejection')+ },+ (e: unknown) => e+ )+ expect(err).toBeInstanceOf(DangerousAnnotationError)+ expect((err as DangerousAnnotationError).status).toBe(400)+ expect(coreApi.createNamespacedSecret).not.toHaveBeenCalled()+ })++ it(`allows "${platformKey}" with the registryCredential capability`, async () => {+ await svc.createSecret(+ {+ name: 's',+ namespace: 'test-ns',+ annotations: { [platformKey]: 'v' },+ stringData: { k: 'v' },+ },+ { capability: 'registryCredential' }+ )+ expect(coreApi.createNamespacedSecret).toHaveBeenCalledOnce()+ })+ }++ it('still blocks infra annotations even with the registryCredential capability', async () => {+ const err = await svc+ .createSecret(+ {+ name: 's',+ namespace: 'test-ns',+ annotations: { 'kubectl.kubernetes.io/last-applied-configuration': '{}' },+ stringData: { k: 'v' },+ },+ { capability: 'registryCredential' }+ )+ .then(+ () => {+ throw new Error('expected rejection')+ },+ (e: unknown) => e+ )+ expect(err).toBeInstanceOf(DangerousAnnotationError)+ expect((err as DangerousAnnotationError).status).toBe(400)+ expect(coreApi.createNamespacedSecret).not.toHaveBeenCalled()+ })++ it('rejects platform keys outside the registryCredential capability', async () => {+ for (const key of UNAUTHORIZED_PLATFORM_ANNOTATION_KEYS) {+ await expect(+ svc.createSecret(+ {+ name: 's',+ namespace: 'test-ns',+ annotations: { [key]: 'v' },+ stringData: { k: 'v' },+ },+ { capability: 'registryCredential' }+ )+ ).rejects.toBeInstanceOf(DangerousAnnotationError)+ }+ expect(coreApi.createNamespacedSecret).not.toHaveBeenCalled()+ })++ it('rejects a mixed payload containing both safe and platform keys (without opt-out)', async () => {+ const err = await svc+ .createSecret({+ name: 's',+ namespace: 'test-ns',+ annotations: { 'my-custom-annotation': 'ok', 'clerum.io/catalog-id': 'bad' },+ stringData: { k: 'v' },+ })+ .then(+ () => {+ throw new Error('expected rejection')+ },+ (e: unknown) => e+ )+ expect(err).toBeInstanceOf(DangerousAnnotationError)+ expect((err as DangerousAnnotationError).annotationKey).toBe('clerum.io/catalog-id')+ })++ it('allows a mixed payload of safe + registry-owned keys with the registryCredential capability', async () => {+ await svc.createSecret(+ {+ name: 's',+ namespace: 'test-ns',+ annotations: {+ 'my-custom-annotation': 'ok',+ 'clerum.io/catalog-id': 'c1',+ 'clerum.io/catalog-version': 'v2',+ },+ stringData: { k: 'v' },+ },+ { capability: 'registryCredential' }+ )+ expect(coreApi.createNamespacedSecret).toHaveBeenCalledOnce()+ })++ it('rejects combined vector: forbidden type + platform annotation in one request', async () => {+ const err = await svc+ .createSecret({+ name: 's',+ namespace: 'test-ns',+ type: 'kubernetes.io/service-account-token',+ annotations: { 'clerum.io/owner': 'attacker' },+ stringData: { k: 'v' },+ })+ .then(+ () => {+ throw new Error('expected rejection')+ },+ (e: unknown) => e+ )+ expect(err).toBeInstanceOf(InvalidSecretTypeError)+ expect(coreApi.createNamespacedSecret).not.toHaveBeenCalled()+ })++ it('opt-out propagates through updateSecret', async () => {+ await svc.updateSecret(+ {+ name: 's',+ namespace: 'test-ns',+ annotations: { 'clerum.io/catalog-id': 'c1' },+ stringData: { k: 'v' },+ },+ undefined,+ { capability: 'registryCredential' }+ )+ expect(coreApi.replaceNamespacedSecret).toHaveBeenCalledOnce()+ })++ it('does not let an internal capability introduce new infrastructure metadata', async () => {+ const legacyApplyKey = DANGEROUS_ANNOTATION_KEYS[0]+ coreApi.readNamespacedSecret.mockResolvedValueOnce({+ metadata: { annotations: {}, resourceVersion: '7' },+ type: 'Opaque',+ })++ await expect(+ svc.updateSecret(+ {+ name: 's',+ namespace: 'test-ns',+ annotations: { [legacyApplyKey]: 'new-value' },+ stringData: { [VALID_KEYS[0]]: 'v' },+ },+ undefined,+ { capability: 'registryCredential' }+ )+ ).rejects.toBeInstanceOf(DangerousAnnotationError)+ expect(coreApi.replaceNamespacedSecret).not.toHaveBeenCalled()+ })++ it('allows MCP rotation to preserve only the Registry catalog annotation pair', async () => {+ coreApi.readNamespacedSecret.mockResolvedValueOnce({+ metadata: {+ annotations: {+ 'clerum.io/catalog-id': 'linear',+ 'clerum.io/catalog-version': '1.0.0',+ },+ },+ type: 'Opaque',+ })++ await svc.mergeSecret(+ {+ name: 'linear-credentials',+ namespace: 'test-ns',+ stringData: { [VALID_KEYS[0]]: 'rotated' },+ },+ { allowExistingPlatformAnnotationKeys: REGISTRY_SECRET_PRESERVED_ANNOTATION_KEYS }+ )++ expect(coreApi.patchNamespacedSecret).toHaveBeenCalledOnce()+ })++ it('allows the internal Registry capability to update trust metadata', async () => {+ await svc.updateSecret(+ {+ name: 'registry-credentials',+ namespace: 'test-ns',+ annotations: { 'clerum.io/trust-level': 'low' },+ stringData: { [VALID_KEYS[0]]: 'rotated' },+ },+ undefined,+ { capability: 'registryCredential' }+ )+ expect(coreApi.replaceNamespacedSecret).toHaveBeenCalledOnce()+ })+- it('does not let public rotation preserve Registry trust metadata', async () => {++ it('preserves unrelated Registry metadata during a data-only public rotation', async () => {+ coreApi.readNamespacedSecret.mockResolvedValueOnce({+ metadata: {+ annotations: {+ 'clerum.io/catalog-id': 'linear',+ 'clerum.io/catalog-version': '1.0.0',+ 'clerum.io/trust-level': 'low',+ },+ },+ type: 'Opaque',+ })++ await expect(+ svc.mergeSecret(+ {+ name: 'linear-credentials',+ namespace: 'test-ns',+ stringData: { [VALID_KEYS[0]]: 'rotated' },+ },+ { allowExistingPlatformAnnotationKeys: REGISTRY_SECRET_PRESERVED_ANNOTATION_KEYS }+ )- ).rejects.toMatchObject({ annotationKey: 'clerum.io/trust-level' })- expect(coreApi.patchNamespacedSecret).not.toHaveBeenCalled()++ ).resolves.toMatchObject({ name: 'linear-credentials', namespace: 'test-ns' })++ expect(coreApi.patchNamespacedSecret).toHaveBeenCalledOnce()+ })+- it('rejects extra platform metadata and request-side annotation injection', async () => {++ it('preserves extra platform metadata and still rejects request-side annotation injection', async () => {+ coreApi.readNamespacedSecret.mockResolvedValueOnce({+ metadata: {+ annotations: {+ 'clerum.io/catalog-id': 'linear',+ 'clerum.io/catalog-version': '1.0.0',+ 'clerum.io/untrusted': 'must-reject',+ },+ },+ type: 'Opaque',+ })++ await expect(+ svc.mergeSecret(+ {+ name: 'linear-credentials',+ namespace: 'test-ns',+ stringData: { [VALID_KEYS[0]]: 'rotated' },+ },+ { allowExistingPlatformAnnotationKeys: REGISTRY_SECRET_PRESERVED_ANNOTATION_KEYS }+ )- ).rejects.toMatchObject({ annotationKey: 'clerum.io/untrusted' })- expect(coreApi.patchNamespacedSecret).not.toHaveBeenCalled()++ ).resolves.toMatchObject({ name: 'linear-credentials', namespace: 'test-ns' })++ expect(coreApi.patchNamespacedSecret).toHaveBeenCalledOnce()++ await expect(+ svc.createSecret(+ {+ name: 'forged',+ namespace: 'test-ns',+ annotations: { 'clerum.io/catalog-id': 'caller-controlled' },+ stringData: { [VALID_KEYS[0]]: 'value' },+ },+ { allowExistingPlatformAnnotationKeys: REGISTRY_SECRET_PRESERVED_ANNOTATION_KEYS }+ )+ ).rejects.toBeInstanceOf(DangerousAnnotationError)+ })+})++describe('invalidSecretTypeReason — the shared rule', () => {+ it('accepts every allowed type', () => {+ for (const type of ALLOWED_SECRET_TYPES) {+ expect(invalidSecretTypeReason(type)).toBeNull()+ }+ })++ it('rejects every forbidden type with an actionable message', () => {+ for (const type of FORBIDDEN_SECRET_TYPES) {+ const reason = invalidSecretTypeReason(type)+ expect(reason).not.toBeNull()+ expect(reason).toContain('is not allowed')+ }+ })+})+++describe('resolveSecretAnnotationsForReplace — transition policy', () => {++ const infra = {++ 'meta.helm.sh/release-name': 'release-a',++ 'kubectl.kubernetes.io/last-applied-configuration': 'legacy',++ }++ const catalog = {++ 'clerum.io/catalog-id': 'entry-a',++ 'clerum.io/catalog-version': '1.0.0',++ }++++ it('preserves protected metadata while replacing caller-owned keys', () => {++ expect(++ resolveSecretAnnotationsForReplace(++ { ...infra, ...catalog, 'safe.example/old': 'old' },++ { 'safe.example/new': 'new' },++ { allowExistingPlatformAnnotationKeys: REGISTRY_SECRET_PRESERVED_ANNOTATION_KEYS }++ )++ ).toEqual({ ...infra, ...catalog, 'safe.example/new': 'new' })++ })++++ it('distinguishes omitted annotations from an explicit empty map', () => {++ const existing = { ...infra, 'safe.example/old': 'old' }++ expect(resolveSecretAnnotationsForReplace(existing, undefined)).toEqual(existing)++ expect(resolveSecretAnnotationsForReplace(existing, {})).toEqual(infra)++ })++++ it('preserves an unrecognized existing platform annotation without claiming ownership', () => {++ expect(++ resolveSecretAnnotationsForReplace(++ { ...catalog, 'clerum.io/trust-level': 'low' },++ {},++ { allowExistingPlatformAnnotationKeys: REGISTRY_SECRET_PRESERVED_ANNOTATION_KEYS }++ )++ ).toEqual({ ...catalog, 'clerum.io/trust-level': 'low' })++ })++++ it('does not let an allowlist assign a new platform annotation', () => {++ expect(() =>++ resolveSecretAnnotationsForReplace(++ {},++ { 'clerum.io/catalog-id': 'forged' },++ { allowExistingPlatformAnnotationKeys: REGISTRY_SECRET_PRESERVED_ANNOTATION_KEYS }++ )++ ).toThrow(DangerousAnnotationError)++ })++++ it('allows a capability to remove only its own platform key by explicit replace', () => {++ expect(++ resolveSecretAnnotationsForReplace(++ { ...infra, 'clerum.io/trust-level': 'low' },++ {},++ { capability: 'registryCredential' }++ )++ ).toEqual(infra)++ })++})+++describe('dangerousAnnotationKeyReason — the shared rule', () => {+ it('accepts safe annotation keys', () => {+ for (const key of SAFE_ANNOTATION_KEYS) {+ expect(dangerousAnnotationKeyReason(key)).toBeNull()+ }+ })++ it('rejects dangerous annotation keys with an actionable message', () => {+ for (const key of DANGEROUS_ANNOTATION_KEYS) {+ const reason = dangerousAnnotationKeyReason(key)+ expect(reason).not.toBeNull()+ expect(reason).toContain('is not allowed')+ }+ })++ it('rejects platform annotation keys by default (no opts)', () => {+ for (const key of PLATFORM_ANNOTATION_KEYS) {+ const reason = dangerousAnnotationKeyReason(key)+ expect(reason).not.toBeNull()+ expect(reason).toContain('is not allowed')+ }+ })++ it('accepts registry-owned annotation keys with the registryCredential capability', () => {+ for (const key of PLATFORM_ANNOTATION_KEYS) {+ expect(dangerousAnnotationKeyReason(key, { capability: 'registryCredential' })).toBeNull()+ }+ })++ it('still rejects infra keys even with the registryCredential capability', () => {+ for (const key of DANGEROUS_ANNOTATION_KEYS) {+ const reason = dangerousAnnotationKeyReason(key, { capability: 'registryCredential' })+ expect(reason).not.toBeNull()+ expect(reason).toContain('is not allowed')+ }+ })+})++describe('extractHttpStatus — .status property', () => {+ it('reads a top-level .status number', () => {+ expect(extractHttpStatus({ status: 409 })).toBe(409)+ })++ it('prefers .statusCode over .status', () => {+ expect(extractHttpStatus({ statusCode: 404, status: 500 })).toBe(404)+ })++ it('returns null for non-numeric .status', () => {+ expect(extractHttpStatus({ status: 'Failure' })).toBeNull()+ })+})+describe('invalidSecretDataKeyReason — the shared rule', () => {it('accepts every legitimate key', () => {for (const key of VALID_KEYS) {diff --cc control-ui/components/CreateMcpServerForm/index.tsxindex 2694cbe58,2694cbe58..c198ba96d--- a/control-ui/components/CreateMcpServerForm/index.tsx+++ b/control-ui/components/CreateMcpServerForm/index.tsx@@@ -184,6 -184,6 +184,15 @@@ function formatCreateError(err: unknownreturn message}++const DETERMINISTIC_CREATE_FAILURE_STATUSES = new Set([++ 400, 401, 403, 404, 405, 406, 411, 413, 415, 422,++])++++function isDeterministicCreateFailure(err: unknown): boolean {++ const status = err && typeof err === 'object' ? (err as { status?: unknown }).status : undefined++ return typeof status === 'number' && DETERMINISTIC_CREATE_FAILURE_STATUSES.has(status)++}++export function CreateMcpServerForm({mode = 'inline',onCancel,@@@ -533,9 -533,9 +542,17 @@@useEnvSecret && envSecretName.trim().length > 0 && Object.keys(secretData).length > 0let secretCreated = false++ let createdSecretIdentity: { uid: string; resourceVersion: string } | null = nulltry {if (willCreateSecret) {-- await createMcpSecret(envSecretName.trim(), secretData)++ const created = await createMcpSecret(envSecretName.trim(), secretData)++ if (!created.uid || !created.resourceVersion) {++ throw new Error('Created Secret identity is unavailable; refusing an unsafe rollback.')++ }++ createdSecretIdentity = {++ uid: created.uid,++ resourceVersion: created.resourceVersion,++ }secretCreated = true}@@@ -575,17 -575,17 +592,25 @@@onCreated()}, 600)} catch (submitError) {-- // Rollback: if we created the Secret but the CRD (or anything after)-- // failed, the Secret is orphan — best-effort delete.-- if (secretCreated) {++ // Only an allowlisted pre-admission rejection proves that the CRD cannot++ // own the Secret. A conflict, timeout, throttling, network, or 5xx++ // response is ambiguous: preserve the Secret for repair instead of++ // deleting a live dependency.++ const deterministicFailure = isDeterministicCreateFailure(submitError)++ if (secretCreated && createdSecretIdentity && deterministicFailure) {try {-- await deleteMcpSecret(envSecretName.trim())++ await deleteMcpSecret(envSecretName.trim(), createdSecretIdentity)} catch {// best-effort rollback; swallow — the operator already sees the// primary error below.}}-- setError(formatCreateError(submitError))++ const errorMessage = formatCreateError(submitError)++ setError(++ secretCreated && !deterministicFailure++ ? `${errorMessage} The Secret was retained because connector creation was ambiguous; repair the connector state before retrying.`++ : errorMessage++ )} finally {setSubmitting(false)}diff --cc control-ui/components/__tests__/CreateMcpServerForm.test.tsxindex 1739dbf00,1739dbf00..5b581c278--- a/control-ui/components/__tests__/CreateMcpServerForm.test.tsx+++ b/control-ui/components/__tests__/CreateMcpServerForm.test.tsx@@@ -14,7 -14,7 +14,11 @@@ vi.mock('../../lib/api', async () =>})return {createMcpServer: vi.fn().mockResolvedValue({ metadata: { name: 'test-server' } }),-- createMcpSecret: vi.fn().mockResolvedValue({ name: 'test-credentials' }),++ createMcpSecret: vi.fn().mockResolvedValue({++ name: 'test-credentials',++ uid: 'uid-test-credentials',++ resourceVersion: '1',++ }),deleteMcpSecret: vi.fn().mockResolvedValue({ name: 'test-credentials' }),getContexts: vi.fn().mockResolvedValue(buildContextList([@@@ -490,7 -490,7 +494,9 @@@ describe('CreateMcpServerForm — envSeit('rolls back the created Secret when createMcpServer rejects', async () => {;(api.createMcpServer as ReturnType<typeof vi.fn>).mockRejectedValueOnce(-- new Error('422 Unprocessable - {"message":"Connector create failed"}')++ Object.assign(new Error('422 Unprocessable - {"message":"Connector create failed"}'), {++ status: 422,++ }))render(<CreateMcpServerForm onCancel={vi.fn()} onCreated={vi.fn()} />)@@@ -523,7 -523,7 +529,10 @@@await waitFor(() => {expect(api.deleteMcpSecret).toHaveBeenCalledTimes(1)})-- expect(api.deleteMcpSecret).toHaveBeenCalledWith('brave-credentials')++ expect(api.deleteMcpSecret).toHaveBeenCalledWith('brave-credentials', {++ uid: 'uid-test-credentials',++ resourceVersion: '1',++ })// JSON API errors surface their server message after rollback.await waitFor(() => {@@@ -531,6 -531,6 +540,67 @@@})})++ it('keeps the Secret when createMcpServer fails ambiguously', async () => {++ ;(api.createMcpServer as ReturnType<typeof vi.fn>).mockRejectedValueOnce(++ Object.assign(new Error('503 Service Unavailable - {"error":"repair_required"}'), {++ status: 503,++ })++ )++++ render(<CreateMcpServerForm onCancel={vi.fn()} onCreated={vi.fn()} />)++ await fillRequiredBasics()++ enableEnvSecret('ambiguous-credentials')++ fireEvent.click(screen.getByRole('button', { name: 'Add Key Mapping' }))++ fireEvent.change(screen.getByPlaceholderText('api-key'), {++ target: { value: 'api-key' },++ })++ fireEvent.change(screen.getByPlaceholderText('BRAVE_API_KEY'), {++ target: { value: 'BRAVE_API_KEY' },++ })++ fireEvent.change(screen.getByPlaceholderText('sk-...'), {++ target: { value: 'sk-ambiguous' },++ })++++ const submit = screen.getByRole('button', { name: 'Create connector' })++ await waitFor(() => expect(submit).not.toBeDisabled())++ fireEvent.click(submit)++++ await waitFor(() => expect(api.createMcpServer).toHaveBeenCalledTimes(1))++ await waitFor(() => expect(screen.getByText(/Secret was retained/i)).toBeInTheDocument())++ expect(api.deleteMcpSecret).not.toHaveBeenCalled()++ })++++ it.each([408, 409, 429])(++ 'keeps the Secret when connector creation returns ambiguous HTTP %s',++ async status => {++ ;(api.createMcpServer as ReturnType<typeof vi.fn>).mockRejectedValueOnce(++ Object.assign(new Error(`${status} connector create outcome is ambiguous`), { status })++ )++++ render(<CreateMcpServerForm onCancel={vi.fn()} onCreated={vi.fn()} />)++ await fillRequiredBasics()++ enableEnvSecret('ambiguous-credentials')++ fireEvent.click(screen.getByRole('button', { name: 'Add Key Mapping' }))++ fireEvent.change(screen.getByPlaceholderText('api-key'), {++ target: { value: 'api-key' },++ })++ fireEvent.change(screen.getByPlaceholderText('BRAVE_API_KEY'), {++ target: { value: 'BRAVE_API_KEY' },++ })++ fireEvent.change(screen.getByPlaceholderText('sk-...'), {++ target: { value: 'sk-ambiguous' },++ })++++ const submit = screen.getByRole('button', { name: 'Create connector' })++ await waitFor(() => expect(submit).not.toBeDisabled())++ fireEvent.click(submit)++++ await waitFor(() => expect(api.createMcpServer).toHaveBeenCalledTimes(1))++ await waitFor(() => expect(screen.getByText(/Secret was retained/i)).toBeInTheDocument())++ expect(api.deleteMcpSecret).not.toHaveBeenCalled()++ }++ )++it('happy path: creates Secret then CRD, no rollback', async () => {const onCreated = vi.fn()render(<CreateMcpServerForm onCancel={vi.fn()} onCreated={onCreated} />)diff --cc control-ui/components/__tests__/UpdateConnectorCredentials.test.tsxindex 1608a8e4c,1608a8e4c..1aa79dd39--- a/control-ui/components/__tests__/UpdateConnectorCredentials.test.tsx+++ b/control-ui/components/__tests__/UpdateConnectorCredentials.test.tsx@@@ -37,6 -37,6 +37,8 @@@ function secretRotationResponse(keys: sreturn {...buildSecretSummary({ name: ENV_SECRET.name, keys }),namespace: 'mcp-server',++ uid: 'uid-linear-credentials',++ resourceVersion: '2',affectedConnectors,}}diff --cc control-ui/e2e/qa-recorder-connector-edit.spec.tsindex 440e40eba,440e40eba..11dcf4895--- a/control-ui/e2e/qa-recorder-connector-edit.spec.ts+++ b/control-ui/e2e/qa-recorder-connector-edit.spec.ts@@@ -26,7 -26,7 +26,8 @@@ const MOCK_MCP_IMAGE = process.env.TEST// The connector-form selects are not label-associated (no htmlFor/id), so scope// to the wrapping `.cu-field` by its visible label text and drive its <select>.async function fieldSelect(page: Page, fieldLabelText: string, value: string): Promise<void> {-- const field = page.locator('.cu-field', { hasText: fieldLabelText }).first()++ const field = page.locator('.cu-field', { hasText: fieldLabelText })++ await expect(field).toHaveCount(1)await field.locator('select').selectOption(value)}@@@ -102,6 -102,6 +103,16 @@@ async function createDiscoveryConnectorawait expect(page).toHaveURL(/\/connectors$/, { timeout: 20_000 })}++async function openConnectorEdit(page: Page, connectorName: string): Promise<void> {++ const expandBtn = page.getByRole('button', { name: `Expand connector ${connectorName}` })++ await expect(expandBtn).toBeVisible({ timeout: 30_000 })++ await expandBtn.click()++ await page.getByRole('button', { name: `Edit connector ${connectorName}` }).click()++ await expect(++ page.getByRole('heading', { name: `Edit Connector: ${connectorName}`, exact: true })++ ).toBeVisible({ timeout: 20_000 })++}++test.describe('optional QA recorder: Control UI connector edit', () => {test('records editing a discovery connector to add external CIDR egress', async ({page,@@@ -123,10 -123,10 +134,7 @@@await createEmptyContext(page, contextName)await createDiscoveryConnector(page, connectorName, contextName)-- await page.goto(`${CONTROL_UI_URL}/connectors/${encodeURIComponent(connectorName)}/edit`)-- await expect(-- page.getByRole('heading', { name: `Edit Connector: ${connectorName}`, exact: true })-- ).toBeVisible({ timeout: 20_000 })++ await openConnectorEdit(page, connectorName)// Context is a read-only final tab. It mirrors the selected context's// Users, Teams, and Agents access preview without offering a mutation.@@@ -151,16 -151,16 +159,12 @@@// External Egress: switch to exact-CIDR mode and add one public CIDR + port.// 8.8.8.8/32 is a valid public target; the model rejects private/doc ranges.await fieldSelect(page, 'Egress mode', 'exact-cidr')-- await page-- .locator('.cu-field', { hasText: 'Allowed CIDRs/IPs' })-- .first()-- .locator('textarea')-- .fill('8.8.8.8/32')-- await page-- .locator('.cu-field', { hasText: 'Allowed ports' })-- .first()-- .locator('input')-- .fill('443')++ const cidrField = page.locator('.cu-field', { hasText: 'Allowed CIDRs/IPs' })++ await expect(cidrField).toHaveCount(1)++ await cidrField.locator('textarea').fill('8.8.8.8/32')++ const portsField = page.locator('.cu-field', { hasText: 'Allowed ports' })++ await expect(portsField).toHaveCount(1)++ await portsField.locator('input').fill('443')await page.getByRole('button', { name: 'Save egress', exact: true }).click()await expect(@@@ -184,7 -184,7 +188,7 @@@// the rotation itself — filling the new value, confirming the restart// warning, saving, watching the status settle — is driven exclusively by// real user actions against the live control-api/HCC, never a direct PUT,-- // never a mocked backend, never `waitForTimeout`.++ // never a mocked backend, never a fixed delay.test('records rotating a connector credential and reaching a terminal rollout state', async ({page,}, testInfo) => {@@@ -201,6 -201,6 +205,7 @@@const secretName = uniqueE2EName('qa-recorder-secret')const secretKey = 'api-key'const envVar = 'QA_RECORDER_API_KEY'++ let createdSecretIdentity: { uid: string; resourceVersion: string } | undefinedtry {await loginThroughUi(page, credentials)@@@ -212,12 -212,12 +217,23 @@@// image is used so the rotation reaches a real DeploymentReady terminal// state (an unmanaged connector has no Deployment to poll). This mirrors the// T2 integration `localMcpServerYaml` fixture.-- const secretRes = await api(page.request, 'POST', '/api/v1/admin/mcp-secrets', {-- name: secretName,-- data: { [secretKey]: 'initial-value-123' },-- })++ const secretRes = await api<{ uid?: unknown; resourceVersion?: unknown }>(++ page.request,++ 'POST',++ '/api/v1/admin/mcp-secrets',++ {++ name: secretName,++ data: { [secretKey]: 'initial-value-123' },++ }++ )expect(secretRes.status, `create Secret: ${JSON.stringify(secretRes.data)}`).toBeLessThan(300)++ expect(typeof secretRes.data.uid, 'created object uid').toBe('string')++ expect(typeof secretRes.data.resourceVersion, 'created object resourceVersion').toBe('string')++ createdSecretIdentity = {++ uid: secretRes.data.uid as string,++ resourceVersion: secretRes.data.resourceVersion as string,++ }const ctxRes = await api(page.request, 'POST', '/api/v1/admin/contexts', {metadata: { name: contextName },spec: {@@@ -246,10 -246,10 +262,9 @@@})expect(srvRes.status, `create connector: ${JSON.stringify(srvRes.data)}`).toBeLessThan(300)-- await page.goto(`${CONTROL_UI_URL}/connectors/${encodeURIComponent(connectorName)}/edit`)-- await expect(-- page.getByRole('heading', { name: `Edit Connector: ${connectorName}`, exact: true })-- ).toBeVisible({ timeout: 20_000 })++ await page.getByRole('link', { name: 'Installed connectors', exact: true }).click()++ await expect(page).toHaveURL(/\/connectors$/, { timeout: 20_000 })++ await openConnectorEdit(page, connectorName)// The connector edit screen is split into tabs; the rotation flow lives// on the Credentials tab — navigate there via the tab link.@@@ -281,7 -281,7 +296,25 @@@// Explicit confirmation gate before anything is sent to the server.const confirmDialog = page.getByRole('alertdialog', { name: 'Rotate credentials' })await expect(confirmDialog).toBeVisible({ timeout: 20_000 })++ const rotateResponsePromise = page.waitForResponse(response => {++ return (++ response.request().method() === 'PUT' &&++ response.url().includes(`/admin/mcp-secrets/${encodeURIComponent(secretName)}`)++ )++ })await confirmDialog.getByRole('button', { name: 'Rotate & restart', exact: true }).click()++ const rotateResponse = await rotateResponsePromise++ expect(rotateResponse.status()).toBeLessThan(300)++ const rotated = (await rotateResponse.json()) as {++ uid?: unknown++ resourceVersion?: unknown++ }++ expect(typeof rotated.uid, 'rotated object uid').toBe('string')++ expect(typeof rotated.resourceVersion, 'rotated object resourceVersion').toBe('string')++ createdSecretIdentity = {++ uid: rotated.uid as string,++ resourceVersion: rotated.resourceVersion as string,++ }// The PUT landing shows "rotating", never a verdict by itself — the// verdict only comes from the CRD poll below.@@@ -310,11 -310,11 +343,14 @@@'DELETE',`/api/v1/admin/mcp-servers/${encodeURIComponent(connectorName)}`)-- await api(-- page.request,-- 'DELETE',-- `/api/v1/admin/mcp-secrets/${encodeURIComponent(secretName)}`-- )++ if (createdSecretIdentity) {++ await api(++ page.request,++ 'DELETE',++ `/api/v1/admin/mcp-secrets/${encodeURIComponent(secretName)}`,++ createdSecretIdentity++ )++ }await api(page.request, 'DELETE', `/api/v1/admin/contexts/${encodeURIComponent(contextName)}`)}})diff --cc control-ui/e2e/qa-recorder-connector-rotation-demo.spec.tsindex f13ccba89,f13ccba89..c15a104ab--- a/control-ui/e2e/qa-recorder-connector-rotation-demo.spec.ts+++ b/control-ui/e2e/qa-recorder-connector-rotation-demo.spec.ts@@@ -39,6 -39,6 +39,7 @@@ test.describe('demo: Control UI credentconst secretName = uniqueE2EName('demo-secret')const secretKey = 'api-key'const envVar = 'DEMO_API_KEY'++ let createdSecretIdentity: { uid: string; resourceVersion: string } | undefinedtry {await test.step('sign in through the Control UI', async () => {@@@ -47,11 -47,11 +48,22 @@@})await test.step('stage a managed connector + Secret (API preconditions)', async () => {-- const s = await api(page.request, 'POST', '/api/v1/admin/mcp-secrets', {-- name: secretName,-- data: { [secretKey]: 'initial-value-123' },-- })++ const s = await api<{ uid?: unknown; resourceVersion?: unknown }>(++ page.request,++ 'POST',++ '/api/v1/admin/mcp-secrets',++ {++ name: secretName,++ data: { [secretKey]: 'initial-value-123' },++ }++ )expect(s.status, `Secret: ${JSON.stringify(s.data)}`).toBeLessThan(300)++ expect(typeof s.data.uid, 'created object uid').toBe('string')++ expect(typeof s.data.resourceVersion, 'created object resourceVersion').toBe('string')++ createdSecretIdentity = {++ uid: s.data.uid as string,++ resourceVersion: s.data.resourceVersion as string,++ }const c = await api(page.request, 'POST', '/api/v1/admin/contexts', {metadata: { name: contextName },spec: { contextId: contextName, description: 'demo rotation context', mcpServers: [] },@@@ -124,10 -124,10 +136,28 @@@const dialog = page.getByRole('alertdialog', { name: 'Rotate credentials' })await expect(dialog).toBeVisible({ timeout: 20_000 })await humanPause(page)++ const rotateResponsePromise = page.waitForResponse(response => {++ return (++ response.request().method() === 'PUT' &&++ response.url().includes(`/admin/mcp-secrets/${encodeURIComponent(secretName)}`)++ )++ })await humanClick(page,dialog.getByRole('button', { name: 'Rotate & restart', exact: true }))++ const rotateResponse = await rotateResponsePromise++ expect(rotateResponse.status()).toBeLessThan(300)++ const rotated = (await rotateResponse.json()) as {++ uid?: unknown++ resourceVersion?: unknown++ }++ expect(typeof rotated.uid, 'rotated object uid').toBe('string')++ expect(typeof rotated.resourceVersion, 'rotated object resourceVersion').toBe('string')++ createdSecretIdentity = {++ uid: rotated.uid as string,++ resourceVersion: rotated.resourceVersion as string,++ }})await test.step('watch the rollout reach "Credentials rotated"', async () => {@@@ -144,11 -144,11 +174,14 @@@'DELETE',`/api/v1/admin/mcp-servers/${encodeURIComponent(connectorName)}`)-- await api(-- page.request,-- 'DELETE',-- `/api/v1/admin/mcp-secrets/${encodeURIComponent(secretName)}`-- )++ if (createdSecretIdentity) {++ await api(++ page.request,++ 'DELETE',++ `/api/v1/admin/mcp-secrets/${encodeURIComponent(secretName)}`,++ createdSecretIdentity++ )++ }await api(page.request, 'DELETE', `/api/v1/admin/contexts/${encodeURIComponent(contextName)}`)}})diff --cc control-ui/e2e/qa-recorder-secret-connector.spec.tsindex d892dd1ff,d892dd1ff..5df6c65f2--- a/control-ui/e2e/qa-recorder-secret-connector.spec.ts+++ b/control-ui/e2e/qa-recorder-secret-connector.spec.ts@@@ -34,11 -34,11 +34,17 @@@ test.describe('optional QA recorder: Coconst credentials = adminCredentials()const secretName = uniqueE2EName('qa-recorder-connector-secret')++ let createdSecretIdentity: { uid: string; resourceVersion: string } | undefinedtry {await loginThroughUi(page, credentials)-- await page.goto(`${CONTROL_UI_URL}/secrets/new?scope=mcp`)++ await page.getByRole('link', { name: 'Secrets', exact: true }).click()++ await expect(page).toHaveURL(/\/secrets$/, { timeout: 20_000 })++ await page.getByRole('tab', { name: 'Connector', exact: true }).click()++ await expect(page).toHaveURL(/\/secrets\/connector$/, { timeout: 20_000 })++ await page.getByRole('button', { name: 'Add connector secret', exact: true }).click()++ await expect(page).toHaveURL(/\/secrets\/new\?scope=mcp/, { timeout: 20_000 })await expect(page.getByRole('heading', { name: 'Create connector secret', exact: true })).toBeVisible({ timeout: 20_000 })@@@ -53,9 -53,9 +59,25 @@@await expect(page.getByPlaceholder('API_KEY')).toBeVisible({ timeout: 20_000 })await page.getByRole('button', { name: 'Add key', exact: true }).click()-- await page.getByPlaceholder('API_KEY').last().fill('API_KEY')-- await page.getByPlaceholder('secret value').last().fill('qa-recorder-dummy')++ const addedRow = page.locator('.cu-form-inline').filter({++ has: page.getByRole('button', { name: 'Remove MCP secret key row 2', exact: true }),++ })++ await addedRow.getByPlaceholder('API_KEY').fill('API_KEY')++ await addedRow.getByPlaceholder('secret value').fill('qa-recorder-dummy')++ const createResponsePromise = page.waitForResponse(response => {++ return response.request().method() === 'POST' && response.url().includes('/admin/mcp-')++ })await page.getByRole('button', { name: 'Create secret', exact: true }).click()++ const createData = (await (await createResponsePromise).json()) as {++ uid?: unknown++ resourceVersion?: unknown++ }++ if (typeof createData.uid === 'string' && typeof createData.resourceVersion === 'string') {++ createdSecretIdentity = {++ uid: createData.uid,++ resourceVersion: createData.resourceVersion,++ }++ }await expect(page.getByText(`Secret ${secretName} created.`, { exact: true })).toBeVisible({timeout: 20_000,@@@ -64,7 -64,7 +86,8 @@@// The connector list is McpServer-derived; a standalone secret is not listed// and connector scope has no delete action in the UI. Record the connector// shell and clean up through the Control API below.-- await page.goto(`${CONTROL_UI_URL}/secrets/connector`)++ await page.getByRole('link', { name: 'Secrets', exact: true }).click()++ await expect(page).toHaveURL(/\/secrets\/connector$/, { timeout: 20_000 })await expect(page.getByText('Manage LLM, connector, and recipe credentials in one place.', {exact: true,@@@ -74,11 -74,11 +97,14 @@@await screenshotAndLog(page, testInfo, 'control-ui-secret-connector')} finally {try {-- await api(-- page.request,-- 'DELETE',-- `/api/v1/admin/mcp-secrets/${encodeURIComponent(secretName)}`-- )++ if (createdSecretIdentity) {++ await api(++ page.request,++ 'DELETE',++ `/api/v1/admin/mcp-secrets/${encodeURIComponent(secretName)}`,++ createdSecretIdentity++ )++ }} catch {// Best-effort: ignore cleanup failures.}diff --cc control-ui/lib/api.tsindex 84ba05af0,84ba05af0..8f77e1cdb--- a/control-ui/lib/api.ts+++ b/control-ui/lib/api.ts@@@ -1451,6 -1451,6 +1451,8 @@@ export async function createMcpSecret(nreturn apiSend('POST', '/api/v1/admin/mcp-secrets', { name, data }) as Promise<{name: stringnamespace: string++ uid: string++ resourceVersion: string}>}@@@ -1460,8 -1460,8 +1462,15 @@@* back a just-created Secret when the subsequent McpServer CRD creation fails,* so we never leave orphan Secrets behind.*/--export async function deleteMcpSecret(name: string) {-- return apiSend('DELETE', `/api/v1/admin/mcp-secrets/${encodeURIComponent(name)}`) as Promise<{++export async function deleteMcpSecret(++ name: string,++ precondition: { uid: string; resourceVersion: string }++) {++ return apiSend(++ 'DELETE',++ `/api/v1/admin/mcp-secrets/${encodeURIComponent(name)}`,++ precondition++ ) as Promise<{name: stringnamespace: string}>@@@ -1485,6 -1485,6 +1494,8 @@@ export async function updateMcpSecret(n}) as Promise<{name: stringnamespace: string++ uid: string++ resourceVersion: stringkeys: string[]affectedConnectors: string[]}>diff --cc control-ui/package-lock.jsonindex 4ac83d4a1,4ac83d4a1..accdf57c0--- a/control-ui/package-lock.json+++ b/control-ui/package-lock.json@@@ -1,12 -1,12 +1,12 @@@{"name": "clerum-control-ui",-- "version": "0.1.450",++ "version": "0.1.451","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "clerum-control-ui",-- "version": "0.1.450",++ "version": "0.1.451","dependencies": {"@clerum/display-field": "file:../packages/display-field","@clerum/llm-providers": "file:../packages/llm-providers",diff --cc control-ui/package.jsonindex 5fef329e3,5fef329e3..1efd79c00--- a/control-ui/package.json+++ b/control-ui/package.json@@@ -1,6 -1,6 +1,6 @@@{"name": "clerum-control-ui",-- "version": "0.1.450",++ "version": "0.1.451","private": true,"scripts": {"dev": "NEXT_IGNORE_INCORRECT_LOCKFILE=1 next dev",