Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure
TypeScript
test(control-ui): producer-backed fixtures and cardinality invariants (PR #277)
Jose Ramirezc9259b83bf72
diff --git a/control-ui/components/__tests__/fixtures/secretResolvedConditions.ts b/control-ui/components/__tests__/fixtures/secretResolvedConditions.tsindex 479cd99c3..cd9dc4559 100644--- a/control-ui/components/__tests__/fixtures/secretResolvedConditions.ts+++ b/control-ui/components/__tests__/fixtures/secretResolvedConditions.ts@@ -10,17 +10,34 @@ import type { McpServerCondition } from '@lib/api'* `reason: 'SecretResolved'` (the condition TYPE reused as a reason, a value the* producer never emits) survived in the resolver fixtures for two rounds.*- * Producer sites, all in `host-context-controller/src/reconciler.ts`:+ * THESE BUILDERS ARE NOT TRUSTED ON THEIR OWN (R1-H2).*- * | builder | type | status | reason | written at |- * |---------------------|-----------------|---------|---------------------|------------|- * | `secretFound` | SecretResolved | 'True' | 'SecretFound' | :1981 (managed), :2063 (WRC-owned) |- * | `secretNotFound` | SecretResolved | 'False' | 'SecretNotFound' | :1872 / :2041, reason from validateSecret :468-472 |- * | `secretMissingKey` | SecretResolved | 'False' | 'SecretMissingKey' | :1872 / :2041, reason from validateSecret :456-459 |- * | `secretAccessDenied`| SecretResolved | 'False' | 'SecretAccessDenied'| :1872 / :2041, reason from validateSecret :474-479 |+ * A handwritten mirror of the producer is exactly as stale as the author who+ * wrote it, and a UI suite cannot tell the difference: if HCC changed a status,+ * reason or message, both the mocked producer output and the assertion would+ * keep encoding the old triple and stay green.*- * The messages are copied from the same producer branches, so a fixture reads- * like a real resource dump rather than an approximation of one.+ * So the mirror is checked, executably, by+ * `../secretResolvedProducerContract.test.ts`. That suite reads+ * `host-context-controller/src/reconciler.ts` off disk, extracts the real+ * `SecretResolved` condition writes and `validateSecret` failure results, and+ * asserts every builder below reproduces exactly those triples — messages+ * included, placeholder by placeholder. A producer contract change turns it+ * red, and a producer site it can no longer find throws rather than passing on+ * an empty match set.+ *+ * The builders are:+ *+ * | builder | status | reason |+ * |----------------------|---------|----------------------|+ * | `secretFound` | 'True' | 'SecretFound' |+ * | `secretNotFound` | 'False' | 'SecretNotFound' |+ * | `secretMissingKey` | 'False' | 'SecretMissingKey' |+ * | `secretAccessDenied` | 'False' | 'SecretAccessDenied' |+ *+ * `ReadError` — the producer's fourth failure reason — has no builder on+ * purpose; the contract suite covers it by extraction and fails if a FIFTH+ * reason ever appears unmodelled.** Anything the producer CANNOT emit — a `SecretResolved` at status `Unknown`, a* reason carried by the wrong condition type, a malformed or absent@@ -44,7 +61,7 @@ const DEFAULT_ENV_VAR = 'LINEAR_WORKSPACE'type Stamped = { at: string }/** `SecretResolved=True` — the Secret exists and every declared key is present.- * reconciler.ts:1981 (managed) and :2063 (WRC-owned) write this exact triple. */+ * Both producer success sites — managed and WRC-owned — write this triple. */export function secretFound({ at }: Stamped): McpServerCondition {return {type: SECRET_RESOLVED,@@ -57,7 +74,7 @@ export function secretFound({ at }: Stamped): McpServerCondition {/** `SecretResolved=False/SecretNotFound` — the Secret does not exist. This is* the ONLY condition that may send a managed connector to the create form.- * Message from reconciler.ts:468 (the k8s 404 branch of validateSecret). */+ * Message from validateSecret's k8s-404 branch. */export function secretNotFound({at,secretName = DEFAULT_SECRET_NAME,@@ -74,7 +91,7 @@ export function secretNotFound({/** `SecretResolved=False/SecretMissingKey` — the Secret EXISTS but lacks a* declared key. The rotate merge-patch adds it, so this must never reach the- * create form. Message from reconciler.ts:456-457. */+ * create form. Message from validateSecret's missing-key branch. */export function secretMissingKey({at,secretName = DEFAULT_SECRET_NAME,@@ -97,7 +114,7 @@ export function secretMissingKey({}/** `SecretResolved=False/SecretAccessDenied` — the Secret may well exist; HCC- * could not read it (k8s 401/403). Message from reconciler.ts:476-477. */+ * could not read it (k8s 401/403). Message from validateSecret's 401/403 branch. */export function secretAccessDenied({at,secretName = DEFAULT_SECRET_NAME,diff --git a/control-ui/components/__tests__/resolveCredentialSurfaceInvariants.test.ts b/control-ui/components/__tests__/resolveCredentialSurfaceInvariants.test.tsnew file mode 100644index 000000000..01771288c--- /dev/null+++ b/control-ui/components/__tests__/resolveCredentialSurfaceInvariants.test.ts@@ -0,0 +1,534 @@+import { describe, expect, it } from 'vitest'+import {+ type CredentialSurface,+ resolveCredentialSurface,+} from '@components/UpdateConnectorCredentials/resolveCredentialSurface'+import type { McpServerCondition } from '@lib/api'+import {+ SECRET_RESOLVED,+ secretFound,+ secretMissingKey,+ secretNotFound,+} from './fixtures/secretResolvedConditions'++// ─── R1-M2: arbitrary-cardinality invariants ───────────────────────────────+//+// The example-based suite in resolveCredentialSurface.test.ts pins the rules+// one scenario at a time, and every scenario it pins uses at most TWO relevant+// SecretResolved conditions. The reviewer reproduced the consequence: mutating+// authority selection to rank only the LAST TWO candidates leaves all 87 tests+// green, because nothing exercises three or more.+//+// This file treats `resolveCredentialSurface` as the pure precedence function+// it is and checks it against an independent REFERENCE MODEL over generated+// inputs of arbitrary cardinality. The reference is written a different way on+// purpose — sort-based selection, and a timestamp validator built from civil+// calendar arithmetic instead of `Date` — so an error shared with the+// implementation cannot cancel out.+//+// Generation is seeded (mulberry32), never `Math.random()`: a red run names the+// seed and iteration and prints the whole case, so it reproduces exactly.+//+// The intentional ORDER-SENSITIVE rule is preserved: on equal rank the LAST+// array entry wins, so permutations are NOT interchangeable and the reference+// encodes the same rule rather than sorting the difference away.++// ─── Reference model ───────────────────────────────────────────────────────++const REFERENCE_RFC3339 =+ /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.(\d+))?(Z|[+-]\d{2}:\d{2})$/++const DAYS_IN_MONTH = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]++function isLeapYear(year: number): boolean {+ return (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0+}++/**+ * Days between 1970-01-01 and the given proleptic-Gregorian civil date+ * (Howard Hinnant's `days_from_civil`). Used instead of `Date` so the reference+ * shares no arithmetic — and no normalization bug — with the implementation.+ */+function daysFromCivil(year: number, month: number, day: number): number {+ const shiftedYear = year - (month <= 2 ? 1 : 0)+ const era = Math.floor(shiftedYear / 400)+ const yearOfEra = shiftedYear - era * 400+ const dayOfYear = Math.floor((153 * (month + (month > 2 ? -3 : 9)) + 2) / 5) + day - 1+ const dayOfEra =+ yearOfEra * 365 + Math.floor(yearOfEra / 4) - Math.floor(yearOfEra / 100) + dayOfYear+ return era * 146_097 + dayOfEra - 719_468+}++/** The intended rank: epoch milliseconds, or the oldest possible rank when the+ * value is not a real instant. Calendar validity is checked by hand. */+function referenceRank(value: unknown): number {+ if (typeof value !== 'string') return Number.NEGATIVE_INFINITY+ const matched = REFERENCE_RFC3339.exec(value)+ if (!matched) return Number.NEGATIVE_INFINITY++ const year = Number(matched[1])+ const month = Number(matched[2])+ const day = Number(matched[3])+ const hour = Number(matched[4])+ const minute = Number(matched[5])+ const second = Number(matched[6])+ const fraction = matched[7]+ const offset = matched[8]++ if (month < 1 || month > 12) return Number.NEGATIVE_INFINITY+ const maxDay = month === 2 && isLeapYear(year) ? 29 : DAYS_IN_MONTH[month - 1]+ if (day < 1 || day > maxDay) return Number.NEGATIVE_INFINITY+ if (hour > 23 || minute > 59 || second > 59) return Number.NEGATIVE_INFINITY++ const millisecond = Number((fraction ?? '').padEnd(3, '0').slice(0, 3))++ let offsetMinutes = 0+ if (offset !== 'Z') {+ const offsetHours = Number(offset.slice(1, 3))+ const offsetMinutePart = Number(offset.slice(4, 6))+ if (offsetHours > 23 || offsetMinutePart > 59) return Number.NEGATIVE_INFINITY+ offsetMinutes = (offset.startsWith('-') ? -1 : 1) * (offsetHours * 60 + offsetMinutePart)+ }++ return (+ daysFromCivil(year, month, day) * 86_400_000 ++ hour * 3_600_000 ++ minute * 60_000 ++ second * 1_000 ++ millisecond -+ offsetMinutes * 60_000+ )+}++/**+ * The intended precedence, implemented by SORTING a copy rather than by a+ * single scan: highest rank last, ties broken by original index so the LAST+ * entry of a tie ends up last. The winner is then the final element.+ */+function referenceResolve(+ conditions: McpServerCondition[] | undefined,+ spec: { managed?: boolean } | undefined+): CredentialSurface {+ const relevant = (conditions ?? [])+ .map((condition, index) => ({ condition, index }))+ .filter(entry => entry.condition.type === SECRET_RESOLVED)++ if (relevant.length === 0) return 'rotate'++ const ordered = [...relevant].sort((left, right) => {+ const leftRank = referenceRank(left.condition.lastTransitionTime)+ const rightRank = referenceRank(right.condition.lastTransitionTime)+ if (leftRank !== rightRank) return leftRank < rightRank ? -1 : 1+ return left.index - right.index+ })++ const winner = ordered[ordered.length - 1].condition+ const claimsAbsence = winner.status === 'False' && winner.reason === 'SecretNotFound'+ if (!claimsAbsence) return 'rotate'+ return spec?.managed === false ? 'recipe-owned' : 'set'+}++// ─── Seeded generator ──────────────────────────────────────────────────────++/** mulberry32 — small, deterministic, and reproducible from its seed. */+function mulberry32(seed: number): () => number {+ let state = seed >>> 0+ return () => {+ state = (state + 0x6d2b79f5) >>> 0+ let t = state+ t = Math.imul(t ^ (t >>> 15), t | 1)+ t ^= t + Math.imul(t ^ (t >>> 7), t | 61)+ return ((t ^ (t >>> 14)) >>> 0) / 4_294_967_296+ }+}++/**+ * Timestamps span every class the resolver distinguishes, and the VALID ones+ * are drawn from a deliberately small pool with duplicates and equivalent+ * offsets, so exact ties are common — that is the only way the positional+ * tie-break gets exercised at all.+ */+const TIMESTAMPS: (string | undefined)[] = [+ // valid, Z, millisecond precision+ '2026-08-06T07:00:00.000Z',+ '2026-08-06T08:00:00.000Z',+ '2026-08-06T09:00:00.000Z',+ '2026-08-06T09:00:00.000Z', // exact duplicate of the above -> guaranteed ties+ // valid, second precision (no fraction)+ '2026-08-06T08:00:00Z',+ // valid, non-Z offsets that resolve to the SAME instant as 08:00Z+ '2026-08-06T10:30:00+02:30',+ '2026-08-06T04:00:00-04:00',+ // valid leap-day+ '2028-02-29T12:00:00.000Z',+ // RFC3339 SYNTAX, invalid calendar. The first two are inside the ISO grammar,+ // so `new Date()` accepts and silently NORMALIZES them (Feb 30 -> Mar 2) —+ // they are what separates strict validation from a bare parse. The rest fall+ // outside the grammar and only pin the regex.+ '2026-02-30T00:00:00.000Z',+ '2027-02-29T12:00:00.000Z', // 2027 is not a leap year+ '2026-13-01T00:00:00.000Z',+ '2026-08-06T25:00:00.000Z',+ '2026-08-06T12:60:00.000Z',+ '2026-08-06T12:00:60.000Z', // leap second+ '2026-08-06T12:00:00+99:00', // out-of-range offset+ // parseable by `Date`, rejected by RFC3339+ '2026-08-07', // date only+ '2026-08-07T12:00:00', // no offset: browser-timezone dependent+ 'Aug 7, 2026', // Date.parse accepts, RFC3339 does not+ '2026-08-07 12:00:00Z', // space instead of T+ '', // empty+ undefined, // property absent altogether+]++const STATUSES: McpServerCondition['status'][] = ['True', 'False', 'Unknown']++const REASONS = [+ 'SecretFound',+ 'SecretNotFound',+ 'SecretMissingKey',+ 'SecretAccessDenied',+ 'ReadError',+ 'SecretValidationFailed',+]++/** Types that must never participate in the selection — including near-misses+ * that a case-insensitive or substring match would wrongly accept. */+const IRRELEVANT_TYPES = [+ 'Ready',+ 'DeploymentReady',+ 'NetworkReady',+ 'secretresolved',+ 'SecretResolvedd',+ 'NotSecretResolved',+]++const SPECS: ({ managed?: boolean } | undefined)[] = [+ { managed: true },+ { managed: false },+ {},+ { managed: undefined },+ undefined,+]++type GeneratedCase = {+ conditions: McpServerCondition[]+ spec: { managed?: boolean } | undefined+ relevantCount: number+}++function makeCondition(+ rand: () => number,+ type: string,+ index: number,+ seq: number+): McpServerCondition {+ const timestamp = TIMESTAMPS[Math.floor(rand() * TIMESTAMPS.length)]+ const condition: Record<string, unknown> = {+ type,+ status: STATUSES[Math.floor(rand() * STATUSES.length)],+ reason: REASONS[Math.floor(rand() * REASONS.length)],+ // Distinct so a failure message identifies exactly which entry won.+ message: `generated condition #${seq} at slot ${index}`,+ }+ // A missing `lastTransitionTime` means the property is ABSENT, not undefined:+ // that is the shape a hand-edited resource actually has.+ if (timestamp !== undefined) condition.lastTransitionTime = timestamp+ return condition as unknown as McpServerCondition+}++/**+ * Relevant cardinality is drawn from a distribution weighted well past two —+ * 3, 4, 5, 6 and 7 relevant conditions all occur — because two is precisely the+ * bound the reviewer's mutant respected.+ */+const RELEVANT_COUNTS = [0, 1, 2, 2, 3, 3, 3, 4, 4, 5, 5, 6, 7]++function generateCase(rand: () => number, seq: number): GeneratedCase {+ const relevantCount = RELEVANT_COUNTS[Math.floor(rand() * RELEVANT_COUNTS.length)]+ const irrelevantCount = Math.floor(rand() * 5)++ const conditions: McpServerCondition[] = []+ for (let i = 0; i < relevantCount; i++) {+ conditions.push(makeCondition(rand, SECRET_RESOLVED, i, seq))+ }+ // Irrelevant conditions are spliced in at RANDOM positions, so they shift the+ // relevant entries' indices and would poison any index-based selection.+ for (let i = 0; i < irrelevantCount; i++) {+ const type = IRRELEVANT_TYPES[Math.floor(rand() * IRRELEVANT_TYPES.length)]+ const at = Math.floor(rand() * (conditions.length + 1))+ conditions.splice(at, 0, makeCondition(rand, type, at, seq))+ }++ return {+ conditions,+ spec: SPECS[Math.floor(rand() * SPECS.length)],+ relevantCount,+ }+}++function describeCase(+ label: string,+ generated: GeneratedCase,+ expected: CredentialSurface,+ actual: CredentialSurface+): string {+ return [+ `${label}`,+ ` expected (reference model): ${expected}`,+ ` actual (implementation): ${actual}`,+ ` spec: ${JSON.stringify(generated.spec)}`,+ ` conditions (${generated.conditions.length}, ${generated.relevantCount} relevant):`,+ ...generated.conditions.map(+ (condition, index) =>+ ` [${index}] rank=${referenceRank(condition.lastTransitionTime)} ${JSON.stringify(condition)}`+ ),+ ].join('\n')+}++/** Runs the full invariant battery on one case. Throws with the whole case on+ * any violation, so a red is reproducible and diagnosable from the output. */+function checkCase(label: string, generated: GeneratedCase): void {+ const { conditions, spec } = generated++ const structureBefore = JSON.stringify(conditions)+ const identityBefore = [...conditions]++ const actual = resolveCredentialSurface(conditions, spec)+ const expected = referenceResolve(conditions, spec)++ if (actual !== expected) {+ throw new Error(+ describeCase(`${label}: disagreed with the reference model`, generated, expected, actual)+ )+ }++ // Determinism: the SAME array must resolve the same way every time. (Two+ // different permutations of a tie legitimately differ — that is the rule.)+ for (let repeat = 0; repeat < 3; repeat++) {+ const again = resolveCredentialSurface(conditions, spec)+ if (again !== actual) {+ throw new Error(describeCase(`${label}: not deterministic`, generated, actual, again))+ }+ }++ // Immutability: the caller's array is React state. No sort, no splice, no+ // reverse — neither the order, the element identity, nor the values.+ if (JSON.stringify(conditions) !== structureBefore) {+ throw new Error(+ `${label}: the conditions array was MUTATED\n before: ${structureBefore}\n after: ${JSON.stringify(conditions)}`+ )+ }+ if (+ conditions.length !== identityBefore.length ||+ identityBefore.some((condition, index) => conditions[index] !== condition)+ ) {+ throw new Error(`${label}: the conditions array was REORDERED (element identity changed)`)+ }+}++// ─── The suites ────────────────────────────────────────────────────────────++const SEEDS = [1, 7, 42, 1337, 20_260_807]+const CASES_PER_SEED = 600++describe('resolveCredentialSurface — reference-model equivalence over generated inputs', () => {+ it('matches the reference model on every generated case', () => {+ let checked = 0+ let highCardinality = 0+ let maxRelevant = 0++ for (const seed of SEEDS) {+ const rand = mulberry32(seed)+ for (let iteration = 0; iteration < CASES_PER_SEED; iteration++) {+ const generated = generateCase(rand, checked)+ checkCase(`seed ${seed} / iteration ${iteration}`, generated)+ checked += 1+ if (generated.relevantCount >= 3) highCardinality += 1+ maxRelevant = Math.max(maxRelevant, generated.relevantCount)+ }+ }++ expect(checked).toBe(SEEDS.length * CASES_PER_SEED)+ // Coverage guard. A generator that quietly stopped producing 3+ relevant+ // conditions would make this whole suite pass while re-opening the exact+ // hole it exists to close, so the shape of the corpus is asserted too.+ expect(maxRelevant).toBeGreaterThanOrEqual(5)+ expect(highCardinality).toBeGreaterThan(checked / 4)+ })++ /**+ * The generated corpus is random; this one is exhaustive. Every array of+ * length 1..4 over a small alphabet chosen so each pair of entries can tie,+ * outrank, or be outranked — 780 cases, all with a known-correct answer.+ *+ * This is what makes 3- and 4-cardinality coverage a fact rather than a+ * property of the PRNG.+ */+ it('matches the reference model on every array of length 1..4 over a tie-rich alphabet', () => {+ // Both valid stamps sit in late February on purpose: see the malformed+ // entry below.+ const T_OLD = '2026-02-27T00:00:00.000Z'+ const T_NEW = '2026-02-28T00:00:00.000Z'+ const alphabet: McpServerCondition[] = [+ secretNotFound({ at: T_OLD }),+ secretFound({ at: T_OLD }),+ secretNotFound({ at: T_NEW }),+ secretFound({ at: T_NEW }),+ // Malformed calendar: shares the oldest rank with every other malformed+ // entry, and must never outrank either valid stamp above.+ //+ // February 30 specifically. Hour 25 and month 13 fall outside the ISO+ // grammar and `new Date()` rejects them outright, so they would NOT+ // distinguish strict validation from a bare parse. February 30 does: it+ // is inside the grammar, `new Date()` normalizes it to March 2, and that+ // ranks it ahead of both valid late-February stamps above.+ { ...secretNotFound({ at: T_NEW }), lastTransitionTime: '2026-02-30T00:00:00.000Z' },+ ]++ let checked = 0+ for (const spec of [{ managed: true }, { managed: false }] as const) {+ for (let length = 1; length <= 4; length++) {+ const total = alphabet.length ** length+ for (let code = 0; code < total; code++) {+ const conditions: McpServerCondition[] = []+ let remaining = code+ for (let slot = 0; slot < length; slot++) {+ conditions.push(alphabet[remaining % alphabet.length])+ remaining = Math.floor(remaining / alphabet.length)+ }+ checkCase(`exhaustive length ${length} / code ${code}`, {+ conditions,+ spec,+ relevantCount: length,+ })+ checked += 1+ }+ }+ }+ expect(checked).toBe(2 * (5 + 25 + 125 + 625))+ })+})++describe('resolveCredentialSurface — R1-M2 named regressions', () => {+ // THE REVIEWER'S COUNTEREXAMPLE. Ranking only the LAST TWO candidates drops+ // the newest condition — the clean resolution — and returns 'set', re-opening+ // POST against a Secret that exists.+ it('ranks ALL relevant conditions, not just the last two', () => {+ const conditions = [+ secretFound({ at: '2026-08-06T09:00:00.000Z' }),+ secretNotFound({ at: '2026-08-06T07:00:00.000Z' }),+ secretNotFound({ at: '2026-08-06T08:00:00.000Z' }),+ ]+ expect(resolveCredentialSurface(conditions, { managed: true })).toBe('rotate')+ expect(referenceResolve(conditions, { managed: true })).toBe('rotate')+ // Same counterexample on a WRC-owned connector: still no create form.+ expect(resolveCredentialSurface(conditions, { managed: false })).toBe('rotate')+ })++ // The mirror image: the newest IS the absence claim, and it sits FIRST behind+ // four newer-looking-but-older entries. A bounded selector misses it and+ // leaves the operator on a rotate form whose PUT can only 404.+ it('finds the newest absence claim when it is buried at the head of five', () => {+ const conditions = [+ secretNotFound({ at: '2026-08-06T09:00:00.000Z' }),+ secretFound({ at: '2026-08-06T05:00:00.000Z' }),+ secretMissingKey({ at: '2026-08-06T06:00:00.000Z' }),+ secretFound({ at: '2026-08-06T07:00:00.000Z' }),+ secretMissingKey({ at: '2026-08-06T08:00:00.000Z' }),+ ]+ expect(resolveCredentialSurface(conditions, { managed: true })).toBe('set')+ expect(resolveCredentialSurface(conditions, { managed: false })).toBe('recipe-owned')+ expect(referenceResolve(conditions, { managed: true })).toBe('set')+ })++ // Seven relevant conditions with the decisive one in the middle, bracketed by+ // irrelevant types that carry the newest timestamps in the array.+ it('ranks the middle of seven correctly with newer irrelevant types around it', () => {+ const newest = '2026-08-06T23:00:00.000Z'+ const conditions: McpServerCondition[] = [+ {+ type: 'Ready',+ status: 'False',+ reason: 'SecretNotFound',+ message: '',+ lastTransitionTime: newest,+ },+ secretFound({ at: '2026-08-06T01:00:00.000Z' }),+ secretMissingKey({ at: '2026-08-06T02:00:00.000Z' }),+ secretFound({ at: '2026-08-06T03:00:00.000Z' }),+ secretNotFound({ at: '2026-08-06T10:00:00.000Z' }),+ secretFound({ at: '2026-08-06T04:00:00.000Z' }),+ secretMissingKey({ at: '2026-08-06T05:00:00.000Z' }),+ secretFound({ at: '2026-08-06T06:00:00.000Z' }),+ {+ type: 'DeploymentReady',+ status: 'False',+ reason: 'SecretNotFound',+ message: '',+ lastTransitionTime: newest,+ },+ ]+ expect(resolveCredentialSurface(conditions, { managed: true })).toBe('set')+ expect(referenceResolve(conditions, { managed: true })).toBe('set')+ })++ // The positional tie-break across FOUR equally-ranked entries: the last one+ // decides, and flipping which verdict sits last flips the surface.+ it('breaks a four-way exact tie on the LAST entry', () => {+ const at = '2026-08-06T09:00:00.000Z'+ const absentLast = [+ secretFound({ at }),+ secretMissingKey({ at }),+ secretFound({ at }),+ secretNotFound({ at }),+ ]+ const resolvedLast = [+ secretNotFound({ at }),+ secretMissingKey({ at }),+ secretNotFound({ at }),+ secretFound({ at }),+ ]+ expect(resolveCredentialSurface(absentLast, { managed: true })).toBe('set')+ expect(resolveCredentialSurface(resolvedLast, { managed: true })).toBe('rotate')+ expect(referenceResolve(absentLast, { managed: true })).toBe('set')+ expect(referenceResolve(resolvedLast, { managed: true })).toBe('rotate')+ })++ // Five malformed timestamps all share the oldest rank, so this is a five-way+ // tie resolved positionally — and none of them may outrank the valid stamp.+ it('keeps every malformed timestamp below a valid one, however many there are', () => {+ const malformed = [+ '2026-02-30T00:00:00.000Z',+ '2026-13-01T00:00:00.000Z',+ '2026-08-06T25:00:00.000Z',+ 'not-a-timestamp',+ '',+ ].map(lastTransitionTime => ({+ ...secretNotFound({ at: '2026-08-06T01:00:00.000Z' }),+ lastTransitionTime,+ }))+ const valid = secretFound({ at: '2020-01-01T00:00:00.000Z' })+ expect(resolveCredentialSurface([...malformed, valid], { managed: true })).toBe('rotate')+ expect(resolveCredentialSurface([valid, ...malformed], { managed: true })).toBe('rotate')+ expect(referenceResolve([...malformed, valid], { managed: true })).toBe('rotate')+ })+})++describe('resolveCredentialSurface — the caller’s array is read-only', () => {+ // A frozen array makes an in-place sort THROW rather than silently reorder,+ // which pins the no-mutation rule independently of the snapshot comparison.+ it('resolves a deep-frozen conditions array without throwing', () => {+ const conditions = Object.freeze(+ [+ secretFound({ at: '2026-08-06T09:00:00.000Z' }),+ secretNotFound({ at: '2026-08-06T07:00:00.000Z' }),+ secretMissingKey({ at: '2026-08-06T08:00:00.000Z' }),+ secretNotFound({ at: '2026-08-06T06:00:00.000Z' }),+ ].map(condition => Object.freeze(condition))+ ) as unknown as McpServerCondition[]++ expect(() => resolveCredentialSurface(conditions, { managed: true })).not.toThrow()+ expect(resolveCredentialSurface(conditions, { managed: true })).toBe('rotate')+ })+})diff --git a/control-ui/components/__tests__/secretResolvedProducerContract.test.ts b/control-ui/components/__tests__/secretResolvedProducerContract.test.tsnew file mode 100644index 000000000..14b6fadf4--- /dev/null+++ b/control-ui/components/__tests__/secretResolvedProducerContract.test.ts@@ -0,0 +1,482 @@+import { describe, expect, it } from 'vitest'+import { readFileSync } from 'node:fs'+import path from 'node:path'+import { fileURLToPath } from 'node:url'+import { resolveCredentialSurface } from '@components/UpdateConnectorCredentials/resolveCredentialSurface'+import type { McpServerCondition } from '@lib/api'+import {+ SECRET_RESOLVED,+ secretAccessDenied,+ secretFound,+ secretMissingKey,+ secretNotFound,+ syntheticCondition,+ withoutTimestamp,+} from './fixtures/secretResolvedConditions'++// ─── R1-H2: the fixture builders are checked AGAINST the real producer ─────+//+// `fixtures/secretResolvedConditions.ts` used to be a handwritten mirror of the+// host-context-controller: if HCC changed a SecretResolved status, reason or+// message, the UI suites stayed green because BOTH the mocked producer output+// and the assertion encoded the UI author's stale assumption.+//+// This suite closes that by reading `host-context-controller/src/reconciler.ts`+// off disk, extracting the condition writes and the `validateSecret` failure+// results as DATA, and asserting the fixture builders reproduce exactly those+// triples. A producer contract change turns this file red.+//+// The extraction is deliberately brittle in the safe direction. Every step that+// can no longer find its producer site throws with a message naming what moved,+// because a silently-empty match set would pass trivially and be worse than the+// handwritten mirror it replaced.+//+// This file reads source text only. It does NOT import the controller: making+// control-ui depend on an HCC package at runtime would be heavier coupling than+// the drift it prevents, and this PR is control-ui-scoped.++const RECONCILER_PATH = path.resolve(+ path.dirname(fileURLToPath(import.meta.url)),+ '../../../host-context-controller/src/reconciler.ts'+)++/** Smallest size the real reconciler has ever been, by a wide margin. A stub,+ * a truncated read or an empty file must not be mistaken for "no producer". */+const MIN_PRODUCER_BYTES = 20_000++function readProducerSource(): string {+ let source: string+ try {+ source = readFileSync(RECONCILER_PATH, 'utf8')+ } catch (error) {+ throw new Error(+ `SecretResolved producer contract: cannot read the producer at ${RECONCILER_PATH}. ` ++ `If the host-context-controller moved, update RECONCILER_PATH — do NOT delete this ` ++ `suite, it is the only thing tying the UI fixtures to the real conditions. ` ++ `(${error instanceof Error ? error.message : String(error)})`+ )+ }+ if (source.length < MIN_PRODUCER_BYTES) {+ throw new Error(+ `SecretResolved producer contract: ${RECONCILER_PATH} is only ${source.length} bytes, ` ++ `below the ${MIN_PRODUCER_BYTES}-byte floor. Refusing to derive a contract from what ` ++ `is almost certainly not the real reconciler.`+ )+ }+ return source+}++const source = readProducerSource()+const lines = source.split('\n')++// ─── Extraction 1: every `SecretResolved` condition write ──────────────────++type ConditionWrite = {+ /** 1-based line of the `type:` property, for failure messages. */+ line: number+ status: string+ /** RAW source expression, e.g. `'SecretFound'` or `secretResult.reason`. */+ reason: string+ /** RAW source expression, e.g. `'Secret resolved and validated'`. */+ message: string+}++function matchProperty(line: string | undefined, re: RegExp, at: number, what: string): string {+ const matched = line === undefined ? null : re.exec(line)+ if (!matched) {+ throw new Error(+ `SecretResolved producer contract: expected a \`${what}\` property at ` ++ `${path.basename(RECONCILER_PATH)}:${at}, found ${JSON.stringify(line ?? null)}. ` ++ `The producer's condition literal changed shape; re-derive this extractor.`+ )+ }+ return matched[1]+}++function extractConditionWrites(): ConditionWrite[] {+ const anchors: number[] = []+ lines.forEach((line, index) => {+ if (/^\s*type: 'SecretResolved',$/.test(line)) anchors.push(index)+ })+ if (anchors.length === 0) {+ throw new Error(+ `SecretResolved producer contract: found NO \`type: 'SecretResolved',\` condition writes in ` ++ `${RECONCILER_PATH}. Either the producer stopped writing the condition the credential ` ++ `screen depends on, or this extractor no longer matches it. Both are release blockers.`+ )+ }+ return anchors.map(index => ({+ line: index + 1,+ status: matchProperty(lines[index + 1], /^\s*status: '([A-Za-z]+)',$/, index + 2, 'status'),+ reason: matchProperty(lines[index + 2], /^\s*reason: (.+),$/, index + 3, 'reason'),+ message: matchProperty(lines[index + 3], /^\s*message: (.+),$/, index + 4, 'message'),+ }))+}++const conditionWrites = extractConditionWrites()++/**+ * The producer sites known when this contract was written: two `True` writes+ * (managed at ~:1981, WRC-owned at ~:2063) and two `False` writes that forward+ * `validateSecret`'s result (~:1872 and ~:2041).+ *+ * A change to this count is not automatically wrong, but it means a NEW way for+ * the UI to observe `SecretResolved` appeared, and the fixture contract below+ * has to be re-derived rather than assumed to still cover it.+ */+const KNOWN_PRODUCER_WRITE_SITES = 4++const isStringLiteral = (expression: string) => /^'[^']*'$/.test(expression)+const unquote = (expression: string) => expression.slice(1, -1)++const literalWrites = conditionWrites.filter(+ write => isStringLiteral(write.reason) && isStringLiteral(write.message)+)+const derivedWrites = conditionWrites.filter(+ write => write.reason === 'secretResult.reason' && write.message === 'secretResult.message'+)++// ─── Extraction 2: `validateSecret`'s failure results ──────────────────────++/** reason -> the message TEMPLATE source the producer builds for it. */+type FailureResult = { reason: string; template: string }++/**+ * Collapses a possibly multi-line, possibly `+`-concatenated template literal+ * into the single template it evaluates to. `\`a \` +\n \`b\`` becomes `a b`.+ */+function normalizeTemplate(raw: string, context: string): string {+ const oneLine = raw.replace(/\s*\n\s*/g, ' ').trim()+ const joined = oneLine.replace(/`\s*\+\s*`/g, '')+ if (!joined.startsWith('`') || !joined.endsWith('`') || joined.length < 2) {+ throw new Error(+ `SecretResolved producer contract: could not read the message template for ${context}. ` ++ `Expected one or more concatenated template literals, got ${JSON.stringify(raw)}.`+ )+ }+ return joined.slice(1, -1)+}++/** Walks BACK from a `return { ok: false, ..., message }` to the `const message =`+ * assignment that fed it, then forward until the literal is closed. */+function templateFromPrecedingAssignment(returnLine: number, reason: string): string {+ for (let index = returnLine; index >= 0; index--) {+ const assignment = /^\s*const message =(.*)$/.exec(lines[index])+ if (!assignment) continue+ let raw = assignment[1]+ let cursor = index+ // Keep consuming lines while the template literal is still open or the+ // expression continues with a trailing `+`.+ while (+ cursor < lines.length - 1 &&+ ((raw.match(/`/g) ?? []).length % 2 === 1 || raw.trimEnd().endsWith('+') || raw.trim() === '')+ ) {+ cursor += 1+ raw += `\n${lines[cursor]}`+ }+ return normalizeTemplate(+ raw,+ `reason '${reason}' (${path.basename(RECONCILER_PATH)}:${index + 1})`+ )+ }+ throw new Error(+ `SecretResolved producer contract: \`return { ok: false, reason: '${reason}', message }\` at ` ++ `${path.basename(RECONCILER_PATH)}:${returnLine + 1} has no preceding \`const message =\`. ` ++ `The producer's failure construction changed; re-derive this extractor.`+ )+}++function extractFailureResults(): FailureResult[] {+ const results: FailureResult[] = []+ lines.forEach((line, index) => {+ // Inline form: `return { ok: false, reason: 'X', message }`+ const inline = /^\s*return \{ ok: false, reason: '([A-Za-z]+)', message \},?$/.exec(line)+ if (inline) {+ results.push({+ reason: inline[1],+ template: templateFromPrecedingAssignment(index, inline[1]),+ })+ return+ }+ // Object form:+ // return {+ // ok: false,+ // reason: 'X',+ // message: `...`,+ // }+ const objectReason = /^\s*reason: '([A-Za-z]+)',$/.exec(line)+ if (objectReason && /^\s*ok: false,$/.test(lines[index - 1] ?? '')) {+ const inlineMessage = /^\s*message: (.+),$/.exec(lines[index + 1] ?? '')+ if (!inlineMessage) {+ throw new Error(+ `SecretResolved producer contract: the \`ok: false\` result at ` ++ `${path.basename(RECONCILER_PATH)}:${index + 1} has no \`message:\` property after its ` ++ `reason. The producer's failure construction changed; re-derive this extractor.`+ )+ }+ results.push({+ reason: objectReason[1],+ template: normalizeTemplate(+ inlineMessage[1],+ `reason '${objectReason[1]}' (${path.basename(RECONCILER_PATH)}:${index + 2})`+ ),+ })+ }+ })+ if (results.length === 0) {+ throw new Error(+ `SecretResolved producer contract: found NO \`ok: false\` validateSecret results in ` ++ `${RECONCILER_PATH}. Every False SecretResolved condition forwards one of them, so an ` ++ `empty set means the extractor is broken, not that the failures are gone.`+ )+ }+ return results+}++const failureResults = extractFailureResults()+const failureByReason = new Map(failureResults.map(result => [result.reason, result]))++/** The declared failure-reason union on `SecretValidationResult`. */+function extractFailureReasonUnion(): string[] {+ const declaration = /^\s*reason: ((?:'[A-Za-z]+'(?:\s*\|\s*)?)+)$/m.exec(source)+ if (!declaration) {+ throw new Error(+ `SecretResolved producer contract: could not find the SecretValidationResult failure-reason ` ++ `union in ${RECONCILER_PATH}. It is the producer's own enumeration of what a False ` ++ `SecretResolved can say; without it this contract cannot detect a new reason.`+ )+ }+ return (declaration[1].match(/'([A-Za-z]+)'/g) ?? []).map(literal => literal.slice(1, -1))+}++const failureReasonUnion = extractFailureReasonUnion()++// ─── Substituting a producer template with sentinel values ─────────────────++const SENTINEL = {+ secretName: 'sentinel-secret-name',+ namespace: 'sentinel-namespace',+ secretKey: 'sentinel-secret-key',+ envVar: 'SENTINEL_ENV_VAR',+ code: 418,+ errMsg: 'sentinel-read-error',+}++/**+ * Producer interpolation expression -> the value the fixture builder puts in+ * that slot. Every value is distinctive, so a builder that fills the right+ * template with the WRONG argument still fails.+ *+ * An unmapped expression throws: a new interpolation in the producer message is+ * exactly the drift this suite exists to catch.+ */+const PLACEHOLDER_VALUES: Record<string, string> = {+ secretName: SENTINEL.secretName,+ 'server.namespace': SENTINEL.namespace,+ 'keyMapping.secretKey': SENTINEL.secretKey,+ 'keyMapping.envVar': SENTINEL.envVar,+ code: String(SENTINEL.code),+ errMsg: SENTINEL.errMsg,+}++function renderProducerTemplate(reason: string): string {+ const result = failureByReason.get(reason)+ if (!result) {+ throw new Error(+ `SecretResolved producer contract: the producer no longer returns reason '${reason}'. ` ++ `It does return: ${failureResults.map(r => r.reason).join(', ')}.`+ )+ }+ return result.template.replace(/\$\{([^}]+)\}/g, (_whole, expression: string) => {+ const value = PLACEHOLDER_VALUES[expression]+ if (value === undefined) {+ throw new Error(+ `SecretResolved producer contract: the message for '${reason}' interpolates ` ++ `\${${expression}}, which no fixture argument maps to. Add it to PLACEHOLDER_VALUES and ` ++ `thread the value through the matching builder in fixtures/secretResolvedConditions.ts.`+ )+ }+ return value+ })+}++const AT = '2026-08-06T04:00:00.000Z'++describe('SecretResolved producer contract — extraction guards', () => {+ it('finds the producer condition writes it expects to find', () => {+ expect(conditionWrites.length).toBe(KNOWN_PRODUCER_WRITE_SITES)+ // Every write must be one of the two known shapes. A third shape means the+ // UI can observe a condition this contract says nothing about.+ expect(literalWrites.length + derivedWrites.length).toBe(conditionWrites.length)+ expect(literalWrites.length).toBeGreaterThan(0)+ expect(derivedWrites.length).toBeGreaterThan(0)+ })++ it('finds a validateSecret failure result for every declared failure reason', () => {+ expect(failureReasonUnion.length).toBeGreaterThan(0)+ expect(new Set(failureResults.map(result => result.reason))).toEqual(+ new Set(failureReasonUnion)+ )+ })++ it('resolves every producer message template to a concrete string', () => {+ for (const reason of failureReasonUnion) {+ const rendered = renderProducerTemplate(reason)+ expect(rendered).not.toContain('${')+ expect(rendered.length).toBeGreaterThan(0)+ }+ })+})++describe('SecretResolved producer contract — fixture builders match the producer', () => {+ it('builds conditions under the producer’s own condition type', () => {+ // Extracted from the anchor the writes were found on, not restated here.+ expect(SECRET_RESOLVED).toBe('SecretResolved')+ for (const write of conditionWrites) {+ expect(lines[write.line - 1].trim()).toBe(`type: '${SECRET_RESOLVED}',`)+ }+ })++ it('secretFound() reproduces the producer’s success triple, and both sites agree', () => {+ const successWrites = literalWrites.filter(write => write.status === 'True')+ expect(successWrites.length).toBeGreaterThan(0)+ // All True sites must write the same triple; otherwise one fixture cannot+ // stand for both and the builder has to grow a discriminator.+ const distinct = new Set(successWrites.map(write => `${write.reason}|${write.message}`))+ expect(distinct.size).toBe(1)++ const producer = successWrites[0]+ const fixture = secretFound({ at: AT })+ expect(fixture.status).toBe(producer.status)+ expect(fixture.reason).toBe(unquote(producer.reason))+ expect(fixture.message).toBe(unquote(producer.message))+ expect(fixture.lastTransitionTime).toBe(AT)+ })++ it('the failure builders reproduce the producer’s status', () => {+ const failureStatuses = new Set(derivedWrites.map(write => write.status))+ expect(failureStatuses.size).toBe(1)+ const status = [...failureStatuses][0]+ expect(secretNotFound({ at: AT }).status).toBe(status)+ expect(secretMissingKey({ at: AT }).status).toBe(status)+ expect(secretAccessDenied({ at: AT }).status).toBe(status)+ })++ it('secretNotFound() reproduces the producer’s 404 reason and message', () => {+ const fixture = secretNotFound({+ at: AT,+ secretName: SENTINEL.secretName,+ namespace: SENTINEL.namespace,+ })+ expect(failureReasonUnion).toContain(fixture.reason)+ expect(fixture.message).toBe(renderProducerTemplate(fixture.reason))+ })++ it('secretMissingKey() reproduces the producer’s missing-key reason and message', () => {+ const fixture = secretMissingKey({+ at: AT,+ secretName: SENTINEL.secretName,+ secretKey: SENTINEL.secretKey,+ envVar: SENTINEL.envVar,+ })+ expect(failureReasonUnion).toContain(fixture.reason)+ expect(fixture.message).toBe(renderProducerTemplate(fixture.reason))+ })++ it('secretAccessDenied() reproduces the producer’s 401/403 reason and message', () => {+ const fixture = secretAccessDenied({+ at: AT,+ secretName: SENTINEL.secretName,+ namespace: SENTINEL.namespace,+ code: SENTINEL.code,+ })+ expect(failureReasonUnion).toContain(fixture.reason)+ expect(fixture.message).toBe(renderProducerTemplate(fixture.reason))+ })++ /**+ * `ReadError` is a transient k8s read failure — HCC could not look, so it is+ * no evidence about the Secret and the resolver must keep the rotate form.+ * It gets no builder because no test needs to distinguish it from+ * `SecretAccessDenied`; the surface assertion below covers it by extraction.+ *+ * Any OTHER unmodelled reason fails here: a new producer reason has to be+ * triaged against the create path before this suite goes green again.+ */+ const UNMODELLED_BY_DESIGN = new Set(['ReadError'])++ it('every producer failure reason is modelled by a builder or explicitly waived', () => {+ const modelled = new Set(+ [+ secretNotFound({ at: AT }),+ secretMissingKey({ at: AT }),+ secretAccessDenied({ at: AT }),+ ].map(condition => condition.reason)+ )+ const unaccounted = failureReasonUnion.filter(+ reason => !modelled.has(reason) && !UNMODELLED_BY_DESIGN.has(reason)+ )+ expect(unaccounted).toEqual([])+ })+})++describe('SecretResolved producer contract — the resolver’s reading of it', () => {+ /** A producer-shaped False condition for an arbitrary extracted reason. */+ function producerFailure(reason: string): McpServerCondition {+ const status = derivedWrites[0].status as McpServerCondition['status']+ return {+ type: SECRET_RESOLVED,+ status,+ reason,+ message: renderProducerTemplate(reason),+ lastTransitionTime: AT,+ }+ }++ it('sends the operator to the create form for exactly one producer failure reason', () => {+ const sendsToCreate = failureReasonUnion.filter(+ reason => resolveCredentialSurface([producerFailure(reason)], { managed: true }) === 'set'+ )+ // One reason, and it is the one `secretNotFound()` builds — not a literal+ // restated here. Every other producer failure keeps the rotate form.+ expect(sendsToCreate).toEqual([secretNotFound({ at: AT }).reason])+ })++ it('keeps the rotate form for the producer’s success triple', () => {+ expect(resolveCredentialSurface([secretFound({ at: AT })], { managed: true })).toBe('rotate')+ })+})++describe('SecretResolved producer contract — adversarial fixtures are provably impossible', () => {+ // The synthetic builders exist so an adversarial fixture is never mistaken+ // for producer shape. These assertions prove they are outside it, derived+ // from the extraction rather than asserted by comment.++ it('the producer never writes SecretResolved at a status the synthetic builder can', () => {+ const producerStatuses = new Set(conditionWrites.map(write => write.status))+ const synthetic = syntheticCondition({ status: 'Unknown', lastTransitionTime: AT })+ expect(producerStatuses.has(synthetic.status)).toBe(false)+ })++ it('the producer never writes a SecretResolved reason under another condition type', () => {+ const synthetic = syntheticCondition({ type: 'Ready', lastTransitionTime: AT })+ expect(synthetic.type).not.toBe(SECRET_RESOLVED)+ // No condition write in the producer carries a SecretResolved failure+ // reason on a non-SecretResolved type.+ const anchorLines = new Set(conditionWrites.map(write => write.line - 1))+ lines.forEach((line, index) => {+ const reason = /^\s*reason: '([A-Za-z]+)',$/.exec(line)+ if (!reason || !failureReasonUnion.includes(reason[1])) return+ const typeLine = lines[index - 1] ?? ''+ // Either it is the validateSecret result itself, or it sits directly+ // under a `type: 'SecretResolved',` anchor.+ const isValidationResult = /^\s*ok: false,$/.test(typeLine)+ expect(isValidationResult || anchorLines.has(index - 2)).toBe(true)+ })+ })++ it('the producer always stamps lastTransitionTime, so the missing-stamp fixture is synthetic', () => {+ expect(/^\s*lastTransitionTime,$/m.test(source)).toBe(true)+ expect(withoutTimestamp(secretNotFound({ at: AT })).lastTransitionTime).toBeUndefined()+ })+})diff --git a/control-ui/package-lock.json b/control-ui/package-lock.jsonindex 5cfbb5214..e9e53e45c 100644--- a/control-ui/package-lock.json+++ b/control-ui/package-lock.json@@ -1,12 +1,12 @@{"name": "clerum-control-ui",- "version": "0.1.401",+ "version": "0.1.402","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "clerum-control-ui",- "version": "0.1.401",+ "version": "0.1.402","dependencies": {"@clerum/llm-providers": "file:../packages/llm-providers","@clerum/workflow-recipe-capability-policy": "file:../packages/workflow-recipe-capability-policy",diff --git a/control-ui/package.json b/control-ui/package.jsonindex 95db2bbe8..893ab751c 100644--- a/control-ui/package.json+++ b/control-ui/package.json@@ -1,6 +1,6 @@{"name": "clerum-control-ui",- "version": "0.1.401",+ "version": "0.1.402","private": true,"scripts": {"dev": "NEXT_IGNORE_INCORRECT_LOCKFILE=1 next dev",