Skip to content

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

TypeScript

test(control-ui): close R1-H2 page coverage and R1-M2 timestamp authority (PR #277)

Jose Ramirez513a386257f5
diff --git a/control-ui/components/UpdateConnectorCredentials/resolveCredentialSurface.ts b/control-ui/components/UpdateConnectorCredentials/resolveCredentialSurface.ts
index 43618ac51..3b7ee5664 100644
--- a/control-ui/components/UpdateConnectorCredentials/resolveCredentialSurface.ts
+++ b/control-ui/components/UpdateConnectorCredentials/resolveCredentialSurface.ts
@@ -29,7 +29,85 @@ export function isRecipeOwned(spec: { managed?: boolean } | undefined): boolean
}
/**
- * Returns the ONE authoritative `SecretResolved` condition.
+ * RFC3339 date-time, the format the Kubernetes API server stamps
+ * `lastTransitionTime` with. Anchored on both ends: a trailing offset or `Z` is
+ * mandatory, so a bare local date-time (which `Date.parse` would happily read
+ * in the browser's timezone) is rejected.
+ */
+const RFC3339 = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.(\d+))?(Z|[+-]\d{2}:\d{2})$/
+
+/**
+ * Parses `lastTransitionTime` STRICTLY, returning epoch milliseconds, or `null`
+ * if the value is not a real instant (mini-spec C2).
+ *
+ * Two checks, and the second one is the load-bearing half:
+ *
+ * 1. syntax — the string must match RFC3339 exactly;
+ * 2. calendar round-trip — the parsed instant must carry back the very
+ * components it was given.
+ *
+ * `new Date('2026-02-30T00:00:00.000Z')` does NOT throw and is NOT `Invalid
+ * Date`: JavaScript silently normalizes February 30 into March 2. A syntax-only
+ * check would therefore accept that value and rank it two days in the FUTURE of
+ * the real February 28 — letting a malformed duplicate absence claim outrank a
+ * valid resolution and force the operator back through the create path. The
+ * round-trip is what rejects it: the normalized date reports day 2, not 30.
+ *
+ * Leap seconds (`:60`) are rejected by the same round-trip. RFC3339 permits
+ * them, the Kubernetes API server never emits one, and ranking such a value
+ * oldest is the safe reading anyway.
+ */
+function parseStrictRfc3339(value: string | undefined): number | null {
+ if (typeof value !== 'string') return null
+ const match = RFC3339.exec(value)
+ if (!match) return null
+
+ const [, year, month, day, hour, minute, second, fraction, offset] = match
+ // Sub-millisecond precision is truncated, exactly as `Date.parse` truncates
+ // it, so the round-trip below compares like with like.
+ const ms = Number((fraction ?? '').padEnd(3, '0').slice(0, 3))
+
+ // setUTCFullYear rather than Date.UTC: the latter maps years 0-99 onto
+ // 1900-1999, which would fail the round-trip for a four-digit year like 0099.
+ const candidate = new Date(0)
+ candidate.setUTCFullYear(Number(year), Number(month) - 1, Number(day))
+ candidate.setUTCHours(Number(hour), Number(minute), Number(second), ms)
+
+ const roundTrips =
+ candidate.getUTCFullYear() === Number(year) &&
+ candidate.getUTCMonth() === Number(month) - 1 &&
+ candidate.getUTCDate() === Number(day) &&
+ candidate.getUTCHours() === Number(hour) &&
+ candidate.getUTCMinutes() === Number(minute) &&
+ candidate.getUTCSeconds() === Number(second) &&
+ candidate.getUTCMilliseconds() === ms
+ if (!roundTrips) return null
+
+ if (offset === 'Z') return candidate.getTime()
+ // `+HH:MM` means the named wall-clock is that far AHEAD of UTC, so the
+ // instant is that much EARLIER than the same components read as UTC.
+ const sign = offset.startsWith('-') ? -1 : 1
+ const offsetHours = Number(offset.slice(1, 3))
+ const offsetMinutes = Number(offset.slice(4, 6))
+ if (offsetHours > 23 || offsetMinutes > 59) return null
+ return candidate.getTime() - sign * (offsetHours * 60 + offsetMinutes) * 60_000
+}
+
+/**
+ * The rank a condition competes on: its strictly-parsed instant, or
+ * `-Infinity` when it has none (mini-spec C3).
+ *
+ * Missing, empty, non-RFC3339 and invalid-calendar timestamps deliberately
+ * share ONE rank — the oldest possible. None of them carries recency evidence,
+ * so none may outrank a well-stamped condition, and there is no meaningful
+ * ordering among them to invent.
+ */
+function rankOf(condition: McpServerCondition): number {
+ return parseStrictRfc3339(condition.lastTransitionTime) ?? Number.NEGATIVE_INFINITY
+}
+
+/**
+ * Returns the ONE authoritative `SecretResolved` condition (mini-spec C1).
*
* The McpServer CRD declares `status.conditions` as an ordinary array and does
* NOT enforce uniqueness per `type`. HCC rewrites a type in place, but legacy
@@ -38,53 +116,43 @@ export function isRecipeOwned(spec: { managed?: boolean } | undefined): boolean
* arbitrarily stale entry win, which forces every key on the operator and
* re-enables POST against a Secret that already exists.
*
- * Ordering, from strongest to weakest key:
+ * Ordering:
+ *
+ * 1. Highest rank wins — the newest strictly-valid `lastTransitionTime`.
+ * Recency is the only real evidence of which statement the controller made
+ * last. A malformed timestamp ranks oldest (`rankOf`), so it can only win
+ * when nothing validly-stamped exists at all.
+ * 2. Among equal ranks — including several sharing the oldest rank — the LAST
+ * entry in array order wins (mini-spec C4). Kubernetes appends new
+ * condition types at the end and rewrites in place, so later position is
+ * the only ordering signal left once the timestamps have said nothing.
*
- * 1. Newest parseable `lastTransitionTime` wins — recency is the only real
- * evidence of which statement the controller made last.
- * 2. An absent, empty or unparseable timestamp ranks as the OLDEST possible.
- * It carries no recency proof, so it must never outrank a well-stamped
- * condition — in particular a malformed absence claim can never beat an
- * observed resolution.
- * 3. On an exact tie, the condition that does NOT claim absence wins.
- * Ambiguity must resolve away from "the Secret is missing": that verdict is
- * the destructive one (it demands every key and re-opens the create path),
- * while the rotate verdict is self-correcting — the PUT answers 404 if the
- * Secret really is gone, and the screen recovers from there.
- * 4. Still tied — every remaining candidate claims absence and therefore
- * agrees — so take the last array entry for determinism.
+ * The tie-break is deliberately positional rather than semantic. An earlier
+ * revision preferred "the candidate that does not claim absence", which reads
+ * as the safer choice but makes the array-order rule unobservable: two
+ * conditions of equal rank either agree on absence (same verdict) or are
+ * separated by that preference, so nothing can ever detect the positional rule
+ * being reversed. An untestable tie-break is not a contract — it is a comment.
+ *
+ * This function READS the array and never writes to it: no `sort`, no `splice`,
+ * no `reverse` (mini-spec C5). Callers pass React state straight from the
+ * fetched McpServer, and reordering it under them would mutate a rendered
+ * resource behind React's back.
*/
function selectAuthoritativeSecretResolved(
conditions: McpServerCondition[] | undefined
): McpServerCondition | undefined {
let best: McpServerCondition | undefined
- let bestTime = Number.NEGATIVE_INFINITY
+ let bestRank = Number.NEGATIVE_INFINITY
for (const candidate of conditions ?? []) {
if (candidate.type !== 'SecretResolved') continue
- const parsed = new Date(candidate.lastTransitionTime ?? '').getTime()
- const time = Number.isNaN(parsed) ? Number.NEGATIVE_INFINITY : parsed
-
- if (!best) {
- best = candidate
- bestTime = time
- continue
- }
- if (time > bestTime) {
- best = candidate
- bestTime = time
- continue
- }
- if (time < bestTime) continue
- // Exact tie (including two unparseable timestamps): rule 3, then rule 4.
- if (claimsAbsence(best) && !claimsAbsence(candidate)) {
+ const rank = rankOf(candidate)
+ // `>=`, not `>`: equal ranks resolve to the LAST such entry (rule 2).
+ if (best === undefined || rank >= bestRank) {
best = candidate
- bestTime = time
- continue
+ bestRank = rank
}
- if (!claimsAbsence(best) && claimsAbsence(candidate)) continue
- best = candidate
- bestTime = time
}
return best
diff --git a/control-ui/components/__tests__/EditMcpServerPageCredentials.test.tsx b/control-ui/components/__tests__/EditMcpServerPageCredentials.test.tsx
index 0ec76f0b2..46c7bfb79 100644
--- a/control-ui/components/__tests__/EditMcpServerPageCredentials.test.tsx
+++ b/control-ui/components/__tests__/EditMcpServerPageCredentials.test.tsx
@@ -5,22 +5,32 @@ import { ToastProvider } from '@components/Toast'
import EditMcpServerPage from '../../app/mcp-servers/[name]/edit/page'
import { createMcpSecret, getMcpServer, getMcpServers, updateMcpSecret } from '../../lib/api'
import type { McpServerCondition, McpServerResource } from '../../lib/api'
+import {
+ secretFound,
+ secretMissingKey,
+ secretNotFound,
+ syntheticCondition,
+} from './fixtures/secretResolvedConditions'
// ─── R1-H2: drive the REAL page, not the component in isolation ────────────
//
// The component tests inject `surface`/`recipeOwned` directly and the resolver
// tests call the resolver directly, so NEITHER covers the wiring in between.
-// The reviewer reproduced that gap twice: deleting the page's `surface` prop
-// left both changed suites 36/36 green, and resolving only the first condition
-// left the resolver suite 8/8 green. These tests close it by rendering the edit
-// page against a producer-shaped getMcpServer() response and asserting the UI
-// an operator would actually see.
+// The reviewer reproduced that gap three times: deleting the page's `surface`
+// prop left both changed suites green, resolving only the first condition left
+// the resolver suite green, and — round 2 — coupling the page's `recipeOwned`
+// to `status.conditions.length === 0` left all 69 changed tests green.
//
+// These tests close it by rendering the edit page against producer-shaped
+// getMcpServer() responses and asserting the UI an operator would actually see.
// Nothing here passes `surface` or `recipeOwned` by hand — the page must derive
-// both from the McpServer it loaded.
+// both from the McpServer it loaded — and every condition comes from the shared
+// producer builder (./fixtures/secretResolvedConditions), so a drift in the HCC
+// is a one-place fix rather than a hunt through hand-written literals.
const SERVER_NAME = 'linear-connector'
const SECRET_NAME = 'linear-credentials'
+const NAMESPACE = 'mcp-server'
const navigation = vi.hoisted(() => ({
params: { name: 'linear-connector' },
@@ -57,32 +67,25 @@ const mockGetMcpServers = vi.mocked(getMcpServers)
const mockUpdateMcpSecret = vi.mocked(updateMcpSecret)
const mockCreateMcpSecret = vi.mocked(createMcpSecret)
-/** A SecretResolved condition in the shape HCC writes it. */
-function secretResolved(
- overrides: Partial<McpServerCondition> & { lastTransitionTime: string }
-): McpServerCondition {
- return {
- type: 'SecretResolved',
- status: 'False',
- reason: 'SecretNotFound',
- message: `Secret "${SECRET_NAME}" not found in namespace "mcp-server"`,
- ...overrides,
- }
-}
+const CONNECTOR_IMAGE = 'ghcr.io/acme/linear-mcp:1.4.0'
/**
- * The producer: an McpServer as `GET /admin/mcp-servers/:name` returns it,
- * including the `spec.envSecret` the page has to narrow and the
- * `status.conditions` array the resolver has to reduce.
+ * An McpServer as `GET /admin/mcp-servers/:name` returns it, including the
+ * `spec.envSecret` the page has to narrow and the `status` the resolver has to
+ * reduce.
+ *
+ * `status` is passed through EXACTLY as given, including `undefined`: the
+ * connector-just-created race leaves the subresource absent altogether, which
+ * is a different shape from `{ conditions: [] }` and has to be testable as one.
*/
function mcpServer(options: {
managed?: boolean
- conditions?: McpServerCondition[]
+ status?: { conditions?: McpServerCondition[] }
}): McpServerResource {
return {
- metadata: { name: SERVER_NAME, namespace: 'mcp-server' },
+ metadata: { name: SERVER_NAME, namespace: NAMESPACE },
spec: {
- image: 'ghcr.io/acme/linear-mcp:1.4.0',
+ image: CONNECTOR_IMAGE,
contextRef: 'default',
...(options.managed === undefined ? {} : { managed: options.managed }),
envSecret: {
@@ -93,7 +96,7 @@ function mcpServer(options: {
],
},
},
- status: { conditions: options.conditions ?? [] },
+ ...(options.status === undefined ? {} : { status: options.status }),
}
}
@@ -108,7 +111,70 @@ async function renderPage(server: McpServerResource) {
// Anchor on the loaded connector's own image: it renders only after
// getMcpServer() resolves, and it is surface-independent (the credential
// panel's own title changes between set/rotate/recipe-owned).
- await screen.findByText('ghcr.io/acme/linear-mcp:1.4.0')
+ await screen.findByText(CONNECTOR_IMAGE)
+}
+
+/** The credential panel, scoped so "no submit control" means no control in
+ * THIS section rather than none on a page that also has Save egress/Cancel. */
+function credentialPanel(): HTMLElement {
+ const heading = screen.getByRole('heading', { name: /^(Update|Set) credentials$/ })
+ const section = heading.closest('section')
+ if (!section) throw new Error('credential FormSection not found')
+ return section
+}
+
+/**
+ * Drives the LATE-DISCOVERY journey: fill PARTIAL rotate data (one of the two
+ * declared keys), submit, confirm, and have the real PUT answer a
+ * status-bearing 404 — the only way a connector whose status never said
+ * "missing" can learn its Secret is gone.
+ */
+async function submitPartialRotateAndGet404() {
+ mockUpdateMcpSecret.mockRejectedValue(
+ Object.assign(new Error(`404 - Secret "${SECRET_NAME}" not found in ${NAMESPACE}`), {
+ status: 404,
+ })
+ )
+ fireEvent.change(screen.getByLabelText('api-key'), { target: { value: 'partial-value' } })
+ fireEvent.click(screen.getByRole('button', { name: 'Rotate credentials' }))
+ const dialog = await screen.findByRole('alertdialog')
+ fireEvent.click(within(dialog).getByRole('button', { name: 'Rotate & restart' }))
+}
+
+/** Invariant O2 at the page level: explanation only. */
+function expectExplanationOnly() {
+ const panel = credentialPanel()
+ expect(within(panel).getByText(/managed by its WorkflowRecipe/i)).toBeInTheDocument()
+ // No credential form at all…
+ expect(panel.querySelectorAll('form')).toHaveLength(0)
+ // …no password inputs (the only kind this screen renders for credentials)…
+ expect(panel.querySelectorAll('input[type="password"]')).toHaveLength(0)
+ // Regex, not the bare key: set mode's label carries the required marker
+ // ("api-key *"), so an exact-string query would pass even if the create form
+ // HAD rendered.
+ expect(screen.queryByLabelText(/^api-key/)).not.toBeInTheDocument()
+ expect(screen.queryByLabelText(/^workspace-id/)).not.toBeInTheDocument()
+ // …no submit control…
+ expect(within(panel).queryAllByRole('button')).toHaveLength(0)
+ expect(screen.queryByRole('button', { name: 'Set credentials' })).not.toBeInTheDocument()
+ expect(screen.queryByRole('button', { name: 'Rotate credentials' })).not.toBeInTheDocument()
+ // …and no copy telling the operator to re-enter every key on a screen that
+ // cannot create anything.
+ expect(screen.queryByText(/Enter every key to recreate it/)).not.toBeInTheDocument()
+ // The load-bearing one: the POST is never reached.
+ expect(mockCreateMcpSecret).not.toHaveBeenCalled()
+}
+
+/** The managed control: the recovery this screen exists to provide. */
+function expectRecoveredIntoCreateForm() {
+ expect(screen.getByRole('button', { name: 'Set credentials' })).toBeInTheDocument()
+ expect(screen.getByText(/This Secret no longer exists\./)).toBeInTheDocument()
+ // "api-key *" in set mode — every declared key is required there.
+ expect(screen.getByLabelText('api-key *')).toBeInTheDocument()
+ expect(screen.getByLabelText('workspace-id *')).toBeInTheDocument()
+ expect(screen.queryByText(/managed by its WorkflowRecipe/i)).not.toBeInTheDocument()
+ // Still no POST: recovering into the form is not submitting it.
+ expect(mockCreateMcpSecret).not.toHaveBeenCalled()
}
beforeEach(() => {
@@ -120,12 +186,128 @@ afterEach(() => {
vi.clearAllMocks()
})
+// ─── R1-H2 / mini-spec §1: ownership is a function of `spec` alone ─────────
+//
+// Invariant O1: `recipeOwned === (spec.managed === false)`, never a function of
+// status. Every shape below resolves the SURFACE to 'rotate' — none of them
+// carries the SecretNotFound condition that would let the resolver spot the
+// missing Secret up front — so ownership is the ONLY thing standing between a
+// managed:false connector and the create form once the PUT 404s.
+//
+// That is what makes the round-2 mutation
+//
+// recipeOwned = (status?.conditions ?? []).length === 0 && managed === false
+//
+// so dangerous: for shapes 3-5 it silently returns false and the late 404
+// re-opens POST on a Secret that belongs to a WorkflowRecipe. Shapes 1-2 are
+// the other half of the pair — they keep the mutant honest about the states it
+// does still get right, so a "fix" that simply hard-codes recipeOwned=false
+// cannot pass either.
+const STATUS_SHAPES: Array<{
+ name: string
+ status?: { conditions?: McpServerCondition[] }
+}> = [
+ // 1. The connector was just created and HCC has not written the status
+ // subresource at all. Nothing observable says anything.
+ { name: 'status absent entirely', status: undefined },
+ // 2. Status exists but is empty — the same information, a different shape.
+ { name: 'empty conditions array', status: { conditions: [] } },
+ // 3. SYNTHETIC ADVERSARY: HCC writes SecretResolved at 'True' or 'False'
+ // only, never 'Unknown'. Included because a partially-reconciled or
+ // hand-edited resource can still present it, and because it is the
+ // cheapest way to have a NON-EMPTY conditions array that proves nothing —
+ // exactly where the length-based mutant goes wrong.
+ {
+ name: 'SecretResolved / Unknown / Reconciling (synthetic)',
+ status: {
+ conditions: [
+ syntheticCondition({
+ status: 'Unknown',
+ reason: 'Reconciling',
+ message: 'Secret resolution in progress',
+ lastTransitionTime: '2026-08-06T03:00:00.000Z',
+ }),
+ ],
+ },
+ },
+ // 4. Producer output, but STALE: the Secret resolved cleanly an hour ago and
+ // has been deleted since. The UI cannot know that until the PUT 404s.
+ {
+ name: 'stale SecretResolved / True / SecretFound',
+ status: { conditions: [secretFound({ at: '2026-08-06T03:00:00.000Z' })] },
+ },
+ // 5. Producer output: the Secret EXISTS but lacks a key — so this one says
+ // the opposite of "missing", and still resolves to rotate.
+ {
+ name: 'SecretResolved / False / SecretMissingKey',
+ status: {
+ conditions: [
+ secretMissingKey({
+ at: '2026-08-06T03:00:00.000Z',
+ secretName: SECRET_NAME,
+ secretKey: 'workspace-id',
+ envVar: 'LINEAR_WORKSPACE',
+ }),
+ ],
+ },
+ },
+]
+
+describe('EditMcpServerPage — ownership survives a late 404 for every status shape', () => {
+ for (const shape of STATUS_SHAPES) {
+ it(`keeps a managed:false connector on explanation-only — ${shape.name}`, async () => {
+ await renderPage(mcpServer({ managed: false, status: shape.status }))
+
+ // It starts as an ordinary rotate form: nothing observable says the
+ // Secret is missing, so the resolver can only answer 'rotate'.
+ expect(screen.getByRole('button', { name: 'Rotate credentials' })).toBeInTheDocument()
+
+ await submitPartialRotateAndGet404()
+
+ await waitFor(() => {
+ expect(screen.getByText(/managed by its WorkflowRecipe/i)).toBeInTheDocument()
+ })
+ expectExplanationOnly()
+ // The partial draft really was submitted — one key of two — so this is
+ // the journey that used to leak into a partial POST, not a no-op.
+ expect(mockUpdateMcpSecret).toHaveBeenCalledWith(SECRET_NAME, { 'api-key': 'partial-value' })
+ })
+
+ it(`still recovers a managed:true connector into the create form — ${shape.name}`, async () => {
+ await renderPage(mcpServer({ managed: true, status: shape.status }))
+
+ expect(screen.getByRole('button', { name: 'Rotate credentials' })).toBeInTheDocument()
+
+ await submitPartialRotateAndGet404()
+
+ await waitFor(() => {
+ expect(screen.getByRole('button', { name: 'Set credentials' })).toBeInTheDocument()
+ })
+ expectRecoveredIntoCreateForm()
+ })
+ }
+
+ // `managed` absent means managed:true (the CRD defaults it, so the API server
+ // always persists it — but a fixture or an older resource may still omit it).
+ // Absence must never be read as recipe-owned.
+ it('treats an ABSENT spec.managed as managed, not as recipe-owned', async () => {
+ await renderPage(mcpServer({ status: { conditions: [] } }))
+ await submitPartialRotateAndGet404()
+ await waitFor(() => {
+ expect(screen.getByRole('button', { name: 'Set credentials' })).toBeInTheDocument()
+ })
+ expectRecoveredIntoCreateForm()
+ })
+})
+
describe('EditMcpServerPage — credential surface wiring', () => {
it('renders the CREATE form when a managed connector reports SecretNotFound', async () => {
await renderPage(
mcpServer({
managed: true,
- conditions: [secretResolved({ lastTransitionTime: '2026-08-06T04:00:00.000Z' })],
+ status: {
+ conditions: [secretNotFound({ at: '2026-08-06T04:00:00.000Z', secretName: SECRET_NAME })],
+ },
})
)
@@ -141,13 +323,11 @@ describe('EditMcpServerPage — credential surface wiring', () => {
await renderPage(
mcpServer({
managed: true,
- conditions: [
- secretResolved({
- reason: 'SecretMissingKey',
- message: `Secret "${SECRET_NAME}" is missing key "workspace-id"`,
- lastTransitionTime: '2026-08-06T04:00:00.000Z',
- }),
- ],
+ status: {
+ conditions: [
+ secretMissingKey({ at: '2026-08-06T04:00:00.000Z', secretName: SECRET_NAME }),
+ ],
+ },
})
)
@@ -160,38 +340,36 @@ describe('EditMcpServerPage — credential surface wiring', () => {
await renderPage(
mcpServer({
managed: false,
- conditions: [secretResolved({ lastTransitionTime: '2026-08-06T04:00:00.000Z' })],
+ status: {
+ conditions: [secretNotFound({ at: '2026-08-06T04:00:00.000Z', secretName: SECRET_NAME })],
+ },
})
)
- expect(screen.getByText(/managed by its WorkflowRecipe/i)).toBeInTheDocument()
- expect(screen.queryByLabelText('api-key')).not.toBeInTheDocument()
- expect(screen.queryByRole('button', { name: 'Set credentials' })).not.toBeInTheDocument()
- expect(screen.queryByRole('button', { name: 'Rotate credentials' })).not.toBeInTheDocument()
+ expectExplanationOnly()
})
// A real status array carries several condition types and no ordering
// guarantee. Only the newest SecretResolved entry may decide the surface.
+ //
+ // The DeploymentReady entry is a SYNTHETIC ADVERSARY: it reuses the
+ // SecretNotFound reason on a type the HCC never writes it on, and carries the
+ // newest timestamp in the array.
it('ignores unrelated conditions and honors the NEWEST SecretResolved entry', async () => {
await renderPage(
mcpServer({
managed: true,
- conditions: [
- {
- type: 'DeploymentReady',
- status: 'False',
- reason: 'SecretNotFound',
- message: 'unrelated condition reusing the reason',
- lastTransitionTime: '2026-08-06T09:00:00.000Z',
- },
- secretResolved({ lastTransitionTime: '2026-08-06T04:00:00.000Z' }),
- secretResolved({
- status: 'True',
- reason: 'SecretResolved',
- message: `Secret "${SECRET_NAME}" resolved`,
- lastTransitionTime: '2026-08-06T05:00:00.000Z',
- }),
- ],
+ status: {
+ conditions: [
+ syntheticCondition({
+ type: 'DeploymentReady',
+ message: 'unrelated condition reusing the reason',
+ lastTransitionTime: '2026-08-06T09:00:00.000Z',
+ }),
+ secretNotFound({ at: '2026-08-06T04:00:00.000Z', secretName: SECRET_NAME }),
+ secretFound({ at: '2026-08-06T05:00:00.000Z' }),
+ ],
+ },
})
)
@@ -204,75 +382,37 @@ describe('EditMcpServerPage — credential surface wiring', () => {
await renderPage(
mcpServer({
managed: true,
- conditions: [
- secretResolved({
- status: 'True',
- reason: 'SecretResolved',
- message: `Secret "${SECRET_NAME}" resolved`,
- lastTransitionTime: '2026-08-06T04:00:00.000Z',
- }),
- secretResolved({ lastTransitionTime: '2026-08-06T05:00:00.000Z' }),
- ],
+ status: {
+ conditions: [
+ secretFound({ at: '2026-08-06T04:00:00.000Z' }),
+ secretNotFound({ at: '2026-08-06T05:00:00.000Z', secretName: SECRET_NAME }),
+ ],
+ },
})
)
expect(screen.getByRole('button', { name: 'Set credentials' })).toBeInTheDocument()
})
-})
-// ─── R1-H1, end to end through the page ────────────────────────────────────
-describe('EditMcpServerPage — late 404 on an unmanaged connector', () => {
- it('never exposes the create form when the rotation PUT 404s and status was absent', async () => {
- // The realistic race: the connector was just created, HCC has not written
- // status yet, so NOTHING observable says the Secret is missing and the
- // resolver can only answer 'rotate'. Ownership must come from the spec.
- await renderPage(mcpServer({ managed: false, conditions: [] }))
-
- // It starts as a normal rotate form — that part is unchanged.
- const rotate = screen.getByRole('button', { name: 'Rotate credentials' })
- mockUpdateMcpSecret.mockRejectedValue(
- Object.assign(new Error(`404 - Secret "${SECRET_NAME}" not found in mcp-server`), {
- status: 404,
+ // The R1-M2 defect, end to end through the page: a malformed calendar date
+ // (February 30, which JavaScript silently normalizes into March 2) must NOT
+ // outrank the valid — and genuinely newer — clean resolution.
+ //
+ // SYNTHETIC ADVERSARY: HCC always stamps a real instant.
+ it('does not let a February-30 duplicate reopen the create form', async () => {
+ await renderPage(
+ mcpServer({
+ managed: true,
+ status: {
+ conditions: [
+ syntheticCondition({ lastTransitionTime: '2026-02-30T00:00:00.000Z' }),
+ secretFound({ at: '2026-02-28T23:59:59.000Z' }),
+ ],
+ },
})
)
- fireEvent.change(screen.getByLabelText('api-key'), { target: { value: 'partial-value' } })
- fireEvent.click(rotate)
- const dialog = await screen.findByRole('alertdialog')
- fireEvent.click(within(dialog).getByRole('button', { name: 'Rotate & restart' }))
-
- await waitFor(() => {
- expect(screen.getByText(/managed by its WorkflowRecipe/i)).toBeInTheDocument()
- })
- // Explanation-only: no create form, no partial POST, and no copy telling the
- // operator to re-enter every key on a screen that cannot create anything.
+ expect(screen.getByRole('button', { name: 'Rotate credentials' })).toBeInTheDocument()
expect(screen.queryByRole('button', { name: 'Set credentials' })).not.toBeInTheDocument()
- expect(screen.queryByLabelText('api-key')).not.toBeInTheDocument()
- expect(screen.queryByText(/Enter every key to recreate it/)).not.toBeInTheDocument()
- expect(mockCreateMcpSecret).not.toHaveBeenCalled()
- })
-
- // The managed control for the same race: the recovery this screen exists to
- // provide must survive the ownership guard.
- it('does open the create form on the same 404 when the connector is managed', async () => {
- await renderPage(mcpServer({ managed: true, conditions: [] }))
-
- mockUpdateMcpSecret.mockRejectedValue(
- Object.assign(new Error(`404 - Secret "${SECRET_NAME}" not found in mcp-server`), {
- status: 404,
- })
- )
-
- fireEvent.change(screen.getByLabelText('api-key'), { target: { value: 'partial-value' } })
- fireEvent.click(screen.getByRole('button', { name: 'Rotate credentials' }))
- const dialog = await screen.findByRole('alertdialog')
- fireEvent.click(within(dialog).getByRole('button', { name: 'Rotate & restart' }))
-
- await waitFor(() => {
- expect(screen.getByRole('button', { name: 'Set credentials' })).toBeInTheDocument()
- })
- expect(screen.getByText(/This Secret no longer exists\./)).toBeInTheDocument()
- expect(screen.queryByText(/managed by its WorkflowRecipe/i)).not.toBeInTheDocument()
- expect(mockCreateMcpSecret).not.toHaveBeenCalled()
})
})
diff --git a/control-ui/components/__tests__/fixtures/secretResolvedConditions.ts b/control-ui/components/__tests__/fixtures/secretResolvedConditions.ts
new file mode 100644
index 000000000..479cd99c3
--- /dev/null
+++ b/control-ui/components/__tests__/fixtures/secretResolvedConditions.ts
@@ -0,0 +1,148 @@
+import type { McpServerCondition } from '@lib/api'
+
+/**
+ * The ONE place `SecretResolved` test fixtures are built (mini-spec §3).
+ *
+ * Every `SecretResolved` condition the UI can ever observe is written by the
+ * host-context-controller, and by nothing else. Hand-writing the triple at each
+ * call site meant the same strings were re-typed in two suites, and a drift in
+ * the producer would have to be chased through both — which is exactly how
+ * `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`:
+ *
+ * | 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 |
+ *
+ * The messages are copied from the same producer branches, so a fixture reads
+ * like a real resource dump rather than an approximation of one.
+ *
+ * Anything the producer CANNOT emit — a `SecretResolved` at status `Unknown`, a
+ * reason carried by the wrong condition type, a malformed or absent
+ * `lastTransitionTime` — must come from `syntheticCondition` /
+ * `withoutTimestamp` below, which exist precisely so an adversarial fixture is
+ * never mistaken for producer shape.
+ */
+
+/** The condition type this module builds. Exported so a test can assert against
+ * the same constant instead of re-typing the string. */
+export const SECRET_RESOLVED = 'SecretResolved'
+
+const DEFAULT_SECRET_NAME = 'linear-credentials'
+const DEFAULT_NAMESPACE = 'mcp-server'
+const DEFAULT_SECRET_KEY = 'workspace-id'
+const DEFAULT_ENV_VAR = 'LINEAR_WORKSPACE'
+
+/** Every builder takes the instant the controller stamped the transition at.
+ * It is mandatory: `lastTransitionTime` is the resolver's only recency
+ * evidence, so a fixture that leaves it implicit hides the thing under test. */
+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. */
+export function secretFound({ at }: Stamped): McpServerCondition {
+ return {
+ type: SECRET_RESOLVED,
+ status: 'True',
+ reason: 'SecretFound',
+ message: 'Secret resolved and validated',
+ lastTransitionTime: at,
+ }
+}
+
+/** `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). */
+export function secretNotFound({
+ at,
+ secretName = DEFAULT_SECRET_NAME,
+ namespace = DEFAULT_NAMESPACE,
+}: Stamped & { secretName?: string; namespace?: string }): McpServerCondition {
+ return {
+ type: SECRET_RESOLVED,
+ status: 'False',
+ reason: 'SecretNotFound',
+ message: `Secret "${secretName}" not found in namespace "${namespace}"`,
+ lastTransitionTime: at,
+ }
+}
+
+/** `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. */
+export function secretMissingKey({
+ at,
+ secretName = DEFAULT_SECRET_NAME,
+ secretKey = DEFAULT_SECRET_KEY,
+ envVar = DEFAULT_ENV_VAR,
+}: Stamped & {
+ secretName?: string
+ secretKey?: string
+ envVar?: string
+}): McpServerCondition {
+ return {
+ type: SECRET_RESOLVED,
+ status: 'False',
+ reason: 'SecretMissingKey',
+ message:
+ `Secret "${secretName}" is missing required key "${secretKey}" ` +
+ `(needed for env var ${envVar})`,
+ lastTransitionTime: at,
+ }
+}
+
+/** `SecretResolved=False/SecretAccessDenied` — the Secret may well exist; HCC
+ * could not read it (k8s 401/403). Message from reconciler.ts:476-477. */
+export function secretAccessDenied({
+ at,
+ secretName = DEFAULT_SECRET_NAME,
+ namespace = DEFAULT_NAMESPACE,
+ code = 403,
+}: Stamped & { secretName?: string; namespace?: string; code?: number }): McpServerCondition {
+ return {
+ type: SECRET_RESOLVED,
+ status: 'False',
+ reason: 'SecretAccessDenied',
+ message:
+ `Access denied reading Secret "${secretName}" in namespace "${namespace}" ` +
+ `(K8s API ${code})`,
+ lastTransitionTime: at,
+ }
+}
+
+/**
+ * SYNTHETIC ADVERSARY — deliberately NOT producer output.
+ *
+ * Use only for shapes the host-context-controller cannot write but a legacy,
+ * hand-edited or partially-reconciled resource can still present to the UI:
+ * a `SecretResolved` at status `Unknown`, an absence reason carried by the wrong
+ * condition type, a malformed `lastTransitionTime`. Every call site must say in
+ * a comment WHY the impossible value is the point of the test.
+ *
+ * Defaults to the `SecretNotFound` triple so a call only has to state the one
+ * field it is adversarial about.
+ */
+export function syntheticCondition(
+ overrides: Partial<McpServerCondition> & { lastTransitionTime: string }
+): McpServerCondition {
+ return { ...secretNotFound({ at: overrides.lastTransitionTime }), ...overrides }
+}
+
+/**
+ * SYNTHETIC ADVERSARY — a condition with NO `lastTransitionTime` at all.
+ *
+ * The CRD marks the field required and HCC always stamps it, so this cannot
+ * come off a live API server; it models a hand-edited resource. The cast is
+ * deliberate — the type says `string`, and the resolver must survive the field
+ * being absent anyway (mini-spec C3).
+ */
+export function withoutTimestamp(condition: McpServerCondition): McpServerCondition {
+ const rest: Record<string, unknown> = { ...condition }
+ delete rest.lastTransitionTime
+ return rest as unknown as McpServerCondition
+}
diff --git a/control-ui/components/__tests__/resolveCredentialSurface.test.ts b/control-ui/components/__tests__/resolveCredentialSurface.test.ts
index 89c6529c3..149b2b8b0 100644
--- a/control-ui/components/__tests__/resolveCredentialSurface.test.ts
+++ b/control-ui/components/__tests__/resolveCredentialSurface.test.ts
@@ -4,53 +4,33 @@ import {
resolveCredentialSurface,
} from '@components/UpdateConnectorCredentials/resolveCredentialSurface'
import type { McpServerCondition } from '@lib/api'
+import {
+ secretAccessDenied,
+ secretFound,
+ secretMissingKey,
+ secretNotFound,
+ syntheticCondition,
+ withoutTimestamp,
+} from './fixtures/secretResolvedConditions'
-// ─── Fixtures are copied from the PRODUCER, not invented ───────────────────
+// ─── Fixtures come from the shared producer builder, never from literals ───
//
-// The only producer of `SecretResolved` is the HCC:
-// host-context-controller/src/reconciler.ts. A fixture that drifts from what it
-// actually writes tests a condition Kubernetes will never hold, and the drift
-// is invisible — the resolver matches on `reason`, so a plausible-but-wrong
-// reason string still exercises "not an absence claim" and stays green while
-// proving nothing about the real one.
+// Every condition below is built by ./fixtures/secretResolvedConditions, which
+// mirrors host-context-controller/src/reconciler.ts. Hand-written triples are
+// how `reason: 'SecretResolved'` (the condition TYPE reused as a reason, which
+// the producer never emits) survived here for two rounds: the resolver only
+// asks "is this an absence claim?", so a plausible-but-wrong reason exercises
+// the same branch and stays green while proving nothing.
//
-// Absence claim: reconciler.ts:2039-2046 writes `SecretResolved` / `False` with
-// `secretResult.reason` and `secretResult.message` straight from validateSecret,
-// whose 404 branch (reconciler.ts:470-473) produces exactly the reason and
-// message below.
-function condition(overrides: Partial<McpServerCondition> = {}): McpServerCondition {
- return {
- type: 'SecretResolved',
- status: 'False',
- reason: 'SecretNotFound',
- message: 'Secret "x-credentials" not found in namespace "mcp-server"',
- lastTransitionTime: '2026-08-06T04:48:48.564Z',
- ...overrides,
- }
-}
+// Fixtures the producer CANNOT emit come from `syntheticCondition` /
+// `withoutTimestamp` and are labelled SYNTHETIC ADVERSARY at the call site.
-// Clean resolution: reconciler.ts:1979-1986 (managed connectors) and
-// :2061-2068 (WRC-owned runtimes) both write this exact triple.
-//
-// The reason is `SecretFound`. It is NOT `SecretResolved` — that is the
-// condition TYPE, and reusing it as the reason is the specific mistake these
-// fixtures used to make. The resolver only asks "is this an absence claim?", so
-// the wrong string passed just as happily, which is what made the drift
-// survivable in the first place.
-function resolvedCondition(overrides: Partial<McpServerCondition> = {}): McpServerCondition {
- return {
- type: 'SecretResolved',
- status: 'True',
- reason: 'SecretFound',
- message: 'Secret resolved and validated',
- lastTransitionTime: '2026-08-06T04:48:48.564Z',
- ...overrides,
- }
-}
+const T0 = '2026-08-06T04:00:00.000Z'
+const T1 = '2026-08-06T05:00:00.000Z'
describe('resolveCredentialSurface', () => {
it('returns "set" when the Secret does not exist on a managed connector', () => {
- expect(resolveCredentialSurface([condition()], { managed: true })).toBe('set')
+ expect(resolveCredentialSurface([secretNotFound({ at: T0 })], { managed: true })).toBe('set')
})
// The load-bearing case: SecretMissingKey means the Secret EXISTS but lacks a
@@ -58,9 +38,18 @@ describe('resolveCredentialSurface', () => {
// only type+status (what McpServerTable does for its badge) would wrongly
// return 'set' here and POST into an AlreadyExists.
it('returns "rotate" when the Secret exists but is missing a key', () => {
- expect(
- resolveCredentialSurface([condition({ reason: 'SecretMissingKey' })], { managed: true })
- ).toBe('rotate')
+ expect(resolveCredentialSurface([secretMissingKey({ at: T0 })], { managed: true })).toBe(
+ 'rotate'
+ )
+ })
+
+ // SecretAccessDenied is a READ failure, not an absence proof: HCC could not
+ // look, so the Secret is probably still there. Sending it to the create form
+ // would POST into an AlreadyExists that control-api collapses to a bare 500.
+ it('returns "rotate" when HCC could not read the Secret', () => {
+ expect(resolveCredentialSurface([secretAccessDenied({ at: T0 })], { managed: true })).toBe(
+ 'rotate'
+ )
})
// Pins the `type` clause on its own. Every other fixture is a SecretResolved
@@ -69,27 +58,36 @@ describe('resolveCredentialSurface', () => {
// condition type reusing that reason) would then be read as a missing Secret
// and send the operator to the create form.
//
- // SYNTHETIC ADVERSARY, not producer output: the HCC writes `SecretNotFound`
- // only on `SecretResolved`. The fixture deliberately misplaces it.
+ // SYNTHETIC ADVERSARY: the HCC writes `SecretNotFound` only on
+ // `SecretResolved`. The fixture deliberately misplaces it.
it('returns "rotate" when SecretNotFound is carried by a different condition type', () => {
expect(
- resolveCredentialSurface([condition({ type: 'Ready', reason: 'SecretNotFound' })], {
+ resolveCredentialSurface([syntheticCondition({ type: 'Ready', lastTransitionTime: T0 })], {
managed: true,
})
).toBe('rotate')
})
- // Pins the `status` clause on its own. The clean-resolution fixture below
- // changes `status` AND `reason` together, so the `reason` clause alone kept it
- // green; this one varies ONLY the status.
+ // Pins the `status` clause on its own. The clean-resolution fixture varies
+ // `status` AND `reason` together, so the `reason` clause alone kept it green;
+ // this one varies ONLY the status.
+ //
+ // SYNTHETIC ADVERSARY: the producer writes `SecretResolved` at 'True' or
+ // 'False' only — never 'Unknown'. This models a hand-edited or
+ // partially-reconciled resource.
it('returns "rotate" when SecretResolved holds SecretNotFound at status Unknown', () => {
- expect(resolveCredentialSurface([condition({ status: 'Unknown' })], { managed: true })).toBe(
- 'rotate'
- )
+ expect(
+ resolveCredentialSurface(
+ [syntheticCondition({ status: 'Unknown', lastTransitionTime: T0 })],
+ {
+ managed: true,
+ }
+ )
+ ).toBe('rotate')
})
it('returns "rotate" when the Secret resolves cleanly', () => {
- expect(resolveCredentialSurface([resolvedCondition()], {})).toBe('rotate')
+ expect(resolveCredentialSurface([secretFound({ at: T0 })], {})).toBe('rotate')
})
it('returns "rotate" when there are no conditions', () => {
@@ -101,21 +99,19 @@ describe('resolveCredentialSurface', () => {
// Secret belongs to the recipe (PUT guards it, POST does not) and HCC never
// creates a Deployment for them, so the success poll could never converge.
it('returns "recipe-owned" for a WRC-owned connector whose Secret is missing', () => {
- expect(resolveCredentialSurface([condition()], { managed: false })).toBe('recipe-owned')
+ expect(resolveCredentialSurface([secretNotFound({ at: T0 })], { managed: false })).toBe(
+ 'recipe-owned'
+ )
})
// The managed check applies ONLY when the Secret is missing: rotation that
// works today on a WRC-owned connector must not be taken away.
it('returns "rotate" for a WRC-owned connector whose Secret resolves', () => {
- expect(
- resolveCredentialSurface([resolvedCondition()], {
- managed: false,
- })
- ).toBe('rotate')
+ expect(resolveCredentialSurface([secretFound({ at: T0 })], { managed: false })).toBe('rotate')
})
})
-// ─── R1-M2: duplicate SecretResolved conditions ────────────────────────────
+// ─── R1-M2 / mini-spec §2: condition authority ─────────────────────────────
//
// The McpServer CRD declares an ordinary conditions array and does NOT enforce
// uniqueness per `type`. HCC normally rewrites a type in place, but a legacy or
@@ -123,179 +119,287 @@ describe('resolveCredentialSurface', () => {
// each other. A `.some()` predicate lets ANY stale absence claim win, which
// forces every key and re-enables POST against a Secret that already exists.
//
-// The resolver therefore selects ONE authoritative SecretResolved condition:
-// 1. newest parseable `lastTransitionTime` wins;
-// 2. an absent/unparseable timestamp ranks as the OLDEST possible, so a
-// malformed absence claim can never outrank a well-stamped resolution;
-// 3. on an exact tie, the condition that does NOT claim absence wins —
-// ambiguity must never resolve to the destructive "the Secret is missing";
-// 4. still tied (they all claim absence, so they agree): last array entry.
-describe('resolveCredentialSurface — duplicate SecretResolved conditions', () => {
+// C1 exactly one SecretResolved condition is authoritative;
+// C2 authority ranks by a STRICTLY validated timestamp (RFC3339 syntax plus a
+// calendar round-trip);
+// C3 missing / empty / non-RFC3339 / invalid-calendar all share one oldest rank;
+// C4 among equal ranks, the LAST array entry wins;
+// C5 the caller's array is never mutated.
+describe('resolveCredentialSurface — C1: one authoritative condition', () => {
it('returns "rotate" when a NEWER duplicate says the Secret resolved cleanly', () => {
expect(
- resolveCredentialSurface(
- [
- condition({ lastTransitionTime: '2026-08-06T04:00:00.000Z' }),
- resolvedCondition({
- lastTransitionTime: '2026-08-06T05:00:00.000Z',
- }),
- ],
- { managed: true }
- )
+ resolveCredentialSurface([secretNotFound({ at: T0 }), secretFound({ at: T1 })], {
+ managed: true,
+ })
).toBe('rotate')
})
it('returns "rotate" when a NEWER duplicate says SecretMissingKey', () => {
expect(
- resolveCredentialSurface(
- [
- condition({ lastTransitionTime: '2026-08-06T04:00:00.000Z' }),
- condition({ reason: 'SecretMissingKey', lastTransitionTime: '2026-08-06T05:00:00.000Z' }),
- ],
- { managed: true }
- )
+ resolveCredentialSurface([secretNotFound({ at: T0 }), secretMissingKey({ at: T1 })], {
+ managed: true,
+ })
).toBe('rotate')
})
- // Array order must not decide anything: the same pair, reversed.
+ // Array order must not decide anything while the timestamps still can: the
+ // same pair, reversed.
it('returns "rotate" when the newer clean duplicate is listed FIRST', () => {
expect(
- resolveCredentialSurface(
- [
- resolvedCondition({
- lastTransitionTime: '2026-08-06T05:00:00.000Z',
- }),
- condition({ lastTransitionTime: '2026-08-06T04:00:00.000Z' }),
- ],
- { managed: true }
- )
+ resolveCredentialSurface([secretFound({ at: T1 }), secretNotFound({ at: T0 })], {
+ managed: true,
+ })
).toBe('rotate')
})
it('returns "set" when the NEWEST duplicate is the SecretNotFound one', () => {
expect(
- resolveCredentialSurface(
- [
- resolvedCondition({
- lastTransitionTime: '2026-08-06T04:00:00.000Z',
- }),
- condition({ lastTransitionTime: '2026-08-06T05:00:00.000Z' }),
- ],
- { managed: true }
- )
+ resolveCredentialSurface([secretFound({ at: T0 }), secretNotFound({ at: T1 })], {
+ managed: true,
+ })
).toBe('set')
})
it('returns "recipe-owned" when the newest duplicate is SecretNotFound on a WRC-owned connector', () => {
expect(
- resolveCredentialSurface(
- [
- resolvedCondition({
- lastTransitionTime: '2026-08-06T04:00:00.000Z',
- }),
- condition({ lastTransitionTime: '2026-08-06T05:00:00.000Z' }),
- ],
- { managed: false }
- )
+ resolveCredentialSurface([secretFound({ at: T0 }), secretNotFound({ at: T1 })], {
+ managed: false,
+ })
).toBe('recipe-owned')
})
- // Tie-break rule 3, both orders: an exact timestamp tie is ambiguous, and
- // ambiguity resolves AWAY from absence.
- it('returns "rotate" when contradictory duplicates share the exact same timestamp', () => {
- const same = '2026-08-06T04:00:00.000Z'
+ // Identical duplicates: same triple, same instant, twice. There is no
+ // contradiction to resolve, so the verdict must simply be that triple's.
+ it('returns the single verdict when the duplicate is byte-identical', () => {
+ expect(
+ resolveCredentialSurface([secretNotFound({ at: T0 }), secretNotFound({ at: T0 })], {
+ managed: true,
+ })
+ ).toBe('set')
+ expect(
+ resolveCredentialSurface([secretFound({ at: T0 }), secretFound({ at: T0 })], {
+ managed: true,
+ })
+ ).toBe('rotate')
+ })
+
+ // Unrelated condition types must not participate in the selection at all —
+ // not as candidates, and not by shifting array order.
+ //
+ // The two bracketing entries are SYNTHETIC ADVERSARIES: they pair a real
+ // SecretResolved reason with the WRONG condition type and carry the NEWEST
+ // timestamps in the array, so a resolver that dropped the `type` clause and
+ // matched on reason alone would pick one of these over either real candidate.
+ it('ignores unrelated condition types regardless of their position or recency', () => {
+ const conditions: McpServerCondition[] = [
+ syntheticCondition({
+ type: 'DeploymentReady',
+ lastTransitionTime: '2026-08-06T09:00:00.000Z',
+ }),
+ secretNotFound({ at: T0 }),
+ syntheticCondition({
+ type: 'Ready',
+ status: 'True',
+ reason: 'SecretFound',
+ lastTransitionTime: '2026-08-06T09:00:00.000Z',
+ }),
+ secretFound({ at: T1 }),
+ ]
+ expect(resolveCredentialSurface(conditions, { managed: true })).toBe('rotate')
+ // Reversing puts the stale SecretNotFound after the newer SecretFound. The
+ // timestamps still decide, so the verdict is unchanged.
+ expect(resolveCredentialSurface([...conditions].reverse(), { managed: true })).toBe('rotate')
+ })
+})
+
+describe('resolveCredentialSurface — C2/C3: strict timestamp validation', () => {
+ // THE R1-M2 CASE. `new Date('2026-02-30T00:00:00.000Z')` neither throws nor
+ // yields Invalid Date — JavaScript normalizes February 30 into March 2. Under
+ // a bare `new Date(...)` comparison the malformed absence claim therefore
+ // ranks TWO DAYS AHEAD of the valid February 28 resolution and wins, forcing
+ // the operator into the create path for a Secret that exists.
+ //
+ // SYNTHETIC ADVERSARY: HCC always stamps a real instant; only a hand-edited
+ // or legacy resource can carry this.
+ it('ranks an invalid CALENDAR date oldest, so it cannot beat a valid older one', () => {
+ const feb30 = syntheticCondition({ lastTransitionTime: '2026-02-30T00:00:00.000Z' })
+ const feb28 = secretFound({ at: '2026-02-28T23:59:59.000Z' })
+ expect(resolveCredentialSurface([feb30, feb28], { managed: true })).toBe('rotate')
+ expect(resolveCredentialSurface([feb28, feb30], { managed: true })).toBe('rotate')
+ })
+
+ // The same normalization trap in the other two positions: month 13 rolls into
+ // the next January, hour 25 into the next day.
+ it('ranks other normalizable components (month 13, hour 25) oldest too', () => {
+ const month13 = syntheticCondition({ lastTransitionTime: '2026-13-01T00:00:00.000Z' })
+ const hour25 = syntheticCondition({ lastTransitionTime: '2026-08-06T25:00:00.000Z' })
+ const valid = secretFound({ at: '2026-08-06T00:00:00.000Z' })
+ expect(resolveCredentialSurface([month13, valid], { managed: true })).toBe('rotate')
+ expect(resolveCredentialSurface([hour25, valid], { managed: true })).toBe('rotate')
+ })
+
+ // Syntax half of C2: values `Date.parse` accepts but RFC3339 does not. A bare
+ // local date-time would be read in the BROWSER's timezone, so the same status
+ // would resolve differently for two operators in different offsets.
+ it('ranks Date-parseable but non-RFC3339 timestamps oldest', () => {
+ const valid = secretFound({ at: '2026-08-06T00:00:00.000Z' })
+ for (const malformed of [
+ '2026-08-07', // date only
+ '2026-08-07T12:00:00', // no offset: browser-timezone dependent
+ 'Aug 7, 2026', // Date.parse accepts this too
+ '2026-08-07 12:00:00Z', // space instead of T
+ ]) {
+ expect(
+ resolveCredentialSurface([syntheticCondition({ lastTransitionTime: malformed }), valid], {
+ managed: true,
+ })
+ ).toBe('rotate')
+ }
+ })
+
+ // C3: every malformed form shares ONE rank, so none of them can outrank a
+ // validly stamped condition — whatever kind of malformed it is.
+ it('ranks missing, empty and unparseable timestamps identically (oldest)', () => {
+ const valid = secretFound({ at: T0 })
+ const missing = withoutTimestamp(secretNotFound({ at: T0 }))
+ const empty = syntheticCondition({ lastTransitionTime: '' })
+ const garbage = syntheticCondition({ lastTransitionTime: 'not-a-timestamp' })
+ for (const malformed of [missing, empty, garbage]) {
+ expect(resolveCredentialSurface([malformed, valid], { managed: true })).toBe('rotate')
+ expect(resolveCredentialSurface([valid, malformed], { managed: true })).toBe('rotate')
+ }
+ })
+
+ // A LONE absence claim with a malformed timestamp still means "missing":
+ // nothing contradicts it, so C3's "oldest rank" costs it nothing.
+ it('still returns "set" for a lone SecretNotFound with an unparseable timestamp', () => {
+ expect(
+ resolveCredentialSurface([syntheticCondition({ lastTransitionTime: 'not-a-timestamp' })], {
+ managed: true,
+ })
+ ).toBe('set')
+ expect(
+ resolveCredentialSurface([withoutTimestamp(secretNotFound({ at: T0 }))], { managed: true })
+ ).toBe('set')
+ })
+
+ // Valid RFC3339 forms the API server can legitimately produce must NOT be
+ // swept into the oldest rank by an over-strict regex: a non-Z offset and a
+ // whole-second stamp are both real. Here the OFFSET is what makes the absence
+ // claim newer (2026-08-06T04:30:00+00:30 == 04:00Z, one hour after 03:00Z).
+ it('accepts non-Z offsets and second-precision stamps as valid instants', () => {
expect(
resolveCredentialSurface(
- [condition({ lastTransitionTime: same }), resolvedCondition({ lastTransitionTime: same })],
+ [
+ secretFound({ at: '2026-08-06T03:00:00Z' }),
+ syntheticCondition({ lastTransitionTime: '2026-08-06T04:30:00+00:30' }),
+ ],
{ managed: true }
)
- ).toBe('rotate')
+ ).toBe('set')
+ // And the offset is applied with the right SIGN: +00:30 is 30 minutes
+ // BEHIND the same wall-clock read as UTC, so this one is now the older.
expect(
resolveCredentialSurface(
- [resolvedCondition({ lastTransitionTime: same }), condition({ lastTransitionTime: same })],
+ [
+ secretFound({ at: '2026-08-06T04:15:00Z' }),
+ syntheticCondition({ lastTransitionTime: '2026-08-06T04:30:00+00:30' }),
+ ],
{ managed: true }
)
).toBe('rotate')
})
+})
+
+describe('resolveCredentialSurface — C4: deterministic tie-break', () => {
+ // Equal rank, so position decides: the LAST entry wins. Both orders are
+ // asserted, and they deliberately differ — that is what makes the rule
+ // observable at all. Preferring "the one that does not claim absence" would
+ // return 'rotate' for both and make the positional rule untestable.
+ it('resolves an exact timestamp tie to the LAST entry, in both orders', () => {
+ const same = T0
+ expect(
+ resolveCredentialSurface([secretNotFound({ at: same }), secretFound({ at: same })], {
+ managed: true,
+ })
+ ).toBe('rotate')
+ expect(
+ resolveCredentialSurface([secretFound({ at: same }), secretNotFound({ at: same })], {
+ managed: true,
+ })
+ ).toBe('set')
+ })
- // Tie-break rule 2. An unparseable timestamp carries no recency proof, so it
- // must not let a stale absence claim outrank a well-stamped resolution.
+ // C3 puts every malformed timestamp on ONE rank, so two malformed conditions
+ // are also a tie — and resolve by the same positional rule.
//
- // DELIBERATELY MALFORMED — not producer output. The HCC always stamps a valid
- // RFC3339 `lastTransitionTime`; these two tests exist for hand-edited or
- // legacy resources, which is the only way such a value reaches the resolver.
- it('returns "rotate" when the SecretNotFound duplicate carries an unparseable timestamp', () => {
+ // SYNTHETIC ADVERSARIES: both timestamps are hand-edited garbage.
+ it('resolves a tie between two malformed timestamps to the LAST entry', () => {
expect(
resolveCredentialSurface(
[
- condition({ lastTransitionTime: 'not-a-timestamp' }),
- resolvedCondition({
- lastTransitionTime: '2026-08-06T04:00:00.000Z',
+ syntheticCondition({ lastTransitionTime: '' }),
+ syntheticCondition({
+ status: 'True',
+ reason: 'SecretFound',
+ lastTransitionTime: 'whenever',
}),
],
{ managed: true }
)
).toBe('rotate')
- })
-
- it('returns "rotate" when BOTH contradictory duplicates carry unparseable timestamps', () => {
expect(
resolveCredentialSurface(
[
- condition({ lastTransitionTime: '' }),
- resolvedCondition({
+ syntheticCondition({
+ status: 'True',
+ reason: 'SecretFound',
lastTransitionTime: 'whenever',
}),
+ syntheticCondition({ lastTransitionTime: '' }),
],
{ managed: true }
)
- ).toBe('rotate')
+ ).toBe('set')
})
- // A LONE absence claim with a malformed timestamp still means "missing":
- // there is nothing contradicting it, so today's behavior is preserved.
- // DELIBERATELY MALFORMED — see above; the HCC never emits this.
- it('returns "set" for a lone SecretNotFound with an unparseable timestamp', () => {
- expect(
- resolveCredentialSurface([condition({ lastTransitionTime: 'not-a-timestamp' })], {
- managed: true,
- })
- ).toBe('set')
+ // Determinism: the same array, resolved repeatedly, always gives the same
+ // answer. (Different permutations of a tie legitimately differ — that IS the
+ // rule; what may never differ is the same input twice.)
+ it('is deterministic for a given array', () => {
+ const tied = [secretFound({ at: T0 }), secretNotFound({ at: T0 })]
+ const verdicts = new Set(
+ Array.from({ length: 5 }, () => resolveCredentialSurface(tied, { managed: true }))
+ )
+ expect(verdicts).toEqual(new Set(['set']))
})
+})
- // Unrelated condition types must not participate in the selection at all —
- // not as candidates, and not by shifting array order.
- //
- // The two bracketing entries are SYNTHETIC ADVERSARIES, not producer output:
- // they pair a real `SecretResolved` reason with the WRONG condition type, and
- // carry the NEWEST timestamps in the array. The HCC only ever writes those
- // reasons on `SecretResolved` (reconciler.ts:2039-2046, :1979-1986), so a
- // resolver that dropped the `type` clause and matched on reason alone would
- // pick one of these instead of either real candidate.
- it('ignores unrelated condition types regardless of their position or recency', () => {
+describe('resolveCredentialSurface — C5: the caller’s array is not mutated', () => {
+ // The page passes `server.status?.conditions` straight from React state. A
+ // resolver that sorted in place to find "the newest" would reorder a rendered
+ // resource behind React's back — no re-render, and every other reader of that
+ // array (the status badge, the conditions table) silently reordered with it.
+ it('leaves the conditions array and its entries untouched', () => {
const conditions: McpServerCondition[] = [
- {
+ secretFound({ at: T1 }),
+ syntheticCondition({
type: 'DeploymentReady',
- status: 'False',
- reason: 'SecretNotFound',
- message: 'noise',
lastTransitionTime: '2026-08-06T09:00:00.000Z',
- },
- condition({ lastTransitionTime: '2026-08-06T04:00:00.000Z' }),
- {
- type: 'Ready',
- status: 'True',
- reason: 'SecretFound',
- message: 'noise',
- lastTransitionTime: '2026-08-06T09:00:00.000Z',
- },
- resolvedCondition({
- lastTransitionTime: '2026-08-06T05:00:00.000Z',
}),
+ secretNotFound({ at: T0 }),
]
+ // Deep snapshot BEFORE, including element identity and order.
+ const order = [...conditions]
+ const snapshot = JSON.parse(JSON.stringify(conditions))
+
expect(resolveCredentialSurface(conditions, { managed: true })).toBe('rotate')
- // Same four conditions, reversed: the verdict is order-independent.
- expect(resolveCredentialSurface([...conditions].reverse(), { managed: true })).toBe('rotate')
+
+ expect(conditions).toHaveLength(3)
+ expect(conditions).toEqual(snapshot)
+ // Identity too: a sort would reorder these references even though the
+ // structural comparison above already covers the values.
+ conditions.forEach((c, i) => expect(c).toBe(order[i]))
})
})
diff --git a/control-ui/package-lock.json b/control-ui/package-lock.json
index d2c4f473b..5cfbb5214 100644
--- a/control-ui/package-lock.json
+++ b/control-ui/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "clerum-control-ui",
- "version": "0.1.400",
+ "version": "0.1.401",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "clerum-control-ui",
- "version": "0.1.400",
+ "version": "0.1.401",
"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.json
index 8d467f529..95db2bbe8 100644
--- a/control-ui/package.json
+++ b/control-ui/package.json
@@ -1,6 +1,6 @@
{
"name": "clerum-control-ui",
- "version": "0.1.400",
+ "version": "0.1.401",
"private": true,
"scripts": {
"dev": "NEXT_IGNORE_INCORRECT_LOCKFILE=1 next dev",