Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure
TypeScript
fix(hcc): close readiness safety review gaps
Alfredo Lopezc7ee2a321e9f
diff --git a/.github/workflows/ci-public.yml b/.github/workflows/ci-public.ymlindex 404216748..461cb9b92 100644--- a/.github/workflows/ci-public.yml+++ b/.github/workflows/ci-public.yml@@ -328,6 +328,9 @@ jobs:- name: Test HCC watch-recovery gate coordinationrun: bash scripts/tests/test-hcc-watch-recovery-gate.sh+ - name: Test HCC API gateway readiness separation+ run: bash scripts/tests/test-hcc-api-gateway-readiness.sh+- name: Test host-storm metric adjudicationrun: bash scripts/tests/test-host-storm-metric-gate.shdiff --git a/deploy/base/control-plane/host-context-controller-api-gateway.yaml b/deploy/base/control-plane/host-context-controller-api-gateway.yamlindex 961cebe48..1c30ccfbc 100644--- a/deploy/base/control-plane/host-context-controller-api-gateway.yaml+++ b/deploy/base/control-plane/host-context-controller-api-gateway.yaml@@ -43,7 +43,7 @@ spec:timeoutSeconds: 5readinessProbe:httpGet:- path: /ready+ path: /healthport: httpscheme: HTTPinitialDelaySeconds: 3diff --git a/deploy/base/control-plane/host-context-controller.yaml b/deploy/base/control-plane/host-context-controller.yamlindex 0d32a622f..31d171eb6 100644--- a/deploy/base/control-plane/host-context-controller.yaml+++ b/deploy/base/control-plane/host-context-controller.yaml@@ -60,6 +60,8 @@ spec:value: sandbox-ui- name: HCC_EXTERNAL_EGRESS_RESYNC_SECvalue: "300"+ - name: HCC_EXTERNAL_EGRESS_DNS_TIMEOUT_MS+ value: "5000"- name: HCC_HOST_K8S_REQUEST_TIMEOUT_MSvalue: "30000"# Bounded cross-Host concurrency for a full/lifecycle Host fleet pass.diff --git a/host-context-controller/README.md b/host-context-controller/README.mdindex 8ee40e981..8ec691a52 100644--- a/host-context-controller/README.md+++ b/host-context-controller/README.md@@ -97,7 +97,21 @@ Servers removed from a Context lose their policies on the next reconcile; deleti- **`exact-host`** (default) — a CIDR binding, or a public DNS hostname resolved to `/32` ipBlocks, on one declared port/protocol. CIDRs and resolved IPs are rejected if they overlap `PUBLIC_EGRESS_EXCEPT_CIDRS` (RFC1918, CGNAT, loopback, link-local incl. cloud metadata, documentation, benchmarking, multicast, reserved ranges). Hostnames like `localhost`, `metadata.goog`, `*.internal`, `*.svc`, `*.cluster.local` are rejected outright.- **`public-web`** — `0.0.0.0/0` on TCP 80/443 with `PUBLIC_EGRESS_EXCEPT_CIDRS` carved out via `except`.-Results are written to the McpServer's `status.conditions` (`ExternalEgressReady`) and `status.resolvedEgressIPs`. A failed binding blocks runtime reconciliation of that server, so a workload cannot start before its egress converges. DNS answers are re-resolved periodically (`HCC_EXTERNAL_EGRESS_RESYNC_SEC`, default 300s).+Results are written to the McpServer's `status.conditions` (`ExternalEgressReady`) and `status.resolvedEgressIPs`. A failed binding blocks runtime reconciliation of that server, so a workload cannot start before its egress converges. DNS-derived allows are never retained across a failed refresh: HCC revokes the unprovable policy before certifying global readiness, while only the affected runtime remains blocked until DNS recovers. Each lookup has a bounded deadline.++HCC readiness certifies authoritative inventory and revocation safety, not+completion of positive policy creation. A renamed or newly requested allow may+therefore remain unavailable after HCC becomes Ready until its additive+reconciliation succeeds. HCC never keeps an obsolete allow merely to avoid+that availability gap: when old and new ownership cannot be proven equivalent,+revocation wins and only the affected runtime remains fail-closed.++During an in-place release, HCC is also the controller that stamps+`CONTEXT_MAPPER_HOST_IMAGE` onto managed mcp-host workloads. The new HCC+producer is consequently running before it replaces those consumers with the+new mcp-host image. For compatibility, an omitted `status.authoritative` field+retains the legacy fail-closed meaning; only an explicit `authoritative: false`+asks a new mcp-host to preserve an unchanged live connection.### Recipe binding policies@@ -267,16 +281,17 @@ a permissive policy — see the NetworkPolicy and GFS tables:### MCP server provisioning-| Variable | Default | Description |-| -------------------------------------------- | ----------------------------------- | ----------------------------------------------------------------------------------------------------------- |-| `CONTEXT_MAPPER_MCPSERVER_IMAGE_PULL_POLICY` | `IfNotPresent` | Pull policy for reconciled McpServer workloads. |-| `CONTEXT_MAPPER_EGRESS_PROXY_IMAGE` | `clerum/nginx-egress-proxy:0.1.0` | Per-server nginx egress proxy for **remote** MCP servers (`spec.remote`). |-| `CONTEXT_MAPPER_STDIO_BRIDGE_IMAGE` | (registry-qualified `stdio-bridge`) | stdio-bridge sidecar image for managed stdio MCP servers. Manifest pins `clerum/stdio-bridge:0.9.5`. |-| `CONTEXT_MAPPER_STDIO_BRIDGE_REQUEST_MEMORY` | `32Mi` | stdio-bridge sidecar memory request. |-| `CONTEXT_MAPPER_STDIO_BRIDGE_REQUEST_CPU` | `50m` | stdio-bridge sidecar CPU request. |-| `CONTEXT_MAPPER_STDIO_BRIDGE_LIMIT_MEMORY` | `128Mi` | stdio-bridge sidecar memory limit. |-| `CONTEXT_MAPPER_STDIO_BRIDGE_LIMIT_CPU` | `200m` | stdio-bridge sidecar CPU limit. |-| `HCC_EXTERNAL_EGRESS_RESYNC_SEC` | `300` | Periodic external-egress DNS resync (seconds), so DNS changes converge without a watch event. `0` disables. |+| Variable | Default | Description |+| -------------------------------------------- | ----------------------------------- | -------------------------------------------------------------------------------------------------------------------- |+| `CONTEXT_MAPPER_MCPSERVER_IMAGE_PULL_POLICY` | `IfNotPresent` | Pull policy for reconciled McpServer workloads. |+| `CONTEXT_MAPPER_EGRESS_PROXY_IMAGE` | `clerum/nginx-egress-proxy:0.1.0` | Per-server nginx egress proxy for **remote** MCP servers (`spec.remote`). |+| `CONTEXT_MAPPER_STDIO_BRIDGE_IMAGE` | (registry-qualified `stdio-bridge`) | stdio-bridge sidecar image for managed stdio MCP servers. Manifest pins `clerum/stdio-bridge:0.9.5`. |+| `CONTEXT_MAPPER_STDIO_BRIDGE_REQUEST_MEMORY` | `32Mi` | stdio-bridge sidecar memory request. |+| `CONTEXT_MAPPER_STDIO_BRIDGE_REQUEST_CPU` | `50m` | stdio-bridge sidecar CPU request. |+| `CONTEXT_MAPPER_STDIO_BRIDGE_LIMIT_MEMORY` | `128Mi` | stdio-bridge sidecar memory limit. |+| `CONTEXT_MAPPER_STDIO_BRIDGE_LIMIT_CPU` | `200m` | stdio-bridge sidecar CPU limit. |+| `HCC_EXTERNAL_EGRESS_RESYNC_SEC` | `300` | Periodic external-egress DNS resync interval (seconds). `0` disables periodic refresh; watch events still reconcile. |+| `HCC_EXTERNAL_EGRESS_DNS_TIMEOUT_MS` | `5000` | Per-hostname DNS lookup deadline in milliseconds. |### mcp-host provisioningdiff --git a/host-context-controller/package-lock.json b/host-context-controller/package-lock.jsonindex dc160d1d5..ea37a6044 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.175",+ "version": "0.1.176","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "clerum-host-context-controller",- "version": "0.1.175",+ "version": "0.1.176","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 e3c5e1512..a605aef45 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.175",+ "version": "0.1.176","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 6da92a177..a82539737 100644--- a/host-context-controller/src/__tests__/reconciler.remote.test.ts+++ b/host-context-controller/src/__tests__/reconciler.remote.test.ts@@ -675,105 +675,6 @@ describe('McpServerReconciler remote egress proxy', () => {})})- describe('canonicalizeRemoteEgressProxyImage', () => {- it('patches stale remote spec.image without mutating the observed cache object', async () => {- const staleRemote = cloneServer(REMOTE_SERVER, {- image: LEGACY_REMOTE_EGRESS_IMAGE,- })-- await (reconciler as any).canonicalizeRemoteEgressProxyImage(staleRemote)-- expect(customApi.patchNamespacedCustomObject).toHaveBeenCalledWith(- expect.objectContaining({- group: 'clerum.io',- version: 'v1alpha1',- namespace: 'mcp-server',- plural: 'mcpservers',- name: 'mcp-sentry-remote',- body: {- spec: {- image: 'clerum/nginx-egress-proxy:0.1.0',- },- },- }),- expect.objectContaining({- middleware: expect.any(Array),- })- )- expect(staleRemote.spec.image).toBe(LEGACY_REMOTE_EGRESS_IMAGE)- expect(lastPatchedStatusConditions(customApi)).toEqual(- expect.arrayContaining([- expect.objectContaining({- type: 'ImageCanonicalized',- status: 'True',- reason: 'RemoteEgressProxyImageMatches',- message: 'Remote McpServer spec.image matches the platform egress proxy image',- }),- ])- )- })-- it('does not patch spec for a remote McpServer already using the platform image', async () => {- const currentRemote = cloneServer(REMOTE_SERVER)-- await (reconciler as any).canonicalizeRemoteEgressProxyImage(currentRemote)-- expect(customApi.patchNamespacedCustomObject).not.toHaveBeenCalled()- expect(lastPatchedStatusConditions(customApi)).toEqual(- expect.arrayContaining([- expect.objectContaining({- type: 'ImageCanonicalized',- status: 'True',- reason: 'RemoteEgressProxyImageMatches',- message: 'Remote McpServer spec.image matches the platform egress proxy image',- }),- ])- )- })-- it('does not patch local McpServers even when their image differs', async () => {- const localServer = cloneServer(LOCAL_SERVER, {- image: 'clerum/custom-local-mcp:1.2.3',- })-- await (reconciler as any).canonicalizeRemoteEgressProxyImage(localServer)-- expect(customApi.patchNamespacedCustomObject).not.toHaveBeenCalled()- expect(customApi.patchNamespacedCustomObjectStatus).not.toHaveBeenCalled()- expect(localServer.spec.image).toBe('clerum/custom-local-mcp:1.2.3')- })-- it('does not throw and records status when declarative image patching fails', async () => {- const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined)- const staleRemote = cloneServer(REMOTE_SERVER, {- image: LEGACY_REMOTE_EGRESS_IMAGE,- })- customApi.patchNamespacedCustomObject.mockRejectedValueOnce(new Error('rbac denied'))-- await expect(- (reconciler as any).canonicalizeRemoteEgressProxyImage(staleRemote)- ).resolves.toBeUndefined()-- expect(staleRemote.spec.image).toBe(LEGACY_REMOTE_EGRESS_IMAGE)- expect(warn).toHaveBeenCalledWith(- expect.stringContaining('Failed to canonicalize remote McpServer'),- expect.any(Error)- )- expect(lastPatchedStatusConditions(customApi)).toEqual(- expect.arrayContaining([- expect.objectContaining({- type: 'ImageCanonicalized',- status: 'False',- reason: 'RemoteEgressProxyImagePatchFailed',- message:- 'Failed to patch remote McpServer spec.image to the platform egress proxy image',- }),- ])- )- warn.mockRestore()- })- })-// ─── Test 3: buildDeployment for local servers ─────────────────────────describe('buildDeployment for local servers', () => {@@ -842,16 +743,12 @@ describe('McpServerReconciler remote egress proxy', () => {expect(cmIndex).toBeLessThan(deployIndex)})- it('should canonicalize stale remote image before syncing ConfigMap and Deployment', async () => {+ it('should use the platform image without rewriting a divergent remote desired image', async () => {const callOrder: string[] = []const staleRemote = cloneServer(REMOTE_SERVER, {image: LEGACY_REMOTE_EGRESS_IMAGE,})- customApi.patchNamespacedCustomObject.mockImplementation(async () => {- callOrder.push('canonicalizeImage')- return {}- })coreApi.createNamespacedConfigMap.mockImplementation(async () => {callOrder.push('createConfigMap')return {}@@ -867,23 +764,28 @@ describe('McpServerReconciler remote egress proxy', () => {await reconciler.reconcile(staleRemote)- expect(callOrder).toEqual([- 'canonicalizeImage',- 'createConfigMap',- 'createService',- 'createDeployment',- ])+ expect(callOrder).toEqual(['createConfigMap', 'createService', 'createDeployment'])expect(staleRemote.spec.image).toBe(LEGACY_REMOTE_EGRESS_IMAGE)- expect(customApi.patchNamespacedCustomObject).toHaveBeenCalledWith(- expect.objectContaining({- body: {- spec: {- image: 'clerum/nginx-egress-proxy:0.1.0',- },- },- }),+ expect(customApi.patchNamespacedCustomObject).not.toHaveBeenCalledWith(+ expect.objectContaining({ body: expect.objectContaining({ spec: expect.anything() }) }),+ expect.anything()+ )+ expect(appsApi.createNamespacedDeployment).toHaveBeenCalledWith(expect.objectContaining({- middleware: expect.any(Array),+ body: expect.objectContaining({+ spec: expect.objectContaining({+ template: expect.objectContaining({+ spec: expect.objectContaining({+ containers: [+ expect.objectContaining({+ name: 'egress-proxy',+ image: 'clerum/nginx-egress-proxy:0.1.0',+ }),+ ],+ }),+ }),+ }),+ }),}))})diff --git a/host-context-controller/src/config.externalEgressDnsTimeout.test.ts b/host-context-controller/src/config.externalEgressDnsTimeout.test.tsnew file mode 100644index 000000000..7396924b9--- /dev/null+++ b/host-context-controller/src/config.externalEgressDnsTimeout.test.ts@@ -0,0 +1,46 @@+import { afterEach, describe, expect, it, vi } from 'vitest'++const originalEnv = process.env++async function loadConfig(raw: string | undefined) {+ vi.resetModules()+ process.env = { ...originalEnv }+ if (raw === undefined) {+ delete process.env.HCC_EXTERNAL_EGRESS_DNS_TIMEOUT_MS+ } else {+ process.env.HCC_EXTERNAL_EGRESS_DNS_TIMEOUT_MS = raw+ }+ return import('./config')+}++afterEach(() => {+ process.env = originalEnv+ vi.resetModules()+})++describe('HCC_EXTERNAL_EGRESS_DNS_TIMEOUT_MS', () => {+ it.each([undefined, '', ' '])('defaults to 5000 for %s', async raw => {+ const { config } = await loadConfig(raw)++ expect(config.externalEgressDnsResolveTimeoutMs).toBe(5_000)+ })++ it.each([+ ['1', 1],+ ['5000', 5_000],+ ['2147483647', 2_147_483_647],+ ])('accepts the positive bounded integer %s', async (raw, expected) => {+ const { config } = await loadConfig(raw)++ expect(config.externalEgressDnsResolveTimeoutMs).toBe(expected)+ })++ it.each(['0', '-1', '1.5', '5000junk', 'NaN', 'Infinity', '2147483648'])(+ "fails configuration validation for '%s'",+ async raw => {+ await expect(loadConfig(raw)).rejects.toThrow(+ 'HCC_EXTERNAL_EGRESS_DNS_TIMEOUT_MS must be a positive integer'+ )+ }+ )+})diff --git a/host-context-controller/src/config.ts b/host-context-controller/src/config.tsindex fb5c805ea..decfeaeb8 100644--- a/host-context-controller/src/config.ts+++ b/host-context-controller/src/config.ts@@ -196,6 +196,10 @@ export interface Config {// requiring a watch event. 0 disables.externalEgressResyncIntervalSec: number+ // Deadline for one DNS resolution attempt. A silent resolver cannot block+ // safety convergence indefinitely.+ externalEgressDnsResolveTimeoutMs: number+// Plugin image-host allowlist (Phase 2.3). Trusted raw-image prefixes for// local-mode McpServer images. Audit mode (default) logs would-be denials// without blocking; enforce mode blocks the workload build.@@ -229,6 +233,17 @@ function getEnvInt(key: string, defaultValue: number): number {return isNaN(parsed) ? defaultValue : parsed}+export function parseExternalEgressDnsTimeoutMs(raw: string | undefined): number {+ if (raw === undefined || raw.trim() === '') return 5_000+ const parsed = Number(raw)+ if (!Number.isSafeInteger(parsed) || parsed <= 0 || parsed > 2_147_483_647) {+ throw new Error(+ `HCC_EXTERNAL_EGRESS_DNS_TIMEOUT_MS must be a positive integer no greater than 2147483647, got '${raw}'`+ )+ }+ return parsed+}+/*** CONTEXT_MAPPER_HEARTBEAT_POLL_MS — cadence of HCC's control-api heartbeat* poll. Fails config load loudly on a non-positive-integer value: a silent@@ -596,6 +611,9 @@ export const config: Config = {// Periodic external-egress DNS resync (default 5 min). 0 disables.externalEgressResyncIntervalSec: getEnvInt('HCC_EXTERNAL_EGRESS_RESYNC_SEC', 300),+ externalEgressDnsResolveTimeoutMs: parseExternalEgressDnsTimeoutMs(+ getEnv('HCC_EXTERNAL_EGRESS_DNS_TIMEOUT_MS')+ ),// Plugin image-host allowlist (Phase 2.3). Permissive default = current// fleet hosts + registry.evenfire.ai; enforce defaults to false (audit mode).diff --git a/host-context-controller/src/hostFleetScheduler.test.ts b/host-context-controller/src/hostFleetScheduler.test.tsindex 82f29c77c..0f6817cfa 100644--- a/host-context-controller/src/hostFleetScheduler.test.ts+++ b/host-context-controller/src/hostFleetScheduler.test.ts@@ -63,6 +63,35 @@ describe('HostFleetScheduler', () => {expect(results).toEqual(['started', 'coalesced', 'coalesced', 'trailing'])})+ it('carries the known lifecycle generation when merging a generation-less full request', async () => {+ const activePass = deferred()+ const requests: HostFleetReconcileRequest[] = []+ const scheduler = new HostFleetScheduler({+ perform: async request => {+ requests.push({ ...request })+ if (requests.length === 1) await activePass.promise+ },+ recordRequest: vi.fn(),+ })+ const generation = scheduler.beginLifecycleTransition()+ const active = scheduler.request('active')+ await vi.waitFor(() => expect(requests).toHaveLength(1))+ scheduler.bumpInputRevision()+ const pendingLifecycle = scheduler.request('lifecycle', generation, 'lifecycle')+ scheduler.bumpInputRevision()+ const pendingFull = scheduler.request('full')++ activePass.resolve()+ await Promise.all([active, pendingLifecycle, pendingFull])++ expect(requests[1]).toMatchObject({+ reason: 'full',+ mode: 'full',+ ccLifecycleGeneration: generation,+ inputRevision: 2,+ })+ })+it('reuses active work only when its mode, revision, and lifecycle generation cover the request', async () => {const activePass = deferred()const requests: HostFleetReconcileRequest[] = []@@ -189,6 +218,32 @@ describe('HostFleetScheduler', () => {expect(perform).not.toHaveBeenCalled()})+ it('does not let a stale applied marker clear the current generation retry', async () => {+ vi.useFakeTimers()+ const perform = vi.fn<(request: HostFleetReconcileRequest) => Promise<void>>(+ async () => undefined+ )+ const scheduler = new HostFleetScheduler({+ perform,+ recordRequest: vi.fn(),+ })+ const staleGeneration = scheduler.beginLifecycleTransition()+ const currentGeneration = scheduler.beginLifecycleTransition()+ scheduler.scheduleLifecycleRetry({+ reason: 'current lifecycle',+ mode: 'lifecycle',+ ccLifecycleGeneration: currentGeneration,+ inputRevision: 0,+ })++ scheduler.markLifecycleApplied(staleGeneration)+ await vi.advanceTimersByTimeAsync(5000)++ expect(perform).toHaveBeenCalledWith(+ expect.objectContaining({ ccLifecycleGeneration: currentGeneration })+ )+ })+it('retries an unapplied current lifecycle generation with bounded backoff', async () => {vi.useFakeTimers()const requests: HostFleetReconcileRequest[] = []diff --git a/host-context-controller/src/hostReconciler.test.ts b/host-context-controller/src/hostReconciler.test.tsindex e5b77d8f5..40a2c8a09 100644--- a/host-context-controller/src/hostReconciler.test.ts+++ b/host-context-controller/src/hostReconciler.test.ts@@ -1185,6 +1185,48 @@ describe('HostReconciler Host inventory mutation authority', () => {expect(ensureServiceAccount).not.toHaveBeenCalled()})+ it('keeps a Host reconcile admitted when a watch replaces dependencies with deep-equal values', async () => {+ const reconciler = makeBasicReconciler()+ const host = {+ ...makeHost({ name: 'deep-equal-dependency', contextRef: 'context-a' }),+ uid: 'deep-equal-dependency-uid',+ generation: 5,+ }+ let selectedContext: unknown = {+ name: 'context-a',+ spec: {+ sharedFileSystems: [{ name: 'documents', mountPath: '/contexts/documents' }],+ },+ }+ reconciler.setResolveCurrentHost(name => (name === host.name ? host : undefined))+ reconciler.setHostMutationAuthority(() => ({+ known: true,+ hostGeneration: 7,+ contextGeneration: 11,+ }))+ reconciler.setResolveHostMutationDependencies(() => [selectedContext])++ const secretReadStarted = deferred()+ const releaseSecretRead = deferred()+ vi.spyOn(reconciler as any, 'validateHostSecret').mockImplementation(async () => {+ secretReadStarted.resolve(undefined)+ await releaseSecretRead.promise+ return { ok: true }+ })+ const admitted = new Error('deep-equal dependency admitted')+ const ensureServiceAccount = vi+ .spyOn(reconciler as any, 'ensureHostServiceAccount')+ .mockRejectedValue(admitted)++ const pending = reconciler.reconcile(host)+ await secretReadStarted.promise+ selectedContext = structuredClone(selectedContext)+ releaseSecretRead.resolve(undefined)++ await expect(pending).rejects.toBe(admitted)+ expect(ensureServiceAccount).toHaveBeenCalled()+ })+it.each([['referenced SharedFileSystem revision',diff --git a/host-context-controller/src/hostReconciler.ts b/host-context-controller/src/hostReconciler.tsindex ac253d7c7..ac4410e15 100644--- a/host-context-controller/src/hostReconciler.ts+++ b/host-context-controller/src/hostReconciler.ts@@ -1,6 +1,7 @@import * as k8s from '@kubernetes/client-node'import { IntOrString } from '@kubernetes/client-node/dist/types.js'import { createHash, randomUUID } from 'crypto'+import { isDeepStrictEqual } from 'node:util'import * as path from 'path'import type { AdministrativeOutcomeReporter } from './administrativeOutcomeReporter'import { config } from './config'@@ -647,12 +648,19 @@ export class HostReconciler {const sameDependencies =capturedDependencies !== undefined &&capturedDependencies.length === currentDependencies.length &&- capturedDependencies.every((value, index) => Object.is(value, currentDependencies[index]))+ capturedDependencies.every((value, index) =>+ isDeepStrictEqual(value, currentDependencies[index])+ )if (!sameDependencies) {throw new HostMutationDependencyChangedError(action, requested.name)}}- return current+ // McpServerWatcher owns the canonical LIST/WATCH cache object. Mutation+ // bodies historically reflect status into their admitted object for+ // same-pass decisions, so detach the working snapshot whenever a live+ // cache resolver is wired. Standalone callers without a resolver retain+ // the legacy caller-visible reflection contract.+ return structuredClone(current)}}diff --git a/host-context-controller/src/k8sClient.test.ts b/host-context-controller/src/k8sClient.test.tsindex 39309f519..1909cfeab 100644--- a/host-context-controller/src/k8sClient.test.ts+++ b/host-context-controller/src/k8sClient.test.ts@@ -577,11 +577,15 @@ describe('McpServerWatcher startup', () => {})await (watcher as any).reconcileHostsReferencingSfs('bootstrap-sfs')await (watcher as any).reconcileHostsReferencingContext('bootstrap-context')+ ;(watcher as any).ccCacheSynced = falseawait (watcher as any).reconcileChannelReaderRevision('bootstrap-channel-secret', 'channels')expect(hostReconciler.reconcile).not.toHaveBeenCalled()expect(hostReconciler.patchChannelReaderRevisionAnnotation).not.toHaveBeenCalled()expect(hostReconciler.reconcileChannelReaderRevision).not.toHaveBeenCalled()+ expect(warnSpy).toHaveBeenCalledWith(+ '[K8s] Deferring CommunicationChannel Secret "channels/bootstrap-channel-secret" Host convergence; CommunicationChannel cache is not authoritative'+ )expect((watcher as any).hostCacheRecoveryTimer).not.toBeNull()} finally {await watcher.stop()@@ -1076,6 +1080,77 @@ describe('McpServerWatcher startup', () => {}})+ it.each([+ ['SharedFileSystem', 'LIST', 'sharedfilesystems', 'startSharedFileSystemWatch'],+ ['SharedFileSystem', 'WATCH', 'sharedfilesystems', 'startSharedFileSystemWatch'],+ ['GlobalFileSystem', 'LIST', 'globalfilesystems', 'startGlobalFileSystemWatch'],+ ['GlobalFileSystem', 'WATCH', 'globalfilesystems', 'startGlobalFileSystemWatch'],+ ] as const)(+ 'does not let a pending %s %s delay NetworkPolicy safety, bootstrap, or readiness certification',+ async (_kind, boundary, plural, watchMethod) => {+ const pendingBoundary = deferred<unknown>()+ const pendingAdditivePolicies = deferred()+ let completeAuthoritativeRevocation: (() => void) | undefined+ mocks.listNamespacedCustomObject.mockImplementation(+ async ({ plural: requestedPlural }: { plural: string }) => {+ if (requestedPlural === 'communicationchannels') {+ return { metadata: { resourceVersion: 'background-lane-rv' }, items: [] }+ }+ if (boundary === 'LIST' && requestedPlural === plural) {+ return pendingBoundary.promise+ }+ return { items: [] }+ }+ )+ mocks.netPolFullReconcile.mockImplementationOnce(+ async (+ _contexts: unknown,+ _servers: unknown,+ options?: { onAuthoritativeRevocationComplete?: () => void }+ ) => {+ completeAuthoritativeRevocation = options?.onAuthoritativeRevocationComplete+ await pendingAdditivePolicies.promise+ }+ )++ const watcher = new McpServerWatcher()+ stubAuthoritativeInventoryWatch(watcher, 'McpServer')+ stubAuthoritativeInventoryWatch(watcher, 'Context')+ const sfsWatch = vi+ .spyOn(watcher as any, 'startSharedFileSystemWatch')+ .mockResolvedValue(undefined)+ const gfsWatch = vi+ .spyOn(watcher as any, 'startGlobalFileSystemWatch')+ .mockResolvedValue(undefined)+ const targetWatch = watchMethod === 'startSharedFileSystemWatch' ? sfsWatch : gfsWatch+ if (boundary === 'WATCH') {+ targetWatch.mockImplementationOnce(() => pendingBoundary.promise as Promise<void>)+ }+ const bootstrap = watcher.start()++ try {+ await vi.waitFor(() => expect(mocks.netPolFullReconcile).toHaveBeenCalledOnce())+ await expect(bootstrap).resolves.toBeUndefined()++ expect(completeAuthoritativeRevocation).toBeTypeOf('function')+ expect(watcher.isReadinessInventoryAuthoritative()).toBe(false)+ if (boundary === 'LIST') {+ expect(targetWatch).not.toHaveBeenCalled()+ } else {+ expect(targetWatch).toHaveBeenCalledOnce()+ }++ completeAuthoritativeRevocation?.()+ await vi.waitFor(() => expect(watcher.isReadinessInventoryAuthoritative()).toBe(true))+ } finally {+ pendingBoundary.resolve({ items: [] })+ pendingAdditivePolicies.resolve(undefined)+ await flushMicrotasks()+ await watcher.stop()+ }+ }+ )+it('starts every initial background convergence lane from the caches current after watches', async () => {const staleServer = {metadata: { name: 'stale-server', namespace: 'mcp-server' },@@ -2222,12 +2297,12 @@ describe('McpServerWatcher startup', () => {randomSpy.mockRestore()})- it('queues SharedFileSystem and GlobalFileSystem watch effects behind their initial passes', async () => {+ it('queues same-object SharedFileSystem and GlobalFileSystem watch effects behind initial passes', async () => {const staleSfs = { name: 'stale-sfs', namespace: 'mcp-host', spec: {} }- const currentSfs = { metadata: { name: 'current-sfs', namespace: 'mcp-host' }, spec: {} }+ const currentSfs = { metadata: { name: 'stale-sfs', namespace: 'mcp-host' }, spec: {} }const staleGfs = { name: 'stale-gfs', namespace: 'mcp-host', spec: {} }const currentGfs = {- metadata: { name: 'current-gfs', namespace: 'mcp-host' },+ metadata: { name: 'stale-gfs', namespace: 'mcp-host' },spec: {},status: {phase: 'Ready',@@ -2947,12 +3022,12 @@ describe('McpServerWatcher startup', () => {const watcher = new McpServerWatcher()let queuedEffectRan = false- const first = (watcher as any)[enqueueMethod](async () => {+ const first = (watcher as any)[enqueueMethod]('same-object', async () => {firstStarted.resolve(undefined)await releaseFirst.promise}) as Promise<void>await firstStarted.promise- const queued = (watcher as any)[enqueueMethod](async () => {+ const queued = (watcher as any)[enqueueMethod]('same-object', async () => {queuedEffectRan = true}) as Promise<void>@@ -2964,6 +3039,90 @@ describe('McpServerWatcher startup', () => {})+ it.each([+ ['SharedFileSystem', 'enqueueSharedFileSystemReconciliation'],+ ['GlobalFileSystem', 'enqueueGlobalFileSystemReconciliation'],+ ] as const)(+ 'serializes the same %s identity without blocking an unrelated fleet member',+ async (_, enqueueMethod) => {+ const firstStarted = deferred()+ const releaseFirst = deferred()+ const secondStarted = deferred()+ const unrelatedStarted = deferred()+ const watcher = new McpServerWatcher()+ let secondRan = false++ const first = (watcher as any)[enqueueMethod]('slow', async () => {+ firstStarted.resolve(undefined)+ await releaseFirst.promise+ }) as Promise<void>+ await firstStarted.promise+ const second = (watcher as any)[enqueueMethod]('slow', async () => {+ secondRan = true+ secondStarted.resolve(undefined)+ }) as Promise<void>+ const unrelated = (watcher as any)[enqueueMethod]('independent', async () => {+ unrelatedStarted.resolve(undefined)+ }) as Promise<void>++ await unrelatedStarted.promise+ expect(secondRan).toBe(false)+ releaseFirst.resolve(undefined)+ await Promise.all([first, second, unrelated])+ await expect(secondStarted.promise).resolves.toBeUndefined()+ await watcher.stop()+ }+ )++ it('keeps a keyed lane alive until a third waiter has consumed the same queue entry', async () => {+ const firstStarted = deferred()+ const releaseFirst = deferred()+ const secondStarted = deferred()+ const releaseSecond = deferred()+ const thirdStarted = deferred()+ let thirdRan = false+ const watcher = new McpServerWatcher()++ const first = (watcher as any).enqueueContextReconciliation('shared', async () => {+ firstStarted.resolve(undefined)+ await releaseFirst.promise+ })+ await firstStarted.promise+ const second = (watcher as any).enqueueContextReconciliation('shared', async () => {+ secondStarted.resolve(undefined)+ await releaseSecond.promise+ })+ const third = (watcher as any).enqueueContextReconciliation('shared', async () => {+ thirdRan = true+ thirdStarted.resolve(undefined)+ })++ expect((watcher as any).contextReconciliationQueues.get('shared').references).toBe(3)+ releaseFirst.resolve(undefined)+ await secondStarted.promise+ expect(thirdRan).toBe(false)+ expect((watcher as any).contextReconciliationQueues.get('shared').references).toBe(2)+ releaseSecond.resolve(undefined)+ await Promise.all([first, second, third])+ expect((watcher as any).contextReconciliationQueues.has('shared')).toBe(false)+ await watcher.stop()+ })++ it('caps initial convergence retry delay after attempts exceed the schedule', async () => {+ vi.useFakeTimers()+ const watcher = new McpServerWatcher()+ const convergence = vi+ .spyOn(watcher as any, 'runInitialMcpServerConvergence')+ .mockResolvedValue(undefined)+ ;(watcher as any).initialConvergenceRetryAttempts.set('McpServer', 99)+ ;(watcher as any).scheduleInitialConvergenceRetry('McpServer')+ await vi.advanceTimersByTimeAsync(299_999)+ expect(convergence).not.toHaveBeenCalled()+ await vi.advanceTimersByTimeAsync(1)+ expect(convergence).toHaveBeenCalledOnce()+ await watcher.stop()+ })+it('defers NetworkPolicy full convergence until both inventories are authoritative', async () => {const watcher = new McpServerWatcher();(watcher as any).contextCacheSynced = true@@ -3181,10 +3340,8 @@ describe('McpServerWatcher startup', () => {it.each([['McpServer', 'startMcpServerWatch'],['Context', 'startContextWatch'],- ['SharedFileSystem', 'startSharedFileSystemWatch'],- ['GlobalFileSystem', 'startGlobalFileSystemWatch'],] as const)(- 'rejects safe bootstrap when the %s watch cannot be established',+ 'keeps safe bootstrap authority-gated when the %s watch cannot be established',async (_kind, method) => {const watcher = new McpServerWatcher()if (method === 'startMcpServerWatch') {@@ -3197,23 +3354,58 @@ describe('McpServerWatcher startup', () => {} 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(`${method} unavailable`)+ expect(watcher.isReadinessInventoryAuthoritative()).toBe(false)+ expect(mocks.netPolFullReconcile).not.toHaveBeenCalled()await watcher.stop()})+ it.each([+ ['SharedFileSystem', 'startSharedFileSystemWatch'],+ ['GlobalFileSystem', 'startGlobalFileSystemWatch'],+ ] as const)(+ 'isolates, logs, and retries an initial %s background watch rejection',+ async (kind, method) => {+ vi.useFakeTimers()+ const failure = new Error(`${method} unavailable`)+ const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {})+ const watcher = new McpServerWatcher()+ stubAuthoritativeInventoryWatch(watcher, 'McpServer')+ stubAuthoritativeInventoryWatch(watcher, 'Context')+ const rejectedWatch = vi+ .spyOn(watcher as any, method)+ .mockRejectedValueOnce(failure)+ .mockResolvedValueOnce(undefined)+ const otherMethod =+ method === 'startSharedFileSystemWatch'+ ? 'startGlobalFileSystemWatch'+ : 'startSharedFileSystemWatch'+ vi.spyOn(watcher as any, otherMethod).mockResolvedValue(undefined)+ vi.spyOn(watcher as any, 'startCommunicationChannelWatch').mockResolvedValue(undefined)++ await expect(watcher.start()).resolves.toBeUndefined()+ await vi.advanceTimersByTimeAsync(0)++ expect(errorSpy).toHaveBeenCalledWith(+ `[K8s] ${kind} background watch failed to start:`,+ failure+ )+ expect(rejectedWatch).toHaveBeenCalledOnce()+ expect(mocks.netPolFullReconcile).toHaveBeenCalledOnce()++ await vi.advanceTimersByTimeAsync(4_999)+ expect(rejectedWatch).toHaveBeenCalledOnce()+ await vi.advanceTimersByTimeAsync(1)+ expect(rejectedWatch).toHaveBeenCalledTimes(2)++ await watcher.stop()+ errorSpy.mockRestore()+ }+ )+it('applies the request deadline wrapper to the finite Host inventory LIST', async () => {mocks.listNamespacedCustomObject.mockImplementation(async ({ plural }: { plural: string }) => {if (plural === 'hosts') return { items: [] }@@ -4426,7 +4618,18 @@ describe('McpServerWatcher Host mutation dependency wiring', () => {const resolveDependencies = hostReconciler._hostMutationDependenciesFnconst original = resolveDependencies(host)- expect(original).toEqual([context, true, 7, documentsV1, true, alphaChannelV1])+ expect(original).toEqual([+ { name: context.name, namespace: context.namespace, spec: context.spec },+ true,+ 7,+ { name: documentsV1.name, namespace: documentsV1.namespace, spec: documentsV1.spec },+ true,+ {+ name: alphaChannelV1.name,+ namespace: alphaChannelV1.namespace,+ spec: alphaChannelV1.spec,+ },+ ]);(watcher as any).sharedFileSystems.set('unrelated', {name: 'unrelated',namespace: 'mcp-host',@@ -4438,11 +4641,7 @@ describe('McpServerWatcher Host mutation dependency wiring', () => {spec: { hostRef: 'beta-host' },})const afterUnrelatedChanges = resolveDependencies(host)- expect(- original.every((value: unknown, index: number) =>- Object.is(value, afterUnrelatedChanges[index])- )- ).toBe(true)+ expect(afterUnrelatedChanges).toEqual(original)const documentsV2 = {...documentsV1,@@ -4450,8 +4649,12 @@ describe('McpServerWatcher Host mutation dependency wiring', () => {};(watcher as any).sharedFileSystems.set(documentsV2.name, documentsV2)const afterSfsRevision = resolveDependencies(host)- expect(afterSfsRevision[3]).toBe(documentsV2)- expect(afterSfsRevision[3]).not.toBe(original[3])+ expect(afterSfsRevision[3]).toEqual({+ name: documentsV2.name,+ namespace: documentsV2.namespace,+ spec: documentsV2.spec,+ })+ expect(afterSfsRevision[3]).not.toEqual(original[3])sfsReconciler.isMountable.mockReturnValue(false)const afterMountabilityChange = resolveDependencies(host)@@ -4466,8 +4669,12 @@ describe('McpServerWatcher Host mutation dependency wiring', () => {};(watcher as any).communicationChannels.set(alphaChannelV2.name, alphaChannelV2)const afterChannelRevision = resolveDependencies(host)- expect(afterChannelRevision.at(-1)).toBe(alphaChannelV2)- expect(afterChannelRevision.at(-1)).not.toBe(original.at(-1))+ expect(afterChannelRevision.at(-1)).toEqual({+ name: alphaChannelV2.name,+ namespace: alphaChannelV2.namespace,+ spec: alphaChannelV2.spec,+ })+ expect(afterChannelRevision.at(-1)).not.toEqual(original.at(-1))})})diff --git a/host-context-controller/src/k8sClient.ts b/host-context-controller/src/k8sClient.tsindex f08a26503..3b58dcdd6 100644--- a/host-context-controller/src/k8sClient.ts+++ b/host-context-controller/src/k8sClient.ts@@ -658,6 +658,8 @@ export class McpServerWatcher implements McpServerProvider {private readonly hostWatchRetryAttempts = new Map<string, number>()private hostCacheSynced = falseprivate hostCacheRecoveryTimer: ReturnType<typeof setTimeout> | null = null+ private sfsWatchRestartTimer: ReturnType<typeof setTimeout> | null = null+ private gfsWatchRestartTimer: ReturnType<typeof setTimeout> | null = null// Host watch LIST-to-WATCH recovery is a dedicated, deduplicated operation// (§10.2). Concurrent recovery signals reuse the in-flight promise so exactly// one LIST + WATCH is installed. Independent per-Host events no longer share a@@ -711,14 +713,19 @@ export class McpServerWatcher implements McpServerProvider {InitialConvergenceLane,ActiveInitialConvergenceRun>()- // 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.+ // Every resource effect serializes by resource identity, so one slow fleet+ // member cannot block unrelated live events while same-resource updates+ // still retain last-writer ordering.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 readonly sharedFileSystemReconciliationQueues = new Map<+ string,+ KeyedReconciliationQueue+ >()+ private readonly globalFileSystemReconciliationQueues = new Map<+ string,+ KeyedReconciliationQueue+ >()private sharedFileSystemCacheRevision = 0private globalFileSystemCacheRevision = 0// Periodic resync timer: K8s watches can drop events on long disconnects;@@ -811,15 +818,31 @@ export class McpServerWatcher implements McpServerProvider {}))this.hostReconciler.setResolveHostMutationDependencies(host => {const context = this.contexts.get(host.spec.contextRef)- const dependencies: unknown[] = [context, this.ccCacheSynced, this.ccWatchGeneration]+ // Lease desired semantics, not cache-object identity or observed status.+ // Kubernetes watch events replace objects and status-only changes may+ // legitimately advance resourceVersion without changing Host inputs.+ const desiredRevision = <T extends { name: string; namespace: string; spec: unknown }>(+ resource: T | undefined+ ) =>+ resource+ ? { name: resource.name, namespace: resource.namespace, spec: resource.spec }+ : undefined+ const dependencies: unknown[] = [+ desiredRevision(context),+ this.ccCacheSynced,+ this.ccWatchGeneration,+ ]for (const ref of context?.spec.sharedFileSystems ?? []) {const sfs = this.sharedFileSystems.get(ref.name)- dependencies.push(sfs, sfs ? this.sharedFileSystemReconciler.isMountable(sfs) : false)+ dependencies.push(+ desiredRevision(sfs),+ sfs ? this.sharedFileSystemReconciler.isMountable(sfs) : false+ )}const channels = this.findCommunicationChannelsByHostRef(host.name).sort((a, b) =>a.name.localeCompare(b.name))- dependencies.push(...channels)+ dependencies.push(...channels.map(channel => desiredRevision(channel)))return dependencies})// Per-CC credentials Secret migration: HostReconciler computes the@@ -1097,18 +1120,59 @@ export class McpServerWatcher implements McpServerProvider {return inventoryAuthoritative() && !resolveCurrent()}- private enqueueSharedFileSystemReconciliation(work: () => Promise<void>): Promise<void> {- return this.sharedFileSystemReconciliationQueue.enqueue(async () => {- if (this.stopped) return- await work()- })+ private enqueueSharedFileSystemReconciliation(+ name: string,+ work: () => Promise<void>+ ): Promise<void> {+ return this.enqueueKeyedReconciliation(this.sharedFileSystemReconciliationQueues, name, work)}- private enqueueGlobalFileSystemReconciliation(work: () => Promise<void>): Promise<void> {- return this.globalFileSystemReconciliationQueue.enqueue(async () => {- if (this.stopped) return- await work()- })+ private enqueueGlobalFileSystemReconciliation(+ name: string,+ work: () => Promise<void>+ ): Promise<void> {+ return this.enqueueKeyedReconciliation(this.globalFileSystemReconciliationQueues, name, work)+ }++ /**+ * Fleet passes acquire every selected object lane in stable order. This+ * preserves their snapshot-wide ordering without making two unrelated live+ * watch events wait behind one another.+ */+ private enqueueKeyedFleetReconciliation(+ queues: Map<string, KeyedReconciliationQueue>,+ keys: string[],+ work: () => Promise<void>+ ): Promise<void> {+ const orderedKeys = [...new Set(keys)].sort()+ const enter = (index: number): Promise<void> => {+ const key = orderedKeys[index]+ if (!key) return work()+ return this.enqueueKeyedReconciliation(queues, key, () => enter(index + 1))+ }+ return enter(0)+ }++ private enqueueSharedFileSystemFleetReconciliation(+ names: string[],+ work: () => Promise<void>+ ): Promise<void> {+ return this.enqueueKeyedFleetReconciliation(+ this.sharedFileSystemReconciliationQueues,+ names,+ work+ )+ }++ private enqueueGlobalFileSystemFleetReconciliation(+ names: string[],+ work: () => Promise<void>+ ): Promise<void> {+ return this.enqueueKeyedFleetReconciliation(+ this.globalFileSystemReconciliationQueues,+ names,+ work+ )}private requireInventoryResourceVersion(@@ -1900,7 +1964,11 @@ export class McpServerWatcher implements McpServerProvider {nextContext: ContextCRD | undefined,isCurrent: () => boolean = () => true): Promise<void> {- return this.enqueueSharedFileSystemReconciliation(async () => {+ const names = [+ ...(prevContext?.spec.sharedFileSystems ?? []).map(ref => ref.name),+ ...(nextContext?.spec.sharedFileSystems ?? []).map(ref => ref.name),+ ]+ return this.enqueueSharedFileSystemFleetReconciliation(names, async () => {if (!isCurrent()) returnawait this.reconcileSharedFileSystemsReferencedByContextCore(prevContext,@@ -2090,7 +2158,12 @@ export class McpServerWatcher implements McpServerProvider {*/async reconcileChannelReaderRevision(secretName: string, secretNamespace: string): Promise<void> {const convergenceReason = `CommunicationChannel Secret "${secretNamespace}/${secretName}" Host convergence`- if (!this.ccCacheSynced) return+ if (!this.ccCacheSynced) {+ console.warn(+ `[K8s] Deferring ${convergenceReason}; CommunicationChannel cache is not authoritative`+ )+ return+ }if (!this.admitHostDependentEffects(convergenceReason)) {return}@@ -2285,51 +2358,6 @@ export class McpServerWatcher implements McpServerProvider {this.scheduleCommunicationChannelCacheRecovery()}- // ── SharedFileSystem initial inventory ──- let initialSfses: SharedFileSystemCRD[] = []- let sfsInventoryComplete = false- try {- initialSfses = await listAllSharedFileSystems()- sfsInventoryComplete = true- for (const sfs of initialSfses) {- this.sharedFileSystems.set(sfs.name, sfs)- }- } catch (error) {- console.error(- '[K8s] Skipping initial SharedFileSystem background convergence because discovery failed:',- error- )- }-- // ── GlobalFileSystem (gfs) initial inventory ──- // gfs is a cluster singleton (DISTINCT from SharedFileSystem). A failed- // discovery (e.g. the CRD not installed yet) is skipped, not fatal — the- // next HCC restart / resync retries. Live updates land via the watch- // and the periodic resync; the deploy applies the singleton before HCC- // reconciles it.- let initialGfses: GlobalFileSystemCRD[] = []- let gfsInventoryComplete = false- try {- initialGfses = await listAllGlobalFileSystems()- gfsInventoryComplete = true- for (const gfs of initialGfses) {- this.globalFileSystems.set(gfs.name, gfs)- }- } catch (error) {- console.error(- '[K8s] Skipping initial GlobalFileSystem background convergence because discovery failed:',- error- )- }-- // SFS/GFS retain their established eventual-resync contract. McpServer,- // Context and Host require authoritative LIST-to-WATCH handoffs before- // readiness. CommunicationChannel recovery instead fails safe by preserving- // replicas and disabling stateless suspension; full convergence remains- // outside readiness for every inventory.- await this.startSharedFileSystemWatch()- await this.startGlobalFileSystemWatch()-console.log(`[K8s] Starting initial Host background convergence... (ccCacheSynced=${this.ccCacheSynced})`)@@ -2401,10 +2429,52 @@ export class McpServerWatcher implements McpServerProvider {// This prevents the startup egress refresh from racing or undoing the safety// pass while keeping readiness independent from both additive fleets.void this.runInitialNetworkPolicyConvergence()- if (sfsInventoryComplete) {+ void this.startSharedFileSystemBackgroundLane()+ void this.startGlobalFileSystemBackgroundLane()+ }++ private async startSharedFileSystemBackgroundLane(): Promise<void> {+ let inventoryComplete = false+ try {+ const initialSfses = await listAllSharedFileSystems()+ inventoryComplete = true+ for (const sfs of initialSfses) this.sharedFileSystems.set(sfs.name, sfs)+ } catch (error) {+ console.error(+ '[K8s] Skipping initial SharedFileSystem background convergence because discovery failed:',+ error+ )+ }+ try {+ await this.startSharedFileSystemWatch()+ } catch (error) {+ console.error('[K8s] SharedFileSystem background watch failed to start:', error)+ this.scheduleSharedFileSystemWatchRestart(5000)+ }+ if (inventoryComplete && !this.stopped) {void this.runInitialSharedFileSystemConvergence()}- if (gfsInventoryComplete) {+ }++ private async startGlobalFileSystemBackgroundLane(): Promise<void> {+ let inventoryComplete = false+ try {+ const initialGfses = await listAllGlobalFileSystems()+ inventoryComplete = true+ for (const gfs of initialGfses) this.globalFileSystems.set(gfs.name, gfs)+ } catch (error) {+ console.error(+ '[K8s] Skipping initial GlobalFileSystem background convergence because discovery failed:',+ error+ )+ }+ try {+ await this.startGlobalFileSystemWatch()+ } catch (error) {+ console.error('[K8s] GlobalFileSystem background watch failed to start:', error)+ this.scheduleGlobalFileSystemWatchRestart(5000)+ }+ if (inventoryComplete && !this.stopped) {void this.runInitialGlobalFileSystemConvergence()}}@@ -2631,7 +2701,8 @@ export class McpServerWatcher implements McpServerProvider {}private runInitialSharedFileSystemConvergence(): Promise<void> {- return this.enqueueSharedFileSystemReconciliation(() =>+ const names = [...this.sharedFileSystems.keys()]+ return this.enqueueSharedFileSystemFleetReconciliation(names, () =>this.runInitialSharedFileSystemConvergenceCore())}@@ -2647,7 +2718,8 @@ export class McpServerWatcher implements McpServerProvider {}private runInitialGlobalFileSystemConvergence(): Promise<void> {- return this.enqueueGlobalFileSystemReconciliation(() =>+ const names = [...this.globalFileSystems.keys()]+ return this.enqueueGlobalFileSystemFleetReconciliation(names, () =>this.runInitialGlobalFileSystemConvergenceCore())}@@ -2688,7 +2760,7 @@ export class McpServerWatcher implements McpServerProvider {}this.sharedFileSystemCacheRevision += 1- await this.enqueueSharedFileSystemReconciliation(async () => {+ await this.enqueueSharedFileSystemReconciliation(sfs.name, async () => {try {if (type === 'ADDED' || type === 'MODIFIED') {await this.sharedFileSystemReconciler.reconcile(sfs)@@ -2715,16 +2787,29 @@ export class McpServerWatcher implements McpServerProvider {const doneCallback = (err: Error | null) => {if (this.stopped) return+ this.sfsWatchRequest = nullif (err) {console.error('[K8s] SharedFileSystem watch error:', err)}console.log('[K8s] SharedFileSystem watch ended, restarting...')- setTimeout(() => this.startSharedFileSystemWatch(), err ? 5000 : 1000)+ this.scheduleSharedFileSystemWatchRestart(err ? 5000 : 1000)}this.sfsWatchRequest = await this.watch.watch(path, {}, watchCallback, doneCallback)}+ private scheduleSharedFileSystemWatchRestart(delayMs: number): void {+ if (this.stopped || this.sfsWatchRestartTimer) return+ this.sfsWatchRestartTimer = setTimeout(() => {+ this.sfsWatchRestartTimer = null+ if (this.stopped) return+ void this.startSharedFileSystemWatch().catch(error => {+ console.error('[K8s] SharedFileSystem background watch restart failed:', error)+ this.scheduleSharedFileSystemWatchRestart(5000)+ })+ }, delayMs)+ }+/*** Watch the GlobalFileSystem singleton (gfs). ADDED/MODIFIED → reconcile the* drive stack; DELETED → tear it down (respecting retainOnDelete). DISTINCT@@ -2757,7 +2842,7 @@ export class McpServerWatcher implements McpServerProvider {this.globalFileSystems.delete(gfs.name)}this.globalFileSystemCacheRevision += 1- await this.enqueueGlobalFileSystemReconciliation(async () => {+ await this.enqueueGlobalFileSystemReconciliation(gfs.name, async () => {try {if (type === 'ADDED' || type === 'MODIFIED') {await this.gfsReconciler.reconcile(gfs)@@ -2772,16 +2857,29 @@ export class McpServerWatcher implements McpServerProvider {const doneCallback = (err: Error | null) => {if (this.stopped) return+ this.gfsWatchRequest = nullif (err) {console.error('[K8s] GlobalFileSystem watch error:', err)}console.log('[K8s] GlobalFileSystem watch ended, restarting...')- setTimeout(() => this.startGlobalFileSystemWatch(), err ? 5000 : 1000)+ this.scheduleGlobalFileSystemWatchRestart(err ? 5000 : 1000)}this.gfsWatchRequest = await this.watch.watch(path, {}, watchCallback, doneCallback)}+ private scheduleGlobalFileSystemWatchRestart(delayMs: number): void {+ if (this.stopped || this.gfsWatchRestartTimer) return+ this.gfsWatchRestartTimer = setTimeout(() => {+ this.gfsWatchRestartTimer = null+ if (this.stopped) return+ void this.startGlobalFileSystemWatch().catch(error => {+ console.error('[K8s] GlobalFileSystem background watch restart failed:', error)+ this.scheduleGlobalFileSystemWatchRestart(5000)+ })+ }, delayMs)+ }+/*** Extracted so unit tests can invoke the handler without spinning up a real* K8s watch. Production calls this from `startCommunicationChannelWatch` and@@ -3002,15 +3100,35 @@ export class McpServerWatcher implements McpServerProvider {* one-time root-directory seed once the writer is up. Idempotent; per-item* failures are logged by fullReconcile, never thrown.*/- private runGfsResync(): Promise<void> {- return this.enqueueGlobalFileSystemReconciliation(() => this.runGfsResyncCore())- }-- private async runGfsResyncCore(): Promise<void> {+ private async runGfsResync(): Promise<void> {if (this.stopped) returntry {const cacheRevisionAtListStart = this.globalFileSystemCacheRevisionconst gfses = await listAllGlobalFileSystems()+ const names = [+ ...this.globalFileSystems.keys(),+ ...gfses.map(globalFileSystem => globalFileSystem.name),+ ]+ return this.enqueueGlobalFileSystemFleetReconciliation(names, () =>+ this.runGfsResyncCore(gfses, cacheRevisionAtListStart)+ )+ } catch (err) {+ console.error(+ `[K8s] GlobalFileSystem periodic resync failed: ${+ err instanceof Error ? err.message : String(err)+ }`+ )+ }+ }++ private async runGfsResyncCore(+ listedGfses?: GlobalFileSystemCRD[],+ listedAtCacheRevision?: number+ ): Promise<void> {+ if (this.stopped) return+ try {+ const cacheRevisionAtListStart = listedAtCacheRevision ?? this.globalFileSystemCacheRevision+ const gfses = listedGfses ?? (await listAllGlobalFileSystems())let reconcileInventory: GlobalFileSystemCRD[]if (cacheRevisionAtListStart === this.globalFileSystemCacheRevision) {this.globalFileSystems.clear()@@ -3029,15 +3147,31 @@ export class McpServerWatcher implements McpServerProvider {}}- private runSfsResync(): Promise<void> {- return this.enqueueSharedFileSystemReconciliation(() => this.runSfsResyncCore())- }-- private async runSfsResyncCore(): Promise<void> {+ private async runSfsResync(): Promise<void> {if (this.stopped) returntry {const cacheRevisionAtListStart = this.sharedFileSystemCacheRevisionconst sfses = await listAllSharedFileSystems()+ const names = [+ ...this.sharedFileSystems.keys(),+ ...sfses.map(sharedFileSystem => sharedFileSystem.name),+ ]+ return this.enqueueSharedFileSystemFleetReconciliation(names, () =>+ this.runSfsResyncCore(sfses, cacheRevisionAtListStart)+ )+ } catch (error) {+ console.error('[K8s] Periodic SharedFileSystem resync failed:', error)+ }+ }++ private async runSfsResyncCore(+ listedSfses?: SharedFileSystemCRD[],+ listedAtCacheRevision?: number+ ): Promise<void> {+ if (this.stopped) return+ try {+ const cacheRevisionAtListStart = listedAtCacheRevision ?? this.sharedFileSystemCacheRevision+ const sfses = listedSfses ?? (await listAllSharedFileSystems())let reconcileInventory: SharedFileSystemCRD[]if (cacheRevisionAtListStart === this.sharedFileSystemCacheRevision) {this.sharedFileSystems.clear()@@ -3650,6 +3784,14 @@ export class McpServerWatcher implements McpServerProvider {clearTimeout(this.hostCacheRecoveryTimer)this.hostCacheRecoveryTimer = null}+ if (this.sfsWatchRestartTimer) {+ clearTimeout(this.sfsWatchRestartTimer)+ this.sfsWatchRestartTimer = null+ }+ if (this.gfsWatchRestartTimer) {+ clearTimeout(this.gfsWatchRestartTimer)+ this.gfsWatchRestartTimer = null+ }this.hostCacheRecoveryIntent = nullif (this.mcpServerCacheRecoveryTimer) {clearTimeout(this.mcpServerCacheRecoveryTimer)diff --git a/host-context-controller/src/main.ts b/host-context-controller/src/main.tsindex 0e2c03176..82d993bb4 100644--- a/host-context-controller/src/main.ts+++ b/host-context-controller/src/main.ts@@ -208,11 +208,11 @@ async function main(): Promise<void> {// reconcileChannelReaderRevision is self-contained (does not throw), so// the .catch here is defensive — it catches any unexpected runtime error// in the SecretInformer's own callback path.- if (!config.devMode && hostReconciler) {+ if (!config.devMode && watcher) {const kc = getKubeConfig()if (kc) {channelSecretInformer = new SecretInformer(kc, config.channelsNamespace, evt => {- watcher?.reconcileChannelReaderRevision(evt.name, evt.namespace).catch(err => {+ watcher.reconcileChannelReaderRevision(evt.name, evt.namespace).catch(err => {console.error('[Main] reconcileChannelReaderRevision failed:', err)})})diff --git a/host-context-controller/src/networkPolicyReconciler.test.ts b/host-context-controller/src/networkPolicyReconciler.test.tsindex f517a5dc6..4ca1c9693 100644--- a/host-context-controller/src/networkPolicyReconciler.test.ts+++ b/host-context-controller/src/networkPolicyReconciler.test.ts@@ -8,7 +8,11 @@ import {networkPolicySafetyPassDurationSeconds,networkPolicySafetyPassPoliciesTotal,} from './metrics'-import { NetworkPolicyReconciler, PUBLIC_EGRESS_EXCEPT_CIDRS } from './networkPolicyReconciler'+import {+ NetworkPolicyReconciler,+ PUBLIC_EGRESS_EXCEPT_CIDRS,+ sameContextDesiredRevision,+} from './networkPolicyReconciler'import { ContextCRD, McpServerCRD } from './types'function deferred<T = void>(): {@@ -40,6 +44,7 @@ vi.mock('./config', () => ({port: 8081,runtimeNamespaces: ['mcp-server', 'mcp-host', 'sandbox-recipes', 'rpc-proxy'],k8sApiCidrs: [],+ externalEgressDnsResolveTimeoutMs: 5_000,},}))@@ -94,7 +99,48 @@ function makeReconciler(})const cache = serverCache ?? new Map()const reconciler = new NetworkPolicyReconciler(kc, cache)- ;(reconciler as unknown as { networkingApi: unknown }).networkingApi = mockApi+ const listedPolicies = new Map<string, k8s.V1NetworkPolicy>()+ const networkingApi = {+ ...mockApi,+ listNamespacedNetworkPolicy: async (args: { namespace: string }) => {+ const response = await mockApi.listNamespacedNetworkPolicy(args)+ const items = (response.items ?? []).map((policy: k8s.V1NetworkPolicy, index: number) => {+ const name = policy.metadata?.name ?? `unnamed-${index}`+ const materialized = {+ ...policy,+ metadata: {+ ...policy.metadata,+ name,+ namespace: policy.metadata?.namespace ?? args.namespace,+ uid: policy.metadata?.uid ?? `${args.namespace}:${name}:uid`,+ resourceVersion: policy.metadata?.resourceVersion ?? '1',+ },+ }+ listedPolicies.set(`${args.namespace}/${name}`, materialized)+ return materialized+ })+ return { ...response, items }+ },+ readNamespacedNetworkPolicy: async (args: { name: string; namespace: string }) => {+ const response = await mockApi.readNamespacedNetworkPolicy(args)+ const listed = listedPolicies.get(`${args.namespace}/${args.name}`)+ return {+ ...listed,+ ...response,+ metadata: {+ ...listed?.metadata,+ ...response.metadata,+ name: response.metadata?.name ?? listed?.metadata?.name ?? args.name,+ namespace: response.metadata?.namespace ?? listed?.metadata?.namespace ?? args.namespace,+ uid:+ response.metadata?.uid ?? listed?.metadata?.uid ?? `${args.namespace}:${args.name}:uid`,+ resourceVersion:+ response.metadata?.resourceVersion ?? listed?.metadata?.resourceVersion ?? '1',+ },+ }+ },+ }+ ;(reconciler as unknown as { networkingApi: unknown }).networkingApi = networkingApi;(reconciler as unknown as { customApi: unknown }).customApi = mockCustomApireturn reconciler}@@ -105,6 +151,7 @@ describe('NetworkPolicyReconciler', () => {let reconciler: NetworkPolicyReconcilerbeforeEach(() => {+ vi.useRealTimers()mockApi = makeMockNetworkingApi()mockCustomApi = makeMockCustomApi()reconciler = makeReconciler(mockApi, undefined, mockCustomApi)@@ -112,6 +159,37 @@ describe('NetworkPolicyReconciler', () => {vi.mocked(dns.resolve4).mockResolvedValue(['1.2.3.4', '5.6.7.8'])})+ it('compares Context desired revisions canonically and fences identity changes', () => {+ const expected: ContextCRD = {+ name: 'default',+ namespace: 'mcp-server',+ uid: 'context-uid',+ generation: 7,+ spec: {+ contextId: 'default',+ mcpServers: ['alpha'],+ sharedFileSystems: [{ name: 'workspace', mountPath: '/workspace' }],+ },+ }+ const reordered: ContextCRD = {+ namespace: 'mcp-server',+ name: 'default',+ generation: 7,+ uid: 'context-uid',+ spec: {+ sharedFileSystems: [{ mountPath: '/workspace', name: 'workspace' }],+ mcpServers: ['alpha'],+ contextId: 'default',+ },+ }++ expect(sameContextDesiredRevision(expected, reordered)).toBe(true)+ expect(sameContextDesiredRevision(expected, { ...reordered, uid: 'replacement-uid' })).toBe(+ false+ )+ expect(sameContextDesiredRevision(expected, { ...reordered, generation: 8 })).toBe(false)+ })+it('records the authoritative safety-pass inventory, completed revocations, and duration', async () => {mockApi.listNamespacedNetworkPolicy.mockResolvedValueOnce({@@ -174,6 +252,7 @@ describe('NetworkPolicyReconciler', () => {{ outcome: 'completed' },expect.any(Number))+ expect(networkPolicySafetyPassDurationSeconds.observe).toHaveBeenCalledTimes(1)})describe('public egress blocklist parity', () => {@@ -398,14 +477,18 @@ describe('NetworkPolicyReconciler', () => {it('removes legacy static policies now replaced by generated scoped policies', async () => {await reconciler.ensureDefaultPolicies()- expect(mockApi.deleteNamespacedNetworkPolicy).toHaveBeenCalledWith({- namespace: 'rpc-proxy',- name: 'allow-desktop-egress-rpc-proxy',- })- expect(mockApi.deleteNamespacedNetworkPolicy).toHaveBeenCalledWith({- namespace: 'mcp-server',- name: 'allow-rpc-proxy-to-managed-mcp-servers',- })+ expect(mockApi.deleteNamespacedNetworkPolicy).toHaveBeenCalledWith(+ expect.objectContaining({+ namespace: 'rpc-proxy',+ name: 'allow-desktop-egress-rpc-proxy',+ })+ )+ expect(mockApi.deleteNamespacedNetworkPolicy).toHaveBeenCalledWith(+ expect.objectContaining({+ namespace: 'mcp-server',+ name: 'allow-rpc-proxy-to-managed-mcp-servers',+ })+ )})it('fails closed when legacy static policy cleanup fails', async () => {@@ -567,7 +650,7 @@ describe('NetworkPolicyReconciler', () => {expect(ingress?.spec?.ingress?.[0]?.ports).toEqual([expect.objectContaining({ port: 4000 })])})- it('does not mutate policies after its combined inventory authority lease is retired', async () => {+ it('stops remaining policy mutations after its combined authority lease is retired', async () => {const cache = new Map<string, McpServerCRD>()cache.set('mongo', {name: 'mongo',@@ -578,11 +661,12 @@ describe('NetworkPolicyReconciler', () => {transport: { type: 'streamableHttp', port: 3000 },},})- const inventoryListed = deferred()- const releaseInventory = deferred<{ items: k8s.V1NetworkPolicy[] }>()- mockApi.listNamespacedNetworkPolicy.mockImplementationOnce(async () => {- inventoryListed.resolve(undefined)- return releaseInventory.promise+ const firstCreateStarted = deferred()+ const releaseFirstCreate = deferred()+ mockApi.createNamespacedNetworkPolicy.mockImplementationOnce(async () => {+ firstCreateStarted.resolve(undefined)+ await releaseFirstCreate.promise+ return {}})const rec = makeReconciler(mockApi, cache)let contextGeneration = 4@@ -600,14 +684,14 @@ describe('NetworkPolicyReconciler', () => {contextGeneration === capturedContextGeneration &&serverGeneration === capturedServerGeneration,})- await inventoryListed.promise+ await firstCreateStarted.promisecontextGeneration = 6serverGeneration = 10- releaseInventory.resolve({ items: [] })+ releaseFirstCreate.resolve(undefined)await reconcile- expect(mockApi.createNamespacedNetworkPolicy).not.toHaveBeenCalled()+ expect(mockApi.createNamespacedNetworkPolicy).toHaveBeenCalledTimes(1)expect(mockApi.replaceNamespacedNetworkPolicy).not.toHaveBeenCalled()expect(mockApi.deleteNamespacedNetworkPolicy).not.toHaveBeenCalled()})@@ -625,11 +709,12 @@ describe('NetworkPolicyReconciler', () => {transport: { type: 'streamableHttp', port: 3000 },},})- const inventoryListed = deferred()- const releaseInventory = deferred<{ items: k8s.V1NetworkPolicy[] }>()- mockApi.listNamespacedNetworkPolicy.mockImplementationOnce(async () => {- inventoryListed.resolve(undefined)- return releaseInventory.promise+ const firstCreateStarted = deferred()+ const releaseFirstCreate = deferred()+ mockApi.createNamespacedNetworkPolicy.mockImplementationOnce(async () => {+ firstCreateStarted.resolve(undefined)+ await releaseFirstCreate.promise+ return {}})const rec = makeReconciler(mockApi, cache)const context: ContextCRD = {@@ -639,7 +724,7 @@ describe('NetworkPolicyReconciler', () => {}const reconcile = rec.reconcileContext(context)- await inventoryListed.promise+ await firstCreateStarted.promisecache.set('mongo', {name: 'mongo',namespace: 'mcp-server',@@ -651,10 +736,10 @@ describe('NetworkPolicyReconciler', () => {transport: { type: 'streamableHttp', port: 4000 },},})- releaseInventory.resolve({ items: [] })+ releaseFirstCreate.resolve(undefined)await reconcile- expect(mockApi.createNamespacedNetworkPolicy).not.toHaveBeenCalled()+ expect(mockApi.createNamespacedNetworkPolicy).toHaveBeenCalledTimes(1)expect(mockApi.replaceNamespacedNetworkPolicy).not.toHaveBeenCalled()expect(mockApi.deleteNamespacedNetworkPolicy).not.toHaveBeenCalled()})@@ -674,11 +759,12 @@ describe('NetworkPolicyReconciler', () => {status: { conditions: [{ type: 'Ready', status: 'False' }] },}cache.set(selected.name, selected)- const inventoryListed = deferred()- const releaseInventory = deferred<{ items: k8s.V1NetworkPolicy[] }>()- mockApi.listNamespacedNetworkPolicy.mockImplementationOnce(async () => {- inventoryListed.resolve(undefined)- return releaseInventory.promise+ const firstCreateStarted = deferred()+ const releaseFirstCreate = deferred()+ mockApi.createNamespacedNetworkPolicy.mockImplementationOnce(async () => {+ firstCreateStarted.resolve(undefined)+ await releaseFirstCreate.promise+ return {}})const rec = makeReconciler(mockApi, cache)const context: ContextCRD = {@@ -688,12 +774,12 @@ describe('NetworkPolicyReconciler', () => {}const reconcile = rec.reconcileContext(context)- await inventoryListed.promise+ await firstCreateStarted.promisecache.set(selected.name, {...selected,status: { conditions: [{ type: 'Ready', status: 'True' }] },})- releaseInventory.resolve({ items: [] })+ releaseFirstCreate.resolve(undefined)await reconcileexpect(mockApi.createNamespacedNetworkPolicy).toHaveBeenCalledTimes(3)@@ -1535,10 +1621,12 @@ describe('NetworkPolicyReconciler', () => {await reconciler.reconcileExternalEgress(server)expect(mockApi.deleteNamespacedNetworkPolicy).toHaveBeenCalledTimes(1)- expect(mockApi.deleteNamespacedNetworkPolicy).toHaveBeenCalledWith({- name: 'ext-egress-openai-mcp-old-example-com-443',- namespace: 'mcp-server',- })+ expect(mockApi.deleteNamespacedNetworkPolicy).toHaveBeenCalledWith(+ expect.objectContaining({+ name: 'ext-egress-openai-mcp-old-example-com-443',+ namespace: 'mcp-server',+ })+ )})it('fails closed when an orphaned external egress policy cannot be deleted', async () => {@@ -1587,14 +1675,18 @@ describe('NetworkPolicyReconciler', () => {await expect(reconciler.reconcileExternalEgress(server)).rejects.toThrow(/dns timeout/)expect(mockApi.deleteNamespacedNetworkPolicy).toHaveBeenCalledTimes(2)- expect(mockApi.deleteNamespacedNetworkPolicy).toHaveBeenCalledWith({- name: 'ext-egress-openai-mcp-api.openai.com-443',- namespace: 'mcp-server',- })- expect(mockApi.deleteNamespacedNetworkPolicy).toHaveBeenCalledWith({- name: 'ext-egress-openai-mcp-old-example-com-443',- namespace: 'mcp-server',- })+ expect(mockApi.deleteNamespacedNetworkPolicy).toHaveBeenCalledWith(+ expect.objectContaining({+ name: 'ext-egress-openai-mcp-api.openai.com-443',+ namespace: 'mcp-server',+ })+ )+ expect(mockApi.deleteNamespacedNetworkPolicy).toHaveBeenCalledWith(+ expect.objectContaining({+ name: 'ext-egress-openai-mcp-old-example-com-443',+ namespace: 'mcp-server',+ })+ )expect(mockCustomApi.patchNamespacedCustomObjectStatus).toHaveBeenCalledWith(expect.objectContaining({body: expect.arrayContaining([@@ -1632,6 +1724,29 @@ describe('NetworkPolicyReconciler', () => {expect(mockApi.deleteNamespacedNetworkPolicy).not.toHaveBeenCalled()})+ it('bounds DNS resolution so a stuck resolver cannot block reconciliation indefinitely', async () => {+ vi.useFakeTimers()+ vi.mocked(dns.resolve4).mockImplementationOnce(() => new Promise(() => undefined))+ const server: McpServerCRD = {+ name: 'stuck-dns-mcp',+ namespace: 'mcp-server',+ spec: {+ contextRef: 'dev',+ image: 'stuck-dns:test',+ transport: { type: 'streamableHttp', port: 3000 },+ egressBindings: [{ dns: 'api.openai.com', port: 443 }],+ },+ }++ const reconcile = reconciler.reconcileExternalEgress(server)+ const rejection = expect(reconcile).rejects.toThrow(/DNS resolution timed out after 5000ms/)+ await vi.advanceTimersByTimeAsync(5_000)+ await rejection++ expect(mockApi.createNamespacedNetworkPolicy).not.toHaveBeenCalled()+ expect(mockApi.replaceNamespacedNetworkPolicy).not.toHaveBeenCalled()+ })+it('skips if no egressBindings', async () => {const server: McpServerCRD = {name: 'basic-mcp',@@ -1682,96 +1797,534 @@ 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: [] },+ it('discovers and revokes orphaned policies with one missing ownership marker in every safety lane', async () => {+ const partiallyLabelledByNamespace: Record<string, k8s.V1NetworkPolicy[]> = {+ 'mcp-server': [+ {+ metadata: {+ name: 'ctx-orphan-context-old-server',+ labels: {+ 'clerum.io/managed-by': 'host-context-controller',+ 'clerum.io/context': 'orphan-context',+ 'clerum.io/mcpserver': 'old-server',+ },+ },+ spec: { podSelector: {}, policyTypes: ['Ingress'] },+ },+ {+ metadata: {+ name: 'ext-egress-orphan-server-old-example-com-443',+ labels: {+ 'clerum.io/policy-type': 'external-egress',+ 'clerum.io/mcpserver': 'orphan-server',+ 'clerum.io/egress-class': 'exact-host',+ },+ },+ spec: { podSelector: {}, policyTypes: ['Egress'] },+ },+ ],+ 'mcp-host': [+ {+ metadata: {+ name: 'ctx-orphan-context-old-server-egress',+ labels: {+ 'clerum.io/policy-type': 'context-allow',+ 'clerum.io/context': 'orphan-context',+ 'clerum.io/mcpserver': 'old-server',+ },+ },+ spec: { podSelector: {}, policyTypes: ['Egress'] },+ },+ ],+ 'rpc-proxy': [+ {+ metadata: {+ name: 'rpc-egress-orphan-context-old-server',+ labels: {+ 'clerum.io/managed-by': 'host-context-controller',+ 'clerum.io/context': 'orphan-context',+ 'clerum.io/mcpserver': 'old-server',+ },+ },+ spec: { podSelector: {}, policyTypes: ['Egress'] },+ },+ ],}- const reconcileContext = vi.spyOn(reconciler, 'reconcileContext').mockResolvedValue(undefined)- const effectKeys: string[] = []+ mockApi.listNamespacedNetworkPolicy.mockImplementation(+ async ({ namespace, labelSelector }: { namespace?: string; labelSelector?: string }) => ({+ items: labelSelector ? [] : (partiallyLabelledByNamespace[namespace ?? ''] ?? []),+ })+ )+ const onAuthoritativeRevocationComplete = vi.fn()- await reconciler.fullReconcile([queuedContext], [], {+ await reconciler.fullReconcile([], [], {ensureDefaults: false,- contextInventoryAuthoritative: () => false,- resolveCurrentContext: () => currentContext,- runContextEffect: async (contextId, work) => {- effectKeys.push(contextId)- await work()- },+ contextInventoryAuthoritative: () => true,+ serverInventoryAuthoritative: () => true,+ onAuthoritativeRevocationComplete,})- expect(effectKeys).toEqual(['captured-context', 'captured-context'])- expect(reconcileContext).not.toHaveBeenCalled()+ expect(mockApi.deleteNamespacedNetworkPolicy).toHaveBeenCalledWith(+ expect.objectContaining({+ name: 'ctx-orphan-context-old-server',+ namespace: 'mcp-server',+ })+ )+ expect(mockApi.deleteNamespacedNetworkPolicy).toHaveBeenCalledWith(+ expect.objectContaining({+ name: 'ctx-orphan-context-old-server-egress',+ namespace: 'mcp-host',+ })+ )+ expect(mockApi.deleteNamespacedNetworkPolicy).toHaveBeenCalledWith(+ expect.objectContaining({+ name: 'rpc-egress-orphan-context-old-server',+ namespace: 'rpc-proxy',+ })+ )+ expect(mockApi.deleteNamespacedNetworkPolicy).toHaveBeenCalledWith(+ expect.objectContaining({+ name: 'ext-egress-orphan-server-old-example-com-443',+ namespace: 'mcp-server',+ })+ )+ expect(mockApi.deleteNamespacedNetworkPolicy).toHaveBeenCalledTimes(4)+ expect(onAuthoritativeRevocationComplete).toHaveBeenCalledOnce()})- it('retires a full-pass Context lease when the selected object is replaced', async () => {- const selected: ContextCRD = {- name: 'full-pass-context',+ it('repairs one-marker live widened policies in every lane before certification', async () => {+ const server: McpServerCRD = {+ name: 'live-server',namespace: 'mcp-server',- spec: { contextId: 'full-pass-context', description: 'old', mcpServers: [] },+ spec: {+ contextRef: 'live-context',+ image: 'live:test',+ transport: { type: 'streamableHttp', port: 3000 },+ egressBindings: [{ cidr: '8.8.8.8/32', port: 443 }],+ },}- const replacement: ContextCRD = {- ...selected,- spec: { ...selected.spec, description: 'new' },+ const context: ContextCRD = {+ name: 'live-context-resource',+ namespace: 'mcp-server',+ spec: { contextId: 'live-context', mcpServers: [server.name] },}- let current = selected- let selectedLease: (() => boolean) | undefined- const mutationStarted = deferred()- const releaseMutation = deferred()- vi.spyOn(reconciler, 'reconcileContext').mockImplementationOnce(async (_context, options) => {- selectedLease = options?.isCurrent- mutationStarted.resolve(undefined)- await releaseMutation.promise+ const cache = new Map([[server.name, server]])+ const rec = makeReconciler(mockApi, cache, mockCustomApi)++ await rec.reconcileContext(context)+ await rec.reconcileExternalEgress(server)+ const generated = mockApi.createNamespacedNetworkPolicy.mock.calls.map(+ call => (call[0] as { body: k8s.V1NetworkPolicy }).body+ )+ const widened = generated.map((policy, index) => ({+ ...policy,+ metadata: {+ ...policy.metadata,+ labels: Object.fromEntries(+ Object.entries(policy.metadata?.labels ?? {}).filter(+ ([label]) =>+ label !== (index % 2 === 0 ? 'clerum.io/managed-by' : 'clerum.io/policy-type')+ )+ ),+ },+ spec: {+ ...policy.spec,+ policyTypes: [...(policy.spec?.policyTypes ?? []), 'Ingress'],+ },+ }))++ vi.clearAllMocks()+ mockApi.listNamespacedNetworkPolicy.mockImplementation(+ async ({ namespace, labelSelector }: { namespace?: string; labelSelector?: string }) => ({+ items: labelSelector+ ? []+ : widened.filter(policy => policy.metadata?.namespace === namespace),+ })+ )+ mockApi.createNamespacedNetworkPolicy.mockRejectedValue(+ Object.assign(new Error('already exists'), { code: 409 })+ )+ const ordering: string[] = []+ mockApi.replaceNamespacedNetworkPolicy.mockImplementation(async ({ name }) => {+ ordering.push(`replace:${name}`)+ return {}})+ const onAuthoritativeRevocationComplete = vi.fn(() => ordering.push('certify'))- const fullPass = reconciler.fullReconcile([selected], [], {+ await rec.fullReconcile([context], [server], {ensureDefaults: false,contextInventoryAuthoritative: () => true,serverInventoryAuthoritative: () => true,- resolveCurrentContext: () => current,+ resolveCurrentContext: () => context,+ resolveCurrentServer: () => server,+ onAuthoritativeRevocationComplete,})- await mutationStarted.promise- expect(selectedLease?.()).toBe(true)- current = replacement- expect(selectedLease?.()).toBe(false)- releaseMutation.resolve(undefined)- await fullPass+ const certificationIndex = ordering.indexOf('certify')+ expect(certificationIndex).toBeGreaterThanOrEqual(4)+ for (const expectedName of [+ 'ctx-live-context-live-server',+ 'ctx-live-context-live-server-egress',+ 'rpc-egress-live-context-live-server',+ 'ext-egress-live-server-8-8-8-8-32-443',+ ]) {+ expect(ordering.indexOf(`replace:${expectedName}`)).toBeGreaterThanOrEqual(0)+ expect(ordering.indexOf(`replace:${expectedName}`)).toBeLessThan(certificationIndex)+ }+ expect(onAuthoritativeRevocationComplete).toHaveBeenCalledOnce()})- it('retires a full-pass external-egress lease when desired state is replaced', async () => {- const selected: McpServerCRD = {- name: 'full-pass-egress',- namespace: 'mcp-server',- uid: 'full-pass-egress-uid',- generation: 1,- spec: {- contextRef: 'dev',- image: 'full-pass-egress:old',- transport: { type: 'streamableHttp', port: 3000 },- egressBindings: [{ dns: 'old.example', port: 443 }],+ it.each([+ [+ 'context ingress',+ 'mcp-server',+ {+ metadata: { name: 'ctx-reserved-context-server', labels: {} },+ spec: { podSelector: {}, policyTypes: ['Ingress'] },},+ ],+ [+ 'host egress',+ 'mcp-host',+ {+ metadata: { name: 'ctx-reserved-context-server-egress', labels: {} },+ spec: { podSelector: {}, policyTypes: ['Egress'] },+ },+ ],+ [+ 'rpc egress',+ 'rpc-proxy',+ {+ metadata: { name: 'rpc-egress-reserved-context-server', labels: {} },+ spec: { podSelector: {}, policyTypes: ['Egress'] },+ },+ ],+ [+ 'external egress',+ 'mcp-server',+ {+ metadata: { name: 'ext-egress-reserved-server-example-443', labels: {} },+ spec: { podSelector: {}, policyTypes: ['Egress'] },+ },+ ],+ ])(+ 'fails closed without takeover for a both-markers-missing reserved %s name',+ async (_lane, namespace, candidate) => {+ mockApi.listNamespacedNetworkPolicy.mockImplementation(+ async ({+ namespace: listedNamespace,+ labelSelector,+ }: {+ namespace?: string+ labelSelector?: string+ }) => ({+ items: !labelSelector && listedNamespace === namespace ? [candidate] : [],+ })+ )+ const onAuthoritativeRevocationComplete = vi.fn()++ await expect(+ reconciler.fullReconcile([], [], {+ ensureDefaults: false,+ contextInventoryAuthoritative: () => true,+ serverInventoryAuthoritative: () => true,+ onAuthoritativeRevocationComplete,+ })+ ).rejects.toThrow(/Ambiguous NetworkPolicy ownership/)++ expect(onAuthoritativeRevocationComplete).not.toHaveBeenCalled()+ expect(mockApi.deleteNamespacedNetworkPolicy).not.toHaveBeenCalled()+ expect(mockApi.replaceNamespacedNetworkPolicy).not.toHaveBeenCalled()}- const replacement: McpServerCRD = {- ...selected,- generation: 2,- spec: {- ...selected.spec,- image: 'full-pass-egress:new',- egressBindings: [{ dns: 'new.example', port: 443 }],+ )++ it('fails closed for an explicit foreign ownership conflict on an HCC-shaped policy', async () => {+ const candidate: k8s.V1NetworkPolicy = {+ metadata: {+ name: 'ext-egress-live-server-api-example-com-443',+ labels: {+ 'clerum.io/managed-by': 'foreign-controller',+ 'clerum.io/policy-type': 'external-egress',+ 'clerum.io/mcpserver': 'live-server',+ },},+ spec: { podSelector: {}, policyTypes: ['Egress'] },}- let current = selected- let selectedLease: (() => boolean) | undefined- const mutationStarted = deferred()- const releaseMutation = deferred()- vi.spyOn(reconciler, 'reconcileExternalEgress').mockImplementationOnce(- async (_server, options) => {+ mockApi.listNamespacedNetworkPolicy.mockImplementation(+ async ({ namespace, labelSelector }: { namespace?: string; labelSelector?: string }) => ({+ items: !labelSelector && namespace === 'mcp-server' ? [candidate] : [],+ })+ )+ const onAuthoritativeRevocationComplete = vi.fn()++ await expect(+ reconciler.fullReconcile([], [], {+ ensureDefaults: false,+ contextInventoryAuthoritative: () => true,+ serverInventoryAuthoritative: () => true,+ onAuthoritativeRevocationComplete,+ })+ ).rejects.toThrow(/Ambiguous NetworkPolicy ownership/)++ expect(onAuthoritativeRevocationComplete).not.toHaveBeenCalled()+ expect(mockApi.deleteNamespacedNetworkPolicy).not.toHaveBeenCalled()+ })++ it('treats a non-reserved external policy missing its manager marker as ambiguous', async () => {+ const candidate: k8s.V1NetworkPolicy = {+ metadata: {+ name: 'custom-egress-policy',+ labels: {+ 'clerum.io/policy-type': 'external-egress',+ 'clerum.io/mcpserver': 'live-server',+ },+ },+ spec: { podSelector: {}, policyTypes: ['Egress'] },+ }+ mockApi.listNamespacedNetworkPolicy.mockImplementation(+ async ({ namespace, labelSelector }: { namespace?: string; labelSelector?: string }) => ({+ items: !labelSelector && namespace === 'mcp-server' ? [candidate] : [],+ })+ )+ const onAuthoritativeRevocationComplete = vi.fn()++ await expect(+ reconciler.fullReconcile([], [], {+ ensureDefaults: false,+ contextInventoryAuthoritative: () => true,+ serverInventoryAuthoritative: () => true,+ onAuthoritativeRevocationComplete,+ })+ ).rejects.toThrow(/Ambiguous NetworkPolicy ownership/)++ expect(mockApi.deleteNamespacedNetworkPolicy).not.toHaveBeenCalled()+ expect(mockApi.replaceNamespacedNetworkPolicy).not.toHaveBeenCalled()+ expect(onAuthoritativeRevocationComplete).not.toHaveBeenCalled()+ })++ it('lets the broad snapshot shadow a selected-owned object that became unrelated at the same UID', async () => {+ const selected: k8s.V1NetworkPolicy = {+ metadata: {+ name: 'legacy-custom-policy',+ uid: 'stable-policy-uid',+ resourceVersion: '7',+ labels: {+ 'clerum.io/managed-by': 'host-context-controller',+ 'clerum.io/policy-type': 'context-allow',+ 'clerum.io/context': 'orphan-context',+ 'clerum.io/mcpserver': 'old-server',+ },+ },+ spec: { podSelector: {}, policyTypes: ['Ingress'] },+ }+ const broadRelabelled: k8s.V1NetworkPolicy = {+ ...selected,+ metadata: {+ ...selected.metadata,+ resourceVersion: '8',+ labels: { 'tenant.example/managed-by': 'tenant-controller' },+ },+ }+ mockApi.listNamespacedNetworkPolicy.mockImplementation(+ async ({ namespace, labelSelector }: { namespace?: string; labelSelector?: string }) => {+ if (namespace !== 'mcp-server') return { items: [] }+ if (labelSelector?.includes('policy-type=context-allow')) return { items: [selected] }+ if (!labelSelector) return { items: [broadRelabelled] }+ return { items: [] }+ }+ )+ const onAuthoritativeRevocationComplete = vi.fn()++ await reconciler.fullReconcile([], [], {+ ensureDefaults: false,+ contextInventoryAuthoritative: () => true,+ serverInventoryAuthoritative: () => true,+ onAuthoritativeRevocationComplete,+ })++ expect(mockApi.deleteNamespacedNetworkPolicy).not.toHaveBeenCalled()+ expect(mockApi.replaceNamespacedNetworkPolicy).not.toHaveBeenCalled()+ expect(onAuthoritativeRevocationComplete).toHaveBeenCalledOnce()+ })++ it('leaves unrelated namespace policies untouched and still certifies', async () => {+ const unrelated: k8s.V1NetworkPolicy = {+ metadata: {+ name: 'tenant-owned-policy',+ labels: {+ 'app.kubernetes.io/managed-by': 'tenant-operator',+ 'tenant.example/purpose': 'custom-egress',+ },+ },+ spec: { podSelector: {}, policyTypes: ['Egress'] },+ }+ mockApi.listNamespacedNetworkPolicy.mockImplementation(+ async ({ namespace, labelSelector }: { namespace?: string; labelSelector?: string }) => ({+ items: !labelSelector && namespace === 'mcp-server' ? [unrelated] : [],+ })+ )+ const onAuthoritativeRevocationComplete = vi.fn()++ await reconciler.fullReconcile([], [], {+ ensureDefaults: false,+ contextInventoryAuthoritative: () => true,+ serverInventoryAuthoritative: () => true,+ onAuthoritativeRevocationComplete,+ })++ expect(onAuthoritativeRevocationComplete).toHaveBeenCalledOnce()+ expect(mockApi.deleteNamespacedNetworkPolicy).not.toHaveBeenCalled()+ expect(mockApi.replaceNamespacedNetworkPolicy).not.toHaveBeenCalled()+ })++ it('fails closed when the broad safety inventory LIST fails', async () => {+ mockApi.listNamespacedNetworkPolicy+ .mockResolvedValueOnce({ items: [] })+ .mockResolvedValueOnce({ items: [] })+ .mockResolvedValueOnce({ items: [] })+ .mockResolvedValueOnce({ items: [] })+ .mockRejectedValueOnce(new Error('broad inventory denied'))+ const onAuthoritativeRevocationComplete = vi.fn()++ await expect(+ reconciler.fullReconcile([], [], {+ ensureDefaults: false,+ contextInventoryAuthoritative: () => true,+ serverInventoryAuthoritative: () => true,+ onAuthoritativeRevocationComplete,+ })+ ).rejects.toThrow('broad inventory denied')++ expect(onAuthoritativeRevocationComplete).not.toHaveBeenCalled()+ expect(mockApi.deleteNamespacedNetworkPolicy).not.toHaveBeenCalled()+ })++ it('withholds certification and mutation when Context authority is lost during the broad LIST', async () => {+ let contextAuthoritative = true+ const candidate: k8s.V1NetworkPolicy = {+ metadata: {+ name: 'ctx-orphan-context-old-server',+ labels: {+ 'clerum.io/policy-type': 'context-allow',+ 'clerum.io/context': 'orphan-context',+ 'clerum.io/mcpserver': 'old-server',+ },+ },+ spec: { podSelector: {}, policyTypes: ['Ingress'] },+ }+ mockApi.listNamespacedNetworkPolicy.mockImplementation(+ async ({ namespace, labelSelector }: { namespace?: string; labelSelector?: string }) => {+ if (!labelSelector && namespace === 'mcp-server') {+ contextAuthoritative = false+ return { items: [candidate] }+ }+ return { items: [] }+ }+ )+ const onAuthoritativeRevocationComplete = vi.fn()++ await reconciler.fullReconcile([], [], {+ ensureDefaults: false,+ contextInventoryAuthoritative: () => contextAuthoritative,+ serverInventoryAuthoritative: () => true,+ onAuthoritativeRevocationComplete,+ })++ expect(onAuthoritativeRevocationComplete).not.toHaveBeenCalled()+ expect(mockApi.deleteNamespacedNetworkPolicy).not.toHaveBeenCalled()+ expect(mockApi.replaceNamespacedNetworkPolicy).not.toHaveBeenCalled()+ })++ 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', 'captured-context'])+ expect(reconcileContext).not.toHaveBeenCalled()+ })++ it('retires a full-pass Context lease when the selected object is replaced', async () => {+ const selected: ContextCRD = {+ name: 'full-pass-context',+ namespace: 'mcp-server',+ spec: { contextId: 'full-pass-context', description: 'old', mcpServers: [] },+ }+ const replacement: ContextCRD = {+ ...selected,+ spec: { ...selected.spec, description: 'new' },+ }+ let current = selected+ let selectedLease: (() => boolean) | undefined+ const mutationStarted = deferred()+ const releaseMutation = deferred()+ vi.spyOn(reconciler, 'reconcileContext').mockImplementationOnce(async (_context, options) => {+ selectedLease = options?.isCurrent+ mutationStarted.resolve(undefined)+ await releaseMutation.promise+ })++ const fullPass = reconciler.fullReconcile([selected], [], {+ ensureDefaults: false,+ contextInventoryAuthoritative: () => true,+ serverInventoryAuthoritative: () => true,+ resolveCurrentContext: () => current,+ })+ await mutationStarted.promise+ expect(selectedLease?.()).toBe(true)++ current = replacement+ expect(selectedLease?.()).toBe(false)+ releaseMutation.resolve(undefined)+ await fullPass+ })++ it('retires a full-pass external-egress lease when desired state is replaced', async () => {+ const selected: McpServerCRD = {+ name: 'full-pass-egress',+ namespace: 'mcp-server',+ uid: 'full-pass-egress-uid',+ generation: 1,+ spec: {+ contextRef: 'dev',+ image: 'full-pass-egress:old',+ transport: { type: 'streamableHttp', port: 3000 },+ egressBindings: [{ dns: 'old.example', port: 443 }],+ },+ }+ const replacement: McpServerCRD = {+ ...selected,+ generation: 2,+ spec: {+ ...selected.spec,+ image: 'full-pass-egress:new',+ egressBindings: [{ dns: 'new.example', port: 443 }],+ },+ }+ let current = selected+ let selectedLease: (() => boolean) | undefined+ const mutationStarted = deferred()+ const releaseMutation = deferred()+ vi.spyOn(reconciler, 'reconcileExternalEgress').mockImplementationOnce(+ async (_server, options) => {selectedLease = options?.isCurrentmutationStarted.resolve(undefined)await releaseMutation.promise@@ -1846,18 +2399,24 @@ describe('NetworkPolicyReconciler', () => {})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',- })+ expect(mockApi.deleteNamespacedNetworkPolicy).toHaveBeenCalledWith(+ expect.objectContaining({+ name: 'ctx-orphan-context-old-server',+ namespace: 'mcp-server',+ })+ )+ expect(mockApi.deleteNamespacedNetworkPolicy).toHaveBeenCalledWith(+ expect.objectContaining({+ name: 'ctx-orphan-context-old-server-egress',+ namespace: 'mcp-host',+ })+ )+ expect(mockApi.deleteNamespacedNetworkPolicy).toHaveBeenCalledWith(+ expect.objectContaining({+ name: 'rpc-egress-orphan-context-old-server',+ namespace: 'rpc-proxy',+ })+ )})it('routes desired and orphan Context policy lanes through canonical contextId effect keys', async () => {@@ -1988,22 +2547,30 @@ describe('NetworkPolicyReconciler', () => {await additiveStarted.promisetry {- 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',- })- expect(mockApi.deleteNamespacedNetworkPolicy).toHaveBeenCalledWith({- name: 'ext-egress-orphan-server-old.example',- namespace: 'mcp-server',- })+ expect(mockApi.deleteNamespacedNetworkPolicy).toHaveBeenCalledWith(+ expect.objectContaining({+ name: 'ctx-orphan-context-old-server',+ namespace: 'mcp-server',+ })+ )+ expect(mockApi.deleteNamespacedNetworkPolicy).toHaveBeenCalledWith(+ expect.objectContaining({+ name: 'ctx-orphan-context-old-server-egress',+ namespace: 'mcp-host',+ })+ )+ expect(mockApi.deleteNamespacedNetworkPolicy).toHaveBeenCalledWith(+ expect.objectContaining({+ name: 'rpc-egress-orphan-context-old-server',+ namespace: 'rpc-proxy',+ })+ )+ expect(mockApi.deleteNamespacedNetworkPolicy).toHaveBeenCalledWith(+ expect.objectContaining({+ name: 'ext-egress-orphan-server-old.example',+ namespace: 'mcp-server',+ })+ )} finally {releaseAdditive.resolve(undefined)await fullPass@@ -2074,18 +2641,24 @@ describe('NetworkPolicyReconciler', () => {await additiveStarted.promisetry {- expect(mockApi.deleteNamespacedNetworkPolicy).toHaveBeenCalledWith({- name: 'ctx-live-context-removed-server',- namespace: 'mcp-server',- })- expect(mockApi.deleteNamespacedNetworkPolicy).toHaveBeenCalledWith({- name: 'ctx-live-context-removed-server-egress',- namespace: 'mcp-host',- })- expect(mockApi.deleteNamespacedNetworkPolicy).toHaveBeenCalledWith({- name: 'rpc-egress-live-context-removed-server',- namespace: 'rpc-proxy',- })+ expect(mockApi.deleteNamespacedNetworkPolicy).toHaveBeenCalledWith(+ expect.objectContaining({+ name: 'ctx-live-context-removed-server',+ namespace: 'mcp-server',+ })+ )+ expect(mockApi.deleteNamespacedNetworkPolicy).toHaveBeenCalledWith(+ expect.objectContaining({+ name: 'ctx-live-context-removed-server-egress',+ namespace: 'mcp-host',+ })+ )+ expect(mockApi.deleteNamespacedNetworkPolicy).toHaveBeenCalledWith(+ expect.objectContaining({+ name: 'rpc-egress-live-context-removed-server',+ namespace: 'rpc-proxy',+ })+ )expect(onAuthoritativeRevocationComplete).toHaveBeenCalledOnce()} finally {releaseAdditive.resolve(undefined)@@ -2137,15 +2710,115 @@ describe('NetworkPolicyReconciler', () => {onAuthoritativeRevocationComplete,})- expect(mockApi.deleteNamespacedNetworkPolicy).toHaveBeenCalledWith({- name: 'ext-egress-live-server-old.example-443',+ expect(mockApi.deleteNamespacedNetworkPolicy).toHaveBeenCalledWith(+ expect.objectContaining({+ name: 'ext-egress-live-server-old.example-443',+ namespace: 'mcp-server',+ })+ )+ expect(ordering.slice(0, 2)).toEqual(['delete', 'certify'])+ expect(onAuthoritativeRevocationComplete).toHaveBeenCalledOnce()+ })++ it('does not let one post-certification Context failure starve later additive owners', async () => {+ const contexts: ContextCRD[] = ['aaa-poisoned', 'bbb-healthy'].map(contextId => ({+ name: `${contextId}-resource`,+ namespace: 'mcp-server',+ spec: { contextId, mcpServers: [] },+ }))+ const server: McpServerCRD = {+ name: 'later-egress-server',namespace: 'mcp-server',+ spec: {+ contextRef: 'bbb-healthy',+ image: 'later:latest',+ transport: { type: 'streamableHttp', port: 3000 },+ egressBindings: [{ cidr: '203.0.113.10/32', port: 443, protocol: 'TCP' }],+ },+ }+ const ordering: string[] = []+ const additiveFailure = new Error('poisoned additive Context')+ vi.spyOn(reconciler, 'reconcileContext').mockImplementation(async context => {+ ordering.push(`context:${context.spec.contextId}`)+ if (context.spec.contextId === 'aaa-poisoned') throw additiveFailure})- expect(ordering.slice(0, 2)).toEqual(['delete', 'certify'])+ vi.spyOn(reconciler, 'reconcileExternalEgress').mockImplementation(async current => {+ ordering.push(`server:${current.name}`)+ })+ const onAuthoritativeRevocationComplete = vi.fn(() => {+ ordering.push('certify')+ })+ const errorLog = vi.spyOn(console, 'error').mockImplementation(() => undefined)++ const error = await reconciler+ .fullReconcile(contexts, [server], {+ ensureDefaults: false,+ contextInventoryAuthoritative: () => true,+ serverInventoryAuthoritative: () => true,+ onAuthoritativeRevocationComplete,+ })+ .then(+ () => undefined,+ failure => failure+ )++ expect(error).toBeInstanceOf(AggregateError)+ expect((error as AggregateError).errors).toEqual([additiveFailure])+ expect(ordering).toEqual([+ 'certify',+ 'context:aaa-poisoned',+ 'context:bbb-healthy',+ 'server:later-egress-server',+ ])+ expect(errorLog).toHaveBeenCalledWith(+ '[NetPol] Additive Context reconciliation failed for "aaa-poisoned":',+ additiveFailure+ )+ })++ it('does not let one post-certification McpServer failure starve later server refreshes', async () => {+ const servers: McpServerCRD[] = ['aaa-poisoned', 'bbb-healthy'].map(name => ({+ name,+ namespace: 'mcp-server',+ spec: {+ contextRef: 'default',+ image: `${name}:latest`,+ transport: { type: 'streamableHttp', port: 3000 },+ egressBindings: [{ cidr: '203.0.113.10/32', port: 443, protocol: 'TCP' }],+ },+ }))+ const ordering: string[] = []+ const additiveFailure = new Error('poisoned additive McpServer')+ vi.spyOn(reconciler, 'reconcileExternalEgress').mockImplementation(async server => {+ ordering.push(server.name)+ if (server.name === 'aaa-poisoned') throw additiveFailure+ })+ const onAuthoritativeRevocationComplete = vi.fn()+ const errorLog = vi.spyOn(console, 'error').mockImplementation(() => undefined)++ const error = await reconciler+ .fullReconcile([], servers, {+ ensureDefaults: false,+ contextInventoryAuthoritative: () => true,+ serverInventoryAuthoritative: () => true,+ onAuthoritativeRevocationComplete,+ })+ .then(+ () => undefined,+ failure => failure+ )++ expect(error).toBeInstanceOf(AggregateError)+ expect((error as AggregateError).errors).toEqual([additiveFailure])+ expect(ordering).toEqual(['aaa-poisoned', 'bbb-healthy'])expect(onAuthoritativeRevocationComplete).toHaveBeenCalledOnce()+ expect(errorLog).toHaveBeenCalledWith(+ '[NetPol] Additive external-egress reconciliation failed for "aaa-poisoned":',+ additiveFailure+ )})- it('revokes same-name Context allow policies whose authoritative server port changed', async () => {+ it('replaces same-name Context allow policies in every lane before certification', async () => {const oldServer: McpServerCRD = {name: 'live-server',namespace: 'mcp-server',@@ -2178,6 +2851,9 @@ describe('NetworkPolicyReconciler', () => {vi.clearAllMocks()serverCache.set(currentServer.name, currentServer)+ mockApi.createNamespacedNetworkPolicy.mockRejectedValue(+ Object.assign(new Error('already exists'), { code: 409 })+ )mockApi.listNamespacedNetworkPolicy.mockImplementation(async ({ namespace, labelSelector }: { namespace?: string; labelSelector?: string }) => {if (labelSelector?.includes('external-egress')) return { items: [] }@@ -2188,7 +2864,14 @@ describe('NetworkPolicyReconciler', () => {)vi.spyOn(rec, 'reconcileContext').mockResolvedValue(undefined)vi.spyOn(rec, 'reconcileExternalEgress').mockResolvedValue(undefined)- const onAuthoritativeRevocationComplete = vi.fn()+ const ordering: string[] = []+ mockApi.replaceNamespacedNetworkPolicy.mockImplementation(+ async ({ namespace }: { namespace?: string }) => {+ ordering.push(`replace:${namespace}`)+ return {}+ }+ )+ const onAuthoritativeRevocationComplete = vi.fn(() => ordering.push('certify'))await rec.fullReconcile([liveContext], [currentServer], {ensureDefaults: false,@@ -2197,117 +2880,375 @@ describe('NetworkPolicyReconciler', () => {onAuthoritativeRevocationComplete,})- expect(mockApi.deleteNamespacedNetworkPolicy).toHaveBeenCalledWith({- name: 'ctx-live-context-live-server',+ expect(ordering).toEqual([+ 'replace:mcp-server',+ 'replace:mcp-host',+ 'replace:rpc-proxy',+ 'certify',+ ])+ expect(mockApi.deleteNamespacedNetworkPolicy).not.toHaveBeenCalled()+ expect(onAuthoritativeRevocationComplete).toHaveBeenCalledOnce()+ })++ it('fails the safety pass without certifying when a same-name Context replacement fails', async () => {+ const oldServer: McpServerCRD = {+ name: 'live-server',+ namespace: 'mcp-server',+ spec: {+ contextRef: 'default',+ image: 'live:latest',+ transport: { type: 'streamableHttp', port: 3000 },+ },+ }+ const currentServer: McpServerCRD = {+ ...oldServer,+ spec: {+ ...oldServer.spec,+ transport: { type: 'streamableHttp', port: 4000 },+ },+ }+ const liveContext: ContextCRD = {+ name: 'live-context-resource',+ namespace: 'mcp-server',+ spec: { contextId: 'live-context', mcpServers: [oldServer.name] },+ }+ const serverCache = new Map([[oldServer.name, oldServer]])+ const rec = makeReconciler(mockApi, serverCache, mockCustomApi)++ await rec.reconcileContext(liveContext)+ const oldPolicies = mockApi.createNamespacedNetworkPolicy.mock.calls.map(+ call => (call[0] as { body: k8s.V1NetworkPolicy }).body+ )++ vi.clearAllMocks()+ serverCache.set(currentServer.name, currentServer)+ mockApi.createNamespacedNetworkPolicy.mockRejectedValue(+ Object.assign(new Error('already exists'), { code: 409 })+ )+ mockApi.listNamespacedNetworkPolicy.mockImplementation(+ async ({ namespace, labelSelector }: { namespace?: string; labelSelector?: string }) => {+ if (labelSelector?.includes('external-egress')) return { items: [] }+ return {+ items: oldPolicies.filter(policy => policy.metadata?.namespace === namespace),+ }+ }+ )+ const replacementFailure = new Error('replace unavailable')+ mockApi.replaceNamespacedNetworkPolicy.mockRejectedValueOnce(replacementFailure)+ const onAuthoritativeRevocationComplete = vi.fn()++ await expect(+ rec.fullReconcile([liveContext], [currentServer], {+ ensureDefaults: false,+ contextInventoryAuthoritative: () => true,+ serverInventoryAuthoritative: () => true,+ onAuthoritativeRevocationComplete,+ })+ ).rejects.toBe(replacementFailure)++ expect(mockApi.deleteNamespacedNetworkPolicy).not.toHaveBeenCalled()+ expect(onAuthoritativeRevocationComplete).not.toHaveBeenCalled()+ expect(networkPolicySafetyPassDurationSeconds.observe).toHaveBeenCalledWith(+ { outcome: 'failed' },+ expect.any(Number)+ )+ expect(networkPolicySafetyPassDurationSeconds.observe).toHaveBeenCalledTimes(1)+ })++ it('retains authoritative same-name policies when only API object key order differs', async () => {+ const server: McpServerCRD = {+ name: 'live-server',namespace: 'mcp-server',+ spec: {+ contextRef: 'default',+ image: 'live:latest',+ transport: { type: 'streamableHttp', port: 3000 },+ },+ }+ const liveContext: ContextCRD = {+ name: 'live-context-resource',+ namespace: 'mcp-server',+ spec: { contextId: 'live-context', mcpServers: [server.name] },+ }+ const rec = makeReconciler(mockApi, new Map([[server.name, server]]), mockCustomApi)+ const reverseObjectKeys = (value: unknown): unknown => {+ if (Array.isArray(value)) return value.map(reverseObjectKeys)+ if (value === null || typeof value !== 'object') return value+ return Object.fromEntries(+ Object.entries(value as Record<string, unknown>)+ .reverse()+ .map(([key, entry]) => [key, reverseObjectKeys(entry)])+ )+ }++ await rec.reconcileContext(liveContext)+ const existingPolicies = mockApi.createNamespacedNetworkPolicy.mock.calls.map(call => {+ const policy = (call[0] as { body: k8s.V1NetworkPolicy }).body+ return { ...policy, spec: reverseObjectKeys(policy.spec) as k8s.V1NetworkPolicySpec }})- expect(mockApi.deleteNamespacedNetworkPolicy).toHaveBeenCalledWith({- name: 'ctx-live-context-live-server-egress',- namespace: 'mcp-host',+ vi.clearAllMocks()+ mockApi.listNamespacedNetworkPolicy.mockImplementation(+ async ({ namespace, labelSelector }: { namespace?: string; labelSelector?: string }) => {+ if (labelSelector?.includes('external-egress')) return { items: [] }+ return {+ items: existingPolicies.filter(policy => policy.metadata?.namespace === namespace),+ }+ }+ )+ vi.spyOn(rec, 'reconcileContext').mockResolvedValue(undefined)+ vi.spyOn(rec, 'reconcileExternalEgress').mockResolvedValue(undefined)++ await rec.fullReconcile([liveContext], [server], {+ ensureDefaults: false,+ contextInventoryAuthoritative: () => true,+ serverInventoryAuthoritative: () => true,+ })++ expect(mockApi.deleteNamespacedNetworkPolicy).not.toHaveBeenCalled()+ })++ it('revokes same-name DNS egress before certifying and refreshes it additively', async () => {+ const oldServer: McpServerCRD = {+ name: 'live-server',+ namespace: 'mcp-server',+ spec: {+ contextRef: 'default',+ image: 'live:latest',+ transport: { type: 'streamableHttp', port: 3000 },+ egressBindings: [{ dns: 'api.example.com', port: 443, protocol: 'TCP' }],+ },+ }+ const currentServer: McpServerCRD = {+ ...oldServer,+ spec: {+ ...oldServer.spec,+ egressBindings: [{ dns: 'api.example.com', port: 443, protocol: 'UDP' }],+ },+ }+ const rec = makeReconciler(mockApi, new Map([[oldServer.name, oldServer]]), mockCustomApi)++ await rec.reconcileExternalEgress(oldServer)+ const oldPolicy = mockApi.createNamespacedNetworkPolicy.mock.calls+ .map(call => (call[0] as { body: k8s.V1NetworkPolicy }).body)+ .find(policy => policy.metadata?.labels?.['clerum.io/policy-type'] === 'external-egress')+ expect(oldPolicy).toBeDefined()++ vi.clearAllMocks()+ const ordering: string[] = []+ mockApi.listNamespacedNetworkPolicy.mockImplementation(+ async ({ labelSelector }: { labelSelector?: string }) =>+ labelSelector?.includes('external-egress') ? { items: [oldPolicy!] } : { items: [] }+ )+ mockApi.createNamespacedNetworkPolicy.mockRejectedValue(+ Object.assign(new Error('already exists'), { code: 409 })+ )+ mockApi.replaceNamespacedNetworkPolicy.mockImplementation(async () => {+ ordering.push('replace')+ return {}+ })+ mockApi.deleteNamespacedNetworkPolicy.mockImplementation(async () => {+ ordering.push('delete')+ return {}+ })+ const onAuthoritativeRevocationComplete = vi.fn(() => {+ ordering.push('certify')+ })++ await rec.fullReconcile([], [currentServer], {+ ensureDefaults: false,+ contextInventoryAuthoritative: () => true,+ serverInventoryAuthoritative: () => true,+ onAuthoritativeRevocationComplete,+ })++ expect(ordering.slice(0, 2)).toEqual(['delete', 'certify'])+ expect(ordering).toContain('replace')+ expect(ordering.indexOf('replace')).toBeGreaterThan(ordering.indexOf('certify'))+ expect(onAuthoritativeRevocationComplete).toHaveBeenCalledOnce()+ })++ it('revokes a divergent same-name DNS policy when its safe replacement cannot resolve', async () => {+ const oldServer: McpServerCRD = {+ name: 'live-server',+ namespace: 'mcp-server',+ spec: {+ contextRef: 'default',+ image: 'live:latest',+ transport: { type: 'streamableHttp', port: 3000 },+ egressBindings: [{ dns: 'api.example.com', port: 443, protocol: 'TCP' }],+ },+ }+ const currentServer: McpServerCRD = {+ ...oldServer,+ spec: {+ ...oldServer.spec,+ egressBindings: [{ dns: 'api.example.com', port: 443, protocol: 'UDP' }],+ },+ }+ const rec = makeReconciler(mockApi, new Map([[oldServer.name, oldServer]]), mockCustomApi)++ await rec.reconcileExternalEgress(oldServer)+ const oldPolicy = mockApi.createNamespacedNetworkPolicy.mock.calls+ .map(call => (call[0] as { body: k8s.V1NetworkPolicy }).body)+ .find(policy => policy.metadata?.labels?.['clerum.io/policy-type'] === 'external-egress')+ expect(oldPolicy).toBeDefined()++ vi.clearAllMocks()+ const ordering: string[] = []+ vi.mocked(dns.resolve4).mockImplementation(async () => {+ ordering.push('dns')+ throw new Error('dns unavailable')+ })+ let currentPolicies = [oldPolicy!]+ mockApi.listNamespacedNetworkPolicy.mockImplementation(+ async ({ labelSelector }: { labelSelector?: string }) =>+ labelSelector?.includes('external-egress') ? { items: currentPolicies } : { items: [] }+ )+ mockApi.deleteNamespacedNetworkPolicy.mockImplementation(async () => {+ ordering.push('delete')+ currentPolicies = []+ return {}})- expect(mockApi.deleteNamespacedNetworkPolicy).toHaveBeenCalledWith({- name: 'rpc-egress-live-context-live-server',- namespace: 'rpc-proxy',+ const onAuthoritativeRevocationComplete = vi.fn(() => {+ ordering.push('certify')})++ await expect(+ rec.fullReconcile([], [currentServer], {+ ensureDefaults: false,+ contextInventoryAuthoritative: () => true,+ serverInventoryAuthoritative: () => true,+ onAuthoritativeRevocationComplete,+ })+ ).rejects.toThrow('One or more additive NetworkPolicy reconciliations failed')++ expect(mockApi.deleteNamespacedNetworkPolicy).toHaveBeenCalledWith(+ expect.objectContaining({+ name: oldPolicy!.metadata!.name!,+ namespace: oldServer.namespace,+ })+ )expect(onAuthoritativeRevocationComplete).toHaveBeenCalledOnce()+ expect(ordering.slice(0, 3)).toEqual(['delete', 'certify', 'dns'])})- it('retains authoritative same-name policies when only API object key order differs', async () => {- const server: McpServerCRD = {- name: 'live-server',+ it('revokes a renamed DNS binding before certification and performs no DNS lookup on the safety path', async () => {+ const oldServer: McpServerCRD = {+ name: 'renamed-dns-server',namespace: 'mcp-server',spec: {contextRef: 'default',- image: 'live:latest',+ image: 'dns:test',transport: { type: 'streamableHttp', port: 3000 },+ egressBindings: [{ dns: 'old.example.com', port: 443 }],},}- const liveContext: ContextCRD = {- name: 'live-context-resource',- namespace: 'mcp-server',- spec: { contextId: 'live-context', mcpServers: [server.name] },- }- const rec = makeReconciler(mockApi, new Map([[server.name, server]]), mockCustomApi)- const reverseObjectKeys = (value: unknown): unknown => {- if (Array.isArray(value)) return value.map(reverseObjectKeys)- if (value === null || typeof value !== 'object') return value- return Object.fromEntries(- Object.entries(value as Record<string, unknown>)- .reverse()- .map(([key, entry]) => [key, reverseObjectKeys(entry)])- )+ const currentServer: McpServerCRD = {+ ...oldServer,+ spec: {+ ...oldServer.spec,+ egressBindings: [{ dns: 'new.example.com', port: 443 }],+ },}+ const rec = makeReconciler(mockApi, new Map([[oldServer.name, oldServer]]), mockCustomApi)+ await rec.reconcileExternalEgress(oldServer)+ const oldPolicy = mockApi.createNamespacedNetworkPolicy.mock.calls+ .map(call => (call[0] as { body: k8s.V1NetworkPolicy }).body)+ .find(policy => policy.metadata?.labels?.['clerum.io/policy-type'] === 'external-egress')!- await rec.reconcileContext(liveContext)- const existingPolicies = mockApi.createNamespacedNetworkPolicy.mock.calls.map(call => {- const policy = (call[0] as { body: k8s.V1NetworkPolicy }).body- return { ...policy, spec: reverseObjectKeys(policy.spec) as k8s.V1NetworkPolicySpec }- })vi.clearAllMocks()+ const ordering: string[] = []+ let currentPolicies = [oldPolicy]mockApi.listNamespacedNetworkPolicy.mockImplementation(- async ({ namespace, labelSelector }: { namespace?: string; labelSelector?: string }) => {- if (labelSelector?.includes('external-egress')) return { items: [] }- return {- items: existingPolicies.filter(policy => policy.metadata?.namespace === namespace),- }- }+ async ({ labelSelector }: { labelSelector?: string }) =>+ labelSelector?.includes('external-egress') ? { items: currentPolicies } : { items: [] })- vi.spyOn(rec, 'reconcileContext').mockResolvedValue(undefined)- vi.spyOn(rec, 'reconcileExternalEgress').mockResolvedValue(undefined)+ mockApi.deleteNamespacedNetworkPolicy.mockImplementation(async ({ name }) => {+ ordering.push('delete')+ currentPolicies = currentPolicies.filter(policy => policy.metadata?.name !== name)+ return {}+ })+ vi.mocked(dns.resolve4).mockImplementation(async () => {+ ordering.push('dns')+ return ['1.2.3.4']+ })+ const onAuthoritativeRevocationComplete = vi.fn(() => {+ expect(dns.resolve4).not.toHaveBeenCalled()+ ordering.push('certify')+ })- await rec.fullReconcile([liveContext], [server], {+ await rec.fullReconcile([], [currentServer], {ensureDefaults: false,contextInventoryAuthoritative: () => true,serverInventoryAuthoritative: () => true,+ onAuthoritativeRevocationComplete,})- expect(mockApi.deleteNamespacedNetworkPolicy).not.toHaveBeenCalled()+ expect(ordering.slice(0, 3)).toEqual(['delete', 'certify', 'dns'])+ expect(mockApi.deleteNamespacedNetworkPolicy).toHaveBeenCalledWith({+ name: oldPolicy.metadata!.name!,+ namespace: oldServer.namespace,+ body: {+ preconditions: {+ uid: `${oldServer.namespace}:${oldPolicy.metadata!.name!}:uid`,+ resourceVersion: '1',+ },+ },+ })})- it('replaces same-name DNS egress before certifying readiness without an allow gap', async () => {+ it('replaces deterministic drift and revokes renamed DNS before certification without resolving DNS', async () => {const oldServer: McpServerCRD = {- name: 'live-server',+ name: 'mixed-drift-server',namespace: 'mcp-server',spec: {contextRef: 'default',- image: 'live:latest',+ image: 'mixed:test',transport: { type: 'streamableHttp', port: 3000 },- egressBindings: [{ dns: 'api.example.com', port: 443, protocol: 'TCP' }],+ egressBindings: [+ { cidr: '8.8.8.8/32', port: 443, protocol: 'TCP' },+ { dns: 'old.example.com', port: 443, protocol: 'TCP' },+ ],},}const currentServer: McpServerCRD = {...oldServer,spec: {...oldServer.spec,- egressBindings: [{ dns: 'api.example.com', port: 443, protocol: 'UDP' }],+ egressBindings: [+ { cidr: '8.8.8.8/32', port: 443, protocol: 'UDP' },+ { dns: 'new.example.com', port: 443, protocol: 'TCP' },+ ],},}const rec = makeReconciler(mockApi, new Map([[oldServer.name, oldServer]]), mockCustomApi)-await rec.reconcileExternalEgress(oldServer)- const oldPolicy = mockApi.createNamespacedNetworkPolicy.mock.calls+ const oldPolicies = mockApi.createNamespacedNetworkPolicy.mock.calls.map(call => (call[0] as { body: k8s.V1NetworkPolicy }).body)- .find(policy => policy.metadata?.labels?.['clerum.io/policy-type'] === 'external-egress')- expect(oldPolicy).toBeDefined()+ .filter(policy => policy.metadata?.labels?.['clerum.io/policy-type'] === 'external-egress')vi.clearAllMocks()const ordering: string[] = []+ let currentPolicies = oldPoliciesmockApi.listNamespacedNetworkPolicy.mockImplementation(async ({ labelSelector }: { labelSelector?: string }) =>- labelSelector?.includes('external-egress') ? { items: [oldPolicy!] } : { items: [] }- )- mockApi.createNamespacedNetworkPolicy.mockRejectedValue(- Object.assign(new Error('already exists'), { code: 409 })+ labelSelector?.includes('external-egress') ? { items: currentPolicies } : { items: [] })mockApi.replaceNamespacedNetworkPolicy.mockImplementation(async () => {ordering.push('replace')return {}})- mockApi.deleteNamespacedNetworkPolicy.mockImplementation(async () => {+ mockApi.deleteNamespacedNetworkPolicy.mockImplementation(async ({ name }) => {ordering.push('delete')+ currentPolicies = currentPolicies.filter(policy => policy.metadata?.name !== name)return {}})+ vi.mocked(dns.resolve4).mockImplementation(async () => {+ ordering.push('dns')+ return ['1.2.3.4']+ })const onAuthoritativeRevocationComplete = vi.fn(() => {+ expect(dns.resolve4).not.toHaveBeenCalled()ordering.push('certify')})@@ -2318,61 +3259,195 @@ describe('NetworkPolicyReconciler', () => {onAuthoritativeRevocationComplete,})- expect(ordering.slice(0, 2)).toEqual(['replace', 'certify'])- expect(onAuthoritativeRevocationComplete).toHaveBeenCalledOnce()+ expect(ordering.slice(0, 4)).toEqual(['replace', 'delete', 'certify', 'dns'])})- it('revokes a divergent same-name DNS policy when its safe replacement cannot resolve', async () => {+ it('aborts certification when an identity-bound safety delete reports a recreate conflict', async () => {+ const server: McpServerCRD = {+ name: 'recreated-dns-server',+ namespace: 'mcp-server',+ spec: {+ contextRef: 'default',+ image: 'dns:test',+ transport: { type: 'streamableHttp', port: 3000 },+ egressBindings: [{ dns: 'api.example.com', port: 443 }],+ },+ }+ const rec = makeReconciler(mockApi, new Map([[server.name, server]]), mockCustomApi)+ await rec.reconcileExternalEgress(server)+ const existing = mockApi.createNamespacedNetworkPolicy.mock.calls+ .map(call => (call[0] as { body: k8s.V1NetworkPolicy }).body)+ .find(policy => policy.metadata?.labels?.['clerum.io/policy-type'] === 'external-egress')!++ vi.clearAllMocks()+ mockApi.listNamespacedNetworkPolicy.mockImplementation(+ async ({ labelSelector }: { labelSelector?: string }) =>+ labelSelector?.includes('external-egress') ? { items: [existing] } : { items: [] }+ )+ const conflict = Object.assign(new Error('delete precondition conflict'), { code: 409 })+ mockApi.deleteNamespacedNetworkPolicy.mockRejectedValue(conflict)+ const onAuthoritativeRevocationComplete = vi.fn()++ await expect(+ rec.fullReconcile([], [server], {+ ensureDefaults: false,+ contextInventoryAuthoritative: () => true,+ serverInventoryAuthoritative: () => true,+ onAuthoritativeRevocationComplete,+ })+ ).rejects.toBe(conflict)++ expect(mockApi.deleteNamespacedNetworkPolicy).toHaveBeenCalledWith({+ name: existing.metadata!.name!,+ namespace: server.namespace,+ body: {+ preconditions: {+ uid: `${server.namespace}:${existing.metadata!.name!}:uid`,+ resourceVersion: '1',+ },+ },+ })+ expect(onAuthoritativeRevocationComplete).not.toHaveBeenCalled()+ })++ it.each([+ [+ 'foreign relabel',+ {+ labels: {+ 'clerum.io/managed-by': 'foreign-controller',+ 'clerum.io/policy-type': 'external-egress',+ 'clerum.io/mcpserver': 'fresh-read-server',+ },+ },+ ],+ ['UID drift', { uid: 'replacement-uid' }],+ ['resourceVersion drift', { resourceVersion: '2' }],+ ])(+ 'aborts a deterministic safety replace after fresh-read %s',+ async (_case, metadataDrift) => {+ const oldServer: McpServerCRD = {+ name: 'fresh-read-server',+ namespace: 'mcp-server',+ spec: {+ contextRef: 'default',+ image: 'fresh:test',+ transport: { type: 'streamableHttp', port: 3000 },+ egressBindings: [{ cidr: '8.8.8.8/32', port: 443, protocol: 'TCP' }],+ },+ }+ const currentServer: McpServerCRD = {+ ...oldServer,+ spec: {+ ...oldServer.spec,+ egressBindings: [{ cidr: '8.8.8.8/32', port: 443, protocol: 'UDP' }],+ },+ }+ const rec = makeReconciler(mockApi, new Map([[oldServer.name, oldServer]]), mockCustomApi)+ await rec.reconcileExternalEgress(oldServer)+ const existing = mockApi.createNamespacedNetworkPolicy.mock.calls+ .map(call => (call[0] as { body: k8s.V1NetworkPolicy }).body)+ .find(policy => policy.metadata?.labels?.['clerum.io/policy-type'] === 'external-egress')!++ vi.clearAllMocks()+ mockApi.listNamespacedNetworkPolicy.mockImplementation(+ async ({ labelSelector }: { labelSelector?: string }) =>+ labelSelector?.includes('external-egress') ? { items: [existing] } : { items: [] }+ )+ mockApi.readNamespacedNetworkPolicy.mockResolvedValue({+ metadata: {+ ...metadataDrift,+ },+ })+ const onAuthoritativeRevocationComplete = vi.fn()++ await expect(+ rec.fullReconcile([], [currentServer], {+ ensureDefaults: false,+ contextInventoryAuthoritative: () => true,+ serverInventoryAuthoritative: () => true,+ onAuthoritativeRevocationComplete,+ })+ ).rejects.toThrow(/changed identity or ownership/)++ expect(mockApi.readNamespacedNetworkPolicy).toHaveBeenCalledWith({+ name: existing.metadata!.name!,+ namespace: oldServer.namespace,+ })+ expect(mockApi.replaceNamespacedNetworkPolicy).not.toHaveBeenCalled()+ expect(onAuthoritativeRevocationComplete).not.toHaveBeenCalled()+ }+ )++ it('uses the fresh identity to complete a deterministic safety replacement before certification', async () => {const oldServer: McpServerCRD = {- name: 'live-server',+ name: 'fresh-success-server',namespace: 'mcp-server',spec: {contextRef: 'default',- image: 'live:latest',+ image: 'fresh:test',transport: { type: 'streamableHttp', port: 3000 },- egressBindings: [{ dns: 'api.example.com', port: 443, protocol: 'TCP' }],+ egressBindings: [{ cidr: '8.8.8.8/32', port: 443, protocol: 'TCP' }],},}const currentServer: McpServerCRD = {...oldServer,spec: {...oldServer.spec,- egressBindings: [{ dns: 'api.example.com', port: 443, protocol: 'UDP' }],+ egressBindings: [{ cidr: '8.8.8.8/32', port: 443, protocol: 'UDP' }],},}const rec = makeReconciler(mockApi, new Map([[oldServer.name, oldServer]]), mockCustomApi)-await rec.reconcileExternalEgress(oldServer)- const oldPolicy = mockApi.createNamespacedNetworkPolicy.mock.calls+ const existing = mockApi.createNamespacedNetworkPolicy.mock.calls.map(call => (call[0] as { body: k8s.V1NetworkPolicy }).body)- .find(policy => policy.metadata?.labels?.['clerum.io/policy-type'] === 'external-egress')- expect(oldPolicy).toBeDefined()+ .find(policy => policy.metadata?.labels?.['clerum.io/policy-type'] === 'external-egress')!vi.clearAllMocks()- vi.mocked(dns.resolve4).mockRejectedValue(new Error('dns unavailable'))+ const ordering: string[] = []mockApi.listNamespacedNetworkPolicy.mockImplementation(async ({ labelSelector }: { labelSelector?: string }) =>- labelSelector?.includes('external-egress') ? { items: [oldPolicy!] } : { items: [] }+ labelSelector?.includes('external-egress') ? { items: [existing] } : { items: [] })- const onAuthoritativeRevocationComplete = vi.fn()+ mockApi.readNamespacedNetworkPolicy.mockImplementation(async () => {+ ordering.push('read')+ return { metadata: { resourceVersion: '1' } }+ })+ mockApi.replaceNamespacedNetworkPolicy.mockImplementation(async () => {+ ordering.push('replace')+ return {}+ })+ const onAuthoritativeRevocationComplete = vi.fn(() => ordering.push('certify'))- await expect(- rec.fullReconcile([], [currentServer], {- ensureDefaults: false,- contextInventoryAuthoritative: () => true,- serverInventoryAuthoritative: () => true,- onAuthoritativeRevocationComplete,- })- ).rejects.toThrow('dns unavailable')+ await rec.fullReconcile([], [currentServer], {+ ensureDefaults: false,+ contextInventoryAuthoritative: () => true,+ serverInventoryAuthoritative: () => true,+ onAuthoritativeRevocationComplete,+ })- expect(mockApi.deleteNamespacedNetworkPolicy).toHaveBeenCalledWith({- name: oldPolicy!.metadata!.name!,+ expect(ordering.slice(0, 3)).toEqual(['read', 'replace', 'certify'])+ expect(mockApi.replaceNamespacedNetworkPolicy).toHaveBeenCalledWith({+ name: existing.metadata!.name!,namespace: oldServer.namespace,+ body: expect.objectContaining({+ metadata: expect.objectContaining({+ name: existing.metadata!.name!,+ namespace: oldServer.namespace,+ resourceVersion: '1',+ }),+ spec: expect.objectContaining({+ egress: expect.arrayContaining([+ expect.objectContaining({+ ports: [expect.objectContaining({ protocol: 'UDP' })],+ }),+ ]),+ }),+ }),})- expect(onAuthoritativeRevocationComplete).not.toHaveBeenCalled()})- it('retains a valid same-intent DNS policy so readiness does not await fleet DNS refresh', async () => {+ it('revokes a same-intent DNS policy before readiness and defers its refresh', async () => {const server: McpServerCRD = {name: 'stable-dns-server',namespace: 'mcp-server',@@ -2391,10 +3466,15 @@ describe('NetworkPolicyReconciler', () => {expect(existing).toBeDefined()vi.clearAllMocks()+ let currentPolicies = [existing!]mockApi.listNamespacedNetworkPolicy.mockImplementation(async ({ labelSelector }: { labelSelector?: string }) =>- labelSelector?.includes('external-egress') ? { items: [existing!] } : { items: [] }+ labelSelector?.includes('external-egress') ? { items: currentPolicies } : { items: [] })+ mockApi.deleteNamespacedNetworkPolicy.mockImplementation(async () => {+ currentPolicies = []+ return {}+ })const additiveStarted = deferred()const releaseAdditive = deferred()vi.spyOn(rec, 'reconcileExternalEgress').mockImplementationOnce(async () => {@@ -2412,7 +3492,12 @@ describe('NetworkPolicyReconciler', () => {await additiveStarted.promisetry {expect(onAuthoritativeRevocationComplete).toHaveBeenCalledOnce()- expect(mockApi.deleteNamespacedNetworkPolicy).not.toHaveBeenCalled()+ expect(mockApi.deleteNamespacedNetworkPolicy).toHaveBeenCalledWith(+ expect.objectContaining({+ name: existing!.metadata!.name!,+ namespace: server.namespace,+ })+ )expect(dns.resolve4).not.toHaveBeenCalled()} finally {releaseAdditive.resolve(undefined)@@ -2420,9 +3505,9 @@ describe('NetworkPolicyReconciler', () => {}})- it('preserves a safety-certified DNS policy on every default refresh failure', async () => {+ it('does not certify safety when a same-intent DNS policy cannot be revoked', async () => {const server: McpServerCRD = {- name: 'stable-dns-server',+ name: 'undeletable-dns-server',namespace: 'mcp-server',spec: {contextRef: 'default',@@ -2439,15 +3524,29 @@ describe('NetworkPolicyReconciler', () => {expect(existing).toBeDefined()vi.clearAllMocks()- vi.mocked(dns.resolve4).mockRejectedValue(new Error('dns unavailable'))mockApi.listNamespacedNetworkPolicy.mockImplementation(async ({ labelSelector }: { labelSelector?: string }) =>labelSelector?.includes('external-egress') ? { items: [existing!] } : { items: [] })- await expect(rec.reconcileExternalEgress(server)).rejects.toThrow('dns unavailable')+ mockApi.deleteNamespacedNetworkPolicy.mockRejectedValue(new Error('delete denied'))+ const onAuthoritativeRevocationComplete = vi.fn()- expect(mockApi.deleteNamespacedNetworkPolicy).not.toHaveBeenCalled()- expect(mockApi.createNamespacedNetworkPolicy).not.toHaveBeenCalled()+ await expect(+ rec.fullReconcile([], [server], {+ ensureDefaults: false,+ contextInventoryAuthoritative: () => true,+ serverInventoryAuthoritative: () => true,+ onAuthoritativeRevocationComplete,+ })+ ).rejects.toThrow('delete denied')++ expect(onAuthoritativeRevocationComplete).not.toHaveBeenCalled()+ expect(mockApi.deleteNamespacedNetworkPolicy).toHaveBeenCalledWith(+ expect.objectContaining({+ name: existing!.metadata!.name!,+ namespace: server.namespace,+ })+ )})it('does not certify revocation when an earlier Context changes while a later owner is paused', async () => {@@ -2706,7 +3805,7 @@ describe('NetworkPolicyReconciler', () => {expect(onAuthoritativeRevocationComplete).not.toHaveBeenCalled()})- it('uses one global inventory LIST per policy lane before additive fleet convergence', async () => {+ it('uses selected lane LISTs plus one broad LIST per bounded namespace before additive convergence', async () => {const contexts: ContextCRD[] = ['alpha', 'beta', 'gamma'].map(contextId => ({name: `${contextId}-resource`,namespace: 'mcp-server',@@ -2737,7 +3836,7 @@ describe('NetworkPolicyReconciler', () => {await additiveStarted.promisetry {- expect(mockApi.listNamespacedNetworkPolicy).toHaveBeenCalledTimes(4)+ expect(mockApi.listNamespacedNetworkPolicy).toHaveBeenCalledTimes(7)expect(mockApi.listNamespacedNetworkPolicy).toHaveBeenCalledWith({namespace: 'mcp-server',labelSelector: expect.stringContaining('policy-type=context-allow'),@@ -2754,6 +3853,15 @@ describe('NetworkPolicyReconciler', () => {namespace: 'mcp-server',labelSelector: expect.stringContaining('policy-type=external-egress'),})+ expect(mockApi.listNamespacedNetworkPolicy).toHaveBeenCalledWith({+ namespace: 'mcp-server',+ })+ expect(mockApi.listNamespacedNetworkPolicy).toHaveBeenCalledWith({+ namespace: 'mcp-host',+ })+ expect(mockApi.listNamespacedNetworkPolicy).toHaveBeenCalledWith({+ namespace: 'rpc-proxy',+ })} finally {releaseAdditive.resolve(undefined)await fullPass@@ -2816,10 +3924,12 @@ describe('NetworkPolicyReconciler', () => {await reconciler.fullReconcile([], [], { serverInventoryComplete: true })- expect(mockApi.deleteNamespacedNetworkPolicy).toHaveBeenCalledWith({- name: 'ext-egress-old-server-api-example-com-443',- namespace: 'mcp-server',- })+ expect(mockApi.deleteNamespacedNetworkPolicy).toHaveBeenCalledWith(+ expect.objectContaining({+ name: 'ext-egress-old-server-api-example-com-443',+ namespace: 'mcp-server',+ })+ )})it('fails closed by deleting HCC-managed policies with missing owner labels', async () => {@@ -2875,22 +3985,30 @@ describe('NetworkPolicyReconciler', () => {serverInventoryComplete: true,})- expect(mockApi.deleteNamespacedNetworkPolicy).toHaveBeenCalledWith({- name: 'malformed-context-ingress',- namespace: 'mcp-server',- })- expect(mockApi.deleteNamespacedNetworkPolicy).toHaveBeenCalledWith({- name: 'malformed-host-egress',- namespace: 'mcp-host',- })- expect(mockApi.deleteNamespacedNetworkPolicy).toHaveBeenCalledWith({- name: 'malformed-rpc-proxy-egress',- namespace: 'rpc-proxy',- })- expect(mockApi.deleteNamespacedNetworkPolicy).toHaveBeenCalledWith({- name: 'malformed-external-egress',- namespace: 'mcp-server',- })+ expect(mockApi.deleteNamespacedNetworkPolicy).toHaveBeenCalledWith(+ expect.objectContaining({+ name: 'malformed-context-ingress',+ namespace: 'mcp-server',+ })+ )+ expect(mockApi.deleteNamespacedNetworkPolicy).toHaveBeenCalledWith(+ expect.objectContaining({+ name: 'malformed-host-egress',+ namespace: 'mcp-host',+ })+ )+ expect(mockApi.deleteNamespacedNetworkPolicy).toHaveBeenCalledWith(+ expect.objectContaining({+ name: 'malformed-rpc-proxy-egress',+ namespace: 'rpc-proxy',+ })+ )+ expect(mockApi.deleteNamespacedNetworkPolicy).toHaveBeenCalledWith(+ expect.objectContaining({+ name: 'malformed-external-egress',+ namespace: 'mcp-server',+ })+ )})it('skips external egress orphan cleanup when startup server discovery is incomplete', async () => {diff --git a/host-context-controller/src/networkPolicyReconciler.ts b/host-context-controller/src/networkPolicyReconciler.tsindex accc491ee..cc20adab1 100644--- a/host-context-controller/src/networkPolicyReconciler.ts+++ b/host-context-controller/src/networkPolicyReconciler.ts@@ -52,13 +52,17 @@ type JsonPatchOperation = {type NetworkPolicyMutationOptions = {isCurrent?: () => booleanexistingPolicies?: k8s.V1NetworkPolicy[]+ onRevoked?: () => void}export function sameContextDesiredRevision(expected: ContextCRD, current: ContextCRD): boolean {return (expected.name === current.name &&expected.namespace === current.namespace &&- JSON.stringify(expected.spec) === JSON.stringify(current.spec)+ expected.uid === current.uid &&+ expected.generation === current.generation &&+ JSON.stringify(canonicalizeNetworkPolicyValue(expected.spec)) ===+ JSON.stringify(canonicalizeNetworkPolicyValue(current.spec)))}@@ -83,6 +87,11 @@ function sameNetworkPolicySpec()}+function hasExpectedPolicyOwnership(policy: k8s.V1NetworkPolicy, policyType: string): boolean {+ const labels = policy.metadata?.labels ?? {}+ return labels[MANAGED_BY_LABEL] === MANAGED_BY_VALUE && labels[POLICY_TYPE_LABEL] === policyType+}+const GROUP = 'clerum.io'const VERSION = 'v1alpha1'const PLURAL_MCPSERVERS = 'mcpservers'@@ -91,6 +100,111 @@ const CONTEXT_LABEL = 'clerum.io/context'const EGRESS_CLASS_LABEL = 'clerum.io/egress-class'const RPC_PROXY_EGRESS_POLICY_TYPE = 'rpc-proxy-egress'const RPC_PROXY_APP_LABEL = 'rpc-proxy'++type SafetyInventoryLane =+ | 'context-ingress'+ | 'context-host-egress'+ | 'context-rpc-egress'+ | 'external-egress'++type SafetyInventoryClassification = 'owned' | 'repairable' | 'ambiguous' | 'unrelated'++function policyHasOwnerShape(policy: k8s.V1NetworkPolicy, lane: SafetyInventoryLane): boolean {+ const labels = policy.metadata?.labels ?? {}+ const hasServerOwner = Boolean(labels[MCPSERVER_LABEL])+ if (lane === 'external-egress') return hasServerOwner+ return Boolean(labels[CONTEXT_LABEL]) && hasServerOwner+}++function policyHasReservedName(policy: k8s.V1NetworkPolicy, lane: SafetyInventoryLane): boolean {+ const name = policy.metadata?.name ?? ''+ switch (lane) {+ case 'context-ingress':+ return name.startsWith('ctx-')+ case 'context-host-egress':+ return name.startsWith('ctx-') && name.endsWith('-egress')+ case 'context-rpc-egress':+ return name.startsWith('rpc-egress-')+ case 'external-egress':+ return name.startsWith('ext-egress-')+ }+}++function policyNameBelongsToDifferentLane(+ policy: k8s.V1NetworkPolicy,+ lane: SafetyInventoryLane+): boolean {+ const name = policy.metadata?.name ?? ''+ if (lane === 'context-ingress') return name.startsWith('ext-egress-')+ if (lane === 'external-egress') return name.startsWith('ctx-')+ return false+}++function expectedPolicyType(lane: SafetyInventoryLane): string {+ return lane === 'context-rpc-egress'+ ? RPC_PROXY_EGRESS_POLICY_TYPE+ : lane === 'external-egress'+ ? EXTERNAL_EGRESS_POLICY_TYPE+ : 'context-allow'+}++/**+ * Classify broad namespace inventory without taking ownership of unrelated+ * policies. A single missing HCC marker is recoverable only when owner labels+ * corroborate the lane. Reserved HCC names and conflicting ownership markers+ * are never adopted implicitly.+ */+function classifySafetyInventoryPolicy(+ policy: k8s.V1NetworkPolicy,+ lane: SafetyInventoryLane+): SafetyInventoryClassification {+ const labels = policy.metadata?.labels ?? {}+ const managedBy = labels[MANAGED_BY_LABEL]+ const policyType = labels[POLICY_TYPE_LABEL]+ const expectedType = expectedPolicyType(lane)+ const managedMatches = managedBy === MANAGED_BY_VALUE+ const typeMatches = policyType === expectedType+ const managedMissing = managedBy === undefined+ const typeMissing = policyType === undefined+ const reservedName = policyHasReservedName(policy, lane)+ const ownerShape = policyHasOwnerShape(policy, lane)++ if (managedMatches && typeMatches) return 'owned'++ const oneMarkerMissing = (managedMatches && typeMissing) || (managedMissing && typeMatches)+ if (managedMissing && typeMatches && ownerShape) {+ return reservedName ? 'repairable' : 'ambiguous'+ }+ if (managedMatches && typeMissing && ownerShape) {+ if (reservedName) return 'repairable'+ if (policyNameBelongsToDifferentLane(policy, lane)) return 'unrelated'+ return 'ambiguous'+ }++ const knownOtherHccType =+ policyType !== undefined &&+ ['context-allow', RPC_PROXY_EGRESS_POLICY_TYPE, EXTERNAL_EGRESS_POLICY_TYPE].includes(+ policyType+ ) &&+ !typeMatches+ const hasRawConflictingMarker =+ (managedBy !== undefined && !managedMatches) || (policyType !== undefined && !typeMatches)+ const hasConflictingMarker =+ (managedBy !== undefined && !managedMatches) ||+ (policyType !== undefined && !typeMatches && !knownOtherHccType)+ if (+ reservedName &&+ ((managedMissing && typeMissing) || hasRawConflictingMarker || oneMarkerMissing)+ ) {+ return 'ambiguous'+ }+ if (ownerShape && hasConflictingMarker) {+ return 'ambiguous'+ }++ return 'unrelated'+}+export const PUBLIC_EGRESS_EXCEPT_CIDRS = ['0.0.0.0/8','10.0.0.0/8',@@ -656,9 +770,6 @@ export class NetworkPolicyReconciler {`[NetPol] Reconciling context "${contextId}" — allowed servers: [${allowedServers.join(', ')}]`)- await this.listPoliciesForContext(contextId)- if (!isCurrent()) return-// Create or update policies for each allowed server.for (const serverName of allowedServers) {if (!isCurrent()) return@@ -697,9 +808,8 @@ export class NetworkPolicyReconciler {)}- // The pre-apply LIST above is an authority fence, not a post-apply cleanup- // snapshot. Re-LIST every lane after the writes so a same-name policy that- // was just replaced is compared in its new form and cannot delete itself.+ // Re-LIST every lane after writes so a same-name policy that was just+ // replaced is compared in its new form and cannot delete itself.await this.revokeStaleContextAllows(context, isCurrent)}@@ -714,6 +824,7 @@ export class NetworkPolicyReconciler {onRevoked?: () => void): Promise<boolean> {if (!isCurrent()) return false+ const safetySnapshotProvided = listedPolicies !== undefinedconst contextId = context.spec.contextIdconst allowedServers = context.spec.mcpServers || []const desiredIngress = new Map<string, k8s.V1NetworkPolicy>()@@ -735,9 +846,36 @@ export class NetworkPolicyReconciler {if (!isCurrent()) return falseconst existingName = existing.metadata?.name || ''const desired = desiredIngress.get(existingName)- if (!desired || !sameNetworkPolicySpec(existing, desired)) {- console.log(`[NetPol] Deleting stale or orphaned policy "${existingName}"`)- await this.deletePolicy(existingName, isCurrent)+ if (!desired) {+ console.log(`[NetPol] Deleting orphaned policy "${existingName}"`)+ if (safetySnapshotProvided) {+ if (!(await this.deleteSafetyPolicySnapshot(config.namespace, existing, isCurrent))) {+ return false+ }+ } else {+ await this.deletePolicy(existingName, isCurrent)+ }+ onRevoked?.()+ } else if (+ !sameNetworkPolicySpec(existing, desired) ||+ !hasExpectedPolicyOwnership(existing, 'context-allow')+ ) {+ console.log(`[NetPol] Replacing stale same-name policy "${existingName}"`)+ if (safetySnapshotProvided) {+ if (+ !(await this.replaceSafetyPolicySnapshot(+ config.namespace,+ existing,+ desired,+ 'context-ingress',+ isCurrent+ ))+ ) {+ return false+ }+ } else {+ await this.applyPolicy(existingName, desired, isCurrent)+ }onRevoked?.()}}@@ -749,9 +887,43 @@ export class NetworkPolicyReconciler {if (!isCurrent()) return falseconst existingName = existing.metadata?.name || ''const desired = desiredHostEgress.get(existingName)- if (!desired || !sameNetworkPolicySpec(existing, desired)) {- console.log(`[NetPol] Deleting stale or orphaned L2 egress policy "${existingName}"`)- await this.deleteEgressPolicy(existingName, isCurrent)+ if (!desired) {+ console.log(`[NetPol] Deleting orphaned L2 egress policy "${existingName}"`)+ if (safetySnapshotProvided) {+ if (!(await this.deleteSafetyPolicySnapshot(config.hostNamespace, existing, isCurrent))) {+ return false+ }+ } else {+ await this.deleteEgressPolicy(existingName, isCurrent)+ }+ onRevoked?.()+ } else if (+ !sameNetworkPolicySpec(existing, desired) ||+ !hasExpectedPolicyOwnership(existing, 'context-allow')+ ) {+ console.log(`[NetPol] Replacing stale same-name L2 egress policy "${existingName}"`)+ if (safetySnapshotProvided) {+ if (+ !(await this.replaceSafetyPolicySnapshot(+ config.hostNamespace,+ existing,+ desired,+ 'context-host-egress',+ isCurrent+ ))+ ) {+ return false+ }+ } else {+ await applyNetworkPolicy(+ this.networkingApi,+ existingName,+ config.hostNamespace,+ desired,+ '[NetPol]',+ isCurrent+ )+ }onRevoked?.()}}@@ -763,9 +935,45 @@ export class NetworkPolicyReconciler {if (!isCurrent()) return falseconst existingName = existing.metadata?.name || ''const desired = desiredRpcProxyEgress.get(existingName)- if (!desired || !sameNetworkPolicySpec(existing, desired)) {- console.log(`[NetPol] Deleting stale or orphaned rpc-proxy egress policy "${existingName}"`)- await this.deletePolicyInNamespace(config.rpcProxyNamespace, existingName, isCurrent)+ if (!desired) {+ console.log(`[NetPol] Deleting orphaned rpc-proxy egress policy "${existingName}"`)+ if (safetySnapshotProvided) {+ if (+ !(await this.deleteSafetyPolicySnapshot(config.rpcProxyNamespace, existing, isCurrent))+ ) {+ return false+ }+ } else {+ await this.deletePolicyInNamespace(config.rpcProxyNamespace, existingName, isCurrent)+ }+ onRevoked?.()+ } else if (+ !sameNetworkPolicySpec(existing, desired) ||+ !hasExpectedPolicyOwnership(existing, RPC_PROXY_EGRESS_POLICY_TYPE)+ ) {+ console.log(`[NetPol] Replacing stale same-name rpc-proxy egress policy "${existingName}"`)+ if (safetySnapshotProvided) {+ if (+ !(await this.replaceSafetyPolicySnapshot(+ config.rpcProxyNamespace,+ existing,+ desired,+ 'context-rpc-egress',+ isCurrent+ ))+ ) {+ return false+ }+ } else {+ await applyNetworkPolicy(+ this.networkingApi,+ existingName,+ config.rpcProxyNamespace,+ desired,+ '[NetPol]',+ isCurrent+ )+ }onRevoked?.()}}@@ -808,6 +1016,43 @@ export class NetworkPolicyReconciler {contexts: ContextCRD[],servers: McpServerCRD[] = [],options: NetworkPolicyFullReconcileOptions = {}+ ): Promise<void> {+ const onAuthoritativeRevocationComplete = options.onAuthoritativeRevocationComplete+ if (!onAuthoritativeRevocationComplete) {+ await this.fullReconcileInternal(contexts, servers, options)+ return+ }++ const safetyPassStartedAt = performance.now()+ let safetyPassDurationRecorded = false+ const recordSafetyPassDuration = (outcome: 'completed' | 'failed'): void => {+ if (safetyPassDurationRecorded) return+ safetyPassDurationRecorded = true+ networkPolicySafetyPassDurationSeconds.observe(+ { outcome },+ (performance.now() - safetyPassStartedAt) / 1_000+ )+ }++ try {+ await this.fullReconcileInternal(contexts, servers, {+ ...options,+ onAuthoritativeRevocationComplete: () => {+ onAuthoritativeRevocationComplete()+ recordSafetyPassDuration('completed')+ },+ })+ recordSafetyPassDuration('failed')+ } catch (error) {+ recordSafetyPassDuration('failed')+ throw error+ }+ }++ private async fullReconcileInternal(+ contexts: ContextCRD[],+ servers: McpServerCRD[] = [],+ options: NetworkPolicyFullReconcileOptions = {}): Promise<void> {console.log(`[NetPol] Running full reconciliation for ${contexts.length} Context(s)`)@@ -815,7 +1060,6 @@ export class NetworkPolicyReconciler {// revocation callback. Ordinary additive reconciles must not be presented// as readiness safety passes.const measureSafetyPass = options.onAuthoritativeRevocationComplete !== undefined- const safetyPassStartedAt = measureSafetyPass ? performance.now() : 0let safetyPassListedPolicies = 0let safetyPassRevokedPolicies = 0const recordSafetyPassRevocation = (): void => {@@ -826,11 +1070,6 @@ export class NetworkPolicyReconciler {// default-policy setup can interleave a watch update with this snapshot.const selectedContextDesiredRevision = options.contextDesiredRevision?.()const selectedServerDesiredRevision = options.serverDesiredRevision?.()-- if (options.ensureDefaults !== false) {- await this.ensureDefaultPolicies()- }-const runContextEffect =options.runContextEffect ?? ((_contextId: string, work: () => Promise<void>) => work())const runServerEffect =@@ -839,6 +1078,10 @@ export class NetworkPolicyReconciler {(options.contextInventoryAuthoritative?.() ?? true) &&(options.serverInventoryAuthoritative?.() ?? true)+ if (options.ensureDefaults !== false) {+ await this.ensureDefaultPolicies()+ }+// 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.@@ -883,7 +1126,7 @@ export class NetworkPolicyReconciler {const desiredContextIds = new Set(contexts.map(c => c.spec.contextId))const cleanupOrphanedContextPolicies = async (policies: k8s.V1NetworkPolicy[],- deletePolicy: (name: string) => Promise<void>,+ deletePolicy: (policy: k8s.V1NetworkPolicy) => Promise<boolean>,describePolicy: (name: string, contextId: string) => string): Promise<void> => {if (!contextCleanupAuthoritative()) return@@ -898,8 +1141,7 @@ export class NetworkPolicyReconciler {console.warn(`[NetPol] Deleting malformed HCC-managed policy "${name}" without ${CONTEXT_LABEL}`)- await deletePolicy(name)- recordSafetyPassRevocation()+ if (await deletePolicy(policy)) recordSafetyPassRevocation()continue}if (!desiredContextIds.has(contextId)) {@@ -915,42 +1157,97 @@ export class NetworkPolicyReconciler {return}console.log(describePolicy(name, contextId))- await deletePolicy(name)- recordSafetyPassRevocation()+ if (await deletePolicy(policy)) recordSafetyPassRevocation()})}}}- const allContextPolicies = contextCleanupAuthoritative()+ let allContextPolicies = contextCleanupAuthoritative()? await this.listAllContextPolicies(): []- const allContextEgressPolicies = contextCleanupAuthoritative()+ let allContextEgressPolicies = contextCleanupAuthoritative()? await this.listAllContextEgressPolicies(): []- const allRpcProxyEgressPolicies = contextCleanupAuthoritative()+ let allRpcProxyEgressPolicies = contextCleanupAuthoritative()? await this.listAllRpcProxyEgressPolicies(): []+ let allExternalPolicies: k8s.V1NetworkPolicy[] = []+ if (options.serverInventoryComplete !== false && serverCleanupAuthoritative()) {+ allExternalPolicies = await this.listAllExternalEgressPolicies()+ }++ // Label selectors alone cannot prove safety: removing either ownership+ // marker would hide an active allow from the selected LIST. Audit the+ // bounded namespaces, then merge only owned or conservatively repairable+ // candidates into their lane. Ambiguous reserved names fail the pass.+ const needsMcpServerBroadInventory =+ contextCleanupAuthoritative() ||+ (options.serverInventoryComplete !== false && serverCleanupAuthoritative())+ const broadMcpServerPolicies = needsMcpServerBroadInventory+ ? await this.listNamespacePoliciesForSafety(config.namespace)+ : []+ const broadHostPolicies = contextCleanupAuthoritative()+ ? await this.listNamespacePoliciesForSafety(config.hostNamespace)+ : []+ const broadRpcProxyPolicies = contextCleanupAuthoritative()+ ? await this.listNamespacePoliciesForSafety(config.rpcProxyNamespace)+ : []++ if (contextCleanupAuthoritative()) {+ allContextPolicies = this.mergeSafetyLaneInventory(+ allContextPolicies,+ broadMcpServerPolicies,+ 'context-ingress'+ )+ allContextEgressPolicies = this.mergeSafetyLaneInventory(+ allContextEgressPolicies,+ broadHostPolicies,+ 'context-host-egress'+ )+ allRpcProxyEgressPolicies = this.mergeSafetyLaneInventory(+ allRpcProxyEgressPolicies,+ broadRpcProxyPolicies,+ 'context-rpc-egress'+ )+ }+ if (options.serverInventoryComplete !== false && serverCleanupAuthoritative()) {+ allExternalPolicies = this.mergeSafetyLaneInventory(+ allExternalPolicies,+ broadMcpServerPolicies,+ 'external-egress'+ )+ }safetyPassListedPolicies +=- allContextPolicies.length + allContextEgressPolicies.length + allRpcProxyEgressPolicies.length+ allContextPolicies.length ++ allContextEgressPolicies.length ++ allRpcProxyEgressPolicies.length ++ allExternalPolicies.length// 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(allContextPolicies,- name => this.deletePolicy(name),+ policy =>+ this.deleteSafetyPolicySnapshot(config.namespace, policy, contextCleanupAuthoritative),(name, contextId) =>`[NetPol] Deleting orphaned policy "${name}" (context "${contextId}" no longer exists)`)await cleanupOrphanedContextPolicies(allContextEgressPolicies,- name => this.deleteEgressPolicy(name),+ policy =>+ this.deleteSafetyPolicySnapshot(config.hostNamespace, policy, contextCleanupAuthoritative),name => `[NetPol] Deleting orphaned L2 egress policy "${name}"`)await cleanupOrphanedContextPolicies(allRpcProxyEgressPolicies,- name => this.deletePolicyInNamespace(config.rpcProxyNamespace, name),+ policy =>+ this.deleteSafetyPolicySnapshot(+ config.rpcProxyNamespace,+ policy,+ contextCleanupAuthoritative+ ),name => `[NetPol] Deleting orphaned rpc-proxy egress policy "${name}"`)@@ -989,12 +1286,9 @@ export class NetworkPolicyReconciler {})}- let allExternalPolicies: k8s.V1NetworkPolicy[] = []// Clean up external egress policies for servers that no longer exist.if (options.serverInventoryComplete !== false && serverCleanupAuthoritative()) {const desiredServerNames = new Set(servers.map(s => s.name))- allExternalPolicies = await this.listAllExternalEgressPolicies()- safetyPassListedPolicies += allExternalPolicies.lengthfor (const policy of allExternalPolicies) {const serverName = policy.metadata?.labels?.[MCPSERVER_LABEL]if (!serverName) {@@ -1008,8 +1302,15 @@ export class NetworkPolicyReconciler {console.warn(`[NetPol] Deleting malformed HCC-managed policy "${name}" without ${MCPSERVER_LABEL}`)- await this.deletePolicyInNamespace(config.namespace, name)- recordSafetyPassRevocation()+ if (+ await this.deleteSafetyPolicySnapshot(+ config.namespace,+ policy,+ serverCleanupAuthoritative+ )+ ) {+ recordSafetyPassRevocation()+ }continue}if (!desiredServerNames.has(serverName)) {@@ -1032,8 +1333,15 @@ export class NetworkPolicyReconciler {return}console.log(`[NetPol] Deleting orphaned external egress policy "${name}"`)- await this.deletePolicyInNamespace(config.namespace, name)- recordSafetyPassRevocation()+ if (+ await this.deleteSafetyPolicySnapshot(+ config.namespace,+ policy,+ serverCleanupAuthoritative+ )+ ) {+ recordSafetyPassRevocation()+ }})}}@@ -1098,10 +1406,6 @@ export class NetworkPolicyReconciler {{ operation: 'revoked' },safetyPassRevokedPolicies)- networkPolicySafetyPassDurationSeconds.observe(- { outcome: 'completed' },- (performance.now() - safetyPassStartedAt) / 1_000- )}options.onAuthoritativeRevocationComplete?.()}@@ -1110,44 +1414,64 @@ export class NetworkPolicyReconciler {// by the authoritative inventory has been revoked. A slow or failing// positive effect therefore cannot extend a stale-permission window after// readiness becomes available.+ const additiveFailures: unknown[] = []for (const context of contexts) {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- const contextEffectIsCurrent = (): boolean => {- if (!contextInventoryIsCurrent()) return false- if (!options.resolveCurrentContext) return true- const latest = options.resolveCurrentContext(current.name)- return latest !== undefined && sameContextDesiredRevision(current, latest)- }- await this.reconcileContext(current, { isCurrent: contextEffectIsCurrent })- })+ try {+ await runContextEffect(contextId, async () => {+ const current = options.resolveCurrentContext+ ? options.resolveCurrentContext(context.name)+ : context+ if (!current || current.spec.contextId !== contextId) return+ const contextEffectIsCurrent = (): boolean => {+ if (!contextInventoryIsCurrent()) return false+ if (!options.resolveCurrentContext) return true+ const latest = options.resolveCurrentContext(current.name)+ return latest !== undefined && sameContextDesiredRevision(current, latest)+ }+ await this.reconcileContext(current, { isCurrent: contextEffectIsCurrent })+ })+ } catch (error) {+ additiveFailures.push(error)+ console.error(`[NetPol] Additive Context reconciliation failed for "${contextId}":`, error)+ }}// Refresh and create external egress policies after certification. The- // safety phase above retains structurally valid same-intent DNS policies- // across restart, while changed bindings use make-before-break before- // readiness. This background refresh therefore cannot create a restart-- // induced deny window or preserve a stale allow.+ // safety phase above revokes every DNS-derived allow because its resolved+ // IP set cannot be proven current without a fresh lookup. DNS latency and+ // failure therefore gate only the affected runtime, never global readiness.for (const server of servers) {- await runServerEffect(server.name, async () => {- const current = options.resolveCurrentServer- ? options.resolveCurrentServer(server.name)- : server- if (!current) return- const serverEffectIsCurrent = (): boolean => {- if (!(options.serverInventoryAuthoritative?.() ?? true)) return false- if (!options.resolveCurrentServer) return true- const latest = options.resolveCurrentServer(current.name)- return latest !== undefined && sameMcpServerDesiredRevision(current, latest)- }- await this.reconcileExternalEgress(current, {- isCurrent: serverEffectIsCurrent,+ try {+ await runServerEffect(server.name, async () => {+ const current = options.resolveCurrentServer+ ? options.resolveCurrentServer(server.name)+ : server+ if (!current) return+ const serverEffectIsCurrent = (): boolean => {+ if (!(options.serverInventoryAuthoritative?.() ?? true)) return false+ if (!options.resolveCurrentServer) return true+ const latest = options.resolveCurrentServer(current.name)+ return latest !== undefined && sameMcpServerDesiredRevision(current, latest)+ }+ await this.reconcileExternalEgress(current, {+ isCurrent: serverEffectIsCurrent,+ })})- })+ } catch (error) {+ additiveFailures.push(error)+ console.error(+ `[NetPol] Additive external-egress reconciliation failed for "${server.name}":`,+ error+ )+ }+ }++ if (additiveFailures.length > 0) {+ throw new AggregateError(+ additiveFailures,+ 'One or more additive NetworkPolicy reconciliations failed'+ )}console.log('[NetPol] Full reconciliation complete')@@ -1244,37 +1568,26 @@ export class NetworkPolicyReconciler {}}- private canRetainDnsEgressPolicy(- policy: k8s.V1NetworkPolicy,- server: McpServerCRD,- binding: EgressBinding- ): boolean {- const expectedProtocol = binding.protocol ?? 'TCP'- return (- policy.metadata?.labels?.[MANAGED_BY_LABEL] === MANAGED_BY_VALUE &&- policy.metadata?.labels?.[POLICY_TYPE_LABEL] === EXTERNAL_EGRESS_POLICY_TYPE &&- policy.metadata?.labels?.[MCPSERVER_LABEL] === server.name &&- policy.metadata?.labels?.[EGRESS_CLASS_LABEL] === 'exact-host' &&- policy.spec?.podSelector?.matchLabels?.[MCPSERVER_LABEL] === server.name &&- policy.spec?.policyTypes?.length === 1 &&- policy.spec.policyTypes[0] === 'Egress' &&- (policy.spec.egress?.length ?? 0) > 0 &&- policy.spec.egress!.every(rule => {- const port = rule.ports?.[0]- const cidr = rule.to?.[0]?.ipBlock?.cidr- return (- rule.ports?.length === 1 &&- port !== undefined &&- port.port === binding.port &&- port.protocol === expectedProtocol &&- rule.to?.length === 1 &&- typeof cidr === 'string' &&- cidr.endsWith('/32') &&- isAllowedExternalEgressCidr(cidr) &&- (rule.to[0].ipBlock?.except?.length ?? 0) === 0- )- })- )+ private async resolveExternalEgressDns(hostname: string): Promise<string[]> {+ let timeout: ReturnType<typeof setTimeout> | undefined+ try {+ return await Promise.race([+ dns.resolve4(hostname),+ new Promise<never>((_, reject) => {+ timeout = setTimeout(+ () =>+ reject(+ new Error(+ `DNS resolution timed out after ${config.externalEgressDnsResolveTimeoutMs}ms`+ )+ ),+ config.externalEgressDnsResolveTimeoutMs+ )+ }),+ ])+ } finally {+ if (timeout !== undefined) clearTimeout(timeout)+ }}private async reconcileExternalEgressSafety(@@ -1324,7 +1637,11 @@ export class NetworkPolicyReconciler {}const stale: k8s.V1NetworkPolicy[] = []- let needsMakeBeforeBreak = false+ const unprovableDnsPolicies: k8s.V1NetworkPolicy[] = []+ const deterministicReplacements: Array<{+ snapshot: k8s.V1NetworkPolicy+ desired: k8s.V1NetworkPolicy+ }> = []for (const existing of existingPolicies) {const name = existing.metadata?.nameconst selected = name ? desired.get(name) : undefined@@ -1333,30 +1650,64 @@ export class NetworkPolicyReconciler {continue}desired.delete(name!)- const retainable = selected.policy- ? sameNetworkPolicySpec(existing, selected.policy)- : this.canRetainDnsEgressPolicy(existing, server, selected.binding)+ if (!selected.policy) {+ unprovableDnsPolicies.push(existing)+ continue+ }+ const retainable =+ sameNetworkPolicySpec(existing, selected.policy) &&+ hasExpectedPolicyOwnership(existing, EXTERNAL_EGRESS_POLICY_TYPE)if (!retainable) {- needsMakeBeforeBreak = true+ deterministicReplacements.push({ snapshot: existing, desired: selected.policy })}}- // A desired replacement with a different name must be created before its- // stale predecessor is removed. A purely missing allow has no stale- // permission to revoke and remains additive work after readiness.- if (stale.length > 0 && desired.size > 0) {- needsMakeBeforeBreak = true- }- if (needsMakeBeforeBreak) {- await this.reconcileExternalEgress(server, { isCurrent, existingPolicies })- return isCurrent()+ // Preserve traffic only with deterministic CIDR/public-web policies. A+ // renamed deterministic binding is created before its stale predecessor is+ // removed; a conflict aborts safety rather than adopting the live object.+ if (stale.length > 0) {+ for (const selected of desired.values()) {+ if (!selected.policy) continue+ if (!(await this.createSafetyPolicy(server.namespace, selected.policy, isCurrent))) {+ return false+ }+ }}+ for (const replacement of deterministicReplacements) {+ if (+ !(await this.replaceSafetyPolicySnapshot(+ server.namespace,+ replacement.snapshot,+ replacement.desired,+ 'external-egress',+ isCurrent+ ))+ ) {+ return false+ }+ onRevoked?.()+ }++ // DNS-derived /32s are unprovable without a fresh lookup. Revoke them+ // immediately; replacement belongs to the additive lane and must not put+ // external DNS latency back on the global readiness path.+ await this.cleanupExternalEgress(+ server.name,+ server.namespace,+ unprovableDnsPolicies,+ async () => isCurrent(),+ onRevoked,+ true+ )+ if (!isCurrent()) return false+await this.cleanupExternalEgress(server.name,server.namespace,stale,async () => isCurrent(),- onRevoked+ onRevoked,+ true)return isCurrent()}@@ -1434,7 +1785,8 @@ export class NetworkPolicyReconciler {const desiredPolicyNames = new Set<string>()const resolvedEgressIPs: McpServerResolvedEgressIP[] = []const failures: string[] = []- const resolvedAt = new Date().toISOString()+ const resolvedAtMs = Date.now()+ const resolvedAt = new Date(resolvedAtMs).toISOString()for (const binding of bindings) {if (!isCurrent()) return@@ -1504,7 +1856,7 @@ export class NetworkPolicyReconciler {continue}try {- const ips = await dns.resolve4(binding.dns)+ const ips = await this.resolveExternalEgressDns(binding.dns)if (!isCurrent()) returnconst uniqueIps = [...new Set(ips)].sort()if (uniqueIps.length === 0) {@@ -1529,14 +1881,6 @@ export class NetworkPolicyReconciler {resolvedEgressIPs.push({ dns: binding.dns, ips: uniqueIps, resolvedAt })console.log(`[NetPol] Resolved ${binding.dns} → [${cidrs.join(', ')}]`)} catch (err) {- const certifiedExisting = existingPolicies.find(- policy =>- policy.metadata?.name === name &&- this.canRetainDnsEgressPolicy(policy, server, binding)- )- if (certifiedExisting !== undefined) {- desiredPolicyNames.add(name)- }failures.push(`failed to resolve hostname "${binding.dns}": ${this.errorMessage(err)}`)continue}@@ -1545,11 +1889,12 @@ export class NetworkPolicyReconciler {}desiredPolicyNames.add(name)+ const desiredPolicy = this.buildExactHostEgressPolicy(server, name, binding, cidrs)await applyNetworkPolicy(this.networkingApi,name,server.namespace,- this.buildExactHostEgressPolicy(server, name, binding, cidrs),+ desiredPolicy,'[NetPol]',isCurrent)@@ -1563,7 +1908,8 @@ export class NetworkPolicyReconciler {const name = policy.metadata?.namereturn Boolean(name) && !desiredPolicyNames.has(name!)}),- async () => isCurrent()+ async () => isCurrent(),+ options.onRevoked)} catch (error) {if (!isCurrent()) return@@ -1612,7 +1958,8 @@ export class NetworkPolicyReconciler {namespace: string,policies?: k8s.V1NetworkPolicy[],deleteAllowed?: () => Promise<boolean>,- onDeleted?: () => void+ onDeleted?: () => void,+ requireSnapshotIdentity = false): Promise<void> {const policiesToDelete =policies ?? (await this.listExternalEgressPoliciesForServer(serverName, namespace))@@ -1622,9 +1969,15 @@ export class NetworkPolicyReconciler {if (!name) continuetry {if (deleteAllowed && !(await deleteAllowed())) return- await this.networkingApi.deleteNamespacedNetworkPolicy({ name, namespace })- console.log(`[NetPol] Deleted external egress policy "${name}"`)- onDeleted?.()+ const deleted = requireSnapshotIdentity+ ? await this.deleteSafetyPolicySnapshot(namespace, policy)+ : await this.networkingApi+ .deleteNamespacedNetworkPolicy({ name, namespace })+ .then(() => true)+ if (deleted) {+ console.log(`[NetPol] Deleted external egress policy "${name}"`)+ onDeleted?.()+ }} catch (error: unknown) {if (getErrorCode(error) !== 404) {console.error(`[NetPol] Failed to delete external egress policy "${name}":`, error)@@ -1879,6 +2232,47 @@ export class NetworkPolicyReconciler {}}+ /** Broad, namespace-bounded inventory used only by the safety pass. */+ private async listNamespacePoliciesForSafety(namespace: string): Promise<k8s.V1NetworkPolicy[]> {+ try {+ const response = await this.networkingApi.listNamespacedNetworkPolicy({ namespace })+ return response.items || []+ } catch (error) {+ console.error(`[NetPol] Failed to list broad NetworkPolicy inventory in ${namespace}:`, error)+ throw error+ }+ }++ private mergeSafetyLaneInventory(+ selected: k8s.V1NetworkPolicy[],+ broad: k8s.V1NetworkPolicy[],+ lane: SafetyInventoryLane+ ): k8s.V1NetworkPolicy[] {+ const result = new Map<string, k8s.V1NetworkPolicy>()+ const keyFor = (policy: k8s.V1NetworkPolicy, index: number): string =>+ policy.metadata?.uid ?? policy.metadata?.name ?? `unnamed-${index}`++ selected.forEach((policy, index) => result.set(keyFor(policy, index), policy))+ broad.forEach((policy, index) => {+ const classification = classifySafetyInventoryPolicy(policy, lane)+ if (classification === 'ambiguous') {+ const name = policy.metadata?.name ?? '<unnamed>'+ throw new Error(+ `Ambiguous NetworkPolicy ownership for reserved HCC ${lane} policy "${name}"`+ )+ }+ if (classification === 'owned' || classification === 'repairable') {+ result.set(keyFor(policy, selected.length + index), policy)+ } else {+ // The broad LIST is later and authoritative for this object identity.+ // Do not retain a selector snapshot after the same object was relabelled+ // out of HCC ownership.+ result.delete(keyFor(policy, selected.length + index))+ }+ })+ return [...result.values()]+ }+/** List all L2 context-allow egress policies in the mcp-host namespace. */private async listAllContextEgressPolicies(): Promise<k8s.V1NetworkPolicy[]> {try {@@ -1935,6 +2329,114 @@ export class NetworkPolicyReconciler {)}+ private safetyPolicyIdentity(policy: k8s.V1NetworkPolicy): {+ name: string+ uid: string+ resourceVersion: string+ } {+ const name = policy.metadata?.name+ const uid = policy.metadata?.uid+ const resourceVersion = policy.metadata?.resourceVersion+ if (!name || !uid || !resourceVersion) {+ throw new Error(+ `NetworkPolicy safety mutation requires name, uid, and resourceVersion for "${name ?? '<unnamed>'}"`+ )+ }+ return { name, uid, resourceVersion }+ }++ /**+ * Delete exactly the policy version classified by the authoritative safety+ * inventory. Kubernetes rejects the preconditions if the name was recreated+ * or changed after LIST, so HCC cannot delete a new or foreign object.+ */+ private async deleteSafetyPolicySnapshot(+ namespace: string,+ policy: k8s.V1NetworkPolicy,+ isCurrent?: () => boolean+ ): Promise<boolean> {+ if (isCurrent && !isCurrent()) return false+ const { name, uid, resourceVersion } = this.safetyPolicyIdentity(policy)+ try {+ await this.networkingApi.deleteNamespacedNetworkPolicy({+ name,+ namespace,+ body: { preconditions: { uid, resourceVersion } },+ })+ console.log(`[NetPol] Deleted safety-inventory policy "${name}" in ${namespace}`)+ return true+ } catch (error: unknown) {+ if (getErrorCode(error) === 404) {+ console.log(`[NetPol] Safety-inventory policy "${name}" already gone`)+ return true+ }+ console.error(+ `[NetPol] Failed identity-bound delete of safety-inventory policy "${name}" in ${namespace}:`,+ error+ )+ throw error+ }+ }++ /**+ * Replace only the exact live object classified by the safety inventory.+ * The fresh read closes ownership drift before mutation; resourceVersion on+ * the replace body closes the remaining read-to-write race.+ */+ private async replaceSafetyPolicySnapshot(+ namespace: string,+ snapshot: k8s.V1NetworkPolicy,+ desired: k8s.V1NetworkPolicy,+ lane: SafetyInventoryLane,+ isCurrent: () => boolean+ ): Promise<boolean> {+ if (!isCurrent()) return false+ const expected = this.safetyPolicyIdentity(snapshot)+ const live = await this.networkingApi.readNamespacedNetworkPolicy({+ name: expected.name,+ namespace,+ })+ if (!isCurrent()) return false+ const actual = this.safetyPolicyIdentity(live)+ const classification = classifySafetyInventoryPolicy(live, lane)+ if (+ actual.uid !== expected.uid ||+ actual.resourceVersion !== expected.resourceVersion ||+ (classification !== 'owned' && classification !== 'repairable')+ ) {+ throw new Error(+ `NetworkPolicy "${expected.name}" changed identity or ownership after the authoritative safety inventory`+ )+ }+ await this.networkingApi.replaceNamespacedNetworkPolicy({+ name: expected.name,+ namespace,+ body: {+ ...desired,+ metadata: {+ ...desired.metadata,+ name: expected.name,+ namespace,+ resourceVersion: actual.resourceVersion,+ },+ },+ })+ return isCurrent()+ }++ private async createSafetyPolicy(+ namespace: string,+ desired: k8s.V1NetworkPolicy,+ isCurrent: () => boolean+ ): Promise<boolean> {+ if (!isCurrent()) return false+ await this.networkingApi.createNamespacedNetworkPolicy({+ namespace,+ body: desired,+ })+ return isCurrent()+ }+/** Delete a NetworkPolicy in mcp-server namespace. */private async deletePolicy(name: string, isCurrent?: () => boolean): Promise<void> {try {diff --git a/host-context-controller/src/reconciler.test.ts b/host-context-controller/src/reconciler.test.tsindex 52916065b..bef186be2 100644--- a/host-context-controller/src/reconciler.test.ts+++ b/host-context-controller/src/reconciler.test.ts@@ -167,24 +167,53 @@ describe('Reconciler managed:false guard (Risk 1.7)', () => {expect(appsApi.createNamespacedDeployment).toHaveBeenCalled()})- it('canonicalizes a remote proxy image without mutating the authoritative cache object', async () => {+ it('completes a remote proxy reconcile without rewriting the desired image', async () => {const server = makeServer({name: 'remote-api',image: 'vendor/original-image:1',remote: { baseUrl: 'https://api.example.com' },})const originalSpec = structuredClone(server.spec)+ let desiredRevisionIsCurrent = true+ customApi.patchNamespacedCustomObject.mockImplementation(+ ({ body }: { body?: { spec?: unknown } }) => {+ if (body?.spec !== undefined) {+ desiredRevisionIsCurrent = false+ }+ return Promise.resolve({})+ }+ )- await reconciler.reconcile(server)+ await reconciler.reconcile(server, {+ isCurrent: () => desiredRevisionIsCurrent,+ })expect(server.spec).toEqual(originalSpec)- expect(customApi.patchNamespacedCustomObject).toHaveBeenCalledWith(- expect.objectContaining({- name: 'remote-api',- body: { spec: { image: 'clerum/nginx-egress-proxy:test' } },- }),+ expect(customApi.patchNamespacedCustomObject).not.toHaveBeenCalledWith(+ expect.objectContaining({ body: expect.objectContaining({ spec: expect.anything() }) }),expect.anything())+ expect(coreApi.createNamespacedConfigMap).toHaveBeenCalledOnce()+ expect(coreApi.createNamespacedService).toHaveBeenCalledOnce()+ expect(appsApi.createNamespacedDeployment).toHaveBeenCalledOnce()+ expect(appsApi.createNamespacedDeployment).toHaveBeenCalledWith(+ expect.objectContaining({+ body: expect.objectContaining({+ spec: expect.objectContaining({+ template: expect.objectContaining({+ spec: expect.objectContaining({+ containers: [+ expect.objectContaining({+ name: 'egress-proxy',+ image: 'clerum/nginx-egress-proxy:test',+ }),+ ],+ }),+ }),+ }),+ }),+ })+ )})it('should log WRC-owned ownership when managed: false', async () => {diff --git a/host-context-controller/src/reconciler.ts b/host-context-controller/src/reconciler.tsindex b1664c887..99ffc1a25 100644--- a/host-context-controller/src/reconciler.ts+++ b/host-context-controller/src/reconciler.ts@@ -1478,92 +1478,6 @@ ${authHeaderLines ? '\n # ── Credential auth headers (envsubst-resolv)}- /**- * Keep remote egress proxy CRDs aligned with the platform-owned runtime image.- *- * Remote servers are rendered as nginx egress proxies and never run- * `server.spec.image`, but stale CR specs can mislead scanners or future- * tooling. Patch only the declarative image field; Deployment rendering still- * uses `config.egressProxyImage` as the authority.- *- * This stays internally non-throwing because image canonicalization is- * best-effort cleanup; a failed CRD patch must not block ConfigMap,- * Service, or Deployment reconciliation for the actual proxy runtime.- */- private async canonicalizeRemoteEgressProxyImage(- server: McpServerCRD,- isCurrent: () => boolean = () => true- ): Promise<void> {- if (!isCurrent()) return- if (!this.isRemote(server)) {- return- }- if (server.spec.image === config.egressProxyImage) {- await this.writeStatusCondition(- server,- {- type: 'ImageCanonicalized',- status: 'True',- reason: 'RemoteEgressProxyImageMatches',- message: 'Remote McpServer spec.image matches the platform egress proxy image',- },- isCurrent- )- return- }-- try {- if (!isCurrent()) return- await this.customApi.patchNamespacedCustomObject(- {- group: 'clerum.io',- version: 'v1alpha1',- namespace: server.namespace,- plural: 'mcpservers',- name: server.name,- body: {- spec: {- image: config.egressProxyImage,- },- },- },- {- middleware: [k8s.setHeaderMiddleware('Content-Type', 'application/merge-patch+json')],- }- )- if (!isCurrent()) return- console.log(- `[Reconciler] Canonicalized remote McpServer "${server.name}" image to ${config.egressProxyImage}`- )- await this.writeStatusCondition(- server,- {- type: 'ImageCanonicalized',- status: 'True',- reason: 'RemoteEgressProxyImageMatches',- message: 'Remote McpServer spec.image matches the platform egress proxy image',- },- isCurrent- )- } catch (err) {- if (!isCurrent()) return- console.warn(- `[Reconciler] Failed to canonicalize remote McpServer "${server.name}" image to ${config.egressProxyImage}:`,- err- )- await this.writeStatusCondition(- server,- {- type: 'ImageCanonicalized',- status: 'False',- reason: 'RemoteEgressProxyImagePatchFailed',- message: 'Failed to patch remote McpServer spec.image to the platform egress proxy image',- },- isCurrent- )- }- }-/*** G11: Update status conditions on McpServer CRD.* Sets NetworkReady and DeploymentReady conditions so WRC can watch@@ -1925,8 +1839,10 @@ ${authHeaderLines ? '\n # ── Credential auth headers (envsubst-resolvtry {// Remote egress proxy: create nginx ConfigMap before Deploymentif (this.isRemote(server)) {- await this.canonicalizeRemoteEgressProxyImage(server, isCurrent)- if (!isCurrent()) return+ // The CRD image remains desired-state input owned by its author. Remote+ // workloads use the platform-owned proxy image selected in+ // buildDeployment(); rewriting spec.image here would bump generation+ // and retire this reconcile before it can create the runtime resources.await this.ensureConfigMap(server, isCurrent)} else {// Phase 2.3: plugin image-host allowlist. Audit mode (default) logs adiff --git a/host-context-controller/src/types.ts b/host-context-controller/src/types.tsindex 56924fdbc..552ed3f0f 100644--- a/host-context-controller/src/types.ts+++ b/host-context-controller/src/types.ts@@ -350,6 +350,8 @@ export interface ContextStatus {export interface ContextCRD {name: stringnamespace: string+ uid?: string+ generation?: numberspec: ContextSpecstatus?: ContextStatus}diff --git a/host-context-controller/test/hostReconciler.heartbeat.test.ts b/host-context-controller/test/hostReconciler.heartbeat.test.tsindex 885477b13..5ab73f48f 100644--- a/host-context-controller/test/hostReconciler.heartbeat.test.ts+++ b/host-context-controller/test/hostReconciler.heartbeat.test.ts@@ -932,6 +932,44 @@ describe('HostReconciler heartbeat mutation admission', () => {})describe('HostReconciler.suspendHostFromHeartbeat', () => {+ it('does not mutate the admitted watch-cache snapshot while applying a suspension', async () => {+ const { reconciler, customApi } = createReconciler()+ const host = makeStatelessHost({+ status: { lifecycle: { state: 'draining', wakeHandledGeneration: 2 } },+ })+ host.uid = 'stateless-host-uid'+ host.generation = 1+ host.resourceVersion = 'cache-rv'+ const snapshot = structuredClone(host)+ Object.freeze(host)+ reconciler.setResolveCurrentHost(name => (name === host.name ? host : undefined))+ reconciler.setHostMutationAuthority(() => ({+ known: true,+ hostGeneration: 1,+ contextGeneration: 1,+ }))+ const draining = freshHostRead({ state: 'draining', wakeHandledGeneration: 2 })+ Object.assign(draining.metadata, {+ uid: host.uid,+ generation: host.generation,+ resourceVersion: 'draining-rv',+ })+ const suspended = freshHostRead({+ state: 'suspended',+ wakeHandledGeneration: 2,+ reason: 'idle',+ })+ Object.assign(suspended.metadata, {+ uid: host.uid,+ generation: host.generation,+ resourceVersion: 'suspended-rv',+ })+ customApi.getNamespacedCustomObject.mockResolvedValueOnce(draining).mockResolvedValue(suspended)++ await expect(reconciler.suspendHostFromHeartbeat(host, 'idle', 2)).resolves.toBe('suspended')+ expect(host).toEqual(snapshot)+ })+it("writes state='suspended' + reason 'idle' durably, then reconciles to replicas=0", async () => {const { reconciler, appsApi, customApi } = createReconciler()const host = makeStatelessHost({diff --git a/mcp-host/package-lock.json b/mcp-host/package-lock.jsonindex a003ab769..65762d649 100644--- a/mcp-host/package-lock.json+++ b/mcp-host/package-lock.json@@ -1,12 +1,12 @@{"name": "clerum-mcp-host",- "version": "0.1.215",+ "version": "0.1.216","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "clerum-mcp-host",- "version": "0.1.215",+ "version": "0.1.216","license": "SEE LICENSE IN LICENSE","dependencies": {"@anthropic-ai/sdk": "^0.32.0",diff --git a/mcp-host/package.json b/mcp-host/package.jsonindex fd8da4977..496b24415 100644--- a/mcp-host/package.json+++ b/mcp-host/package.json@@ -1,6 +1,6 @@{"name": "clerum-mcp-host",- "version": "0.1.215",+ "version": "0.1.216","description": "MCP Host - reads Host CRD and provides LLM access via OpenAI/Claude","main": "dist/main.js","engines": {diff --git a/mcp-host/src/__tests__/main.mcpInitialization.test.ts b/mcp-host/src/__tests__/main.mcpInitialization.test.tsindex 2aa2dde99..a4e13588b 100644--- a/mcp-host/src/__tests__/main.mcpInitialization.test.ts+++ b/mcp-host/src/__tests__/main.mcpInitialization.test.ts@@ -1640,7 +1640,7 @@ describe('reconcileAuthoritativeMcpSnapshot', () => {})- it('retains legacy fail-closed teardown when status authority is undefined', async () => {+ it('preserves the legacy fail-closed revocation contract when HCC omits authoritative', async () => {const previous = readyServer()const legacyNotReady = readyServer({status: { deployed: false, ready: false, message: 'Deployment not ready' },@@ -1663,7 +1663,12 @@ describe('reconcileAuthoritativeMcpSnapshot', () => {})expect(manager.removeServer).toHaveBeenCalledWith(previous.name)- expect(manager.addServer).toHaveBeenCalledWith(legacyNotReady, undefined, expect.any(Object))+ expect(manager.addServer).toHaveBeenCalledWith(+ legacyNotReady,+ undefined,+ expect.objectContaining({ isCurrent: expect.any(Function) })+ )+ expect(serverState.get(previous.name)).toBe(JSON.stringify(legacyNotReady))})it('admits an unconnected server when its observed readiness becomes true', async () => {diff --git a/mcp-host/src/contextMapperClient.test.ts b/mcp-host/src/contextMapperClient.test.tsindex 28d0aae67..ddb1e23cc 100644--- a/mcp-host/src/contextMapperClient.test.ts+++ b/mcp-host/src/contextMapperClient.test.ts@@ -13,7 +13,10 @@ describe('ContextMapperClient readiness and discovery', () => {const client = new ContextMapperClient('http://context-mapper.test')await expect(client.healthCheck()).resolves.toBe(true)- expect(fetchMock).toHaveBeenCalledWith('http://context-mapper.test/ready')+ expect(fetchMock).toHaveBeenCalledWith(+ 'http://context-mapper.test/ready',+ expect.objectContaining({ signal: expect.any(AbortSignal) })+ )})it('rejects an HTTP 503 during initial discovery instead of returning an empty fleet', async () => {@@ -62,6 +65,14 @@ describe('ContextMapperClient readiness and discovery', () => {await expect(client.listServersByContext('production')).resolves.toEqual([])})++ it('does not convert a failed all-server request into an authoritative empty fleet', async () => {+ const networkError = new Error('connection reset')+ vi.stubGlobal('fetch', vi.fn().mockRejectedValue(networkError))+ const client = new ContextMapperClient('http://context-mapper.test')++ await expect(client.listAllServers()).rejects.toBe(networkError)+ })})describe('ContextMapperClient.pollServers', () => {@@ -96,6 +107,27 @@ describe('ContextMapperClient.pollServers', () => {await expect(client.pollServers('production')).rejects.toBe(networkError)})+ it('bounds a silent HCC request so authoritative polling cannot stall indefinitely', async () => {+ vi.stubGlobal(+ 'fetch',+ vi.fn().mockImplementation((_url: string, init?: RequestInit) => {+ return new Promise((_resolve, reject) => {+ const signal = init?.signal+ if (!signal) return+ signal.addEventListener(+ 'abort',+ () =>+ reject(signal.reason ?? new DOMException('The operation was aborted', 'AbortError')),+ { once: true }+ )+ })+ })+ )+ const client = new ContextMapperClient('http://context-mapper.test', 10)++ await expect(client.pollServers('production')).rejects.toMatchObject({ name: 'TimeoutError' })+ })+it('accepts an HTTP 200 empty fleet as an authoritative deletion snapshot', async () => {vi.stubGlobal('fetch',diff --git a/mcp-host/src/contextMapperClient.ts b/mcp-host/src/contextMapperClient.tsindex bb2fdba3f..6aeefb5d0 100644--- a/mcp-host/src/contextMapperClient.ts+++ b/mcp-host/src/contextMapperClient.ts@@ -18,14 +18,24 @@ export interface AuthTokenResponse {message?: string}+const DEFAULT_CONTEXT_MAPPER_REQUEST_TIMEOUT_MS = 10_000+/*** Context Mapper client.*/export class ContextMapperClient {private baseUrl: string+ private requestTimeoutMs: number- constructor(baseUrl: string) {+ constructor(baseUrl: string, requestTimeoutMs = DEFAULT_CONTEXT_MAPPER_REQUEST_TIMEOUT_MS) {this.baseUrl = baseUrl.replace(/\/$/, '') // Remove trailing slash+ this.requestTimeoutMs = requestTimeoutMs+ }++ private fetch(input: string): Promise<Response> {+ return fetch(input, {+ signal: AbortSignal.timeout(this.requestTimeoutMs),+ })}/**@@ -33,7 +43,7 @@ export class ContextMapperClient {*/async healthCheck(): Promise<boolean> {try {- const response = await fetch(`${this.baseUrl}/ready`)+ const response = await this.fetch(`${this.baseUrl}/ready`)return response.ok} catch (error) {console.error('[ContextMapper] Health check failed:', error)@@ -43,24 +53,21 @@ export class ContextMapperClient {/*** List all McpServers.+ * Rejects transport and HTTP failures so a future caller cannot confuse an+ * unavailable controller with an authoritative empty fleet.*/async listAllServers(): Promise<McpServerInfo[]> {- try {- console.log('[ContextMapper] Fetching all McpServers')-- const response = await fetch(`${this.baseUrl}/api/v1/mcpservers`)+ console.log('[ContextMapper] Fetching all McpServers')- if (!response.ok) {- throw new Error(`HTTP ${response.status}: ${response.statusText}`)- }+ const response = await this.fetch(`${this.baseUrl}/api/v1/mcpservers`)- const data = (await response.json()) as McpServersResponse- console.log(`[ContextMapper] Found ${data.servers.length} McpServer(s)`)- return data.servers- } catch (error) {- console.error('[ContextMapper] Failed to list servers:', error)- return []+ if (!response.ok) {+ throw new Error(`HTTP ${response.status}: ${response.statusText}`)}++ const data = (await response.json()) as McpServersResponse+ console.log(`[ContextMapper] Found ${data.servers.length} McpServer(s)`)+ return data.servers}/**@@ -71,7 +78,7 @@ export class ContextMapperClient {async listServersByContext(contextRef: string): Promise<McpServerInfo[]> {console.log(`[ContextMapper] Fetching McpServers for context: ${contextRef}`)- const response = await fetch(+ const response = await this.fetch(`${this.baseUrl}/api/v1/mcpservers/context/${encodeURIComponent(contextRef)}`)@@ -93,7 +100,7 @@ export class ContextMapperClient {async getAuthToken(serverName: string): Promise<string | undefined> {console.log(`[ContextMapper] Fetching auth token for server: ${serverName}`)- const response = await fetch(+ const response = await this.fetch(`${this.baseUrl}/api/v1/mcpservers/${encodeURIComponent(serverName)}/auth`)@@ -119,7 +126,7 @@ export class ContextMapperClient {* unavailable controller as an authoritative empty inventory.*/async pollServers(contextRef: string): Promise<{ servers: McpServerInfo[]; timestamp: string }> {- const response = await fetch(+ const response = await this.fetch(`${this.baseUrl}/api/v1/mcpservers/context/${encodeURIComponent(contextRef)}`)diff --git a/mcp-host/src/main.ts b/mcp-host/src/main.tsindex cad8c1607..9ae322c02 100644--- a/mcp-host/src/main.ts+++ b/mcp-host/src/main.ts@@ -829,7 +829,11 @@ async function initializeMcpServers(contextRef: string): Promise<void> {throw new Error('MCP manager was not installed after authoritative discovery')}const connectedServers = mcpManager.getConnectedServers()- console.log(`[Main] Connected to ${connectedServers.length} MCP server(s)`)+ console.log(+ config.devMode+ ? `[Main] Connected to ${connectedServers.length} MCP server(s)`+ : `[Main] Published the initial MCP fleet manager with ${connectedServers.length} currently connected server(s); background reconciliation may still be in progress`+ )if (connectedServers.length > 0) {const tools = mcpManager.getAllTools()diff --git a/mcp-host/src/mcp/authoritativeFleet.ts b/mcp-host/src/mcp/authoritativeFleet.tsindex 9c3c5aa3d..523fc60d5 100644--- a/mcp-host/src/mcp/authoritativeFleet.ts+++ b/mcp-host/src/mcp/authoritativeFleet.ts@@ -798,9 +798,9 @@ export async function reconcileAuthoritativeMcpSnapshot(options: {}if (!server.status?.ready) {- // An authoritative ready=false, and a legacy ready=false with no- // authority marker, retain the existing fail-closed behavior. Re-adding- // a not-ready server does not connect; it updates observed status.+ // Explicit authoritative ready=false and legacy ready=false both revoke.+ // Only the negotiated authoritative=false state preserves a live+ // connection; field absence must retain the legacy fail-closed contract.if (connectedNames.has(server.name)) {await options.manager.removeServer(server.name)}diff --git a/nginx-egress-proxy/README.md b/nginx-egress-proxy/README.mdindex b4c205974..372f8e5aa 100644--- a/nginx-egress-proxy/README.md+++ b/nginx-egress-proxy/README.md@@ -53,10 +53,10 @@ reference is platform-controlled:| `CONTEXT_MAPPER_EGRESS_PROXY_IMAGE` | host-context-controller | `clerum/nginx-egress-proxy:0.1.0` || `CONTROL_API_REMOTE_MCP_EGRESS_PROXY_IMAGE` | control-api (registry install stamps `spec.image` for remote entries) | `clerum/nginx-egress-proxy:0.1.0` |-HCC additionally canonicalizes `spec.image` of remote McpServers back to the-platform image (`canonicalizeRemoteEgressProxyImage`) as best-effort cleanup;-the enforcement is that Deployment rendering always stamps the configured-platform image, so a CRD's `spec.image` is never what runs.+HCC does not rewrite `spec.image` during reconciliation: that field remains+desired state owned by the CRD author. Deployment rendering always stamps the+configured platform image for remote egress proxies, so a remote CRD's+`spec.image` is never what runs.## Portsdiff --git a/scripts/e2e/e2e-hcc-communicationchannel-watch-recovery.sh b/scripts/e2e/e2e-hcc-communicationchannel-watch-recovery.shindex 42bfee3e2..480b9abd9 100755--- a/scripts/e2e/e2e-hcc-communicationchannel-watch-recovery.sh+++ b/scripts/e2e/e2e-hcc-communicationchannel-watch-recovery.sh@@ -35,7 +35,8 @@ command -v jq >/dev/null 2>&1 || { echo "jq is required" >&2; exit 1; }exit 1}kctl get nodes -o json | jq -e \- 'any(.items[]; .metadata.labels["minikube.k8s.io/name"] != null)' >/dev/null || {+ --arg context "$E2E_KUBECONTEXT" \+ 'any(.items[]; .metadata.labels["minikube.k8s.io/name"] == $context)' >/dev/null || {echo "Refusing HCC fault injection: target is not a minikube cluster." >&2exit 1}@@ -62,7 +63,7 @@ HCC_LOG_BUFFER="$(mktemp "${TMPDIR:-/tmp}/hcc-watch-stream.XXXXXX")"NON_FIXTURE_BASELINE="$(mktemp "${TMPDIR:-/tmp}/hcc-watch-baseline.XXXXXX")"NON_FIXTURE_AFTER="$(mktemp "${TMPDIR:-/tmp}/hcc-watch-after.XXXXXX")"CLEANUP_KINDS="deployments,services,secrets,serviceaccounts,roles,rolebindings,networkpolicies,persistentvolumeclaims"-START_TIME="" HCC_UID="" HCC_RESTARTS="" CONTROL_IDENTITY=""+START_TIME="" HCC_UID="" HCC_RESTARTS="" CONTROL_IDENTITY="" ORIGINAL_REPLICAS=""HCC_LOG_STREAM_PID=""# Mirrors COMMUNICATION_CHANNEL_CACHE_RECOVERY_RETRY_MS in k8sClient.ts.CC_RECOVERY_RETRY_SECONDS=5@@ -87,8 +88,10 @@ print_hcc_proxy_rollout_diagnostics() {kctl get pods -n "$HCC_NS" -l "app=${HCC_DEPLOY}" -o json |jq -r '.items[] |+ .metadata.name as $pod |+ .status.phase as $phase |.status.containerStatuses[]? |- "pod=\(.metadata.name) phase=\(.status.phase // "unknown") ready=\(.ready) restarts=\(.restartCount) waiting=\(.state.waiting.reason // "none") terminated=\(.state.terminated.reason // "none") exitCode=\(.state.terminated.exitCode // "none") lastTerminated=\(.lastState.terminated.reason // "none") lastExitCode=\(.lastState.terminated.exitCode // "none")"+ "pod=\($pod) phase=\($phase // "unknown") ready=\(.ready) restarts=\(.restartCount) waiting=\(.state.waiting.reason // "none") terminated=\(.state.terminated.reason // "none") exitCode=\(.state.terminated.exitCode // "none") lastTerminated=\(.lastState.terminated.reason // "none") lastExitCode=\(.lastState.terminated.exitCode // "none")"' >&2 || truewhile IFS= read -r pod; do@@ -154,6 +157,8 @@ cleanup() {elsecleanup_failed=1print_hcc_repair_instructions+ echo " kubectl --context=${E2E_KUBECONTEXT} -n ${HCC_NS} scale deployment/${HCC_DEPLOY} --replicas=${ORIGINAL_REPLICAS:-1}" >&2+ echo " kubectl --context=${E2E_KUBECONTEXT} -n ${HCC_NS} rollout status deployment/${HCC_DEPLOY} --timeout=180s" >&2fifinalize_hcc_watch_gate_lock "$cleanup_failed" "$restore_ok" || cleanup_failed=1rm -f "$HCC_LOG_BUFFER" "$NON_FIXTURE_BASELINE" "$NON_FIXTURE_AFTER"@@ -171,6 +176,11 @@ header "HCC CommunicationChannel watch recovery"require_branch_owned_hcc_gateacquire_hcc_watch_gate_lock || die "another HCC watch-recovery gate owns this profile"kctl get deployment "$HCC_DEPLOY" -n "$HCC_NS" >/dev/null+ORIGINAL_REPLICAS="$(+ kctl get deployment "$HCC_DEPLOY" -n "$HCC_NS" -o jsonpath='{.spec.replicas}'+)"+[ "$ORIGINAL_REPLICAS" = 1 ] ||+ die "expected exactly one HCC replica, found ${ORIGINAL_REPLICAS:-unknown}"kctl get host "$SOURCE_HOST" -n "$HOST_NS" >/dev/nullhost_override="$(kctl get deployment "$HCC_DEPLOY" -n "$HCC_NS" \diff --git a/scripts/e2e/e2e-hcc-mcp-context-readiness.sh b/scripts/e2e/e2e-hcc-mcp-context-readiness.shindex d68ab1719..959006129 100755--- a/scripts/e2e/e2e-hcc-mcp-context-readiness.sh+++ b/scripts/e2e/e2e-hcc-mcp-context-readiness.sh@@ -5,13 +5,14 @@# The gate runs only on an exact-HEAD, branch-owned Minikube profile. It routes# HCC DNS through an isolated in-cluster proxy that forwards every query except# one fixture hostname. The gate first lets HCC create a real external-egress-# policy. A same-intent restart then holds DNS through a real retry and proves-# the certified policy keeps the same UID/spec while HCC remains Ready. A-# second phase changes that binding's protocol while HCC is stopped; holding-# DNS now proves the divergent allow is revoked and HCC remains unready until-# the UDP replacement exists. A real Context watch update must still converge-# its three NetworkPolicies during that hold. The fleet is wider than the-# bounded worker width, covering the original large-fleet symptom.+# policy. A same-intent restart then proves the safety pass revokes that+# DNS-derived allow without attempting DNS and certifies global readiness while+# the affected runtime stays blocked. DNS release lets the additive lane create+# the current TCP policy and runtime. A second phase changes that binding's+# protocol while HCC is stopped and proves the same contract for TCP-to-UDP+# replacement. A real Context watch update still converges its three+# NetworkPolicies. The fleet is wider than the bounded worker width, covering+# the original large-fleet symptom.set -euo pipefailSCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"@@ -82,7 +83,6 @@ NEW_HCC_POD=""HCC_UID=""HCC_RESTARTS=""HCC_PORT=""-CERTIFIED_POLICY_IDENTITY=""HCC_MUTATED=0DNS_BLOCKER_CREATED=0MCP_CREATED=0@@ -99,6 +99,7 @@ HCC_GATE_LOCK_NAME=""HCC_GATE_LOCK_UID=""# shellcheck disable=SC2034HCC_GATE_FINALIZATION_FAILURE=""+HCC_READY_PROBE_DIAGNOSTIC=""[[ "$MCP_FLEET_SIZE" =~ ^[0-9]+$ ]] && [ "$MCP_FLEET_SIZE" -gt 10 ] &&[ "$MCP_FLEET_SIZE" -le 24 ] || {@@ -183,6 +184,20 @@ hcc_log_contains() {grep -Fq "$marker" <<<"$logs"}+hcc_log_count() {+ local marker=$1 logs+ [ -n "$NEW_HCC_POD" ] || return 1+ logs="$(kctl logs "pod/${NEW_HCC_POD}" -n "$HCC_NS" \+ -c host-context-controller 2>/dev/null)" || return 1+ grep -Fc "$marker" <<<"$logs" || true+}++hcc_log_count_exceeds() {+ local marker=$1 baseline=$2 current+ current="$(hcc_log_count "$marker")" || return 1+ [ "$current" -gt "$baseline" ]+}+dns_log_contains() {local marker=$1 logslogs="$(kctl logs "deployment/${DNS_BLOCKER_NAME}" -n "$HCC_NS" 2>/dev/null)" ||@@ -226,14 +241,19 @@ initial_network_policy_retry_progress_is_observed() {}external_egress_retry_progress_is_observed() {- local logs+ local logs marker[ -n "$NEW_HCC_POD" ] || return 1logs="$(kctl logs "pod/${NEW_HCC_POD}" -n "$HCC_NS" \-c host-context-controller 2>/dev/null)" || return 1+ marker="Scheduling external egress retry "grep -Fq \"Initial external egress reconciliation failed for ${MCP_NS}/${MCP_NAME};" <<<"$logs" &&- grep -Fq "Scheduling external egress retry " <<<"$logs" &&- grep -Fq "for McpServer \"${MCP_NAME}\"" <<<"$logs"+ awk \+ -v marker="$marker" \+ -v server="for McpServer \"${MCP_NAME}\"" '+ index($0, marker) && index($0, server) { found = 1 }+ END { exit found ? 0 : 1 }+ ' <<<"$logs"}external_egress_retry_rearmed_is_observed() {@@ -298,18 +318,37 @@ fixture_runtime_absent() {resource_absent service "$MCP_NAME" "$MCP_NS"}-fixture_runtime_and_ready_absent() {- fixture_runtime_absent &&- kctl get mcpserver "$MCP_NAME" -n "$MCP_NS" -o json 2>/dev/null |+mcpserver_current_ready() {+ local name=$1+ kctl get mcpserver "$name" -n "$MCP_NS" -o json 2>/dev/null |jq -e '+ .metadata.generation as $generation |any(.status.conditions[]?;.type == "Ready" and .status == "True" and- (.observedGeneration // -1) == .metadata.generation- ) | not+ (.observedGeneration // -1) == $generation+ )' >/dev/null}+mcpserver_current_ready_absent() {+ local name=$1 resource+ resource="$(kctl get mcpserver "$name" -n "$MCP_NS" -o json 2>/dev/null)" ||+ return 1+ jq -e '+ .metadata.generation as $generation |+ any(+ .status.conditions[]?;+ .type == "Ready" and .status == "True" and+ (.observedGeneration // -1) == $generation+ ) | not+ ' <<<"$resource" >/dev/null+}++fixture_runtime_and_ready_absent() {+ fixture_runtime_absent && mcpserver_current_ready_absent "$MCP_NAME"+}+context_policies_absent() {resource_absent networkpolicy "$CONTEXT_POLICY" "$MCP_NS" &&resource_absent networkpolicy "$CONTEXT_EGRESS_POLICY" "$HOST_NS" &&@@ -317,11 +356,17 @@ context_policies_absent() {}context_policies_converged() {- kctl get networkpolicy "$CONTEXT_POLICY" -n "$MCP_NS" -o json |+ local context_id=${1:-$CONTEXT_ID}+ local context_name=${2:-$CONTEXT_NAME}+ local server=${3:-$MCP_NAME}+ local ingress_policy="ctx-${context_id}-${server}"+ local host_egress_policy="${ingress_policy}-egress"+ local rpc_egress_policy="rpc-egress-${context_id}-${server}"+ kctl get networkpolicy "$ingress_policy" -n "$MCP_NS" -o json |jq -e \- --arg contextId "$CONTEXT_ID" \- --arg contextName "$CONTEXT_NAME" \- --arg server "$MCP_NAME" \+ --arg contextId "$context_id" \+ --arg contextName "$context_name" \+ --arg server "$server" \--arg hostNs "$HOST_NS" \--arg rpcNs "$RPC_PROXY_NS" \--arg mcpNs "$MCP_NS" \@@ -353,11 +398,11 @@ context_policies_converged() {.podSelector.matchLabels.app == "mcp-proxy")' >/dev/null || return 1- kctl get networkpolicy "$CONTEXT_EGRESS_POLICY" -n "$HOST_NS" -o json |+ kctl get networkpolicy "$host_egress_policy" -n "$HOST_NS" -o json |jq -e \- --arg contextId "$CONTEXT_ID" \- --arg contextName "$CONTEXT_NAME" \- --arg server "$MCP_NAME" \+ --arg contextId "$context_id" \+ --arg contextName "$context_name" \+ --arg server "$server" \--arg mcpNs "$MCP_NS" \--arg managedByLabel "$MANAGED_BY_LABEL" \--arg managedByValue "$MANAGED_BY_VALUE" \@@ -379,10 +424,10 @@ context_policies_converged() {] == $mcpNs and.spec.egress[0].to[0].podSelector.matchLabels[$serverLabel] == $server' >/dev/null || return 1- kctl get networkpolicy "$RPC_EGRESS_POLICY" -n "$RPC_PROXY_NS" -o json |+ kctl get networkpolicy "$rpc_egress_policy" -n "$RPC_PROXY_NS" -o json |jq -e \- --arg contextId "$CONTEXT_ID" \- --arg server "$MCP_NAME" \+ --arg contextId "$context_id" \+ --arg server "$server" \--arg mcpNs "$MCP_NS" \--arg managedByLabel "$MANAGED_BY_LABEL" \--arg managedByValue "$MANAGED_BY_VALUE" \@@ -446,21 +491,6 @@ external_egress_policy_absent() {[ -z "$policies" ]}-external_egress_policy_identity() {- kctl get networkpolicy -n "$MCP_NS" \- -l "${MCP_SERVER_LABEL}=${MCP_NAME},${POLICY_TYPE_LABEL}=external-egress" \- -o json |- jq -ceS '- select((.items | length) == 1) |- {uid: .items[0].metadata.uid, spec: .items[0].spec}- '-}--certified_external_egress_policy_is_unchanged() {- [ -n "$CERTIFIED_POLICY_IDENTITY" ] &&- [ "$(external_egress_policy_identity)" = "$CERTIFIED_POLICY_IDENTITY" ]-}-fixture_runtime_converged_with_protocol() {local protocol=$1 desired availabledesired="$(kctl get deployment "$MCP_NAME" -n "$MCP_NS" \@@ -469,9 +499,7 @@ fixture_runtime_converged_with_protocol() {-o jsonpath='{.status.availableReplicas}' 2>/dev/null)" || return 1[ "${desired:-0}" -ge 1 ] && [ "${available:-0}" -ge 1 ] || return 1kctl get service "$MCP_NAME" -n "$MCP_NS" >/dev/null 2>&1 || return 1- kctl get mcpserver "$MCP_NAME" -n "$MCP_NS" -o json |- jq -e 'any(.status.conditions[]?; .type == "Ready" and .status == "True")' >/dev/null ||- return 1+ mcpserver_current_ready "$MCP_NAME" || return 1external_egress_policy_converged_with_protocol "$protocol"}@@ -502,16 +530,16 @@ peer_fleet_runtime_absent() {}peer_fleet_converged() {- local index server desired available+ local index server context desired availablefor ((index = 1; index < ${#MCP_FLEET_NAMES[@]}; index++)); doserver="${MCP_FLEET_NAMES[index]}"+ context="${CONTEXT_FLEET_NAMES[index]}"desired="$(kctl get deployment "$server" -n "$MCP_NS" -o jsonpath='{.spec.replicas}' 2>/dev/null)" || return 1available="$(kctl get deployment "$server" -n "$MCP_NS" -o jsonpath='{.status.availableReplicas}' 2>/dev/null)" || return 1[ "${desired:-0}" -ge 1 ] && [ "${available:-0}" -ge 1 ] || return 1kctl get service "$server" -n "$MCP_NS" >/dev/null 2>&1 || return 1- kctl get mcpserver "$server" -n "$MCP_NS" -o json | jq -e '- any(.status.conditions[]?; .type == "Ready" and .status == "True")- ' >/dev/null || return 1+ mcpserver_current_ready "$server" || return 1+ context_policies_converged "$context" "$context" "$server" || return 1done}@@ -588,9 +616,7 @@ fixture_converged() {-o jsonpath='{.status.availableReplicas}' 2>/dev/null)" || return 1[ "${desired:-0}" -ge 1 ] && [ "${available:-0}" -ge 1 ] || return 1kctl get service "$MCP_NAME" -n "$MCP_NS" >/dev/null 2>&1 || return 1- kctl get mcpserver "$MCP_NAME" -n "$MCP_NS" -o json |- jq -e 'any(.status.conditions[]?; .type == "Ready" and .status == "True")' >/dev/null ||- return 1+ mcpserver_current_ready "$MCP_NAME" || return 1external_egress_policy_converged || return 1context_policies_converged}@@ -669,35 +695,23 @@ probe_hcc_ready_pod() {}probe_new_hcc_ready_endpoint() {+ local output first_line+ HCC_READY_PROBE_DIAGNOSTIC="HCC_READY_PROBE category=pod-not-selected"[ -n "$NEW_HCC_POD" ] || return 1- kctl exec "pod/${NEW_HCC_POD}" -n "$HCC_NS" -c host-context-controller -- \- env "HCC_E2E_PORT=${HCC_PORT}" \- node -e '+ if output="$(+ kctl exec "pod/${NEW_HCC_POD}" -n "$HCC_NS" -c host-context-controller -- \+ env "HCC_E2E_PORT=${HCC_PORT}" \+ node -e 'const http = require("node:http");- const request = http.get(- {host: "127.0.0.1", port: Number(process.env.HCC_E2E_PORT), path: "/ready"},- response => {- let body = "";- response.setEncoding("utf8");- response.on("data", chunk => { body += chunk; });- response.on("end", () => {- let parsed;- try { parsed = JSON.parse(body); } catch { process.exit(2); }- process.exit(response.statusCode === 200 && parsed?.ready === true ? 0 : 3);- });+ let finished = false;+ const finish = (code, category, detail = "") => {+ if (finished) return;+ finished = true;+ if (category) {+ console.error(`HCC_READY_PROBE category=${category}${detail}`);}- );- request.setTimeout(2000, () => request.destroy(new Error("timeout")));- request.once("error", () => process.exit(4));- ' >/dev/null 2>&1-}--probe_new_hcc_unready_endpoint() {- [ -n "$NEW_HCC_POD" ] || return 1- kctl exec "pod/${NEW_HCC_POD}" -n "$HCC_NS" -c host-context-controller -- \- env "HCC_E2E_PORT=${HCC_PORT}" \- node -e '- const http = require("node:http");+ process.exitCode = code;+ };const request = http.get({host: "127.0.0.1", port: Number(process.env.HCC_E2E_PORT), path: "/ready"},response => {@@ -705,25 +719,54 @@ probe_new_hcc_unready_endpoint() {response.setEncoding("utf8");response.on("data", chunk => { body += chunk; });response.on("end", () => {+ if (response.statusCode !== 200) {+ finish(3, "http-status", ` status=${response.statusCode ?? "unknown"}`);+ return;+ }let parsed;- try { parsed = JSON.parse(body); } catch { process.exit(2); }- process.exit(response.statusCode === 503 && parsed?.ready === false ? 0 : 3);+ try {+ parsed = JSON.parse(body);+ } catch {+ finish(2, "json-invalid");+ return;+ }+ if (parsed?.ready !== true) {+ finish(3, "json-ready-false");+ return;+ }+ finish(0);});});- request.setTimeout(2000, () => request.destroy(new Error("timeout")));- request.once("error", () => process.exit(4));- ' >/dev/null 2>&1-}--hcc_unready_after_stale_policy_revoked() {- probe_new_hcc_unready_endpoint && external_egress_policy_absent+ request.setTimeout(2000, () => {+ finish(4, "timeout");+ request.destroy();+ });+ request.once("error", () => finish(5, "transport"));+ ' 2>&1+ )"; then+ HCC_READY_PROBE_DIAGNOSTIC=""+ return 0+ fi+ first_line="${output%%$'\n'*}"+ case "$first_line" in+ "HCC_READY_PROBE category="*)+ printf -v HCC_READY_PROBE_DIAGNOSTIC '%.240s' "$first_line"+ ;;+ *)+ HCC_READY_PROBE_DIAGNOSTIC="HCC_READY_PROBE category=kubectl-exec"+ ;;+ esac+ return 1}-hcc_ready_only_after_current_policy_applied() {+hcc_ready_after_stale_policy_revoked() {probe_new_hcc_ready_endpoint || return 1- external_egress_policy_converged ||- die "HCC served /ready=200 before the safe replacement external-egress policy existed"+ if external_egress_policy_absent; then+ return 0+ fi+ HCC_READY_PROBE_DIAGNOSTIC="HCC_READY_PROBE category=stale-policy-present"+ return 1}hcc_restore_is_verified() {@@ -783,7 +826,7 @@ NODEnode -e "$hold_script"}-delete_fixture_runtime_preserving_external_policy() {+delete_fixture_runtime_leaving_dns_policy_for_safety() {local failed=0kctl delete deployment "$MCP_NAME" -n "$MCP_NS" \--ignore-not-found --wait=true --timeout=60s >/dev/null 2>&1 || failed=1@@ -877,6 +920,10 @@ Inspect before changing anything:kubectl --context=${E2E_KUBECONTEXT} get mcpserver,context -A -l e2e.clerum.io/suite=${SUITE_NAME}Do not remove the HCC gate lock until HCC health and fixture absence are verified.++Restore the original HCC replica count before verifying rollout and /ready:+ kubectl --context=${E2E_KUBECONTEXT} -n ${HCC_NS} scale deployment/${HCC_DEPLOY} --replicas=${ORIGINAL_REPLICAS:-1}+ kubectl --context=${E2E_KUBECONTEXT} -n ${HCC_NS} rollout status deployment/${HCC_DEPLOY} --timeout=240sEOF}@@ -977,7 +1024,8 @@ header "HCC readiness during initial McpServer and Context convergence"require_branch_owned_hcc_gate "$HCC_NS"kctl get nodes -o json |- jq -e 'any(.items[]; .metadata.labels["minikube.k8s.io/name"] != null)' >/dev/null ||+ jq -e --arg context "$E2E_KUBECONTEXT" \+ 'any(.items[]; .metadata.labels["minikube.k8s.io/name"] == $context)' >/dev/null ||die "target context is not a minikube cluster"suite_resources_absent ||die "stale ${SUITE_NAME} resources exist; inspect them before starting a new fault injection"@@ -1280,20 +1328,19 @@ EOFwait_until 180 "HCC to create the real initial TCP external-egress policy" \external_egress_policy_converged_with_protocol "$INITIAL_EXTERNAL_EGRESS_PROTOCOL" ||die "HCC never created the initial external-egress policy for the stale-policy fixture"-CERTIFIED_POLICY_IDENTITY="$(external_egress_policy_identity)" ||- die "could not capture the certified TCP policy UID and spec"-ok "HCC created and certified a real TCP external-egress policy"+ok "HCC created a real initial TCP external-egress policy"-# Availability phase: restart with the exact same desired binding. Safety may-# certify the existing policy without DNS, and every later refresh/retry must-# preserve that same object while DNS is unavailable.+# Same-intent safety phase: restart with the exact same desired binding. The+# safety pass must revoke the DNS-derived policy without resolving DNS, certify+# global readiness, and leave the affected runtime blocked for the additive+# lane.kctl scale deployment "$HCC_DEPLOY" -n "$HCC_NS" --replicas=0 >/dev/nullwait_until 120 "existing HCC pods to stop" hcc_pods_absent ||die "existing HCC pod did not stop"-delete_fixture_runtime_preserving_external_policy ||+delete_fixture_runtime_leaving_dns_policy_for_safety ||die "could not remove the initial MCP runtime while retaining its external-egress policy"-certified_external_egress_policy_is_unchanged ||- die "the certified TCP policy changed before the same-intent restart"+external_egress_policy_converged_with_protocol "$INITIAL_EXTERNAL_EGRESS_PROTOCOL" ||+ die "the initial TCP policy disappeared before the same-intent safety pass"create_peer_fleet || die "could not create the gate-owned MCP/Context peer fleet"ok "created ${#MCP_FLEET_NAMES[@]} gate-owned MCP/Context fixtures before fleet bootstrap"@@ -1311,16 +1358,16 @@ read -r HCC_UID HCC_RESTARTS <<<"$identity"wait_until 120 "same-intent external-egress refresh to reach the DNS hold" \dns_hold_observed_since_arm ||die "same-intent external-egress refresh never reached the DNS hold"-wait_until_fast 60 "HCC /ready with a certified policy while DNS refresh is held" \- probe_new_hcc_ready_endpoint ||- die "HCC readiness incorrectly waited for same-intent DNS refresh"-fixture_runtime_absent ||- die "HCC became ready only after the held fleet runtime resources had already converged"+wait_until_fast 60 "HCC readiness after revoking the same-intent DNS policy" \+ hcc_ready_after_stale_policy_revoked ||+ die "HCC did not revoke the same-intent DNS policy before global readiness (${HCC_READY_PROBE_DIAGNOSTIC:-HCC_READY_PROBE category=unknown})"+fixture_runtime_and_ready_absent ||+ die "the affected runtime or Ready status escaped the held same-intent DNS boundary"wait_until 30 "Kubernetes to corroborate same-intent HCC readiness" \hcc_kubernetes_readiness_is_exact ||die "Kubernetes did not corroborate same-intent HCC readiness"-certified_external_egress_policy_is_unchanged ||- die "the certified policy was deleted or rewritten before the first retry"+external_egress_policy_absent ||+ die "the same-intent DNS policy reappeared before additive retry"wait_until 120 "a real same-intent external-egress retry to be scheduled" \external_egress_retry_progress_is_observed ||die "the held same-intent refresh did not schedule a real retry"@@ -1328,30 +1375,33 @@ wait_until 180 "the scheduled same-intent external-egress retry to execute" \external_egress_retry_rearmed_is_observed ||die "the scheduled same-intent external-egress retry did not execute"probe_new_hcc_ready_endpoint ||- die "HCC lost readiness after a same-intent DNS retry"-certified_external_egress_policy_is_unchanged ||- die "a same-intent retry deleted or rewrote the certified policy"+ die "HCC lost readiness after a same-intent DNS retry (${HCC_READY_PROBE_DIAGNOSTIC:-HCC_READY_PROBE category=unknown})"+external_egress_policy_absent ||+ die "a held same-intent retry recreated the DNS policy without current resolution"dns_has_not_released_since_hold ||- die "the DNS blocker released before the retry preservation assertion"-ok "same-intent DNS failure and retry preserved the policy UID/spec while HCC stayed Ready"+ die "the DNS blocker released before the retry revocation assertion"+ok "same-intent safety revoked the DNS policy while HCC stayed Ready and runtime stayed blocked"release_dns_blocker || die "could not release the same-intent DNS query"wait_until 30 "DNS blocker to answer the same-intent query" \dns_released_since_hold ||die "DNS blocker did not answer the same-intent query"+wait_until 120 "current TCP external-egress policy after same-intent DNS release" \+ external_egress_policy_converged_with_protocol "$INITIAL_EXTERNAL_EGRESS_PROTOCOL" ||+ die "the current TCP external-egress policy did not converge after DNS release"wait_until 180 "same-intent runtime convergence after DNS release" \fixture_runtime_converged_with_protocol "$INITIAL_EXTERNAL_EGRESS_PROTOCOL" ||die "same-intent runtime did not converge after DNS release"-# Security phase: a protocol change invalidates the certified policy. The old+# Security phase: a protocol change invalidates the current TCP policy. The old# TCP allow must be revoked even when DNS prevents constructing the UDP policy.kctl scale deployment "$HCC_DEPLOY" -n "$HCC_NS" --replicas=0 >/dev/nullwait_until 120 "same-intent HCC pod to stop" hcc_pods_absent ||die "same-intent HCC pod did not stop"-delete_fixture_runtime_preserving_external_policy ||+delete_fixture_runtime_leaving_dns_policy_for_safety ||die "could not remove the same-intent runtime before the divergent revision"-certified_external_egress_policy_is_unchanged ||- die "the certified TCP policy changed before the divergent revision"+external_egress_policy_converged_with_protocol "$INITIAL_EXTERNAL_EGRESS_PROTOCOL" ||+ die "the current TCP policy disappeared before the divergent safety pass"hold_dns_blocker || die "could not hold the divergent fixture DNS query"DNS_RELEASE_COUNT_AT_HOLD="$(dns_release_count)" ||die "could not capture the DNS release baseline before the divergent revision"@@ -1375,25 +1425,28 @@ read -r HCC_UID HCC_RESTARTS <<<"$identity"wait_until 120 "fixture external-egress DNS query to reach the hold proxy" \dns_hold_observed_since_arm ||die "NetworkPolicy safety convergence never reached the divergent DNS hold"-wait_until_fast 120 "HCC to stay unready after revoking the divergent stale policy" \- hcc_unready_after_stale_policy_revoked ||- die "HCC did not revoke the divergent stale policy before readiness"+wait_until_fast 120 "HCC readiness after revoking the divergent stale policy" \+ hcc_ready_after_stale_policy_revoked ||+ die "HCC did not become globally ready after revoking the divergent stale policy (${HCC_READY_PROBE_DIAGNOSTIC:-HCC_READY_PROBE category=unknown})"+wait_until 30 "Kubernetes to corroborate HCC readiness during divergent DNS hold" \+ hcc_kubernetes_readiness_is_exact ||+ die "Kubernetes did not corroborate HCC readiness during divergent DNS hold"dns_log_contains "holding DNS A ${TARGET_DNS}" ||die "DNS hold ended before the fail-closed revocation assertion"if ! dns_has_not_released_since_hold; thendie "DNS blocker released before the fail-closed revocation assertion"fifixture_runtime_and_ready_absent ||- die "fixture runtime or Ready status appeared before safe egress replacement"+ die "fixture runtime or Ready status appeared while divergent DNS remained held"external_egress_policy_absent ||- die "a divergent external-egress policy survived before safe replacement"+ die "a divergent external-egress policy survived the fail-closed revocation"context_policies_absent ||die "Context policy existed before the Context watch update"baseline_policies_exist ||die "baseline safety NetworkPolicies are absent during safety convergence"hcc_identity_is_stable ||die "HCC restarted while the MCP external-egress query was held"-ok "/ready is 503 and the divergent stale policy is absent while replacement is blocked"+ok "/ready is 200 while the divergent stale policy and affected runtime remain absent"ok "baseline NetworkPolicies remain present throughout fail-closed safety convergence"initial_empty_context_log="[NetPol] Reconciling context \"${CONTEXT_ID}\" — allowed servers: []"@@ -1423,33 +1476,39 @@ wait_until 120 "all three latest-Context NetworkPolicies to converge during thefixture_runtime_and_ready_absent ||die "McpServer runtime or Ready status escaped the deterministic DNS hold boundary"external_egress_policy_absent ||- die "a divergent external-egress policy reappeared before safe replacement"+ die "a divergent external-egress policy reappeared while DNS remained held"dns_log_contains "holding DNS A ${TARGET_DNS}" ||die "DNS hold evidence disappeared before Context policy convergence"if ! dns_has_not_released_since_hold; thendie "DNS blocker released the McpServer query before the Context isolation assertion"fi-probe_new_hcc_unready_endpoint ||- die "HCC became ready before the safe replacement policy existed"-if hcc_kubernetes_readiness_is_exact; then- die "Kubernetes reported HCC Ready before the safe replacement policy existed"-fi+probe_new_hcc_ready_endpoint ||+ die "HCC lost global readiness while the affected runtime remained safely blocked (${HCC_READY_PROBE_DIAGNOSTIC:-HCC_READY_PROBE category=unknown})"+hcc_kubernetes_readiness_is_exact ||+ die "Kubernetes lost HCC readiness during isolated Context convergence"hcc_identity_is_stable ||die "HCC restarted while Context policies converged around the held MCP entity"ok "the MODIFIED handler, not the initial empty-Context pass, converged all three policies"-ok "McpServer runtime and divergent policy stayed absent until safe replacement"+ok "global readiness and Context progress continued while the affected runtime stayed blocked"++initial_policy_run_marker="Running initial NetworkPolicy background reconciliation"+initial_policy_complete_marker="[NetPol] Full reconciliation complete"+initial_policy_run_count_before_release="$(hcc_log_count "$initial_policy_run_marker")" ||+ die "could not snapshot initial NetworkPolicy run evidence before DNS release"+initial_policy_complete_count_before_release="$(+ hcc_log_count "$initial_policy_complete_marker"+)" || die "could not snapshot initial NetworkPolicy completion evidence before DNS release"release_dns_blocker ||die "could not release the fixture DNS query"wait_until 30 "DNS blocker to answer the held query" \dns_released_since_hold ||die "DNS blocker did not answer the held query"-wait_until_fast 120 "HCC /ready only after the current replacement policy is applied" \- hcc_ready_only_after_current_policy_applied ||- die "HCC did not become ready after the safe replacement policy was applied"-wait_until 30 "replacement HCC pod and Deployment to corroborate readiness" \- hcc_kubernetes_readiness_is_exact ||- die "Kubernetes did not corroborate HCC readiness after the direct ordering assertion"+wait_until 120 "current UDP external-egress policy after DNS release" \+ external_egress_policy_converged_with_protocol UDP ||+ die "the current UDP external-egress policy did not converge after DNS release"+probe_new_hcc_ready_endpoint ||+ die "HCC lost readiness while the released UDP policy converged (${HCC_READY_PROBE_DIAGNOSTIC:-HCC_READY_PROBE category=unknown})"wait_until 300 "McpServer runtime, status, and latest Context NetworkPolicies to converge" \fixture_converged ||die "McpServer/Context/NetworkPolicy convergence did not complete after DNS release"@@ -1457,10 +1516,12 @@ wait_until 300 "all peer MCP/Context runtimes to converge after releasing the hepeer_fleet_converged ||die "peer MCP/Context fleet did not converge after the held primary egress was released"wait_until 60 "initial NetworkPolicy full pass to run" \- hcc_log_contains "Running initial NetworkPolicy background reconciliation" ||+ hcc_log_count_exceeds \+ "$initial_policy_run_marker" "$initial_policy_run_count_before_release" ||die "initial NetworkPolicy convergence was not observed after releasing MCP convergence"wait_until 60 "initial NetworkPolicy retry to complete after DNS release" \- hcc_log_contains "[NetPol] Full reconciliation complete" ||+ hcc_log_count_exceeds \+ "$initial_policy_complete_marker" "$initial_policy_complete_count_before_release" ||die "initial NetworkPolicy convergence did not recover after DNS release"hcc_identity_is_stable ||die "HCC restarted instead of completing the released background convergence"@@ -1472,9 +1533,9 @@ echo "$final_probe" | jq -e \.fixture == $fixture and .fixtureReady == true and .contextRef == $context' >/dev/null ||die "HCC final probe returned an invalid result: ${final_probe}"-ok "DNS release replaced the old policy before readiness and then created the real runtime"+ok "DNS release created the current UDP policy and affected runtime without gating HCC readiness"ok "the full worker-width-crossing peer fleet converged after releasing the held primary egress"ok "Context ingress, mcp-host egress, and rpc-proxy egress policies reflect the latest watch state"-ok "HCC stayed unready through divergent revocation and became Ready only after replacement"+ok "HCC stayed Ready through divergent revocation while the affected runtime remained fail-closed"header "HCC McpServer/Context assertions complete; restoring branch-owned runtime"diff --git a/scripts/e2e/e2e-hcc-readiness-bootstrap.sh b/scripts/e2e/e2e-hcc-readiness-bootstrap.shindex e26ac3b4a..7386eb561 100755--- a/scripts/e2e/e2e-hcc-readiness-bootstrap.sh+++ b/scripts/e2e/e2e-hcc-readiness-bootstrap.sh@@ -43,6 +43,7 @@ command -v jq >/dev/null 2>&1 || {HCC_NS="${HCC_NS:-control-plane}"HCC_DEPLOY="${HCC_DEPLOY:-host-context-controller}"+HCC_GATEWAY_DEPLOY="${HCC_GATEWAY_DEPLOY:-host-context-controller-api-gateway}"HOST_NS="${MCP_HOST_NS:-mcp-host}"MCP_NS="${MCP_SERVER_NS:-mcp-server}"TOKEN_REQUEST_PATH="/api/v1/auth/mcp-host/${HOST_NS}/standalone/tokens"@@ -203,6 +204,70 @@ probe_hcc_ready_pod() {' >/dev/null 2>&1}+running_hcc_gateway_pod() {+ running_pod_name "$HCC_NS" "app=${HCC_GATEWAY_DEPLOY}"+}++hcc_gateway_deployment_ready() {+ kctl get deployment "$HCC_GATEWAY_DEPLOY" -n "$HCC_NS" -o json |+ jq -e '+ .spec.replicas == 1 and+ .status.observedGeneration == .metadata.generation and+ (.status.updatedReplicas // 0) == 1 and+ (.status.readyReplicas // 0) == 1 and+ (.status.availableReplicas // 0) == 1 and+ (.status.unavailableReplicas // 0) == 0+ ' >/dev/null+}++hcc_gateway_local_health_ok() {+ local pod+ pod="$(running_hcc_gateway_pod)" || return 1+ kctl exec "pod/${pod}" -n "$HCC_NS" -c nginx -- \+ wget -qO- http://127.0.0.1:8081/health |+ jq -e '.status == "ok"' >/dev/null+}++hcc_gateway_ready_proxy_unavailable() {+ local pod output status+ pod="$(running_hcc_gateway_pod)" || return 1+ output="$(+ kctl exec "pod/${pod}" -n "$HCC_NS" -c nginx -- \+ wget -O /dev/null -S http://127.0.0.1:8081/ready 2>&1+ )" && return 1+ status="$(+ awk '+ /^[[:space:]]*HTTP\/[0-9.]+[[:space:]]+[0-9][0-9][0-9]([[:space:]]|$)/ {+ code = $2+ }+ END {+ if (code != "") print code+ }+ ' <<<"$output"+ )"+ [ "$status" = 502 ]+}++hcc_gateway_remains_ready_without_hcc() {+ local duration=$1 deadline+ deadline=$(( $(date +%s) + duration ))+ while [ "$(date +%s)" -lt "$deadline" ]; do+ hcc_gateway_deployment_ready &&+ hcc_gateway_local_health_ok &&+ hcc_gateway_ready_proxy_unavailable ||+ return 1+ sleep 1+ done+}++hcc_gateway_ready_proxy_recovers() {+ local pod+ pod="$(running_hcc_gateway_pod)" || return 1+ kctl exec "pod/${pod}" -n "$HCC_NS" -c nginx -- \+ wget -qO- http://127.0.0.1:8081/ready |+ jq -e '.ready == true and .status == "ready"' >/dev/null+}+fixture_inputs_absent() {local hosts contexts secretshosts="$(kctl get host -n "$HOST_NS" -l "e2e.clerum.io/suite=${SUITE_NAME}" \@@ -358,6 +423,10 @@ Inspect before changing anything:Do not remove the blocker or HCC gate lock until HCC configuration, rollout, Pod readiness,/ready, and fixture absence are verified.++Restore the original HCC replica count before verifying rollout and /ready:+ kubectl --context=${E2E_KUBECONTEXT} -n ${HCC_NS} scale deployment/${HCC_DEPLOY} --replicas=${ORIGINAL_REPLICAS:-1}+ kubectl --context=${E2E_KUBECONTEXT} -n ${HCC_NS} rollout status deployment/${HCC_DEPLOY} --timeout=180sEOF}@@ -437,7 +506,8 @@ require_branch_owned_hcc_gate "$HCC_NS"ok "branch helper, profile, exact HEAD/fingerprint/gate verified"kctl get nodes -o json |- jq -e 'any(.items[]; .metadata.labels["minikube.k8s.io/name"] != null)' >/dev/null ||+ jq -e --arg context "$E2E_KUBECONTEXT" \+ 'any(.items[]; .metadata.labels["minikube.k8s.io/name"] == $context)' >/dev/null ||die "target context is not a minikube cluster"readiness_blocker_suite_absent ||die "stale HCC readiness blocker resources exist; inspect them before fault injection"@@ -626,6 +696,9 @@ HCC_MUTATED=1kctl scale deployment "$HCC_DEPLOY" -n "$HCC_NS" --replicas=0 >/dev/nullwait_until 120 "existing HCC pods to stop" hcc_pods_absent ||die "existing HCC pod did not stop"+hcc_gateway_remains_ready_without_hcc 20 ||+ die "HCC API gateway did not remain Ready on local /health while proxied /ready was unavailable"+ok "API gateway remained Ready for a complete probe-failure window while /ready reflected HCC unavailability"create_host_fixtures ||die "could not create the gate-owned Host fleet while HCC was stopped"ok "created ${FIXTURE_HOST_COUNT} gate-owned Hosts without modifying any real Host or Secret"@@ -695,9 +768,12 @@ echo "$probe_result" | jq -e \'.readyStatus == 200 and .discoveryStatus == 200 and (.discoveredServers | type == "number")' \>/dev/null ||die "HCC HTTP probe returned an invalid result: ${probe_result}"+hcc_gateway_ready_proxy_recovers ||+ die "HCC API gateway /ready did not recover after HCC became ready"initial_host_pass_is_active "$new_hcc_pod" ||die "initial Host reconciliation failed or completed before the HTTP assertions finished"ok "/ready returned 200 while the initial Host fleet pass remained active"+ok "API gateway /ready recovered without changing its local readiness"ok "/api/v1/mcpservers returned a valid live discovery response during that same pass"header "HCC readiness assertions passed; restoring branch-owned runtime"diff --git a/scripts/e2e/e2e-host-storm-gate.sh b/scripts/e2e/e2e-host-storm-gate.shindex b98dbd5da..f001f8ae1 100755--- a/scripts/e2e/e2e-host-storm-gate.sh+++ b/scripts/e2e/e2e-host-storm-gate.sh@@ -58,12 +58,15 @@# watch-DELETE path, which by design does not touch this counter) —# A5 remains the falsifiable cleanup proof.# A7 recovered fleet convergence is bounded, from-# clerum_hcc_host_fleet_requests_total (scrape C2): failed == 0 in both-# windows, exactly one background full pass starts after the replacement-# LIST→WATCH, and trailing <= coalesced. Cold start produces one request,-# so requiring a coalesced request here would invent a second signal; the-# concurrent-request coalescing contract is covered deterministically by-# hostFleetScheduler.test.ts.+# clerum_hcc_host_fleet_requests_total (scrape C2) plus the replacement+# pod's explicit initial-fleet COMPLETED log: failed == 0 in both windows,+# the exact replacement pod completes its startup fleet pass, and+# trailing <= coalesced. The pod identity, completion marker, and A4's+# successful recovery histogram form the causal fence; started is not+# capped because an independent request may legitimately begin after the+# recovery pass settles. Requiring a coalesced request here would invent+# a second overlapping signal; the concurrent-request coalescing contract+# is covered deterministically by hostFleetScheduler.test.ts.# A8 wake ingredient integrity: the woken Host leaves state=suspended and# reaches a Ready pod within STORM_WAKE_READY_BUDGET_S of the wake# POST. This is an ingredient-integrity bound (a silently no-op wake@@ -95,23 +98,26 @@## ----------------------------------------------------------------------# INPUTS (environment; fail-loud if missing/invalid)-# CONTEXT kubectl context. REFUSED unless it matches-# ^clerum-(test|codex-|detached-|claude-) — a local minikube-# profile. Any GKE / *prod* context is rejected outright.+# KUBECONTEXT / E2E_K8S_CONTEXT+# Exact generated branch-owned minikube context.+# MINIKUBE_PROFILE+# Must equal that context.+# E2E_EXPECTED_PRE_GATE_GATE+# Exact gate recorded by the branch-owned pre-gate sync.+# E2E_HCC_HOST_STORM_FAULT_INJECTION=1+# Explicit acknowledgement of the disruptive HCC pod restart.## OPTIONAL INPUTS# E2E_STORM_WAKE_HOST_REF suspended-wake target (default chatllm-stateless,# the seeded stateless Host — it must exist with# spec.lifecycle.stateless=true and be associated to the E2E# user; seed via scripts/e2e/seed-stateless-host.sh).-# EXTERNAL_REST_API_BASE_URL default http://127.0.0.1:8091-# RPC_PROXY_BASE_URL default http://127.0.0.1:8094# E2E_DEV_LOGIN_EMAIL default [email protected]# E2E_USER_PASSWORD default ${ADMIN_PASSWORD:-changeme123!}# STORM_CONTEXT_REF Context CR fixtures reference (default context1)# STORM_MODEL_PROVIDER / STORM_MODEL_NAME fixture model (default zai/glm-5.1)-# HCC_METRICS_LOCAL_PORT ephemeral scrape port (default 18082)-# KEEP_FIXTURES set to 1 to skip teardown (diagnosis only)+# CLERUM_PROFILE_PORTS_ENV optional explicit path to the selected branch+# profile's generated ports.env.## Prereqs (each a HARD FAIL with the concrete reason):# - branch HCC image deployed (clerum_hcc_host_delete_cleanup_total@@ -120,7 +126,10 @@# - external-rest-api + rpc-proxy reachable (make minikube-pf-all)## Usage:-# CONTEXT=clerum-test bash scripts/e2e/e2e-host-storm-gate.sh+# MINIKUBE_PROFILE=<profile> KUBECONTEXT=<profile> \+# E2E_EXPECTED_PRE_GATE_GATE=<gate> \+# E2E_HCC_HOST_STORM_FAULT_INJECTION=1 \+# bash scripts/e2e/e2e-host-storm-gate.sh## EXIT CODES# 0 every storm assertion passed and teardown left zero fixtures@@ -129,6 +138,17 @@# ======================================================================set -euo pipefail+SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"+# shellcheck source=scripts/e2e/e2e-lib.sh+# shellcheck disable=SC1091+source "${SCRIPT_DIR}/e2e-lib.sh"+# shellcheck source=scripts/e2e/_lib/hcc-watch-recovery-fixture.sh+# shellcheck disable=SC1091+source "${SCRIPT_DIR}/_lib/hcc-watch-recovery-fixture.sh"+# shellcheck source=scripts/e2e/_lib/hcc-watch-recovery-lock.sh+# shellcheck disable=SC1091+source "${SCRIPT_DIR}/_lib/hcc-watch-recovery-lock.sh"+# ─── Constants mirrored from host-context-controller/src/{constants,config}.ts ──readonly MANAGED_BY_LABEL='clerum.io/managed-by'readonly MANAGED_BY_VALUE='host-context-controller'@@ -142,6 +162,10 @@ readonly CONTROL_NS='control-plane'readonly HCC_DEPLOY='host-context-controller'readonly HCC_PORT='8081' # containerPort http (deploy/base/control-plane)readonly HCC_METRICS_PATH='/metrics' # server.ts GET /metrics+readonly HCC_PASS_COMPLETED_MARKER='Completed Host reconciliation after initial Host reconciliation'+readonly HCC_PASS_FAILED_MARKER='Host reconciliation after initial Host reconciliation failed'+# Shared HCC ownership/lock helpers use HCC_NS.+HCC_NS="$CONTROL_NS"# Owned-child kinds + namespaces of a per-Host bundle (mirrors# measure-host-bundle-reconcile.sh — includes per-Host NetworkPolicies).@@ -248,26 +272,44 @@ print_results() {log "fairness and convergence under realistic concurrency, not API degradation."}-# ─── kubectl wrapper — EVERY call carries --context (CLAUDE.md mandate) ──-kctl() { kubectl --context "$CONTEXT" "$@"; }-# ─── Portable time helper (python3; mirrors measure script) ───────────now_ms() { python3 -c 'import time;print(int(time.time()*1000))'; }# ─── Strict local-profile context guard (fail-loud) ───────────────────require_storm_context() {- [[ -n "${CONTEXT:-}" ]] || die "CONTEXT is required (a local minikube profile context)." 2- case "$CONTEXT" in- *gke_*|*prod*)- die "Refusing: CONTEXT='${CONTEXT}' looks like a GKE/production context. Local profiles only." 2 ;;- esac- if [[ ! "$CONTEXT" =~ ^clerum-(test|codex-|detached-|claude-) ]]; then- die "Refusing: CONTEXT='${CONTEXT}' is not an allowed local profile. Must match ^clerum-(test|codex-|detached-|claude-)." 2- fi+ [[ -n "${E2E_KUBECONTEXT:-}" ]] ||+ die "KUBECONTEXT or E2E_K8S_CONTEXT must select an explicit branch-scoped minikube context." 2+ is_branch_scoped_e2e_context "$E2E_KUBECONTEXT" ||+ die "Refusing Host storm fault injection on non-branch context '${E2E_KUBECONTEXT}'." 2+ require_safe_kube_context ||+ die "context '${E2E_KUBECONTEXT}' is not an allowed local E2E context." 2if ! kctl get nodes -o name >/dev/null 2>&1; then- die "CONTEXT='${CONTEXT}' is not reachable (kubectl get nodes failed). Start the profile and its port-forwards." 1+ die "context '${E2E_KUBECONTEXT}' is not reachable (kubectl get nodes failed)." 1fi- log "context OK: ${CONTEXT}"+ kctl get nodes -o json | jq -e --arg context "$E2E_KUBECONTEXT" \+ 'any(.items[]; .metadata.labels["minikube.k8s.io/name"] == $context)' >/dev/null ||+ die "target context is not the exact selected minikube profile '${E2E_KUBECONTEXT}'." 2+ log "branch-owned minikube context OK: ${E2E_KUBECONTEXT}"+}++load_branch_profile_endpoints() {+ local ports_env external_url rpc_url+ ports_env="${CLERUM_PROFILE_PORTS_ENV:-${HOME}/.cache/clerum/minikube-profiles/${E2E_KUBECONTEXT}/ports.env}"+ [[ -r "$ports_env" ]] ||+ die "branch profile ports evidence is missing at ${ports_env}; refresh the branch-profile helper." 2+ external_url="$(profile_env_value EXTERNAL_REST_API_BASE_URL "$ports_env")"+ [[ -n "$external_url" ]] ||+ external_url="$(profile_env_value EXTERNAL_REST_API_URL "$ports_env")"+ rpc_url="$(profile_env_value RPC_PROXY_BASE_URL "$ports_env")"+ [[ -n "$rpc_url" ]] ||+ rpc_url="$(profile_env_value RPC_PROXY_URL "$ports_env")"+ [[ "$external_url" =~ ^http://127\.0\.0\.1:[0-9]{2,5}$ ]] ||+ die "branch ports.env has no valid loopback External REST URL." 2+ [[ "$rpc_url" =~ ^http://127\.0\.0\.1:[0-9]{2,5}$ ]] ||+ die "branch ports.env has no valid loopback RPC proxy URL." 2+ EXT_BASE="$external_url"+ RPC_BASE="$rpc_url"+ log "using branch-profile endpoints from ${ports_env}"}require_deps() {@@ -305,8 +347,8 @@ STORM_CREATED_HOSTS=()STORM_DELETE_HOSTS=()STORM_URGENT_PROBE_HOSTS=()WAKE_HOST_REF="${E2E_STORM_WAKE_HOST_REF:-chatllm-stateless}"-EXT_BASE="${EXTERNAL_REST_API_BASE_URL:-http://127.0.0.1:8091}"-RPC_BASE="${RPC_PROXY_BASE_URL:-http://127.0.0.1:8094}"+EXT_BASE=''+RPC_BASE=''DEV_EMAIL="${E2E_DEV_LOGIN_EMAIL:[email protected]}"DEV_PASSWORD="${E2E_USER_PASSWORD:-${ADMIN_PASSWORD:-changeme123!}}"STORM_CTX_REF="${STORM_CONTEXT_REF:-context1}"@@ -320,6 +362,14 @@ T_CREATE_FIRST_MS=''; T_DELETE_MS=''; T_WAKE_MS=''; T_KILL_MS=''; T_CREATE_LAST_PF_PID=''HCC_ENV_SAVED=''TEARDOWN_DONE=0+TEARDOWN_CLEANUP_FAILED=0+HCC_RESTORE_OK=1+STORM_FIXTURES_CREATED=0+# Read and mutated by the sourced compare-and-swap lock helper.+HCC_GATE_LOCK_ACQUIRED=0+HCC_GATE_LOCK_NAME=''+HCC_GATE_LOCK_UID=''+HCC_GATE_FINALIZATION_FAILURE=''cleanup_portforward() {if [[ -n "$PF_PID" ]] && kill -0 "$PF_PID" 2>/dev/null; then@@ -349,10 +399,16 @@ restore_hcc_env() {_hcc_restore_args[[ ${#args[@]} -gt 0 ]] || { HCC_ENV_SAVED=''; return 0; }log "Restoring HCC cadence env on deployment/${HCC_DEPLOY}"- kctl set env "deployment/${HCC_DEPLOY}" -n "$CONTROL_NS" "${args[@]}" >/dev/null 2>&1 || \- warn "failed to restore HCC env (manual check advised)"- kctl rollout status "deployment/${HCC_DEPLOY}" -n "$CONTROL_NS" --timeout=180s >/dev/null 2>&1 || \+ if ! kctl set env "deployment/${HCC_DEPLOY}" -n "$CONTROL_NS" "${args[@]}" >/dev/null 2>&1; then+ warn "failed to restore HCC env (manual check required)"+ HCC_RESTORE_OK=0+ return 1+ fi+ if ! kctl rollout status "deployment/${HCC_DEPLOY}" -n "$CONTROL_NS" --timeout=180s >/dev/null 2>&1; thenwarn "HCC rollout did not settle after env restore"+ HCC_RESTORE_OK=0+ return 1+ fiHCC_ENV_SAVED=''}@@ -367,10 +423,12 @@ restore_hcc_env_strict() {[[ ${#args[@]} -gt 0 ]] || { HCC_ENV_SAVED=''; return 0; }log "Restoring HCC cadence env on deployment/${HCC_DEPLOY} (strict)"if ! kctl set env "deployment/${HCC_DEPLOY}" -n "$CONTROL_NS" "${args[@]}" >/dev/null 2>&1; then+ HCC_RESTORE_OK=0fail "cadence restore FAILED — the profile is left with test cadences on deployment/${HCC_DEPLOY} (the EXIT trap retries best-effort; verify manually)"return 0fiif ! kctl rollout status "deployment/${HCC_DEPLOY}" -n "$CONTROL_NS" --timeout=180s >/dev/null 2>&1; then+ HCC_RESTORE_OK=0fail "HCC rollout did not settle after the cadence restore — verify deployment/${HCC_DEPLOY} manually"return 0fi@@ -380,10 +438,11 @@ restore_hcc_env_strict() {# shellcheck disable=SC2329 # invoked via the EXIT trap belowcleanup_on_exit() {- local status=$?+ local status=$? cleanup_failed=0set +ecleanup_portforward- if [[ "$TEARDOWN_DONE" != '1' && -n "$RUN_ID" && "${KEEP_FIXTURES:-}" != '1' ]]; then+ if [[ "$TEARDOWN_DONE" != '1' && "$STORM_FIXTURES_CREATED" == '1' && -n "$RUN_ID" ]]; then+ cleanup_failed=1local sel="${FIXTURE_LABEL_KEY}=${FIXTURE_LABEL_VAL},${FIXTURE_RUN_KEY}=${RUN_ID}"warn "abnormal exit — best-effort deletion of storm fixtures (${sel})"kctl -n "$MCP_HOST_NS" delete host -l "$sel" --wait=false >/dev/null 2>&1 || \@@ -391,7 +450,10 @@ cleanup_on_exit() {kctl -n "$MCP_HOST_NS" delete secret -l "$sel" --wait=false >/dev/null 2>&1 || \warn "best-effort fixture Secret deletion failed (manual check advised)"fi- restore_hcc_env+ restore_hcc_env || HCC_RESTORE_OK=0+ if ! finalize_hcc_watch_gate_lock "$cleanup_failed" "$HCC_RESTORE_OK"; then+ status=1+ fiexit "$status"}trap cleanup_on_exit EXIT@@ -543,14 +605,30 @@ storm_diagnostics() {# different pod (e.g. a terminating one during a rollout) than the one the# identity guard checked; cross-pod counter deltas would false-PASS A4.scrape_hcc_metrics() {- local out="$1" pod="$2" lport="${HCC_METRICS_LOCAL_PORT:-18082}"- local url="http://127.0.0.1:${lport}${HCC_METRICS_PATH}"- kctl -n "$CONTROL_NS" port-forward "pod/${pod}" "${lport}:${HCC_PORT}" >"${WORK_DIR}/pf.log" 2>&1 &+ local out="$1" pod="$2" lport='' url pf_log+ pf_log="${WORK_DIR}/pf-${pod}.log"+ # Let kubectl allocate a process-owned loopback port. A fixed port is+ # machine-global and can silently collide with another branch/profile gate.+ kctl -n "$CONTROL_NS" port-forward --address=127.0.0.1 \+ "pod/${pod}" ":${HCC_PORT}" >"$pf_log" 2>&1 &PF_PID=$!# shellcheck disable=SC2329 # invoked by name via wait_until+ _pf_ready_probe() {+ kill -0 "$PF_PID" 2>/dev/null || return 1+ lport="$(sed -nE 's/^Forwarding from 127\.0\.0\.1:([0-9]+) -> .*/\1/p' "$pf_log" | head -n1)"+ [[ "$lport" =~ ^[0-9]+$ ]]+ }+ # shellcheck disable=SC2329 # invoked by name via wait_until+ _pf_diag() { { echo '----- port-forward log -----'; cat "$pf_log" 2>/dev/null; } >&2; }+ if ! wait_until 30 1 "random HCC metrics port-forward" _pf_ready_probe _pf_diag; then+ cleanup_portforward+ return 1+ fi+ url="http://127.0.0.1:${lport}${HCC_METRICS_PATH}"+ # shellcheck disable=SC2329 # invoked by name via wait_until_scrape_probe() { curl -fsS --max-time 3 "$url" -o "$out" 2>/dev/null; }# shellcheck disable=SC2329 # invoked by name via wait_until- _scrape_diag() { { echo '----- port-forward log -----'; cat "${WORK_DIR}/pf.log" 2>/dev/null; } >&2; }+ _scrape_diag() { _pf_diag; }if ! wait_until 30 2 "HCC metrics scrape -> ${out}" _scrape_probe _scrape_diag; thencleanup_portforwardreturn 1@@ -695,8 +773,15 @@ _wake_target_diag() {require_depsrequire_storm_contextinit_run+[[ "${KEEP_FIXTURES:-0}" != '1' ]] ||+ die "KEEP_FIXTURES=1 is diagnostic-only and cannot produce a probative T2 Host-storm result; refusing before mutation." 2+[[ "${E2E_HCC_HOST_STORM_FAULT_INJECTION:-0}" == '1' ]] ||+ die "Set E2E_HCC_HOST_STORM_FAULT_INJECTION=1 to acknowledge the temporary HCC pod restart." 2+require_branch_owned_hcc_gate "$CONTROL_NS"+load_branch_profile_endpointsheader "Prerequisites"+ok "branch helper, profile, exact HEAD/fingerprint/gate, and minikube node label verified"if kctl get deployment "$HCC_DEPLOY" -n "$CONTROL_NS" >/dev/null 2>&1; thenok "HCC deployment present in ${CONTROL_NS}"else@@ -736,12 +821,18 @@ elsefail "cannot mint RPC token for hostRef=${WAKE_HOST_REF} -- is ${DEV_EMAIL} associated to it? Seed: bash scripts/e2e/seed-stateless-host.sh"print_results; exit 1fi+if acquire_hcc_watch_gate_lock; then+ ok "exclusive shared HCC fault-injection lock acquired"+else+ die "another disruptive HCC gate owns context ${E2E_KUBECONTEXT}"+fi# ======================================================================# Prep 1 — storm fixtures that will be DELETED mid-storm (bundles must# exist first: deleting a bundle-less Host proves nothing)# ======================================================================header "Prep — pre-create ${STORM_DELETE_COUNT} delete-target fixture Hosts"+STORM_FIXTURES_CREATED=1ensure_fixture_secretfor h in "${STORM_DELETE_HOSTS[@]}"; doapply_storm_host "$h" false@@ -959,6 +1050,41 @@ elseprint_results; exit 1fi+# A7's causal business signal is the replacement pod's own completion log for+# its startup fleet reconciliation. A scheduled/started counter is insufficient:+# it can increment before the pass fails, stalls, or is superseded.+FLEET_COMPLETION_PROVEN=0+replacement_fleet_state=''+# shellcheck disable=SC2329 # invoked by name via wait_until+_replacement_fleet_completed_probe() {+ local logs current_pod+ current_pod="$(hcc_pod_name)"+ [[ -n "$current_pod" && "$current_pod" == "$HCC_POD_C" ]] || return 1+ logs="$(kctl -n "$CONTROL_NS" logs "pod/${HCC_POD_C}" \+ -c host-context-controller 2>/dev/null)" || return 1+ if printf '%s\n' "$logs" | grep -Fq "$HCC_PASS_FAILED_MARKER"; then+ replacement_fleet_state='failed'+ return 0+ fi+ if printf '%s\n' "$logs" | grep -Fq "$HCC_PASS_COMPLETED_MARKER"; then+ replacement_fleet_state='completed'+ return 0+ fi+ return 1+}+if ! wait_until "$STORM_CONVERGENCE_DEADLINE_S" 2 \+ "replacement HCC initial Host fleet reconciliation completion" \+ _replacement_fleet_completed_probe storm_diagnostics; then+ fail "A7: replacement pod did not complete its initial Host fleet reconciliation within ${STORM_CONVERGENCE_DEADLINE_S}s"+ print_results; exit 1+fi+if [[ "$replacement_fleet_state" != 'completed' ]]; then+ fail "A7: replacement pod's initial Host fleet reconciliation failed"+ storm_diagnostics; print_results; exit 1+fi+FLEET_COMPLETION_PROVEN=1+ok "A7 input: replacement pod logged completed initial Host fleet reconciliation"+# shellcheck disable=SC2329 # invoked by name via wait_until_all_created_deploys_probe() {local h@@ -1171,7 +1297,7 @@ METRIC_VERDICTS="${WORK_DIR}/metric-verdicts.txt"if ! SCRAPE_A="$SCRAPE_A" SCRAPE_B="$SCRAPE_B" SCRAPE_C1="$SCRAPE_C1" SCRAPE_C2="$SCRAPE_C2" SCRAPE_D="$SCRAPE_D" \SCRAPE_WAKE_PRE="$SCRAPE_WAKE_PRE" SCRAPE_WAKE_POST="$SCRAPE_WAKE_POST" \P95_BUDGET_S="$STORM_URGENT_P95_BUDGET_S" RECOVERY_BUDGET_S="$STORM_WATCH_RECOVERY_BUDGET_S" \- MIN_URGENT_SAMPLES="$STORM_URGENT_PROBE_COUNT" \+ MIN_URGENT_SAMPLES="$STORM_URGENT_PROBE_COUNT" FLEET_COMPLETION_PROVEN="$FLEET_COMPLETION_PROVEN" \python3 >"$METRIC_VERDICTS" <<'PY'import os, re, sysfrom collections import defaultdict@@ -1331,14 +1457,16 @@ post_coalesced = counter(c2, fm, "result", "coalesced")post_trailing = counter(c2, fm, "result", "trailing")post_failed = counter(c2, fm, "result", "failed")problems = []-if pre_failed > 0 or post_failed > 0:+if pre_failed != 0 or post_failed > 0:problems.append(f"fleet pass failures (pre={pre_failed:.0f} post={post_failed:.0f})")-if post_started != 1:- problems.append(f"expected exactly one recovery fleet pass on the replacement pod, got started={post_started:.0f}")+if os.environ.get("FLEET_COMPLETION_PROVEN") != "1":+ problems.append("replacement-pod initial fleet completion was not causally proven")if post_trailing > post_coalesced:problems.append(f"trailing={post_trailing:.0f} > coalesced={post_coalesced:.0f} (violates the single-pending-slot structure)")-detail = (f"started={post_started:.0f} coalesced={post_coalesced:.0f} "- f"trailing={post_trailing:.0f} failed={post_failed:.0f} (pre-kill failed delta={pre_failed:.0f})")+detail = (f"completion-proven={os.environ.get('FLEET_COMPLETION_PROVEN', 'missing')} "+ f"started={post_started:.0f} coalesced={post_coalesced:.0f} "+ f"trailing={post_trailing:.0f} failed={post_failed:.0f} "+ f"(replacement pod; A4 recovery-success fenced; pre-kill failed delta={pre_failed:.0f})")if problems:verdicts.append(("A7-fleet-recovery-bounded", False, "; ".join(problems) + f" [{detail}]"))else:@@ -1391,11 +1519,7 @@ fi# The profile and seeded data (including the wake target) stay.# ======================================================================header "Teardown — storm fixtures (${FIXTURE_RUN_KEY}=${RUN_ID})"-if [[ "${KEEP_FIXTURES:-}" == '1' ]]; then- warn "KEEP_FIXTURES=1 — leaving fixtures in place for diagnosis (run-id ${RUN_ID})"- TEARDOWN_DONE=1-else- STORM_SEL="${FIXTURE_LABEL_KEY}=${FIXTURE_LABEL_VAL},${FIXTURE_RUN_KEY}=${RUN_ID}"+STORM_SEL="${FIXTURE_LABEL_KEY}=${FIXTURE_LABEL_VAL},${FIXTURE_RUN_KEY}=${RUN_ID}"kctl -n "$MCP_HOST_NS" delete host -l "$STORM_SEL" --wait=false >/dev/null 2>&1 || \warn "teardown: label-selector Host deletion returned nonzero (leftover check below is authoritative)"kctl -n "$MCP_HOST_NS" delete secret -l "$STORM_SEL" --wait=false >/dev/null 2>&1 || \@@ -1418,6 +1542,7 @@ elseok "teardown: all storm fixture Hosts deleted via the supported CR path"elsefail "teardown: storm fixture Hosts still present after ${STORM_TEARDOWN_DEADLINE_S}s (run-id ${RUN_ID})"+ TEARDOWN_CLEANUP_FAILED=1fi# FAIL-CLOSED (B2): an unverifiable read counts as a leftover — the teardown@@ -1484,14 +1609,19 @@ elseok "teardown: zero storm-fixture leftovers across ${BUNDLE_NAMESPACES} (profile and seeded data untouched)"elsefail "teardown: ${TEARDOWN_LEFTOVER} storm fixture subject(s) left resources behind (run-id ${RUN_ID}) — investigate before trusting results"+ TEARDOWN_CLEANUP_FAILED=1fi- TEARDOWN_DONE=1-fi+TEARDOWN_DONE=1# M3: on the success path a failed cadence restore must FAIL the gate# (restore_hcc_env_strict registers fail() and leaves HCC_ENV_SAVED for# the trap's best-effort retry); the EXIT trap keeps the lenient restore.restore_hcc_env_strict+if ! finalize_hcc_watch_gate_lock "$TEARDOWN_CLEANUP_FAILED" "$HCC_RESTORE_OK"; then+ fail "shared HCC fault-injection lock was retained fail-closed; follow the printed repair instructions"+else+ ok "exclusive shared HCC fault-injection lock finalized"+fiprint_resultsif [[ "$g_fail" -gt 0 ]]; thendiff --git a/scripts/tests/test-hcc-api-gateway-readiness.sh b/scripts/tests/test-hcc-api-gateway-readiness.shnew file mode 100644index 000000000..6623ff56e--- /dev/null+++ b/scripts/tests/test-hcc-api-gateway-readiness.sh@@ -0,0 +1,134 @@+#!/usr/bin/env bash+# Functions under test are evaluated from the E2E source, so ShellCheck cannot+# see their use of the mock environment variables declared by each harness.+# shellcheck disable=SC2034+set -euo pipefail++ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)"+DEPLOYMENT="${ROOT}/deploy/base/control-plane/host-context-controller-api-gateway.yaml"+CONFIGMAP="${ROOT}/deploy/base/control-plane/configmaps.yaml"+BOOTSTRAP_E2E="${ROOT}/scripts/e2e/e2e-hcc-readiness-bootstrap.sh"++fail() {+ echo "FAIL: $1" >&2+ exit 1+}++readiness_probe="$(+ awk '+ /^[[:space:]]*readinessProbe:/ { in_probe = 1; next }+ in_probe && /^[[:space:]]*resources:/ { exit }+ in_probe { print }+ ' "${DEPLOYMENT}"+)"++if ! grep -Eq '^[[:space:]]*path:[[:space:]]*/health[[:space:]]*$' <<<"${readiness_probe}"; then+ fail "HCC API gateway readiness probe must use the gateway-local /health endpoint"+fi+echo "PASS: HCC API gateway readiness probe uses the gateway-local /health endpoint"++hcc_config="$(+ awk '+ BEGIN { RS = "---" }+ /name:[[:space:]]*host-context-controller-api-gateway/ { print; exit }+ ' "${CONFIGMAP}"+)"++if [[ -z "${hcc_config}" ]]; then+ fail "HCC API gateway nginx ConfigMap is missing"+fi++health_location="$(+ awk '+ /^[[:space:]]*location = \/health \{/ { in_location = 1 }+ in_location { print }+ in_location && /^[[:space:]]*\}[[:space:]]*$/ { exit }+ ' <<<"${hcc_config}"+)"++if [[ "${health_location}" != *'return 200'* ]] ||+ [[ "${health_location}" == *'proxy_pass'* ]]; then+ fail "HCC API gateway /health must remain a local nginx health response"+fi+echo "PASS: HCC API gateway /health remains local to nginx"++ready_location="$(+ awk '+ /^[[:space:]]*location = \/ready \{/ { in_location = 1 }+ in_location { print }+ in_location && /^[[:space:]]*\}[[:space:]]*$/ { exit }+ ' <<<"${hcc_config}"+)"++if [[ "${ready_location}" != *'proxy_pass http://host_context_controller_upstream;'* ]]; then+ fail "HCC API gateway /ready must continue proxying the HCC readiness contract"+fi+echo "PASS: HCC API gateway /ready continues proxying HCC readiness"++runtime_hold_function="$(+ sed -n '/^hcc_gateway_remains_ready_without_hcc() {$/,/^}$/p' "${BOOTSTRAP_E2E}"+)"+unavailable_probe_function="$(+ sed -n '/^hcc_gateway_ready_proxy_unavailable() {$/,/^}$/p' "${BOOTSTRAP_E2E}"+)"+if [[ "${runtime_hold_function}" != *'hcc_gateway_deployment_ready'* ]] ||+ [[ "${runtime_hold_function}" != *'hcc_gateway_local_health_ok'* ]] ||+ [[ "${runtime_hold_function}" != *'hcc_gateway_ready_proxy_unavailable'* ]] ||+ ! grep -Fq 'hcc_gateway_remains_ready_without_hcc 20' "${BOOTSTRAP_E2E}"; then+ fail "bootstrap E2E must hold HCC unavailable across a full gateway probe-failure window"+fi+echo "PASS: bootstrap E2E proves gateway readiness remains local while HCC is unavailable"++if (+ HCC_NS=control-plane+ running_hcc_gateway_pod() { printf '%s\n' gateway-pod; }+ kctl() {+ printf '%s\n' ' HTTP/1.1 502 Bad Gateway'+ return 8+ }+ eval "${unavailable_probe_function}"+ hcc_gateway_ready_proxy_unavailable+); then+ echo "PASS: gateway hold accepts the explicit upstream-unavailable HTTP status"+else+ fail "gateway hold rejects the expected upstream-unavailable HTTP status"+fi++if (+ HCC_NS=control-plane+ running_hcc_gateway_pod() { printf '%s\n' gateway-pod; }+ kctl() {+ printf '%s\n' 'error: unable to upgrade connection: container not found'+ return 1+ }+ eval "${unavailable_probe_function}"+ ! hcc_gateway_ready_proxy_unavailable+); then+ echo "PASS: gateway hold rejects kubectl or container transport failure"+else+ fail "gateway hold can mistake kubectl or container transport failure for upstream unavailability"+fi++if (+ HCC_NS=control-plane+ running_hcc_gateway_pod() { printf '%s\n' gateway-pod; }+ kctl() {+ printf '%s\n' 'healthy upstream response'+ return 0+ }+ eval "${unavailable_probe_function}"+ ! hcc_gateway_ready_proxy_unavailable+); then+ echo "PASS: gateway hold rejects a successful proxied /ready response"+else+ fail "gateway hold can accept a successful proxied /ready response as unavailable"+fi++hold_line="$(grep -nF 'hcc_gateway_remains_ready_without_hcc 20' "${BOOTSTRAP_E2E}" | cut -d: -f1)"+restart_line="$(grep -nF 'kctl scale deployment "$HCC_DEPLOY" -n "$HCC_NS" --replicas=1' "${BOOTSTRAP_E2E}" | cut -d: -f1)"+recovery_line="$(grep -nF 'hcc_gateway_ready_proxy_recovers ||' "${BOOTSTRAP_E2E}" | cut -d: -f1)"+if [[ -z "${hold_line}" || -z "${restart_line}" || -z "${recovery_line}" ]] ||+ (( hold_line >= restart_line || restart_line >= recovery_line )); then+ fail "gateway unavailable/ready/recovery assertions must surround the HCC restart"+fi+echo "PASS: bootstrap E2E proves proxied /ready failure and recovery in causal order"diff --git a/scripts/tests/test-hcc-watch-recovery-gate.sh b/scripts/tests/test-hcc-watch-recovery-gate.shindex b73b3ccb3..562eb8705 100755--- a/scripts/tests/test-hcc-watch-recovery-gate.sh+++ b/scripts/tests/test-hcc-watch-recovery-gate.sh@@ -14,6 +14,13 @@ GATES=("$WATCH_GATE" "$READINESS_GATE" "$MCP_READINESS_GATE")LOCK_HELPER="${SCRIPT_DIR}/_lib/hcc-watch-recovery-lock.sh"LOG_HELPER="${SCRIPT_DIR}/_lib/hcc-watch-recovery-logs.sh"FIXTURE_HELPER="${SCRIPT_DIR}/_lib/hcc-watch-recovery-fixture.sh"+HCC_K8S_CLIENT="${ROOT}/host-context-controller/src/k8sClient.ts"+HCC_EGRESS_COORDINATOR="$(+ printf '%s' "${ROOT}/host-context-controller/src/externalEgressConvergenceCoordinator.ts"+)"+HCC_NETWORK_POLICY_RECONCILER="$(+ printf '%s' "${ROOT}/host-context-controller/src/networkPolicyReconciler.ts"+)"WATCH_GATE_TARGET="$(sed -n '/^test-e2e-hcc-communicationchannel-watch-recovery:/,/^$/p' "${ROOT}/Makefile")"MOCK_STATE_FILE="$(mktemp "${TMPDIR:-/tmp}/hcc-lock-test.XXXXXX")"MOCK_LOG_FILE="$(mktemp "${TMPDIR:-/tmp}/hcc-log-test.XXXXXX")"@@ -32,6 +39,24 @@ for script in "${GATES[@]}" "$LOCK_HELPER" "$LOG_HELPER" "$FIXTURE_HELPER"; dofidone+# A node carrying a minikube label from another profile must not satisfy the+# destructive-gate boundary. Each gate binds the label value to the explicit+# context instead of accepting any non-null label.+matching_nodes='{"items":[{"metadata":{"labels":{"minikube.k8s.io/name":"branch-profile"}}}]}'+mismatched_nodes='{"items":[{"metadata":{"labels":{"minikube.k8s.io/name":"other-profile"}}}]}'+if jq -e --arg context branch-profile \+ 'any(.items[]; .metadata.labels["minikube.k8s.io/name"] == $context)' \+ <<<"$matching_nodes" >/dev/null &&+ ! jq -e --arg context branch-profile \+ 'any(.items[]; .metadata.labels["minikube.k8s.io/name"] == $context)' \+ <<<"$mismatched_nodes" >/dev/null &&+ [ "$(grep -Fl 'minikube.k8s.io/name"] == $context' "${GATES[@]}" | wc -l | tr -d ' ')" = 3 ] &&+ ! grep -Fq 'minikube.k8s.io/name"] != null' "${GATES[@]}"; then+ pass "all destructive HCC gates bind the minikube node label to the explicit profile"+else+ fail "an HCC gate can accept a minikube node owned by another profile"+fi+# Literal source-code assertions.# shellcheck disable=SC2016if [[ "$WATCH_GATE_TARGET" == *'E2E_EXPECTED_PRE_GATE_GATE="$(E2E_EXPECTED_PRE_GATE_GATE)"'* ]] &&@@ -58,6 +83,31 @@ elsefail "proxy rollout failure can discard the distinguishing HCC startup evidence"fi+if (+ HCC_NS=control-plane+ HCC_DEPLOY='host-context-controller'+ kctl() {+ if [ "$1" = get ] && [ "$2" = pods ] && [[ "$*" == *"-o jsonpath="* ]]; then+ printf '%s\n' hcc-pod+ elif [ "$1" = get ] && [ "$2" = pods ]; then+ printf '%s\n' '{"items":[{"metadata":{"name":"hcc-pod"},"status":{"phase":"Pending","containerStatuses":[{"name":"host-context-controller","ready":false,"restartCount":2,"state":{"waiting":{"reason":"CrashLoopBackOff"}},"lastState":{}}]}}]}'+ elif [ "$1" = logs ]; then+ printf '%s\n' 'bounded diagnostic log'+ else+ return 1+ fi+ }+ eval "$proxy_rollout_function"+ output="$(print_hcc_proxy_rollout_diagnostics 2>&1)"+ [[ "$output" == *"pod=hcc-pod phase=Pending"* ]] &&+ [[ "$output" != *"pod=null"* ]] &&+ [[ "$output" != *"phase=null"* ]]+); then+ pass "proxy rollout diagnostics retain the parent pod identity and phase"+else+ fail "proxy rollout diagnostics lose pod metadata inside container status iteration"+fi+# The proxy changes only the HCC client's target hostname. The HCC's# allow-k8s-api-egress policies must retain the Kubernetes-injected API IP,# which is the explicit fail-closed configuration seam for CIDR policy data.@@ -84,6 +134,26 @@ elsefail "readiness gate duplicates, bypasses, or splits the shared branch-owned proof"fi+bootstrap_repair_function="$(+ sed -n '/^print_repair_instructions() {$/,/^}$/p' "$READINESS_GATE"+)"+mcp_repair_function="$(+ sed -n '/^print_repair_instructions() {$/,/^}$/p' "$MCP_READINESS_GATE"+)"+# Literal source-code assertions: every fail-closed repair path must restore+# the captured replica count before treating rollout health as repair proof.+# shellcheck disable=SC2016+if [[ "$bootstrap_repair_function" == *'scale deployment/${HCC_DEPLOY} --replicas=${ORIGINAL_REPLICAS:-1}'* ]] &&+ [[ "$bootstrap_repair_function" == *'rollout status deployment/${HCC_DEPLOY} --timeout=180s'* ]] &&+ [[ "$mcp_repair_function" == *'scale deployment/${HCC_DEPLOY} --replicas=${ORIGINAL_REPLICAS:-1}'* ]] &&+ [[ "$mcp_repair_function" == *'rollout status deployment/${HCC_DEPLOY} --timeout=240s'* ]] &&+ grep -Fq 'scale deployment/${HCC_DEPLOY} --replicas=${ORIGINAL_REPLICAS:-1}' "$WATCH_GATE" &&+ grep -Fq 'rollout status deployment/${HCC_DEPLOY} --timeout=180s' "$WATCH_GATE"; then+ pass "all HCC repair instructions restore the original replica count and verify rollout"+else+ fail "an HCC repair path can leave the controller scaled to zero"+fi+fixture_gate_function="$(sed -n '/^require_branch_owned_hcc_gate() {$/,/^}$/p' "$FIXTURE_HELPER")"marker_get_count="$(grep -Fc 'kctl get configmap clerum-pre-gate-sync-state' <<<"$fixture_gate_function"@@ -240,6 +310,12 @@ retry_progress_function="$(retry_rearmed_function="$(sed -n '/^external_egress_retry_rearmed_is_observed() {$/,/^}$/p' "$MCP_READINESS_GATE")"+hcc_log_count_function="$(+ sed -n '/^hcc_log_count() {$/,/^}$/p' "$MCP_READINESS_GATE"+)"+hcc_log_count_exceeds_function="$(+ sed -n '/^hcc_log_count_exceeds() {$/,/^}$/p' "$MCP_READINESS_GATE"+)"if (NEW_HCC_POD=hcc-podHCC_NS=control-plane@@ -265,6 +341,46 @@ if (elsefail "the injected DNS hold cannot distinguish expected live retry progress"fi+if (+ NEW_HCC_POD=hcc-pod+ HCC_NS=control-plane+ MCP_NS=mcp-server+ MCP_NAME=e2e-held-server+ CONTEXT_NAME=e2e-context+ MOCK_HCC_LOG='+[K8s] Initial external egress reconciliation failed for mcp-server/e2e-held-server; runtime reconciliation will stay blocked until retry succeeds: dns timeout+[K8s] Scheduling external egress retry 1/3 for McpServer "different-server" in 5000ms+[K8s] unrelated message for McpServer "e2e-held-server"+'+ kctl() { printf '%s\n' "$MOCK_HCC_LOG"; }+ eval "$retry_progress_function"+ ! external_egress_retry_progress_is_observed+); then+ pass "external-egress retry evidence cannot combine a peer retry with the fixture server marker"+else+ fail "external-egress retry evidence can be assembled from different log lines or servers"+fi+if (+ NEW_HCC_POD=hcc-pod+ HCC_NS=control-plane+ MCP_NS=mcp-server+ MCP_NAME=e2e-held-server+ CONTEXT_NAME=e2e-context+ MOCK_HCC_LOG='+[K8s] Initial external egress reconciliation failed for mcp-server/e2e-held-server; runtime reconciliation will stay blocked until retry succeeds: dns timeout+[K8s] Scheduling external egress retry 1/3 for McpServer "e2e-held-server" in 5000ms+'+ for ((line = 0; line < 4096; line++)); do+ MOCK_HCC_LOG+=$'\n[K8s] unrelated high-volume log line'+ done+ kctl() { printf '%s\n' "$MOCK_HCC_LOG"; }+ eval "$retry_progress_function"+ external_egress_retry_progress_is_observed+); then+ pass "an early matching retry line survives a high-volume log buffer without SIGPIPE ambiguity"+else+ fail "a valid early retry marker is lost in a high-volume log buffer"+fiif (NEW_HCC_POD=hcc-podHCC_NS=control-plane@@ -295,6 +411,351 @@ elsefail "the safety retry predicate passes vacuously when HCC logs are unavailable"fi+if (+ NEW_HCC_POD=hcc-pod+ HCC_NS=control-plane+ marker='[NetPol] Full reconciliation complete'+ MOCK_HCC_LOG="$marker"+ kctl() { printf '%s\n' "$MOCK_HCC_LOG"; }+ eval "$hcc_log_count_function"+ eval "$hcc_log_count_exceeds_function"+ baseline="$(hcc_log_count "$marker")" &&+ ! hcc_log_count_exceeds "$marker" "$baseline" &&+ MOCK_HCC_LOG="${MOCK_HCC_LOG}"$'\n'"$marker" &&+ hcc_log_count_exceeds "$marker" "$baseline"+); then+ pass "post-release NetworkPolicy waits require evidence newer than their baseline snapshot"+else+ fail "post-release NetworkPolicy waits can pass on a pre-release log marker"+fi+# Literal source-code assertions bind both final waits to their pre-release+# counters; a plain contains check would make either wait vacuous.+# shellcheck disable=SC2016+if grep -Fq 'initial_policy_run_count_before_release="$(hcc_log_count "$initial_policy_run_marker")"' \+ "$MCP_READINESS_GATE" &&+ grep -Fq 'initial_policy_complete_count_before_release="$(' "$MCP_READINESS_GATE" &&+ [ "$(grep -Fc 'hcc_log_count_exceeds \' "$MCP_READINESS_GATE")" = 2 ]; then+ pass "both final NetworkPolicy waits are causally fenced by pre-release counts"+else+ fail "a final NetworkPolicy wait is not fenced from earlier startup logs"+fi++# Keep the runtime log contract consumed above tied to its producer. Template+# literals are checked as their fixed text plus the variable that supplies the+# dynamic identity, avoiding a rendered-string grep that would produce false+# drift reports.+if grep -Fq 'Initial external egress reconciliation failed for ${key};' \+ "$HCC_EGRESS_COORDINATOR" &&+ grep -Fq 'Scheduling external egress retry ${attempt}/${EXTERNAL_EGRESS_RETRY_DELAYS_MS.length}' \+ "$HCC_EGRESS_COORDINATOR" &&+ grep -Fq 'for McpServer "${this.retryIntents.get(key)!.server.name}"' \+ "$HCC_EGRESS_COORDINATOR" &&+ grep -Fq 'Initial NetworkPolicy background reconciliation failed:' \+ "$HCC_K8S_CLIENT" &&+ grep -Fq 'Scheduling initial ${lane} background convergence retry ${attempt}' \+ "$HCC_K8S_CLIENT" &&+ grep -Fq 'Context watch event: ${type} for ${context.name}' \+ "$HCC_K8S_CLIENT" &&+ grep -Fq 'Running initial NetworkPolicy background reconciliation...' \+ "$HCC_K8S_CLIENT" &&+ grep -Fq 'Reconciling context "${contextId}" — allowed servers: [${allowedServers.join(' \+ "$HCC_NETWORK_POLICY_RECONCILER" &&+ grep -Fq "[NetPol] Full reconciliation complete" \+ "$HCC_NETWORK_POLICY_RECONCILER"; then+ pass "MCP readiness log predicates remain bound to their runtime producers"+else+ fail "an MCP readiness log predicate drifted from its runtime producer"+fi++fixture_mcp_runtime_absent_function="$(+ sed -n '/^fixture_mcp_runtime_absent() {$/,/^}$/p' "$MCP_READINESS_GATE"+)"+hcc_kubernetes_readiness_function="$(+ sed -n '/^hcc_kubernetes_readiness_is_exact() {$/,/^}$/p' "$MCP_READINESS_GATE"+)"+external_policy_protocol_function="$(+ sed -n '/^external_egress_policy_converged_with_protocol() {$/,/^}$/p' \+ "$MCP_READINESS_GATE"+)"+hcc_ready_after_revoke_function="$(+ sed -n '/^hcc_ready_after_stale_policy_revoked() {$/,/^}$/p' "$MCP_READINESS_GATE"+)"+ready_probe_function="$(+ sed -n '/^probe_new_hcc_ready_endpoint() {$/,/^}$/p' "$MCP_READINESS_GATE"+)"++run_ready_probe_failure_case() (+ local expected=$1+ MOCK_READY_PROBE_OUTPUT=$2+ NEW_HCC_POD=hcc-pod+ HCC_NS=control-plane+ HCC_PORT=8080+ HCC_READY_PROBE_DIAGNOSTIC=""+ kctl() {+ printf '%s\n' "$MOCK_READY_PROBE_OUTPUT"+ return 1+ }+ eval "$ready_probe_function"+ ! probe_new_hcc_ready_endpoint &&+ [ "$HCC_READY_PROBE_DIAGNOSTIC" = "HCC_READY_PROBE category=${expected}" ]+)++if run_ready_probe_failure_case timeout 'HCC_READY_PROBE category=timeout' &&+ run_ready_probe_failure_case transport 'HCC_READY_PROBE category=transport' &&+ run_ready_probe_failure_case 'http-status status=503' \+ 'HCC_READY_PROBE category=http-status status=503' &&+ run_ready_probe_failure_case json-ready-false \+ 'HCC_READY_PROBE category=json-ready-false'; then+ pass "ready probe preserves distinct timeout, transport, HTTP, and ready=false diagnostics"+else+ fail "ready probe collapses a failure boundary into an indiagnostic boolean"+fi+if (+ NEW_HCC_POD=hcc-pod+ HCC_NS=control-plane+ HCC_PORT=8080+ HCC_READY_PROBE_DIAGNOSTIC="stale"+ kctl() { return 0; }+ eval "$ready_probe_function"+ probe_new_hcc_ready_endpoint && [ -z "$HCC_READY_PROBE_DIAGNOSTIC" ]+); then+ pass "successful ready probe clears stale failure diagnostics"+else+ fail "successful ready probe retains a misleading prior diagnostic"+fi+if (+ NEW_HCC_POD=hcc-pod+ HCC_NS=control-plane+ HCC_PORT=8080+ HCC_READY_PROBE_DIAGNOSTIC=""+ kctl() {+ printf '%s\n' 'untrusted kubectl output containing super-secret material'+ return 1+ }+ eval "$ready_probe_function"+ ! probe_new_hcc_ready_endpoint &&+ [ "$HCC_READY_PROBE_DIAGNOSTIC" = 'HCC_READY_PROBE category=kubectl-exec' ]+); then+ pass "ready probe replaces untrusted exec output with a bounded sanitized category"+else+ fail "ready probe can leak untrusted exec output into diagnostics"+fi+# Literal source-code assertions guarantee one request and bounded categories,+# without logging the response body, headers, URL, or transport error text.+if [ "$(grep -Fc 'kctl exec' <<<"$ready_probe_function")" = 1 ] &&+ [[ "$ready_probe_function" == *'finish(4, "timeout")'* ]] &&+ [[ "$ready_probe_function" == *'finish(5, "transport")'* ]] &&+ [[ "$ready_probe_function" == *'finish(3, "http-status"'* ]] &&+ [[ "$ready_probe_function" == *'finish(3, "json-ready-false")'* ]] &&+ [[ "$ready_probe_function" == *"printf -v HCC_READY_PROBE_DIAGNOSTIC '%.240s'"* ]] &&+ [[ "$ready_probe_function" != *'console.error(body'* ]] &&+ [[ "$ready_probe_function" != *'error.message'* ]]; then+ pass "ready probe uses one request and emits only bounded non-secret failure categories"+else+ fail "ready probe duplicates requests or exposes an unbounded diagnostic surface"+fi++if (+ MCP_NS=mcp-server+ MCP_NAME=e2e-held-server+ MCP_SERVER_LABEL=clerum.io/mcp-server+ POLICY_TYPE_LABEL=clerum.io/policy-type+ fixture_runtime_absent() { return 0; }+ kctl() { return 0; }+ eval "$fixture_mcp_runtime_absent_function"+ fixture_mcp_runtime_absent+); then+ pass "fixture absence predicate accepts an absent runtime and external-egress policy"+else+ fail "fixture absence predicate rejects an actually absent runtime"+fi+if (+ MCP_NS=mcp-server+ MCP_NAME=e2e-held-server+ MCP_SERVER_LABEL=clerum.io/mcp-server+ POLICY_TYPE_LABEL=clerum.io/policy-type+ fixture_runtime_absent() { return 0; }+ kctl() { printf '%s\n' 'networkpolicy.networking.k8s.io/stale-policy'; }+ eval "$fixture_mcp_runtime_absent_function"+ ! fixture_mcp_runtime_absent+); then+ pass "fixture absence predicate rejects a surviving external-egress policy"+else+ fail "fixture absence predicate can hide a surviving external-egress policy"+fi+if (+ MCP_NS=mcp-server+ MCP_NAME=e2e-held-server+ MCP_SERVER_LABEL=clerum.io/mcp-server+ POLICY_TYPE_LABEL=clerum.io/policy-type+ fixture_runtime_absent() { return 1; }+ kctl() { return 0; }+ eval "$fixture_mcp_runtime_absent_function"+ ! fixture_mcp_runtime_absent+); then+ pass "fixture absence predicate rejects a surviving MCP runtime"+else+ fail "fixture absence predicate can hide a surviving MCP runtime"+fi++if (+ NEW_HCC_POD=hcc-pod+ HCC_UID=pod-uid+ HCC_NS=control-plane+ HCC_DEPLOY='host-context-controller'+ kctl() {+ case "$2" in+ pod)+ printf '%s\n' '{"metadata":{"uid":"pod-uid"},"status":{"conditions":[{"type":"Ready","status":"True"}],"containerStatuses":[{"name":"host-context-controller","ready":true}]}}'+ ;;+ deployment)+ printf '%s\n' '{"metadata":{"generation":4},"spec":{"replicas":1},"status":{"observedGeneration":4,"updatedReplicas":1,"readyReplicas":1,"availableReplicas":1,"unavailableReplicas":0}}'+ ;;+ *) return 1 ;;+ esac+ }+ eval "$hcc_kubernetes_readiness_function"+ hcc_kubernetes_readiness_is_exact+); then+ pass "exact Kubernetes readiness accepts one current Ready HCC identity"+else+ fail "exact Kubernetes readiness rejects current Ready HCC evidence"+fi+if (+ NEW_HCC_POD=hcc-pod+ HCC_UID=pod-uid+ HCC_NS=control-plane+ HCC_DEPLOY='host-context-controller'+ kctl() {+ case "$2" in+ pod)+ printf '%s\n' '{"metadata":{"uid":"pod-uid"},"status":{"conditions":[{"type":"Ready","status":"True"}],"containerStatuses":[{"name":"host-context-controller","ready":true}]}}'+ ;;+ deployment)+ printf '%s\n' '{"metadata":{"generation":5},"spec":{"replicas":1},"status":{"observedGeneration":4,"updatedReplicas":1,"readyReplicas":1,"availableReplicas":1,"unavailableReplicas":0}}'+ ;;+ *) return 1 ;;+ esac+ }+ eval "$hcc_kubernetes_readiness_function"+ ! hcc_kubernetes_readiness_is_exact+); then+ pass "exact Kubernetes readiness rejects a stale Deployment generation"+else+ fail "exact Kubernetes readiness can accept stale Deployment status"+fi++if (+ MCP_NS=mcp-server+ MCP_NAME=e2e-held-server+ MCP_SERVER_LABEL=clerum.io/mcp-server+ POLICY_TYPE_LABEL=clerum.io/policy-type+ MANAGED_BY_LABEL=app.kubernetes.io/managed-by+ MANAGED_BY_VALUE='host-context-controller'+ EXTERNAL_EGRESS_CIDR=203.0.113.10/32+ EXTERNAL_EGRESS_PORT=443+ kctl() {+ printf '%s\n' '{"items":[{"metadata":{"labels":{"app.kubernetes.io/managed-by":"host-context-controller","clerum.io/policy-type":"external-egress","clerum.io/mcp-server":"e2e-held-server"}},"spec":{"podSelector":{"matchLabels":{"clerum.io/mcp-server":"e2e-held-server"}},"policyTypes":["Egress"],"egress":[{"ports":[{"port":443,"protocol":"UDP"}],"to":[{"ipBlock":{"cidr":"203.0.113.10/32"}}]}]}}]}'+ }+ eval "$external_policy_protocol_function"+ external_egress_policy_converged_with_protocol UDP &&+ ! external_egress_policy_converged_with_protocol TCP+); then+ pass "external-egress convergence binds the exact current protocol"+else+ fail "external-egress convergence can accept a stale protocol"+fi++mcpserver_current_ready_function="$(+ sed -n '/^mcpserver_current_ready() {$/,/^}$/p' "$MCP_READINESS_GATE"+)"+mcpserver_current_ready_absent_function="$(+ sed -n '/^mcpserver_current_ready_absent() {$/,/^}$/p' "$MCP_READINESS_GATE"+)"+fixture_runtime_and_ready_absent_function="$(+ sed -n '/^fixture_runtime_and_ready_absent() {$/,/^}$/p' "$MCP_READINESS_GATE"+)"+fixture_runtime_converged_function="$(+ sed -n '/^fixture_runtime_converged_with_protocol() {$/,/^}$/p' "$MCP_READINESS_GATE"+)"+peer_fleet_converged_function="$(+ sed -n '/^peer_fleet_converged() {$/,/^}$/p' "$MCP_READINESS_GATE"+)"+fixture_converged_function="$(+ sed -n '/^fixture_converged() {$/,/^}$/p' "$MCP_READINESS_GATE"+)"+if (+ MCP_NS=mcp-server+ GENERATION=7+ OBSERVED_GENERATION=7+ kctl() {+ printf '{"metadata":{"generation":%s},"status":{"conditions":[{"type":"Ready","status":"True","observedGeneration":%s}]}}\n' \+ "$GENERATION" "$OBSERVED_GENERATION"+ }+ eval "$mcpserver_current_ready_function"+ eval "$mcpserver_current_ready_absent_function"+ mcpserver_current_ready current &&+ ! mcpserver_current_ready_absent current &&+ OBSERVED_GENERATION=6 &&+ ! mcpserver_current_ready stale &&+ mcpserver_current_ready_absent stale+) &&+ [[ "$fixture_runtime_and_ready_absent_function" == *'mcpserver_current_ready_absent "$MCP_NAME"'* ]] &&+ [[ "$fixture_runtime_converged_function" == *'mcpserver_current_ready "$MCP_NAME"'* ]] &&+ [[ "$peer_fleet_converged_function" == *'mcpserver_current_ready "$server"'* ]] &&+ [[ "$fixture_converged_function" == *'mcpserver_current_ready "$MCP_NAME"'* ]]; then+ pass "McpServer runtime predicates accept only Ready status observed for the current generation"+else+ fail "McpServer runtime predicates can accept stale Ready status or bypass the canonical check"+fi++if (+ MCP_NS=mcp-server+ MCP_NAME=e2e-held-server+ fixture_runtime_absent() { return 0; }+ kctl() { return 1; }+ eval "$mcpserver_current_ready_absent_function"+ eval "$fixture_runtime_and_ready_absent_function"+ ! fixture_runtime_and_ready_absent+); then+ pass "McpServer Ready absence fails closed when the API read is unavailable"+else+ fail "an unavailable McpServer API read can masquerade as Ready absence"+fi++if (+ probe_new_hcc_ready_endpoint() { return 0; }+ external_egress_policy_absent() { return 0; }+ eval "$hcc_ready_after_revoke_function"+ hcc_ready_after_stale_policy_revoked+); then+ pass "divergent DNS hold permits global readiness only after stale-policy revocation"+else+ fail "divergent DNS hold rejects globally safe readiness evidence"+fi+if (+ HCC_READY_PROBE_DIAGNOSTIC=""+ probe_new_hcc_ready_endpoint() { return 0; }+ external_egress_policy_absent() { return 1; }+ eval "$hcc_ready_after_revoke_function"+ ! hcc_ready_after_stale_policy_revoked &&+ [ "$HCC_READY_PROBE_DIAGNOSTIC" = 'HCC_READY_PROBE category=stale-policy-present' ]+); then+ pass "global readiness evidence rejects a surviving divergent policy"+else+ fail "global readiness can self-confirm while a divergent policy survives"+fi+if (+ probe_new_hcc_ready_endpoint() { return 1; }+ external_egress_policy_absent() { return 0; }+ eval "$hcc_ready_after_revoke_function"+ ! hcc_ready_after_stale_policy_revoked+); then+ pass "stale-policy revocation alone cannot substitute for global readiness"+else+ fail "divergent hold evidence can pass without HCC readiness"+fi+# shellcheck source=scripts/e2e/_lib/hcc-watch-recovery-logs.shsource "$LOG_HELPER"HCC_LOG_BUFFER="$MOCK_LOG_FILE"@@ -383,29 +844,41 @@ elsefail "peer fleet cleanup is armed only after all applies complete"fi-readiness_boundary_function="$(- sed -n '/^hcc_ready_only_after_current_policy_applied() {$/,/^}$/p' "$MCP_READINESS_GATE"+divergent_ready_function="$(+ sed -n '/^hcc_ready_after_stale_policy_revoked() {$/,/^}$/p' "$MCP_READINESS_GATE")"-direct_ready_line="$(- grep -nF 'wait_until_fast 120 "HCC /ready only after the current replacement policy is applied"' \+divergent_ready_line="$(+ grep -nF 'wait_until_fast 120 "HCC readiness after revoking the divergent stale policy"' \"$MCP_READINESS_GATE" | cut -d: -f1)"-kubernetes_ready_line="$(- grep -nF 'wait_until 30 "replacement HCC pod and Deployment to corroborate readiness"' \+divergent_context_line="$(+ grep -nF 'wait_until 120 "all three latest-Context NetworkPolicies to converge during the MCP hold"' \+ "$MCP_READINESS_GATE" | cut -d: -f1+)"+divergent_release_line="$(+ grep -nF 'release_dns_blocker ||' "$MCP_READINESS_GATE" | tail -1 | cut -d: -f1+)"+udp_policy_line="$(+ grep -nF 'wait_until 120 "current UDP external-egress policy after DNS release"' \"$MCP_READINESS_GATE" | cut -d: -f1)"# shellcheck disable=SC2016-if [[ "$readiness_boundary_function" == *'probe_new_hcc_ready_endpoint || return 1'* ]] &&- [[ "$readiness_boundary_function" == *'external_egress_policy_converged ||'* ]] &&- [ -n "$direct_ready_line" ] && [ -n "$kubernetes_ready_line" ] &&- [ "$direct_ready_line" -lt "$kubernetes_ready_line" ]; then- pass "direct /ready ordering is asserted against current policy materialization before Kubernetes corroboration"+if [[ "$divergent_ready_function" == *'probe_new_hcc_ready_endpoint || return 1'* ]] &&+ [[ "$divergent_ready_function" == *'external_egress_policy_absent'* ]] &&+ [ -n "$divergent_ready_line" ] && [ -n "$divergent_context_line" ] &&+ [ -n "$divergent_release_line" ] && [ -n "$udp_policy_line" ] &&+ [ "$divergent_ready_line" -lt "$divergent_context_line" ] &&+ [ "$divergent_context_line" -lt "$divergent_release_line" ] &&+ [ "$divergent_release_line" -lt "$udp_policy_line" ] &&+ ! grep -Fq 'probe_new_hcc_unready_endpoint' "$MCP_READINESS_GATE" &&+ ! grep -Fq '/ready is 503' "$MCP_READINESS_GATE"; then+ pass "divergent DNS hold proves global readiness, fail-closed runtime isolation, and post-release UDP convergence"else- fail "readiness ordering still relies on the delayed Kubernetes Pod Ready signal"+ fail "the MCP gate still couples global readiness to divergent DNS replacement"fi-same_intent_capture_line="$(- grep -nF 'CERTIFIED_POLICY_IDENTITY="$(external_egress_policy_identity)"' \+initial_tcp_policy_line="$(+ grep -nF 'wait_until 180 "HCC to create the real initial TCP external-egress policy"' \"$MCP_READINESS_GATE" | cut -d: -f1)"same_intent_retry_line="$(@@ -413,11 +886,11 @@ same_intent_retry_line="$("$MCP_READINESS_GATE" | cut -d: -f1)"same_intent_ready_line="$(- grep -nF 'wait_until_fast 60 "HCC /ready with a certified policy while DNS refresh is held"' \+ grep -nF 'wait_until_fast 60 "HCC readiness after revoking the same-intent DNS policy"' \"$MCP_READINESS_GATE" | cut -d: -f1)"same_intent_incomplete_line="$(- grep -nF 'HCC became ready only after the held fleet runtime resources had already converged' \+ grep -nF 'the affected runtime or Ready status escaped the held same-intent DNS boundary' \"$MCP_READINESS_GATE" | cut -d: -f1)"same_intent_retry_execution_line="$(@@ -425,26 +898,40 @@ same_intent_retry_execution_line="$("$MCP_READINESS_GATE" | cut -d: -f1)"same_intent_recheck_line="$(- grep -nF 'a same-intent retry deleted or rewrote the certified policy' \+ grep -nF 'a held same-intent retry recreated the DNS policy without current resolution' \+ "$MCP_READINESS_GATE" | cut -d: -f1+)"+same_intent_release_line="$(+ grep -nF 'release_dns_blocker || die "could not release the same-intent DNS query"' \+ "$MCP_READINESS_GATE" | cut -d: -f1+)"+same_intent_tcp_policy_line="$(+ grep -nF 'wait_until 120 "current TCP external-egress policy after same-intent DNS release"' \"$MCP_READINESS_GATE" | cut -d: -f1)"divergent_revoke_line="$(- grep -nF 'wait_until_fast 120 "HCC to stay unready after revoking the divergent stale policy"' \+ grep -nF 'wait_until_fast 120 "HCC readiness after revoking the divergent stale policy"' \"$MCP_READINESS_GATE" | cut -d: -f1)"-if [ -n "$same_intent_capture_line" ] && [ -n "$same_intent_retry_line" ] &&+if [ -n "$initial_tcp_policy_line" ] && [ -n "$same_intent_retry_line" ] &&[ -n "$same_intent_ready_line" ] && [ -n "$same_intent_incomplete_line" ] &&[ -n "$same_intent_retry_execution_line" ] &&- [ -n "$same_intent_recheck_line" ] && [ -n "$divergent_revoke_line" ] &&- [ "$same_intent_capture_line" -lt "$same_intent_ready_line" ] &&+ [ -n "$same_intent_recheck_line" ] && [ -n "$same_intent_release_line" ] &&+ [ -n "$same_intent_tcp_policy_line" ] && [ -n "$divergent_revoke_line" ] &&+ [ "$initial_tcp_policy_line" -lt "$same_intent_ready_line" ] &&[ "$same_intent_ready_line" -lt "$same_intent_incomplete_line" ] &&[ "$same_intent_incomplete_line" -lt "$same_intent_retry_line" ] &&[ "$same_intent_retry_line" -lt "$same_intent_retry_execution_line" ] &&[ "$same_intent_retry_execution_line" -lt "$same_intent_recheck_line" ] &&- [ "$same_intent_recheck_line" -lt "$divergent_revoke_line" ]; then- pass "same-intent UID/spec preservation through retry precedes divergent fail-closed revocation"+ [ "$same_intent_recheck_line" -lt "$same_intent_release_line" ] &&+ [ "$same_intent_release_line" -lt "$same_intent_tcp_policy_line" ] &&+ [ "$same_intent_tcp_policy_line" -lt "$divergent_revoke_line" ] &&+ ! grep -Fq 'CERTIFIED_POLICY_IDENTITY' "$MCP_READINESS_GATE" &&+ ! grep -Fq 'external_egress_policy_identity' "$MCP_READINESS_GATE" &&+ ! grep -Fq 'UID/spec' "$MCP_READINESS_GATE"; then+ pass "same-intent safety revokes before readiness and additive TCP convergence follows DNS release"else- fail "the MCP readiness gate does not cover both DNS availability and revocation contracts"+ fail "the MCP readiness gate still preserves a DNS policy or gates readiness on additive convergence"fiprintf '%s\n' \@@ -583,6 +1070,26 @@ fiactive_guard_function="$(sed -n '/^initial_host_pass_is_active() {$/,/^}$/p' "$READINESS_GATE")"+initial_host_startup_producer="$(+ sed -n \+ '/Starting initial Host background convergence/,/const resyncSec = config.hostResyncIntervalSec/p' \+ "$HCC_K8S_CLIENT"+)"+# The bootstrap guard's negative COMPLETE/FAIL checks are safe only while all+# three consumed markers remain bound to the runtime templates and the startup+# call supplies the exact reason that renders the terminal pair.+if grep -Fq 'Starting initial Host background convergence...' \+ "$HCC_K8S_CLIENT" &&+ grep -Fq 'Completed Host reconciliation after ${reason}' \+ "$HCC_K8S_CLIENT" &&+ grep -Fq 'Host reconciliation after ${reason} failed:' \+ "$HCC_K8S_CLIENT" &&+ [[ "$initial_host_startup_producer" == *'await this.recoverHostInventoryAndWatch('* ]] &&+ [[ "$initial_host_startup_producer" == *"'initial Host reconciliation',"* ]]; then+ pass "bootstrap START/COMPLETE/FAIL markers remain bound to the initial Host producer reason"+else+ fail "bootstrap Host pass markers drifted from their runtime producer or reason binding"+fi# shellcheck disable=SC2016probe_result_line="$(grep -nF 'probe_result="$(kctl exec' "$READINESS_GATE" | cut -d: -f1)"# shellcheck disable=SC2016@@ -705,7 +1212,7 @@ if grep -Fq 'source "${SCRIPT_DIR}/_lib/hcc-watch-recovery-fixture.sh"' \grep -Fq 'hcc_pods_absent' "$MCP_READINESS_GATE" &&! grep -Fq -- '--for=delete' "$MCP_READINESS_GATE" &&! grep -Fq 'port: 8081' "$MCP_READINESS_GATE" &&- [ "$mcp_port_probe_count" = 4 ] &&+ [ "$mcp_port_probe_count" = 3 ] &&[ "$mcp_pod_absence_count" = 4 ]; thenpass "MCP readiness gate shares exact-head ownership and uses bounded portable runtime probes"else@@ -719,10 +1226,15 @@ fi# must exist while HCC is stopped, otherwise it would not exercise startup.mcp_peer_create_line="$(grep -nF 'create_peer_fleet || die' "$MCP_READINESS_GATE" | cut -d: -f1)"mcp_restart_line="$(grep -nF 'kctl scale deployment "$HCC_DEPLOY" -n "$HCC_NS" --replicas=1' "$MCP_READINESS_GATE" | tail -1 | cut -d: -f1)"+peer_fleet_converged_body="$(+ sed -n '/^peer_fleet_converged() {$/,/^}$/p' "$MCP_READINESS_GATE"+)"if grep -Fq 'MCP_FLEET_SIZE="${E2E_HCC_MCP_FLEET_SIZE:-11}"' "$MCP_READINESS_GATE" &&grep -Fq '[ "$MCP_FLEET_SIZE" -gt 10 ]' "$MCP_READINESS_GATE" &&grep -Fq 'create_peer_fleet' "$MCP_READINESS_GATE" &&grep -Fq 'peer_fleet_converged' "$MCP_READINESS_GATE" &&+ [[ "$peer_fleet_converged_body" == *'mcpserver_current_ready "$server"'* ]] &&+ [[ "$peer_fleet_converged_body" == *'context_policies_converged "$context" "$context" "$server"'* ]] &&grep -Fq 'all peer MCP/Context runtimes to converge after releasing the held primary egress' "$MCP_READINESS_GATE" &&[ -n "$mcp_peer_create_line" ] && [ -n "$mcp_restart_line" ] &&[ "$mcp_peer_create_line" -lt "$mcp_restart_line" ]; thendiff --git a/scripts/tests/test-host-storm-metric-gate.sh b/scripts/tests/test-host-storm-metric-gate.shindex b0c86764c..829634095 100755--- a/scripts/tests/test-host-storm-metric-gate.sh+++ b/scripts/tests/test-host-storm-metric-gate.sh@@ -24,6 +24,7 @@ extract_adjudicator() {write_metrics() {local path=$1 le_05=$2 le_5=$3 le_15=$4 total=$5 fleet_started=${6:-0}+ local fleet_coalesced=${7:-0} fleet_trailing=${8:-0} fleet_failed=${9:-0}cat >"$path" <<EOF# TYPE clerum_hcc_host_delete_cleanup_total counterclerum_hcc_host_delete_cleanup_total{outcome="queued"} 0@@ -32,9 +33,9 @@ clerum_hcc_host_delete_cleanup_total{outcome="completed"} 0clerum_hcc_host_delete_cleanup_total{outcome="retried"} 0clerum_hcc_host_delete_cleanup_total{outcome="superseded"} 0clerum_hcc_host_fleet_requests_total{result="started"} ${fleet_started}-clerum_hcc_host_fleet_requests_total{result="coalesced"} 0-clerum_hcc_host_fleet_requests_total{result="trailing"} 0-clerum_hcc_host_fleet_requests_total{result="failed"} 0+clerum_hcc_host_fleet_requests_total{result="coalesced"} ${fleet_coalesced}+clerum_hcc_host_fleet_requests_total{result="trailing"} ${fleet_trailing}+clerum_hcc_host_fleet_requests_total{result="failed"} ${fleet_failed}clerum_hcc_host_reconcile_queue_wait_seconds_bucket{lane="urgent",outcome="success",le="0.5"} ${le_05}clerum_hcc_host_reconcile_queue_wait_seconds_bucket{lane="urgent",outcome="success",le="5"} ${le_5}clerum_hcc_host_reconcile_queue_wait_seconds_bucket{lane="urgent",outcome="success",le="15"} ${le_15}@@ -65,7 +66,7 @@ write_metrics "${WORK_DIR}/d.prom" 10 10 10 10write_metrics "${WORK_DIR}/wake_post.prom" 19 19 20 20run_adjudicator() {- local wake_post=$1+ local wake_post=$1 fleet_completion_proven=${2:-1}SCRAPE_A="${WORK_DIR}/a.prom" \SCRAPE_B="${WORK_DIR}/b.prom" \SCRAPE_C1="${WORK_DIR}/c1.prom" \@@ -80,6 +81,7 @@ run_adjudicator() {P95_BUDGET_S=5 \RECOVERY_BUDGET_S=15 \MIN_URGENT_SAMPLES=10 \+ FLEET_COMPLETION_PROVEN="$fleet_completion_proven" \python3 "$ADJUDICATOR"}@@ -97,6 +99,33 @@ HEALTHY_OUTPUT="$(run_adjudicator "${WORK_DIR}/wake_healthy.prom")"grep -Fq 'VERDICT|A2-wake-urgent-hard-gate|PASS|' <<<"$HEALTHY_OUTPUT" ||fail "healthy wake window did not pass its hard gate"+# A7 is fenced to the replacement pod's explicit initial-fleet COMPLETED log.+# A second non-overlapping request can therefore be legitimate activity after+# recovery; an absolute started==1 assertion must not false-red it.+write_metrics "${WORK_DIR}/c2.prom" 0 0 0 0 2+TWO_STARTS_OUTPUT="$(run_adjudicator "${WORK_DIR}/wake_healthy.prom")"+grep -Fq 'VERDICT|A7-fleet-recovery-bounded|PASS|' <<<"$TWO_STARTS_OUTPUT" ||+ fail "healthy replacement-pod recovery false-reds when a second sequential fleet request starts"++write_metrics "${WORK_DIR}/c2.prom" 0 0 0 0 0+NO_START_OUTPUT="$(run_adjudicator "${WORK_DIR}/wake_healthy.prom")"+grep -Fq 'VERDICT|A7-fleet-recovery-bounded|PASS|' <<<"$NO_START_OUTPUT" ||+ fail "A7 still treats a scheduled counter as stronger than causal completion evidence"++NO_COMPLETION_OUTPUT="$(run_adjudicator "${WORK_DIR}/wake_healthy.prom" 0)"+grep -Fq 'VERDICT|A7-fleet-recovery-bounded|FAIL|' <<<"$NO_COMPLETION_OUTPUT" ||+ fail "A7 false-passed without replacement-pod fleet completion evidence"++write_metrics "${WORK_DIR}/c2.prom" 0 0 0 0 2 0 0 1+FAILED_PASS_OUTPUT="$(run_adjudicator "${WORK_DIR}/wake_healthy.prom")"+grep -Fq 'VERDICT|A7-fleet-recovery-bounded|FAIL|' <<<"$FAILED_PASS_OUTPUT" ||+ fail "A7 false-passed a failed replacement-pod fleet pass"++write_metrics "${WORK_DIR}/c2.prom" 0 0 0 0 2 1 2+UNBOUNDED_TRAILING_OUTPUT="$(run_adjudicator "${WORK_DIR}/wake_healthy.prom")"+grep -Fq 'VERDICT|A7-fleet-recovery-bounded|FAIL|' <<<"$UNBOUNDED_TRAILING_OUTPUT" ||+ fail "A7 false-passed trailing fleet work without a matching coalesced request"+WAKE_EVIDENCE_FUNCTION="$(sed -n '/^_wake_urgent_evidence_recorded() {$/,/^}$/p' "$GATE")"@@ -183,4 +212,69 @@ if [[ -z "$fresh_scrape_line" || -z "$kill_line" ]] ||fail "fresh scrape B does not precede the HCC kill"fi-echo "PASS: host-storm oracle binds wake generation, fences metrics, and refreshes the pre-kill baseline"+# The destructive Host storm must use the same exact-HEAD/profile/fingerprint+# ownership contract and exclusive compare-and-swap lock as every HCC gate.+# shellcheck disable=SC2016+for required in \+ 'source "${SCRIPT_DIR}/e2e-lib.sh"' \+ 'source "${SCRIPT_DIR}/_lib/hcc-watch-recovery-fixture.sh"' \+ 'source "${SCRIPT_DIR}/_lib/hcc-watch-recovery-lock.sh"' \+ 'require_branch_owned_hcc_gate "$CONTROL_NS"' \+ 'acquire_hcc_watch_gate_lock' \+ 'finalize_hcc_watch_gate_lock'; do+ grep -Fq "$required" "$GATE" ||+ fail "Host storm omits shared HCC gate contract: ${required}"+done+grep -Fq '.metadata.labels["minikube.k8s.io/name"] == $context' "$GATE" ||+ fail "Host storm does not bind the node's exact minikube profile label"+grep -Fq 'MINIKUBE_PROFILE must explicitly select context' \+ "${ROOT}/scripts/e2e/_lib/hcc-watch-recovery-fixture.sh" ||+ fail "shared profile ownership helper no longer binds MINIKUBE_PROFILE"++# Branch-owned URLs must come from the selected profile's ports.env. Fixed+# machine-global service or metrics ports are a cross-worktree false-green risk.+grep -Fq 'CLERUM_PROFILE_PORTS_ENV' "$GATE" ||+ fail "Host storm does not load branch-profile port evidence"+grep -Fq 'profile_env_value EXTERNAL_REST_API_URL' "$GATE" ||+ fail "Host storm does not derive External REST from branch ports.env"+grep -Fq 'profile_env_value RPC_PROXY_URL' "$GATE" ||+ fail "Host storm does not derive RPC proxy from branch ports.env"+if grep -Eq '127\.0\.0\.1:(8091|8094|18082)' "$GATE"; then+ fail "Host storm retains a fixed machine-global service or metrics port"+fi+grep -Fq '"pod/${pod}" ":${HCC_PORT}"' "$GATE" ||+ fail "HCC metric scrape no longer asks kubectl for a process-owned random port"++# KEEP_FIXTURES may be useful interactively, but it cannot produce PASS evidence+# or leave a lock-free mutated profile that could later be mistaken for T2.+keep_guard_line="$(grep -nF 'KEEP_FIXTURES=1 is diagnostic-only and cannot produce a probative T2 Host-storm result' "$GATE" | cut -d: -f1)"+branch_gate_line="$(grep -nF 'require_branch_owned_hcc_gate "$CONTROL_NS"' "$GATE" | cut -d: -f1)"+if [[ -z "$keep_guard_line" || -z "$branch_gate_line" ]] ||+ (( keep_guard_line >= branch_gate_line )); then+ fail "KEEP_FIXTURES is not rejected before branch verification and mutation"+fi+if grep -Fq 'leaving fixtures in place' "$GATE"; then+ fail "Host storm can still report through the fixture-retention path"+fi++# Completion must be read from the exact replacement pod and established+# before C1/C2 metric adjudication. Merely observing `started` is not proof.+FLEET_COMPLETION_FUNCTION="$(+ sed -n '/^_replacement_fleet_completed_probe() {$/,/^}$/p' "$GATE"+)"+grep -Fq '"$current_pod" == "$HCC_POD_C"' <<<"$FLEET_COMPLETION_FUNCTION" ||+ fail "fleet completion probe is not fenced to the replacement pod"+grep -Fq '"pod/${HCC_POD_C}"' <<<"$FLEET_COMPLETION_FUNCTION" ||+ fail "fleet completion probe reads a deployment aggregate instead of the replacement pod"+grep -Fq '$HCC_PASS_COMPLETED_MARKER' <<<"$FLEET_COMPLETION_FUNCTION" ||+ fail "fleet completion probe does not require the explicit COMPLETED marker"+grep -Fq '$HCC_PASS_FAILED_MARKER' <<<"$FLEET_COMPLETION_FUNCTION" ||+ fail "fleet completion probe does not fail loud on the explicit FAILED marker"+completion_wait_line="$(grep -nF '"replacement HCC initial Host fleet reconciliation completion"' "$GATE" | cut -d: -f1)"+c1_line="$(grep -nF 'scrape_hcc_metrics "$SCRAPE_C1" "$HCC_POD_C"' "$GATE" | head -n1 | cut -d: -f1)"+if [[ -z "$completion_wait_line" || -z "$c1_line" ]] ||+ (( completion_wait_line >= c1_line )); then+ fail "replacement fleet completion is not causally established before post-recovery metrics"+fi++echo "PASS: host-storm oracle binds exact branch/profile ownership, shared fault locking, random endpoints, wake generation, and causal fleet completion"