Skip to content

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

TypeScript
76.8 KB
Raw Blame
import { DEFAULT_ALLOWED_PLUGIN_IMAGE_PREFIXES } from '@clerum/image-policy'
import {
  type SigningMaterial,
  parseSigningMaterial,
  parseVerifierMaterial,
} from '@clerum/jwt-key-policy'
import { type DevJwtSlot, loadOrCreateDevJwtSigningMaterial } from './devSigningKeys.js'
import { REACTIVE_REFRESH_BUFFER_MS } from './oauth/tokenHelper.js'
import { rootLogger } from './observability/logger.js'

function boundedIntegerEnv(name: string, fallback: number, min: number, max: number): number {
  const parsed = Number(process.env[name])
  return Number.isSafeInteger(parsed) && parsed >= min && parsed <= max ? parsed : fallback
}

type Config = {
  port: number
  jsonBodyLimit: string
  namespace: string
  hostsNamespace: string
  contextsNamespace: string
  communicationChannelsNamespace: string
  mcpServersNamespace: string
  llmHooksNamespace: string
  sandboxNamespace: string
  sandboxUiNamespace: string
  secretsNamespace: string
  pgConnectionString: string
  internalTokens: string[]
  internalServiceTokens: Record<string, string>
  internalControlJwtWrcHmacSecret: string
  internalControlJwtHccHmacSecret: string
  allowedIssuanceNamespaces: string[]
  memberRegistrationMode: 'remote' | 'hosted'
  memberRegistrationExternalHubBaseUrl: string
  memberRegistrationServiceBaseUrl: string
  memberRegistrationServiceHmacSecret: string
  memberRegistrationServiceHmacKid: string
  memberRegistrationTenantId: string
  desktopExternalRestApiBaseUrl: string
  desktopRpcProxyBaseUrl: string
  desktopProfileUiBaseUrl: string
  desktopAppName: string
  desktopGfsOperatorLinkingEnabled: boolean
  controlUiBaseUrl: string
  controlUiAppName: string
  sessionJwtPrivateKey: string
  jwtIssuer: string
  jwtAudience: string
  rpcJwtPrivateKey: string
  rpcJwtPublicKey: string
  rpcJwtIssuer: string
  rpcJwtAudience: string
  rpcTokenTtlSeconds: number
  hostSecretLabelKey: string
  hostSecretLabelValue: string
  policyAuthAudience: string
  googleClientId: string
  adminJwtPrivateKey: string
  adminJwtIssuer: string
  adminJwtAudience: string
  adminJwtTtlSeconds: number
  /**
   * Optional RS256 private key used exclusively to sign registry identity
   * vouchers (POST /api/v1/registry/identity-voucher). Managed mode requires
   * this dedicated material; self-hosted mode resolves its enrolled identity.
   *
   * Rationale: a captured admin session JWT (aud=control-ui, 1h TTL) signed by
   * the SAME key as a voucher (aud=registry-api, 60s TTL) becomes a usable
   * voucher if the registry ever loosens its `aud` check. Provisioning a
   * separate keypair eliminates that confused-deputy class. The registry must
   * be configured with the matching CONTROL_API_PUBLIC_KEY.
   */
  registryVoucherPrivateKey: string
  // The registry-assigned key_id (uuid) used as the voucher `kid` header in
  // MANAGED mode (spec §14.2). Delivered by the managed operator in the registry-voucher Secret
  // as CONTROL_API_REGISTRY_VOUCHER_KID. Self-hosted reads kid from the DB row.
  registryVoucherKid: string
  // Registry consumer config — added in Path A.
  // CLERUM_REGISTRY_URL: where to find the registry. Required; validated
  // against an allowlist at startup (see validateConfig).
  registryUrl: string
  // OAuth2 client_credentials. Required only when registryAuthEnabled=true.
  registryClientId: string
  registryClientSecret: string
  // Toggle. False = no Bearer header, no startup credential check (minikube).
  registryAuthEnabled: boolean
  // Explicit credential + kid source discriminator (spec §14.3 / S10). NEVER
  // absence-based: managed = env/Secret, self-hosted = the registry_connection
  // DB row. Required when registryAuthEnabled; logged at boot.
  registryConnectionMode: 'managed' | 'self-hosted'
  // Publisher UI surface (Sidebar entry + /publisher route) toggle, surfaced
  // to control-ui on the publish-scope response. Static config value — not
  // part of resolvePublishScope()'s cached registry-derived fields. Default
  // ON for every deploy (managed and self-hosted);
  // CONTROL_API_PUBLISHER_UI_ENABLED='false' disables it.
  publisherUiEnabled: boolean
  adminAuthMaxFailures: number
  adminAuthLockMinutes: number
  adminBootstrapUsername: string
  adminBootstrapEmail: string
  adminBootstrapPasswordHash: string
  adminDefaultAgentNames: string[]
  adminDefaultContextIds: string[]
  mcpHostJwtAccessTtlSec: number
  mcpHostJwtRefreshTtlSec: number
  mcpHostJwtControlTtlSec: number
  mcpHostJwtMaxHostRefs: number
  mcpHostJwtMaxHostRefLength: number
  oauthBrokerJwtTtlSec: number
  // OAuth mcp-server broker (POST /api/v1/mcp-oauth/user-token) kill-switch.
  // DEFAULT OFF (fail-closed): the endpoint must look absent in production
  // until the U4 mcp-host runtime lands, honoring the PR promise "do not enable
  // OAuth mcp-servers in production until U4 lands". When off the route returns
  // 404 not_found before any auth/token work. MCP_OAUTH_BROKER_ENABLED=true
  // opts a deploy in deliberately.
  mcpOauthBrokerEnabled: boolean
  userApprovalRequestDefaultTtlSec: number
  userApprovalRequestMaxTtlSec: number
  userApprovalRequestExpiryIntervalMs: number
  usageRollup5MinIntervalMs: number
  usageRollupHourlyIntervalMs: number
  usageRollupDailyIntervalMs: number
  usageRetentionIntervalMs: number
  budgetReservationSweepIntervalMs: number
  // LLM catalog discovery sync cron (Fase 4). Runs syncDiscoveredModels()
  // periodically. Code default off; the base deploy enables it
  // (deploy/base/control-plane/configmaps.yaml). When on, one tick a few
  // seconds after start and then one every llmCatalogSyncIntervalMs (default
  // 24h), cross-replica-deduped by a session advisory lock inside the cron.
  llmCatalogSyncCronEnabled: boolean
  // Default OFF. Codex subscription management/admission stays dark until
  // CONTROL_API_CODEX_SUBSCRIPTION_ENABLED=true.
  codexSubscriptionEnabled: boolean
  // Public Codex CLI OAuth client id. Not a secret; PKCE/device flow protect the
  // grant. Override only to pin a documented registration.
  codexOAuthClientId: string
  // Default OFF. Grok SuperGrok/coding-plan management stays dark until
  // CONTROL_API_GROK_SUBSCRIPTION_ENABLED=true.
  grokSubscriptionEnabled: boolean
  // Public Grok CLI OAuth client id. Not a secret; device-code flow protects
  // the grant. Override only to pin a documented registration.
  grokOAuthClientId: string
  // Default OFF. When on, a periodic tick re-runs the SAME catalog sync the
  // connect flow and the manual Hub action drive, for every live connected
  // subscription grant of every enabled broker. Without it a grant's catalog is
  // written once at connect and never refreshed on its own.
  subscriptionCatalogSyncCronEnabled: boolean
  // Deliberately conservative: each tick issues one upstream catalog call PER
  // CONNECTION, and a Grok refresh inside the 5-minute skew rotates the refresh
  // token. A short interval is an abuse risk, not a freshness win.
  subscriptionCatalogSyncIntervalMs: number
  llmCatalogSyncIntervalMs: number
  // How long image-input evidence derived from models.dev stays valid, counted
  // from the catalog CAPTURE time (not the wall clock). Past it the shared
  // contract resolves the row to `unknown` with reason `evidence_expired` and
  // images are refused loudly until the next sync. Default 30 days; refused at
  // boot when it is below twice llmCatalogSyncIntervalMs and the cron is on.
  llmCatalogImageEvidenceTtlMs: number
  // §4.5 sanity guard, layer 3: absolute plausibility floor. If a LIVE run's
  // TOTAL mapped model count is below this, the whole run SKIPS stale-marking
  // (a flappy/truncated external catalog must not mass-stale the allowlist);
  // the inert `enabled=false` inserts still proceed. Calibrated off the vendored
  // snapshot (~1058 mapped models across 22 providers) — a conservative <10%
  // floor catches a catastrophic collapse without tripping on normal variation.
  modelsDevMinPlausibleLiveTotal: number
  // §4.5 sanity guard, layer 2: per-provider low/zero-live floor. A provider
  // that returns FEWER than this many live models but still has discovery rows
  // in DB is treated as suspicious and NOT stale-marked. 0 (the default) means
  // only the zero-live case is guarded (the mandatory floor); a higher value
  // also guards implausibly-low provider counts.
  llmCatalogSyncProviderMinLive: number
  registryPullSecretReconcileIntervalMs: number
  // OAuth proactive-refresh cron (mini-spec L). Default OFF until e2e; renews
  // remote access tokens inside the proactive window so a background grant's
  // rotating refresh token is exercised before it lapses, and sweeps DCR
  // client-secret expiry (avisar/degradar only).
  oauthProactiveRefreshCronEnabled: boolean
  oauthProactiveRefreshIntervalMs: number
  // Bp — proactive buffer. A grant is a candidate while its access token expires
  // within this window. MUST be > REACTIVE_REFRESH_BUFFER_MS (Br); validated at
  // boot (mini-spec §3 invariant `Bp > Br`).
  oauthProactiveRefreshBufferMs: number
  // Wc — warn window for a DCR confidential client_secret nearing expiry.
  oauthDcrSecretWarnMs: number
  budgetReservationTtlSeconds: number
  approvalRetentionDays: number
  userApprovalRequestArchiveCronEnabled: boolean
  userApprovalRequestArchiveBatchSize: number
  // Archive cron: workflow_runs -> workflow_runs_audit. The grace window holds
  // terminal runs in the live table so admin UI stays fast without unioning archived rows.
  workflowRunsArchiveCronEnabled: boolean
  workflowRunsArchiveIntervalMs: number
  workflowRunsArchiveGraceMs: number
  workflowRunsArchiveBatchSize: number
  // Schedule worker replaces K8s CronJobs: polls workflow_schedules under an
  // advisory lock for cross-replica dedup, fires matured schedules via
  // workflowRunService.createRun(actor_type='scheduled').
  workflowScheduleWorkerEnabled: boolean
  workflowScheduleWorkerIntervalMs: number
  workflowScheduleWorkerBatchSize: number
  workflowMaxWorkloadsPerRecipe: number
  workflowUiEgressInternalMaxItems: number
  workflowMaxSteps: number
  workflowStepDependsOnMaxItems: number
  workflowStepAllowedToolsMaxItems: number
  workflowStepMcpServersMaxItems: number
  workflowArtifactDownloadMaxBytes: number
  // Per-minute rate limits (PG-backed token buckets).
  approvalRlRequestPerMin: number
  adminSubscriptionReadPerMin: number
  adminSubscriptionWritePerMin: number
  subscriptionOAuthCallbackPerMin: number
  adminWorkflowReadPerMin: number
  adminWorkflowGrantReadPerMin: number
  adminWorkflowGrantWritePerMin: number
  adminWorkflowTriggerPerMin: number
  adminOutputsReadPerMin: number
  llmProviderAttemptAuthorizePerMin: number
  llmProviderAttemptAuthorizeAnonymousIpPerMin: number
  adminRegistryKeysPerMin: number
  adminRegistryGrantsPerMin: number
  adminRegistryConnectStatusPerMin: number
  adminRegistryConnectRequestPerMin: number
  adminRegistryConnectRecoveryPerMin: number
  adminConnectorDeleteEdgePerMin: number
  adminConnectorDeletePerMin: number
  pluginSdkAdminRlPerMin: number
  pluginSdkInternalRlPerMin: number
  pluginSdkCredentialRlPerMin: number
  pluginSdkAuthenticatedPreauthRlPerMin: number
  adminGfsGrantsPerMin: number
  adminGfsSharesPerMin: number
  adminGfsLegacyGrantReportPerMin: number
  approvalRlRefreshPerMin: number
  approvalRlExternalPerMin: number
  approvalRlExternalEdgePerMin: number
  approvalRlExternalClientIpPerMin: number
  oauthBrokerRlPerMin: number
  adminPublicTokenRlPerMin: number
  adminPublicTokenIpRlPerMin: number
  // Plugin Workload SDK platform rate limits (issue #348): per-minute
  // ceilings on the plugin abuse surface (data-path + pre-auth). Platform
  // protection, not per-service business quotas — usage/cost stays governed
  // by Token Budgets.
  pluginSdkNotificationsRlPerMin: number
  pluginSdkPromptBridgeRlPerMin: number
  pluginSdkRequestBucketRlPerMin: number
  pluginSdkPreauthRlPerMin: number
  // External Desktop GFS is a separate authority plane. The process-local
  // ingress backstop is intentionally wider than the distributed operation
  // buckets so normal Desktop read waterfalls cannot consume the security
  // budgets before authority resolution. The narrower values remain the
  // authoritative per-user/IP/actor operation ceilings.
  externalGfsIngressRlPerMin: number
  externalGfsTokenUserRlPerMin: number
  externalGfsTokenIpRlPerMin: number
  // Aggregate source-IP ceiling before authority resolution. This is a
  // defense-in-depth ceiling across authenticated non-token GFS traffic; it
  // is intentionally wider than the per-class/session/actor budgets.
  externalGfsIpRlPerMin: number
  // Each read class has its own budget, sized from its own observed peak; the
  // three mutation classes share one narrower budget. A Desktop root refresh
  // legitimately performs many resource reads, while grants and shares are
  // read only when the Manage dialog opens.
  externalGfsResourceReadRlPerMin: number
  externalGfsProxyReadRlPerMin: number
  externalGfsGrantsReadRlPerMin: number
  externalGfsSharesReadRlPerMin: number
  externalGfsOperationRlPerMin: number
  // Stateless-agent wake endpoint: per-host wake rate limit + server-side
  // coalescence window for the wake-annotation projection.
  hostWakeRlPerMin: number
  hostWakeCoalesceWindowMs: number
  approvalMediumChallengeTtlSec: number
  telegramProviderEventChallengeTtlSec: number
  approvalMediumChallengeMaxAttempts: number
  workflowApprovalNotificationDeliveryEnabled: boolean
  workflowApprovalNotificationDeliveryIntervalMs: number
  workflowApprovalNotificationDeliveryBatchSize: number
  workflowApprovalTelegramApiRoot: string
  workflowApprovalSlackApiRoot: string
  notificationStreamHeartbeatMs: number
  notificationStreamMaxLifetimeMs: number
  notificationStreamSnapshotLimit: number
  entityChangeDispatchIntervalMs: number
  entityChangeRetentionSeconds: number
  entityChangeDispatchBatchSize: number
  entityChangeMaxRecoveryEvents: number
  entityChangeStreamPollMs: number
  entityChangeUserVisibilityRefreshMs: number
  entityChangeStreamHeartbeatMs: number
  entityChangeStreamMaxLifetimeMs: number
  entityChangeStreamMaxConnections: number
  entityChangeStreamMaxConnectionsPerPrincipal: number
  notificationsDesktopFirstEnabled: boolean
  notificationDesktopGraceSeconds: number
  // Stricter than the normal refresh limiter: a client reaching reissue has
  // already exhausted refresh retries and is declaring auth broken — repeat
  // hits indicate either a real crash-loop recovery (bounded by pod restart
  // cadence) or an attacker replaying.
  approvalRlReissuePerMin: number
  approvalRlCleanupIntervalMs: number
  adminRevokedTokenCleanupIntervalMs: number
  // OAuth callback: symmetric secrets for state HMAC + refresh token
  // encryption. Keep both at least 32 chars / hex-encoded 64 chars so dev
  // defaults are usable without ceremony but prod overrides are forced.
  oauthStateHmacSecret: string
  oauthEncryptionKey: string
  // Public base URL the OAuth callback is reachable at (e.g.
  // https://example.com). Used to build the redirect_uri for the token
  // exchange so it matches the authorize step regardless of the internal proxy
  // chain's Host header. Empty → fall back to the request Host (local dev).
  oauthCallbackBaseUrl: string
  // SharedFileSystem — namespace housing both the CRD and the per-SFS
  // workspace-files-controller Service.
  sharedFilesystemsNamespace: string
  // Audience claim used by browsing JWTs; must match WSF_JWT_AUDIENCE on
  // the per-SFS wfc Deployment. The signing key is reused from rpcJwtPrivateKey.
  wfcJwtAudience: string
  // TTL for browsing JWTs minted by /admin/shared-filesystems/:name/token.
  wfcTokenTtlSeconds: number
  // gfs (Global File System) — audience claim for gfsc access tokens; gfsc
  // verifies aud === gfsTokenAudience. The signing key is reused from
  // rpcJwtPrivateKey (the open core uses one platform keypair; per-tenant keys
  // are the managed edition, P6).
  gfsTokenAudience: string
  // TTL for gfs access tokens minted by POST /api/v1/gfs/token.
  gfsTokenTtlSeconds: number
  // In-cluster base URL of the gfsc read ClusterIP Service (gfs namespace).
  gfscBaseUrl: string
  // In-cluster base URL of the writer-only gfsc Service for mutations.
  gfscWriteBaseUrl: string
  // Timeout (ms) for the control-api→gfsc proxied fetch. Homologous with the browser
  // client (GFS_UPLOAD_TIMEOUT_MS, 300s) and the control-ui server proxy
  // (CONTROL_API_PROXY_TIMEOUT_MS, set to 300s in the deployment; its route.ts code
  // fallback is 30s). This one defaults to 300s in code. Raise all three together.
  gfscProxyTimeoutMs: number
  // Upload-v2 edge admission. These are transport-abuse budgets, separate
  // from the 200 MiB product/file limit and GFSC's 4/16 stream authority.
  gfsUploadRequestPerMinute: number
  gfsUploadIpRequestPerMinute: number
  gfsUploadByteUnitBytes: number
  gfsUploadByteUnitsPerMinute: number
  gfsUploadIpByteUnitsPerMinute: number
  gfsUploadMaxActivePerSubject: number
  gfsUploadMaxActivePerIp: number
  gfsUploadMaxActiveGlobal: number
  gfsUploadMaxPartBytes: number
  // ClusterIP service URL template for the per-SFS wfc. {hash} is replaced
  // with the 10-char sfsHash that HCC's sharedFileSystemReconciler computes.
  // The template ends without a trailing slash; the proxy concatenates the
  // browser-side path. Default points at the in-cluster Service name from
  // sharedFileSystemFactory.wfcServiceName().
  wfcServiceUrlTemplate: string
  // Plugin image-host allowlist (Phase 2.3). Trusted raw-image prefixes for
  // local-mode McpServer images. Audit mode (default) adds no validation
  // error; enforce mode rejects installs/updates with a disallowed image.
  allowedPluginImagePrefixes: string[]
  enforcePluginImageAllowlist: boolean
  curatedHookOrgs: string[]
  defaultHookTrustCap: string
}

function assertNotPlaceholder(label: string, value: string): void {
  // Fail loud if the former overlay placeholder ever leaks into a running pod.
  // These tokens must be populated by `deploy/scripts/apply-inter-service-tokens.sh`
  // (kubectl patch --type=merge), not by kustomize. A `replace-with-*` value
  // means CI wiped the Secret back to the canary state — refuse to start.
  if (/^replace-with-/.test(value)) {
    throw new Error(
      `${label} has placeholder value "${value}". Run deploy/scripts/apply-inter-service-tokens.sh before deploying.`
    )
  }
}

// Parse a millisecond timeout env: must be a positive integer within the
// setTimeout/AbortSignal safe range (2^31-1); anything else falls back to the
// default (never lets NaN/overflow reach AbortSignal.timeout).
function parseTimeoutMs(raw: string | undefined, fallback: number): number {
  const parsed = raw ? Number(raw) : Number.NaN
  return Number.isInteger(parsed) && parsed > 0 && parsed <= 2_147_483_647 ? parsed : fallback
}

function parseInternalTokens(input: string): string[] {
  const tokens = input
    .split(',')
    .map(v => v.trim())
    .filter(Boolean)
  tokens.forEach((t, i) => assertNotPlaceholder(`CONTROL_API_INTERNAL_TOKENS[${i}]`, t))
  return tokens
}

function parseInternalServiceTokens(input: string): Record<string, string> {
  const result: Record<string, string> = {}
  for (const rawPair of input.split(',')) {
    const pair = rawPair.trim()
    if (!pair) continue
    const [service, ...rest] = pair.split('=')
    const key = String(service || '').trim()
    const value = rest.join('=').trim()
    if (!key || !value) continue
    assertNotPlaceholder(`CONTROL_API_INTERNAL_SERVICE_TOKENS[${key}]`, value)
    result[key] = value
  }
  assertDistinctBrokerProxyTokens(result)
  return result
}

function assertDistinctBrokerProxyTokens(tokens: Record<string, string>): void {
  const brokers = ['codex-llm-proxy', 'grok-llm-proxy']
  const seen = new Map<string, string>()
  for (const name of brokers) {
    const token = tokens[name]
    if (!token) continue
    const owner = seen.get(token)
    if (owner) {
      throw new Error(`internal service tokens for "${owner}" and "${name}" must be distinct`)
    }
    seen.set(token, name)
  }
}

function parseCsvList(input: string): string[] {
  return Array.from(
    new Set(
      input
        .split(',')
        .map(v => v.trim().toLowerCase())
        .filter(Boolean)
    )
  )
}

function required(name: string): string {
  const value = process.env[name]
  if (!value) {
    throw new Error(`Missing required environment variable: ${name}`)
  }
  return value
}

function requiredOrDevDefault(name: string, devDefault: string): string {
  const value = process.env[name]
  if (value) return value
  if (process.env.NODE_ENV !== 'production') return devDefault
  return required(name)
}

// Canonical decimal text only. Number() alone also reads '0x5A', '90.0', '9e1',
// ' 90' and '+90' as 90, which boots with a value the operator never wrote.
const CANONICAL_POSITIVE_INTEGER = /^[1-9]\d*$/
const CANONICAL_NON_NEGATIVE_INTEGER = /^(0|[1-9]\d*)$/

function positiveIntegerFromEnv(name: string, defaultValue: number): number {
  const raw = process.env[name]
  if (raw === undefined || raw.trim() === '') return defaultValue

  const value = Number(raw)
  if (!CANONICAL_POSITIVE_INTEGER.test(raw) || !Number.isSafeInteger(value)) {
    throw new Error(`${name} must be a positive integer`)
  }
  return value
}

/**
 * A non-negative integer env (>= 0). Unlike `positiveIntegerFromEnv`, 0 is a
 * valid, meaningful value here (the per-provider stale floor's default: guard
 * only the zero-live case). An unset/blank env yields the default; any other
 * non-integer / negative value is refused at boot rather than silently coerced.
 */
function nonNegativeIntegerFromEnv(name: string, defaultValue: number): number {
  const raw = process.env[name]
  if (raw === undefined || raw.trim() === '') return defaultValue
  const value = Number(raw)
  if (!CANONICAL_NON_NEGATIVE_INTEGER.test(raw) || !Number.isSafeInteger(value)) {
    throw new Error(`${name} must be a non-negative integer`)
  }
  return value
}

function boundedIntegerFromEnv(name: string, defaultValue: number, maxValue: number): number {
  const value = positiveIntegerFromEnv(name, defaultValue)
  if (value > maxValue) {
    throw new Error(`${name} must be an integer between 1 and ${maxValue}`)
  }
  return value
}

/**
 * A background-loop interval: a positive integer of milliseconds that must also clear a
 * floor.
 *
 * The floor is the part `positiveIntegerFromEnv` cannot express. `1` parses perfectly and
 * still reconciles a thousand times a second, so for a value handed straight to
 * `setInterval` "positive" is not the same as "sane". Refused at boot rather than clamped,
 * for the same reason every other invalid value here is refused: a silently corrected
 * interval leaves the operator's setting and the running behaviour disagreeing forever.
 */
function intervalMsFromEnv(name: string, defaultValue: number, minValue: number): number {
  const value = positiveIntegerFromEnv(name, defaultValue)
  if (value < minValue) {
    throw new Error(`${name} must be an integer >= ${minValue} (milliseconds)`)
  }
  return value
}

// Also the target namespace for the allowlist ConfigMap (cross-service contract):
// mcp-host + WRC read `clerum-llm-allowed-models` from here — see
// services/llmAllowedModelsConfigMap.ts.
const HOSTS_NAMESPACE = process.env.CONTROL_API_HOSTS_NAMESPACE || 'mcp-host'
const MCP_SERVERS_NAMESPACE = process.env.CONTROL_API_MCP_SERVERS_NAMESPACE || 'mcp-server'
const LLM_HOOKS_NAMESPACE = process.env.CONTROL_API_LLM_HOOKS_NAMESPACE || 'llm-hooks'
const SANDBOX_NAMESPACE = process.env.CONTROL_API_SANDBOX_NAMESPACE || 'sandbox-recipes'
const SANDBOX_UI_NAMESPACE = process.env.CONTROL_API_SANDBOX_UI_NAMESPACE || 'sandbox-ui'
const DEFAULT_MCP_HOST_JWT_MAX_HOST_REFS = 32
const DEFAULT_MCP_HOST_JWT_MAX_HOST_REF_LENGTH = 63 + 1 + 253
const REGISTRY_PULL_SECRET_RECONCILE_MIN_INTERVAL_MS = 10_000
// A 24h-default cron should never be dialed below a minute — refuse a hot loop.
const LLM_CATALOG_SYNC_MIN_INTERVAL_MS = 60_000
// Image-input evidence written by a sync expires this long after the capture it
// came from. The floor is two sync intervals: anything shorter would expire the
// evidence before the cron could possibly renew it.
const LLM_CATALOG_IMAGE_EVIDENCE_MIN_TTL_MS = 2 * LLM_CATALOG_SYNC_MIN_INTERVAL_MS
// Unlike the discovery sync (one call to models.dev per tick), a subscription
// reconciliation tick calls each broker once PER CONNECTED GRANT and can rotate
// a Grok refresh token on the way. Fifteen minutes is the floor below which the
// cron stops being a reconciler and becomes traffic against the vendor.
const SUBSCRIPTION_CATALOG_SYNC_MIN_INTERVAL_MS = 15 * 60_000
const WORKFLOW_MAX_WORKLOADS_PER_RECIPE_CEILING = 25
const WORKFLOW_UI_EGRESS_INTERNAL_MAX_ITEMS_CEILING = 25
const WORKFLOW_MAX_STEPS_CEILING = 100
const WORKFLOW_STEP_DEPENDS_ON_MAX_ITEMS_CEILING = 100
const WORKFLOW_STEP_ALLOWED_TOOLS_MAX_ITEMS_CEILING = 100
// The step mcpServers env can only lower this value; the CRD hard ceiling remains 20.
const WORKFLOW_STEP_MCP_SERVERS_MAX_ITEMS_CEILING = 20
// The actor-keyed external GFS budgets accept an environment override up to a
// compiled ceiling; a larger value refuses to boot. The two 480 budgets may
// double; the two 120 budgets may reach 480.
const EXTERNAL_GFS_RESOURCE_READ_RL_PER_MIN_CEILING = 960
const EXTERNAL_GFS_PROXY_READ_RL_PER_MIN_CEILING = 960
const EXTERNAL_GFS_GRANTS_READ_RL_PER_MIN_CEILING = 480
const EXTERNAL_GFS_SHARES_READ_RL_PER_MIN_CEILING = 480
const EXTERNAL_GFS_OPERATION_RL_PER_MIN_CEILING = 180
// 100 requests per second from one source on one public admin route.
const ADMIN_PUBLIC_TOKEN_IP_RL_PER_MIN_CEILING = 6_000

function parseRegistryConnectionMode(): 'managed' | 'self-hosted' {
  const raw = process.env.REGISTRY_CONNECTION_MODE
  if (raw === undefined || raw === '') return 'managed' // default; requiredness enforced in the guard below
  if (raw === 'managed' || raw === 'self-hosted') return raw
  throw new Error(`REGISTRY_CONNECTION_MODE must be 'managed' or 'self-hosted' (got '${raw}')`)
}

type ExternalRateLimitSource = 'default' | 'environment'

function externalRateLimitSettingFromEnv(
  name: string,
  defaultValue: number
): { value: number; source: ExternalRateLimitSource } {
  const raw = process.env[name]
  return {
    value: positiveIntegerFromEnv(name, defaultValue),
    source: raw === undefined || raw.trim() === '' ? 'default' : 'environment',
  }
}

// External routes intentionally have three independent dimensions with
// different scopes. operation <= session < clientIp is the recommended
// capacity topology, but it is not a correctness invariant: an operator may
// deliberately tune any one scope without changing the other two. Keep scalar
// values fail-closed, preserve exact overrides, and make a crossed topology an
// actionable boot advisory instead of a service-startup failure.
const externalRateLimitConfig = (() => {
  const operation = externalRateLimitSettingFromEnv('APPROVAL_RL_EXTERNAL_PER_MIN', 60)
  const session = externalRateLimitSettingFromEnv('APPROVAL_RL_EXTERNAL_EDGE_PER_MIN', 120)
  const clientIp = externalRateLimitSettingFromEnv('APPROVAL_RL_EXTERNAL_CLIENT_IP_PER_MIN', 1200)
  const followsRecommendedTopology =
    operation.value <= session.value && session.value < clientIp.value

  if (!followsRecommendedTopology) {
    rootLogger.warn(
      {
        event: 'external_rate_limit_topology_advisory',
        resolved: { operation, session, clientIp },
        recommendedTopology: 'operation <= session < clientIp',
      },
      'External rate limits cross the recommended topology; preserving configured values'
    )
  }

  return {
    operation: operation.value,
    session: session.value,
    clientIp: clientIp.value,
  }
})()

function failClosedBooleanFromEnv(name: string): boolean {
  const raw = process.env[name]
  if (raw === undefined || raw === '' || raw === 'false') return false
  if (raw === 'true') return true
  throw new Error(`${name} must be 'true' or 'false' (got '${raw}')`)
}

const CLERUM_DEV_MODE_ENABLED = process.env.CLERUM_DEV_MODE === 'true'
if (process.env.NODE_ENV === 'production' && CLERUM_DEV_MODE_ENABLED) {
  throw new Error(
    '[SECURITY] Startup rejected: CLERUM_DEV_MODE=true is not allowed with NODE_ENV=production. ' +
      'Provide deployment-specific JWT signing keys and unset CLERUM_DEV_MODE.'
  )
}

const JWT_SIGNING_KEY_ENV_NAMES: Record<DevJwtSlot, string> = {
  rpc: 'CONTROL_API_RPC_JWT_PRIVATE_KEY',
  session: 'CONTROL_API_SESSION_JWT_PRIVATE_KEY',
  admin: 'CONTROL_API_ADMIN_JWT_PRIVATE_KEY',
}

const DEV_ADMIN_PASSWORD_HASH = '$2b$12$9QdfGGp5KYg8osGa1n0.DuwQiB1RopCWIDJhmsuK4ygjTmIT8pvgy'

// Validate every explicit input before dev-store access. A malformed configured
// slot must not cause another slot to generate a new local identity.
const explicitJwtSigningMaterial: Partial<Record<DevJwtSlot, SigningMaterial>> = {}
for (const slot of ['rpc', 'session', 'admin'] as const) {
  const envName = JWT_SIGNING_KEY_ENV_NAMES[slot]
  const raw = process.env[envName]
  if (raw) explicitJwtSigningMaterial[slot] = parseSigningMaterial(raw, envName)
}
const voucherRaw = process.env.CONTROL_API_REGISTRY_VOUCHER_PRIVATE_KEY
const voucherMaterial = voucherRaw
  ? parseSigningMaterial(voucherRaw, 'CONTROL_API_REGISTRY_VOUCHER_PRIVATE_KEY')
  : undefined
const rpcVerifierRaw = process.env.CONTROL_API_RPC_JWT_PUBLIC_KEY
const explicitRpcVerifier = rpcVerifierRaw
  ? parseVerifierMaterial(
      rpcVerifierRaw,
      'effective RPC JWT verifier public key (CONTROL_API_RPC_JWT_PUBLIC_KEY)'
    )
  : undefined

function assertRpcIdentity(signing: SigningMaterial): void {
  if (explicitRpcVerifier && explicitRpcVerifier.fingerprint !== signing.fingerprint) {
    throw new Error(
      'CONTROL_API_RPC_JWT_PUBLIC_KEY must correspond to CONTROL_API_RPC_JWT_PRIVATE_KEY'
    )
  }
}
if (explicitJwtSigningMaterial.rpc) assertRpcIdentity(explicitJwtSigningMaterial.rpc)
if (!CLERUM_DEV_MODE_ENABLED) {
  for (const slot of ['rpc', 'session', 'admin'] as const) {
    if (!explicitJwtSigningMaterial[slot]) required(JWT_SIGNING_KEY_ENV_NAMES[slot])
  }
}
const jwtSigningMaterial = Object.fromEntries(
  (['rpc', 'session', 'admin'] as const).map(slot => [
    slot,
    explicitJwtSigningMaterial[slot] ?? loadOrCreateDevJwtSigningMaterial(slot),
  ])
) as Record<DevJwtSlot, SigningMaterial>
assertRpcIdentity(jwtSigningMaterial.rpc)

const memberRegistrationMode: 'remote' | 'hosted' = (() => {
  const raw = (process.env.CONTROL_API_MEMBER_REGISTRATION_MODE || 'remote').trim()
  if (raw !== 'remote' && raw !== 'hosted') {
    throw new Error(
      `CONTROL_API_MEMBER_REGISTRATION_MODE must be 'remote' or 'hosted' (got '${raw}')`
    )
  }
  return raw
})()

// "Present" = non-empty after trim: blanking a value in the deploy Secret must
// count as absent (spec §8.1 — apply-inter-service-tokens.sh re-adds the key).
function memberRegistrationEnvPresent(name: string): boolean {
  const value = process.env[name]
  return typeof value === 'string' && value.trim() !== ''
}

if (memberRegistrationMode === 'hosted') {
  // Fail fast on ambiguity — scoped to the DELIBERATELY-set identity vars only.
  // HMAC_SECRET is excluded: the shipped deploy unconditionally injects it via
  // the control-api-internal-tokens Secret (spec §8.1), so it is ignorable legacy.
  const injectedIdentity = [
    'CONTROL_API_MEMBER_REGISTRATION_HMAC_KID',
    'CONTROL_API_MEMBER_REGISTRATION_TENANT_ID',
  ].filter(memberRegistrationEnvPresent)
  if (injectedIdentity.length > 0) {
    throw new Error(
      `[SECURITY] CONTROL_API_MEMBER_REGISTRATION_MODE=hosted is mutually exclusive with an injected remote member-registration identity. Unset: ${injectedIdentity.join(', ')}`
    )
  }
  if (memberRegistrationEnvPresent('CONTROL_API_MEMBER_REGISTRATION_HMAC_SECRET')) {
    rootLogger.warn(
      { event: 'hosted_member_registration_env_secret_ignored' },
      'Hosted member-registration uses its enrolled credentials'
    )
  }
}

// Computed once so every consumer below reads the exact same resolved value
// (rather than re-parsing REGISTRY_CONNECTION_MODE a second time).
const registryConnectionMode: 'managed' | 'self-hosted' = parseRegistryConnectionMode()

// Computed as locals because the two values are coupled: image-input evidence
// written by a sync expires TTL after the capture it came from, so a TTL shorter
// than the refresh cadence would expire every claim before the next tick could
// renew it. The cross-field check below is only meaningful while the cron is the
// thing doing the refreshing; with the cron off the operator owns the cadence
// (documented in docs/llm-providers/README.md).
const llmCatalogSyncIntervalMs = intervalMsFromEnv(
  'LLM_CATALOG_SYNC_INTERVAL_MS',
  24 * 60 * 60 * 1000,
  LLM_CATALOG_SYNC_MIN_INTERVAL_MS
)
const llmCatalogImageEvidenceTtlMs = intervalMsFromEnv(
  'LLM_CATALOG_IMAGE_EVIDENCE_TTL_MS',
  30 * 24 * 60 * 60 * 1000,
  LLM_CATALOG_IMAGE_EVIDENCE_MIN_TTL_MS
)
if (
  process.env.LLM_CATALOG_SYNC_CRON_ENABLED === 'true' &&
  llmCatalogImageEvidenceTtlMs < 2 * llmCatalogSyncIntervalMs
) {
  throw new Error(
    'LLM_CATALOG_IMAGE_EVIDENCE_TTL_MS must be at least twice LLM_CATALOG_SYNC_INTERVAL_MS when LLM_CATALOG_SYNC_CRON_ENABLED=true'
  )
}

// Bp (proactive buffer). Computed as a local so the `Bp > Br` invariant
// (mini-spec L §3) is validated BEFORE the config object is built — a proactive
// window that does not clear the reactive buffer would let the two paths compete
// for the same row on the happy path, defeating the idempotency argument. Br is
// the reactive buffer's single source of truth (`tokenHelper.ts`), never a
// re-typed literal. Fail-fast (throw) rather than clamp, like every other
// invalid config value here.
const oauthProactiveRefreshBufferMs = positiveIntegerFromEnv(
  'OAUTH_PROACTIVE_REFRESH_BUFFER_MS',
  300_000
)
if (oauthProactiveRefreshBufferMs <= REACTIVE_REFRESH_BUFFER_MS) {
  throw new Error(
    `OAUTH_PROACTIVE_REFRESH_BUFFER_MS (${oauthProactiveRefreshBufferMs}) must be greater than the reactive refresh buffer (${REACTIVE_REFRESH_BUFFER_MS}ms)`
  )
}

export const config: Config = {
  port: Number(process.env.CONTROL_API_PORT || 8090),
  jsonBodyLimit: process.env.CONTROL_API_JSON_BODY_LIMIT || '150mb',
  namespace: process.env.CONTROL_API_NAMESPACE || 'mcp-server',
  hostsNamespace: HOSTS_NAMESPACE,
  contextsNamespace: process.env.CONTROL_API_CONTEXTS_NAMESPACE || 'mcp-server',
  communicationChannelsNamespace:
    process.env.CONTROL_API_COMMUNICATION_CHANNELS_NAMESPACE || 'channels',
  mcpServersNamespace: MCP_SERVERS_NAMESPACE,
  llmHooksNamespace: LLM_HOOKS_NAMESPACE,
  sandboxNamespace: SANDBOX_NAMESPACE,
  sandboxUiNamespace: SANDBOX_UI_NAMESPACE,
  secretsNamespace: process.env.CONTROL_API_SECRETS_NAMESPACE || 'mcp-host',
  pgConnectionString:
    process.env.CONTROL_API_PG_CONNECTION_STRING ||
    'postgres://postgres:[email protected]:5432/profiles',
  internalTokens: parseInternalTokens(
    process.env.CONTROL_API_INTERNAL_TOKENS || 'dev-external-rest-api-token,dev-rpc-proxy-token'
  ),
  internalServiceTokens: parseInternalServiceTokens(
    process.env.CONTROL_API_INTERNAL_SERVICE_TOKENS ||
      'external-rest-api=dev-external-rest-api-token,rpc-proxy=dev-rpc-proxy-token,webhook-proxy=dev-webhook-proxy-token,workflow-approval-reader=dev-wa-reader-token,codex-llm-proxy=dev-codex-llm-proxy-token,grok-llm-proxy=dev-grok-llm-proxy-token'
  ),
  internalControlJwtWrcHmacSecret: requiredOrDevDefault(
    'INTERNAL_CONTROL_JWT_WRC_HMAC_SECRET',
    'dev-wrc-internal-control-jwt-hmac-secret-32-bytes'
  ),
  internalControlJwtHccHmacSecret: requiredOrDevDefault(
    'INTERNAL_CONTROL_JWT_HCC_HMAC_SECRET',
    'dev-hcc-internal-control-jwt-hmac-secret-32-bytes'
  ),
  allowedIssuanceNamespaces: parseCsvList(
    process.env.CONTROL_API_ALLOWED_ISSUANCE_NAMESPACES || `${HOSTS_NAMESPACE},${SANDBOX_NAMESPACE}`
  ),
  memberRegistrationMode,
  memberRegistrationExternalHubBaseUrl:
    process.env.CONTROL_API_MEMBER_REGISTRATION_EXTERNAL_HUB_BASE_URL ||
    'https://registration.evenfire.ai/api/v1',
  memberRegistrationServiceBaseUrl:
    memberRegistrationMode === 'hosted'
      ? process.env.CONTROL_API_MEMBER_REGISTRATION_SERVICE_BASE_URL || ''
      : requiredOrDevDefault(
          'CONTROL_API_MEMBER_REGISTRATION_SERVICE_BASE_URL',
          'http://member-registration-service.profiles.svc.cluster.local:8092/api/v1'
        ),
  memberRegistrationServiceHmacSecret: (() => {
    if (memberRegistrationMode === 'hosted') {
      // Hosted mode never signs with the env secret; see the module-scope warning.
      return ''
    }
    const value = requiredOrDevDefault(
      'CONTROL_API_MEMBER_REGISTRATION_HMAC_SECRET',
      'dev-member-registration-hmac-secret'
    )
    assertNotPlaceholder('CONTROL_API_MEMBER_REGISTRATION_HMAC_SECRET', value)
    return value
  })(),
  memberRegistrationServiceHmacKid:
    process.env.CONTROL_API_MEMBER_REGISTRATION_HMAC_KID || 'example-dev',
  memberRegistrationTenantId:
    process.env.CONTROL_API_MEMBER_REGISTRATION_TENANT_ID || 'example-dev',
  desktopExternalRestApiBaseUrl:
    process.env.CONTROL_API_DESKTOP_EXTERNAL_REST_API_BASE_URL || 'http://127.0.0.1:8091',
  desktopRpcProxyBaseUrl:
    process.env.CONTROL_API_DESKTOP_RPC_PROXY_BASE_URL || 'http://127.0.0.1:8094',
  desktopProfileUiBaseUrl:
    process.env.CONTROL_API_DESKTOP_PROFILE_UI_BASE_URL || 'http://127.0.0.1:3001',
  desktopAppName: process.env.CONTROL_API_DESKTOP_APP_NAME || 'Evenfire',
  // Narrow, explicit elevation switch. Missing/false is intentionally OFF;
  // this must not inherit registry, password-seeding, or generic deploy mode.
  desktopGfsOperatorLinkingEnabled: failClosedBooleanFromEnv(
    'CONTROL_API_DESKTOP_GFS_OPERATOR_LINKING_ENABLED'
  ),
  controlUiBaseUrl: process.env.CONTROL_API_CONTROL_UI_BASE_URL || 'http://127.0.0.1:3000',
  controlUiAppName: process.env.CONTROL_API_CONTROL_UI_APP_NAME || 'Evenfire',
  sessionJwtPrivateKey: jwtSigningMaterial.session.privatePem,
  jwtIssuer: requiredOrDevDefault('CONTROL_API_JWT_ISSUER', 'control-api'),
  jwtAudience: requiredOrDevDefault('CONTROL_API_JWT_AUDIENCE', 'profile-ui'),
  rpcJwtPrivateKey: jwtSigningMaterial.rpc.privatePem,
  rpcJwtPublicKey: explicitRpcVerifier?.publicPem ?? jwtSigningMaterial.rpc.publicPem,
  rpcJwtIssuer: requiredOrDevDefault('CONTROL_API_RPC_JWT_ISSUER', 'control-api'),
  rpcJwtAudience: requiredOrDevDefault('CONTROL_API_RPC_JWT_AUDIENCE', 'rpc-proxy'),
  rpcTokenTtlSeconds: Number(process.env.CONTROL_API_RPC_TOKEN_TTL_SECONDS || 300),
  hostSecretLabelKey: process.env.CONTROL_API_HOST_SECRET_LABEL_KEY || 'clerum.io/host-secret',
  hostSecretLabelValue: process.env.CONTROL_API_HOST_SECRET_LABEL_VALUE || 'true',
  policyAuthAudience: process.env.CONTROL_API_POLICY_AUTH_AUDIENCE || 'control-api',
  googleClientId: requiredOrDevDefault('CONTROL_API_GOOGLE_CLIENT_ID', 'dev-google-client-id'),
  adminJwtPrivateKey: jwtSigningMaterial.admin.privatePem,
  adminJwtIssuer: requiredOrDevDefault('CONTROL_API_ADMIN_JWT_ISSUER', 'control-api'),
  adminJwtAudience: requiredOrDevDefault('CONTROL_API_ADMIN_JWT_AUDIENCE', 'control-ui'),
  adminJwtTtlSeconds: Number(process.env.CONTROL_API_ADMIN_JWT_TTL_SECONDS || 60 * 60),
  // No implicit admin identity substitution; managed mode requires this key.
  registryVoucherPrivateKey: voucherMaterial?.privatePem ?? '',
  registryVoucherKid: process.env.CONTROL_API_REGISTRY_VOUCHER_KID ?? '',
  registryUrl: process.env.CLERUM_REGISTRY_URL ?? '',
  registryClientId: process.env.CLERUM_REGISTRY_CLIENT_ID ?? '',
  registryClientSecret: process.env.CLERUM_REGISTRY_CLIENT_SECRET ?? '',
  registryAuthEnabled: process.env.CLERUM_REGISTRY_AUTH_ENABLED === 'true',
  registryConnectionMode,
  // Default ON for every deploy now that the Publisher UI is production-ready
  // (publish → install verified end-to-end); only an explicit
  // CONTROL_API_PUBLISHER_UI_ENABLED='false' disables it. This flag only exposes
  // the surface — the control-ui still fails CLOSED for curator / non-org-bound
  // deploys (isPublisherEnabled requires scope.scope !== null && !curator), so an
  // unconnected self-hosted deploy won't show the Publisher regardless.
  publisherUiEnabled: process.env.CONTROL_API_PUBLISHER_UI_ENABLED !== 'false',
  adminAuthMaxFailures: Number(process.env.CONTROL_API_ADMIN_AUTH_MAX_FAILURES || 5),
  adminAuthLockMinutes: Number(process.env.CONTROL_API_ADMIN_AUTH_LOCK_MINUTES || 15),
  adminBootstrapUsername: requiredOrDevDefault('CONTROL_API_ADMIN_BOOTSTRAP_USERNAME', 'admin'),
  adminBootstrapEmail: process.env.CONTROL_API_ADMIN_BOOTSTRAP_EMAIL || '',
  adminBootstrapPasswordHash: requiredOrDevDefault(
    'CONTROL_API_ADMIN_BOOTSTRAP_PASSWORD_HASH',
    DEV_ADMIN_PASSWORD_HASH
  ),
  adminDefaultAgentNames: (process.env.CONTROL_API_ADMIN_DEFAULT_AGENT_NAMES || 'chatllm')
    .split(',')
    .map(v => v.trim())
    .filter(Boolean),
  adminDefaultContextIds: (process.env.CONTROL_API_ADMIN_DEFAULT_CONTEXT_IDS || 'context1')
    .split(',')
    .map(v => v.trim())
    .filter(Boolean),
  mcpHostJwtAccessTtlSec: Number(process.env.WORKFLOW_APPROVAL_ACCESS_TTL_SEC || 600),
  mcpHostJwtRefreshTtlSec: Number(process.env.WORKFLOW_APPROVAL_REFRESH_TTL_SEC || 3600),
  mcpHostJwtControlTtlSec: Number(process.env.MCP_HOST_JWT_CONTROL_TTL_SEC || 600),
  mcpHostJwtMaxHostRefs: positiveIntegerFromEnv(
    'MCP_HOST_JWT_MAX_HOST_REFS',
    DEFAULT_MCP_HOST_JWT_MAX_HOST_REFS
  ),
  mcpHostJwtMaxHostRefLength: positiveIntegerFromEnv(
    'MCP_HOST_JWT_MAX_HOST_REF_LENGTH',
    DEFAULT_MCP_HOST_JWT_MAX_HOST_REF_LENGTH
  ),
  oauthBrokerJwtTtlSec: Number(process.env.CONTROL_API_OAUTH_BROKER_JWT_TTL_SEC || 600),
  // Fail-closed kill-switch: same default-OFF idiom as
  // desktopGfsOperatorLinkingEnabled. Missing/'false' → OFF; only 'true' enables.
  mcpOauthBrokerEnabled: failClosedBooleanFromEnv('MCP_OAUTH_BROKER_ENABLED'),
  userApprovalRequestDefaultTtlSec: Number(process.env.WORKFLOW_APPROVAL_DEFAULT_TTL_SEC || 86400),
  userApprovalRequestMaxTtlSec: Number(process.env.WORKFLOW_APPROVAL_MAX_TTL_SEC || 604800),
  userApprovalRequestExpiryIntervalMs: Number(
    process.env.WORKFLOW_APPROVAL_EXPIRY_INTERVAL_MS || 60000
  ),
  usageRollup5MinIntervalMs: Number(process.env.USAGE_ROLLUP_5MIN_INTERVAL_MS || 60_000),
  usageRollupHourlyIntervalMs: Number(process.env.USAGE_ROLLUP_HOURLY_INTERVAL_MS || 300_000),
  usageRollupDailyIntervalMs: Number(process.env.USAGE_ROLLUP_DAILY_INTERVAL_MS || 3_600_000),
  usageRetentionIntervalMs: Number(process.env.USAGE_RETENTION_INTERVAL_MS || 86_400_000),
  // Budget danger-zone reservation sweep (deletes expired rows). Cleanup only —
  // expired reservations already stop counting via the `expires_at > NOW()`
  // filter, so a coarse interval (default 60s) is fine.
  budgetReservationSweepIntervalMs: Number(
    process.env.BUDGET_RESERVATION_SWEEP_INTERVAL_MS || 60_000
  ),
  // Default OFF: `=== 'true'`, NOT the default-on `(x ?? 'true') !== 'false'`
  // idiom used by the other crons. This one stays dark until an operator turns
  // it on deliberately.
  llmCatalogSyncCronEnabled: process.env.LLM_CATALOG_SYNC_CRON_ENABLED === 'true',
  // Default OFF. Absent or any value other than the exact token `true` keeps
  // Codex subscription management and admission dark.
  codexSubscriptionEnabled: process.env.CONTROL_API_CODEX_SUBSCRIPTION_ENABLED === 'true',
  // Public native client used by the Codex CLI ChatGPT login. This is not a
  // confidential client secret. Browser OAuth requires a deployment-registered
  // client id; the default CLI client supports device-code connect only.
  codexOAuthClientId:
    process.env.CONTROL_API_CODEX_OAUTH_CLIENT_ID || 'app_EMoamEEZ73f0CkXaXp7hrann',
  grokSubscriptionEnabled: process.env.CONTROL_API_GROK_SUBSCRIPTION_ENABLED === 'true',
  // Default OFF, same exact-token idiom as the discovery cron above: the
  // reconciliation stays dark until an operator turns it on deliberately.
  subscriptionCatalogSyncCronEnabled: process.env.SUBSCRIPTION_CATALOG_SYNC_CRON_ENABLED === 'true',
  subscriptionCatalogSyncIntervalMs: intervalMsFromEnv(
    'SUBSCRIPTION_CATALOG_SYNC_INTERVAL_MS',
    6 * 60 * 60 * 1000,
    SUBSCRIPTION_CATALOG_SYNC_MIN_INTERVAL_MS
  ),
  // Public native client used by Grok CLI / SuperGrok device-code login.
  // This is not a confidential client secret. Same shape as Codex above.
  grokOAuthClientId:
    process.env.CONTROL_API_GROK_OAUTH_CLIENT_ID || 'b1a00492-073a-47ea-816f-4c329264a828',
  // Both computed above the literal (same env var, default and 60s floor as the
  // inline form they replace): the TTL is validated against the interval, which
  // needs both values in scope before the object is built.
  llmCatalogSyncIntervalMs,
  llmCatalogImageEvidenceTtlMs,
  modelsDevMinPlausibleLiveTotal: positiveIntegerFromEnv(
    'MODELS_DEV_MIN_PLAUSIBLE_LIVE_TOTAL',
    100
  ),
  llmCatalogSyncProviderMinLive: nonNegativeIntegerFromEnv('LLM_CATALOG_SYNC_PROVIDER_MIN_LIVE', 0),
  // How often to re-assert the platform image-pull credential. This is a standing
  // invariant, not a fast path: a WorkflowRecipe created by `kubectl apply` or the WRC
  // `deploy_recipe` tool never touches control-api, so the credential has to be there
  // already. Installs still provision synchronously, so this interval only bounds how long
  // a CRD created OUTSIDE control-api waits. Coarse (10 min) on purpose — each tick is a
  // few reads and no mint once the cluster is healthy.
  //
  // Validated, not merely parsed: this value goes straight into `setInterval`, and each tick
  // costs a Postgres advisory-lock transaction plus a Secret read per platform namespace. A
  // 10s floor is still two orders of magnitude below the default and far above anything that
  // could pass for a hot loop.
  registryPullSecretReconcileIntervalMs: intervalMsFromEnv(
    'REGISTRY_PULL_SECRET_RECONCILE_INTERVAL_MS',
    600_000,
    REGISTRY_PULL_SECRET_RECONCILE_MIN_INTERVAL_MS
  ),
  // OAuth proactive-refresh cron (mini-spec L). Default OFF: `=== 'true'`, so the
  // sweep stays dark until an operator opts in after e2e.
  oauthProactiveRefreshCronEnabled: process.env.OAUTH_PROACTIVE_REFRESH_CRON_ENABLED === 'true',
  oauthProactiveRefreshIntervalMs: positiveIntegerFromEnv(
    'OAUTH_PROACTIVE_REFRESH_INTERVAL_MS',
    60_000
  ),
  // Computed + validated above the literal (Bp > Br must hold before the object
  // is built): see `oauthProactiveRefreshBufferMs` local.
  oauthProactiveRefreshBufferMs,
  // Wc — default 7 days.
  oauthDcrSecretWarnMs: positiveIntegerFromEnv('OAUTH_DCR_SECRET_WARN_MS', 604_800_000),
  // Danger-zone reservation TTL (§9.8a: ~2-3× the rollup lag, ~5 min). Short
  // enough that a hung reservation auto-frees; long enough that real spend has
  // reached the rollups before it expires (no double-count on the next check).
  // This is the task-level TTL. A Codex or Grok provider attempt reserves for
  // its whole lifetime plus this value, and the in-flight usage grace adds it
  // to the longest attempt (services/llmProviderAttemptEnvelope.ts).
  budgetReservationTtlSeconds: positiveIntegerFromEnv('BUDGET_RESERVATION_TTL_SECONDS', 300),
  // Default 180 days. Archival runs daily at 02:00 UTC; older terminal
  // approvals move to the archive table.
  approvalRetentionDays: positiveIntegerFromEnv('APPROVAL_RETENTION_DAYS', 180),
  userApprovalRequestArchiveCronEnabled:
    (process.env.APPROVAL_ARCHIVE_CRON_ENABLED ?? 'true') !== 'false',
  userApprovalRequestArchiveBatchSize: positiveIntegerFromEnv('APPROVAL_ARCHIVE_BATCH_SIZE', 500),
  // workflow_runs archive cron defaults:
  //   interval 15 min, grace 1h, batch 500 (matches approvals).
  workflowRunsArchiveCronEnabled:
    (process.env.WORKFLOW_RUNS_ARCHIVE_CRON_ENABLED ?? 'true') !== 'false',
  workflowRunsArchiveIntervalMs: Number(
    process.env.WORKFLOW_RUNS_ARCHIVE_INTERVAL_MS || 15 * 60 * 1000
  ),
  workflowRunsArchiveGraceMs: Number(process.env.WORKFLOW_RUNS_ARCHIVE_GRACE_MS || 60 * 60 * 1000),
  workflowRunsArchiveBatchSize: Number(process.env.WORKFLOW_RUNS_ARCHIVE_BATCH_SIZE || 500),
  // Schedule worker defaults:
  //   interval 10s (low latency vs cron granularity of 1min),
  //   batch 50 rows per sweep, enabled by default.
  workflowScheduleWorkerEnabled:
    (process.env.WORKFLOW_SCHEDULE_WORKER_ENABLED ?? 'true') !== 'false',
  workflowScheduleWorkerIntervalMs: Number(
    process.env.WORKFLOW_SCHEDULE_WORKER_INTERVAL_MS || 10_000
  ),
  workflowScheduleWorkerBatchSize: Number(process.env.WORKFLOW_SCHEDULE_WORKER_BATCH_SIZE || 50),
  workflowMaxWorkloadsPerRecipe: boundedIntegerFromEnv(
    'CLERUM_WORKFLOW_MAX_WORKLOADS_PER_RECIPE',
    WORKFLOW_MAX_WORKLOADS_PER_RECIPE_CEILING,
    WORKFLOW_MAX_WORKLOADS_PER_RECIPE_CEILING
  ),
  workflowUiEgressInternalMaxItems: boundedIntegerFromEnv(
    'CLERUM_WORKFLOW_UI_EGRESS_INTERNAL_MAX_ITEMS',
    WORKFLOW_UI_EGRESS_INTERNAL_MAX_ITEMS_CEILING,
    WORKFLOW_UI_EGRESS_INTERNAL_MAX_ITEMS_CEILING
  ),
  workflowMaxSteps: boundedIntegerFromEnv(
    'CLERUM_WORKFLOW_MAX_STEPS',
    WORKFLOW_MAX_STEPS_CEILING,
    WORKFLOW_MAX_STEPS_CEILING
  ),
  workflowStepDependsOnMaxItems: boundedIntegerFromEnv(
    'CLERUM_WORKFLOW_STEP_DEPENDS_ON_MAX_ITEMS',
    WORKFLOW_STEP_DEPENDS_ON_MAX_ITEMS_CEILING,
    WORKFLOW_STEP_DEPENDS_ON_MAX_ITEMS_CEILING
  ),
  workflowStepAllowedToolsMaxItems: boundedIntegerFromEnv(
    'CLERUM_WORKFLOW_STEP_ALLOWED_TOOLS_MAX_ITEMS',
    50,
    WORKFLOW_STEP_ALLOWED_TOOLS_MAX_ITEMS_CEILING
  ),
  workflowStepMcpServersMaxItems: boundedIntegerFromEnv(
    'CLERUM_WORKFLOW_STEP_MCP_SERVERS_MAX_ITEMS',
    WORKFLOW_STEP_MCP_SERVERS_MAX_ITEMS_CEILING,
    WORKFLOW_STEP_MCP_SERVERS_MAX_ITEMS_CEILING
  ),
  workflowArtifactDownloadMaxBytes: positiveIntegerFromEnv(
    'CLERUM_ATTACHMENT_MAX_BYTES',
    50 * 1024 * 1024
  ),
  adminSubscriptionReadPerMin: positiveIntegerFromEnv(
    'CONTROL_API_ADMIN_SUBSCRIPTION_READ_PER_MIN',
    150
  ),
  adminSubscriptionWritePerMin: positiveIntegerFromEnv(
    'CONTROL_API_ADMIN_SUBSCRIPTION_WRITE_PER_MIN',
    100
  ),
  subscriptionOAuthCallbackPerMin: positiveIntegerFromEnv(
    'CONTROL_API_SUBSCRIPTION_OAUTH_CALLBACK_PER_MIN',
    100
  ),
  adminWorkflowReadPerMin: positiveIntegerFromEnv('CONTROL_API_ADMIN_WORKFLOW_READ_PER_MIN', 300),
  adminWorkflowGrantReadPerMin: positiveIntegerFromEnv(
    'CONTROL_API_ADMIN_WORKFLOW_GRANT_READ_PER_MIN',
    300
  ),
  adminWorkflowGrantWritePerMin: positiveIntegerFromEnv(
    'CONTROL_API_ADMIN_WORKFLOW_GRANT_WRITE_PER_MIN',
    100
  ),
  adminWorkflowTriggerPerMin: positiveIntegerFromEnv(
    'CONTROL_API_ADMIN_WORKFLOW_TRIGGER_PER_MIN',
    50
  ),
  adminOutputsReadPerMin: positiveIntegerFromEnv('CONTROL_API_ADMIN_OUTPUTS_READ_PER_MIN', 150),
  llmProviderAttemptAuthorizePerMin: positiveIntegerFromEnv(
    'CONTROL_API_LLM_PROVIDER_ATTEMPT_AUTHORIZE_PER_MIN',
    300
  ),
  llmProviderAttemptAuthorizeAnonymousIpPerMin: positiveIntegerFromEnv(
    'CONTROL_API_LLM_PROVIDER_ATTEMPT_AUTHORIZE_ANONYMOUS_IP_PER_MIN',
    60
  ),
  adminRegistryKeysPerMin: positiveIntegerFromEnv('CONTROL_API_ADMIN_REGISTRY_KEYS_PER_MIN', 150),
  adminRegistryGrantsPerMin: positiveIntegerFromEnv(
    'CONTROL_API_ADMIN_REGISTRY_GRANTS_PER_MIN',
    150
  ),
  adminRegistryConnectStatusPerMin: positiveIntegerFromEnv(
    'CONTROL_API_ADMIN_REGISTRY_CONNECT_STATUS_PER_MIN',
    150
  ),
  adminRegistryConnectRequestPerMin: positiveIntegerFromEnv(
    'CONTROL_API_ADMIN_REGISTRY_CONNECT_REQUEST_PER_MIN',
    15
  ),
  adminRegistryConnectRecoveryPerMin: positiveIntegerFromEnv(
    'CONTROL_API_ADMIN_REGISTRY_CONNECT_RECOVERY_PER_MIN',
    50
  ),
  adminConnectorDeleteEdgePerMin: positiveIntegerFromEnv(
    'CONTROL_API_ADMIN_CONNECTOR_DELETE_EDGE_PER_MIN',
    300
  ),
  adminConnectorDeletePerMin: positiveIntegerFromEnv(
    'CONTROL_API_ADMIN_CONNECTOR_DELETE_PER_MIN',
    150
  ),
  pluginSdkAdminRlPerMin: positiveIntegerFromEnv('CONTROL_API_PLUGIN_SDK_ADMIN_PER_MIN', 600),
  pluginSdkInternalRlPerMin: positiveIntegerFromEnv('CONTROL_API_PLUGIN_SDK_INTERNAL_PER_MIN', 600),
  pluginSdkCredentialRlPerMin: positiveIntegerFromEnv(
    'CONTROL_API_PLUGIN_SDK_CREDENTIAL_PER_MIN',
    1800
  ),
  pluginSdkAuthenticatedPreauthRlPerMin: positiveIntegerFromEnv(
    'CONTROL_API_PLUGIN_SDK_AUTHENTICATED_PREAUTH_PER_MIN',
    6000
  ),
  adminGfsGrantsPerMin: positiveIntegerFromEnv('CONTROL_API_ADMIN_GFS_GRANTS_PER_MIN', 150),
  adminGfsSharesPerMin: positiveIntegerFromEnv('CONTROL_API_ADMIN_GFS_SHARES_PER_MIN', 150),
  adminGfsLegacyGrantReportPerMin: positiveIntegerFromEnv(
    'CONTROL_API_ADMIN_GFS_LEGACY_GRANT_REPORT_PER_MIN',
    150
  ),
  approvalRlRequestPerMin: positiveIntegerFromEnv('APPROVAL_RL_REQUEST_PER_MIN', 600),
  approvalRlRefreshPerMin: positiveIntegerFromEnv('APPROVAL_RL_REFRESH_PER_MIN', 100),
  approvalRlExternalPerMin: externalRateLimitConfig.operation,
  approvalRlExternalEdgePerMin: externalRateLimitConfig.session,
  // By default the source-IP backstop is wider than the per-session edge bucket
  // so a shared NAT does not turn the 120/min fairness budget into a
  // platform-wide ceiling. Operators may override these independent scopes;
  // crossed values are preserved after the boot advisory above.
  approvalRlExternalClientIpPerMin: externalRateLimitConfig.clientIp,
  oauthBrokerRlPerMin: positiveIntegerFromEnv('CONTROL_API_OAUTH_BROKER_RL_PER_MIN', 300),
  // The public control-admin token routes (password reset, invitation, email
  // confirmation) have two buckets per route. The first keys on source IP and
  // the submitted value (email, login or token prefix): one person retrying.
  // The second keys on source IP alone and caps value rotation from one
  // source. Many admins can share one public IP (a corporate VPN egress, an
  // office NAT), so the IP ceiling is 15x the per-value one, and a request the
  // per-value bucket refuses is not charged to the IP bucket.
  adminPublicTokenRlPerMin: positiveIntegerFromEnv('CONTROL_API_ADMIN_PUBLIC_TOKEN_RL_PER_MIN', 20),
  adminPublicTokenIpRlPerMin: boundedIntegerFromEnv(
    'CONTROL_API_ADMIN_PUBLIC_TOKEN_IP_RL_PER_MIN',
    300,
    ADMIN_PUBLIC_TOKEN_IP_RL_PER_MIN_CEILING
  ),
  // Plugin Workload SDK platform rate limits (issue #348). Parsed via
  // positiveIntegerFromEnv so invalid operator config (non-integer, zero,
  // negative) fails loud at boot instead of running with NaN limits, which
  // would effectively fail open.
  pluginSdkNotificationsRlPerMin: positiveIntegerFromEnv(
    'CONTROL_API_PLUGIN_SDK_NOTIFICATIONS_PER_MIN',
    750
  ),
  pluginSdkPromptBridgeRlPerMin: positiveIntegerFromEnv(
    'CONTROL_API_PLUGIN_SDK_PROMPTBRIDGE_PER_MIN',
    600
  ),
  pluginSdkRequestBucketRlPerMin: positiveIntegerFromEnv(
    'CONTROL_API_PLUGIN_SDK_REQUEST_BUCKET_PER_MIN',
    6000
  ),
  pluginSdkPreauthRlPerMin: positiveIntegerFromEnv('CONTROL_API_PLUGIN_SDK_PREAUTH_PER_MIN', 600),
  // External GFS authority-boundary budgets. The four keyed by source IP or
  // by token minting stay compiled: an IP bucket is shared behind a NAT, so
  // loosening it widens a blast radius beyond one user, and token minting
  // does not scale with the number of open surfaces. The 1800/min ingress
  // guard is only a coarse process-local backstop.
  externalGfsIngressRlPerMin: 1_800,
  externalGfsTokenUserRlPerMin: 10,
  externalGfsTokenIpRlPerMin: 600,
  externalGfsIpRlPerMin: 1_200,
  // The actor-keyed budgets are overridable within a compiled ceiling. Each
  // class's value feeds that class's pre-resolution session and (class, IP)
  // buckets, its resolved per-actor bucket and its express backstop in
  // routes/external/gfs.ts, all through externalGfsClassRlPerMin.
  // assertExternalGfsBudgetInvariants below refuses a combination where
  // mutations exceed a read class or a read class exceeds the per-IP
  // all-class bucket.
  //
  // The four read classes sum to 1200 per calendar minute (480 + 480 + 120 +
  // 120), which equals the all-class pre:ip bucket (1200): one source IP is
  // capped at that value whatever the class mix. With one shared read budget
  // the nominal sum was 1920. No all-read per-actor cap exists; the test
  // suite states the sum instead of a boot invariant.
  //
  // A budget L is per calendar minute in Postgres. The per-route express
  // backstop has its own 60 s window, started by a key's first request, so
  // the two windows are not aligned: one actor can pass about 2L - 1 requests
  // of a class in any sliding 60 s, per control-api replica (959 at 480).
  // The stress suite's E2 case pins that bound.
  //
  // Peaks below are the busiest sliding 60 s of the 30-day funnel log, prod /
  // dev.
  //
  // Resource (resolve, capabilities, upload status, resources, affordances,
  // children): 133 / 85, the prod peak being the 2026-09-18 incident. One
  // Desktop surface peaks at 58 resource reads/min after PR #702. 480 covers
  // eight surfaces of one user and is 3.6x the incident peak.
  externalGfsResourceReadRlPerMin: boundedIntegerFromEnv(
    'CONTROL_API_EXTERNAL_GFS_RESOURCE_READ_RL_PER_MIN',
    480,
    EXTERNAL_GFS_RESOURCE_READ_RL_PER_MIN_CEILING
  ),
  // Proxy read: 12 / 14. 480 rather than 120 because planned per-row
  // thumbnails fan out one proxy read per listed row, as affordances do today.
  externalGfsProxyReadRlPerMin: boundedIntegerFromEnv(
    'CONTROL_API_EXTERNAL_GFS_PROXY_READ_RL_PER_MIN',
    480,
    EXTERNAL_GFS_PROXY_READ_RL_PER_MIN_CEILING
  ),
  // Grants and shares reads: 4 / 4 and 2 / 4. Both happen only when the
  // Manage dialog opens; 120 is 30x the observed peak.
  externalGfsGrantsReadRlPerMin: boundedIntegerFromEnv(
    'CONTROL_API_EXTERNAL_GFS_GRANTS_READ_RL_PER_MIN',
    120,
    EXTERNAL_GFS_GRANTS_READ_RL_PER_MIN_CEILING
  ),
  externalGfsSharesReadRlPerMin: boundedIntegerFromEnv(
    'CONTROL_API_EXTERNAL_GFS_SHARES_READ_RL_PER_MIN',
    120,
    EXTERNAL_GFS_SHARES_READ_RL_PER_MIN_CEILING
  ),
  // Operation: one maximum-size Desktop upload is at least 27 mutations
  // (ceil(200 MiB / 8 MiB) parts + create + complete, desktop-app
  // src/gfs/upload.ts), and a 429 on a part is retried and counted again.
  // 90 keeps three concurrent uploads out of that retry band. Derivation is
  // regression-guarded by test/config.externalGfsBudgets.test.ts.
  externalGfsOperationRlPerMin: boundedIntegerFromEnv(
    'CONTROL_API_EXTERNAL_GFS_OPERATION_RL_PER_MIN',
    90,
    EXTERNAL_GFS_OPERATION_RL_PER_MIN_CEILING
  ),
  // Default derived from the wake mechanism's worst case, not picked ad hoc.
  // rpc-proxy's wake-and-hold loop re-triggers POST /rpc/hosts/:hostRef/wake
  // every wakeRetriggerMs=15000 for up to wakeMaxHoldMs=48000 (defaults in
  // rpc-proxy/src/config.ts), so one held request costs
  // 1 + floor(48000/15000) = 4 calls per rpc-proxy instance; rpc-proxy runs
  // replicas: 2 (deploy/base/rpc-proxy/rpc-proxy.yaml) with per-instance
  // dedup, so the mechanism alone can emit 8 calls / 48s (10.0/min) per
  // host. Desktop prewarm adds a burst of up to 3 calls per device.
  // Middleware order in routes/rpc-access/hosts.ts is limiter BEFORE
  // handler, and the hostWakeCoalesceWindowMs coalescer runs INSIDE the
  // handler (it coalesces annotation projections, not calls) — coalesced
  // calls therefore still consume rate-limit budget, so this budget must
  // cover RAW calls (the arithmetic above counts raw calls). 30/min is >=3x
  // the single-hold mechanism volume and covers one held wake plus prewarm
  // bursts from a few concurrent devices (4 x 3 = 12) plus a real message.
  // Derivation is regression-guarded by test/config.hostWakeRateLimit.test.ts.
  hostWakeRlPerMin: positiveIntegerFromEnv('CONTROL_API_HOST_WAKE_RL_PER_MIN', 150),
  hostWakeCoalesceWindowMs: Number(process.env.CONTROL_API_HOST_WAKE_COALESCE_WINDOW_MS || 2000),
  approvalMediumChallengeTtlSec: Number(
    process.env.WORKFLOW_APPROVAL_MEDIUM_CHALLENGE_TTL_SEC || 60 * 60
  ),
  telegramProviderEventChallengeTtlSec: positiveIntegerFromEnv(
    'TELEGRAM_PROVIDER_EVENT_CHALLENGE_TTL_SEC',
    120
  ),
  approvalMediumChallengeMaxAttempts: Number(
    process.env.WORKFLOW_APPROVAL_MEDIUM_CHALLENGE_MAX_ATTEMPTS || 5
  ),
  workflowApprovalNotificationDeliveryEnabled:
    (process.env.WORKFLOW_APPROVAL_NOTIFICATION_DELIVERY_ENABLED ?? 'true') !== 'false',
  workflowApprovalNotificationDeliveryIntervalMs: positiveIntegerFromEnv(
    'WORKFLOW_APPROVAL_NOTIFICATION_DELIVERY_INTERVAL_MS',
    5_000
  ),
  workflowApprovalNotificationDeliveryBatchSize: boundedIntegerFromEnv(
    'WORKFLOW_APPROVAL_NOTIFICATION_DELIVERY_BATCH_SIZE',
    10,
    50
  ),
  workflowApprovalTelegramApiRoot:
    process.env.WORKFLOW_APPROVAL_TELEGRAM_API_ROOT || 'https://api.telegram.org',
  workflowApprovalSlackApiRoot:
    process.env.WORKFLOW_APPROVAL_SLACK_API_ROOT || 'https://slack.com/api',
  notificationStreamHeartbeatMs: Number(process.env.NOTIFICATION_STREAM_HEARTBEAT_MS || 25 * 1000),
  notificationStreamMaxLifetimeMs: Number(
    process.env.NOTIFICATION_STREAM_MAX_LIFETIME_MS || 10 * 60 * 1000
  ),
  notificationStreamSnapshotLimit: Number(process.env.NOTIFICATION_STREAM_SNAPSHOT_LIMIT || 50),
  entityChangeDispatchIntervalMs: boundedIntegerEnv(
    'ENTITY_CHANGE_DISPATCH_INTERVAL_MS',
    500,
    100,
    5000
  ),
  entityChangeRetentionSeconds: boundedIntegerEnv(
    'ENTITY_CHANGE_RETENTION_SECONDS',
    24 * 60 * 60,
    60 * 60,
    30 * 24 * 60 * 60
  ),
  entityChangeDispatchBatchSize: boundedIntegerEnv(
    'ENTITY_CHANGE_DISPATCH_BATCH_SIZE',
    1000,
    1,
    10000
  ),
  entityChangeMaxRecoveryEvents: boundedIntegerEnv(
    'ENTITY_CHANGE_MAX_RECOVERY_EVENTS',
    10000,
    1,
    100000
  ),
  entityChangeStreamPollMs: boundedIntegerEnv('ENTITY_CHANGE_STREAM_POLL_MS', 1000, 250, 5000),
  entityChangeUserVisibilityRefreshMs: boundedIntegerEnv(
    'ENTITY_CHANGE_USER_VISIBILITY_REFRESH_MS',
    4000,
    1000,
    5000
  ),
  entityChangeStreamHeartbeatMs: boundedIntegerEnv(
    'ENTITY_CHANGE_STREAM_HEARTBEAT_MS',
    20 * 1000,
    1000,
    60 * 1000
  ),
  entityChangeStreamMaxLifetimeMs: boundedIntegerEnv(
    'ENTITY_CHANGE_STREAM_MAX_LIFETIME_MS',
    10 * 60 * 1000,
    30 * 1000,
    60 * 60 * 1000
  ),
  entityChangeStreamMaxConnections: boundedIntegerEnv(
    'ENTITY_CHANGE_STREAM_MAX_CONNECTIONS',
    256,
    1,
    10000
  ),
  entityChangeStreamMaxConnectionsPerPrincipal: boundedIntegerEnv(
    'ENTITY_CHANGE_STREAM_MAX_CONNECTIONS_PER_PRINCIPAL',
    8,
    1,
    1000
  ),
  notificationsDesktopFirstEnabled:
    (process.env.NOTIFICATIONS_DESKTOP_FIRST_ENABLED ?? 'true') !== 'false',
  // Parse safely: a non-empty non-numeric env (e.g. "disabled") yields NaN,
  // which would flow into the notification enqueue make_interval($N::int) and
  // break ALL SDK notification delivery. Fall back to 90 for non-finite/negative.
  notificationDesktopGraceSeconds: (() => {
    const n = Number(process.env.NOTIFICATION_DESKTOP_GRACE_SECONDS || 90)
    return Number.isFinite(n) && n >= 0 ? Math.floor(n) : 90
  })(),
  approvalRlReissuePerMin: positiveIntegerFromEnv('APPROVAL_RL_REISSUE_PER_MIN', 25),
  // Cleanup of stale token-bucket rows (older than 5 min — the only active
  // window). 5 min lines up with the longest bucket window we use.
  approvalRlCleanupIntervalMs: Number(process.env.APPROVAL_RL_CLEANUP_INTERVAL_MS || 5 * 60_000),
  adminRevokedTokenCleanupIntervalMs: Number(
    process.env.CONTROL_API_ADMIN_REVOKED_TOKEN_CLEANUP_INTERVAL_MS || 5 * 60_000
  ),
  oauthStateHmacSecret: requiredOrDevDefault(
    'CONTROL_API_OAUTH_STATE_HMAC_SECRET',
    'dev-oauth-state-hmac-secret-32-bytes-pad'
  ),
  oauthEncryptionKey: requiredOrDevDefault(
    'CONTROL_API_OAUTH_ENCRYPTION_KEY',
    // 32-byte hex-encoded dev key (AES-256-GCM). Prod must override.
    '00112233445566778899aabbccddeeff00112233445566778899aabbccddeeff'
  ),
  // Optional: when set, used verbatim as the origin of the public OAuth callback
  // URL (the redirect_uri). Empty → derive from the request Host (local dev).
  oauthCallbackBaseUrl: process.env.CONTROL_API_OAUTH_CALLBACK_BASE_URL ?? '',
  // SharedFileSystem feature defaults — keep these aligned with the wfc
  // service's WSF_* env names and with HCC's CONTEXT_MAPPER_WFC_* defaults.
  //
  // v1 invariant: SharedFileSystem CRDs always live with the Hosts that mount
  // their PVCs read-only, i.e. in the Hosts namespace. So this MUST default to
  // HOSTS_NAMESPACE (not a hardcoded `mcp-host`): on a per-tenant managed cluster
  // the Hosts namespace is `mcp-host-<slug>`, and the SharedFilesystems admin
  // route + the granted RBAC both target that tenant namespace. Defaulting to
  // a bare `mcp-host` made the route query the untenanted namespace and 403
  // (its RBAC is granted in `mcp-host-<slug>`, never `mcp-host`). The explicit
  // CONTROL_API_SHARED_FILESYSTEMS_NAMESPACE override still wins when set.
  sharedFilesystemsNamespace:
    process.env.CONTROL_API_SHARED_FILESYSTEMS_NAMESPACE || HOSTS_NAMESPACE,
  wfcJwtAudience: process.env.CONTROL_API_WFC_JWT_AUDIENCE || 'workspace-files-controller',
  wfcTokenTtlSeconds: Number(process.env.CONTROL_API_WFC_TOKEN_TTL_SECONDS || 300),
  gfsTokenAudience: process.env.CONTROL_API_GFS_JWT_AUDIENCE || 'gfs-controller',
  gfsTokenTtlSeconds: Number(process.env.CONTROL_API_GFS_TOKEN_TTL_SECONDS || 3600),
  gfscBaseUrl: process.env.CONTROL_API_GFSC_BASE_URL || 'http://gfsc.gfs.svc.cluster.local:8087',
  gfscWriteBaseUrl:
    process.env.CONTROL_API_GFSC_WRITE_BASE_URL || 'http://gfsc-writer.gfs.svc.cluster.local:8087',
  gfscProxyTimeoutMs: parseTimeoutMs(process.env.CONTROL_API_GFSC_PROXY_TIMEOUT_MS, 300_000),
  gfsUploadRequestPerMinute: positiveIntegerFromEnv(
    'CONTROL_API_GFS_UPLOAD_REQUESTS_PER_MINUTE',
    120
  ),
  gfsUploadIpRequestPerMinute: positiveIntegerFromEnv(
    'CONTROL_API_GFS_UPLOAD_IP_REQUESTS_PER_MINUTE',
    600
  ),
  gfsUploadByteUnitBytes: 1024 * 1024,
  gfsUploadByteUnitsPerMinute: positiveIntegerFromEnv('CONTROL_API_GFS_UPLOAD_MIB_PER_MINUTE', 512),
  gfsUploadIpByteUnitsPerMinute: positiveIntegerFromEnv(
    'CONTROL_API_GFS_UPLOAD_IP_MIB_PER_MINUTE',
    2048
  ),
  gfsUploadMaxActivePerSubject: positiveIntegerFromEnv(
    'CONTROL_API_GFS_UPLOAD_MAX_ACTIVE_PER_SUBJECT',
    8
  ),
  gfsUploadMaxActivePerIp: positiveIntegerFromEnv('CONTROL_API_GFS_UPLOAD_MAX_ACTIVE_PER_IP', 16),
  gfsUploadMaxActiveGlobal: positiveIntegerFromEnv('CONTROL_API_GFS_UPLOAD_MAX_ACTIVE_GLOBAL', 32),
  gfsUploadMaxPartBytes: boundedIntegerFromEnv(
    'CONTROL_API_GFS_UPLOAD_MAX_PART_BYTES',
    16 * 1024 * 1024,
    16 * 1024 * 1024
  ),
  // {hash} = first 10 chars of sha256(`${ns}/${name}`); see sharedFileSystemHash
  // in host-context-controller/src/k8s/sharedFileSystemFactory.ts.
  wfcServiceUrlTemplate:
    process.env.CONTROL_API_WFC_SERVICE_URL_TEMPLATE ||
    'http://wfc-{hash}.mcp-host.svc.cluster.local:8086',
  // Plugin image-host allowlist (Phase 2.3). Permissive default = current
  // fleet hosts + registry.evenfire.ai; enforce defaults to false (audit
  // mode). NOT parseCsvList — that lowercases, which would corrupt prefixes.
  allowedPluginImagePrefixes: (
    process.env.CONTROL_API_ALLOWED_IMAGE_PREFIXES ??
    [...DEFAULT_ALLOWED_PLUGIN_IMAGE_PREFIXES].join(',')
  )
    .split(',')
    .map(s => s.trim())
    .filter(Boolean),
  // Match HCC's getEnvBool truthy set (true/1, case-insensitive) so the paired
  // enforce flags (CONTROL_API_/CONTEXT_MAPPER_ENFORCE_IMAGE_ALLOWLIST) agree on
  // operator input and don't diverge at the enforce flip.
  enforcePluginImageAllowlist:
    (process.env.CONTROL_API_ENFORCE_IMAGE_ALLOWLIST ?? '').toLowerCase() === 'true' ||
    process.env.CONTROL_API_ENFORCE_IMAGE_ALLOWLIST === '1',
  // Guardrails install-hook trust policy (spec §8.4 / registry gap #1). The
  // registry's entries.trust_level is publisher-influenced, so the saga only
  // honors it for CURATED orgs; every other org's hook is capped at
  // `defaultHookTrustCap` regardless of the column. The cluster's OWN org (from
  // resolvePublishScope) and official evenfire (`@clerum`/`@evenfire`) are ALWAYS
  // curated — not listed here — so this env is purely ADDITIVE, for extra
  // third-party orgs the operator chooses to trust. Empty by default. Case-
  // sensitive (org scopes carry '@'); NOT parseCsvList (which lowercases).
  curatedHookOrgs: (process.env.CONTROL_API_CURATED_HOOK_ORGS ?? '')
    .split(',')
    .map(s => s.trim())
    .filter(Boolean),
  // Trust ceiling applied to a non-curated org's hook. `mid` lets a self-published
  // hook clear a `mid` floor but never reach `high` (so it can never unlock the
  // content+egress combination gated at `high`, §8.4).
  defaultHookTrustCap: (process.env.CONTROL_API_DEFAULT_HOOK_TRUST_CAP ?? 'mid').toLowerCase(),
}

/**
 * Refuse an incoherent set of external GFS budgets at boot. Never clamps: a
 * corrected value would leave the operator's setting and the running limit
 * disagreeing.
 *
 * - A mutation class must not be allowed more freely than its read
 *   counterpart: resource, grants and shares mutations share one budget,
 *   which must not exceed any of the three read budgets. proxy-read has no
 *   mutation counterpart.
 * - No read class may exceed the per-IP all-class bucket in front of it;
 *   otherwise that bucket caps it under a different key and the configured
 *   number is never reached.
 *
 * The per-IP check cannot fire from the environment today: the largest read
 * ceiling (960) is below the compiled per-IP budget (1200). It guards a change
 * to either compiled value, and test/config.externalGfsBudgets.test.ts pins
 * the relation for every read class.
 */
export function assertExternalGfsBudgetInvariants(budgets: {
  resourceReadPerMin: number
  proxyReadPerMin: number
  grantsReadPerMin: number
  sharesReadPerMin: number
  operationPerMin: number
  ipPerMin: number
}): void {
  const reads = [
    ['CONTROL_API_EXTERNAL_GFS_RESOURCE_READ_RL_PER_MIN', budgets.resourceReadPerMin, true],
    ['CONTROL_API_EXTERNAL_GFS_PROXY_READ_RL_PER_MIN', budgets.proxyReadPerMin, false],
    ['CONTROL_API_EXTERNAL_GFS_GRANTS_READ_RL_PER_MIN', budgets.grantsReadPerMin, true],
    ['CONTROL_API_EXTERNAL_GFS_SHARES_READ_RL_PER_MIN', budgets.sharesReadPerMin, true],
  ] as const
  for (const [name, readPerMin, hasMutationCounterpart] of reads) {
    if (hasMutationCounterpart && budgets.operationPerMin > readPerMin) {
      throw new Error(
        `CONTROL_API_EXTERNAL_GFS_OPERATION_RL_PER_MIN (${budgets.operationPerMin}) must not ` +
          `exceed ${name} (${readPerMin})`
      )
    }
    if (readPerMin > budgets.ipPerMin) {
      throw new Error(
        `${name} (${readPerMin}) must not exceed ` +
          `the per-IP external GFS budget externalGfsIpRlPerMin (${budgets.ipPerMin})`
      )
    }
  }
}

assertExternalGfsBudgetInvariants({
  resourceReadPerMin: config.externalGfsResourceReadRlPerMin,
  proxyReadPerMin: config.externalGfsProxyReadRlPerMin,
  grantsReadPerMin: config.externalGfsGrantsReadRlPerMin,
  sharesReadPerMin: config.externalGfsSharesReadRlPerMin,
  operationPerMin: config.externalGfsOperationRlPerMin,
  ipPerMin: config.externalGfsIpRlPerMin,
})

/**
 * A per-IP ceiling below the per-value limit would let one shared IP (an
 * office, a VPN egress) be refused before a single admin on it reached their
 * own limit, so that combination is refused at boot.
 */
export function assertAdminPublicTokenBudgetInvariants(budgets: {
  perValuePerMin: number
  perIpPerMin: number
}): void {
  if (budgets.perIpPerMin < budgets.perValuePerMin) {
    throw new Error(
      `CONTROL_API_ADMIN_PUBLIC_TOKEN_IP_RL_PER_MIN (${budgets.perIpPerMin}) must not be below ` +
        `CONTROL_API_ADMIN_PUBLIC_TOKEN_RL_PER_MIN (${budgets.perValuePerMin})`
    )
  }
}

assertAdminPublicTokenBudgetInvariants({
  perValuePerMin: config.adminPublicTokenRlPerMin,
  perIpPerMin: config.adminPublicTokenIpRlPerMin,
})

// Namespace config validation: fail fast if any namespace is empty.
// Empty namespace would target the K8s default namespace — a silent security gap.
const NAMESPACE_KEYS: (keyof Config)[] = [
  'hostsNamespace',
  'contextsNamespace',
  'communicationChannelsNamespace',
  'mcpServersNamespace',
  'llmHooksNamespace',
  'sandboxNamespace',
  'sandboxUiNamespace',
  'secretsNamespace',
  'sharedFilesystemsNamespace',
]
for (const key of NAMESPACE_KEYS) {
  if (!(config[key] as string).trim()) {
    throw new Error(
      `[CONFIG] Namespace config "${key}" is empty. ` +
        'All namespace values must be non-empty strings.'
    )
  }
}

// Registry consumer auth guard: when auth is on, refuse to boot without OAuth2
// credentials; separately, refuse a registry URL outside the allowlist for any
// deployment that will really talk to a registry (defense against
// cross-environment misconfiguration sending writes to the wrong registry).

// A configured URL is MANDATORY whenever auth is on. Today this is enforced
// implicitly — allowed.includes('') is never true, so an empty URL falls
// through to the allowlist throw. The allowlist block below is preconditioned
// on registryUrl !== '', which would SKIP that throw and let a managed
// deployment with auth on and no URL boot, then fail later with a bare fetch
// URL-parse TypeError. Kept as its own check so the OR cannot swallow it.
if (config.registryAuthEnabled && config.registryUrl === '') {
  throw new Error('CLERUM_REGISTRY_URL is required when CLERUM_REGISTRY_AUTH_ENABLED=true')
}

// URL allowlist — defense against cross-environment misconfiguration sending
// writes to the wrong registry. Enforced whenever the deployment will really
// talk to a registry: an EXPLICITLY self-hosted deployment (which POSTs its
// registration before any credentials exist, so gating this on auth was always
// backwards), or any auth-enabled deployment. The shared registry
// `registry.evenfire.ai` is the default a self-hoster connects to (see
// docs/how-to/connect-to-registry.md); the in-cluster URL covers a
// self-hosted registry-api. A deployment that runs its own registry adds its
// URL via CLERUM_REGISTRY_URL_ALLOWLIST (comma-separated) rather than editing
// this list. `example.com` is the reserved-domain fixture used across the
// test suite — inert (no real registry) and kept so tests need no churn.
//
// The gate must never be `config.registryUrl !== ''` alone — dropping the
// self-hosted disjunct is exactly the rejected design that broke managed mode
// (see the regression test below). Reading process.env directly here is
// defensive against a future change to the parser's default; for today's
// parser it is equivalent to config.registryConnectionMode, not itself
// load-bearing.
if (
  config.registryUrl !== '' &&
  (process.env.REGISTRY_CONNECTION_MODE === 'self-hosted' || config.registryAuthEnabled)
) {
  const allowed = [
    'https://registry.evenfire.ai',
    'http://registry-api.registry.svc.cluster.local:8085',
    'https://example.com',
    // Trim-only (NOT parseCsvList, which lowercases) — the entries are compared
    // verbatim against config.registryUrl, which is not lowercased.
    ...(process.env.CLERUM_REGISTRY_URL_ALLOWLIST || '')
      .split(',')
      .map(s => s.trim())
      .filter(Boolean),
  ]
  if (process.env.CLERUM_DEV_MODE === 'true') {
    allowed.push('http://localhost:8085')
  }
  if (!allowed.includes(config.registryUrl)) {
    throw new Error(
      `CLERUM_REGISTRY_URL=${config.registryUrl} is not in the registry URL allowlist: ${allowed.join(', ')}`
    )
  }
}

// Mode requirement (S10: never infer mode from which credentials exist) and the
// managed credential/voucher checks stay gated on auth, UNCHANGED.
if (config.registryAuthEnabled) {
  // Mode must be set EXPLICITLY when the registry is enabled — never inferred
  // from which credentials happen to be present (S10: no silent split-brain).
  if (!process.env.REGISTRY_CONNECTION_MODE) {
    throw new Error(
      'REGISTRY_CONNECTION_MODE is required (managed|self-hosted) when CLERUM_REGISTRY_AUTH_ENABLED=true'
    )
  }
  rootLogger.info(
    { event: 'registry_connection_mode', mode: config.registryConnectionMode },
    'Registry connection mode'
  )

  if (config.registryConnectionMode === 'managed') {
    // Managed machine creds live in env (unchanged).
    if (!config.registryClientId) {
      throw new Error(
        'CLERUM_REGISTRY_CLIENT_ID is required in managed mode with registry auth enabled'
      )
    }
    if (!config.registryClientSecret) {
      throw new Error(
        'CLERUM_REGISTRY_CLIENT_SECRET is required in managed mode with registry auth enabled'
      )
    }
    // Voucher v2 material is MANDATORY in managed mode (M3 cutover done — no
    // break-glass legacy fallback remains).
    if (!config.registryVoucherPrivateKey) {
      throw new Error(
        'CONTROL_API_REGISTRY_VOUCHER_PRIVATE_KEY is required in managed mode (voucher v2)'
      )
    }
    if (!config.registryVoucherKid) {
      throw new Error('CONTROL_API_REGISTRY_VOUCHER_KID is required in managed mode (voucher v2)')
    }
  }
  // self-hosted: env creds/material NOT required here — they come from the
  // registry_connection row. The "no row" fail-fast is an async guard in main.ts
  // AFTER initDb (config.ts is sync and cannot query Postgres). See Task 8.
}

if (process.env.NODE_ENV === 'production') {
  // NOTE: the old voucher-key fallback WARN (dedicated key unset → sign with the
  // admin JWT key) is gone. Under voucher v2 a managed prod boot without the
  // dedicated key/kid FAILS FAST in the registryAuthEnabled guard above (unless
  // break-glass), so there is no silent fallback left to warn about.

  for (const [serviceName, token] of Object.entries(config.internalServiceTokens)) {
    if (/^dev-/.test(token)) {
      throw new Error(
        `[SECURITY] Production startup rejected: default dev internal service token detected for "${serviceName}". ` +
          'Set CONTROL_API_INTERNAL_SERVICE_TOKENS to deployment-specific secrets.'
      )
    }
  }
}