Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure
TypeScript
chore: merge dev into desktop loading improvements
Josué7f2087fd6bd7
diff --cc control-api/package-lock.jsonindex 96de124bf,96de124bf..ff14bc2b4--- a/control-api/package-lock.json+++ b/control-api/package-lock.json@@@ -1,12 -1,12 +1,12 @@@{"name": "clerum-control-api",-- "version": "0.1.366",++ "version": "0.1.367","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "clerum-control-api",-- "version": "0.1.366",++ "version": "0.1.367","dependencies": {"@clerum/image-policy": "file:../packages/image-policy","@clerum/llm-providers": "file:../packages/llm-providers",diff --cc control-api/package.jsonindex c394516e6,c394516e6..2a655b11c--- a/control-api/package.json+++ b/control-api/package.json@@@ -1,6 -1,6 +1,6 @@@{"name": "clerum-control-api",-- "version": "0.1.366",++ "version": "0.1.367","description": "Internal Clerum control plane REST API + UI for managing CRDs and secrets","main": "dist/main.js","engines": {diff --cc control-ui/components/__tests__/GovernedTraceSurface.test.tsxindex d936f52be,97b8e7025..1a984cab3--- a/control-ui/components/__tests__/GovernedTraceSurface.test.tsx+++ b/control-ui/components/__tests__/GovernedTraceSurface.test.tsx@@@ -1,6 -1,6 +1,7 @@@import { afterEach, describe, expect, it, vi } from 'vitest'import { cleanup, fireEvent, render, screen, waitFor, within } from '@testing-library/react'import {++ type InfrastructureCostScopeCatalog,getGovernedTraceEvents,getInfrastructureCostScopes,getInfrastructureTraceCosts,diff --cc control-ui/e2e/host-stateless-channel-rejection.spec.tsindex 000000000,ecf8655fe..3467625f3mode 000000,100644..100644--- a/control-ui/e2e/host-stateless-channel-rejection.spec.ts+++ b/control-ui/e2e/host-stateless-channel-rejection.spec.ts@@@ -1,0 -1,229 +1,232 @@@+ /**+ * E2E -- Operator visibility: stateless × CommunicationChannel hard-rejection banner+ *+ * Validates plan Addendum 6 item 4 (issue #791) on the LIVE control-ui host detail+ * view: a stateless Host that has a CONFIRMED CommunicationChannel association is+ * hard-rejected by HCC (effectiveMode=stateful + StatelessEnableRejected condition),+ * and the operator sees a prominent warning banner carrying the status reason+ * VERBATIM plus the disassociation recovery action. Removing the channel clears it.+ *+ * Why this spec arranges via a direct CRD write (kubectl), not the control-api:+ * The normal control-api/UI path CANNOT reach this state by design — control-api+ * rejects associating a CommunicationChannel with a stateless Host, and rejects+ * flipping a channel-bound Host to stateless, both with 409+ * `stateless_host_communication_channel_conflict`+ * (control-api/src/routes/admin/resources.ts). The hard-rejection is HCC's+ * defensive backstop for direct/racing CRD writes (AP-7,+ * docs/architecture/stateless-invariants.md). So this spec reproduces exactly that+ * race: it `kubectl apply`s a CommunicationChannel referencing a dedicated stateless+ * Host, then asserts the operator-facing banner.+ *+ * Opt-in: this spec is skipped unless E2E_STATELESS_CHANNEL_REJECTION=1, because it+ * requires a dedicated stateless Host and a kubectl context.+ *+ * KNOWN RED in this repository, for a reason unrelated to the executor fix: the+ * assertion below reads `status.lifecycle.effectiveMode`, which is NOT part of this+ * repo's HostLifecycleStatus (see host-context-controller/src/types.ts) and is never+ * written by this tree's HCC. The channel hard-rejection itself DOES work here — it is+ * observable through the StatelessEnableRejected condition, the stateful pod template,+ * and the banner text — but this spec will fail on the effectiveMode token until the+ * upstream hostLifecycleDecision model is ported. Do not weaken the assertion to make+ * it pass; port the model, or assert on the condition instead.+ *+ * Prerequisites (when enabled):+ * 1. Port-forwards running (control-ui :3000, control-api :8090).+ * 2. Admin credentials: ADMIN_USER, ADMIN_PASS.+ * 3. E2E_STATELESS_HOST — a dedicated Host with spec.lifecycle.stateless=true that is+ * NOT chatllm-stateless (avoids colliding with the transient Test 2d window of+ * scripts/e2e/e2e-stateless-suspend-wake.sh on a shared profile).+ * 4. E2E_KUBECONTEXT (or CONTEXT) — an allowed kubectl context (clerum-test /+ * clerum-codex-* / gke_<project>_<zone>_<cluster>). Passed to every kubectl call.+ */-import { execFileSync } from 'node:child_process'+ import { type Page, expect, test } from '@playwright/test'++import { execFileSync } from 'node:child_process'++ const BASE_UI = process.env.CONTROL_UI_URL || 'http://localhost:3000'+ const ADMIN_USER = process.env.ADMIN_USER || 'admin'+ const ADMIN_PASS = process.env.ADMIN_PASS || 'admin123!'++ const ENABLED = process.env.E2E_STATELESS_CHANNEL_REJECTION === '1'+ const HOST = process.env.E2E_STATELESS_HOST || ''+ const KUBECONTEXT = process.env.E2E_KUBECONTEXT || process.env.CONTEXT || ''+ const HOSTS_NS = process.env.E2E_HOSTS_NAMESPACE || 'mcp-host'+ const CHANNELS_NS = process.env.E2E_CHANNELS_NAMESPACE || 'channels'+ const REJECTED_CONDITION = 'StatelessEnableRejected'++ // Unique per run so parallel/leftover runs never collide, and cleanup is targeted.+ const CC_NAME = `e2e-vis-stateless-reject-${Date.now()}`++ function kubectl(args: string[], input?: string): string {+ if (!KUBECONTEXT) {+ throw new Error(+ 'E2E_KUBECONTEXT (or CONTEXT) must be set to an allowed context; kubectl context is never inferred.'+ )+ }+ return execFileSync('kubectl', ['--context', KUBECONTEXT, ...args], {+ encoding: 'utf8',+ ...(input !== undefined ? { input } : {}),+ })+ }++ function getHostJson(): {+ effectiveMode?: string+ rejected?: boolean+ rejectionMessage?: string+ } {+ const raw = kubectl(['get', 'host', HOST, '-n', HOSTS_NS, '-o', 'json'])+ const obj = JSON.parse(raw) as {+ status?: {+ lifecycle?: { effectiveMode?: string }+ conditions?: Array<{ type?: string; status?: string; message?: string }>+ }+ }+ const condition = obj.status?.conditions?.find(c => c.type === REJECTED_CONDITION)+ return {+ effectiveMode: obj.status?.lifecycle?.effectiveMode,+ rejected: condition?.status === 'True',+ rejectionMessage: condition?.message,+ }+ }++ function applyChannel(): void {+ const manifest = `apiVersion: clerum.io/v1alpha1+ kind: CommunicationChannel+ metadata:+ name: ${CC_NAME}+ namespace: ${CHANNELS_NS}+ spec:+ hostRef: ${HOST}+ email:+ - channelId: "INBOX"+ emails:+ - "[email protected]"+ `+ kubectl(['apply', '-n', CHANNELS_NS, '-f', '-'], manifest)+ }++ function deleteChannel(): void {+ try {+ kubectl(['delete', 'communicationchannel', CC_NAME, '-n', CHANNELS_NS, '--ignore-not-found'])+ } catch (err) {+ // Cleanup is best-effort; surface it but never mask a prior assertion failure.+ console.warn(`[e2e] failed to delete CommunicationChannel ${CC_NAME}: ${String(err)}`)+ }+ }++ async function login(page: Page) {+ await page.goto(BASE_UI)+ await page.waitForSelector('text=Sign in', { timeout: 15_000 })+ const inputs = page.locator('input')+ await inputs.nth(0).fill(ADMIN_USER)+ await inputs.nth(1).fill(ADMIN_PASS)+ await page.locator('button:has-text("Sign in")').last().click()+ await page.waitForSelector('text=Marketplace', { timeout: 20_000 })+ }++ test.describe('operator sees the stateless × CommunicationChannel hard-rejection banner', () => {+ test.skip(+ !ENABLED,+ 'opt-in: set E2E_STATELESS_CHANNEL_REJECTION=1 (with E2E_STATELESS_HOST, E2E_KUBECONTEXT) and deploy the Addendum-6 executor fix'+ )++ test.beforeAll(() => {+ // Fail loud on missing prerequisites rather than skipping silently.+ if (!HOST) throw new Error('E2E_STATELESS_HOST must name a dedicated stateless Host.')- if (!KUBECONTEXT) throw new Error('E2E_KUBECONTEXT (or CONTEXT) must be set to an allowed context.')++ if (!KUBECONTEXT)++ throw new Error('E2E_KUBECONTEXT (or CONTEXT) must be set to an allowed context.')+ const host = getHostJson()+ // Guard: the target must actually be a stateless Host, or the whole scenario is invalid.+ const statelessRaw = kubectl([+ 'get',+ 'host',+ HOST,+ '-n',+ HOSTS_NS,+ '-o',+ 'jsonpath={.spec.lifecycle.stateless}',+ ]).trim()+ if (statelessRaw !== 'true') {+ throw new Error(+ `E2E_STATELESS_HOST "${HOST}" must have spec.lifecycle.stateless=true (got "${statelessRaw}"). Host status: ${JSON.stringify(host)}`+ )+ }+ // Ensure a clean slate from any aborted prior run.+ deleteChannel()+ })++ test.afterAll(() => {+ deleteChannel()+ })++ test('renders the hard-rejection warning verbatim and clears it after disassociation', async ({+ page,+ }) => {+ // Arrange: the AP-7 racing CRD write — associate a channel with the stateless Host.+ applyChannel()++ // HCC hard-rejects on the next reconcile: effectiveMode=stateful + rejected condition.+ // Bounded, fail-loud poll — on timeout the last observed status is reported.+ await expect+ .poll(() => JSON.stringify(getHostJson()), {+ timeout: 120_000,+ intervals: [2_000],+ message:+ 'HCC did not hard-reject the stateless Host after the CommunicationChannel was applied ' ++ '(requires the Addendum-6 executor fix deployed).',+ })- .toMatch(/"effectiveMode":"stateful".*"rejected":true|"rejected":true.*"effectiveMode":"stateful"/)++ .toMatch(++ /"effectiveMode":"stateful".*"rejected":true|"rejected":true.*"effectiveMode":"stateful"/++ )++ const rejectionMessage = getHostJson().rejectionMessage+ expect(rejectionMessage, 'StatelessEnableRejected condition must carry a message').toBeTruthy()+ // Contract (Addendum 6): the message names the channel count AND the recovery action.+ expect(rejectionMessage).toMatch(/disassociate/i)++ // Assert the operator-facing banner shows the status message VERBATIM.+ // The verbatim reason renders on TWO deliberate operator-visibility surfaces —+ // the warning banner AND the lifecycle chip — so scope each assertion to its+ // own surface rather than letting an unscoped getByText(reason) collide across+ // both (strict-mode violation).+ await login(page)+ await page.goto(`${BASE_UI}/hosts/${encodeURIComponent(HOST)}`)+ // Anchor on the banner CONTAINER, not the 'Stateless mode rejected:' text —+ // that phrase lives in a <strong> leaf whose text is only the prefix, so the+ // reason (a sibling text node in the same .cu-banner--warning div) is not part+ // of the leaf. Match the container by class + its heading text, then assert+ // the reason WITHIN it.+ const rejectionBanner = page.locator('.cu-banner--warning', {+ hasText: 'Stateless mode rejected:',+ })+ await expect(rejectionBanner).toBeVisible({ timeout: 20_000 })+ // (1) the warning banner container carries the reason verbatim+ await expect(rejectionBanner).toContainText(rejectionMessage as string, { timeout: 20_000 })+ // (2) the lifecycle chip is a second visibility surface — assert it deliberately- await expect(- page.locator('.cu-chip', { hasText: rejectionMessage as string })- ).toBeVisible({ timeout: 20_000 })++ await expect(page.locator('.cu-chip', { hasText: rejectionMessage as string })).toBeVisible({++ timeout: 20_000,++ })++ // Disassociation recovery: remove the channel; HCC clears the rejection.+ // Strict delete (not the best-effort cleanup helper) so a real failure here+ // fails the test loudly instead of being swallowed mid-scenario.+ kubectl(['delete', 'communicationchannel', CC_NAME, '-n', CHANNELS_NS, '--ignore-not-found'])+ await expect+ .poll(() => JSON.stringify(getHostJson()), {+ timeout: 120_000,+ intervals: [2_000],+ message: 'HCC did not clear the hard-rejection after the CommunicationChannel was removed.',+ })+ .toMatch(/"rejected":false/)++ // BOTH surfaces must clear once the Host reports stateless-active again: the+ // warning banner disappears AND the rejection reason no longer renders on any+ // surface (banner or lifecycle chip).+ await page.reload()+ await expect(+ page.locator('.cu-banner--warning', { hasText: 'Stateless mode rejected:' })+ ).toHaveCount(0, { timeout: 20_000 })+ await expect(page.getByText(rejectionMessage as string, { exact: false })).toHaveCount(0, {+ timeout: 20_000,+ })+ })+ })diff --cc control-ui/package-lock.jsonindex 4067d27be,0df8e963d..432434e56--- a/control-ui/package-lock.json+++ b/control-ui/package-lock.json@@@ -1,12 -1,12 +1,12 @@@{"name": "clerum-control-ui",-- "version": "0.1.349",++ "version": "0.1.350","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "clerum-control-ui",-- "version": "0.1.349",++ "version": "0.1.350","dependencies": {"@clerum/llm-providers": "file:../packages/llm-providers","@clerum/workflow-recipe-capability-policy": "file:../packages/workflow-recipe-capability-policy",diff --cc control-ui/package.jsonindex 18f386936,18f386936..605ca4edd--- a/control-ui/package.json+++ b/control-ui/package.json@@@ -1,6 -1,6 +1,6 @@@{"name": "clerum-control-ui",-- "version": "0.1.349",++ "version": "0.1.350","private": true,"scripts": {"dev": "NEXT_IGNORE_INCORRECT_LOCKFILE=1 next dev",diff --cc desktop-app/test/e2e-playwright/stateless-wake.test.tsindex 99f158087,dddb6c05e..d94b0c954--- a/desktop-app/test/e2e-playwright/stateless-wake.test.ts+++ b/desktop-app/test/e2e-playwright/stateless-wake.test.ts@@@ -450,3 -566,724 +566,721 @@@ test('Scenario 3 — end-to-end wake jocontentType: 'application/json',})})++ // Reads the server-side session catalog through the SAME wake-capable RPC the+ // workspace uses (`GET …/sessions`, now `host:session:read` + `host:wake:write`,+ // issue #791). Returns a structured result so a wake 403 or transport failure+ // FAILS the caller loudly instead of collapsing to an empty list.+ async function readStatelessSessionIds(+ appPage: import('@playwright/test').Page+ ): Promise<{ error: string | null; chatIds: string[] }> {+ return appPage.evaluate(async hostRef => {+ try {+ const result = await window.clerum.rpc.listSessions(hostRef)+ const items = (result?.items ?? []) as unknown as Array<{ chatId?: unknown }>+ const chatIds = items+ .map(item => (typeof item.chatId === 'string' ? item.chatId : ''))+ .filter((id: string) => id.length > 0)+ return { error: null, chatIds }+ } catch (error) {+ return {+ error: error instanceof Error ? error.message : String(error),+ chatIds: [] as string[],+ }+ }+ }, HOST_REF)+ }++ // Loads the host-level model list through the wake-capable RPC (`GET …/models`,+ // now `host:session:read` + `host:wake:write`). A structured error surfaces a+ // wake 403; a `null` model list is a legitimate compat outcome, not a failure.+ async function probeStatelessHostModels(+ appPage: import('@playwright/test').Page+ ): Promise<{ error: string | null; modelCount: number | null }> {+ return appPage.evaluate(async hostRef => {+ try {+ const result = await window.clerum.rpc.getHostModels(hostRef, '')+ const models = (result as unknown as { models?: unknown[] } | null)?.models+ return { error: null, modelCount: Array.isArray(models) ? models.length : null }+ } catch (error) {+ return {+ error: error instanceof Error ? error.message : String(error),+ modelCount: null,+ }+ }+ }, HOST_REF)+ }++ // Fires the app's own wake op (window.clerum.rpc.prewarmHost → POST …/wake) as a+ // member of the cold burst, and returns its raw response. The 202 `wake-requested`+ // status is control-api's Postgres-backed AUTHORITATIVE signal that the host was+ // SUSPENDED at first touch — robust to the transparent sub-hold-deadline wakes that+ // blind the UI waking-state oracle (a fast rpc-proxy wake-and-hold returns the LLM+ // reply with no visible waking-state, so the affordance never renders). `active`+ // (200) means the host was already warm. `skipped` ('cooldown'/'in-flight' — the+ // app's own useHostPrewarmController may prewarm on chat mount; the 60s cooldown+ // clears across the 180s idle, and any residual collision surfaces here) or a+ // missing status is INDETERMINATE — the caller MUST fail loud, never classify warm.+ async function probeStatelessPrewarm(appPage: import('@playwright/test').Page): Promise<{+ error: string | null+ status: string | null+ skipped: string | null+ requested: boolean | null+ }> {+ return appPage.evaluate(async hostRef => {+ try {+ const result = await window.clerum.rpc.prewarmHost(hostRef)+ return {+ // AppService.prewarmHost surfaces operational failures as a RESOLVED+ // result ({ requested: false, error }), not a throw, so the catch below+ // never sees them. Propagate result.error here or the indeterminate+ // diagnostics would drop the real cause behind a status='null'.+ error: typeof result?.error === 'string' ? result.error : null,+ status: typeof result?.status === 'string' ? result.status : null,+ skipped: typeof result?.skipped === 'string' ? result.skipped : null,+ requested: typeof result?.requested === 'boolean' ? result.requested : null,+ }+ } catch (error) {+ return {+ error: error instanceof Error ? error.message : String(error),+ status: null,+ skipped: null,+ requested: null,+ }+ }+ }, HOST_REF)+ }++ // Navigate to the dedicated agent view (no active chat) where the visible+ // "Latest sessions for selected agent" region renders — the same path the sibling+ // stateless-watch-session-continuity spec uses (Agents → Open details → Go to+ // Chat). Returns the region locator so callers can assert on session buttons by+ // data-chat-id. isDedicatedAgentView is `!activeChatId` (ChatThread.tsx), so this+ // view is the only place the session list is visible.+ async function openDedicatedAgentSessions(+ appPage: import('@playwright/test').Page+ ): Promise<import('@playwright/test').Locator> {+ await openAgentsPage(appPage)+ await expect(appPage.getByRole('heading', { name: /^Agents$/ })).toBeVisible({ timeout: 20_000 })+ const detailsButton = appPage.getByRole('button', {+ name: `Open details for ${HOST_REF}`,+ exact: true,+ })+ await expect(detailsButton).toHaveCount(1)+ await expect(detailsButton).toBeVisible({ timeout: 30_000 })+ await expect(detailsButton).toBeEnabled()+ await detailsButton.click()+ await expect(appPage.getByRole('region', { name: 'Agent details' })).toBeVisible({+ timeout: 20_000,+ })+ const goToChat = appPage.getByRole('button', { name: 'Go to Chat', exact: true })+ await expect(goToChat).toBeVisible({ timeout: 20_000 })+ await expect(goToChat).toBeEnabled()+ await goToChat.click()+ await expect(appPage.getByTestId('chat-input')).toBeVisible({ timeout: 30_000 })+ await expect(appPage.getByRole('button', { name: /^Switch chat agent$/ })).toContainText(+ HOST_REF,+ { timeout: 30_000 }+ )+ const sessions = appPage.getByRole('region', { name: 'Latest sessions for selected agent' })+ await expect(sessions).toBeVisible({ timeout: 30_000 })+ return sessions+ }++ // The active chat's message-list carries aria-current='true' and a UUID+ // data-chat-id once a chat is selected (ChatThread.tsx). Returns that identity.+ //+ // KNOWN-RED SITE: this tree's ChatThread.tsx renders `message-list` with only+ // `data-testid` + `className`, so the `aria-current` expectation below is where+ // Scenario 4 fails. See the KNOWN RED block in this file's header for why the+ // fix is a renderer-lineage port and not a DOM patch. Do NOT relax these two+ // assertions to make the scenario pass.+ async function readActiveChatId(appPage: import('@playwright/test').Page): Promise<string> {+ const messageList = appPage.getByTestId('message-list')+ await expect(messageList).toHaveAttribute('aria-current', 'true', { timeout: TURN_TIMEOUT })+ await expect(messageList).toHaveAttribute('data-chat-id', CHAT_UUID_RE, { timeout: TURN_TIMEOUT })+ const chatId = await messageList.getAttribute('data-chat-id')+ if (!chatId || !CHAT_UUID_RE.test(chatId)) {+ throw new Error('[stateless-wake] active chat did not expose a UUID chat identity')+ }+ return chatId+ }++ // B1 — assert a chat identity is visible in the "Latest sessions" list, not only+ // reported by the RPC. Reuses the sibling's `button[data-chat-id="..."]` pattern.+ async function expectSessionButtonVisible(+ sessions: import('@playwright/test').Locator,+ chatId: string+ ): Promise<void> {+ const button = sessions.locator(`button[data-chat-id="${chatId}"]`)+ await expect(+ button,+ `Session identity ${chatId} must be visible in the "Latest sessions" list`+ ).toHaveCount(1)+ await expect(button).toBeVisible()+ }++ // Read the chat identities currently rendered as session buttons. Waits (bounded)+ // until at least two are listed — on a re-suspended host the catalog is served+ // through the wake-capable read, so this resolves after that wake; a genuinely+ // empty catalog fails the caller's assertion loudly rather than silently.+ async function readSessionButtonChatIds(+ sessions: import('@playwright/test').Locator+ ): Promise<string[]> {+ const buttons = sessions.locator('button[data-chat-id]')+ await expect(buttons.nth(1)).toBeVisible({ timeout: WAKE_VISIBLE_TIMEOUT })+ const ids = await buttons.evaluateAll(nodes =>+ nodes.map(node => node.getAttribute('data-chat-id') || '').filter(Boolean)+ )+ return [...new Set(ids)]+ }++ // Click a listed session and confirm it became the active chat (its identity+ // moves onto the message-list). Leaves the dedicated view for the thread view.+ async function openExistingSession(+ appPage: import('@playwright/test').Page,+ sessions: import('@playwright/test').Locator,+ chatId: string+ ): Promise<void> {+ const button = sessions.locator(`button[data-chat-id="${chatId}"]`)+ await expect(button).toHaveCount(1)+ await expect(button).toBeVisible()+ await expect(button).toBeEnabled()+ await button.click()+ const messageList = appPage.getByTestId('message-list')+ await expect(messageList).toHaveAttribute('data-chat-id', chatId, { timeout: 30_000 })+ await expect(messageList).toHaveAttribute('aria-current', 'true')+ }++ // SF2 — transcript continuity through the visible UI: the earlier assistant reply+ // carrying `marker` must still be rendered in the reopened chat's message-list.+ async function expectAssistantMarkerRendered(+ appPage: import('@playwright/test').Page,+ marker: string+ ): Promise<void> {+ const response = appPage+ .getByTestId('message-list')+ .getByTestId('agent-response')+ .filter({ hasText: marker })+ await expect(+ response,+ `Assistant reply containing "${marker}" must still render in the reopened transcript`+ ).toHaveCount(1)+ await expect(response).toBeVisible({ timeout: TURN_TIMEOUT })+ }++ // SF3 — prove the model list is genuinely usable, not merely "did not 403". The+ // composer's model chip only becomes an interactive button once the host served a+ // usable model list (ModelSelector returns null until data loads and renders a+ // non-interactive chip only when degraded), so a visible interactive picker with+ // selectable options is itself the proof.-async function exerciseVisibleModelPicker(- appPage: import('@playwright/test').Page-): Promise<void> {++async function exerciseVisibleModelPicker(appPage: import('@playwright/test').Page): Promise<void> {+ const trigger = appPage.getByRole('button', { name: /^Model — / })+ await expect(+ trigger,+ 'the composer model picker must render a selectable model chip'+ ).toBeVisible({ timeout: TURN_TIMEOUT })+ await trigger.click()+ const menu = appPage.getByRole('menu', { name: 'Select model' })+ await expect(menu).toBeVisible({ timeout: 10_000 })+ const options = menu.getByRole('menuitemradio')+ await expect(options.first()).toBeVisible({ timeout: 10_000 })+ expect(+ await options.count(),+ 'the visible model picker must list at least one selectable model'+ ).toBeGreaterThan(0)+ // Close the picker without changing the selection (Escape closes it — see the+ // ModelSelector keydown handler — leaving the pending turn untouched).+ await appPage.keyboard.press('Escape')+ await expect(menu).toBeHidden({ timeout: 10_000 })+ }++ // Log out through the visible settings menu and confirm the login screen returns.+ async function logoutViaUi(appPage: import('@playwright/test').Page): Promise<void> {+ const settingsMenu = appPage.getByTestId('nav-settings-menu')+ await expect(settingsMenu).toBeVisible({ timeout: 15_000 })+ await expect(settingsMenu).toBeEnabled()+ await settingsMenu.click()+ const logout = appPage.getByTestId('logout-btn')+ await expect(logout).toBeVisible({ timeout: 10_000 })+ await expect(logout).toBeEnabled()+ await logout.click()+ await expect(appPage.locator('#email-input')).toBeVisible({ timeout: 20_000 })+ }++ // §15.5 real-user journey (the spec-side steps the wake-scope change enables and+ // that Scenarios 1–3 do not exercise): two distinct chats, the CONCURRENT+ // list-sessions + load-models + send-message burst driven against the FIRST cold+ // wake (chat A, replicas 0), the VISIBLE session list carrying both identities+ // before and after navigation, VISIBLE transcript continuity, a usable model+ // picker, and a logout/login continuity cycle. The session/model reads now carry+ // host:wake:write, so the reads must not 403, must not fabricate an empty session+ // list, and must not lose either chat's identity across navigation or the auth+ // cycle. The repeat suspend/wake cycle (step 11) is Scenario 5, driven by the+ // bash gate's second pass after a fresh suspension.+ test('Scenario 4 — concurrent session/model/message on a COLD wake, then two-chat continuity across nav + login', async ({+ appPage,+ }, testInfo) => {+ test.setTimeout(720_000)++ // Attach the dialog listener BEFORE any send so no unhandled wake dialog slips+ // past the whole journey.+ const dialogs: string[] = []+ appPage.on('dialog', dialog => {+ dialogs.push(dialog.message())+ void dialog.dismiss()+ })++ // N5 — cheap env guard before any expensive UI navigation.+ requireSuspendPrecondition()++ // Chat A — the first distinct conversation, driven as a CONCURRENT cold burst+ // against a genuinely replicas-0 host. Scenario 0's prewarm already woke the+ // host, so we first re-suspend it in-spec: open the agent composer (a wake),+ // then idle for a FIXED bounded window so the aggressive HCC test cadences scale+ // it back to 0. No early probe send during the idle — a probe is itself a wake+ // that would burn the cold state. SF1: the concurrent list-sessions ++ // load-models burst then runs against THIS in-flight cold wake, so the+ // wake-scoped reads are exercised while the host is actually waking — not+ // against an already-warm host.+ await openStatelessAgent(appPage)+ const chatInput = appPage.getByTestId('chat-input')+ const sendButton = appPage.getByRole('button', { name: /send message/i })++ // Deliberate in-spec re-suspension (Option A). Log the window bounds so the+ // orchestrator audit can verify the idle actually elapsed. FIXED ceiling wait,+ // no early exit: deterministic over fast.+ const idleStartedAt = new Date().toISOString()+ console.log(+ `[StatelessWakeJourney] ${JSON.stringify({+ scenario: 'scenario-4-idle-resuspend',+ phase: 'start',+ host_ref: HOST_REF,+ idle_ms: SCENARIO4_IDLE_RESUSPEND_MS,+ at: idleStartedAt,+ })}`+ )+ await appPage.waitForTimeout(SCENARIO4_IDLE_RESUSPEND_MS)+ const idleEndedAt = new Date().toISOString()+ console.log(+ `[StatelessWakeJourney] ${JSON.stringify({+ scenario: 'scenario-4-idle-resuspend',+ phase: 'end',+ host_ref: HOST_REF,+ idle_ms: SCENARIO4_IDLE_RESUSPEND_MS,+ at: idleEndedAt,+ })}`+ )++ const markerA = `WAKE_S4_A_${Date.now()}`+ await chatInput.fill(`Reply with exactly: ${markerA}`)+ // FOUR concurrent ops as the first touch against the (now re-suspended) host: the+ // authoritative wake (prewarmHost) + the two wake-scoped reads + the send. Keep+ // the click LAST so the explicit prewarm and reads race the send's own+ // server-side reactive wake (rpc-proxy wake-and-hold) — a strictly harder+ // exercise of the coordinator dedup (the Desktop mirror of bash Test 6). The+ // prewarm's status is the cold/warm oracle; the UI waking-state affordance is NOT+ // used for the mode because a transparent sub-hold-deadline wake never renders it.- const [prewarmDuringColdWake, sessionsDuringColdWake, modelsDuringColdWake] =- await Promise.all([- probeStatelessPrewarm(appPage),- readStatelessSessionIds(appPage),- probeStatelessHostModels(appPage),- sendButton.click(),- ])++ const [prewarmDuringColdWake, sessionsDuringColdWake, modelsDuringColdWake] = await Promise.all([++ probeStatelessPrewarm(appPage),++ readStatelessSessionIds(appPage),++ probeStatelessHostModels(appPage),++ sendButton.click(),++ ])+ expect(+ sessionsDuringColdWake.error,+ `[stateless-wake] concurrent listSessions during the COLD wake must not 403/fail — ${sessionsDuringColdWake.error}`+ ).toBeNull()+ expect(+ modelsDuringColdWake.error,+ `[stateless-wake] concurrent getHostModels during the COLD wake must not 403/fail — ${modelsDuringColdWake.error}`+ ).toBeNull()++ // Authoritative cold/warm classification from the app's own prewarm response+ // (control-api Postgres-backed). 'wake-requested' (202) proves the host was+ // SUSPENDED at first touch; 'active' (200) proves it was already warm. An error,+ // a `skipped` (cooldown/in-flight), or a missing/unknown status is INDETERMINATE+ // — fail loud naming the reason, never silently classify warm.+ // Every indeterminate throw below carries the FULL raw prewarm payload+ // (status + skipped + requested + error) so a classification failure is+ // debuggable from the log alone, not just the single field that branched.+ const rawPrewarmA = JSON.stringify(prewarmDuringColdWake)+ let modeA: 'warm' | 'cold'+ if (prewarmDuringColdWake.error) {+ throw new Error(+ `[stateless-wake] Scenario 4 prewarm oracle errored (${prewarmDuringColdWake.error}); ` ++ `cannot classify the cold burst. INDETERMINATE — not warm. Raw prewarm payload: ` ++ `${rawPrewarmA}. Idle window: ${idleStartedAt} → ${idleEndedAt}.`+ )+ } else if (prewarmDuringColdWake.skipped) {+ throw new Error(+ `[stateless-wake] Scenario 4 prewarm was skipped='${prewarmDuringColdWake.skipped}' ` ++ `(cooldown or in-flight collision with the app's own prewarm controller), so it ` ++ `returned no authoritative wake status. INDETERMINATE — never classified as warm. ` ++ `Raw prewarm payload: ${rawPrewarmA}. Idle window: ${idleStartedAt} → ${idleEndedAt}.`+ )+ } else if (prewarmDuringColdWake.status === 'wake-requested') {+ modeA = 'cold'+ } else if (prewarmDuringColdWake.status === 'active') {+ modeA = 'warm'+ } else {+ throw new Error(+ `[stateless-wake] Scenario 4 prewarm returned a non-classifiable status=` ++ `'${prewarmDuringColdWake.status}' (expected 'wake-requested' | 'active'). INDETERMINATE. ` ++ `Raw prewarm payload: ${rawPrewarmA}.`+ )+ }+ // Audit trail: emit the RAW prewarm response alongside the derived mode.+ await recordMode(testInfo, 'scenario-4-chat-a-cold-burst', modeA, {+ prewarm: {+ status: prewarmDuringColdWake.status,+ skipped: prewarmDuringColdWake.skipped,+ requested: prewarmDuringColdWake.requested,+ error: prewarmDuringColdWake.error,+ },+ })+ // Await the marker reply for continuity (chatIdA + the transcript legs below need+ // the turn to complete). resolveWakeOutcome covers both the transparent-warm and+ // the visible-waking-state retry paths; its return value is intentionally NOT the+ // mode oracle — the prewarm status above is authoritative.+ await resolveWakeOutcome(appPage, markerA)+ // Scenario 4 is the runtime proof of THIS PR's core contract — a CONCURRENT+ // session/model/message burst against a SUSPENDED host (the wake-displacement+ // fix). A warm burst proves nothing about it, so fail loud rather than record a+ // silent warm degrade. The FIXED idle above should have re-suspended the host;+ // a warm outcome means it stayed up.+ expect(+ modeA,+ `[stateless-wake] Scenario 4 cold burst took the WARM branch (prewarm status=` ++ `'${prewarmDuringColdWake.status}') after a fixed ` ++ `${Math.round(SCENARIO4_IDLE_RESUSPEND_MS / 1000)}s in-spec idle. This scenario ` ++ `must exercise the concurrent-on-COLD contract (replicas-0 wake-displacement). ` ++ `The aggressive HCC test cadences from the bash gate (idle floor 1m + drain + ` ++ `poll) must scale the host to 0 within that window; a warm burst means the host ` ++ `never re-suspended and the cold contract was NOT exercised. Idle window: ` ++ `${idleStartedAt} → ${idleEndedAt}.`+ ).toBe('cold')+ await expectComposerIdleReady(appPage, chatInput)+ const chatIdA = await readActiveChatId(appPage)++ // Chat B — a SECOND distinct conversation on the same agent (New chat again).+ // The host is warm now, so this send exercises the warm path.+ await openStatelessAgent(appPage)+ const markerB = `WAKE_S4_B_${Date.now()}`+ await chatInput.fill(`Reply with exactly: ${markerB}`)+ await sendButton.click()+ const modeB = await resolveWakeOutcome(appPage, markerB)+ await recordMode(testInfo, 'scenario-4-chat-b', modeB)+ await expectComposerIdleReady(appPage, chatInput)+ const chatIdB = await readActiveChatId(appPage)+ expect(chatIdA, 'the two chats must have distinct server identities').not.toBe(chatIdB)++ // B1 (a) — BEFORE the post-warm burst, assert BOTH chat identities are visible+ // in the "Latest sessions" region (not only through the RPC read). The region+ // renders only in the dedicated agent view, so navigate there first.+ let sessions = await openDedicatedAgentSessions(appPage)+ await expectSessionButtonVisible(sessions, chatIdA)+ await expectSessionButtonVisible(sessions, chatIdB)++ // Keep the RPC session read as the transport-level no-403 + identity proof.+ const before = await readStatelessSessionIds(appPage)+ expect(+ before.error,+ `[stateless-wake] listSessions must not 403 on wake — ${before.error}`+ ).toBeNull()+ const idsBefore = new Set(before.chatIds)+ expect(+ idsBefore.has(chatIdA) && idsBefore.has(chatIdB),+ 'both chat identities must surface in the server session list'+ ).toBe(true)++ // Reopen chat B (leaving the dedicated view) so the composer + model picker are+ // mounted for the warm-path burst and the SF3 model proof.+ await openExistingSession(appPage, sessions, chatIdB)++ // SF3 — the model list must be genuinely usable, not merely "did not 403".+ // Assert a positive model count over the wake-capable RPC AND drive the visible+ // model picker to prove selectable options render.+ const modelsWarm = await probeStatelessHostModels(appPage)+ expect(+ modelsWarm.error,+ `[stateless-wake] warm getHostModels must not fail — ${modelsWarm.error}`+ ).toBeNull()+ expect(+ modelsWarm.modelCount ?? 0,+ 'the stateless fixture host must expose at least one model on the warm path'+ ).toBeGreaterThan(0)+ await exerciseVisibleModelPicker(appPage)++ // Post-warm concurrent burst (kept — one warm turn): list sessions + load+ // models while a third send drives the composer, proving the wake-capable reads+ // stay 200 even while a send is in flight, and the send is not double-forwarded+ // (SF4).+ const markerC = `WAKE_S4_C_${Date.now()}`+ await chatInput.fill(`Reply with exactly: ${markerC}`)+ const [sessionsDuringWarm, modelsDuringWarm] = await Promise.all([+ readStatelessSessionIds(appPage),+ probeStatelessHostModels(appPage),+ sendButton.click(),+ ])+ expect(+ sessionsDuringWarm.error,+ `[stateless-wake] concurrent warm listSessions must not fail — ${sessionsDuringWarm.error}`+ ).toBeNull()+ expect(+ modelsDuringWarm.error,+ `[stateless-wake] concurrent warm getHostModels must not fail — ${modelsDuringWarm.error}`+ ).toBeNull()+ expect(+ new Set(sessionsDuringWarm.chatIds).size,+ 'concurrent listSessions must not drop either chat identity'+ ).toBeGreaterThanOrEqual(2)++ const modeC = await resolveWakeOutcome(appPage, markerC)+ await recordMode(testInfo, 'scenario-4-concurrent-warm', modeC)+ await expectComposerIdleReady(appPage, chatInput)++ // SF4 — no duplicate: the user's prompt AND the assistant's reply each render+ // exactly once in chat B's thread.+ const chatBList = appPage.getByTestId('message-list')+ await expect(chatBList.getByText(`Reply with exactly: ${markerC}`)).toHaveCount(1)+ await expect(chatBList.getByTestId('agent-response').filter({ hasText: markerC })).toHaveCount(1)++ // Step 9 + B1 (b) — navigate away to Agents and back into the dedicated sessions+ // view; assert BOTH identities are STILL visible in the session list.+ sessions = await openDedicatedAgentSessions(appPage)+ await expectSessionButtonVisible(sessions, chatIdA)+ await expectSessionButtonVisible(sessions, chatIdB)+ const after = await readStatelessSessionIds(appPage)+ expect(+ after.error,+ `[stateless-wake] post-navigation listSessions must not 403/fail — ${after.error}`+ ).toBeNull()+ const idsAfter = new Set(after.chatIds)+ for (const id of [chatIdA, chatIdB]) {+ expect(+ idsAfter.has(id),+ `Session identity ${id} must survive navigating away to Agents and back.`+ ).toBe(true)+ }++ // SF2 — transcript continuity through the VISIBLE UI: reopen chat A, then chat+ // B, and assert each earlier assistant reply is still rendered in message-list+ // (not merely chatId set-membership).+ await openExistingSession(appPage, sessions, chatIdA)+ await expectAssistantMarkerRendered(appPage, markerA)+ sessions = await openDedicatedAgentSessions(appPage)+ await openExistingSession(appPage, sessions, chatIdB)+ await expectAssistantMarkerRendered(appPage, markerB)+ await expectAssistantMarkerRendered(appPage, markerC)++ // §15.5 step 10 (SF5) — logout/login continuity: log out through the visible+ // settings menu, log back in as the SAME seeded user through the visible+ // email/password screen (loginAs → no Keychain, no storage injection), and+ // assert both identities and their transcript content survive the auth cycle.+ await logoutViaUi(appPage)+ await loginAs(appPage, E2E_EMAIL)+ sessions = await openDedicatedAgentSessions(appPage)+ await expectSessionButtonVisible(sessions, chatIdA)+ await expectSessionButtonVisible(sessions, chatIdB)+ await openExistingSession(appPage, sessions, chatIdA)+ await expectAssistantMarkerRendered(appPage, markerA)+ sessions = await openDedicatedAgentSessions(appPage)+ await openExistingSession(appPage, sessions, chatIdB)+ await expectAssistantMarkerRendered(appPage, markerB)++ // No unhandled wake dialog across the entire journey.+ expect(dialogs).toHaveLength(0)+ })++ // §15.5 step 11 — repeat one suspend/wake cycle to exclude a one-shot cache+ // artifact. This scenario runs ONLY in the bash gate's second Playwright pass+ // (grep "second cycle" + E2E_STATELESS_CYCLE=2), after force_idle_and_suspend has+ // suspended the host a SECOND time. On a fresh login it proves the chats created+ // in the first pass survived the second suspension (visible session list ++ // transcript) and that a fresh send wakes the host again and continues the same+ // thread.+ function requireSecondCyclePass(): void {+ if (STATELESS_CYCLE !== '2') {+ throw new Error(+ '[stateless-wake] E2E_STATELESS_CYCLE!=2 — the repeat suspend/wake cycle scenario must be ' ++ "driven by the bash gate's SECOND Playwright pass, after a second force_idle_and_suspend " ++ 're-suspends the host. Running it in the first pass would race a still-warm host and prove ' ++ 'nothing about a repeat cycle.'+ )+ }+ }++ test('Scenario 5 — repeat suspend/wake cycle keeps prior chats continuous (second cycle)', async ({+ appPage,+ }, testInfo) => {+ test.setTimeout(600_000)++ const dialogs: string[] = []+ appPage.on('dialog', dialog => {+ dialogs.push(dialog.message())+ void dialog.dismiss()+ })++ requireSecondCyclePass()+ requireSuspendPrecondition()++ // The chats from the first pass persist server-side across the second suspend.+ // Opening the dedicated session view serves the catalog through the wake-capable+ // read; a re-suspended host must therefore surface >= 2 prior sessions here+ // without a 403 or a false-empty catalog.+ const sessions = await openDedicatedAgentSessions(appPage)+ const priorIds = await readSessionButtonChatIds(sessions)+ expect(+ priorIds.length,+ 'the >=2 chats created in the first cycle must survive a SECOND suspend/wake'+ ).toBeGreaterThanOrEqual(2)++ const catalog = await readStatelessSessionIds(appPage)+ expect(+ catalog.error,+ `[stateless-wake] cycle-2 listSessions must not 403 on the re-suspended host — ${catalog.error}`+ ).toBeNull()+ expect(+ new Set(catalog.chatIds).size,+ 'the wake-capable session catalog must still report both prior chats after a second suspend'+ ).toBeGreaterThanOrEqual(2)++ // Reopen the first prior chat: its transcript (a prior assistant reply) must+ // still render — continuity BEFORE the measured second wake. This reopen is a+ // wake-capable read, so it (and the Playwright login/mount prewarm) may leave+ // the host warm; the in-spec re-suspension below restores a genuine replicas-0+ // state before the measured cold burst.+ const [targetChatId] = priorIds+ if (!targetChatId) {+ throw new Error('[stateless-wake] cycle-2 session catalog exposed no prior chat to reopen')+ }+ await openExistingSession(appPage, sessions, targetChatId)+ const messageList = appPage.getByTestId('message-list')+ const priorResponse = messageList.getByTestId('agent-response').first()+ await expect(+ priorResponse,+ 'a prior assistant reply must still render in the reopened chat after the second suspend'+ ).toBeVisible({ timeout: WAKE_VISIBLE_TIMEOUT })+ await expect(priorResponse).not.toHaveText('', { timeout: TURN_TIMEOUT })+ await expect(priorResponse).not.toHaveClass(/chat-bubble--error/)++ // Deliberate in-spec re-suspension, IDENTICAL to Scenario 4's established+ // pattern. The catalog + reopen reads above legitimately woke the host, and the+ // Playwright preflight/login/mount prewarm may already have warmed it, so+ // measuring the second wake right now would race a still-warm host (the cycle-2+ // warm-flake). Idle for a FIXED bounded window so the aggressive HCC test+ // cadences (idle floor 1m + drain + poll, set by the bash gate) scale the host+ // back to 0. No early probe send during the idle — a probe is itself a wake that+ // would burn the cold state. Log the window bounds so the orchestrator audit can+ // verify the idle actually elapsed. This makes the "repeat suspend/wake" cycle+ // the in-spec deterministic one, faithful to its own title.+ const idleStartedAt = new Date().toISOString()+ console.log(+ `[StatelessWakeJourney] ${JSON.stringify({+ scenario: 'scenario-5-idle-resuspend',+ phase: 'start',+ host_ref: HOST_REF,+ idle_ms: SCENARIO4_IDLE_RESUSPEND_MS,+ at: idleStartedAt,+ })}`+ )+ await appPage.waitForTimeout(SCENARIO4_IDLE_RESUSPEND_MS)+ const idleEndedAt = new Date().toISOString()+ console.log(+ `[StatelessWakeJourney] ${JSON.stringify({+ scenario: 'scenario-5-idle-resuspend',+ phase: 'end',+ host_ref: HOST_REF,+ idle_ms: SCENARIO4_IDLE_RESUSPEND_MS,+ at: idleEndedAt,+ })}`+ )++ // Drive the SECOND wake through the UI as a CONCURRENT cold burst on the FIRST+ // post-idle send into the SAME existing thread: the authoritative wake+ // (prewarmHost) races the send's own server-side reactive wake, exactly like+ // Scenario 4. Keep the click LAST. The prewarm 202 'wake-requested' is the+ // cold/warm oracle (control-api Postgres-backed); the UI waking-state affordance+ // is NOT used for the mode because a transparent sub-hold-deadline wake never+ // renders it.+ const chatInput = appPage.getByTestId('chat-input')+ const sendButton = appPage.getByRole('button', { name: /send message/i })+ const markerCycle2 = `WAKE_S5_${Date.now()}`+ await chatInput.fill(`Reply with exactly: ${markerCycle2}`)+ const [prewarmSecondCycle] = await Promise.all([+ probeStatelessPrewarm(appPage),+ sendButton.click(),+ ])++ // Authoritative cold/warm classification from the app's own prewarm response.+ // 'wake-requested' (202) proves the host was SUSPENDED at first touch; 'active'+ // (200) proves it was already warm. An error, a `skipped` (cooldown/in-flight),+ // or a missing/unknown status is INDETERMINATE — fail loud naming the reason and+ // the full raw payload, never silently classify warm.+ const rawPrewarm5 = JSON.stringify(prewarmSecondCycle)+ let mode: 'warm' | 'cold'+ if (prewarmSecondCycle.error) {+ throw new Error(+ `[stateless-wake] Scenario 5 prewarm oracle errored (${prewarmSecondCycle.error}); ` ++ `cannot classify the second-cycle wake. INDETERMINATE — not warm. Raw prewarm ` ++ `payload: ${rawPrewarm5}. Idle window: ${idleStartedAt} → ${idleEndedAt}.`+ )+ } else if (prewarmSecondCycle.skipped) {+ throw new Error(+ `[stateless-wake] Scenario 5 prewarm was skipped='${prewarmSecondCycle.skipped}' ` ++ `(cooldown or in-flight collision with the app's own prewarm controller), so it ` ++ `returned no authoritative wake status. INDETERMINATE — never classified as warm. ` ++ `Raw prewarm payload: ${rawPrewarm5}. Idle window: ${idleStartedAt} → ${idleEndedAt}.`+ )+ } else if (prewarmSecondCycle.status === 'wake-requested') {+ mode = 'cold'+ } else if (prewarmSecondCycle.status === 'active') {+ mode = 'warm'+ } else {+ throw new Error(+ `[stateless-wake] Scenario 5 prewarm returned a non-classifiable status=` ++ `'${prewarmSecondCycle.status}' (expected 'wake-requested' | 'active'). INDETERMINATE. ` ++ `Raw prewarm payload: ${rawPrewarm5}.`+ )+ }+ // Audit trail: emit the RAW prewarm response alongside the derived mode.+ await recordMode(testInfo, 'scenario-5-second-cycle', mode, {+ prewarm: {+ status: prewarmSecondCycle.status,+ skipped: prewarmSecondCycle.skipped,+ requested: prewarmSecondCycle.requested,+ error: prewarmSecondCycle.error,+ },+ })+ // Scenario 5 is the REPEAT suspend/wake proof: the second cycle must exercise a+ // genuine replicas-0 wake, not a warm no-op. Fail loud on a warm burst — it means+ // the fixed idle did not re-suspend the host and the repeat-cold contract was NOT+ // exercised.+ expect(+ mode,+ `[stateless-wake] Scenario 5 second-cycle burst took the WARM branch (prewarm status=` ++ `'${prewarmSecondCycle.status}') after a fixed ` ++ `${Math.round(SCENARIO4_IDLE_RESUSPEND_MS / 1000)}s in-spec idle. The repeat cycle must ` ++ `exercise a second replicas-0 wake; a warm burst means the host never re-suspended and ` ++ `the repeat-cold contract was NOT exercised. Idle window: ${idleStartedAt} → ${idleEndedAt}.`+ ).toBe('cold')+ // resolveWakeOutcome drives the transparent-warm / visible-waking-state retry and+ // verifies the marker reply completed; its return value is intentionally NOT the+ // mode oracle — the prewarm status above is authoritative.+ await resolveWakeOutcome(appPage, markerCycle2)+ await expectComposerIdleReady(appPage, chatInput)++ // Identity survives the SECOND wake too — continuity AFTER the measured cold wake.+ const afterWake = await readStatelessSessionIds(appPage)+ expect(+ afterWake.error,+ `[stateless-wake] post-second-wake listSessions must not 403/fail — ${afterWake.error}`+ ).toBeNull()+ const afterIds = new Set(afterWake.chatIds)+ for (const id of priorIds.slice(0, 2)) {+ expect(afterIds.has(id), `chat ${id} must survive the second suspend/wake cycle`).toBe(true)+ }++ expect(dialogs).toHaveLength(0)+ })diff --cc desktop-app/test/rpcTokenManager.test.tsindex c5df4f1e7,4126151c4..7e603ad3c--- a/desktop-app/test/rpcTokenManager.test.ts+++ b/desktop-app/test/rpcTokenManager.test.ts@@@ -1,109 -1,157 +1,159 @@@- import { describe, it, expect, vi, beforeEach } from "vitest";-import { describe, it, expect, vi } from "vitest";----vi.mock("../src/config.js", () => ({-- config: { requestTimeoutMs: 5000, externalRestApiBaseUrl: "http://localhost:8091" },--}));--vi.mock("../src/httpClient.js", () => ({++import { describe, expect, it, vi } from 'vitest'++import type { AuthClient } from '../src/authClient.js'++import { RpcTokenManager } from '../src/rpcTokenManager.js'++++vi.mock('../src/config.js', () => ({++ config: { requestTimeoutMs: 5000, externalRestApiBaseUrl: 'http://localhost:8091' },++}))++vi.mock('../src/httpClient.js', () => ({requestJson: vi.fn(),-- ApiError: class extends Error { status = 0; bodyText = ""; },--}));----import { RpcTokenManager } from "../src/rpcTokenManager.js";--import type { AuthClient } from "../src/authClient.js";++ ApiError: class extends Error {++ status = 0++ bodyText = ''++ },++}))// ── Helpers ───────────────────────────────────────────────────────────────────--function makeAuthClient(token = "rpc-token-123", expiresInSeconds = 60) {++function makeAuthClient(token = 'rpc-token-123', expiresInSeconds = 60) {return {issueRpcToken: vi.fn().mockResolvedValue({token,-- teamId: "team-1",-- scopes: ["host:message:invoke"],-- hostRefs: ["chatllm"],++ teamId: 'team-1',++ scopes: ['host:message:invoke'],++ hostRefs: ['chatllm'],expiresInSeconds,}),-- } as unknown as AuthClient;++ } as unknown as AuthClient}// ── Tests ─────────────────────────────────────────────────────────────────────--describe("RpcTokenManager — initial state", () => {-- it("returns null expiresAtMs before any token is fetched", () => {-- const manager = new RpcTokenManager(makeAuthClient());-- const meta = manager.getMetadata();++describe('RpcTokenManager — initial state', () => {++ it('returns null expiresAtMs before any token is fetched', () => {++ const manager = new RpcTokenManager(makeAuthClient())++ const meta = manager.getMetadata()-- expect(meta.expiresAtMs).toBeNull();-- expect(meta.scopes).toEqual([]);-- expect(meta.hostRefs).toEqual([]);-- });--});++ expect(meta.expiresAtMs).toBeNull()++ expect(meta.scopes).toEqual([])++ expect(meta.hostRefs).toEqual([])++ })++})--describe("RpcTokenManager — clear()", () => {-- it("resets cache so next getOrIssue() fetches fresh", async () => {-- const authClient = makeAuthClient();-- const manager = new RpcTokenManager(authClient);++describe('RpcTokenManager — clear()', () => {++ it('resets cache so next getOrIssue() fetches fresh', async () => {++ const authClient = makeAuthClient()++ const manager = new RpcTokenManager(authClient)// Prime cache-- await manager.getOrIssue("sess-token", ["host:message:invoke"]);-- expect(authClient.issueRpcToken).toHaveBeenCalledOnce();++ await manager.getOrIssue('sess-token', ['host:message:invoke'])++ expect(authClient.issueRpcToken).toHaveBeenCalledOnce()// After clear(), a second getOrIssue() should re-fetch-- manager.clear();-- await manager.getOrIssue("sess-token", ["host:message:invoke"]);-- expect(authClient.issueRpcToken).toHaveBeenCalledTimes(2);-- });--});----describe("RpcTokenManager — getOrIssue()", () => {-- it("fetches a new token when cache is empty", async () => {-- const authClient = makeAuthClient("rpc-fresh-token");-- const manager = new RpcTokenManager(authClient);---- const result = await manager.getOrIssue("sess-token", ["host:message:invoke"]);-- expect(result.token).toBe("rpc-fresh-token");-- expect(authClient.issueRpcToken).toHaveBeenCalledOnce();-- });---- it("reuses cached token on second call when not expired", async () => {-- const authClient = makeAuthClient("rpc-cached-token", 60);-- const manager = new RpcTokenManager(authClient);---- const first = await manager.getOrIssue("sess-token", ["host:message:invoke"]);-- const second = await manager.getOrIssue("sess-token", ["host:message:invoke"]);---- expect(first.token).toBe(second.token);++ manager.clear()++ await manager.getOrIssue('sess-token', ['host:message:invoke'])++ expect(authClient.issueRpcToken).toHaveBeenCalledTimes(2)++ })++})++++describe('RpcTokenManager — getOrIssue()', () => {++ it('fetches a new token when cache is empty', async () => {++ const authClient = makeAuthClient('rpc-fresh-token')++ const manager = new RpcTokenManager(authClient)++++ const result = await manager.getOrIssue('sess-token', ['host:message:invoke'])++ expect(result.token).toBe('rpc-fresh-token')++ expect(authClient.issueRpcToken).toHaveBeenCalledOnce()++ })++++ it('reuses cached token on second call when not expired', async () => {++ const authClient = makeAuthClient('rpc-cached-token', 60)++ const manager = new RpcTokenManager(authClient)++++ const first = await manager.getOrIssue('sess-token', ['host:message:invoke'])++ const second = await manager.getOrIssue('sess-token', ['host:message:invoke'])++++ expect(first.token).toBe(second.token)// Should only have fetched once (cache hit)-- expect(authClient.issueRpcToken).toHaveBeenCalledOnce();-- });++ expect(authClient.issueRpcToken).toHaveBeenCalledOnce()++ })-- it("re-fetches when token is expired (expiresInSeconds = 0)", async () => {-- const authClient = makeAuthClient("rpc-expired", 0);-- const manager = new RpcTokenManager(authClient);++ it('re-fetches when token is expired (expiresInSeconds = 0)', async () => {++ const authClient = makeAuthClient('rpc-expired', 0)++ const manager = new RpcTokenManager(authClient)// First call populates cache with 0s TTL (expired immediately)-- await manager.getOrIssue("sess-token", ["host:message:invoke"]);++ await manager.getOrIssue('sess-token', ['host:message:invoke'])// Override to return fresh tokenvi.mocked(authClient.issueRpcToken).mockResolvedValueOnce({-- token: "rpc-fresh-2",- accessScope: "team",-- teamId: "team-1",-- scopes: ["host:message:invoke"],-- hostRefs: ["chatllm"],++ token: 'rpc-fresh-2',++ accessScope: 'team',++ teamId: 'team-1',++ scopes: ['host:message:invoke'],++ hostRefs: ['chatllm'],expiresInSeconds: 60,-- });-- const result = await manager.getOrIssue("sess-token", ["host:message:invoke"]);- expect(result.token).toBe("rpc-fresh-2");- expect(authClient.issueRpcToken).toHaveBeenCalledTimes(2);- });-- it("returns metadata reflecting cached token after first fetch", async () => {- const manager = new RpcTokenManager(makeAuthClient("tok", 120));- await manager.getOrIssue("sess", ["host:message:invoke"]);-- const meta = manager.getMetadata();- expect(meta.expiresAtMs).toBeGreaterThan(Date.now());- expect(meta.scopes).toContain("host:message:invoke");- expect(meta.hostRefs).toContain("chatllm");- });- });++ })+- const result = await manager.getOrIssue("sess-token", ["host:message:invoke"]);- expect(result.token).toBe("rpc-fresh-2");- expect(authClient.issueRpcToken).toHaveBeenCalledTimes(2);- });++ const result = await manager.getOrIssue('sess-token', ['host:message:invoke'])++ expect(result.token).toBe('rpc-fresh-2')++ expect(authClient.issueRpcToken).toHaveBeenCalledTimes(2)++ })+- it("returns metadata reflecting cached token after first fetch", async () => {- const manager = new RpcTokenManager(makeAuthClient("tok", 120));- await manager.getOrIssue("sess", ["host:message:invoke"]);++ it('returns metadata reflecting cached token after first fetch', async () => {++ const manager = new RpcTokenManager(makeAuthClient('tok', 120))++ await manager.getOrIssue('sess', ['host:message:invoke'])+- const meta = manager.getMetadata();- expect(meta.expiresAtMs).toBeGreaterThan(Date.now());- expect(meta.scopes).toContain("host:message:invoke");- expect(meta.hostRefs).toContain("chatllm");- });-});++ const meta = manager.getMetadata()++ expect(meta.expiresAtMs).toBeGreaterThan(Date.now())++ expect(meta.scopes).toContain('host:message:invoke')++ expect(meta.hostRefs).toContain('chatllm')++ })++})++ // ── Subset-scope reuse: INTENTIONAL, pinned on purpose ────────────────────────+ //+ // A narrower request is satisfied from a cached SUPERSET token, so the token a+ // caller receives can carry scopes it did not ask for — including+ // host:wake:write on a stream/observability surface. That is deliberate: it+ // keeps issuance to one round trip instead of one per distinct scope set, and+ // it is NOT a wake risk, because possessing the scope never wakes a Host —+ // rpc-proxy triggers a wake only from its explicit per-route allowlist plus the+ // isWakeCapable gate (wakeAndHold.ts).+ //+ // This test exists so the behavior is a pinned contract rather than an+ // undocumented side effect: if someone later makes stream open a wake-capable+ // route, or narrows this cache to exact-scope keying, one of these two+ // assertions turns red and forces the decision to be made explicitly.-describe("RpcTokenManager — subset scope reuse", () => {- it("serves a narrower request from the cached superset token, which still carries host:wake:write", async () => {++describe('RpcTokenManager — subset scope reuse', () => {++ it('serves a narrower request from the cached superset token, which still carries host:wake:write', async () => {+ const authClient = {+ issueRpcToken: vi.fn().mockResolvedValue({- token: "rpc-token-superset",- accessScope: "team",- teamId: "team-1",- scopes: ["host:activity:read", "host:task:read", "host:wake:write"],- hostRefs: ["chatllm"],++ token: 'rpc-token-superset',++ accessScope: 'team',++ teamId: 'team-1',++ scopes: ['host:activity:read', 'host:task:read', 'host:wake:write'],++ hostRefs: ['chatllm'],+ expiresInSeconds: 60,+ }),- } as unknown as AuthClient;- const manager = new RpcTokenManager(authClient);++ } as unknown as AuthClient++ const manager = new RpcTokenManager(authClient)++ // Broad issuance (e.g. a finite operation that legitimately needs wake).+ await manager.getOrIssue(- "sess-token",- ["host:activity:read", "host:task:read", "host:wake:write"],- ["chatllm"]- );- expect(authClient.issueRpcToken).toHaveBeenCalledOnce();++ 'sess-token',++ ['host:activity:read', 'host:task:read', 'host:wake:write'],++ ['chatllm']++ )++ expect(authClient.issueRpcToken).toHaveBeenCalledOnce()++ // Narrower request (e.g. an observability read) — served from cache.- const reused = await manager.getOrIssue("sess-token", ["host:activity:read"], ["chatllm"]);++ const reused = await manager.getOrIssue('sess-token', ['host:activity:read'], ['chatllm'])++ // 1. Exactly ONE issuance: the subset did not trigger a second round trip.- expect(authClient.issueRpcToken).toHaveBeenCalledOnce();++ expect(authClient.issueRpcToken).toHaveBeenCalledOnce()+ // 2. The DELIVERED token is the cached superset — it still carries wake.- expect(reused.token).toBe("rpc-token-superset");- expect(reused.scopes).toContain("host:wake:write");- });-});++ expect(reused.token).toBe('rpc-token-superset')++ expect(reused.scopes).toContain('host:wake:write')++ })++})diff --cc host-context-controller/package-lock.jsonindex 854e35948,854e35948..2e04d1e84--- a/host-context-controller/package-lock.json+++ b/host-context-controller/package-lock.json@@@ -1,12 -1,12 +1,12 @@@{"name": "clerum-host-context-controller",-- "version": "0.1.157",++ "version": "0.1.158","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "clerum-host-context-controller",-- "version": "0.1.157",++ "version": "0.1.158","license": "SEE LICENSE IN LICENSE","dependencies": {"@clerum/image-policy": "file:../packages/image-policy",diff --cc host-context-controller/package.jsonindex 0fc08aae0,0fc08aae0..32eca539e--- a/host-context-controller/package.json+++ b/host-context-controller/package.json@@@ -1,6 -1,6 +1,6 @@@{"name": "clerum-host-context-controller",-- "version": "0.1.157",++ "version": "0.1.158","description": "Host Context Controller - provides McpServer CRDs to mcp-host via REST API","main": "dist/main.js","engines": {diff --cc host-context-controller/src/hostReconciler.test.tsindex af87512ae,c6d258c89..495a4bc38--- a/host-context-controller/src/hostReconciler.test.ts+++ b/host-context-controller/src/hostReconciler.test.ts@@@ -10,10 -10,25 +10,29 @@@ importcreateMockNetworkingApi,createMockRbacApi,} from '../test/__fixtures__/testMocks'- import { HostFleetReconcileError, HostReconciler } from './hostReconciler'-import { HostFleetReconcileError, HostReconciler, destructiveCleanupAllowed } from './hostReconciler'++import {++ HostFleetReconcileError,++ HostReconciler,++ destructiveCleanupAllowed,++} from './hostReconciler'import { HostK8sRequestTimeoutError } from './k8s/hostK8sApiClient'+ import { registry } from './metrics'import { HostCRD } from './types'+ function deferred<T = void>(): {+ promise: Promise<T>+ resolve: (value: T | PromiseLike<T>) => void+ reject: (reason?: unknown) => void+ } {+ let resolve!: (value: T | PromiseLike<T>) => void+ let reject!: (reason?: unknown) => void+ const promise = new Promise<T>((res, rej) => {+ resolve = res+ reject = rej+ })+ return { promise, resolve, reject }+ }+vi.mock('./config', () => ({config: {hostNamespace: 'mcp-host',@@@ -387,35 -348,28 +352,34 @@@ describe('HostReconciler fleet failureconst internals = reconciler as unknown as {listManagedHostDeployments(): Promise<k8s.V1Deployment[]>deleteHostRuntimeResources(name: string, namespace: string): Promise<void>- sweepOrphanChannelReaderResources(hosts: string[]): Promise<void>- sweepOrphanHostNetworkPolicies(hosts: string[]): Promise<void>}- const firstOrphanFailure = new Error('first orphan cleanup failed')- const channelListFailure = new Error('channel-reader list failed')- const channelDeleteFailure = new Error('channel-reader delete failed')- const networkListFailure = new Error('NetworkPolicy list failed')- const channelSweepFailure = new AggregateError(- [channelListFailure, channelDeleteFailure],- 'channel-reader sweep failed'- )- const networkSweepFailure = new AggregateError(- [networkListFailure],- 'NetworkPolicy sweep failed'- )+ const orphanFailure = new Error('first orphan cleanup failed')vi.spyOn(internals, 'listManagedHostDeployments').mockResolvedValue([- { metadata: { name: 'orphan-a', namespace: 'mcp-host' } } as k8s.V1Deployment,- { metadata: { name: 'orphan-b', namespace: 'mcp-host' } } as k8s.V1Deployment,+ {+ metadata: {+ name: 'orphan-a',+ namespace: 'mcp-host',- labels: { 'clerum.io/managed-by': 'host-context-controller', 'clerum.io/host': 'orphan-a' },++ labels: {++ 'clerum.io/managed-by': 'host-context-controller',++ 'clerum.io/host': 'orphan-a',++ },+ },+ } as k8s.V1Deployment,+ {+ metadata: {+ name: 'orphan-b',+ namespace: 'mcp-host',- labels: { 'clerum.io/managed-by': 'host-context-controller', 'clerum.io/host': 'orphan-b' },++ labels: {++ 'clerum.io/managed-by': 'host-context-controller',++ 'clerum.io/host': 'orphan-b',++ },+ },+ } as k8s.V1Deployment,])- const deleteRuntime = vi+ const del = vi.spyOn(internals, 'deleteHostRuntimeResources')- .mockRejectedValueOnce(firstOrphanFailure)+ .mockRejectedValueOnce(orphanFailure).mockResolvedValueOnce()- const channelSweep = vi- .spyOn(internals, 'sweepOrphanChannelReaderResources')- .mockRejectedValue(channelSweepFailure)- const networkPolicySweep = vi- .spyOn(internals, 'sweepOrphanHostNetworkPolicies')- .mockRejectedValue(networkSweepFailure)let thrown: unknowntry {@@@ -424,46 -378,203 +388,213 @@@thrown = error}- expect(deleteRuntime.mock.calls.map(([name]) => name)).toEqual(['orphan-a', 'orphan-b'])- expect(channelSweep).toHaveBeenCalledWith([])- expect(networkPolicySweep).toHaveBeenCalledWith([])- expect(thrown).toBeInstanceOf(AggregateError)- expect((thrown as AggregateError).errors).toEqual([- firstOrphanFailure,- channelSweepFailure,- networkSweepFailure,- ])- expect(channelSweepFailure.errors).toEqual([channelListFailure, channelDeleteFailure])- expect(networkSweepFailure.errors).toEqual([networkListFailure])- })-- it('continues every channel-reader resource sweep and aggregates non-404 failures', async () => {- const deploymentListFailure = new Error('Deployment list failed')- const serviceDeleteFailure = new Error('Service delete failed')- const secretListFailure = new Error('Secret list failed')- const appsApi = createMockAppsApi()- appsApi.listNamespacedDeployment.mockRejectedValue(deploymentListFailure)- const coreApi = Object.assign(createMockCoreApi(), {- listNamespacedService: vi.fn().mockResolvedValue({- items: [- {+ expect(del.mock.calls.map(([name]) => name).sort()).toEqual(['orphan-a', 'orphan-b'])+ expect(getObj).toHaveBeenCalledTimes(2)+ expect(thrown).toBeInstanceOf(HostFleetReconcileError)+ expect((thrown as HostFleetReconcileError).cleanupFailures).toContain(orphanFailure)+ })+ })++ /**+ * Current value of clerum_hcc_host_delete_cleanup_total for one `outcome`+ * label. Read from the live HCC registry (metrics are NOT mocked here), so a+ * skip that fails to record is caught rather than passing silently.+ */+ async function readHostDeleteCleanupOutcome(outcome: string): Promise<number> {+ const metric = registry.getSingleMetric('clerum_hcc_host_delete_cleanup_total')+ if (!metric) throw new Error('clerum_hcc_host_delete_cleanup_total is not registered')+ const snapshot = await metric.get()+ const match = snapshot.values.find(entry => entry.labels.outcome === outcome)+ return match?.value ?? 0+ }++ function makeCleanupReconciler(customApi: { getNamespacedCustomObject: ReturnType<typeof vi.fn> }) {+ return new HostReconciler({} as k8s.KubeConfig, {+ appsApi: asAppsApi(createMockAppsApi()),+ coreApi: asCoreApi(createMockCoreApi()),+ networkingApi: asNetworkingApi(createMockNetworkingApi()),+ rbacApi: asRbacApi(createMockRbacApi()),+ customApi: customApi as unknown as k8s.CustomObjectsApi,+ })+ }++ describe('HostReconciler bounded fleet workers', () => {+ it('admits at most the configured number of Host reconciles concurrently', async () => {+ const reconciler = new HostReconciler({} as k8s.KubeConfig, {+ appsApi: asAppsApi(createMockAppsApi()),+ coreApi: asCoreApi(createMockCoreApi()),+ networkingApi: asNetworkingApi(createMockNetworkingApi()),+ rbacApi: asRbacApi(createMockRbacApi()),+ })+ // Isolate reconcile concurrency from the cleanup phase.- vi.spyOn(reconciler as unknown as { collectHostCleanupFailures(...args: unknown[]): Promise<unknown[]> }, 'collectHostCleanupFailures').mockResolvedValue([])++ vi.spyOn(++ reconciler as unknown as {++ collectHostCleanupFailures(...args: unknown[]): Promise<unknown[]>++ },++ 'collectHostCleanupFailures'++ ).mockResolvedValue([])+ let active = 0+ let maxActive = 0+ const gates: Array<() => void> = []+ vi.spyOn(reconciler, 'reconcile').mockImplementation(async () => {+ active += 1+ maxActive = Math.max(maxActive, active)+ await new Promise<void>(resolve => gates.push(resolve))+ active -= 1+ })+ const hosts = ['h1', 'h2', 'h3', 'h4'].map(name => makeHost({ name }))+ const pass = reconciler.fullReconcile(hosts)++ // Only two workers may run at once; the pool must not admit h3/h4 yet.+ await vi.waitFor(() => expect(gates.length).toBe(2))+ expect(maxActive).toBe(2)++ // Drain: each release lets the pool admit the next queued Host key.+ for (let i = 0; i < hosts.length; i++) {+ await vi.waitFor(() => expect(gates.length).toBeGreaterThan(0))+ gates.shift()!()+ }+ await pass+ expect(maxActive).toBe(2)+ })++ it('keeps urgent per-Host events outside the fleet worker budget', async () => {+ const reconciler = new HostReconciler({} as k8s.KubeConfig, {+ appsApi: asAppsApi(createMockAppsApi()),+ coreApi: asCoreApi(createMockCoreApi()),+ networkingApi: asNetworkingApi(createMockNetworkingApi()),+ rbacApi: asRbacApi(createMockRbacApi()),+ })- vi.spyOn(reconciler as unknown as { collectHostCleanupFailures(...args: unknown[]): Promise<unknown[]> }, 'collectHostCleanupFailures').mockResolvedValue([])++ vi.spyOn(++ reconciler as unknown as {++ collectHostCleanupFailures(...args: unknown[]): Promise<unknown[]>++ },++ 'collectHostCleanupFailures'++ ).mockResolvedValue([])+ let active = 0+ let maxActive = 0+ const gates = new Map<string, () => void>()+ vi.spyOn(reconciler, 'reconcile').mockImplementation(async host => {+ active += 1+ maxActive = Math.max(maxActive, active)+ await new Promise<void>(resolve => gates.set(host.name, resolve))+ active -= 1+ })+ const fleetHosts = ['f1', 'f2', 'f3', 'f4'].map(name => makeHost({ name }))+ const pass = reconciler.fullReconcile(fleetHosts)+ await vi.waitFor(() => expect(gates.size).toBe(2)) // fleet budget saturated++ // An urgent event for an unrelated Host must still be admitted immediately,+ // even though the fleet workers already occupy the whole budget.+ const urgent = reconciler.reconcile(makeHost({ name: 'urgent' }), 'urgent')+ await vi.waitFor(() => expect(gates.has('urgent')).toBe(true))+ expect(maxActive).toBe(3) // 2 fleet + 1 urgent++ // Drain repeatedly so the remaining fleet workers (f3/f4) are admitted and+ // released as earlier ones finish.+ const settled = Promise.all([pass, urgent])+ for (let i = 0; i < 12; i++) {+ for (const [name, resolve] of [...gates]) {+ gates.delete(name)+ resolve()+ }+ await Promise.resolve()+ await Promise.resolve()+ }+ await settled+ })+ })++ describe('HostReconciler lifecycle-only vs full pass cleanup boundary', () => {+ it('reconcileHosts (lifecycle-only) runs NO orphan cleanup; fullReconcile does', async () => {+ const reconciler = new HostReconciler({} as k8s.KubeConfig, {+ appsApi: asAppsApi(createMockAppsApi()),+ coreApi: asCoreApi(createMockCoreApi()),+ networkingApi: asNetworkingApi(createMockNetworkingApi()),+ rbacApi: asRbacApi(createMockRbacApi()),+ })+ const internals = reconciler as unknown as {+ collectHostReconcileFailures(...args: unknown[]): Promise<unknown[]>+ collectHostCleanupFailures(...args: unknown[]): Promise<unknown[]>+ }+ const reconcileFailures = vi+ .spyOn(internals, 'collectHostReconcileFailures')+ .mockResolvedValue([])+ const cleanup = vi.spyOn(internals, 'collectHostCleanupFailures').mockResolvedValue([])++ // The lifecycle-only pass is what CommunicationChannel recovery and the+ // heartbeat-driven fleet convergence dispatch through (k8sClient+ // reconcileHosts()). It MUST NOT run destructive orphan cleanup: a+ // lifecycle pass whose watch authority is stale could otherwise delete a+ // just-created Host's children (Risk register: "Stale full pass deletes a+ // new Host's resources" — critical). Only the authoritative full pass,+ // which captures watch authority up front, is allowed to clean up.+ await reconciler.reconcileHosts([makeHost({ name: 'h1' })])+ expect(reconcileFailures).toHaveBeenCalledTimes(1)+ expect(cleanup).not.toHaveBeenCalled()++ // The authoritative full pass is the ONLY caller that runs orphan cleanup.+ await reconciler.fullReconcile([makeHost({ name: 'h1' })])+ expect(cleanup).toHaveBeenCalledTimes(1)+ })+ })++ describe('HostReconciler bounded orphan cleanup (Addendum 2)', () => {+ it('deletes orphan bundles through the bounded worker pool, never an unbounded fan-out', async () => {+ const getObj = vi.fn().mockRejectedValue({ code: 404 })+ const reconciler = makeCleanupReconciler({ getNamespacedCustomObject: getObj })+ reconciler.setHostWatchAuthority(() => ({ known: true, generation: 1 }))+ reconciler.setResolveCurrentHost(() => undefined) // every candidate is an orphan+ const internals = reconciler as unknown as {+ listManagedHostDeployments(): Promise<k8s.V1Deployment[]>+ deleteHostRuntimeResources(name: string, namespace: string): Promise<void>+ }+ vi.spyOn(internals, 'listManagedHostDeployments').mockResolvedValue(+ ['orphan-a', 'orphan-b', 'orphan-c', 'orphan-d'].map(+ name =>+ ({metadata: {- name: 'channel-reader-orphan',+ name,+ namespace: 'mcp-host',labels: {- app: 'channel-reader','clerum.io/managed-by': 'host-context-controller',- 'clerum.io/host': 'orphan',+ 'clerum.io/host': name,},},- },- ],- }),+ }) as k8s.V1Deployment+ )+ )+ let active = 0+ let maxActive = 0+ const gates: Array<() => void> = []+ vi.spyOn(internals, 'deleteHostRuntimeResources').mockImplementation(async () => {+ active += 1+ maxActive = Math.max(maxActive, active)+ await new Promise<void>(resolve => gates.push(resolve))+ active -= 1})- coreApi.deleteNamespacedService.mockRejectedValue(serviceDeleteFailure)- coreApi.listNamespacedSecret.mockRejectedValue(secretListFailure)++ const pass = reconciler.fullReconcile([])++ // Bound = HCC_HOST_FULL_RECONCILE_CONCURRENCY (2): only two orphan bundles+ // delete at once; the pool must not admit orphan-c/orphan-d yet.+ await vi.waitFor(() => expect(gates.length).toBe(2))+ expect(maxActive).toBe(2)++ for (let i = 0; i < 4; i++) {+ await vi.waitFor(() => expect(gates.length).toBeGreaterThan(0))+ gates.shift()!()+ }+ await pass+ expect(maxActive).toBe(2)+ })+ })++ describe('HostReconciler bounded channel-reader revision fan-out (Addendum 2)', () => {+ it('patches every affected Host through the bounded worker pool', async () => {const reconciler = new HostReconciler({} as k8s.KubeConfig, {- appsApi: asAppsApi(appsApi),- coreApi: asCoreApi(coreApi),+ appsApi: asAppsApi(createMockAppsApi()),+ coreApi: asCoreApi(createMockCoreApi()),networkingApi: asNetworkingApi(createMockNetworkingApi()),rbacApi: asRbacApi(createMockRbacApi()),})diff --cc host-context-controller/src/hostReconciler.tsindex c6ca15041,6d5b3edf3..c77a3e14c--- a/host-context-controller/src/hostReconciler.ts+++ b/host-context-controller/src/hostReconciler.ts@@@ -19,6 -19,6 +19,13 @@@ import} from './k8s/sharedFileSystemFactory'import { hccLogger } from './logger'import { issueMcpHostRuntimeTokens } from './mcpHostRuntimeTokenIssuerClient'++import {++ hostCleanupDeferredTotal,++ hostDeleteCleanupTotal,++ hostReconcileDurationSeconds,++ hostReconcileInFlight,++ hostReconcileQueueWaitSeconds,++} from './metrics'import {MCP_HOST_GFS_TOKEN_SECRET_KEY,MCP_HOST_RUNTIME_TOKEN_SECRET_ACCESS_KEY,@@@ -3643,217 -3794,320 +3794,324 @@@ export class HostReconciler)}- async reconcileDelete(name: string, namespace: string): Promise<void> {- await this.deleteHostRuntimeResources(name, namespace)- this.clearStatus(name)- this.desktopHosts.delete(name)+ /**+ * Delete a Host's runtime bundle.+ *+ * `opts.skipIf` is an OPTIONAL fence evaluated INSIDE the per-Host serializer,+ * immediately before anything destructive runs. Callers whose "this Host is+ * gone" decision was made BEFORE admission (the watch-recovery diff, which+ * compares LIST-time names) pass it so a same-name Host recreated during the+ * admission window is not wiped: the recreation's ADDED sets the cache and+ * enters this Host's chain FIRST, its reconcile rebuilds the bundle, and only+ * then does the stale delete reach the front of the strict-FIFO queue.+ * Ownership labels cannot discriminate here — the rebuilt bundle carries+ * identical `clerum.io/host` + managed-by labels — and no uid is available on+ * that path, so cache presence at admission is the correct fence. This+ * mirrors the F2/#827 in-serializer re-check in collectHostCleanupFailures.+ *+ * Callers that omit `opts` keep the previous unconditional behavior exactly.+ */+ async reconcileDelete(+ name: string,+ namespace: string,+ opts?: { skipIf?: () => boolean }+ ): Promise<void> {+ // A DELETED event must not race an in-flight create/update for the same+ // Host: route it through the same per-Host serializer as reconcile(). The+ // global convergence tail no longer provides this ordering.+ await this.lifecycle.serializeByHost(name, async () => {+ if (opts?.skipIf?.()) {+ // Same vocabulary the watch path already reports for this condition+ // (reconcileHostWatchEvent), so the skip is observable, not silent.+ hostDeleteCleanupTotal.inc({ outcome: 'superseded' })+ return+ }+ await this.deleteHostRuntimeResources(name, namespace)+ this.clearStatus(name)+ this.desktopHosts.delete(name)+ })}- private async collectHostReconcileFailures(desiredHosts: HostCRD[]): Promise<unknown[]> {- const failures: unknown[] = []- for (const host of desiredHosts) {+ /**+ * Reconcile the fleet with bounded cross-Host concurrency. Dispatches Host+ * KEYS (not stale object snapshots): each worker resolves the CURRENT cached+ * Host at execution time and skips entries the cache no longer holds+ * (superseded by a delete/newer event). Failures are aggregated completely.+ */+ private async collectHostReconcileFailures(+ desiredHosts: HostCRD[],+ source: HostReconcileSource+ ): Promise<unknown[]> {+ const snapshotByName = new Map(desiredHosts.map(h => [h.name, h]))+ const resolve = this.resolveCurrentHost ?? ((name: string) => snapshotByName.get(name))+ const keys = desiredHosts.map(h => h.name)+ return runBoundedHostWorkers(keys, config.hostFullReconcileConcurrency, async name => {+ const host = resolve(name)+ if (!host) return // absent/superseded since the pass captured its snapshottry {- await this.reconcile(host)+ await this.reconcile(host, source)} catch (error) {- console.error(`[HostReconciler] Fleet reconcile failed for Host "${host.name}":`, error)- failures.push(error)+ console.error(`[HostReconciler] Fleet reconcile failed for Host "${name}":`, error)+ throw error}- }- return failures+ })}- private async collectHostCleanupFailures(desiredHosts: HostCRD[]): Promise<unknown[]> {+ /**+ * Orphan cleanup with the §10.5 authority contract (replaces the accidental+ * safety the removed global tail used to provide):+ * - runs only with known watch authority and the SAME generation captured at+ * pass start;+ * - compares candidates with the CURRENT cache, not the pass snapshot;+ * - groups candidates by owning logical Host from ownership labels; a+ * candidate with no derivable owner is NEVER deleted (deferred + recorded);+ * - performs ONE fresh authoritative Host read per orphan Host; a confirmed+ * 404 (while authority stays valid) authorizes deleting that Host's entire+ * owned bundle INSIDE the Host's per-Host serializer;+ * - defers (with a bounded reason) on unknown authority, generation drift,+ * watch loss, a present read, or a failed read.+ */+ private async collectHostCleanupFailures(+ capturedAuthority: HostWatchAuthoritySnapshot+ ): Promise<unknown[]> {const failures: unknown[] = []- let existingDeployments: k8s.V1Deployment[] = []+ const authorityValid = (): boolean => {+ const current = this.hostWatchAuthority()+ return (+ capturedAuthority.known &&+ current.known &&+ capturedAuthority.generation === current.generation+ )+ }++ if (!authorityValid()) {+ const current = this.hostWatchAuthority()- const reason = !capturedAuthority.known || !current.known ? 'authority_unknown' : 'generation_changed'++ const reason =++ !capturedAuthority.known || !current.known ? 'authority_unknown' : 'generation_changed'+ hostCleanupDeferredTotal.inc({ reason })+ console.warn(`[HostReconciler] Deferring orphan cleanup: ${reason}`)+ return failures+ }++ let candidates: CleanupCandidate[]try {- existingDeployments = await this.listManagedHostDeployments()+ candidates = await this.gatherCleanupCandidates(failures)} catch (error) {- console.error('[HostReconciler] Failed to list managed host deployments:', error)failures.push(error)+ return failures}- const desiredNames = new Set(desiredHosts.map(h => h.name))- for (const deployment of existingDeployments) {- const name = deployment.metadata?.name || ''- const namespace = deployment.metadata?.namespace || config.hostNamespace- if (!desiredNames.has(name)) {- try {- await this.deleteHostRuntimeResources(name, namespace)- } catch (error) {- console.error(`[HostReconciler] Fleet cleanup failed for orphan Host "${name}":`, error)- failures.push(error)- }++ const cacheHasHost = (name: string): boolean =>+ this.resolveCurrentHost ? this.resolveCurrentHost(name) !== undefined : false++ const orphanHosts = new Set<string>()+ for (const candidate of candidates) {+ if (!candidate.owner) {+ // Never delete a resource whose owning Host cannot be derived.+ hostCleanupDeferredTotal.inc({ reason: 'no_owner_label' })+ console.warn(+ `[HostReconciler] Deferring orphan candidate ${candidate.kind}/${candidate.name}: no derivable owning Host`+ )+ continue}+ if (cacheHasHost(candidate.owner)) continue // still present → retain+ orphanHosts.add(candidate.owner)}- const knownHostNames = desiredHosts.map(h => h.name)- for (const sweep of [- () => this.sweepOrphanChannelReaderResources(knownHostNames),- () => this.sweepOrphanHostNetworkPolicies(knownHostNames),- ]) {- try {- await sweep()- } catch (error) {- failures.push(error)+ // §10.5 destructive cleanup runs per orphan logical Host. Each Host's owned+ // write set is disjoint (§10.4 inventory) and each destructive bundle runs+ // inside that Host's own `serializeByHost` chain, so distinct orphan Hosts+ // are provably independent. Addendum 2: dispatch them through the same+ // bounded worker pool as the fleet (reusing HCC_HOST_FULL_RECONCILE_CONCURRENCY)+ // instead of a serial `for … await` — never an unbounded fan-out at the K8s+ // API. Same-Host ordering is still guaranteed by serializeByHost, and delete+ // failures still aggregate completely because runBoundedHostWorkers collects+ // every lane's throw.+ const cleanupFailures = await runBoundedHostWorkers(+ Array.from(orphanHosts),+ config.hostFullReconcileConcurrency,+ async hostName => {+ if (!authorityValid()) {+ hostCleanupDeferredTotal.inc({ reason: 'watch_lost' })+ console.warn(+ `[HostReconciler] Deferring orphan cleanup for "${hostName}": watch authority lost`+ )+ return+ }+ const presence = await this.readHostPresence(hostName)+ if (presence === 'present') return // reappeared → retain+ if (presence === 'error') {+ hostCleanupDeferredTotal.inc({ reason: 'fresh_read_failed' })+ return+ }+ if (+ !destructiveCleanupAllowed({+ watchAuthorityKnown: this.hostWatchAuthority().known,+ capturedWatchGeneration: capturedAuthority.generation,+ currentWatchGeneration: this.hostWatchAuthority().generation,+ currentCacheOmitsHost: !cacheHasHost(hostName),+ // Derived, not hardcoded. `presence` is provably 'absent' here (the+ // 'present' and 'error' branches returned above), so this evaluates+ // to the identical literal and the runtime behavior is unchanged.+ // Deriving it makes the mapping total: if readHostPresence ever+ // grows a fourth outcome, the else-branch type stops satisfying+ // freshAuthoritativeRead's union and the compiler rejects it —+ // instead of silently labelling a non-404 read as 'confirmed404'+ // in a value that is DECISIONAL (a conjunct of+ // destructiveCleanupAllowed, :94-95), not telemetry.+ freshAuthoritativeRead: presence === 'absent' ? 'confirmed404' : presence,+ })+ ) {+ hostCleanupDeferredTotal.inc({ reason: 'watch_lost' })+ return+ }+ try {+ await this.lifecycle.serializeByHost(hostName, async () => {+ // F2 / #827 TOCTOU: a same-name Host recreated between the fresh read+ // above and admission into this serializer updates the current cache+ // (its ADDED event sets the cache before its reconcile runs, and that+ // reconcile serializes ahead of this delete). Re-check the current+ // cache INSIDE the serializer so a just-recreated Host's bundle is+ // never deleted by this stale cleanup.+ if (cacheHasHost(hostName)) {+ hostCleanupDeferredTotal.inc({ reason: 'recreated' })+ return+ }+ await this.deleteHostRuntimeResources(hostName, config.hostNamespace)+ })+ } catch (error) {+ console.error(+ `[HostReconciler] Fleet cleanup failed for orphan Host "${hostName}":`,+ error+ )+ throw error+ }}- }+ )+ failures.push(...cleanupFailures)return failures}- async reconcileHosts(desiredHosts: HostCRD[]): Promise<void> {- const hostFailures = await this.collectHostReconcileFailures(desiredHosts)- if (hostFailures.length > 0) {- throw new HostFleetReconcileError(hostFailures, [])+ /**+ * List every managed resource that could be an orphan and derive its owning+ * logical Host from ownership labels. List failures are collected into+ * `listFailures` (reported by the caller) so a partial discovery still cleans+ * what it could confidently attribute. Candidates never drive a delete on+ * their own — the caller applies the fresh-read authority gate.+ */+ private async gatherCleanupCandidates(listFailures: unknown[]): Promise<CleanupCandidate[]> {+ const candidates: CleanupCandidate[] = []+ const pushOwner = (kind: string, name: string | undefined, owner: string | undefined): void => {+ if (!name) return+ candidates.push({ kind, name, owner })}- }- async fullReconcile(desiredHosts: HostCRD[]): Promise<void> {- const hostFailures = await this.collectHostReconcileFailures(desiredHosts)- const cleanupFailures = await this.collectHostCleanupFailures(desiredHosts)- if (hostFailures.length > 0 || cleanupFailures.length > 0) {- throw new HostFleetReconcileError(hostFailures, cleanupFailures)+ try {+ for (const deployment of await this.listManagedHostDeployments()) {+ pushOwner(+ 'Deployment',+ deployment.metadata?.name,+ deployment.metadata?.labels?.[HOST_LABEL]+ )+ }+ } catch (error) {+ console.error('[HostReconciler] Failed to list managed host deployments:', error)+ listFailures.push(error)}- }-- private async listManagedHostDeployments(): Promise<k8s.V1Deployment[]> {- const response = await this.appsApi.listNamespacedDeployment({- namespace: config.hostNamespace,- labelSelector: `${MANAGED_BY_LABEL}=${MANAGED_BY_VALUE}`,- })- return (response.items || []).filter(item => item.metadata?.labels?.[HOST_LABEL])- }- /**- * Sweep orphan channel-reader resources from the channels namespace.- * Lists Deployments and Secrets carrying our management labels, then- * deletes those whose clerum.io/host label points at a Host that no- * longer exists. Catches CRDs deleted while HCC was down (UI cascade- * may have been skipped or interrupted).- */- private async sweepOrphanChannelReaderResources(knownHosts: string[]): Promise<void> {- const known = new Set(knownHosts)- const ns = config.channelsNamespace- const failures: unknown[] = []-- // Deployment sweep+ const channelsNs = config.channelsNamespace+ const managed = (labels: Record<string, string> | undefined): boolean =>+ labels?.[MANAGED_BY_LABEL] === MANAGED_BY_VALUEtry {- const list = await this.appsApi.listNamespacedDeployment({ namespace: ns })+ const list = await this.appsApi.listNamespacedDeployment({ namespace: channelsNs })for (const dep of list.items ?? []) {- const labels = dep.metadata?.labels ?? {}- if (labels.app !== 'channel-reader') continue- if (labels[MANAGED_BY_LABEL] !== MANAGED_BY_VALUE) continue- const host = labels[HOST_LABEL]- if (!host || known.has(host)) continue- const name = dep.metadata?.name- if (!name) continue- try {- await this.appsApi.deleteNamespacedDeployment({- name,- namespace: ns,- })- console.log(`[HostReconciler] orphan sweep deleted Deployment ${name}`)- } catch (err) {- if (getErrorCode(err) !== 404) {- console.warn(`[HostReconciler] orphan Deployment delete failed:`, err)- failures.push(err)- }- }+ const labels = dep.metadata?.labels+ if (labels?.app !== 'channel-reader' || !managed(labels)) continue+ pushOwner('ChannelReaderDeployment', dep.metadata?.name, labels[HOST_LABEL])}- } catch (err) {- console.warn('[HostReconciler] orphan Deployment sweep list failed:', err)- failures.push(err)+ } catch (error) {+ console.warn('[HostReconciler] channel-reader Deployment candidate list failed:', error)+ listFailures.push(error)}-- // Service sweeptry {- const list = await this.coreApi.listNamespacedService({ namespace: ns })+ const list = await this.coreApi.listNamespacedService({ namespace: channelsNs })for (const svc of list.items ?? []) {- const labels = svc.metadata?.labels ?? {}- if (labels.app !== 'channel-reader') continue- if (labels[MANAGED_BY_LABEL] !== MANAGED_BY_VALUE) continue- const host = labels[HOST_LABEL]- if (!host || known.has(host)) continue- const name = svc.metadata?.name- if (!name) continue- try {- await this.coreApi.deleteNamespacedService({- name,- namespace: ns,- })- console.log(`[HostReconciler] orphan sweep deleted Service ${name}`)- } catch (err) {- if (getErrorCode(err) !== 404) {- console.warn(`[HostReconciler] orphan Service delete failed:`, err)- failures.push(err)- }- }+ const labels = svc.metadata?.labels+ if (labels?.app !== 'channel-reader' || !managed(labels)) continue+ pushOwner('ChannelReaderService', svc.metadata?.name, labels[HOST_LABEL])}- } catch (err) {- console.warn('[HostReconciler] orphan Service sweep list failed:', err)- failures.push(err)- }-- // Secret sweep — server-side label filter limits the list response to- // Secrets HCC created. The channels-namespace Role grants `secrets: delete`- // broadly because K8s RBAC has no resourceName wildcards, but the actual- // operation here only ever sees managed Secrets, and the in-loop label- // guard below is a defense-in-depth check against any future code path- // that drops the labelSelector.- const sweepLabelSelector = [- `${MANAGED_BY_LABEL}=${MANAGED_BY_VALUE}`,- 'clerum.io/component=channel-reader',- ].join(',')+ } catch (error) {+ console.warn('[HostReconciler] channel-reader Service candidate list failed:', error)+ listFailures.push(error)+ }try {const list = await this.coreApi.listNamespacedSecret({- namespace: ns,- labelSelector: sweepLabelSelector,+ namespace: channelsNs,- labelSelector: [`${MANAGED_BY_LABEL}=${MANAGED_BY_VALUE}`, 'clerum.io/component=channel-reader'].join(','),++ labelSelector: [++ `${MANAGED_BY_LABEL}=${MANAGED_BY_VALUE}`,++ 'clerum.io/component=channel-reader',++ ].join(','),})for (const sec of list.items ?? []) {- const labels = sec.metadata?.labels ?? {}- // Belt-and-suspenders: re-verify the managed-by + component labels- // even though the labelSelector should already have filtered them.- // If a future bug drops the selector, this prevents an unscoped- // delete sweep across the channels namespace.- if (labels[MANAGED_BY_LABEL] !== MANAGED_BY_VALUE) continue- if (labels['clerum.io/component'] !== 'channel-reader') continue- const host = labels[HOST_LABEL]- if (!host || known.has(host)) continue- const name = sec.metadata?.name- if (!name) continue- try {- await this.coreApi.deleteNamespacedSecret({- name,- namespace: ns,- })- // Structured audit line — every Secret deletion HCC performs.- // Operators tail this to monitor unexpected deletes.- console.log(- `[HostReconciler] AUDIT: orphan sweep deleted Secret name=${name} ns=${ns} host=${host}`- )- } catch (err) {- if (getErrorCode(err) !== 404) {- console.warn(`[HostReconciler] orphan Secret delete failed:`, err)- failures.push(err)- }+ const labels = sec.metadata?.labels+ if (!managed(labels) || labels?.['clerum.io/component'] !== 'channel-reader') continue+ pushOwner('ChannelReaderSecret', sec.metadata?.name, labels[HOST_LABEL])+ }+ } catch (error) {+ console.warn('[HostReconciler] channel-reader Secret candidate list failed:', error)+ listFailures.push(error)+ }++ // #827 (Addendum 4 item 4): partial-leftover discovery. A bundle whose+ // Deployment — and even its NetworkPolicies — are already gone must still be+ // discovered from ANY surviving owned resource. List every owned kind HCC+ // writes in the host namespace by ownership label and derive the owner from+ // clerum.io/host; a candidate without a derivable owner is never deleted by+ // the caller (§10.5).+ const hostNs = config.hostNamespace+ const managedSelector = `${MANAGED_BY_LABEL}=${MANAGED_BY_VALUE}`+ const gatherOwnedKind = async (+ kind: string,+ list: () => Promise<{+ items?: Array<{ metadata?: { name?: string; labels?: Record<string, string> } }>+ }>+ ): Promise<void> => {+ try {+ const res = await list()+ for (const item of res.items ?? []) {+ if (!managed(item.metadata?.labels)) continue+ pushOwner(kind, item.metadata?.name, item.metadata?.labels?.[HOST_LABEL])}+ } catch (error) {+ console.warn(`[HostReconciler] ${kind} candidate list failed in ${hostNs}:`, error)+ listFailures.push(error)}- } catch (err) {- console.warn('[HostReconciler] orphan Secret sweep list failed:', err)- failures.push(err)}- throwCleanupFailures(failures, 'Failed to sweep orphan channel-reader resources')- }+ await gatherOwnedKind('Service', () =>+ this.coreApi.listNamespacedService({ namespace: hostNs, labelSelector: managedSelector })+ )+ await gatherOwnedKind('PersistentVolumeClaim', () =>+ this.coreApi.listNamespacedPersistentVolumeClaim({+ namespace: hostNs,+ labelSelector: managedSelector,+ })+ )+ await gatherOwnedKind('ServiceAccount', () =>+ this.coreApi.listNamespacedServiceAccount({+ namespace: hostNs,+ labelSelector: managedSelector,+ })+ )+ await gatherOwnedKind('Secret', () =>+ this.coreApi.listNamespacedSecret({ namespace: hostNs, labelSelector: managedSelector })+ )+ await gatherOwnedKind('Role', () =>+ this.rbacApi.listNamespacedRole({ namespace: hostNs, labelSelector: managedSelector })+ )+ await gatherOwnedKind('RoleBinding', () =>+ this.rbacApi.listNamespacedRoleBinding({ namespace: hostNs, labelSelector: managedSelector })+ )- /**- * Sweep orphan per-Host NetworkPolicies in both `channels` and `mcp-host`- * namespaces. Lists NPs carrying our managed-by label, deletes those whose- * clerum.io/host points at a Host that no longer exists.- *- * Filter is `clerum.io/managed-by=host-context-controller` — leaves the- * static base policies (no managed-by label) untouched.- */- private async sweepOrphanHostNetworkPolicies(knownHosts: string[]): Promise<void> {- const known = new Set(knownHosts)- const failures: unknown[] = []for (const ns of [config.channelsNamespace, config.hostNamespace, config.rpcProxyNamespace]) {try {const list = await this.networkingApi.listNamespacedNetworkPolicy({@@@ -3861,28 -4115,67 +4119,66 @@@labelSelector: `${MANAGED_BY_LABEL}=${MANAGED_BY_VALUE}`,})for (const np of list.items ?? []) {- const labels = np.metadata?.labels ?? {}- const host = labels[HOST_LABEL]- if (!host || known.has(host)) continue- const name = np.metadata?.name- if (!name) continue- try {- await this.networkingApi.deleteNamespacedNetworkPolicy({ name, namespace: ns })- console.log(`[HostReconciler] orphan sweep deleted NetworkPolicy ${name} in ${ns}`)- } catch (err) {- if (getErrorCode(err) !== 404) {- console.warn(`[HostReconciler] orphan NP delete failed:`, err)- failures.push(err)- }- }+ pushOwner('NetworkPolicy', np.metadata?.name, np.metadata?.labels?.[HOST_LABEL])}- } catch (err) {- console.warn(`[HostReconciler] orphan NP sweep list failed in ${ns}:`, err)- failures.push(err)+ } catch (error) {+ console.warn(`[HostReconciler] NetworkPolicy candidate list failed in ${ns}:`, error)+ listFailures.push(error)}}- throwCleanupFailures(failures, 'Failed to sweep orphan Host NetworkPolicies')++ return candidates+ }++ /**+ * One fresh authoritative Host read. `absent` is a confirmed 404 (the Host is+ * genuinely gone). `present` means the Host reappeared. `error` (timeout,+ * forbidden, 5xx) is deliberately NOT surfaced as a pass failure — the caller+ * defers with a bounded reason, matching the §13.2 cleanup matrix.+ */+ private async readHostPresence(name: string): Promise<'absent' | 'present' | 'error'> {+ try {+ await this.customApi.getNamespacedCustomObject({+ group: HOST_GROUP,+ version: HOST_VERSION,+ namespace: config.hostNamespace,+ plural: HOST_PLURAL,+ name,+ })+ return 'present'+ } catch (error) {+ if (getErrorCode(error) === 404) return 'absent'+ console.warn(`[HostReconciler] Fresh authoritative read for orphan "${name}" failed:`, error)+ return 'error'+ }+ }++ async reconcileHosts(desiredHosts: HostCRD[]): Promise<void> {+ const hostFailures = await this.collectHostReconcileFailures(desiredHosts, 'fleet')+ if (hostFailures.length > 0) {+ throw new HostFleetReconcileError(hostFailures, [])+ }+ }++ async fullReconcile(desiredHosts: HostCRD[]): Promise<void> {+ // Capture watch authority + generation at pass start (§10.5 step 1) so+ // cleanup can prove nothing shifted underneath it before deleting.+ const capturedAuthority = this.hostWatchAuthority()+ const hostFailures = await this.collectHostReconcileFailures(desiredHosts, 'fleet')+ // Cleanup runs only after every fleet worker has settled.+ const cleanupFailures = await this.collectHostCleanupFailures(capturedAuthority)+ if (hostFailures.length > 0 || cleanupFailures.length > 0) {+ throw new HostFleetReconcileError(hostFailures, cleanupFailures)+ }+ }++ private async listManagedHostDeployments(): Promise<k8s.V1Deployment[]> {+ const response = await this.appsApi.listNamespacedDeployment({+ namespace: config.hostNamespace,+ labelSelector: `${MANAGED_BY_LABEL}=${MANAGED_BY_VALUE}`,+ })+ return (response.items || []).filter(item => item.metadata?.labels?.[HOST_LABEL])}-}function canonicalStringify(obj: Record<string, unknown>): string {diff --cc host-context-controller/src/k8sClient.test.tsindex cdf5223f1,281d44568..f65ddef68--- a/host-context-controller/src/k8sClient.test.ts+++ b/host-context-controller/src/k8sClient.test.ts@@@ -2313,13 -2369,11 +2369,12 @@@ describe('McpServerWatcher Host periodiconst reconcile = vi.spyOn(hostReconciler, 'reconcile').mockImplementation(async host => {order.push(`watch:${host.name}:${host.generation}`)})- const reconcileDelete = vi- .spyOn(hostReconciler, 'reconcileDelete')- .mockImplementation(async name => {- order.push(`delete:${name}`)- })await (watcher as any).startHostWatch('test-host-rv')-- if (!hostWatchCallback) throw new Error('Host watch callback was not installed')- // Cache already synced: the full pass blocks purely on the mocked- // fullReconcile and does not drive recovery, isolating admission behavior.++ if (!hostWatchCallback)++ throw new Error('Host watch callback was not installed')++ // Cache already synced: the full pass blocks purely on the mocked++ // fullReconcile and does not drive recovery, isolating admission behavior.+ ;(watcher as any).hostCacheSynced = trueconst full = (watcher as any).requestHostFleetReconcile('Periodic resync',@@@ -2327,22 -2381,77 +2382,73 @@@'full') as Promise<void>await vi.waitFor(() => expect(mocks.hostFullReconcile).toHaveBeenCalledOnce())- const modified = hostWatchCallback('MODIFIED', {- metadata: { name: 'updated-host', namespace: 'mcp-host', generation: 2 },- spec: { host: 'updated-host', lifecycle: { stateless: true } },- })- const deleted = hostWatchCallback('DELETED', {- metadata: { name: 'deleted-host', namespace: 'mcp-host', generation: 2 },- spec: { host: 'deleted-host' },++ // A watch event for an INDEPENDENT Host must reconcile without waiting for+ // the blocked full pass — the removed global tail no longer gates it.+ const independent = hostWatchCallback('MODIFIED', {+ metadata: { name: 'independent-host', namespace: 'mcp-host', generation: 5 },+ spec: { host: 'independent-host', lifecycle: { stateless: true } },})+ await vi.waitFor(() =>+ expect(reconcile).toHaveBeenCalledWith(+ expect.objectContaining({ name: 'independent-host', generation: 5 }),+ 'urgent' // direct watch admission reconciles on the urgent lane (F1)+ )+ )+ // Independent Host progressed while the full pass is still blocked.+ expect(order).toContain('watch:independent-host:5')+ expect(order).not.toContain('full:end')- await Promise.resolve()- expect(reconcile).not.toHaveBeenCalled()- expect(reconcileDelete).not.toHaveBeenCalled()fullReconcile.resolve()- await Promise.all([full, modified, deleted])+ await Promise.all([full, independent])+ expect(order).toContain('full:end')+ watcher.stop()+ })++ it('dispatches same-Host watch events to the per-Host chain in causal order', async () => {+ vi.clearAllMocks()+ const order: string[] = []+ type HostWatchCallback = (type: string, host: unknown) => Promise<void>+ let hostWatchCallback: HostWatchCallback | undefined+ mocks.watch.mockImplementation(+ async (path: string, _query: unknown, callback: HostWatchCallback) => {+ if (path.endsWith('/hosts')) hostWatchCallback = callback+ return { abort: vi.fn() }+ }+ )+ mocks.listNamespacedCustomObject.mockImplementation(async () => ({ items: [] }))+ const watcher = new McpServerWatcher()+ const hostReconciler = watcher.getHostReconciler()+ // The reconcile()/reconcileDelete() spies stand in for the per-Host chain;+ // the actual serializeByHost non-overlap guarantee is proven in+ // hostReconciler.test.ts (delete serialization). Here we assert the+ // k8sClient dispatch order for the SAME Host is causal and the final cache+ // state belongs to the newest event (§13.1: N+1 follows the same chain).+ vi.spyOn(hostReconciler, 'reconcile').mockImplementation(async (host: HostCRD) => {+ order.push(`reconcile:${host.name}:${host.generation}`)+ })+ vi.spyOn(hostReconciler, 'reconcileDelete').mockImplementation(async (name: string) => {+ order.push(`delete:${name}`)+ })+ await (watcher as any).startHostWatch('same-host-rv')+ if (!hostWatchCallback) throw new Error('Host watch callback was not installed')+ ;(watcher as any).hostCacheSynced = true- expect(order).toEqual(['full:start', 'full:end', 'watch:updated-host:2', 'delete:deleted-host'])+ await hostWatchCallback('MODIFIED', {+ metadata: { name: 'same-host', namespace: 'mcp-host', generation: 1 },+ spec: { host: 'same-host', lifecycle: { stateless: false } },+ })+ await hostWatchCallback('MODIFIED', {+ metadata: { name: 'same-host', namespace: 'mcp-host', generation: 2 },+ spec: { host: 'same-host', lifecycle: { stateless: true } },+ })+ await hostWatchCallback('DELETED', {+ metadata: { name: 'same-host', namespace: 'mcp-host', generation: 3 },+ spec: { host: 'same-host' },+ })+- expect(order).toEqual([- 'reconcile:same-host:1',- 'reconcile:same-host:2',- 'delete:same-host',- ])++ expect(order).toEqual(['reconcile:same-host:1', 'reconcile:same-host:2', 'delete:same-host'])+ expect((watcher as any).hosts.has('same-host')).toBe(false)watcher.stop()})@@@ -3049,6 -3183,251 +3180,257 @@@ describe('McpServerWatcher Host watch gwatcher.stop()})+ it('recovery diff enqueues an immediate per-Host delete for a disappeared Host (#827 item 1)', async () => {+ vi.clearAllMocks()+ const watcher = new McpServerWatcher()+ const reconcileDelete = vi+ .spyOn(watcher.getHostReconciler(), 'reconcileDelete')+ .mockResolvedValue(undefined)+ // Fresh authoritative snapshot holds only "live-host"; "gone-host" was in the+ // pre-recovery inventory (previousNames) and has genuinely disappeared.+ ;(watcher as any).enqueueRecoveredHostDeletes(+ [{ name: 'live-host', namespace: 'mcp-host', uid: 'u1', spec: { host: 'live-host' } }],+ new Set(['live-host', 'gone-host'])+ )+ await vi.waitFor(() =>+ expect(reconcileDelete).toHaveBeenCalledWith('gone-host', 'mcp-host', expect.anything())+ )+ // A Host still present in the fresh snapshot is never deleted.- expect(reconcileDelete).not.toHaveBeenCalledWith(- 'live-host',- 'mcp-host',- expect.anything()- )++ expect(reconcileDelete).not.toHaveBeenCalledWith('live-host', 'mcp-host', expect.anything())+ watcher.stop()+ })++ // The recovery diff resolves absence at LIST time. Between that diff and the+ // moment the delete is admitted to the per-Host serializer, the recreation's+ // ADDED can land: the watch callback sets `this.hosts` SYNCHRONOUSLY and+ // enters the per-Host chain FIRST, while the fire-and-forget dispatch queues+ // the delete SECOND. serializeByHost is strict FIFO, so without a fence the+ // new bundle is created and then wiped. The fence must therefore read the+ // LIVE cache at admission, not a value captured at enqueue time.+ //+ // This is the case the sibling recreation test does NOT cover: there the+ // recreated Host is present in the snapshot, so enqueueRecoveredHostDeletes+ // short-circuits on snapshotNames.has(name) and never dispatches at all.+ it('recovery delete carries a live-cache fence for a Host recreated during admission (#827 F2 parity)', async () => {+ vi.clearAllMocks()+ const watcher = new McpServerWatcher()+ const reconcileDelete = vi+ .spyOn(watcher.getHostReconciler(), 'reconcileDelete')+ .mockResolvedValue(undefined)+ // "ghost" is absent from the fresh authoritative snapshot → genuinely+ // disappeared → dispatched for delete.+ ;(watcher as any).enqueueRecoveredHostDeletes([], new Set(['ghost']))+ await vi.waitFor(() => expect(reconcileDelete).toHaveBeenCalled())++ const [, , opts] = reconcileDelete.mock.calls[0] as [+ string,+ string,+ { skipIf?: () => boolean } | undefined,+ ]+ expect(opts?.skipIf, 'the recovery delete must carry a skipIf fence').toBeTypeOf('function')++ // Cache does not hold the name → the Host really is gone → do NOT skip.+ expect(opts!.skipIf!()).toBe(false)++ // The recreation lands in the live cache during the admission window.+ ;(watcher as any).hosts.set('ghost', {+ name: 'ghost',+ namespace: 'mcp-host',+ uid: 'uid-recreated',+ generation: 1,+ spec: { host: 'ghost' },+ })+ // Same fence, re-evaluated at admission → skip the destructive delete.+ expect(opts!.skipIf!()).toBe(true)+ watcher.stop()+ })++ it('recovery diff reconciles (does NOT delete) a same-name Host recreated with a new uid (#827 items 1+2)', async () => {+ vi.clearAllMocks()+ const watcher = new McpServerWatcher()+ const reconcile = vi+ .spyOn(watcher.getHostReconciler(), 'reconcile')+ .mockResolvedValue(undefined)+ const reconcileDelete = vi+ .spyOn(watcher.getHostReconciler(), 'reconcileDelete')+ .mockResolvedValue(undefined)+ // The recreated Host is the CURRENT cache entry the urgent dispatch resolves.+ ;(watcher as any).hosts.set('x', {+ name: 'x',+ namespace: 'mcp-host',+ uid: 'uid-B',+ generation: 1,+ spec: { host: 'x' },+ })+ // Same name, same generation (reset to 1), but a DIFFERENT uid than before.+ ;(watcher as any).enqueueRecoveredUrgentHosts(+ [{ name: 'x', namespace: 'mcp-host', uid: 'uid-B', generation: 1, spec: { host: 'x' } }],+ new Set(['x']),+ new Map([['x', 1]]),+ new Map([['x', 'uid-A']])+ )+ // The snapshot still contains "x" by name, so the recovery-delete diff never+ // treats it as a disappearance.+ ;(watcher as any).enqueueRecoveredHostDeletes(+ [{ name: 'x', namespace: 'mcp-host', uid: 'uid-B', generation: 1, spec: { host: 'x' } }],+ new Set(['x'])+ )+ await vi.waitFor(() =>+ expect(reconcile).toHaveBeenCalledWith(expect.objectContaining({ name: 'x' }), 'urgent')+ )+ expect(reconcileDelete).not.toHaveBeenCalled()+ watcher.stop()+ })++ it('suppresses a watch event whose identity (uid) differs from the cached Host (#827 item 2)', () => {+ const watcher = new McpServerWatcher()- ;(watcher as any).hosts.set('x', { name: 'x', namespace: 'mcp-host', uid: 'uid-B', generation: 3 })++ ;(watcher as any).hosts.set('x', {++ name: 'x',++ namespace: 'mcp-host',++ uid: 'uid-B',++ generation: 3,++ })+ ;(watcher as any).latestHostWatchEventRevisions.set('x', 7)+ // A stale MODIFIED carrying the OLD identity must not act on the recreated one.+ expect(+ (watcher as any).isCurrentHostWatchEvent(+ 'MODIFIED',+ { name: 'x', namespace: 'mcp-host', uid: 'uid-A', generation: 3 },+ 7+ )+ ).toBe(false)+ // The current identity is admitted.+ expect(+ (watcher as any).isCurrentHostWatchEvent(+ 'MODIFIED',+ { name: 'x', namespace: 'mcp-host', uid: 'uid-B', generation: 3 },+ 7+ )+ ).toBe(true)+ watcher.stop()+ })++ it('recovery urgently admits a wake-pending Host that is otherwise unchanged (§10.2 step 7 wake branch)', async () => {+ vi.clearAllMocks()+ const watcher = new McpServerWatcher()+ const reconcile = vi+ .spyOn(watcher.getHostReconciler(), 'reconcile')+ .mockResolvedValue(undefined)+ // A Host unchanged by name, generation AND uid but carrying a pending wake+ // annotation must still be admitted on the urgent lane after recovery, so a+ // wake discovered during the LIST→WATCH gap is not deferred to the slow+ // background fleet pass (A3: 2m47s admission vs 3s execution). This closes+ // the recovery-time wake branch that the watch-time admission test does not+ // exercise: deleting `|| wakePending` from enqueueRecoveredUrgentHosts()+ // would make this assertion fail.+ ;(watcher as any).hosts.set('waker', {+ name: 'waker',+ namespace: 'mcp-host',+ uid: 'u1',+ generation: 4,+ annotations: { 'clerum.io/wake-requested': '7' },+ spec: { host: 'waker' },+ })+ ;(watcher as any).enqueueRecoveredUrgentHosts(+ [+ {+ name: 'waker',+ namespace: 'mcp-host',+ uid: 'u1',+ generation: 4,+ annotations: { 'clerum.io/wake-requested': '7' },+ spec: { host: 'waker' },+ },+ ],+ new Set(['waker']), // NOT new+ new Map([['waker', 4]]), // NOT changed (same generation)+ new Map([['waker', 'u1']]) // NOT recreated (same uid)+ )+ await vi.waitFor(() =>- expect(reconcile).toHaveBeenCalledWith(- expect.objectContaining({ name: 'waker' }),- 'urgent'- )++ expect(reconcile).toHaveBeenCalledWith(expect.objectContaining({ name: 'waker' }), 'urgent')+ )+ watcher.stop()+ })++ it('recovery does NOT urgently dispatch a fully-unchanged Host with no wake annotation', async () => {+ vi.clearAllMocks()+ const watcher = new McpServerWatcher()+ const reconcile = vi+ .spyOn(watcher.getHostReconciler(), 'reconcile')+ .mockResolvedValue(undefined)+ // Same name, generation and uid as before recovery and no wake pending: the+ // background fleet pass already covers it, so recovery must NOT enqueue a+ // redundant urgent reconcile (guards the negative side of the predicate).+ ;(watcher as any).hosts.set('steady', {+ name: 'steady',+ namespace: 'mcp-host',+ uid: 'u1',+ generation: 4,+ spec: { host: 'steady' },+ })+ ;(watcher as any).enqueueRecoveredUrgentHosts(- [{ name: 'steady', namespace: 'mcp-host', uid: 'u1', generation: 4, spec: { host: 'steady' } }],++ [++ {++ name: 'steady',++ namespace: 'mcp-host',++ uid: 'u1',++ generation: 4,++ spec: { host: 'steady' },++ },++ ],+ new Set(['steady']),+ new Map([['steady', 4]]),+ new Map([['steady', 'u1']])+ )+ // Let any erroneously-scheduled async dispatch run before asserting absence.+ await Promise.resolve()+ await Promise.resolve()+ expect(reconcile).not.toHaveBeenCalled()+ watcher.stop()+ })++ it('reconciles a retried Host watch event on the "retry" lane, not "urgent" (F1)', async () => {+ vi.useFakeTimers()+ let hostWatchCallback: ((type: string, apiObj: any) => Promise<void>) | undefined+ mocks.watch.mockImplementation(+ async (+ _path: string,+ _params: object,+ callback: (type: string, apiObj: any) => Promise<void>+ ) => {+ hostWatchCallback = callback+ return { abort: vi.fn() }+ }+ )+ const watcher = new McpServerWatcher()+ const reconcile = vi+ .spyOn(watcher.getHostReconciler(), 'reconcile')+ .mockRejectedValueOnce(new Error('transient'))+ .mockResolvedValue(undefined)+ await (watcher as any).startHostWatch('test-host-rv')+ if (!hostWatchCallback) throw new Error('Host watch callback was not installed')++ await hostWatchCallback('MODIFIED', {+ metadata: { name: 'retry-lane-host', namespace: 'mcp-host', generation: 2 },+ spec: { host: 'retry-lane-host', lifecycle: { stateless: true } },+ })+ // First attempt is the direct/urgent admission.+ expect(reconcile).toHaveBeenNthCalledWith(+ 1,+ expect.objectContaining({ name: 'retry-lane-host' }),+ 'urgent'+ )+ await vi.advanceTimersByTimeAsync(5000)+ // The retry attempt populates the distinct "retry" lane.+ expect(reconcile).toHaveBeenNthCalledWith(+ 2,+ expect.objectContaining({ name: 'retry-lane-host' }),+ 'retry'+ )+ watcher.stop()+ vi.useRealTimers()+ })+it('automatically retries a transient Host watch reconciliation failure', async () => {vi.useFakeTimers()let hostWatchCallback: ((type: string, apiObj: any) => Promise<void>) | undefineddiff --cc host-context-controller/src/k8sClient.tsindex c452d9c4c,e850c29ae..ea754b7b5--- a/host-context-controller/src/k8sClient.ts+++ b/host-context-controller/src/k8sClient.ts@@@ -17,7 -17,17 +17,12 @@@ import { config } from './configimport { gfsDefaultFactoryConfig } from './gfsConfig'import { GfsReconciler } from './gfsReconciler'import { ControlApiGfsSeedClient } from './gfsSeedClient'- import { HostFleetReconcileError, HostReconciler, type ResolvedSfsMount } from './hostReconciler'+ import {+ HostFleetReconcileError,- HostReconciler,+ type HostReconcileSource,++ HostReconciler,+ type ResolvedSfsMount,+ } from './hostReconciler'-import {- hostDeleteCleanupTotal,- hostFleetRequestsTotal,- hostWatchRecoverySeconds,-} from './metrics'import {type InfrastructureTelemetryReporter,createInfrastructureTelemetryReporter,@@@ -25,6 -35,6 +30,7 @@@import { K8sGfsApi } from './k8s/gfsK8sApi'import { makeHostK8sApiClient } from './k8s/hostK8sApiClient'import { pvcName as sfsPvcName } from './k8s/sharedFileSystemFactory'++import { hostDeleteCleanupTotal, hostFleetRequestsTotal, hostWatchRecoverySeconds } from './metrics'import { NetworkPolicyReconciler } from './networkPolicyReconciler'import { McpServerReconciler } from './reconciler'import { SharedFileSystemReconciler } from './sharedFileSystemReconciler'diff --cc host-context-controller/src/metrics.tsindex 5dd7c2549,4de90228e..75b8cc5f0--- a/host-context-controller/src/metrics.ts+++ b/host-context-controller/src/metrics.ts@@@ -42,6 -42,33 +42,31 @@@ function gauge(options:})}+ /**+ * Buckets spanning sub-second admission through the urgent (5s), watch-recovery+ * (15s), and wake (45s) budgets, plus longer diagnostic tails. Shared by every+ * HCC reconcile/recovery latency histogram.+ */-const RECONCILE_LATENCY_BUCKETS = [- 0.05, 0.1, 0.25, 0.5, 1, 2, 5, 15, 45, 120,-] as const++const RECONCILE_LATENCY_BUCKETS = [0.05, 0.1, 0.25, 0.5, 1, 2, 5, 15, 45, 120] as const++ /** Idempotent Histogram helper mirroring counter()/gauge(). */+ function histogram(options: {+ name: string+ help: string+ labelNames?: readonly string[]+ buckets?: readonly number[]+ }): Histogram<string> {+ const existing = registry.getSingleMetric(options.name)+ if (existing) return existing as Histogram<string>+ return new Histogram({+ name: options.name,+ help: options.help,+ labelNames: [...(options.labelNames ?? [])],+ buckets: [...(options.buckets ?? RECONCILE_LATENCY_BUCKETS)],+ registers: [registry],+ })+ }+export const mcpServersTotal = gauge({name: 'clerum_hcc_mcpservers_total',help: 'Total number of McpServer CRDs tracked by HCC',diff --cc host-context-controller/test/hostReconciler.heartbeat.test.tsindex 3c5ce8ece,eb28006b4..9be3bba71--- a/host-context-controller/test/hostReconciler.heartbeat.test.ts+++ b/host-context-controller/test/hostReconciler.heartbeat.test.ts@@@ -439,7 -439,7 +439,8 @@@ describe('HostReconciler.publishSuspendlifecycle: {state: 'active',wakeHandledGeneration: 0,- reason: '1 CommunicationChannel(s) reference this Host',- reason: '1 CommunicationChannel(s) reference this Host; disassociate them to enable the requested stateless lifecycle',++ reason:++ '1 CommunicationChannel(s) reference this Host; disassociate them to enable the requested stateless lifecycle',},},})@@@ -452,7 -452,7 +453,8 @@@freshHostRead({state: 'active',wakeHandledGeneration: 0,- reason: '1 CommunicationChannel(s) reference this Host',- reason: '1 CommunicationChannel(s) reference this Host; disassociate them to enable the requested stateless lifecycle',++ reason:++ '1 CommunicationChannel(s) reference this Host; disassociate them to enable the requested stateless lifecycle',}))diff --cc host-context-controller/test/hostReconciler.lifecycle.test.tsindex b665f6268,c8d653513..61c5a98f9--- a/host-context-controller/test/hostReconciler.lifecycle.test.ts+++ b/host-context-controller/test/hostReconciler.lifecycle.test.ts@@@ -793,7 -793,7 +793,8 @@@ describe('HostReconciler stateless lifeexpect(writes[1].lifecycle).toEqual({state: 'active',wakeHandledGeneration: 5,- reason: '1 CommunicationChannel(s) reference this Host',- reason: '1 CommunicationChannel(s) reference this Host; disassociate them to enable the requested stateless lifecycle',++ reason:++ '1 CommunicationChannel(s) reference this Host; disassociate them to enable the requested stateless lifecycle',})expect(rejectedCondition(writes[1])).toMatchObject({status: 'True',@@@ -872,7 -872,7 +873,8 @@@expect(writes[1].lifecycle).toEqual({state: 'active',wakeHandledGeneration: 6,- reason: '1 CommunicationChannel(s) reference this Host',- reason: '1 CommunicationChannel(s) reference this Host; disassociate them to enable the requested stateless lifecycle',++ reason:++ '1 CommunicationChannel(s) reference this Host; disassociate them to enable the requested stateless lifecycle',})})@@@ -988,7 -988,7 +990,9 @@@)const writes = lifecycleStatusWrites(customApi)expect(writes).toHaveLength(2)- expect(writes[1].lifecycle?.reason).toBe('1 CommunicationChannel(s) reference this Host')- expect(writes[1].lifecycle?.reason).toBe('1 CommunicationChannel(s) reference this Host; disassociate them to enable the requested stateless lifecycle')++ expect(writes[1].lifecycle?.reason).toBe(++ '1 CommunicationChannel(s) reference this Host; disassociate them to enable the requested stateless lifecycle'++ )})it('does not repeat bootstrap provisioning when channel ingress already existed in spec', async () => {@@@ -1321,7 -1388,7 +1392,8 @@@ describe('HostReconciler stateless lifeexpect(writes[0].lifecycle).toEqual({state: 'active',wakeHandledGeneration: 3,- reason: '1 CommunicationChannel(s) reference this Host',- reason: '1 CommunicationChannel(s) reference this Host; disassociate them to enable the requested stateless lifecycle',++ reason:++ '1 CommunicationChannel(s) reference this Host; disassociate them to enable the requested stateless lifecycle',})expect(rejectedCondition(writes[0]).status).toBe('True')})@@@ -1535,7 -1602,7 +1607,8 @@@ describe('HostReconciler stateless lifeexpect(writes.at(-1)?.lifecycle).toEqual({state: 'active',wakeHandledGeneration: 3,- reason: '1 CommunicationChannel(s) reference this Host',- reason: '1 CommunicationChannel(s) reference this Host; disassociate them to enable the requested stateless lifecycle',++ reason:++ '1 CommunicationChannel(s) reference this Host; disassociate them to enable the requested stateless lifecycle',})})@@@ -1563,7 -1630,7 +1636,8 @@@expect(writes.at(-1)?.lifecycle).toEqual({state: 'active',wakeHandledGeneration: 2,- reason: '1 CommunicationChannel(s) reference this Host',- reason: '1 CommunicationChannel(s) reference this Host; disassociate them to enable the requested stateless lifecycle',++ reason:++ '1 CommunicationChannel(s) reference this Host; disassociate them to enable the requested stateless lifecycle',})})@@@ -1589,7 -1656,7 +1663,8 @@@expect(writes.at(-1)?.lifecycle).toEqual({state: 'suspended',wakeHandledGeneration: 5,- reason: '1 CommunicationChannel(s) reference this Host',- reason: '1 CommunicationChannel(s) reference this Host; disassociate them to enable the requested stateless lifecycle',++ reason:++ '1 CommunicationChannel(s) reference this Host; disassociate them to enable the requested stateless lifecycle',})})diff --cc host-context-controller/test/statelessDeployment.workspaceLayout.test.tsindex 000000000,790d3833b..7b75c2327mode 000000,100644..100644--- a/host-context-controller/test/statelessDeployment.workspaceLayout.test.ts+++ b/host-context-controller/test/statelessDeployment.workspaceLayout.test.ts@@@ -1,0 -1,331 +1,330 @@@+ import { afterEach, describe, expect, it } from 'vitest'+ import { execFileSync, spawnSync } from 'node:child_process'+ import {+ existsSync,+ lstatSync,+ mkdirSync,+ mkdtempSync,+ readFileSync,+ readdirSync,+ rmSync,+ symlinkSync,+ writeFileSync,+ } from 'node:fs'+ import { tmpdir } from 'node:os'+ import { join } from 'node:path'+ import { buildWorkspaceLayoutInitScript } from '../src/statelessDeployment'++ const roots: string[] = []++ function makeRoot(): string {+ const root = mkdtempSync(join(tmpdir(), 'clerum-workspace-layout-'))+ roots.push(root)+ return root+ }++ function runMigration(root: string): void {+ execFileSync('/bin/sh', ['-c', buildWorkspaceLayoutInitScript(root)], { stdio: 'pipe' })+ }++ function migrationFailure(root: string): { stderr?: Buffer } {+ try {+ runMigration(root)+ } catch (error) {+ return error as { stderr?: Buffer }+ }+ throw new Error('expected workspace layout migration to fail')+ }++ // Captures stderr even on SUCCESS (execFileSync only surfaces stderr on throw),+ // so the loud round-trip resolution log can be asserted on a passing migration.+ function runMigrationCapture(root: string): { status: number; stderr: string } {+ const res = spawnSync('/bin/sh', ['-c', buildWorkspaceLayoutInitScript(root)], {+ encoding: 'utf8',+ })+ if (res.error) throw res.error+ return { status: res.status ?? -1, stderr: res.stderr ?? '' }+ }++ function stateBackups(root: string, prefix = 'state.db'): string[] {+ return readdirSync(join(root, 'state'))+ .filter(name => name.startsWith(`${prefix}.pre-`) && name.endsWith('.bak'))+ .sort()+ }++ afterEach(() => {+ for (const root of roots.splice(0)) rmSync(root, { recursive: true, force: true })+ })++ describe('stateless workspace layout migration', () => {+ it('moves legacy workspace and SQLite files once and is idempotent', () => {+ const root = makeRoot()+ writeFileSync(join(root, 'notes.md'), 'workspace-data')+ writeFileSync(join(root, 'state.db'), 'durable-db')++ runMigration(root)+ runMigration(root)++ expect(readFileSync(join(root, 'workspace', 'notes.md'), 'utf8')).toBe('workspace-data')+ expect(readFileSync(join(root, 'state', 'state.db'), 'utf8')).toBe('durable-db')- }, // This is the only case that launches the migration shell twice. Keep its- // runner budget above the generic 5s limit so CI process contention cannot++ }, // runner budget above the generic 5s limit so CI process contention cannot // This is the only case that launches the migration shell twice. Keep its+ // turn a completed idempotency check into a harness timeout.+ 15_000)++ it('finishes a partial migration whose SQLite source is already under workspace', () => {+ const root = makeRoot()+ mkdirSync(join(root, 'workspace'))+ writeFileSync(join(root, 'workspace', 'state.db'), 'durable-db')++ runMigration(root)++ expect(readFileSync(join(root, 'state', 'state.db'), 'utf8')).toBe('durable-db')+ })++ it.each([+ {+ rootArtifact: 'state.db',+ workspaceArtifact: 'state.db-wal',+ },+ {+ rootArtifact: 'state.db-shm',+ workspaceArtifact: 'state.db',+ },+ ])(+ 'fails closed when $rootArtifact and $workspaceArtifact split SQLite source authority',+ ({ rootArtifact, workspaceArtifact }) => {+ const root = makeRoot()+ mkdirSync(join(root, 'workspace'))+ writeFileSync(join(root, 'notes.md'), 'must-stay-root')+ writeFileSync(join(root, rootArtifact), 'root-artifact')+ writeFileSync(join(root, 'workspace', workspaceArtifact), 'workspace-artifact')++ expect(String(migrationFailure(root).stderr)).toContain(+ 'SQLite artifacts are split across root and workspace'+ )+ expect(readFileSync(join(root, 'notes.md'), 'utf8')).toBe('must-stay-root')+ expect(readFileSync(join(root, rootArtifact), 'utf8')).toBe('root-artifact')+ expect(readFileSync(join(root, 'workspace', workspaceArtifact), 'utf8')).toBe(+ 'workspace-artifact'+ )+ }+ )++ it('fails closed without overwriting a duplicate workspace entry', () => {+ const root = makeRoot()+ mkdirSync(join(root, 'workspace'))+ writeFileSync(join(root, 'notes.md'), 'legacy-data')+ writeFileSync(join(root, 'workspace', 'notes.md'), 'current-data')++ expect(String(migrationFailure(root).stderr)).toContain('workspace layout migration collision')+ expect(readFileSync(join(root, 'notes.md'), 'utf8')).toBe('legacy-data')+ expect(readFileSync(join(root, 'workspace', 'notes.md'), 'utf8')).toBe('current-data')+ })++ it('fails closed without overwriting an existing durable SQLite file', () => {+ const root = makeRoot()+ mkdirSync(join(root, 'workspace'))+ mkdirSync(join(root, 'state'))+ writeFileSync(join(root, 'workspace', 'state.db'), 'legacy-db')+ writeFileSync(join(root, 'state', 'state.db'), 'current-db')++ expect(String(migrationFailure(root).stderr)).toContain('workspace layout migration collision')+ expect(readFileSync(join(root, 'workspace', 'state.db'), 'utf8')).toBe('legacy-db')+ expect(readFileSync(join(root, 'state', 'state.db'), 'utf8')).toBe('current-db')+ })++ it('resolves a root SQLite round-trip collision: backs up the older destination and migrates the fresher root source', () => {+ // Addendum 6 item 6 (newest-source-wins): a stateful<->stateless round-trip+ // leaves BOTH root state.db (freshest — the stateful life just left) and an+ // earlier stateless life's state/state.db. The migration must self-heal, not+ // deadlock: back up the older destination (never delete) and migrate the+ // fresher root source in, while non-SQLite root content still moves to+ // workspace/.+ const root = makeRoot()+ mkdirSync(join(root, 'workspace'))+ mkdirSync(join(root, 'state'))+ writeFileSync(join(root, 'notes.md'), 'must-migrate-to-workspace')+ writeFileSync(join(root, 'state.db'), 'fresh-stateful-db')+ writeFileSync(join(root, 'state', 'state.db'), 'older-stateless-db')++ const { status, stderr } = runMigrationCapture(root)++ expect(status).toBe(0)+ // Fresher root data migrated into the durable destination.+ expect(readFileSync(join(root, 'state', 'state.db'), 'utf8')).toBe('fresh-stateful-db')+ expect(existsSync(join(root, 'state.db'))).toBe(false)+ // Non-SQLite root content still migrated to workspace/.+ expect(readFileSync(join(root, 'workspace', 'notes.md'), 'utf8')).toBe(+ 'must-migrate-to-workspace'+ )+ // Older destination preserved (never deleted) as a timestamped backup.+ const backups = stateBackups(root)+ expect(backups).toHaveLength(1)+ expect(readFileSync(join(root, 'state', backups[0]), 'utf8')).toBe('older-stateless-db')+ // Loud one-line resolution log naming the backup + migration.+ expect(stderr).toContain('newest-source-wins round-trip resolution')+ expect(stderr).toContain('.pre-')+ })++ it('renames wal/shm destination companions in lockstep with the state.db backup', () => {+ const root = makeRoot()+ mkdirSync(join(root, 'state'))+ for (const db of ['state.db', 'state.db-wal', 'state.db-shm']) {+ writeFileSync(join(root, db), `fresh-${db}`)+ writeFileSync(join(root, 'state', db), `older-${db}`)+ }++ const { status } = runMigrationCapture(root)+ expect(status).toBe(0)++ // All three fresher root companions migrated into state/.+ for (const db of ['state.db', 'state.db-wal', 'state.db-shm']) {+ expect(readFileSync(join(root, 'state', db), 'utf8')).toBe(`fresh-${db}`)+ expect(existsSync(join(root, db))).toBe(false)+ }+ // All three older destinations backed up under ONE shared timestamp suffix.+ const backups = readdirSync(join(root, 'state'))+ .filter(name => name.endsWith('.bak'))+ .sort()+ expect(backups).toHaveLength(3)+ const suffixes = new Set(+ backups.map(name => name.replace(/^state\.db(-wal|-shm)?\.pre-/, '').replace(/\.bak$/, ''))+ )+ expect(suffixes.size).toBe(1)+ expect(+ readFileSync(join(root, 'state', backups.find(f => f.startsWith('state.db.pre-'))!), 'utf8')+ ).toBe('older-state.db')+ expect(+ readFileSync(+ join(root, 'state', backups.find(f => f.startsWith('state.db-wal.pre-'))!),+ 'utf8'+ )+ ).toBe('older-state.db-wal')+ expect(+ readFileSync(+ join(root, 'state', backups.find(f => f.startsWith('state.db-shm.pre-'))!),+ 'utf8'+ )+ ).toBe('older-state.db-shm')+ })++ it('is idempotent after a backup: a second run with no root source is a no-op', () => {+ const root = makeRoot()+ mkdirSync(join(root, 'state'))+ writeFileSync(join(root, 'state.db'), 'fresh-db')+ writeFileSync(join(root, 'state', 'state.db'), 'older-db')++ const first = runMigrationCapture(root)+ expect(first.status).toBe(0)+ const afterFirst = stateBackups(root)+ expect(afterFirst).toHaveLength(1)++ const second = runMigrationCapture(root)+ expect(second.status).toBe(0)+ // No new backup, destination unchanged, no resolution log on the no-op run.+ expect(stateBackups(root)).toEqual(afterFirst)+ expect(readFileSync(join(root, 'state', 'state.db'), 'utf8')).toBe('fresh-db')+ expect(second.stderr).not.toContain('newest-source-wins')+ })++ it('backs up under a NEW unique suffix on each later round-trip collision', () => {+ const root = makeRoot()+ mkdirSync(join(root, 'state'))+ writeFileSync(join(root, 'state.db'), 'stateful-life-1')+ writeFileSync(join(root, 'state', 'state.db'), 'stateless-life-0')++ expect(runMigrationCapture(root).status).toBe(0)+ // A new stateful life re-creates the root source for a second round-trip.+ writeFileSync(join(root, 'state.db'), 'stateful-life-2')+ expect(runMigrationCapture(root).status).toBe(0)++ // Two distinct backups: nothing was overwritten across the two collisions.+ const backups = stateBackups(root)+ expect(backups).toHaveLength(2)+ const contents = backups.map(name => readFileSync(join(root, 'state', name), 'utf8')).sort()+ expect(contents).toEqual(['stateful-life-1', 'stateless-life-0'].sort())+ // Final durable state is the newest life.+ expect(readFileSync(join(root, 'state', 'state.db'), 'utf8')).toBe('stateful-life-2')+ })++ it('keeps a WORKSPACE SQLite source colliding with the destination fail-loud (genuinely ambiguous)', () => {+ // Only the ROOT round-trip collision self-heals. A workspace SQLite source+ // (an interrupted partial migration) colliding with an existing durable+ // destination stays fail-loud, preserving every source for recovery.+ const root = makeRoot()+ mkdirSync(join(root, 'workspace'))+ mkdirSync(join(root, 'state'))+ writeFileSync(join(root, 'workspace', 'state.db'), 'legacy-db')+ writeFileSync(join(root, 'state', 'state.db'), 'current-db')++ expect(String(migrationFailure(root).stderr)).toContain('workspace layout migration collision')+ expect(readFileSync(join(root, 'workspace', 'state.db'), 'utf8')).toBe('legacy-db')+ expect(readFileSync(join(root, 'state', 'state.db'), 'utf8')).toBe('current-db')+ expect(stateBackups(root)).toHaveLength(0)+ })++ it.each(['workspace', 'state'])(+ 'rejects a symlinked %s directory without writing through it',+ managedDir => {+ const root = makeRoot()+ const outside = makeRoot()+ symlinkSync(outside, join(root, managedDir), 'dir')+ writeFileSync(join(root, managedDir === 'workspace' ? 'notes.md' : 'state.db'), 'must-stay')++ expect(String(migrationFailure(root).stderr)).toContain(+ `${managedDir} directory is a symlink`+ )+ expect(+ readFileSync(join(root, managedDir === 'workspace' ? 'notes.md' : 'state.db'), 'utf8')+ ).toBe('must-stay')+ expect(existsSync(join(outside, 'notes.md'))).toBe(false)+ expect(existsSync(join(outside, 'state.db'))).toBe(false)+ }+ )++ it('rejects a symlinked PVC root without touching its target', () => {+ const target = makeRoot()+ const parent = makeRoot()+ const linkedRoot = join(parent, 'workspace-root')+ writeFileSync(join(target, 'notes.md'), 'target-data')+ symlinkSync(target, linkedRoot, 'dir')++ expect(String(migrationFailure(linkedRoot).stderr)).toContain('PVC root is a symlink')+ expect(readFileSync(join(target, 'notes.md'), 'utf8')).toBe('target-data')+ expect(existsSync(join(target, 'workspace'))).toBe(false)+ expect(existsSync(join(target, 'state'))).toBe(false)+ })++ it('rejects a symlinked legacy source without moving it or touching its target', () => {+ const root = makeRoot()+ const outside = makeRoot()+ const outsideTarget = join(outside, 'target.txt')+ const source = join(root, 'notes.md')+ writeFileSync(outsideTarget, 'outside-data')+ symlinkSync(outsideTarget, source)++ expect(String(migrationFailure(root).stderr)).toContain('legacy source is a symlink')+ expect(lstatSync(source).isSymbolicLink()).toBe(true)+ expect(readFileSync(outsideTarget, 'utf8')).toBe('outside-data')+ expect(existsSync(join(root, 'workspace', 'notes.md'))).toBe(false)+ })++ it.each(['workspace', 'state'])(+ 'rejects a symlinked SQLite artifact under %s without touching its target',+ sqliteDir => {+ const root = makeRoot()+ const outside = makeRoot()+ const outsideTarget = join(outside, 'outside-state.db')+ mkdirSync(join(root, sqliteDir))+ writeFileSync(outsideTarget, 'outside-db')+ symlinkSync(outsideTarget, join(root, sqliteDir, 'state.db'))+ if (sqliteDir === 'state') writeFileSync(join(root, 'state.db'), 'legacy-db')++ expect(String(migrationFailure(root).stderr)).toContain('SQLite')+ expect(readFileSync(outsideTarget, 'utf8')).toBe('outside-db')+ expect(lstatSync(join(root, sqliteDir, 'state.db')).isSymbolicLink()).toBe(true)+ if (sqliteDir === 'state')+ expect(readFileSync(join(root, 'state.db'), 'utf8')).toBe('legacy-db')+ }+ )+ })diff --cc mcp-host/package-lock.jsonindex 39fc80840,39fc80840..f488d15a3--- a/mcp-host/package-lock.json+++ b/mcp-host/package-lock.json@@@ -1,12 -1,12 +1,12 @@@{"name": "clerum-mcp-host",-- "version": "0.1.209",++ "version": "0.1.210","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "clerum-mcp-host",-- "version": "0.1.209",++ "version": "0.1.210","license": "SEE LICENSE IN LICENSE","dependencies": {"@anthropic-ai/sdk": "^0.32.0",diff --cc mcp-host/package.jsonindex 720639769,720639769..076738265--- a/mcp-host/package.json+++ b/mcp-host/package.json@@@ -1,6 -1,6 +1,6 @@@{"name": "clerum-mcp-host",-- "version": "0.1.209",++ "version": "0.1.210","description": "MCP Host - reads Host CRD and provides LLM access via OpenAI/Claude","main": "dist/main.js","engines": {diff --cc rpc-proxy/package-lock.jsonindex 69bb9f161,69bb9f161..26bef05e7--- a/rpc-proxy/package-lock.json+++ b/rpc-proxy/package-lock.json@@@ -1,12 -1,12 +1,12 @@@{"name": "clerum-rpc-proxy",-- "version": "0.1.50",++ "version": "0.1.52","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "clerum-rpc-proxy",-- "version": "0.1.50",++ "version": "0.1.52","dependencies": {"cors": "^2.8.5","express": "^4.21.2",diff --cc rpc-proxy/package.jsonindex 8d54ca64b,8d54ca64b..d0951fe4e--- a/rpc-proxy/package.json+++ b/rpc-proxy/package.json@@@ -1,6 -1,6 +1,6 @@@{"name": "clerum-rpc-proxy",-- "version": "0.1.50",++ "version": "0.1.52","description": "External-facing RPC proxy for tenant-scoped MCP access","main": "dist/main.js","engines": {diff --cc rpc-proxy/src/__tests__/wake-route-coverage.test.tsindex 000000000,eed0e33ba..b7289c749mode 000000,100644..100644--- a/rpc-proxy/src/__tests__/wake-route-coverage.test.ts+++ b/rpc-proxy/src/__tests__/wake-route-coverage.test.ts@@@ -1,0 -1,554 +1,559 @@@+ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'+ import type { Response as ExpressResponse } from 'express'+ import express from 'express'+ import request from 'supertest'+ import {+ createRpcRouter,+ respondControlApiHostAccessRejection,+ respondUpstreamUnavailable,+ } from '../routes/rpc.js'++ // ── Issue #791 §11.4/§11.5 — extend wake-and-hold to the remaining finite+ // Desktop routes, and prove terminal-response (duplicate-write) safety in the+ // route-level outer catches. Wake capability rides on the token; the route+ // scope guards are UNCHANGED.++ const authTokenMock = vi.hoisted(() => ({ verifyRpcToken: vi.fn() }))+ const serviceMock = vi.hoisted(() => ({+ listAllowedServersForUser: vi.fn(),+ resolveServerConnectionForUser: vi.fn(),+ resolveHostConnectionForUser: vi.fn(),+ validateRpcRequest: vi.fn(),+ forwardRpcToServer: vi.fn(),+ forwardHostMessageToHost: vi.fn(),+ forwardHostActivity: vi.fn(),+ forwardHostStatus: vi.fn(),+ forwardHostHealth: vi.fn(),+ forwardTaskResultFromHost: vi.fn(),+ forwardCancelToHost: vi.fn(),+ UpstreamHostError: class UpstreamHostError extends Error {+ constructor(+ public readonly status: number,+ public readonly bodySnippet: string+ ) {+ super(`Upstream host returned ${status}: ${bodySnippet}`)+ this.name = 'UpstreamHostError'+ }+ },+ }))+ const controlApiMock = vi.hoisted(() => ({+ fetchUserAllowedServersFromControlApi: vi.fn(),+ fetchHostConnectionFromControlApi: vi.fn(),+ requestHostWakeFromControlApi: vi.fn(),+ }))++ vi.mock('../authToken.js', () => authTokenMock)+ vi.mock('../services/mcpProxyService.js', () => serviceMock)+ vi.mock('../services/controlApiRestService.js', () => controlApiMock)++ const HOST_CONNECTION = {+ name: 'chatllm',+ url: 'http://chatllm.mcp-host.svc.cluster.local:8080',+ headers: { 'x-clerum-edge-caller': 'rpc-proxy' },+ }++ function claims(scopes: string[]) {+ return {+ sub: 'user-uuid-123',+ typ: 'user' as const,+ accessScope: 'team' as const,+ teamId: 'team-1',+ scopes,+ hostRefs: ['chatllm'],+ jti: 'j1',+ iat: 1,+ exp: 9999999999,+ }+ }++ function makeApp() {+ const app = express()+ app.use(express.json())+ app.use(createRpcRouter())+ app.use(+ (err: unknown, _req: express.Request, res: express.Response, _next: express.NextFunction) => {+ res.status(500).json({ error: err instanceof Error ? err.message : 'Internal error' })+ }+ )+ return app+ }+-function mockFetchResponse(status: number, body: string, headers?: Record<string, string>): Response {++function mockFetchResponse(++ status: number,++ body: string,++ headers?: Record<string, string>++): Response {+ return {+ ok: status >= 200 && status < 300,+ status,+ headers: new Headers(headers),+ text: () => Promise.resolve(body),+ arrayBuffer: () => Promise.resolve(Buffer.from(body).buffer as ArrayBuffer),+ } as unknown as Response+ }++ function hostDownError(): Error {+ return new TypeError('fetch failed')+ }++ function drainingResponse(): Response {+ return mockFetchResponse(503, JSON.stringify({ code: 'host_draining', retryAfterMs: 1000 }), {+ 'content-type': 'application/json',+ })+ }++ const originalFetch = globalThis.fetch++ beforeEach(() => {+ vi.clearAllMocks()+ serviceMock.resolveHostConnectionForUser.mockResolvedValue({ ...HOST_CONNECTION })- controlApiMock.requestHostWakeFromControlApi.mockResolvedValue({ kind: 'active', wakeGeneration: null })++ controlApiMock.requestHostWakeFromControlApi.mockResolvedValue({++ kind: 'active',++ wakeGeneration: null,++ })+ })++ afterEach(() => {+ globalThis.fetch = originalFetch+ })++ describe('§11.4 wake coverage — GET /rpc/hosts/:hostRef/models', () => {+ it('a wake-capable token wakes on host-down and forwards after active', async () => {+ authTokenMock.verifyRpcToken.mockReturnValue(claims(['host:session:read', 'host:wake:write']))+ const fetchMock = vi+ .fn()+ .mockRejectedValueOnce(hostDownError())+ .mockResolvedValueOnce(- mockFetchResponse(200, JSON.stringify({ models: [] }), { 'content-type': 'application/json' })++ mockFetchResponse(200, JSON.stringify({ models: [] }), {++ 'content-type': 'application/json',++ })+ )+ globalThis.fetch = fetchMock as unknown as typeof fetch++ const res = await request(makeApp())+ .get('/rpc/hosts/chatllm/models')+ .set('authorization', 'Bearer tok')+ .expect(200)++ expect(res.body).toEqual({ models: [] })+ expect(controlApiMock.requestHostWakeFromControlApi).toHaveBeenCalledWith('chatllm', 'tok')+ expect(fetchMock).toHaveBeenCalledTimes(2)+ })++ it('a NON-wake token gets the deterministic legacy result and triggers NO wake', async () => {+ authTokenMock.verifyRpcToken.mockReturnValue(claims(['host:session:read']))+ const fetchMock = vi.fn().mockRejectedValue(hostDownError())+ globalThis.fetch = fetchMock as unknown as typeof fetch++ const res = await request(makeApp())+ .get('/rpc/hosts/chatllm/models')+ .set('authorization', 'Bearer tok')+ .expect(502)++ expect(res.body).toEqual({ error: 'Upstream host unavailable' })+ expect(controlApiMock.requestHostWakeFromControlApi).not.toHaveBeenCalled()+ })+ })++ describe('§11.4 wake coverage — POST /rpc/hosts/:hostRef/model', () => {+ it('wakes on host-down and forwards after active', async () => {+ authTokenMock.verifyRpcToken.mockReturnValue(claims(['host:model:write', 'host:wake:write']))+ const fetchMock = vi+ .fn()+ .mockRejectedValueOnce(hostDownError())+ .mockResolvedValueOnce(mockFetchResponse(200, JSON.stringify({ effective: 'next-task' })))+ globalThis.fetch = fetchMock as unknown as typeof fetch++ const res = await request(makeApp())+ .post('/rpc/hosts/chatllm/model')+ .set('authorization', 'Bearer tok')+ .send({ chatId: 'c1', model: 'claude-haiku-4-5' })+ .expect(200)++ expect(res.body).toEqual({ effective: 'next-task' })+ expect(controlApiMock.requestHostWakeFromControlApi).toHaveBeenCalledWith('chatllm', 'tok')+ })+ })++ describe('§11.4 wake coverage — context-breakdown honors the draining fence', () => {+ it('a 503 host_draining triggers a wake and re-forwards after active', async () => {+ authTokenMock.verifyRpcToken.mockReturnValue(claims(['host:session:read', 'host:wake:write']))+ const fetchMock = vi+ .fn()+ .mockResolvedValueOnce(drainingResponse())+ .mockResolvedValueOnce(+ mockFetchResponse(200, JSON.stringify({ breakdown: {} }), {+ 'content-type': 'application/json',+ })+ )+ globalThis.fetch = fetchMock as unknown as typeof fetch++ const res = await request(makeApp())+ .get('/rpc/hosts/chatllm/sessions/chatllm/c1/context-breakdown')+ .set('authorization', 'Bearer tok')+ .expect(200)++ expect(res.body).toEqual({ breakdown: {} })+ expect(controlApiMock.requestHostWakeFromControlApi).toHaveBeenCalledWith('chatllm', 'tok')+ })++ it('a plain upstream 404 is NOT treated as a wake trigger (passes through)', async () => {+ authTokenMock.verifyRpcToken.mockReturnValue(claims(['host:session:read', 'host:wake:write']))- globalThis.fetch = vi- .fn()- .mockResolvedValue(- mockFetchResponse(404, JSON.stringify({ error: 'session not found' }), {- 'content-type': 'application/json',- })- ) as unknown as typeof fetch++ globalThis.fetch = vi.fn().mockResolvedValue(++ mockFetchResponse(404, JSON.stringify({ error: 'session not found' }), {++ 'content-type': 'application/json',++ })++ ) as unknown as typeof fetch++ const res = await request(makeApp())+ .get('/rpc/hosts/chatllm/sessions/chatllm/missing/context-breakdown')+ .set('authorization', 'Bearer tok')+ .expect(404)++ expect(res.body).toEqual({ error: 'session not found' })+ expect(controlApiMock.requestHostWakeFromControlApi).not.toHaveBeenCalled()+ })+ })++ describe('§11.4 wake coverage — approvals approve', () => {+ it('wakes on host-down and forwards after active', async () => {+ authTokenMock.verifyRpcToken.mockReturnValue(claims(['host:approval:write', 'host:wake:write']))+ const fetchMock = vi+ .fn()+ .mockRejectedValueOnce(hostDownError())+ .mockResolvedValueOnce(mockFetchResponse(200, JSON.stringify({ ok: true })))+ globalThis.fetch = fetchMock as unknown as typeof fetch++ const res = await request(makeApp())+ .post('/rpc/hosts/chatllm/approvals/approve')+ .set('authorization', 'Bearer tok')+ .send({ toolCallId: 'tc-1' })+ .expect(200)++ // The approve route relays the upstream body verbatim as a raw string+ // (no JSON content-type is set), so read it via res.text.+ expect(JSON.parse(res.text)).toEqual({ ok: true })+ expect(controlApiMock.requestHostWakeFromControlApi).toHaveBeenCalledWith('chatllm', 'tok')+ })+ })++ describe('§11.4 wake coverage — artifacts list and download', () => {+ it('artifacts list wakes on host-down and forwards after active', async () => {+ authTokenMock.verifyRpcToken.mockReturnValue(claims(['host:task:read', 'host:wake:write']))+ const fetchMock = vi+ .fn()+ .mockRejectedValueOnce(hostDownError())+ .mockResolvedValueOnce(mockFetchResponse(200, JSON.stringify([{ filename: 'a.pdf' }])))+ globalThis.fetch = fetchMock as unknown as typeof fetch++ const res = await request(makeApp())+ .get('/rpc/hosts/chatllm/artifacts')+ .set('authorization', 'Bearer tok')+ .expect(200)++ expect(JSON.parse(res.text)).toEqual([{ filename: 'a.pdf' }])+ expect(controlApiMock.requestHostWakeFromControlApi).toHaveBeenCalledWith('chatllm', 'tok')+ })++ it('artifact download wakes on host-down and streams after active', async () => {+ authTokenMock.verifyRpcToken.mockReturnValue(claims(['host:task:read', 'host:wake:write']))+ const fetchMock = vi+ .fn()+ .mockRejectedValueOnce(hostDownError())+ .mockResolvedValueOnce(+ mockFetchResponse(200, 'PDF-BYTES', { 'content-type': 'application/pdf' })+ )+ globalThis.fetch = fetchMock as unknown as typeof fetch++ const res = await request(makeApp())+ .get('/rpc/hosts/chatllm/artifacts/report.pdf/download')+ .set('authorization', 'Bearer tok')+ .expect(200)++ expect(res.headers['content-type']).toContain('application/pdf')+ expect(controlApiMock.requestHostWakeFromControlApi).toHaveBeenCalledWith('chatllm', 'tok')+ })+ })++ // ── §13.4 row 1 — GET /rpc/hosts/:hostRef/sessions/:agent/:chatId/messages ──+ // sessions-passthrough.test.ts already proves the "wake accepted, host still+ // down → host_waking" variant for this transcript route; the "retry after+ // readiness → operation result" cell (§13.4 row 1 proper) is proven here.+ describe('§13.4 row 1 — session transcript wakes on host-down and re-forwards after active', () => {+ it('a wake-capable token wakes then re-forwards the transcript after active', async () => {+ authTokenMock.verifyRpcToken.mockReturnValue(claims(['host:session:read', 'host:wake:write']))+ const fetchMock = vi+ .fn()+ .mockRejectedValueOnce(hostDownError())+ .mockResolvedValueOnce(+ mockFetchResponse(200, JSON.stringify({ agent: 'chatllm', chatId: 'c1', turns: [] }), {+ 'content-type': 'application/json',+ })+ )+ globalThis.fetch = fetchMock as unknown as typeof fetch++ const res = await request(makeApp())+ .get('/rpc/hosts/chatllm/sessions/chatllm/c1/messages')+ .set('authorization', 'Bearer tok')+ .expect(200)++ expect(res.body).toEqual({ agent: 'chatllm', chatId: 'c1', turns: [] })+ expect(controlApiMock.requestHostWakeFromControlApi).toHaveBeenCalledWith('chatllm', 'tok')+ expect(fetchMock).toHaveBeenCalledTimes(2)+ })+ })++ // ── §11.4 wake coverage — approvals/deny (row 1) ────────────────────────────+ // Closes the audit gap: POST approvals/deny had no route-level wake test at+ // all. Mirrors the approve row-1 test above; the route stays host:approval:write+ // and relays the upstream body verbatim as a raw string.+ describe('§11.4 wake coverage — approvals deny', () => {+ it('wakes on host-down and forwards after active', async () => {+ authTokenMock.verifyRpcToken.mockReturnValue(claims(['host:approval:write', 'host:wake:write']))+ const fetchMock = vi+ .fn()+ .mockRejectedValueOnce(hostDownError())+ .mockResolvedValueOnce(mockFetchResponse(200, JSON.stringify({ ok: true })))+ globalThis.fetch = fetchMock as unknown as typeof fetch++ const res = await request(makeApp())+ .post('/rpc/hosts/chatllm/approvals/deny')+ .set('authorization', 'Bearer tok')+ .send({ toolCallId: 'tc-1' })+ .expect(200)++ expect(JSON.parse(res.text)).toEqual({ ok: true })+ expect(controlApiMock.requestHostWakeFromControlApi).toHaveBeenCalledWith('chatllm', 'tok')+ })+ })++ // ── §13.4 row 3 — GET /rpc/hosts/:hostRef/tasks/:taskId/result ──────────────+ // The other finite routes assert their plain-forward path in their own suites+ // (model-selection, approval-artifacts, sessions-passthrough). The task-result+ // route only had the wake path, so its active/ready row is proven here: even a+ // wake-capable token never touches the wake plane when the host is up.+ describe('§13.4 row 3 — task result forwards normally on an active host', () => {+ it('an active host forwards the task result and never touches the wake plane', async () => {- authTokenMock.verifyRpcToken.mockReturnValue(- claims(['host:message:invoke', 'host:wake:write'])- )++ authTokenMock.verifyRpcToken.mockReturnValue(claims(['host:message:invoke', 'host:wake:write']))+ serviceMock.forwardTaskResultFromHost.mockResolvedValue({+ status: 'completed',+ response: 'done',+ })++ const res = await request(makeApp())+ .get('/rpc/hosts/chatllm/tasks/t-7/result')+ .set('authorization', 'Bearer tok')+ .expect(200)++ expect(res.body).toEqual({ status: 'completed', response: 'done' })+ expect(serviceMock.forwardTaskResultFromHost).toHaveBeenCalledTimes(1)+ expect(controlApiMock.requestHostWakeFromControlApi).not.toHaveBeenCalled()+ })+ })++ // ── §13.4 row 2 — suspended host + NON-wake token ───────────────────────────+ // A finite operation whose token lacks host:wake:write must return today's+ // deterministic legacy availability result (502 Upstream host unavailable) and+ // NEVER consult the wake plane — no fallback grant is minted (§11.2, §13.4).+ // GET /models already asserts this cell above; the remaining finite routes are+ // proven here so every wake-eligible route has an explicit non-wake row.+ describe('§13.4 row 2 — NON-wake token gets the deterministic legacy result and triggers NO wake', () => {+ it('POST messages', async () => {+ authTokenMock.verifyRpcToken.mockReturnValue(claims(['host:message:invoke']))+ serviceMock.forwardHostMessageToHost.mockRejectedValue(hostDownError())++ const res = await request(makeApp())+ .post('/rpc/hosts/chatllm/messages')+ .set('authorization', 'Bearer tok')+ .send({ content: 'hello' })+ .expect(502)++ expect(res.body).toEqual({ error: 'Upstream host unavailable' })+ expect(controlApiMock.requestHostWakeFromControlApi).not.toHaveBeenCalled()+ })++ it('POST approvals/approve', async () => {+ authTokenMock.verifyRpcToken.mockReturnValue(claims(['host:approval:write']))+ globalThis.fetch = vi.fn().mockRejectedValue(hostDownError()) as unknown as typeof fetch++ const res = await request(makeApp())+ .post('/rpc/hosts/chatllm/approvals/approve')+ .set('authorization', 'Bearer tok')+ .send({ toolCallId: 'tc-1' })+ .expect(502)++ expect(res.body).toEqual({ error: 'Upstream host unavailable' })+ expect(controlApiMock.requestHostWakeFromControlApi).not.toHaveBeenCalled()+ })++ it('POST approvals/deny', async () => {+ authTokenMock.verifyRpcToken.mockReturnValue(claims(['host:approval:write']))+ globalThis.fetch = vi.fn().mockRejectedValue(hostDownError()) as unknown as typeof fetch++ const res = await request(makeApp())+ .post('/rpc/hosts/chatllm/approvals/deny')+ .set('authorization', 'Bearer tok')+ .send({ toolCallId: 'tc-1' })+ .expect(502)++ expect(res.body).toEqual({ error: 'Upstream host unavailable' })+ expect(controlApiMock.requestHostWakeFromControlApi).not.toHaveBeenCalled()+ })++ it('GET sessions', async () => {+ authTokenMock.verifyRpcToken.mockReturnValue(claims(['host:session:read']))+ globalThis.fetch = vi.fn().mockRejectedValue(hostDownError()) as unknown as typeof fetch++ const res = await request(makeApp())+ .get('/rpc/hosts/chatllm/sessions')+ .set('authorization', 'Bearer tok')+ .expect(502)++ expect(res.body).toEqual({ error: 'Upstream host unavailable' })+ expect(controlApiMock.requestHostWakeFromControlApi).not.toHaveBeenCalled()+ })++ it('GET sessions/:agent/:chatId/messages (transcript)', async () => {+ authTokenMock.verifyRpcToken.mockReturnValue(claims(['host:session:read']))+ globalThis.fetch = vi.fn().mockRejectedValue(hostDownError()) as unknown as typeof fetch++ const res = await request(makeApp())+ .get('/rpc/hosts/chatllm/sessions/chatllm/c1/messages')+ .set('authorization', 'Bearer tok')+ .expect(502)++ expect(res.body).toEqual({ error: 'Upstream host unavailable' })+ expect(controlApiMock.requestHostWakeFromControlApi).not.toHaveBeenCalled()+ })++ it('GET sessions/:agent/:chatId/context-breakdown', async () => {+ authTokenMock.verifyRpcToken.mockReturnValue(claims(['host:session:read']))+ globalThis.fetch = vi.fn().mockRejectedValue(hostDownError()) as unknown as typeof fetch++ const res = await request(makeApp())+ .get('/rpc/hosts/chatllm/sessions/chatllm/c1/context-breakdown')+ .set('authorization', 'Bearer tok')+ .expect(502)++ expect(res.body).toEqual({ error: 'Upstream host unavailable' })+ expect(controlApiMock.requestHostWakeFromControlApi).not.toHaveBeenCalled()+ })++ it('POST model', async () => {+ authTokenMock.verifyRpcToken.mockReturnValue(claims(['host:model:write']))+ globalThis.fetch = vi.fn().mockRejectedValue(hostDownError()) as unknown as typeof fetch++ const res = await request(makeApp())+ .post('/rpc/hosts/chatllm/model')+ .set('authorization', 'Bearer tok')+ .send({ chatId: 'c1', model: 'claude-haiku-4-5' })+ .expect(502)++ expect(res.body).toEqual({ error: 'Upstream host unavailable' })+ expect(controlApiMock.requestHostWakeFromControlApi).not.toHaveBeenCalled()+ })++ it('GET tasks/:taskId/result', async () => {+ authTokenMock.verifyRpcToken.mockReturnValue(claims(['host:message:invoke']))+ serviceMock.forwardTaskResultFromHost.mockRejectedValue(hostDownError())++ const res = await request(makeApp())+ .get('/rpc/hosts/chatllm/tasks/t-1/result')+ .set('authorization', 'Bearer tok')+ .expect(502)++ expect(res.body).toEqual({ error: 'Upstream host unavailable' })+ expect(controlApiMock.requestHostWakeFromControlApi).not.toHaveBeenCalled()+ })++ it('POST tasks/:taskId/cancel', async () => {+ authTokenMock.verifyRpcToken.mockReturnValue(claims(['host:message:invoke']))+ serviceMock.forwardCancelToHost.mockRejectedValue(hostDownError())++ const res = await request(makeApp())+ .post('/rpc/hosts/chatllm/tasks/t-1/cancel')+ .set('authorization', 'Bearer tok')+ .expect(502)++ expect(res.body).toEqual({ error: 'Upstream host unavailable' })+ expect(controlApiMock.requestHostWakeFromControlApi).not.toHaveBeenCalled()+ })++ it('GET artifacts', async () => {+ authTokenMock.verifyRpcToken.mockReturnValue(claims(['host:task:read']))+ globalThis.fetch = vi.fn().mockRejectedValue(hostDownError()) as unknown as typeof fetch++ const res = await request(makeApp())+ .get('/rpc/hosts/chatllm/artifacts')+ .set('authorization', 'Bearer tok')+ .expect(502)++ expect(res.body).toEqual({ error: 'Upstream host unavailable' })+ expect(controlApiMock.requestHostWakeFromControlApi).not.toHaveBeenCalled()+ })++ it('GET artifacts/:filename/download', async () => {+ authTokenMock.verifyRpcToken.mockReturnValue(claims(['host:task:read']))+ globalThis.fetch = vi.fn().mockRejectedValue(hostDownError()) as unknown as typeof fetch++ const res = await request(makeApp())+ .get('/rpc/hosts/chatllm/artifacts/report.pdf/download')+ .set('authorization', 'Bearer tok')+ .expect(502)++ expect(res.body).toEqual({ error: 'Upstream host unavailable' })+ expect(controlApiMock.requestHostWakeFromControlApi).not.toHaveBeenCalled()+ })+ })++ // ── §11.5 terminal-response (duplicate-write) safety ────────────────────────+ describe('§11.5 route outer-catch responders guard headersSent (one-shot settlement)', () => {+ type FakeRes = {+ headersSent: boolean+ statusCode: number+ body: unknown+ status: (code: number) => FakeRes+ json: (payload: unknown) => FakeRes+ }+ function makeRes(headersSent = false): FakeRes {+ const res: FakeRes = {+ headersSent,+ statusCode: 0,+ body: undefined,+ status(code: number) {+ res.statusCode = code+ return res+ },+ json(payload: unknown) {+ if (res.headersSent) throw new Error('Cannot set headers after they are sent to the client')+ res.headersSent = true+ res.body = payload+ return res+ },+ }+ return res+ }++ it('respondUpstreamUnavailable is a no-op once the response is committed', () => {+ const res = makeRes(true)+ expect(() =>+ respondUpstreamUnavailable(res as unknown as ExpressResponse, new Error('boom'))+ ).not.toThrow()+ expect(res.statusCode).toBe(0)+ })++ it('respondUpstreamUnavailable still writes 502 when the response is uncommitted', () => {+ const res = makeRes(false)+ respondUpstreamUnavailable(res as unknown as ExpressResponse, new Error('boom'))+ expect(res.statusCode).toBe(502)+ expect(res.body).toEqual({ error: 'Upstream host unavailable' })+ })++ it('respondControlApiHostAccessRejection is a no-op once the response is committed', () => {+ const res = makeRes(true)+ expect(() =>+ respondControlApiHostAccessRejection(res as unknown as ExpressResponse, 403)+ ).not.toThrow()+ expect(res.statusCode).toBe(0)+ })+ })diff --cc rpc-proxy/src/routes/rpc.tsindex afbf6f802,e06ad0f9a..5f73f9836--- a/rpc-proxy/src/routes/rpc.ts+++ b/rpc-proxy/src/routes/rpc.ts@@@ -1,5 -1,5 +1,5 @@@import { Router } from 'express'- import type { Response as ExpressResponse } from 'express'-import type { NextFunction, Response as ExpressResponse } from 'express'++import type { Response as ExpressResponse, NextFunction } from 'express'import { randomUUID } from 'crypto'import { config } from '../config.js'import {@@@ -546,23 -643,45 +643,51 @@@ export function createRpcRouter(): Rout}const baseUrl = host.url.replace(/\/+$/, '')console.info(`[RPC_PROXY] user=${auth.sub} host=${hostRef} method=list-sessions`)+ const upstreamUrl = new URL(`${baseUrl}/v1/runtime/sessions`)+ for (const key of ['limit', 'cursor'] as const) {+ if (typeof req.query[key] === 'string') {+ upstreamUrl.searchParams.set(key, req.query[key])+ }+ }- const response = await fetch(upstreamUrl, {- method: 'GET',- headers: { ...host.headers },- })- const body = await response.text()- res- .status(response.status)- .type(response.headers.get('content-type') || 'application/json')- .send(body)+ // Wake-eligible finite operation (§11.4): the route scope stays+ // host:session:read; wake capability rides on the token. A suspended+ // (network-down) or draining Host triggers a wake-and-hold instead of a+ // bare next(error)/passthrough.+ const forwardSessionList = async () => {- const response = await fetch(`${baseUrl}/v1/runtime/sessions`, {++ const response = await fetch(upstreamUrl, {+ method: 'GET',+ headers: { ...host.headers },+ })+ const body = await response.text()+ const draining = sessionDrainingFence(response, body)+ if (draining) throw draining+ res+ .status(response.status)+ .type(response.headers.get('content-type') || 'application/json')+ .send(body)+ }+ try {+ await forwardSessionList()+ } catch (error) {+ // A sanitized session boundary can also wrap local response-body+ // failures. Wake only when its retained cause proves the host is+ // unavailable, or when the host explicitly returned the draining+ // fence; otherwise preserve the ordinary sanitized error path.+ if (!isWakeEligibleHostError(error)) {+ throw error+ }+ await respondWithWakeAndHold({+ res,+ hostRef,+ host,+ claims: auth,+ rpcAccessToken,+ attemptUpstream: forwardSessionList,+ respondLegacy: legacyError => respondUpstreamUnavailable(res, legacyError),+ })+ }} catch (error) {- next(error)+ guardedNext(res, next, error)}})@@@ -594,25 -713,40 +719,48 @@@console.info(`[RPC_PROXY] user=${auth.sub} host=${hostRef} method=get-session-messages agent=${agent} chatId=${chatId}`)+ const upstreamUrl = new URL(+ `${baseUrl}/v1/runtime/sessions/${encodeURIComponent(agent)}/${encodeURIComponent(chatId)}/messages`+ )+ for (const key of ['limit', 'beforeTurn', 'afterTurn'] as const) {+ if (typeof req.query[key] === 'string') {+ upstreamUrl.searchParams.set(key, req.query[key])+ }+ }- const response = await fetch(upstreamUrl, {- method: 'GET',- headers: { ...host.headers },- })- const body = await response.text()- res- .status(response.status)- .type(response.headers.get('content-type') || 'application/json')- .send(body)+ // Wake-eligible finite operation (§11.4): scope stays host:session:read.+ const forwardTranscript = async () => {- const response = await fetch(- `${baseUrl}/v1/runtime/sessions/${encodeURIComponent(agent)}/${encodeURIComponent(chatId)}/messages`,- { method: 'GET', headers: { ...host.headers } }- )++ const response = await fetch(upstreamUrl, {++ method: 'GET',++ headers: { ...host.headers },++ })+ const body = await response.text()+ const draining = sessionDrainingFence(response, body)+ if (draining) throw draining+ res+ .status(response.status)+ .type(response.headers.get('content-type') || 'application/json')+ .send(body)+ }+ try {+ await forwardTranscript()+ } catch (error) {+ // See the list route above: availability recovery is deliberately+ // narrower than the generic sanitized upstream-error boundary.+ if (!isWakeEligibleHostError(error)) {+ throw error+ }+ await respondWithWakeAndHold({+ res,+ hostRef,+ host,+ claims: auth,+ rpcAccessToken,+ attemptUpstream: forwardTranscript,+ respondLegacy: legacyError => respondUpstreamUnavailable(res, legacyError),+ })+ }} catch (error) {- next(error)+ guardedNext(res, next, error)}})diff --cc rpc-proxy/src/services/__tests__/probeHostHealth.test.tsindex 000000000,07b34521b..7efd0f186mode 000000,100644..100644--- a/rpc-proxy/src/services/__tests__/probeHostHealth.test.ts+++ b/rpc-proxy/src/services/__tests__/probeHostHealth.test.ts@@@ -1,0 -1,74 +1,73 @@@+ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'+ import type { ResolvedServerConnection } from '../../types.js'++// vi.mock is hoisted above imports, so the static import resolves the mock.++import { probeHostReadyViaHealth } from '../wakeAndHold.js'++ // The wake-and-hold readiness probe must use mcp-host's UNAUTHENTICATED+ // /v1/runtime/health endpoint (Issue #791 §11.3), which comes up before MCP+ // background init and is the same signal the Pod readiness probe uses — not+ // /v1/runtime/status (edge-guarded). We mock the REST module so the probe's+ // dependency is observable.+ const restMock = vi.hoisted(() => ({+ forwardHostHealth: vi.fn(),+ forwardHostStatus: vi.fn(),+ }))++ vi.mock('../mcpHostRestService.js', () => restMock)+-// vi.mock is hoisted above imports, so the static import resolves the mock.-import { probeHostReadyViaHealth } from '../wakeAndHold.js'-+ const HOST: ResolvedServerConnection = {+ name: 'chatllm',+ url: 'http://chatllm.mcp-host.svc.cluster.local:8080',+ headers: {},+ }++ beforeEach(() => {+ restMock.forwardHostHealth.mockReset()+ restMock.forwardHostStatus.mockReset()+ })++ afterEach(() => {+ vi.restoreAllMocks()+ })++ describe('probeHostReadyViaHealth', () => {+ it('probes /v1/runtime/health (not /v1/runtime/status) and returns true on a healthy answer', async () => {+ restMock.forwardHostHealth.mockResolvedValue({+ hostRef: 'chatllm',+ status: 'ok',+ observedAt: new Date().toISOString(),+ })++ const ready = await probeHostReadyViaHealth(HOST)++ expect(ready).toBe(true)+ expect(restMock.forwardHostHealth).toHaveBeenCalledTimes(1)+ expect(restMock.forwardHostHealth).toHaveBeenCalledWith(HOST)+ expect(restMock.forwardHostStatus).not.toHaveBeenCalled()+ })++ it('returns false when the health endpoint times out (AbortError)', async () => {+ const abort = new Error('The operation was aborted')+ abort.name = 'AbortError'+ restMock.forwardHostHealth.mockRejectedValue(abort)++ expect(await probeHostReadyViaHealth(HOST)).toBe(false)+ })++ it('returns false when the connection is refused (pod still suspended)', async () => {+ restMock.forwardHostHealth.mockRejectedValue(new TypeError('fetch failed'))++ expect(await probeHostReadyViaHealth(HOST)).toBe(false)+ })++ it('returns false when the health endpoint answers non-2xx (throws UpstreamHostError)', async () => {+ const upstream = Object.assign(new Error('Upstream host returned 503'), {+ name: 'UpstreamHostError',+ status: 503,+ bodySnippet: '',+ })+ restMock.forwardHostHealth.mockRejectedValue(upstream)++ expect(await probeHostReadyViaHealth(HOST)).toBe(false)+ })+ })diff --cc rpc-proxy/src/services/__tests__/wakeCoordinator.principal.test.tsindex 000000000,3ad2db1d7..03329a2bemode 000000,100644..100644--- a/rpc-proxy/src/services/__tests__/wakeCoordinator.principal.test.ts+++ b/rpc-proxy/src/services/__tests__/wakeCoordinator.principal.test.ts@@@ -1,0 -1,347 +1,351 @@@+ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'+ import type { ResolvedServerConnection, RpcAccessClaims, RpcScope } from '../../types.js'+ import {+ WakeAndHoldCoordinator,+ type WakeCoordinatorDeps,+ wakeCoordinationKey,+ } from '../wakeAndHold.js'++ // ── Issue #791 §11.1/§11.2/§13.3/§13.4 — principal-scoped wake coordination ──+ //+ // The old coordinator grouped by hostRef and picked the "latest by expiry"+ // authorization with NO principal/scope check. This suite pins the corrected+ // contract: coordination is keyed by principal + Host, only a same-principal+ // wake-capable authorization may occupy/replace the wake slot, non-wake tokens+ // never trigger a wake nor displace the wake authorization, and different+ // principals never share a group.++ const MAX_HOLD_MS = 90_000+ const POLL_MS = 2_000+ const RETRIGGER_MS = 15_000++ function conn(name = 'chatllm', url?: string): ResolvedServerConnection {+ return { name, url: url ?? `http://${name}:8080`, headers: {} }+ }++ function makeClaims(+ overrides: Partial<Omit<RpcAccessClaims, 'exp'>> & { expMs?: number } = {}+ ): RpcAccessClaims {+ const expMs = overrides.expMs ?? Date.now() + 3_600_000+ return {+ sub: overrides.sub ?? 'user-a',+ typ: overrides.typ ?? 'user',+ accessScope: overrides.accessScope ?? 'user',+ teamId: overrides.teamId ?? null,+ scopes: overrides.scopes ?? (['host:wake:write', 'host:message:invoke'] as RpcScope[]),+ hostRefs: overrides.hostRefs ?? ['chatllm'],+ jti: overrides.jti ?? 'jti-1',+ iat: 1,+ exp: Math.floor(expMs / 1000),+ }+ }++ function makeCoordinator(overrides?: Partial<WakeCoordinatorDeps>): {+ coordinator: WakeAndHoldCoordinator+ requestWake: ReturnType<typeof vi.fn>+ probeReady: ReturnType<typeof vi.fn>+ } {+ const requestWake = vi.fn().mockResolvedValue({ kind: 'wake-requested', wakeGeneration: 1 })+ const probeReady = vi.fn().mockResolvedValue(false)+ const coordinator = new WakeAndHoldCoordinator({+ requestWake,+ probeReady,+ maxHoldMs: MAX_HOLD_MS,+ pollMs: POLL_MS,+ retriggerMs: RETRIGGER_MS,+ maxTrackedCoordinations: 1_000,+ ...overrides,+ })+ return { coordinator, requestWake, probeReady }+ }++ function hold(+ coordinator: WakeAndHoldCoordinator,+ claims: RpcAccessClaims,+ token: string,+ host: ResolvedServerConnection = conn(),+ hostRef = 'chatllm'+ ) {+ return coordinator.hold({ hostRef, host, claims, rpcAccessToken: token })+ }++ let warnSpy: ReturnType<typeof vi.spyOn>+ let debugSpy: ReturnType<typeof vi.spyOn>+ let infoSpy: ReturnType<typeof vi.spyOn>++ beforeEach(() => {+ vi.useFakeTimers()+ warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {})+ debugSpy = vi.spyOn(console, 'debug').mockImplementation(() => {})+ infoSpy = vi.spyOn(console, 'info').mockImplementation(() => {})+ })++ afterEach(() => {+ expect(vi.getTimerCount()).toBe(0) // no dangling timers, ever+ vi.useRealTimers()+ warnSpy.mockRestore()+ debugSpy.mockRestore()+ infoSpy.mockRestore()+ })++ describe('wakeCoordinationKey', () => {+ it('excludes jti/exp/role/scopes and is stable across token rotation for one principal', () => {+ const a = makeClaims({ jti: 'j1', expMs: Date.now() + 1_000_000, scopes: ['host:wake:write'] })- const b = makeClaims({ jti: 'j2', expMs: Date.now() + 9_000_000, scopes: ['host:session:read'] })++ const b = makeClaims({++ jti: 'j2',++ expMs: Date.now() + 9_000_000,++ scopes: ['host:session:read'],++ })+ expect(wakeCoordinationKey(a, 'chatllm')).toBe(wakeCoordinationKey(b, 'chatllm'))+ })++ it('separates user, team, and service principals and never contains bearer material', () => {+ const user = makeClaims({ typ: 'user', accessScope: 'user', teamId: null, sub: 'u1' })+ const team = makeClaims({ typ: 'user', accessScope: 'team', teamId: 't1', sub: 'u1' })+ const service = makeClaims({ typ: 'service', accessScope: 'service', teamId: 't1', sub: 'svc' })+ const keys = [+ wakeCoordinationKey(user, 'chatllm'),+ wakeCoordinationKey(team, 'chatllm'),+ wakeCoordinationKey(service, 'chatllm'),+ ]+ expect(new Set(keys).size).toBe(3)+ for (const key of keys) expect(key).not.toContain('bearer')+ })+ })++ describe('§13.3 wake coordination matrix', () => {+ it('row 1: wake-capable A + non-wake A (later expiry) → retain A wake auth; add waiter only', async () => {+ const { coordinator, requestWake, probeReady } = makeCoordinator()+ const a = makeClaims({ scopes: ['host:wake:write', 'host:session:read'] })+ const pA = hold(coordinator, a, 'tok-wake')+ expect(requestWake).toHaveBeenCalledTimes(1)+ expect(requestWake).toHaveBeenCalledWith('chatllm', 'tok-wake')++ const nonWakeLater = makeClaims({+ scopes: ['host:session:read'],+ expMs: Date.now() + 7_200_000,+ })+ const pB = hold(coordinator, nonWakeLater, 'tok-nonwake')++ expect(coordinator.trackedCoordinationCount()).toBe(1) // same principal group+ expect(requestWake).toHaveBeenCalledTimes(1) // the non-wake waiter triggered NO new wake+ expect(requestWake).not.toHaveBeenCalledWith('chatllm', 'tok-nonwake')++ probeReady.mockResolvedValue(true)+ await vi.advanceTimersByTimeAsync(POLL_MS)+ const [oA, oB] = await Promise.all([pA, pB])+ expect(oA.kind).toBe('proceed')+ expect(oB.kind).toBe('proceed')+ })++ it('row 2: wake-capable A + fresher wake-capable A → replace wake authorization + connection', async () => {+ const { coordinator, requestWake, probeReady } = makeCoordinator()+ const a = makeClaims({ expMs: Date.now() + 1_000_000 })+ const pA = hold(coordinator, a, 'tok-a', conn('chatllm', 'http://chatllm-old:8080'))++ const fresher = makeClaims({ expMs: Date.now() + 2_000_000 })+ const freshHost = conn('chatllm', 'http://chatllm-fresh:8080')+ const pA2 = hold(coordinator, fresher, 'tok-a2', freshHost)++ // Readiness probe now uses the fresher connection.+ await vi.advanceTimersByTimeAsync(POLL_MS)+ expect(probeReady).toHaveBeenCalledWith(freshHost)+ // The next wake retrigger uses the fresher wake token.+ await vi.advanceTimersByTimeAsync(RETRIGGER_MS)+ expect(requestWake).toHaveBeenCalledWith('chatllm', 'tok-a2')++ coordinator.drain()+ await Promise.all([pA, pA2])+ })++ it('row 3: user A / team 1 vs user A / team 2 → separate groups', async () => {+ const { coordinator, requestWake } = makeCoordinator()+ const t1 = makeClaims({ accessScope: 'team', teamId: 'team-1' })+ const t2 = makeClaims({ accessScope: 'team', teamId: 'team-2' })+ const p1 = hold(coordinator, t1, 'tok-t1')+ const p2 = hold(coordinator, t2, 'tok-t2')+ expect(coordinator.trackedCoordinationCount()).toBe(2)+ expect(requestWake).toHaveBeenCalledTimes(2)+ coordinator.drain()+ await Promise.all([p1, p2])+ })++ it('row 4: user A vs user B → separate groups', async () => {+ const { coordinator, requestWake } = makeCoordinator()+ const a = makeClaims({ sub: 'user-a' })+ const b = makeClaims({ sub: 'user-b' })+ const pa = hold(coordinator, a, 'tok-a')+ const pb = hold(coordinator, b, 'tok-b')+ expect(coordinator.trackedCoordinationCount()).toBe(2)+ expect(requestWake).toHaveBeenCalledTimes(2)+ coordinator.drain()+ await Promise.all([pa, pb])+ })++ it('row 5: no wake authorization + non-wake authorization → no unauthorized wake attempt', async () => {+ const { coordinator, requestWake } = makeCoordinator()+ const nonWake = makeClaims({ scopes: ['host:session:read'] })+ const outcome = await hold(coordinator, nonWake, 'tok-nonwake')+ expect(outcome.kind).toBe('legacy')+ expect(requestWake).not.toHaveBeenCalled()+ expect(coordinator.trackedCoordinationCount()).toBe(0)+ })++ it('key is delimiter-safe: boundary-shifting identifiers cannot collide two principals', () => {+ const p1 = makeClaims({ sub: 'a|team', accessScope: 'team', teamId: 'x' })+ const p2 = makeClaims({ sub: 'a', accessScope: 'team', teamId: 'team|x' })+ expect(wakeCoordinationKey(p1, 'chatllm')).not.toBe(wakeCoordinationKey(p2, 'chatllm'))+ })++ it('drain() is a terminal fence: a hold arriving after drain settles immediately and parks nothing', async () => {+ const { coordinator, requestWake } = makeCoordinator()+ coordinator.drain('shutdown')+ const outcome = await hold(coordinator, makeClaims(), 'tok-after-drain')+ expect(outcome).toEqual({+ kind: 'waking',+ retryAfterMs: POLL_MS,+ reason: 'shutting-down',+ lastKnownState: 'unknown',+ })+ expect(requestWake).not.toHaveBeenCalled()+ expect(coordinator.trackedCoordinationCount()).toBe(0)+ })++ it('row 6: expired wake authorization + non-wake waiter → deterministic terminal, no wake', async () => {+ const { coordinator, requestWake } = makeCoordinator()+ // Wake-capable token with a short budget (~2s) creates the group.+ const shortWake = makeClaims({+ scopes: ['host:wake:write', 'host:session:read'],+ expMs: Date.now() + 4_000,+ })+ const pShort = hold(coordinator, shortWake, 'tok-short')+ // A long-lived non-wake waiter keeps the entry alive after the wake token dies.+ const longNonWake = makeClaims({ scopes: ['host:session:read'], expMs: Date.now() + 3_600_000 })+ const pLong = hold(coordinator, longNonWake, 'tok-long')++ await vi.advanceTimersByTimeAsync(2_000) // short wake token budget expires+ expect((await pShort).kind).toBe('waking')+ expect(coordinator.trackedCoordinationCount()).toBe(1) // entry persists for the long waiter++ await vi.advanceTimersByTimeAsync(2_000) // now past the wake token's exp+ const late = makeClaims({ scopes: ['host:session:read'], expMs: Date.now() + 3_600_000 })+ const oLate = await hold(coordinator, late, 'tok-late')+ expect(oLate.kind).toBe('legacy')+ expect(requestWake).not.toHaveBeenCalledWith('chatllm', 'tok-late')++ coordinator.drain()+ await pLong+ })++ it('row 7: wake succeeds, health pending, several same-principal waiters → one wake, each proceeds', async () => {+ const { coordinator, requestWake, probeReady } = makeCoordinator()+ const a = makeClaims()+ const pendings = [+ hold(coordinator, a, 'tok-1'),+ hold(coordinator, a, 'tok-2'),+ hold(coordinator, a, 'tok-3'),+ ]+ expect(coordinator.trackedCoordinationCount()).toBe(1)+ expect(requestWake).toHaveBeenCalledTimes(1) // one wake sequence for the principal group++ probeReady.mockResolvedValue(true)+ await vi.advanceTimersByTimeAsync(POLL_MS)+ for (const outcome of await Promise.all(pendings)) {+ expect(outcome.kind).toBe('proceed')+ }+ expect(coordinator.trackedCoordinationCount()).toBe(0)+ })++ it('row 8: waiter settles, a later probe failure does not re-settle', async () => {+ const { coordinator, requestWake, probeReady } = makeCoordinator()+ void requestWake+ probeReady.mockResolvedValueOnce(true) // first probe: ready → settle proceed+ const pending = hold(coordinator, makeClaims(), 'tok-1')+ await vi.advanceTimersByTimeAsync(POLL_MS)+ expect((await pending).kind).toBe('proceed')+ expect(coordinator.trackedCoordinationCount()).toBe(0)++ // Advancing past every window makes NO further probe/settle — group is gone.+ const probeCalls = probeReady.mock.calls.length+ await vi.advanceTimersByTimeAsync(MAX_HOLD_MS * 2)+ expect(probeReady.mock.calls.length).toBe(probeCalls)+ expect(coordinator.trackedCoordinationCount()).toBe(0)+ })+ })++ describe('§13.4 operation outcomes (unit level)', () => {+ it('active runtime → proceed immediately, no hold loop', async () => {+ const { coordinator, requestWake, probeReady } = makeCoordinator()+ requestWake.mockResolvedValue({ kind: 'active', wakeGeneration: null })+ const outcome = await hold(coordinator, makeClaims(), 'tok')+ expect(outcome).toEqual({ kind: 'proceed', lastKnownState: 'active' })+ expect(probeReady).not.toHaveBeenCalled()+ })++ it('stateful unavailable (not-stateless) → legacy, never a stateless wake hold', async () => {+ const { coordinator, requestWake } = makeCoordinator()+ requestWake.mockResolvedValue({ kind: 'not-stateless' })+ const outcome = await hold(coordinator, makeClaims(), 'tok')+ expect(outcome).toEqual({ kind: 'legacy', reason: 'not-stateless' })+ expect(coordinator.trackedCoordinationCount()).toBe(0)+ })++ it('suspended + no wake grant → no fallback grant; deterministic legacy result', async () => {+ const { coordinator, requestWake } = makeCoordinator()+ const outcome = await hold(coordinator, makeClaims({ scopes: ['host:session:read'] }), 'tok')+ expect(outcome.kind).toBe('legacy')+ expect(requestWake).not.toHaveBeenCalled()+ })+ })++ describe('a mid-hold wake auth rejection distinguishes initial from retrigger', () => {+ it('an initial wake 403 settles the group legacy', async () => {+ const { coordinator, requestWake } = makeCoordinator()+ requestWake.mockResolvedValue({ kind: 'auth', status: 403 })+ const outcome = await hold(coordinator, makeClaims(), 'tok')+ expect(outcome).toEqual({ kind: 'legacy', reason: 'wake-auth-403' })+ expect(coordinator.trackedCoordinationCount()).toBe(0)+ })++ it('a retrigger wake 403 does NOT collapse still-valid waiters (initial guard)', async () => {+ const { coordinator, requestWake, probeReady } = makeCoordinator()+ requestWake+ .mockResolvedValueOnce({ kind: 'wake-requested', wakeGeneration: 1 })+ .mockResolvedValue({ kind: 'auth', status: 403 }) // retrigger rejected+ probeReady.mockResolvedValue(false)++ const pending = hold(coordinator, makeClaims(), 'tok')+ await vi.advanceTimersByTimeAsync(RETRIGGER_MS) // fire one retrigger (auth 403)+ // The group is still held (bounded by deadlines), not collapsed to legacy.+ expect(coordinator.trackedCoordinationCount()).toBe(1)++ await vi.advanceTimersByTimeAsync(MAX_HOLD_MS)+ const outcome = await pending+ expect(outcome).toMatchObject({ kind: 'waking' })+ expect(coordinator.trackedCoordinationCount()).toBe(0)+ })+ })++ describe('shutdown drain', () => {+ it('settles every parked waiter deterministically and leaves no dangling timers', async () => {+ const { coordinator, requestWake, probeReady } = makeCoordinator()+ void requestWake+ void probeReady+ const a = hold(coordinator, makeClaims({ sub: 'user-a' }), 'tok-a', conn('chatllm'), 'chatllm')+ const b = hold(+ coordinator,+ makeClaims({ sub: 'user-b', hostRefs: ['other'] }),+ 'tok-b',+ conn('other'),+ 'other'+ )+ expect(coordinator.trackedCoordinationCount()).toBe(2)++ coordinator.drain()++ const [oa, ob] = await Promise.all([a, b])+ expect(oa.kind).toBe('waking')+ expect(ob.kind).toBe('waking')+ expect(coordinator.trackedCoordinationCount()).toBe(0)+ })+ })diff --cc rpc-proxy/src/services/wakeAndHold.tsindex 2a8d12c92,a60c3a9d1..a8b769594--- a/rpc-proxy/src/services/wakeAndHold.ts+++ b/rpc-proxy/src/services/wakeAndHold.ts@@@ -115,7 -217,10 +217,15 @@@ export class WakeAndHoldCoordinatorconst activeEntry = entryreturn await new Promise<WakeHoldOutcome>(resolve => {const id = ++this.waiterSeq- const timer = setTimeout(() => {- const waiter: Waiter = { id, resolve, timer: null as unknown as NodeJS.Timeout, settled: false }++ const waiter: Waiter = {++ id,++ resolve,++ timer: null as unknown as NodeJS.Timeout,++ settled: false,++ }+ waiter.timer = setTimeout(() => {+ if (waiter.settled) return+ waiter.settled = trueactiveEntry.waiters.delete(id)resolve({kind: 'waking',