/**
 * Fail-closed protection for the user's REAL OpenCodex home while tests run.
 *
 * A management-route unit test once passed an in-memory fixture config to a handler
 * that persisted it through the process-global writer, replacing a live 41KB,
 * ten-provider `~/.opencodex/config.json` with an 874-byte fixture on a real machine.
 * Credentials survived only because the store files are separate; the providers were
 * recoverable only because an unrelated backup snapshot happened to exist.
 * (devlog `_plan/260730_codex_rs_upstream_v2_live_handoff/070`.)
 *
 * Two properties matter more than breadth here:
 *
 * 1. It must be INERT in production. Guessing "am I a test?" from ecosystem variables
 *    like NODE_ENV would brick `NODE_ENV=test ocx ...` for a user who did nothing
 *    wrong — worse than the bug it prevents. Arming requires OCX_TEST_HOME_GUARD=1,
 *    which this repository's test preload sets, or a process whose entry module is a
 *    Bun test file (see {@link isBunTestFileProcess}); no production entrypoint is one.
 * 2. It must fail CLOSED for code nobody has written yet. So it denies ONE path — the
 *    captured production home — instead of allow-listing known-good test directories.
 *    An allowlist would have to be opted into, and the test that forgets is exactly
 *    how this incident happened.
 */
import { homedir } from "node:os";
import { basename, dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
import { realpathSync } from "node:fs";
import { fileURLToPath } from "node:url";

const GUARD_ENV = "OCX_TEST_HOME_GUARD";
/**
 * Set by `scripts/test.ts` to the ORIGINAL home before it hands the child a rewritten
 * HOME. On that path `homedir()` already points at the sandbox by the time this module
 * loads, so the true home is only knowable from this hand-off.
 */
const REAL_HOME_ENV = "OCX_REAL_HOME";
/** Set by `scripts/test.ts` to the developer's own Claude config directory before it sandboxes one. */
const REAL_CLAUDE_CONFIG_DIR_ENV = "OCX_REAL_CLAUDE_CONFIG_DIR";

/**
 * Resolve symlinks so two spellings of one location compare equal — macOS hands out
 * `/var/folders/...` whose realpath is `/private/var/folders/...` — and so a path that
 * merely *points* at the protected home cannot slip past a string comparison. A path
 * that does not exist yet canonicalizes through its nearest existing ancestor, which is
 * the common case for a config file about to be created.
 */
function canonicalize(path: string): string {
  let current = resolve(path);
  const unresolved: string[] = [];
  for (;;) {
    try {
      return join(realpathSync.native(current), ...unresolved.reverse());
    } catch {
      const parent = dirname(current);
      if (parent === current) return resolve(path);
      unresolved.push(current.slice(parent.length + 1));
      current = parent;
    }
  }
}

/**
 * Captured ONCE at module load, before any harness replaces HOME/USERPROFILE. Reading
 * `homedir()` later would return the sandbox and leave the real home unprotected — the
 * guard would be perfectly inverted while its tests still looked green.
 */
const REAL_HOME = process.env[REAL_HOME_ENV]?.trim() || homedir();
const PROTECTED_HOME = canonicalize(join(REAL_HOME, ".opencodex"));
const PROTECTED_CODEX_HOME = canonicalize(join(REAL_HOME, ".codex"));
/**
 * The developer's Claude config directory: the default `<real home>/.claude`, plus their own
 * `CLAUDE_CONFIG_DIR` when they set one. `scripts/test.ts` hands the original over as
 * `OCX_REAL_CLAUDE_CONFIG_DIR` because its child already starts with a sandboxed
 * `CLAUDE_CONFIG_DIR`; a bare run imports this module before the preload rewrites the
 * environment, so `CLAUDE_CONFIG_DIR` still holds the developer's value here.
 *
 * Claude agent sync prunes generated `agents/ocx-*.md`, and a bare `bun test` once did that
 * to a live directory: Bun's `os.homedir()` ignores a HOME rewritten after startup (#6775).
 */
const REAL_CLAUDE_CONFIG_DIRS = [...new Set([
  join(REAL_HOME, ".claude"),
  process.env[REAL_CLAUDE_CONFIG_DIR_ENV]?.trim() || process.env.CLAUDE_CONFIG_DIR?.trim() || join(REAL_HOME, ".claude"),
])];
const PROTECTED_CLAUDE_TREES = REAL_CLAUDE_CONFIG_DIRS.map(path => ({
  path: canonicalize(path),
  lexical: resolve(path),
  label: "the real Claude config directory",
}));
/**
 * `~/Library/LaunchAgents` needs its own entry because HOME isolation does not reach it:
 * `os.homedir()` reads the password database, not `$HOME`, so a macOS test that rewrites
 * HOME still resolves `plistPath()` to the developer's real LaunchAgents directory. The
 * launchd install tests were doing exactly that — replacing the live
 * `com.opencodex.proxy.plist` with one whose token file, log path and Bun paths all point
 * into a temp sandbox, for as long as the case ran. launchd holds its own parsed copy, so
 * nothing broke until the job next restarted.
 */
const PROTECTED_LAUNCH_AGENTS = canonicalize(join(REAL_HOME, "Library", "LaunchAgents"));

/** The production home this process protects. Exported for the guard's own tests. */
export function protectedHomeForTests(): string {
  return PROTECTED_HOME;
}

/** The production Codex home this process protects when tests write native credentials. */
export function protectedCodexHomeForTests(): string {
  return PROTECTED_CODEX_HOME;
}

/** The Claude config directories this process protects. Exported for the guard's own tests. */
export function protectedClaudeConfigDirsForTests(): readonly string[] {
  return PROTECTED_CLAUDE_TREES.map(tree => tree.path);
}

/**
 * The file names Bun's test runner discovers: `.test`, `_test`, `.spec` or `_spec` before a
 * JS/TS extension. Under `bun test`, `Bun.main` names the test file being evaluated, in the
 * main runner and in `--parallel` workers alike. Every production entrypoint — the CLI, the
 * service daemon, the compiled sidecar (`/$bunfs/...`), a release script — has a different name.
 */
const BUN_TEST_FILE = /[._](?:test|spec)\.[cm]?[jt]sx?$/i;

/**
 * Whether this process runs a Bun test file as its entry module.
 *
 * This exists for the run that never loads `tests/preload.ts`. Bun resolves `bunfig.toml` from
 * the CURRENT WORKING DIRECTORY, so `cd /tmp && bun test <repo>/tests/x.test.ts` skips the
 * preload: HOME stays real, OPENCODEX_HOME stays unset, and before this check the guard stayed
 * down, so an OAuth save landed in the developer's real `~/.opencodex/auth.json` (#7407).
 * Bun exposes no runner flag, and NODE_ENV=test is both settable by users and overridable by the
 * runner's caller, so the entry file's name is the one signal that production never carries.
 *
 * A file passed by explicit path under a non-test name (`bun test ./scratch.ts`) is not
 * recognised; every repository suite is a `*.test.ts`, the only name `tests/test-layout.test.ts` admits.
 *
 * The converse also holds: `bun run ./something.test.ts` arms, because nothing distinguishes it
 * from the runner. That is accepted. Requiring NODE_ENV=test as well would exempt every developer
 * whose shell exports another NODE_ENV (`bun test` keeps an existing value), reopening #7407;
 * the cost of the false positive is a refused real-home write from a script named like a test.
 */
export function isBunTestFileProcess(): boolean {
  const main = (globalThis as { Bun?: { main?: unknown } }).Bun?.main;
  const entry = typeof main === "string" ? main : process.argv[1];
  return typeof entry === "string" && BUN_TEST_FILE.test(basename(entry));
}

/**
 * Armed when the preload (or a harness) set OCX_TEST_HOME_GUARD=1, or when this process runs a
 * Bun test file and nobody set the flag. An explicit OCX_TEST_HOME_GUARD=0 is how a test case
 * exercises the production branch of a guarded call, so it disarms even inside a test file.
 */
export function isTestHomeGuardArmed(): boolean {
  const flag = process.env[GUARD_ENV];
  if (flag === "1") return true;
  if (flag === "0") return false;
  return isBunTestFileProcess();
}

/**
 * A test process that armed through its entry file publishes the flag, so the CLI and helper
 * processes it spawns — whose own entry is not a test file — inherit the arming instead of
 * writing the real home they also inherited. Runs at import, which in such a run happens before
 * any test body. A production process never matches, so it never reaches the assignment. Any value
 * but the explicit "0" opt-out is normalised, because an empty or stray value arms this process by
 * name but would leave a non-test child, which cannot match by name, disarmed.
 */
if (process.env[GUARD_ENV] !== "0" && process.env[GUARD_ENV] !== "1" && isBunTestFileProcess()) {
  process.env[GUARD_ENV] = "1";
}

/**
 * Appended to a refusal when no preload ran, because the fix there is different: the test did
 * not forget OPENCODEX_HOME, the whole run started from a directory without bunfig.toml.
 */
function missingPreloadHint(): string {
  if (process.env.OCX_TEST_PRELOAD_PID !== undefined) return "";
  return " This test process did not load tests/preload.ts — Bun reads bunfig.toml from the "
    + "current working directory — so nothing was sandboxed. Run bun test from the repository "
    + "root, or pass --preload <repo>/tests/preload.ts.";
}

/**
 * Whether `dir` IS the protected production home, decided with the SAME canonicalization as
 * {@link assertNotRealHomeUnderTest}.
 *
 * For the caller that must FILTER the real home out of a candidate list instead of refusing
 * one write: `serviceStatePaths()` in `src/service.ts` keeps a legacy
 * `~/.opencodex/service-state.json` entry so an install made before OPENCODEX_HOME existed
 * can still be found, and under an armed test process that entry is the developer's live
 * record. Exported so that filter cannot drift onto a weaker comparison — `resolve()` alone
 * calls `/var/folders/...` and `/private/var/folders/...` different paths, which is exactly
 * how a macOS sandbox path slips past a string compare.
 */
export function isProtectedHomeUnderTest(dir: string): boolean {
  if (!isTestHomeGuardArmed()) return false;
  return samePathIgnoringPlatformCase(canonicalize(dir), PROTECTED_HOME);
}

/**
 * Throw when an armed test process is about to write the real OpenCodex home.
 *
 * Call FIRST inside a writer, before any mkdir/chmod/write, so a rejected write leaves
 * nothing behind. Silent no-op when disarmed (production) or when `dir` is any other
 * location, including a suite's own `mkdtemp` fixture — no registration required, which
 * is what keeps the 54 existing suites that write config working untouched.
 */
export function assertNotRealHomeUnderTest(dir: string): void {
  if (!isTestHomeGuardArmed()) return;
  if (!samePathIgnoringPlatformCase(canonicalize(dir), PROTECTED_HOME)) return;
  throw new Error(
    `refusing to write the real OpenCodex home (${PROTECTED_HOME}) from a test process. `
    + "Point OPENCODEX_HOME at a temp directory for this test, or inject persistence "
    + "instead of calling the global writer (see devlog 260730_codex_rs_upstream_v2_live_handoff/070)."
    + missingPreloadHint(),
  );
}

/** The production LaunchAgents directory this process protects. Exported for its tests. */
export function protectedLaunchAgentsDirForTests(): string {
  return PROTECTED_LAUNCH_AGENTS;
}

/**
 * Throw when an armed test process is about to write the real `~/Library/LaunchAgents`.
 *
 * Same contract as {@link assertNotRealHomeUnderTest}: call before any mkdir/write, and
 * pass a DIRECTORY. A launchd test gives `installLaunchd` an explicit plist path inside its
 * own fixture directory instead.
 */
export function assertNotRealLaunchAgentsUnderTest(dir: string): void {
  if (!isTestHomeGuardArmed()) return;
  if (!samePathIgnoringPlatformCase(canonicalize(dir), PROTECTED_LAUNCH_AGENTS)) return;
  throw new Error(
    `refusing to write the real LaunchAgents directory (${PROTECTED_LAUNCH_AGENTS}) from a test `
    + "process: os.homedir() ignores HOME, so rewriting HOME does not move this path. Pass an "
    + "explicit plist path inside the test's own fixture directory instead.",
  );
}

/** Throw when an armed test process is about to write the real native Codex home. */
export function assertNotRealCodexHomeUnderTest(dir: string): void {
  if (!isTestHomeGuardArmed()) return;
  if (!samePathIgnoringPlatformCase(canonicalize(dir), PROTECTED_CODEX_HOME)) return;
  throw new Error(
    `refusing to write the real Codex home (${PROTECTED_CODEX_HOME}) from a test process. `
    + "Point CODEX_HOME at a temp directory for this test before writing Codex files "
    + "(auth.json, the catalog, models_cache.json, the journal or config.toml)."
    + missingPreloadHint(),
  );
}

/**
 * Throw when an armed test process is about to write or prune inside the real Claude config
 * directory. Unlike the OpenCodex and Codex homes this refuses descendants too, and callers pass
 * every directory they are about to touch (the config root AND its `agents`/`cache` child), so a
 * sandbox child that is a link into the real directory is judged by where it resolves.
 *
 * The protected roots are resolved at check time rather than at import, so a custom directory
 * created after this module loaded still compares by its current identity. On macOS and Windows,
 * whose default filesystems ignore case, paths compare case-insensitively: `.CLAUDE` is the same
 * directory there. Comparing too broadly only refuses more, which is the safe direction here.
 *
 * Call FIRST, outside any best-effort catch, so a refusal is visible and nothing is touched.
 */
export function assertNotRealClaudeConfigUnderTest(...paths: string[]): void {
  if (!isTestHomeGuardArmed()) return;
  const roots = currentClaudeConfigRoots();
  for (const path of paths) {
    for (const candidate of [canonicalize(path), resolve(path)]) {
      for (const root of roots) {
        if (!isSameOrInsideIgnoringPlatformCase(root, candidate)) continue;
        throw new Error(
          `refusing to write the real Claude config directory (${root}) from a test process. `
          + "Set CLAUDE_CONFIG_DIR to a temp directory, or pass an explicit config directory "
          + "(for a server, startServer's managementApi.claudeAgentConfigDir).",
        );
      }
    }
  }
}

function currentClaudeConfigRoots(): string[] {
  return REAL_CLAUDE_CONFIG_DIRS.flatMap(path => [canonicalize(path), resolve(path)]);
}

function foldPlatformCase(path: string): string {
  return process.platform === "darwin" || process.platform === "win32" ? path.toLowerCase() : path;
}

/**
 * Path equality as the default filesystem on this platform sees it. A not-yet-existing
 * `.OPENCODEX` canonicalizes through its parent and keeps its spelling, so a plain `===`
 * against the canonical home calls it a different directory on Windows and macOS (#7853).
 */
function samePathIgnoringPlatformCase(a: string, b: string): boolean {
  return foldPlatformCase(a) === foldPlatformCase(b);
}

function isSameOrInsideIgnoringPlatformCase(root: string, candidate: string): boolean {
  const parent = foldPlatformCase(root);
  const child = foldPlatformCase(candidate);
  if (parent === child) return true;
  const rel = relative(parent, child);
  // Only a leading ".." COMPONENT leaves the root, split on this platform's separator: a child
  // named "..fixture", or "..\\fixture" on POSIX where a backslash is a filename character, is inside.
  return rel !== "" && !isAbsolute(rel) && rel !== ".." && !rel.startsWith(`..${sep}`);
}

/**
 * The trees a removal must never reach, and the reason each one is named.
 *
 * The writer guard above cannot help here. `rmSync` is plain `node:fs`: it calls no writer of
 * ours, so no assertion of ours runs, and by the time anything could observe the damage the
 * directory is already gone. On 2026-09-15 that is exactly what happened — a test resolved the
 * process-global config directory and removed it, taking every OAuth login, the Codex account
 * store, the service tokens and a 372MB usage ledger with it.
 */
const PROTECTED_TREES: ReadonlyArray<{ path: string; lexical: string; label: string }> = [
  { path: PROTECTED_HOME, lexical: resolve(join(REAL_HOME, ".opencodex")), label: "the real OpenCodex home" },
  { path: PROTECTED_CODEX_HOME, lexical: resolve(join(REAL_HOME, ".codex")), label: "the real Codex home" },
  {
    path: PROTECTED_LAUNCH_AGENTS,
    lexical: resolve(join(REAL_HOME, "Library", "LaunchAgents")),
    label: "the real LaunchAgents directory",
  },
  ...PROTECTED_CLAUDE_TREES,
];
const PROTECTED_REAL_HOME = canonicalize(REAL_HOME);
const LEXICAL_REAL_HOME = resolve(REAL_HOME);

/** Canonical paths whose removal is refused. Exported so the guard's tests cannot drift off them. */
export function protectedRemovalTreesForTests(): readonly string[] {
  return [PROTECTED_REAL_HOME, ...PROTECTED_TREES.map(tree => tree.path)];
}

/**
 * Whether `child` sits strictly below `parent`, both already canonicalized.
 *
 * Containment is decided per path component, with case folded where the filesystem folds it.
 * A prefix test on the relative path called a direct child named `..backup` "outside", so the
 * removal guard let it through (#7853).
 */
function isInside(parent: string, child: string): boolean {
  return !samePathIgnoringPlatformCase(parent, child) && isSameOrInsideIgnoringPlatformCase(parent, child);
}

/**
 * Whether `child` sits strictly below `parent` with case PRESERVED, deciding per path component.
 *
 * Only for the checkout exemption below, which LIFTS a refusal. Folding case there would let a
 * running checkout at `~/.codex/worktrees/repo` exempt a distinct `~/.codex/worktrees/REPO` on a
 * case-sensitive macOS volume. Protection decisions fold, because comparing too broadly only refuses
 * more; an exemption must not, because the same breadth removes more.
 */
function isInsidePreservingCase(parent: string, child: string): boolean {
  if (parent === child) return false;
  const rel = relative(parent, child);
  return rel !== "" && !isAbsolute(rel) && rel !== ".." && !rel.startsWith(`..${sep}`);
}

let checkoutRootSpellings: readonly string[] | undefined;

/**
 * Both spellings of the checkout that loaded this module (`src/lib` -> repository root).
 *
 * Lazy so a production process, which never removes anything through this guard, does no work
 * for it at module load. In a compiled binary the module URL sits under a virtual root, so the
 * result names no real checkout and the exemption below can never apply.
 */
function checkoutRoots(): readonly string[] {
  if (checkoutRootSpellings === undefined) {
    let lexical: string | null = null;
    try {
      lexical = resolve(fileURLToPath(new URL("../..", import.meta.url)));
    } catch {
      // A non-file module URL names no checkout: no exemption.
    }
    checkoutRootSpellings = lexical === null ? [] : [...new Set([canonicalize(lexical), lexical])];
  }
  return checkoutRootSpellings;
}

/**
 * Whether `candidate` is repository content of a checkout that itself lives inside `protectedPath`.
 *
 * A Codex-app worktree is a checkout under `~/.codex/worktrees/`, and forty suites keep their
 * fixture directory beside the test file. Refusing every path inside `~/.codex` refused those
 * suites' own cleanup, 863 failures in one run, although nothing there is Codex state. The lift
 * is deliberately narrow: it applies to one tree, only when a checkout spelling is strictly
 * inside that tree and the candidate is strictly inside that checkout. The checkout root itself,
 * its ancestors and every sibling stay refused, and a checkout that merely CONTAINS a protected
 * tree (one at `$HOME`, or the virtual root of a compiled build) never qualifies.
 */
function isOwnCheckoutContent(protectedPath: string, candidate: string): boolean {
  return checkoutRoots().some(root => isInsidePreservingCase(protectedPath, root) && isInsidePreservingCase(root, candidate));
}

/**
 * Why removing `target` is refused, or `null` when it is not a protected location.
 *
 * Three relations are refused, not one. Equality alone would still permit
 * `rmSync(getConfigPath())` against a live `config.json`, and it would permit
 * `rmSync(homedir())`, which takes the protected tree with it. So a target is refused when it
 * IS a protected tree, when it sits INSIDE one, or when it is an ANCESTOR of one. The one lift is
 * content of the running checkout when that checkout lives inside the tree
 * ({@link isOwnCheckoutContent}); it never applies to equality or ancestry.
 *
 * Canonicalization is what makes a symlink useless as a bypass: a temp path that merely points
 * at the real home resolves to the real home before any comparison happens. Each spelling is
 * judged on its own and any refusal wins, so a link inside the checkout that resolves into the
 * protected tree is refused through its canonical form.
 */
export function protectedRemovalReason(target: string): string | null {
  // Both spellings are judged, not just the canonical one. Canonicalization is what defeats a
  // symlink alias, but it also resolves the target away: if `~/.opencodex` is itself a link,
  // the literal path a caller passed is the thing that gets unlinked, and only the lexical
  // form still names it. Upstream Codex makes the same distinction in its writable-root
  // handling, keeping logical and resolved forms side by side rather than collapsing to one.
  for (const candidate of [canonicalize(target), resolve(target)]) {
    if (samePathIgnoringPlatformCase(candidate, PROTECTED_REAL_HOME) || samePathIgnoringPlatformCase(candidate, LEXICAL_REAL_HOME)) {
      return `the real home directory (${PROTECTED_REAL_HOME})`;
    }
    for (const tree of PROTECTED_TREES) {
      for (const protectedPath of [tree.path, tree.lexical]) {
        if (samePathIgnoringPlatformCase(candidate, protectedPath)) return `${tree.label} (${protectedPath})`;
        if (isInside(protectedPath, candidate) && !isOwnCheckoutContent(protectedPath, candidate)) {
          return `a path inside ${tree.label} (${protectedPath})`;
        }
        if (isInside(candidate, protectedPath)) return `an ancestor of ${tree.label} (${protectedPath})`;
      }
    }
    // The Claude directory is judged like its writer guard: roots resolved now, case folded
    // where the filesystem folds it, so an alias created after import is still refused.
    for (const root of currentClaudeConfigRoots()) {
      if (isSameOrInsideIgnoringPlatformCase(root, candidate)) {
        // Same narrow lift as the trees above: content of the running checkout when that
        // checkout itself lives inside the directory. Never the root itself.
        if (foldPlatformCase(root) !== foldPlatformCase(candidate) && isOwnCheckoutContent(root, candidate)) continue;
        return `the real Claude config directory or a path inside it (${root})`;
      }
      if (isSameOrInsideIgnoringPlatformCase(candidate, root)) return `an ancestor of the real Claude config directory (${root})`;
    }
  }
  return null;
}

/**
 * Throw before a removal that would reach a protected tree.
 *
 * Deliberately NOT gated on {@link isTestHomeGuardArmed}. `tests/preload.ts` is loaded from the
 * `bunfig.toml` Bun finds in the CURRENT WORKING DIRECTORY, so a run started outside the
 * repository leaves OPENCODEX_HOME unset and resolves the developer's real home. Such a run now
 * arms through its test-file entry, but a helper launched as a plain script does not, and the
 * incident was exactly this unsandboxed shape, so the refusal has to hold without arming.
 * Nothing in production calls this; the callers are test helpers, where the only cost of an
 * unconditional check is a path comparison.
 */
export function assertRemovalOutsideProtectedTrees(target: string): void {
  const reason = protectedRemovalReason(target);
  if (reason === null) return;
  throw new Error(
    `refusing to remove ${reason} from a test process: "${target}" resolves there. `
    + "Create the directory this test owns with createTempHome() from tests/helpers/temp-home "
    + "and remove that handle instead (see devlog 260730_codex_rs_upstream_v2_live_handoff/070).",
  );
}
