Skip to content

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

TypeScript

feat(control-api): live model-impact module + ?force gate on llm-models PUT/DELETE (Pieza B)

Diego Zacarias5f0140a2cf0d
diff --git a/control-api/package-lock.json b/control-api/package-lock.json
index 9bb4e2174..4f27babd1 100644
--- a/control-api/package-lock.json
+++ b/control-api/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "clerum-control-api",
- "version": "0.1.434",
+ "version": "0.1.435",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "clerum-control-api",
- "version": "0.1.434",
+ "version": "0.1.435",
"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.json
index 87c5b1e45..1c47faa52 100644
--- a/control-api/package.json
+++ b/control-api/package.json
@@ -1,6 +1,6 @@
{
"name": "clerum-control-api",
- "version": "0.1.434",
+ "version": "0.1.435",
"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.ts
index bf5248fe1..3aebea4e1 100644
--- a/control-api/src/routes/admin/llmModels.ts
+++ b/control-api/src/routes/admin/llmModels.ts
@@ -1,5 +1,6 @@
import { type Request, type Response, Router } from 'express'
import { z } from 'zod'
+import { config } from '../../config.js'
import { asyncHandler } from '../../http/asyncHandler.js'
import type { K8sGateway } from '../../k8s.js'
import type { UiAuthedRequest } from '../../middleware/controlUIAuth.js'
@@ -15,6 +16,11 @@ import {
updateLlmAllowedModelSchema,
} from '../../services/llmAllowedModels.js'
import { getLastCatalogSyncRun, syncDiscoveredModels } from '../../services/llmCatalogSync.js'
+import {
+ computeModelImpact,
+ modelImpactHasReferences,
+ modelImpactSourcesFromGateway,
+} from '../../services/llmModelImpact.js'
// `id` is a UUID column; a malformed id would otherwise reach Postgres and
// raise 22P02 (→ 500). Treat a non-UUID id as a missing row (404).
@@ -41,6 +47,13 @@ function handleServiceError(res: Response, error: unknown): boolean {
return false
}
+// `?force=true` opts the operator past the availability-reduction gate (Fase 3).
+// Only the exact string `true` counts; absent / `false` / garbage / a repeated
+// param (array) all read as NOT forced — fail-safe toward SHOWING the impact.
+function isForced(req: Request): boolean {
+ return req.query.force === 'true'
+}
+
// Admin identity for the audit row. Auth is enforced upstream by the control-ui
// auth gate; `sub` is the admin UUID. Fall back defensively so a mutation is
// never silently unattributed.
@@ -76,6 +89,44 @@ export function createAdminLlmModelsRouter(gateway: K8sGateway): Router {
}
}
+ // The exact set of namespaces a Host can occupy. Mirrors the canonical host
+ // fan-out (`ResourceService.listNamespacesForPlural('hosts')` =
+ // `config.hostsNamespace` + the control-api default namespace); every admin
+ // write pins Hosts to `config.hostsNamespace` via `enforceNamespace`, so this
+ // is the full universe. Passed explicitly (not the `'*'` sentinel) so the
+ // impact enumeration LISTs each namespace fail-loud instead of swallowing
+ // per-namespace LIST errors — see llmModelImpact.ts.
+ const hostNamespaces = Array.from(new Set([config.hostsNamespace, config.namespace]))
+
+ // Live references to a `(provider, model)` pair, enumerated from the real
+ // producers (K8s Host LIST + grant SQL). The `?force`/attention seam shares
+ // this single module (regla D4).
+ const impactSources = modelImpactSourcesFromGateway(gateway, hostNamespaces)
+
+ // Availability-reduction gate (Fase 3). A DELETE (always) or a PUT that flips
+ // `enabled` true→false yanks the model out of the runtime allowlist ConfigMap.
+ // Without `?force`, if any Host/grant still references `(provider, model)`,
+ // answer 409 WITH the impact body so the operator sees what would be stranded
+ // instead of breaking it silently. Returns true when a 409 was sent (the
+ // caller must stop). `?force=true` skips the enumeration entirely and proceeds.
+ async function blockedByImpact(
+ req: Request,
+ res: Response,
+ provider: string,
+ model: string
+ ): Promise<boolean> {
+ if (isForced(req)) return false
+ const impact = await computeModelImpact(provider, model, impactSources)
+ if (!modelImpactHasReferences(impact)) return false
+ res.status(409).json({
+ error: 'model_in_use',
+ message:
+ 'this model is still referenced by one or more Hosts or grants; retry with ?force=true to disable/remove it and leave those references pointing at a disabled/removed model',
+ impact,
+ })
+ return true
+ }
+
// ── 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 operator
@@ -161,6 +212,23 @@ export function createAdminLlmModelsRouter(gateway: K8sGateway): Router {
sendZodError(res, parsed.error)
return
}
+ // Read the stored row FIRST: needed both to 404 a missing row and to
+ // classify whether this write REDUCES availability. Only a transition of
+ // `enabled` true→false pulls the model out of the runtime ConfigMap and
+ // can strand references; a PUT that keeps it enabled (incl. a re-enable or
+ // a metadata-only edit) never trips the gate.
+ const existing = await getAllowedModel(req.params.id)
+ if (!existing) {
+ res.status(404).json({ error: 'not_found' })
+ return
+ }
+ const reducesAvailability = existing.enabled === true && parsed.data.enabled === false
+ if (
+ reducesAvailability &&
+ (await blockedByImpact(req, res, existing.provider, existing.model))
+ ) {
+ return
+ }
let model
try {
model = await updateAllowedModel(req.params.id, parsed.data, actorOf(req))
@@ -184,7 +252,24 @@ export function createAdminLlmModelsRouter(gateway: K8sGateway): Router {
res.status(404).json({ error: 'not_found' })
return
}
- const deleted = await deleteAllowedModel(req.params.id, actorOf(req))
+ // Read the stored row first so we know the `(provider, model)` whose impact
+ // to compute AND can 404 a missing row before any destructive work. A
+ // DELETE always removes the model, so the gate runs unconditionally (unless
+ // `?force`). This handler now shares the router's `handleServiceError`
+ // path for consistency with POST/PUT.
+ const existing = await getAllowedModel(req.params.id)
+ if (!existing) {
+ res.status(404).json({ error: 'not_found' })
+ return
+ }
+ if (await blockedByImpact(req, res, existing.provider, existing.model)) return
+ let deleted
+ try {
+ deleted = await deleteAllowedModel(req.params.id, actorOf(req))
+ } catch (error) {
+ if (handleServiceError(res, error)) return
+ throw error
+ }
if (!deleted) {
res.status(404).json({ error: 'not_found' })
return
diff --git a/control-api/src/services/llmModelImpact.ts b/control-api/src/services/llmModelImpact.ts
new file mode 100644
index 000000000..dc6730fe5
--- /dev/null
+++ b/control-api/src/services/llmModelImpact.ts
@@ -0,0 +1,217 @@
+/**
+ * LLM-model impact enumeration (spec Fase 3). Enumerates every LIVE reference to
+ * an operator-allowlist `(provider, model)` pair, so a destructive allowlist
+ * mutation (DELETE, or a PUT that disables the model) can warn the operator
+ * about the Hosts/grants it would silently invalidate instead of breaking them
+ * in the dark.
+ *
+ * This feeds a SAFETY GATE: an under-report lets the operator disable a still-
+ * referenced model believing it is free — exactly the silent breakage the phase
+ * exists to prevent. So the enumeration is FAIL-LOUD: if any Host LIST fails, the
+ * whole computation REJECTS (propagates) rather than returning a partial result,
+ * and the caller fails the destructive op closed.
+ *
+ * A `(provider, model)` pair is referenced from FOUR sources — a hybrid of the
+ * live K8s CRD store and Postgres:
+ * 1. Host `spec.model` (the primary model the Host defaults to) [CRD]
+ * 2. Host `spec.allowedModels[]` (the per-Host offered subset) [CRD]
+ * 3. Host `spec.llmPolicy.fallbacks[]` (the provider-fallback policy) [CRD]
+ * 4. `plugin_workload_sdk_grants.allowed_models` (grant model allowlist) [PG]
+ *
+ * OUT OF SCOPE by design (spec §3.2 + §5): grant `prompt_targets` are NOT
+ * enumerated. The spec limits the grant impact surface to `allowed_models` (§3.2)
+ * and excludes promptBridge from carrying a warning surface (§5). References that
+ * exist only through `prompt_targets` are intentionally not reported here — this
+ * is a deliberate scope boundary, not a missing source.
+ *
+ * NAMESPACE COVERAGE. Host CRDs live in the operator's host namespace(s). This
+ * module enumerates the SAME set the canonical host fan-out uses — the injected
+ * `hostNamespaces` (built from `config.hostsNamespace` + the control-api default
+ * namespace, mirroring `ResourceService.listNamespacesForPlural('hosts')`) — and
+ * LISTs each ONE BY ONE via `listResource('hosts', ns)`. It deliberately does NOT
+ * use the `namespace='*'` sentinel: `ResourceService` swallows per-namespace LIST
+ * errors on that path (`catch {}`), which would silently under-report. The
+ * per-namespace path propagates, giving the fail-loud guarantee above. Every
+ * admin write pins Hosts to `config.hostsNamespace` (`enforceNamespace`), so this
+ * set is the full universe a Host can occupy. Cost: O(#namespaces) LIST calls,
+ * each O(#Hosts).
+ *
+ * The GRANT match is by MODEL NAME ONLY, not `(provider, model)`. The grant
+ * `allowed_models` column is a provider-LESS flat model-name list and is NOT
+ * enforced to hold only models of the grant's `provider` column (the write-gate
+ * validates `prompt_targets` per-provider, but `allowed_models` is passed through
+ * free-form and can span providers). Filtering by `provider` would therefore
+ * UNDER-report — the unsafe direction for a safety gate. Matching by model name
+ * may over-report a same-named model under a different provider (added operator
+ * friction, never silent breakage), which is the fail-safe trade-off.
+ *
+ * ONE module, TWO callers (regla D4): the `?force` gate on PUT/DELETE
+ * (`routes/admin/llmModels.ts`) and, later, `GET /admin/attention` (Fase 5).
+ * Neither reconstructs the impact — both call `computeModelImpact`.
+ */
+import { offeredKey } from '../routes/admin/modelAllowlistTolerance.js'
+import { isPlainObject } from '../utils/isPlainObject.js'
+import { type PluginWorkloadSdkGrant, listGrantsReferencingModel } from './pluginWorkloadSdkDb.js'
+
+/** Which Host spec source referenced the pair. A Host may match in several. */
+export type HostModelRole = 'primary' | 'allowedModels' | 'fallback'
+
+/** A Host CR that references the pair, with the roles it matched in. */
+export interface HostModelReference {
+ namespace: string
+ name: string
+ roles: HostModelRole[]
+}
+
+/** A grant that references the pair through its `allowed_models` list. */
+export interface GrantModelReference {
+ id: string
+ recipeNamespace: string
+ recipeName: string
+ capabilityFamily: string
+}
+
+/** The enumerated live references to a `(provider, model)` pair. */
+export interface ModelImpact {
+ provider: string
+ model: string
+ hostsAffected: HostModelReference[]
+ grantsAffected: GrantModelReference[]
+}
+
+/**
+ * Injectable sources so the enumeration stays unit-testable without a real K8s
+ * client or DB. Both callers build these from the real producers via
+ * `modelImpactSourcesFromGateway`.
+ */
+export interface ModelImpactSources {
+ /** The exact set of namespaces a Host can occupy (the canonical host set). */
+ hostNamespaces: string[]
+ /**
+ * LIST Hosts in ONE namespace. MUST propagate (reject) on failure — the
+ * enumeration relies on that for its fail-loud/fail-closed guarantee.
+ */
+ listHostsInNamespace: (namespace: string) => Promise<unknown[]>
+ /** Grants whose `allowed_models` list contains `model` (provider-less match). */
+ listGrantsForModel: (model: string) => Promise<PluginWorkloadSdkGrant[]>
+}
+
+/** Minimal gateway surface this module needs — a per-namespace Host LIST. */
+interface HostListGateway {
+ listResource: (plural: 'hosts', namespace?: string) => Promise<unknown[]>
+}
+
+/**
+ * Wire the impact sources to the real producers: live per-namespace Host LIST via
+ * the K8s gateway (NO `'*'` — see the fail-loud rationale above) and the grant
+ * SQL query. `hostNamespaces` is supplied by the caller from config so the single
+ * source of truth for "where Hosts live" stays in one place.
+ */
+export function modelImpactSourcesFromGateway(
+ gateway: HostListGateway,
+ hostNamespaces: string[]
+): ModelImpactSources {
+ return {
+ hostNamespaces,
+ listHostsInNamespace: namespace => gateway.listResource('hosts', namespace),
+ listGrantsForModel: model => listGrantsReferencingModel(model),
+ }
+}
+
+/**
+ * The roles in which a Host spec references the target `(provider, model)` pair
+ * (keyed via `offeredKey`, the same NUL-separated key the write-gate uses so a
+ * model id containing spaces can never collide with a distinct pair). Empty when
+ * the Host does not reference it. Purely structural and defensive: any
+ * malformed/partial entry is skipped, never throws.
+ */
+function hostRolesReferencing(spec: unknown, targetKey: string): HostModelRole[] {
+ if (!isPlainObject(spec)) return []
+ const roles: HostModelRole[] = []
+
+ // 1. primary — spec.model
+ const model = spec.model
+ if (isPlainObject(model)) {
+ const name = typeof model.name === 'string' ? model.name.trim() : ''
+ const provider = typeof model.provider === 'string' ? model.provider.trim() : ''
+ if (name && provider && offeredKey(provider, name) === targetKey) roles.push('primary')
+ }
+
+ // 2. allowedModels — spec.allowedModels[]
+ const allowedModels = spec.allowedModels
+ if (Array.isArray(allowedModels)) {
+ for (const entry of allowedModels) {
+ if (!isPlainObject(entry)) continue
+ const provider = typeof entry.provider === 'string' ? entry.provider.trim() : ''
+ const m = typeof entry.model === 'string' ? entry.model.trim() : ''
+ if (provider && m && offeredKey(provider, m) === targetKey) {
+ roles.push('allowedModels')
+ break
+ }
+ }
+ }
+
+ // 3. fallback — spec.llmPolicy.fallbacks[]
+ const llmPolicy = spec.llmPolicy
+ if (isPlainObject(llmPolicy) && Array.isArray(llmPolicy.fallbacks)) {
+ for (const entry of llmPolicy.fallbacks) {
+ if (!isPlainObject(entry)) continue
+ const provider = typeof entry.provider === 'string' ? entry.provider.trim() : ''
+ const m = typeof entry.model === 'string' ? entry.model.trim() : ''
+ if (provider && m && offeredKey(provider, m) === targetKey) {
+ roles.push('fallback')
+ break
+ }
+ }
+ }
+
+ return roles
+}
+
+/**
+ * Enumerate every live reference to `(provider, model)` across the four sources.
+ * Aggregation over the injected sources — its only I/O is the Host LIST per
+ * namespace and the grant query, both of which it lets REJECT (fail-loud). No
+ * try/catch: a partial enumeration must never be returned to a safety gate.
+ * Shared verbatim by the `?force` gate and the Fase 5 attention endpoint.
+ */
+export async function computeModelImpact(
+ provider: string,
+ model: string,
+ sources: ModelImpactSources
+): Promise<ModelImpact> {
+ const targetKey = offeredKey(provider, model)
+
+ const hostsAffected: HostModelReference[] = []
+ for (const namespace of sources.hostNamespaces) {
+ // No catch: a failed LIST propagates so the caller fails the destructive op
+ // CLOSED instead of acting on a partial (under-reported) impact.
+ const hosts = await sources.listHostsInNamespace(namespace)
+ for (const host of hosts) {
+ if (!isPlainObject(host)) continue
+ const roles = hostRolesReferencing(host.spec, targetKey)
+ if (roles.length === 0) continue
+ const metadata = isPlainObject(host.metadata) ? host.metadata : {}
+ hostsAffected.push({
+ namespace: typeof metadata.namespace === 'string' ? metadata.namespace : namespace,
+ name: typeof metadata.name === 'string' ? metadata.name : '',
+ roles,
+ })
+ }
+ }
+
+ const grants = await sources.listGrantsForModel(model)
+ const grantsAffected: GrantModelReference[] = grants.map(grant => ({
+ id: grant.id,
+ recipeNamespace: grant.recipeNamespace,
+ recipeName: grant.recipeName,
+ capabilityFamily: grant.capabilityFamily,
+ }))
+
+ return { provider, model, hostsAffected, grantsAffected }
+}
+
+/** True when the pair has at least one live Host or grant reference. */
+export function modelImpactHasReferences(impact: ModelImpact): boolean {
+ return impact.hostsAffected.length > 0 || impact.grantsAffected.length > 0
+}
diff --git a/control-api/src/services/pluginWorkloadSdkDb.ts b/control-api/src/services/pluginWorkloadSdkDb.ts
index 01569d5b0..30e83eecc 100644
--- a/control-api/src/services/pluginWorkloadSdkDb.ts
+++ b/control-api/src/services/pluginWorkloadSdkDb.ts
@@ -640,6 +640,44 @@ export async function listGrants(filter?: {
return (result.rows as Record<string, unknown>[]).map(mapGrantRow)
}
+/**
+ * Grants whose `allowed_models` list names `model` — the 4th source of the
+ * LLM-model impact enumeration (Fase 3, `llmModelImpact.ts`).
+ *
+ * MATCH BY MODEL NAME ONLY, deliberately NOT by `(provider, model)`. The
+ * `allowed_models` column is a provider-LESS flat model-name list and is NOT
+ * enforced to hold only models of the grant's `provider` column: the write-gate
+ * (`routes/admin/pluginWorkloadSdk.ts`) validates `prompt_targets` per-provider,
+ * but `allowed_models` is parsed from the request body free-form and passed
+ * straight through — and since `prompt_targets` can span multiple providers, the
+ * mirrored `allowed_models` set can too. Filtering by `provider` would therefore
+ * UNDER-report references, the unsafe direction for a safety gate that gates a
+ * destructive disable/delete. Matching by model name may over-report a same-named
+ * model under a different provider (extra operator friction, never silent
+ * breakage) — the fail-safe trade-off. This is exercised by the realPostgres
+ * integration test `db.listGrantsReferencingModel.realPostgres.integration`.
+ *
+ * No `policy_state` and no `provider IS NOT NULL` filter: a grant is surfaced
+ * whenever it names the model, including legacy NULL-provider and
+ * `revoking`/`disabled` rows (fail-loud — never hide a dangling reference).
+ *
+ * `allowed_models @> to_jsonb($1::text)` is jsonb array-contains-scalar: for a
+ * text `model`, `to_jsonb('m'::text)` is the JSON string `"m"`, and a jsonb
+ * array `@>` a scalar is true when the array contains that element.
+ */
+export async function listGrantsReferencingModel(
+ model: string,
+ db: DbClient = pool
+): Promise<PluginWorkloadSdkGrant[]> {
+ const result = await db.query(
+ `SELECT * FROM plugin_workload_sdk_grants
+ WHERE allowed_models @> to_jsonb($1::text)
+ ORDER BY recipe_namespace, recipe_name, capability_family`,
+ [model]
+ )
+ return (result.rows as Record<string, unknown>[]).map(mapGrantRow)
+}
+
/**
* Read-only migration gate for promptBridge rows written before the ordered
* target policy existed. Legacy rows are intentionally never inferred or
diff --git a/control-api/test/db.listGrantsReferencingModel.realPostgres.integration.test.ts b/control-api/test/db.listGrantsReferencingModel.realPostgres.integration.test.ts
new file mode 100644
index 000000000..3974ec3ed
--- /dev/null
+++ b/control-api/test/db.listGrantsReferencingModel.realPostgres.integration.test.ts
@@ -0,0 +1,112 @@
+import { afterAll, beforeAll, describe, expect, it } from 'vitest'
+import { randomBytes } from 'node:crypto'
+import { Pool } from 'pg'
+import { initDb } from '../src/db.js'
+import { listGrantsReferencingModel } from '../src/services/pluginWorkloadSdkDb.js'
+
+// FIX C (T1/T3): exercise the REAL jsonb `@>` containment of
+// listGrantsReferencingModel against a real Postgres — the risky part the unit
+// test necessarily stubs. Skipped without CONTROL_API_REAL_PG_ADMIN_URL, but
+// runnable in CI/local where a Postgres is present. The rows are inserted with
+// SQL (minimal grant rows) because the query semantics — not the row DTO shape —
+// are what is under test here; the DTO shape is covered by mapGrantRow tests.
+
+const adminUrl = process.env.CONTROL_API_REAL_PG_ADMIN_URL
+const describeRealPostgres = adminUrl ? describe : describe.skip
+
+function databaseUrl(baseUrl: string, database: string): string {
+ const url = new URL(baseUrl)
+ url.pathname = `/${database}`
+ return url.toString()
+}
+
+describeRealPostgres('listGrantsReferencingModel jsonb containment on real PostgreSQL', () => {
+ const database = `control_api_grant_impact_${randomBytes(6).toString('hex')}`
+ const connectionString = databaseUrl(
+ adminUrl ?? 'postgresql://[email protected]/postgres',
+ database
+ )
+ let adminPool: Pool
+ let dbPool: Pool
+
+ beforeAll(async () => {
+ adminPool = new Pool({ connectionString: adminUrl })
+ await adminPool.query(`CREATE DATABASE "${database.replace(/"/g, '""')}"`)
+ dbPool = new Pool({ connectionString })
+ await initDb({ connect: () => dbPool.connect() })
+
+ // A grant naming the target model under provider 'claude'.
+ await insertGrant(dbPool, {
+ recipeName: 'names-target-under-claude',
+ provider: 'claude',
+ allowedModels: ['claude-haiku-4-5', 'claude-sonnet-4-5'],
+ })
+ // A grant naming the SAME target model but under a DIFFERENT provider — the
+ // fail-safe case: a provider filter would wrongly drop this. It MUST match.
+ await insertGrant(dbPool, {
+ recipeName: 'names-target-under-openai',
+ provider: 'openai',
+ allowedModels: ['claude-haiku-4-5'],
+ })
+ // A legacy NULL-provider grant that still names the model — must match.
+ await insertGrant(dbPool, {
+ recipeName: 'names-target-null-provider',
+ provider: null,
+ allowedModels: ['claude-haiku-4-5'],
+ })
+ // A grant that does NOT name the target model — must be excluded.
+ await insertGrant(dbPool, {
+ recipeName: 'no-target',
+ provider: 'claude',
+ allowedModels: ['claude-sonnet-4-5'],
+ })
+ })
+
+ afterAll(async () => {
+ await dbPool?.end()
+ if (!adminPool) return
+ await adminPool.query(
+ `SELECT pg_terminate_backend(pid)
+ FROM pg_stat_activity
+ WHERE datname = $1
+ AND pid <> pg_backend_pid()`,
+ [database]
+ )
+ await adminPool.query(`DROP DATABASE IF EXISTS "${database.replace(/"/g, '""')}"`)
+ await adminPool.end()
+ })
+
+ async function insertGrant(
+ pool: Pool,
+ row: { recipeName: string; provider: string | null; allowedModels: string[] }
+ ): Promise<void> {
+ await pool.query(
+ `INSERT INTO plugin_workload_sdk_grants
+ (recipe_namespace, recipe_name, capability_family, provider, allowed_models, allowed_callers)
+ VALUES ('sandbox-recipes', $1, 'promptBridge', $2, $3::jsonb, '["worker"]'::jsonb)`,
+ [row.recipeName, row.provider, JSON.stringify(row.allowedModels)]
+ )
+ }
+
+ it('matches every grant naming the model — across providers and NULL provider — and excludes others', async () => {
+ const grants = await listGrantsReferencingModel('claude-haiku-4-5', dbPool)
+ const names = grants.map(g => g.recipeName).sort()
+ expect(names).toEqual([
+ 'names-target-null-provider',
+ 'names-target-under-claude',
+ 'names-target-under-openai',
+ ])
+ })
+
+ it('containment (not equality): a model listed among several still matches', async () => {
+ const grants = await listGrantsReferencingModel('claude-sonnet-4-5', dbPool)
+ const names = grants.map(g => g.recipeName).sort()
+ // Present in the two-entry claude grant AND the no-target grant's list.
+ expect(names).toEqual(['names-target-under-claude', 'no-target'])
+ })
+
+ it('returns nothing for a model no grant names', async () => {
+ const grants = await listGrantsReferencingModel('gpt-4o-mini', dbPool)
+ expect(grants).toEqual([])
+ })
+})
diff --git a/control-api/test/routes.adminLlmModels.test.ts b/control-api/test/routes.adminLlmModels.test.ts
index 92db74c6b..06deb5f46 100644
--- a/control-api/test/routes.adminLlmModels.test.ts
+++ b/control-api/test/routes.adminLlmModels.test.ts
@@ -233,8 +233,14 @@ describe('admin llm-models routes', () => {
})
it('PUT /admin/llm-models/:id updates and returns 200', async () => {
+ // A disable (enabled true→false) now runs the availability-reduction gate
+ // first: gate read + grant-impact query + the update's own read/UPDATE/audit.
+ // Hosts come from the (empty) MockGateway store, so there is no impact and
+ // the write proceeds.
mockPoolQuery
- .mockResolvedValueOnce({ rows: [MODEL_ROW], rowCount: 1 }) // getAllowedModel
+ .mockResolvedValueOnce({ rows: [MODEL_ROW], rowCount: 1 }) // gate getAllowedModel
+ .mockResolvedValueOnce({ rows: [], rowCount: 0 }) // grant-impact query → none
+ .mockResolvedValueOnce({ rows: [MODEL_ROW], rowCount: 1 }) // updateAllowedModel read
.mockResolvedValueOnce({ rows: [{ ...MODEL_ROW, enabled: false }], rowCount: 1 }) // UPDATE
.mockResolvedValueOnce({ rows: [], rowCount: 1 }) // audit
const res = await authed('put', `/api/v1/admin/llm-models/${MODEL_ROW.id}`)
@@ -260,8 +266,12 @@ describe('admin llm-models routes', () => {
})
it('DELETE /admin/llm-models/:id returns 204 on success', async () => {
+ // A DELETE always runs the impact gate first: gate read + grant-impact query,
+ // then the delete's own read/DELETE/audit. Empty MockGateway → no impact.
mockPoolQuery
- .mockResolvedValueOnce({ rows: [MODEL_ROW], rowCount: 1 }) // getAllowedModel
+ .mockResolvedValueOnce({ rows: [MODEL_ROW], rowCount: 1 }) // gate getAllowedModel
+ .mockResolvedValueOnce({ rows: [], rowCount: 0 }) // grant-impact query → none
+ .mockResolvedValueOnce({ rows: [MODEL_ROW], rowCount: 1 }) // deleteAllowedModel read
.mockResolvedValueOnce({ rows: [], rowCount: 1 }) // DELETE
.mockResolvedValueOnce({ rows: [], rowCount: 1 }) // audit
await authed('delete', `/api/v1/admin/llm-models/${MODEL_ROW.id}`).expect(204)
diff --git a/control-api/test/routes.adminLlmModelsImpact.test.ts b/control-api/test/routes.adminLlmModelsImpact.test.ts
new file mode 100644
index 000000000..9b53b8dd8
--- /dev/null
+++ b/control-api/test/routes.adminLlmModelsImpact.test.ts
@@ -0,0 +1,333 @@
+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 3: the `?force` availability-reduction gate on PUT/DELETE of
+// `/admin/llm-models`. These are OBSERVABLE-contract tests (T4): they assert the
+// HTTP status (409 vs 200/204) and the impact body the operator sees, never an
+// internal count. Host references are produced by the REAL gateway producer
+// (`createResource` → `listResource`, T1), never hand-built CR literals; grant
+// references flow through the REAL `mapGrantRow` inside `listGrantsReferencingModel`.
+
+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 MODEL = 'claude-haiku-4-5'
+const MODEL_ID = '11111111-1111-4111-8111-111111111111'
+
+// The stored allowlist row the gate reads. Mutable so a test can flip `enabled`.
+function makeModelRow(overrides: Record<string, unknown> = {}) {
+ return {
+ id: MODEL_ID,
+ provider: PROVIDER,
+ model: MODEL,
+ vendor: 'Anthropic',
+ display_name: null,
+ context_window_tokens: 200000,
+ enabled: true,
+ source: 'manual',
+ discovered_at: null,
+ last_seen_at: null,
+ stale: false,
+ 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` DB row shaped to the migration schema. The
+// production impact path runs it through the REAL `mapGrantRow`, so what the
+// 409 body carries is genuinely mapper output — not a hand-authored grant DTO.
+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: [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 (robust to call ORDER — the gate adds reads
+ * ahead of the mutation). `modelRow` is the stored allowlist row; `grantRows`
+ * are the raw grant rows the impact query returns.
+ */
+function installPool(opts: { modelRow?: Record<string, unknown> | null; grantRows?: unknown[] }) {
+ const modelRow = opts.modelRow === undefined ? makeModelRow() : opts.modelRow
+ const grantRows = opts.grantRows ?? []
+ mockPoolQuery.mockImplementation(async (sql: string) => {
+ const text = String(sql)
+ if (/FROM plugin_workload_sdk_grants/.test(text))
+ return { rows: grantRows, rowCount: grantRows.length }
+ if (/FROM llm_allowed_models\b/.test(text) && /WHERE id/.test(text)) {
+ return { rows: modelRow ? [modelRow] : [], rowCount: modelRow ? 1 : 0 }
+ }
+ if (/UPDATE llm_allowed_models/.test(text)) {
+ return { rows: [makeModelRow({ enabled: false })], rowCount: 1 }
+ }
+ if (/DELETE FROM llm_allowed_models/.test(text)) return { rows: [], rowCount: 1 }
+ // audit inserts and anything else
+ return { rows: [], rowCount: 1 }
+ })
+}
+
+function app(gateway: MockGateway) {
+ return createApp(gateway as never)
+}
+
+function authed(method: 'get' | 'post' | 'put' | 'delete', path: string, gateway: MockGateway) {
+ return request(app(gateway))[method](path).set('Cookie', 'control_ui_admin_session=admin-token')
+}
+
+// Seed a Host CR through the REAL gateway producer (mirrors prod create/list).
+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: { provider: PROVIDER, name: MODEL } }
+const allowedModelsSpec = { allowedModels: [{ provider: PROVIDER, model: MODEL }] }
+const fallbackSpec = { llmPolicy: { fallbacks: [{ provider: PROVIDER, model: MODEL }] } }
+
+describe('admin llm-models ?force impact gate', () => {
+ beforeEach(() => {
+ mockPoolQuery.mockReset()
+ mockVerifyAdminToken.mockReset()
+ mockVerifyAdminToken.mockReturnValue(ADMIN_CLAIMS)
+ mockIsAdminTokenRevoked.mockReset()
+ mockIsAdminTokenRevoked.mockResolvedValue(false)
+ mockFindAdminById.mockReset()
+ mockFindAdminById.mockResolvedValue(ACTIVE_ADMIN)
+ })
+
+ afterEach(() => {
+ vi.clearAllMocks()
+ })
+
+ it('DELETE with a Host reference and no ?force → 409 with the impact body', async () => {
+ installPool({})
+ const gateway = new MockGateway('mcp-host')
+ await seedHost(gateway, 'agent-a', primarySpec)
+
+ const res = await authed('delete', `/api/v1/admin/llm-models/${MODEL_ID}`, gateway).expect(409)
+ expect(res.body.error).toBe('model_in_use')
+ expect(res.body.impact.provider).toBe(PROVIDER)
+ expect(res.body.impact.model).toBe(MODEL)
+ expect(res.body.impact.hostsAffected).toEqual([
+ { namespace: 'mcp-host', name: 'agent-a', roles: ['primary'] },
+ ])
+ expect(res.body.impact.grantsAffected).toEqual([])
+ })
+
+ it('DELETE with a reference AND ?force=true → proceeds (204)', async () => {
+ installPool({})
+ const gateway = new MockGateway('mcp-host')
+ await seedHost(gateway, 'agent-a', primarySpec)
+
+ await authed('delete', `/api/v1/admin/llm-models/${MODEL_ID}?force=true`, gateway).expect(204)
+ })
+
+ it('DELETE with no references → deletes without 409 (204)', async () => {
+ installPool({})
+ const gateway = new MockGateway('mcp-host') // no hosts, no grants
+ await authed('delete', `/api/v1/admin/llm-models/${MODEL_ID}`, gateway).expect(204)
+ })
+
+ it('PUT enabled true→false with a reference and no ?force → 409', async () => {
+ installPool({ modelRow: makeModelRow({ enabled: true }) })
+ const gateway = new MockGateway('mcp-host')
+ await seedHost(gateway, 'agent-a', primarySpec)
+
+ const res = await authed('put', `/api/v1/admin/llm-models/${MODEL_ID}`, gateway)
+ .send({ enabled: false })
+ .expect(409)
+ expect(res.body.error).toBe('model_in_use')
+ expect(res.body.impact.hostsAffected).toHaveLength(1)
+ })
+
+ it('PUT enabled true→false with a reference AND ?force=true → 200', async () => {
+ installPool({ modelRow: makeModelRow({ enabled: true }) })
+ const gateway = new MockGateway('mcp-host')
+ await seedHost(gateway, 'agent-a', primarySpec)
+
+ await authed('put', `/api/v1/admin/llm-models/${MODEL_ID}?force=true`, gateway)
+ .send({ enabled: false })
+ .expect(200)
+ })
+
+ it('PUT that does NOT reduce availability (enabled stays true) → never 409 even with references', async () => {
+ installPool({ modelRow: makeModelRow({ enabled: true }) })
+ const gateway = new MockGateway('mcp-host')
+ await seedHost(gateway, 'agent-a', primarySpec)
+
+ // Re-enable / metadata edit: enabled true→true. The gate must not fire.
+ await authed('put', `/api/v1/admin/llm-models/${MODEL_ID}`, gateway)
+ .send({ enabled: true, display_name: 'Claude Haiku' })
+ .expect(200)
+ })
+
+ it('PUT enabled false→false (already disabled) → never 409', async () => {
+ installPool({ modelRow: makeModelRow({ enabled: false }) })
+ const gateway = new MockGateway('mcp-host')
+ await seedHost(gateway, 'agent-a', primarySpec)
+
+ await authed('put', `/api/v1/admin/llm-models/${MODEL_ID}`, gateway)
+ .send({ enabled: false })
+ .expect(200)
+ })
+
+ it('DELETE with a reference ONLY from a grant (no Hosts) → still 409', async () => {
+ installPool({ grantRows: [makeGrantRow()] })
+ const gateway = new MockGateway('mcp-host') // no hosts
+
+ const res = await authed('delete', `/api/v1/admin/llm-models/${MODEL_ID}`, gateway).expect(409)
+ expect(res.body.impact.hostsAffected).toEqual([])
+ expect(res.body.impact.grantsAffected).toEqual([
+ {
+ id: '22222222-2222-4222-8222-222222222222',
+ recipeNamespace: 'sandbox-recipes',
+ recipeName: 'nightly-summary',
+ capabilityFamily: 'promptBridge',
+ },
+ ])
+ })
+
+ // ── One test per Host source (primary / allowedModels / fallbacks) ──────────
+ for (const [label, spec, role] of [
+ ['primary (spec.model)', primarySpec, 'primary'],
+ ['allowedModels (spec.allowedModels[])', allowedModelsSpec, 'allowedModels'],
+ ['fallbacks (spec.llmPolicy.fallbacks[])', fallbackSpec, 'fallback'],
+ ] as const) {
+ it(`a reference ONLY from Host ${label} alone trips the 409`, async () => {
+ installPool({})
+ const gateway = new MockGateway('mcp-host')
+ await seedHost(gateway, 'agent-a', spec)
+
+ const res = await authed('delete', `/api/v1/admin/llm-models/${MODEL_ID}`, gateway).expect(
+ 409
+ )
+ expect(res.body.impact.hostsAffected).toEqual([
+ { namespace: 'mcp-host', name: 'agent-a', roles: [role] },
+ ])
+ })
+ }
+
+ it('detects Host references across the REAL enumerated namespaces (both host namespaces)', async () => {
+ // The route enumerates the actual host namespace set (config.hostsNamespace +
+ // config.namespace), LISTing each; MockGateway scopes by namespace, so this
+ // reflects real coverage rather than an unfiltered `'*'` dump.
+ expect(config.hostsNamespace).not.toBe(config.namespace) // precondition: two distinct namespaces
+ installPool({})
+ const gateway = new MockGateway('mcp-host')
+ await seedHost(gateway, 'agent-a', primarySpec, config.hostsNamespace)
+ await seedHost(gateway, 'agent-b', allowedModelsSpec, config.namespace)
+
+ const res = await authed('delete', `/api/v1/admin/llm-models/${MODEL_ID}`, gateway).expect(409)
+ const affected = (res.body.impact.hostsAffected as Array<{ namespace: string; name: string }>)
+ .map(h => `${h.namespace}/${h.name}`)
+ .sort()
+ expect(affected).toEqual(
+ [`${config.hostsNamespace}/agent-a`, `${config.namespace}/agent-b`].sort()
+ )
+ })
+
+ it('a Host referencing a DIFFERENT model does not trip the gate', async () => {
+ installPool({})
+ const gateway = new MockGateway('mcp-host')
+ await seedHost(gateway, 'agent-other', {
+ model: { provider: PROVIDER, name: 'some-other-model' },
+ })
+
+ await authed('delete', `/api/v1/admin/llm-models/${MODEL_ID}`, gateway).expect(204)
+ })
+
+ it('FAILS CLOSED: a Host LIST error rejects the destructive op (5xx), never a silent delete', async () => {
+ // The impact enumeration is a safety gate: if the K8s LIST fails, the gate
+ // must NOT let the delete through under-reported. computeModelImpact
+ // propagates → asyncHandler → 500, so the model is never removed.
+ installPool({})
+ const gateway = new MockGateway('mcp-host')
+ gateway.listResource = vi.fn(async () => {
+ throw new Error('k8s apiserver LIST failed')
+ })
+
+ await authed('delete', `/api/v1/admin/llm-models/${MODEL_ID}`, gateway).expect(500)
+ // The destructive DELETE against Postgres must never have run.
+ const ranDelete = mockPoolQuery.mock.calls.some(c =>
+ /DELETE FROM llm_allowed_models/.test(String(c[0]))
+ )
+ expect(ranDelete).toBe(false)
+ })
+
+ it('nit: PUT partial WITHOUT enabled (metadata-only) with references → 200 (gate not tripped)', async () => {
+ installPool({ modelRow: makeModelRow({ enabled: true }) })
+ const gateway = new MockGateway('mcp-host')
+ await seedHost(gateway, 'agent-a', primarySpec)
+
+ await authed('put', `/api/v1/admin/llm-models/${MODEL_ID}`, gateway)
+ .send({ display_name: 'Claude Haiku' })
+ .expect(200)
+ })
+})
diff --git a/control-api/test/services.llmModelImpact.test.ts b/control-api/test/services.llmModelImpact.test.ts
new file mode 100644
index 000000000..be9dfc8f5
--- /dev/null
+++ b/control-api/test/services.llmModelImpact.test.ts
@@ -0,0 +1,154 @@
+import { describe, expect, it } from 'vitest'
+import {
+ type ModelImpactSources,
+ computeModelImpact,
+ modelImpactHasReferences,
+} from '../src/services/llmModelImpact.js'
+import { mapGrantRow } from '../src/services/pluginWorkloadSdkDb.js'
+import { MockGateway } from './mockGateway.js'
+
+// Module-level tests for the impact enumerator. Host CRs come from the REAL
+// gateway producer (`createResource` → per-namespace `listResource`, T1); the
+// grant source is injected as the output of the REAL `mapGrantRow` (T1), never a
+// hand-built DTO. MockGateway.listResource(plural, ns) scopes by namespace, so
+// the per-namespace fan-out is exercised faithfully.
+
+const PROVIDER = 'claude'
+const MODEL = 'claude-haiku-4-5'
+
+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: [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,
+ }
+}
+
+function sourcesFrom(
+ gateway: MockGateway,
+ opts: { hostNamespaces?: string[]; grantRows?: unknown[] } = {}
+): ModelImpactSources {
+ return {
+ hostNamespaces: opts.hostNamespaces ?? ['mcp-host'],
+ listHostsInNamespace: namespace => gateway.listResource('hosts', namespace),
+ listGrantsForModel: async () =>
+ ((opts.grantRows ?? []) as Record<string, unknown>[]).map(mapGrantRow),
+ }
+}
+
+describe('computeModelImpact', () => {
+ it('reports EVERY role a single Host references the pair in', async () => {
+ const gateway = new MockGateway('mcp-host')
+ await gateway.createResource(
+ 'hosts',
+ {
+ metadata: { name: 'agent-a' },
+ spec: {
+ model: { provider: PROVIDER, name: MODEL }, // primary
+ allowedModels: [{ provider: PROVIDER, model: MODEL }], // allowedModels
+ llmPolicy: { fallbacks: [{ provider: PROVIDER, model: MODEL }] }, // fallback
+ },
+ },
+ 'mcp-host'
+ )
+
+ const impact = await computeModelImpact(PROVIDER, MODEL, sourcesFrom(gateway))
+ expect(impact.hostsAffected).toHaveLength(1)
+ expect(impact.hostsAffected[0].roles).toEqual(['primary', 'allowedModels', 'fallback'])
+ expect(modelImpactHasReferences(impact)).toBe(true)
+ })
+
+ it('returns no references when nothing points at the pair', async () => {
+ const gateway = new MockGateway('mcp-host')
+ await gateway.createResource(
+ 'hosts',
+ { metadata: { name: 'agent-a' }, spec: { model: { provider: PROVIDER, name: 'other' } } },
+ 'mcp-host'
+ )
+ const impact = await computeModelImpact(PROVIDER, MODEL, sourcesFrom(gateway))
+ expect(impact.hostsAffected).toEqual([])
+ expect(impact.grantsAffected).toEqual([])
+ expect(modelImpactHasReferences(impact)).toBe(false)
+ })
+
+ it('maps grant references through the real mapGrantRow', async () => {
+ const gateway = new MockGateway('mcp-host')
+ const impact = await computeModelImpact(
+ PROVIDER,
+ MODEL,
+ sourcesFrom(gateway, { grantRows: [makeGrantRow()] })
+ )
+ expect(impact.grantsAffected).toEqual([
+ {
+ id: '22222222-2222-4222-8222-222222222222',
+ recipeNamespace: 'sandbox-recipes',
+ recipeName: 'nightly-summary',
+ capabilityFamily: 'promptBridge',
+ },
+ ])
+ })
+
+ it('aggregates Host references across MULTIPLE namespaces (per-namespace scoping)', async () => {
+ const gateway = new MockGateway('mcp-host')
+ // MockGateway.listResource(plural, ns) filters by namespace, so a host in
+ // ns-b must NOT surface under an ns-a LIST — this exercises real scoping.
+ await gateway.createResource(
+ 'hosts',
+ { metadata: { name: 'agent-a' }, spec: { model: { provider: PROVIDER, name: MODEL } } },
+ 'ns-a'
+ )
+ await gateway.createResource(
+ 'hosts',
+ {
+ metadata: { name: 'agent-b' },
+ spec: { allowedModels: [{ provider: PROVIDER, model: MODEL }] },
+ },
+ 'ns-b'
+ )
+
+ const impact = await computeModelImpact(
+ PROVIDER,
+ MODEL,
+ sourcesFrom(gateway, { hostNamespaces: ['ns-a', 'ns-b'] })
+ )
+ const seen = impact.hostsAffected.map(h => `${h.namespace}/${h.name}`).sort()
+ expect(seen).toEqual(['ns-a/agent-a', 'ns-b/agent-b'])
+ })
+
+ it('FAILS LOUD: a namespace LIST error REJECTS instead of returning a partial impact', async () => {
+ const gateway = new MockGateway('mcp-host')
+ await gateway.createResource(
+ 'hosts',
+ { metadata: { name: 'agent-a' }, spec: { model: { provider: PROVIDER, name: MODEL } } },
+ 'ns-a'
+ )
+ const sources: ModelImpactSources = {
+ hostNamespaces: ['ns-a', 'ns-broken'],
+ listHostsInNamespace: async namespace => {
+ if (namespace === 'ns-broken') throw new Error('k8s LIST failed')
+ return gateway.listResource('hosts', namespace)
+ },
+ listGrantsForModel: async () => [],
+ }
+ await expect(computeModelImpact(PROVIDER, MODEL, sources)).rejects.toThrow('k8s LIST failed')
+ })
+})
diff --git a/control-api/test/services.llmModelImpactGrantQuery.test.ts b/control-api/test/services.llmModelImpactGrantQuery.test.ts
new file mode 100644
index 000000000..ecc349fa6
--- /dev/null
+++ b/control-api/test/services.llmModelImpactGrantQuery.test.ts
@@ -0,0 +1,32 @@
+import { afterEach, describe, expect, it, vi } from 'vitest'
+
+// Minimum coverage (T1/T3 discipline): the grant impact query must run the jsonb
+// containment against the MODEL param only — no provider filter. The full jsonb
+// `@>` semantics are exercised end-to-end in
+// `db.listGrantsReferencingModel.realPostgres.integration.test.ts` (skipped
+// without a real Postgres); this unit test pins that the right SQL + params reach
+// pool.query so the risky part is not stubbed away entirely.
+
+const mockPoolQuery = vi.fn()
+vi.mock('../src/db.js', () => ({
+ pool: { query: (...args: unknown[]) => mockPoolQuery(...args) },
+}))
+
+describe('listGrantsReferencingModel query', () => {
+ afterEach(() => vi.clearAllMocks())
+
+ it('matches by MODEL name only (no provider filter) and passes [model] to pool.query', async () => {
+ const { listGrantsReferencingModel } = await import('../src/services/pluginWorkloadSdkDb.js')
+ mockPoolQuery.mockResolvedValueOnce({ rows: [] })
+
+ await listGrantsReferencingModel('claude-haiku-4-5')
+
+ expect(mockPoolQuery).toHaveBeenCalledTimes(1)
+ const [sql, params] = mockPoolQuery.mock.calls[0] as [string, unknown[]]
+ expect(sql).toMatch(/allowed_models\s+@>\s+to_jsonb\(\$1::text\)/)
+ // The unsafe direction for a safety gate would be a provider filter — assert
+ // there is none, so a cross-provider allowed_models entry cannot be dropped.
+ expect(sql).not.toMatch(/provider\s*=/)
+ expect(params).toEqual(['claude-haiku-4-5'])
+ })
+})