Skip to content

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

TypeScript

fix(control-api,control-ui): address review round 3 and an unclear profile refusal

Alfredo Lopez07f3eaf71560
diff --git a/control-api/package-lock.json b/control-api/package-lock.json
index 177496fb9..aa6d7ce06 100644
--- a/control-api/package-lock.json
+++ b/control-api/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "clerum-control-api",
- "version": "0.1.717",
+ "version": "0.1.718",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "clerum-control-api",
- "version": "0.1.717",
+ "version": "0.1.718",
"dependencies": {
"@clerum/display-field": "file:../packages/display-field",
"@clerum/grok-provider-attempt-contract": "file:../packages/grok-provider-attempt-contract",
diff --git a/control-api/package.json b/control-api/package.json
index fa9a4b96e..ad822f2bb 100644
--- a/control-api/package.json
+++ b/control-api/package.json
@@ -1,6 +1,6 @@
{
"name": "clerum-control-api",
- "version": "0.1.717",
+ "version": "0.1.718",
"description": "Internal Clerum control plane REST API + UI for managing CRDs and secrets",
"main": "dist/main.js",
"engines": {
diff --git a/control-api/src/routes/admin/secrets.ts b/control-api/src/routes/admin/secrets.ts
index 7ce1bcecf..6d2c60d4c 100644
--- a/control-api/src/routes/admin/secrets.ts
+++ b/control-api/src/routes/admin/secrets.ts
@@ -9,6 +9,7 @@ import { extractK8sError } from '../../http/k8sError.js'
import { enforceNamespace } from '../../http/namespaceAudit.js'
import { isValidDNSSubdomain } from '../../http/rfc1123.js'
import { K8sGateway, extractHttpStatus } from '../../k8s.js'
+import { CalendarMinuteRateLimitStore } from '../../middleware/calendarMinuteRateLimitStore.js'
import type { UiAuthedRequest } from '../../middleware/controlUIAuth.js'
import { rateLimitMiddleware } from '../../middleware/rateLimitMiddleware.js'
import { rootLogger } from '../../observability/logger.js'
@@ -56,23 +57,35 @@ const defaultMcpSecretRollbackPermitStore: McpSecretRollbackPermitStore = {
finalize: finalizeMcpSecretRollbackPermitClaim,
}
-const mcpSecretDeleteEdgeRateLimit = rateLimit({
- windowMs: 60_000,
- limit: config.adminConnectorDeleteEdgePerMin,
- standardHeaders: 'draft-7',
- legacyHeaders: false,
- // Keyed on `sub`, not `jti`: `signAdminToken` mints a fresh `jti` on every
- // login (utils/auth/adminAuthToken.ts:21), so a per-`jti` budget resets each
- // time the same admin re-authenticates. `sub` is the stable principal, which
- // is what the sibling admin buckets use (registry.ts:4420, :4556) and what
- // pluginWorkloadSdkRateLimits.ts:63-66 already did.
- keyGenerator: req => {
- const adminSub = (req as UiAuthedRequest).adminAuth?.sub
- return adminSub
- ? `admin-session:${createHash('sha256').update(adminSub).digest('hex')}`
- : ipKeyGenerator(req.ip ?? '127.0.0.1')
- },
-})
+/**
+ * Edge counter in front of the `admin_mcp_secret_delete` ledger. An admin
+ * principal is counted on the calendar minute, like the ledger, so the edge
+ * cannot stay exhausted after the ledger has reset. The anonymous fallback
+ * carries the `:ip:` marker, which keeps the first-hit window of the other
+ * source-IP safeguards.
+ */
+export function createMcpSecretDeleteEdgeRateLimit() {
+ return rateLimit({
+ windowMs: 60_000,
+ store: new CalendarMinuteRateLimitStore(),
+ limit: config.adminConnectorDeleteEdgePerMin,
+ standardHeaders: 'draft-7',
+ legacyHeaders: false,
+ // Keyed on `sub`, not `jti`: `signAdminToken` mints a fresh `jti` on every
+ // login (utils/auth/adminAuthToken.ts:21), so a per-`jti` budget resets each
+ // time the same admin re-authenticates. `sub` is the stable principal, which
+ // is what the sibling admin buckets use (registry.ts:4420, :4556) and what
+ // pluginWorkloadSdkRateLimits.ts:63-66 already did.
+ keyGenerator: req => {
+ const adminSub = (req as UiAuthedRequest).adminAuth?.sub
+ return adminSub
+ ? `admin-session:${createHash('sha256').update(adminSub).digest('hex')}`
+ : `admin-mcp-secret-delete-edge:ip:${ipKeyGenerator(req.ip ?? '127.0.0.1')}`
+ },
+ })
+}
+
+const mcpSecretDeleteEdgeRateLimit = createMcpSecretDeleteEdgeRateLimit()
const mcpSecretDeleteRateLimit = rateLimitMiddleware({
bucketType: 'admin_mcp_secret_delete',
diff --git a/control-api/test/routes.mcpSecretsDeleteEdge.test.ts b/control-api/test/routes.mcpSecretsDeleteEdge.test.ts
new file mode 100644
index 000000000..928e944d1
--- /dev/null
+++ b/control-api/test/routes.mcpSecretsDeleteEdge.test.ts
@@ -0,0 +1,71 @@
+import { afterEach, describe, expect, it, vi } from 'vitest'
+import express from 'express'
+import request from 'supertest'
+import { config } from '../src/config.js'
+import { createMcpSecretDeleteEdgeRateLimit } from '../src/routes/admin/secrets.js'
+
+vi.mock('../src/services/rateLimiterService.js', () => ({ checkAndIncrement: vi.fn() }))
+
+function edgeApp(adminSub?: string) {
+ const instance = express()
+ instance.use((req, _res, next) => {
+ if (adminSub) {
+ ;(req as express.Request & { adminAuth?: { sub: string } }).adminAuth = { sub: adminSub }
+ }
+ next()
+ })
+ instance.use(createMcpSecretDeleteEdgeRateLimit())
+ // Counts the requests the edge admitted, so each denial is paired with the
+ // admissions that preceded it.
+ const admitted = { count: 0 }
+ instance.delete('/edge', (_req, res) => {
+ admitted.count += 1
+ res.json({ ok: true })
+ })
+ return { instance, admitted }
+}
+
+describe('MCP Secret delete edge rate limit', () => {
+ const original = config.adminConnectorDeleteEdgePerMin
+
+ afterEach(() => {
+ config.adminConnectorDeleteEdgePerMin = original
+ vi.useRealTimers()
+ })
+
+ it('resets an admin principal on the calendar minute, like the delete ledger', async () => {
+ config.adminConnectorDeleteEdgePerMin = 2
+ vi.useFakeTimers({ toFake: ['Date'] })
+ vi.setSystemTime(new Date('2026-01-01T00:00:50.000Z'))
+ const { instance, admitted } = edgeApp('admin-a')
+
+ await request(instance).delete('/edge').expect(200)
+ await request(instance).delete('/edge').expect(200)
+ await request(instance).delete('/edge').expect(429)
+ expect(admitted.count).toBe(2)
+
+ // Ten seconds later the ledger's calendar minute has turned; the edge in
+ // front of it must admit the same admin again.
+ vi.setSystemTime(new Date('2026-01-01T00:01:00.500Z'))
+ await request(instance).delete('/edge').expect(200)
+ expect(admitted.count).toBe(3)
+ })
+
+ it('keeps the first-hit window for the anonymous source-IP fallback', async () => {
+ config.adminConnectorDeleteEdgePerMin = 1
+ vi.useFakeTimers({ toFake: ['Date'] })
+ vi.setSystemTime(new Date('2026-01-01T00:00:50.000Z'))
+ const { instance, admitted } = edgeApp()
+
+ await request(instance).delete('/edge').expect(200)
+ await request(instance).delete('/edge').expect(429)
+ // The calendar minute turning does not reset a source-IP key.
+ vi.setSystemTime(new Date('2026-01-01T00:01:00.500Z'))
+ await request(instance).delete('/edge').expect(429)
+ expect(admitted.count).toBe(1)
+
+ vi.setSystemTime(new Date('2026-01-01T00:01:50.500Z'))
+ await request(instance).delete('/edge').expect(200)
+ expect(admitted.count).toBe(2)
+ })
+})
diff --git a/control-ui/lib/__tests__/readRequestCache.test.ts b/control-ui/lib/__tests__/readRequestCache.test.ts
index 294ebe51a..59e40a054 100644
--- a/control-ui/lib/__tests__/readRequestCache.test.ts
+++ b/control-ui/lib/__tests__/readRequestCache.test.ts
@@ -345,14 +345,91 @@ describe('bounded metadata read reuse', () => {
).catch(() => undefined),
])
firstController.abort()
- fetchMock.mockResolvedValueOnce(success({ recovered: true }))
+ fetchMock
+ .mockResolvedValueOnce(success({ recovered: true }))
+ .mockResolvedValueOnce(success({ connections: ['recovered'] }))
await vi.advanceTimersByTimeAsync(12_000)
expect(fetchMock).toHaveBeenCalledTimes(2)
+ // Both URLs were denied, so the one recovery rereads each of them once.
await vi.advanceTimersByTimeAsync(8_000)
- expect(fetchMock).toHaveBeenCalledTimes(3)
+ expect(fetchMock).toHaveBeenCalledTimes(4)
await expect(apiGet('/api/v1/admin/capabilities', {}, metadataOptions)).resolves.toEqual({
recovered: true,
})
+ await expect(
+ apiGet('/api/v1/admin/connections', {}, { metadataRead: 'subscription-connections' })
+ ).resolves.toEqual({ connections: ['recovered'] })
+ expect(fetchMock).toHaveBeenCalledTimes(4)
+ })
+
+ it('rereads every URL the server denied while the family recovery was scheduled', async () => {
+ const codexUrl = '/api/v1/admin/codex-subscription/connections'
+ const grokUrl = '/api/v1/admin/grok-subscription/connections'
+ const connectionOptions = { metadataRead: 'subscription-connections' } as const
+ const pending: Array<(response: Response) => void> = []
+ fetchMock.mockImplementation(
+ () =>
+ new Promise<Response>(resolve => {
+ pending.push(resolve)
+ })
+ )
+ // Both inventories are in flight before either denial arrives, as when an
+ // Agent page loads its Codex and Grok connections together.
+ const codex = apiGet(codexUrl, {}, connectionOptions).catch(reason => reason)
+ const grok = apiGet(grokUrl, {}, connectionOptions).catch(reason => reason)
+ await vi.advanceTimersByTimeAsync(0)
+ expect(pending).toHaveLength(2)
+ pending[0](throttled(12))
+ pending[1](throttled(12))
+ expect(await codex).toMatchObject({ status: 429 })
+ expect(await grok).toMatchObject({ status: 429 })
+
+ fetchMock.mockReset()
+ fetchMock.mockImplementation((url: string) =>
+ Promise.resolve(success({ from: url.includes('grok') ? 'grok' : 'codex' }))
+ )
+ await vi.advanceTimersByTimeAsync(12_000)
+ const recoveredUrls = fetchMock.mock.calls.map(([url]) => String(url))
+ expect(recoveredUrls).toHaveLength(2)
+ expect(recoveredUrls.filter(url => url.endsWith(codexUrl))).toHaveLength(1)
+ expect(recoveredUrls.filter(url => url.endsWith(grokUrl))).toHaveLength(1)
+
+ // A Retry after the recovery is served from the recovered entries, so it
+ // cannot spend a third read in the same window.
+ await expect(apiGet(codexUrl, {}, connectionOptions)).resolves.toEqual({ from: 'codex' })
+ await expect(apiGet(grokUrl, {}, connectionOptions)).resolves.toEqual({ from: 'grok' })
+ expect(fetchMock).toHaveBeenCalledTimes(2)
+ })
+
+ it('stops the family recovery at the first member the server denies again', async () => {
+ const codexUrl = '/api/v1/admin/codex-subscription/connections'
+ const grokUrl = '/api/v1/admin/grok-subscription/connections'
+ const connectionOptions = { metadataRead: 'subscription-connections' } as const
+ const pending: Array<(response: Response) => void> = []
+ fetchMock.mockImplementation(
+ () =>
+ new Promise<Response>(resolve => {
+ pending.push(resolve)
+ })
+ )
+ const codex = apiGet(codexUrl, {}, connectionOptions).catch(reason => reason)
+ const grok = apiGet(grokUrl, {}, connectionOptions).catch(reason => reason)
+ await vi.advanceTimersByTimeAsync(0)
+ expect(pending).toHaveLength(2)
+ pending[0](throttled(12))
+ pending[1](throttled(12))
+ expect(await codex).toMatchObject({ status: 429 })
+ expect(await grok).toMatchObject({ status: 429 })
+
+ fetchMock.mockReset()
+ fetchMock.mockImplementation(() => Promise.resolve(throttled(12)))
+ await vi.advanceTimersByTimeAsync(12_000)
+ // The first reread is denied, which restores the family cooldown; the
+ // second member is not sent into it, and no further attempt is scheduled.
+ expect(fetchMock).toHaveBeenCalledOnce()
+ expect(String(fetchMock.mock.calls[0][0])).toMatch(/codex-subscription\/connections$/)
+ await vi.advanceTimersByTimeAsync(24_000)
+ expect(fetchMock).toHaveBeenCalledOnce()
})
it('makes only one recovery when throttle timing is unavailable', async () => {
diff --git a/control-ui/lib/api.ts b/control-ui/lib/api.ts
index 832b9ed22..811d8ac15 100644
--- a/control-ui/lib/api.ts
+++ b/control-ui/lib/api.ts
@@ -15,7 +15,6 @@ import type {
import {
clearReadRequestPrincipal,
completeReadRequestRecovery,
- failReadRequestRecovery,
getReadRequestCacheEntry,
getReadRequestCacheGeneration,
getReadRequestCooldown,
@@ -550,13 +549,11 @@ async function apiRead(
reserveReadRequestRecovery(
familyKey,
Date.now() + delayMs,
- signal => {
- if (!sameReadContext(requestEpoch, requestPrincipalKey)) return
- void apiRead(path, query, { ...options, signal, refresh: false }, true).then(
- () => completeReadRequestRecovery(familyKey),
- reason => failReadRequestRecovery(familyKey, reason)
- )
- },
+ metadataKey ?? url,
+ signal =>
+ sameReadContext(requestEpoch, requestPrincipalKey)
+ ? apiRead(path, query, { ...options, signal, refresh: false }, true)
+ : Promise.reject(new AuthExpiredError()),
metadataKey ? Array.from(consumers, consumer => consumer.signal) : [options.signal]
)
}
diff --git a/control-ui/lib/readRequestCache.ts b/control-ui/lib/readRequestCache.ts
index f535015db..3722830a1 100644
--- a/control-ui/lib/readRequestCache.ts
+++ b/control-ui/lib/readRequestCache.ts
@@ -23,6 +23,9 @@ type RecoveryEntry = {
resolve: () => void
reject: (error: unknown) => void
state: 'scheduled' | 'running'
+ // Every URL whose own read was denied while this recovery was scheduled,
+ // in denial order. Each is reread once at the deadline.
+ members: Map<string, (signal: AbortSignal) => Promise<unknown>>
removeListeners: () => void
addSubscribers: (signals: Array<AbortSignal | undefined>) => void
}
@@ -203,10 +206,16 @@ export function getReadRequestRecovery(key: string): Promise<void> | undefined {
return recovery && recovery.deadlineMs <= Date.now() ? recovery.pending : undefined
}
+/**
+ * Reserve the family's single recovery, or join the scheduled one. A denied
+ * URL that joins adds its own reread, so concurrently denied siblings are all
+ * recovered by the same attempt instead of only the URL that reserved it.
+ */
export function reserveReadRequestRecovery(
key: string,
deadlineMs: number,
- recover: (signal: AbortSignal) => void,
+ memberKey: string,
+ recover: (signal: AbortSignal) => Promise<unknown>,
signals: Array<AbortSignal | undefined> = [undefined]
): boolean {
if (!isBrowser() || METADATA_READ_MAX_RECOVERY_ATTEMPTS < 1) return false
@@ -215,6 +224,7 @@ export function reserveReadRequestRecovery(
if (existing.state === 'scheduled') {
existing.deadlineMs = Math.max(existing.deadlineMs, deadlineMs)
existing.addSubscribers(signals)
+ if (!existing.members.has(memberKey)) existing.members.set(memberKey, recover)
}
return false
}
@@ -245,6 +255,7 @@ export function reserveReadRequestRecovery(
resolve,
reject,
state: 'scheduled',
+ members: new Map([[memberKey, recover]]),
removeListeners: () =>
watchedSignals.forEach(signal => signal.removeEventListener('abort', onAbort)),
addSubscribers: addedSignals => {
@@ -279,7 +290,7 @@ export function reserveReadRequestRecovery(
}
entry.timer = undefined
entry.state = 'running'
- recover(controller.signal)
+ void runRecovery(key, entry)
},
Math.min(2_147_483_647, Math.max(0, entry.deadlineMs - Date.now()))
)
@@ -288,23 +299,39 @@ export function reserveReadRequestRecovery(
return true
}
-export function completeReadRequestRecovery(key: string): void {
- const recovery = recoveries.get(key)
- if (recovery?.timer) clearTimeout(recovery.timer)
- recovery?.removeListeners()
- recovery?.resolve()
+/**
+ * Reread the members one at a time. The first failure ends the attempt: a
+ * fresh denial has already set the family cooldown, so the remaining members
+ * would only be refused locally. Either outcome releases the entry, which keeps
+ * one recovery per denial while letting a later denial schedule its own.
+ */
+async function runRecovery(key: string, entry: RecoveryEntry): Promise<void> {
+ try {
+ for (const recover of entry.members.values()) {
+ if (recoveries.get(key) !== entry || entry.controller.signal.aborted) return
+ await recover(entry.controller.signal)
+ }
+ } catch (error) {
+ if (recoveries.get(key) !== entry) return
+ recoveries.delete(key)
+ entry.removeListeners()
+ entry.reject(error)
+ return
+ }
+ if (recoveries.get(key) !== entry) return
recoveries.delete(key)
+ entry.removeListeners()
+ entry.resolve()
}
-export function failReadRequestRecovery(key: string, error: unknown): void {
- // Only the running recovery reports its own failure. Its denial could not
- // reserve another attempt, so releasing the entry keeps one recovery per
- // denial while letting a later denial in this family schedule its own.
+export function completeReadRequestRecovery(key: string): void {
const recovery = recoveries.get(key)
- if (recovery?.state !== 'running') return
- recoveries.delete(key)
+ // A running recovery settles itself once every member has been reread.
+ if (!recovery || recovery.state === 'running') return
+ if (recovery.timer) clearTimeout(recovery.timer)
recovery.removeListeners()
- recovery.reject(error)
+ recovery.resolve()
+ recoveries.delete(key)
}
export function __resetReadRequestCacheForTests(): void {
diff --git a/control-ui/package-lock.json b/control-ui/package-lock.json
index 522870105..bbe61f2ce 100644
--- a/control-ui/package-lock.json
+++ b/control-ui/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "clerum-control-ui",
- "version": "0.1.713",
+ "version": "0.1.714",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "clerum-control-ui",
- "version": "0.1.713",
+ "version": "0.1.714",
"dependencies": {
"@clerum/display-field": "file:../packages/display-field",
"@clerum/frontend-components": "file:../packages/frontend-components",
diff --git a/control-ui/package.json b/control-ui/package.json
index 532129fc6..215b5cce3 100644
--- a/control-ui/package.json
+++ b/control-ui/package.json
@@ -1,6 +1,6 @@
{
"name": "clerum-control-ui",
- "version": "0.1.713",
+ "version": "0.1.714",
"private": true,
"scripts": {
"dev": "NEXT_IGNORE_INCORRECT_LOCKFILE=1 next dev",
diff --git a/docs/architecture/administrative-rate-limits.md b/docs/architecture/administrative-rate-limits.md
index 291f1ab14..563870ece 100644
--- a/docs/architecture/administrative-rate-limits.md
+++ b/docs/architecture/administrative-rate-limits.md
@@ -150,9 +150,12 @@ maximum 128 entries, origin/principal/scope/session-epoch binding and a shared
subscription-read cooldown. Ordinary Agent sections do not fetch optional
subscription inventory; editor opening loads it when needed.
-At most one shared idempotent recovery GET proceeds after a denial deadline.
-A denied recovery schedules no further attempt, but it releases its
-reservation, so the next denial in that read family schedules its own. Forced refresh respects the same pause. Authentication changes, 401 and
+One shared recovery runs per read family after a denial deadline. It rereads,
+once each and one at a time, every URL the server denied while it was
+scheduled (for example the Codex and Grok inventories loaded together), and
+stops at the first reread that is denied again. A denied recovery schedules no
+further attempt, but it releases its reservation, so the next denial in that
+read family schedules its own. Forced refresh respects the same pause. Authentication changes, 401 and
cross-tab invalidation fence old awaits and clear identity-bound state.
Aborting one subscriber does not cancel another subscriber’s shared request.
SSR does not retain cached/deduplicated results across requests.
diff --git a/docs/deploy/minikube.md b/docs/deploy/minikube.md
index d68f1db62..2983c8268 100644
--- a/docs/deploy/minikube.md
+++ b/docs/deploy/minikube.md
@@ -280,6 +280,7 @@ An unreadable list is a refusal, never an empty list.
| `HOST must be 127.0.0.1` | branch-profile forwards bind only `127.0.0.1` |
| `CACHE_ROOT ...` | the profile cache root is unscoped, a symlink, not a directory, or contains a control character |
| `PROFILE_METADATA_MISSING` | `profile.env` of an existing profile is missing or unreadable; it is never regenerated |
+| `PROFILE_NOT_FOUND: no profile named <name> exists` | `MINIKUBE_PROFILE` names a profile with no directory; the message names the profile this worktree and branch derive, which is the only name `branch-profile-start` creates |
| `PROFILE_PORTS_MISSING`, `PROFILE_PORTS_INVALID` | `ports.env` is missing or disagrees with its port base and `HOST` |
| `BRANCH_PROFILE_KUBECONFIG_UNREADABLE` | the kubeconfig contexts cannot be read |
| `BRANCH_PROFILE_CONTEXT_DANGLING` | the profile's context has no resolvable cluster or no server |
diff --git a/scripts/minikube-profiles/branch-profile.sh b/scripts/minikube-profiles/branch-profile.sh
index 7bc272745..bc1d1bddf 100755
--- a/scripts/minikube-profiles/branch-profile.sh
+++ b/scripts/minikube-profiles/branch-profile.sh
@@ -285,7 +285,7 @@ resolve_profile() {
printf '%s\n' "${output}" >&2
die "PROFILE_METADATA_MISSING: profile metadata for ${EXPLICIT_PROFILE:-this branch} is missing or unreadable; restore profile.env from a backup or stop and ask. branch-profile-start only creates metadata when the profile directory does not exist and never regenerates it for an existing one"
fi
- if [[ -n "${EXPLICIT_PROFILE}" || ${status} -ne 3 || "${output}" != *PROFILE_NOT_FOUND:* ]]; then
+ if [[ ${status} -ne 3 || "${output}" != *PROFILE_NOT_FOUND:* ]]; then
printf '%s\n' "${output}" >&2
die 'profile ownership resolution failed closed'
fi
@@ -302,6 +302,12 @@ resolve_profile() {
die 'stable identity output is incomplete'
[[ "${WORKTREE_ID}" =~ ^[0-9a-f]{40}$ && "${OWNER_ID}" =~ ^[0-9a-f]{40}$ ]] ||
die 'stable identity output is malformed'
+ # An explicit selection of a profile that does not exist is created only
+ # under the name this worktree and branch derive, exactly as without the
+ # selection. Any other name is refused with the name that would be created.
+ if [[ -n "${EXPLICIT_PROFILE}" && "${EXPLICIT_PROFILE}" != "${PROFILE}" ]]; then
+ die "PROFILE_NOT_FOUND: no profile named ${EXPLICIT_PROFILE} exists. This worktree and branch derive ${PROFILE}: unset MINIKUBE_PROFILE or set it to that name to create it"
+ fi
validate_profile_name
set_profile_paths
if [[ -e "${CACHE_DIR}" || -L "${CACHE_DIR}" ]]; then
diff --git a/scripts/minikube/profile-owner.sh b/scripts/minikube/profile-owner.sh
index d24abeb27..d390f93fd 100755
--- a/scripts/minikube/profile-owner.sh
+++ b/scripts/minikube/profile-owner.sh
@@ -359,6 +359,14 @@ profile_owner_resolve() {
if [[ -n "${explicit_profile_env}" || -n "${explicit_profile}" ]]; then
if [[ -z "${explicit_profile_env}" ]]; then
profile_env="${profile_root}/${explicit_profile}/profile.env"
+ # A selected name with no directory is an absent profile, not a profile
+ # whose metadata was lost; report it as such so the caller can say so.
+ if [[ -n "${explicit_profile}" && ! -e "${profile_root}/${explicit_profile}" &&
+ ! -L "${profile_root}/${explicit_profile}" ]]; then
+ profile_owner_error PROFILE_NOT_FOUND \
+ "selected profile has no directory: ${profile_root}/${explicit_profile}"
+ return 3
+ fi
else
profile_env="${explicit_profile_env}"
fi
diff --git a/scripts/tests/test-branch-profile-lifecycle.sh b/scripts/tests/test-branch-profile-lifecycle.sh
index aa8af1335..c8656a85c 100755
--- a/scripts/tests/test-branch-profile-lifecycle.sh
+++ b/scripts/tests/test-branch-profile-lifecycle.sh
@@ -580,6 +580,34 @@ assert_log_lacks 'minikube' 'a branch profile without profile.env must not reach
assert_log_lacks 'kubectl' 'a branch profile without profile.env must not reach kubectl'
mv "${tmp}/branch-profile.env" "${profile_dir}/profile.env"
+# An explicit selection of a profile with no directory at all is an absent
+# profile, not lost metadata. The refusal names PROFILE_NOT_FOUND and the
+# derived name, and never sends the operator to restore a profile.env.
+reset_state
+bp explicit-absent start MINIKUBE_PROFILE=clerum-absent-profile
+assert_rc 1 'start of an explicit profile that has no directory'
+assert_output_has 'PROFILE_NOT_FOUND: no profile named clerum-absent-profile exists' \
+ 'the refusal of an absent explicit profile names the code'
+assert_output_has "This worktree and branch derive ${profile}" \
+ 'the refusal of an absent explicit profile names the derived profile'
+assert_output_lacks 'PROFILE_METADATA_MISSING' 'an absent explicit profile is not missing metadata'
+assert_output_lacks 'restore profile.env' 'an absent explicit profile is not sent to restore metadata'
+assert_log_lacks 'minikube' 'an absent explicit profile must not reach minikube'
+assert_log_lacks 'kubectl' 'an absent explicit profile must not reach kubectl'
+[[ ! -e "${cache_root}/clerum-absent-profile" ]] ||
+ fail 'the refusal of an absent explicit profile created its directory'
+ok
+
+# Selecting the derived name explicitly while it does not exist behaves like
+# no selection: the resolver derives and returns that same profile.
+mv "${profile_dir}" "${tmp}/explicit-derived-aside"
+reset_state
+bp explicit-derived-absent resolve "MINIKUBE_PROFILE=${profile}"
+assert_rc 0 'resolve of the derived profile selected explicitly before it exists'
+assert_output_has "PROFILE=${profile}" 'the explicit derived selection resolves to the derived profile'
+if [[ -e "${profile_dir}" ]]; then mv "${profile_dir}" "${tmp}/explicit-derived-created"; fi
+mv "${tmp}/explicit-derived-aside" "${profile_dir}"
+
# A profile the resolver derives on its own (no explicit selection) must still
# carry the hashed suffix. With the branch profile set aside, the adopted
# profile is the only persisted record for this worktree and branch.
diff --git a/scripts/tests/test-minikube-profile-owner.sh b/scripts/tests/test-minikube-profile-owner.sh
index 140cb3b3a..87b80da5b 100755
--- a/scripts/tests/test-minikube-profile-owner.sh
+++ b/scripts/tests/test-minikube-profile-owner.sh
@@ -234,6 +234,10 @@ expect_failure PROFILE_METADATA_MISSING 'explicit profile without metadata' \
"${OWNER_SCRIPT}" resolve --repo-dir "${repo_a}" --branch "${branch}" \
--profile-root "${missing_metadata_root}" --profile "${legacy_profile}"
+expect_failure PROFILE_NOT_FOUND 'explicit profile without a directory' \
+ "${OWNER_SCRIPT}" resolve --repo-dir "${repo_a}" --branch "${branch}" \
+ --profile-root "${missing_metadata_root}" --profile clerum-absent-profile
+
missing_stable_metadata_root="${TMP_ROOT}/missing-stable-metadata"
mkdir -p "${missing_stable_metadata_root}/${profile_a}"
write_ports "${missing_stable_metadata_root}/${profile_a}/ports.env" 27500