Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure
TypeScript
fix(hcc): preserve authoritative fleet convergence
Alfredo Lopezff5fe09fbdc6
diff --git a/host-context-controller/package-lock.json b/host-context-controller/package-lock.jsonindex c672234da..7ed85b211 100644--- a/host-context-controller/package-lock.json+++ b/host-context-controller/package-lock.json@@ -1,12 +1,12 @@{"name": "clerum-host-context-controller",- "version": "0.1.163",+ "version": "0.1.164","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "clerum-host-context-controller",- "version": "0.1.163",+ "version": "0.1.164","license": "SEE LICENSE IN LICENSE","dependencies": {"@clerum/image-policy": "file:../packages/image-policy",diff --git a/host-context-controller/package.json b/host-context-controller/package.jsonindex 85b46b7c4..9bf751897 100644--- a/host-context-controller/package.json+++ b/host-context-controller/package.json@@ -1,6 +1,6 @@{"name": "clerum-host-context-controller",- "version": "0.1.163",+ "version": "0.1.164","description": "Host Context Controller - provides McpServer CRDs to mcp-host via REST API","main": "dist/main.js","engines": {diff --git a/host-context-controller/src/__tests__/reconciler.remote.test.ts b/host-context-controller/src/__tests__/reconciler.remote.test.tsindex 09c0b5b84..f7beaaf38 100644--- a/host-context-controller/src/__tests__/reconciler.remote.test.ts+++ b/host-context-controller/src/__tests__/reconciler.remote.test.ts@@ -171,7 +171,14 @@ function lastPatchedStatusConditions(customApi: MockCustomApi): any[] {const calls = customApi.patchNamespacedCustomObjectStatus.mock.callsconst lastCall = calls[calls.length - 1]?.[0]const patch = lastCall?.body- const value = Array.isArray(patch) ? patch[0]?.value : undefined+ const statusAdd = Array.isArray(patch)+ ? patch.find(+ candidate =>+ candidate?.op === 'add' &&+ (candidate.path === '/status' || candidate.path === '/status/conditions')+ )+ : undefined+ const value = statusAdd?.valuereturn Array.isArray(value) ? value : (value?.conditions ?? [])}@@ -1115,6 +1122,12 @@ describe('McpServerReconciler remote egress proxy', () => {})describe('reconcileDelete for remote servers', () => {+ beforeEach(() => {+ reconciler.setInventoryAuthority(() => ({ known: true, generation: 1 }))+ reconciler.setResolveCurrentServer(() => undefined)+ customApi.getNamespacedCustomObject.mockRejectedValue(make404Error())+ })+it('should clean up ConfigMap via deleteResources', async () => {mockHccOwnedRuntimeReads(appsApi, coreApi)diff --git a/host-context-controller/src/gfsReconciler.test.ts b/host-context-controller/src/gfsReconciler.test.tsindex c9cde6bcb..d2fd7965b 100644--- a/host-context-controller/src/gfsReconciler.test.ts+++ b/host-context-controller/src/gfsReconciler.test.ts@@ -2,7 +2,7 @@ import { describe, expect, it } from 'vitest'import type * as k8s from '@kubernetes/client-node'import { GfsK8sApi, GfsReconciler, GfsSeedClient } from './gfsReconciler'import { GfsFactoryConfig } from './k8s/gfsFactory'-import type { GlobalFileSystemCRD } from './types'+import type { GlobalFileSystemCRD, GlobalFileSystemStatus } from './types'const config: GfsFactoryConfig = {gfsNamespace: 'gfs',@@ -42,11 +42,12 @@ class FakeApi implements GfsK8sApi {netpols: string[] = []pvcs: string[] = []deleted: string[] = []- statuses: { phase?: string; serviceUrl?: string }[] = []+ statuses: GlobalFileSystemStatus[] = []writerNeedsUpdate = truewriterAvailable = truewriterAvailabilitySequence: boolean[] = []failPvc = false+ statusFailuresRemaining = 0async applyPvc(pvc: k8s.V1PersistentVolumeClaim): Promise<void> {if (this.failPvc) throw new Error('simulated PVC apply failure')@@ -101,11 +102,11 @@ class FakeApi implements GfsK8sApi {async deletePvc(name: string): Promise<void> {this.deleted.push(`pvc/${name}`)}- async patchStatus(- _name: string,- _ns: string,- status: { phase?: string; serviceUrl?: string }- ): Promise<void> {+ async patchStatus(_name: string, _ns: string, status: GlobalFileSystemStatus): Promise<void> {+ if (this.statusFailuresRemaining > 0) {+ this.statusFailuresRemaining--+ throw new Error('simulated status patch failure')+ }this.statuses.push(status)}}@@ -218,6 +219,59 @@ describe('GfsReconciler.reconcile', () => {expect(seed.calls).toBe(1)})+ it('does not rewrite unchanged status but still publishes a later phase transition', async () => {+ const api = new FakeApi()+ api.writerNeedsUpdate = false+ const reconciler = new GfsReconciler(api, config, undefined, 0, 0)++ await reconciler.reconcile(gfs)+ const observedReady = { ...gfs, status: api.statuses[0] }+ await reconciler.reconcile(observedReady)++ expect(api.statuses).toHaveLength(1)+ expect(api.statuses[0]?.phase).toBe('Ready')++ api.writerAvailable = false+ await reconciler.reconcile(observedReady)++ expect(api.statuses.map(status => status.phase)).toEqual(['Ready', 'Initializing'])+ })++ it('publishes status for a same-name recreation even when the DELETE watch was missed', async () => {+ const api = new FakeApi()+ const reconciler = new GfsReconciler(api, config)++ await reconciler.reconcile(gfs)+ await reconciler.reconcile({ ...gfs, status: api.statuses[0] })+ await reconciler.reconcile({ ...gfs, status: undefined })++ expect(api.statuses).toHaveLength(2)+ })++ it('repairs status that was removed externally after HCC observed its prior write', async () => {+ const api = new FakeApi()+ const reconciler = new GfsReconciler(api, config)++ await reconciler.reconcile(gfs)+ await reconciler.reconcile({ ...gfs, status: api.statuses[0] })+ await reconciler.reconcile({ ...gfs, status: undefined })++ expect(api.statuses).toHaveLength(2)+ expect(api.statuses.at(-1)?.phase).toBe('Ready')+ })++ it('retries an unchanged status when the previous patch failed', async () => {+ const api = new FakeApi()+ api.statusFailuresRemaining = 1+ const reconciler = new GfsReconciler(api, config)++ await expect(reconciler.reconcile(gfs)).rejects.toThrow('simulated status patch failure')+ await expect(reconciler.reconcile(gfs)).resolves.toBeUndefined()++ expect(api.statuses).toHaveLength(1)+ expect(api.statuses[0]?.phase).toBe('Ready')+ })+it('reports Initializing and does NOT seed when the writer is not yet available', async () => {const api = new FakeApi()api.writerAvailable = false@@ -265,4 +319,15 @@ describe('GfsReconciler.reconcileDelete', () => {expect(api.deleted).toContain('pvc/gfs-drive')expect(api.deleted.at(-1)).toBe('pvc/gfs-drive') // bytes removed LAST})++ it('publishes status again after delete clears the prior write suppression', async () => {+ const api = new FakeApi()+ const reconciler = new GfsReconciler(api, config)++ await reconciler.reconcile(gfs)+ await reconciler.reconcileDelete(gfs)+ await reconciler.reconcile(gfs)++ expect(api.statuses).toHaveLength(2)+ })})diff --git a/host-context-controller/src/gfsReconciler.ts b/host-context-controller/src/gfsReconciler.tsindex de5e29ea2..0462a12e6 100644--- a/host-context-controller/src/gfsReconciler.ts+++ b/host-context-controller/src/gfsReconciler.ts@@ -95,6 +95,27 @@ export class GfsReconciler {} while (true)}+ private async writeStatus(+ gfs: GlobalFileSystemCRD,+ status: GlobalFileSystemStatus+ ): Promise<void> {+ // Compare against status observed on this exact LIST/watch object, not+ // process memory keyed only by name. A local name cache could suppress the+ // repair of a recreated object when its DELETE event was missed, or of+ // status that another actor removed. Conversely, an identical observed+ // status proves this is our own status-only MODIFIED event and closes the+ // patch -> watch -> reconcile loop without another API write.+ if (+ gfs.status?.phase === status.phase &&+ gfs.status?.pvcName === status.pvcName &&+ gfs.status?.serviceName === status.serviceName &&+ gfs.status?.serviceUrl === status.serviceUrl+ ) {+ return+ }+ await this.api.patchStatus(gfs.name, gfs.namespace, status)+ }+async reconcile(gfs: GlobalFileSystemCRD): Promise<void> {const ns = this.config.gfsNamespaceconst writerDeployment = buildDeployment(gfs, this.config, 'writer')@@ -135,7 +156,7 @@ export class GfsReconciler {}const phase = writerReady ? 'Ready' : 'Initializing'- await this.api.patchStatus(gfs.name, gfs.namespace, {+ await this.writeStatus(gfs, {phase,pvcName: pvcName(gfs),serviceName: serviceName(gfs),diff --git a/host-context-controller/src/k8sClient.test.ts b/host-context-controller/src/k8sClient.test.tsindex b8ea88e58..7de8392f2 100644--- a/host-context-controller/src/k8sClient.test.ts+++ b/host-context-controller/src/k8sClient.test.ts@@ -2,7 +2,13 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'import * as http from 'http'import { HostFleetReconcileError } from './hostReconciler'import { HostK8sRequestTimeoutError } from './k8s/hostK8sApiClient'-import { McpServerWatcher, listAllCommunicationChannels, listAllHosts } from './k8sClient'+import {+ McpServerWatcher,+ getContext,+ listAllCommunicationChannels,+ listAllGlobalFileSystems,+ listAllHosts,+} from './k8sClient'import { ContextMapperServer } from './server'import type { HostCRD } from './types'@@ -52,8 +58,28 @@ async function requestReadyOverHttp(server: ContextMapperServer): Promise<{})}+function stubAuthoritativeInventoryWatch(+ watcher: McpServerWatcher,+ kind: 'McpServer' | 'Context',+ effect?: () => void | Promise<void>+) {+ const method = kind === 'McpServer' ? 'startMcpServerWatch' : 'startContextWatch'+ const generationField = kind === 'McpServer' ? 'mcpWatchGeneration' : 'contextWatchGeneration'+ const requestField = kind === 'McpServer' ? 'mcpWatchRequest' : 'ctxWatchRequest'+ return vi.spyOn(watcher as any, method).mockImplementation(async () => {+ const generation = ((watcher as any)[generationField] as number) + 1+ ;(watcher as any)[generationField] = generation+ ;(watcher as any)[requestField] = { abort: vi.fn() }+ await effect?.()+ return generation+ })+}+const mocks = vi.hoisted(() => {const listNamespacedCustomObject = vi.fn()+ const getNamespacedCustomObject = vi+ .fn()+ .mockRejectedValue(Object.assign(new Error('not found'), { code: 404 }))const ensureDefaultPolicies = vi.fn().mockResolvedValue(undefined)const netPolFullReconcile = vi.fn().mockResolvedValue(undefined)const serverFullReconcile = vi.fn().mockResolvedValue(undefined)@@ -65,6 +91,7 @@ const mocks = vi.hoisted(() => {const createAdministrativeOutcomeReporter = vi.fn().mockReturnValue(undefined)return {listNamespacedCustomObject,+ getNamespacedCustomObject,ensureDefaultPolicies,netPolFullReconcile,serverFullReconcile,@@ -119,7 +146,8 @@ vi.mock('@kubernetes/client-node', () => {if (request.plural === 'hosts') mocks.hostListCallOptions(options)const response = await mocks.listNamespacedCustomObject(request)if (- request.plural === 'hosts' &&+ request.plural &&+ ['hosts', 'mcpservers', 'contexts'].includes(request.plural) &&response &&typeof response === 'object' &&!('metadata' in response)@@ -129,11 +157,17 @@ vi.mock('@kubernetes/client-node', () => {// production missing-resourceVersion failure path.return {...response,- metadata: { resourceVersion: 'test-host-collection-rv' },+ metadata: {+ resourceVersion:+ request.plural === 'hosts'+ ? 'test-host-collection-rv'+ : `test-${request.plural}-collection-rv`,+ },}}return response},+ getNamespacedCustomObject: mocks.getNamespacedCustomObject,}}return {}@@ -158,6 +192,8 @@ vi.mock('./reconciler', () => ({reconcile = vi.fn()reconcileDelete = vi.fn()getStatus = vi.fn()+ setInventoryAuthority = vi.fn()+ setResolveCurrentServer = vi.fn()},}))@@ -208,6 +244,7 @@ vi.mock('./networkPolicyReconciler', () => ({fullReconcile = mocks.netPolFullReconcilereconcileExternalEgress = vi.fn()reconcileContext = vi.fn()+ reconcileDeleteContext = vi.fn()cleanupExternalEgress = vi.fn()},}))@@ -240,7 +277,7 @@ describe('McpServerWatcher startup', () => {mocks.watch.mockReset().mockResolvedValue({ abort: vi.fn() })mocks.listNamespacedCustomObject.mockImplementation(async ({ plural }: { plural: string }) => {if (plural === 'mcpservers') return { items: [] }- if (plural === 'contexts') throw new Error('context discovery failed')+ if (plural === 'contexts') return { items: [] }if (plural === 'hosts') return { items: [] }if (plural === 'sharedfilesystems') return { items: [] }if (plural === 'communicationchannels')@@ -266,24 +303,340 @@ describe('McpServerWatcher startup', () => {})})- it('ensures default policies even when initial Context discovery fails', async () => {+ it('ensures baseline policies before opening any inventory watch', async () => {const watcher = new McpServerWatcher()- vi.spyOn(watcher as any, 'startMcpServerWatch').mockImplementation(async () => undefined)- vi.spyOn(watcher as any, 'startContextWatch').mockImplementation(async () => undefined)- vi.spyOn(watcher as any, 'startSharedFileSystemWatch').mockImplementation(async () => undefined)- vi.spyOn(watcher as any, 'startGlobalFileSystemWatch').mockImplementation(async () => undefined)- // #281 (Task 9): startCommunicationChannelWatch is wired into start() — stub to prevent the real watch from firing.- vi.spyOn(watcher as any, 'startCommunicationChannelWatch').mockImplementation(- async () => undefined- )await watcher.start()expect(mocks.ensureDefaultPolicies).toHaveBeenCalledTimes(1)- expect(mocks.netPolFullReconcile).not.toHaveBeenCalled()- await vi.waitFor(() => expect(mocks.serverFullReconcile).toHaveBeenCalledWith([]))+ expect(mocks.ensureDefaultPolicies.mock.invocationCallOrder[0]).toBeLessThan(+ mocks.watch.mock.invocationCallOrder[0]+ )+ await vi.waitFor(() =>+ expect(mocks.serverFullReconcile).toHaveBeenCalledWith([], {+ runEffect: expect.any(Function),+ })+ )expect(mocks.hostFullReconcile).toHaveBeenCalledWith([])expect(mocks.sfsFullReconcile).toHaveBeenCalledWith([])+ await watcher.stop()+ })++ it('fails safe bootstrap and keeps readiness unavailable when baseline NetworkPolicies fail', async () => {+ const policyError = new Error('baseline NetworkPolicies unavailable')+ mocks.ensureDefaultPolicies.mockRejectedValueOnce(policyError)+ const watcher = new McpServerWatcher()+ const server = new ContextMapperServer(watcher, 0)+ await server.start()+ const bootstrap = watcher.start().then(() => server.setReady(true))++ try {+ await expect(bootstrap).rejects.toThrow(policyError)+ const ready = await requestReadyOverHttp(server)+ expect(ready.statusCode).toBe(503)+ expect(JSON.parse(ready.body)).toEqual({ status: 'starting', ready: false })+ expect(mocks.watch).not.toHaveBeenCalled()+ expect(mocks.serverFullReconcile).not.toHaveBeenCalled()+ expect(mocks.netPolFullReconcile).not.toHaveBeenCalled()+ } finally {+ await server.stop()+ await watcher.stop()+ }+ })++ it('starts McpServer and Context watches from their inventory resourceVersions', async () => {+ const watcher = new McpServerWatcher()++ await (watcher as any).startMcpServerWatch('mcp-inventory-rv')+ await (watcher as any).startContextWatch('context-inventory-rv')++ expect(mocks.watch).toHaveBeenNthCalledWith(+ 1,+ expect.stringContaining('/mcpservers'),+ { resourceVersion: 'mcp-inventory-rv' },+ expect.any(Function),+ expect.any(Function)+ )+ expect(mocks.watch).toHaveBeenNthCalledWith(+ 2,+ expect.stringContaining('/contexts'),+ { resourceVersion: 'context-inventory-rv' },+ expect.any(Function),+ expect.any(Function)+ )+ watcher.stop()+ })++ it.each([+ ['McpServer', 'mcpservers'],+ ['Context', 'contexts'],+ ] as const)(+ 'rejects safe bootstrap when the %s inventory LIST is unavailable',+ async (_kind, failingPlural) => {+ mocks.listNamespacedCustomObject.mockImplementation(+ async ({ plural }: { plural: string }) => {+ if (plural === failingPlural) throw new Error(`${plural} inventory unavailable`)+ if (plural === 'communicationchannels') {+ return { metadata: { resourceVersion: 'cc-rv' }, items: [] }+ }+ return { items: [] }+ }+ )+ const watcher = new McpServerWatcher()++ await expect(watcher.start()).rejects.toThrow(`${failingPlural} inventory unavailable`)++ expect(mocks.serverFullReconcile).not.toHaveBeenCalled()+ expect(mocks.netPolFullReconcile).not.toHaveBeenCalled()+ await watcher.stop()+ }+ )++ it.each([+ ['McpServer', 'mcpservers'],+ ['Context', 'contexts'],+ ] as const)(+ 'rejects safe bootstrap when the %s collection resourceVersion is missing',+ async (kind, missingPlural) => {+ mocks.listNamespacedCustomObject.mockImplementation(+ async ({ plural }: { plural: string }) => {+ if (plural === missingPlural) return { metadata: {}, items: [] }+ if (plural === 'communicationchannels') {+ return { metadata: { resourceVersion: 'cc-rv' }, items: [] }+ }+ return { items: [] }+ }+ )+ const watcher = new McpServerWatcher()++ await expect(watcher.start()).rejects.toThrow(`${kind} snapshot missing resourceVersion`)++ expect(mocks.serverFullReconcile).not.toHaveBeenCalled()+ expect(mocks.netPolFullReconcile).not.toHaveBeenCalled()+ await watcher.stop()+ }+ )++ it('replays McpServer and Context changes from the inventory resourceVersion before convergence', async () => {+ const staleServer = {+ metadata: {+ name: 'gap-server',+ namespace: 'mcp-server',+ uid: 'gap-server-uid',+ generation: 1,+ },+ spec: {+ contextRef: 'default',+ image: 'clerum/gap-server:test',+ transport: { type: 'streamableHttp' as const, port: 3000 },+ },+ }+ const staleContext = {+ metadata: { name: 'gap-context', namespace: 'mcp-server' },+ spec: { contextId: 'gap-context', mcpServers: [] },+ }+ const currentContext = {+ metadata: { name: 'gap-context', namespace: 'mcp-server' },+ spec: { contextId: 'gap-context', mcpServers: ['current-server'] },+ }+ mocks.listNamespacedCustomObject.mockImplementation(async ({ plural }: { plural: string }) => {+ if (plural === 'mcpservers') {+ return { metadata: { resourceVersion: 'opaque/mcp:101' }, items: [staleServer] }+ }+ if (plural === 'contexts') {+ return { metadata: { resourceVersion: 'opaque/context:202' }, items: [staleContext] }+ }+ if (plural === 'communicationchannels') {+ return { metadata: { resourceVersion: 'cc-rv' }, items: [] }+ }+ return { items: [] }+ })+ mocks.watch.mockImplementation(async (path, options, callback) => {+ if (path.endsWith('/mcpservers')) {+ expect(options).toEqual({ resourceVersion: 'opaque/mcp:101' })+ await callback('DELETED', staleServer)+ }+ if (path.endsWith('/contexts')) {+ expect(options).toEqual({ resourceVersion: 'opaque/context:202' })+ await callback('MODIFIED', currentContext)+ }+ return { abort: vi.fn() }+ })+ const watcher = new McpServerWatcher()++ await watcher.start()++ await vi.waitFor(() => {+ expect(mocks.serverFullReconcile).toHaveBeenCalledWith([], {+ runEffect: expect.any(Function),+ })+ expect(mocks.netPolFullReconcile).toHaveBeenCalledWith(+ [expect.objectContaining({ spec: currentContext.spec })],+ [],+ expect.objectContaining({+ serverInventoryComplete: true,+ ensureDefaults: false,+ contextInventoryAuthoritative: expect.any(Function),+ serverInventoryAuthoritative: expect.any(Function),+ })+ )+ })+ expect(watcher.getAllServers()).toEqual([])+ await watcher.stop()+ })++ it('recovers a closed McpServer watch through a fresh authoritative snapshot', async () => {+ vi.useFakeTimers()+ const callbacks: Array<(type: string, apiObj: any) => Promise<void>> = []+ const doneCallbacks: Array<(error: Error | null) => void> = []+ const watchQueries: unknown[] = []+ mocks.watch.mockImplementation(async (path, options, callback, done) => {+ if (path.endsWith('/mcpservers')) {+ callbacks.push(callback)+ doneCallbacks.push(done)+ watchQueries.push(options)+ }+ return { abort: vi.fn() }+ })+ mocks.listNamespacedCustomObject.mockImplementation(async ({ plural }: { plural: string }) => {+ if (plural === 'mcpservers') {+ return {+ metadata: { resourceVersion: 'mcp-recovery-rv' },+ items: [+ {+ metadata: {+ name: 'recovered-server',+ namespace: 'mcp-server',+ uid: 'recovered-uid',+ generation: 1,+ },+ spec: {+ contextRef: 'default',+ image: 'clerum/recovered:test',+ transport: { type: 'streamableHttp' as const, port: 3000 },+ },+ },+ ],+ }+ }+ return { items: [] }+ })+ const watcher = new McpServerWatcher()+ ;(watcher as any).contextCacheSynced = true+ ;(watcher as any).hostCacheSynced = true+ await (watcher as any).restartMcpServerWatch({+ resourceVersion: 'mcp-start-rv',+ servers: [],+ })+ expect(watcher.isReadinessInventoryAuthoritative()).toBe(true)++ doneCallbacks[0](Object.assign(new Error('resource version expired'), { statusCode: 410 }))+ expect(watcher.isReadinessInventoryAuthoritative()).toBe(false)+ await vi.advanceTimersByTimeAsync(5000)+ await vi.waitFor(() => expect(watchQueries).toHaveLength(2))++ expect(watchQueries).toEqual([+ { resourceVersion: 'mcp-start-rv' },+ { resourceVersion: 'mcp-recovery-rv' },+ ])+ expect(watcher.getAllServers()).toEqual([expect.objectContaining({ name: 'recovered-server' })])+ expect(callbacks).toHaveLength(2)+ expect(watcher.isReadinessInventoryAuthoritative()).toBe(true)+ await watcher.stop()+ expect(watcher.isReadinessInventoryAuthoritative()).toBe(false)+ })++ it('ignores a late McpServer callback from a retired watch generation', async () => {+ const callbacks: Array<(type: string, apiObj: any) => Promise<void>> = []+ mocks.watch.mockImplementation(async (path, _options, callback) => {+ if (path.endsWith('/mcpservers')) callbacks.push(callback)+ return { abort: vi.fn() }+ })+ const watcher = new McpServerWatcher()+ await (watcher as any).restartMcpServerWatch({+ resourceVersion: 'mcp-old-rv',+ servers: [],+ })+ await (watcher as any).restartMcpServerWatch({+ resourceVersion: 'mcp-new-rv',+ servers: [+ {+ name: 'current-server',+ namespace: 'mcp-server',+ uid: 'current-uid',+ generation: 1,+ spec: {+ contextRef: 'default',+ image: 'clerum/current:test',+ transport: { type: 'streamableHttp' as const, port: 3000 },+ },+ },+ ],+ })++ await callbacks[0]('ADDED', {+ metadata: {+ name: 'stale-server',+ namespace: 'mcp-server',+ uid: 'stale-uid',+ generation: 1,+ },+ spec: {+ contextRef: 'default',+ image: 'clerum/stale:test',+ transport: { type: 'streamableHttp' as const, port: 3000 },+ },+ })++ expect(watcher.getAllServers().map(server => server.name)).toEqual(['current-server'])+ await watcher.stop()+ })++ it('recovers a closed Context watch through a fresh authoritative snapshot', async () => {+ vi.useFakeTimers()+ const doneCallbacks: Array<(error: Error | null) => void> = []+ const watchQueries: unknown[] = []+ mocks.watch.mockImplementation(async (path, options, _callback, done) => {+ if (path.endsWith('/contexts')) {+ doneCallbacks.push(done)+ watchQueries.push(options)+ }+ return { abort: vi.fn() }+ })+ mocks.listNamespacedCustomObject.mockImplementation(async ({ plural }: { plural: string }) => {+ if (plural === 'contexts') {+ return {+ metadata: { resourceVersion: 'context-recovery-rv' },+ items: [+ {+ metadata: { name: 'recovered-context', namespace: 'mcp-server' },+ spec: { contextId: 'recovered-context', mcpServers: [] },+ },+ ],+ }+ }+ return { items: [] }+ })+ const watcher = new McpServerWatcher()+ ;(watcher as any).mcpServerCacheSynced = true+ await (watcher as any).restartContextWatch({+ resourceVersion: 'context-start-rv',+ contexts: [],+ })++ doneCallbacks[0](Object.assign(new Error('resource version expired'), { statusCode: 410 }))+ await vi.advanceTimersByTimeAsync(5000)+ await vi.waitFor(() => expect(watchQueries).toHaveLength(2))++ expect(watchQueries).toEqual([+ { resourceVersion: 'context-start-rv' },+ { resourceVersion: 'context-recovery-rv' },+ ])+ expect((watcher as any).contexts.get('recovered-context')).toEqual(+ expect.objectContaining({ name: 'recovered-context' })+ )+ await vi.waitFor(() => expect(mocks.netPolFullReconcile).toHaveBeenCalled())+ await watcher.stop()})it('completes safe bootstrap while every initial convergence lane continues in background', async () => {@@ -303,12 +656,8 @@ describe('McpServerWatcher startup', () => {return { items: [] }})const watcher = new McpServerWatcher()- const startMcpServerWatch = vi- .spyOn(watcher as any, 'startMcpServerWatch')- .mockResolvedValue(undefined)- const startContextWatch = vi- .spyOn(watcher as any, 'startContextWatch')- .mockResolvedValue(undefined)+ const startMcpServerWatch = stubAuthoritativeInventoryWatch(watcher, 'McpServer')+ const startContextWatch = stubAuthoritativeInventoryWatch(watcher, 'Context')const startSharedFileSystemWatch = vi.spyOn(watcher as any, 'startSharedFileSystemWatch').mockResolvedValue(undefined)@@ -402,11 +751,11 @@ describe('McpServerWatcher startup', () => {return { items: [] }})const watcher = new McpServerWatcher()- vi.spyOn(watcher as any, 'startMcpServerWatch').mockImplementation(async () => {+ stubAuthoritativeInventoryWatch(watcher, 'McpServer', () => {;(watcher as any).servers.clear();(watcher as any).servers.set(currentServer.name, currentServer)})- vi.spyOn(watcher as any, 'startContextWatch').mockImplementation(async () => {+ stubAuthoritativeInventoryWatch(watcher, 'Context', () => {;(watcher as any).contexts.clear();(watcher as any).contexts.set(currentContext.name, currentContext)})@@ -423,127 +772,651 @@ describe('McpServerWatcher startup', () => {await watcher.start()await vi.waitFor(() => {- expect(mocks.serverFullReconcile).toHaveBeenCalledWith([currentServer])- expect(mocks.netPolFullReconcile).toHaveBeenCalledWith([currentContext], [currentServer], {- serverInventoryComplete: true,- ensureDefaults: false,+ expect(mocks.serverFullReconcile).toHaveBeenCalledWith([currentServer], {+ runEffect: expect.any(Function),})+ expect(mocks.netPolFullReconcile).toHaveBeenCalledWith(+ [currentContext],+ [currentServer],+ expect.objectContaining({+ serverInventoryComplete: true,+ ensureDefaults: false,+ contextInventoryAuthoritative: expect.any(Function),+ serverInventoryAuthoritative: expect.any(Function),+ })+ )expect(mocks.sfsFullReconcile).toHaveBeenCalledWith([currentSfs])expect(gfsFullReconcile).toHaveBeenCalledWith([currentGfs])})- watcher.stop()+ watcher.stop()+ })++ it('updates discovery without re-reconciling a status-only McpServer watch event', async () => {+ const previousServer = {+ name: 'status-server',+ namespace: 'mcp-server',+ uid: 'status-server-uid',+ generation: 7,+ annotations: { 'clerum.io/recipe': 'status-recipe' },+ labels: { 'clerum.io/workload': 'status-server' },+ spec: {+ contextRef: 'default',+ image: 'clerum/status-server:test',+ transport: { type: 'streamableHttp' as const, port: 3000 },+ },+ }+ const watcher = new McpServerWatcher()+ ;(watcher as any).servers.set(previousServer.name, previousServer)+ const changed = vi.fn()+ watcher.onChange(changed)+ const reconciler = (watcher as any).reconciler+ const netPol = (watcher as any).netPolReconciler+ const callback = (watcher as any).getMcpServerWatchCallback()++ await callback('MODIFIED', {+ metadata: {+ name: previousServer.name,+ namespace: previousServer.namespace,+ uid: previousServer.uid,+ generation: previousServer.generation,+ annotations: previousServer.annotations,+ labels: previousServer.labels,+ },+ spec: previousServer.spec,+ status: { conditions: [{ type: 'Ready', status: 'True' }] },+ })++ expect(watcher.getAllServers()[0]?.status).toEqual({+ conditions: [{ type: 'Ready', status: 'True' }],+ })+ expect(changed).toHaveBeenCalledOnce()+ expect(reconciler.reconcile).not.toHaveBeenCalled()+ expect(netPol.reconcileExternalEgress).not.toHaveBeenCalled()++ await callback('MODIFIED', {+ metadata: {+ name: previousServer.name,+ namespace: previousServer.namespace,+ uid: previousServer.uid,+ generation: 8,+ annotations: previousServer.annotations,+ labels: previousServer.labels,+ },+ spec: { ...previousServer.spec, image: 'clerum/status-server:next' },+ })+ expect(reconciler.reconcile).toHaveBeenCalledOnce()+ await watcher.stop()+ })++ it('uses only the bounded fleet pass for the cold-start Host snapshot', async () => {+ const initialHosts = Array.from({ length: 50 }, (_, index) => ({+ metadata: {+ name: `initial-host-${index}`,+ namespace: 'mcp-host',+ uid: `initial-host-uid-${index}`,+ generation: 1,+ },+ spec: {+ host: `initial-host-${index}`,+ contextRef: 'default',+ secretRef: 'host-secret',+ },+ }))+ mocks.listNamespacedCustomObject.mockImplementation(async ({ plural }: { plural: string }) => {+ if (plural === 'hosts') {+ return {+ metadata: { resourceVersion: 'initial-host-rv' },+ items: initialHosts,+ }+ }+ if (plural === 'communicationchannels') {+ return { metadata: { resourceVersion: 'initial-cc-rv' }, items: [] }+ }+ return { items: [] }+ })+ const watcher = new McpServerWatcher()+ const urgentReconcile = vi.spyOn(watcher.getHostReconciler(), 'reconcile')++ await watcher.start()+ await vi.waitFor(() =>+ expect(mocks.hostFullReconcile).toHaveBeenCalledWith(+ initialHosts.map(host =>+ expect.objectContaining({+ name: host.metadata.name,+ generation: host.metadata.generation,+ })+ )+ )+ )+ await flushMicrotasks()++ expect(mocks.hostFullReconcile).toHaveBeenCalledOnce()+ expect(urgentReconcile).not.toHaveBeenCalled()+ await watcher.stop()+ })++ it('admits a McpServer watch reconciliation while initial convergence is blocked on another server', async () => {+ const staleServer = {+ name: 'stale-server',+ namespace: 'mcp-server',+ spec: {+ contextRef: 'default',+ image: 'clerum/stale-server:test',+ transport: { type: 'streamableHttp' as const, port: 3000 },+ egressBindings: [{ dns: 'stale.example', port: 443 }],+ },+ }+ const currentServer = {+ metadata: { name: 'current-server', namespace: 'mcp-server' },+ spec: {+ contextRef: 'default',+ image: 'clerum/current-server:test',+ transport: { type: 'streamableHttp' as const, port: 3000 },+ },+ }+ const egressStarted = deferred()+ const releaseEgress = deferred()+ const reconciliationOrder: string[] = []+ const watcher = new McpServerWatcher()+ ;(watcher as any).mcpServerCacheSynced = true+ ;(watcher as any).servers.set(staleServer.name, staleServer)+ const netPol = (watcher as any).netPolReconciler+ netPol.reconcileExternalEgress.mockImplementationOnce(async () => {+ egressStarted.resolve(undefined)+ await releaseEgress.promise+ })+ mocks.serverFullReconcile.mockImplementationOnce(async (servers, options) => {+ await Promise.all(+ servers.map((selected: { name: string }) =>+ options.runEffect(selected.name, async () => {+ reconciliationOrder.push('initial')+ })+ )+ )+ })+ const reconciler = (watcher as any).reconciler+ reconciler.reconcile.mockImplementationOnce(async () => {+ reconciliationOrder.push('watch')+ })++ const convergence = (watcher as any).runInitialMcpServerConvergence()+ await egressStarted.promise+ const watchConvergence = (watcher as any).getMcpServerWatchCallback()('MODIFIED', currentServer)++ await flushMicrotasks()+ expect(reconciler.reconcile).toHaveBeenCalledWith(+ expect.objectContaining({ name: 'current-server' })+ )++ releaseEgress.resolve(undefined)+ await Promise.all([convergence, watchConvergence])++ expect(reconciliationOrder).toEqual(['watch', 'initial'])+ expect(reconciler.reconcile).toHaveBeenLastCalledWith(+ expect.objectContaining({ name: 'current-server' })+ )+ await watcher.stop()+ })++ it('admits an initial server without egress while another initial server waits on DNS', async () => {+ const dnsBlockedServer = {+ name: 'dns-blocked-server',+ namespace: 'mcp-server',+ uid: 'dns-blocked-server-uid',+ generation: 1,+ spec: {+ contextRef: 'default',+ image: 'clerum/dns-blocked-server:test',+ transport: { type: 'streamableHttp' as const, port: 3000 },+ egressBindings: [{ dns: 'blocked.example', port: 443 }],+ },+ }+ const independentServer = {+ name: 'independent-server',+ namespace: 'mcp-server',+ uid: 'independent-server-uid',+ generation: 1,+ spec: {+ contextRef: 'default',+ image: 'clerum/independent-server:test',+ transport: { type: 'streamableHttp' as const, port: 3000 },+ },+ }+ const egressStarted = deferred()+ const releaseEgress = deferred()+ const watcher = new McpServerWatcher()+ ;(watcher as any).mcpServerCacheSynced = true+ ;(watcher as any).servers.set(dnsBlockedServer.name, dnsBlockedServer)+ ;(watcher as any).servers.set(independentServer.name, independentServer)+ const netPol = (watcher as any).netPolReconciler+ const reconciler = (watcher as any).reconciler+ netPol.reconcileExternalEgress.mockImplementationOnce(async () => {+ egressStarted.resolve(undefined)+ await releaseEgress.promise+ })+ mocks.serverFullReconcile.mockImplementationOnce(+ async (+ servers: Array<typeof dnsBlockedServer | typeof independentServer>,+ options: { runEffect: (serverName: string, work: () => Promise<void>) => Promise<void> }+ ) => {+ await Promise.all(+ servers.map(server => options.runEffect(server.name, () => reconciler.reconcile(server)))+ )+ }+ )++ const convergence = (watcher as any).runInitialMcpServerConvergence()+ await egressStarted.promise+ await flushMicrotasks()++ expect(reconciler.reconcile).toHaveBeenCalledWith(independentServer)+ expect(reconciler.reconcile).not.toHaveBeenCalledWith(dnsBlockedServer)++ releaseEgress.resolve(undefined)+ await convergence++ expect(reconciler.reconcile).toHaveBeenCalledWith(dnsBlockedServer)+ await watcher.stop()+ })++ it('admits a Context watch reconciliation while initial policy convergence is blocked', async () => {+ const staleContext = {+ name: 'stale-context',+ namespace: 'mcp-server',+ spec: { contextId: 'stale-context', mcpServers: [] },+ }+ const currentContext = {+ metadata: { name: 'current-context', namespace: 'mcp-server' },+ spec: { contextId: 'current-context', mcpServers: [] },+ }+ const fullReconcileStarted = deferred()+ const releaseFullReconcile = deferred()+ const reconciliationOrder: string[] = []+ const watcher = new McpServerWatcher()+ ;(watcher as any).mcpServerCacheSynced = true+ ;(watcher as any).contextCacheSynced = true+ ;(watcher as any).contexts.set(staleContext.name, staleContext)+ mocks.netPolFullReconcile.mockImplementationOnce(async () => {+ fullReconcileStarted.resolve(undefined)+ await releaseFullReconcile.promise+ reconciliationOrder.push('initial')+ })+ const netPol = (watcher as any).netPolReconciler+ netPol.reconcileContext.mockImplementationOnce(async () => {+ reconciliationOrder.push('watch')+ })+ let contextWatchCallback:+ | ((type: string, apiObj: typeof currentContext) => Promise<void>)+ | undefined+ mocks.watch.mockImplementationOnce(async (_path, _options, callback) => {+ contextWatchCallback = callback+ return { abort: vi.fn() }+ })+ await (watcher as any).startContextWatch('context-queue-rv')++ const convergence = (watcher as any).runInitialNetworkPolicyConvergence(true)+ await fullReconcileStarted.promise+ const watchConvergence = contextWatchCallback!('MODIFIED', currentContext)++ await flushMicrotasks()+ expect(netPol.reconcileContext).toHaveBeenCalledWith(+ expect.objectContaining({ name: 'current-context' })+ )++ releaseFullReconcile.resolve(undefined)+ await Promise.all([convergence, watchConvergence])++ expect(reconciliationOrder).toEqual(['watch', 'initial'])+ expect(netPol.reconcileContext).toHaveBeenLastCalledWith(+ expect.objectContaining({ name: 'current-context' })+ )+ await watcher.stop()+ })++ it('makes a recreated Context the last writer after same-contextId orphan cleanup', async () => {+ const contextName = 'recreated-context-resource'+ const contextId = 'recreated-context'+ const recreatedContext = {+ metadata: { name: contextName, namespace: 'mcp-server' },+ spec: {+ contextId,+ description: 'recreated',+ mcpServers: [],+ },+ }+ const orphanCleanupStarted = deferred()+ const releaseOrphanCleanup = deferred()+ const order: string[] = []+ const watcher = new McpServerWatcher()+ ;(watcher as any).mcpServerCacheSynced = true+ ;(watcher as any).contextCacheSynced = true+ mocks.netPolFullReconcile.mockImplementationOnce(+ async (+ _contexts: unknown[],+ _servers: unknown[],+ options: {+ runContextEffect: (effectContextId: string, work: () => Promise<void>) => Promise<void>+ }+ ) => {+ await options.runContextEffect(contextId, async () => {+ orphanCleanupStarted.resolve(undefined)+ await releaseOrphanCleanup.promise+ order.push('orphan-delete')+ })+ }+ )+ const netPol = (watcher as any).netPolReconciler+ netPol.reconcileContext.mockImplementationOnce(async () => {+ order.push('live-recreate')+ })+ let contextWatchCallback:+ | ((type: string, apiObj: typeof recreatedContext) => Promise<void>)+ | undefined+ mocks.watch.mockImplementationOnce(async (_path, _options, callback) => {+ contextWatchCallback = callback+ return { abort: vi.fn() }+ })+ await (watcher as any).startContextWatch('recreated-context-rv')++ const convergence = (watcher as any).runInitialNetworkPolicyConvergence()+ await orphanCleanupStarted.promise+ const recreation = contextWatchCallback!('ADDED', recreatedContext)+ await flushMicrotasks()++ expect(netPol.reconcileContext).not.toHaveBeenCalled()++ releaseOrphanCleanup.resolve(undefined)+ await Promise.all([convergence, recreation])++ expect(order).toEqual(['orphan-delete', 'live-recreate'])+ expect(netPol.reconcileContext).toHaveBeenLastCalledWith(+ expect.objectContaining({+ name: contextName,+ spec: expect.objectContaining({ contextId, description: 'recreated' }),+ })+ )+ await watcher.stop()+ })++ it('retires old contextId policies before reconciling a mutable Context identity', async () => {+ const oldContext = {+ name: 'mutable-context-resource',+ namespace: 'mcp-server',+ spec: {+ contextId: 'old-context-id',+ mcpServers: ['redis-tools'],+ },+ }+ const newContext = {+ metadata: { name: oldContext.name, namespace: oldContext.namespace },+ spec: {+ contextId: 'new-context-id',+ mcpServers: ['redis-tools'],+ },+ }+ mocks.listNamespacedCustomObject.mockImplementation(async ({ plural }: { plural: string }) => {+ if (plural === 'contexts') {+ return {+ metadata: { resourceVersion: 'mutable-context-rv' },+ items: [newContext],+ }+ }+ return { items: [] }+ })+ let contextWatchCallback:+ | ((type: string, apiObj: typeof newContext) => Promise<void>)+ | undefined+ mocks.watch.mockImplementationOnce(async (_path, _options, callback) => {+ contextWatchCallback = callback+ return { abort: vi.fn() }+ })+ const watcher = new McpServerWatcher()+ ;(watcher as any).contexts.set(oldContext.name, oldContext)+ ;(watcher as any).contextCacheSynced = true+ const netPol = (watcher as any).netPolReconciler+ const order: string[] = []+ netPol.reconcileDeleteContext.mockImplementation(async (contextId: string) => {+ order.push(`delete:${contextId}`)+ })+ netPol.reconcileContext.mockImplementation(async (context: typeof oldContext) => {+ order.push(`reconcile:${context.spec.contextId}`)+ })+ await (watcher as any).startContextWatch('mutable-context-rv')++ await contextWatchCallback!('MODIFIED', newContext)++ expect(order).toEqual(['delete:old-context-id', 'reconcile:new-context-id'])+ expect(netPol.reconcileDeleteContext).toHaveBeenCalledWith(+ 'old-context-id',+ expect.any(Function)+ )+ await watcher.stop()+ })++ it('retires queued Context policy work immediately when its watch ends', async () => {+ const context = {+ metadata: { name: 'retired-context-resource', namespace: 'mcp-server' },+ spec: { contextId: 'retired-context-id', mcpServers: [] },+ }+ const blockerStarted = deferred()+ const releaseBlocker = deferred()+ let contextWatchCallback: ((type: string, apiObj: typeof context) => Promise<void>) | undefined+ let contextWatchDone: ((error: Error | null) => void) | undefined+ mocks.watch.mockImplementationOnce(async (_path, _options, callback, done) => {+ contextWatchCallback = callback+ contextWatchDone = done+ return { abort: vi.fn() }+ })+ const watcher = new McpServerWatcher()+ const netPol = (watcher as any).netPolReconciler+ await (watcher as any).startContextWatch('retired-context-rv')+ const blocker = (watcher as any).enqueueContextReconciliation(+ context.spec.contextId,+ async () => {+ blockerStarted.resolve(undefined)+ await releaseBlocker.promise+ }+ )+ await blockerStarted.promise++ const event = contextWatchCallback!('MODIFIED', context)+ contextWatchDone!(null)+ releaseBlocker.resolve(undefined)+ await Promise.all([blocker, event])++ expect(netPol.reconcileContext).not.toHaveBeenCalled()+ await watcher.stop()})- it('queues a McpServer watch reconciliation behind an in-flight initial fleet pass', async () => {- const staleServer = {- name: 'stale-server',- namespace: 'mcp-server',+ it('serializes McpServer-driven Context policy work with a newer Context watch revision', async () => {+ const server = {+ metadata: {+ name: 'context-policy-server',+ namespace: 'mcp-server',+ uid: 'context-policy-server-uid',+ generation: 1,+ },spec: {- contextRef: 'default',- image: 'clerum/stale-server:test',+ contextRef: 'context-policy',+ image: 'clerum/context-policy-server:test',transport: { type: 'streamableHttp' as const, port: 3000 },- egressBindings: [{ dns: 'stale.example', port: 443 }],},}- const currentServer = {- metadata: { name: 'current-server', namespace: 'mcp-server' },+ const oldContext = {+ name: 'context-policy-resource',+ namespace: 'mcp-server',spec: {- contextRef: 'default',- image: 'clerum/current-server:test',- transport: { type: 'streamableHttp' as const, port: 3000 },+ contextId: 'context-policy',+ description: 'old',+ mcpServers: [server.metadata.name],},}- const egressStarted = deferred()- const releaseEgress = deferred()- const reconciliationOrder: string[] = []+ const newContext = {+ metadata: { name: oldContext.name, namespace: oldContext.namespace },+ spec: {+ ...oldContext.spec,+ description: 'new',+ },+ }+ const oldStarted = deferred()+ const releaseOld = deferred()+ const order: string[] = []+ let contextWatchCallback:+ | ((type: string, apiObj: typeof newContext) => Promise<void>)+ | undefined+ mocks.watch.mockImplementationOnce(async (_path, _options, callback) => {+ contextWatchCallback = callback+ return { abort: vi.fn() }+ })const watcher = new McpServerWatcher()- ;(watcher as any).servers.set(staleServer.name, staleServer)+ ;(watcher as any).contexts.set(oldContext.name, oldContext)const netPol = (watcher as any).netPolReconciler- netPol.reconcileExternalEgress.mockImplementationOnce(async () => {- egressStarted.resolve(undefined)- await releaseEgress.promise- })- mocks.serverFullReconcile.mockImplementationOnce(async () => {- reconciliationOrder.push('initial')- })- const reconciler = (watcher as any).reconciler- reconciler.reconcile.mockImplementationOnce(async () => {- reconciliationOrder.push('watch')+ netPol.reconcileContext.mockImplementation(async (context: typeof oldContext) => {+ if (context.spec.description === 'old') {+ oldStarted.resolve(undefined)+ await releaseOld.promise+ order.push('old')+ return+ }+ order.push('new')})+ await (watcher as any).startContextWatch('context-policy-rv')- const convergence = (watcher as any).runInitialMcpServerConvergence()- await egressStarted.promise- const watchConvergence = (watcher as any).getMcpServerWatchCallback()('MODIFIED', currentServer)-+ const serverEvent = (watcher as any).getMcpServerWatchCallback()('MODIFIED', server)+ await oldStarted.promise+ const contextEvent = contextWatchCallback!('MODIFIED', newContext)await flushMicrotasks()- expect(reconciler.reconcile).not.toHaveBeenCalled()- releaseEgress.resolve(undefined)- await Promise.all([convergence, watchConvergence])+ expect(netPol.reconcileContext).toHaveBeenCalledTimes(1)+ releaseOld.resolve(undefined)+ await Promise.all([serverEvent, contextEvent])- expect(reconciliationOrder).toEqual(['initial', 'watch'])- expect(reconciler.reconcile).toHaveBeenLastCalledWith(- expect.objectContaining({ name: 'current-server' })+ expect(order).toEqual(['old', 'new'])+ expect(netPol.reconcileContext).toHaveBeenLastCalledWith(+ expect.objectContaining({+ spec: expect.objectContaining({ description: 'new' }),+ }))await watcher.stop()})- it('queues a Context watch reconciliation behind an in-flight initial policy pass', async () => {- const staleContext = {- name: 'stale-context',+ it('keeps live control-plane events responsive during a periodic external-egress fleet resync', async () => {+ const server = {+ name: 'periodic-egress-server',namespace: 'mcp-server',- spec: { contextId: 'stale-context', mcpServers: [] },+ uid: 'periodic-egress-uid',+ generation: 1,+ spec: {+ contextRef: 'default',+ image: 'clerum/periodic-egress:test',+ transport: { type: 'streamableHttp' as const, port: 3000 },+ egressBindings: [{ dns: 'periodic.example', port: 443 }],+ },}- const currentContext = {- metadata: { name: 'current-context', namespace: 'mcp-server' },- spec: { contextId: 'current-context', mcpServers: [] },+ const context = {+ metadata: { name: 'live-context', namespace: 'mcp-server' },+ spec: { contextId: 'live-context', mcpServers: [] },}- const fullReconcileStarted = deferred()- const releaseFullReconcile = deferred()- const reconciliationOrder: string[] = []- const watcher = new McpServerWatcher()- ;(watcher as any).contexts.set(staleContext.name, staleContext)- mocks.netPolFullReconcile.mockImplementationOnce(async () => {- fullReconcileStarted.resolve(undefined)- await releaseFullReconcile.promise- reconciliationOrder.push('initial')- })- const netPol = (watcher as any).netPolReconciler- netPol.reconcileContext.mockImplementationOnce(async () => {- reconciliationOrder.push('watch')- })- let contextWatchCallback:- | ((type: string, apiObj: typeof currentContext) => Promise<void>)- | undefined+ const resyncStarted = deferred()+ const releaseResync = deferred()+ let contextWatchCallback: ((type: string, apiObj: typeof context) => Promise<void>) | undefinedmocks.watch.mockImplementationOnce(async (_path, _options, callback) => {contextWatchCallback = callbackreturn { abort: vi.fn() }})- await (watcher as any).startContextWatch()+ const randomSpy = vi.spyOn(Math, 'random').mockReturnValue(0)+ const watcher = new McpServerWatcher()+ ;(watcher as any).servers.set(server.name, server)+ const netPol = (watcher as any).netPolReconciler+ netPol.reconcileExternalEgress.mockImplementationOnce(async () => {+ resyncStarted.resolve(undefined)+ await releaseResync.promise+ })+ await (watcher as any).startContextWatch('live-context-rv')- const convergence = (watcher as any).runInitialNetworkPolicyConvergence(true)- await fullReconcileStarted.promise- const watchConvergence = contextWatchCallback!('MODIFIED', currentContext)+ const firstResync = (watcher as any).runExternalEgressResync() as Promise<void>+ const overlappingResync = (watcher as any).runExternalEgressResync() as Promise<void>+ expect(overlappingResync).toBe(firstResync)+ await resyncStarted.promise+ const liveEvent = contextWatchCallback!('MODIFIED', context)await flushMicrotasks()- expect(netPol.reconcileContext).not.toHaveBeenCalled()+ expect(netPol.reconcileContext).toHaveBeenCalledWith(+ expect.objectContaining({ name: 'live-context' })+ )- releaseFullReconcile.resolve(undefined)- await Promise.all([convergence, watchConvergence])+ releaseResync.resolve(undefined)+ await Promise.all([firstResync, liveEvent])+ await watcher.stop()+ randomSpy.mockRestore()+ })- expect(reconciliationOrder).toEqual(['initial', 'watch'])- expect(netPol.reconcileContext).toHaveBeenLastCalledWith(- expect.objectContaining({ name: 'current-context' })+ it('uses the latest cached McpServer after periodic external-egress jitter', async () => {+ vi.useFakeTimers()+ const staleServer = {+ name: 'periodic-egress-server',+ namespace: 'mcp-server',+ uid: 'periodic-egress-uid',+ generation: 1,+ spec: {+ contextRef: 'default',+ image: 'clerum/periodic-egress:old',+ transport: { type: 'streamableHttp' as const, port: 3000 },+ egressBindings: [{ dns: 'old.example', port: 443 }],+ },+ }+ const currentServer = {+ metadata: {+ name: staleServer.name,+ namespace: staleServer.namespace,+ uid: staleServer.uid,+ generation: 2,+ },+ spec: {+ ...staleServer.spec,+ image: 'clerum/periodic-egress:new',+ egressBindings: [{ dns: 'new.example', port: 443 }],+ },+ }+ const randomSpy = vi.spyOn(Math, 'random').mockReturnValue(0.5)+ const watcher = new McpServerWatcher()+ ;(watcher as any).servers.set(staleServer.name, staleServer)+ const netPol = (watcher as any).netPolReconciler++ const periodic = (watcher as any).runExternalEgressResync() as Promise<void>+ await flushMicrotasks()+ await (watcher as any).getMcpServerWatchCallback()('MODIFIED', currentServer)+ await vi.advanceTimersByTimeAsync(2500)+ await periodic++ expect(netPol.reconcileExternalEgress).toHaveBeenLastCalledWith(+ expect.objectContaining({+ name: staleServer.name,+ generation: 2,+ spec: expect.objectContaining({+ egressBindings: [{ dns: 'new.example', port: 443 }],+ }),+ }))await watcher.stop()+ randomSpy.mockRestore()})it('queues SharedFileSystem and GlobalFileSystem watch effects behind their initial passes', async () => {const staleSfs = { name: 'stale-sfs', namespace: 'mcp-host', spec: {} }const currentSfs = { metadata: { name: 'current-sfs', namespace: 'mcp-host' }, spec: {} }const staleGfs = { name: 'stale-gfs', namespace: 'mcp-host', spec: {} }- const currentGfs = { metadata: { name: 'current-gfs', namespace: 'mcp-host' }, spec: {} }+ const currentGfs = {+ metadata: { name: 'current-gfs', namespace: 'mcp-host' },+ spec: {},+ status: {+ phase: 'Ready',+ pvcName: 'gfs-drive',+ serviceName: 'gfsc',+ serviceUrl: 'http://gfsc.gfs.svc.cluster.local:8087',+ },+ }const sfsInitialStarted = deferred()const releaseSfsInitial = deferred()const gfsInitialStarted = deferred()@@ -603,6 +1476,9 @@ describe('McpServerWatcher startup', () => {expect(sfsOrder).toEqual(['initial', 'watch'])expect(gfsOrder).toEqual(['initial', 'watch'])+ expect(gfsReconcile).toHaveBeenCalledWith(+ expect.objectContaining({ status: currentGfs.status })+ )await watcher.stop()})@@ -686,6 +1562,7 @@ describe('McpServerWatcher startup', () => {const egressStarted = deferred()const releaseEgress = deferred()const watcher = new McpServerWatcher()+ ;(watcher as any).mcpServerCacheSynced = true;(watcher as any).servers.set(initialServer.name, initialServer)const netPol = (watcher as any).netPolReconcilernetPol.reconcileExternalEgress.mockImplementationOnce(async () => {@@ -693,6 +1570,13 @@ describe('McpServerWatcher startup', () => {await releaseEgress.promise})const reconciler = (watcher as any).reconciler+ mocks.serverFullReconcile.mockImplementationOnce(async (servers, options) => {+ await Promise.all(+ servers.map((selected: { name: string }) =>+ options.runEffect(selected.name, () => reconciler.reconcile(selected))+ )+ )+ })const initial = (watcher as any).runInitialMcpServerConvergence()await egressStarted.promise@@ -702,29 +1586,77 @@ describe('McpServerWatcher startup', () => {releaseEgress.resolve(undefined)await Promise.all([initial, queuedWatch])- expect(mocks.serverFullReconcile).not.toHaveBeenCalled()+ expect(mocks.serverFullReconcile).toHaveBeenCalledOnce()expect(reconciler.reconcile).not.toHaveBeenCalled()})it('keeps an incomplete McpServer inventory non-authoritative across NetworkPolicy retries', async () => {vi.useFakeTimers()const watcher = new McpServerWatcher()+ ;(watcher as any).contextCacheSynced = true+ ;(watcher as any).mcpServerCacheSynced = falsemocks.netPolFullReconcile.mockRejectedValueOnce(new Error('initial NetworkPolicy reconciliation failed')).mockResolvedValueOnce(undefined)const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {})- await (watcher as any).runInitialNetworkPolicyConvergence(false)+ await (watcher as any).runInitialNetworkPolicyConvergence()await vi.advanceTimersByTimeAsync(5000)- expect(mocks.netPolFullReconcile).toHaveBeenLastCalledWith([], [], {- serverInventoryComplete: false,- ensureDefaults: false,- })+ expect(mocks.netPolFullReconcile).toHaveBeenLastCalledWith(+ [],+ [],+ expect.objectContaining({+ serverInventoryComplete: false,+ ensureDefaults: false,+ contextInventoryAuthoritative: expect.any(Function),+ serverInventoryAuthoritative: expect.any(Function),+ })+ )await watcher.stop()errorSpy.mockRestore()})+ it('fences NetworkPolicy orphan cleanup to the inventory generations captured by the pass', async () => {+ const watcher = new McpServerWatcher()+ ;(watcher as any).contextCacheSynced = true+ ;(watcher as any).mcpServerCacheSynced = true+ ;(watcher as any).contextWatchGeneration = 17+ ;(watcher as any).mcpWatchGeneration = 23+ let options:+ | {+ contextInventoryAuthoritative: () => boolean+ serverInventoryAuthoritative: () => boolean+ }+ | undefined+ mocks.netPolFullReconcile.mockImplementationOnce(+ async (+ _contexts: unknown[],+ _servers: unknown[],+ received: {+ contextInventoryAuthoritative: () => boolean+ serverInventoryAuthoritative: () => boolean+ }+ ) => {+ options = received+ }+ )++ await (watcher as any).runInitialNetworkPolicyConvergence()++ expect(options?.contextInventoryAuthoritative()).toBe(true)+ expect(options?.serverInventoryAuthoritative()).toBe(true)++ // A recovered watch may already be authoritative again, but it is a+ // different snapshot generation and cannot authorize cleanup by this pass.+ ;(watcher as any).contextWatchGeneration = 18+ ;(watcher as any).mcpWatchGeneration = 24++ expect(options?.contextInventoryAuthoritative()).toBe(false)+ expect(options?.serverInventoryAuthoritative()).toBe(false)+ await watcher.stop()+ })+it('retries failed initial McpServer convergence without delaying safe bootstrap', async () => {vi.useFakeTimers()const server = {@@ -748,8 +1680,8 @@ describe('McpServerWatcher startup', () => {.mockResolvedValueOnce(undefined)const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {})const watcher = new McpServerWatcher()- vi.spyOn(watcher as any, 'startMcpServerWatch').mockResolvedValue(undefined)- vi.spyOn(watcher as any, 'startContextWatch').mockResolvedValue(undefined)+ stubAuthoritativeInventoryWatch(watcher, 'McpServer')+ stubAuthoritativeInventoryWatch(watcher, 'Context')vi.spyOn(watcher as any, 'startSharedFileSystemWatch').mockResolvedValue(undefined)vi.spyOn(watcher as any, 'startGlobalFileSystemWatch').mockResolvedValue(undefined)vi.spyOn(watcher as any, 'startCommunicationChannelWatch').mockResolvedValue(undefined)@@ -784,8 +1716,8 @@ describe('McpServerWatcher startup', () => {.mockResolvedValueOnce(undefined)const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {})const watcher = new McpServerWatcher()- vi.spyOn(watcher as any, 'startMcpServerWatch').mockResolvedValue(undefined)- vi.spyOn(watcher as any, 'startContextWatch').mockResolvedValue(undefined)+ stubAuthoritativeInventoryWatch(watcher, 'McpServer')+ stubAuthoritativeInventoryWatch(watcher, 'Context')vi.spyOn(watcher as any, 'startSharedFileSystemWatch').mockResolvedValue(undefined)vi.spyOn(watcher as any, 'startGlobalFileSystemWatch').mockResolvedValue(undefined)vi.spyOn(watcher as any, 'startCommunicationChannelWatch').mockResolvedValue(undefined)@@ -799,26 +1731,53 @@ describe('McpServerWatcher startup', () => {expect(mocks.netPolFullReconcile).toHaveBeenLastCalledWith([expect.objectContaining({ name: 'initial-context' })],[],- { serverInventoryComplete: true, ensureDefaults: false }+ expect.objectContaining({+ serverInventoryComplete: true,+ ensureDefaults: false,+ contextInventoryAuthoritative: expect.any(Function),+ serverInventoryAuthoritative: expect.any(Function),+ }))watcher.stop()errorSpy.mockRestore()})- it('rejects safe bootstrap when the McpServer watch cannot be established', async () => {- const watcher = new McpServerWatcher()- vi.spyOn(watcher as any, 'startMcpServerWatch').mockRejectedValue(- new Error('watch unavailable')- )- vi.spyOn(watcher as any, 'startContextWatch').mockResolvedValue(undefined)- vi.spyOn(watcher as any, 'startSharedFileSystemWatch').mockResolvedValue(undefined)- vi.spyOn(watcher as any, 'startGlobalFileSystemWatch').mockResolvedValue(undefined)- vi.spyOn(watcher as any, 'startCommunicationChannelWatch').mockResolvedValue(undefined)+ it.each([+ ['McpServer', 'startMcpServerWatch'],+ ['Context', 'startContextWatch'],+ ['SharedFileSystem', 'startSharedFileSystemWatch'],+ ['GlobalFileSystem', 'startGlobalFileSystemWatch'],+ ] as const)(+ 'rejects safe bootstrap when the %s watch cannot be established',+ async (_kind, method) => {+ const watcher = new McpServerWatcher()+ if (method === 'startMcpServerWatch') {+ vi.spyOn(watcher as any, method).mockRejectedValue(new Error(`${method} unavailable`))+ } else {+ stubAuthoritativeInventoryWatch(watcher, 'McpServer')+ }+ if (method === 'startContextWatch') {+ vi.spyOn(watcher as any, method).mockRejectedValue(new Error(`${method} unavailable`))+ } else if (method !== 'startMcpServerWatch') {+ stubAuthoritativeInventoryWatch(watcher, 'Context')+ }+ if (method === 'startSharedFileSystemWatch') {+ vi.spyOn(watcher as any, method).mockRejectedValue(new Error(`${method} unavailable`))+ } else {+ vi.spyOn(watcher as any, 'startSharedFileSystemWatch').mockResolvedValue(undefined)+ }+ if (method === 'startGlobalFileSystemWatch') {+ vi.spyOn(watcher as any, method).mockRejectedValue(new Error(`${method} unavailable`))+ } else {+ vi.spyOn(watcher as any, 'startGlobalFileSystemWatch').mockResolvedValue(undefined)+ }+ vi.spyOn(watcher as any, 'startCommunicationChannelWatch').mockResolvedValue(undefined)- await expect(watcher.start()).rejects.toThrow('watch unavailable')- watcher.stop()- })+ await expect(watcher.start()).rejects.toThrow(`${method} unavailable`)+ await watcher.stop()+ }+ )it('applies the request deadline wrapper to the finite Host inventory LIST', async () => {mocks.listNamespacedCustomObject.mockImplementation(async ({ plural }: { plural: string }) => {@@ -865,6 +1824,33 @@ describe('McpServerWatcher startup', () => {])})+ it('preserves observed GlobalFileSystem status from the Kubernetes inventory boundary', async () => {+ const status = {+ phase: 'Ready',+ pvcName: 'gfs-drive',+ serviceName: 'gfsc',+ serviceUrl: 'http://gfsc.gfs.svc.cluster.local:8087',+ }+ mocks.listNamespacedCustomObject.mockImplementation(async ({ plural }: { plural: string }) => {+ if (plural === 'globalfilesystems') {+ return {+ items: [+ {+ metadata: { name: 'gfs', namespace: 'gfs' },+ spec: {},+ status,+ },+ ],+ }+ }+ return { items: [] }+ })++ await expect(listAllGlobalFileSystems()).resolves.toEqual([+ expect.objectContaining({ name: 'gfs', namespace: 'gfs', status }),+ ])+ })+it('reconciles startup external egress before runtime full reconciliation', async () => {const eventLog: string[] = []const server = {@@ -889,17 +1875,24 @@ describe('McpServerWatcher startup', () => {mocks.ensureDefaultPolicies.mockImplementation(async () => {eventLog.push('defaults')})- mocks.serverFullReconcile.mockImplementation(async () => {- eventLog.push('runtime')- })-const watcher = new McpServerWatcher()+ const reconciler = (watcher as any).reconciler+ mocks.serverFullReconcile.mockImplementation(async (servers, options) => {+ await Promise.all(+ servers.map((selected: { name: string }) =>+ options.runEffect(selected.name, async () => {+ eventLog.push('runtime')+ await reconciler.reconcile(selected)+ })+ )+ )+ })const netPol = (watcher as any).netPolReconcilernetPol.reconcileExternalEgress.mockImplementation(async () => {eventLog.push('egress')})- vi.spyOn(watcher as any, 'startMcpServerWatch').mockImplementation(async () => undefined)- vi.spyOn(watcher as any, 'startContextWatch').mockImplementation(async () => undefined)+ stubAuthoritativeInventoryWatch(watcher, 'McpServer')+ stubAuthoritativeInventoryWatch(watcher, 'Context')vi.spyOn(watcher as any, 'startSharedFileSystemWatch').mockImplementation(async () => undefined)vi.spyOn(watcher as any, 'startGlobalFileSystemWatch').mockImplementation(async () => undefined)vi.spyOn(watcher as any, 'startCommunicationChannelWatch').mockImplementation(@@ -908,11 +1901,12 @@ describe('McpServerWatcher startup', () => {await watcher.start()- await vi.waitFor(() => expect(mocks.serverFullReconcile).toHaveBeenCalledOnce())+ await vi.waitFor(() => expect(eventLog).toContain('runtime'))expect(eventLog.slice(0, 3)).toEqual(['defaults', 'egress', 'runtime'])- expect(mocks.serverFullReconcile).toHaveBeenCalledWith([- expect.objectContaining({ name: 'web-search' }),- ])+ expect(mocks.serverFullReconcile).toHaveBeenCalledWith(+ [expect.objectContaining({ name: 'web-search' })],+ { runEffect: expect.any(Function) }+ )watcher.stop()})@@ -940,12 +1934,20 @@ describe('McpServerWatcher startup', () => {})const watcher = new McpServerWatcher()+ const reconciler = (watcher as any).reconciler+ mocks.serverFullReconcile.mockImplementation(async (servers, options) => {+ await Promise.all(+ servers.map((selected: { name: string }) =>+ options.runEffect(selected.name, () => reconciler.reconcile(selected))+ )+ )+ })const netPol = (watcher as any).netPolReconcilernetPol.reconcileExternalEgress.mockRejectedValueOnce(new Error('dns resolution failed'))const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {})const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {})- vi.spyOn(watcher as any, 'startMcpServerWatch').mockImplementation(async () => undefined)- vi.spyOn(watcher as any, 'startContextWatch').mockImplementation(async () => undefined)+ stubAuthoritativeInventoryWatch(watcher, 'McpServer')+ stubAuthoritativeInventoryWatch(watcher, 'Context')vi.spyOn(watcher as any, 'startSharedFileSystemWatch').mockImplementation(async () => undefined)vi.spyOn(watcher as any, 'startGlobalFileSystemWatch').mockImplementation(async () => undefined)vi.spyOn(watcher as any, 'startCommunicationChannelWatch').mockImplementation(@@ -955,8 +1957,12 @@ describe('McpServerWatcher startup', () => {await watcher.start()await vi.waitFor(() => expect(mocks.serverFullReconcile).toHaveBeenCalledOnce())- expect(mocks.serverFullReconcile).toHaveBeenCalledWith([])+ expect(mocks.serverFullReconcile).toHaveBeenCalledWith(+ [expect.objectContaining({ name: 'web-search' })],+ { runEffect: expect.any(Function) }+ )expect(netPol.reconcileExternalEgress).toHaveBeenCalledTimes(1)+ expect(reconciler.reconcile).not.toHaveBeenCalled()watcher.stop()errorSpy.mockRestore()@@ -964,6 +1970,29 @@ describe('McpServerWatcher startup', () => {})})+describe('getContext error semantics', () => {+ beforeEach(() => {+ vi.clearAllMocks()+ })++ it('preserves not-found semantics only for an authoritative 404', async () => {+ mocks.getNamespacedCustomObject.mockRejectedValueOnce(+ Object.assign(new Error('context absent'), { code: 404 })+ )++ await expect(getContext('missing-context')).resolves.toBeNull()+ })++ it('propagates non-404 API failures instead of converting discovery to an empty fleet', async () => {+ const unavailable = Object.assign(new Error('apiserver unavailable'), {+ response: { statusCode: 503 },+ })+ mocks.getNamespacedCustomObject.mockRejectedValueOnce(unavailable)++ await expect(getContext('production-context')).rejects.toBe(unavailable)+ })+})+describe('McpServerWatcher external egress retries', () => {const serverObject = {metadata: { name: 'redis-tools', namespace: 'mcp-server' },@@ -988,24 +2017,74 @@ describe('McpServerWatcher external egress retries', () => {const watcher = new McpServerWatcher()const netPol = (watcher as any).netPolReconcilerconst reconciler = (watcher as any).reconciler- netPol.reconcileExternalEgress.mockRejectedValueOnce(new Error('api temporarily unavailable'))- netPol.reconcileExternalEgress.mockResolvedValue(undefined)+ const bindingReconciler = (watcher as any).bindingReconciler+ const serverWithBindings = {+ ...serverObject,+ metadata: {+ ...serverObject.metadata,+ annotations: {+ 'clerum.io/recipe-bindings': JSON.stringify([+ { source: 'redis-tools', target: 'downstream' },+ ]),+ },+ },+ }+ ;(watcher as any).contexts.set('context1', {+ name: 'context1',+ namespace: 'mcp-server',+ spec: { contextId: 'context1', mcpServers: ['redis-tools'] },+ })+ netPol.reconcileExternalEgress.mockRejectedValueOnce(new Error('api temporarily unavailable'))+ netPol.reconcileExternalEgress.mockResolvedValue(undefined)+ vi.spyOn(console, 'error').mockImplementation(() => {})+ vi.spyOn(console, 'warn').mockImplementation(() => {})++ const watchCallback = (watcher as any).getMcpServerWatchCallback()+ await watchCallback('ADDED', serverWithBindings)++ expect(netPol.reconcileExternalEgress).toHaveBeenCalledTimes(1)+ expect(bindingReconciler.reconcileBindings).not.toHaveBeenCalled()+ expect(netPol.reconcileContext).not.toHaveBeenCalled()++ await vi.advanceTimersByTimeAsync(5000)++ expect(netPol.reconcileExternalEgress).toHaveBeenCalledTimes(2)+ expect(reconciler.reconcile).toHaveBeenCalledTimes(1)+ expect(reconciler.reconcile).toHaveBeenCalledWith(+ expect.objectContaining({ name: 'redis-tools' })+ )+ expect(bindingReconciler.reconcileBindings).toHaveBeenCalledTimes(1)+ expect(netPol.reconcileContext).toHaveBeenCalledWith(+ expect.objectContaining({+ spec: expect.objectContaining({ contextId: 'context1' }),+ })+ )++ watcher.stop()+ })++ it('retries the complete pipeline when a no-egress runtime reconcile fails', async () => {+ const watcher = new McpServerWatcher()+ const reconciler = (watcher as any).reconciler+ const noEgressServer = {+ ...serverObject,+ spec: {+ ...serverObject.spec,+ egressBindings: undefined,+ },+ }+ reconciler.reconcile+ .mockRejectedValueOnce(new Error('deployment temporarily unavailable'))+ .mockResolvedValue(undefined)vi.spyOn(console, 'error').mockImplementation(() => {})vi.spyOn(console, 'warn').mockImplementation(() => {})- const watchCallback = (watcher as any).getMcpServerWatchCallback()- await watchCallback('ADDED', serverObject)-- expect(netPol.reconcileExternalEgress).toHaveBeenCalledTimes(1)+ await (watcher as any).getMcpServerWatchCallback()('ADDED', noEgressServer)+ expect(reconciler.reconcile).toHaveBeenCalledTimes(1)await vi.advanceTimersByTimeAsync(5000)- expect(netPol.reconcileExternalEgress).toHaveBeenCalledTimes(2)- expect(reconciler.reconcile).toHaveBeenCalledTimes(1)- expect(reconciler.reconcile).toHaveBeenCalledWith(- expect.objectContaining({ name: 'redis-tools' })- )-+ expect(reconciler.reconcile).toHaveBeenCalledTimes(2)watcher.stop()})@@ -1069,7 +2148,7 @@ describe('McpServerWatcher external egress retries', () => {watcher.stop()})- it('does not let periodic external egress resync cancel a pending runtime retry', async () => {+ it('continues a pending runtime pipeline during periodic external egress resync', async () => {const watcher = new McpServerWatcher()const netPol = (watcher as any).netPolReconcilerconst reconciler = (watcher as any).reconciler@@ -1079,6 +2158,7 @@ describe('McpServerWatcher external egress retries', () => {vi.spyOn(console, 'error').mockImplementation(() => {})vi.spyOn(console, 'warn').mockImplementation(() => {})vi.spyOn(console, 'log').mockImplementation(() => {})+ vi.spyOn(Math, 'random').mockReturnValue(0)const watchCallback = (watcher as any).getMcpServerWatchCallback()await watchCallback('ADDED', serverObject)@@ -1088,16 +2168,113 @@ describe('McpServerWatcher external egress retries', () => {await (watcher as any).runExternalEgressResync()- expect(netPol.reconcileExternalEgress).toHaveBeenCalledTimes(1)+ expect(netPol.reconcileExternalEgress).toHaveBeenCalledTimes(2)+ expect(reconciler.reconcile).toHaveBeenCalledTimes(2)await vi.advanceTimersByTimeAsync(5000)-expect(netPol.reconcileExternalEgress).toHaveBeenCalledTimes(2)expect(reconciler.reconcile).toHaveBeenCalledTimes(2)watcher.stop()})+ it('keeps retrying an ADDED pipeline at the capped delay until it recovers', async () => {+ const watcher = new McpServerWatcher()+ const netPol = (watcher as any).netPolReconciler+ const reconciler = (watcher as any).reconciler+ netPol.reconcileExternalEgress+ .mockRejectedValueOnce(new Error('initial outage'))+ .mockRejectedValueOnce(new Error('outage after 5s'))+ .mockRejectedValueOnce(new Error('outage after 15s'))+ .mockRejectedValueOnce(new Error('outage after 30s'))+ .mockResolvedValue(undefined)+ vi.spyOn(console, 'error').mockImplementation(() => {})+ vi.spyOn(console, 'warn').mockImplementation(() => {})++ await (watcher as any).getMcpServerWatchCallback()('ADDED', serverObject)+ await vi.advanceTimersByTimeAsync(5000)+ await vi.advanceTimersByTimeAsync(15000)+ await vi.advanceTimersByTimeAsync(30000)++ expect(netPol.reconcileExternalEgress).toHaveBeenCalledTimes(4)+ expect(reconciler.reconcile).not.toHaveBeenCalled()++ await vi.advanceTimersByTimeAsync(30000)++ expect(netPol.reconcileExternalEgress).toHaveBeenCalledTimes(5)+ expect(reconciler.reconcile).toHaveBeenCalledTimes(1)+ watcher.stop()+ })++ it('keeps retrying a partial DELETE pipeline at the capped delay until it recovers', async () => {+ const watcher = new McpServerWatcher()+ ;(watcher as any).mcpServerCacheSynced = true+ const netPol = (watcher as any).netPolReconciler+ const reconciler = (watcher as any).reconciler+ const bindingReconciler = (watcher as any).bindingReconciler+ netPol.cleanupExternalEgress+ .mockRejectedValueOnce(new Error('initial cleanup outage'))+ .mockRejectedValueOnce(new Error('cleanup outage after 5s'))+ .mockRejectedValueOnce(new Error('cleanup outage after 15s'))+ .mockRejectedValueOnce(new Error('cleanup outage after 30s'))+ .mockResolvedValue(undefined)+ vi.spyOn(console, 'error').mockImplementation(() => {})+ vi.spyOn(console, 'warn').mockImplementation(() => {})++ await (watcher as any).getMcpServerWatchCallback()('DELETED', serverObject)+ await vi.advanceTimersByTimeAsync(5000)+ await vi.advanceTimersByTimeAsync(15000)+ await vi.advanceTimersByTimeAsync(30000)++ expect(netPol.cleanupExternalEgress).toHaveBeenCalledTimes(4)+ expect(reconciler.reconcileDelete).not.toHaveBeenCalled()+ expect(bindingReconciler.cleanupBindings).not.toHaveBeenCalled()++ await vi.advanceTimersByTimeAsync(30000)++ expect(netPol.cleanupExternalEgress).toHaveBeenCalledTimes(5)+ expect(reconciler.reconcileDelete).toHaveBeenCalledWith('redis-tools', 'mcp-server')+ expect(bindingReconciler.cleanupBindings).toHaveBeenCalledWith('redis-tools')+ watcher.stop()+ })++ it('bounds concurrent durable retries across McpServers', async () => {+ const watcher = new McpServerWatcher()+ const reconciler = (watcher as any).reconciler+ const release = deferred()+ let active = 0+ let maxActive = 0+ reconciler.reconcile.mockImplementation(async () => {+ active += 1+ maxActive = Math.max(maxActive, active)+ await release.promise+ active -= 1+ })+ vi.spyOn(console, 'warn').mockImplementation(() => {})++ for (let index = 0; index < 11; index += 1) {+ const server = {+ name: `server-${index}`,+ namespace: 'mcp-server',+ spec: {+ ...serverObject.spec,+ egressBindings: undefined,+ },+ }+ ;(watcher as any).servers.set(server.name, server)+ ;(watcher as any).scheduleExternalEgressRetry('ADDED', server)+ }++ await vi.advanceTimersByTimeAsync(5000)+ await flushMicrotasks()++ expect(maxActive).toBe(10)++ release.resolve(undefined)+ await flushMicrotasks()+ watcher.stop()+ })+it('reconciles external egress before runtime reconciliation on ADDED events', async () => {const watcher = new McpServerWatcher()const netPol = (watcher as any).netPolReconciler@@ -1136,7 +2313,10 @@ describe('McpServerWatcher external egress retries', () => {it('retries failed external egress cleanup from a DELETED event', async () => {const watcher = new McpServerWatcher()+ ;(watcher as any).mcpServerCacheSynced = trueconst netPol = (watcher as any).netPolReconciler+ const reconciler = (watcher as any).reconciler+ const bindingReconciler = (watcher as any).bindingReconcilernetPol.cleanupExternalEgress.mockRejectedValueOnce(new Error('delete temporarily unavailable'))netPol.cleanupExternalEgress.mockResolvedValue(undefined)vi.spyOn(console, 'error').mockImplementation(() => {})@@ -1150,11 +2330,234 @@ describe('McpServerWatcher external egress retries', () => {await vi.advanceTimersByTimeAsync(5000)expect(netPol.cleanupExternalEgress).toHaveBeenCalledTimes(2)- expect(netPol.cleanupExternalEgress).toHaveBeenLastCalledWith('redis-tools', 'mcp-server')+ expect(netPol.cleanupExternalEgress).toHaveBeenLastCalledWith(+ 'redis-tools',+ 'mcp-server',+ undefined,+ expect.any(Function)+ )+ expect(reconciler.reconcileDelete).toHaveBeenCalledWith('redis-tools', 'mcp-server')+ expect(bindingReconciler.cleanupBindings).toHaveBeenCalledWith('redis-tools')++ watcher.stop()+ })++ it('retires queued McpServer work immediately when its watch ends', async () => {+ const blockerStarted = deferred()+ const releaseBlocker = deferred()+ let watchCallback: ((type: string, apiObj: typeof serverObject) => Promise<void>) | undefined+ let watchDone: ((error: Error | null) => void) | undefined+ mocks.watch.mockImplementationOnce(async (_path, _options, callback, done) => {+ watchCallback = callback+ watchDone = done+ return { abort: vi.fn() }+ })+ const watcher = new McpServerWatcher()+ const netPol = (watcher as any).netPolReconciler+ await (watcher as any).startMcpServerWatch('mcp-watch-rv')+ const blocker = (watcher as any).enqueueMcpServerReconciliation(+ { name: 'redis-tools', namespace: 'mcp-server' },+ async () => {+ blockerStarted.resolve(undefined)+ await releaseBlocker.promise+ }+ )+ await blockerStarted.promise++ const event = watchCallback!('ADDED', serverObject)+ watchDone!(null)+ releaseBlocker.resolve(undefined)+ await Promise.all([blocker, event])++ expect(netPol.reconcileExternalEgress).not.toHaveBeenCalled()+ await watcher.stop()+ })++ it('retries the recreated server when an older DELETE retry timer already owns the key', async () => {+ const deletedServer = {+ metadata: {+ name: 'redis-tools',+ namespace: 'mcp-server',+ uid: 'redis-tools-old-uid',+ generation: 1,+ },+ spec: serverObject.spec,+ }+ const recreatedServer = {+ metadata: {+ name: 'redis-tools',+ namespace: 'mcp-server',+ uid: 'redis-tools-new-uid',+ generation: 1,+ },+ spec: { ...serverObject.spec, image: 'redis-tools:recreated' },+ }+ const watcher = new McpServerWatcher()+ ;(watcher as any).mcpServerCacheSynced = true+ const netPol = (watcher as any).netPolReconciler+ const reconciler = (watcher as any).reconciler+ netPol.cleanupExternalEgress.mockRejectedValueOnce(new Error('cleanup unavailable'))+ netPol.reconcileExternalEgress+ .mockRejectedValueOnce(new Error('recreated policy unavailable'))+ .mockResolvedValue(undefined)+ vi.spyOn(console, 'error').mockImplementation(() => {})+ vi.spyOn(console, 'warn').mockImplementation(() => {})+ const watchCallback = (watcher as any).getMcpServerWatchCallback()++ await watchCallback('DELETED', deletedServer)+ await watchCallback('ADDED', recreatedServer)+ await vi.advanceTimersByTimeAsync(5000)++ expect(netPol.cleanupExternalEgress).toHaveBeenCalledTimes(1)+ expect(netPol.reconcileExternalEgress).toHaveBeenCalledTimes(2)+ expect(reconciler.reconcile).toHaveBeenCalledOnce()+ expect(reconciler.reconcile).toHaveBeenCalledWith(+ expect.objectContaining({+ uid: 'redis-tools-new-uid',+ generation: 1,+ spec: expect.objectContaining({ image: 'redis-tools:recreated' }),+ })+ )++ watcher.stop()+ })++ it('retries the latest DELETE cleanup when an older ADD retry timer already owns the key', async () => {+ const server = {+ metadata: {+ name: 'redis-tools',+ namespace: 'mcp-server',+ uid: 'redis-tools-uid',+ generation: 3,+ },+ spec: serverObject.spec,+ }+ const watcher = new McpServerWatcher()+ ;(watcher as any).mcpServerCacheSynced = true+ const netPol = (watcher as any).netPolReconciler+ netPol.reconcileExternalEgress.mockRejectedValueOnce(new Error('policy unavailable'))+ netPol.cleanupExternalEgress+ .mockRejectedValueOnce(new Error('cleanup unavailable'))+ .mockResolvedValue(undefined)+ vi.spyOn(console, 'error').mockImplementation(() => {})+ vi.spyOn(console, 'warn').mockImplementation(() => {})+ const watchCallback = (watcher as any).getMcpServerWatchCallback()++ await watchCallback('ADDED', server)+ await watchCallback('DELETED', server)+ await vi.advanceTimersByTimeAsync(5000)++ expect(netPol.reconcileExternalEgress).toHaveBeenCalledTimes(1)+ expect(netPol.cleanupExternalEgress).toHaveBeenCalledTimes(2)++ watcher.stop()+ })++ it('does not continue to runtime or bindings after stop releases a live DNS hold', async () => {+ const egressStarted = deferred()+ const releaseEgress = deferred()+ const server = {+ metadata: {+ name: 'redis-tools',+ namespace: 'mcp-server',+ uid: 'redis-tools-uid',+ generation: 1,+ annotations: {+ 'clerum.io/recipe-bindings': JSON.stringify([+ { source: 'redis-tools', target: 'downstream' },+ ]),+ },+ },+ spec: serverObject.spec,+ }+ const watcher = new McpServerWatcher()+ const netPol = (watcher as any).netPolReconciler+ const reconciler = (watcher as any).reconciler+ const bindingReconciler = (watcher as any).bindingReconciler+ netPol.reconcileExternalEgress.mockImplementationOnce(async () => {+ egressStarted.resolve(undefined)+ await releaseEgress.promise+ })+ const watchCallback = (watcher as any).getMcpServerWatchCallback()++ const reconcile = watchCallback('ADDED', server)+ await egressStarted.promise+ await watcher.stop()+ releaseEgress.resolve(undefined)+ await reconcile++ expect(reconciler.reconcile).not.toHaveBeenCalled()+ expect(bindingReconciler.reconcileBindings).not.toHaveBeenCalled()+ })++ it('does not run an older runtime revision after newer desired state arrives during egress', async () => {+ const egressStarted = deferred()+ const releaseEgress = deferred()+ const oldServer = {+ metadata: {+ name: 'redis-tools',+ namespace: 'mcp-server',+ uid: 'redis-tools-uid',+ generation: 1,+ },+ spec: { ...serverObject.spec, image: 'redis-tools:old' },+ }+ const newServer = {+ metadata: {+ name: 'redis-tools',+ namespace: 'mcp-server',+ uid: 'redis-tools-uid',+ generation: 2,+ },+ spec: { ...serverObject.spec, image: 'redis-tools:new' },+ }+ const watcher = new McpServerWatcher()+ const netPol = (watcher as any).netPolReconciler+ const reconciler = (watcher as any).reconciler+ netPol.reconcileExternalEgress+ .mockImplementationOnce(async () => {+ egressStarted.resolve(undefined)+ await releaseEgress.promise+ })+ .mockResolvedValue(undefined)+ const watchCallback = (watcher as any).getMcpServerWatchCallback()++ const oldReconcile = watchCallback('ADDED', oldServer)+ await egressStarted.promise+ const newReconcile = watchCallback('MODIFIED', newServer)+ releaseEgress.resolve(undefined)+ await Promise.all([oldReconcile, newReconcile])++ expect(reconciler.reconcile).toHaveBeenCalledOnce()+ expect(reconciler.reconcile).toHaveBeenCalledWith(+ expect.objectContaining({+ generation: 2,+ spec: expect.objectContaining({ image: 'redis-tools:new' }),+ })+ )watcher.stop()})+ it('does not resume periodic external egress work from jitter after stop', async () => {+ const watcher = new McpServerWatcher()+ const netPol = (watcher as any).netPolReconciler+ ;(watcher as any).servers.set('redis-tools', {+ name: 'redis-tools',+ namespace: 'mcp-server',+ spec: serverObject.spec,+ })+ vi.spyOn(Math, 'random').mockReturnValue(0.5)++ const resync = (watcher as any).runExternalEgressResync()+ await flushMicrotasks()+ await watcher.stop()+ await vi.advanceTimersByTimeAsync(2500)+ await resync++ expect(netPol.reconcileExternalEgress).not.toHaveBeenCalled()+ })+it('periodic resync reuses external egress reconciliation for cached servers with bindings', async () => {const watcher = new McpServerWatcher()const netPol = (watcher as any).netPolReconciler@@ -1225,6 +2628,26 @@ describe('McpServerWatcher external egress retries', () => {warn.mockRestore()watcher.stop()})++ it('does not start another external egress mutation after stop releases an in-flight wait', async () => {+ const watcher = new McpServerWatcher()+ const netPol = (watcher as any).netPolReconciler+ const server = {+ name: 'redis-tools',+ namespace: 'mcp-server',+ spec: serverObject.spec,+ }+ const existing = deferred()+ ;(watcher as any).externalEgressInFlight.set('mcp-server/redis-tools', existing.promise)++ const run = (watcher as any).runExternalEgressOnce('MODIFIED', server)+ await flushMicrotasks()+ await watcher.stop()+ existing.resolve(undefined)+ await run++ expect(netPol.reconcileExternalEgress).not.toHaveBeenCalled()+ })})describe('McpServerWatcher.countCommunicationChannels', () => {@@ -1412,8 +2835,8 @@ describe('McpServerWatcher.start ordering (#281 R6-bis)', () => {})const watcher = new McpServerWatcher()- vi.spyOn(watcher as any, 'startMcpServerWatch').mockResolvedValue(undefined)- vi.spyOn(watcher as any, 'startContextWatch').mockResolvedValue(undefined)+ stubAuthoritativeInventoryWatch(watcher, 'McpServer')+ stubAuthoritativeInventoryWatch(watcher, 'Context')vi.spyOn(watcher as any, 'startSharedFileSystemWatch').mockResolvedValue(undefined)vi.spyOn(watcher as any, 'startGlobalFileSystemWatch').mockResolvedValue(undefined)const ccWatchSpy = vi.spyOn(watcher as any, 'startCommunicationChannelWatch')@@ -1452,8 +2875,8 @@ describe('McpServerWatcher.start ordering (#281 R6-bis)', () => {const watcher = new McpServerWatcher()- vi.spyOn(watcher as any, 'startMcpServerWatch').mockResolvedValue(undefined)- vi.spyOn(watcher as any, 'startContextWatch').mockResolvedValue(undefined)+ stubAuthoritativeInventoryWatch(watcher, 'McpServer')+ stubAuthoritativeInventoryWatch(watcher, 'Context')vi.spyOn(watcher as any, 'startSharedFileSystemWatch').mockResolvedValue(undefined)vi.spyOn(watcher as any, 'startGlobalFileSystemWatch').mockResolvedValue(undefined)const ccWatchSpy = vi@@ -2253,8 +3676,8 @@ describe('McpServerWatcher CommunicationChannel cache recovery', () => {activePasses -= 1})const watcher = new McpServerWatcher()- vi.spyOn(watcher as any, 'startMcpServerWatch').mockResolvedValue(undefined)- vi.spyOn(watcher as any, 'startContextWatch').mockResolvedValue(undefined)+ stubAuthoritativeInventoryWatch(watcher, 'McpServer')+ stubAuthoritativeInventoryWatch(watcher, 'Context')vi.spyOn(watcher as any, 'startSharedFileSystemWatch').mockResolvedValue(undefined)vi.spyOn(watcher as any, 'startGlobalFileSystemWatch').mockResolvedValue(undefined)vi.spyOn(watcher as any, 'scheduleCommunicationChannelCacheRecovery').mockImplementation(@@ -2446,6 +3869,50 @@ describe('McpServerWatcher Host periodic resync serialization', () => {expect(mocks.hostFullReconcile).toHaveBeenCalledTimes(1)})+ it('queues a trailing full Host pass when Context recovery lands during an active pass', async () => {+ vi.clearAllMocks()+ const activePass = deferred()+ mocks.hostFullReconcile+ .mockReset()+ .mockImplementationOnce(() => activePass.promise)+ .mockResolvedValue(undefined)+ mocks.listNamespacedCustomObject.mockImplementation(async ({ plural }: { plural: string }) => {+ if (plural === 'contexts') {+ return {+ metadata: { resourceVersion: 'recovered-context-rv' },+ items: [+ {+ metadata: { name: 'recovered-context', namespace: 'mcp-server' },+ spec: {+ contextId: 'recovered-context',+ mcpServers: [],+ sharedFileSystems: [{ name: 'recovered-sfs' }],+ },+ },+ ],+ }+ }+ return { items: [] }+ })+ mocks.watch.mockReset().mockResolvedValue({ abort: vi.fn() })+ const watcher = new McpServerWatcher()+ ;(watcher as any).hostCacheSynced = true++ const first = (watcher as any).requestHostFleetReconcile(+ 'before Context recovery'+ ) as Promise<void>+ await vi.waitFor(() => expect(mocks.hostFullReconcile).toHaveBeenCalledTimes(1))++ await expect((watcher as any).recoverContextInventoryAndWatch()).resolves.toBe(true)+ expect(mocks.hostFullReconcile).toHaveBeenCalledTimes(1)++ activePass.resolve(undefined)+ await first+ await vi.waitFor(() => expect(mocks.hostFullReconcile).toHaveBeenCalledTimes(2))++ await watcher.stop()+ })+it('does not invent another fleet transition during a failed periodic cache recovery', async () => {vi.clearAllMocks()const watcher = new McpServerWatcher()@@ -2464,6 +3931,33 @@ describe('McpServerWatcher Host periodic resync serialization', () => {watcher.stop()})+ it('coalesces the newest Host input revision into the serialized trailing pass', async () => {+ vi.clearAllMocks()+ const watcher = new McpServerWatcher()+ const activePass = deferred()+ const requests: Array<{ inputRevision: number }> = []+ vi.spyOn(watcher as any, 'performHostFleetReconcile').mockImplementation(+ async (...args: unknown[]) => {+ const request = args[0] as { inputRevision: number }+ requests.push({ ...request })+ if (requests.length === 1) await activePass.promise+ }+ )+ ;(watcher as any).hostFleetInputRevision = 1+ const first = (watcher as any).requestHostFleetReconcile('active') as Promise<void>+ ;(watcher as any).hostFleetInputRevision = 2+ const second = (watcher as any).requestHostFleetReconcile('pending-v2') as Promise<void>+ ;(watcher as any).hostFleetInputRevision = 3+ const third = (watcher as any).requestHostFleetReconcile('pending-v3') as Promise<void>++ activePass.resolve(undefined)+ await Promise.all([first, second, third])++ expect(requests).toHaveLength(2)+ expect(requests[1].inputRevision).toBe(3)+ watcher.stop()+ })+it('collapses overlapping fleet requests into one serialized trailing pass', async () => {vi.clearAllMocks()const fleetV1 = [diff --git a/host-context-controller/src/k8sClient.ts b/host-context-controller/src/k8sClient.tsindex 14f466e7b..a7cd77fc7 100644--- a/host-context-controller/src/k8sClient.ts+++ b/host-context-controller/src/k8sClient.ts@@ -30,6 +30,11 @@ import {import { K8sGfsApi } from './k8s/gfsK8sApi'import { makeHostK8sApiClient } from './k8s/hostK8sApiClient'import { pvcName as sfsPvcName } from './k8s/sharedFileSystemFactory'+import {+ confirmAuthoritativeMcpServerAbsence,+ isMcpServerStatusOnlyUpdate,+ sameMcpServerDesiredRevision,+} from './mcpServerSafety'import { hostDeleteCleanupTotal, hostFleetRequestsTotal, hostWatchRecoverySeconds } from './metrics'import { NetworkPolicyReconciler } from './networkPolicyReconciler'import { McpServerReconciler } from './reconciler'@@ -48,6 +53,7 @@ import {SharedFileSystemCRD,SharedFileSystemSpec,} from './types'+import { getErrorCode } from './utils'// Only initialize K8s client if not in dev modelet customObjectsApi: k8s.CustomObjectsApi | null = null@@ -90,6 +96,7 @@ const EXTERNAL_EGRESS_RESYNC_JITTER_MS = 5000// sweep made provider.start() fail and Kubernetes restarted HCC. These retries// retain that convergence guarantee now that the sweeps run in the background.const INITIAL_CONVERGENCE_RETRY_DELAYS_MS = [5000, 15000, 30000, 60000, 300000]+const INVENTORY_CACHE_RECOVERY_RETRY_MS = 5000const COMMUNICATION_CHANNEL_CACHE_RECOVERY_RETRY_MS = 5000const COMMUNICATION_CHANNEL_FLEET_RETRY_DELAYS_MS = [5000, 15000, 30000, 60000, 300000]const HOST_CACHE_RECOVERY_RETRY_MS = 5000@@ -103,13 +110,25 @@ type CommunicationChannelSnapshot = {resourceVersion?: string}+type McpServerSnapshot = {+ servers: McpServerCRD[]+ resourceVersion?: string+}++type ContextSnapshot = {+ contexts: ContextCRD[]+ resourceVersion?: string+}+type HostSnapshot = {hosts: HostCRD[]resourceVersion?: string}type HostFleetReconcileMode = 'full' | 'lifecycle'+type HostInventoryRecoveryCause = 'cold-start' | 'watch-recovery'type HostWatchEventType = 'ADDED' | 'MODIFIED' | 'DELETED'+type McpServerWatchEventType = 'ADDED' | 'MODIFIED' | 'DELETED'type InitialConvergenceLane = 'McpServer' | 'NetworkPolicy'/**@@ -132,10 +151,42 @@ class SerializedReconciliationQueue {}}+type KeyedReconciliationQueue = {+ queue: SerializedReconciliationQueue+ references: number+}++class AsyncConcurrencyLimiter {+ private active = 0+ private readonly waiters: Array<() => void> = []++ constructor(private readonly limit: number) {}++ async run<T>(work: () => Promise<T>): Promise<T> {+ if (this.active >= this.limit) {+ await new Promise<void>(resolve => this.waiters.push(resolve))+ }+ this.active += 1+ try {+ return await work()+ } finally {+ this.active -= 1+ this.waiters.shift()?.()+ }+ }+}++type ExternalEgressRetryIntent = {+ sequence: number+ type: McpServerWatchEventType+ server: McpServerCRD+}+type HostFleetReconcileRequest = {reason: stringmode: HostFleetReconcileModeccLifecycleGeneration?: number+ inputRevision: number}type PendingHostFleetReconcile = HostFleetReconcileRequest & {@@ -151,6 +202,7 @@ function hostFleetRequestCovers(): boolean {const modeCovered = active.mode === 'full' || requested.mode === 'lifecycle'if (!modeCovered) return false+ if (active.inputRevision !== requested.inputRevision) return falseif (requested.ccLifecycleGeneration === undefined) return truereturn active.ccLifecycleGeneration === requested.ccLifecycleGeneration}@@ -164,6 +216,7 @@ function mergeHostFleetRequests(return {reason: requested.reason,mode: pending.mode === 'full' || requested.mode === 'full' ? 'full' : 'lifecycle',+ inputRevision: Math.max(pending.inputRevision, requested.inputRevision),ccLifecycleGeneration:pendingGeneration === undefined? requestedGeneration@@ -211,7 +264,7 @@ export interface McpServerProvider {/*** List all McpServer CRDs in the namespace.*/-export async function listAllMcpServers(): Promise<McpServerCRD[]> {+async function listMcpServerSnapshot(): Promise<McpServerSnapshot> {if (!customObjectsApi) {throw new Error('K8s client not initialized - are you in dev mode?')}@@ -227,6 +280,7 @@ export async function listAllMcpServers(): Promise<McpServerCRD[]> {})const list = response as {+ metadata?: { resourceVersion?: string }items: Array<{metadata: {name: string@@ -253,17 +307,21 @@ export async function listAllMcpServers(): Promise<McpServerCRD[]> {}))console.log(`[K8s] Found ${servers.length} McpServer(s)`)- return servers+ return { servers, resourceVersion: list.metadata?.resourceVersion }} catch (error) {console.error('[K8s] Failed to list McpServers:', error)throw error}}+export async function listAllMcpServers(): Promise<McpServerCRD[]> {+ return (await listMcpServerSnapshot()).servers+}+/*** List all Context CRDs in the namespace.*/-export async function listAllContexts(): Promise<ContextCRD[]> {+async function listContextSnapshot(): Promise<ContextSnapshot> {if (!customObjectsApi) {throw new Error('K8s client not initialized - are you in dev mode?')}@@ -279,6 +337,7 @@ export async function listAllContexts(): Promise<ContextCRD[]> {})const list = response as {+ metadata?: { resourceVersion?: string }items: Array<{metadata: { name: string; namespace?: string }spec: ContextSpec@@ -292,13 +351,17 @@ export async function listAllContexts(): Promise<ContextCRD[]> {}))console.log(`[K8s] Found ${contexts.length} Context(s)`)- return contexts+ return { contexts, resourceVersion: list.metadata?.resourceVersion }} catch (error) {console.error('[K8s] Failed to list Contexts:', error)throw error}}+export async function listAllContexts(): Promise<ContextCRD[]> {+ return (await listContextSnapshot()).contexts+}+/*** List all Host CRDs in host namespace.*/@@ -452,12 +515,17 @@ export async function listAllGlobalFileSystems(): Promise<GlobalFileSystemCRD[]>plural: PLURAL_GLOBALFILESYSTEMS,})const list = response as {- items: Array<{ metadata: { name: string; namespace?: string }; spec: GlobalFileSystemSpec }>+ items: Array<{+ metadata: { name: string; namespace?: string }+ spec: GlobalFileSystemSpec+ status?: GlobalFileSystemCRD['status']+ }>}return list.items.map(item => ({name: item.metadata.name,namespace: item.metadata.namespace || namespace,spec: item.spec,+ status: item.status,}))} catch (error) {console.error('[K8s] Failed to list GlobalFileSystems:', error)@@ -558,7 +626,7 @@ export async function getContext(contextId: string): Promise<ContextCRD | null>return null}console.error(`[K8s] Failed to read Context CRD:`, error)- return null+ throw error}}@@ -580,6 +648,14 @@ export class McpServerWatcher implements McpServerProvider {private sharedFileSystems: Map<string, SharedFileSystemCRD> = new Map()private globalFileSystems: Map<string, GlobalFileSystemCRD> = new Map()private communicationChannels: Map<string, CommunicationChannelCRD> = new Map()+ private mcpWatchGeneration = 0+ private contextWatchGeneration = 0+ private mcpServerCacheSynced = false+ private contextCacheSynced = false+ private mcpServerCacheRecoveryTimer: ReturnType<typeof setTimeout> | null = null+ private contextCacheRecoveryTimer: ReturnType<typeof setTimeout> | null = null+ private mcpServerCacheRecoveryInFlight: Promise<boolean> | null = null+ private contextCacheRecoveryInFlight: Promise<boolean> | null = null// A watch callback can still settle after its stream reports completion.// Host reconciles change the mcp-host pod template, so stale callbacks must// never replay an older Host spec after a replacement watch is active.@@ -610,6 +686,7 @@ export class McpServerWatcher implements McpServerProvider {private ccFleetRetryAttempt = 0private hostFleetReconcileInFlight: ActiveHostFleetReconcile | null = nullprivate hostFleetReconcilePending: PendingHostFleetReconcile | null = null+ private hostFleetInputRevision = 0private resolveHostFleetShutdown: () => void = () => {}private readonly hostFleetShutdown = new Promise<void>(resolve => {this.resolveHostFleetShutdown = resolve@@ -627,20 +704,24 @@ export class McpServerWatcher implements McpServerProvider {private readonly administrativeOutcomeReporter?: AdministrativeOutcomeReporterprivate readonly externalEgressRetryTimers = new Map<string, ReturnType<typeof setTimeout>>()private readonly externalEgressRetryAttempts = new Map<string, number>()+ private readonly externalEgressRetryIntents = new Map<string, ExternalEgressRetryIntent>()+ private externalEgressRetrySequence = 0+ private readonly externalEgressRetryLimiter = new AsyncConcurrencyLimiter(+ EXTERNAL_EGRESS_RESYNC_MAX_CONCURRENCY+ )private readonly externalEgressInFlight = new Map<string, Promise<void>>()+ private externalEgressResyncInFlight: Promise<void> | null = nullprivate readonly initialConvergenceRetryTimers = new Map<InitialConvergenceLane,ReturnType<typeof setTimeout>>()private readonly initialConvergenceRetryAttempts = new Map<InitialConvergenceLane, number>()- // An incomplete McpServer inventory must remain non-authoritative across a- // retry: promoting it would allow the NetworkPolicy full pass to delete- // external-egress policies for servers HCC has not successfully listed.- private initialNetworkPolicyRetryServerInventoryComplete: boolean | undefined- // Full reconciles in these domains perform fleet-wide orphan cleanup. Watch- // events and periodic resyncs therefore share an ordered effect stream with- // their initial pass; otherwise an older sweep could win after a newer event.- private readonly controlPlaneReconciliationQueue = new SerializedReconciliationQueue()+ // McpServer and Context effects serialize by resource identity, so one slow+ // fleet member cannot block unrelated live events while same-resource+ // updates still retain last-writer ordering. SFS/GFS keep their established+ // domain-wide queues.+ private readonly mcpServerReconciliationQueues = new Map<string, KeyedReconciliationQueue>()+ private readonly contextReconciliationQueues = new Map<string, KeyedReconciliationQueue>()private readonly sharedFileSystemReconciliationQueue = new SerializedReconciliationQueue()private readonly globalFileSystemReconciliationQueue = new SerializedReconciliationQueue()private sharedFileSystemCacheRevision = 0@@ -668,6 +749,11 @@ export class McpServerWatcher implements McpServerProvider {}this.watch = new k8s.Watch(kc)this.reconciler = new McpServerReconciler(kc)+ this.reconciler.setInventoryAuthority(() => ({+ known: this.mcpServerCacheSynced,+ generation: this.mcpWatchGeneration,+ }))+ this.reconciler.setResolveCurrentServer(name => this.servers.get(name))const infrastructureTelemetryReporter = config.controlApiBaseUrl? createInfrastructureTelemetryReporter(config.governedTracingEnabled, {baseUrl: config.controlApiBaseUrl,@@ -752,13 +838,168 @@ export class McpServerWatcher implements McpServerProvider {return this.ccCacheSynced}- private enqueueControlPlaneReconciliation(work: () => Promise<void>): Promise<void> {- return this.controlPlaneReconciliationQueue.enqueue(async () => {- if (this.stopped) return- await work()+ /**+ * Readiness authority covers the inventories that back HCC discovery,+ * Context policy decisions, and Host API/runtime ownership. Communication+ * Channel loss is intentionally excluded: that subsystem already fails safe+ * by preserving replicas and disabling stateless suspension until recovery.+ * SFS/GFS retain their established eventual-resync contract.+ */+ isReadinessInventoryAuthoritative(): boolean {+ return (+ !this.stopped && this.mcpServerCacheSynced && this.contextCacheSynced && this.hostCacheSynced+ )+ }++ private retireMcpServerWatch(expectedGeneration?: number): boolean {+ if (expectedGeneration !== undefined && expectedGeneration !== this.mcpWatchGeneration) {+ return false+ }+ this.mcpServerCacheSynced = false+ this.mcpWatchGeneration += 1+ this.mcpWatchRequest?.abort()+ this.mcpWatchRequest = null+ return true+ }++ private retireContextWatch(expectedGeneration?: number): boolean {+ if (expectedGeneration !== undefined && expectedGeneration !== this.contextWatchGeneration) {+ return false+ }+ this.contextCacheSynced = false+ this.contextWatchGeneration += 1+ this.ctxWatchRequest?.abort()+ this.ctxWatchRequest = null+ return true+ }++ private async enqueueKeyedReconciliation(+ queues: Map<string, KeyedReconciliationQueue>,+ key: string,+ work: () => Promise<void>+ ): Promise<void> {+ let entry = queues.get(key)+ if (!entry) {+ entry = { queue: new SerializedReconciliationQueue(), references: 0 }+ queues.set(key, entry)+ }+ entry.references+++ try {+ await entry.queue.enqueue(async () => {+ if (this.stopped) return+ await work()+ })+ } finally {+ entry.references--+ if (entry.references === 0 && queues.get(key) === entry) queues.delete(key)+ }+ }++ private enqueueMcpServerReconciliation(+ server: Pick<McpServerCRD, 'name' | 'namespace'>,+ work: () => Promise<void>+ ): Promise<void> {+ return this.enqueueKeyedReconciliation(+ this.mcpServerReconciliationQueues,+ `${server.namespace}/${server.name}`,+ work+ )+ }++ private enqueueContextReconciliation(+ contextId: string,+ work: () => Promise<void>+ ): Promise<void> {+ return this.enqueueKeyedReconciliation(this.contextReconciliationQueues, contextId, work)+ }++ private enqueueContextIdentityReconciliation(+ contextIds: string[],+ work: () => Promise<void>+ ): Promise<void> {+ const keys = [...new Set(contextIds)].sort()+ const enter = (index: number): Promise<void> => {+ const key = keys[index]+ if (!key) return work()+ return this.enqueueContextReconciliation(key, () => enter(index + 1))+ }+ return enter(0)+ }++ private async mcpServerAbsentForDelete(+ name: string,+ namespace: string,+ watchGeneration: number+ ): Promise<boolean> {+ if (!customObjectsApi) return false+ return confirmAuthoritativeMcpServerAbsence({+ inventoryAuthoritative: () =>+ this.mcpServerCacheSynced && this.mcpWatchGeneration === watchGeneration,+ resolveCurrent: () => this.servers.get(name),+ readCurrent: () =>+ customObjectsApi.getNamespacedCustomObject({+ group: GROUP,+ version: VERSION,+ namespace,+ plural: PLURAL_MCPSERVERS,+ name,+ }),})}+ private async contextAbsentForDelete(+ name: string,+ namespace: string,+ watchGeneration: number+ ): Promise<boolean> {+ if (+ !this.contextCacheSynced ||+ this.contextWatchGeneration !== watchGeneration ||+ this.contexts.has(name) ||+ !customObjectsApi+ ) {+ return false+ }+ try {+ await customObjectsApi.getNamespacedCustomObject({+ group: GROUP,+ version: VERSION,+ namespace,+ plural: PLURAL_CONTEXTS,+ name,+ })+ return false+ } catch (error: unknown) {+ if (getErrorCode(error) !== 404) throw error+ }+ return (+ this.contextCacheSynced &&+ this.contextWatchGeneration === watchGeneration &&+ !this.contexts.has(name)+ )+ }++ private async contextIdAbsentForDelete(+ contextId: string,+ watchGeneration: number+ ): Promise<boolean> {+ const inventoryAuthoritative = () =>+ this.contextCacheSynced && this.contextWatchGeneration === watchGeneration+ const resolveCurrent = () =>+ [...this.contexts.values()].find(context => context.spec.contextId === contextId)+ if (!customObjectsApi || !inventoryAuthoritative() || resolveCurrent()) return false++ const response = (await customObjectsApi.listNamespacedCustomObject({+ group: GROUP,+ version: VERSION,+ namespace: config.namespace,+ plural: PLURAL_CONTEXTS,+ })) as { items?: Array<{ spec?: { contextId?: string } }> }+ if ((response.items ?? []).some(context => context.spec?.contextId === contextId)) return false++ return inventoryAuthoritative() && !resolveCurrent()+ }+private enqueueSharedFileSystemReconciliation(work: () => Promise<void>): Promise<void> {return this.sharedFileSystemReconciliationQueue.enqueue(async () => {if (this.stopped) return@@ -773,6 +1014,153 @@ export class McpServerWatcher implements McpServerProvider {})}+ private requireInventoryResourceVersion(+ kind: 'McpServer' | 'Context',+ resourceVersion: string | undefined+ ): string {+ if (!resourceVersion) {+ throw new Error(`${kind} snapshot missing resourceVersion`)+ }+ return resourceVersion+ }++ private installMcpServerSnapshot(snapshot: McpServerSnapshot): void {+ this.servers.clear()+ for (const server of snapshot.servers) {+ this.servers.set(server.name, server)+ }+ }++ private installContextSnapshot(snapshot: ContextSnapshot): void {+ this.contexts.clear()+ for (const context of snapshot.contexts) {+ this.contexts.set(context.name, context)+ }+ }++ private async restartMcpServerWatch(snapshot: McpServerSnapshot): Promise<number> {+ const resourceVersion = this.requireInventoryResourceVersion(+ 'McpServer',+ snapshot.resourceVersion+ )+ this.mcpServerCacheSynced = false+ this.installMcpServerSnapshot(snapshot)+ const watchGeneration = await this.startMcpServerWatch(resourceVersion)+ if (+ this.stopped ||+ watchGeneration !== this.mcpWatchGeneration ||+ this.mcpWatchRequest === null+ ) {+ throw new Error('McpServer snapshot could not be paired with an active watch')+ }+ this.mcpServerCacheSynced = true+ return watchGeneration+ }++ private async restartContextWatch(snapshot: ContextSnapshot): Promise<number> {+ const resourceVersion = this.requireInventoryResourceVersion(+ 'Context',+ snapshot.resourceVersion+ )+ this.contextCacheSynced = false+ this.installContextSnapshot(snapshot)+ const watchGeneration = await this.startContextWatch(resourceVersion)+ if (+ this.stopped ||+ watchGeneration !== this.contextWatchGeneration ||+ this.ctxWatchRequest === null+ ) {+ throw new Error('Context snapshot could not be paired with an active watch')+ }+ this.contextCacheSynced = true+ return watchGeneration+ }++ private recoverMcpServerInventoryAndWatch(): Promise<boolean> {+ if (this.stopped) return Promise.resolve(false)+ if (this.mcpServerCacheRecoveryInFlight) return this.mcpServerCacheRecoveryInFlight++ const recovery = (async () => {+ try {+ const snapshot = await listMcpServerSnapshot()+ if (this.stopped) return false+ await this.restartMcpServerWatch(snapshot)+ if (this.stopped) return false+ this.changeCallback?.()+ void this.runInitialMcpServerConvergence()+ if (this.contextCacheSynced) {+ void this.runInitialNetworkPolicyConvergence()+ }+ return true+ } catch (error) {+ this.mcpServerCacheSynced = false+ console.error('[K8s] McpServer cache recovery failed:', error)+ return false+ }+ })()++ this.mcpServerCacheRecoveryInFlight = recovery+ void recovery.finally(() => {+ if (this.mcpServerCacheRecoveryInFlight === recovery) {+ this.mcpServerCacheRecoveryInFlight = null+ }+ })+ return recovery+ }++ private recoverContextInventoryAndWatch(): Promise<boolean> {+ if (this.stopped) return Promise.resolve(false)+ if (this.contextCacheRecoveryInFlight) return this.contextCacheRecoveryInFlight++ const recovery = (async () => {+ try {+ const snapshot = await listContextSnapshot()+ if (this.stopped) return false+ await this.restartContextWatch(snapshot)+ if (this.stopped) return false+ this.hostFleetInputRevision += 1+ void this.runInitialNetworkPolicyConvergence()+ void this.runInitialSharedFileSystemConvergence()+ if (this.hostCacheSynced) {+ void this.requestHostFleetReconcile('Context cache recovery', undefined, 'full')+ }+ return true+ } catch (error) {+ this.contextCacheSynced = false+ console.error('[K8s] Context cache recovery failed:', error)+ return false+ }+ })()++ this.contextCacheRecoveryInFlight = recovery+ void recovery.finally(() => {+ if (this.contextCacheRecoveryInFlight === recovery) {+ this.contextCacheRecoveryInFlight = null+ }+ })+ return recovery+ }++ private scheduleMcpServerCacheRecovery(): void {+ if (this.stopped || this.mcpServerCacheRecoveryTimer) return+ this.mcpServerCacheRecoveryTimer = setTimeout(() => {+ this.mcpServerCacheRecoveryTimer = null+ void this.recoverMcpServerInventoryAndWatch().then(recovered => {+ if (!recovered) this.scheduleMcpServerCacheRecovery()+ })+ }, INVENTORY_CACHE_RECOVERY_RETRY_MS)+ }++ private scheduleContextCacheRecovery(): void {+ if (this.stopped || this.contextCacheRecoveryTimer) return+ this.contextCacheRecoveryTimer = setTimeout(() => {+ this.contextCacheRecoveryTimer = null+ void this.recoverContextInventoryAndWatch().then(recovered => {+ if (!recovered) this.scheduleContextCacheRecovery()+ })+ }, INVENTORY_CACHE_RECOVERY_RETRY_MS)+ }+private installCommunicationChannelSnapshot(snapshot: CommunicationChannelSnapshot): void {this.communicationChannels.clear()for (const channel of snapshot.channels) {@@ -931,11 +1319,16 @@ export class McpServerWatcher implements McpServerProvider {*/private recoverHostInventoryAndWatch(convergenceReason = 'Host watch recovery convergence',- ccLifecycleGeneration?: number+ ccLifecycleGeneration?: number,+ cause: HostInventoryRecoveryCause = 'watch-recovery'): Promise<HostCRD[]> {if (this.stopped) return Promise.resolve([])if (this.hostRecoveryInFlight) return this.hostRecoveryInFlight- const recovery = this.performHostInventoryRecovery(convergenceReason, ccLifecycleGeneration)+ const recovery = this.performHostInventoryRecovery(+ convergenceReason,+ ccLifecycleGeneration,+ cause+ )this.hostRecoveryInFlight = recoveryconst clear = (): void => {if (this.hostRecoveryInFlight === recovery) this.hostRecoveryInFlight = null@@ -946,7 +1339,8 @@ export class McpServerWatcher implements McpServerProvider {private async performHostInventoryRecovery(convergenceReason: string,- ccLifecycleGeneration?: number+ ccLifecycleGeneration: number | undefined,+ cause: HostInventoryRecoveryCause): Promise<HostCRD[]> {const startedAt = Date.now()// Capture the pre-recovery inventory so step 7 can distinguish genuinely@@ -996,17 +1390,19 @@ export class McpServerWatcher implements McpServerProvider {clearTimeout(this.hostCacheRecoveryTimer)this.hostCacheRecoveryTimer = null}- this.enqueueRecoveredUrgentHosts(- snapshot.hosts,- previousNames,- previousGenerations,- previousUids- )- // Addendum 4 (#827): a Host present before recovery and absent from the- // fresh authoritative snapshot genuinely disappeared. Enqueue an immediate- // per-Host delete cleanup so a DELETE lost to watch retirement is never- // silently dropped.- this.enqueueRecoveredHostDeletes(snapshot.hosts, previousNames)+ if (cause === 'watch-recovery') {+ this.enqueueRecoveredUrgentHosts(+ snapshot.hosts,+ previousNames,+ previousGenerations,+ previousUids+ )+ // Addendum 4 (#827): a Host present before recovery and absent from the+ // fresh authoritative snapshot genuinely disappeared. Enqueue an immediate+ // per-Host delete cleanup so a DELETE lost to watch retirement is never+ // silently dropped.+ this.enqueueRecoveredHostDeletes(snapshot.hosts, previousNames)+ }// Request a coalesced background full pass, but do NOT await it before// declaring watch recovery complete.void this.requestHostFleetReconcile(convergenceReason, ccLifecycleGeneration, 'full')@@ -1345,6 +1741,7 @@ export class McpServerWatcher implements McpServerProvider {reason,mode: requestMode,ccLifecycleGeneration,+ inputRevision: this.hostFleetInputRevision,}const active = this.hostFleetReconcileInFlightif (!active) {@@ -1371,6 +1768,7 @@ export class McpServerWatcher implements McpServerProvider {this.hostFleetReconcilePending.reason = merged.reasonthis.hostFleetReconcilePending.mode = merged.modethis.hostFleetReconcilePending.ccLifecycleGeneration = merged.ccLifecycleGeneration+ this.hostFleetReconcilePending.inputRevision = merged.inputRevision}// The request did not start its own pass; it is queued behind the active one.hostFleetRequestsTotal.inc({ result: 'coalesced' })@@ -1624,20 +2022,31 @@ export class McpServerWatcher implements McpServerProvider {* event.*/async reconcileByEnvSecret(secretName: string, secretNamespace: string): Promise<void> {- await this.enqueueControlPlaneReconciliation(async () => {- for (const server of this.servers.values()) {- if (server.namespace !== secretNamespace) continue- if (server.spec.envSecret?.name !== secretName) continue- try {- console.log(- `[K8s] Re-reconciling McpServer "${server.name}" after Secret "${secretName}" change`- )- await this.reconciler.reconcile(server)- } catch (err) {- console.error(`[K8s] Secret-triggered reconcile failed for "${server.name}":`, err)- }- }- })+ const selected = [...this.servers.values()].filter(+ server => server.namespace === secretNamespace && server.spec.envSecret?.name === secretName+ )+ await Promise.all(+ selected.map(server =>+ this.enqueueMcpServerReconciliation(server, async () => {+ const current = this.servers.get(server.name)+ if (+ !current ||+ current.namespace !== secretNamespace ||+ current.spec.envSecret?.name !== secretName+ ) {+ return+ }+ try {+ console.log(+ `[K8s] Re-reconciling McpServer "${current.name}" after Secret "${secretName}" change`+ )+ await this.reconciler.reconcile(current)+ } catch (err) {+ console.error(`[K8s] Secret-triggered reconcile failed for "${current.name}":`, err)+ }+ })+ )+ )}/**@@ -1665,7 +2074,7 @@ export class McpServerWatcher implements McpServerProvider {transport,auth: server.spec.auth,enabled: server.spec.enabled !== false,- status: this.reconciler.getStatus(server.name),+ status: this.reconciler.getStatus(server),}}@@ -1720,44 +2129,19 @@ export class McpServerWatcher implements McpServerProvider {* Start watching for changes and run initial reconciliation.*/async start(): Promise<void> {- let initialServers: McpServerCRD[] = []- let serverInventoryComplete = false- try {- initialServers = await listAllMcpServers()- serverInventoryComplete = true- for (const server of initialServers) {- this.servers.set(server.name, server)- }- } catch (error) {- console.error(- '[K8s] Skipping initial McpServer full reconciliation because server discovery failed:',- error- )- }+ // L0/L1 isolation and removal of legacy permissive policies are mandatory+ // bootstrap barriers. They are a fixed-size safety operation, independent+ // of fleet size, and must succeed before HCC can watch or reconcile runtimes.+ await this.netPolReconciler.ensureDefaultPolicies()- // Ensure baseline network policies exist even if initial Context discovery fails.- try {- await this.enqueueControlPlaneReconciliation(() =>- this.netPolReconciler.ensureDefaultPolicies()- )- } catch (error) {- console.error('[K8s] Failed to ensure default NetworkPolicies before startup:', error)- }+ // Discovery and policy caches become authoritative only when each complete+ // LIST snapshot is paired with a watch continuing from its opaque collection+ // resourceVersion. Full fleet convergence happens later in the background.+ const initialServerSnapshot = await listMcpServerSnapshot()+ await this.restartMcpServerWatch(initialServerSnapshot)- let initialContexts: ContextCRD[] = []- let contextInventoryComplete = false- try {- initialContexts = await listAllContexts()- contextInventoryComplete = true- for (const context of initialContexts) {- this.contexts.set(context.name, context)- }- } catch (error) {- console.error(- '[K8s] Skipping initial NetworkPolicy background convergence because context discovery failed:',- error- )- }+ const initialContextSnapshot = await listContextSnapshot()+ await this.restartContextWatch(initialContextSnapshot)// ── CommunicationChannel snapshot + watch — MUST complete before Host fullReconcile ──// A stateless Host may suspend only after this controller has a complete@@ -1842,12 +2226,9 @@ export class McpServerWatcher implements McpServerProvider {)}- // Safety-critical bootstrap ends only after every ordinary watch is- // established and the Host snapshot is paired with its resourceVersion-- // continuing watch. The full reconciliation work launched below is- // deliberately not part of readiness.- await this.startMcpServerWatch()- await this.startContextWatch()+ // SFS/GFS retain their established eventual-resync contract. McpServer,+ // Context, CommunicationChannel and Host use authoritative LIST-to-WATCH+ // handoffs before readiness; full convergence remains outside readiness.await this.startSharedFileSystemWatch()await this.startGlobalFileSystemWatch()@@ -1860,7 +2241,8 @@ export class McpServerWatcher implements McpServerProvider {: this.ccLifecycleGenerationawait this.recoverHostInventoryAndWatch('initial Host reconciliation',- initialLifecycleGeneration+ initialLifecycleGeneration,+ 'cold-start')const resyncSec = config.hostResyncIntervalSec@@ -1914,12 +2296,8 @@ export class McpServerWatcher implements McpServerProvider {// the readiness probe. Each lane snapshots its cache only after cache/watch// bootstrap above, so a watch event accepted during startup is not undone by// a pre-watch inventory snapshot.- if (serverInventoryComplete) {- void this.runInitialMcpServerConvergence()- }- if (contextInventoryComplete) {- void this.runInitialNetworkPolicyConvergence(serverInventoryComplete)- }+ void this.runInitialMcpServerConvergence()+ void this.runInitialNetworkPolicyConvergence()if (sfsInventoryComplete) {void this.runInitialSharedFileSystemConvergence()}@@ -1929,22 +2307,32 @@ export class McpServerWatcher implements McpServerProvider {}private runInitialMcpServerConvergence(): Promise<void> {- return this.enqueueControlPlaneReconciliation(() => this.runInitialMcpServerConvergenceCore())+ return this.runInitialMcpServerConvergenceCore()}private async runInitialMcpServerConvergenceCore(): Promise<void> {+ if (!this.mcpServerCacheSynced) returntry {const initialServers = [...this.servers.values()]- const initialExternalEgressFailures =- await this.reconcileInitialExternalEgressBeforeRuntime(initialServers)+ const initialExternalEgressGates =+ this.reconcileInitialExternalEgressBeforeRuntime(initialServers)if (this.stopped) return- // Servers with egressBindings reconcile only after their external egress- // policies have converged, matching the ADDED/MODIFIED watch contract.- const runtimeServers = initialServers.filter(- server => !initialExternalEgressFailures.has(this.externalEgressRetryKey(server))- )console.log('[K8s] Running initial McpServer background reconciliation...')- await this.reconciler.fullReconcile(runtimeServers)+ await this.reconciler.fullReconcile(initialServers, {+ runEffect: async (serverName, work) => {+ const selected = this.servers.get(serverName)+ const laneOwner = selected ?? {+ name: serverName,+ namespace: config.namespace,+ }+ const externalEgressReady = initialExternalEgressGates.get(+ this.externalEgressRetryKey(laneOwner)+ )+ if (externalEgressReady && !(await externalEgressReady)) return+ if (this.stopped) return+ await this.enqueueMcpServerReconciliation(laneOwner, work)+ },+ })this.clearInitialConvergenceRetry('McpServer')} catch (error) {console.error('[K8s] Initial McpServer background reconciliation failed:', error)@@ -1952,27 +2340,42 @@ export class McpServerWatcher implements McpServerProvider {}}- private runInitialNetworkPolicyConvergence(serverInventoryComplete: boolean): Promise<void> {- return this.enqueueControlPlaneReconciliation(() =>- this.runInitialNetworkPolicyConvergenceCore(serverInventoryComplete)- )+ private runInitialNetworkPolicyConvergence(): Promise<void> {+ return this.runInitialNetworkPolicyConvergenceCore()}- private async runInitialNetworkPolicyConvergenceCore(- serverInventoryComplete: boolean- ): Promise<void> {+ private async runInitialNetworkPolicyConvergenceCore(): Promise<void> {+ if (!this.contextCacheSynced) returntry {const initialContexts = [...this.contexts.values()]const initialServers = [...this.servers.values()]+ const contextInventoryGeneration = this.contextWatchGeneration+ const serverInventoryGeneration = this.mcpWatchGenerationconsole.log('[K8s] Running initial NetworkPolicy background reconciliation...')await this.netPolReconciler.fullReconcile(initialContexts, initialServers, {- serverInventoryComplete,+ serverInventoryComplete: this.mcpServerCacheSynced,ensureDefaults: false,+ contextInventoryAuthoritative: () =>+ this.contextCacheSynced && this.contextWatchGeneration === contextInventoryGeneration,+ serverInventoryAuthoritative: () =>+ this.mcpServerCacheSynced && this.mcpWatchGeneration === serverInventoryGeneration,+ runContextEffect: (contextId, work) => this.enqueueContextReconciliation(contextId, work),+ runServerEffect: (serverName, work) => {+ const selected = this.servers.get(serverName)+ return this.enqueueMcpServerReconciliation(+ selected ?? { name: serverName, namespace: config.namespace },+ work+ )+ },+ resolveCurrentContext: name => this.contexts.get(name),+ resolveCurrentContextById: contextId =>+ [...this.contexts.values()].find(context => context.spec.contextId === contextId),+ resolveCurrentServer: name => this.servers.get(name),})this.clearInitialConvergenceRetry('NetworkPolicy')} catch (error) {console.error('[K8s] Initial NetworkPolicy background reconciliation failed:', error)- this.scheduleInitialConvergenceRetry('NetworkPolicy', serverInventoryComplete)+ this.scheduleInitialConvergenceRetry('NetworkPolicy')}}@@ -1983,19 +2386,9 @@ export class McpServerWatcher implements McpServerProvider {this.initialConvergenceRetryTimers.delete(lane)}this.initialConvergenceRetryAttempts.delete(lane)- if (lane === 'NetworkPolicy') {- this.initialNetworkPolicyRetryServerInventoryComplete = undefined- }}- private scheduleInitialConvergenceRetry(- lane: InitialConvergenceLane,- serverInventoryComplete?: boolean- ): void {- if (lane === 'NetworkPolicy' && serverInventoryComplete !== undefined) {- this.initialNetworkPolicyRetryServerInventoryComplete =- (this.initialNetworkPolicyRetryServerInventoryComplete ?? true) && serverInventoryComplete- }+ private scheduleInitialConvergenceRetry(lane: InitialConvergenceLane): void {if (this.stopped || this.initialConvergenceRetryTimers.has(lane)) returnconst attempt = (this.initialConvergenceRetryAttempts.get(lane) ?? 0) + 1@@ -2015,9 +2408,7 @@ export class McpServerWatcher implements McpServerProvider {void this.runInitialMcpServerConvergence()return}- void this.runInitialNetworkPolicyConvergence(- this.initialNetworkPolicyRetryServerInventoryComplete ?? false- )+ void this.runInitialNetworkPolicyConvergence()}, delayMs)this.initialConvergenceRetryTimers.set(lane, timer)}@@ -2130,12 +2521,17 @@ export class McpServerWatcher implements McpServerProvider {const watchCallback = async (type: string,- apiObj: { metadata: { name: string; namespace?: string }; spec: GlobalFileSystemSpec }+ apiObj: {+ metadata: { name: string; namespace?: string }+ spec: GlobalFileSystemSpec+ status?: GlobalFileSystemCRD['status']+ }) => {const gfs: GlobalFileSystemCRD = {name: apiObj.metadata.name,namespace: apiObj.metadata.namespace || namespace,spec: apiObj.spec,+ status: apiObj.status,}console.log(`[K8s] GlobalFileSystem watch event: ${type} for ${gfs.name}`)if (type === 'ADDED' || type === 'MODIFIED') {@@ -2451,7 +2847,14 @@ export class McpServerWatcher implements McpServerProvider {}private runExternalEgressResync(): Promise<void> {- return this.enqueueControlPlaneReconciliation(() => this.runExternalEgressResyncCore())+ if (this.externalEgressResyncInFlight) return this.externalEgressResyncInFlight+ const run = this.runExternalEgressResyncCore().finally(() => {+ if (this.externalEgressResyncInFlight === run) {+ this.externalEgressResyncInFlight = null+ }+ })+ this.externalEgressResyncInFlight = run+ return run}private async runExternalEgressResyncCore(): Promise<void> {@@ -2475,65 +2878,107 @@ export class McpServerWatcher implements McpServerProvider {console.log(`[K8s] Skipping external egress resync for ${key}; reconcile in flight`)continue}- if (this.externalEgressRetryTimers.has(key)) {- console.log(`[K8s] Skipping external egress resync for ${key}; retry already scheduled`)- continue- }const jitterMs = Math.floor(Math.random() * EXTERNAL_EGRESS_RESYNC_JITTER_MS)if (jitterMs > 0) await delay(jitterMs)- try {- await this.runExternalEgressOnce('MODIFIED', server)- } catch (error) {- console.error(`[K8s] External egress periodic resync failed for ${key}:`, error)- this.scheduleExternalEgressRetry('MODIFIED', server)- }+ if (this.stopped) return+ await this.enqueueMcpServerReconciliation(server, async () => {+ // The fleet snapshot above selects work only. Resolve desired state+ // after entering the same per-server FIFO lane as watch and retry+ // effects, so a newer revision can never be overwritten by stale+ // periodic work.+ const current = this.servers.get(server.name)+ if (+ this.stopped ||+ !current ||+ current.namespace !== server.namespace ||+ (current.spec.egressBindings?.length ?? 0) === 0+ ) {+ return+ }+ try {+ // A pending intent represents the full ordered pipeline, not only+ // DNS state. Continue it in this same per-server FIFO lane so a+ // successful periodic refresh also heals runtime and bindings.+ const retryIntent = this.externalEgressRetryIntents.get(key)+ if (retryIntent) {+ await this.retryExternalEgressCore(retryIntent)+ return+ }+ await this.runExternalEgressOnce('MODIFIED', current, {+ clearRetryOnSuccess: false,+ })+ } catch (error) {+ console.error(`[K8s] External egress periodic resync failed for ${key}:`, error)+ this.scheduleExternalEgressRetry('MODIFIED', current)+ }+ })}})await Promise.all(workers)}- private async reconcileInitialExternalEgressBeforeRuntime(+ private reconcileInitialExternalEgressBeforeRuntime(servers: McpServerCRD[]- ): Promise<Set<string>> {- const failures = new Set<string>()+ ): Map<string, Promise<boolean>> {+ const gates = new Map<string, Promise<boolean>>()const serversWithExternalEgress = servers.filter(server => (server.spec.egressBindings?.length ?? 0) > 0).sort((a, b) => `${a.namespace}/${a.name}`.localeCompare(`${b.namespace}/${b.name}`))- if (serversWithExternalEgress.length === 0) return failures+ if (serversWithExternalEgress.length === 0) return gatesconsole.log(`[K8s] Reconciling external egress before startup runtime reconciliation for ` +`${serversWithExternalEgress.length} McpServer(s)`)- for (const server of serversWithExternalEgress) {- const key = this.externalEgressRetryKey(server)- try {- await this.runExternalEgressOnce('MODIFIED', server)- } catch (error) {- failures.add(key)- console.error(- `[K8s] Initial external egress reconciliation failed for ${key}; ` +- 'runtime reconciliation will stay blocked until retry succeeds:',- error- )- this.scheduleExternalEgressRetry('MODIFIED', server)- }+ const limiter = new AsyncConcurrencyLimiter(EXTERNAL_EGRESS_RESYNC_MAX_CONCURRENCY)+ for (const selected of serversWithExternalEgress) {+ const key = this.externalEgressRetryKey(selected)+ const gate = limiter.run(async () => {+ let ready = false+ await this.enqueueMcpServerReconciliation(selected, async () => {+ if (this.stopped) return+ const current = this.servers.get(selected.name)+ if (+ !current ||+ current.namespace !== selected.namespace ||+ !sameMcpServerDesiredRevision(selected, current)+ ) {+ return+ }+ try {+ await this.runExternalEgressOnce('MODIFIED', current)+ const latest = this.servers.get(selected.name)+ ready =+ !this.stopped &&+ latest !== undefined &&+ sameMcpServerDesiredRevision(selected, latest)+ } catch (error) {+ console.error(+ `[K8s] Initial external egress reconciliation failed for ${key}; ` ++ 'runtime reconciliation will stay blocked until retry succeeds:',+ error+ )+ this.scheduleExternalEgressRetry('MODIFIED', current)+ }+ })+ return ready+ })+ gates.set(key, gate)}-- return failures+ return gates}/*** Start watching McpServer CRDs.*/- private getMcpServerWatchCallback(): (- type: string,- apiObj: McpServerWatchObject- ) => Promise<void> {+ private getMcpServerWatchCallback(+ watchGeneration = this.mcpWatchGeneration+ ): (type: string, apiObj: McpServerWatchObject) => Promise<void> {return async (type, apiObj) => {+ if (this.stopped || watchGeneration !== this.mcpWatchGeneration) returnconst server: McpServerCRD = {name: apiObj.metadata.name,namespace: apiObj.metadata.namespace || config.namespace,@@ -2547,26 +2992,82 @@ export class McpServerWatcher implements McpServerProvider {console.log(`[K8s] McpServer watch event: ${type} for ${server.name}`)+ const previous = this.servers.get(server.name)+// Update cacheif (type === 'ADDED' || type === 'MODIFIED') {this.servers.set(server.name, server)} else if (type === 'DELETED') {- this.servers.delete(server.name)+ if (!previous?.uid || !server.uid || previous.uid === server.uid) {+ this.servers.delete(server.name)+ }}- await this.enqueueControlPlaneReconciliation(() =>- this.reconcileMcpServerWatchEvent(type, server)+ // HCC writes McpServer status during reconciliation. Those writes emit+ // MODIFIED events but do not change the desired runtime or policy state.+ // Suppress that self-induced work while still publishing the fresh status+ // through discovery. Any UID/spec/annotation/label change remains live.+ if (type === 'MODIFIED' && previous && isMcpServerStatusOnlyUpdate(previous, server)) {+ this.changeCallback?.()+ return+ }++ await this.enqueueMcpServerReconciliation(server, () =>+ this.reconcileMcpServerWatchEvent(type, server, watchGeneration))}}- private async reconcileMcpServerWatchEvent(type: string, server: McpServerCRD): Promise<void> {+ private async reconcileMcpServerWatchEvent(+ type: string,+ server: McpServerCRD,+ watchGeneration: number,+ retryIntent?: ExternalEgressRetryIntent+ ): Promise<void> {+ if (this.stopped || watchGeneration !== this.mcpWatchGeneration) return+ if (+ retryIntent &&+ this.externalEgressRetryIntents.get(this.externalEgressRetryKey(retryIntent.server))+ ?.sequence !== retryIntent.sequence+ ) {+ return+ }+ const current = this.servers.get(server.name)+ if (type === 'DELETED') {+ // A same-name recreation may already be accepted while this callback+ // waits for its per-server effect. The newer identity owns the key.+ if (current) return+ } else {+ if (!current || current.namespace !== server.namespace) return+ server = current+ }+// External egress is part of the workload's pre-start contract. Reconcile// it before HCC creates or updates any managed runtime Deployment so a// stdio MCP with egressBindings cannot start before ExternalEgressReady.if (type === 'ADDED' || type === 'MODIFIED') {try {- await this.runExternalEgressOnce(type, server)+ await this.runExternalEgressOnce(type, server, {+ clearRetryOnSuccess: retryIntent === undefined,+ })+ } catch (error) {+ console.error(+ `[K8s] External egress reconciliation failed for ${server.name}; runtime reconciliation blocked:`,+ error+ )+ this.scheduleExternalEgressRetry(type, server)+ this.changeCallback?.()+ return+ }+ } else {+ const deleteAllowed = () =>+ this.mcpServerAbsentForDelete(server.name, server.namespace, watchGeneration)+ if (!(await deleteAllowed())) return+ try {+ await this.runExternalEgressOnce(type, server, {+ clearRetryOnSuccess: retryIntent === undefined,+ deleteAllowed,+ })} catch (error) {console.error(`[K8s] External egress reconciliation failed for ${server.name}; runtime reconciliation blocked:`,@@ -2578,6 +3079,15 @@ export class McpServerWatcher implements McpServerProvider {}}+ if (type === 'ADDED' || type === 'MODIFIED') {+ if (!this.mcpServerWatchEffectIsCurrent(server, watchGeneration)) return+ server = this.servers.get(server.name)!+ } else if (+ !(await this.mcpServerAbsentForDelete(server.name, server.namespace, watchGeneration))+ ) {+ return+ }+// Trigger deployment reconciliation.try {if (type === 'ADDED' || type === 'MODIFIED') {@@ -2587,12 +3097,18 @@ export class McpServerWatcher implements McpServerProvider {}} catch (error) {console.error(`[K8s] Reconciliation failed for ${server.name}:`, error)- if (- (type === 'ADDED' || type === 'MODIFIED') &&- (server.spec.egressBindings?.length ?? 0) > 0- ) {- this.scheduleExternalEgressRetry(type, server)- }+ this.scheduleExternalEgressRetry(type, server)+ this.changeCallback?.()+ return+ }++ if (type === 'ADDED' || type === 'MODIFIED') {+ if (!this.mcpServerWatchEffectIsCurrent(server, watchGeneration)) return+ server = this.servers.get(server.name)!+ } else if (+ !(await this.mcpServerAbsentForDelete(server.name, server.namespace, watchGeneration))+ ) {+ return}// Trigger binding policy reconciliation (L3 ingress/egress).@@ -2609,68 +3125,114 @@ export class McpServerWatcher implements McpServerProvider {mcpWorkloadName,server.name)+ if (!this.mcpServerWatchEffectIsCurrent(server, watchGeneration)) return+ server = this.servers.get(server.name)!}// Re-reconcile cached Contexts after the server cache is populated.- for (const ctx of this.contexts.values()) {- if (!ctx.spec.mcpServers?.includes(server.name)) continue+ for (const selectedContext of this.contexts.values()) {+ if (!this.mcpServerWatchEffectIsCurrent(server, watchGeneration)) return+ if (!selectedContext.spec.mcpServers?.includes(server.name)) continue+ const selectedContextId = selectedContext.spec.contextIdconsole.log(- `[K8s] Re-reconciling context "${ctx.name}" after McpServer "${server.name}" cached`+ `[K8s] Re-reconciling context "${selectedContext.name}" after McpServer "${server.name}" cached`)- await this.netPolReconciler.reconcileContext(ctx)+ await this.enqueueContextReconciliation(selectedContextId, async () => {+ if (!this.mcpServerWatchEffectIsCurrent(server, watchGeneration)) return+ const currentContext = this.contexts.get(selectedContext.name)+ if (+ currentContext?.spec.contextId !== selectedContextId ||+ !currentContext.spec.mcpServers?.includes(server.name)+ ) {+ return+ }+ await this.netPolReconciler.reconcileContext(currentContext)+ })}} else if (type === 'DELETED') {const recipeName = server.labels?.['clerum.io/recipe'] ?? server.nameawait this.bindingReconciler.cleanupBindings(recipeName)- await this.runExternalEgressOnce(type, server)}} catch (error) {console.error(`[K8s] Binding/egress reconciliation failed for ${server.name}:`, error)- if (type === 'ADDED' || type === 'MODIFIED' || type === 'DELETED') {- this.scheduleExternalEgressRetry(type, server)- }+ this.scheduleExternalEgressRetry(type, server)+ this.changeCallback?.()+ return}+ if (retryIntent) this.clearExternalEgressRetryIntent(retryIntent)this.changeCallback?.()}- private async startMcpServerWatch(): Promise<void> {+ private async startMcpServerWatch(resourceVersion: string): Promise<number> {+ this.requireInventoryResourceVersion('McpServer', resourceVersion)const path = `/apis/${GROUP}/${VERSION}/namespaces/${config.namespace}/${PLURAL_MCPSERVERS}`console.log(`[K8s] Starting McpServer watch`)+ const watchGeneration = ++this.mcpWatchGeneration+ if (this.mcpWatchRequest) {+ this.mcpWatchRequest.abort()+ this.mcpWatchRequest = null+ }+ let watchEnded = false- const watchCallback = this.getMcpServerWatchCallback()+ const watchCallback = this.getMcpServerWatchCallback(watchGeneration)const doneCallback = (err: Error | null) => {- if (this.stopped) return+ if (watchEnded) return+ watchEnded = true+ if (this.stopped || watchGeneration !== this.mcpWatchGeneration) return+ if (!this.retireMcpServerWatch(watchGeneration)) returnif (err) {console.error('[K8s] McpServer watch error:', err)}- console.log('[K8s] McpServer watch ended, restarting...')- setTimeout(() => this.startMcpServerWatch(), err ? 5000 : 1000)+ console.log('[K8s] McpServer watch ended; recovering authoritative inventory...')+ this.scheduleMcpServerCacheRecovery()}- this.mcpWatchRequest = await this.watch.watch(path, {}, watchCallback, doneCallback)+ const request = await this.watch.watch(path, { resourceVersion }, watchCallback, doneCallback)+ if (this.stopped || watchGeneration !== this.mcpWatchGeneration || watchEnded) {+ request.abort()+ return watchGeneration+ }+ this.mcpWatchRequest = request+ return watchGeneration}private externalEgressRetryKey(server: Pick<McpServerCRD, 'name' | 'namespace'>): string {return `${server.namespace}/${server.name}`}+ private mcpServerWatchEffectIsCurrent(expected: McpServerCRD, watchGeneration: number): boolean {+ if (this.stopped || watchGeneration !== this.mcpWatchGeneration) return false+ const current = this.servers.get(expected.name)+ return current !== undefined && sameMcpServerDesiredRevision(expected, current)+ }+private async runExternalEgressOnce(type: string,server: McpServerCRD,- options: { clearRetryOnSuccess?: boolean } = {}+ options: {+ clearRetryOnSuccess?: boolean+ deleteAllowed?: () => Promise<boolean>+ } = {}): Promise<void> {+ if (this.stopped) returnconst clearRetryOnSuccess = options.clearRetryOnSuccess ?? trueconst key = this.externalEgressRetryKey(server)const existing = this.externalEgressInFlight.get(key)if (existing) {console.warn(`[K8s] Waiting for external egress reconcile for ${key}; already in flight`)await existing+ if (this.stopped) return}const run = (async () => {if (type === 'DELETED') {- await this.netPolReconciler.cleanupExternalEgress(server.name, server.namespace)+ await this.netPolReconciler.cleanupExternalEgress(+ server.name,+ server.namespace,+ undefined,+ options.deleteAllowed+ )} else {await this.netPolReconciler.reconcileExternalEgress(server)}@@ -2696,81 +3258,114 @@ export class McpServerWatcher implements McpServerProvider {this.externalEgressRetryTimers.delete(key)}this.externalEgressRetryAttempts.delete(key)+ this.externalEgressRetryIntents.delete(key)+ }++ private clearExternalEgressRetryIntent(intent: ExternalEgressRetryIntent): void {+ const key = this.externalEgressRetryKey(intent.server)+ if (this.externalEgressRetryIntents.get(key)?.sequence !== intent.sequence) return+ this.clearExternalEgressRetry(intent.server)+ }++ private sameExternalEgressRetryTarget(+ previous: ExternalEgressRetryIntent,+ type: McpServerWatchEventType,+ server: McpServerCRD+ ): boolean {+ const previousPresent = previous.type !== 'DELETED'+ const nextPresent = type !== 'DELETED'+ return previousPresent === nextPresent && sameMcpServerDesiredRevision(previous.server, server)}private scheduleExternalEgressRetry(type: string, server: McpServerCRD): void {if (type !== 'ADDED' && type !== 'MODIFIED' && type !== 'DELETED') returnif (this.stopped) return+ const cached = this.servers.get(server.name)+ const retryType: McpServerWatchEventType =+ cached && cached.namespace === server.namespace+ ? type === 'ADDED' && sameMcpServerDesiredRevision(server, cached)+ ? 'ADDED'+ : 'MODIFIED'+ : 'DELETED'+ const retryServer = cached && cached.namespace === server.namespace ? cached : serverconst key = this.externalEgressRetryKey(server)+ const previousIntent = this.externalEgressRetryIntents.get(key)+ if (+ previousIntent &&+ !this.sameExternalEgressRetryTarget(previousIntent, retryType, retryServer)+ ) {+ this.externalEgressRetryAttempts.delete(key)+ }+ const intent: ExternalEgressRetryIntent = {+ sequence: ++this.externalEgressRetrySequence,+ type: retryType,+ server: retryServer,+ }+ this.externalEgressRetryIntents.set(key, intent)if (this.externalEgressRetryTimers.has(key)) return- const attempt = (this.externalEgressRetryAttempts.get(key) ?? 0) + 1+ const attempt = Math.min(+ (this.externalEgressRetryAttempts.get(key) ?? 0) + 1,+ EXTERNAL_EGRESS_RETRY_DELAYS_MS.length+ )const delayMs = EXTERNAL_EGRESS_RETRY_DELAYS_MS[attempt - 1]- if (!delayMs) {- console.error(- `[K8s] External egress retry exhausted for McpServer "${server.name}" in namespace "${server.namespace}"`- )- return- }this.externalEgressRetryAttempts.set(key, attempt)+ const capped = attempt === EXTERNAL_EGRESS_RETRY_DELAYS_MS.lengthconsole.warn(- `[K8s] Scheduling external egress retry ${attempt}/${EXTERNAL_EGRESS_RETRY_DELAYS_MS.length} ` ++ `[K8s] Scheduling external egress retry ${attempt}/${EXTERNAL_EGRESS_RETRY_DELAYS_MS.length}` ++ `${capped ? ' (capped)' : ''} ` +`for McpServer "${server.name}" in ${delayMs}ms`)const timer = setTimeout(() => {this.externalEgressRetryTimers.delete(key)- void this.retryExternalEgress(type, server)+ const currentIntent = this.externalEgressRetryIntents.get(key)+ if (currentIntent) {+ void this.externalEgressRetryLimiter.run(() => this.retryExternalEgress(currentIntent))+ }}, delayMs)this.externalEgressRetryTimers.set(key, timer)}- private retryExternalEgress(type: string, server: McpServerCRD): Promise<void> {- return this.enqueueControlPlaneReconciliation(() => this.retryExternalEgressCore(type, server))+ private retryExternalEgress(intent: ExternalEgressRetryIntent): Promise<void> {+ return this.enqueueMcpServerReconciliation(intent.server, () =>+ this.retryExternalEgressCore(intent)+ )}- private async retryExternalEgressCore(type: string, server: McpServerCRD): Promise<void> {+ private async retryExternalEgressCore(intent: ExternalEgressRetryIntent): Promise<void> {if (this.stopped) return- try {- if (type === 'DELETED') {- await this.runExternalEgressOnce(type, server)- } else {- const current = this.servers.get(server.name)- if (!current || current.namespace !== server.namespace) {- this.clearExternalEgressRetry(server)- return- }- await this.runExternalEgressOnce(type, current, { clearRetryOnSuccess: false })- try {- await this.reconciler.reconcile(current)- this.clearExternalEgressRetry(current)- } catch (error) {- console.error(- `[K8s] Runtime reconciliation after external egress retry failed for ${server.name}:`,- error- )- this.scheduleExternalEgressRetry(type, current)- }- }- } catch (error) {- console.error(`[K8s] External egress retry failed for ${server.name}:`, error)- this.scheduleExternalEgressRetry(type, server)- }+ const key = this.externalEgressRetryKey(intent.server)+ if (this.externalEgressRetryIntents.get(key)?.sequence !== intent.sequence) return++ const current = this.servers.get(intent.server.name)+ const type: McpServerWatchEventType =+ current && current.namespace === intent.server.namespace ? 'MODIFIED' : 'DELETED'+ const server = type === 'DELETED' ? intent.server : current!+ await this.reconcileMcpServerWatchEvent(type, server, this.mcpWatchGeneration, intent)}/*** Start watching Context CRDs for NetworkPolicy reconciliation.*/- private async startContextWatch(): Promise<void> {+ private async startContextWatch(resourceVersion: string): Promise<number> {+ this.requireInventoryResourceVersion('Context', resourceVersion)const path = `/apis/${GROUP}/${VERSION}/namespaces/${config.namespace}/${PLURAL_CONTEXTS}`console.log(`[K8s] Starting Context watch`)+ const watchGeneration = ++this.contextWatchGeneration+ if (this.ctxWatchRequest) {+ this.ctxWatchRequest.abort()+ this.ctxWatchRequest = null+ }+ let watchEnded = falseconst watchCallback = async (type: string,apiObj: { metadata: { name: string; namespace?: string }; spec: ContextSpec }) => {+ if (this.stopped || watchGeneration !== this.contextWatchGeneration) returnconst context: ContextCRD = {name: apiObj.metadata.name,namespace: apiObj.metadata.namespace || config.namespace,@@ -2796,20 +3391,54 @@ export class McpServerWatcher implements McpServerProvider {const nextForSfs = type === 'DELETED' ? undefined : contextvoid this.reconcileSharedFileSystemsReferencedByContext(previous, nextForSfs)- await this.enqueueControlPlaneReconciliation(async () => {+ const previousContextId = previous?.spec.contextId+ const effectContextIds =+ previousContextId && previousContextId !== context.spec.contextId+ ? [previousContextId, context.spec.contextId]+ : [context.spec.contextId]+ await this.enqueueContextIdentityReconciliation(effectContextIds, async () => {+ if (this.stopped || watchGeneration !== this.contextWatchGeneration) return+try {+ if (previousContextId && previousContextId !== context.spec.contextId) {+ const oldIdDeleteAllowed = () =>+ this.contextIdAbsentForDelete(previousContextId, watchGeneration)+ if (await oldIdDeleteAllowed()) {+ await this.netPolReconciler.reconcileDeleteContext(+ previousContextId,+ oldIdDeleteAllowed+ )+ }+ }++ if (this.stopped || watchGeneration !== this.contextWatchGeneration) return+ const current = this.contexts.get(context.name)+ if (type === 'DELETED') {+ if (current) return+ } else if (current?.spec.contextId !== context.spec.contextId) {+ return+ }if (type === 'ADDED' || type === 'MODIFIED') {- await this.netPolReconciler.reconcileContext(context)+ await this.netPolReconciler.reconcileContext(current!)} else if (type === 'DELETED') {- await this.netPolReconciler.reconcileDeleteContext(context.spec.contextId)+ const deleteAllowed = () =>+ this.contextAbsentForDelete(context.name, context.namespace, watchGeneration)+ if (!(await deleteAllowed())) return+ await this.netPolReconciler.reconcileDeleteContext(+ context.spec.contextId,+ deleteAllowed+ )}} catch (error) {console.error(`[K8s] NetworkPolicy reconciliation failed for context ${context.name}:`,error)+ void this.runInitialNetworkPolicyConvergence()+ return}+ if (this.stopped || watchGeneration !== this.contextWatchGeneration) return// Re-reconcile any Host that points at this Context so that changes to// spec.sharedFileSystems[] propagate into the mcp-host pod template.try {@@ -2827,15 +3456,24 @@ export class McpServerWatcher implements McpServerProvider {}const doneCallback = (err: Error | null) => {- if (this.stopped) return+ if (watchEnded) return+ watchEnded = true+ if (this.stopped || watchGeneration !== this.contextWatchGeneration) return+ if (!this.retireContextWatch(watchGeneration)) returnif (err) {console.error('[K8s] Context watch error:', err)}- console.log('[K8s] Context watch ended, restarting...')- setTimeout(() => this.startContextWatch(), err ? 5000 : 1000)+ console.log('[K8s] Context watch ended; recovering authoritative inventory...')+ this.scheduleContextCacheRecovery()}- this.ctxWatchRequest = await this.watch.watch(path, {}, watchCallback, doneCallback)+ const request = await this.watch.watch(path, { resourceVersion }, watchCallback, doneCallback)+ if (this.stopped || watchGeneration !== this.contextWatchGeneration || watchEnded) {+ request.abort()+ return watchGeneration+ }+ this.ctxWatchRequest = request+ return watchGeneration}/**@@ -2937,6 +3575,8 @@ export class McpServerWatcher implements McpServerProvider {*/async stop(): Promise<void> {this.stopped = true+ this.retireMcpServerWatch()+ this.retireContextWatch()this.ccCacheSynced = falsethis.hostCacheSynced = falsethis.hostWatchGeneration += 1@@ -2956,6 +3596,14 @@ export class McpServerWatcher implements McpServerProvider {clearTimeout(this.hostCacheRecoveryTimer)this.hostCacheRecoveryTimer = null}+ if (this.mcpServerCacheRecoveryTimer) {+ clearTimeout(this.mcpServerCacheRecoveryTimer)+ this.mcpServerCacheRecoveryTimer = null+ }+ if (this.contextCacheRecoveryTimer) {+ clearTimeout(this.contextCacheRecoveryTimer)+ this.contextCacheRecoveryTimer = null+ }this.clearAllHostWatchRetries()if (this.resyncTimer) {clearInterval(this.resyncTimer)@@ -2978,6 +3626,7 @@ export class McpServerWatcher implements McpServerProvider {}this.externalEgressRetryTimers.clear()this.externalEgressRetryAttempts.clear()+ this.externalEgressRetryIntents.clear()this.externalEgressInFlight.clear()for (const timer of this.initialConvergenceRetryTimers.values()) {clearTimeout(timer)diff --git a/host-context-controller/src/main.ts b/host-context-controller/src/main.tsindex 0e1502aa5..d311ced40 100644--- a/host-context-controller/src/main.ts+++ b/host-context-controller/src/main.ts@@ -113,6 +113,9 @@ async function main(): Promise<void> {const hasDesktopFn = hostReconciler? (hostRef: string) => hostReconciler.hasDesktop(hostRef): undefined+ const providerAuthoritativeFn = watcher+ ? () => watcher.isReadinessInventoryAuthoritative()+ : undefined// Stateless heartbeat consumption — mcp-host pods authenticate their// heartbeats toward control-api's /mcp-host facade (control-api is the@@ -145,16 +148,22 @@ async function main(): Promise<void> {`target=${config.controlApiBaseUrl})`)}- server = new ContextMapperServer(provider, config.port, hostReconciler, hasDesktopFn)+ server = new ContextMapperServer(+ provider,+ config.port,+ hostReconciler,+ hasDesktopFn,+ providerAuthoritativeFn+ )await server.start()// One-shot legacy sweep: delete the static `clerum-channel-reader`// Deployment if it still exists in the channels namespace. MUST run- // BEFORE provider.start(): provider.start() invokes fullReconcile on- // the initial Host list, which creates per-Host channel-reader Deployments- // that immediately try to long-poll Telegram. If the static is still- // alive at that moment, both pods compete on the same bot's getUpdates- // and Telegram 409s one of them. Sweeping first guarantees zero overlap.+ // BEFORE provider.start(): provider startup establishes the Host inventory+ // watch and schedules its initial fleet convergence, which creates per-Host+ // channel-reader Deployments in the background. If the static is still alive+ // when that work begins, both pods compete on the same bot's getUpdates and+ // Telegram 409s one of them. Sweeping first guarantees zero overlap.// Idempotent; 404 (already gone) is the steady state. See issue #273// for the empirical reproduction.if (!config.devMode && hostReconciler) {diff --git a/host-context-controller/src/mcpServerSafety.test.ts b/host-context-controller/src/mcpServerSafety.test.tsnew file mode 100644index 000000000..ce4e3bcb7--- /dev/null+++ b/host-context-controller/src/mcpServerSafety.test.ts@@ -0,0 +1,231 @@+import { describe, expect, it, vi } from 'vitest'+import {+ confirmAuthoritativeMcpServerAbsence,+ isMcpServerStatusOnlyUpdate,+ sameMcpServerDesiredRevision,+} from './mcpServerSafety'+import type { McpServerCRD } from './types'++function makeServer(overrides: Partial<McpServerCRD> = {}): McpServerCRD {+ return {+ name: 'web-search',+ namespace: 'mcp-server',+ uid: 'web-search-uid',+ generation: 7,+ annotations: { 'clerum.io/recipe': 'research' },+ labels: { 'clerum.io/workload': 'web-search' },+ spec: {+ contextRef: 'default',+ image: 'clerum/web-search:test',+ transport: { type: 'streamableHttp', port: 3000 },+ },+ ...overrides,+ }+}++describe('sameMcpServerDesiredRevision', () => {+ it('matches equal desired state while ignoring status and one-sided identity metadata', () => {+ const expected = makeServer({+ status: { conditions: [{ type: 'Ready', status: 'False' }] },+ })+ const current = makeServer({+ uid: undefined,+ generation: undefined,+ status: { conditions: [{ type: 'Ready', status: 'True' }] },+ })++ expect(sameMcpServerDesiredRevision(expected, current)).toBe(true)+ expect(sameMcpServerDesiredRevision(current, expected)).toBe(true)+ })++ it('rejects a different resource key', () => {+ const expected = makeServer()++ expect(sameMcpServerDesiredRevision(expected, makeServer({ name: 'doc-generator' }))).toBe(+ false+ )+ expect(sameMcpServerDesiredRevision(expected, makeServer({ namespace: 'other' }))).toBe(false)+ })++ it('rejects differing UID or generation only when both sides provide the field', () => {+ const expected = makeServer()++ expect(sameMcpServerDesiredRevision(expected, makeServer({ uid: 'replacement-uid' }))).toBe(+ false+ )+ expect(sameMcpServerDesiredRevision(expected, makeServer({ generation: 8 }))).toBe(false)+ expect(sameMcpServerDesiredRevision(expected, makeServer({ uid: undefined }))).toBe(true)+ expect(sameMcpServerDesiredRevision(expected, makeServer({ generation: undefined }))).toBe(true)+ })++ it('uses JSON equality for spec, annotations, and labels', () => {+ const expected = makeServer({+ labels: { first: '1', second: '2' },+ })++ expect(+ sameMcpServerDesiredRevision(+ expected,+ makeServer({+ spec: {+ ...expected.spec,+ image: 'clerum/web-search:next',+ },+ labels: expected.labels,+ })+ )+ ).toBe(false)+ expect(+ sameMcpServerDesiredRevision(+ expected,+ makeServer({+ annotations: { 'clerum.io/recipe': 'other' },+ labels: expected.labels,+ })+ )+ ).toBe(false)+ expect(+ sameMcpServerDesiredRevision(+ expected,+ makeServer({+ labels: { second: '2', first: '1' },+ })+ )+ ).toBe(false)+ })+})++describe('isMcpServerStatusOnlyUpdate', () => {+ it('accepts only an exact identity and generation with unchanged desired state', () => {+ const previous = makeServer({+ status: { conditions: [{ type: 'Ready', status: 'False' }] },+ })+ const current = makeServer({+ status: { conditions: [{ type: 'Ready', status: 'True' }] },+ })++ expect(isMcpServerStatusOnlyUpdate(previous, current)).toBe(true)+ })++ it('does not suppress events when UID or generation equality is only one-sided', () => {+ const previous = makeServer()++ expect(isMcpServerStatusOnlyUpdate(previous, makeServer({ uid: undefined }))).toBe(false)+ expect(isMcpServerStatusOnlyUpdate(previous, makeServer({ generation: undefined }))).toBe(false)+ })++ it('does not suppress a desired-state change', () => {+ const previous = makeServer()+ const current = makeServer({+ labels: { 'clerum.io/workload': 'replacement' },+ })++ expect(isMcpServerStatusOnlyUpdate(previous, current)).toBe(false)+ })+})++describe('confirmAuthoritativeMcpServerAbsence', () => {+ it('stops before the API read when inventory is not authoritative', async () => {+ const resolveCurrent = vi.fn((): McpServerCRD | undefined => undefined)+ const readCurrent = vi.fn()++ await expect(+ confirmAuthoritativeMcpServerAbsence({+ inventoryAuthoritative: () => false,+ resolveCurrent,+ readCurrent,+ })+ ).resolves.toBe(false)+ expect(resolveCurrent).not.toHaveBeenCalled()+ expect(readCurrent).not.toHaveBeenCalled()+ })++ it('stops before the API read when the cache already contains the current server', async () => {+ const readCurrent = vi.fn()++ await expect(+ confirmAuthoritativeMcpServerAbsence({+ inventoryAuthoritative: () => true,+ resolveCurrent: () => makeServer(),+ readCurrent,+ })+ ).resolves.toBe(false)+ expect(readCurrent).not.toHaveBeenCalled()+ })++ it('rejects absence when the API read returns a current object', async () => {+ const readCurrent = vi.fn().mockResolvedValue({+ metadata: { name: 'web-search', namespace: 'mcp-server' },+ })++ await expect(+ confirmAuthoritativeMcpServerAbsence({+ inventoryAuthoritative: () => true,+ resolveCurrent: () => undefined,+ readCurrent,+ })+ ).resolves.toBe(false)+ expect(readCurrent).toHaveBeenCalledOnce()+ })++ it('propagates a non-404 API read failure', async () => {+ const apiError = Object.assign(new Error('unavailable'), { code: 503 })++ await expect(+ confirmAuthoritativeMcpServerAbsence({+ inventoryAuthoritative: () => true,+ resolveCurrent: () => undefined,+ readCurrent: vi.fn().mockRejectedValue(apiError),+ })+ ).rejects.toBe(apiError)+ })++ it('rejects absence when inventory authority is lost after a 404', async () => {+ const inventoryAuthoritative = vi.fn().mockReturnValueOnce(true).mockReturnValueOnce(false)+ const resolveCurrent = vi.fn((): McpServerCRD | undefined => undefined)++ await expect(+ confirmAuthoritativeMcpServerAbsence({+ inventoryAuthoritative,+ resolveCurrent,+ readCurrent: vi+ .fn()+ .mockRejectedValue(Object.assign(new Error('not found'), { code: 404 })),+ })+ ).resolves.toBe(false)+ expect(resolveCurrent).toHaveBeenCalledOnce()+ })++ it('rejects absence when the server is recreated in cache after a 404', async () => {+ const resolveCurrent = vi+ .fn<() => McpServerCRD | undefined>()+ .mockReturnValueOnce(undefined)+ .mockReturnValueOnce(makeServer())++ await expect(+ confirmAuthoritativeMcpServerAbsence({+ inventoryAuthoritative: () => true,+ resolveCurrent,+ readCurrent: vi+ .fn()+ .mockRejectedValue(Object.assign(new Error('not found'), { code: 404 })),+ })+ ).resolves.toBe(false)+ expect(resolveCurrent).toHaveBeenCalledTimes(2)+ })++ it('confirms absence after a 404 when authority and cache absence remain stable', async () => {+ const inventoryAuthoritative = vi.fn(() => true)+ const resolveCurrent = vi.fn((): McpServerCRD | undefined => undefined)++ await expect(+ confirmAuthoritativeMcpServerAbsence({+ inventoryAuthoritative,+ resolveCurrent,+ readCurrent: vi.fn().mockRejectedValue({ response: { statusCode: 404 } }),+ })+ ).resolves.toBe(true)+ expect(inventoryAuthoritative).toHaveBeenCalledTimes(2)+ expect(resolveCurrent).toHaveBeenCalledTimes(2)+ })+})diff --git a/host-context-controller/src/mcpServerSafety.ts b/host-context-controller/src/mcpServerSafety.tsnew file mode 100644index 000000000..1cad6c02a--- /dev/null+++ b/host-context-controller/src/mcpServerSafety.ts@@ -0,0 +1,57 @@+import type { McpServerCRD } from './types'+import { getErrorCode } from './utils'++export function sameMcpServerDesiredRevision(+ expected: McpServerCRD,+ current: McpServerCRD+): boolean {+ if (expected.name !== current.name || expected.namespace !== current.namespace) return false+ if (expected.uid && current.uid && expected.uid !== current.uid) return false+ if (+ expected.generation !== undefined &&+ current.generation !== undefined &&+ expected.generation !== current.generation+ ) {+ return false+ }++ return (+ JSON.stringify(expected.spec) === JSON.stringify(current.spec) &&+ JSON.stringify(expected.annotations ?? {}) === JSON.stringify(current.annotations ?? {}) &&+ JSON.stringify(expected.labels ?? {}) === JSON.stringify(current.labels ?? {})+ )+}++export function isMcpServerStatusOnlyUpdate(+ previous: McpServerCRD,+ current: McpServerCRD+): boolean {+ return (+ previous.uid === current.uid &&+ previous.generation === current.generation &&+ sameMcpServerDesiredRevision(previous, current)+ )+}++export interface AuthoritativeMcpServerAbsenceCheck {+ inventoryAuthoritative: () => boolean+ resolveCurrent: () => McpServerCRD | undefined+ readCurrent: () => Promise<unknown>+}++export async function confirmAuthoritativeMcpServerAbsence({+ inventoryAuthoritative,+ resolveCurrent,+ readCurrent,+}: AuthoritativeMcpServerAbsenceCheck): Promise<boolean> {+ if (!inventoryAuthoritative() || resolveCurrent()) return false++ try {+ await readCurrent()+ return false+ } catch (error: unknown) {+ if (getErrorCode(error) !== 404) throw error+ }++ return inventoryAuthoritative() && !resolveCurrent()+}diff --git a/host-context-controller/src/networkPolicyReconciler.test.ts b/host-context-controller/src/networkPolicyReconciler.test.tsindex 359b03746..9e8afce2f 100644--- a/host-context-controller/src/networkPolicyReconciler.test.ts+++ b/host-context-controller/src/networkPolicyReconciler.test.ts@@ -3,9 +3,18 @@ import * as k8s from '@kubernetes/client-node'import * as dns from 'node:dns/promises'import { readFileSync } from 'node:fs'import { join } from 'node:path'+import { confirmAuthoritativeMcpServerAbsence } from './mcpServerSafety'import { NetworkPolicyReconciler, PUBLIC_EGRESS_EXCEPT_CIDRS } from './networkPolicyReconciler'import { ContextCRD, McpServerCRD } from './types'+vi.mock('./mcpServerSafety', async () => {+ const actual = await vi.importActual<typeof import('./mcpServerSafety')>('./mcpServerSafety')+ return {+ ...actual,+ confirmAuthoritativeMcpServerAbsence: vi.fn(actual.confirmAuthoritativeMcpServerAbsence),+ }+})+// Mock configvi.mock('./config', () => ({config: {@@ -36,7 +45,17 @@ function makeMockNetworkingApi() {function makeMockCustomApi() {return {- getNamespacedCustomObjectStatus: vi.fn().mockResolvedValue({ status: {} }),+ getNamespacedCustomObject: vi+ .fn()+ .mockRejectedValue(Object.assign(new Error('not found'), { code: 404 })),+ listNamespacedCustomObject: vi.fn().mockResolvedValue({ items: [] }),+ getNamespacedCustomObjectStatus: vi.fn().mockResolvedValue({+ metadata: {+ generation: 7,+ resourceVersion: 'status-rv-default',+ },+ status: {},+ }),patchNamespacedCustomObjectStatus: vi.fn().mockResolvedValue({}),}}@@ -624,6 +643,188 @@ describe('NetworkPolicyReconciler', () => {)})+ it('identity-fences the status patch and preserves unrelated conditions', async () => {+ mockCustomApi.getNamespacedCustomObjectStatus.mockResolvedValueOnce({+ metadata: {+ uid: 'openai-mcp-uid',+ generation: 7,+ resourceVersion: 'status-rv-17',+ },+ status: {+ conditions: [+ {+ type: 'RuntimeReady',+ status: 'True',+ reason: 'DeploymentAvailable',+ message: 'Runtime deployment is available',+ lastTransitionTime: '2026-07-29T00:00:00.000Z',+ observedGeneration: 7,+ },+ ],+ },+ })+ const server: McpServerCRD = {+ name: 'openai-mcp',+ namespace: 'mcp-server',+ uid: 'openai-mcp-uid',+ generation: 7,+ spec: {+ contextRef: 'dev',+ image: 'openai:latest',+ transport: { type: 'streamableHttp', url: 'http://openai:3000', port: 3000 },+ egressBindings: [{ dns: 'api.openai.com', port: 443 }],+ },+ }++ await reconciler.reconcileExternalEgress(server)++ const patch = mockCustomApi.patchNamespacedCustomObjectStatus.mock.calls[0][0].body+ expect(patch.slice(0, 3)).toEqual([+ { op: 'test', path: '/metadata/uid', value: 'openai-mcp-uid' },+ { op: 'test', path: '/metadata/generation', value: 7 },+ { op: 'test', path: '/metadata/resourceVersion', value: 'status-rv-17' },+ ])+ expect(patch).toEqual(+ expect.arrayContaining([+ expect.objectContaining({+ path: '/status/conditions',+ value: expect.arrayContaining([+ expect.objectContaining({+ type: 'RuntimeReady',+ reason: 'DeploymentAvailable',+ }),+ expect.objectContaining({+ type: 'ExternalEgressReady',+ status: 'True',+ observedGeneration: 7,+ }),+ ]),+ }),+ ])+ )+ })++ it('fences every identity field read from status when synthetic input omits them', async () => {+ mockCustomApi.getNamespacedCustomObjectStatus.mockResolvedValueOnce({+ metadata: {+ uid: 'openai-mcp-uid',+ generation: 7,+ resourceVersion: 'status-rv-17',+ },+ status: {},+ })+ const server: McpServerCRD = {+ name: 'openai-mcp',+ namespace: 'mcp-server',+ spec: {+ contextRef: 'dev',+ image: 'openai:latest',+ transport: { type: 'streamableHttp', url: 'http://openai:3000', port: 3000 },+ egressBindings: [{ dns: 'api.openai.com', port: 443 }],+ },+ }++ await reconciler.reconcileExternalEgress(server)++ const patch = mockCustomApi.patchNamespacedCustomObjectStatus.mock.calls[0][0].body+ expect(patch.slice(0, 3)).toEqual([+ { op: 'test', path: '/metadata/uid', value: 'openai-mcp-uid' },+ { op: 'test', path: '/metadata/generation', value: 7 },+ { op: 'test', path: '/metadata/resourceVersion', value: 'status-rv-17' },+ ])+ })++ it.each([+ {+ name: 'UID',+ currentMetadata: {+ uid: 'replacement-uid',+ generation: 7,+ resourceVersion: 'status-rv-18',+ },+ },+ {+ name: 'generation',+ currentMetadata: {+ uid: 'openai-mcp-uid',+ generation: 8,+ resourceVersion: 'status-rv-18',+ },+ },+ ])(+ 'rejects a stale $name before patching external egress status',+ async ({ currentMetadata }) => {+ mockCustomApi.getNamespacedCustomObjectStatus.mockResolvedValueOnce({+ metadata: currentMetadata,+ status: {},+ })+ const server: McpServerCRD = {+ name: 'openai-mcp',+ namespace: 'mcp-server',+ uid: 'openai-mcp-uid',+ generation: 7,+ spec: {+ contextRef: 'dev',+ image: 'openai:latest',+ transport: { type: 'streamableHttp', url: 'http://openai:3000', port: 3000 },+ egressBindings: [{ dns: 'api.openai.com', port: 443 }],+ },+ }++ await expect(reconciler.reconcileExternalEgress(server)).rejects.toThrow(/stale McpServer/i)++ expect(mockCustomApi.patchNamespacedCustomObjectStatus).not.toHaveBeenCalled()+ }+ )++ it('fails closed when a same-generation status writer wins the resourceVersion race', async () => {+ const conflict = Object.assign(new Error('JSON patch test failed'), { code: 409 })+ mockCustomApi.getNamespacedCustomObjectStatus.mockResolvedValueOnce({+ metadata: {+ uid: 'openai-mcp-uid',+ generation: 7,+ resourceVersion: 'status-rv-17',+ },+ status: {+ conditions: [+ {+ type: 'RuntimeReady',+ status: 'True',+ reason: 'DeploymentAvailable',+ lastTransitionTime: '2026-07-29T00:00:00.000Z',+ },+ ],+ },+ })+ mockCustomApi.patchNamespacedCustomObjectStatus.mockRejectedValueOnce(conflict)+ const server: McpServerCRD = {+ name: 'openai-mcp',+ namespace: 'mcp-server',+ uid: 'openai-mcp-uid',+ generation: 7,+ spec: {+ contextRef: 'dev',+ image: 'openai:latest',+ transport: { type: 'streamableHttp', url: 'http://openai:3000', port: 3000 },+ egressBindings: [{ dns: 'api.openai.com', port: 443 }],+ },+ }++ await expect(reconciler.reconcileExternalEgress(server)).rejects.toBe(conflict)++ expect(mockCustomApi.patchNamespacedCustomObjectStatus).toHaveBeenCalledWith(+ expect.objectContaining({+ body: expect.arrayContaining([+ {+ op: 'test',+ path: '/metadata/resourceVersion',+ value: 'status-rv-17',+ },+ ]),+ })+ )+ })+it('fails closed when ExternalEgressReady status cannot be written', async () => {const statusError = new Error('status update denied')mockCustomApi.patchNamespacedCustomObjectStatus.mockRejectedValueOnce(statusError)@@ -1109,6 +1310,14 @@ describe('NetworkPolicyReconciler', () => {await expect((reconciler as any).listAllContextPolicies()).rejects.toThrow('api list denied')})+ it('propagates all-context mcp-host egress policy list failures', async () => {+ mockApi.listNamespacedNetworkPolicy.mockRejectedValueOnce(new Error('api list denied'))++ await expect((reconciler as any).listAllContextEgressPolicies()).rejects.toThrow(+ 'api list denied'+ )+ })+it('propagates all external-egress policy list failures', async () => {mockApi.listNamespacedNetworkPolicy.mockRejectedValueOnce(new Error('api list denied'))@@ -1119,6 +1328,151 @@ describe('NetworkPolicyReconciler', () => {})describe('startup fullReconcile', () => {+ it('does not reconcile a queued Context when its current contextId changed', async () => {+ const queuedContext: ContextCRD = {+ name: 'mutable-context-resource',+ namespace: 'mcp-server',+ spec: { contextId: 'captured-context', mcpServers: [] },+ }+ const currentContext: ContextCRD = {+ ...queuedContext,+ spec: { contextId: 'replacement-context', mcpServers: [] },+ }+ const reconcileContext = vi.spyOn(reconciler, 'reconcileContext').mockResolvedValue(undefined)+ const effectKeys: string[] = []++ await reconciler.fullReconcile([queuedContext], [], {+ ensureDefaults: false,+ contextInventoryAuthoritative: () => false,+ resolveCurrentContext: () => currentContext,+ runContextEffect: async (contextId, work) => {+ effectKeys.push(contextId)+ await work()+ },+ })++ expect(effectKeys).toEqual(['captured-context'])+ expect(reconcileContext).not.toHaveBeenCalled()+ })++ it('deletes orphaned Context policies in all three namespaces through the canonical contextId effect key', async () => {+ const effectKeys: string[] = []+ mockApi.listNamespacedNetworkPolicy.mockImplementation(+ async ({ namespace, labelSelector }: { namespace?: string; labelSelector?: string }) => {+ if (namespace === 'mcp-server' && labelSelector?.includes('context-allow')) {+ return {+ items: [+ {+ metadata: {+ name: 'ctx-orphan-context-old-server',+ labels: { 'clerum.io/context': 'orphan-context' },+ },+ },+ ],+ }+ }+ if (namespace === 'mcp-host' && labelSelector?.includes('context-allow')) {+ return {+ items: [+ {+ metadata: {+ name: 'ctx-orphan-context-old-server-egress',+ labels: { 'clerum.io/context': 'orphan-context' },+ },+ },+ ],+ }+ }+ if (namespace === 'rpc-proxy' && labelSelector?.includes('rpc-proxy-egress')) {+ return {+ items: [+ {+ metadata: {+ name: 'rpc-egress-orphan-context-old-server',+ labels: { 'clerum.io/context': 'orphan-context' },+ },+ },+ ],+ }+ }+ return { items: [] }+ }+ )++ await reconciler.fullReconcile([], [], {+ ensureDefaults: false,+ contextInventoryAuthoritative: () => true,+ runContextEffect: async (contextId, work) => {+ effectKeys.push(contextId)+ await work()+ },+ })++ expect(effectKeys).toEqual(['orphan-context', 'orphan-context', 'orphan-context'])+ expect(mockApi.deleteNamespacedNetworkPolicy).toHaveBeenCalledWith({+ name: 'ctx-orphan-context-old-server',+ namespace: 'mcp-server',+ })+ expect(mockApi.deleteNamespacedNetworkPolicy).toHaveBeenCalledWith({+ name: 'ctx-orphan-context-old-server-egress',+ namespace: 'mcp-host',+ })+ expect(mockApi.deleteNamespacedNetworkPolicy).toHaveBeenCalledWith({+ name: 'rpc-egress-orphan-context-old-server',+ namespace: 'rpc-proxy',+ })+ })++ it('routes desired and orphan Context policy lanes through canonical contextId effect keys', async () => {+ const desiredContext: ContextCRD = {+ name: 'desired-context-resource',+ namespace: 'mcp-server',+ spec: { contextId: 'desired-context', mcpServers: [] },+ }+ const effectKeys: string[] = []+ vi.spyOn(reconciler, 'reconcileContext').mockResolvedValue(undefined)+ mockApi.listNamespacedNetworkPolicy.mockImplementation(+ async ({ namespace, labelSelector }: { namespace?: string; labelSelector?: string }) => {+ if (namespace === 'mcp-server' && labelSelector?.includes('context-allow')) {+ return {+ items: [+ {+ metadata: {+ name: 'ctx-orphan-context-old-server',+ labels: { 'clerum.io/context': 'orphan-context' },+ },+ },+ ],+ }+ }+ if (namespace === 'rpc-proxy' && labelSelector?.includes('rpc-proxy-egress')) {+ return {+ items: [+ {+ metadata: {+ name: 'rpc-egress-orphan-context-old-server',+ labels: { 'clerum.io/context': 'orphan-context' },+ },+ },+ ],+ }+ }+ return { items: [] }+ }+ )++ await reconciler.fullReconcile([desiredContext], [], {+ ensureDefaults: false,+ contextInventoryAuthoritative: () => true,+ runContextEffect: async (contextId, work) => {+ effectKeys.push(contextId)+ await work()+ },+ })++ expect(effectKeys).toEqual(['desired-context', 'orphan-context', 'orphan-context'])+ })+it('reconciles external egress policies for existing servers on startup', async () => {const server: McpServerCRD = {name: 'airtable-mcp',@@ -1209,6 +1563,236 @@ describe('NetworkPolicyReconciler', () => {namespace: 'mcp-server',})})++ it('finishes desired Context reconciliation but stops Context and rpc-proxy orphan cleanup when authority is lost after inventory listing', async () => {+ const desiredContext: ContextCRD = {+ name: 'current',+ namespace: 'mcp-server',+ spec: { contextId: 'current', mcpServers: [] },+ }+ const reconcileContext = vi.spyOn(reconciler, 'reconcileContext').mockResolvedValue(undefined)+ const contextInventoryAuthoritative = vi+ .fn()+ .mockReturnValueOnce(true)+ .mockReturnValueOnce(false)+ .mockReturnValue(true)++ mockApi.listNamespacedNetworkPolicy.mockImplementation(+ async ({ namespace, labelSelector }: { namespace?: string; labelSelector?: string }) => {+ if (namespace === 'mcp-server' && labelSelector?.includes('policy-type=context-allow')) {+ return {+ items: [+ {+ metadata: {+ name: 'ctx-deleted-context-old-server',+ labels: { 'clerum.io/context': 'deleted-context' },+ },+ },+ ],+ }+ }+ if (labelSelector?.includes('external-egress')) return { items: [] }+ return { items: [] }+ }+ )++ await reconciler.fullReconcile([desiredContext], [], {+ ensureDefaults: false,+ contextInventoryAuthoritative,+ })++ expect(reconcileContext).toHaveBeenCalledWith(desiredContext)+ expect(contextInventoryAuthoritative).toHaveBeenCalledTimes(2)+ expect(mockApi.deleteNamespacedNetworkPolicy).not.toHaveBeenCalledWith({+ name: 'ctx-deleted-context-old-server',+ namespace: 'mcp-server',+ })+ expect(mockApi.listNamespacedNetworkPolicy).not.toHaveBeenCalledWith(+ expect.objectContaining({+ namespace: 'rpc-proxy',+ labelSelector: expect.stringContaining('policy-type=rpc-proxy-egress'),+ })+ )+ })++ it('finishes desired McpServer reconciliation but stops external-egress orphan cleanup when authority is lost after inventory listing', async () => {+ const desiredServer: McpServerCRD = {+ name: 'current-server',+ namespace: 'mcp-server',+ spec: {+ contextRef: 'current',+ image: 'current:latest',+ transport: { type: 'streamableHttp', url: 'http://current:3000', port: 3000 },+ },+ }+ const reconcileExternalEgress = vi+ .spyOn(reconciler, 'reconcileExternalEgress')+ .mockResolvedValue(undefined)+ const serverInventoryAuthoritative = vi+ .fn()+ .mockReturnValueOnce(true)+ .mockReturnValueOnce(false)+ .mockReturnValue(true)++ mockApi.listNamespacedNetworkPolicy.mockImplementation(+ async ({ labelSelector }: { labelSelector?: string }) => {+ if (labelSelector?.includes('external-egress')) {+ return {+ items: [+ {+ metadata: {+ name: 'ext-egress-deleted-server-api-example-com-443',+ labels: { 'clerum.io/mcpserver': 'deleted-server' },+ },+ },+ ],+ }+ }+ return { items: [] }+ }+ )++ await reconciler.fullReconcile([], [desiredServer], {+ ensureDefaults: false,+ serverInventoryComplete: true,+ serverInventoryAuthoritative,+ })++ expect(reconcileExternalEgress).toHaveBeenCalledWith(desiredServer)+ expect(serverInventoryAuthoritative).toHaveBeenCalledTimes(2)+ expect(mockApi.deleteNamespacedNetworkPolicy).not.toHaveBeenCalledWith({+ name: 'ext-egress-deleted-server-api-example-com-443',+ namespace: 'mcp-server',+ })+ })++ it('does not delete any Context policy lane when a same-contextId CRD exists before its watch event arrives', async () => {+ mockCustomApi.listNamespacedCustomObject.mockResolvedValue({+ items: [{ metadata: { name: 'recreated-context' }, spec: { contextId: 'recreated' } }],+ })+ mockApi.listNamespacedNetworkPolicy.mockImplementation(+ async ({ namespace, labelSelector }: { namespace?: string; labelSelector?: string }) => {+ if (namespace === 'mcp-server' && labelSelector?.includes('context-allow')) {+ return {+ items: [+ {+ metadata: {+ name: 'ctx-recreated-server',+ labels: { 'clerum.io/context': 'recreated' },+ },+ },+ ],+ }+ }+ if (namespace === 'mcp-host' && labelSelector?.includes('context-allow')) {+ return {+ items: [+ {+ metadata: {+ name: 'ctx-recreated-server-egress',+ labels: { 'clerum.io/context': 'recreated' },+ },+ },+ ],+ }+ }+ if (namespace === 'rpc-proxy' && labelSelector?.includes('rpc-proxy-egress')) {+ return {+ items: [+ {+ metadata: {+ name: 'rpc-egress-recreated-server',+ labels: { 'clerum.io/context': 'recreated' },+ },+ },+ ],+ }+ }+ return { items: [] }+ }+ )++ await reconciler.fullReconcile([], [], {+ ensureDefaults: false,+ contextInventoryAuthoritative: () => true,+ })++ expect(mockCustomApi.listNamespacedCustomObject).toHaveBeenCalled()+ expect(mockApi.listNamespacedNetworkPolicy).toHaveBeenCalledWith(+ expect.objectContaining({+ namespace: 'mcp-host',+ labelSelector: expect.stringContaining('policy-type=context-allow'),+ })+ )+ expect(mockApi.deleteNamespacedNetworkPolicy).not.toHaveBeenCalled()+ })++ it('does not delete external-egress policy when a same-name McpServer exists before ADDED arrives', async () => {+ mockCustomApi.getNamespacedCustomObject.mockResolvedValue({+ metadata: { name: 'recreated-server', uid: 'new-uid' },+ })+ mockApi.listNamespacedNetworkPolicy.mockImplementation(+ async ({ labelSelector }: { labelSelector?: string }) => {+ if (labelSelector?.includes('external-egress')) {+ return {+ items: [+ {+ metadata: {+ name: 'ext-egress-recreated-server-api-example-com-443',+ labels: { 'clerum.io/mcpserver': 'recreated-server' },+ },+ },+ ],+ }+ }+ return { items: [] }+ }+ )++ await reconciler.fullReconcile([], [], {+ ensureDefaults: false,+ serverInventoryComplete: true,+ serverInventoryAuthoritative: () => true,+ })++ expect(mockCustomApi.getNamespacedCustomObject).toHaveBeenCalledWith(+ expect.objectContaining({ plural: 'mcpservers', name: 'recreated-server' })+ )+ expect(mockApi.deleteNamespacedNetworkPolicy).not.toHaveBeenCalled()+ })++ it('delegates startup McpServer orphan safety to the canonical absence helper', async () => {+ mockApi.listNamespacedNetworkPolicy.mockImplementation(+ async ({ labelSelector }: { labelSelector?: string }) => {+ if (labelSelector?.includes('external-egress')) {+ return {+ items: [+ {+ metadata: {+ name: 'ext-egress-orphan-server-api-example-com-443',+ labels: { 'clerum.io/mcpserver': 'orphan-server' },+ },+ },+ ],+ }+ }+ return { items: [] }+ }+ )++ await reconciler.fullReconcile([], [], {+ ensureDefaults: false,+ serverInventoryComplete: true,+ serverInventoryAuthoritative: () => true,+ })++ expect(confirmAuthoritativeMcpServerAbsence).toHaveBeenCalledTimes(1)+ expect(confirmAuthoritativeMcpServerAbsence).toHaveBeenCalledWith({+ inventoryAuthoritative: expect.any(Function),+ resolveCurrent: expect.any(Function),+ readCurrent: expect.any(Function),+ })+ })})describe('L3 — cleanupExternalEgress', () => {diff --git a/host-context-controller/src/networkPolicyReconciler.ts b/host-context-controller/src/networkPolicyReconciler.tsindex aa19d54ca..8c96b5fdc 100644--- a/host-context-controller/src/networkPolicyReconciler.ts+++ b/host-context-controller/src/networkPolicyReconciler.ts@@ -25,6 +25,7 @@ import {MCPSERVER_LABEL,POLICY_TYPE_LABEL,} from './constants'+import { confirmAuthoritativeMcpServerAbsence } from './mcpServerSafety'import {ContextCRD,EgressBinding,@@ -36,7 +37,7 @@ import {import { applyNetworkPolicy, getErrorCode } from './utils'type JsonPatchOperation = {- op: 'add' | 'replace' | 'remove'+ op: 'add' | 'replace' | 'remove' | 'test'path: stringvalue?: unknown}@@ -44,6 +45,7 @@ type JsonPatchOperation = {const GROUP = 'clerum.io'const VERSION = 'v1alpha1'const PLURAL_MCPSERVERS = 'mcpservers'+const PLURAL_CONTEXTS = 'contexts'const CONTEXT_LABEL = 'clerum.io/context'const EGRESS_CLASS_LABEL = 'clerum.io/egress-class'const RPC_PROXY_EGRESS_POLICY_TYPE = 'rpc-proxy-egress'@@ -156,6 +158,23 @@ function k8sApiEgressPodSelector(namespace: string): k8s.V1LabelSelector {return { matchLabels: { 'clerum.io/k8s-api-egress': 'true' } }}+export interface NetworkPolicyFullReconcileOptions {+ serverInventoryComplete?: boolean+ ensureDefaults?: boolean+ /**+ * Dynamic authority checks are intentionally callbacks: watch authority can+ * be lost after the startup snapshot but before an orphan delete begins.+ * Omitted callbacks preserve the historical authoritative-by-default API.+ */+ contextInventoryAuthoritative?: () => boolean+ serverInventoryAuthoritative?: () => boolean+ runContextEffect?: (contextId: string, work: () => Promise<void>) => Promise<void>+ runServerEffect?: (serverName: string, work: () => Promise<void>) => Promise<void>+ resolveCurrentContext?: (name: string) => ContextCRD | undefined+ resolveCurrentContextById?: (contextId: string) => ContextCRD | undefined+ resolveCurrentServer?: (name: string) => McpServerCRD | undefined+}+export class NetworkPolicyReconciler {private networkingApi: k8s.NetworkingV1Apiprivate customApi: k8s.CustomObjectsApi@@ -630,12 +649,16 @@ export class NetworkPolicyReconciler {/*** Delete all NetworkPolicies for a deleted Context.*/- async reconcileDeleteContext(contextId: string): Promise<void> {+ async reconcileDeleteContext(+ contextId: string,+ deleteAllowed?: () => Promise<boolean>+ ): Promise<void> {console.log(`[NetPol] Context "${contextId}" deleted — removing all policies`)const policies = await this.listPoliciesForContext(contextId)for (const policy of policies) {const name = policy.metadata?.name || ''+ if (deleteAllowed && !(await deleteAllowed())) returnawait this.deletePolicy(name)}@@ -643,11 +666,12 @@ export class NetworkPolicyReconciler {const egressPolicies = await this.listEgressPoliciesForContext(contextId)for (const policy of egressPolicies) {const name = policy.metadata?.name || ''+ if (deleteAllowed && !(await deleteAllowed())) returnawait this.deleteEgressPolicy(name)}// Also delete L2 rpc-proxy egress policies- await this.deleteRpcProxyPoliciesForContext(contextId)+ await this.deleteRpcProxyPoliciesForContext(contextId, deleteAllowed)}/**@@ -656,7 +680,7 @@ export class NetworkPolicyReconciler {async fullReconcile(contexts: ContextCRD[],servers: McpServerCRD[] = [],- options: { serverInventoryComplete?: boolean; ensureDefaults?: boolean } = {}+ options: NetworkPolicyFullReconcileOptions = {}): Promise<void> {console.log(`[NetPol] Running full reconciliation for ${contexts.length} Context(s)`)@@ -664,56 +688,156 @@ export class NetworkPolicyReconciler {await this.ensureDefaultPolicies()}+ const runContextEffect =+ options.runContextEffect ?? ((_contextId: string, work: () => Promise<void>) => work())+ const runServerEffect =+ options.runServerEffect ?? ((_serverName: string, work: () => Promise<void>) => work())+// Reconcile each contextfor (const context of contexts) {- await this.reconcileContext(context)+ const contextId = context.spec.contextId+ await runContextEffect(contextId, async () => {+ const current = options.resolveCurrentContext+ ? options.resolveCurrentContext(context.name)+ : context+ if (!current || current.spec.contextId !== contextId) return+ await this.reconcileContext(current)+ })}// Reconcile external egress for all existing servers on startup so a// controller restart converges pre-existing McpServer CRDs too.for (const server of servers) {- await this.reconcileExternalEgress(server)+ await runServerEffect(server.name, async () => {+ const current = options.resolveCurrentServer+ ? options.resolveCurrentServer(server.name)+ : server+ if (!current) return+ await this.reconcileExternalEgress(current)+ })}- // Delete policies for contexts that no longer exist- const desiredContextIds = new Set(contexts.map(c => c.spec.contextId))- const allContextPolicies = await this.listAllContextPolicies()-- for (const policy of allContextPolicies) {- const contextId = policy.metadata?.labels?.[CONTEXT_LABEL]- if (contextId && !desiredContextIds.has(contextId)) {- const name = policy.metadata?.name || ''- console.log(- `[NetPol] Deleting orphaned policy "${name}" (context "${contextId}" no longer exists)`+ // Authority is monotonic within this pass. Once a watch loses authority,+ // this inventory snapshot cannot safely become authoritative again even if+ // the callback flips back before the next delete.+ let contextAuthorityLost = false+ let contextAuthorityWarningLogged = false+ const contextCleanupAuthoritative = (): boolean => {+ if (+ !contextAuthorityLost &&+ options.contextInventoryAuthoritative &&+ !options.contextInventoryAuthoritative()+ ) {+ contextAuthorityLost = true+ }+ if (contextAuthorityLost && !contextAuthorityWarningLogged) {+ contextAuthorityWarningLogged = true+ console.warn(+ '[NetPol] Skipping remaining Context policy orphan cleanup because Context inventory authority was lost')- await this.deletePolicy(name)}+ return !contextAuthorityLost}- // Also clean up orphaned rpc-proxy egress policies- const allRpcProxyPolicies = await this.listAllRpcProxyEgressPolicies()- for (const policy of allRpcProxyPolicies) {- const ctxId = policy.metadata?.labels?.[CONTEXT_LABEL]- if (ctxId && !desiredContextIds.has(ctxId)) {- const pName = policy.metadata?.name || ''- console.log(`[NetPol] Deleting orphaned rpc-proxy egress policy "${pName}"`)- await this.deletePolicyInNamespace(config.rpcProxyNamespace, pName)+ const desiredContextIds = new Set(contexts.map(c => c.spec.contextId))+ const cleanupOrphanedContextPolicies = async (+ listPolicies: () => Promise<k8s.V1NetworkPolicy[]>,+ deletePolicy: (name: string) => Promise<void>,+ describePolicy: (name: string, contextId: string) => string+ ): Promise<void> => {+ if (!contextCleanupAuthoritative()) return+ const policies = await listPolicies()+ for (const policy of policies) {+ const contextId = policy.metadata?.labels?.[CONTEXT_LABEL]+ if (contextId && !desiredContextIds.has(contextId)) {+ const name = policy.metadata?.name || ''+ await runContextEffect(contextId, async () => {+ if (+ !(await this.contextOrphanDeleteAllowed(+ contextId,+ contextCleanupAuthoritative,+ options.resolveCurrentContextById+ ))+ ) {+ return+ }+ console.log(describePolicy(name, contextId))+ await deletePolicy(name)+ })+ }}}+ // Delete orphaned Context policies across every L2 lane. Each lane uses+ // the canonical contextId effect key and rechecks authority plus live CRD+ // presence immediately before its delete.+ await cleanupOrphanedContextPolicies(+ () => this.listAllContextPolicies(),+ name => this.deletePolicy(name),+ (name, contextId) =>+ `[NetPol] Deleting orphaned policy "${name}" (context "${contextId}" no longer exists)`+ )+ await cleanupOrphanedContextPolicies(+ () => this.listAllContextEgressPolicies(),+ name => this.deleteEgressPolicy(name),+ name => `[NetPol] Deleting orphaned L2 egress policy "${name}"`+ )+ await cleanupOrphanedContextPolicies(+ () => this.listAllRpcProxyEgressPolicies(),+ name => this.deletePolicyInNamespace(config.rpcProxyNamespace, name),+ name => `[NetPol] Deleting orphaned rpc-proxy egress policy "${name}"`+ )++ let serverAuthorityLost = false+ let serverAuthorityWarningLogged = false+ const serverCleanupAuthoritative = (): boolean => {+ if (+ !serverAuthorityLost &&+ options.serverInventoryAuthoritative &&+ !options.serverInventoryAuthoritative()+ ) {+ serverAuthorityLost = true+ }+ if (serverAuthorityLost && !serverAuthorityWarningLogged) {+ serverAuthorityWarningLogged = true+ console.warn(+ '[NetPol] Skipping remaining external egress orphan cleanup because McpServer inventory authority was lost'+ )+ }+ return !serverAuthorityLost+ }+// Clean up external egress policies for servers that no longer exist.- if (options.serverInventoryComplete !== false) {+ if (options.serverInventoryComplete !== false && serverCleanupAuthoritative()) {const desiredServerNames = new Set(servers.map(s => s.name))const allExternalPolicies = await this.listAllExternalEgressPolicies()for (const policy of allExternalPolicies) {const serverName = policy.metadata?.labels?.[MCPSERVER_LABEL]if (serverName && !desiredServerNames.has(serverName)) {const name = policy.metadata?.name || ''- console.log(`[NetPol] Deleting orphaned external egress policy "${name}"`)- await this.deletePolicyInNamespace(config.namespace, name)+ await runServerEffect(serverName, async () => {+ if (+ !(await confirmAuthoritativeMcpServerAbsence({+ inventoryAuthoritative: serverCleanupAuthoritative,+ resolveCurrent: () => options.resolveCurrentServer?.(serverName),+ readCurrent: () =>+ this.customApi.getNamespacedCustomObject({+ group: GROUP,+ version: VERSION,+ namespace: config.namespace,+ plural: PLURAL_MCPSERVERS,+ name: serverName,+ }),+ }))+ ) {+ return+ }+ console.log(`[NetPol] Deleting orphaned external egress policy "${name}"`)+ await this.deletePolicyInNamespace(config.namespace, name)+ })}}- } else {+ } else if (options.serverInventoryComplete === false) {console.warn('[NetPol] Skipping external egress orphan cleanup because server inventory is incomplete')@@ -722,6 +846,24 @@ export class NetworkPolicyReconciler {console.log('[NetPol] Full reconciliation complete')}+ private async contextOrphanDeleteAllowed(+ contextId: string,+ inventoryAuthoritative: () => boolean,+ resolveCurrentContextById?: (contextId: string) => ContextCRD | undefined+ ): Promise<boolean> {+ if (!inventoryAuthoritative() || resolveCurrentContextById?.(contextId)) return false++ const response = (await this.customApi.listNamespacedCustomObject({+ group: GROUP,+ version: VERSION,+ namespace: config.namespace,+ plural: PLURAL_CONTEXTS,+ })) as { items?: Array<{ spec?: { contextId?: string } }> }+ if ((response.items ?? []).some(context => context.spec?.contextId === contextId)) return false++ return inventoryAuthoritative() && !resolveCurrentContextById?.(contextId)+ }+// ─── L3 External Egress ────────────────────────────────────────────/**@@ -989,7 +1131,8 @@ export class NetworkPolicyReconciler {async cleanupExternalEgress(serverName: string,namespace: string,- policies?: k8s.V1NetworkPolicy[]+ policies?: k8s.V1NetworkPolicy[],+ deleteAllowed?: () => Promise<boolean>): Promise<void> {const policiesToDelete =policies ?? (await this.listExternalEgressPoliciesForServer(serverName, namespace))@@ -998,6 +1141,7 @@ export class NetworkPolicyReconciler {const name = policy.metadata?.nameif (!name) continuetry {+ if (deleteAllowed && !(await deleteAllowed())) returnawait this.networkingApi.deleteNamespacedNetworkPolicy({ name, namespace })console.log(`[NetPol] Deleted external egress policy "${name}"`)} catch (error: unknown) {@@ -1090,6 +1234,13 @@ export class NetworkPolicyReconciler {): Promise<void> {let currentStatus: McpServerCrdStatus = {}let hasStatusObject = false+ let currentMetadata:+ | {+ uid?: string+ generation?: number+ resourceVersion?: string+ }+ | undefinedtry {const current = (await this.customApi.getNamespacedCustomObjectStatus({@@ -1098,7 +1249,15 @@ export class NetworkPolicyReconciler {namespace: server.namespace,plural: PLURAL_MCPSERVERS,name: server.name,- })) as { status?: McpServerCrdStatus }+ })) as {+ metadata?: {+ uid?: string+ generation?: number+ resourceVersion?: string+ }+ status?: McpServerCrdStatus+ }+ currentMetadata = current.metadatahasStatusObject = typeof current.status === 'object' && current.status !== nullcurrentStatus = current.status ?? {}} catch (error) {@@ -1115,6 +1274,19 @@ export class NetworkPolicyReconciler {throw error}+ if (+ (server.uid !== undefined && currentMetadata?.uid !== server.uid) ||+ (server.generation !== undefined && currentMetadata?.generation !== server.generation)+ ) {+ throw new Error(+ `Refusing to write external egress status for stale McpServer "${server.name}": ` ++ `expected uid=${String(server.uid)} generation=${String(server.generation)}, ` ++ `read uid=${String(currentMetadata?.uid)} generation=${String(+ currentMetadata?.generation+ )}`+ )+ }+const nextConditions = this.mergeStatusCondition(currentStatus.conditions ?? [], {type: 'ExternalEgressReady',status,@@ -1138,12 +1310,33 @@ export class NetworkPolicyReconciler {return}- const statusPatch: JsonPatchOperation[] = hasStatusObject+ const identityFence: JsonPatchOperation[] = []+ const expectedUid = server.uid ?? currentMetadata?.uid+ if (expectedUid !== undefined) {+ identityFence.push({ op: 'test', path: '/metadata/uid', value: expectedUid })+ }+ const expectedGeneration = server.generation ?? currentMetadata?.generation+ if (expectedGeneration !== undefined) {+ identityFence.push({+ op: 'test',+ path: '/metadata/generation',+ value: expectedGeneration,+ })+ }+ if (currentMetadata?.resourceVersion !== undefined) {+ identityFence.push({+ op: 'test',+ path: '/metadata/resourceVersion',+ value: currentMetadata.resourceVersion,+ })+ }+ const statusMutation: JsonPatchOperation[] = hasStatusObject? [{ op: 'add', path: '/status/resolvedEgressIPs', value: stableResolvedEgressIPs },{ op: 'add', path: '/status/conditions', value: nextConditions },]: [{ op: 'add', path: '/status', value: nextStatus }]+ const statusPatch = [...identityFence, ...statusMutation]try {await this.customApi.patchNamespacedCustomObjectStatus({@@ -1198,6 +1391,20 @@ export class NetworkPolicyReconciler {}}+ /** List all L2 context-allow egress policies in the mcp-host namespace. */+ private async listAllContextEgressPolicies(): Promise<k8s.V1NetworkPolicy[]> {+ try {+ const response = await this.networkingApi.listNamespacedNetworkPolicy({+ namespace: config.hostNamespace,+ labelSelector: `${MANAGED_BY_LABEL}=${MANAGED_BY_VALUE},${POLICY_TYPE_LABEL}=context-allow`,+ })+ return response.items || []+ } catch (error) {+ console.error('[NetPol] Failed to list all Context egress policies:', error)+ throw error+ }+ }+/** List all external-egress policies in the MCP server namespace. */private async listAllExternalEgressPolicies(): Promise<k8s.V1NetworkPolicy[]> {try {@@ -1326,11 +1533,15 @@ export class NetworkPolicyReconciler {}/** Delete all rpc-proxy egress policies for a given context. */- private async deleteRpcProxyPoliciesForContext(contextId: string): Promise<void> {+ private async deleteRpcProxyPoliciesForContext(+ contextId: string,+ deleteAllowed?: () => Promise<boolean>+ ): Promise<void> {try {const policies = await this.listRpcProxyEgressPoliciesForContext(contextId)for (const policy of policies) {const name = policy.metadata?.name || ''+ if (deleteAllowed && !(await deleteAllowed())) returnawait this.deletePolicyInNamespace(config.rpcProxyNamespace, name)}} catch (error) {diff --git a/host-context-controller/src/reconciler.test.ts b/host-context-controller/src/reconciler.test.tsindex 394e4b2af..dbaaf79e9 100644--- a/host-context-controller/src/reconciler.test.ts+++ b/host-context-controller/src/reconciler.test.ts@@ -404,7 +404,12 @@ describe('PR-B B1 — writeStatusCondition', () => {const getPatchedConditions = () => {const patch = customApi.patchNamespacedCustomObjectStatus.mock.calls[0][0]- const op = patch.body[0]+ const op = patch.body.find(+ (candidate: { op?: string; path?: string }) =>+ candidate.op === 'add' &&+ (candidate.path === '/status' || candidate.path === '/status/conditions')+ )+ if (!op) throw new Error('status condition add operation was not emitted')const conditions = op.path === '/status' ? op.value.conditions : op.valuereturn { patch, op, conditions }}@@ -506,6 +511,216 @@ describe('PR-B B1 — writeStatusCondition', () => {expect(types).toContain('Ready')})+ it('records the reconciled McpServer generation on status conditions', async () => {+ const server = {+ ...makeServer({ name: 'pg' }),+ generation: 17,+ }++ await reconciler.writeStatusCondition(server, {+ type: 'Ready',+ status: 'True',+ reason: 'ReconcileSuccess',+ message: 'done',+ })++ const { conditions } = getPatchedConditions()+ expect(conditions.find((condition: { type: string }) => condition.type === 'Ready')).toEqual(+ expect.objectContaining({+ status: 'True',+ observedGeneration: 17,+ })+ )+ })++ it('re-reads and preserves a concurrent condition after a resourceVersion conflict', async () => {+ const networkReady = {+ type: 'NetworkReady',+ status: 'True',+ reason: 'NetworkPoliciesApplied',+ message: 'network ready',+ lastTransitionTime: '2020-01-01T00:00:00.000Z',+ }+ const externalEgressReady = {+ type: 'ExternalEgressReady',+ status: 'True',+ reason: 'EgressPolicyApplied',+ message: 'external egress ready',+ lastTransitionTime: '2020-01-02T00:00:00.000Z',+ }+ customApi.getNamespacedCustomObjectStatus+ .mockResolvedValueOnce({+ metadata: { resourceVersion: '100' },+ status: { conditions: [networkReady] },+ })+ .mockResolvedValueOnce({+ metadata: { resourceVersion: '101' },+ status: { conditions: [networkReady, externalEgressReady] },+ })+ customApi.patchNamespacedCustomObjectStatus+ .mockRejectedValueOnce(Object.assign(new Error('resourceVersion conflict'), { code: 409 }))+ .mockResolvedValueOnce({})++ const server: McpServerCRD = {+ ...makeServer({ name: 'pg' }),+ uid: 'uid-pg',+ generation: 17,+ }+ await reconciler.writeStatusCondition(server, {+ type: 'Ready',+ status: 'True',+ reason: 'ReconcileSuccess',+ message: 'done',+ })++ expect(customApi.getNamespacedCustomObjectStatus).toHaveBeenCalledTimes(2)+ expect(customApi.patchNamespacedCustomObjectStatus).toHaveBeenCalledTimes(2)+ expect(customApi.patchNamespacedCustomObjectStatus.mock.calls[0][0].body).toContainEqual({+ op: 'test',+ path: '/metadata/resourceVersion',+ value: '100',+ })+ const secondPatch = customApi.patchNamespacedCustomObjectStatus.mock.calls[1][0].body+ expect(secondPatch).toContainEqual({+ op: 'test',+ path: '/metadata/resourceVersion',+ value: '101',+ })+ const conditionPatch = secondPatch.find(+ (candidate: { op?: string; path?: string }) =>+ candidate.op === 'add' && candidate.path === '/status/conditions'+ )+ expect(conditionPatch?.value.map((written: { type: string }) => written.type)).toEqual([+ 'NetworkReady',+ 'ExternalEgressReady',+ 'Ready',+ ])+ })++ it('bounds resourceVersion conflict retries', async () => {+ const currentStatus = {+ metadata: { resourceVersion: '100' },+ status: { conditions: [] },+ }+ customApi.getNamespacedCustomObjectStatus+ .mockResolvedValueOnce(currentStatus)+ .mockResolvedValueOnce(currentStatus)+ .mockResolvedValueOnce(currentStatus)+ const conflict = Object.assign(new Error('resourceVersion conflict'), { code: 422 })+ customApi.patchNamespacedCustomObjectStatus+ .mockRejectedValueOnce(conflict)+ .mockRejectedValueOnce(conflict)+ .mockRejectedValueOnce(conflict)+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined)++ await reconciler.writeStatusCondition(+ {+ ...makeServer({ name: 'pg' }),+ uid: 'uid-pg',+ generation: 17,+ },+ {+ type: 'Ready',+ status: 'True',+ reason: 'ReconcileSuccess',+ message: 'done',+ }+ )++ expect(customApi.getNamespacedCustomObjectStatus).toHaveBeenCalledTimes(3)+ expect(customApi.patchNamespacedCustomObjectStatus).toHaveBeenCalledTimes(3)+ expect(warn).toHaveBeenCalledWith(+ expect.stringContaining('Failed to write status condition Ready=True'),+ conflict+ )+ warn.mockRestore()+ })++ it('guards the status patch with the captured UID, generation, and resourceVersion', async () => {+ const staleServer: McpServerCRD = {+ ...makeServer({ name: 'recreated' }),+ uid: 'uid-before-recreation',+ generation: 1,+ }+ customApi.getNamespacedCustomObjectStatus.mockResolvedValueOnce({+ metadata: { resourceVersion: '100' },+ status: { conditions: [] },+ })+ const writeFailure = Object.assign(new Error('status API unavailable'), {+ code: 500,+ })+ customApi.patchNamespacedCustomObjectStatus.mockImplementationOnce(async request => {+ expect(request.body.slice(0, 3)).toEqual([+ {+ op: 'test',+ path: '/metadata/uid',+ value: 'uid-before-recreation',+ },+ {+ op: 'test',+ path: '/metadata/generation',+ value: 1,+ },+ {+ op: 'test',+ path: '/metadata/resourceVersion',+ value: '100',+ },+ ])+ throw writeFailure+ })+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined)++ await reconciler.writeStatusCondition(staleServer, {+ type: 'Ready',+ status: 'True',+ reason: 'ReconcileSuccess',+ message: 'stale reconcile result',+ })++ expect(warn).toHaveBeenCalledWith(+ expect.stringContaining('Failed to write status condition Ready=True'),+ writeFailure+ )+ warn.mockRestore()+ })++ it('refreshes observedGeneration even when the condition payload is otherwise unchanged', async () => {+ customApi.getNamespacedCustomObjectStatus.mockResolvedValueOnce({+ status: {+ conditions: [+ {+ type: 'Ready',+ status: 'True',+ reason: 'ReconcileSuccess',+ message: 'done',+ observedGeneration: 16,+ lastTransitionTime: '2020-01-01T00:00:00.000Z',+ },+ ],+ },+ })+ const server = {+ ...makeServer({ name: 'pg' }),+ generation: 17,+ }++ await reconciler.writeStatusCondition(server, {+ type: 'Ready',+ status: 'True',+ reason: 'ReconcileSuccess',+ message: 'done',+ })++ const { conditions } = getPatchedConditions()+ expect(conditions.find((condition: { type: string }) => condition.type === 'Ready')).toEqual(+ expect.objectContaining({+ observedGeneration: 17,+ lastTransitionTime: '2020-01-01T00:00:00.000Z',+ })+ )+ })+it('creates the status object when the CRD has no status yet', async () => {customApi.getNamespacedCustomObjectStatus.mockResolvedValueOnce({})@@ -607,6 +822,162 @@ describe('PR-B B1 — writeStatusCondition', () => {})})+describe('restart-safe discovery status', () => {+ const appsApi = createMockAppsApi()+ const coreApi = createMockCoreApi()+ const customApi = createMockCustomApi()+ let reconciler: McpServerReconciler++ beforeEach(() => {+ vi.clearAllMocks()+ reconciler = new McpServerReconciler({} as k8s.KubeConfig, {+ appsApi: asAppsApi(appsApi),+ coreApi: asCoreApi(coreApi),+ customApi: asCustomApi(customApi),+ })+ })++ it('uses a persisted Ready condition only when it observes the current generation', () => {+ const server: McpServerCRD = {+ ...makeServer({ name: 'restart-safe' }),+ generation: 7,+ status: {+ conditions: [+ {+ type: 'Ready',+ status: 'True',+ reason: 'ReconcileSuccess',+ message: 'Deployment created',+ observedGeneration: 7,+ },+ ],+ },+ }++ expect(reconciler.getStatus(server)).toEqual({+ deployed: true,+ ready: true,+ message: 'Deployment created',+ authoritative: true,+ })+ })++ it.each([+ ['stale', 6],+ ['unversioned', undefined],+ ])('fails closed for a %s persisted Ready condition', (_label, observedGeneration) => {+ const server: McpServerCRD = {+ ...makeServer({ name: 'restart-unsafe' }),+ generation: 7,+ status: {+ conditions: [+ {+ type: 'Ready',+ status: 'True',+ reason: 'ReconcileSuccess',+ message: 'Deployment created',+ observedGeneration,+ },+ ],+ },+ }++ expect(reconciler.getStatus(server)).toEqual({+ deployed: false,+ ready: false,+ message: 'Not reconciled yet',+ authoritative: false,+ })+ })++ it('fails closed when persisted Ready conditions conflict for the current generation', () => {+ const server: McpServerCRD = {+ ...makeServer({ name: 'restart-conflict' }),+ generation: 7,+ status: {+ conditions: [+ {+ type: 'Ready',+ status: 'True',+ reason: 'ReconcileSuccess',+ observedGeneration: 7,+ },+ {+ type: 'Ready',+ status: 'False',+ reason: 'SecretValidationFailed',+ observedGeneration: 7,+ },+ ],+ },+ }++ expect(reconciler.getStatus(server)).toEqual({+ deployed: false,+ ready: false,+ message: 'Not reconciled yet',+ authoritative: false,+ })+ })++ it('prefers fresh in-memory status over persisted status from the same generation', async () => {+ const server: McpServerCRD = {+ ...makeServer({ name: 'live-status' }),+ generation: 3,+ status: {+ conditions: [+ {+ type: 'Ready',+ status: 'True',+ reason: 'ReconcileSuccess',+ observedGeneration: 3,+ },+ ],+ },+ }+ appsApi.readNamespacedDeployment.mockResolvedValueOnce({+ status: { readyReplicas: 0 },+ })++ await reconciler.reconcile(server)++ expect(reconciler.getStatus(server)).toEqual(+ expect.objectContaining({+ deployed: true,+ ready: false,+ authoritative: true,+ })+ )+ })++ it.each([+ ['generation changes', 'stable-uid', 4],+ ['the same name is recreated', 'replacement-uid', 3],+ ])('does not reuse in-memory status when %s', async (_case, uid, generation) => {+ const original: McpServerCRD = {+ ...makeServer({ name: 'identity-fenced' }),+ uid: 'original-uid',+ generation: 3,+ }+ await reconciler.reconcile(original)+ expect(reconciler.getStatus(original).ready).toBe(true)++ const current: McpServerCRD = {+ ...original,+ uid,+ generation,+ status: undefined,+ }++ expect(reconciler.getStatus(current)).toEqual({+ deployed: false,+ ready: false,+ message: 'Not reconciled yet',+ authoritative: false,+ })+ })+})+describe('ownership-safe fail-closed cleanup', () => {const appsApi = createMockAppsApi()const coreApi = createMockCoreApi()@@ -718,6 +1089,373 @@ describe('ownership-safe fail-closed cleanup', () => {})})+describe('full reconciliation inventory authority', () => {+ const appsApi = createMockAppsApi()+ const coreApi = createMockCoreApi()+ const customApi = createMockCustomApi()+ let reconciler: McpServerReconciler++ beforeEach(() => {+ vi.clearAllMocks()+ customApi.getNamespacedCustomObject.mockRejectedValue(+ Object.assign(new Error('not found'), { code: 404 })+ )+ reconciler = new McpServerReconciler({} as k8s.KubeConfig, {+ appsApi: asAppsApi(appsApi),+ coreApi: asCoreApi(coreApi),+ customApi: asCustomApi(customApi),+ })+ })++ it('rejects when Deployment inventory LIST fails so startup retry remains possible', async () => {+ const inventoryError = new Error('deployment inventory unavailable')+ const error = vi.spyOn(console, 'error').mockImplementation(() => undefined)+ appsApi.listNamespacedDeployment.mockRejectedValueOnce(inventoryError)++ await expect(reconciler.fullReconcile([])).rejects.toBe(inventoryError)++ expect(error).toHaveBeenCalledWith(+ '[Reconciler] Failed to list managed deployments:',+ inventoryError+ )+ error.mockRestore()+ })++ it('defaults to fail-closed orphan cleanup until an authority source is wired', async () => {+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined)+ appsApi.listNamespacedDeployment.mockResolvedValueOnce({+ items: [+ {+ metadata: {+ name: 'orphan-server',+ namespace: 'mcp-server',+ },+ },+ ],+ })++ await reconciler.fullReconcile([])++ expect(appsApi.deleteNamespacedDeployment).not.toHaveBeenCalled()+ expect(coreApi.deleteNamespacedService).not.toHaveBeenCalled()+ expect(warn).toHaveBeenCalledWith(expect.stringContaining('inventory authority'))+ warn.mockRestore()+ })++ it('finishes desired reconciliation but skips orphan cleanup if inventory authority is lost mid-pass', async () => {+ let authority = { known: true, generation: 7 }+ reconciler.setInventoryAuthority(() => authority)+ const desired = makeServer({ name: 'desired-server' })+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined)+ const reconcile = vi.spyOn(reconciler, 'reconcile').mockImplementation(async () => {+ authority = { known: false, generation: 8 }+ })+ appsApi.listNamespacedDeployment.mockResolvedValueOnce({+ items: [+ {+ metadata: {+ name: 'orphan-server',+ namespace: 'mcp-server',+ },+ },+ ],+ })++ await reconciler.fullReconcile([desired])++ expect(reconcile).toHaveBeenCalledOnce()+ expect(reconcile).toHaveBeenCalledWith(desired)+ expect(appsApi.deleteNamespacedDeployment).not.toHaveBeenCalled()+ expect(coreApi.deleteNamespacedService).not.toHaveBeenCalled()+ expect(warn).toHaveBeenCalledWith(expect.stringContaining('inventory authority'))+ warn.mockRestore()+ })++ it('skips orphan cleanup if the authoritative inventory generation changes mid-pass', async () => {+ let authority = { known: true, generation: 11 }+ reconciler.setInventoryAuthority(() => authority)+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined)+ vi.spyOn(reconciler, 'reconcile').mockImplementation(async () => {+ authority = { known: true, generation: 12 }+ })+ appsApi.listNamespacedDeployment.mockResolvedValueOnce({+ items: [+ {+ metadata: {+ name: 'orphan-server',+ namespace: 'mcp-server',+ },+ },+ ],+ })++ await reconciler.fullReconcile([makeServer({ name: 'desired-server' })])++ expect(appsApi.deleteNamespacedDeployment).not.toHaveBeenCalled()+ expect(coreApi.deleteNamespacedService).not.toHaveBeenCalled()+ expect(warn).toHaveBeenCalledWith(expect.stringContaining('inventory authority'))+ warn.mockRestore()+ })++ it('deletes an orphan when inventory authority remains known and stable', async () => {+ reconciler.setInventoryAuthority(() => ({ known: true, generation: 21 }))+ appsApi.listNamespacedDeployment.mockResolvedValueOnce({+ items: [+ {+ metadata: {+ name: 'orphan-server',+ namespace: 'mcp-server',+ },+ },+ ],+ })++ await reconciler.fullReconcile([])++ expect(appsApi.deleteNamespacedDeployment).toHaveBeenCalledWith({+ name: 'orphan-server',+ namespace: 'mcp-server',+ })+ expect(coreApi.deleteNamespacedService).toHaveBeenCalledWith({+ name: 'orphan-server',+ namespace: 'mcp-server',+ })+ })++ it('skips a startup runtime revision superseded before its keyed effect is admitted', async () => {+ const snapshot: McpServerCRD = {+ ...makeServer({ name: 'updated-server' }),+ generation: 1,+ spec: {+ contextRef: 'default',+ image: 'clerum/updated-server:old',+ transport: { type: 'streamableHttp', port: 3000 },+ },+ }+ const current: McpServerCRD = {+ ...makeServer({ name: 'updated-server' }),+ generation: 2,+ spec: {+ contextRef: 'default',+ image: 'clerum/updated-server:new',+ transport: { type: 'streamableHttp', port: 3000 },+ egressBindings: [{ dns: 'new.example', port: 443 }],+ },+ }+ reconciler.setInventoryAuthority(() => ({ known: true, generation: 40 }))+ reconciler.setResolveCurrentServer(() => current)+ const reconcile = vi.spyOn(reconciler, 'reconcile')++ await reconciler.fullReconcile([snapshot])++ expect(reconcile).not.toHaveBeenCalled()+ })++ it('admits independent desired effects while another server effect is blocked', async () => {+ const blocked = makeServer({ name: 'blocked-server' })+ const independent = makeServer({ name: 'independent-server' })+ let markBlockedStarted!: () => void+ let releaseBlocked!: () => void+ const blockedStarted = new Promise<void>(resolve => {+ markBlockedStarted = resolve+ })+ const blockedRelease = new Promise<void>(resolve => {+ releaseBlocked = resolve+ })+ const reconcile = vi.spyOn(reconciler, 'reconcile').mockResolvedValue(undefined)+ const fullReconcile = reconciler.fullReconcile([blocked, independent], {+ runEffect: async (serverName, work) => {+ if (serverName === blocked.name) {+ markBlockedStarted()+ await blockedRelease+ }+ await work()+ },+ })++ await blockedStarted+ await Promise.resolve()++ expect(reconcile).toHaveBeenCalledWith(independent)+ expect(reconcile).not.toHaveBeenCalledWith(blocked)++ releaseBlocked()+ await fullReconcile++ expect(reconcile).toHaveBeenCalledWith(blocked)+ })++ it('bounds desired-effect admission without serializing independent siblings', async () => {+ const desired = Array.from({ length: 25 }, (_, index) =>+ makeServer({ name: `bounded-server-${index}` })+ )+ let active = 0+ let maxActive = 0+ let startedBeforeRelease = 0+ let releaseAll!: () => void+ const release = new Promise<void>(resolve => {+ releaseAll = resolve+ })+ const reconcile = vi.spyOn(reconciler, 'reconcile').mockResolvedValue(undefined)+ const options = {+ maxConcurrency: 3,+ runEffect: async (_serverName: string, work: () => Promise<void>) => {+ active += 1+ startedBeforeRelease += 1+ maxActive = Math.max(maxActive, active)+ await release+ try {+ await work()+ } finally {+ active -= 1+ }+ },+ }++ const fullReconcile = reconciler.fullReconcile(desired, options)+ await vi.waitFor(() => expect(active).toBeGreaterThanOrEqual(3))+ await Promise.resolve()+ const observedMaxActive = maxActive+ const observedStartedBeforeRelease = startedBeforeRelease++ releaseAll()+ await fullReconcile++ expect(observedMaxActive).toBe(3)+ expect(observedStartedBeforeRelease).toBe(3)+ expect(reconcile).toHaveBeenCalledTimes(desired.length)+ })++ it('waits for every admitted desired effect before reporting a sibling failure', async () => {+ const failed = makeServer({ name: 'failed-server' })+ const slow = makeServer({ name: 'slow-server' })+ let markSlowStarted!: () => void+ let releaseSlow!: () => void+ const slowStarted = new Promise<void>(resolve => {+ markSlowStarted = resolve+ })+ const slowRelease = new Promise<void>(resolve => {+ releaseSlow = resolve+ })+ const reconcile = vi.spyOn(reconciler, 'reconcile').mockResolvedValue(undefined)++ const fullReconcile = reconciler.fullReconcile([failed, slow], {+ runEffect: async (serverName, work) => {+ if (serverName === failed.name) {+ throw new Error('failed server gate')+ }+ markSlowStarted()+ await slowRelease+ await work()+ },+ })+ let settled = false+ const observed = fullReconcile.then(+ () => undefined,+ error => error+ )+ void observed.then(() => {+ settled = true+ })++ await slowStarted+ await Promise.resolve()+ await Promise.resolve()++ expect(settled).toBe(false)++ releaseSlow()+ const error = await observed++ expect(error).toBeInstanceOf(AggregateError)+ expect(error).toMatchObject({+ message: 'Failed to reconcile desired McpServers',+ })+ expect(reconcile).toHaveBeenCalledWith(slow)+ })++ it('aggregates every desired-effect failure after all bounded workers settle', async () => {+ const failures = [+ new Error('first desired failure'),+ new Error('second desired failure'),+ new Error('third desired failure'),+ ]+ const desired = failures.map((_, index) => makeServer({ name: `failed-${index}` }))+ const reconcile = vi.spyOn(reconciler, 'reconcile').mockResolvedValue(undefined)++ const error = await reconciler+ .fullReconcile(desired, {+ maxConcurrency: 2,+ runEffect: async serverName => {+ throw failures[Number(serverName.replace('failed-', ''))]+ },+ })+ .then(+ () => undefined,+ reason => reason+ )++ expect(error).toBeInstanceOf(AggregateError)+ expect((error as AggregateError).errors).toEqual(failures)+ expect(reconcile).not.toHaveBeenCalled()+ })++ it('does not delete an orphan candidate that was added to the same-generation cache mid-pass', async () => {+ const currentServers = new Map<string, McpServerCRD>()+ ;(reconciler as any).setResolveCurrentServer((name: string) => currentServers.get(name))+ reconciler.setInventoryAuthority(() => ({ known: true, generation: 31 }))+ appsApi.listNamespacedDeployment.mockImplementationOnce(async () => {+ currentServers.set('orphan-server', makeServer({ name: 'orphan-server' }))+ return {+ items: [+ {+ metadata: {+ name: 'orphan-server',+ namespace: 'mcp-server',+ },+ },+ ],+ }+ })++ await reconciler.fullReconcile([])++ expect(customApi.getNamespacedCustomObject).not.toHaveBeenCalled()+ expect(appsApi.deleteNamespacedDeployment).not.toHaveBeenCalled()+ expect(coreApi.deleteNamespacedService).not.toHaveBeenCalled()+ })++ it('does not delete an orphan candidate when a fresh API GET sees a same-name CRD before ADDED arrives', async () => {+ ;(reconciler as any).setResolveCurrentServer(() => undefined)+ reconciler.setInventoryAuthority(() => ({ known: true, generation: 32 }))+ customApi.getNamespacedCustomObject.mockResolvedValueOnce({+ metadata: { name: 'orphan-server', namespace: 'mcp-server', uid: 'recreated-uid' },+ })+ appsApi.listNamespacedDeployment.mockResolvedValueOnce({+ items: [+ {+ metadata: {+ name: 'orphan-server',+ namespace: 'mcp-server',+ },+ },+ ],+ })++ await reconciler.fullReconcile([])++ expect(customApi.getNamespacedCustomObject).toHaveBeenCalledWith(+ expect.objectContaining({+ namespace: 'mcp-server',+ plural: 'mcpservers',+ name: 'orphan-server',+ })+ )+ expect(appsApi.deleteNamespacedDeployment).not.toHaveBeenCalled()+ expect(coreApi.deleteNamespacedService).not.toHaveBeenCalled()+ })+})+describe('updateStatusConditions', () => {const appsApi = createMockAppsApi()const coreApi = createMockCoreApi()diff --git a/host-context-controller/src/reconciler.ts b/host-context-controller/src/reconciler.tsindex b1c1c5d62..0d2e59caf 100644--- a/host-context-controller/src/reconciler.ts+++ b/host-context-controller/src/reconciler.ts@@ -15,6 +15,10 @@ import { classifyPluginImage } from '@clerum/image-policy'import { isWorkflowRecipeDefaultAllowedCapability } from '@clerum/workflow-recipe-capability-policy'import { config } from './config'import { MANAGED_BY_LABEL, MANAGED_BY_VALUE, MCPSERVER_LABEL } from './constants'+import {+ confirmAuthoritativeMcpServerAbsence,+ sameMcpServerDesiredRevision,+} from './mcpServerSafety'import { mcpserverMissingSecret } from './metrics'import { McpServerCRD, McpServerStatus } from './types'import {@@ -47,6 +51,7 @@ export interface McpServerCondition {reason: stringmessage: stringlastTransitionTime: string+ observedGeneration?: number}type McpServerReconcilerDeps = {@@ -56,6 +61,16 @@ type McpServerReconcilerDeps = {networkingApi?: k8s.NetworkingV1Api}+export type McpServerInventoryAuthoritySnapshot = {+ known: boolean+ generation: number+}++export type McpServerFullReconcileOptions = {+ runEffect?: (serverName: string, work: () => Promise<void>) => Promise<void>+ maxConcurrency?: number+}+// G2: Pre-deploy handshake constantsconst PRE_DEPLOY_ANNOTATION = 'clerum.io/pre-deploy'const NETWORK_READY_ANNOTATION = 'clerum.io/network-ready'@@ -67,6 +82,13 @@ const HEADER_NAME_RE = /^[A-Za-z0-9-]+$/// Bound the value length so a pathological CRD cannot blow up the ConfigMap.const MAX_AUTH_HEADER_VALUE_LENGTH = 2048const WRC_OWNED_RUNTIME_READY_REASON = 'WrcOwnedRuntimeRegistered'+// Keep fleet admission aligned with the external-egress convergence lane:+// enough parallelism for independent servers without allocating one pending+// effect promise per fleet member.+const DEFAULT_FULL_RECONCILE_MAX_CONCURRENCY = 10+// Status is a read/merge/write transaction shared with other controllers.+// Bound optimistic-conflict retries so a hot object cannot stall reconciliation.+const STATUS_CONDITION_WRITE_MAX_ATTEMPTS = 3function throwCleanupFailures(failures: unknown[], message: string): void {if (failures.length > 0) {@@ -74,14 +96,58 @@ function throwCleanupFailures(failures: unknown[], message: string): void {}}+async function mapSettledWithConcurrency<T, TResult>(+ items: readonly T[],+ maxConcurrency: number,+ work: (item: T, index: number) => Promise<TResult>+): Promise<Array<PromiseSettledResult<TResult>>> {+ if (!Number.isInteger(maxConcurrency) || maxConcurrency < 1) {+ throw new RangeError('maxConcurrency must be a positive integer')+ }++ const results = new Array<PromiseSettledResult<TResult>>(items.length)+ let nextIndex = 0+ const worker = async (): Promise<void> => {+ while (nextIndex < items.length) {+ const index = nextIndex+ nextIndex += 1+ try {+ results[index] = {+ status: 'fulfilled',+ value: await work(items[index], index),+ }+ } catch (reason) {+ results[index] = { status: 'rejected', reason }+ }+ }+ }++ const workerCount = Math.min(maxConcurrency, items.length)+ await Promise.all(Array.from({ length: workerCount }, () => worker()))+ return results+}+export class McpServerReconciler {private readonly appsApi: k8s.AppsV1Apiprivate readonly coreApi: k8s.CoreV1Apiprivate readonly customApi: k8s.CustomObjectsApiprivate readonly networkingApi?: k8s.NetworkingV1Api+ /**+ * Snapshot the McpServer LIST→WATCH authority owned by McpServerWatcher.+ * The fail-closed default prevents orphan cleanup until the watcher wires+ * the real authority source.+ */+ private inventoryAuthority: () => McpServerInventoryAuthoritySnapshot = () => ({+ known: false,+ generation: 0,+ })+ private resolveCurrentServer?: (name: string) => McpServerCRD | undefined+/** Tracks the deployment status of each managed McpServer. */private readonly statusMap: Map<string, McpServerStatus> = new Map()+ private readonly statusIdentities: Map<string, Pick<McpServerCRD, 'uid' | 'generation'>> =+ new Map()/** G7: Tracks the initial `managed` value per McpServer to enforce immutability. */private readonly managedSnapshot: Map<string, boolean> = new Map()@@ -106,18 +172,93 @@ export class McpServerReconciler {(typeof kc.makeApiClient === 'function' ? kc.makeApiClient(k8s.NetworkingV1Api) : undefined)}+ /**+ * Late-bound authority source for destructive full-reconcile cleanup.+ * A full pass may finish reconciling desired servers, but it may delete an+ * orphan only while the same authoritative inventory generation remains+ * active from pass start through delete admission.+ */+ setInventoryAuthority(fn: () => McpServerInventoryAuthoritySnapshot): void {+ this.inventoryAuthority = fn+ }++ /**+ * Resolve current cache membership at effect admission. Full-reconcile+ * snapshots select candidates only; they must never overwrite or delete a+ * same-name CRD accepted by the continuing watch.+ */+ setResolveCurrentServer(fn: (name: string) => McpServerCRD | undefined): void {+ this.resolveCurrentServer = fn+ }+// ─── Status ────────────────────────────────────────────────────────/*** Get deployment status for an McpServer.- * Returns unknown status if the server hasn't been reconciled yet.+ * Returns current in-memory status when this process has reconciled the+ * server. After a controller restart, a generation-matched persisted Ready+ * condition is the only safe fallback: a legacy condition without+ * observedGeneration, or a condition for an older spec generation, cannot+ * prove that the current desired runtime is ready.*/- getStatus(name: string): McpServerStatus {+ getStatus(serverOrName: string | McpServerCRD): McpServerStatus {+ const name = typeof serverOrName === 'string' ? serverOrName : serverOrName.name+ const current = this.statusMap.get(name)+ if (current && (typeof serverOrName === 'string' || this.statusIdentityMatches(serverOrName))) {+ return typeof serverOrName === 'string' ? current : { ...current, authoritative: true }+ }++ if (typeof serverOrName !== 'string' && serverOrName.generation !== undefined) {+ const readyConditions =+ serverOrName.status?.conditions?.filter(condition => condition.type === 'Ready') ?? []+ const persistedReady =+ readyConditions.length === 1 &&+ readyConditions[0].observedGeneration === serverOrName.generation+ ? readyConditions[0]+ : undefined+ if (persistedReady) {+ const ready = persistedReady.status === 'True'+ return {+ deployed: ready,+ ready,+ message: persistedReady.message,+ authoritative: true,+ }+ }+ }++ return {+ deployed: false,+ ready: false,+ message: 'Not reconciled yet',+ authoritative: false,+ }+ }++ private statusIdentityMatches(server: McpServerCRD): boolean {+ const identity = this.statusIdentities.get(server.name)return (- this.statusMap.get(name) ?? { deployed: false, ready: false, message: 'Not reconciled yet' }+ identity !== undefined &&+ identity.uid === server.uid &&+ identity.generation === server.generation)}+ private beginStatusTracking(server: McpServerCRD): void {+ if (!this.statusIdentityMatches(server)) {+ this.statusMap.delete(server.name)+ const timer = this.readinessTimers.get(server.name)+ if (timer) {+ clearTimeout(timer)+ this.readinessTimers.delete(server.name)+ }+ }+ this.statusIdentities.set(server.name, {+ uid: server.uid,+ generation: server.generation,+ })+ }+/*** Update the status of an McpServer after reconciliation.*/@@ -130,6 +271,7 @@ export class McpServerReconciler {*/private clearStatus(name: string): void {this.statusMap.delete(name)+ this.statusIdentities.delete(name)this.managedSnapshot.delete(name)const timer = this.readinessTimers.get(name)if (timer) {@@ -155,12 +297,8 @@ export class McpServerReconciler {* Poll deployment readiness until ready or maxAttempts reached.* Cancels any existing poll for the same server name.*/- private pollReadiness(- name: string,- namespace: string,- intervalMs = 5000,- maxAttempts = 12- ): void {+ private pollReadiness(server: McpServerCRD, intervalMs = 5000, maxAttempts = 12): void {+ const { name, namespace } = server// Cancel any existing poll for this serverconst existing = this.readinessTimers.get(name)if (existing) {@@ -173,10 +311,17 @@ export class McpServerReconciler {const poll = async () => {attempts++const ready = await this.checkDeploymentReady(name, namespace)+ if (!this.statusIdentityMatches(server)) returnif (ready) {this.setStatus(name, { deployed: true, ready: true, message: 'Running' })this.readinessTimers.delete(name)+ await this.writeStatusCondition(server, {+ type: 'Ready',+ status: 'True',+ reason: 'ReconcileSuccess',+ message: 'Deployment created',+ })console.log(`[Reconciler] McpServer "${name}" is now ready (after ${attempts} poll(s))`)return}@@ -1045,12 +1190,16 @@ ${authHeaderLines ? '\n # ── Credential auth headers (envsubst-resolv* Name matches are not enough: WRC-owned `managed:false` runtimes can share* names with McpServer CRDs, so every delete verifies HCC ownership labels.*/- private async deleteResources(name: string, namespace: string): Promise<void> {+ private async deleteResources(+ name: string,+ namespace: string,+ deleteAllowed?: () => Promise<boolean>+ ): Promise<void> {const failures: unknown[] = []for (const cleanup of [- () => this.deleteDeploymentIfHccOwned(name, namespace),- () => this.deleteConfigMapIfHccOwned(`${name}-nginx-conf`, namespace, name),- () => this.deleteServiceIfHccOwned(name, namespace),+ () => this.deleteDeploymentIfHccOwned(name, namespace, deleteAllowed),+ () => this.deleteConfigMapIfHccOwned(`${name}-nginx-conf`, namespace, name, deleteAllowed),+ () => this.deleteServiceIfHccOwned(name, namespace, deleteAllowed),]) {try {await cleanup()@@ -1072,7 +1221,11 @@ ${authHeaderLines ? '\n # ── Credential auth headers (envsubst-resolvreturn labels[MANAGED_BY_LABEL] === MANAGED_BY_VALUE && labels[MCPSERVER_LABEL] === serverName}- private async deleteDeploymentIfHccOwned(name: string, namespace: string): Promise<void> {+ private async deleteDeploymentIfHccOwned(+ name: string,+ namespace: string,+ deleteAllowed?: () => Promise<boolean>+ ): Promise<void> {let deployment: k8s.V1Deploymenttry {deployment = await this.appsApi.readNamespacedDeployment({ name, namespace })@@ -1090,6 +1243,7 @@ ${authHeaderLines ? '\n # ── Credential auth headers (envsubst-resolvconsole.warn(`[Reconciler] Skipping Deployment "${name}" delete — not HCC-owned`)return}+ if (deleteAllowed && !(await deleteAllowed())) returntry {await this.appsApi.deleteNamespacedDeployment({ name, namespace })@@ -1107,7 +1261,8 @@ ${authHeaderLines ? '\n # ── Credential auth headers (envsubst-resolvprivate async deleteConfigMapIfHccOwned(configMapName: string,namespace: string,- serverName: string+ serverName: string,+ deleteAllowed?: () => Promise<boolean>): Promise<void> {let configMap: k8s.V1ConfigMaptry {@@ -1126,6 +1281,7 @@ ${authHeaderLines ? '\n # ── Credential auth headers (envsubst-resolvconsole.warn(`[Reconciler] Skipping ConfigMap "${configMapName}" delete — not HCC-owned`)return}+ if (deleteAllowed && !(await deleteAllowed())) returntry {await this.coreApi.deleteNamespacedConfigMap({ name: configMapName, namespace })@@ -1140,7 +1296,11 @@ ${authHeaderLines ? '\n # ── Credential auth headers (envsubst-resolv}}- private async deleteServiceIfHccOwned(name: string, namespace: string): Promise<void> {+ private async deleteServiceIfHccOwned(+ name: string,+ namespace: string,+ deleteAllowed?: () => Promise<boolean>+ ): Promise<void> {let service: k8s.V1Servicetry {service = await this.coreApi.readNamespacedService({ name, namespace })@@ -1158,6 +1318,7 @@ ${authHeaderLines ? '\n # ── Credential auth headers (envsubst-resolvconsole.warn(`[Reconciler] Skipping Service "${name}" delete — not HCC-owned`)return}+ if (deleteAllowed && !(await deleteAllowed())) returntry {await this.coreApi.deleteNamespacedService({ name, namespace })@@ -1172,7 +1333,11 @@ ${authHeaderLines ? '\n # ── Credential auth headers (envsubst-resolv}}- private async deleteNetworkPoliciesForServer(name: string, namespace: string): Promise<void> {+ private async deleteNetworkPoliciesForServer(+ name: string,+ namespace: string,+ deleteAllowed?: () => Promise<boolean>+ ): Promise<void> {if (!this.networkingApi) returnconst failures: unknown[] = []const namespaces = [...new Set([namespace, config.hostNamespace, config.rpcProxyNamespace])]@@ -1186,6 +1351,7 @@ ${authHeaderLines ? '\n # ── Credential auth headers (envsubst-resolvconst policyName = policy.metadata.nameif (!policyName) continuetry {+ if (deleteAllowed && !(await deleteAllowed())) returnawait this.networkingApi.deleteNamespacedNetworkPolicy({name: policyName,namespace: policyNamespace,@@ -1217,15 +1383,19 @@ ${authHeaderLines ? '\n # ── Credential auth headers (envsubst-resolvthrowCleanupFailures(failures, `Failed to delete NetworkPolicies for McpServer "${name}"`)}- private async deleteRuntimeResources(name: string, namespace: string): Promise<void> {+ private async deleteRuntimeResources(+ name: string,+ namespace: string,+ deleteAllowed?: () => Promise<boolean>+ ): Promise<void> {const failures: unknown[] = []try {- await this.deleteResources(name, namespace)+ await this.deleteResources(name, namespace, deleteAllowed)} catch (error) {failures.push(error)}try {- await this.deleteNetworkPoliciesForServer(name, namespace)+ await this.deleteNetworkPoliciesForServer(name, namespace, deleteAllowed)} catch (error) {failures.push(error)}@@ -1382,6 +1552,7 @@ ${authHeaderLines ? '\n # ── Credential auth headers (envsubst-resolv** Failure modes:* - 404 (CRD deleted mid-reconcile) → log + swallow.+ * - 409/422 (optimistic conflict) → re-read, re-merge, bounded retry.* - Other errors → log + swallow (status writes are best-effort).*/async writeStatusCondition(@@ -1390,42 +1561,8 @@ ${authHeaderLines ? '\n # ── Credential auth headers (envsubst-resolv): Promise<void> {const now = new Date().toISOString()- // Fetch current status to preserve existing conditions.- let existingConditions: McpServerCondition[] = []- let hasStatusObject = false- try {- const current = (await this.customApi.getNamespacedCustomObjectStatus({- group: 'clerum.io',- version: 'v1alpha1',- namespace: server.namespace,- plural: 'mcpservers',- name: server.name,- })) as { status?: { conditions?: McpServerCondition[] } }- hasStatusObject = typeof current.status === 'object' && current.status !== null- existingConditions = current.status?.conditions ?? []- } catch (error) {- if (getErrorCode(error) === 404) {- console.warn(- `[Reconciler] McpServer "${server.name}" deleted mid-reconcile — skipping status update`- )- return- }- console.warn(- `[Reconciler] Failed to read status for "${server.name}" — skipping status update for type "${condition.type}" to avoid clobbering other status fields:`,- error- )- return- }-- const prior = existingConditions.find(c => c.type === condition.type)- const unchanged =- prior !== undefined &&- prior.status === condition.status &&- prior.reason === condition.reason &&- prior.message === condition.message-// Update the missing-secret gauge for SecretResolved conditions.- // Do this BEFORE the no-op short-circuit so the gauge stays current+ // Do this before any no-op short-circuit so the gauge stays current// across reconciles even when we skip the API patch.if (condition.type === 'SecretResolved' && server.spec.envSecret) {const labels = {@@ -1436,55 +1573,139 @@ ${authHeaderLines ? '\n # ── Credential auth headers (envsubst-resolvmcpserverMissingSecret.set(labels, condition.status === 'False' ? 1 : 0)}- // Skip the patch when the condition is identical to what's already on- // the CRD. Without this, every reconcile bumps the McpServer's- // resourceVersion, fires another watch event, triggers another- // reconcile — a tight self-loop that also amplifies NetworkPolicy- // optimistic-lock contention downstream.- if (unchanged) {- return- }+ for (let attempt = 1; attempt <= STATUS_CONDITION_WRITE_MAX_ATTEMPTS; attempt += 1) {+ // Re-read on every optimistic-conflict retry. Merging against the+ // latest resourceVersion preserves conditions written by peer+ // controllers between our read and patch.+ let existingConditions: McpServerCondition[] = []+ let hasStatusObject = false+ let resourceVersion: string | undefined+ try {+ const current = (await this.customApi.getNamespacedCustomObjectStatus({+ group: 'clerum.io',+ version: 'v1alpha1',+ namespace: server.namespace,+ plural: 'mcpservers',+ name: server.name,+ })) as {+ metadata?: { resourceVersion?: string }+ status?: { conditions?: McpServerCondition[] }+ }+ hasStatusObject = typeof current.status === 'object' && current.status !== null+ existingConditions = current.status?.conditions ?? []+ resourceVersion = current.metadata?.resourceVersion+ } catch (error) {+ if (getErrorCode(error) === 404) {+ console.warn(+ `[Reconciler] McpServer "${server.name}" deleted mid-reconcile — skipping status update`+ )+ return+ }+ console.warn(+ `[Reconciler] Failed to read status for "${server.name}" — skipping status update for type "${condition.type}" to avoid clobbering other status fields:`,+ error+ )+ return+ }- const lastTransitionTime =- prior && prior.status === condition.status ? prior.lastTransitionTime : now+ const prior = existingConditions.find(c => c.type === condition.type)+ const observedGeneration = condition.observedGeneration ?? server.generation+ const unchanged =+ prior !== undefined &&+ prior.status === condition.status &&+ prior.reason === condition.reason &&+ prior.message === condition.message &&+ prior.observedGeneration === observedGeneration++ // Skip the patch when the condition is identical to what's already on+ // the CRD. Without this, every reconcile bumps the McpServer's+ // resourceVersion, fires another watch event, triggers another+ // reconcile — a tight self-loop that also amplifies NetworkPolicy+ // optimistic-lock contention downstream.+ if (unchanged) {+ return+ }- const merged: McpServerCondition = {- type: condition.type,- status: condition.status,- reason: condition.reason,- message: condition.message,- lastTransitionTime,- }+ const lastTransitionTime =+ prior && prior.status === condition.status ? prior.lastTransitionTime : now- const nextConditions = [...existingConditions.filter(c => c.type !== condition.type), merged]+ const merged: McpServerCondition = {+ type: condition.type,+ status: condition.status,+ reason: condition.reason,+ message: condition.message,+ lastTransitionTime,+ ...(observedGeneration !== undefined && { observedGeneration }),+ }- const statusPatch = hasStatusObject- ? [{ op: 'add', path: '/status/conditions', value: nextConditions }]- : [{ op: 'add', path: '/status', value: { conditions: nextConditions } }]+ const nextConditions = [...existingConditions.filter(c => c.type !== condition.type), merged]++ const writePreconditions: Array<{+ op: 'test'+ path: string+ value: string | number+ }> = []+ if (server.uid !== undefined) {+ writePreconditions.push({+ op: 'test',+ path: '/metadata/uid',+ value: server.uid,+ })+ }+ if (server.generation !== undefined) {+ writePreconditions.push({+ op: 'test',+ path: '/metadata/generation',+ value: server.generation,+ })+ }+ if (resourceVersion !== undefined) {+ writePreconditions.push({+ op: 'test',+ path: '/metadata/resourceVersion',+ value: resourceVersion,+ })+ }+ const statusPatch = [+ ...writePreconditions,+ ...(hasStatusObject+ ? [{ op: 'add', path: '/status/conditions', value: nextConditions }]+ : [{ op: 'add', path: '/status', value: { conditions: nextConditions } }]),+ ]- try {- // The generated client prefers JSON Patch for this endpoint. Send an- // actual patch document so status writes keep working across client- // upgrades instead of relying on merge-patch object bodies.- await this.customApi.patchNamespacedCustomObjectStatus({- group: 'clerum.io',- version: 'v1alpha1',- namespace: server.namespace,- plural: 'mcpservers',- name: server.name,- body: statusPatch,- })- } catch (error) {- if (getErrorCode(error) === 404) {+ try {+ // The generated client prefers JSON Patch for this endpoint. Send an+ // actual patch document so status writes keep working across client+ // upgrades instead of relying on merge-patch object bodies.+ await this.customApi.patchNamespacedCustomObjectStatus({+ group: 'clerum.io',+ version: 'v1alpha1',+ namespace: server.namespace,+ plural: 'mcpservers',+ name: server.name,+ body: statusPatch,+ })+ return+ } catch (error) {+ const errorCode = getErrorCode(error)+ if (errorCode === 404) {+ console.warn(+ `[Reconciler] McpServer "${server.name}" deleted mid-reconcile — status patch skipped`+ )+ return+ }+ if (+ (errorCode === 409 || errorCode === 422) &&+ attempt < STATUS_CONDITION_WRITE_MAX_ATTEMPTS+ ) {+ continue+ }console.warn(- `[Reconciler] McpServer "${server.name}" deleted mid-reconcile — status patch skipped`+ `[Reconciler] Failed to write status condition ${condition.type}=${condition.status} on "${server.name}":`,+ error)return}- console.warn(- `[Reconciler] Failed to write status condition ${condition.type}=${condition.status} on "${server.name}":`,- error- )}}@@ -1513,6 +1734,8 @@ ${authHeaderLines ? '\n # ── Credential auth headers (envsubst-resolv}private async performReconcile(server: McpServerCRD): Promise<void> {+ this.beginStatusTracking(server)+// G7: Enforce managed field immutability — once set, cannot changeconst currentManaged = server.spec.managed ?? trueconst previousManaged = this.managedSnapshot.get(server.name)@@ -1686,7 +1909,7 @@ ${authHeaderLines ? '\n # ── Credential auth headers (envsubst-resolv// If not ready yet, poll until it becomes readyif (!ready) {- this.pollReadiness(server.name, server.namespace)+ this.pollReadiness(server)}}@@ -1756,18 +1979,55 @@ ${authHeaderLines ? '\n # ── Credential auth headers (envsubst-resolv*/async reconcileDelete(name: string, namespace: string): Promise<void> {console.log(`[Reconciler] McpServer "${name}" deleted — cleaning up resources`)- await this.deleteRuntimeResources(name, namespace)+ const capturedAuthority = this.inventoryAuthority()+ await this.deleteRuntimeResources(name, namespace, () =>+ this.orphanDeleteAllowed(name, namespace, capturedAuthority)+ )this.clearStatus(name)}+ private authorityMatches(captured: McpServerInventoryAuthoritySnapshot): boolean {+ const current = this.inventoryAuthority()+ return captured.known && current.known && captured.generation === current.generation+ }++ /**+ * A cache miss is not proof of absence: the API watch may have accepted an+ * ADDED event that has not reached this process yet. Confirm a 404 from the+ * API and then recheck both cache membership and LIST→WATCH authority+ * immediately before every destructive delete.+ */+ private async orphanDeleteAllowed(+ name: string,+ namespace: string,+ capturedAuthority: McpServerInventoryAuthoritySnapshot+ ): Promise<boolean> {+ return confirmAuthoritativeMcpServerAbsence({+ inventoryAuthoritative: () => this.authorityMatches(capturedAuthority),+ resolveCurrent: () => this.resolveCurrentServer?.(name),+ readCurrent: () =>+ this.customApi.getNamespacedCustomObject({+ group: 'clerum.io',+ version: 'v1alpha1',+ namespace,+ plural: 'mcpservers',+ name,+ }),+ })+ }+/*** Full reconciliation pass — sync desired state with actual state.* Called on startup to handle CRDs that were created while the skill-mapper was down.*/- async fullReconcile(desiredServers: McpServerCRD[]): Promise<void> {+ async fullReconcile(+ desiredServers: McpServerCRD[],+ options: McpServerFullReconcileOptions = {}+ ): Promise<void> {console.log(`[Reconciler] Running full reconciliation for ${desiredServers.length} McpServer(s)`)+ const capturedAuthority = this.inventoryAuthority()// Get all deployments managed by skill-mapperconst existingDeployments = await this.listManagedDeployments()@@ -1777,18 +2037,51 @@ ${authHeaderLines ? '\n # ── Credential auth headers (envsubst-resolv.map(s => s.name))- // Create or update desired servers- for (const server of desiredServers) {- await this.reconcile(server)- }+ const runEffect =+ options.runEffect ?? ((_serverName: string, work: () => Promise<void>) => work())+ const maxConcurrency = options.maxConcurrency ?? DEFAULT_FULL_RECONCILE_MAX_CONCURRENCY++ // Create or update desired servers independently. runEffect owns each+ // per-server lane, so a slow fleet member cannot become a process-wide+ // startup barrier. The finite worker pool admits no more than the configured+ // number of effects at once, while still waiting for every desired result+ // before reporting aggregated failures or moving to orphan cleanup.+ const desiredResults = await mapSettledWithConcurrency(desiredServers, maxConcurrency, server =>+ runEffect(server.name, async () => {+ const current = this.resolveCurrentServer ? this.resolveCurrentServer(server.name) : server+ // Cache mutation happens synchronously before its keyed watch effect is+ // queued. If this startup item was superseded, skip it and let the+ // newer queued event perform external-egress-before-runtime using its+ // own spec; reconciling the newer runtime here could otherwise race+ // ahead of that safety policy.+ if (!current || !sameMcpServerDesiredRevision(server, current)) return+ await this.reconcile(current)+ })+ )+ throwCleanupFailures(+ desiredResults+ .filter((result): result is PromiseRejectedResult => result.status === 'rejected')+ .map(result => result.reason),+ 'Failed to reconcile desired McpServers'+ )// Delete orphaned deployments (managed by us but no longer desired)for (const deployment of existingDeployments) {const name = deployment.metadata?.name || ''if (!desiredNames.has(name)) {const namespace = deployment.metadata?.namespace || config.namespace- console.log(`[Reconciler] Removing orphaned resources for "${name}"`)- await this.deleteRuntimeResources(name, namespace)+ await runEffect(name, async () => {+ if (!(await this.orphanDeleteAllowed(name, namespace, capturedAuthority))) {+ console.warn(+ `[Reconciler] Deferring orphan cleanup for "${name}": McpServer exists or inventory authority is unknown or changed`+ )+ return+ }+ console.log(`[Reconciler] Removing orphaned resources for "${name}"`)+ await this.deleteRuntimeResources(name, namespace, () =>+ this.orphanDeleteAllowed(name, namespace, capturedAuthority)+ )+ })}}@@ -1807,7 +2100,7 @@ ${authHeaderLines ? '\n # ── Credential auth headers (envsubst-resolvreturn response.items || []} catch (error) {console.error('[Reconciler] Failed to list managed deployments:', error)- return []+ throw error}}}diff --git a/host-context-controller/src/server.test.ts b/host-context-controller/src/server.test.tsindex 633a48992..2448b6661 100644--- a/host-context-controller/src/server.test.ts+++ b/host-context-controller/src/server.test.ts@@ -1,4 +1,4 @@-import { afterEach, describe, expect, it } from 'vitest'+import { afterEach, describe, expect, it, vi } from 'vitest'import { McpServerProvider } from './k8sClient'import { ContextMapperServer } from './server'@@ -75,6 +75,7 @@ describe('ContextMapperServer readiness', () => {afterEach(async () => {await server?.stop()server = null+ vi.restoreAllMocks()})it('serves health immediately but gates readiness and API responses until warm-up completes', async () => {@@ -82,7 +83,10 @@ describe('ContextMapperServer readiness', () => {let response = await invoke(server, '/health')expect(response.statusCode).toBe(200)- expect(JSON.parse(response.body)).toEqual({ status: 'ok', ready: false })+ expect(JSON.parse(response.body)).toEqual({+ status: 'ok',+ ready: false,+ })response = await invoke(server, '/ready')expect(response.statusCode).toBe(503)@@ -108,4 +112,85 @@ describe('ContextMapperServer readiness', () => {contextRef: '*',})})++ it('tracks provider authority dynamically after warm-up and fails API requests closed', async () => {+ let providerAuthoritative = true+ server = new ContextMapperServer(+ new FakeProvider(),+ 0,+ undefined,+ undefined,+ () => providerAuthoritative+ )++ let response = await invoke(server, '/ready')+ expect(response.statusCode).toBe(503)+ expect(JSON.parse(response.body)).toEqual({ status: 'starting', ready: false })++ server.setReady(true)++ response = await invoke(server, '/ready')+ expect(response.statusCode).toBe(200)+ expect(JSON.parse(response.body)).toEqual({ status: 'ready', ready: true })++ providerAuthoritative = false++ response = await invoke(server, '/ready')+ expect(response.statusCode).toBe(503)+ expect(JSON.parse(response.body)).toEqual({ status: 'degraded', ready: false })++ response = await invoke(server, '/health')+ expect(response.statusCode).toBe(200)+ expect(JSON.parse(response.body)).toEqual({+ status: 'ok',+ ready: false,+ })++ response = await invoke(server, '/api/v1/mcpservers')+ expect(response.statusCode).toBe(503)+ expect(JSON.parse(response.body)).toEqual({+ error: 'Service Unavailable',+ message: 'Context mapper provider inventory is not authoritative',+ })++ providerAuthoritative = true++ response = await invoke(server, '/ready')+ expect(response.statusCode).toBe(200)+ expect(JSON.parse(response.body)).toEqual({ status: 'ready', ready: true })++ response = await invoke(server, '/api/v1/mcpservers')+ expect(response.statusCode).toBe(200)+ })++ it('fails readiness closed when the provider authority check throws', async () => {+ const authorityError = new Error('authority unavailable')+ const errorLog = vi.spyOn(console, 'error').mockImplementation(() => undefined)+ server = new ContextMapperServer(new FakeProvider(), 0, undefined, undefined, () => {+ throw authorityError+ })+ server.setReady(true)++ const response = await invoke(server, '/ready')++ expect(response.statusCode).toBe(503)+ expect(JSON.parse(response.body)).toEqual({ status: 'degraded', ready: false })+ expect(errorLog).toHaveBeenCalledWith(+ '[Server] Provider authority readiness check failed:',+ authorityError+ )+ })++ it('withdraws readiness as soon as shutdown begins', async () => {+ server = new ContextMapperServer(new FakeProvider(), 0)+ server.setReady(true)++ expect((await invoke(server, '/ready')).statusCode).toBe(200)++ await server.stop()++ const response = await invoke(server, '/ready')+ expect(response.statusCode).toBe(503)+ expect(JSON.parse(response.body)).toEqual({ status: 'starting', ready: false })+ })})diff --git a/host-context-controller/src/server.ts b/host-context-controller/src/server.tsindex 7be800a8e..23b1d3327 100644--- a/host-context-controller/src/server.ts+++ b/host-context-controller/src/server.ts@@ -8,24 +8,31 @@ import { McpServerProvider } from './k8sClient'import { registry } from './metrics'import { ErrorResponse, McpServersResponse } from './types'+type ReadinessState =+ | { ready: true; status: 'ready' }+ | { ready: false; status: 'starting' | 'degraded'; message: string }+export class ContextMapperServer {private server: http.Server | null = nullprivate provider: McpServerProviderprivate port: numberprivate hostReconciler: HostReconciler | nullprivate hasDesktopFn: ((hostRef: string) => boolean) | null+ private providerAuthoritativeFn: () => booleanprivate ready = falseconstructor(provider: McpServerProvider,port: number = config.port,hostReconciler?: HostReconciler,- hasDesktopFn?: (hostRef: string) => boolean+ hasDesktopFn?: (hostRef: string) => boolean,+ providerAuthoritativeFn: () => boolean = () => true) {this.provider = providerthis.port = portthis.hostReconciler = hostReconciler ?? nullthis.hasDesktopFn = hasDesktopFn ?? null+ this.providerAuthoritativeFn = providerAuthoritativeFn}/**@@ -35,6 +42,30 @@ export class ContextMapperServer {this.ready = ready}+ private getReadinessState(): ReadinessState {+ if (!this.ready) {+ return {+ ready: false,+ status: 'starting',+ message: 'Context mapper is still starting',+ }+ }++ try {+ if (this.providerAuthoritativeFn()) {+ return { ready: true, status: 'ready' }+ }+ } catch (err) {+ console.error('[Server] Provider authority readiness check failed:', err)+ }++ return {+ ready: false,+ status: 'degraded',+ message: 'Context mapper provider inventory is not authoritative',+ }+ }+private async handleRequest(req: http.IncomingMessage, res: http.ServerResponse): Promise<void> {// CORS headersres.setHeader('Access-Control-Allow-Origin', '*')@@ -57,15 +88,20 @@ export class ContextMapperServer {// Health checkif (req.method === 'GET' && url.pathname === '/health') {- this.sendJson(res, 200, { status: 'ok', ready: this.ready })+ const readiness = this.getReadinessState()+ this.sendJson(res, 200, {+ status: 'ok',+ ready: readiness.ready,+ })return}// Readiness checkif (req.method === 'GET' && url.pathname === '/ready') {- this.sendJson(res, this.ready ? 200 : 503, {- status: this.ready ? 'ready' : 'starting',- ready: this.ready,+ const readiness = this.getReadinessState()+ this.sendJson(res, readiness.ready ? 200 : 503, {+ status: readiness.status,+ ready: readiness.ready,})return}@@ -78,10 +114,11 @@ export class ContextMapperServer {return}- if (!this.ready) {+ const readiness = this.getReadinessState()+ if (!readiness.ready) {this.sendJson(res, 503, {error: 'Service Unavailable',- message: 'Context mapper is still starting',+ message: readiness.message,})return}@@ -198,7 +235,8 @@ export class ContextMapperServer {endpoints: {'GET /': 'This information page','GET /health': "Health check endpoint - returns { status: 'ok', ready: boolean }",- 'GET /ready': 'Readiness endpoint - returns 200 only after warm-up completes',+ 'GET /ready':+ 'Readiness endpoint - returns 200 after warm-up while provider inventory is authoritative','GET /api/v1/mcpservers': 'List all McpServer resources','GET /api/v1/mcpservers/context/:contextRef':'List McpServers filtered by contextRef (only enabled servers)',@@ -346,9 +384,12 @@ export class ContextMapperServer {* Stop the server.*/stop(): Promise<void> {+ this.ready = false+ const activeServer = this.server+ this.server = nullreturn new Promise(resolve => {- if (this.server) {- this.server.close(() => {+ if (activeServer) {+ activeServer.close(() => {console.log('[Server] Context Mapper stopped')resolve()})diff --git a/host-context-controller/src/types.ts b/host-context-controller/src/types.tsindex a7488dc7d..56924fdbc 100644--- a/host-context-controller/src/types.ts+++ b/host-context-controller/src/types.ts@@ -509,6 +509,12 @@ export interface McpServerStatus {ready: boolean/** Human-readable status message. */message?: string+ /**+ * Whether HCC can tie this status to the current McpServer identity and+ * generation. False means discovery is authoritative but runtime status has+ * not yet been re-established after controller startup.+ */+ authoritative?: boolean}/**