import { execFile } from "node:child_process";
import { createHash, createHmac, randomBytes } from "node:crypto";
import { constants as fsConstants } from "node:fs";
import {
  chmod,
  lstat,
  mkdir,
  open,
  readFile,
  readdir,
  realpath
} from "node:fs/promises";
import path from "node:path";
import { promisify, TextDecoder } from "node:util";
import {
  createDefaultRunrailReviewContract,
  parseRunrailReviewContract,
  RUNRAIL_REVIEW_CONTRACT_PATH
} from "./runrail-review-contract-core.mjs";

const execFileAsync = promisify(execFile);
const fatalUtf8Decoder = new TextDecoder("utf-8", { fatal: true });

export const RUNRAIL_REVIEW_SESSION = Object.freeze({
  schemaVersion: 1,
  artifactType: "runrail-review-session",
  dispositionArtifactType: "runrail-review-session-disposition",
  inspectionArtifactType: "runrail-review-repository-inspection",
  profile: "runrail-review-session-v1",
  product: "Runrail Local v1",
  maximumTopActions: 3,
  maximumHistoryEntries: 100,
  maximumDispositionsPerSession: 200
});

export const RUNRAIL_REPOSITORY_READINESS = Object.freeze({
  schemaVersion: 1,
  artifactType: "runrail-repository-readiness-receipt",
  profile: "runrail-repository-readiness-v1",
  product: "Runrail Local v1"
});

export const RUNRAIL_REPOSITORY_READINESS_HANDOFF = Object.freeze({
  schemaVersion: 1,
  artifactType: "runrail-repository-readiness-handoff",
  profile: "runrail-repository-readiness-handoff-v1",
  product: "Runrail Local v1"
});

export const RUNRAIL_REVIEW_DISPOSITION_KINDS = Object.freeze([
  "useful",
  "not-relevant",
  "accepted-exception"
]);

const dispositionKindSet = new Set(RUNRAIL_REVIEW_DISPOSITION_KINDS);
const verdictSet = new Set([
  "blocked",
  "needs-attention",
  "ready-for-human-decision"
]);
const SHA256_PATTERN = /^[a-f0-9]{64}$/;
const COMMIT_PATTERN = /^[a-f0-9]{40,64}$/;
const REVIEW_ID_PATTERN = /^RRS-[A-F0-9]{24}$/;
const DISPOSITION_ID_PATTERN = /^RSD-[A-F0-9]{24}$/;
const REPO_FINGERPRINT_PATTERN = /^RRF-[A-F0-9]{64}$/;
const FINDING_ID_PATTERN = /^[A-Z][A-Z0-9_]{2,63}$/;
const MAX_REF_LENGTH = 200;
const MAX_LOCAL_BRANCHES = 256;
const MAX_CANDIDATE_BRANCHES = 64;
const MAX_DEFAULT_BASES = 8;
const MAX_AHEAD_COMMITS = 1_000;
const MAX_TREE_BYTES = 8 * 1024 * 1024;
const MAX_TRACKED_PATHS = 20_000;
const MAX_LANGUAGE_ROWS = 16;
const MAX_AUDIT_BYTES = 2 * 1024 * 1024;
const MAX_COVERAGE_BYTES = 4 * 1024 * 1024;
const MAX_HISTORY_DIRECTORIES = 1_000;
const SALT_FILE_NAME = ".runrail-review-session-salt";
const HISTORY_REPOSITORIES_DIRECTORY = "repositories";
const HISTORY_SESSIONS_DIRECTORY = "sessions";
const SESSION_FILE_NAME = "session.json";
const DISPOSITIONS_DIRECTORY = "dispositions";

const languageByExtension = new Map([
  [".c", ["c", "C"]],
  [".cc", ["cpp", "C++"]],
  [".cjs", ["javascript", "JavaScript"]],
  [".cpp", ["cpp", "C++"]],
  [".cs", ["csharp", "C#"]],
  [".css", ["css", "CSS"]],
  [".cts", ["typescript", "TypeScript"]],
  [".go", ["go", "Go"]],
  [".h", ["c", "C"]],
  [".hpp", ["cpp", "C++"]],
  [".html", ["html", "HTML"]],
  [".java", ["java", "Java"]],
  [".js", ["javascript", "JavaScript"]],
  [".json", ["json", "JSON"]],
  [".jsx", ["javascript", "JavaScript"]],
  [".kt", ["kotlin", "Kotlin"]],
  [".kts", ["kotlin", "Kotlin"]],
  [".mjs", ["javascript", "JavaScript"]],
  [".mts", ["typescript", "TypeScript"]],
  [".php", ["php", "PHP"]],
  [".ps1", ["powershell", "PowerShell"]],
  [".py", ["python", "Python"]],
  [".rb", ["ruby", "Ruby"]],
  [".rs", ["rust", "Rust"]],
  [".scss", ["scss", "SCSS"]],
  [".sh", ["shell", "Shell"]],
  [".sql", ["sql", "SQL"]],
  [".swift", ["swift", "Swift"]],
  [".tf", ["terraform", "Terraform"]],
  [".toml", ["toml", "TOML"]],
  [".ts", ["typescript", "TypeScript"]],
  [".tsx", ["typescript", "TypeScript"]],
  [".xml", ["xml", "XML"]],
  [".yaml", ["yaml", "YAML"]],
  [".yml", ["yaml", "YAML"]]
]);

const topActionDefinitions = Object.freeze({
  RESOLVE_PREFLIGHT_BLOCKERS: Object.freeze({
    label: "Resolve the failed audit preflight"
  }),
  RESOLVE_REVIEW_CONTRACT: Object.freeze({
    label: "Resolve the base-owned review contract"
  }),
  REVISE_FLAGGED_HUNKS: Object.freeze({
    label: "Revise hunks marked needs revision"
  }),
  RESOLVE_HIGH_FINDINGS: Object.freeze({
    label: "Resolve or explicitly except high findings"
  }),
  COMPLETE_REVIEW_COVERAGE: Object.freeze({
    label: "Complete local hunk review coverage"
  }),
  ADDRESS_MEDIUM_FINDINGS: Object.freeze({
    label: "Address or explicitly except medium findings"
  }),
  RECORD_HUMAN_DECISION: Object.freeze({
    label: "Record the authorized human decision"
  })
});

export class RunrailReviewSessionError extends Error {
  constructor(code, message) {
    super(message);
    this.name = "RunrailReviewSessionError";
    this.code = code;
  }
}

function fail(code, message) {
  throw new RunrailReviewSessionError(code, message);
}

function isRecord(value) {
  if (value === null || typeof value !== "object" || Array.isArray(value)) return false;
  const prototype = Object.getPrototypeOf(value);
  return prototype === Object.prototype || prototype === null;
}

function stableValue(value, seen = new Set()) {
  if (
    value === null ||
    typeof value === "string" ||
    typeof value === "boolean"
  ) {
    return value;
  }
  if (typeof value === "number") {
    if (!Number.isFinite(value)) fail("invalid-json-value", "Stable JSON accepts only finite numbers.");
    return value;
  }
  if (Array.isArray(value)) {
    if (seen.has(value)) fail("invalid-json-value", "Stable JSON values must not contain cycles.");
    seen.add(value);
    const normalized = value.map((entry) => stableValue(entry, seen));
    seen.delete(value);
    return normalized;
  }
  if (!isRecord(value)) {
    fail("invalid-json-value", "Stable JSON accepts only plain JSON objects.");
  }
  if (seen.has(value)) fail("invalid-json-value", "Stable JSON values must not contain cycles.");
  seen.add(value);
  const normalized = Object.fromEntries(
    Object.keys(value)
      .sort()
      .map((key) => {
        if (value[key] === undefined) {
          fail("invalid-json-value", "Stable JSON objects must not contain undefined values.");
        }
        return [key, stableValue(value[key], seen)];
      })
  );
  seen.delete(value);
  return normalized;
}

export function stableRunrailReviewSessionJson(value) {
  return `${JSON.stringify(stableValue(value), null, 2)}\n`;
}

function sha256(value) {
  return createHash("sha256").update(value).digest("hex");
}

export function computeRunrailReviewSessionChecksum(value) {
  return sha256(stableRunrailReviewSessionJson(value));
}

function exactKeys(value, expected, label, code = "review-session-invalid") {
  if (!isRecord(value)) fail(code, `${label} must be a plain object.`);
  const actual = Object.keys(value).sort();
  const required = [...expected].sort();
  if (
    actual.length !== required.length ||
    actual.some((key, index) => key !== required[index])
  ) {
    fail(code, `${label} has an invalid field set.`);
  }
}

function boundedString(value, label, minimum, maximum, code = "review-session-invalid") {
  if (
    typeof value !== "string" ||
    value !== value.trim() ||
    value.length < minimum ||
    value.length > maximum ||
    /[\0-\x08\x0b\x0c\x0e-\x1f\x7f\u202a-\u202e\u2066-\u2069]/u.test(value)
  ) {
    fail(code, `${label} must be bounded plain text.`);
  }
  return value;
}

function canonicalTimestamp(value, label, code = "review-session-invalid") {
  if (typeof value !== "string") fail(code, `${label} must be an ISO timestamp.`);
  const parsed = new Date(value);
  if (!Number.isFinite(parsed.getTime()) || parsed.toISOString() !== value) {
    fail(code, `${label} must be a canonical ISO timestamp.`);
  }
  return value;
}

function normalizeNow(now = new Date()) {
  const parsed = now instanceof Date ? new Date(now.getTime()) : new Date(now);
  if (!Number.isFinite(parsed.getTime())) {
    fail("review-session-time-invalid", "The review-session clock is invalid.");
  }
  return parsed;
}

function compareText(left, right) {
  return left < right ? -1 : left > right ? 1 : 0;
}

function compareSessionsNewestFirst(left, right) {
  const byTime = compareText(right.createdAt, left.createdAt);
  return byTime || compareText(right.reviewId, left.reviewId);
}

function compareDispositionsOldestFirst(left, right) {
  const byTime = compareText(left.createdAt, right.createdAt);
  return byTime || compareText(left.dispositionId, right.dispositionId);
}

function expectBoolean(value, label, code = "review-session-invalid") {
  if (typeof value !== "boolean") fail(code, `${label} must be a boolean.`);
}

function expectInteger(value, label, minimum, maximum, code = "review-session-invalid") {
  if (!Number.isSafeInteger(value) || value < minimum || value > maximum) {
    fail(code, `${label} must be a bounded integer.`);
  }
}

function expectSha256(value, label, code = "review-session-invalid") {
  if (typeof value !== "string" || !SHA256_PATTERN.test(value)) {
    fail(code, `${label} must be a lowercase SHA-256 value.`);
  }
}

function expectCommit(value, label, code = "review-session-invalid") {
  if (typeof value !== "string" || !COMMIT_PATTERN.test(value)) {
    fail(code, `${label} must be a Git commit identifier.`);
  }
}

function absoluteLocalPath(value, label, code = "review-session-invalid") {
  if (
    typeof value !== "string" ||
    value.length < 2 ||
    value.length > 4_096 ||
    !path.isAbsolute(value) ||
    value !== path.normalize(value) ||
    /[\0\r\n]/u.test(value)
  ) {
    fail(code, `${label} must be a normalized absolute local path.`);
  }
  return value;
}

function isInsideOrEqual(candidate, root) {
  const relative = path.relative(root, candidate);
  return (
    relative === "" ||
    (
      relative !== ".." &&
      !relative.startsWith(`..${path.sep}`) &&
      !path.isAbsolute(relative)
    )
  );
}

function pathsOverlap(left, right) {
  return isInsideOrEqual(left, right) || isInsideOrEqual(right, left);
}

function validateId(value, pattern, label, code = "review-session-invalid") {
  if (typeof value !== "string" || !pattern.test(value)) {
    fail(code, `${label} is invalid.`);
  }
  return value;
}

export function validateRunrailReviewRef(value, label = "Git ref") {
  const ref = String(value ?? "");
  if (
    ref.length < 1 ||
    ref.length > MAX_REF_LENGTH ||
    ref !== ref.trim() ||
    ref === "@" ||
    /^(?:HEAD|FETCH_HEAD|ORIG_HEAD|MERGE_HEAD|CHERRY_PICK_HEAD|REVERT_HEAD)$/i.test(ref) ||
    !/^[A-Za-z0-9][A-Za-z0-9._/-]*$/.test(ref) ||
    ref.startsWith("-") ||
    ref.startsWith("/") ||
    ref.endsWith("/") ||
    ref.endsWith(".") ||
    ref.includes("..") ||
    ref.includes("@{") ||
    ref.includes("//") ||
    ref.includes("\\") ||
    /[~^:?*[\]\s\x00-\x1f\x7f]/u.test(ref)
  ) {
    fail("unsafe-git-ref", `${label} must be a bounded, explicit Git branch or commit reference.`);
  }
  const parts = ref.split("/");
  if (
    parts.some(
      (part) =>
        part.length === 0 ||
        part === "." ||
        part === ".." ||
        part.startsWith(".") ||
        part.endsWith(".") ||
        part.toLowerCase().endsWith(".lock")
    )
  ) {
    fail("unsafe-git-ref", `${label} contains an unsafe Git ref component.`);
  }
  return ref;
}

function isolatedGitEnvironment() {
  const allowed = [
    "ComSpec",
    "LANG",
    "LC_ALL",
    "PATH",
    "PATHEXT",
    "SystemDrive",
    "SystemRoot",
    "TEMP",
    "TMP",
    "TMPDIR",
    "WINDIR"
  ];
  return {
    ...Object.fromEntries(
      allowed
        .filter((key) => typeof process.env[key] === "string")
        .map((key) => [key, process.env[key]])
    ),
    GIT_ATTR_NOSYSTEM: "1",
    GIT_CONFIG_GLOBAL: process.platform === "win32" ? "NUL" : "/dev/null",
    GIT_CONFIG_NOSYSTEM: "1",
    GIT_NO_REPLACE_OBJECTS: "1",
    GIT_OPTIONAL_LOCKS: "0",
    GIT_TERMINAL_PROMPT: "0",
    LC_ALL: "C"
  };
}

async function git(repo, args, options = {}) {
  return execFileAsync(
    "git",
    [
      "-c",
      `core.hooksPath=${process.platform === "win32" ? "NUL" : "/dev/null"}`,
      "-c",
      "core.fsmonitor=false",
      "-c",
      "core.useBuiltinFSMonitor=false",
      "-C",
      repo,
      ...args
    ],
    {
      encoding: options.buffer ? null : "utf8",
      env: isolatedGitEnvironment(),
      maxBuffer: options.maxBuffer || 8 * 1024 * 1024,
      shell: false,
      timeout: options.timeout || 30_000,
      windowsHide: true
    }
  );
}

async function gitWithAllowedExit(repo, args, allowedExitCodes, options = {}) {
  try {
    return { ok: true, ...(await git(repo, args, options)) };
  } catch (error) {
    if (allowedExitCodes.includes(Number(error?.code))) {
      return {
        ok: false,
        stdout: options.buffer ? Buffer.alloc(0) : "",
        stderr: options.buffer ? Buffer.alloc(0) : ""
      };
    }
    throw error;
  }
}

async function assertRepositoryRoot(repoInput) {
  if (typeof repoInput !== "string" || !path.isAbsolute(repoInput)) {
    fail("source-repo-path-invalid", "The reviewed repository path must be absolute.");
  }
  const requested = path.normalize(repoInput);
  let requestedEntry;
  try {
    requestedEntry = await lstat(requested);
  } catch {
    fail("source-repo-not-found", "The reviewed repository does not exist.");
  }
  if (requestedEntry.isSymbolicLink()) {
    fail("source-repo-symlink", "The reviewed repository root must not be a symbolic link.");
  }
  if (!requestedEntry.isDirectory()) {
    fail("source-repo-type", "The reviewed repository root must be a directory.");
  }

  const canonical = await realpath(requested);
  const canonicalEntry = await lstat(canonical);
  if (!canonicalEntry.isDirectory() || canonicalEntry.isSymbolicLink()) {
    fail("source-repo-type", "The reviewed repository root must be a real directory.");
  }

  let inside;
  let topLevel;
  try {
    ({ stdout: inside } = await git(canonical, ["rev-parse", "--is-inside-work-tree"]));
    ({ stdout: topLevel } = await git(canonical, ["rev-parse", "--show-toplevel"]));
  } catch {
    fail("source-repo-not-git", "The reviewed repository must be a Git worktree.");
  }
  if (String(inside).trim() !== "true") {
    fail("source-repo-not-git", "The reviewed repository must be a Git worktree.");
  }
  let canonicalTopLevel;
  try {
    canonicalTopLevel = await realpath(String(topLevel).trim());
  } catch {
    fail("source-repo-not-git", "The Git worktree root could not be resolved.");
  }
  if (canonicalTopLevel !== canonical) {
    fail("source-repo-root-required", "Review inspection requires the exact Git worktree root.");
  }

  const dotGitPath = path.join(canonical, ".git");
  try {
    const dotGit = await lstat(dotGitPath);
    if (dotGit.isSymbolicLink()) {
      fail("source-git-metadata-symlink", "The repository .git entry must not be a symbolic link.");
    }
    if (!dotGit.isDirectory() && !dotGit.isFile()) {
      fail("source-git-metadata-type", "The repository .git entry has an unsupported type.");
    }
  } catch (error) {
    if (error instanceof RunrailReviewSessionError) throw error;
    fail("source-repo-not-git", "The reviewed repository has no supported .git entry.");
  }

  try {
    const { stdout } = await git(canonical, [
      "for-each-ref",
      "--format=%(refname)",
      "refs/replace"
    ]);
    if (String(stdout).trim()) {
      fail(
        "git-replacement-objects-not-allowed",
        "Git replacement-object refs are not accepted for review discovery."
      );
    }
  } catch (error) {
    if (error instanceof RunrailReviewSessionError) throw error;
    fail("source-repo-inspection-failed", "The repository reference inventory could not be read.");
  }
  return canonical;
}

async function currentHead(repo) {
  let stdout;
  try {
    ({ stdout } = await git(repo, ["rev-parse", "--verify", "HEAD^{commit}"]));
  } catch {
    fail("source-repo-head-invalid", "The reviewed repository must have a commit at HEAD.");
  }
  const commit = String(stdout).trim();
  expectCommit(commit, "Repository HEAD", "source-repo-head-invalid");
  return commit;
}

async function currentBranch(repo) {
  const result = await gitWithAllowedExit(
    repo,
    ["symbolic-ref", "--quiet", "--short", "HEAD"],
    [1]
  );
  if (!result.ok) return null;
  const branch = String(result.stdout).trim();
  return validateRunrailReviewRef(branch, "Current branch");
}

async function captureRepositoryState(repo) {
  const [head, branch, status, index] = await Promise.all([
    currentHead(repo),
    currentBranch(repo),
    git(repo, ["status", "--porcelain=v1", "-z", "--untracked-files=all"], {
      buffer: true,
      maxBuffer: 16 * 1024 * 1024
    }),
    git(repo, ["ls-files", "--stage", "-z"], {
      buffer: true,
      maxBuffer: 16 * 1024 * 1024
    })
  ]);
  return {
    headCommit: head,
    currentBranch: branch,
    clean: status.stdout.length === 0,
    checksumSha256: computeRunrailReviewSessionChecksum({
      headCommit: head,
      currentBranch: branch,
      indexChecksumSha256: sha256(index.stdout),
      statusChecksumSha256: sha256(status.stdout)
    })
  };
}

async function inspectBaseReviewContract(repo, baseCommit) {
  const object = `${baseCommit}:${RUNRAIL_REVIEW_CONTRACT_PATH}`;
  const result = await gitWithAllowedExit(
    repo,
    ["show", "--no-ext-diff", "--no-textconv", "--format=", object],
    [128],
    { maxBuffer: 65 * 1024 }
  );
  if (!result.ok) {
    const contract = createDefaultRunrailReviewContract();
    return {
      source: "built-in",
      valid: true,
      profile: contract.artifactType,
      ruleCount: contract.rules.length,
      checksumSha256: sha256(stableRunrailReviewSessionJson(contract)),
      errorCode: null
    };
  }
  try {
    const contract = parseRunrailReviewContract(String(result.stdout));
    return {
      source: "baseline-file",
      valid: true,
      profile: contract.artifactType,
      ruleCount: contract.rules.length,
      checksumSha256: sha256(stableRunrailReviewSessionJson(contract)),
      errorCode: null
    };
  } catch (error) {
    return {
      source: "baseline-file",
      valid: false,
      profile: null,
      ruleCount: 0,
      checksumSha256: null,
      errorCode: String(error?.code || "review-contract-invalid")
    };
  }
}

async function resolveCommit(repo, refInput, label) {
  const ref = validateRunrailReviewRef(refInput, label);
  let stdout;
  try {
    ({ stdout } = await git(repo, [
      "rev-parse",
      "--verify",
      "--end-of-options",
      `${ref}^{commit}`
    ]));
  } catch {
    fail("git-ref-not-found", `${label} does not resolve to a commit in the reviewed repository.`);
  }
  const commit = String(stdout).trim();
  expectCommit(commit, label, "git-ref-not-found");
  return { ref, commit };
}

async function listLocalBranches(repo) {
  let stdout;
  try {
    ({ stdout } = await git(repo, [
      "for-each-ref",
      "--format=%(refname:short)%09%(objectname)",
      "refs/heads"
    ]));
  } catch {
    fail("source-repo-inspection-failed", "Local branches could not be inventoried.");
  }
  const lines = String(stdout)
    .split(/\r?\n/u)
    .filter(Boolean);
  if (lines.length > MAX_LOCAL_BRANCHES) {
    fail(
      "local-branch-boundary",
      `Review discovery accepts at most ${MAX_LOCAL_BRANCHES} local branches.`
    );
  }
  const branches = lines.map((line) => {
    const tab = line.indexOf("\t");
    if (tab < 1) fail("source-repo-inspection-failed", "A local branch row is malformed.");
    const ref = validateRunrailReviewRef(line.slice(0, tab), "Local branch");
    const commit = line.slice(tab + 1);
    expectCommit(commit, "Local branch commit", "source-repo-inspection-failed");
    return { ref, commit };
  });
  if (new Set(branches.map((entry) => entry.ref)).size !== branches.length) {
    fail("source-repo-inspection-failed", "Local branch names must be unique.");
  }
  return branches.sort((left, right) => compareText(left.ref, right.ref));
}

async function listRemoteBranches(repo) {
  let stdout;
  try {
    ({ stdout } = await git(repo, [
      "for-each-ref",
      "--format=%(refname:short)%09%(objectname)",
      "refs/remotes"
    ]));
  } catch {
    return [];
  }
  return String(stdout)
    .split(/\r?\n/u)
    .filter(Boolean)
    .map((line) => {
      const tab = line.indexOf("\t");
      if (tab < 1) return null;
      try {
        const ref = validateRunrailReviewRef(line.slice(0, tab), "Remote branch");
        const commit = line.slice(tab + 1);
        expectCommit(commit, "Remote branch commit", "source-repo-inspection-failed");
        return { ref, commit };
      } catch {
        return null;
      }
    })
    .filter(Boolean)
    .sort((left, right) => compareText(left.ref, right.ref));
}

async function isAncestor(repo, ancestorCommit, descendantCommit) {
  const result = await gitWithAllowedExit(
    repo,
    ["merge-base", "--is-ancestor", ancestorCommit, descendantCommit],
    [1]
  );
  return result.ok;
}

async function aheadCommitCount(repo, baseCommit, candidateCommit) {
  let stdout;
  try {
    ({ stdout } = await git(repo, [
      "rev-list",
      "--count",
      `--max-count=${MAX_AHEAD_COMMITS}`,
      `${baseCommit}..${candidateCommit}`,
      "--"
    ]));
  } catch {
    fail("source-repo-inspection-failed", "Candidate branch distance could not be computed.");
  }
  const count = Number.parseInt(String(stdout).trim(), 10);
  if (!Number.isSafeInteger(count) || count < 0 || count > MAX_AHEAD_COMMITS) {
    fail("source-repo-inspection-failed", "Candidate branch distance is invalid.");
  }
  return {
    aheadCommitCount: count,
    aheadCommitCountCapped: count === MAX_AHEAD_COMMITS
  };
}

async function discoverDefaultBaseCandidates(repo, branches, headCommit, branch) {
  const remoteBranches = await listRemoteBranches(repo);
  const localByName = new Map(branches.map((entry) => [entry.ref, entry]));
  const remoteByName = new Map(remoteBranches.map((entry) => [entry.ref, entry]));
  const candidates = [];
  const seen = new Set();
  const add = (entry, source) => {
    if (!entry || seen.has(entry.ref) || candidates.length >= MAX_DEFAULT_BASES) return;
    seen.add(entry.ref);
    candidates.push({ ref: entry.ref, commit: entry.commit, source });
  };

  const remoteHead = await gitWithAllowedExit(
    repo,
    ["symbolic-ref", "--quiet", "--short", "refs/remotes/origin/HEAD"],
    [1]
  );
  if (remoteHead.ok) {
    const ref = String(remoteHead.stdout).trim();
    if (ref) add(remoteByName.get(ref), "remote-default");
  }

  for (const name of ["main", "master", "trunk", "develop"]) {
    add(localByName.get(name), "local-conventional");
  }
  for (const name of ["origin/main", "origin/master", "origin/trunk", "origin/develop"]) {
    add(remoteByName.get(name), "remote-conventional");
  }

  for (const entry of branches) {
    if (
      candidates.length >= MAX_DEFAULT_BASES ||
      entry.ref === branch ||
      entry.commit === headCommit
    ) {
      continue;
    }
    if (await isAncestor(repo, entry.commit, headCommit)) {
      add(entry, "local-ancestor");
    }
  }
  return candidates;
}

async function discoverCandidateBranches(repo, branches, baseCommit) {
  const candidates = [];
  for (const branch of branches) {
    if (branch.commit === baseCommit) continue;
    if (!(await isAncestor(repo, baseCommit, branch.commit))) continue;
    const distance = await aheadCommitCount(repo, baseCommit, branch.commit);
    if (distance.aheadCommitCount < 1) continue;
    candidates.push({ ...branch, ...distance });
  }
  candidates.sort((left, right) => compareText(left.ref, right.ref));
  return {
    rows: candidates.slice(0, MAX_CANDIDATE_BRANCHES),
    totalCount: candidates.length,
    truncated: candidates.length > MAX_CANDIDATE_BRANCHES,
    allRows: candidates
  };
}

function decodeNullTerminatedPaths(buffer) {
  if (!Buffer.isBuffer(buffer)) {
    fail("source-repo-inspection-failed", "The tracked path inventory is invalid.");
  }
  if (buffer.length === 0) return [];
  if (buffer.at(-1) !== 0) {
    fail("source-repo-inspection-failed", "The tracked path inventory is not NUL terminated.");
  }
  const paths = [];
  let start = 0;
  for (let index = 0; index < buffer.length; index += 1) {
    if (buffer[index] !== 0) continue;
    const bytes = buffer.subarray(start, index);
    start = index + 1;
    if (bytes.length === 0) continue;
    let value;
    try {
      value = fatalUtf8Decoder.decode(bytes);
    } catch {
      fail("source-repo-path-encoding", "Tracked Git paths must be valid UTF-8.");
    }
    if (!Buffer.from(value, "utf8").equals(bytes)) {
      fail("source-repo-path-encoding", "Tracked Git paths must round-trip through UTF-8.");
    }
    paths.push(value);
    if (paths.length > MAX_TRACKED_PATHS) {
      fail(
        "tracked-path-boundary",
        `Language discovery accepts at most ${MAX_TRACKED_PATHS} tracked paths.`
      );
    }
  }
  return paths;
}

async function discoverLanguageStack(repo, headCommit) {
  let stdout;
  try {
    ({ stdout } = await git(
      repo,
      ["ls-tree", "-r", "-z", "--name-only", headCommit],
      { buffer: true, maxBuffer: MAX_TREE_BYTES }
    ));
  } catch {
    fail("tracked-path-boundary", "The tracked path inventory exceeded its read boundary.");
  }
  const trackedPaths = decodeNullTerminatedPaths(stdout);
  const counts = new Map();
  let recognizedFileCount = 0;
  for (const trackedPath of trackedPaths) {
    const extension = path.posix.extname(trackedPath).toLowerCase();
    const language = languageByExtension.get(extension);
    if (!language) continue;
    recognizedFileCount += 1;
    const [id, label] = language;
    const current = counts.get(id) || { id, label, fileCount: 0 };
    current.fileCount += 1;
    counts.set(id, current);
  }
  const allLanguages = [...counts.values()].sort(
    (left, right) =>
      right.fileCount - left.fileCount ||
      compareText(left.id, right.id)
  );
  return {
    trackedFileCount: trackedPaths.length,
    recognizedFileCount,
    otherFileCount: trackedPaths.length - recognizedFileCount,
    languages: allLanguages.slice(0, MAX_LANGUAGE_ROWS),
    truncated: allLanguages.length > MAX_LANGUAGE_ROWS
  };
}

function inspectionBodyChecksum(body) {
  return computeRunrailReviewSessionChecksum(body);
}

function repositoryReadinessProjection({
  clean,
  baseConfirmed,
  reviewPolicy,
  candidateCount
}) {
  let status = "ready-to-review";
  let label = "Ready to review";
  let nextAction = {
    id: "start-candidate-review",
    label: "Repository readiness is confirmed. Start the candidate review after enrollment."
  };
  if (!clean) {
    status = "blocked";
    label = "Working tree needs attention";
    nextAction = {
      id: "clean-working-tree",
      label: "Commit or stash local changes, then inspect again."
    };
  } else if (!baseConfirmed) {
    status = "setup-needed";
    label = "Base branch needed";
    nextAction = {
      id: "confirm-base",
      label: "Confirm a local base branch, then inspect again."
    };
  } else if (reviewPolicy === "invalid") {
    status = "blocked";
    label = "Review policy needs attention";
    nextAction = {
      id: "repair-review-policy",
      label: "Repair the base-owned review contract, then inspect again."
    };
  } else if (candidateCount === 0) {
    status = "setup-needed";
    label = "Candidate branch needed";
    nextAction = {
      id: "create-candidate",
      label: "Create a candidate branch with commits ahead of the base, then inspect again."
    };
  } else if (candidateCount > 1) {
    status = "selection-required";
    label = "Choose a candidate";
    nextAction = {
      id: "choose-candidate",
      label: "Choose one discovered candidate branch to continue."
    };
  }
  return {
    status,
    label,
    nextAction,
    checks: [
      {
        id: "local-git",
        label: "Local Git checkout",
        status: "pass",
        detail: "Repository structure was inspected locally."
      },
      {
        id: "working-tree",
        label: "Working tree",
        status: clean ? "pass" : "blocked",
        detail: clean ? "No local working-tree changes detected." : "Local working-tree changes require attention."
      },
      {
        id: "base",
        label: "Base branch",
        status: baseConfirmed ? "pass" : "attention",
        detail: baseConfirmed ? "A local base revision is confirmed." : "A local base revision still needs confirmation."
      },
      {
        id: "review-policy",
        label: "Review policy",
        status: reviewPolicy === "invalid" ? "blocked" : baseConfirmed ? "pass" : "info",
        detail: reviewPolicy === "base-owned"
          ? "The base-owned review contract is valid."
          : reviewPolicy === "built-in"
            ? "The bounded built-in review policy will be used."
            : reviewPolicy === "invalid"
              ? "The base-owned review contract is invalid."
              : "Review policy will be resolved after base confirmation."
      },
      {
        id: "candidate",
        label: "Candidate branch",
        status: candidateCount === 0 ? "attention" : candidateCount === 1 ? "pass" : "info",
        detail: candidateCount === 0
          ? "No local branch is ahead of the confirmed base."
          : candidateCount === 1
            ? "One local candidate is ready to select."
            : "Multiple local candidates are available for selection."
      }
    ]
  };
}

const repositoryReadinessHandoffDefinitions = Object.freeze({
  "clean-working-tree": Object.freeze({
    title: "Protect local work, then restore a clean checkout",
    objective: "Preserve the current work and return the working tree to a clean state.",
    doneWhen: "Git reports no staged, unstaged, or untracked working-tree changes."
  }),
  "confirm-base": Object.freeze({
    title: "Confirm the review base",
    objective: "Select the local branch that owns the review policy and should be treated as the review base.",
    doneWhen: "Runrail can resolve one explicit local base branch to a commit."
  }),
  "repair-review-policy": Object.freeze({
    title: "Repair the base-owned review policy",
    objective: "Make the existing base-owned .runrail/review-contract.json valid without weakening its intended rules.",
    doneWhen: "Runrail validates the base-owned review contract during a new read-only inspection."
  }),
  "create-candidate": Object.freeze({
    title: "Prepare one candidate revision",
    objective: "Create or update one local candidate branch so it contains at least one committed revision ahead of the confirmed base.",
    doneWhen: "Runrail discovers at least one local candidate branch ahead of the confirmed base."
  }),
  "choose-candidate": Object.freeze({
    title: "Choose the candidate to review",
    objective: "Select one of the locally discovered candidate branches for the bounded review.",
    doneWhen: "One explicit candidate is selected in Runrail; no branch is merged or checked out by Runrail."
  }),
  "start-candidate-review": Object.freeze({
    title: "Start the bounded candidate review",
    objective: "Use verified Starter or Pro access to review the selected local candidate against the confirmed base.",
    doneWhen: "Runrail produces a checksum-verified local review packet and still leaves the final decision to a human."
  })
});

const repositoryReadinessHandoffGuardrails = Object.freeze([
  "Preserve existing work and the base-owned review policy.",
  "Do not push, merge, delete work, or weaken policy without explicit human approval.",
  "Return to Runrail and inspect again after completing only the stated objective."
]);

export function verifyRunrailRepositoryInspection(inspection) {
  exactKeys(
    inspection,
    [
      "schemaVersion",
      "artifactType",
      "profile",
      "product",
      "repositoryPath",
      "headCommit",
      "currentBranch",
      "detachedHead",
      "clean",
      "defaultBaseCandidates",
      "confirmedBase",
      "reviewContract",
      "candidateLocalBranches",
      "candidateLocalBranchCount",
      "candidateLocalBranchesTruncated",
      "languageStack",
      "sourceStateChecksumSha256",
      "boundaries",
      "checksumSha256"
    ],
    "Repository inspection",
    "repository-inspection-invalid"
  );
  if (
    inspection.schemaVersion !== RUNRAIL_REVIEW_SESSION.schemaVersion ||
    inspection.artifactType !== RUNRAIL_REVIEW_SESSION.inspectionArtifactType ||
    inspection.profile !== RUNRAIL_REVIEW_SESSION.profile ||
    inspection.product !== RUNRAIL_REVIEW_SESSION.product
  ) {
    fail("repository-inspection-invalid", "The repository inspection identity is invalid.");
  }
  absoluteLocalPath(
    inspection.repositoryPath,
    "Repository inspection path",
    "repository-inspection-invalid"
  );
  expectCommit(inspection.headCommit, "Repository inspection HEAD", "repository-inspection-invalid");
  if (inspection.currentBranch !== null) {
    validateRunrailReviewRef(inspection.currentBranch, "Repository inspection branch");
  }
  expectBoolean(
    inspection.detachedHead,
    "Repository inspection detached flag",
    "repository-inspection-invalid"
  );
  if (inspection.detachedHead !== (inspection.currentBranch === null)) {
    fail("repository-inspection-invalid", "The detached-HEAD fields do not agree.");
  }
  expectBoolean(
    inspection.clean,
    "Repository inspection clean flag",
    "repository-inspection-invalid"
  );
  if (
    !Array.isArray(inspection.defaultBaseCandidates) ||
    inspection.defaultBaseCandidates.length > MAX_DEFAULT_BASES
  ) {
    fail("repository-inspection-invalid", "Default base candidates exceed their boundary.");
  }
  const baseRefs = new Set();
  for (const entry of inspection.defaultBaseCandidates) {
    exactKeys(
      entry,
      ["ref", "commit", "source"],
      "Default base candidate",
      "repository-inspection-invalid"
    );
    validateRunrailReviewRef(entry.ref, "Default base candidate");
    expectCommit(entry.commit, "Default base candidate commit", "repository-inspection-invalid");
    if (
      !new Set([
        "remote-default",
        "local-conventional",
        "remote-conventional",
        "local-ancestor"
      ]).has(entry.source) ||
      baseRefs.has(entry.ref)
    ) {
      fail("repository-inspection-invalid", "A default base candidate is invalid or duplicated.");
    }
    baseRefs.add(entry.ref);
  }
  if (inspection.confirmedBase !== null) {
    exactKeys(
      inspection.confirmedBase,
      ["ref", "commit"],
      "Confirmed base",
      "repository-inspection-invalid"
    );
    validateRunrailReviewRef(inspection.confirmedBase.ref, "Confirmed base");
    expectCommit(inspection.confirmedBase.commit, "Confirmed base commit", "repository-inspection-invalid");
  }
  exactKeys(
    inspection.reviewContract,
    [
      "source",
      "valid",
      "profile",
      "ruleCount",
      "checksumSha256",
      "errorCode"
    ],
    "Repository review contract",
    "repository-inspection-invalid"
  );
  if (
    !new Set(["built-in", "baseline-file", "unconfirmed"]).has(
      inspection.reviewContract.source
    )
  ) {
    fail("repository-inspection-invalid", "The review-contract source is invalid.");
  }
  expectBoolean(
    inspection.reviewContract.valid,
    "Repository review-contract validity",
    "repository-inspection-invalid"
  );
  expectInteger(
    inspection.reviewContract.ruleCount,
    "Repository review-contract rule count",
    0,
    32,
    "repository-inspection-invalid"
  );
  if (inspection.reviewContract.source === "unconfirmed") {
    if (
      inspection.confirmedBase !== null ||
      inspection.reviewContract.valid !== false ||
      inspection.reviewContract.profile !== null ||
      inspection.reviewContract.ruleCount !== 0 ||
      inspection.reviewContract.checksumSha256 !== null ||
      inspection.reviewContract.errorCode !== "base-not-confirmed"
    ) {
      fail("repository-inspection-invalid", "The unconfirmed review-contract state is invalid.");
    }
  } else if (inspection.reviewContract.valid) {
    if (
      inspection.confirmedBase === null ||
      inspection.reviewContract.profile !== "runrail-review-contract" ||
      inspection.reviewContract.errorCode !== null
    ) {
      fail("repository-inspection-invalid", "The valid review-contract state is invalid.");
    }
    expectSha256(
      inspection.reviewContract.checksumSha256,
      "Repository review-contract checksum",
      "repository-inspection-invalid"
    );
  } else if (
    inspection.reviewContract.source !== "baseline-file" ||
    inspection.reviewContract.profile !== null ||
    inspection.reviewContract.ruleCount !== 0 ||
    inspection.reviewContract.checksumSha256 !== null ||
    typeof inspection.reviewContract.errorCode !== "string" ||
    !inspection.reviewContract.errorCode
  ) {
    fail("repository-inspection-invalid", "The invalid review-contract state is invalid.");
  }
  if (
    !Array.isArray(inspection.candidateLocalBranches) ||
    inspection.candidateLocalBranches.length > MAX_CANDIDATE_BRANCHES
  ) {
    fail("repository-inspection-invalid", "Candidate branch rows exceed their boundary.");
  }
  const candidateRefs = new Set();
  for (const entry of inspection.candidateLocalBranches) {
    exactKeys(
      entry,
      [
        "ref",
        "commit",
        "aheadCommitCount",
        "aheadCommitCountCapped"
      ],
      "Candidate local branch",
      "repository-inspection-invalid"
    );
    validateRunrailReviewRef(entry.ref, "Candidate local branch");
    expectCommit(entry.commit, "Candidate local branch commit", "repository-inspection-invalid");
    expectInteger(
      entry.aheadCommitCount,
      "Candidate ahead count",
      1,
      MAX_AHEAD_COMMITS,
      "repository-inspection-invalid"
    );
    expectBoolean(
      entry.aheadCommitCountCapped,
      "Candidate ahead-count cap",
      "repository-inspection-invalid"
    );
    if (
      entry.aheadCommitCountCapped !==
        (entry.aheadCommitCount === MAX_AHEAD_COMMITS) ||
      candidateRefs.has(entry.ref)
    ) {
      fail("repository-inspection-invalid", "A candidate branch row is inconsistent.");
    }
    candidateRefs.add(entry.ref);
  }
  expectInteger(
    inspection.candidateLocalBranchCount,
    "Candidate branch count",
    inspection.candidateLocalBranches.length,
    MAX_LOCAL_BRANCHES,
    "repository-inspection-invalid"
  );
  expectBoolean(
    inspection.candidateLocalBranchesTruncated,
    "Candidate branch truncation",
    "repository-inspection-invalid"
  );
  if (
    inspection.candidateLocalBranchesTruncated !==
      (inspection.candidateLocalBranchCount >
        inspection.candidateLocalBranches.length) ||
    (inspection.confirmedBase === null &&
      (
        inspection.candidateLocalBranchCount !== 0 ||
        inspection.candidateLocalBranches.length !== 0
      ))
  ) {
    fail("repository-inspection-invalid", "Candidate branch summary is inconsistent.");
  }
  verifyLanguageStack(inspection.languageStack, "repository-inspection-invalid");
  expectSha256(
    inspection.sourceStateChecksumSha256,
    "Repository state checksum",
    "repository-inspection-invalid"
  );
  exactKeys(
    inspection.boundaries,
    [
      "localOnly",
      "authority",
      "networkUsed",
      "modelUsed",
      "providerUsed",
      "projectTestsExecuted",
      "patchApplied",
      "sourceMutationPerformed",
      "rawCommandOutputIncluded"
    ],
    "Repository inspection boundaries",
    "repository-inspection-invalid"
  );
  if (
    inspection.boundaries.localOnly !== true ||
    inspection.boundaries.authority !== "none" ||
    inspection.boundaries.networkUsed !== false ||
    inspection.boundaries.modelUsed !== false ||
    inspection.boundaries.providerUsed !== false ||
    inspection.boundaries.projectTestsExecuted !== false ||
    inspection.boundaries.patchApplied !== false ||
    inspection.boundaries.sourceMutationPerformed !== false ||
    inspection.boundaries.rawCommandOutputIncluded !== false
  ) {
    fail("repository-inspection-authority", "Repository inspection expanded its authority boundary.");
  }
  const { checksumSha256, ...body } = inspection;
  expectSha256(checksumSha256, "Repository inspection checksum", "repository-inspection-invalid");
  if (inspectionBodyChecksum(body) !== checksumSha256) {
    fail("repository-inspection-checksum", "The repository inspection checksum is invalid.");
  }
  return inspection;
}

export function verifyRunrailRepositoryReadinessReceipt(receipt) {
  exactKeys(
    receipt,
    [
      "schemaVersion",
      "artifactType",
      "profile",
      "product",
      "status",
      "label",
      "nextAction",
      "checks",
      "summary",
      "boundaries",
      "checksumSha256"
    ],
    "Repository readiness receipt",
    "repository-readiness-invalid"
  );
  if (
    receipt.schemaVersion !== RUNRAIL_REPOSITORY_READINESS.schemaVersion ||
    receipt.artifactType !== RUNRAIL_REPOSITORY_READINESS.artifactType ||
    receipt.profile !== RUNRAIL_REPOSITORY_READINESS.profile ||
    receipt.product !== RUNRAIL_REPOSITORY_READINESS.product
  ) {
    fail("repository-readiness-invalid", "The repository readiness identity is invalid.");
  }
  if (!new Set(["blocked", "setup-needed", "selection-required", "ready-to-review"]).has(receipt.status)) {
    fail("repository-readiness-invalid", "The repository readiness status is invalid.");
  }
  if (typeof receipt.label !== "string" || receipt.label.length < 1 || receipt.label.length > 80) {
    fail("repository-readiness-invalid", "The repository readiness label is invalid.");
  }
  exactKeys(
    receipt.nextAction,
    ["id", "label"],
    "Repository readiness next action",
    "repository-readiness-invalid"
  );
  if (
    typeof receipt.nextAction.id !== "string" ||
    !/^[a-z][a-z0-9-]{2,63}$/u.test(receipt.nextAction.id) ||
    typeof receipt.nextAction.label !== "string" ||
    receipt.nextAction.label.length < 1 ||
    receipt.nextAction.label.length > 180
  ) {
    fail("repository-readiness-invalid", "The repository readiness next action is invalid.");
  }
  if (!Array.isArray(receipt.checks) || receipt.checks.length !== 5) {
    fail("repository-readiness-invalid", "The repository readiness checks are incomplete.");
  }
  const expectedCheckIds = ["local-git", "working-tree", "base", "review-policy", "candidate"];
  receipt.checks.forEach((check, index) => {
    exactKeys(
      check,
      ["id", "label", "status", "detail"],
      "Repository readiness check",
      "repository-readiness-invalid"
    );
    if (
      check.id !== expectedCheckIds[index] ||
      typeof check.label !== "string" ||
      check.label.length < 1 ||
      check.label.length > 80 ||
      !new Set(["pass", "attention", "blocked", "info"]).has(check.status) ||
      typeof check.detail !== "string" ||
      check.detail.length < 1 ||
      check.detail.length > 160
    ) {
      fail("repository-readiness-invalid", "A repository readiness check is invalid.");
    }
  });
  exactKeys(
    receipt.summary,
    ["clean", "baseConfirmed", "reviewPolicy", "candidateCount", "candidateCountBucket", "languageCountBucket"],
    "Repository readiness summary",
    "repository-readiness-invalid"
  );
  expectBoolean(receipt.summary.clean, "Repository readiness clean flag", "repository-readiness-invalid");
  expectBoolean(receipt.summary.baseConfirmed, "Repository readiness base flag", "repository-readiness-invalid");
  if (
    !new Set(["unconfirmed", "built-in", "base-owned", "invalid"]).has(receipt.summary.reviewPolicy) ||
    !Number.isInteger(receipt.summary.candidateCount) ||
    receipt.summary.candidateCount < 0 ||
    receipt.summary.candidateCount > MAX_LOCAL_BRANCHES ||
    !new Set(["none", "one", "multiple"]).has(receipt.summary.candidateCountBucket) ||
    !new Set(["none", "one", "multiple"]).has(receipt.summary.languageCountBucket)
  ) {
    fail("repository-readiness-invalid", "The repository readiness summary is invalid.");
  }
  const expectedCandidateCountBucket = receipt.summary.candidateCount === 0
    ? "none"
    : receipt.summary.candidateCount === 1
      ? "one"
      : "multiple";
  if (receipt.summary.candidateCountBucket !== expectedCandidateCountBucket) {
    fail("repository-readiness-invalid", "The repository readiness candidate summary is inconsistent.");
  }
  const expectedProjection = repositoryReadinessProjection(receipt.summary);
  if (
    receipt.status !== expectedProjection.status ||
    receipt.label !== expectedProjection.label ||
    stableRunrailReviewSessionJson(receipt.nextAction) !==
      stableRunrailReviewSessionJson(expectedProjection.nextAction) ||
    stableRunrailReviewSessionJson(receipt.checks) !==
      stableRunrailReviewSessionJson(expectedProjection.checks)
  ) {
    fail("repository-readiness-invalid", "The repository readiness decision does not match its verified summary.");
  }
  exactKeys(
    receipt.boundaries,
    [
      "localOnly",
      "stored",
      "pathIncluded",
      "branchIncluded",
      "commitIncluded",
      "sourceIncluded",
      "diffIncluded",
      "networkUsed",
      "projectTestsExecuted",
      "sourceMutation",
      "authority"
    ],
    "Repository readiness boundaries",
    "repository-readiness-invalid"
  );
  if (
    receipt.boundaries.localOnly !== true ||
    receipt.boundaries.stored !== false ||
    receipt.boundaries.pathIncluded !== false ||
    receipt.boundaries.branchIncluded !== false ||
    receipt.boundaries.commitIncluded !== false ||
    receipt.boundaries.sourceIncluded !== false ||
    receipt.boundaries.diffIncluded !== false ||
    receipt.boundaries.networkUsed !== false ||
    receipt.boundaries.projectTestsExecuted !== false ||
    receipt.boundaries.sourceMutation !== false ||
    receipt.boundaries.authority !== "none"
  ) {
    fail("repository-readiness-invalid", "The repository readiness boundary expanded.");
  }
  if (!SHA256_PATTERN.test(receipt.checksumSha256)) {
    fail("repository-readiness-invalid", "The repository readiness checksum is invalid.");
  }
  const body = Object.fromEntries(
    Object.entries(receipt).filter(([key]) => key !== "checksumSha256")
  );
  if (computeRunrailReviewSessionChecksum(body) !== receipt.checksumSha256) {
    fail("repository-readiness-invalid", "The repository readiness checksum does not match its body.");
  }
  return receipt;
}

export function buildRunrailRepositoryReadinessReceipt(inspectionInput) {
  const inspection = verifyRunrailRepositoryInspection(inspectionInput);
  const candidateCount = inspection.candidateLocalBranchCount;
  const candidateCountBucket = candidateCount === 0
    ? "none"
    : candidateCount === 1
      ? "one"
      : "multiple";
  const languageCount = inspection.languageStack.languages.length;
  const languageCountBucket = languageCount === 0
    ? "none"
    : languageCount === 1
      ? "one"
      : "multiple";
  const baseConfirmed = inspection.confirmedBase !== null;
  const reviewPolicy = !baseConfirmed
    ? "unconfirmed"
    : inspection.reviewContract.valid !== true
      ? "invalid"
      : inspection.reviewContract.source === "baseline-file"
        ? "base-owned"
        : "built-in";

  const projection = repositoryReadinessProjection({
    clean: inspection.clean,
    baseConfirmed,
    reviewPolicy,
    candidateCount
  });

  const body = {
    schemaVersion: RUNRAIL_REPOSITORY_READINESS.schemaVersion,
    artifactType: RUNRAIL_REPOSITORY_READINESS.artifactType,
    profile: RUNRAIL_REPOSITORY_READINESS.profile,
    product: RUNRAIL_REPOSITORY_READINESS.product,
    ...projection,
    summary: {
      clean: inspection.clean,
      baseConfirmed,
      reviewPolicy,
      candidateCount,
      candidateCountBucket,
      languageCountBucket
    },
    boundaries: {
      localOnly: true,
      stored: false,
      pathIncluded: false,
      branchIncluded: false,
      commitIncluded: false,
      sourceIncluded: false,
      diffIncluded: false,
      networkUsed: false,
      projectTestsExecuted: false,
      sourceMutation: false,
      authority: "none"
    }
  };
  return verifyRunrailRepositoryReadinessReceipt({
    ...body,
    checksumSha256: computeRunrailReviewSessionChecksum(body)
  });
}

export function verifyRunrailRepositoryReadinessHandoff(handoff) {
  exactKeys(
    handoff,
    [
      "schemaVersion",
      "artifactType",
      "profile",
      "product",
      "status",
      "actionId",
      "title",
      "objective",
      "doneWhen",
      "returnStep",
      "guardrails",
      "sourceReceiptChecksumSha256",
      "boundaries",
      "checksumSha256"
    ],
    "Repository readiness handoff",
    "repository-readiness-handoff-invalid"
  );
  if (
    handoff.schemaVersion !== RUNRAIL_REPOSITORY_READINESS_HANDOFF.schemaVersion ||
    handoff.artifactType !== RUNRAIL_REPOSITORY_READINESS_HANDOFF.artifactType ||
    handoff.profile !== RUNRAIL_REPOSITORY_READINESS_HANDOFF.profile ||
    handoff.product !== RUNRAIL_REPOSITORY_READINESS_HANDOFF.product
  ) {
    fail("repository-readiness-handoff-invalid", "The repository readiness handoff identity is invalid.");
  }
  const definition = repositoryReadinessHandoffDefinitions[handoff.actionId];
  const expectedStatusByAction = Object.freeze({
    "clean-working-tree": "blocked",
    "confirm-base": "setup-needed",
    "repair-review-policy": "blocked",
    "create-candidate": "setup-needed",
    "choose-candidate": "selection-required",
    "start-candidate-review": "ready-to-review"
  });
  if (
    !definition ||
    handoff.status !== expectedStatusByAction[handoff.actionId] ||
    handoff.title !== definition.title ||
    handoff.objective !== definition.objective ||
    handoff.doneWhen !== definition.doneWhen ||
    handoff.returnStep !== "Inspect the repository again in Runrail." ||
    stableRunrailReviewSessionJson(handoff.guardrails) !==
      stableRunrailReviewSessionJson(repositoryReadinessHandoffGuardrails)
  ) {
    fail("repository-readiness-handoff-invalid", "The repository readiness handoff guidance is inconsistent.");
  }
  boundedString(handoff.title, "Repository readiness handoff title", 1, 120, "repository-readiness-handoff-invalid");
  boundedString(handoff.objective, "Repository readiness handoff objective", 1, 260, "repository-readiness-handoff-invalid");
  boundedString(handoff.doneWhen, "Repository readiness handoff done condition", 1, 220, "repository-readiness-handoff-invalid");
  boundedString(handoff.returnStep, "Repository readiness handoff return step", 1, 120, "repository-readiness-handoff-invalid");
  if (!Array.isArray(handoff.guardrails) || handoff.guardrails.length !== 3) {
    fail("repository-readiness-handoff-invalid", "The repository readiness handoff guardrails are incomplete.");
  }
  handoff.guardrails.forEach((entry, index) => {
    boundedString(entry, `Repository readiness handoff guardrail ${index + 1}`, 1, 180, "repository-readiness-handoff-invalid");
  });
  expectSha256(
    handoff.sourceReceiptChecksumSha256,
    "Repository readiness handoff source receipt",
    "repository-readiness-handoff-invalid"
  );
  exactKeys(
    handoff.boundaries,
    [
      "localOnly",
      "stored",
      "pathIncluded",
      "branchIncluded",
      "commitIncluded",
      "sourceIncluded",
      "diffIncluded",
      "networkUsed",
      "projectTestsExecuted",
      "sourceMutation",
      "authority"
    ],
    "Repository readiness handoff boundaries",
    "repository-readiness-handoff-invalid"
  );
  if (
    handoff.boundaries.localOnly !== true ||
    handoff.boundaries.stored !== false ||
    handoff.boundaries.pathIncluded !== false ||
    handoff.boundaries.branchIncluded !== false ||
    handoff.boundaries.commitIncluded !== false ||
    handoff.boundaries.sourceIncluded !== false ||
    handoff.boundaries.diffIncluded !== false ||
    handoff.boundaries.networkUsed !== false ||
    handoff.boundaries.projectTestsExecuted !== false ||
    handoff.boundaries.sourceMutation !== false ||
    handoff.boundaries.authority !== "none"
  ) {
    fail("repository-readiness-handoff-authority", "The repository readiness handoff expanded its authority boundary.");
  }
  expectSha256(handoff.checksumSha256, "Repository readiness handoff checksum", "repository-readiness-handoff-invalid");
  const { checksumSha256, ...body } = handoff;
  if (computeRunrailReviewSessionChecksum(body) !== checksumSha256) {
    fail("repository-readiness-handoff-checksum", "The repository readiness handoff checksum does not match its body.");
  }
  return handoff;
}

export function buildRunrailRepositoryReadinessHandoff(receiptInput) {
  const receipt = verifyRunrailRepositoryReadinessReceipt(receiptInput);
  const definition = repositoryReadinessHandoffDefinitions[receipt.nextAction.id];
  if (!definition) {
    fail("repository-readiness-handoff-invalid", "The readiness action has no bounded handoff definition.");
  }
  const body = {
    schemaVersion: RUNRAIL_REPOSITORY_READINESS_HANDOFF.schemaVersion,
    artifactType: RUNRAIL_REPOSITORY_READINESS_HANDOFF.artifactType,
    profile: RUNRAIL_REPOSITORY_READINESS_HANDOFF.profile,
    product: RUNRAIL_REPOSITORY_READINESS_HANDOFF.product,
    status: receipt.status,
    actionId: receipt.nextAction.id,
    title: definition.title,
    objective: definition.objective,
    doneWhen: definition.doneWhen,
    returnStep: "Inspect the repository again in Runrail.",
    guardrails: [...repositoryReadinessHandoffGuardrails],
    sourceReceiptChecksumSha256: receipt.checksumSha256,
    boundaries: {
      localOnly: true,
      stored: false,
      pathIncluded: false,
      branchIncluded: false,
      commitIncluded: false,
      sourceIncluded: false,
      diffIncluded: false,
      networkUsed: false,
      projectTestsExecuted: false,
      sourceMutation: false,
      authority: "none"
    }
  };
  return verifyRunrailRepositoryReadinessHandoff({
    ...body,
    checksumSha256: computeRunrailReviewSessionChecksum(body)
  });
}

export function renderRunrailRepositoryReadinessHandoff(handoffInput) {
  const handoff = verifyRunrailRepositoryReadinessHandoff(handoffInput);
  return [
    "Runrail Review-Ready Brief",
    `Status: ${handoff.status}`,
    `Objective: ${handoff.objective}`,
    `Done when: ${handoff.doneWhen}`,
    `Return: ${handoff.returnStep}`,
    "Guardrails:",
    ...handoff.guardrails.map((entry) => `- ${entry}`),
    `Readiness receipt: ${handoff.sourceReceiptChecksumSha256}`,
    `Brief checksum: ${handoff.checksumSha256}`,
    "Boundary: path-free local guidance only; no source, diff, network, project test, source mutation, or execution authority."
  ].join("\n");
}

function verifyLanguageStack(stack, code = "review-session-invalid") {
  exactKeys(
    stack,
    [
      "trackedFileCount",
      "recognizedFileCount",
      "otherFileCount",
      "languages",
      "truncated"
    ],
    "Language stack",
    code
  );
  for (const key of ["trackedFileCount", "recognizedFileCount", "otherFileCount"]) {
    expectInteger(stack[key], `Language stack ${key}`, 0, MAX_TRACKED_PATHS, code);
  }
  if (
    stack.recognizedFileCount + stack.otherFileCount !== stack.trackedFileCount ||
    !Array.isArray(stack.languages) ||
    stack.languages.length > MAX_LANGUAGE_ROWS
  ) {
    fail(code, "The language stack summary is inconsistent.");
  }
  const ids = new Set();
  let previous = null;
  let visibleRecognizedCount = 0;
  for (const row of stack.languages) {
    exactKeys(row, ["id", "label", "fileCount"], "Language stack row", code);
    if (
      typeof row.id !== "string" ||
      !/^[a-z][a-z0-9-]{0,31}$/.test(row.id) ||
      ids.has(row.id)
    ) {
      fail(code, "A language stack identifier is invalid or duplicated.");
    }
    boundedString(row.label, "Language stack label", 1, 40, code);
    expectInteger(row.fileCount, "Language stack file count", 1, MAX_TRACKED_PATHS, code);
    if (
      previous &&
      (
        row.fileCount > previous.fileCount ||
        (
          row.fileCount === previous.fileCount &&
          compareText(row.id, previous.id) < 0
        )
      )
    ) {
      fail(code, "Language stack rows are not in deterministic order.");
    }
    ids.add(row.id);
    visibleRecognizedCount += row.fileCount;
    previous = row;
  }
  expectBoolean(stack.truncated, "Language stack truncation", code);
  if (
    (!stack.truncated && visibleRecognizedCount !== stack.recognizedFileCount) ||
    (stack.truncated && stack.languages.length !== MAX_LANGUAGE_ROWS)
  ) {
    fail(code, "The language stack truncation summary is invalid.");
  }
}

export async function inspectRunrailReviewRepository({
  repo,
  base = null
}) {
  const repositoryPath = await assertRepositoryRoot(repo);
  const stateBefore = await captureRepositoryState(repositoryPath);
  const branches = await listLocalBranches(repositoryPath);
  const defaultBaseCandidates = await discoverDefaultBaseCandidates(
    repositoryPath,
    branches,
    stateBefore.headCommit,
    stateBefore.currentBranch
  );
  const confirmedBase = base === null
    ? null
    : await resolveCommit(repositoryPath, base, "Confirmed base");
  const reviewContract = confirmedBase
    ? await inspectBaseReviewContract(repositoryPath, confirmedBase.commit)
    : {
        source: "unconfirmed",
        valid: false,
        profile: null,
        ruleCount: 0,
        checksumSha256: null,
        errorCode: "base-not-confirmed"
      };
  const discoveredCandidates = confirmedBase
    ? await discoverCandidateBranches(
        repositoryPath,
        branches,
        confirmedBase.commit
      )
    : { rows: [], totalCount: 0, truncated: false };
  const languageStack = await discoverLanguageStack(
    repositoryPath,
    stateBefore.headCommit
  );
  const stateAfter = await captureRepositoryState(repositoryPath);
  if (stateAfter.checksumSha256 !== stateBefore.checksumSha256) {
    fail(
      "source-repo-changed-during-inspection",
      "The repository changed while its read-only review metadata was inspected."
    );
  }
  const body = {
    schemaVersion: RUNRAIL_REVIEW_SESSION.schemaVersion,
    artifactType: RUNRAIL_REVIEW_SESSION.inspectionArtifactType,
    profile: RUNRAIL_REVIEW_SESSION.profile,
    product: RUNRAIL_REVIEW_SESSION.product,
    repositoryPath,
    headCommit: stateBefore.headCommit,
    currentBranch: stateBefore.currentBranch,
    detachedHead: stateBefore.currentBranch === null,
    clean: stateBefore.clean,
    defaultBaseCandidates,
    confirmedBase,
    reviewContract,
    candidateLocalBranches: discoveredCandidates.rows,
    candidateLocalBranchCount: discoveredCandidates.totalCount,
    candidateLocalBranchesTruncated: discoveredCandidates.truncated,
    languageStack,
    sourceStateChecksumSha256: stateBefore.checksumSha256,
    boundaries: {
      localOnly: true,
      authority: "none",
      networkUsed: false,
      modelUsed: false,
      providerUsed: false,
      projectTestsExecuted: false,
      patchApplied: false,
      sourceMutationPerformed: false,
      rawCommandOutputIncluded: false
    }
  };
  const inspection = {
    ...body,
    checksumSha256: inspectionBodyChecksum(body)
  };
  return verifyRunrailRepositoryInspection(inspection);
}

async function ensureHistoryRoot(historyRootInput, { create }) {
  if (
    typeof historyRootInput !== "string" ||
    !path.isAbsolute(historyRootInput) ||
    historyRootInput.length > 4_096 ||
    /[\0\r\n]/u.test(historyRootInput)
  ) {
    fail("history-root-invalid", "An explicit absolute history root is required.");
  }
  const requested = path.normalize(historyRootInput);
  let entry;
  try {
    entry = await lstat(requested);
  } catch (error) {
    if (error?.code !== "ENOENT" || !create) {
      if (error?.code === "ENOENT") return null;
      fail("history-root-invalid", "The history root could not be inspected.");
    }
    await mkdir(requested, { recursive: true, mode: 0o700 });
    entry = await lstat(requested);
  }
  if (entry.isSymbolicLink()) {
    fail("history-root-symlink", "The review history root must not be a symbolic link.");
  }
  if (!entry.isDirectory()) {
    fail("history-root-type", "The review history root must be a directory.");
  }
  if (process.platform !== "win32") await chmod(requested, 0o700);
  const canonical = await realpath(requested);
  const canonicalEntry = await lstat(canonical);
  if (!canonicalEntry.isDirectory() || canonicalEntry.isSymbolicLink()) {
    fail("history-root-type", "The review history root must resolve to a real directory.");
  }
  return canonical;
}

async function assertHistoryRootDisjointBeforeMutation(
  historyRootInput,
  repositoryPath
) {
  if (
    typeof historyRootInput !== "string" ||
    !path.isAbsolute(historyRootInput)
  ) {
    fail("history-root-invalid", "An explicit absolute history root is required.");
  }
  const requested = path.normalize(historyRootInput);
  if (pathsOverlap(requested, repositoryPath)) {
    fail(
      "history-root-overlaps-source",
      "Review history must be stored outside the reviewed repository."
    );
  }

  let cursor = requested;
  const missingParts = [];
  while (true) {
    try {
      const entry = await lstat(cursor);
      if (cursor === requested && entry.isSymbolicLink()) {
        fail(
          "history-root-symlink",
          "The review history root must not be a symbolic link."
        );
      }
      const canonicalAncestor = await realpath(cursor);
      const predicted = path.join(canonicalAncestor, ...missingParts);
      if (pathsOverlap(predicted, repositoryPath)) {
        fail(
          "history-root-overlaps-source",
          "Review history must be stored outside the reviewed repository."
        );
      }
      return;
    } catch (error) {
      if (error instanceof RunrailReviewSessionError) throw error;
      if (error?.code !== "ENOENT") {
        fail("history-root-invalid", "The history root could not be inspected safely.");
      }
      const parent = path.dirname(cursor);
      if (parent === cursor) {
        fail("history-root-invalid", "The history root has no resolvable ancestor.");
      }
      missingParts.unshift(path.basename(cursor));
      cursor = parent;
    }
  }
}

function safeHistoryName(value, pattern, label) {
  validateId(value, pattern, label, "history-path-invalid");
  return value;
}

async function ensurePrivateDirectory(parent, name) {
  if (!/^[A-Za-z0-9._-]{1,100}$/.test(name) || name === "." || name === "..") {
    fail("history-path-invalid", "A review history directory name is invalid.");
  }
  const candidate = path.join(parent, name);
  if (!isInsideOrEqual(candidate, parent) || candidate === parent) {
    fail("history-path-invalid", "A review history path escaped its parent.");
  }
  try {
    await mkdir(candidate, { mode: 0o700 });
  } catch (error) {
    if (error?.code !== "EEXIST") throw error;
  }
  const entry = await lstat(candidate);
  if (entry.isSymbolicLink() || !entry.isDirectory()) {
    fail("history-path-symlink", "Review history directories must be real directories.");
  }
  if (process.platform !== "win32") await chmod(candidate, 0o700);
  const canonical = await realpath(candidate);
  if (!isInsideOrEqual(canonical, parent) || canonical === parent) {
    fail("history-path-invalid", "A review history directory escaped its parent.");
  }
  return canonical;
}

async function requirePrivateDirectory(parent, name) {
  const candidate = path.join(parent, name);
  if (!isInsideOrEqual(candidate, parent) || candidate === parent) {
    fail("history-path-invalid", "A review history path escaped its parent.");
  }
  let entry;
  try {
    entry = await lstat(candidate);
  } catch (error) {
    if (error?.code === "ENOENT") return null;
    throw error;
  }
  if (entry.isSymbolicLink() || !entry.isDirectory()) {
    fail("history-path-symlink", "Review history directories must be real directories.");
  }
  const canonical = await realpath(candidate);
  if (!isInsideOrEqual(canonical, parent) || canonical === parent) {
    fail("history-path-invalid", "A review history directory escaped its parent.");
  }
  return canonical;
}

async function writeExclusiveOwnerFile(filePath, contents) {
  const flags =
    fsConstants.O_CREAT |
    fsConstants.O_EXCL |
    fsConstants.O_WRONLY |
    (fsConstants.O_NOFOLLOW || 0);
  let handle;
  try {
    handle = await open(filePath, flags, 0o600);
    await handle.writeFile(contents, "utf8");
    await handle.sync();
  } finally {
    await handle?.close();
  }
  if (process.platform !== "win32") await chmod(filePath, 0o600);
}

async function readStableSalt(historyRoot) {
  const saltPath = path.join(historyRoot, SALT_FILE_NAME);
  if (!isInsideOrEqual(saltPath, historyRoot) || saltPath === historyRoot) {
    fail("history-path-invalid", "The private fingerprint salt path is invalid.");
  }
  let entry;
  try {
    entry = await lstat(saltPath);
  } catch (error) {
    if (error?.code !== "ENOENT") throw error;
    const generated = `${randomBytes(32).toString("hex")}\n`;
    try {
      await writeExclusiveOwnerFile(saltPath, generated);
    } catch (writeError) {
      if (writeError?.code !== "EEXIST") throw writeError;
    }
    entry = await lstat(saltPath);
  }
  if (entry.isSymbolicLink() || !entry.isFile() || entry.size !== 65) {
    fail("history-salt-invalid", "The private repository fingerprint salt is invalid.");
  }
  if (process.platform !== "win32") await chmod(saltPath, 0o600);
  const salt = await readFile(saltPath, "utf8");
  if (!/^[a-f0-9]{64}\n$/.test(salt)) {
    fail("history-salt-invalid", "The private repository fingerprint salt is malformed.");
  }
  return Buffer.from(salt.trim(), "hex");
}

async function repositoryHistoryRoot(historyRoot, repoFingerprint, { create }) {
  const repositories = create
    ? await ensurePrivateDirectory(historyRoot, HISTORY_REPOSITORIES_DIRECTORY)
    : await requirePrivateDirectory(historyRoot, HISTORY_REPOSITORIES_DIRECTORY);
  if (!repositories) return null;
  const fingerprintName = safeHistoryName(
    repoFingerprint,
    REPO_FINGERPRINT_PATTERN,
    "Repository fingerprint"
  );
  const repositoryRoot = create
    ? await ensurePrivateDirectory(repositories, fingerprintName)
    : await requirePrivateDirectory(repositories, fingerprintName);
  if (!repositoryRoot) return null;
  const sessions = create
    ? await ensurePrivateDirectory(repositoryRoot, HISTORY_SESSIONS_DIRECTORY)
    : await requirePrivateDirectory(repositoryRoot, HISTORY_SESSIONS_DIRECTORY);
  if (!sessions) return null;
  return { repositoryRoot, sessions };
}

export async function createRunrailRepoFingerprint({
  historyRoot,
  repo,
  inspection = null
}) {
  const verifiedInspection = inspection
    ? verifyRunrailRepositoryInspection(inspection)
    : await inspectRunrailReviewRepository({ repo });
  if (
    repo !== undefined &&
    path.normalize(repo) !== verifiedInspection.repositoryPath &&
    await realpath(path.normalize(repo)) !== verifiedInspection.repositoryPath
  ) {
    fail("repository-inspection-mismatch", "The supplied repository and inspection do not match.");
  }
  await assertHistoryRootDisjointBeforeMutation(
    historyRoot,
    verifiedInspection.repositoryPath
  );
  const canonicalHistoryRoot = await ensureHistoryRoot(historyRoot, { create: true });
  if (pathsOverlap(canonicalHistoryRoot, verifiedInspection.repositoryPath)) {
    fail(
      "history-root-overlaps-source",
      "Review history must be stored outside the reviewed repository."
    );
  }
  const salt = await readStableSalt(canonicalHistoryRoot);
  const digest = createHmac("sha256", salt)
    .update(
      `runrail-review-repository-fingerprint-v1\0${verifiedInspection.repositoryPath}`,
      "utf8"
    )
    .digest("hex")
    .toUpperCase();
  return `RRF-${digest}`;
}

function bodyWithoutChecksum(value) {
  return Object.fromEntries(
    Object.entries(value).filter(([key]) => key !== "checksumSha256")
  );
}

export function verifyRunrailAuditV4(audit) {
  if (!isRecord(audit)) fail("audit-v4-invalid", "A Runrail schema-v4 audit is required.");
  exactKeys(
    audit,
    [
      "schemaVersion",
      "artifactType",
      "product",
      "runId",
      "passed",
      "preflightPassed",
      "scope",
      "source",
      "policy",
      "decision",
      "reviewContract",
      "verifier",
      "materialized",
      "boundaries",
      "checksumSha256"
    ],
    "Runrail audit",
    "audit-v4-invalid"
  );
  if (
    audit.schemaVersion !== 4 ||
    audit.artifactType !== "runrail-candidate-branch-review" ||
    audit.product !== RUNRAIL_REVIEW_SESSION.product ||
    typeof audit.runId !== "string" ||
    !/^RRV-[A-F0-9]{16}-[a-f0-9]{8}$/.test(audit.runId)
  ) {
    fail("audit-v4-invalid", "The Runrail audit identity is not schema v4.");
  }
  expectBoolean(audit.passed, "Audit passed", "audit-v4-invalid");
  expectBoolean(audit.preflightPassed, "Audit preflight", "audit-v4-invalid");
  if (audit.passed !== audit.preflightPassed) {
    fail("audit-v4-invalid", "The audit outcome fields must agree.");
  }
  exactKeys(
    audit.scope,
    [
      "policyAndSyntaxPreflight",
      "reviewContractEvaluated",
      "projectTestsExecuted",
      "semanticCorrectnessEvaluated",
      "securityReviewPerformed"
    ],
    "Audit scope",
    "audit-v4-invalid"
  );
  if (
    audit.scope.policyAndSyntaxPreflight !== true ||
    audit.scope.reviewContractEvaluated !== true ||
    audit.scope.projectTestsExecuted !== false ||
    audit.scope.semanticCorrectnessEvaluated !== false ||
    audit.scope.securityReviewPerformed !== false
  ) {
    fail("audit-v4-authority", "The audit scope boundary is invalid.");
  }
  exactKeys(
    audit.source,
    [
      "baseCommit",
      "candidateCommit",
      "sourceCheckoutUnchanged",
      "sourceApplyPerformed"
    ],
    "Audit source",
    "audit-v4-invalid"
  );
  expectCommit(audit.source.baseCommit, "Audit base commit", "audit-v4-invalid");
  expectCommit(audit.source.candidateCommit, "Audit candidate commit", "audit-v4-invalid");
  if (audit.source.baseCommit === audit.source.candidateCommit) {
    fail("audit-v4-invalid", "The audit base and candidate commits must differ.");
  }
  expectBoolean(
    audit.source.sourceCheckoutUnchanged,
    "Audit source checkout state",
    "audit-v4-invalid"
  );
  if (audit.source.sourceApplyPerformed !== false) {
    fail("audit-v4-authority", "The audit must not report source apply.");
  }
  if (!isRecord(audit.policy)) fail("audit-v4-invalid", "The audit policy is invalid.");
  expectInteger(
    audit.policy.changedFileCount,
    "Audit changed-file count",
    1,
    100,
    "audit-v4-invalid"
  );
  if (
    !Array.isArray(audit.policy.changedFiles) ||
    audit.policy.changedFiles.length !== audit.policy.changedFileCount
  ) {
    fail("audit-v4-invalid", "The audit changed-file summary is invalid.");
  }
  expectInteger(
    audit.policy.diffLineCount,
    "Audit diff-line count",
    1,
    5_000,
    "audit-v4-invalid"
  );
  expectSha256(audit.policy.diffSha256, "Audit diff checksum", "audit-v4-invalid");
  if (
    audit.policy.pathBoundaryPassed !== true ||
    audit.policy.arbitraryCommandAccepted !== false ||
    audit.policy.secretFindingCount !== 0 ||
    audit.policy.symlinkCount !== 0 ||
    audit.policy.specialEntryCount !== 0 ||
    audit.policy.binaryDiffCount !== 0
  ) {
    fail("audit-v4-authority", "The audit policy boundary is invalid.");
  }
  const changedPaths = new Set();
  for (const row of audit.policy.changedFiles) {
    if (
      !isRecord(row) ||
      !new Set(["A", "M", "D"]).has(row.status) ||
      typeof row.path !== "string" ||
      row.path.length < 1 ||
      row.path.length > 240 ||
      row.path.startsWith("/") ||
      row.path.includes("\\") ||
      row.path.split("/").some((part) => part === "" || part === "." || part === "..") ||
      changedPaths.has(row.path)
    ) {
      fail("audit-v4-invalid", "An audit changed-file row is invalid.");
    }
    changedPaths.add(row.path);
  }
  if (
    !isRecord(audit.reviewContract) ||
    audit.reviewContract.profile !== "runrail-review-contract-v1" ||
    audit.reviewContract.contractPath !== ".runrail/review-contract.json" ||
    audit.reviewContract.baselineBound !== true ||
    audit.reviewContract.candidateCouldWeakenBaseline !== false ||
    typeof audit.reviewContract.passed !== "boolean"
  ) {
    fail("audit-v4-invalid", "The audit review-contract evaluation is invalid.");
  }
  if (
    !isRecord(audit.decision) ||
    audit.decision.policyProfile !== "runrail-review-policy-v1" ||
    !new Set(["low", "medium", "high"]).has(audit.decision.riskLevel) ||
    !isRecord(audit.decision.findingCounts) ||
    !Array.isArray(audit.decision.findings) ||
    audit.decision.findings.length < 1 ||
    audit.decision.findings.length > 20 ||
    audit.decision.humanApprovalRequired !== true ||
    audit.decision.mergeReady !== false ||
    audit.decision.projectTestsRequired !== true
  ) {
    fail("audit-v4-invalid", "The audit deterministic decision is invalid.");
  }
  const observedCounts = { high: 0, medium: 0, info: 0 };
  const findingIds = new Set();
  for (const finding of audit.decision.findings) {
    if (
      !isRecord(finding) ||
      !FINDING_ID_PATTERN.test(String(finding.id || "")) ||
      !new Set(["high", "medium", "info"]).has(finding.severity) ||
      findingIds.has(finding.id)
    ) {
      fail("audit-v4-invalid", "An audit finding is invalid or duplicated.");
    }
    findingIds.add(finding.id);
    observedCounts[finding.severity] += 1;
  }
  for (const severity of ["high", "medium", "info"]) {
    expectInteger(
      audit.decision.findingCounts[severity],
      `Audit ${severity} finding count`,
      0,
      20,
      "audit-v4-invalid"
    );
    if (audit.decision.findingCounts[severity] !== observedCounts[severity]) {
      fail("audit-v4-invalid", "Audit finding counts do not match the finding rows.");
    }
  }
  const expectedRisk = observedCounts.high > 0
    ? "high"
    : observedCounts.medium > 0
      ? "medium"
      : "low";
  if (
    audit.decision.riskLevel !== expectedRisk ||
    audit.decision.specialistReviewRequired !== (expectedRisk === "high")
  ) {
    fail("audit-v4-invalid", "The audit risk fields do not match its findings.");
  }
  if (
    !isRecord(audit.verifier) ||
    typeof audit.verifier.passed !== "boolean" ||
    audit.verifier.arbitraryCommandAccepted !== false ||
    audit.verifier.repositoryCodeImported !== false ||
    audit.verifier.projectCodeExecuted !== false ||
    audit.verifier.externalPluginsEnabled !== false ||
    audit.verifier.rawOutputStored !== false
  ) {
    fail("audit-v4-authority", "The audit verifier boundary is invalid.");
  }
  const expectedPassed =
    audit.verifier.passed &&
    audit.reviewContract.passed &&
    audit.source.sourceCheckoutUnchanged;
  if (audit.passed !== expectedPassed) {
    fail("audit-v4-invalid", "The audit outcome does not match its preflight inputs.");
  }
  if (
    !isRecord(audit.boundaries) ||
    audit.boundaries.networkRequired !== false ||
    audit.boundaries.browserExecutionEnabled !== false ||
    audit.boundaries.repositoryUploadEnabled !== false ||
    audit.boundaries.automaticSourceApplyEnabled !== false ||
    audit.boundaries.learnedRuntimeAuthorityAdded !== false
  ) {
    fail("audit-v4-authority", "The audit expanded its authority boundary.");
  }
  expectSha256(audit.checksumSha256, "Audit checksum", "audit-v4-invalid");
  if (
    computeRunrailReviewSessionChecksum(bodyWithoutChecksum(audit)) !==
    audit.checksumSha256
  ) {
    fail("audit-v4-checksum", "The schema-v4 audit checksum is invalid.");
  }
  return audit;
}

function verifiedCoverageSummary(summary, code = "coverage-invalid") {
  exactKeys(
    summary,
    [
      "hunkCount",
      "reviewedCount",
      "needsRevisionCount",
      "unreviewedCount",
      "carriedForwardCount",
      "attentionComplete"
    ],
    "Review Coverage summary",
    code
  );
  for (const key of [
    "hunkCount",
    "reviewedCount",
    "needsRevisionCount",
    "unreviewedCount",
    "carriedForwardCount"
  ]) {
    expectInteger(summary[key], `Review Coverage ${key}`, 0, 2_000, code);
  }
  expectBoolean(summary.attentionComplete, "Review Coverage attention", code);
  if (
    summary.reviewedCount +
      summary.needsRevisionCount +
      summary.unreviewedCount !==
      summary.hunkCount ||
    summary.carriedForwardCount > summary.hunkCount ||
    summary.attentionComplete !==
      (
        summary.hunkCount > 0 &&
        summary.unreviewedCount === 0
      )
  ) {
    fail(code, "The Review Coverage summary is inconsistent.");
  }
  return summary;
}

export function verifyRunrailReviewCoverage(coverage, audit = null) {
  exactKeys(
    coverage,
    [
      "schemaVersion",
      "artifactType",
      "profile",
      "product",
      "coverageId",
      "source",
      "provenance",
      "summary",
      "hunks",
      "boundaries",
      "checksumSha256"
    ],
    "Review Coverage",
    "coverage-invalid"
  );
  if (
    coverage.schemaVersion !== 1 ||
    coverage.artifactType !== "runrail-hunk-continuity" ||
    coverage.profile !== "runrail-hunk-continuity-v1" ||
    coverage.product !== RUNRAIL_REVIEW_SESSION.product ||
    typeof coverage.coverageId !== "string" ||
    !/^COV-[A-F0-9]{24}$/.test(coverage.coverageId)
  ) {
    fail("coverage-invalid", "The Review Coverage identity is invalid.");
  }
  if (!isRecord(coverage.source)) {
    fail("coverage-invalid", "The Review Coverage source binding is invalid.");
  }
  expectSha256(
    coverage.source.auditChecksumSha256,
    "Review Coverage audit checksum",
    "coverage-invalid"
  );
  expectSha256(
    coverage.source.diffSha256,
    "Review Coverage diff checksum",
    "coverage-invalid"
  );
  if (
    audit &&
    (
      coverage.source.auditChecksumSha256 !== audit.checksumSha256 ||
      coverage.source.diffSha256 !== audit.policy.diffSha256
    )
  ) {
    fail("coverage-audit-mismatch", "Review Coverage belongs to a different audit.");
  }
  verifiedCoverageSummary(coverage.summary);
  if (!Array.isArray(coverage.hunks) || coverage.hunks.length !== coverage.summary.hunkCount) {
    fail("coverage-invalid", "Review Coverage hunk rows do not match the summary.");
  }
  const observed = {
    reviewedCount: 0,
    needsRevisionCount: 0,
    unreviewedCount: 0,
    carriedForwardCount: 0
  };
  const hunkIds = new Set();
  for (const hunk of coverage.hunks) {
    if (
      !isRecord(hunk) ||
      typeof hunk.hunkId !== "string" ||
      !/^HNK-[A-F0-9]{24}$/.test(hunk.hunkId) ||
      hunkIds.has(hunk.hunkId) ||
      !new Set(["reviewed", "needs-revision", "unreviewed"]).has(hunk.status) ||
      typeof hunk.carriedFromPrevious !== "boolean"
    ) {
      fail("coverage-invalid", "A Review Coverage hunk is invalid or duplicated.");
    }
    hunkIds.add(hunk.hunkId);
    if (hunk.status === "reviewed") observed.reviewedCount += 1;
    if (hunk.status === "needs-revision") observed.needsRevisionCount += 1;
    if (hunk.status === "unreviewed") observed.unreviewedCount += 1;
    if (hunk.carriedFromPrevious) observed.carriedForwardCount += 1;
  }
  for (const key of Object.keys(observed)) {
    if (observed[key] !== coverage.summary[key]) {
      fail("coverage-invalid", "Review Coverage hunk counts do not match the summary.");
    }
  }
  if (
    !isRecord(coverage.boundaries) ||
    coverage.boundaries.pathFree !== true ||
    coverage.boundaries.authority !== "none" ||
    coverage.boundaries.humanAttentionNotApproval !== true ||
    coverage.boundaries.mergeReady !== false ||
    coverage.boundaries.projectTestsExecuted !== false ||
    coverage.boundaries.networkUsed !== false ||
    coverage.boundaries.repositoryOpened !== false ||
    coverage.boundaries.sourceMutation !== false ||
    coverage.boundaries.originAuthenticated !== false
  ) {
    fail("coverage-authority", "Review Coverage expanded its authority boundary.");
  }
  expectSha256(coverage.checksumSha256, "Review Coverage checksum", "coverage-invalid");
  if (
    computeRunrailReviewSessionChecksum(bodyWithoutChecksum(coverage)) !==
    coverage.checksumSha256
  ) {
    fail("coverage-checksum", "The Review Coverage checksum is invalid.");
  }
  return coverage;
}

function dispositionIdentity(body) {
  return `RSD-${computeRunrailReviewSessionChecksum(body)
    .slice(0, 24)
    .toUpperCase()}`;
}

export function buildRunrailReviewDisposition({
  reviewId,
  repoFingerprint,
  auditChecksumSha256,
  findingId,
  kind,
  reason = null,
  owner = null,
  expiresAt = null,
  createdAt = new Date().toISOString(),
  previousDispositionChecksumSha256 = null
}) {
  validateId(reviewId, REVIEW_ID_PATTERN, "Review ID", "disposition-invalid");
  validateId(
    repoFingerprint,
    REPO_FINGERPRINT_PATTERN,
    "Repository fingerprint",
    "disposition-invalid"
  );
  expectSha256(auditChecksumSha256, "Disposition audit checksum", "disposition-invalid");
  validateId(findingId, FINDING_ID_PATTERN, "Disposition finding ID", "disposition-invalid");
  if (!dispositionKindSet.has(kind)) {
    fail("disposition-invalid", "The review disposition kind is unsupported.");
  }
  canonicalTimestamp(createdAt, "Disposition createdAt", "disposition-invalid");
  if (
    previousDispositionChecksumSha256 !== null &&
    !SHA256_PATTERN.test(String(previousDispositionChecksumSha256))
  ) {
    fail("disposition-invalid", "The previous disposition checksum is invalid.");
  }
  let normalizedReason = reason;
  let normalizedOwner = owner;
  let normalizedExpiresAt = expiresAt;
  if (kind === "accepted-exception") {
    normalizedReason = boundedString(
      reason,
      "Accepted-exception reason",
      1,
      500,
      "disposition-invalid"
    );
    normalizedOwner = boundedString(
      owner,
      "Accepted-exception owner",
      1,
      120,
      "disposition-invalid"
    );
    normalizedExpiresAt = canonicalTimestamp(
      expiresAt,
      "Accepted-exception expiresAt",
      "disposition-invalid"
    );
    if (normalizedExpiresAt <= createdAt) {
      fail(
        "disposition-expiry-invalid",
        "An accepted exception must expire after it is created."
      );
    }
  } else {
    if (reason !== null) {
      normalizedReason = boundedString(
        reason,
        "Disposition reason",
        1,
        500,
        "disposition-invalid"
      );
    }
    if (owner !== null) {
      normalizedOwner = boundedString(
        owner,
        "Disposition owner",
        1,
        120,
        "disposition-invalid"
      );
    }
    if (expiresAt !== null) {
      fail(
        "disposition-expiry-invalid",
        "Only accepted exceptions may have an expiry."
      );
    }
  }
  const identityBody = {
    reviewId,
    repoFingerprint,
    auditChecksumSha256,
    findingId,
    kind,
    reason: normalizedReason,
    owner: normalizedOwner,
    expiresAt: normalizedExpiresAt,
    createdAt,
    previousDispositionChecksumSha256
  };
  const dispositionId = dispositionIdentity(identityBody);
  const body = {
    schemaVersion: RUNRAIL_REVIEW_SESSION.schemaVersion,
    artifactType: RUNRAIL_REVIEW_SESSION.dispositionArtifactType,
    profile: RUNRAIL_REVIEW_SESSION.profile,
    product: RUNRAIL_REVIEW_SESSION.product,
    dispositionId,
    ...identityBody
  };
  const disposition = {
    ...body,
    checksumSha256: computeRunrailReviewSessionChecksum(body)
  };
  return disposition;
}

export function verifyRunrailReviewDisposition(disposition) {
  exactKeys(
    disposition,
    [
      "schemaVersion",
      "artifactType",
      "profile",
      "product",
      "dispositionId",
      "reviewId",
      "repoFingerprint",
      "auditChecksumSha256",
      "findingId",
      "kind",
      "reason",
      "owner",
      "expiresAt",
      "createdAt",
      "previousDispositionChecksumSha256",
      "checksumSha256"
    ],
    "Review disposition",
    "disposition-invalid"
  );
  if (
    disposition.schemaVersion !== RUNRAIL_REVIEW_SESSION.schemaVersion ||
    disposition.artifactType !== RUNRAIL_REVIEW_SESSION.dispositionArtifactType ||
    disposition.profile !== RUNRAIL_REVIEW_SESSION.profile ||
    disposition.product !== RUNRAIL_REVIEW_SESSION.product
  ) {
    fail("disposition-invalid", "The review disposition identity is invalid.");
  }
  validateId(
    disposition.dispositionId,
    DISPOSITION_ID_PATTERN,
    "Disposition ID",
    "disposition-invalid"
  );
  const rebuilt = buildRunrailReviewDisposition({
    reviewId: disposition.reviewId,
    repoFingerprint: disposition.repoFingerprint,
    auditChecksumSha256: disposition.auditChecksumSha256,
    findingId: disposition.findingId,
    kind: disposition.kind,
    reason: disposition.reason,
    owner: disposition.owner,
    expiresAt: disposition.expiresAt,
    createdAt: disposition.createdAt,
    previousDispositionChecksumSha256:
      disposition.previousDispositionChecksumSha256
  });
  if (
    rebuilt.dispositionId !== disposition.dispositionId ||
    rebuilt.checksumSha256 !== disposition.checksumSha256
  ) {
    fail("disposition-checksum", "The review disposition checksum is invalid.");
  }
  return disposition;
}

export function isRunrailReviewDispositionActive(
  disposition,
  { now = new Date() } = {}
) {
  verifyRunrailReviewDisposition(disposition);
  const current = normalizeNow(now);
  return (
    disposition.kind === "accepted-exception" &&
    new Date(disposition.expiresAt).getTime() > current.getTime()
  );
}

function latestDispositionsByFinding(dispositions, {
  auditChecksumSha256 = null,
  reviewId = null
} = {}) {
  const latest = new Map();
  for (const disposition of [...dispositions].sort(compareDispositionsOldestFirst)) {
    verifyRunrailReviewDisposition(disposition);
    if (
      (auditChecksumSha256 &&
        disposition.auditChecksumSha256 !== auditChecksumSha256) ||
      (reviewId && disposition.reviewId !== reviewId)
    ) {
      continue;
    }
    latest.set(disposition.findingId, disposition);
  }
  return latest;
}

function deriveVerdictFromEvidence({
  preflightPassed,
  contractPassed,
  highFindingIds,
  mediumFindingIds,
  coverageSummary,
  dispositions,
  auditChecksumSha256,
  reviewId,
  now
}) {
  const latest = latestDispositionsByFinding(dispositions, {
    auditChecksumSha256,
    reviewId
  });
  const activeAcceptedExceptionIds = [...latest.entries()]
    .filter(([, disposition]) =>
      isRunrailReviewDispositionActive(disposition, { now })
    )
    .map(([findingId]) => findingId)
    .filter((findingId) =>
      highFindingIds.includes(findingId) ||
      mediumFindingIds.includes(findingId)
    )
    .sort(compareText);
  const accepted = new Set(activeAcceptedExceptionIds);
  const unresolvedHighFindingIds = highFindingIds
    .filter((findingId) => !accepted.has(findingId))
    .sort(compareText);
  const unresolvedMediumFindingIds = mediumFindingIds
    .filter((findingId) => !accepted.has(findingId))
    .sort(compareText);

  const blocked =
    !preflightPassed ||
    !contractPassed ||
    coverageSummary.needsRevisionCount > 0 ||
    unresolvedHighFindingIds.length > 0;
  const needsAttention =
    !blocked &&
    (
      unresolvedMediumFindingIds.length > 0 ||
      coverageSummary.unreviewedCount > 0
    );
  const status = blocked
    ? "blocked"
    : needsAttention
      ? "needs-attention"
      : "ready-for-human-decision";

  const actions = [];
  const addAction = (id, count) => {
    if (
      count < 1 ||
      actions.length >= RUNRAIL_REVIEW_SESSION.maximumTopActions
    ) {
      return;
    }
    actions.push({ id, label: topActionDefinitions[id].label, count });
  };
  if (!preflightPassed) addAction("RESOLVE_PREFLIGHT_BLOCKERS", 1);
  if (!contractPassed) addAction("RESOLVE_REVIEW_CONTRACT", 1);
  addAction(
    "REVISE_FLAGGED_HUNKS",
    coverageSummary.needsRevisionCount
  );
  addAction("RESOLVE_HIGH_FINDINGS", unresolvedHighFindingIds.length);
  addAction("COMPLETE_REVIEW_COVERAGE", coverageSummary.unreviewedCount);
  addAction("ADDRESS_MEDIUM_FINDINGS", unresolvedMediumFindingIds.length);
  if (status === "ready-for-human-decision") {
    addAction("RECORD_HUMAN_DECISION", 1);
  }
  return {
    status,
    activeAcceptedExceptionFindingIds: activeAcceptedExceptionIds,
    unresolvedHighFindingIds,
    unresolvedMediumFindingIds,
    topActions: actions
  };
}

export function deriveRunrailReviewSessionVerdict({
  audit,
  coverage = null,
  coverageSummary = coverage?.summary,
  dispositions = [],
  reviewId = null,
  now = new Date()
}) {
  verifyRunrailAuditV4(audit);
  if (coverage) verifyRunrailReviewCoverage(coverage, audit);
  verifiedCoverageSummary(coverageSummary);
  if (!Array.isArray(dispositions) || dispositions.length > RUNRAIL_REVIEW_SESSION.maximumDispositionsPerSession) {
    fail("disposition-boundary", "Review verdict input contains too many dispositions.");
  }
  if (reviewId !== null) {
    validateId(reviewId, REVIEW_ID_PATTERN, "Review ID", "review-session-invalid");
  }
  const highFindingIds = audit.decision.findings
    .filter((finding) => finding.severity === "high")
    .map((finding) => finding.id);
  const mediumFindingIds = audit.decision.findings
    .filter((finding) => finding.severity === "medium")
    .map((finding) => finding.id);
  return deriveVerdictFromEvidence({
    preflightPassed: audit.preflightPassed,
    contractPassed: audit.reviewContract.passed,
    highFindingIds,
    mediumFindingIds,
    coverageSummary,
    dispositions,
    auditChecksumSha256: audit.checksumSha256,
    reviewId,
    now
  });
}

function sessionIdentity({
  repoFingerprint,
  parentReviewId,
  createdAt,
  baseCommit,
  candidateCommit,
  auditChecksumSha256,
  coverageChecksumSha256
}) {
  return `RRS-${computeRunrailReviewSessionChecksum({
    repoFingerprint,
    parentReviewId,
    createdAt,
    baseCommit,
    candidateCommit,
    auditChecksumSha256,
    coverageChecksumSha256
  })
    .slice(0, 24)
    .toUpperCase()}`;
}

function verifyFindingIds(value, label, expectedCount, code = "review-session-invalid") {
  if (!Array.isArray(value) || value.length !== expectedCount) {
    fail(code, `${label} does not match its count.`);
  }
  const seen = new Set();
  let prior = null;
  for (const findingId of value) {
    validateId(findingId, FINDING_ID_PATTERN, label, code);
    if (
      seen.has(findingId) ||
      (prior !== null && compareText(prior, findingId) >= 0)
    ) {
      fail(code, `${label} must be unique and sorted.`);
    }
    seen.add(findingId);
    prior = findingId;
  }
}

function verifyVerdict(verdict, evidence, code = "review-session-invalid") {
  exactKeys(
    verdict,
    [
      "status",
      "activeAcceptedExceptionFindingIds",
      "unresolvedHighFindingIds",
      "unresolvedMediumFindingIds",
      "topActions"
    ],
    "Review verdict",
    code
  );
  if (!verdictSet.has(verdict.status)) fail(code, "The review verdict is invalid.");
  if (
    !Array.isArray(verdict.activeAcceptedExceptionFindingIds) ||
    verdict.activeAcceptedExceptionFindingIds.length !== 0
  ) {
    fail(code, "Immutable session records must begin without accepted exceptions.");
  }
  verifyFindingIds(
    verdict.unresolvedHighFindingIds,
    "Unresolved high finding IDs",
    evidence.findingIds.high.length,
    code
  );
  verifyFindingIds(
    verdict.unresolvedMediumFindingIds,
    "Unresolved medium finding IDs",
    evidence.findingIds.medium.length,
    code
  );
  if (
    !Array.isArray(verdict.topActions) ||
    verdict.topActions.length < 1 ||
    verdict.topActions.length > RUNRAIL_REVIEW_SESSION.maximumTopActions
  ) {
    fail(code, "The review verdict top actions are invalid.");
  }
  const actionIds = new Set();
  for (const action of verdict.topActions) {
    exactKeys(action, ["id", "label", "count"], "Top action", code);
    if (
      !topActionDefinitions[action.id] ||
      action.label !== topActionDefinitions[action.id].label ||
      actionIds.has(action.id)
    ) {
      fail(code, "A review top action is invalid or duplicated.");
    }
    expectInteger(action.count, "Top action count", 1, 2_000, code);
    actionIds.add(action.id);
  }
  const expected = deriveVerdictFromEvidence({
    preflightPassed: evidence.preflightPassed,
    contractPassed: evidence.contractPassed,
    highFindingIds: evidence.findingIds.high,
    mediumFindingIds: evidence.findingIds.medium,
    coverageSummary: evidence.coverageSummary,
    dispositions: [],
    auditChecksumSha256: evidence.auditChecksumSha256,
    reviewId: null,
    now: new Date(0)
  });
  if (stableRunrailReviewSessionJson(expected) !== stableRunrailReviewSessionJson(verdict)) {
    fail(code, "The immutable review verdict does not match its evidence.");
  }
}

export function verifyRunrailReviewSession(session) {
  exactKeys(
    session,
    [
      "schemaVersion",
      "artifactType",
      "profile",
      "product",
      "reviewId",
      "repoFingerprint",
      "parentReviewId",
      "createdAt",
      "local",
      "discovery",
      "evidence",
      "verdict",
      "boundaries",
      "checksumSha256"
    ],
    "Review session"
  );
  if (
    session.schemaVersion !== RUNRAIL_REVIEW_SESSION.schemaVersion ||
    session.artifactType !== RUNRAIL_REVIEW_SESSION.artifactType ||
    session.profile !== RUNRAIL_REVIEW_SESSION.profile ||
    session.product !== RUNRAIL_REVIEW_SESSION.product
  ) {
    fail("review-session-invalid", "The review session identity is invalid.");
  }
  validateId(session.reviewId, REVIEW_ID_PATTERN, "Review ID");
  validateId(session.repoFingerprint, REPO_FINGERPRINT_PATTERN, "Repository fingerprint");
  if (session.parentReviewId !== null) {
    validateId(session.parentReviewId, REVIEW_ID_PATTERN, "Parent review ID");
    if (session.parentReviewId === session.reviewId) {
      fail("review-session-invalid", "A review session cannot parent itself.");
    }
  }
  canonicalTimestamp(session.createdAt, "Review session createdAt");
  exactKeys(
    session.local,
    [
      "repositoryPath",
      "currentBranch",
      "detachedHead",
      "baseRef",
      "baseCommit",
      "candidateRef",
      "candidateCommit",
      "artifactRootPath",
      "auditPath",
      "coveragePath"
    ],
    "Review session local paths"
  );
  for (const [key, label] of [
    ["repositoryPath", "Repository path"],
    ["artifactRootPath", "Artifact root path"],
    ["auditPath", "Audit path"],
    ["coveragePath", "Coverage path"]
  ]) {
    absoluteLocalPath(session.local[key], label);
  }
  if (
    !isInsideOrEqual(session.local.auditPath, session.local.artifactRootPath) ||
    !isInsideOrEqual(session.local.coveragePath, session.local.artifactRootPath)
  ) {
    fail("review-session-invalid", "Review artifact paths escaped their artifact root.");
  }
  if (session.local.currentBranch !== null) {
    validateRunrailReviewRef(session.local.currentBranch, "Current branch");
  }
  expectBoolean(session.local.detachedHead, "Detached HEAD");
  if (session.local.detachedHead !== (session.local.currentBranch === null)) {
    fail("review-session-invalid", "The review session detached-HEAD fields disagree.");
  }
  validateRunrailReviewRef(session.local.baseRef, "Base ref");
  validateRunrailReviewRef(session.local.candidateRef, "Candidate ref");
  expectCommit(session.local.baseCommit, "Base commit");
  expectCommit(session.local.candidateCommit, "Candidate commit");
  if (session.local.baseCommit === session.local.candidateCommit) {
    fail("review-session-invalid", "The session base and candidate commits must differ.");
  }
  exactKeys(
    session.discovery,
    [
      "defaultBaseCandidates",
      "candidateAheadCommitCount",
      "candidateAheadCommitCountCapped",
      "languageStack",
      "sourceStateChecksumSha256"
    ],
    "Review session discovery"
  );
  if (
    !Array.isArray(session.discovery.defaultBaseCandidates) ||
    session.discovery.defaultBaseCandidates.length > MAX_DEFAULT_BASES
  ) {
    fail("review-session-invalid", "Session default bases exceed their boundary.");
  }
  for (const base of session.discovery.defaultBaseCandidates) {
    exactKeys(base, ["ref", "commit", "source"], "Session default base");
    validateRunrailReviewRef(base.ref, "Session default base");
    expectCommit(base.commit, "Session default base commit");
  }
  expectInteger(
    session.discovery.candidateAheadCommitCount,
    "Candidate ahead count",
    1,
    MAX_AHEAD_COMMITS
  );
  expectBoolean(
    session.discovery.candidateAheadCommitCountCapped,
    "Candidate ahead-count cap"
  );
  if (
    session.discovery.candidateAheadCommitCountCapped !==
      (session.discovery.candidateAheadCommitCount === MAX_AHEAD_COMMITS)
  ) {
    fail("review-session-invalid", "The candidate ahead-count cap is inconsistent.");
  }
  verifyLanguageStack(session.discovery.languageStack);
  expectSha256(
    session.discovery.sourceStateChecksumSha256,
    "Source state checksum"
  );
  exactKeys(
    session.evidence,
    [
      "auditSchemaVersion",
      "auditRunId",
      "auditChecksumSha256",
      "auditFileSha256",
      "coverageChecksumSha256",
      "coverageFileSha256",
      "preflightPassed",
      "contractPassed",
      "findingCounts",
      "findingIds",
      "coverageSummary"
    ],
    "Review session evidence"
  );
  if (
    session.evidence.auditSchemaVersion !== 4 ||
    typeof session.evidence.auditRunId !== "string" ||
    !/^RRV-[A-F0-9]{16}-[a-f0-9]{8}$/.test(session.evidence.auditRunId)
  ) {
    fail("review-session-invalid", "The session audit identity is invalid.");
  }
  for (const key of [
    "auditChecksumSha256",
    "auditFileSha256",
    "coverageChecksumSha256",
    "coverageFileSha256"
  ]) {
    expectSha256(session.evidence[key], `Session ${key}`);
  }
  expectBoolean(session.evidence.preflightPassed, "Session preflight");
  expectBoolean(session.evidence.contractPassed, "Session contract");
  exactKeys(
    session.evidence.findingCounts,
    ["high", "medium", "info"],
    "Session finding counts"
  );
  exactKeys(
    session.evidence.findingIds,
    ["high", "medium", "info"],
    "Session finding IDs"
  );
  for (const severity of ["high", "medium", "info"]) {
    expectInteger(
      session.evidence.findingCounts[severity],
      `Session ${severity} finding count`,
      0,
      20
    );
    verifyFindingIds(
      session.evidence.findingIds[severity],
      `Session ${severity} finding IDs`,
      session.evidence.findingCounts[severity]
    );
  }
  const allFindingIds = [
    ...session.evidence.findingIds.high,
    ...session.evidence.findingIds.medium,
    ...session.evidence.findingIds.info
  ];
  if (new Set(allFindingIds).size !== allFindingIds.length) {
    fail("review-session-invalid", "Session finding IDs must be unique across severities.");
  }
  verifiedCoverageSummary(session.evidence.coverageSummary, "review-session-invalid");
  verifyVerdict(session.verdict, session.evidence);
  exactKeys(
    session.boundaries,
    [
      "localOnly",
      "authority",
      "networkUsed",
      "modelUsed",
      "providerUsed",
      "projectTestsExecuted",
      "patchApplied",
      "repositoryContentIncluded",
      "patchContentIncluded",
      "rawCommandOutputIncluded",
      "sourceMutationPerformed"
    ],
    "Review session boundaries"
  );
  if (
    session.boundaries.localOnly !== true ||
    session.boundaries.authority !== "none" ||
    session.boundaries.networkUsed !== false ||
    session.boundaries.modelUsed !== false ||
    session.boundaries.providerUsed !== false ||
    session.boundaries.projectTestsExecuted !== false ||
    session.boundaries.patchApplied !== false ||
    session.boundaries.repositoryContentIncluded !== false ||
    session.boundaries.patchContentIncluded !== false ||
    session.boundaries.rawCommandOutputIncluded !== false ||
    session.boundaries.sourceMutationPerformed !== false
  ) {
    fail("review-session-authority", "The review session expanded its authority boundary.");
  }
  const expectedReviewId = sessionIdentity({
    repoFingerprint: session.repoFingerprint,
    parentReviewId: session.parentReviewId,
    createdAt: session.createdAt,
    baseCommit: session.local.baseCommit,
    candidateCommit: session.local.candidateCommit,
    auditChecksumSha256: session.evidence.auditChecksumSha256,
    coverageChecksumSha256: session.evidence.coverageChecksumSha256
  });
  if (expectedReviewId !== session.reviewId) {
    fail("review-session-invalid", "The review session ID does not match its immutable identity.");
  }
  expectSha256(session.checksumSha256, "Review session checksum");
  if (
    computeRunrailReviewSessionChecksum(bodyWithoutChecksum(session)) !==
    session.checksumSha256
  ) {
    fail("review-session-checksum", "The review session checksum is invalid.");
  }
  return session;
}

async function readBoundedRegularFile(filePath, maximumBytes, code) {
  const normalized = absoluteLocalPath(filePath, "Artifact path", code);
  let entry;
  try {
    entry = await lstat(normalized);
  } catch {
    fail(code, "A required review artifact does not exist.");
  }
  if (entry.isSymbolicLink() || !entry.isFile()) {
    fail(code, "Review artifacts must be regular non-symlink files.");
  }
  if (entry.size < 2 || entry.size > maximumBytes) {
    fail(code, "A review artifact exceeds its size boundary.");
  }
  const canonical = await realpath(normalized);
  if (canonical !== normalized) {
    fail(code, "Review artifact paths must not traverse symbolic links.");
  }
  const flags = fsConstants.O_RDONLY | (fsConstants.O_NOFOLLOW || 0);
  const handle = await open(normalized, flags);
  try {
    const openedEntry = await handle.stat();
    if (!openedEntry.isFile() || openedEntry.size !== entry.size) {
      fail(code, "A review artifact changed while it was opened.");
    }
    const bytes = await handle.readFile();
    if (bytes.length !== entry.size) {
      fail(code, "A review artifact changed while it was read.");
    }
    return { path: canonical, bytes };
  } finally {
    await handle.close();
  }
}

function parseJsonArtifact(bytes, label, code) {
  let value;
  try {
    value = JSON.parse(bytes.toString("utf8"));
  } catch {
    fail(code, `${label} must contain valid JSON.`);
  }
  return value;
}

async function readReviewArtifacts({ auditPath, coveragePath }) {
  const normalizedAuditPath = absoluteLocalPath(auditPath, "Audit path", "artifact-path-invalid");
  const artifactRootInput = path.dirname(normalizedAuditPath);
  const rootEntry = await lstat(artifactRootInput).catch(() => null);
  if (!rootEntry || rootEntry.isSymbolicLink() || !rootEntry.isDirectory()) {
    fail("artifact-root-invalid", "The review artifact root must be a real directory.");
  }
  const artifactRootPath = await realpath(artifactRootInput);
  if (artifactRootPath !== artifactRootInput) {
    fail("artifact-root-symlink", "The review artifact root must not traverse a symbolic link.");
  }
  const normalizedCoveragePath = absoluteLocalPath(
    coveragePath,
    "Coverage path",
    "artifact-path-invalid"
  );
  if (
    !isInsideOrEqual(normalizedAuditPath, artifactRootPath) ||
    !isInsideOrEqual(normalizedCoveragePath, artifactRootPath)
  ) {
    fail("artifact-path-containment", "Review artifacts must remain inside the audit artifact root.");
  }
  const auditFile = await readBoundedRegularFile(
    normalizedAuditPath,
    MAX_AUDIT_BYTES,
    "audit-artifact-invalid"
  );
  const coverageFile = await readBoundedRegularFile(
    normalizedCoveragePath,
    MAX_COVERAGE_BYTES,
    "coverage-artifact-invalid"
  );
  const audit = verifyRunrailAuditV4(
    parseJsonArtifact(auditFile.bytes, "Audit artifact", "audit-artifact-invalid")
  );
  const coverage = verifyRunrailReviewCoverage(
    parseJsonArtifact(
      coverageFile.bytes,
      "Review Coverage artifact",
      "coverage-artifact-invalid"
    ),
    audit
  );
  return {
    artifactRootPath,
    auditPath: auditFile.path,
    coveragePath: coverageFile.path,
    audit,
    coverage,
    auditFileSha256: sha256(auditFile.bytes),
    coverageFileSha256: sha256(coverageFile.bytes)
  };
}

function relationToTarget(session, target) {
  if (session.repoFingerprint !== target.repoFingerprint) return null;
  if (session.local.candidateCommit === target.baseCommit) return "linear-successor";
  if (session.local.baseCommit === target.baseCommit) return "same-base";
  return null;
}

export function findLatestRelatedPriorSession(sessionsOrOptions, targetInput = null) {
  const sessions = Array.isArray(sessionsOrOptions)
    ? sessionsOrOptions
    : sessionsOrOptions?.sessions;
  const target = Array.isArray(sessionsOrOptions)
    ? targetInput
    : sessionsOrOptions;
  if (!Array.isArray(sessions) || !isRecord(target)) {
    fail("review-history-invalid", "Related-session lookup requires history rows and a target.");
  }
  validateId(
    target.repoFingerprint,
    REPO_FINGERPRINT_PATTERN,
    "Target repository fingerprint",
    "review-history-invalid"
  );
  expectCommit(target.baseCommit, "Target base commit", "review-history-invalid");
  expectCommit(target.candidateCommit, "Target candidate commit", "review-history-invalid");
  if (target.createdAt !== undefined) {
    canonicalTimestamp(target.createdAt, "Target createdAt", "review-history-invalid");
  }
  const currentReviewId = target.reviewId || null;
  return [...sessions]
    .map(verifyRunrailReviewSession)
    .filter((session) => session.reviewId !== currentReviewId)
    .filter((session) => !target.createdAt || session.createdAt < target.createdAt)
    .filter((session) => relationToTarget(session, target))
    .sort(compareSessionsNewestFirst)
    .at(0) || null;
}

async function readSessionFile(sessionPath) {
  const entry = await lstat(sessionPath).catch(() => null);
  if (!entry || entry.isSymbolicLink() || !entry.isFile() || entry.size > MAX_AUDIT_BYTES) {
    fail("review-history-invalid", "A stored review session file is invalid.");
  }
  const contents = await readFile(sessionPath, "utf8");
  let value;
  try {
    value = JSON.parse(contents);
  } catch {
    fail("review-history-invalid", "A stored review session is not valid JSON.");
  }
  const session = verifyRunrailReviewSession(value);
  if (stableRunrailReviewSessionJson(session) !== contents) {
    fail("review-history-invalid", "A stored review session is not canonical JSON.");
  }
  return session;
}

async function listSessionsInternal(historyRoot, repoFingerprint) {
  const repositoryHistory = await repositoryHistoryRoot(
    historyRoot,
    repoFingerprint,
    { create: false }
  );
  if (!repositoryHistory) return [];
  const entries = await readdir(repositoryHistory.sessions, { withFileTypes: true });
  if (entries.length > MAX_HISTORY_DIRECTORIES) {
    fail("review-history-boundary", "Stored review history exceeds its directory boundary.");
  }
  const sessions = [];
  for (const entry of entries) {
    if (
      !entry.isDirectory() ||
      entry.isSymbolicLink() ||
      !REVIEW_ID_PATTERN.test(entry.name)
    ) {
      fail("review-history-invalid", "Review history contains an unsupported entry.");
    }
    const sessionRoot = path.join(repositoryHistory.sessions, entry.name);
    const canonicalSessionRoot = await realpath(sessionRoot);
    if (!isInsideOrEqual(canonicalSessionRoot, repositoryHistory.sessions)) {
      fail("review-history-invalid", "A review session directory escaped history.");
    }
    const session = await readSessionFile(
      path.join(canonicalSessionRoot, SESSION_FILE_NAME)
    );
    if (
      session.reviewId !== entry.name ||
      session.repoFingerprint !== repoFingerprint
    ) {
      fail("review-history-invalid", "A stored session does not match its history path.");
    }
    sessions.push(session);
  }
  return sessions.sort(compareSessionsNewestFirst);
}

export async function listRunrailReviewSessions({
  historyRoot,
  repoFingerprint,
  limit = 50
}) {
  validateId(
    repoFingerprint,
    REPO_FINGERPRINT_PATTERN,
    "Repository fingerprint",
    "review-history-invalid"
  );
  expectInteger(
    limit,
    "Review history limit",
    1,
    RUNRAIL_REVIEW_SESSION.maximumHistoryEntries,
    "review-history-limit"
  );
  const canonicalHistoryRoot = await ensureHistoryRoot(historyRoot, { create: false });
  if (!canonicalHistoryRoot) return [];
  return (await listSessionsInternal(canonicalHistoryRoot, repoFingerprint)).slice(0, limit);
}

async function listReviewRepositoryFingerprints(historyRoot) {
  const canonicalHistoryRoot = await ensureHistoryRoot(historyRoot, { create: false });
  if (!canonicalHistoryRoot) return { canonicalHistoryRoot: null, repoFingerprints: [] };
  const repositories = await requirePrivateDirectory(
    canonicalHistoryRoot,
    HISTORY_REPOSITORIES_DIRECTORY
  );
  if (!repositories) {
    return { canonicalHistoryRoot, repoFingerprints: [] };
  }
  const entries = await readdir(repositories, { withFileTypes: true });
  if (entries.length > MAX_HISTORY_DIRECTORIES) {
    fail("review-history-boundary", "Stored repository history exceeds its directory boundary.");
  }
  const repoFingerprints = [];
  for (const entry of entries) {
    if (
      !entry.isDirectory() ||
      entry.isSymbolicLink() ||
      !REPO_FINGERPRINT_PATTERN.test(entry.name)
    ) {
      fail("review-history-invalid", "Review history contains an unsupported repository entry.");
    }
    const canonicalRepositoryRoot = await realpath(path.join(repositories, entry.name));
    if (!isInsideOrEqual(canonicalRepositoryRoot, repositories)) {
      fail("review-history-invalid", "A repository history directory escaped its parent.");
    }
    repoFingerprints.push(entry.name);
  }
  return {
    canonicalHistoryRoot,
    repoFingerprints: repoFingerprints.sort(compareText)
  };
}

export async function listAllRunrailReviewSessions({
  historyRoot,
  limit = RUNRAIL_REVIEW_SESSION.maximumHistoryEntries
}) {
  expectInteger(
    limit,
    "Review history limit",
    1,
    RUNRAIL_REVIEW_SESSION.maximumHistoryEntries,
    "review-history-limit"
  );
  const { canonicalHistoryRoot, repoFingerprints } =
    await listReviewRepositoryFingerprints(historyRoot);
  if (!canonicalHistoryRoot) return [];
  const sessions = [];
  for (const repoFingerprint of repoFingerprints) {
    sessions.push(
      ...(await listSessionsInternal(canonicalHistoryRoot, repoFingerprint))
    );
  }
  return sessions.sort(compareSessionsNewestFirst).slice(0, limit);
}

export async function findRunrailReviewSession({
  historyRoot,
  reviewId
}) {
  validateId(reviewId, REVIEW_ID_PATTERN, "Review ID", "review-history-invalid");
  const { canonicalHistoryRoot, repoFingerprints } =
    await listReviewRepositoryFingerprints(historyRoot);
  if (!canonicalHistoryRoot) {
    fail("review-session-not-found", "The requested review session does not exist.");
  }
  let match = null;
  for (const repoFingerprint of repoFingerprints) {
    const sessions = await listSessionsInternal(
      canonicalHistoryRoot,
      repoFingerprint
    );
    const candidate = sessions.find((session) => session.reviewId === reviewId);
    if (!candidate) continue;
    if (match) {
      fail("review-history-invalid", "The review session ID is duplicated.");
    }
    match = candidate;
  }
  if (!match) {
    fail("review-session-not-found", "The requested review session does not exist.");
  }
  return match;
}

export async function loadRunrailReviewSession({
  historyRoot,
  repoFingerprint,
  reviewId
}) {
  validateId(
    repoFingerprint,
    REPO_FINGERPRINT_PATTERN,
    "Repository fingerprint",
    "review-history-invalid"
  );
  validateId(reviewId, REVIEW_ID_PATTERN, "Review ID", "review-history-invalid");
  const canonicalHistoryRoot = await ensureHistoryRoot(historyRoot, { create: false });
  if (!canonicalHistoryRoot) {
    fail("review-session-not-found", "The requested review session does not exist.");
  }
  const repositoryHistory = await repositoryHistoryRoot(
    canonicalHistoryRoot,
    repoFingerprint,
    { create: false }
  );
  if (!repositoryHistory) {
    fail("review-session-not-found", "The requested review session does not exist.");
  }
  const sessionRoot = await requirePrivateDirectory(
    repositoryHistory.sessions,
    reviewId
  );
  if (!sessionRoot) {
    fail("review-session-not-found", "The requested review session does not exist.");
  }
  const session = await readSessionFile(path.join(sessionRoot, SESSION_FILE_NAME));
  if (
    session.reviewId !== reviewId ||
    session.repoFingerprint !== repoFingerprint
  ) {
    fail("review-history-invalid", "The stored session identity does not match its path.");
  }
  return session;
}

async function resolveSelectedCandidate(repo, baseCommit, candidateInput) {
  const candidateRefInput = validateRunrailReviewRef(
    candidateInput,
    "Candidate local branch"
  );
  const candidateRef = candidateRefInput.startsWith("refs/heads/")
    ? candidateRefInput.slice("refs/heads/".length)
    : candidateRefInput;
  validateRunrailReviewRef(candidateRef, "Candidate local branch");
  const branches = await listLocalBranches(repo);
  const candidate = branches.find((entry) => entry.ref === candidateRef);
  if (!candidate) {
    fail("candidate-local-branch-required", "The candidate must be an existing local branch.");
  }
  if (candidate.commit === baseCommit || !(await isAncestor(repo, baseCommit, candidate.commit))) {
    fail("candidate-not-ahead", "The candidate local branch must be ahead of the confirmed base.");
  }
  const distance = await aheadCommitCount(repo, baseCommit, candidate.commit);
  if (distance.aheadCommitCount < 1) {
    fail("candidate-not-ahead", "The candidate local branch must be ahead of the confirmed base.");
  }
  return { ...candidate, ...distance };
}

export async function createRunrailReviewSession({
  repo,
  historyRoot,
  base,
  candidate,
  auditPath,
  coveragePath,
  parentReviewId = undefined,
  createdAt = new Date().toISOString(),
  now = new Date()
}) {
  const clock = normalizeNow(now);
  canonicalTimestamp(createdAt, "Review session createdAt");
  if (new Date(createdAt).getTime() > clock.getTime()) {
    fail("review-session-time-invalid", "A review session cannot be created in the future.");
  }
  const inspection = await inspectRunrailReviewRepository({ repo, base });
  const selectedCandidate = await resolveSelectedCandidate(
    inspection.repositoryPath,
    inspection.confirmedBase.commit,
    candidate
  );
  const artifacts = await readReviewArtifacts({ auditPath, coveragePath });
  if (
    artifacts.audit.source.baseCommit !== inspection.confirmedBase.commit ||
    artifacts.audit.source.candidateCommit !== selectedCandidate.commit
  ) {
    fail(
      "audit-ref-mismatch",
      "The schema-v4 audit does not match the confirmed base and candidate commits."
    );
  }
  await assertHistoryRootDisjointBeforeMutation(
    historyRoot,
    inspection.repositoryPath
  );
  const canonicalHistoryRoot = await ensureHistoryRoot(historyRoot, { create: true });
  if (pathsOverlap(canonicalHistoryRoot, inspection.repositoryPath)) {
    fail(
      "history-root-overlaps-source",
      "Review history must be stored outside the reviewed repository."
    );
  }
  const repoFingerprint = await createRunrailRepoFingerprint({
    historyRoot: canonicalHistoryRoot,
    inspection
  });
  const existingSessions = await listSessionsInternal(
    canonicalHistoryRoot,
    repoFingerprint
  );
  const parentTarget = {
    repoFingerprint,
    baseCommit: inspection.confirmedBase.commit,
    candidateCommit: selectedCandidate.commit,
    createdAt
  };
  const latestRelated = findLatestRelatedPriorSession(
    existingSessions,
    parentTarget
  );
  let selectedParentReviewId = latestRelated?.reviewId || null;
  if (parentReviewId !== undefined) {
    if (parentReviewId !== null) {
      validateId(
        parentReviewId,
        REVIEW_ID_PATTERN,
        "Parent review ID",
        "parent-review-invalid"
      );
    }
    if (parentReviewId !== selectedParentReviewId) {
      fail(
        "parent-review-invalid",
        "The supplied parent is not the latest related prior review session."
      );
    }
    selectedParentReviewId = parentReviewId;
  }
  const findingIds = {
    high: artifacts.audit.decision.findings
      .filter((finding) => finding.severity === "high")
      .map((finding) => finding.id)
      .sort(compareText),
    medium: artifacts.audit.decision.findings
      .filter((finding) => finding.severity === "medium")
      .map((finding) => finding.id)
      .sort(compareText),
    info: artifacts.audit.decision.findings
      .filter((finding) => finding.severity === "info")
      .map((finding) => finding.id)
      .sort(compareText)
  };
  const evidence = {
    auditSchemaVersion: 4,
    auditRunId: artifacts.audit.runId,
    auditChecksumSha256: artifacts.audit.checksumSha256,
    auditFileSha256: artifacts.auditFileSha256,
    coverageChecksumSha256: artifacts.coverage.checksumSha256,
    coverageFileSha256: artifacts.coverageFileSha256,
    preflightPassed: artifacts.audit.preflightPassed,
    contractPassed: artifacts.audit.reviewContract.passed,
    findingCounts: {
      high: findingIds.high.length,
      medium: findingIds.medium.length,
      info: findingIds.info.length
    },
    findingIds,
    coverageSummary: { ...artifacts.coverage.summary }
  };
  const verdict = deriveVerdictFromEvidence({
    preflightPassed: evidence.preflightPassed,
    contractPassed: evidence.contractPassed,
    highFindingIds: evidence.findingIds.high,
    mediumFindingIds: evidence.findingIds.medium,
    coverageSummary: evidence.coverageSummary,
    dispositions: [],
    auditChecksumSha256: evidence.auditChecksumSha256,
    reviewId: null,
    now: clock
  });
  const reviewId = sessionIdentity({
    repoFingerprint,
    parentReviewId: selectedParentReviewId,
    createdAt,
    baseCommit: inspection.confirmedBase.commit,
    candidateCommit: selectedCandidate.commit,
    auditChecksumSha256: artifacts.audit.checksumSha256,
    coverageChecksumSha256: artifacts.coverage.checksumSha256
  });
  const body = {
    schemaVersion: RUNRAIL_REVIEW_SESSION.schemaVersion,
    artifactType: RUNRAIL_REVIEW_SESSION.artifactType,
    profile: RUNRAIL_REVIEW_SESSION.profile,
    product: RUNRAIL_REVIEW_SESSION.product,
    reviewId,
    repoFingerprint,
    parentReviewId: selectedParentReviewId,
    createdAt,
    local: {
      repositoryPath: inspection.repositoryPath,
      currentBranch: inspection.currentBranch,
      detachedHead: inspection.detachedHead,
      baseRef: inspection.confirmedBase.ref,
      baseCommit: inspection.confirmedBase.commit,
      candidateRef: selectedCandidate.ref,
      candidateCommit: selectedCandidate.commit,
      artifactRootPath: artifacts.artifactRootPath,
      auditPath: artifacts.auditPath,
      coveragePath: artifacts.coveragePath
    },
    discovery: {
      defaultBaseCandidates: inspection.defaultBaseCandidates,
      candidateAheadCommitCount: selectedCandidate.aheadCommitCount,
      candidateAheadCommitCountCapped:
        selectedCandidate.aheadCommitCountCapped,
      languageStack: inspection.languageStack,
      sourceStateChecksumSha256: inspection.sourceStateChecksumSha256
    },
    evidence,
    verdict,
    boundaries: {
      localOnly: true,
      authority: "none",
      networkUsed: false,
      modelUsed: false,
      providerUsed: false,
      projectTestsExecuted: false,
      patchApplied: false,
      repositoryContentIncluded: false,
      patchContentIncluded: false,
      rawCommandOutputIncluded: false,
      sourceMutationPerformed: false
    }
  };
  const session = verifyRunrailReviewSession({
    ...body,
    checksumSha256: computeRunrailReviewSessionChecksum(body)
  });

  const stateBeforeWrite = await captureRepositoryState(inspection.repositoryPath);
  if (stateBeforeWrite.checksumSha256 !== inspection.sourceStateChecksumSha256) {
    fail(
      "source-repo-changed-during-session",
      "The source repository changed before the immutable session was stored."
    );
  }
  const repositoryHistory = await repositoryHistoryRoot(
    canonicalHistoryRoot,
    repoFingerprint,
    { create: true }
  );
  const sessionRootPath = path.join(repositoryHistory.sessions, reviewId);
  try {
    await mkdir(sessionRootPath, { mode: 0o700 });
  } catch (error) {
    if (error?.code === "EEXIST") {
      fail("review-session-exists", "This immutable review session already exists.");
    }
    throw error;
  }
  const sessionRoot = await realpath(sessionRootPath);
  if (!isInsideOrEqual(sessionRoot, repositoryHistory.sessions)) {
    fail("history-path-invalid", "The immutable session path escaped review history.");
  }
  if (process.platform !== "win32") await chmod(sessionRoot, 0o700);
  const dispositionsRoot = await ensurePrivateDirectory(
    sessionRoot,
    DISPOSITIONS_DIRECTORY
  );
  const sessionPath = path.join(sessionRoot, SESSION_FILE_NAME);
  await writeExclusiveOwnerFile(
    sessionPath,
    stableRunrailReviewSessionJson(session)
  );
  const stored = await readSessionFile(sessionPath);
  if (stored.checksumSha256 !== session.checksumSha256) {
    fail("review-session-write-invalid", "The stored immutable session did not verify.");
  }
  const stateAfterWrite = await captureRepositoryState(inspection.repositoryPath);
  if (stateAfterWrite.checksumSha256 !== inspection.sourceStateChecksumSha256) {
    fail(
      "source-repo-changed-during-session",
      "The source repository changed while the immutable session was stored."
    );
  }
  return {
    session,
    sessionPath,
    dispositionsRoot,
    inspection
  };
}

function dispositionFileName(disposition) {
  const stamp = disposition.createdAt.replace(/[-:.TZ]/gu, "");
  return `${stamp}-${disposition.dispositionId}.json`;
}

async function sessionStorageRoots(historyRoot, repoFingerprint, reviewId) {
  const repositoryHistory = await repositoryHistoryRoot(
    historyRoot,
    repoFingerprint,
    { create: false }
  );
  if (!repositoryHistory) {
    fail("review-session-not-found", "The requested review session does not exist.");
  }
  const sessionRoot = await requirePrivateDirectory(
    repositoryHistory.sessions,
    reviewId
  );
  if (!sessionRoot) {
    fail("review-session-not-found", "The requested review session does not exist.");
  }
  const dispositionsRoot = await requirePrivateDirectory(
    sessionRoot,
    DISPOSITIONS_DIRECTORY
  );
  if (!dispositionsRoot) {
    fail("review-history-invalid", "The review session disposition directory is missing.");
  }
  return { sessionRoot, dispositionsRoot };
}

export async function listRunrailReviewDispositions({
  historyRoot,
  repoFingerprint,
  reviewId
}) {
  const session = await loadRunrailReviewSession({
    historyRoot,
    repoFingerprint,
    reviewId
  });
  const canonicalHistoryRoot = await ensureHistoryRoot(historyRoot, { create: false });
  const { dispositionsRoot } = await sessionStorageRoots(
    canonicalHistoryRoot,
    repoFingerprint,
    reviewId
  );
  const entries = await readdir(dispositionsRoot, { withFileTypes: true });
  if (entries.length > RUNRAIL_REVIEW_SESSION.maximumDispositionsPerSession) {
    fail("disposition-boundary", "The review session has too many disposition records.");
  }
  const dispositions = [];
  for (const entry of entries) {
    if (!entry.isFile() || entry.isSymbolicLink() || !/^[0-9]{17}-RSD-[A-F0-9]{24}\.json$/.test(entry.name)) {
      fail("review-history-invalid", "The disposition log contains an unsupported entry.");
    }
    const dispositionPath = path.join(dispositionsRoot, entry.name);
    const file = await readBoundedRegularFile(
      dispositionPath,
      64 * 1024,
      "disposition-invalid"
    );
    let parsed;
    try {
      parsed = JSON.parse(file.bytes.toString("utf8"));
    } catch {
      fail("disposition-invalid", "A stored disposition is not valid JSON.");
    }
    const disposition = verifyRunrailReviewDisposition(parsed);
    if (
      dispositionFileName(disposition) !== entry.name ||
      disposition.reviewId !== reviewId ||
      disposition.repoFingerprint !== repoFingerprint ||
      disposition.auditChecksumSha256 !== session.evidence.auditChecksumSha256 ||
      stableRunrailReviewSessionJson(disposition) !== file.bytes.toString("utf8")
    ) {
      fail("review-history-invalid", "A disposition does not match its append-only log.");
    }
    dispositions.push(disposition);
  }
  dispositions.sort(compareDispositionsOldestFirst);
  let previousChecksumSha256 = null;
  for (const disposition of dispositions) {
    if (
      disposition.previousDispositionChecksumSha256 !==
      previousChecksumSha256
    ) {
      fail("disposition-chain-invalid", "The append-only disposition chain is invalid.");
    }
    previousChecksumSha256 = disposition.checksumSha256;
  }
  return dispositions;
}

export async function appendRunrailReviewDisposition({
  historyRoot,
  repoFingerprint,
  reviewId,
  findingId,
  kind,
  reason = null,
  owner = null,
  expiresAt = null,
  createdAt = new Date().toISOString(),
  now = new Date()
}) {
  const clock = normalizeNow(now);
  canonicalTimestamp(createdAt, "Disposition createdAt", "disposition-invalid");
  if (new Date(createdAt).getTime() > clock.getTime()) {
    fail("disposition-time-invalid", "A disposition cannot be created in the future.");
  }
  const session = await loadRunrailReviewSession({
    historyRoot,
    repoFingerprint,
    reviewId
  });
  const findingIds = new Set([
    ...session.evidence.findingIds.high,
    ...session.evidence.findingIds.medium,
    ...session.evidence.findingIds.info
  ]);
  if (!findingIds.has(findingId)) {
    fail("disposition-finding-invalid", "The disposition must target a finding in this review.");
  }
  if (
    kind === "accepted-exception" &&
    (
      typeof expiresAt !== "string" ||
      new Date(expiresAt).getTime() <= clock.getTime()
    )
  ) {
    fail(
      "disposition-expiry-invalid",
      "An accepted exception requires a valid future expiresAt."
    );
  }
  const existing = await listRunrailReviewDispositions({
    historyRoot,
    repoFingerprint,
    reviewId
  });
  const previous = existing.at(-1) || null;
  if (previous && createdAt <= previous.createdAt) {
    fail(
      "disposition-time-invalid",
      "Append-only dispositions require a strictly increasing createdAt."
    );
  }
  const disposition = buildRunrailReviewDisposition({
    reviewId,
    repoFingerprint,
    auditChecksumSha256: session.evidence.auditChecksumSha256,
    findingId,
    kind,
    reason,
    owner,
    expiresAt,
    createdAt,
    previousDispositionChecksumSha256: previous?.checksumSha256 || null
  });
  const canonicalHistoryRoot = await ensureHistoryRoot(historyRoot, { create: false });
  const { dispositionsRoot } = await sessionStorageRoots(
    canonicalHistoryRoot,
    repoFingerprint,
    reviewId
  );
  const dispositionPath = path.join(
    dispositionsRoot,
    dispositionFileName(disposition)
  );
  if (!isInsideOrEqual(dispositionPath, dispositionsRoot)) {
    fail("history-path-invalid", "The disposition path escaped review history.");
  }
  await writeExclusiveOwnerFile(
    dispositionPath,
    stableRunrailReviewSessionJson(disposition)
  );
  const stored = await listRunrailReviewDispositions({
    historyRoot,
    repoFingerprint,
    reviewId
  });
  if (stored.at(-1)?.checksumSha256 !== disposition.checksumSha256) {
    fail("disposition-write-invalid", "The appended disposition did not verify.");
  }
  return { disposition, dispositionPath };
}

export function evaluateRunrailReviewSession(
  session,
  dispositions = [],
  { now = new Date() } = {}
) {
  verifyRunrailReviewSession(session);
  if (
    !Array.isArray(dispositions) ||
    dispositions.length > RUNRAIL_REVIEW_SESSION.maximumDispositionsPerSession
  ) {
    fail("disposition-boundary", "Review evaluation contains too many dispositions.");
  }
  for (const disposition of dispositions) {
    verifyRunrailReviewDisposition(disposition);
    if (
      disposition.reviewId !== session.reviewId ||
      disposition.repoFingerprint !== session.repoFingerprint ||
      disposition.auditChecksumSha256 !== session.evidence.auditChecksumSha256
    ) {
      fail("disposition-session-mismatch", "A disposition belongs to another review session.");
    }
  }
  return deriveVerdictFromEvidence({
    preflightPassed: session.evidence.preflightPassed,
    contractPassed: session.evidence.contractPassed,
    highFindingIds: session.evidence.findingIds.high,
    mediumFindingIds: session.evidence.findingIds.medium,
    coverageSummary: session.evidence.coverageSummary,
    dispositions,
    auditChecksumSha256: session.evidence.auditChecksumSha256,
    reviewId: session.reviewId,
    now
  });
}

export const discoverRunrailReviewRepository = inspectRunrailReviewRepository;
export const createSaltedRunrailRepoFingerprint = createRunrailRepoFingerprint;
export const listRunrailReviewHistory = listRunrailReviewSessions;
export const listAllRunrailReviewHistory = listAllRunrailReviewSessions;
export const appendRunrailReviewSessionDisposition =
  appendRunrailReviewDisposition;
export const findLatestRelatedRunrailReviewSession =
  findLatestRelatedPriorSession;
