Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure
TypeScript
feat(control-api): add admin attention feed of stale-but-referenced models (Pieza C)
Diego Zacarias8578a51da1db
diff --git a/control-api/package-lock.json b/control-api/package-lock.jsonindex 31b8ca7a5..9b40bbd85 100644--- a/control-api/package-lock.json+++ b/control-api/package-lock.json@@ -1,12 +1,12 @@{"name": "clerum-control-api",- "version": "0.1.436",+ "version": "0.1.437","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "clerum-control-api",- "version": "0.1.436",+ "version": "0.1.437","dependencies": {"@clerum/image-policy": "file:../packages/image-policy","@clerum/llm-providers": "file:../packages/llm-providers",diff --git a/control-api/package.json b/control-api/package.jsonindex c73ab25e9..513de4d55 100644--- a/control-api/package.json+++ b/control-api/package.json@@ -1,6 +1,6 @@{"name": "clerum-control-api",- "version": "0.1.436",+ "version": "0.1.437","description": "Internal Clerum control plane REST API + UI for managing CRDs and secrets","main": "dist/main.js","engines": {diff --git a/control-api/src/routes/admin/llmModels.ts b/control-api/src/routes/admin/llmModels.tsindex 3aebea4e1..b6c536c2d 100644--- a/control-api/src/routes/admin/llmModels.ts+++ b/control-api/src/routes/admin/llmModels.ts@@ -12,9 +12,11 @@ import {deleteAllowedModel,getAllowedModel,listAllowedModels,+ listStaleAllowedModels,updateAllowedModel,updateLlmAllowedModelSchema,} from '../../services/llmAllowedModels.js'+import { computeAttention } from '../../services/llmAttention.js'import { getLastCatalogSyncRun, syncDiscoveredModels } from '../../services/llmCatalogSync.js'import {computeModelImpact,@@ -127,6 +129,25 @@ export function createAdminLlmModelsRouter(gateway: K8sGateway): Router {return true}+ // ── Operator attention feed (Fase 5, Pieza C) ───────────────────────────────+ // Persistent alert backing the non-destructive Fase 4 cron: every `stale`+ // catalog model that is STILL referenced by a Host/grant, so the operator can+ // disable it through the impact-gated PUT. Only actionable items (referenced)+ // appear; an unreferenced stale model yields nothing. Reuses `impactSources`+ // (the same fail-loud enumeration the `?force` gate uses, regla D4): if any+ // Host LIST fails, `computeAttention` propagates → asyncHandler → 500, never a+ // partial feed that hides a live reference. Inherits the `/admin/*` control-ui+ // admin auth gate (app.ts) — no new auth. Extensible: `items[].kind` is an+ // open union with one member today (`stale_model_referenced`).+ router.get(+ '/admin/attention',+ asyncHandler(async (_req: Request, res: Response) => {+ const staleModels = await listStaleAllowedModels()+ const report = await computeAttention(staleModels, impactSources)+ res.status(200).json(report)+ })+ )+// ── Discovery (F2, spec 09 §2 + §8-F2) ──────────────────────────────────────// On-demand catalog sync from the public models.dev catalog into// `llm_allowed_models` as disabled `source='discovery'` rows for operatordiff --git a/control-api/src/services/llmAllowedModels.ts b/control-api/src/services/llmAllowedModels.tsindex c803dce7d..0269ab385 100644--- a/control-api/src/services/llmAllowedModels.ts+++ b/control-api/src/services/llmAllowedModels.ts@@ -215,6 +215,22 @@ export async function listAllowedModels(db: DbClient = pool): Promise<LlmAllowedreturn (result.rows as Record<string, unknown>[]).map(rowToModel)}+/**+ * Stale rows only — models the Fase 4 sync flagged as vanished from the external+ * catalog (`stale=true`) but left `enabled` intact. The operator-attention feed+ * (Fase 5) enumerates these and reports the ones still referenced. Deterministic+ * ordering keeps the feed stable across calls.+ */+export async function listStaleAllowedModels(db: DbClient = pool): Promise<LlmAllowedModel[]> {+ const result = await db.query(+ `SELECT ${MODEL_COLUMNS}+ FROM llm_allowed_models+ WHERE stale+ ORDER BY provider ASC, model ASC`+ )+ return (result.rows as Record<string, unknown>[]).map(rowToModel)+}+export async function getAllowedModel(id: string,db: DbClient = pooldiff --git a/control-api/src/services/llmAttention.ts b/control-api/src/services/llmAttention.tsnew file mode 100644index 000000000..95a8648b1--- /dev/null+++ b/control-api/src/services/llmAttention.ts@@ -0,0 +1,132 @@+/**+ * Operator-attention feed (spec Fase 5, Pieza C — `GET /admin/attention`).+ *+ * The Fase 4 catalog-sync cron marks models `stale=true` when they vanish from+ * the external catalog WITHOUT disabling them (`enabled` stays intact → they+ * remain in the runtime allowlist ConfigMap and keep working). That+ * non-destructive default is only safe if the operator is told to act. This+ * module produces that persistent alert: the set of ACTIONABLE attention items.+ *+ * TODAY there is exactly one item kind — a `stale` model that is STILL+ * referenced by some Host/grant, so the operator must decide to disable it+ * (through the Fase 3 impact-gated PUT). A `stale` model that nobody references+ * is NOT actionable and produces NO item.+ *+ * The `kind` discriminator is an OPEN string union on purpose: future phases add+ * item kinds (e.g. a re-appeared model, a pricing gap) without breaking the+ * frontend, which switches on `kind`.+ *+ * REFERENCE LOGIC IS NOT RECONSTRUCTED HERE (regla D4). The "who references+ * (provider, model)" enumeration is `computeModelImpact` (Fase 3,+ * `llmModelImpact.ts`) verbatim — the SAME module the `?force` write-gate uses.+ * This module only enumerates the stale set and calls it once per stale model.+ *+ * FAIL-LOUD (coherent with the Fase 3 safety gate). `computeModelImpact` rejects+ * if any Host LIST fails, and this module does NOT catch: a partial feed that+ * silently drops a referenced-model warning is exactly the under-report the+ * whole phase exists to prevent, so the endpoint answers 500 rather than a+ * truncated list. One un-verifiable model tumbles the whole endpoint.+ *+ * COST. `computeModelImpact` is invoked once per stale model; each call is+ * O(#hostNamespaces) K8s LISTs + one grant query. To keep the K8s cost flat as+ * the stale set grows, the Host LISTs are MEMOIZED per namespace across the loop+ * (`memoizeHostLists`): the apiserver is hit once per namespace for the whole+ * request instead of once per (stale model × namespace). Grant queries stay+ * per-model (O(#stale) Postgres reads) — a batched query would be a new SQL+ * surface, and grants are the cheap side. The memoization preserves fail-loud:+ * a rejected LIST promise is cached and re-thrown on the next await, so the loop+ * still aborts on the first namespace that fails.+ */+import {+ type GrantModelReference,+ type HostModelReference,+ type ModelImpactSources,+ computeModelImpact,+ modelImpactHasReferences,+} from './llmModelImpact.js'++/** The only attention kind today; the union is open for future kinds. */+export const ATTENTION_KIND_STALE_MODEL_REFERENCED = 'stale_model_referenced'++/**+ * A `stale` catalog model that is still referenced by a live Host/grant — the+ * operator must disable it (impact-gated PUT) to converge. Carries the same+ * `hostsAffected`/`grantsAffected` shape the Fase 3 impact body uses, so the+ * frontend renders both surfaces identically.+ */+export interface StaleModelReferencedItem {+ kind: typeof ATTENTION_KIND_STALE_MODEL_REFERENCED+ provider: string+ model: string+ displayName?: string+ hostsAffected: HostModelReference[]+ grantsAffected: GrantModelReference[]+}++/** Extensible union — one member today, more kinds in later phases. */+export type AttentionItem = StaleModelReferencedItem++/** The `GET /admin/attention` response contract consumed by the UI banner. */+export interface AttentionReport {+ items: AttentionItem[]+ /** ISO-8601 instant the feed was computed (for a "as of" label in the UI). */+ generatedAt: string+}++/** Minimal stale-model shape this module needs (subset of `LlmAllowedModel`). */+export interface StaleModelInput {+ provider: string+ model: string+ display_name: string | null+}++/**+ * Wrap `sources` so each namespace's Host LIST runs at most once per request.+ * Caches the PROMISE (not the resolved array) so a rejection is memoized too and+ * still propagates on every await — the fail-loud guarantee is preserved.+ */+function memoizeHostLists(sources: ModelImpactSources): ModelImpactSources {+ const hostListByNamespace = new Map<string, Promise<unknown[]>>()+ return {+ hostNamespaces: sources.hostNamespaces,+ listHostsInNamespace: namespace => {+ let cached = hostListByNamespace.get(namespace)+ if (!cached) {+ cached = sources.listHostsInNamespace(namespace)+ hostListByNamespace.set(namespace, cached)+ }+ return cached+ },+ listGrantsForModel: sources.listGrantsForModel,+ }+}++/**+ * Build the attention feed from the stale set. Enumerates each stale model's+ * live references via `computeModelImpact` (regla D4 — no reconstruction) and+ * emits an item ONLY when there is at least one reference (actionable). Lets any+ * LIST rejection propagate (fail-loud → the route answers 500).+ */+export async function computeAttention(+ staleModels: StaleModelInput[],+ sources: ModelImpactSources+): Promise<AttentionReport> {+ const memoizedSources = memoizeHostLists(sources)+ const items: AttentionItem[] = []+ for (const staleModel of staleModels) {+ const impact = await computeModelImpact(staleModel.provider, staleModel.model, memoizedSources)+ if (!modelImpactHasReferences(impact)) continue+ const item: StaleModelReferencedItem = {+ kind: ATTENTION_KIND_STALE_MODEL_REFERENCED,+ provider: impact.provider,+ model: impact.model,+ hostsAffected: impact.hostsAffected,+ grantsAffected: impact.grantsAffected,+ }+ // display_name is nullable in the catalog; only surface it when present so+ // the UI can fall back to the raw model id without a null check.+ if (staleModel.display_name) item.displayName = staleModel.display_name+ items.push(item)+ }+ return { items, generatedAt: new Date().toISOString() }+}diff --git a/control-api/test/routes.adminAttention.test.ts b/control-api/test/routes.adminAttention.test.tsnew file mode 100644index 000000000..4044e1526--- /dev/null+++ b/control-api/test/routes.adminAttention.test.ts@@ -0,0 +1,311 @@+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'+import request from 'supertest'+import { createApp } from '../src/app.js'+import { config } from '../src/config.js'+import { MockGateway } from './mockGateway.js'++// ── Fase 5, Pieza C: GET /admin/attention. OBSERVABLE-contract tests (T4): they+// assert the HTTP BODY the frontend banner consumes (the attention items + their+// impact), never an internal helper. Host references are produced by the REAL+// gateway producer (`createResource` → per-namespace `listResource`, T1); grant+// references flow through the REAL `mapGrantRow` inside `listGrantsReferencingModel`+// (T1) — never hand-built DTOs. The stale set comes from the REAL `rowToModel`+// mapper via `listStaleAllowedModels` (raw DB rows shaped to the migration).++const mockPoolQuery = vi.fn()+const mockVerifyAdminToken = vi.fn()+const mockIsAdminTokenRevoked = vi.fn()+const mockFindAdminById = vi.fn()++vi.mock('../src/db.js', () => ({+ pool: {+ query: (...args: unknown[]) => mockPoolQuery(...args),+ },+}))++vi.mock('../src/utils/auth/adminAuthToken.js', () => ({+ verifyAdminToken: (...args: unknown[]) => mockVerifyAdminToken(...args),+}))++vi.mock('../src/services/adminAuthService.js', () => ({+ findAdminById: (...args: unknown[]) => mockFindAdminById(...args),+ isAdminTokenRevoked: (...args: unknown[]) => mockIsAdminTokenRevoked(...args),+}))++const ADMIN_CLAIMS = {+ sub: '00000000-0000-4000-8000-000000000001',+ typ: 'user' as const,+ role: 'admin' as const,+ jti: 'admin-jti',+ exp: Math.floor(Date.now() / 1000) + 3600,+}++const ACTIVE_ADMIN = {+ id: ADMIN_CLAIMS.sub,+ username: 'admin',+ email: '[email protected]',+ passwordHash: 'hash',+ sessionVersion: 0,+ role: 'admin' as const,+ status: 'active' as const,+ failedAttempts: 0,+ lockedUntil: null,+}++const PROVIDER = 'claude'+const STALE_MODEL = 'claude-haiku-4-5'+const OTHER_STALE_MODEL = 'claude-opus-legacy'++// A raw `llm_allowed_models` DB row shaped to the migration schema, run through+// the REAL `rowToModel` mapper on the way out (T1). `stale` defaults true here+// because the WHERE-stale query only ever returns stale rows.+function makeModelRow(overrides: Record<string, unknown> = {}) {+ return {+ id: '11111111-1111-4111-8111-111111111111',+ provider: PROVIDER,+ model: STALE_MODEL,+ vendor: 'Anthropic',+ display_name: null,+ context_window_tokens: 200000,+ enabled: true,+ source: 'manual',+ discovered_at: null,+ last_seen_at: null,+ stale: true,+ created_at: new Date('2026-07-01T00:00:00Z'),+ updated_at: new Date('2026-07-01T00:00:00Z'),+ ...overrides,+ }+}++// A raw `plugin_workload_sdk_grants` row; the production path runs it through the+// REAL `mapGrantRow`, so the body carries genuine mapper output.+function makeGrantRow(overrides: Record<string, unknown> = {}) {+ return {+ id: '22222222-2222-4222-8222-222222222222',+ recipe_namespace: 'sandbox-recipes',+ recipe_name: 'nightly-summary',+ capability_family: 'promptBridge',+ provider: PROVIDER,+ allowed_models: [STALE_MODEL],+ allowed_event_types: [],+ allowed_target_refs: [],+ allowed_user_refs: [],+ allowed_callers: ['worker'],+ quota_limits: {},+ model_policies: {},+ prompt_targets: [],+ default_target_ref: null,+ policy_revision: 1,+ policy_state: 'active',+ policy_reviewed_at: null,+ policy_reviewed_by: null,+ revocation_id: null,+ created_at: new Date('2026-07-01T00:00:00Z'),+ updated_at: new Date('2026-07-01T00:00:00Z'),+ ...overrides,+ }+}++/**+ * Route `pool.query` by SQL text. `staleRows` are the rows the stale-list query+ * returns; `grantRowsByModel` maps a model name → the raw grant rows the+ * per-model impact query returns for it (keyed on the query's `$1` param).+ */+function installPool(opts: {+ staleRows?: unknown[]+ grantRowsByModel?: Record<string, unknown[]>+}) {+ const staleRows = opts.staleRows ?? []+ const grantRowsByModel = opts.grantRowsByModel ?? {}+ mockPoolQuery.mockImplementation(async (sql: string, params?: unknown[]) => {+ const text = String(sql)+ if (/FROM plugin_workload_sdk_grants/.test(text)) {+ const model = String(params?.[0] ?? '')+ const rows = grantRowsByModel[model] ?? []+ return { rows, rowCount: rows.length }+ }+ if (/FROM llm_allowed_models/.test(text) && /WHERE stale/.test(text)) {+ return { rows: staleRows, rowCount: staleRows.length }+ }+ return { rows: [], rowCount: 0 }+ })+}++function app(gateway: MockGateway) {+ return createApp(gateway as never)+}++function authedGet(gateway: MockGateway) {+ return request(app(gateway))+ .get('/api/v1/admin/attention')+ .set('Cookie', 'control_ui_admin_session=admin-token')+}++async function seedHost(+ gateway: MockGateway,+ name: string,+ spec: Record<string, unknown>,+ namespace = 'mcp-host'+) {+ await gateway.createResource('hosts', { metadata: { name }, spec }, namespace)+}++const primarySpec = (model = STALE_MODEL) => ({ model: { provider: PROVIDER, name: model } })++describe('GET /admin/attention', () => {+ beforeEach(() => {+ mockPoolQuery.mockReset()+ mockVerifyAdminToken.mockReset()+ mockVerifyAdminToken.mockReturnValue(ADMIN_CLAIMS)+ mockIsAdminTokenRevoked.mockReset()+ mockIsAdminTokenRevoked.mockResolvedValue(false)+ mockFindAdminById.mockReset()+ mockFindAdminById.mockResolvedValue(ACTIVE_ADMIN)+ })++ afterEach(() => {+ vi.clearAllMocks()+ })++ it('requires control-ui admin auth (401 without the session cookie)', async () => {+ installPool({ staleRows: [] })+ const gateway = new MockGateway('mcp-host')+ await request(app(gateway)).get('/api/v1/admin/attention').expect(401)+ })++ it('stale model referenced by a Host → one item with hostsAffected', async () => {+ installPool({ staleRows: [makeModelRow({ display_name: 'Claude Haiku' })] })+ const gateway = new MockGateway('mcp-host')+ await seedHost(gateway, 'agent-a', primarySpec())++ const res = await authedGet(gateway).expect(200)+ expect(res.body.items).toEqual([+ {+ kind: 'stale_model_referenced',+ provider: PROVIDER,+ model: STALE_MODEL,+ displayName: 'Claude Haiku',+ hostsAffected: [{ namespace: 'mcp-host', name: 'agent-a', roles: ['primary'] }],+ grantsAffected: [],+ },+ ])+ expect(typeof res.body.generatedAt).toBe('string')+ expect(Number.isNaN(Date.parse(res.body.generatedAt))).toBe(false)+ })++ it('stale model referenced ONLY by a grant → item with grantsAffected, empty hosts', async () => {+ installPool({+ staleRows: [makeModelRow()],+ grantRowsByModel: { [STALE_MODEL]: [makeGrantRow()] },+ })+ const gateway = new MockGateway('mcp-host') // no hosts++ const res = await authedGet(gateway).expect(200)+ expect(res.body.items).toHaveLength(1)+ expect(res.body.items[0]).toMatchObject({+ kind: 'stale_model_referenced',+ provider: PROVIDER,+ model: STALE_MODEL,+ hostsAffected: [],+ grantsAffected: [+ {+ id: '22222222-2222-4222-8222-222222222222',+ recipeNamespace: 'sandbox-recipes',+ recipeName: 'nightly-summary',+ capabilityFamily: 'promptBridge',+ },+ ],+ })+ // display_name was null → the field must be absent, not null.+ expect(res.body.items[0]).not.toHaveProperty('displayName')+ })++ it('stale model with NO references → not actionable → absent from the feed', async () => {+ installPool({ staleRows: [makeModelRow()] })+ const gateway = new MockGateway('mcp-host') // no hosts, no grants++ const res = await authedGet(gateway).expect(200)+ expect(res.body.items).toEqual([])+ })++ it('a NON-stale model that IS referenced never appears (not in the stale set)', async () => {+ // The stale query returns only STALE_MODEL. A Host references a DIFFERENT,+ // non-stale model — it must not generate an attention item.+ installPool({ staleRows: [makeModelRow()] })+ const gateway = new MockGateway('mcp-host')+ await seedHost(gateway, 'agent-nonstale', primarySpec('claude-sonnet-current'))++ const res = await authedGet(gateway).expect(200)+ expect(res.body.items).toEqual([])+ })++ it('no stale models → empty feed', async () => {+ installPool({ staleRows: [] })+ const gateway = new MockGateway('mcp-host')+ await seedHost(gateway, 'agent-a', primarySpec())++ const res = await authedGet(gateway).expect(200)+ expect(res.body.items).toEqual([])+ })++ it('mixed set: only the referenced stale model yields an item', async () => {+ installPool({+ staleRows: [+ makeModelRow({ id: '11111111-1111-4111-8111-111111111111', model: STALE_MODEL }),+ makeModelRow({ id: '33333333-3333-4333-8333-333333333333', model: OTHER_STALE_MODEL }),+ ],+ })+ const gateway = new MockGateway('mcp-host')+ // Only STALE_MODEL is referenced; OTHER_STALE_MODEL is stranded/unreferenced.+ await seedHost(gateway, 'agent-a', primarySpec(STALE_MODEL))++ const res = await authedGet(gateway).expect(200)+ expect(res.body.items).toHaveLength(1)+ expect(res.body.items[0].model).toBe(STALE_MODEL)+ })++ it('preserves the stable stale-list order (provider, model) with ≥2 referenced items', async () => {+ // `listStaleAllowedModels` sorts ORDER BY provider, model; the feed must+ // carry that order through unchanged. Both providers are `claude`, so model+ // decides: `claude-haiku-4-5` < `claude-opus-legacy`. The UI relies on it.+ installPool({+ staleRows: [+ makeModelRow({ id: '11111111-1111-4111-8111-111111111111', model: STALE_MODEL }),+ makeModelRow({ id: '33333333-3333-4333-8333-333333333333', model: OTHER_STALE_MODEL }),+ ],+ })+ const gateway = new MockGateway('mcp-host')+ await seedHost(gateway, 'agent-a', primarySpec(STALE_MODEL))+ await seedHost(gateway, 'agent-b', primarySpec(OTHER_STALE_MODEL))++ const res = await authedGet(gateway).expect(200)+ expect(res.body.items.map((i: { model: string }) => i.model)).toEqual([+ STALE_MODEL,+ OTHER_STALE_MODEL,+ ])+ })++ it('detects stale references across BOTH real host namespaces', async () => {+ expect(config.hostsNamespace).not.toBe(config.namespace) // precondition+ installPool({ staleRows: [makeModelRow()] })+ const gateway = new MockGateway('mcp-host')+ await seedHost(gateway, 'agent-a', primarySpec(), config.namespace)++ const res = await authedGet(gateway).expect(200)+ expect(res.body.items).toHaveLength(1)+ expect(res.body.items[0].hostsAffected).toEqual([+ { namespace: config.namespace, name: 'agent-a', roles: ['primary'] },+ ])+ })++ it('FAILS LOUD: a Host LIST error tumbles the whole endpoint (500), never a partial feed', async () => {+ installPool({ staleRows: [makeModelRow()] })+ const gateway = new MockGateway('mcp-host')+ gateway.listResource = vi.fn(async () => {+ throw new Error('k8s apiserver LIST failed')+ })++ await authedGet(gateway).expect(500)+ })+})diff --git a/control-api/test/services.llmAttention.test.ts b/control-api/test/services.llmAttention.test.tsnew file mode 100644index 000000000..02bdc6153--- /dev/null+++ b/control-api/test/services.llmAttention.test.ts@@ -0,0 +1,157 @@+import { describe, expect, it, vi } from 'vitest'+import { type StaleModelInput, computeAttention } from '../src/services/llmAttention.js'+import { type ModelImpactSources } from '../src/services/llmModelImpact.js'+import { mapGrantRow } from '../src/services/pluginWorkloadSdkDb.js'+import { MockGateway } from './mockGateway.js'++// Module-level tests for the attention feed builder. Host CRs come from the REAL+// gateway producer (`createResource` → per-namespace `listResource`, T1); the+// grant source is the output of the REAL `mapGrantRow` (T1). These complement+// the HTTP-contract tests in routes.adminAttention.test.ts (T4) with the cost+// (memoization) and fail-loud guarantees the endpoint depends on.++const PROVIDER = 'claude'+const MODEL_A = 'claude-haiku-4-5'+const MODEL_B = 'claude-opus-legacy'+const NAMESPACES = ['mcp-host', 'control-api']++function stale(model: string, display_name: string | null = null): StaleModelInput {+ return { provider: PROVIDER, model, display_name }+}++function makeGrantRow(model: string, overrides: Record<string, unknown> = {}) {+ return {+ id: '22222222-2222-4222-8222-222222222222',+ recipe_namespace: 'sandbox-recipes',+ recipe_name: 'nightly-summary',+ capability_family: 'promptBridge',+ provider: PROVIDER,+ allowed_models: [model],+ allowed_event_types: [],+ allowed_target_refs: [],+ allowed_user_refs: [],+ allowed_callers: ['worker'],+ quota_limits: {},+ model_policies: {},+ prompt_targets: [],+ default_target_ref: null,+ policy_revision: 1,+ policy_state: 'active',+ policy_reviewed_at: null,+ policy_reviewed_by: null,+ revocation_id: null,+ created_at: new Date('2026-07-01T00:00:00Z'),+ updated_at: new Date('2026-07-01T00:00:00Z'),+ ...overrides,+ }+}++/** Sources wired to the real gateway producer, with an injected grant lookup. */+function sourcesFor(+ gateway: MockGateway,+ grantRowsByModel: Record<string, unknown[]> = {}+): ModelImpactSources {+ return {+ hostNamespaces: NAMESPACES,+ listHostsInNamespace: namespace => gateway.listResource('hosts', namespace),+ listGrantsForModel: async model =>+ ((grantRowsByModel[model] ?? []) as Record<string, unknown>[]).map(mapGrantRow),+ }+}++async function seedHost(gateway: MockGateway, name: string, model: string, namespace = 'mcp-host') {+ await gateway.createResource(+ 'hosts',+ { metadata: { name }, spec: { model: { provider: PROVIDER, name: model } } },+ namespace+ )+}++describe('computeAttention', () => {+ it('emits an item only for referenced stale models, carrying the impact', async () => {+ const gateway = new MockGateway('mcp-host')+ await seedHost(gateway, 'agent-a', MODEL_A)++ const report = await computeAttention(+ [stale(MODEL_A, 'Claude Haiku'), stale(MODEL_B)],+ sourcesFor(gateway)+ )++ expect(report.items).toEqual([+ {+ kind: 'stale_model_referenced',+ provider: PROVIDER,+ model: MODEL_A,+ displayName: 'Claude Haiku',+ hostsAffected: [{ namespace: 'mcp-host', name: 'agent-a', roles: ['primary'] }],+ grantsAffected: [],+ },+ ])+ expect(typeof report.generatedAt).toBe('string')+ })++ it('an unreferenced stale model yields no item; empty stale set → empty feed', async () => {+ const gateway = new MockGateway('mcp-host') // no hosts+ expect((await computeAttention([stale(MODEL_A)], sourcesFor(gateway))).items).toEqual([])+ expect((await computeAttention([], sourcesFor(gateway))).items).toEqual([])+ })++ it('grant-only reference produces an item with grantsAffected', async () => {+ const gateway = new MockGateway('mcp-host')+ const report = await computeAttention(+ [stale(MODEL_A)],+ sourcesFor(gateway, { [MODEL_A]: [makeGrantRow(MODEL_A)] })+ )+ expect(report.items).toHaveLength(1)+ expect(report.items[0].grantsAffected).toEqual([+ {+ id: '22222222-2222-4222-8222-222222222222',+ recipeNamespace: 'sandbox-recipes',+ recipeName: 'nightly-summary',+ capabilityFamily: 'promptBridge',+ },+ ])+ expect(report.items[0].hostsAffected).toEqual([])+ })++ it('COST: Host LIST runs once per namespace regardless of stale-set size (memoized)', async () => {+ const gateway = new MockGateway('mcp-host')+ await seedHost(gateway, 'agent-a', MODEL_A)+ const base = sourcesFor(gateway)+ const listSpy = vi.fn(base.listHostsInNamespace)+ const sources: ModelImpactSources = { ...base, listHostsInNamespace: listSpy }++ // Three stale models, two namespaces. Without memoization this would be 6+ // LISTs; memoized it is exactly one per namespace = 2.+ await computeAttention([stale(MODEL_A), stale(MODEL_B), stale('claude-x')], sources)++ expect(listSpy).toHaveBeenCalledTimes(NAMESPACES.length)+ const listedNamespaces = listSpy.mock.calls.map(c => c[0]).sort()+ expect(listedNamespaces).toEqual([...NAMESPACES].sort())+ })++ it('FAILS LOUD: a Host LIST rejection propagates (no partial feed)', async () => {+ const gateway = new MockGateway('mcp-host')+ gateway.listResource = vi.fn(async () => {+ throw new Error('k8s apiserver LIST failed')+ })+ await expect(+ computeAttention([stale(MODEL_A), stale(MODEL_B)], sourcesFor(gateway))+ ).rejects.toThrow(/LIST failed/)+ })++ it('FAILS LOUD on the GRANT side too: a grant-query rejection propagates', async () => {+ // The module docstring claims fail-loud for ANY source, not just the K8s+ // LIST. Prove the PG grant lookup half: if listGrantsForModel rejects, the+ // whole computation rejects rather than dropping a possibly-referenced model.+ const gateway = new MockGateway('mcp-host') // no hosts → forces the grant query to run+ const sources: ModelImpactSources = {+ hostNamespaces: NAMESPACES,+ listHostsInNamespace: namespace => gateway.listResource('hosts', namespace),+ listGrantsForModel: async () => {+ throw new Error('postgres grant query failed')+ },+ }+ await expect(computeAttention([stale(MODEL_A)], sources)).rejects.toThrow(/grant query failed/)+ })+})