Skip to content

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

TypeScript

fix(hcc): keep phase-2 certification off the readiness probe (#477)

Alfredo Lopezd653c91e0e3f
diff --git a/host-context-controller/package-lock.json b/host-context-controller/package-lock.json
index 1cd5126c3..1d7ff668d 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.246",
+ "version": "0.1.247",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "clerum-host-context-controller",
- "version": "0.1.246",
+ "version": "0.1.247",
"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.json
index b813d7c9f..44516712a 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.246",
+ "version": "0.1.247",
"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/main.ts b/host-context-controller/src/main.ts
index a391b698e..59668c3b1 100644
--- a/host-context-controller/src/main.ts
+++ b/host-context-controller/src/main.ts
@@ -23,6 +23,7 @@ import { McpApiAuthenticator } from './mcpApiAuthentication'
import { McpAuthorizationService } from './mcpAuthorization'
import {
resolveHostAuthoritativeFn,
+ resolveProbeAuthoritativeFn,
resolveProviderAuthoritativeFn,
resolveReadinessDetailFn,
} from './readinessGate'
@@ -150,6 +151,11 @@ async function main(): Promise<void> {
// dev (R2-M1). See resolveHostAuthoritativeFn.
const hostAuthoritativeFn = resolveHostAuthoritativeFn(watcher)
const readinessDetailFn = resolveReadinessDetailFn(watcher)
+ // /ready uses watch freshness only. Phase-2 certification stays on the
+ // per-request gate (providerAuthoritativeFn). Omitting this 10th argument
+ // would keep /ready on the 6-clause predicate and kubelet would evict
+ // during an uncertified safety window.
+ const probeAuthoritativeFn = resolveProbeAuthoritativeFn(watcher)
// Stateless heartbeat consumption — mcp-host pods authenticate their
// heartbeats toward control-api's /mcp-host facade (control-api is the
@@ -192,7 +198,8 @@ async function main(): Promise<void> {
hostAuthoritativeFn,
mcpAuthenticator,
mcpAuthorization,
- readinessDetailFn
+ readinessDetailFn,
+ probeAuthoritativeFn
)
await server.start()
diff --git a/host-context-controller/src/readinessGate.test.ts b/host-context-controller/src/readinessGate.test.ts
index 321ffb91b..b124689ff 100644
--- a/host-context-controller/src/readinessGate.test.ts
+++ b/host-context-controller/src/readinessGate.test.ts
@@ -1,8 +1,11 @@
-import { describe, expect, it } from 'vitest'
+import { describe, expect, it, vi } from 'vitest'
import {
type ReadinessInventoryDetail,
+ isProbeReadinessAuthoritative,
+ probeReadinessReasonsFromDetail,
readinessReasonsFromDetail,
resolveHostAuthoritativeFn,
+ resolveProbeAuthoritativeFn,
resolveProviderAuthoritativeFn,
resolveReadinessDetailFn,
} from './readinessGate'
@@ -114,3 +117,72 @@ describe('readinessReasonsFromDetail', () => {
).toEqual(['revocation_revision_mismatch'])
})
})
+
+describe('isProbeReadinessAuthoritative (A1-T01)', () => {
+ it('stays authoritative when only phase-2 certification is down', () => {
+ expect(
+ isProbeReadinessAuthoritative(
+ authoritativeDetail({
+ safetyInventoryCertified: false,
+ contextRevisionAligned: false,
+ serverRevisionAligned: false,
+ })
+ )
+ ).toBe(true)
+ })
+
+ it.each([
+ ['stopped', { stopped: true }],
+ ['mcpServerCacheSynced', { mcpServerCacheSynced: false }],
+ ['contextCacheSynced', { contextCacheSynced: false }],
+ ['hostCacheSynced', { hostCacheSynced: false }],
+ ] as const)('is false when probe clause %s is flipped', (_name, override) => {
+ expect(isProbeReadinessAuthoritative(authoritativeDetail(override))).toBe(false)
+ })
+})
+
+describe('resolveProbeAuthoritativeFn', () => {
+ it('A1-T02 does not call the 6-clause inventory predicate', () => {
+ const sixClause = vi.fn(() => false)
+ const watcher = {
+ getReadinessInventoryDetail: () =>
+ authoritativeDetail({
+ safetyInventoryCertified: false,
+ contextRevisionAligned: false,
+ serverRevisionAligned: false,
+ }),
+ isReadinessInventoryAuthoritative: sixClause,
+ }
+ expect(resolveProbeAuthoritativeFn(watcher)()).toBe(true)
+ expect(sixClause).not.toHaveBeenCalled()
+ })
+
+ it('A1-T03 grants authority when there is no watcher (R3-B1)', () => {
+ expect(resolveProbeAuthoritativeFn(null)()).toBe(true)
+ })
+
+ it('A1-T14 re-reads inventory detail on every invocation', () => {
+ let detail = authoritativeDetail({ safetyInventoryCertified: false })
+ const watcher = { getReadinessInventoryDetail: () => detail }
+ const probeFn = resolveProbeAuthoritativeFn(watcher)
+ expect(probeFn()).toBe(true)
+ detail = { ...detail, hostCacheSynced: false }
+ expect(probeFn()).toBe(false)
+ detail = { ...detail, hostCacheSynced: true }
+ expect(probeFn()).toBe(true)
+ })
+})
+
+describe('probeReadinessReasonsFromDetail (A1-T04)', () => {
+ it('emits only the host watch reason when phase-2 clauses are also down', () => {
+ expect(
+ probeReadinessReasonsFromDetail(
+ authoritativeDetail({
+ hostCacheSynced: false,
+ safetyInventoryCertified: false,
+ contextRevisionAligned: false,
+ })
+ )
+ ).toEqual(['host_watch_unsynced'])
+ })
+})
diff --git a/host-context-controller/src/readinessGate.ts b/host-context-controller/src/readinessGate.ts
index 105c148a1..3bf8d516c 100644
--- a/host-context-controller/src/readinessGate.ts
+++ b/host-context-controller/src/readinessGate.ts
@@ -84,3 +84,55 @@ export function resolveHostAuthoritativeFn(
): () => boolean {
return watcher ? () => watcher.isHostInventoryAuthoritative() : () => true
}
+
+/**
+ * Kubelet /ready authority: watch freshness only.
+ *
+ * Phase-2 certification (`safetyInventoryCertified`) and revocation-revision
+ * alignment stay on the per-request gate. A stale allow must 503 data
+ * endpoints without making kubelet evict the Pod.
+ */
+export function isProbeReadinessAuthoritative(detail: ReadinessInventoryDetail): boolean {
+ return (
+ !detail.stopped &&
+ detail.mcpServerCacheSynced &&
+ detail.contextCacheSynced &&
+ detail.hostCacheSynced
+ )
+}
+
+/**
+ * Closed-gate reasons for the kubelet /ready probe.
+ *
+ * Never emits `safety_pass_uncertified` or `revocation_revision_mismatch` —
+ * those belong to the per-request 6-clause gate.
+ */
+export function probeReadinessReasonsFromDetail(
+ detail: ReadinessInventoryDetail
+): ReadinessReason[] {
+ const reasons: ReadinessReason[] = []
+ if (detail.stopped) reasons.push('controller_stopped')
+ if (!detail.mcpServerCacheSynced) reasons.push('mcp_watch_unsynced')
+ if (!detail.contextCacheSynced) reasons.push('context_watch_unsynced')
+ if (!detail.hostCacheSynced) reasons.push('host_watch_unsynced')
+ return reasons
+}
+
+/**
+ * Resolve the kubelet /ready probe gate from the watcher.
+ *
+ * Production (McpServerWatcher present): /ready follows watch freshness
+ * (`isProbeReadinessAuthoritative` on the live inventory detail). MUST NOT
+ * call `isReadinessInventoryAuthoritative` — that 6-clause predicate includes
+ * phase-2 certification and would re-couple the probe to the safety pass.
+ *
+ * Dev (no watcher): same R3-B1 decision as the provider gate — authority is
+ * unconditional so the server's fail-closed default cannot pin /ready at 503.
+ */
+export function resolveProbeAuthoritativeFn(
+ watcher: { getReadinessInventoryDetail(): ReadinessInventoryDetail } | null
+): () => boolean {
+ return watcher
+ ? () => isProbeReadinessAuthoritative(watcher.getReadinessInventoryDetail())
+ : () => true
+}
diff --git a/host-context-controller/src/readinessSafetyFence.integration.test.ts b/host-context-controller/src/readinessSafetyFence.integration.test.ts
index dbdf29093..d8b853023 100644
--- a/host-context-controller/src/readinessSafetyFence.integration.test.ts
+++ b/host-context-controller/src/readinessSafetyFence.integration.test.ts
@@ -12,12 +12,19 @@
* predicate, and the HTTP server are the production classes, so the assertion
* is end-to-end: a delete that loses its uid/resourceVersion precondition
* during the additive phase — the 409 a second writer produces, and every
- * rollout opens a two-replica window for one — must turn /ready from 200 into
- * 503, and a later clean pass must turn it back.
+ * rollout opens a two-replica window for one — must 503 per-request data
+ * endpoints while /ready stays 200 (watch freshness only), and a later clean
+ * pass must reopen the API.
*/
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import * as http from 'http'
import { McpServerWatcher } from './k8sClient'
+import {
+ resolveHostAuthoritativeFn,
+ resolveProbeAuthoritativeFn,
+ resolveProviderAuthoritativeFn,
+ resolveReadinessDetailFn,
+} from './readinessGate'
import { ContextMapperServer } from './server'
const mocks = vi.hoisted(() => ({
@@ -145,6 +152,20 @@ async function readyStatus(server: InstanceType<typeof ContextMapperServer>): Pr
})
}
+async function apiStatus(server: InstanceType<typeof ContextMapperServer>): Promise<number> {
+ const listener = (server as unknown as { server: http.Server | null }).server
+ const address = listener?.address()
+ if (!address || typeof address === 'string') throw new Error('readiness listener never bound')
+ return new Promise((resolve, reject) => {
+ http
+ .get({ host: '127.0.0.1', port: address.port, path: '/api/v1/mcpservers' }, res => {
+ res.resume()
+ res.on('end', () => resolve(res.statusCode ?? 0))
+ })
+ .on('error', reject)
+ })
+}
+
/** Aligns every revocation counter so only the fence can gate readiness. */
function alignRevocationCounters(watcher: InstanceType<typeof McpServerWatcher>): void {
const w = watcher as unknown as Record<string, unknown>
@@ -169,8 +190,17 @@ describe('readiness withdrawal on a real lost delete fence', () => {
mocks.replaceNamespacedNetworkPolicy.mockResolvedValue({})
mocks.readNamespacedNetworkPolicy.mockResolvedValue(stalePolicy)
watcher = new McpServerWatcher()
- server = new ContextMapperServer(watcher, 0, undefined, undefined, () =>
- watcher.isReadinessInventoryAuthoritative()
+ server = new ContextMapperServer(
+ watcher,
+ 0,
+ undefined,
+ undefined,
+ resolveProviderAuthoritativeFn(watcher),
+ resolveHostAuthoritativeFn(watcher),
+ undefined,
+ undefined,
+ resolveReadinessDetailFn(watcher),
+ resolveProbeAuthoritativeFn(watcher)
)
await server.start()
server.setReady(true)
@@ -226,7 +256,8 @@ describe('readiness withdrawal on a real lost delete fence', () => {
// Only the fence knows this pass left an allow it classified as stale.
alignRevocationCounters(watcher)
expect(reconciler.hasCertifiedSafetyInventory()).toBe(false)
- expect(await readyStatus(server)).toBe(503)
+ expect(await apiStatus(server)).toBe(503)
+ expect(await readyStatus(server)).toBe(200)
// The retry lands: the allow is gone and the pass certifies again.
mocks.listNamespacedNetworkPolicy.mockResolvedValue({ items: [] })
@@ -304,7 +335,8 @@ describe('readiness withdrawal on a real lost delete fence', () => {
alignRevocationCounters(watcher)
expect(reconciler.hasCertifiedSafetyInventory()).toBe(false)
- expect(await readyStatus(server)).toBe(503)
+ expect(await apiStatus(server)).toBe(503)
+ expect(await readyStatus(server)).toBe(200)
// A clean authoritative pass re-certifies and reopens the gate.
mocks.listNamespacedNetworkPolicy.mockResolvedValue({ items: [] })
@@ -385,7 +417,8 @@ describe('readiness withdrawal on a real lost delete fence', () => {
).rejects.toThrow()
alignRevocationCounters(watcher)
expect(reconciler.hasCertifiedSafetyInventory()).toBe(false)
- expect(await readyStatus(server)).toBe(503)
+ expect(await apiStatus(server)).toBe(503)
+ expect(await readyStatus(server)).toBe(200)
// Fire a same-identity MODIFIED delta. Its scoped revocation completes
// (its label-scoped LISTs are clean) and it carries a delta certificate,
@@ -411,7 +444,8 @@ describe('readiness withdrawal on a real lost delete fence', () => {
expect(w.networkPolicyRevocationContextRevision).not.toBe(w.contextDesiredRevision)
expect(reconciler.hasCertifiedSafetyInventory()).toBe(false)
alignRevocationCounters(watcher)
- expect(await readyStatus(server)).toBe(503)
+ expect(await apiStatus(server)).toBe(503)
+ expect(await readyStatus(server)).toBe(200)
} finally {
warnSpy.mockRestore()
}
@@ -503,7 +537,8 @@ describe('readiness withdrawal on a real lost delete fence', () => {
expect(w.networkPolicyRevocationContextRevision).not.toBe(w.contextDesiredRevision)
expect(reconciler.hasCertifiedSafetyInventory()).toBe(false)
alignRevocationCounters(watcher)
- expect(await readyStatus(server)).toBe(503)
+ expect(await apiStatus(server)).toBe(503)
+ expect(await readyStatus(server)).toBe(200)
} finally {
warnSpy.mockRestore()
}
diff --git a/host-context-controller/src/server.test.ts b/host-context-controller/src/server.test.ts
index 5d6909eba..32c62e5a7 100644
--- a/host-context-controller/src/server.test.ts
+++ b/host-context-controller/src/server.test.ts
@@ -14,6 +14,7 @@ import {
import {
type ReadinessInventoryDetail,
resolveHostAuthoritativeFn,
+ resolveProbeAuthoritativeFn,
resolveProviderAuthoritativeFn,
resolveReadinessDetailFn,
} from './readinessGate'
@@ -814,7 +815,10 @@ describe('ContextMapperServer /ready reasons', () => {
})
})
- it('emits closed reasons through the main.ts resolve*Fn wiring', async () => {
+ it('emits closed reasons through the omitted-probe fallback resolve*Fn wiring', async () => {
+ // A1 fallback / T10: the 10th constructor arg is omitted on purpose so
+ // /ready still uses the 6-clause provider gate. Production main.ts now
+ // wires resolveProbeAuthoritativeFn; that split is covered below.
let detail = authoritativeDetail()
const watcher = {
isReadinessInventoryAuthoritative: () =>
@@ -854,3 +858,236 @@ describe('ContextMapperServer /ready reasons', () => {
})
})
})
+
+describe('ContextMapperServer /ready probe cut (A1)', () => {
+ let server: ContextMapperServer | null = null
+
+ const authoritativeDetail = (
+ overrides: Partial<ReadinessInventoryDetail> = {}
+ ): ReadinessInventoryDetail => ({
+ stopped: false,
+ mcpServerCacheSynced: true,
+ contextCacheSynced: true,
+ hostCacheSynced: true,
+ safetyInventoryCertified: true,
+ contextRevisionAligned: true,
+ serverRevisionAligned: true,
+ ...overrides,
+ })
+
+ function sixClauseAuthoritative(detail: ReadinessInventoryDetail): boolean {
+ return (
+ !detail.stopped &&
+ detail.mcpServerCacheSynced &&
+ detail.contextCacheSynced &&
+ detail.hostCacheSynced &&
+ detail.safetyInventoryCertified &&
+ detail.contextRevisionAligned &&
+ detail.serverRevisionAligned
+ )
+ }
+
+ function mainLikeServer(
+ detailRef: { current: ReadinessInventoryDetail },
+ extras: {
+ authenticator?: McpApiAuthenticator
+ authorization?: McpAuthorizationService
+ } = {}
+ ): ContextMapperServer {
+ const watcher = {
+ isReadinessInventoryAuthoritative: () => sixClauseAuthoritative(detailRef.current),
+ isHostInventoryAuthoritative: () =>
+ !detailRef.current.stopped && detailRef.current.hostCacheSynced,
+ getReadinessInventoryDetail: () => detailRef.current,
+ }
+ return new ContextMapperServer(
+ new FakeProvider(),
+ 0,
+ undefined,
+ undefined,
+ resolveProviderAuthoritativeFn(watcher),
+ resolveHostAuthoritativeFn(watcher),
+ extras.authenticator,
+ extras.authorization,
+ resolveReadinessDetailFn(watcher),
+ resolveProbeAuthoritativeFn(watcher)
+ )
+ }
+
+ afterEach(async () => {
+ await server?.stop()
+ server = null
+ vi.restoreAllMocks()
+ })
+
+ it('A1-T05 keeps /ready 200 when only the safety pass is uncertified', async () => {
+ const detailRef = { current: authoritativeDetail({ safetyInventoryCertified: false }) }
+ const authenticator = { authenticate: () => principal } as unknown as McpApiAuthenticator
+ server = mainLikeServer(detailRef, {
+ authenticator,
+ authorization: new McpAuthorizationService(new FakeAuthorityStore()),
+ })
+ server.setReady(true)
+
+ const ready = await invoke(server, '/ready')
+ expect(ready.statusCode).toBe(200)
+ expect(JSON.parse(ready.body)).toEqual({ status: 'ready', ready: true })
+ expect(JSON.parse(ready.body)).not.toHaveProperty('reasons')
+
+ const inventory = await invoke(server, '/api/v1/mcpservers')
+ expect(inventory.statusCode).toBe(503)
+
+ const hostInventory = await invoke(server, '/api/v2/hosts/self/mcpservers')
+ expect(hostInventory.statusCode).toBe(503)
+ expect(JSON.parse(hostInventory.body)).toEqual({ error: 'authorization_unavailable' })
+ })
+
+ it.each([
+ ['serverRevisionAligned', { serverRevisionAligned: false }],
+ ['contextRevisionAligned', { contextRevisionAligned: false }],
+ ] as const)('A1-T06 keeps /ready 200 when only %s is false', async (_name, override) => {
+ const detailRef = { current: authoritativeDetail(override) }
+ const authenticator = { authenticate: () => principal } as unknown as McpApiAuthenticator
+ server = mainLikeServer(detailRef, {
+ authenticator,
+ authorization: new McpAuthorizationService(new FakeAuthorityStore()),
+ })
+ server.setReady(true)
+
+ const ready = await invoke(server, '/ready')
+ expect(ready.statusCode).toBe(200)
+ expect(JSON.parse(ready.body)).toEqual({ status: 'ready', ready: true })
+ expect(JSON.parse(ready.body)).not.toHaveProperty('reasons')
+
+ const inventory = await invoke(server, '/api/v1/mcpservers')
+ expect(inventory.statusCode).toBe(503)
+
+ const hostInventory = await invoke(server, '/api/v2/hosts/self/mcpservers')
+ expect(hostInventory.statusCode).toBe(503)
+ expect(JSON.parse(hostInventory.body)).toEqual({ error: 'authorization_unavailable' })
+ })
+
+ it('A1-T07 reports only the host watch reason on /ready when phase-2 is also down', async () => {
+ const detailRef = {
+ current: authoritativeDetail({
+ hostCacheSynced: false,
+ safetyInventoryCertified: false,
+ }),
+ }
+ server = mainLikeServer(detailRef)
+ server.setReady(true)
+
+ const ready = await invoke(server, '/ready')
+ expect(ready.statusCode).toBe(503)
+ expect(JSON.parse(ready.body)).toEqual({
+ status: 'degraded',
+ ready: false,
+ reasons: ['host_watch_unsynced'],
+ })
+ })
+
+ it('A1-T08 withholds /ready while starting or stopping even if the probe gate is always true', async () => {
+ server = new ContextMapperServer(
+ new FakeProvider(),
+ 0,
+ undefined,
+ undefined,
+ () => true,
+ () => true,
+ undefined,
+ undefined,
+ undefined,
+ () => true
+ )
+
+ let ready = await invoke(server, '/ready')
+ expect(ready.statusCode).toBe(503)
+ expect(JSON.parse(ready.body)).toEqual({ status: 'starting', ready: false })
+
+ server.setReady(true)
+ ready = await invoke(server, '/ready')
+ expect(ready.statusCode).toBe(200)
+
+ server.setReady(false)
+ ready = await invoke(server, '/ready')
+ expect(ready.statusCode).toBe(503)
+ expect(JSON.parse(ready.body)).toEqual({ status: 'starting', ready: false })
+
+ server.setReady(true)
+ await server.stop()
+ ready = await invoke(server, '/ready')
+ expect(ready.statusCode).toBe(503)
+ expect(JSON.parse(ready.body)).toEqual({ status: 'starting', ready: false })
+ })
+
+ it('A1-T09 fails /ready closed when the probe gate throws', async () => {
+ server = new ContextMapperServer(
+ new FakeProvider(),
+ 0,
+ undefined,
+ undefined,
+ () => true,
+ () => true,
+ undefined,
+ undefined,
+ undefined,
+ () => {
+ throw new Error('probe authority unavailable')
+ }
+ )
+ server.setReady(true)
+
+ const ready = await invoke(server, '/ready')
+ expect(ready.statusCode).toBe(503)
+ expect(JSON.parse(ready.body)).toEqual({ status: 'degraded', ready: false })
+ })
+
+ it('A1-T10 keeps /ready on the 6-clause gate when the 10th argument is omitted', async () => {
+ const detail = authoritativeDetail({ safetyInventoryCertified: false })
+ server = new ContextMapperServer(
+ new FakeProvider(),
+ 0,
+ undefined,
+ undefined,
+ () => sixClauseAuthoritative(detail),
+ () => false,
+ undefined,
+ undefined,
+ () => detail
+ )
+ server.setReady(true)
+
+ const ready = await invoke(server, '/ready')
+ expect(ready.statusCode).toBe(503)
+ expect(JSON.parse(ready.body)).toEqual({
+ status: 'degraded',
+ ready: false,
+ reasons: ['safety_pass_uncertified'],
+ })
+ })
+
+ it('A1-T11 503s both lanes when the MCP watch is unsynced and heals both on the same instance', async () => {
+ const detailRef = { current: authoritativeDetail({ mcpServerCacheSynced: false }) }
+ server = mainLikeServer(detailRef)
+ server.setReady(true)
+
+ let ready = await invoke(server, '/ready')
+ expect(ready.statusCode).toBe(503)
+ expect(JSON.parse(ready.body)).toEqual({
+ status: 'degraded',
+ ready: false,
+ reasons: ['mcp_watch_unsynced'],
+ })
+
+ let inventory = await invoke(server, '/api/v1/mcpservers')
+ expect(inventory.statusCode).toBe(503)
+
+ detailRef.current = authoritativeDetail()
+ ready = await invoke(server, '/ready')
+ expect(ready.statusCode).toBe(200)
+ expect(JSON.parse(ready.body)).toEqual({ status: 'ready', ready: true })
+
+ inventory = await invoke(server, '/api/v1/mcpservers')
+ expect(inventory.statusCode).toBe(200)
+ })
+})
diff --git a/host-context-controller/src/server.ts b/host-context-controller/src/server.ts
index 515c2fb2d..71e3bcb3e 100644
--- a/host-context-controller/src/server.ts
+++ b/host-context-controller/src/server.ts
@@ -20,6 +20,7 @@ import { mcpHostApiRequestsTotal, registry } from './metrics'
import {
type ReadinessInventoryDetail,
type ReadinessReason,
+ probeReadinessReasonsFromDetail,
readinessReasonsFromDetail,
} from './readinessGate'
import { McpServersResponse } from './types'
@@ -101,17 +102,19 @@ export class ContextMapperServer {
private providerAuthoritativeFn: () => boolean
private hostAuthoritativeFn: () => boolean
private readinessDetailFn: (() => ReadinessInventoryDetail) | undefined
+ private probeAuthoritativeFn: (() => boolean) | undefined
private ready = false
private lastReadinessTransitionKey = ''
+ private lastProbeReadinessTransitionKey = ''
constructor(
provider: McpServerProvider,
port: number = config.port,
hostReconciler?: HostReconciler,
hasDesktopFn?: (hostRef: string) => boolean,
- // Fails closed. /ready is the assertion that no stale allow is live, and a
- // caller that omits this gate gets no type error, so the default must
- // withhold readiness rather than grant it.
+ // Fails closed. Per-request data endpoints assert that no stale allow is
+ // live, and a caller that omits this gate gets no type error, so the
+ // default must withhold authority rather than grant it.
providerAuthoritativeFn: () => boolean = () => false,
// Desktop status needs ONLY Host inventory authority, not the full
// readiness inventory. Fails closed like providerAuthoritativeFn: a caller
@@ -119,7 +122,12 @@ export class ContextMapperServer {
hostAuthoritativeFn: () => boolean = () => false,
mcpAuthenticator?: McpApiAuthenticator,
mcpAuthorization?: McpAuthorizationService,
- readinessDetailFn?: () => ReadinessInventoryDetail
+ readinessDetailFn?: () => ReadinessInventoryDetail,
+ // Optional kubelet /ready gate. When omitted, /ready falls back to
+ // providerAuthoritativeFn (6-clause) so omitting this argument can never
+ // weaken readiness. Production wires resolveProbeAuthoritativeFn so the
+ // probe ignores phase-2 certification.
+ probeAuthoritativeFn?: () => boolean
) {
this.provider = provider
this.port = port
@@ -131,6 +139,7 @@ export class ContextMapperServer {
this.providerAuthoritativeFn = providerAuthoritativeFn
this.hostAuthoritativeFn = hostAuthoritativeFn
this.readinessDetailFn = readinessDetailFn
+ this.probeAuthoritativeFn = probeAuthoritativeFn
}
/**
@@ -163,11 +172,26 @@ export class ContextMapperServer {
}
}
- private emitReadinessTransition(state: ReadinessState): void {
+ private collectProbeReadinessReasons(): ReadinessReason[] | undefined {
+ if (!this.readinessDetailFn) return undefined
+ try {
+ return probeReadinessReasonsFromDetail(this.readinessDetailFn())
+ } catch (err) {
+ readinessLog.error('readiness detail check failed', { err })
+ return undefined
+ }
+ }
+
+ private emitReadinessTransition(
+ state: ReadinessState,
+ keyHolder:
+ | 'lastReadinessTransitionKey'
+ | 'lastProbeReadinessTransitionKey' = 'lastReadinessTransitionKey'
+ ): void {
const reasons = !state.ready ? (state.reasons ?? []) : []
const key = `${state.ready}:${state.status}:${reasons.join(',')}`
- if (key === this.lastReadinessTransitionKey) return
- this.lastReadinessTransitionKey = key
+ if (key === this[keyHolder]) return
+ this[keyHolder] = key
if (state.ready) {
readinessLog.info('readiness became ready')
return
@@ -206,6 +230,45 @@ export class ContextMapperServer {
return degraded
}
+ /**
+ * Kubelet /ready state. When probeAuthoritativeFn is omitted, fall back to
+ * the 6-clause provider gate so omitting the 10th constructor argument
+ * cannot weaken readiness.
+ */
+ private getProbeReadinessState(): ReadinessState {
+ if (this.probeAuthoritativeFn === undefined) {
+ return this.getReadinessState()
+ }
+ if (!this.ready) {
+ const starting: ReadinessState = {
+ ready: false,
+ status: 'starting',
+ message: 'Context mapper is still starting',
+ }
+ this.emitReadinessTransition(starting, 'lastProbeReadinessTransitionKey')
+ return starting
+ }
+
+ try {
+ if (this.probeAuthoritativeFn()) {
+ const ready: ReadinessState = { ready: true, status: 'ready' }
+ this.emitReadinessTransition(ready, 'lastProbeReadinessTransitionKey')
+ return ready
+ }
+ } catch (err) {
+ readinessLog.error('probe authority readiness check failed', { err })
+ }
+
+ const degraded: ReadinessState = {
+ ready: false,
+ status: 'degraded',
+ message: 'Context mapper provider inventory is not authoritative',
+ reasons: this.collectProbeReadinessReasons(),
+ }
+ this.emitReadinessTransition(degraded, 'lastProbeReadinessTransitionKey')
+ return degraded
+ }
+
private async handleRequest(req: http.IncomingMessage, res: http.ServerResponse): Promise<void> {
const url = new URL(req.url || '/', `http://localhost:${this.port}`)
const isLegacyHostSelectedMcpRoute =
@@ -253,9 +316,9 @@ export class ContextMapperServer {
return
}
- // Readiness check
+ // Readiness check — watch freshness only when a probe gate is wired.
if (req.method === 'GET' && url.pathname === '/ready') {
- const readiness = this.getReadinessState()
+ const readiness = this.getProbeReadinessState()
const body: { status: string; ready: boolean; reasons?: ReadinessReason[] } = {
status: readiness.status,
ready: readiness.ready,