Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure
TypeScript
feat(control-api): asymmetric no-worsening tolerance for the LLM allowlist write-gate (Pieza D)
Diego Zacarias3c07716d1a14
diff --git a/control-api/package-lock.json b/control-api/package-lock.jsonindex c47b8b39f..9bb4e2174 100644--- a/control-api/package-lock.json+++ b/control-api/package-lock.json@@ -1,12 +1,12 @@{"name": "clerum-control-api",- "version": "0.1.441",+ "version": "0.1.434","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "clerum-control-api",- "version": "0.1.441",+ "version": "0.1.434","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 6c2fdadf9..87c5b1e45 100644--- a/control-api/package.json+++ b/control-api/package.json@@ -1,6 +1,6 @@{"name": "clerum-control-api",- "version": "0.1.441",+ "version": "0.1.434","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/hostSpecValidation.ts b/control-api/src/routes/admin/hostSpecValidation.tsindex bc923e0e5..afa4ae825 100644--- a/control-api/src/routes/admin/hostSpecValidation.ts+++ b/control-api/src/routes/admin/hostSpecValidation.ts@@ -6,6 +6,15 @@ import {} from '@clerum/llm-providers'import { isModelAllowed as isModelAllowedDefault } from '../../services/llmAllowedModels.js'import { isPlainObject } from '../../utils/isPlainObject.js'+import {+ type HostSpecIncoherenceToleratedEvent,+ type IncoherenceToleranceGate,+} from './hostWriteGateAudit.js'+import {+ type CoverageSet,+ isNonWorseningToleration,+ offeredKey,+} from './modelAllowlistTolerance.js'// A Kubernetes Secret/ConfigMap data key: `[-._a-zA-Z0-9]`, max 253 chars.// A fallback `credentialSlot` names a key inside the chatllm-api-keys Secret, so@@ -46,6 +55,26 @@ export interface HostSpecValidationDeps {isModelAllowed: (provider: string, model: string) => Promise<boolean>}+/**+ * Per-write context for the no-worsening tolerance (Pieza D). ABSENT on create+ * (there is no stored CR, so tolerance can never apply — a fresh spec may not+ * introduce a disabled model). Supplied on update by the admin facade, which+ * reads the stored Host CR before the write.+ */+export interface HostSpecValidationContext {+ /** The stored Host CR spec read before this write; absent on create. */+ stored?: Record<string, unknown>+ /** Host identity for the audit event payload. */+ hostRef?: { namespace: string; name: string }+ /**+ * OUTPUT sink. When the write is ACCEPTED, the validator appends here the+ * audit events for each tolerated gate. It does NOT emit them: the caller+ * emits only AFTER the write persists (mini-spec 01), so a write that a later+ * step (secretRef check, K8s conflict) rejects leaves no audit record.+ */+ tolerations?: HostSpecIncoherenceToleratedEvent[]+}+// spec.lifecycle follows the facade's contract for optional spec objects,// exactly like spec.desktop: the admin facade forwards body.spec to the K8s// client WHOLESALE (resourceService.updateResource is a full replace via@@ -94,8 +123,20 @@ const HostLifecycleSchema = z*/export async function validateHostSpec(spec: Record<string, unknown>,- deps: HostSpecValidationDeps = { isModelAllowed: isModelAllowedDefault }+ deps: HostSpecValidationDeps = { isModelAllowed: isModelAllowedDefault },+ context: HostSpecValidationContext = {}): Promise<{ errors: Array<{ field: string; message: string }> } | null> {+ // Contract guard (mini-spec 01): passing `stored` enables tolerance, so the+ // caller MUST also pass the `tolerations` sink — otherwise a tolerated pair+ // would be accepted while its audit event is silently dropped ("never silent"+ // violated). Couple them: a caller that supplies `stored` without a sink is a+ // programming error, not a silent degrade.+ if (context.stored !== undefined && context.tolerations === undefined) {+ throw new Error(+ 'validateHostSpec: context.tolerations sink is required when context.stored is provided (a tolerated pair must never be emitted silently)'+ )+ }+// Structural (sync, zod) checks first: accumulate approval + lifecycle shape// errors so a payload bad in both surfaces both — dev's stateless contract// pinned by test/routes.resources.test.ts.@@ -124,6 +165,18 @@ export async function validateHostSpec(}if (structuralErrors.length > 0) return { errors: structuralErrors }+ // No-worsening tolerance context (Pieza D), computed once and shared by the 3+ // global-allowlist gates below. On create `context.stored` is absent, so+ // `storedPairs` is empty and no gate can tolerate — a fresh spec may never+ // introduce a disabled model.+ const tol: HostToleranceBundle = {+ context,+ storedRoles: storedRoleSets(context.stored),+ incomingCov: hostCoverage(spec),+ storedCov: hostCoverage(context.stored),+ pending: [],+ }+// R3 model allowlist. Enforcement is keyed on the PRESENCE of `spec.model.name`// (not just a truthy string) so a non-string/garbage name cannot slip past the// gate — that is strictly fail-closed. A spec with no `name` key at all is left@@ -153,7 +206,7 @@ export async function validateHostSpec(}}const allowed = await deps.isModelAllowed(provider, name)- if (!allowed) {+ if (!allowed && !toleratePair(provider, name, 'primary', tol)) {return {errors: [{@@ -171,28 +224,163 @@ export async function validateHostSpec(// (same fail-closed gate as spec.model.name), so a broken fallback is caught// on write instead of surfacing only during the incident it was meant to// absorb (spec V16). `credentialSlot`, when present, is format-checked only.- const policyErrors = await validateLlmPolicy(spec.llmPolicy, deps)+ const policyErrors = await validateLlmPolicy(spec.llmPolicy, deps, tol)if (policyErrors) return policyErrors// Topic 3a per-host allowlist. Runs AFTER the global-allowlist gates above, so// by the time coherence is checked the primary + fallbacks are already known// to be valid GLOBAL pairs; this narrows them to the host's offered subset.- const allowedModelsErrors = await validateAllowedModels(spec, deps)+ const allowedModelsErrors = await validateAllowedModels(spec, deps, tol)if (allowedModelsErrors) return allowedModelsErrors+ // The write PASSED validation: hand the queued tolerations to the caller via+ // the context sink. The caller emits them only AFTER the write persists — never+ // here, so a later rejection (secretRef check, K8s conflict) leaves no audit+ // record (mini-spec 01, persist-ordering fix).+ if (context.tolerations) context.tolerations.push(...tol.pending)+return null}-// Separator for the offered-pair set key. A NUL byte can appear in neither a-// provider id nor a model id (both are validated at the global-allowlist DB-// layer against space/NUL-free patterns), so distinct `(provider, model)` pairs-// can never collide onto the same key — even though a model id may itself carry-// spaces (Azure deployment names).-const OFFERED_KEY_SEP = '\u0000'+/**+ * The stored `(provider, model)` pairs a Host spec references, ranked by ROLE+ * ACTIVENESS (mini-spec 01 v2 — role-scoped tolerance):+ *+ * - `primary` — the ACTIVE slot (`spec.model`), the default mcp-host routes.+ * - `any` — every referenced pair, across primary + fallbacks + subset.+ *+ * Tolerance at the ACTIVE `primary` gate is strict (`P ∈ primary`), so a disabled+ * pair that was only a fallback/subset entry cannot be PROMOTED to the active+ * default. The non-active gates (fallback, subset) accept `P ∈ any`, so DEMOTING+ * a disabled pair from primary to a less-active role — pure non-worsening — is+ * tolerated. This mirrors the grant seam (`storedDefaultTarget` strict for the+ * default slot, `storedAnyTarget` for the rest), keeping Host and grants+ * symmetric (D4). Both sets are empty when there is no stored spec (create), so+ * tolerance never applies to a fresh Host.+ */+interface StoredRoleSets {+ /** The active slot: `spec.model`. */+ primary: ReadonlySet<string>+ /** Union of every referenced pair (primary ∪ fallbacks ∪ allowedModels). */+ any: ReadonlySet<string>+}++function storedRoleSets(stored: Record<string, unknown> | undefined): StoredRoleSets {+ const primary = new Set<string>()+ const any = new Set<string>()+ if (!isPlainObject(stored)) return { primary, any }+ const model = stored.model+ if (+ isPlainObject(model) &&+ typeof model.name === 'string' &&+ typeof model.provider === 'string'+ ) {+ const name = model.name.trim()+ const provider = model.provider.trim()+ if (name && provider) {+ const key = offeredKey(provider, name)+ primary.add(key)+ any.add(key)+ }+ }+ const llmPolicy = stored.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 fbModel = typeof entry.model === 'string' ? entry.model.trim() : ''+ if (provider && fbModel) any.add(offeredKey(provider, fbModel))+ }+ }+ const allowedModels = stored.allowedModels+ if (Array.isArray(allowedModels)) {+ for (const entry of allowedModels) {+ if (!isPlainObject(entry)) continue+ const provider = typeof entry.provider === 'string' ? entry.provider.trim() : ''+ const model2 = typeof entry.model === 'string' ? entry.model.trim() : ''+ if (provider && model2) any.add(offeredKey(provider, model2))+ }+ }+ return { primary, any }+}++/**+ * Coverage a Host spec offers, for condition (b). `spec.allowedModels` absent,+ * non-array, or EMPTY means "offers the full global allowlist" (Topic 3a+ * back-compat), represented by the `'UNIVERSAL'` sentinel; a non-empty array is+ * the finite set of offered `(provider, model)` keys.+ */+function hostCoverage(spec: Record<string, unknown> | undefined): CoverageSet {+ if (!isPlainObject(spec)) return 'UNIVERSAL'+ const allowedModels = spec.allowedModels+ if (!Array.isArray(allowedModels) || allowedModels.length === 0) return 'UNIVERSAL'+ const keys = new Set<string>()+ for (const entry of allowedModels) {+ if (!isPlainObject(entry)) continue+ const provider = typeof entry.provider === 'string' ? entry.provider.trim() : ''+ const model = typeof entry.model === 'string' ? entry.model.trim() : ''+ if (provider && model) keys.add(offeredKey(provider, model))+ }+ return keys+}++/**+ * Shared no-worsening decision for a Host write gate. Returns `true` (and emits+ * the audit event) when the disallowed `(provider, model)` pair may be tolerated+ * because the write does not worsen a pre-existing incoherence.+ */++/** The precomputed no-worsening tolerance inputs, shared by the 3 Host gates. */+interface HostToleranceBundle {+ context: HostSpecValidationContext+ storedRoles: StoredRoleSets+ incomingCov: CoverageSet+ storedCov: CoverageSet+ /**+ * Audit events for tolerated gates, ACCUMULATED here and copied into+ * `context.tolerations` only once `validateHostSpec` confirms the write is+ * ACCEPTED (returns null). Never emitted by the validator — the caller emits+ * after the write persists. A write that a later gate hard-rejects (422)+ * leaves no audit record. One event per tolerated gate decision.+ */+ pending: HostSpecIncoherenceToleratedEvent[]+}-/** Stable key for an offered `(provider, model)` pair. */-function offeredKey(provider: string, model: string): string {- return `${provider}${OFFERED_KEY_SEP}${model}`+/**+ * Decide whether a disallowed `(provider, model)` may be tolerated at `gate`+ * because the write does not worsen a pre-existing incoherence AND the pair does+ * not GAIN activeness (role-scoped, mini-spec 01 v2). On tolerance, QUEUES the+ * audit event (not emitted until the whole write persists) and returns true so+ * the gate skips its rejection.+ */+function toleratePair(+ provider: string,+ model: string,+ gate: 'primary' | 'fallback' | 'subset',+ tol: HostToleranceBundle+): boolean {+ // Role-scoped membership. The ACTIVE `primary` slot is strict: the pair must+ // have been the stored primary (blocks promotion). Non-active gates accept any+ // stored role (allows demotion — pure non-worsening).+ const storedRoleSet = gate === 'primary' ? tol.storedRoles.primary : tol.storedRoles.any+ const tolerated = isNonWorseningToleration({+ pairKey: offeredKey(provider, model),+ storedReferencedPairKeys: storedRoleSet,+ incomingCoverage: tol.incomingCov,+ storedCoverage: tol.storedCov,+ })+ if (!tolerated) return false+ tol.pending.push({+ resourceKind: 'host',+ namespace: tol.context.hostRef?.namespace ?? '',+ name: tol.context.hostRef?.name ?? '',+ provider,+ model,+ gate,+ offeredBefore: tol.storedCov,+ offeredAfter: tol.incomingCov,+ })+ return true}/**@@ -212,7 +400,8 @@ function offeredKey(provider: string, model: string): string {*/async function validateAllowedModels(spec: Record<string, unknown>,- deps: HostSpecValidationDeps+ deps: HostSpecValidationDeps,+ tol: HostToleranceBundle): Promise<{ errors: Array<{ field: string; message: string }> } | null> {const allowedModels = spec.allowedModelsif (allowedModels === undefined) return null@@ -251,9 +440,11 @@ async function validateAllowedModels(}// Global-allowlist gate LAST (only async/DB check): a pair not in the global- // catalog can never be offered by a host.+ // catalog can never be offered by a host — unless tolerating a pre-existing+ // incoherence this write does not worsen (Pieza D). A tolerated pair is still+ // added to `offered` so the coherence gate below sees the host as offering it.const allowed = await deps.isModelAllowed(provider, model)- if (!allowed) {+ if (!allowed && !toleratePair(provider, model, 'subset', tol)) {return {errors: [{@@ -328,7 +519,8 @@ async function validateAllowedModels(*/async function validateLlmPolicy(llmPolicy: unknown,- deps: HostSpecValidationDeps+ deps: HostSpecValidationDeps,+ tol: HostToleranceBundle): Promise<{ errors: Array<{ field: string; message: string }> } | null> {if (llmPolicy === undefined) return nullif (!isPlainObject(llmPolicy)) {@@ -405,9 +597,10 @@ async function validateLlmPolicy(}// Allowlist gate LAST: it is the only async (DB) check, so cheap structural- // rejections above avoid a needless query.+ // rejections above avoid a needless query. Tolerated (Pieza D) when the pair+ // is a pre-existing incoherence this write does not worsen.const allowed = await deps.isModelAllowed(provider, model)- if (!allowed) {+ if (!allowed && !toleratePair(provider, model, 'fallback', tol)) {return {errors: [{diff --git a/control-api/src/routes/admin/hostWriteGateAudit.ts b/control-api/src/routes/admin/hostWriteGateAudit.tsnew file mode 100644index 000000000..fcfb6f986--- /dev/null+++ b/control-api/src/routes/admin/hostWriteGateAudit.ts@@ -0,0 +1,92 @@+import { rootLogger } from '../../observability/logger.js'+import { type CoverageSet, OFFERED_KEY_SEP } from './modelAllowlistTolerance.js'++/**+ * Audit signal for the asymmetric "no-worsening" tolerance of the global+ * `model_not_allowed` write gate (spec Fase 2, Pieza D).+ *+ * When a gate tolerates a `(provider, model)` pair that is NOT in the operator+ * allowlist — because the write does not worsen a pre-existing incoherence+ * (`isNonWorseningToleration`) — it MUST never be silent. Each tolerated gate+ * decision emits exactly one structured audit event through this single shared+ * helper, so the four call sites (the 3 Host gates + the grant gate) cannot+ * diverge on the event shape or forget to emit. Emission is deferred until the+ * write PERSISTS: the write gates only QUEUE tolerations, and the caller emits+ * them after the K8s/DB write succeeds — a write rejected by a later gate+ * (422/400) or that fails to persist (K8s 409, DB error) leaves no audit record,+ * so the trail records only tolerations that actually took hold.+ * (A single pair filling two roles — e.g. primary AND a `spec.allowedModels`+ * entry — is a distinct decision at each gate and legitimately emits once per+ * gate, each event carrying its own `gate`.)+ *+ * This is an OBSERVABILITY signal, not a governed authority mutation: the Host/+ * grant write that provoked the tolerance is already recorded in the governed+ * administrative trail. So it rides the audit-only `rootLogger.warn` channel+ * (the same idiom as `namespaceAudit`'s SECURITY events), NOT the tamper-evident+ * tracing pipeline — which, fed fabricated write-gate context, would only+ * degrade that pipeline's guarantees.+ */+export const HOST_SPEC_INCOHERENCE_TOLERATED_EVENT = 'host_spec_incoherence_tolerated' as const++/** Which of the four global-allowlist gates tolerated the pair. */+export type IncoherenceToleranceGate = 'primary' | 'subset' | 'fallback' | 'grant'++export interface HostSpecIncoherenceToleratedEvent {+ /** The resource whose write was tolerated. */+ resourceKind: 'host' | 'grant'+ /** Namespace of the Host CR / grant recipe. */+ namespace: string+ /** Host name / grant recipe name. */+ name: string+ /** The disallowed pair that was tolerated. */+ provider: string+ model: string+ /** The gate that tolerated it. */+ gate: IncoherenceToleranceGate+ /** Coverage the record offered BEFORE this write (evidence of no-worsening). */+ offeredBefore: CoverageSet+ /** Coverage the record offers AFTER this write. */+ offeredAfter: CoverageSet+}++/** Callback shape injected into the write gates so emission is testable via the seam. */+export type EmitHostSpecIncoherenceTolerated = (event: HostSpecIncoherenceToleratedEvent) => void++function coverageForLog(+ coverage: CoverageSet+): 'universal' | Array<{ provider?: string; model: string }> {+ if (coverage === 'UNIVERSAL') return 'universal'+ // Host coverage keys are `offeredKey(provider, model)` joined by a NUL byte;+ // split them back into readable pairs so the structured log carries no control+ // char. GRANT coverage keys are plain model names (grant `allowed_models` is a+ // flat, provider-less list) — those have no separator, so we log just `model`+ // (the event's top-level `provider` already carries the grant's provider).+ return [...coverage].sort().map(key => {+ const sep = key.indexOf(OFFERED_KEY_SEP)+ return sep === -1+ ? { model: key }+ : { provider: key.slice(0, sep), model: key.slice(sep + OFFERED_KEY_SEP.length) }+ })+}++/**+ * Default emitter: a single structured audit-log line. Callers inject this by+ * default; tests inject a spy through the same seam.+ */+export const emitHostSpecIncoherenceTolerated: EmitHostSpecIncoherenceTolerated = event => {+ rootLogger.warn(+ {+ module: 'host-write-gate',+ event: HOST_SPEC_INCOHERENCE_TOLERATED_EVENT,+ resourceKind: event.resourceKind,+ namespace: event.namespace,+ name: event.name,+ provider: event.provider,+ model: event.model,+ gate: event.gate,+ offeredBefore: coverageForLog(event.offeredBefore),+ offeredAfter: coverageForLog(event.offeredAfter),+ },+ `tolerated pre-existing model_not_allowed incoherence on ${event.resourceKind} write (no worsening)`+ )+}diff --git a/control-api/src/routes/admin/modelAllowlistTolerance.ts b/control-api/src/routes/admin/modelAllowlistTolerance.tsnew file mode 100644index 000000000..03ecef6a3--- /dev/null+++ b/control-api/src/routes/admin/modelAllowlistTolerance.ts@@ -0,0 +1,101 @@+/**+ * Asymmetric "no-worsening" tolerance for the global `model_not_allowed` write+ * gate (spec Fase 2, Pieza D — antecedente 02 §3.4).+ *+ * PROBLEM (gap G3 — the editability trap). Once a Host's default (or any model a+ * Host/grant references) falls out of the operator allowlist (`enabled=false`),+ * the on-write `model_not_allowed` gate rejects EVERY future edit of that record+ * with 422 — including the very edit that would fix it. The operator we ask to+ * correct it cannot even open the record.+ *+ * FIX. Tolerate a `(provider, model)` pair that is NOT in the allowlist ON WRITE+ * — but ONLY when the write does not make things worse. Tolerance is+ * "no-worsening", NOT "unchanged": all three conditions must hold.+ *+ * (a) the offending `(provider, model)` pair is IDENTICAL to one already+ * referenced by the STORED record (CR/grant read before this write), AND+ * (b) the incoming coverage (`spec.allowedModels` / grant `allowed_models`) is+ * a SUPERSET of the stored coverage — the write cannot remove coverage,+ * AND+ * (c) the incoherence ALREADY existed in the stored record (the pair was+ * already outside the allowlist before this write).+ *+ * Why (b) is load-bearing — the two-step bypass it closes:+ * write-1: `allowedModels=[M], model=M` (accepted while M is enabled)+ * …M is later disabled globally…+ * write-2: reduce the subset, keep `model=M` intact+ * Without (b), write-2 would be tolerated (pair unchanged) and the operator+ * would have quietly shrunk a host's offered set around a now-disabled model.+ * Requiring incoming ⊇ stored rejects write-2 with the original 422.+ *+ * Why (c) is entailed by (a) here, not a second DB read. Tolerance is only ever+ * consulted for a pair the gate JUST found to be disallowed against the CURRENT+ * allowlist snapshot. The allowlist is a single snapshot per write, so a pair+ * that is (a) present in the stored record AND currently disallowed was+ * necessarily already disallowed while stored — i.e. the incoherence pre-existed.+ * A brand-new disallowed pair (absent from the stored record) fails (a) and is+ * therefore never tolerated: this is NOT an allowlist bypass for new models.+ *+ * This module is a PURE decision function `(stored, incoming) → tolerateQ` with+ * no I/O, so it is exhaustively property-tested (fast-check) and shared verbatim+ * by all four call sites (the 3 Host gates + the grant gate) — one predicate, no+ * drift.+ */++// A NUL byte can appear in neither a provider id nor a model id (both validated+// against space/NUL-free patterns at the global-allowlist DB layer), so distinct+// `(provider, model)` pairs can never collide onto the same key — even though a+// model id may itself carry spaces (Azure deployment names).+export const OFFERED_KEY_SEP = '\u0000'++/** Stable key for a `(provider, model)` pair. */+export function offeredKey(provider: string, model: string): string {+ return `${provider}${OFFERED_KEY_SEP}${model}`+}++/**+ * Coverage the record offers. A finite `Set` of coverage keys, or the sentinel+ * `'UNIVERSAL'` for "offers everything" (an absent/empty `spec.allowedModels`,+ * which the Host gate treats as the full global allowlist). `'UNIVERSAL'` is the+ * top element: it is a superset of every finite set and of itself, and no finite+ * set is a superset of it.+ */+export type CoverageSet = ReadonlySet<string> | 'UNIVERSAL'++/** True when `incoming` covers at least everything `stored` covered (incoming ⊇ stored). */+export function coverageIsSuperset(incoming: CoverageSet, stored: CoverageSet): boolean {+ if (incoming === 'UNIVERSAL') return true+ // A finite incoming set can never re-cover a previously-universal offering:+ // narrowing "everything" to a finite list strictly removes coverage.+ if (stored === 'UNIVERSAL') return false+ for (const key of stored) {+ if (!incoming.has(key)) return false+ }+ return true+}++export interface NonWorseningToleranceInput {+ /** Key (`offeredKey`) of the pair the gate just found disallowed. */+ pairKey: string+ /** Keys of every `(provider, model)` pair referenced by the STORED record. */+ storedReferencedPairKeys: ReadonlySet<string>+ /** Coverage the incoming write offers. */+ incomingCoverage: CoverageSet+ /** Coverage the stored record offered. */+ storedCoverage: CoverageSet+}++/**+ * Decide whether a disallowed pair may be tolerated on write because the write+ * does not worsen the situation. Encodes (a)+(c) as membership of the stored+ * referenced-pair set and (b) as the coverage-superset check. Returns `false`+ * for a create (empty `storedReferencedPairKeys`), so a fresh record can never+ * introduce a disabled model under tolerance.+ */+export function isNonWorseningToleration(input: NonWorseningToleranceInput): boolean {+ // (a) + (c): the offending pair must already be referenced by the stored+ // record. On create the stored set is empty, so this is always false.+ if (!input.storedReferencedPairKeys.has(input.pairKey)) return false+ // (b): the incoming write may not remove coverage.+ return coverageIsSuperset(input.incomingCoverage, input.storedCoverage)+}diff --git a/control-api/src/routes/admin/pluginWorkloadSdk.ts b/control-api/src/routes/admin/pluginWorkloadSdk.tsindex 2800dd4f6..5aae16b21 100644--- a/control-api/src/routes/admin/pluginWorkloadSdk.ts+++ b/control-api/src/routes/admin/pluginWorkloadSdk.ts@@ -28,6 +28,16 @@ import {upsertGrant,} from '../../services/pluginWorkloadSdkDb.js'import { isPlainObject } from '../../utils/isPlainObject.js'+import {+ type EmitHostSpecIncoherenceTolerated,+ type HostSpecIncoherenceToleratedEvent,+ emitHostSpecIncoherenceTolerated as emitHostSpecIncoherenceToleratedDefault,+} from './hostWriteGateAudit.js'+import {+ type CoverageSet,+ isNonWorseningToleration,+ offeredKey,+} from './modelAllowlistTolerance.js'// ─── Plugin Workload SDK — admin routes (plan §2.6) ──────────────────────// Admin auth is enforced upstream by the control-ui auth gate in app.ts@@ -251,7 +261,20 @@ function parsePromptTargets(value: unknown, res: Response): PluginWorkloadSdkProreturn targets}-export function createAdminPluginWorkloadSdkRouter(): Router {+export interface AdminPluginWorkloadSdkRouterDeps {+ /**+ * Emit the audit signal for a tolerated pre-existing model_not_allowed+ * incoherence on a grant write (Pieza D). Injected so the "never silent"+ * guarantee is testable through the seam; defaults to the shared emitter.+ */+ emitIncoherenceTolerated?: EmitHostSpecIncoherenceTolerated+}++export function createAdminPluginWorkloadSdkRouter(+ deps: AdminPluginWorkloadSdkRouterDeps = {}+): Router {+ const emitIncoherenceTolerated =+ deps.emitIncoherenceTolerated ?? emitHostSpecIncoherenceToleratedDefaultconst router = Router()router.use('/admin/plugin-workload-sdk', createPluginWorkloadSdkAdminRateLimit())@@ -371,6 +394,10 @@ export function createAdminPluginWorkloadSdkRouter(): Router {// provider is resolved, every allowedModels entry must exist enabled under// that provider in the `llm_allowed_models` allowlist (checked below).let provider: string | undefined+ // Pieza D — queued grant tolerations, flushed only once the write is+ // ACCEPTED (right before upsert). A grant rejected by a later 400 leaves no+ // audit record.+ const pendingGrantTolerations: HostSpecIncoherenceToleratedEvent[] = []if (capabilityFamily === 'promptBridge') {const rawProvider = typeof body.provider === 'string' ? body.provider.trim() : ''if (!rawProvider) {@@ -400,9 +427,73 @@ export function createAdminPluginWorkloadSdkRouter(): Router {target.model,])}+ // Pieza D — role-scoped no-worsening tolerance (editability trap, mini-spec+ // 01). A grant that references a model later disabled globally would+ // otherwise be uneditable (every save 400s `model_not_allowed`). Tolerate a+ // disabled `(provider, model)` iff (b) the incoming `allowed_models` does+ // NOT shrink the stored coverage AND it kept its ROLE: the incoming DEFAULT+ // target (`promptTargets[0]`) is tolerated only if it was the stored default+ // target; a NON-default target only if it was any stored target (demotion is+ // not worsening). Promoting a disabled non-default target to the default slot+ // is NOT tolerated. A brand-new disabled model is never tolerated. The stored+ // grant is read lazily — only when a candidate rejection appears — so the+ // all-enabled happy path keeps its single-query cost.+ const incomingDefaultKey = offeredKey(promptTargets[0]!.provider, promptTargets[0]!.model)+ let storedLoaded = false+ let storedDefaultTarget = new Set<string>()+ let storedAnyTarget = new Set<string>()+ // Grant `allowed_models` is a flat model-name list; treat it as a literal+ // finite coverage set (NOT the Host UNIVERSAL-on-empty semantics) so an+ // emptied list is a strict reduction, not a widening.+ const incomingCoverage: CoverageSet = new Set(allowedModels)+ let storedCoverage: CoverageSet = new Set<string>()+ const loadStoredGrant = async (): Promise<void> => {+ if (storedLoaded) return+ storedLoaded = true+ const storedGrant = (await listGrants({ recipeNamespace, recipeName }))?.find(+ existing => existing.capabilityFamily === capabilityFamily+ )+ const storedTargets = storedGrant?.promptTargets ?? []+ storedDefaultTarget = new Set(+ storedTargets[0] ? [offeredKey(storedTargets[0].provider, storedTargets[0].model)] : []+ )+ storedAnyTarget = new Set(storedTargets.map(t => offeredKey(t.provider, t.model)))+ storedCoverage = new Set(storedGrant?.allowedModels ?? [])+ }for (const [targetProvider, targetModels] of modelsByProvider) {const enabled = new Set(await listEnabledModelNamesForProvider(targetProvider))- const offenders = targetModels.filter(model => !enabled.has(model))+ const rawOffenders = targetModels.filter(model => !enabled.has(model))+ if (rawOffenders.length === 0) continue+ await loadStoredGrant()+ const offenders: string[] = []+ for (const model of rawOffenders) {+ const pairKey = offeredKey(targetProvider, model)+ // Role of the offending pair in the INCOMING grant: the default slot+ // (`promptTargets[0]`) must have been the stored default; any other+ // target may have been any stored target.+ const storedRoleSet =+ pairKey === incomingDefaultKey ? storedDefaultTarget : storedAnyTarget+ const tolerated = isNonWorseningToleration({+ pairKey,+ storedReferencedPairKeys: storedRoleSet,+ incomingCoverage,+ storedCoverage,+ })+ if (tolerated) {+ pendingGrantTolerations.push({+ resourceKind: 'grant',+ namespace: recipeNamespace,+ name: recipeName,+ provider: targetProvider,+ model,+ gate: 'grant',+ offeredBefore: storedCoverage,+ offeredAfter: incomingCoverage,+ })+ } else {+ offenders.push(model)+ }+ }if (offenders.length > 0) {res.status(400).json({error: 'model_not_allowed',@@ -451,6 +542,9 @@ export function createAdminPluginWorkloadSdkRouter(): Router {},(req as UiAuthedRequest).adminAuth!.sub)+ // Grant PERSISTED: NOW emit any Pieza D tolerations (never before the upsert+ // lands, so a failed upsert leaves no audit record — mini-spec 01).+ for (const event of pendingGrantTolerations) emitIncoherenceTolerated(event)res.status(200).json({ grant })}))diff --git a/control-api/src/routes/admin/resources.ts b/control-api/src/routes/admin/resources.tsindex 6c00d42d0..74a088e38 100644--- a/control-api/src/routes/admin/resources.ts+++ b/control-api/src/routes/admin/resources.ts@@ -19,6 +19,10 @@ import {} from './communicationChannelSpecHelpers.js'import { validateHostSecretRef } from './hostSecrets.js'import { validateHostSpec } from './hostSpecValidation.js'+import {+ type HostSpecIncoherenceToleratedEvent,+ emitHostSpecIncoherenceTolerated,+} from './hostWriteGateAudit.js'const PROVIDER_SETTINGS_FIELDS: Readonly<Record<string, readonly string[]>> = {telegramSettings: ['botHandle', 'replyOnlyWhenMentioned'],@@ -482,7 +486,11 @@ export function createAdminResourcesRouter(gateway: K8sGateway): Router {// Early validation for Host specs — spec.approval.tools shape + R3 model// allowlist enforcement (fail-closed for a declared spec.model.name).if (plural === 'hosts' && body.spec) {- const issue = await validateHostSpec(body.spec)+ // Create: no stored CR, so the no-worsening tolerance (Pieza D) can never+ // apply — a fresh Host may not introduce a disabled model.+ const issue = await validateHostSpec(body.spec, undefined, {+ hostRef: { namespace: ns, name: body.metadata.name },+ })if (issue) {res.status(422).json(issue)return@@ -546,6 +554,9 @@ export function createAdminResourcesRouter(gateway: K8sGateway): Router {}spec: Record<string, unknown>}+ // Pieza D tolerations granted during Host validation, emitted only after+ // the CR persists (below). Empty for every non-host / non-tolerated write.+ const hostTolerations: HostSpecIncoherenceToleratedEvent[] = []if (plural === 'communicationchannels' && body.spec) {const errors = validateCommunicationChannelSpec(body.spec)@@ -568,7 +579,28 @@ export function createAdminResourcesRouter(gateway: K8sGateway): Router {}if (plural === 'hosts' && body.spec) {- const issue = await validateHostSpec(body.spec)+ // Update: read the stored CR so the write gate can tolerate a pre-existing+ // model_not_allowed incoherence this write does not worsen (Pieza D — the+ // editability trap). If the stored CR cannot be read, tolerance is skipped+ // (fail-closed: the gate behaves exactly as before this feature).+ let storedHostSpec: Record<string, unknown> | undefined+ try {+ const existing = (await gateway.getResource(plural, req.params.name, ns)) as {+ spec?: Record<string, unknown>+ } | null+ storedHostSpec =+ existing?.spec && typeof existing.spec === 'object' ? existing.spec : undefined+ } catch {+ storedHostSpec = undefined+ }+ const issue = await validateHostSpec(body.spec, undefined, {+ stored: storedHostSpec,+ hostRef: { namespace: ns, name: req.params.name },+ // Sink for tolerations granted by validation; emitted below ONLY after+ // the CR persists (mini-spec 01), so a secretRef 422 or a K8s conflict+ // leaves no audit record.+ tolerations: hostTolerations,+ })if (issue) {res.status(422).json(issue)return@@ -627,6 +659,9 @@ export function createAdminResourcesRouter(gateway: K8sGateway): Router {}try {const updated = await gateway.updateResource(plural, req.params.name, updateBody, ns)+ // Host CR persisted: NOW emit any Pieza D tolerations (never before the+ // write lands, so a K8s conflict/error leaves no audit record).+ for (const event of hostTolerations) emitHostSpecIncoherenceTolerated(event)if (plural === 'communicationchannels' && body.spec) {const missingField = missingPersistedProviderSetting(updateBody.spec, updated)if (missingField) {diff --git a/control-api/src/services/pluginWorkloadSdkDb.ts b/control-api/src/services/pluginWorkloadSdkDb.tsindex b376e3fb2..01569d5b0 100644--- a/control-api/src/services/pluginWorkloadSdkDb.ts+++ b/control-api/src/services/pluginWorkloadSdkDb.ts@@ -324,7 +324,7 @@ function promptTargets(value: unknown): PluginWorkloadSdkPromptTarget[] {})}-function mapGrantRow(row: Record<string, unknown>): PluginWorkloadSdkGrant {+export function mapGrantRow(row: Record<string, unknown>): PluginWorkloadSdkGrant {const family = row.capability_familyif (!PLUGIN_WORKLOAD_SDK_FAMILIES.includes(family as PluginWorkloadSdkFamily)) {throw new Error(`unknown capability_family from db: ${String(family)}`)diff --git a/control-api/test/routes.adminPluginWorkloadSdk.test.ts b/control-api/test/routes.adminPluginWorkloadSdk.test.tsindex 74c7ba2e1..7a8a0d30a 100644--- a/control-api/test/routes.adminPluginWorkloadSdk.test.ts+++ b/control-api/test/routes.adminPluginWorkloadSdk.test.ts@@ -501,6 +501,252 @@ describe('routes/admin/pluginWorkloadSdk — grants', () => {expect(sdkDb.upsertGrant).not.toHaveBeenCalled()})+ // ── Pieza D: no-worsening tolerance for grant `allowed_models` (G3) ─────────+ describe('no-worsening tolerance', () => {+ const buildAppWithEmit = (emit: (event: unknown) => void) => {+ const app = express()+ app.use(express.json())+ app.use((req, _res, next) => {+ ;(req as unknown as { adminAuth: { sub?: string } }).adminAuth = { sub: DEFAULT_ADMIN_SUB }+ next()+ })+ app.use(createAdminPluginWorkloadSdkRouter({ emitIncoherenceTolerated: emit as never }))+ return app+ }+ // T1: derive the stored grant through the real row producer (`mapGrantRow`, the+ // same mapper `listGrants` uses) rather than hand-shaping a grant object, so+ // the fixture cannot drift from what the DB layer actually emits.+ const makeStoredGrant = (+ over: { promptTargets?: unknown; allowedModels?: string[] } = {}+ ): sdkDb.PluginWorkloadSdkGrant =>+ sdkDb.mapGrantRow({+ id: 'g-stored',+ recipe_namespace: validGrantBody.recipeNamespace,+ recipe_name: validGrantBody.recipeName,+ capability_family: 'promptBridge',+ provider: 'zai',+ allowed_models: over.allowedModels ?? validGrantBody.allowedModels,+ prompt_targets: over.promptTargets ?? validGrantBody.promptTargets,+ created_at: '2026-01-01T00:00:00.000Z',+ updated_at: '2026-01-01T00:00:00.000Z',+ })+ const storedGrant = makeStoredGrant()++ it('tolerates a disabled promptTarget unchanged when coverage is not reduced (200 + emits)', async () => {+ // glm-4.7 is now disabled (enabled set omits it); the stored grant already+ // referenced it and the write does not shrink allowed_models.+ vi.mocked(pool.query).mockResolvedValue({+ rows: [{ model: 'other-enabled' }],+ rowCount: 1,+ } as never)+ vi.mocked(sdkDb.listGrants).mockResolvedValue([storedGrant] as never)+ vi.mocked(sdkDb.upsertGrant).mockResolvedValue({ id: 'g1' } as never)+ const emit = vi.fn()+ const res = await request(buildAppWithEmit(emit))+ .post('/admin/plugin-workload-sdk/grants')+ .send(validGrantBody)+ expect(res.status).toBe(200)+ expect(emit).toHaveBeenCalledWith(+ expect.objectContaining({+ resourceKind: 'grant',+ namespace: 'sandbox-recipes',+ name: 'sdk-recipe',+ provider: 'zai',+ model: 'glm-4.7',+ gate: 'grant',+ })+ )+ expect(sdkDb.upsertGrant).toHaveBeenCalled()+ })++ it('does NOT tolerate a coverage reduction around a disabled model → 400 (condition b)', async () => {+ // Stored offered {glm-4.7, glm-extra}; the write drops glm-extra while+ // keeping disabled glm-4.7 — a strict allowed_models reduction. Must 400.+ vi.mocked(pool.query).mockResolvedValue({+ rows: [{ model: 'other-enabled' }],+ rowCount: 1,+ } as never)+ vi.mocked(sdkDb.listGrants).mockResolvedValue([+ makeStoredGrant({ allowedModels: ['glm-4.7', 'glm-extra'] }),+ ] as never)+ const emit = vi.fn()+ const res = await request(buildAppWithEmit(emit))+ .post('/admin/plugin-workload-sdk/grants')+ .send(validGrantBody) // allowedModels: ['glm-4.7'] → glm-extra dropped+ expect(res.status).toBe(400)+ expect(res.body.error).toBe('model_not_allowed')+ expect(res.body.models).toEqual(['glm-4.7'])+ expect(emit).not.toHaveBeenCalled()+ expect(sdkDb.upsertGrant).not.toHaveBeenCalled()+ })++ it('does NOT tolerate a newly introduced disabled model → 400 (condition c)', async () => {+ // glm-4.7 stays enabled; the write introduces a NEW disabled target glm-new+ // absent from the stored grant. Even though coverage grows, (a)/(c) fail.+ vi.mocked(pool.query).mockResolvedValue({+ rows: [{ model: 'glm-4.7' }],+ rowCount: 1,+ } as never)+ vi.mocked(sdkDb.listGrants).mockResolvedValue([storedGrant] as never)+ const emit = vi.fn()+ const res = await request(buildAppWithEmit(emit))+ .post('/admin/plugin-workload-sdk/grants')+ .send({+ ...validGrantBody,+ allowedModels: ['glm-4.7', 'glm-new'],+ promptTargets: [+ ...validGrantBody.promptTargets,+ {+ targetRef: 'new-target',+ provider: 'zai',+ model: 'glm-new',+ credentialSlot: 'zai-api-key',+ },+ ],+ })+ expect(res.status).toBe(400)+ expect(res.body.error).toBe('model_not_allowed')+ expect(res.body.models).toEqual(['glm-new'])+ expect(emit).not.toHaveBeenCalled()+ expect(sdkDb.upsertGrant).not.toHaveBeenCalled()+ })++ it('does NOT tolerate promoting a disabled NON-default target to the default slot → 400 (mini-spec repro #3)', async () => {+ // Stored default = glm-4.7 (enabled); glm-old is a disabled NON-default+ // target. The write moves glm-old to promptTargets[0] (the default). Coverage+ // is not reduced, but role-scoping rejects the promotion to default.+ vi.mocked(pool.query).mockResolvedValue({+ rows: [{ model: 'glm-4.7' }],+ rowCount: 1,+ } as never) // glm-old disabled+ vi.mocked(sdkDb.listGrants).mockResolvedValue([+ makeStoredGrant({+ allowedModels: ['glm-4.7', 'glm-old'],+ promptTargets: [+ {+ targetRef: 'primary-zai',+ provider: 'zai',+ model: 'glm-4.7',+ credentialSlot: 'zai-api-key',+ },+ {+ targetRef: 'secondary',+ provider: 'zai',+ model: 'glm-old',+ credentialSlot: 'zai-api-key',+ },+ ],+ }),+ ] as never)+ const emit = vi.fn()+ const res = await request(buildAppWithEmit(emit))+ .post('/admin/plugin-workload-sdk/grants')+ .send({+ ...validGrantBody,+ allowedModels: ['glm-4.7', 'glm-old'],+ defaultTargetRef: 'secondary',+ promptTargets: [+ {+ targetRef: 'secondary',+ provider: 'zai',+ model: 'glm-old',+ credentialSlot: 'zai-api-key',+ },+ {+ targetRef: 'primary-zai',+ provider: 'zai',+ model: 'glm-4.7',+ credentialSlot: 'zai-api-key',+ },+ ],+ })+ expect(res.status).toBe(400)+ expect(res.body.error).toBe('model_not_allowed')+ expect(res.body.models).toEqual(['glm-old'])+ expect(emit).not.toHaveBeenCalled()+ expect(sdkDb.upsertGrant).not.toHaveBeenCalled()+ })++ it('tolerates DEMOTING a disabled default target to a non-default slot → 200 (not worsening)', async () => {+ // Stored default = glm-old (disabled). The write demotes it to a non-default+ // slot (glm-4.7 becomes the new, enabled default). Losing activity is not+ // worsening, so the disabled glm-old is tolerated at its non-default slot.+ vi.mocked(pool.query).mockResolvedValue({+ rows: [{ model: 'glm-4.7' }],+ rowCount: 1,+ } as never) // glm-old disabled, glm-4.7 enabled+ vi.mocked(sdkDb.listGrants).mockResolvedValue([+ makeStoredGrant({+ allowedModels: ['glm-old', 'glm-4.7'],+ promptTargets: [+ {+ targetRef: 'legacy',+ provider: 'zai',+ model: 'glm-old',+ credentialSlot: 'zai-api-key',+ },+ {+ targetRef: 'primary-zai',+ provider: 'zai',+ model: 'glm-4.7',+ credentialSlot: 'zai-api-key',+ },+ ],+ }),+ ] as never)+ vi.mocked(sdkDb.upsertGrant).mockResolvedValue({ id: 'g1' } as never)+ const emit = vi.fn()+ const res = await request(buildAppWithEmit(emit))+ .post('/admin/plugin-workload-sdk/grants')+ .send({+ ...validGrantBody,+ allowedModels: ['glm-4.7', 'glm-old'],+ defaultTargetRef: 'primary-zai',+ promptTargets: [+ {+ targetRef: 'primary-zai',+ provider: 'zai',+ model: 'glm-4.7',+ credentialSlot: 'zai-api-key',+ },+ {+ targetRef: 'legacy',+ provider: 'zai',+ model: 'glm-old',+ credentialSlot: 'zai-api-key',+ },+ ],+ })+ expect(res.status).toBe(200)+ expect(emit).toHaveBeenCalledWith(+ expect.objectContaining({+ resourceKind: 'grant',+ provider: 'zai',+ model: 'glm-old',+ gate: 'grant',+ })+ )+ expect(sdkDb.upsertGrant).toHaveBeenCalled()+ })++ it('does NOT emit the audit event when the upsert fails to persist (persist-safe)', async () => {+ // A tolerable disabled default target, but upsertGrant throws → the write did+ // not persist → no audit record must be emitted.+ vi.mocked(pool.query).mockResolvedValue({+ rows: [{ model: 'other-enabled' }],+ rowCount: 1,+ } as never)+ vi.mocked(sdkDb.listGrants).mockResolvedValue([storedGrant] as never)+ vi.mocked(sdkDb.upsertGrant).mockRejectedValue(new Error('db down'))+ const emit = vi.fn()+ const res = await request(buildAppWithEmit(emit))+ .post('/admin/plugin-workload-sdk/grants')+ .send(validGrantBody)+ expect(res.status).toBeGreaterThanOrEqual(500)+ expect(emit).not.toHaveBeenCalled()+ })+ })+it('returns 400 when deleting without recipe scope', async () => {const res = await request(buildApp()).delete('/admin/plugin-workload-sdk/grants/g1')expect(res.status).toBe(400)diff --git a/control-api/test/routes.hostSpecValidation.test.ts b/control-api/test/routes.hostSpecValidation.test.tsindex 9d19d7ac7..6bad3806c 100644--- a/control-api/test/routes.hostSpecValidation.test.ts+++ b/control-api/test/routes.hostSpecValidation.test.ts@@ -434,4 +434,291 @@ describe('validateHostSpec', () => {expect(res!.errors[0].message).toContain('model_not_offered')})})++ // ── Pieza D: role-scoped no-worsening tolerance (editability trap G3) ────────+ // Once a Host's default (or a referenced model) falls out of the allowlist, the+ // global `model_not_allowed` gate rejected EVERY future edit — including the+ // fix. Tolerance lets a write through iff it does not worsen a pre-existing+ // incoherence AND the pair keeps its ROLE (primary/fallback/subset). The+ // validator no longer emits: it appends the granted tolerations to+ // `context.tolerations`; the route emits them only after the CR persists.+ describe('no-worsening tolerance (Pieza D, role-scoped)', () => {+ // isModelAllowed keyed on `${provider}:${model}`; anything not listed is disabled.+ const allowlist = (...enabled: string[]) => {+ const set = new Set(enabled)+ return vi.fn((p: string, m: string) => Promise.resolve(set.has(`${p}:${m}`)))+ }+ const hostRef = { namespace: 'mcp-host', name: 'h1' }++ it('re-saving a disabled PRIMARY in the same role, coverage not reduced → 200 + tolerated', async () => {+ const isModelAllowed = allowlist() // M disabled+ const tolerations: Array<Record<string, unknown>> = []+ const stored = { model: { provider: 'claude', name: 'M' } }+ const res = await validateHostSpec(+ { model: { provider: 'claude', name: 'M' } },+ { isModelAllowed },+ { stored, hostRef, tolerations }+ )+ expect(res).toBeNull() // → 200+ expect(tolerations).toEqual([+ expect.objectContaining({+ resourceKind: 'host',+ namespace: 'mcp-host',+ name: 'h1',+ provider: 'claude',+ model: 'M',+ gate: 'primary',+ offeredBefore: 'UNIVERSAL',+ offeredAfter: 'UNIVERSAL',+ }),+ ])+ })++ it('widening coverage while re-saving a disabled primary is still tolerated (G3 not broken)', async () => {+ const isModelAllowed = allowlist('claude:A') // M disabled, A enabled+ const tolerations: Array<Record<string, unknown>> = []+ const stored = {+ model: { provider: 'claude', name: 'M' },+ allowedModels: [{ provider: 'claude', model: 'M' }],+ }+ const res = await validateHostSpec(+ {+ model: { provider: 'claude', name: 'M' },+ allowedModels: [+ { provider: 'claude', model: 'M' },+ { provider: 'claude', model: 'A' },+ ],+ },+ { isModelAllowed },+ { stored, hostRef, tolerations }+ )+ expect(res).toBeNull()+ // M tolerated at BOTH the primary gate and the subset gate (same role each).+ expect(tolerations.map(t => t.gate).sort()).toEqual(['primary', 'subset'])+ })++ it('keeps a disabled FALLBACK as a fallback → 200 + tolerated (gate=fallback)', async () => {+ const isModelAllowed = allowlist('claude:A') // F disabled, A enabled+ const tolerations: Array<Record<string, unknown>> = []+ const stored = {+ model: { provider: 'claude', name: 'A' },+ llmPolicy: { fallbacks: [{ provider: 'claude', model: 'F' }] },+ }+ const res = await validateHostSpec(+ {+ model: { provider: 'claude', name: 'A' },+ llmPolicy: { fallbacks: [{ provider: 'claude', model: 'F' }] },+ },+ { isModelAllowed },+ { stored, hostRef, tolerations }+ )+ expect(res).toBeNull()+ expect(tolerations).toEqual([expect.objectContaining({ gate: 'fallback', model: 'F' })])+ })++ it('ROLE ELEVATION fallback→primary is NOT tolerated → 422 (mini-spec repro #1)', async () => {+ // Stored: primary A (enabled), fallback M (disabled). The write promotes the+ // disabled fallback M to the active primary default without shrinking+ // coverage. Per-par tolerance let this through (200); role-scoped rejects it.+ const isModelAllowed = allowlist('claude:A') // M disabled+ const tolerations: Array<Record<string, unknown>> = []+ const stored = {+ model: { provider: 'claude', name: 'A' },+ llmPolicy: { fallbacks: [{ provider: 'claude', model: 'M' }] },+ }+ const res = await validateHostSpec(+ {+ model: { provider: 'claude', name: 'M' },+ llmPolicy: { fallbacks: [{ provider: 'claude', model: 'M' }] },+ },+ { isModelAllowed },+ { stored, hostRef, tolerations }+ )+ expect(res).not.toBeNull() // → 422+ expect(res!.errors[0].field).toBe('spec.model.name')+ expect(res!.errors[0].message).toContain('model_not_allowed')+ expect(tolerations).toEqual([]) // nothing emitted for a rejected write+ })++ it('ROLE ELEVATION allowedModels→primary is NOT tolerated → 422 (mini-spec repro #2)', async () => {+ // Stored: primary A (enabled), allowedModels [A, M(disabled)]. The write makes+ // the disabled subset-only M the primary default.+ const isModelAllowed = allowlist('claude:A') // M disabled+ const tolerations: Array<Record<string, unknown>> = []+ const stored = {+ model: { provider: 'claude', name: 'A' },+ allowedModels: [+ { provider: 'claude', model: 'A' },+ { provider: 'claude', model: 'M' },+ ],+ }+ const res = await validateHostSpec(+ {+ model: { provider: 'claude', name: 'M' },+ allowedModels: [+ { provider: 'claude', model: 'A' },+ { provider: 'claude', model: 'M' },+ ],+ },+ { isModelAllowed },+ { stored, hostRef, tolerations }+ )+ expect(res).not.toBeNull() // → 422 at the primary gate+ expect(res!.errors[0].field).toBe('spec.model.name')+ expect(tolerations).toEqual([])+ })++ it('a NEW disabled fallback (never stored) is NOT tolerated → 422 (condition c)', async () => {+ const isModelAllowed = allowlist('claude:A') // X disabled+ const tolerations: Array<Record<string, unknown>> = []+ const stored = {+ model: { provider: 'claude', name: 'A' },+ llmPolicy: { fallbacks: [{ provider: 'claude', model: 'A' }] },+ }+ const res = await validateHostSpec(+ {+ model: { provider: 'claude', name: 'A' },+ llmPolicy: { fallbacks: [{ provider: 'claude', model: 'X' }] },+ },+ { isModelAllowed },+ { stored, hostRef, tolerations }+ )+ expect(res).not.toBeNull()+ expect(res!.errors[0].field).toBe('spec.llmPolicy.fallbacks[0].model')+ expect(tolerations).toEqual([])+ })++ it('BYPASS BLOCKED: reducing the subset around a disabled model → 422 (condition b)', async () => {+ // Same role (subset), but coverage shrinks (drops N) → still rejected.+ const isModelAllowed = allowlist('claude:A') // M, N disabled+ const tolerations: Array<Record<string, unknown>> = []+ const stored = {+ model: { provider: 'claude', name: 'A' },+ allowedModels: [+ { provider: 'claude', model: 'A' },+ { provider: 'claude', model: 'M' },+ { provider: 'claude', model: 'N' },+ ],+ }+ const res = await validateHostSpec(+ {+ model: { provider: 'claude', name: 'A' },+ allowedModels: [+ { provider: 'claude', model: 'A' },+ { provider: 'claude', model: 'M' },+ ],+ },+ { isModelAllowed },+ { stored, hostRef, tolerations }+ )+ expect(res).not.toBeNull()+ expect(res!.errors[0].field).toBe('spec.allowedModels[1].model')+ expect(tolerations).toEqual([])+ })++ it('narrowing a previously-UNIVERSAL offering around a disabled primary → 422 (condition b)', async () => {+ const isModelAllowed = allowlist() // M disabled+ const tolerations: Array<Record<string, unknown>> = []+ const stored = { model: { provider: 'claude', name: 'M' } } // allowedModels absent → UNIVERSAL+ const res = await validateHostSpec(+ {+ model: { provider: 'claude', name: 'M' },+ allowedModels: [{ provider: 'claude', model: 'M' }],+ },+ { isModelAllowed },+ { stored, hostRef, tolerations }+ )+ expect(res).not.toBeNull()+ expect(tolerations).toEqual([])+ })++ it('DEMOTION primary→fallback is tolerated → 200 + tolerated (mini-spec v2)', async () => {+ // Stored: primary M (disabled). The write moves M OUT of the active slot to+ // a fallback and installs an enabled primary A. M loses activeness — pure+ // non-worsening — so it is tolerated at the (non-active) fallback gate. v1's+ // exact-same-role rule wrongly rejected this with 422.+ const isModelAllowed = allowlist('claude:A') // M disabled, A enabled+ const tolerations: Array<Record<string, unknown>> = []+ const stored = { model: { provider: 'claude', name: 'M' } }+ const res = await validateHostSpec(+ {+ model: { provider: 'claude', name: 'A' },+ llmPolicy: { fallbacks: [{ provider: 'claude', model: 'M' }] },+ },+ { isModelAllowed },+ { stored, hostRef, tolerations }+ )+ expect(res).toBeNull() // → 200+ expect(tolerations).toEqual([expect.objectContaining({ gate: 'fallback', model: 'M' })])+ })++ it('DEMOTION away from the primary slot into the subset is tolerated → 200 (mini-spec v2)', async () => {+ // Stored: primary M (disabled), coverage [M]. The write installs enabled A as+ // primary and keeps M as a (non-active) subset entry, widening coverage. M is+ // no longer the active default → non-worsening → tolerated at the subset gate.+ const isModelAllowed = allowlist('claude:A') // M disabled, A enabled+ const tolerations: Array<Record<string, unknown>> = []+ const stored = {+ model: { provider: 'claude', name: 'M' },+ allowedModels: [{ provider: 'claude', model: 'M' }],+ }+ const res = await validateHostSpec(+ {+ model: { provider: 'claude', name: 'A' },+ allowedModels: [+ { provider: 'claude', model: 'A' },+ { provider: 'claude', model: 'M' },+ ],+ },+ { isModelAllowed },+ { stored, hostRef, tolerations }+ )+ expect(res).toBeNull()+ expect(tolerations).toEqual([expect.objectContaining({ gate: 'subset', model: 'M' })])+ })++ it('throws when `stored` is provided without a `tolerations` sink (never-silent contract guard)', async () => {+ const isModelAllowed = allowlist()+ await expect(+ validateHostSpec(+ { model: { provider: 'claude', name: 'M' } },+ { isModelAllowed },+ { stored: { model: { provider: 'claude', name: 'M' } }, hostRef } // no `tolerations`+ )+ ).rejects.toThrow(/tolerations sink is required/)+ })++ it('never tolerates on CREATE (no stored CR) → 422', async () => {+ const isModelAllowed = allowlist() // M disabled+ const tolerations: Array<Record<string, unknown>> = []+ const res = await validateHostSpec(+ { model: { provider: 'claude', name: 'M' } },+ { isModelAllowed },+ { hostRef, tolerations } // no `stored`+ )+ expect(res).not.toBeNull()+ expect(res!.errors[0].message).toContain('model_not_allowed')+ expect(tolerations).toEqual([])+ })++ it('does NOT record a toleration when a LATER gate hard-rejects the write (persist-safe)', async () => {+ // Primary M is a tolerable same-role incoherence, but a NEW disabled fallback+ // X hard-rejects the write. Because validation fails, the queued M toleration+ // is NOT handed to context.tolerations → the route emits nothing.+ const isModelAllowed = allowlist() // M and X disabled+ const tolerations: Array<Record<string, unknown>> = []+ const stored = { model: { provider: 'claude', name: 'M' } }+ const res = await validateHostSpec(+ {+ model: { provider: 'claude', name: 'M' },+ llmPolicy: { fallbacks: [{ provider: 'claude', model: 'X' }] },+ },+ { isModelAllowed },+ { stored, hostRef, tolerations }+ )+ expect(res).not.toBeNull()+ expect(res!.errors[0].field).toBe('spec.llmPolicy.fallbacks[0].model')+ expect(tolerations).toEqual([])+ })+ })})diff --git a/control-api/test/routes.modelAllowlistTolerance.test.ts b/control-api/test/routes.modelAllowlistTolerance.test.tsnew file mode 100644index 000000000..a63984b58--- /dev/null+++ b/control-api/test/routes.modelAllowlistTolerance.test.ts@@ -0,0 +1,207 @@+import { describe, expect, it } from 'vitest'+import fc from 'fast-check'+import {+ type CoverageSet,+ coverageIsSuperset,+ isNonWorseningToleration,+ offeredKey,+} from '../src/routes/admin/modelAllowlistTolerance.js'++// The no-worsening tolerance predicate is a PURE function `(stored, incoming) →+// tolerateQ` with precedence rules (a/b/c of Pieza D). Property-based tests (T2)+// explore the precedence combinations that enumerated cases miss.++const arbPairKey = fc+ .tuple(+ fc.constantFrom('claude', 'openai', 'groq', 'zai'),+ fc.string({ minLength: 1, maxLength: 6 })+ )+ .map(([p, m]) => offeredKey(p, m))++const arbKeySet = fc.array(arbPairKey, { maxLength: 8 }).map(keys => new Set(keys))+const arbCoverage: fc.Arbitrary<CoverageSet> = fc.oneof(+ fc.constant('UNIVERSAL' as const),+ arbKeySet+)++function isSuperset(incoming: CoverageSet, stored: CoverageSet): boolean {+ if (incoming === 'UNIVERSAL') return true+ if (stored === 'UNIVERSAL') return false+ for (const k of stored) if (!incoming.has(k)) return false+ return true+}++describe('coverageIsSuperset', () => {+ it('UNIVERSAL covers everything (top element)', () => {+ fc.assert(fc.property(arbCoverage, cov => coverageIsSuperset('UNIVERSAL', cov)))+ })++ it('only UNIVERSAL covers a UNIVERSAL offering', () => {+ fc.assert(+ fc.property(arbCoverage, incoming => {+ expect(coverageIsSuperset(incoming, 'UNIVERSAL')).toBe(incoming === 'UNIVERSAL')+ })+ )+ })++ it('is reflexive: any coverage is a superset of itself', () => {+ fc.assert(fc.property(arbCoverage, cov => coverageIsSuperset(cov, cov)))+ })++ it('agrees with the reference set-superset relation', () => {+ fc.assert(+ fc.property(arbCoverage, arbCoverage, (incoming, stored) => {+ expect(coverageIsSuperset(incoming, stored)).toBe(isSuperset(incoming, stored))+ })+ )+ })+})++describe('isNonWorseningToleration', () => {+ it('CANONICAL: identical pre-existing pair + superset coverage → always tolerates', () => {+ fc.assert(+ fc.property(arbPairKey, arbKeySet, arbCoverage, (pairKey, otherStored, storedCoverage) => {+ // Guarantee (a): the offending pair is referenced by the stored record.+ const storedReferencedPairKeys = new Set([...otherStored, pairKey])+ // Guarantee (b): incoming is a superset of stored — extend it with extras.+ const extra = new Set([offeredKey('extra', 'x'), offeredKey('extra', 'y')])+ const incomingCoverage: CoverageSet =+ storedCoverage === 'UNIVERSAL' ? 'UNIVERSAL' : new Set([...storedCoverage, ...extra])+ expect(+ isNonWorseningToleration({+ pairKey,+ storedReferencedPairKeys,+ incomingCoverage,+ storedCoverage,+ })+ ).toBe(true)+ })+ )+ })++ it('a pair absent from the stored record is NEVER tolerated (conditions a/c)', () => {+ fc.assert(+ fc.property(arbPairKey, arbKeySet, arbCoverage, arbCoverage, (pairKey, stored, inc, st) => {+ const storedReferencedPairKeys = new Set([...stored])+ storedReferencedPairKeys.delete(pairKey) // ensure absence+ expect(+ isNonWorseningToleration({+ pairKey,+ storedReferencedPairKeys,+ incomingCoverage: inc,+ storedCoverage: st,+ })+ ).toBe(false)+ })+ )+ })++ it('a strict coverage reduction is NEVER tolerated, even for a pre-existing pair (condition b)', () => {+ fc.assert(+ fc.property(arbPairKey, arbKeySet, (pairKey, storedFinite) => {+ // stored covers pairKey plus at least one extra that incoming will drop.+ const dropped = offeredKey('dropped', 'z')+ const storedCoverage = new Set([...storedFinite, dropped])+ const incomingCoverage = new Set([...storedFinite]) // dropped removed+ incomingCoverage.delete(dropped)+ const storedReferencedPairKeys = new Set([pairKey])+ expect(+ isNonWorseningToleration({+ pairKey,+ storedReferencedPairKeys,+ incomingCoverage,+ storedCoverage,+ })+ ).toBe(false)+ })+ )+ })++ it('equals membership(a) AND superset(b) for arbitrary inputs (full spec)', () => {+ fc.assert(+ fc.property(arbPairKey, arbKeySet, arbCoverage, arbCoverage, (pairKey, stored, inc, st) => {+ const expected = stored.has(pairKey) && isSuperset(inc, st)+ expect(+ isNonWorseningToleration({+ pairKey,+ storedReferencedPairKeys: stored,+ incomingCoverage: inc,+ storedCoverage: st,+ })+ ).toBe(expected)+ })+ )+ })++ it('create (empty stored referenced set) never tolerates', () => {+ fc.assert(+ fc.property(arbPairKey, arbCoverage, arbCoverage, (pairKey, inc, st) => {+ expect(+ isNonWorseningToleration({+ pairKey,+ storedReferencedPairKeys: new Set(),+ incomingCoverage: inc,+ storedCoverage: st,+ })+ ).toBe(false)+ })+ )+ })+})++// Role-scoped selection at the caller seam (mini-spec 01 v2). The pure predicate+// is gate-agnostic; the caller passes the ACTIVE-slot set (`storedPrimary`) at+// the active gate and the union (`storedAny`, with primary ⊆ any) at non-active+// gates. These properties pin that two-tier rule: demotion tolerated, promotion+// to the active slot never.+describe('role-scoped selection invariant (mini-spec v2)', () => {+ // storedPrimary ⊆ storedAny, as the role sets always relate.+ const arbRoleSets = arbKeySet.chain(any =>+ fc.subarray([...any]).map(primary => ({ any, primary: new Set(primary) }))+ )+ const selectFor = (+ gate: 'primary' | 'nonactive',+ roles: { primary: ReadonlySet<string>; any: ReadonlySet<string> }+ ): ReadonlySet<string> => (gate === 'primary' ? roles.primary : roles.any)++ it('tolerated(active) ⇒ P ∈ storedPrimary; tolerated(non-active) ⇒ P ∈ storedAny', () => {+ fc.assert(+ fc.property(+ arbPairKey,+ arbRoleSets,+ fc.constantFrom<'primary' | 'nonactive'>('primary', 'nonactive'),+ arbCoverage,+ arbCoverage,+ (pairKey, roles, gate, inc, st) => {+ const tolerated = isNonWorseningToleration({+ pairKey,+ storedReferencedPairKeys: selectFor(gate, roles),+ incomingCoverage: inc,+ storedCoverage: st,+ })+ if (!tolerated) return+ if (gate === 'primary') expect(roles.primary.has(pairKey)).toBe(true)+ else expect(roles.any.has(pairKey)).toBe(true)+ }+ )+ )+ })++ it('PROMOTION is never tolerated: a pair in storedAny but not storedPrimary is rejected at the active gate', () => {+ fc.assert(+ fc.property(arbPairKey, arbKeySet, arbCoverage, arbCoverage, (pairKey, others, inc, st) => {+ // pairKey exists in `any` (via `others`) but is explicitly NOT the primary.+ const any = new Set([...others, pairKey])+ const primary = new Set([...others].filter(k => k !== pairKey))+ expect(+ isNonWorseningToleration({+ pairKey,+ storedReferencedPairKeys: selectFor('primary', { primary, any }),+ incomingCoverage: inc,+ storedCoverage: st,+ })+ ).toBe(false)+ })+ )+ })+})diff --git a/control-api/test/routes.resources.hostTolerance.test.ts b/control-api/test/routes.resources.hostTolerance.test.tsnew file mode 100644index 000000000..219f8366f--- /dev/null+++ b/control-api/test/routes.resources.hostTolerance.test.ts@@ -0,0 +1,99 @@+import { beforeEach, describe, expect, it, vi } from 'vitest'+import express from 'express'+import request from 'supertest'+import { config } from '../src/config.js'+import { createAdminResourcesRouter } from '../src/routes/admin/resources.js'+import { MockGateway } from './mockGateway.js'++// Route-level proof (mini-spec 01) that the Pieza D audit event is emitted ONLY+// after the Host CR persists — never on a rejected or failed write. isModelAllowed+// is mocked to disable the model; the logger is mocked to observe emission.++const llm = vi.hoisted(() => ({ isModelAllowed: vi.fn() }))+vi.mock('../src/services/llmAllowedModels.js', async () => {+ const actual = await vi.importActual<typeof import('../src/services/llmAllowedModels.js')>(+ '../src/services/llmAllowedModels.js'+ )+ return { ...actual, isModelAllowed: llm.isModelAllowed }+})++const log = vi.hoisted(() => {+ const warn = vi.fn()+ const stub = () => ({+ warn,+ info: vi.fn(),+ error: vi.fn(),+ debug: vi.fn(),+ trace: vi.fn(),+ fatal: vi.fn(),+ child: () => stub(),+ })+ return { warn, rootLogger: stub() }+})+vi.mock('../src/observability/logger.js', () => ({ rootLogger: log.rootLogger }))++const HOSTS_NS = config.hostsNamespace+const disabledModelSpec = { model: { provider: 'claude', name: 'M' } }++function buildApp(gateway: MockGateway) {+ const app = express()+ app.use(express.json())+ app.use(createAdminResourcesRouter(gateway as never))+ return app+}++beforeEach(() => {+ log.warn.mockReset()+ // M is disabled globally; everything else is enabled.+ llm.isModelAllowed.mockImplementation((_p: string, m: string) => Promise.resolve(m !== 'M'))+})++describe('Host tolerance audit — emit only after persist (mini-spec 01)', () => {+ it('emits host_spec_incoherence_tolerated after a successful update', async () => {+ const gateway = new MockGateway(HOSTS_NS)+ // Seed the trapped Host directly (its default M is now disabled).+ await gateway.createResource(+ 'hosts',+ { metadata: { name: 'h1' }, spec: disabledModelSpec },+ HOSTS_NS+ )++ const res = await request(buildApp(gateway))+ .put('/admin/hosts/h1')+ .send({ spec: disabledModelSpec })++ expect(res.status).toBe(200)+ expect(log.warn).toHaveBeenCalledWith(+ expect.objectContaining({+ event: 'host_spec_incoherence_tolerated',+ gate: 'primary',+ provider: 'claude',+ model: 'M',+ name: 'h1',+ }),+ expect.any(String)+ )+ })++ it('does NOT emit when the CR fails to persist (updateResource throws)', async () => {+ class ThrowingGateway extends MockGateway {+ override async updateResource(): Promise<unknown> {+ throw new Error('k8s write failed')+ }+ }+ const gateway = new ThrowingGateway(HOSTS_NS)+ await gateway.createResource(+ 'hosts',+ { metadata: { name: 'h1' }, spec: disabledModelSpec },+ HOSTS_NS+ )++ const res = await request(buildApp(gateway))+ .put('/admin/hosts/h1')+ .send({ spec: disabledModelSpec })++ expect(res.status).toBeGreaterThanOrEqual(500)+ // Validation tolerated M, but the write did not persist → no audit record.+ expect(log.warn).not.toHaveBeenCalled()+ })+})