import { aliasTemplateError } from "../providers/alias-template";
import { redactSecretString } from "../lib/redact";
import { parseDashboardTrustedProxy } from "./dashboard-trusted-proxy";
import { readExistingSpendSalt, spendPoolAliasesError, validatePoolAliasOwners } from "../lib/spend-pool-alias-validation";
import { isSubagentModelEntry, rawSubagentModelForce } from "./subagent-models";
import { validRemainingQuotaAccountIds } from "../codex/account-use-remaining";
import { protocolConfigSchema } from "./schema/config-schema";
import { createHash } from "node:crypto";
import { lstatSync, readFileSync } from "node:fs";
import { join } from "node:path";
import * as z from "zod/v4";
import { compactionRecoveryConfigError } from "./schema/compaction-recovery";
import { nativeReasoningRetentionConfigError } from "./schema/native-reasoning-retention";
import { WORKFLOW_BUDGET_SHAPE_HINT, workflowBudgetConfigError } from "./schema/workflow-budget";
import { ROUTED_CATALOG_DEFAULTS_SHAPE_HINT, routedCatalogDefaultsConfigError } from "./schema/routed-catalog-defaults";
import { desktopCompatibilityConfigError } from "./schema/desktop-compatibility";
import { blockedModelRedirectsError } from "./schema/blocked-model-redirects";
import { mainAccountHardLockFallbackError } from "./schema/main-account-hard-lock-fallback";
import { fallbackPolicyError } from "./schema/fallback-policy";
import { subscriptionReserveConfigError } from "./schema/subscription-reserve";
import type { OcxConfig } from "../types";
import { anthropicAccountPoolConfigError, anthropicOAuthInstanceConfigError, anthropicSidecarConfigError } from "./schema/anthropic-account-pool";
import { configReasoningPinsConfigError } from "./provider-validation";
import { loopbackCompanionAllowed } from "../codex/loopback-target";
import { UPSTREAM_HOST_CIRCUIT_MAX_THRESHOLD } from "../codex/upstream-host-health";
import { MAX_APP_OWNED_MEMORY_BUDGET_MB, MIN_APP_OWNED_MEMORY_BUDGET_MB } from "../lib/app-owned-memory";
import { isMissingPathError } from "./atomic-write";
import { getConfigDir, getConfigPath } from "./paths";
import { getDefaultConfig } from "./proxy-env";
import { salvageConfigCandidate } from "./salvage";
import { projectRemovedOpenCodeFreeSnapshot } from "./removed-opencode-free-backup";
import { sanitizeOpenCodeOverridesForLoad } from "./opencode-wire-upgrade";
import {
  sanitizeReasoningPinsForLoad,
  sanitizeAgyAcpForLoad,
  sanitizeRetryOn429ForLoad,
  sanitizeCapabilityDeclarationsForLoad,
  sanitizeModelCostsForLoad,
  sanitizeCreditPriceForLoad,
  sanitizeAutoReviewForLoad,
  degradedListenerWarnings,
  degradedReasoningRetentionWarning,
  degradedCodexAccountPriorityWarnings,
  degradedCodexQuotaAutoRefreshWarning,
  normalizeApiKeyIds,
  CLAUDE_SUBAGENT_EFFORTS,
  isClaudeSubagentEffort,
  rawClaudeSubagentEffort,
  normalizeClaudeSubagentEffort,
  malformedUpstreamHostCircuitThresholdWarning,
  malformedPlaintextV2AgentMessagesWarning,
  malformedAgentTaskRecoveryWarning,
  malformedRuntimeRoleWarning,
  malformedOptionalRemoteBlockWarning,
  malformedClientConnectionWarning,
  malformedQuotaResetNotifyWarning,
  malformedCatalogAutoRefreshWarning,
  malformedCodexPoolWarning,
  malformedTelemetryWarning,
  malformedSpendWarning,
  rawConfigRecord,
  malformedNativeSubagentFields,
  malformedNativeSubagentFieldWarning,
  malformedCodexAuthMethodWarning,
  malformedCodexAccountPickerWarning,
  nativeSubagentSyncDisabledReason,
  normalizeNativeSubagentSync,
  inheritedFastWireConflictProviderNames,
  inheritedFastWireConflictWarning,
  sanitizeModelDisplayNamesForLoad,
} from "./load-degrade";
import { configSchema } from "./schema/config-schema";
import {
  agentTaskRecoverySchema,
  catalogAutoRefreshSchema,
  clientConnectionSchema,
  CODEX_ACCOUNT_PIN_PATTERN,
  codexAccountPrioritiesSchema,
  codexAccountAutoSwitchThresholdsSchema,
  codexPoolSchema,
  codexQuotaAutoRefreshSchema,
  credentialGroupsSchema,
  hubConfigSchema,
  quotaResetNotifySchema,
  remoteGuiConfigSchema,
  runtimeRoleSchema,
  spendSchema,
  chatgptDesktopSchema,
  chatgptDesktopConfigIssue,
  compactionRoutingSchema,
  reasoningRetentionSchema,
  skillsConfigSchema,
  telemetryConfigSchema,
  memoryModelsSchema,
} from "./schema/leaf-validators";

export type ConfigDiagnostics = {
  config: OcxConfig;
  source: "default" | "file" | "fallback";
  error: string | null;
  /** Non-fatal config concerns; absent when there are no warnings. */
  warnings?: string[];
};

function rawPoolAliasesError(value: unknown): string | undefined {
  const record = rawConfigRecord(value);
  if (!record) return undefined;
  const aliases = record.spendPoolAliases;
  const shapeError = spendPoolAliasesError(aliases);
  if (shapeError) return shapeError;
  const mapping = rawConfigRecord(aliases);
  if (!mapping || Object.keys(mapping).length === 0) return undefined;
  const providers = rawConfigRecord(record.providers ?? {});
  if (!providers) return "providers must be an object to validate spendPoolAliases";
  const targetError = spendPoolAliasesError(aliases, Object.keys(providers));
  if (targetError) return targetError;
  const salt = readExistingSpendSalt(getConfigDir());
  if (!salt) return "spendPoolAliases requires a safely readable existing spend salt";
  return validatePoolAliasOwners(aliases, salt, Object.keys(providers));
}

export type ConfigFileSnapshot = {
  diagnostics: ConfigDiagnostics;
  /** Exact file contents, including a possible BOM, used as the optimistic revision. */
  raw?: string;
};

function configPlaceholderWarnings(config: OcxConfig): string[] {
  const warnings: string[] = [];
  for (const [name, provider] of Object.entries(config.providers)) {
    const placeholder = provider.baseUrl.match(/\{[^}]*\}/)?.[0];
    if (placeholder) {
      warnings.push(`providers.${name}.baseUrl contains unresolved ${placeholder}; set the real provider URL`);
    }
  }
  return warnings;
}

function validFileConfigDiagnostics(config: OcxConfig, rawParsed: unknown, repairs: readonly string[]): ConfigDiagnostics {
  // Unsafe hand-edited optional values are disabled in memory instead of rejecting
  // the entire config, which would hide unrelated providers/accounts. The next
  // ordinary save persists the normalized absence.
  const syncDisabledReason = nativeSubagentSyncDisabledReason(config, rawParsed);
  const rawForce = rawSubagentModelForce(rawParsed);
  const rawEffort = rawClaudeSubagentEffort(rawParsed);
  const normalized = normalizeClaudeSubagentEffort(normalizeNativeSubagentSync(config, rawParsed), rawParsed);
  const warnings = [...repairs, ...configPlaceholderWarnings(normalized)];
  const codexAuthWarning = malformedCodexAuthMethodWarning(rawParsed);
  if (codexAuthWarning) warnings.push(codexAuthWarning);
  if (rawForce !== undefined && !isSubagentModelEntry(rawForce)) warnings.push("claudeCode.subagentModelForce ignored: expected a safe roster-style model id");
  if (normalized.chatgptDesktop?.appServerShim === true && process.platform !== "darwin") {
    warnings.push("chatgptDesktop.appServerShim is experimental and macOS only; ignored on this platform");
  }
  const chatgptDesktopIssue = chatgptDesktopConfigIssue(rawParsed);
  if (chatgptDesktopIssue) warnings.push(`${chatgptDesktopIssue}; the whole chatgptDesktop block is ignored, so the ChatGPT desktop integration reads as off`);
  warnings.push(...inheritedFastWireConflictProviderNames(normalized).map(inheritedFastWireConflictWarning));
  warnings.push(...degradedCodexAccountPriorityWarnings(rawParsed, normalized));
  warnings.push(...degradedListenerWarnings(rawParsed, normalized));
  if (blockedModelRedirectsError(rawParsed)) warnings.push("blockedModelRedirects ignored: expected a map of nonempty model keys to nonempty string targets");
  if (nativeReasoningRetentionConfigError(rawParsed)) warnings.push("nativeReasoningRetention ignored: expected only optional boolean modelSwitch and accountSwitch fields; both remain off");
  if (workflowBudgetConfigError(rawParsed)) warnings.push("workflowBudget ignored: " + WORKFLOW_BUDGET_SHAPE_HINT + "; the built-in ceilings remain");
  if (routedCatalogDefaultsConfigError(rawParsed)) warnings.push("routedCatalogDefaults ignored: " + ROUTED_CATALOG_DEFAULTS_SHAPE_HINT + "; routed catalog rows keep their derived values");
  if (mainAccountHardLockFallbackError(rawParsed)) warnings.push("codexMainAccountHardLockFallback ignored: expected a nonblank model selector and an optional declared reasoningEffort");
  if (fallbackPolicyError(rawParsed)) warnings.push("fallback partly ignored: expected boolean model/provider switches, providers/routes/devices maps of them, and devices.<id>.localFallback; ignored leaves keep today's fallback behavior");
  if (subscriptionReserveConfigError(rawParsed)) warnings.push("subscriptionReserve ignored: invalid weekly reserve policy");
  const quotaAutoRefreshWarning = degradedCodexQuotaAutoRefreshWarning(rawParsed, normalized);
  if (quotaAutoRefreshWarning) warnings.push(quotaAutoRefreshWarning);
  if (rawEffort !== undefined && !isClaudeSubagentEffort(rawEffort)) {
    warnings.push(`claudeCode.subagentEffort ignored: expected one of ${CLAUDE_SUBAGENT_EFFORTS.join(", ")}`);
  }
  warnings.push(...malformedNativeSubagentFields(rawParsed).map(malformedNativeSubagentFieldWarning));
  const pickerWarning = malformedCodexAccountPickerWarning(rawParsed);
  if (pickerWarning) warnings.push(pickerWarning);
  const hostCircuitWarning = malformedUpstreamHostCircuitThresholdWarning(rawParsed);
  if (hostCircuitWarning) warnings.push(hostCircuitWarning);
  const recoveryWarning = malformedAgentTaskRecoveryWarning(rawParsed);
  if (recoveryWarning) warnings.push(recoveryWarning);
  const runtimeRoleWarning = malformedRuntimeRoleWarning(rawParsed);
  if (runtimeRoleWarning) warnings.push(runtimeRoleWarning);
  const hubWarning = malformedOptionalRemoteBlockWarning(rawParsed, "hub");
  if (hubWarning) warnings.push(hubWarning);
  const remoteGuiWarning = malformedOptionalRemoteBlockWarning(rawParsed, "remoteGui");
  if (remoteGuiWarning) warnings.push(remoteGuiWarning);
  const clientWarning = malformedClientConnectionWarning(rawParsed);
  if (clientWarning) warnings.push(clientWarning);
  const notifyWarning = malformedQuotaResetNotifyWarning(rawParsed);
  if (notifyWarning) warnings.push(notifyWarning);
  const catalogRefreshWarning = malformedCatalogAutoRefreshWarning(rawParsed);
  if (catalogRefreshWarning) warnings.push(catalogRefreshWarning);
  const codexPoolWarning = malformedCodexPoolWarning(rawParsed);
  if (codexPoolWarning) warnings.push(codexPoolWarning);
  const telemetryWarning = malformedTelemetryWarning(rawParsed);
  if (telemetryWarning) warnings.push(telemetryWarning);
  const spendWarning = malformedSpendWarning(rawParsed);
  if (spendWarning) warnings.push(spendWarning);
  const retentionWarning = degradedReasoningRetentionWarning(rawParsed, normalized);
  if (retentionWarning) warnings.push(retentionWarning);
  if (rawPoolAliasesError(rawParsed)) {
    warnings.push("spendPoolAliases invalid: configured pool admission is refused until the mapping is corrected");
  }
  const plaintextWarning = malformedPlaintextV2AgentMessagesWarning(rawParsed);
  if (plaintextWarning) warnings.push(plaintextWarning);
  if (syncDisabledReason) {
    warnings.push(`syncCodexSubagentDefaults ignored: ${syncDisabledReason}`);
  }
  return {
    config: normalized,
    source: "file",
    error: anthropicOAuthInstanceConfigError(rawParsed) ?? anthropicAccountPoolConfigError(rawParsed) ?? anthropicSidecarConfigError(rawParsed) ?? null,
    ...(warnings.length > 0 ? { warnings } : {}),
  };
}

export function subagentDefaultSyncEffective(
  config: Pick<OcxConfig, "syncCodexSubagentDefaults" | "injectionModel">,
): boolean {
  return config.syncCodexSubagentDefaults === true && Boolean(config.injectionModel?.trim());
}

export function mergeConfigDefaults(parsed: unknown): unknown {
  if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return parsed;
  const defaults = getDefaultConfig();
  const raw = parsed as Record<string, unknown>;
  // Same absence-is-meaningful pin as the repair merge above.
  const merged: Record<string, unknown> = {
    ...defaults,
    ...raw,
    subagentModelsVersion: raw.subagentModelsVersion,
    multiAgentMode: raw.multiAgentMode,
    multiAgentSurfaceAdvisoryVersion: raw.multiAgentSurfaceAdvisoryVersion,
  };
  if (raw.providers && typeof raw.providers === "object" && defaults.providers) {
    merged.providers = { ...defaults.providers, ...(raw.providers as Record<string, unknown>) };
  }
  return merged;
}

function schemaDiagnosticsError(error: z.ZodError): string {
  const details = error.issues.map(issue => {
    const path = issue.path.map(segment => typeof segment === "string" ? redactSecretString(segment) : segment).join(".") || "config";
    return `${path}: ${redactSecretString(issue.message)}`;
  });
  return details.length > 0 ? `schema_invalid: ${details.join("; ")}` : "schema_invalid";
}

/**
 * Reject a hostname the schema deliberately degrades on read. Load-time has to keep a
 * blank value non-fatal (see the `hostname` field comment), but an incoming write is a
 * live caller who can be told the value is wrong — silently rewriting it to loopback
 * would look like the bind succeeded on the address they asked for.
 */
function blankHostnameError(value: unknown): string | null {
  if (!value || typeof value !== "object" || Array.isArray(value)) return null;
  const hostname = (value as Record<string, unknown>).hostname;
  if (hostname === undefined) return null;
  if (typeof hostname !== "string" || !hostname.trim()) {
    return "schema_invalid: hostname: must be a nonblank bind address";
  }
  return null;
}

function claudeSubagentEffortError(value: unknown): string | null {
  const effort = rawClaudeSubagentEffort(value);
  if (effort === undefined || isClaudeSubagentEffort(effort)) return null;
  return `schema_invalid: claudeCode.subagentEffort: must be one of ${CLAUDE_SUBAGENT_EFFORTS.join(", ")}`;
}

function appOwnedMemoryBudgetError(value: unknown): string | null {
  if (!value || typeof value !== "object" || Array.isArray(value)) return null;
  const budget = (value as Record<string, unknown>).appOwnedMemoryBudgetMb;
  if (budget === undefined) return null;
  if (typeof budget !== "number" || !Number.isInteger(budget)
    || budget < MIN_APP_OWNED_MEMORY_BUDGET_MB || budget > MAX_APP_OWNED_MEMORY_BUDGET_MB) {
    return `schema_invalid: appOwnedMemoryBudgetMb: must be an integer from ${MIN_APP_OWNED_MEMORY_BUDGET_MB} to ${MAX_APP_OWNED_MEMORY_BUDGET_MB}`;
  }
  return null;
}

function upstreamHostCircuitThresholdError(value: unknown): string | null {
  const raw = rawConfigRecord(value);
  if (!raw || !Object.hasOwn(raw, "upstreamHostCircuitThreshold")) return null;
  const threshold = raw.upstreamHostCircuitThreshold;
  if (threshold === undefined) return null;
  if (typeof threshold === "number"
    && Number.isInteger(threshold)
    && threshold >= 0
    && threshold <= UPSTREAM_HOST_CIRCUIT_MAX_THRESHOLD) return null;
  return `schema_invalid: upstreamHostCircuitThreshold: must be an integer from 0 to ${UPSTREAM_HOST_CIRCUIT_MAX_THRESHOLD}`;
}

// The schema degrades an unknown codec to identity so a hand edit cannot break startup; a live write
// or import must instead be refused, or it would report success and then drop the value (#7247).
function upstreamRequestCompressionError(value: unknown): string | null {
  const raw = rawConfigRecord(value);
  if (!raw || !Object.hasOwn(raw, "upstreamRequestCompression")) return null;
  const mode = raw.upstreamRequestCompression;
  if (mode === undefined || mode === "off" || mode === "gzip" || mode === "zstd") return null;
  return "schema_invalid: upstreamRequestCompression: must be \"off\", \"gzip\" or \"zstd\"";
}

function upstreamHistorySlimConfigError(value: unknown): string | null {
  const raw = rawConfigRecord(value);
  if (!raw || !Object.hasOwn(raw, "upstreamHistorySlim")) return null;
  const mode = raw.upstreamHistorySlim;
  if (mode === undefined || mode === "off" || mode === "codex") return null;
  return "schema_invalid: upstreamHistorySlim: must be \"off\" or \"codex\"";
}

function plaintextV2AgentMessagesError(value: unknown): string | null {
  return malformedPlaintextV2AgentMessagesWarning(value)
    ? "schema_invalid: plaintextV2AgentMessages: must be a boolean or omitted"
    : null;
}

function agentTaskRecoveryError(value: unknown): string | null {
  const raw = rawConfigRecord(value);
  if (!raw || !Object.hasOwn(raw, "agentTaskRecovery") || raw.agentTaskRecovery === undefined) return null;
  const result = agentTaskRecoverySchema.safeParse(raw.agentTaskRecovery);
  if (result.success) return null;
  const issue = result.error.issues[0];
  const field = issue?.path.join(".");
  return `schema_invalid: agentTaskRecovery${field ? `.${field}` : ""}: ${issue?.message ?? "invalid configuration"}`;
}

function runtimeRoleError(value: unknown): string | null {
  const raw = rawConfigRecord(value);
  if (!raw || !Object.hasOwn(raw, "runtimeRole") || raw.runtimeRole === undefined) return null;
  if (runtimeRoleSchema.safeParse(raw.runtimeRole).success) return null;
  return 'schema_invalid: runtimeRole: must be one of "standalone", "hub", or "client"';
}

function remoteGuiConfigError(value: unknown): string | null {
  const raw = rawConfigRecord(value);
  if (!raw) return null;
  for (const [key, schema] of [
    ["hub", hubConfigSchema],
    ["remoteGui", remoteGuiConfigSchema],
  ] as const) {
    if (!Object.hasOwn(raw, key) || raw[key] === undefined) continue;
    const result = schema.safeParse(raw[key]);
    if (result.success) continue;
    const issue = result.error.issues[0];
    const field = issue?.path.join(".");
    return `schema_invalid: ${key}${field ? `.${field}` : ""}: ${issue?.message ?? "invalid configuration"}`;
  }
  return null;
}

function clientConnectionConfigError(value: unknown): string | null {
  const raw = rawConfigRecord(value);
  if (!raw || !Object.hasOwn(raw, "client") || raw.client === undefined) return null;
  const result = clientConnectionSchema.safeParse(raw.client);
  if (result.success) return null;
  const issue = result.error.issues[0];
  const field = issue?.path.join(".");
  return `schema_invalid: client${field ? `.${field}` : ""}: ${issue?.message ?? "invalid client connection"}`;
}

function clientRolePairError(value: unknown): string | null {
  const raw = rawConfigRecord(value);
  if (!raw) return null;
  const hasClient = Object.hasOwn(raw, "client") && raw.client !== undefined;
  if (raw.runtimeRole === "client" && !hasClient) {
    return "schema_invalid: runtimeRole client requires a complete client connection";
  }
  if (hasClient && raw.runtimeRole !== "client") {
    return "schema_invalid: client connection requires runtimeRole client";
  }
  return null;
}

function quotaResetNotifyError(value: unknown): string | null {
  const raw = rawConfigRecord(value);
  if (!raw || !Object.hasOwn(raw, "quotaResetNotify") || raw.quotaResetNotify === undefined) return null;
  const result = quotaResetNotifySchema.safeParse(raw.quotaResetNotify);
  if (result.success) return null;
  const issue = result.error.issues[0];
  const field = issue?.path.join(".");
  return `schema_invalid: quotaResetNotify${field ? `.${field}` : ""}: ${issue?.message ?? "invalid configuration"}`;
}

function catalogAutoRefreshError(value: unknown): string | null {
  const raw = rawConfigRecord(value);
  if (!raw || !Object.hasOwn(raw, "catalogAutoRefresh") || raw.catalogAutoRefresh === undefined) return null;
  const result = catalogAutoRefreshSchema.safeParse(raw.catalogAutoRefresh);
  if (result.success) return null;
  const issue = result.error.issues[0];
  const field = issue?.path.join(".");
  return `schema_invalid: catalogAutoRefresh${field ? `.${field}` : ""}: ${issue?.message ?? "invalid configuration"}`;
}

/**
 * The read path degrades a malformed spend section to undefined, which means no ceiling is
 * enforced. Reject it on write so `ocx config set` cannot store a budget that reads back as
 * configured and refuses nothing -- a ceiling that is not enforced looks identical to one
 * nothing has reached.
 */
function spendError(value: unknown): string | null {
  const raw = rawConfigRecord(value);
  if (!raw || !Object.hasOwn(raw, "spend") || raw.spend === undefined) return null;
  const result = spendSchema.safeParse(raw.spend);
  if (result.success) return null;
  const issue = result.error.issues[0];
  const field = issue?.path.join(".");
  return `schema_invalid: spend${field ? `.${field}` : ""}: ${issue?.message ?? "invalid configuration"}`;
}

/**
 * The read path degrades a malformed pool policy to undefined, which for an exclusion policy means
 * the excluded accounts quietly keep serving traffic. Reject it on write so `ocx config set` cannot
 * create a policy that looks applied and is not.
 */
function codexPoolError(value: unknown): string | null {
  const raw = rawConfigRecord(value);
  if (!raw || !Object.hasOwn(raw, "codexPool") || raw.codexPool === undefined) return null;
  const result = codexPoolSchema.safeParse(raw.codexPool);
  if (result.success) return null;
  const issue = result.error.issues[0];
  const field = issue?.path.join(".");
  return `schema_invalid: codexPool${field ? `.${field}` : ""}: ${issue?.message ?? "invalid configuration"}`;
}

/**
 * Same reasoning as {@link blankHostnameError}, and more urgent: the read path degrades a
 * malformed selection-order map to undefined, which on a write would drop every entry the
 * user had accumulated and still report success. A load-time degrade leaves the raw map in
 * the file to be repaired by hand; a degraded write erases it. One bad `ocx config set`
 * must not cost the whole map, so a live caller is told instead.
 */
function codexAccountPrioritiesError(value: unknown): string | null {
  const raw = rawConfigRecord(value);
  if (!raw) return null;
  if (raw.codexAccountPriorities !== undefined) {
    const parsed = codexAccountPrioritiesSchema.safeParse(raw.codexAccountPriorities);
    if (!parsed.success) {
      return schemaDiagnosticsError(parsed.error).replace("schema_invalid: ", "schema_invalid: codexAccountPriorities.");
    }
  }
  if (raw.codexAccountAutoSwitchThresholds !== undefined) {
    const parsed = codexAccountAutoSwitchThresholdsSchema.safeParse(raw.codexAccountAutoSwitchThresholds);
    if (!parsed.success) {
      return schemaDiagnosticsError(parsed.error)
        .replace("schema_invalid: ", "schema_invalid: codexAccountAutoSwitchThresholds.");
    }
  }
  // Tested as a string rather than coerced: `String(123)` matches the id pattern, so a
  // coercing guard waves a non-string pin through to the schema, where `.catch(undefined)`
  // drops it and reports the write as a success — the exact silent-degrade this guards.
  const pin = raw.activeCodexAccountPinned;
  if (pin !== undefined && (typeof pin !== "string" || !CODEX_ACCOUNT_PIN_PATTERN.test(pin))) {
    return "schema_invalid: activeCodexAccountPinned: must be an account id";
  }
  return null;
}

function codexAccountSelectionPreferencesError(value: unknown): string | null {
  const raw = rawConfigRecord(value);
  if (!raw) return null;
  for (const key of ["codexAccountPriorityFailback", "codexPreserveSignedInAccount"]) {
    if (raw[key] !== undefined && typeof raw[key] !== "boolean") {
      return `schema_invalid: ${key}: must be a boolean or omitted`;
    }
  }
  return null;
}

/**
 * Same reasoning as {@link codexAccountPrioritiesError}, plus one of its own. The read
 * path drops an invalid grouping, so a degraded write would erase a declaration the
 * operator is still editing and still report success. And an ambiguous declaration --
 * one id used twice, one credential in two groups -- has no safe silent answer at all:
 * resolving it by list order would quietly merge two quota domains. A live caller is
 * told which group is the problem instead.
 */
export function poolCredentialGroupsError(value: unknown): string | null {
  const pool = rawConfigRecord(rawConfigRecord(value)?.pool);
  if (!pool || pool.credentialGroups === undefined) return null;
  const parsed = credentialGroupsSchema.safeParse(pool.credentialGroups);
  if (parsed.success) return null;
  const details = parsed.error.issues.map(issue => {
    const path = issue.path.join(".");
    return path ? `${path}: ${issue.message}` : issue.message;
  }).join("; ");
  return `schema_invalid: pool.credentialGroups: ${details}`;
}

function codexQuotaAutoRefreshError(value: unknown): string | null {
  const raw = rawConfigRecord(value);
  if (!raw || raw.codexQuotaAutoRefresh === undefined) return null;
  const parsed = codexQuotaAutoRefreshSchema.safeParse(raw.codexQuotaAutoRefresh);
  if (parsed.success) return null;
  const details = parsed.error.issues.map(issue => {
    const path = issue.path.join(".");
    const message = path === ""
      ? issue.message.replace(/^codexQuotaAutoRefresh\s*/, "")
      : issue.message;
    return `codexQuotaAutoRefresh${path ? `.${path}` : ""}: ${message}`;
  });
  return `schema_invalid: ${details.join("; ")}`;
}

function googleAntigravityStaticCatalogVersionError(value: unknown): string | null {
  const raw = rawConfigRecord(value);
  if (!raw || !Object.hasOwn(raw, "googleAntigravityStaticCatalogVersion")) return null;
  const version = raw.googleAntigravityStaticCatalogVersion;
  if (version === undefined || version === 1 || version === 2) return null;
  return "schema_invalid: googleAntigravityStaticCatalogVersion: must be 1, 2, or omitted";
}

function codexAccountPickerEnabledError(value: unknown): string | null {
  const raw = rawConfigRecord(value);
  if (!raw) return null;
  const descriptor = Object.getOwnPropertyDescriptor(raw, "codexAccountPickerEnabled");
  if (!descriptor) {
    return "codexAccountPickerEnabled" in raw
      ? "schema_invalid: codexAccountPickerEnabled: must be an own boolean data property or omitted"
      : null;
  }
  if (!("value" in descriptor)) {
    return "schema_invalid: codexAccountPickerEnabled: must be an own boolean data property or omitted";
  }
  const enabled = descriptor.value;
  if (enabled === undefined || typeof enabled === "boolean") return null;
  return "schema_invalid: codexAccountPickerEnabled: must be a boolean or omitted";
}

function emptyCompletionRetryError(value: unknown): string | null {
  const raw = rawConfigRecord(value);
  if (!raw || !Object.hasOwn(raw, "emptyCompletionRetry")) return null;
  const enabled = raw.emptyCompletionRetry;
  if (enabled === undefined || typeof enabled === "boolean") return null;
  return "schema_invalid: emptyCompletionRetry: must be a boolean or omitted";
}

function dropCodexSafetyBufferingError(value: unknown): string | null {
  const raw = rawConfigRecord(value);
  if (!raw || !Object.hasOwn(raw, "dropCodexSafetyBuffering")) return null;
  const enabled = raw.dropCodexSafetyBuffering;
  if (enabled === undefined || typeof enabled === "boolean") return null;
  return "schema_invalid: dropCodexSafetyBuffering: must be a boolean or omitted";
}

function showCodexCreditsError(value: unknown): string | null {
  const raw = rawConfigRecord(value);
  if (!raw || !Object.hasOwn(raw, "showCodexCredits")) return null;
  const enabled = raw.showCodexCredits;
  if (enabled === undefined || typeof enabled === "boolean") return null;
  return "schema_invalid: showCodexCredits: must be a boolean or omitted";
}

function creditCodexAccountIdsError(value: unknown): string | null {
  const raw = rawConfigRecord(value);
  if (!raw || !Object.hasOwn(raw, "creditCodexAccountIds")) return null;
  const ids = raw.creditCodexAccountIds;
  if (ids === undefined) return null;
  if (Array.isArray(ids) && ids.every(id => typeof id === "string" && /^[a-zA-Z0-9._-]{1,64}$/.test(id))) return null;
  return "schema_invalid: creditCodexAccountIds: must be an array of account ids or omitted";
}

function remainingQuotaAccountIdsError(value: unknown): string | null {
  const ids = rawConfigRecord(value)?.codexUseRemainingQuotaAccountIds;
  return ids === undefined || validRemainingQuotaAccountIds(ids) ? null
    : "schema_invalid: codexUseRemainingQuotaAccountIds: must be an array of Codex account ids or omitted";
}

function oauthOpenBrowserError(value: unknown): string | null {
  const raw = rawConfigRecord(value);
  if (!raw || !Object.hasOwn(raw, "oauthOpenBrowser")) return null;
  const enabled = raw.oauthOpenBrowser;
  if (enabled === undefined || typeof enabled === "boolean") return null;
  return "schema_invalid: oauthOpenBrowser: must be a boolean or omitted";
}

function codexAuthMethodError(value: unknown): string | null {
  return malformedCodexAuthMethodWarning(value)
    ? 'schema_invalid: codexAuthMethod: must be "auto", "device-only", or omitted'
    : null;
}

/** Validate an in-memory config candidate without touching disk. Used by headless CLI import/set. */
/**
 * Reject a loopback-listener port that collides with the proxy port (#1102), and a port-less
 * companion listener on a bind address that already owns 127.0.0.1 (#4236).
 *
 * The schema can only check the shape of each field on its own; the two ports being distinct —
 * and the port-less form being compatible with `hostname` — are relationships between fields.
 * Letting either through would surface as a startup failure after the public listener already
 * bound, which reads like an unrelated port conflict.
 *
 * Both keys are read from the same candidate, so `ocx config set hostname 127.0.0.1` on a host
 * whose listener is already the companion form is refused by this same check, with the same
 * message, rather than breaking the next start.
 *
 * This is write-time only, matching `blankHostnameError`: a live caller can be told the value
 * is wrong, whereas a hand-edited config on the read path degrades to undefined rather than
 * resetting the whole file. `assertLoopbackListenerBindable` repeats the decision at startup so
 * a hand edit that skipped this boundary fails with the same sentence instead of EADDRINUSE.
 */
function loopbackListenerPortError(value: unknown): string | null {
  if (!value || typeof value !== "object" || Array.isArray(value)) return null;
  const listener = (value as Record<string, unknown>).unauthenticatedLoopbackListener;
  if (listener === undefined) return null;
  if (!listener || typeof listener !== "object" || Array.isArray(listener)) {
    return "schema_invalid: unauthenticatedLoopbackListener: must be an object or omitted";
  }
  const entry = listener as Record<string, unknown>;
  // `enabled` must be a real boolean. The schema's `.catch(undefined)` would otherwise DELETE
  // a `"true"` string entry and report success, leaving an operator convinced they enabled an
  // unauthenticated listener that is in fact off. Load-time still degrades quietly — a hand
  // edit must not reset the file — but a live caller gets told.
  if (typeof entry.enabled !== "boolean") {
    return "schema_invalid: unauthenticatedLoopbackListener.enabled: must be a boolean";
  }
  if (entry.enabled !== true) return null;
  const hostname = typeof (value as Record<string, unknown>).hostname === "string"
    ? (value as Record<string, unknown>).hostname as string
    : undefined;
  const proxyPort = (value as Record<string, unknown>).port;
  const listenerPort = entry.port;
  // The companion form. `port` omitted means "same port as the public listener, on 127.0.0.1",
  // which only exists as a free address when the public listener is bound somewhere else.
  if (listenerPort === undefined) {
    return loopbackCompanionBindError(
      hostname,
      typeof proxyPort === "number" ? proxyPort : 10100,
    );
  }
  if (typeof listenerPort !== "number" || !Number.isInteger(listenerPort) || listenerPort < 1 || listenerPort > 65535) {
    return "schema_invalid: unauthenticatedLoopbackListener.port: must be an integer port when enabled, or omitted to share the proxy port";
  }
  if (typeof proxyPort === "number" && proxyPort === listenerPort) {
    return "schema_invalid: unauthenticatedLoopbackListener.port: must differ from the proxy port";
  }
  return null;
}

/**
 * The one sentence both the write boundary and startup use for an impossible companion bind.
 *
 * Exported so `startServer` can fail with the identical text: an operator who hand-edited the
 * file past `validateConfigCandidate` must read the same diagnosis, not EADDRINUSE.
 */
export function loopbackCompanionBindError(
  hostname: string | undefined,
  proxyPort: number,
): string | null {
  if (loopbackCompanionAllowed(hostname)) return null;
  const bind = (hostname ?? "").trim() || "127.0.0.1";
  return "schema_invalid: unauthenticatedLoopbackListener: a port-less listener binds "
    + `127.0.0.1:${proxyPort}, which the public listener on hostname "${bind}" already holds. `
    + "Either set a distinct unauthenticatedLoopbackListener.port, or remove the listener — a "
    + "loopback bind already admits local callers without a credential.";
}

/** #8338: the persisted schema drops a malformed trusted-proxy block; a live write gets the reason. */
function dashboardTrustedProxyConfigError(value: unknown): string | null {
  const raw = rawConfigRecord(value);
  if (!raw || !Object.hasOwn(raw, "dashboardTrustedProxy") || raw.dashboardTrustedProxy === undefined) return null;
  const parsed = parseDashboardTrustedProxy(raw.dashboardTrustedProxy);
  return typeof parsed === "string" ? `schema_invalid: dashboardTrustedProxy: ${parsed}` : null;
}

/**
 * #7705: load drops a hand-edited template that does not validate; a live write that carries one
 * (a provider-wide save, `ocx config set`) gets the same reason the alias-template route gives.
 */
function providerAliasTemplateConfigError(value: unknown): string | null {
  const providers = rawConfigRecord(rawConfigRecord(value)?.providers);
  if (!providers) return null;
  for (const [name, provider] of Object.entries(providers)) {
    const template = rawConfigRecord(provider)?.aliasTemplate;
    if (template === undefined) continue;
    const problem = typeof template === "string" ? aliasTemplateError(template) : "template must be a string";
    if (problem) return `schema_invalid: providers.${name}.aliasTemplate: ${problem}`;
  }
  return null;
}

/**
 * Validate the hub management ingress at the live-write boundary.
 *
 * The persisted schema intentionally degrades a malformed hand edit to disabled so a typo in
 * this opt-in listener cannot discard providers or credentials. A live config mutation must not
 * get that leniency: it receives an exact field error before the degrading schema is applied.
 */
function managementIngressConfigError(value: unknown): string | null {
  const raw = rawConfigRecord(value);
  if (!raw) return null;
  const hub = rawConfigRecord(raw.hub);
  if (!hub || !Object.hasOwn(hub, "managementIngress") || hub.managementIngress === undefined) return null;
  const ingress = rawConfigRecord(hub.managementIngress);
  if (!ingress) {
    return "schema_invalid: hub.managementIngress: must be an object or omitted";
  }
  if (typeof ingress.enabled !== "boolean") {
    return "schema_invalid: hub.managementIngress.enabled: must be a boolean";
  }
  const keys = Object.keys(ingress);
  if (ingress.enabled === false) {
    return keys.length === 1
      ? null
      : "schema_invalid: hub.managementIngress: disabled ingress accepts only enabled";
  }
  if (keys.some(key => key !== "enabled" && key !== "port")) {
    return "schema_invalid: hub.managementIngress: contains an unsupported field";
  }
  const ingressPort = ingress.port;
  if (typeof ingressPort !== "number" || !Number.isInteger(ingressPort) || ingressPort < 1 || ingressPort > 65535) {
    return "schema_invalid: hub.managementIngress.port: must be an integer port when enabled";
  }
  if (raw.runtimeRole !== "hub") {
    return "schema_invalid: hub.managementIngress: enabled ingress requires runtimeRole hub";
  }
  const proxyPort = typeof raw.port === "number" ? raw.port : 10100;
  if (proxyPort === ingressPort) {
    return "schema_invalid: hub.managementIngress.port: must differ from the proxy port";
  }
  const loopback = rawConfigRecord(raw.unauthenticatedLoopbackListener);
  if (loopback?.enabled === true && loopback.port === ingressPort) {
    return "schema_invalid: hub.managementIngress.port: must differ from unauthenticatedLoopbackListener.port";
  }
  return null;
}

/** Load degrades malformed metrics export config to off; live writes reject the same shape. */
export function metricsExportConfigError(value: unknown): string | null {
  const raw = rawConfigRecord(value);
  if (!raw || !Object.hasOwn(raw, "metricsExport") || raw.metricsExport === undefined) return null;
  const metricsExport = rawConfigRecord(raw.metricsExport);
  if (!metricsExport) return "schema_invalid: metricsExport: must be an object or omitted";
  if (Object.keys(metricsExport).some(key => key !== "enabled")) {
    return "schema_invalid: metricsExport: contains an unsupported field";
  }
  if (metricsExport.enabled !== undefined && typeof metricsExport.enabled !== "boolean") {
    return "schema_invalid: metricsExport.enabled: must be a boolean";
  }
  return null;
}

/** Load degrades a malformed service health recovery section to off; live writes reject it. */
export function serviceHealthRecoveryConfigError(value: unknown): string | null {
  const raw = rawConfigRecord(value);
  if (!raw || !Object.hasOwn(raw, "serviceHealthRecovery") || raw.serviceHealthRecovery === undefined) return null;
  const section = rawConfigRecord(raw.serviceHealthRecovery);
  if (!section) return "schema_invalid: serviceHealthRecovery: must be an object or omitted";
  if (Object.keys(section).some(key => key !== "enabled")) {
    return "schema_invalid: serviceHealthRecovery: contains an unsupported field";
  }
  if (section.enabled !== undefined && typeof section.enabled !== "boolean") {
    return "schema_invalid: serviceHealthRecovery.enabled: must be a boolean";
  }
  return null;
}


function skillsConfigError(value: unknown): string | null {
  const raw = rawConfigRecord(value);
  if (!raw || !Object.hasOwn(raw, "skills") || raw.skills === undefined) return null;
  const result = skillsConfigSchema.safeParse(raw.skills);
  if (result.success) return null;
  const issue = result.error.issues[0];
  const field = issue?.path.join(".");
  return "schema_invalid: skills" + (field ? "." + field : "") + ": " + (issue?.message ?? "invalid configuration");
}

export function telemetryConfigError(value: unknown): string | null {
  const raw = rawConfigRecord(value);
  if (!raw || !Object.hasOwn(raw, "telemetry") || raw.telemetry === undefined) return null;
  const result = telemetryConfigSchema.safeParse(raw.telemetry);
  if (result.success) return null;
  const issue = result.error.issues[0];
  const field = issue?.path.join(".");
  return "schema_invalid: telemetry" + (field ? "." + field : "") + ": " + (issue?.message ?? "invalid configuration");
}

export function validateConfigCandidate(value: unknown): { ok: true; config: OcxConfig } | { ok: false; error: string } {
  const chatgptDesktop = rawConfigRecord(value)?.chatgptDesktop;
  if (chatgptDesktop !== undefined && !chatgptDesktopSchema.safeParse(chatgptDesktop).success) {
    return { ok: false, error: "schema_invalid: chatgptDesktop: requires an optional boolean appServerShim and no other fields" };
  }
  const compactionRouting = rawConfigRecord(value)?.compactionRouting;
  const reasoningRetention = rawConfigRecord(value)?.reasoningRetention;
  if (reasoningRetention !== undefined && !reasoningRetentionSchema.safeParse(reasoningRetention).success) {
    return { ok: false, error: "schema_invalid: reasoningRetention: requires optional boolean enabled, maxContextPercent greater than 0 and at most 100 and/or positive integer maxTokens, with no other fields" };
  }
  if (compactionRouting !== undefined && !compactionRoutingSchema.safeParse(compactionRouting).success) {
    return { ok: false, error: "schema_invalid: compactionRouting: requires a nonblank model, an optional valid reasoningEffort, and optional non-repeating triggers drawn from \"manual\" and \"auto\"" };
  }
  const memoryModels = rawConfigRecord(value)?.memoryModels;
  if (memoryModels !== undefined && !memoryModelsSchema.safeParse(memoryModels).success) {
    return { ok: false, error: "schema_invalid: memoryModels: requires a nonblank model and an optional declared reasoningEffort per configured phase, and no other fields" };
  }
  const protocols = rawConfigRecord(value)?.protocols;
  if (protocols !== undefined && !protocolConfigSchema.safeParse(protocols).success) {
    return { ok: false, error: "schema_invalid: protocols: expected valid protocol policy and boolean rollout flags" };
  }
  const anthropicError = anthropicOAuthInstanceConfigError(value) ?? anthropicAccountPoolConfigError(value) ?? anthropicSidecarConfigError(value);
  if (anthropicError) return { ok: false, error: anthropicError };
  const boundaryError = blockedModelRedirectsError(value)
    // OCX-11: the read schema degrades a malformed fallback leaf to absent, which would silently
    // drop a refusal on the next whole-config save; the write boundary rejects it instead.
    ?? fallbackPolicyError(value)
    ?? subscriptionReserveConfigError(value)
    ?? nativeReasoningRetentionConfigError(value)
    ?? workflowBudgetConfigError(value)
    ?? routedCatalogDefaultsConfigError(value)
    ?? mainAccountHardLockFallbackError(value)
    ?? compactionRecoveryConfigError(value) ?? desktopCompatibilityConfigError(value) ?? configReasoningPinsConfigError(value)
    ?? blankHostnameError(value)
    ?? (rawSubagentModelForce(value) !== undefined && !isSubagentModelEntry(rawSubagentModelForce(value)) ? "schema_invalid: claudeCode.subagentModelForce: expected a safe roster-style model id" : null)
    ?? claudeSubagentEffortError(value)
    ?? appOwnedMemoryBudgetError(value)
    ?? upstreamHostCircuitThresholdError(value)
    ?? upstreamRequestCompressionError(value)
    ?? upstreamHistorySlimConfigError(value)
    ?? plaintextV2AgentMessagesError(value)
    ?? agentTaskRecoveryError(value)
    ?? quotaResetNotifyError(value)
    ?? catalogAutoRefreshError(value)
    ?? (rawPoolAliasesError(value) ? "schema_invalid: spendPoolAliases: invalid pool identity mapping" : null)
    ?? spendError(value)
    ?? codexPoolError(value)
    ?? googleAntigravityStaticCatalogVersionError(value)
    ?? codexAccountPrioritiesError(value)
    ?? codexAccountSelectionPreferencesError(value)
    ?? poolCredentialGroupsError(value)
    ?? codexQuotaAutoRefreshError(value)
    ?? codexAccountPickerEnabledError(value)
    ?? emptyCompletionRetryError(value)
    ?? dropCodexSafetyBufferingError(value)
    ?? oauthOpenBrowserError(value)
    ?? codexAuthMethodError(value)
    ?? showCodexCreditsError(value)
    ?? creditCodexAccountIdsError(value)
    ?? remainingQuotaAccountIdsError(value)
    ?? runtimeRoleError(value)
    ?? remoteGuiConfigError(value)
    ?? clientConnectionConfigError(value)
    ?? clientRolePairError(value)
    ?? loopbackListenerPortError(value)
    ?? managementIngressConfigError(value)
    ?? providerAliasTemplateConfigError(value)
    ?? dashboardTrustedProxyConfigError(value)
    ?? metricsExportConfigError(value)
    ?? serviceHealthRecoveryConfigError(value)
    ?? telemetryConfigError(value)
    ?? skillsConfigError(value);
  if (boundaryError) return { ok: false, error: boundaryError };
  const result = configSchema.safeParse(value);
  if (result.success) {
    const config = normalizeApiKeyIds(result.data as OcxConfig);
    return { ok: true, config };
  }
  return { ok: false, error: schemaDiagnosticsError(result.error) };
}

export function configDiagnosticsFromRaw(raw: string, options: { warn?: (message: string) => void } = {}): ConfigDiagnostics {
  return configDiagnosticsFromText(raw, undefined, options.warn);
}

function configDiagnosticsFromText(raw: string, file?: { path: string; bytes: Uint8Array }, warn?: (message: string) => void): ConfigDiagnostics {
  try {
    const repairs: string[] = [];
    const reportAgyRepair = (message: string): void => {
      repairs.push(message);
      (warn ?? console.warn)(`⚠️  config.json ${message}`);
    };
    const parsed = JSON.parse(raw.replace(/^\uFEFF/, ""));
    projectRemovedOpenCodeFreeSnapshot(parsed, file);
    sanitizeOpenCodeOverridesForLoad(parsed);
    sanitizeReasoningPinsForLoad(parsed, warn);
    // Same degradation as loadConfig: a hand-edited invalid retryOn429 must not trip the
    // schema and send the caller a default-config fallback (the config command could then
    // persist that fallback over the user's providers/keys).
    sanitizeModelDisplayNamesForLoad(parsed, warn);
    sanitizeAutoReviewForLoad(parsed, warn);
    sanitizeRetryOn429ForLoad(parsed, warn);
    sanitizeAgyAcpForLoad(parsed, reportAgyRepair);
    sanitizeModelCostsForLoad(parsed, warn);
    sanitizeCreditPriceForLoad(parsed, message => {
      repairs.push(message);
      (warn ?? console.warn)(message);
    });
    sanitizeCapabilityDeclarationsForLoad(parsed, warn);
    const result = configSchema.safeParse(parsed);
    if (result.success) {
      return validFileConfigDiagnostics(normalizeApiKeyIds(result.data as OcxConfig), parsed, repairs);
    }

    const merged = mergeConfigDefaults(parsed);
    sanitizeAgyAcpForLoad(merged, reportAgyRepair);
    const retryResult = configSchema.safeParse(merged);
    if (retryResult.success) {
      return validFileConfigDiagnostics(normalizeApiKeyIds(retryResult.data as OcxConfig), parsed, repairs);
    }

    // #1785: one invalid routing profile must not make diagnostics report the built-in
    // defaults AS the config, because a later config write persists those defaults over the
    // operator's providers, keys and prices.
    //
    // The failure is still reported. `source` stays "fallback" and `error` keeps the real
    // schema message -- diagnostics is the surface that tells callers the file is invalid,
    // and every consumer that must refuse an invalid config (provider reload, catalog sync,
    // cost reconcile, codex admission) gates on exactly those two fields. Only `config`
    // changes: it carries the salvaged document instead of factory defaults, so a caller
    // that ignores the error and writes it back preserves what the operator configured.
    const salvaged = salvageConfigCandidate(merged, retryResult.error);
    if (salvaged) {
      const config = normalizeApiKeyIds(salvaged.parsed);
      const warnings = [...repairs, ...degradedListenerWarnings(parsed, config)];
      const chatgptDesktopIssue = chatgptDesktopConfigIssue(parsed);
      if (chatgptDesktopIssue) warnings.push(`${chatgptDesktopIssue}; the whole chatgptDesktop block is ignored, so the ChatGPT desktop integration reads as off`);
      return {
        config,
        source: "fallback",
        error: schemaDiagnosticsError(result.error),
        ...(warnings.length > 0 ? { warnings } : {}),
      };
    }

    return {
      config: getDefaultConfig(), source: "fallback", error: schemaDiagnosticsError(result.error),
      ...(repairs.length > 0 ? { warnings: repairs } : {}),
    };
  } catch {
    return { config: getDefaultConfig(), source: "fallback", error: "invalid_json" };
  }
}

export function readConfigFileSnapshot(options: { passive?: boolean } = {}): ConfigFileSnapshot {
  try {
    const path = getConfigPath();
    const bytes = readFileSync(path);
    const raw = bytes.toString("utf-8");
    return { diagnostics: configDiagnosticsFromText(raw, options.passive ? undefined : { path, bytes }), raw };
  } catch (error) {
    if (isMissingPathError(error)) {
      return {
        diagnostics: { config: getDefaultConfig(), source: "default", error: null },
      };
    }
    return {
      diagnostics: { config: getDefaultConfig(), source: "fallback", error: "invalid_json" },
    };
  }
}

/** Passive observations project retired providers without publishing recovery backups. */
export function readConfigDiagnostics(options: { passive?: boolean } = {}): ConfigDiagnostics {
  return readConfigFileSnapshot(options).diagnostics;
}

/** Read-only init preflight. Occupied unsafe entries are never treated as absence. */
export function observeInitialConfigState(): "missing" | "exists" | "invalid" {
  try {
    if (!lstatSync(getConfigPath()).isFile()) return "invalid";
  } catch (error) {
    return isMissingPathError(error) ? "missing" : "invalid";
  }
  return readConfigFileSnapshot().diagnostics.source === "file" ? "exists" : "invalid";
}

/**
 * The persisted config, plus a digest of the EXACT bytes it was parsed from.
 *
 * A union rather than a nullable digest, because `{ kind: "read" }` with no
 * digest is a state that cannot occur — and a state that cannot occur should
 * not be a state that can be written down. Refusing it at runtime is a check
 * somebody eventually forgets; making it unrepresentable is not.
 *
 * Why a byte digest at all: the Codex write lock compares an authority snapshot
 * taken before the lock against one taken while holding it, and its config
 * component used to hash the PARSED object. Two files that differ only in
 * whitespace or key order parse identically, so a non-cooperating writer could
 * rewrite the file between admission and commit and the comparison would see
 * nothing. Hashing what was actually read closes that.
 *
 * `readConfigFileSnapshot` stays private on purpose. Its `raw` carries provider
 * API keys and admission tokens, and `privacy:scan` reads tracked source text,
 * not runtime values — so it would not catch a caller that logged or serialized
 * that string. The digest travels; the bytes do not.
 */
export type ConfigAdmissionSnapshot =
  | Readonly<{ kind: "read"; diagnostics: ConfigDiagnostics; contentSha256: string }>
  | Readonly<{ kind: "unreadable"; diagnostics: ConfigDiagnostics; contentSha256: null }>;

export function readConfigAdmissionSnapshot(): ConfigAdmissionSnapshot {
  const path = getConfigPath();
  let bytes: Buffer;
  try {
    // ONE read. Hashing the file and then reading it again to parse would leave
    // a window for the two to disagree, which is the exact hazard this exists
    // to detect — the check would become a second chance to be wrong.
    bytes = readFileSync(path);
  } catch (error) {
    return {
      kind: "unreadable",
      diagnostics: isMissingPathError(error)
        ? { config: getDefaultConfig(), source: "default", error: null }
        : { config: getDefaultConfig(), source: "fallback", error: "invalid_json" },
      contentSha256: null,
    };
  }
  return {
    kind: "read",
    // Decoded from the same buffer that was hashed, not re-read from disk.
    diagnostics: configDiagnosticsFromText(bytes.toString("utf-8"), { path, bytes }),
    contentSha256: createHash("sha256").update(bytes).digest("hex"),
  };
}
