import { spawn } from "node:child_process";
import { createHash, randomBytes } from "node:crypto";
import { constants as fsConstants } from "node:fs";
import { createServer } from "node:http";
import path from "node:path";
import {
  chmod,
  lstat,
  mkdir,
  open as openFile,
  readdir,
  readFile,
  realpath
} from "node:fs/promises";
import { fileURLToPath } from "node:url";
import {
  buildRunrailHunkAttentionManifest,
  parseRunrailPatchHunks,
  verifyRunrailHunkContinuity,
  writeRunrailHunkContinuityArtifacts
} from "./runrail-hunk-continuity-core.mjs";
import { buildRunrailReviewFocus } from "./runrail-review-focus-core.mjs";
import {
  stableRunrailPassportJson,
  verifyRunrailDeviceSignedReviewPassport,
  verifyRunrailReviewPassport
} from "./runrail-review-passport-core.mjs";
import {
  assertRunrailLocalDesktopAccess,
  assertRunrailLocalFeatureAccess,
  assertRunrailLocalHistoryAccess,
  createRunrailNativeEnrollmentHandoff,
  enrollRunrailDeviceFromHandoff,
  signRunrailDeviceReviewPassport
} from "./runrail-local-entitlement-core.mjs";
import {
  appendRunrailReviewDisposition,
  buildRunrailRepositoryReadinessHandoff,
  buildRunrailRepositoryReadinessReceipt,
  createRunrailRepoFingerprint,
  createRunrailReviewSession,
  evaluateRunrailReviewSession,
  findRunrailReviewSession,
  inspectRunrailReviewRepository,
  listAllRunrailReviewSessions,
  listRunrailReviewDispositions,
  listRunrailReviewSessions,
  verifyRunrailAuditV4
} from "./runrail-review-session-core.mjs";
import {
  loadRunrailRepositoryTrustProfile,
  loadRunrailWeeklyEngineeringReport
} from "./runrail-trust-profile-core.mjs";
import {
  buildRunrailCandidateTournament,
  writeRunrailCandidateTournament
} from "./runrail-candidate-tournament-core.mjs";
import { loadRunrailProofGraph } from "./runrail-proof-graph-core.mjs";
import {
  RUNRAIL_AGENT_ASSURANCE,
  buildRunrailAgentAssurancePacket,
  evaluateRunrailAgentAssurance,
  verifyRunrailAgentAssuranceResult,
  writeRunrailAgentAssurancePacket,
  writeRunrailAgentAssuranceResult
} from "./runrail-agent-assurance-core.mjs";
import {
  createRunrailAgentAdapterRegistry,
  createRunrailAgentLaunchReceipt,
  createRunrailAgentOperation,
  stableRunrailAgentLaunchReceiptJson,
  verifyRunrailAgentLaunchReceipt
} from "./runrail-agent-bridge-core.mjs";
import {
  RUNRAIL_EXTERNAL_EVIDENCE,
  createRunrailExternalEvidenceReceipt,
  listRunrailExternalEvidenceReceipts,
  writeRunrailExternalEvidenceReceipt
} from "./runrail-external-evidence-core.mjs";
import {
  buildRunrailAgentOutcomeSummary,
  createRunrailAgentOutcome,
  listRunrailAgentOutcomes,
  writeRunrailAgentOutcome
} from "./runrail-agent-outcome-ledger-core.mjs";
import {
  createRunrailProductMetricEvent,
  loadRunrailProductMetricsSummary,
  writeRunrailProductMetricEvent
} from "./runrail-product-metrics-core.mjs";
import { LOCAL_AUDIT_RUNNER } from "./veyact-local-audit-runner-core.mjs";
import { migrateRunrailNativeState } from "./runrail-native-state-migration.mjs";

const sourceRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");
const distributionRoot = path.resolve(process.env.RUNRAIL_DISTRIBUTION_ROOT || sourceRoot);
const desktopRoot = path.join(distributionRoot, "desktop");
const cliEntry = path.resolve(
  process.env.RUNRAIL_CLI_ENTRY || path.join(distributionRoot, "packages", "runrail-local", "bin", "runrail.mjs")
);
const localRunnerEntry = path.join(
  distributionRoot,
  "scripts",
  "veyact-local-audit-runner.mjs"
);
const maxBodyBytes = 16 * 1024;
const maxExternalEvidenceBodyBytes =
  Math.ceil(RUNRAIL_EXTERNAL_EVIDENCE.maximumDecodedBytes / 3) * 4 + 4096;
const maxDiffBytes = 2 * 1024 * 1024;
const maxDiffFiles = 200;
const maxDiffHunks = 2_000;
const maxDiffLines = 10_000;
const maxDiffLineLength = 16 * 1024;
const commandTimeoutMs = 180_000;
const openerSpawnTimeoutMs = 5_000;
const processTreeGraceMs = 1_500;
const configuredProductVersion = String(process.env.RUNRAIL_PRODUCT_VERSION || "2.4.14").trim();
const desktopProductVersion = /^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/.test(configuredProductVersion)
  ? configuredProductVersion
  : "2.4.14";
const deepSeekEnvironmentKeys = Object.freeze([
  "RUNRAIL_DEEPSEEK_ADVISORY_API_KEY",
  "RUNRAIL_DEEPSEEK_ADVISORY_ENABLED"
]);
const defaultReviewHistoryRoot = path.join(
  LOCAL_AUDIT_RUNNER.operatorRoot,
  "review-history"
);
const publicPreviewReviewRecordName = "PUBLIC_PREVIEW_REVIEW.json";

const staticFiles = new Map([
  ["/", { file: "index.html", type: "text/html; charset=utf-8" }],
  ["/index.html", { file: "index.html", type: "text/html; charset=utf-8" }],
  ["/app.css", { file: "app.css", type: "text/css; charset=utf-8" }],
  ["/app.js", { file: "app.js", type: "text/javascript; charset=utf-8" }],
  ["/icon-192.png", { file: "icon-192.png", type: "image/png" }],
  ["/icon-512.png", { file: "icon-512.png", type: "image/png" }],
  ["/favicon.ico", { file: "favicon.ico", type: "image/x-icon" }]
]);
const entitlementMutationRoutes = new Set([
  "/api/review/evidence/import",
  "/api/outcomes/record",
  "/api/trust/profile",
  "/api/tournament",
  "/api/review",
  "/api/agents/launch",
  "/api/review/handoff",
  "/api/coverage",
  "/api/review/rerun",
  "/api/review/disposition",
  "/api/revision",
  "/api/recommend"
]);

function sendJson(response, statusCode, payload) {
  if (response.destroyed || response.writableEnded) return false;
  try {
    response.writeHead(statusCode, { "Content-Type": "application/json; charset=utf-8" });
    response.end(`${JSON.stringify(payload)}\n`);
    return true;
  } catch {
    if (!response.destroyed) response.destroy();
    return false;
  }
}

function sendBody(response, statusCode, contentType, body) {
  if (response.destroyed || response.writableEnded) return false;
  try {
    response.writeHead(statusCode, { "Content-Type": contentType });
    response.end(body);
    return true;
  } catch {
    if (!response.destroyed) response.destroy();
    return false;
  }
}

function assertExactRequestKeys(body, allowedKeys, label) {
  const allowed = new Set(allowedKeys);
  const actual = Object.keys(body);
  if (actual.some((key) => !allowed.has(key))) {
    const error = new Error(`${label} contains an unsupported request field.`);
    error.code = "desktop-input-invalid";
    throw error;
  }
}

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

function sameLocalPath(left, right) {
  const leftPath = path.resolve(left);
  const rightPath = path.resolve(right);
  return process.platform === "win32"
    ? leftPath.toLowerCase() === rightPath.toLowerCase()
    : leftPath === rightPath;
}

function publicPreviewReviewRecordBody({ reviewId, auditChecksumSha256, createdAt }) {
  return {
    schemaVersion: 1,
    artifactType: "runrail-public-preview-review",
    productVersion: desktopProductVersion,
    reviewId,
    auditChecksumSha256,
    createdAt,
    candidateReviewCount: 1,
    rerunAvailable: false,
    authority: "none",
    executionAuthorityGranted: false
  };
}

function verifyPublicPreviewReviewRecord(record) {
  const expectedKeys = [
    "artifactType",
    "auditChecksumSha256",
    "authority",
    "candidateReviewCount",
    "checksumSha256",
    "createdAt",
    "executionAuthorityGranted",
    "productVersion",
    "rerunAvailable",
    "reviewId",
    "schemaVersion"
  ];
  const actualKeys = Object.keys(record || {}).sort();
  const { checksumSha256, ...body } = record || {};
  if (
    JSON.stringify(actualKeys) !== JSON.stringify(expectedKeys) ||
    body.schemaVersion !== 1 ||
    body.artifactType !== "runrail-public-preview-review" ||
    body.productVersion !== desktopProductVersion ||
    !/^RRS-[A-F0-9]{24}$/u.test(String(body.reviewId || "")) ||
    !/^[a-f0-9]{64}$/u.test(String(body.auditChecksumSha256 || "")) ||
    !Number.isFinite(Date.parse(String(body.createdAt || ""))) ||
    body.candidateReviewCount !== 1 ||
    body.rerunAvailable !== false ||
    body.authority !== "none" ||
    body.executionAuthorityGranted !== false ||
    checksumSha256 !== sha256(JSON.stringify(body))
  ) {
    const error = new Error(
      "The local public-preview review record is invalid. Reinstall Runrail before starting another preview review."
    );
    error.code = "desktop-preview-review-record-invalid";
    throw error;
  }
  return Object.freeze({ ...body, checksumSha256 });
}

async function publicPreviewReviewRecordPath(reviewHistoryRoot) {
  const root = path.resolve(reviewHistoryRoot);
  await mkdir(root, { recursive: true, mode: 0o700 });
  const rootEntry = await lstat(root);
  if (
    !rootEntry.isDirectory() ||
    rootEntry.isSymbolicLink() ||
    !sameLocalPath(await realpath(root), root)
  ) {
    const error = new Error(
      "The local public-preview review root must be an ordinary owned directory."
    );
    error.code = "desktop-preview-review-root-invalid";
    throw error;
  }
  return path.join(root, publicPreviewReviewRecordName);
}

async function loadPublicPreviewReviewRecord(reviewHistoryRoot) {
  const recordPath = await publicPreviewReviewRecordPath(reviewHistoryRoot);
  const entry = await lstat(recordPath).catch((error) => {
    if (error?.code === "ENOENT") return null;
    throw error;
  });
  if (!entry) return null;
  if (
    !entry.isFile() ||
    entry.isSymbolicLink() ||
    entry.size < 2 ||
    entry.size > 16 * 1024 ||
    !sameLocalPath(await realpath(recordPath), recordPath)
  ) {
    const error = new Error("The local public-preview review record is unsafe.");
    error.code = "desktop-preview-review-record-invalid";
    throw error;
  }
  try {
    return verifyPublicPreviewReviewRecord(
      JSON.parse(await readFile(recordPath, "utf8"))
    );
  } catch (error) {
    if (error?.code === "desktop-preview-review-record-invalid") throw error;
    const invalid = new Error("The local public-preview review record is invalid.");
    invalid.code = "desktop-preview-review-record-invalid";
    throw invalid;
  }
}

async function writePublicPreviewReviewRecord(reviewHistoryRoot, {
  reviewId,
  auditChecksumSha256,
  createdAt
}) {
  const recordPath = await publicPreviewReviewRecordPath(reviewHistoryRoot);
  const body = publicPreviewReviewRecordBody({
    reviewId,
    auditChecksumSha256,
    createdAt
  });
  const record = {
    ...body,
    checksumSha256: sha256(JSON.stringify(body))
  };
  let handle;
  try {
    handle = await openFile(recordPath, "wx", 0o600);
    await handle.writeFile(`${JSON.stringify(record, null, 2)}\n`, "utf8");
    await handle.sync();
  } catch (error) {
    if (error?.code === "EEXIST") {
      const exhausted = new Error(
        "This installation already used its one real public-preview review. Enroll Starter or Pro to review another candidate."
      );
      exhausted.code = "desktop-preview-review-limit-reached";
      throw exhausted;
    }
    throw error;
  } finally {
    await handle?.close();
  }
  if (process.platform !== "win32") await chmod(recordPath, 0o600);
  return verifyPublicPreviewReviewRecord(record);
}

function publicError(error) {
  const code = typeof error?.code === "string" ? error.code : "desktop-command-failed";
  const message = String(error?.message || "The local Runrail command failed.")
    .replaceAll(process.env.RUNRAIL_DEEPSEEK_ADVISORY_API_KEY || "\u0000", "[redacted]")
    .slice(0, 1200);
  return { ok: false, code, message };
}

function applySecurityHeaders(response, origin) {
  response.setHeader(
    "Content-Security-Policy",
    `default-src 'none'; script-src 'self'; style-src 'self'; img-src 'self' data:; connect-src ${origin}; base-uri 'none'; form-action 'none'; frame-ancestors 'none'; object-src 'none'`
  );
  response.setHeader("Cache-Control", "no-store");
  response.setHeader("Cross-Origin-Opener-Policy", "same-origin");
  response.setHeader("Cross-Origin-Resource-Policy", "same-origin");
  response.setHeader("Permissions-Policy", "camera=(), microphone=(), geolocation=(), payment=(), usb=()");
  response.setHeader("Referrer-Policy", "no-referrer");
  response.setHeader("X-Content-Type-Options", "nosniff");
  response.setHeader("X-Frame-Options", "DENY");
}

async function readJsonBody(request, maximumBytes = maxBodyBytes) {
  const chunks = [];
  let size = 0;
  for await (const chunk of request) {
    size += chunk.length;
    if (size > maximumBytes) {
      const error = new Error("The local request exceeded its bounded size limit.");
      error.code = "desktop-request-too-large";
      throw error;
    }
    chunks.push(chunk);
  }
  if (chunks.length === 0) return {};
  try {
    return JSON.parse(Buffer.concat(chunks).toString("utf8"));
  } catch {
    const error = new Error("The local request body must contain valid JSON.");
    error.code = "desktop-request-invalid";
    throw error;
  }
}

function boundedText(value, field, maxLength = 4096) {
  const text = String(value || "").trim();
  if (!text || text.length > maxLength || text.includes("\u0000")) {
    const error = new Error(`${field} is required and must stay within ${maxLength} characters.`);
    error.code = "desktop-input-invalid";
    throw error;
  }
  return text;
}

function absoluteRepoPath(value) {
  const repo = boundedText(value, "Repository path");
  if (!path.isAbsolute(repo)) {
    const error = new Error("Repository path must be absolute on this machine.");
    error.code = "desktop-repo-path";
    throw error;
  }
  return path.resolve(repo);
}

function absoluteArtifactPath(value, field) {
  const artifactPath = boundedText(value, field);
  if (!path.isAbsolute(artifactPath)) {
    const error = new Error(`${field} must be an absolute path on this machine.`);
    error.code = "desktop-artifact-path";
    throw error;
  }
  return path.resolve(artifactPath);
}

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

function referenceName(value) {
  const ref = String(value || "").trim();
  return ref.startsWith("refs/heads/") ? ref.slice("refs/heads/".length) : ref;
}

function inspectionForDesktop(inspection, repoId, history = []) {
  const defaultBase = inspection.confirmedBase?.ref ||
    inspection.defaultBaseCandidates.at(0)?.ref ||
    "";
  const readiness = buildRunrailRepositoryReadinessReceipt(inspection);
  return {
    ...inspection,
    repoId,
    repo: inspection.repositoryPath,
    path: inspection.repositoryPath,
    defaultBase,
    baseCandidates: inspection.defaultBaseCandidates,
    candidateBranches: inspection.candidateLocalBranches,
    stack: inspection.languageStack.languages,
    readiness,
    readinessHandoff: buildRunrailRepositoryReadinessHandoff(readiness),
    contract: inspection.reviewContract,
    history
  };
}

function decodeGitQuotedPath(value) {
  const raw = String(value || "");
  if (!raw.startsWith("\"") || !raw.endsWith("\"")) return raw;
  const encoded = [];
  const body = raw.slice(1, -1);
  const namedEscapes = Object.freeze({
    a: 0x07,
    b: 0x08,
    t: 0x09,
    n: 0x0a,
    v: 0x0b,
    f: 0x0c,
    r: 0x0d,
    "\"": 0x22,
    "\\": 0x5c
  });
  for (let index = 0; index < body.length; index += 1) {
    const character = body[index];
    if (character !== "\\") {
      const codePoint = body.codePointAt(index);
      const visible = String.fromCodePoint(codePoint);
      encoded.push(Buffer.from(visible, "utf8"));
      if (codePoint > 0xffff) index += 1;
      continue;
    }
    const escaped = body[index + 1];
    if (!escaped) {
      const error = new Error("The review diff contains an invalid quoted path.");
      error.code = "desktop-diff-invalid";
      throw error;
    }
    if (Object.hasOwn(namedEscapes, escaped)) {
      encoded.push(Buffer.from([namedEscapes[escaped]]));
      index += 1;
      continue;
    }
    const octal = body.slice(index + 1, index + 4);
    if (/^[0-7]{3}$/u.test(octal)) {
      encoded.push(Buffer.from([Number.parseInt(octal, 8)]));
      index += 3;
      continue;
    }
    const error = new Error("The review diff contains an unsupported path escape.");
    error.code = "desktop-diff-invalid";
    throw error;
  }
  try {
    return new TextDecoder("utf-8", { fatal: true }).decode(
      Buffer.concat(encoded)
    );
  } catch {
    const error = new Error("The review diff path is not valid UTF-8.");
    error.code = "desktop-diff-invalid";
    throw error;
  }
}

function boundedDiffPath(value) {
  const raw = decodeGitQuotedPath(String(value || "").trim());
  const candidate =
    raw.startsWith("b/") || raw.startsWith("a/") ? raw.slice(2) : raw;
  if (
    !candidate ||
    candidate === "/dev/null" ||
    candidate.length > 1_024 ||
    candidate.includes("\u0000") ||
    path.isAbsolute(candidate) ||
    /^[a-z]:[\\/]/iu.test(candidate) ||
    candidate.startsWith("\\\\") ||
    candidate.startsWith("file://") ||
    candidate.startsWith("~/") ||
    candidate.split(/[\\/]+/u).includes("..")
  ) {
    const error = new Error(
      "The checksum-bound review diff contains an invalid repository-relative file path."
    );
    error.code = "desktop-diff-invalid";
    throw error;
  }
  return candidate;
}

export function buildRunrailDiffInspection(patchText, coverage) {
  if (
    typeof patchText !== "string" ||
    Buffer.byteLength(patchText, "utf8") > maxDiffBytes ||
    !coverage ||
    !Array.isArray(coverage.hunks) ||
    coverage.hunks.length > maxDiffHunks
  ) {
    const error = new Error(
      "The review diff is missing or exceeds its bounded inspection limits."
    );
    error.code = "desktop-diff-invalid";
    throw error;
  }
  const verifiedHunks = parseRunrailPatchHunks(patchText, {
    sourceAuditChecksumSha256: coverage.source.auditChecksumSha256,
    diffSha256: coverage.source.diffSha256
  });
  if (
    verifiedHunks.length !== coverage.hunks.length ||
    verifiedHunks.some(
      (hunk, index) => hunk.hunkId !== coverage.hunks[index]?.hunkId
    )
  ) {
    const error = new Error(
      "The review diff hunk sequence no longer matches Review Coverage."
    );
    error.code = "desktop-diff-coverage-mismatch";
    throw error;
  }

  const lines = (
    patchText.endsWith("\n") ? patchText.slice(0, -1) : patchText
  ).split("\n");
  const files = [];
  let currentFile = null;
  let currentHunk = null;
  let hunkIndex = 0;
  let deliveredLineCount = 0;

  for (const line of lines) {
    if (line.length > maxDiffLineLength) {
      const error = new Error(
        "The review diff contains a line that exceeds the inspection boundary."
      );
      error.code = "desktop-diff-invalid";
      throw error;
    }
    if (line.startsWith("diff --git ")) {
      if (files.length >= maxDiffFiles) {
        const error = new Error(
          "The review diff contains too many files for bounded inspection."
        );
        error.code = "desktop-diff-invalid";
        throw error;
      }
      currentFile = {
        path: "",
        hunks: []
      };
      files.push(currentFile);
      currentHunk = null;
      continue;
    }
    if (line.startsWith("+++ ") && currentFile) {
      const nextPath = line.slice(4);
      if (nextPath !== "/dev/null") currentFile.path = boundedDiffPath(nextPath);
      continue;
    }
    if (
      line.startsWith("--- ") &&
      currentFile &&
      !currentFile.path &&
      line.slice(4) !== "/dev/null"
    ) {
      const previousPath = line.slice(4);
      currentFile.path = boundedDiffPath(
        previousPath.startsWith("a/") ? previousPath.slice(2) : previousPath
      );
      continue;
    }
    if (!line.startsWith("@@ ")) {
      if (!currentHunk) continue;
      deliveredLineCount += 1;
      if (deliveredLineCount > maxDiffLines) {
        const error = new Error(
          "The review diff contains too many lines for bounded inspection."
        );
        error.code = "desktop-diff-invalid";
        throw error;
      }
      const prefix = line.slice(0, 1);
      currentHunk.lines.push({
        kind: prefix === "+"
          ? "addition"
          : prefix === "-"
            ? "removal"
            : prefix === "\\"
              ? "marker"
              : "context",
        prefix,
        text: prefix === "\\" ? line : line.slice(1)
      });
      continue;
    }
    if (!currentFile || !currentFile.path || hunkIndex >= coverage.hunks.length) {
      const error = new Error(
        "The review diff no longer matches its checksum-bound Review Coverage."
      );
      error.code = "desktop-diff-coverage-mismatch";
      throw error;
    }
    currentHunk = {
      hunkId: verifiedHunks[hunkIndex].hunkId,
      header: line,
      lines: []
    };
    currentFile.hunks.push(currentHunk);
    hunkIndex += 1;
  }

  const inspectedFiles = files.filter((file) => file.hunks.length > 0);
  if (
    hunkIndex !== coverage.hunks.length ||
    inspectedFiles.some((file) => !file.path)
  ) {
    const error = new Error(
      "The review diff hunk sequence no longer matches Review Coverage."
    );
    error.code = "desktop-diff-coverage-mismatch";
    throw error;
  }

  return {
    files: inspectedFiles,
    summary: {
      fileCount: inspectedFiles.length,
      hunkCount: hunkIndex,
      lineCount: deliveredLineCount
    }
  };
}

function childStillRunning(child) {
  return Boolean(child && child.exitCode === null && child.signalCode == null);
}

function waitForChildClose(child, timeoutMs) {
  if (!childStillRunning(child)) return Promise.resolve();
  return Promise.race([
    new Promise((resolve) => child.once("close", resolve)),
    new Promise((resolve) => {
      const timer = setTimeout(resolve, timeoutMs);
      timer.unref();
    })
  ]);
}

export async function terminateCliProcessTree(child, {
  platform = process.platform,
  graceMs = processTreeGraceMs,
  spawnProcess = spawn
} = {}) {
  if (!childStillRunning(child)) return false;
  const pid = Number(child.pid);
  if (!Number.isInteger(pid) || pid <= 0) {
    child.kill();
    return true;
  }

  if (platform === "win32") {
    await new Promise((resolve) => {
      let settled = false;
      const taskkill = spawnProcess("taskkill.exe", ["/PID", String(pid), "/T", "/F"], {
        stdio: "ignore",
        windowsHide: true
      });
      const finish = () => {
        if (settled) return;
        settled = true;
        resolve();
      };
      taskkill.once("error", finish);
      taskkill.once("close", finish);
    });
    if (childStillRunning(child)) child.kill();
    await waitForChildClose(child, graceMs);
    return true;
  }

  try {
    process.kill(-pid, "SIGTERM");
  } catch {
    child.kill("SIGTERM");
  }
  await waitForChildClose(child, graceMs);
  if (childStillRunning(child)) {
    try {
      process.kill(-pid, "SIGKILL");
    } catch {
      child.kill("SIGKILL");
    }
    await waitForChildClose(child, graceMs);
  }
  return true;
}

export function runrailDesktopChildEnvironment({
  env = process.env,
  allowDeepSeek = false
} = {}) {
  const childEnv = { ...env };
  if (!allowDeepSeek) {
    for (const key of deepSeekEnvironmentKeys) delete childEnv[key];
  }
  return childEnv;
}

function createCliOperation(args, {
  env = runrailDesktopChildEnvironment(),
  allowNonZeroResult = false,
  internalPreviewReview = false
} = {}) {
  const child = spawn(
    process.execPath,
    [internalPreviewReview ? localRunnerEntry : cliEntry, ...args, "--json"],
    {
    detached: process.platform !== "win32",
    env,
    stdio: ["ignore", "pipe", "pipe"],
    windowsHide: true
    }
  );
  let stdout = "";
  let stderr = "";
  let timedOut = false;
  let stopPromise = null;
  const stop = () => {
    if (!stopPromise) stopPromise = terminateCliProcessTree(child);
    return stopPromise;
  };
  const timer = setTimeout(() => {
    timedOut = true;
    void stop();
  }, commandTimeoutMs);
  timer.unref();

  child.stdout.on("data", (chunk) => {
    stdout = `${stdout}${chunk}`;
    if (Buffer.byteLength(stdout) > 16 * 1024 * 1024) void stop();
  });
  child.stderr.on("data", (chunk) => {
    stderr = `${stderr}${chunk}`.slice(-16 * 1024);
  });

  const result = new Promise((resolve, reject) => {
    child.once("error", reject);
    child.once("close", (exitCode, signal) => {
      clearTimeout(timer);
      let payload = null;
      try {
        payload = JSON.parse(stdout);
      } catch {}

      if (payload && (exitCode === 0 || allowNonZeroResult)) {
        resolve({ ...payload, commandExitCode: exitCode ?? 1 });
        return;
      }
      const message = timedOut
        ? "The local Runrail command timed out."
        : String(stderr || payload?.message || `The local Runrail command exited ${exitCode ?? signal ?? "unexpectedly"}.`).trim();
      const error = new Error(message);
      error.code = timedOut ? "desktop-command-timeout" : (payload?.code || "desktop-command-failed");
      reject(error);
    });
  });
  return { child, result, stop };
}

export function desktopOpenCommand(
  url,
  { platform = process.platform, env = process.env } = {}
) {
  if (platform === "win32") {
    return { command: "rundll32.exe", args: ["url.dll,FileProtocolHandler", url], mode: "windows" };
  }
  if (platform === "darwin") {
    return { command: "open", args: [url], mode: "macos" };
  }
  if (platform === "linux" && (env.WSL_DISTRO_NAME || env.WSL_INTEROP)) {
    return { command: "cmd.exe", args: ["/c", "start", "", url], mode: "wsl2-host-browser" };
  }
  return { command: "xdg-open", args: [url], mode: "linux" };
}

function openerFailure(error, mode) {
  const code = typeof error?.code === "string" ? error.code : "desktop-opener-failed";
  const message = String(error?.message || "The desktop browser opener failed.")
    .replace(/[\r\n\t]+/g, " ")
    .slice(0, 500);
  return { attempted: true, opened: false, mode, code, message };
}

async function openLocalApp(url, { spawnProcess = spawn } = {}) {
  const { command, args, mode } = desktopOpenCommand(url);
  let child;
  try {
    child = spawnProcess(command, args, {
      detached: true,
      stdio: "ignore",
      windowsHide: true
    });
  } catch (error) {
    return openerFailure(error, mode);
  }

  return new Promise((resolve) => {
    let settled = false;
    const settle = (result) => {
      if (settled) return;
      settled = true;
      clearTimeout(timer);
      resolve(result);
    };
    const timer = setTimeout(() => {
      const error = new Error("The desktop browser opener did not report a spawn result.");
      error.code = "desktop-opener-timeout";
      settle(openerFailure(error, mode));
    }, openerSpawnTimeoutMs);
    timer.unref();

    child.once("spawn", () => settle({ attempted: true, opened: true, mode, code: null }));
    child.on("error", (error) => settle(openerFailure(error, mode)));
    child.once("close", (exitCode, signal) => {
      if (settled) return;
      const error = new Error(
        `The desktop browser opener closed before spawning (${exitCode ?? signal ?? "unknown"}).`
      );
      error.code = "desktop-opener-closed";
      settle(openerFailure(error, mode));
    });
    try {
      child.unref();
    } catch (error) {
      settle(openerFailure(error, mode));
    }
  });
}

export async function startRunrailDesktop({
  port = 0,
  open = true,
  initialRepo = "",
  reviewHistoryRoot: requestedReviewHistoryRoot = defaultReviewHistoryRoot,
  cliOperationFactory = createCliOperation,
  agentRegistryFactory = createRunrailAgentAdapterRegistry,
  agentOperationFactory = createRunrailAgentOperation,
  openerSpawn = spawn,
  onOpenerWarning = (message) => process.stderr.write(`${message}\n`)
} = {}) {
  if (!Number.isInteger(port) || port < 0 || port > 65_535) {
    const error = new Error("Desktop port must be an integer between 0 and 65535.");
    error.code = "desktop-port-invalid";
    throw error;
  }
  if (initialRepo && !path.isAbsolute(initialRepo)) {
    const error = new Error("Desktop initial repository path must be absolute.");
    error.code = "desktop-repo-path";
    throw error;
  }
  if (!path.isAbsolute(requestedReviewHistoryRoot)) {
    const error = new Error("Desktop review history root must be absolute.");
    error.code = "desktop-history-path";
    throw error;
  }
  const subscriberReviewHistoryRoot = path.resolve(requestedReviewHistoryRoot);
  const publicPreviewReviewHistoryRoot = path.join(
    subscriberReviewHistoryRoot,
    "public-preview"
  );
  let reviewHistoryRoot = subscriberReviewHistoryRoot;
  const nativeMigration = process.env.RUNRAIL_PRODUCT_VERSION === "3.0.0"
    ? await migrateRunrailNativeState({ operatorRoot: LOCAL_AUDIT_RUNNER.operatorRoot })
    : null;

  const sessionToken = randomBytes(32).toString("base64url");
  const desktopMetricBinding = randomBytes(32).toString("hex");
  const allowedAuditPaths = new Set();
  const coverageByAuditPath = new Map();
  const reviewContextByAuditPath = new Map();
  const assuranceBaselineByReviewId = new Map();
  let busy = false;
  let activeCommandRoute = "";
  const commandLockDebug = process.env.RUNRAIL_DESKTOP_DEBUG_COMMAND_LOCK === "true";
  const debugCommandLock = (event, route) => {
    if (!commandLockDebug) return;
    process.stderr.write(`[runrail-desktop-command-lock] ${event} ${route || "none"}\n`);
  };
  const activeOperations = new Set();
  const clientCleanupPromises = new Set();
  let acceptingOperations = true;
  let operationShutdownPromise = null;
  let serverClosePromise = null;
  let origin = "";
  let currentMetricPlan = "preview";
  let activationMetricRecorded = false;
  const metricWriteFailures = [];
  let resolveClosed;
  const closed = new Promise((resolve) => {
    resolveClosed = resolve;
  });

  function metricPlatform() {
    if (process.platform === "win32") return "windows";
    if (process.platform === "darwin") return "macos";
    if (process.env.WSL_DISTRO_NAME || process.env.WSL_INTEROP) return "wsl2";
    if (process.platform === "linux") return "linux";
    return "unknown";
  }

  function metricEntitlementStage(entitlement) {
    if (entitlement?.mode === "legacy-subscriber-package") return "preview";
    if (entitlement?.usable === true && entitlement?.verified === true) {
      return entitlement.status === "valid" ? "enrolled" : "offline";
    }
    if (entitlement?.status === "expired" || entitlement?.usable === false) {
      return "expired";
    }
    return "unenrolled";
  }

  async function recordLocalProductMetric({
    eventType,
    stage,
    repoFingerprint = null,
    operationBinding = null,
    recordedAt = new Date().toISOString(),
    durationMilliseconds = null
  }) {
    try {
      return await writeRunrailProductMetricEvent({
        historyRoot: reviewHistoryRoot,
        event: createRunrailProductMetricEvent({
          eventType,
          stage,
          recordedAt,
          repoFingerprint,
          operationBinding,
          plan: currentMetricPlan,
          platform: metricPlatform(),
          version: desktopProductVersion,
          durationMilliseconds
        })
      });
    } catch (error) {
      metricWriteFailures.push({
        code:
          typeof error?.code === "string"
            ? error.code
            : "product-metric-write-failed",
        recordedAt: new Date().toISOString()
      });
      if (metricWriteFailures.length > 20) metricWriteFailures.shift();
      return null;
    }
  }

  async function reviewHistoryView(session) {
    const dispositions = await listRunrailReviewDispositions({
      historyRoot: reviewHistoryRoot,
      repoFingerprint: session.repoFingerprint,
      reviewId: session.reviewId
    });
    const verdict = evaluateRunrailReviewSession(session, dispositions);
    return {
      reviewId: session.reviewId,
      repoId: session.repoFingerprint,
      parentReviewId: session.parentReviewId,
      createdAt: session.createdAt,
      base: session.local.baseRef,
      candidate: session.local.candidateRef,
      verdict,
      evidence: session.evidence,
      dispositionCount: dispositions.length,
      boundaries: {
        localOnly: true,
        authority: "none",
        sourceContentIncluded: false,
        diffContentIncluded: false,
        rawCommandOutputIncluded: false
      }
    };
  }

  async function listHistory(repoFingerprint = null) {
    const sessions = repoFingerprint
      ? await listRunrailReviewSessions({
          historyRoot: reviewHistoryRoot,
          repoFingerprint,
          limit: 100
        })
      : await listAllRunrailReviewSessions({
          historyRoot: reviewHistoryRoot,
          limit: 100
        });
    return Promise.all(sessions.map(reviewHistoryView));
  }

  function rememberOwnedReview(result, context) {
    if (!result?.reportPath) return;
    const auditPath = path.resolve(result.reportPath);
    allowedAuditPaths.add(auditPath);
    if (result.coverage && result.patchPath && result.outputRoot && result.report) {
      coverageByAuditPath.set(auditPath, {
        audit: result.report,
        patchPath: path.resolve(result.patchPath),
        reviewRoot: path.resolve(result.outputRoot),
        coverage: result.coverage
      });
    }
    reviewContextByAuditPath.set(auditPath, {
      ...context,
      auditPath,
      coveragePath: result.coveragePath
        ? path.resolve(result.coveragePath)
        : path.join(path.dirname(auditPath), "coverage", "coverage.json"),
      passportPath: result.passportPath
        ? path.resolve(result.passportPath)
        : path.join(path.dirname(auditPath), "REVIEW_PASSPORT.json")
    });
  }

  async function persistReviewSession(result, context) {
    rememberOwnedReview(result, context);
    if (!result?.reportPath || !result?.coveragePath) return result;
    const repo = absoluteRepoPath(context.repo);
    const base = boundedText(context.base, "Base reference", 256);
    let candidate = boundedText(context.candidate, "Candidate reference", 256);
    const inspection = await inspectRunrailReviewRepository({ repo, base });
    if (context.guidedSample === true) {
      candidate = inspection.currentBranch || candidate;
    } else {
      const candidateName = referenceName(candidate);
      const matchingBranches = inspection.candidateLocalBranches.filter(
        (entry) => entry.ref === candidateName || entry.commit === candidate
      );
      if (matchingBranches.length !== 1) {
        const error = new Error(
          "The candidate must resolve to exactly one local branch ahead of the confirmed base."
        );
        error.code = "desktop-candidate-local-branch";
        throw error;
      }
      candidate = matchingBranches[0].ref;
    }
    const stored = await createRunrailReviewSession({
      repo,
      historyRoot: reviewHistoryRoot,
      base,
      candidate,
      auditPath: path.resolve(result.reportPath),
      coveragePath: path.resolve(result.coveragePath)
    });
    reviewContextByAuditPath.set(path.resolve(result.reportPath), {
      ...reviewContextByAuditPath.get(path.resolve(result.reportPath)),
      repo,
      base: stored.session.local.baseRef,
      candidate: stored.session.local.candidateRef,
      reviewId: stored.session.reviewId,
      guidedSample: context.guidedSample === true
    });
    const dispositions = await listRunrailReviewDispositions({
      historyRoot: reviewHistoryRoot,
      repoFingerprint: stored.session.repoFingerprint,
      reviewId: stored.session.reviewId
    });
    const verdict = evaluateRunrailReviewSession(stored.session, dispositions);
    const history = await listHistory(stored.session.repoFingerprint);
    return {
      ...result,
      reviewId: stored.session.reviewId,
      repoId: stored.session.repoFingerprint,
      session: stored.session,
      verdict,
      history,
      inspection: inspectionForDesktop(
        stored.inspection,
        stored.session.repoFingerprint,
        history
      )
    };
  }

  async function loadSessionByReviewId(value) {
    const reviewId = boundedText(value, "Review ID", 64);
    return findRunrailReviewSession({
      historyRoot: reviewHistoryRoot,
      reviewId
    });
  }

  async function readSessionAudit(session) {
    const artifactRoot = path.resolve(session.local.artifactRootPath);
    const auditPath = path.resolve(session.local.auditPath);
    if (
      !isInsideOrEqual(auditPath, artifactRoot) ||
      auditPath === artifactRoot
    ) {
      const error = new Error(
        "The review audit path escaped its local artifact root."
      );
      error.code = "desktop-audit-path";
      throw error;
    }
    const entry = await lstat(auditPath).catch(() => null);
    if (
      !entry ||
      entry.isSymbolicLink() ||
      !entry.isFile() ||
      entry.size < 2 ||
      entry.size > 2 * 1024 * 1024
    ) {
      const error = new Error(
        "The review audit is missing or no longer a bounded ordinary file."
      );
      error.code = "desktop-audit-invalid";
      throw error;
    }
    const canonicalAuditPath = await realpath(auditPath);
    if (
      canonicalAuditPath !== auditPath ||
      !isInsideOrEqual(canonicalAuditPath, artifactRoot)
    ) {
      const error = new Error(
        "The review audit no longer resolves inside its artifact root."
      );
      error.code = "desktop-audit-invalid";
      throw error;
    }
    let audit;
    try {
      audit = verifyRunrailAuditV4(
        JSON.parse(await readFile(canonicalAuditPath, "utf8"))
      );
    } catch {
      const error = new Error(
        "The review audit failed its schema or checksum verification."
      );
      error.code = "desktop-audit-invalid";
      throw error;
    }
    if (audit.checksumSha256 !== session.evidence.auditChecksumSha256) {
      const error = new Error(
        "The review audit does not belong to this immutable review session."
      );
      error.code = "desktop-audit-session-mismatch";
      throw error;
    }
    return audit;
  }

  async function assuranceHistoryForSession(session) {
    const visited = new Set([session.reviewId]);
    const historicalFindingIds = new Set();
    let parentReviewId = session.parentReviewId;
    let historicalReviewCount = 0;
    while (parentReviewId !== null) {
      if (historicalReviewCount >= 100 || visited.has(parentReviewId)) {
        const error = new Error(
          "The local review lineage is cyclic or exceeds its assurance boundary."
        );
        error.code = "desktop-assurance-lineage-invalid";
        throw error;
      }
      visited.add(parentReviewId);
      const parent = await loadSessionByReviewId(parentReviewId);
      if (parent.repoFingerprint !== session.repoFingerprint) {
        const error = new Error(
          "The local review lineage crossed a repository boundary."
        );
        error.code = "desktop-assurance-lineage-invalid";
        throw error;
      }
      historicalReviewCount += 1;
      for (const severity of ["high", "medium", "info"]) {
        for (const findingId of parent.evidence.findingIds[severity]) {
          historicalFindingIds.add(findingId);
        }
      }
      parentReviewId = parent.parentReviewId;
    }
    return {
      historicalFindingIds: [...historicalFindingIds],
      historicalReviewCount
    };
  }

  async function readSessionCoverage(session) {
    const artifactRoot = path.resolve(session.local.artifactRootPath);
    const coveragePath = path.resolve(session.local.coveragePath);
    if (
      !isInsideOrEqual(coveragePath, artifactRoot) ||
      coveragePath === artifactRoot
    ) {
      const error = new Error(
        "The Review Coverage path escaped its local artifact root."
      );
      error.code = "desktop-coverage-path";
      throw error;
    }
    const entry = await lstat(coveragePath).catch(() => null);
    if (
      !entry ||
      entry.isSymbolicLink() ||
      !entry.isFile() ||
      entry.size < 2 ||
      entry.size > 2 * 1024 * 1024
    ) {
      const error = new Error(
        "Review Coverage is missing or no longer a bounded ordinary file."
      );
      error.code = "desktop-coverage-invalid";
      throw error;
    }
    const canonicalCoveragePath = await realpath(coveragePath);
    if (
      canonicalCoveragePath !== coveragePath ||
      !isInsideOrEqual(canonicalCoveragePath, artifactRoot)
    ) {
      const error = new Error(
        "Review Coverage no longer resolves inside its artifact root."
      );
      error.code = "desktop-coverage-invalid";
      throw error;
    }
    let coverage;
    try {
      coverage = verifyRunrailHunkContinuity(
        JSON.parse(await readFile(canonicalCoveragePath, "utf8"))
      );
    } catch {
      const error = new Error(
        "Review Coverage failed its schema or checksum verification."
      );
      error.code = "desktop-coverage-invalid";
      throw error;
    }
    if (
      coverage.checksumSha256 !==
      session.evidence.coverageChecksumSha256
    ) {
      const error = new Error(
        "Review Coverage does not belong to this immutable review session."
      );
      error.code = "desktop-coverage-session-mismatch";
      throw error;
    }
    return coverage;
  }

  async function readSessionPatch(session, {
    audit = null,
    coverage = null
  } = {}) {
    const artifactRoot = path.resolve(session.local.artifactRootPath);
    const patchPath = path.join(artifactRoot, "candidate.patch");
    if (!isInsideOrEqual(patchPath, artifactRoot) || patchPath === artifactRoot) {
      const error = new Error(
        "The review diff path escaped its local artifact root."
      );
      error.code = "desktop-diff-path";
      throw error;
    }
    const entry = await lstat(patchPath).catch(() => null);
    if (
      !entry ||
      entry.isSymbolicLink() ||
      !entry.isFile() ||
      entry.size < 1 ||
      entry.size > maxDiffBytes
    ) {
      const error = new Error(
        "The review diff is missing or no longer a bounded ordinary file."
      );
      error.code = "desktop-diff-invalid";
      throw error;
    }
    const canonicalPatchPath = await realpath(patchPath);
    if (
      canonicalPatchPath !== patchPath ||
      !isInsideOrEqual(canonicalPatchPath, artifactRoot)
    ) {
      const error = new Error(
        "The review diff no longer resolves inside its artifact root."
      );
      error.code = "desktop-diff-invalid";
      throw error;
    }
    const handle = await openFile(
      canonicalPatchPath,
      fsConstants.O_RDONLY | (fsConstants.O_NOFOLLOW || 0)
    );
    let patchText;
    try {
      const openedEntry = await handle.stat();
      if (!openedEntry.isFile() || openedEntry.size !== entry.size) {
        const error = new Error(
          "The review diff changed while it was being verified."
        );
        error.code = "desktop-diff-invalid";
        throw error;
      }
      patchText = await handle.readFile({ encoding: "utf8" });
      if (Buffer.byteLength(patchText, "utf8") !== openedEntry.size) {
        const error = new Error(
          "The review diff changed while it was being read."
        );
        error.code = "desktop-diff-invalid";
        throw error;
      }
    } finally {
      await handle.close();
    }

    const verifiedAudit = audit || await readSessionAudit(session);
    const verifiedCoverage = coverage || await readSessionCoverage(session);
    const patchChecksum = sha256(patchText);
    if (
      patchChecksum !== verifiedAudit.policy.diffSha256 ||
      patchChecksum !== verifiedCoverage.source.diffSha256
    ) {
      const error = new Error(
        "The review diff does not match its immutable audit and Review Coverage."
      );
      error.code = "desktop-diff-checksum-mismatch";
      throw error;
    }
    return {
      patchText,
      patchPath: canonicalPatchPath,
      patchChecksum
    };
  }

  async function revisionComparisonAvailable() {
    try {
      await assertRunrailLocalFeatureAccess("revision-comparison", {
        opportunisticRenewal: false
      });
      return true;
    } catch (error) {
      if (error?.code === "runrail-feature-not-entitled") return false;
      throw error;
    }
  }

  async function assertAssuranceAncestry(beforeSession, currentSession) {
    if (
      beforeSession.reviewId === currentSession.reviewId ||
      beforeSession.repoFingerprint !== currentSession.repoFingerprint
    ) {
      const error = new Error(
        "Agent Assurance requires two distinct reviews from the same local repository history."
      );
      error.code = "desktop-assurance-lineage-invalid";
      throw error;
    }
    const visited = new Set([currentSession.reviewId]);
    let parentReviewId = currentSession.parentReviewId;
    for (let depth = 0; parentReviewId !== null && depth < 100; depth += 1) {
      if (visited.has(parentReviewId)) break;
      visited.add(parentReviewId);
      const parent = await loadSessionByReviewId(parentReviewId);
      if (parent.repoFingerprint !== currentSession.repoFingerprint) break;
      if (parent.reviewId === beforeSession.reviewId) return true;
      parentReviewId = parent.parentReviewId;
    }
    const error = new Error(
      "Agent Assurance requires a server-owned ancestor of the current review."
    );
    error.code = "desktop-assurance-lineage-invalid";
    throw error;
  }

  async function findAssuranceBaselineSession(currentSession) {
    const visited = new Set([currentSession.reviewId]);
    let parentReviewId = currentSession.parentReviewId;
    let immediateParent = null;
    for (let depth = 0; parentReviewId !== null && depth < 100; depth += 1) {
      if (visited.has(parentReviewId)) {
        const error = new Error(
          "The local review lineage is cyclic or exceeds its assurance boundary."
        );
        error.code = "desktop-assurance-lineage-invalid";
        throw error;
      }
      visited.add(parentReviewId);
      const parent = await loadSessionByReviewId(parentReviewId);
      if (parent.repoFingerprint !== currentSession.repoFingerprint) {
        const error = new Error(
          "The local review lineage crossed a repository boundary."
        );
        error.code = "desktop-assurance-lineage-invalid";
        throw error;
      }
      immediateParent ||= parent;
      if (
        parent.local.candidateCommit !== currentSession.local.candidateCommit
      ) {
        return parent;
      }
      parentReviewId = parent.parentReviewId;
    }
    if (parentReviewId !== null) {
      const error = new Error(
        "The local review lineage exceeds its assurance boundary."
      );
      error.code = "desktop-assurance-lineage-invalid";
      throw error;
    }
    return immediateParent;
  }

  async function findPersistedAssuranceResult(currentSession) {
    const assuranceRoot = path.join(
      currentSession.local.artifactRootPath,
      RUNRAIL_AGENT_ASSURANCE.outputDirectory
    );
    const rootEntry = await lstat(assuranceRoot).catch(() => null);
    if (!rootEntry) return null;
    if (
      rootEntry.isSymbolicLink() ||
      !rootEntry.isDirectory() ||
      await realpath(assuranceRoot) !== assuranceRoot
    ) {
      const error = new Error(
        "The Agent Assurance artifact root is not an ordinary local directory."
      );
      error.code = "desktop-assurance-artifact-invalid";
      throw error;
    }
    const entries = await readdir(assuranceRoot, { withFileTypes: true });
    if (entries.length > 256) {
      const error = new Error(
        "The Agent Assurance artifact root exceeds its inspection boundary."
      );
      error.code = "desktop-assurance-artifact-invalid";
      throw error;
    }
    const resultsBySourceAudit = new Map();
    for (const entry of entries) {
      if (!/^RAR-[A-F0-9]{24}$/u.test(entry.name)) continue;
      if (!entry.isDirectory() || entry.isSymbolicLink()) {
        const error = new Error(
          "A persisted Agent Assurance result directory is invalid."
        );
        error.code = "desktop-assurance-artifact-invalid";
        throw error;
      }
      const resultPath = path.join(assuranceRoot, entry.name, "result.json");
      const resultEntry = await lstat(resultPath).catch(() => null);
      if (
        !resultEntry ||
        resultEntry.isSymbolicLink() ||
        !resultEntry.isFile() ||
        resultEntry.size < 2 ||
        resultEntry.size > RUNRAIL_AGENT_ASSURANCE.maximumArtifactBytes ||
        await realpath(resultPath) !== resultPath
      ) {
        const error = new Error(
          "A persisted Agent Assurance result is invalid."
        );
        error.code = "desktop-assurance-artifact-invalid";
        throw error;
      }
      let result;
      try {
        result = verifyRunrailAgentAssuranceResult(
          JSON.parse(await readFile(resultPath, "utf8"))
        );
      } catch {
        const error = new Error(
          "A persisted Agent Assurance result failed verification."
        );
        error.code = "desktop-assurance-artifact-invalid";
        throw error;
      }
      if (
        result.currentEvidence.auditChecksumSha256 !==
          currentSession.evidence.auditChecksumSha256 ||
        result.currentEvidence.coverageChecksumSha256 !==
          currentSession.evidence.coverageChecksumSha256
      ) {
        continue;
      }
      resultsBySourceAudit.set(
        result.packet.sourceAuditChecksumSha256,
        { result, resultPath }
      );
    }
    if (resultsBySourceAudit.size === 0) return null;

    const visited = new Set([currentSession.reviewId]);
    let parentReviewId = currentSession.parentReviewId;
    for (let depth = 0; parentReviewId !== null && depth < 100; depth += 1) {
      if (visited.has(parentReviewId)) break;
      visited.add(parentReviewId);
      const parent = await loadSessionByReviewId(parentReviewId);
      if (parent.repoFingerprint !== currentSession.repoFingerprint) break;
      const stored = resultsBySourceAudit.get(
        parent.evidence.auditChecksumSha256
      );
      if (stored) {
        return {
          baseline: parent,
          ...stored
        };
      }
      parentReviewId = parent.parentReviewId;
    }
    const error = new Error(
      "A persisted Agent Assurance result no longer maps to this review lineage."
    );
    error.code = "desktop-assurance-stale";
    throw error;
  }

  async function buildAssuranceForSessions(beforeSession, currentSession) {
    await assertAssuranceAncestry(beforeSession, currentSession);
    const history = await assuranceHistoryForSession(beforeSession);
    const beforeAudit = await readSessionAudit(beforeSession);
    const currentAudit = await readSessionAudit(currentSession);
    const currentCoverage = await readSessionCoverage(currentSession);
    const packet = buildRunrailAgentAssurancePacket({
      audit: beforeAudit,
      ...history
    });
    const result = evaluateRunrailAgentAssurance({
      packet,
      beforeAudit,
      afterAudit: currentAudit,
      afterCoverage: currentCoverage
    });
    return {
      packet,
      result,
      beforeAudit,
      currentAudit,
      currentCoverage
    };
  }

  async function writeAssuranceForSessions(beforeSession, currentSession) {
    await assertAssuranceAncestry(beforeSession, currentSession);
    const packetWritten = await writeAssurancePacketForSession(beforeSession);
    const resultWritten = await writeRunrailAgentAssuranceResult({
      packet: packetWritten.packet,
      beforeAudit: await readSessionAudit(beforeSession),
      afterAudit: await readSessionAudit(currentSession),
      afterCoverage: await readSessionCoverage(currentSession),
      reviewRoot: currentSession.local.artifactRootPath
    });
    return {
      packet: packetWritten.packet,
      packetPath: packetWritten.packetPath,
      briefPath: packetWritten.briefPath,
      result: resultWritten.result,
      resultPath: resultWritten.resultPath,
      reviewPath: resultWritten.reviewPath,
      boundaries: {
        localOnly: true,
        pathFreePortableEvidence: true,
        projectTestsExecuted: false,
        patchApplied: false,
        networkUsed: false,
        providerUsed: false,
        authority: "none"
      }
    };
  }

  async function writeAssurancePacketForSession(session) {
    const history = await assuranceHistoryForSession(session);
    return writeRunrailAgentAssurancePacket({
      audit: await readSessionAudit(session),
      reviewRoot: session.local.artifactRootPath,
      ...history
    });
  }

  async function agentRegistryForSession(session = null) {
    const blockedRoots = [
      sourceRoot,
      distributionRoot,
      reviewHistoryRoot
    ];
    if (session) {
      blockedRoots.push(
        session.local.repositoryPath,
        session.local.artifactRootPath
      );
    }
    return agentRegistryFactory({ blockedRoots });
  }

  async function agentWorkingRoot(session) {
    const repositoryPath = path.resolve(session.local.repositoryPath);
    const entry = await lstat(repositoryPath).catch(() => null);
    if (!entry?.isDirectory() || entry.isSymbolicLink()) {
      const error = new Error(
        "The reviewed repository is no longer an ordinary local directory."
      );
      error.code = "agent-bridge-cwd-invalid";
      throw error;
    }
    const canonical = await realpath(repositoryPath);
    if (canonical !== repositoryPath) {
      const error = new Error(
        "The reviewed repository path now traverses a symbolic link."
      );
      error.code = "agent-bridge-cwd-invalid";
      throw error;
    }
    return canonical;
  }

  async function persistAgentLaunchReceipt(packetWritten, launchResult) {
    const receipt = createRunrailAgentLaunchReceipt({
      packetChecksumSha256: packetWritten.packet.checksumSha256,
      adapterId: launchResult.adapterId,
      startedAt: launchResult.startedAt,
      endedAt: launchResult.endedAt,
      outcome: launchResult.outcome,
      exitCode: launchResult.exitCode,
      signal: launchResult.signal
    });
    const packetRoot = path.dirname(path.resolve(packetWritten.packetPath));
    const launchRoot = path.join(packetRoot, "launches");
    if (
      !isInsideOrEqual(launchRoot, packetRoot) ||
      launchRoot === packetRoot
    ) {
      const error = new Error("Agent launch receipt root escaped its packet.");
      error.code = "agent-bridge-receipt-path";
      throw error;
    }
    await mkdir(launchRoot, { recursive: true, mode: 0o700 });
    const launchRootEntry = await lstat(launchRoot);
    if (
      !launchRootEntry.isDirectory() ||
      launchRootEntry.isSymbolicLink() ||
      await realpath(launchRoot) !== launchRoot
    ) {
      const error = new Error("Agent launch receipt root is unsafe.");
      error.code = "agent-bridge-receipt-path";
      throw error;
    }
    const receiptPath = path.join(launchRoot, `${receipt.receiptId}.json`);
    if (
      !isInsideOrEqual(receiptPath, launchRoot) ||
      receiptPath === launchRoot
    ) {
      const error = new Error("Agent launch receipt path escaped its root.");
      error.code = "agent-bridge-receipt-path";
      throw error;
    }
    const serialized = stableRunrailAgentLaunchReceiptJson(receipt);
    const existing = await lstat(receiptPath).catch(() => null);
    if (existing) {
      if (
        !existing.isFile() ||
        existing.isSymbolicLink() ||
        existing.size < 2 ||
        existing.size > 32 * 1024 ||
        await realpath(receiptPath) !== receiptPath
      ) {
        const error = new Error("Existing agent launch receipt is unsafe.");
        error.code = "agent-bridge-receipt-invalid";
        throw error;
      }
      const stored = verifyRunrailAgentLaunchReceipt(
        JSON.parse(await readFile(receiptPath, "utf8"))
      );
      if (stored.checksumSha256 !== receipt.checksumSha256) {
        const error = new Error(
          "A different agent launch receipt already uses this identity."
        );
        error.code = "agent-bridge-receipt-exists";
        throw error;
      }
      return stored;
    }
    const handle = await openFile(receiptPath, "wx", 0o600);
    try {
      await handle.writeFile(serialized, "utf8");
      await handle.sync();
    } finally {
      await handle.close();
    }
    if (process.platform !== "win32") await chmod(receiptPath, 0o600);
    return verifyRunrailAgentLaunchReceipt(
      JSON.parse(await readFile(receiptPath, "utf8"))
    );
  }

  async function hydrateReviewSession(session) {
    const audit = await readSessionAudit(session);
    const coverage = await readSessionCoverage(session);
    const patch = await readSessionPatch(session, { audit, coverage });
    const { passport, passportPath } = await readSessionPassport(session);
    const dispositions = await listRunrailReviewDispositions({
      historyRoot: reviewHistoryRoot,
      repoFingerprint: session.repoFingerprint,
      reviewId: session.reviewId
    });
    const history = await listHistory(session.repoFingerprint);
    const verdict = evaluateRunrailReviewSession(session, dispositions);
    const externalEvidence = await listRunrailExternalEvidenceReceipts({
      artifactRoot: session.local.artifactRootPath
    });
    rememberOwnedReview({
      reportPath: session.local.auditPath,
      coveragePath: session.local.coveragePath,
      passportPath,
      patchPath: patch.patchPath,
      outputRoot: session.local.artifactRootPath,
      report: audit,
      coverage
    }, {
      repo: session.local.repositoryPath,
      base: session.local.baseRef,
      candidate: session.local.candidateRef,
      guidedSample: false
    });

    const mappedBaselineId = assuranceBaselineByReviewId.get(session.reviewId);
    const persistedAssurance = mappedBaselineId
      ? null
      : await findPersistedAssuranceResult(session);
    const baseline = mappedBaselineId
      ? await loadSessionByReviewId(mappedBaselineId)
      : persistedAssurance?.baseline ||
        await findAssuranceBaselineSession(session);
    const computedAssurance = baseline
      ? await buildAssuranceForSessions(baseline, session)
      : null;
    let assurance = computedAssurance;
    let assurancePersisted = false;
    if (computedAssurance) {
      const resultPath = persistedAssurance?.resultPath || path.join(
        session.local.artifactRootPath,
        RUNRAIL_AGENT_ASSURANCE.outputDirectory,
        computedAssurance.result.resultId,
        "result.json"
      );
      const resultEntry = await lstat(resultPath).catch(() => null);
      if (resultEntry) {
        if (
          resultEntry.isSymbolicLink() ||
          !resultEntry.isFile() ||
          resultEntry.size < 2 ||
          resultEntry.size > RUNRAIL_AGENT_ASSURANCE.maximumArtifactBytes ||
          await realpath(resultPath) !== resultPath
        ) {
          const error = new Error(
            "The persisted Agent Assurance result is not a bounded ordinary artifact."
          );
          error.code = "desktop-assurance-artifact-invalid";
          throw error;
        }
        let storedResult;
        try {
          storedResult = persistedAssurance?.result ||
            verifyRunrailAgentAssuranceResult(
              JSON.parse(await readFile(resultPath, "utf8"))
            );
        } catch {
          const error = new Error(
            "The persisted Agent Assurance result failed verification."
          );
          error.code = "desktop-assurance-artifact-invalid";
          throw error;
        }
        if (
          storedResult.checksumSha256 !==
          computedAssurance.result.checksumSha256
        ) {
          const error = new Error(
            "The persisted Agent Assurance result is stale for this review."
          );
          error.code = "desktop-assurance-stale";
          throw error;
        }
        assurance = {
          ...computedAssurance,
          result: storedResult
        };
        assurancePersisted = true;
      }
    }
    const weekStartedAt = new Date();
    weekStartedAt.setUTCHours(0, 0, 0, 0);
    weekStartedAt.setUTCDate(
      weekStartedAt.getUTCDate() - ((weekStartedAt.getUTCDay() + 6) % 7)
    );
    const currentWeekReviews = history.filter(
      (entry) => Date.parse(entry.createdAt) >= weekStartedAt.getTime()
    );
    return {
      ok: true,
      reviewId: session.reviewId,
      repoId: session.repoFingerprint,
      session,
      report: audit,
      reportPath: session.local.auditPath,
      focus: buildRunrailReviewFocus(audit),
      coverage,
      coveragePath: session.local.coveragePath,
      passport,
      passportPath,
      dispositions,
      verdict,
      externalEvidence,
      assurance: assurance
        ? {
            beforeReviewId: baseline.reviewId,
            packet: assurance.packet,
            result: assurance.result,
            persisted: assurancePersisted,
            boundaries: {
              localOnly: true,
              pathFreePortableEvidence: true,
              projectTestsExecuted: false,
              patchApplied: false,
              networkUsed: false,
              providerUsed: false,
              authority: "none"
            }
          }
        : null,
      history,
      weeklyState: {
        weekStartedAt: weekStartedAt.toISOString(),
        reviewCount: currentWeekReviews.length,
        currentReviewId: session.reviewId,
        currentVerdict: verdict.status,
        unresolvedAttentionCount:
          Number(coverage.summary.unreviewedCount || 0) +
          Number(coverage.summary.needsRevisionCount || 0)
      },
      boundaries: {
        localOnly: true,
        serverOwnedReviewId: true,
        checksumVerified: true,
        pathFree: false,
        localArtifactPathsIncluded: true,
        browserStorage: false,
        portableExport: false,
        sourceMutation: false,
        projectTestsExecuted: false,
        networkUsed: false,
        authority: "none"
      }
    };
  }

  async function readSessionPassport(session) {
    const artifactRoot = path.resolve(session.local.artifactRootPath);
    const passportPath = path.join(artifactRoot, "REVIEW_PASSPORT.json");
    if (!isInsideOrEqual(passportPath, artifactRoot) || passportPath === artifactRoot) {
      const error = new Error("The review passport path escaped its local artifact root.");
      error.code = "desktop-passport-path";
      throw error;
    }
    const entry = await lstat(passportPath).catch(() => null);
    if (!entry || entry.isSymbolicLink() || !entry.isFile() || entry.size > 256 * 1024) {
      const error = new Error("The review passport is missing or no longer an ordinary file.");
      error.code = "desktop-passport-invalid";
      throw error;
    }
    const canonicalPassportPath = await realpath(passportPath);
    if (
      canonicalPassportPath !== passportPath ||
      !isInsideOrEqual(canonicalPassportPath, artifactRoot)
    ) {
      const error = new Error("The review passport no longer resolves inside its artifact root.");
      error.code = "desktop-passport-invalid";
      throw error;
    }
    let passport;
    try {
      passport = verifyRunrailReviewPassport(
        JSON.parse(await readFile(canonicalPassportPath, "utf8"))
      );
    } catch {
      const error = new Error("The review passport failed its schema or checksum verification.");
      error.code = "desktop-passport-invalid";
      throw error;
    }
    if (passport.auditChecksumSha256 !== session.evidence.auditChecksumSha256) {
      const error = new Error("The review passport does not belong to this immutable review session.");
      error.code = "desktop-passport-session-mismatch";
      throw error;
    }
    return { passport, passportPath: canonicalPassportPath };
  }

  async function persistDeviceSignedPassport(session, signedPassport) {
    verifyRunrailDeviceSignedReviewPassport(signedPassport);
    const artifactRoot = path.resolve(session.local.artifactRootPath);
    const signedPassportPath = path.join(
      artifactRoot,
      "REVIEW_PASSPORT.device-signed.json"
    );
    if (
      !isInsideOrEqual(signedPassportPath, artifactRoot) ||
      signedPassportPath === artifactRoot
    ) {
      const error = new Error("The device-signed passport path escaped its local artifact root.");
      error.code = "desktop-passport-path";
      throw error;
    }
    const existing = await lstat(signedPassportPath).catch(() => null);
    if (existing) {
      if (
        existing.isSymbolicLink() ||
        !existing.isFile() ||
        existing.size < 2 ||
        existing.size > 512 * 1024
      ) {
        const error = new Error("The existing device-signed passport is not a bounded ordinary file.");
        error.code = "desktop-passport-invalid";
        throw error;
      }
      const canonicalPath = await realpath(signedPassportPath);
      if (
        canonicalPath !== signedPassportPath ||
        !isInsideOrEqual(canonicalPath, artifactRoot)
      ) {
        const error = new Error("The existing device-signed passport traverses a symbolic link.");
        error.code = "desktop-passport-invalid";
        throw error;
      }
      let parsed;
      try {
        parsed = verifyRunrailDeviceSignedReviewPassport(
          JSON.parse(await readFile(canonicalPath, "utf8"))
        );
      } catch {
        const error = new Error("The existing device-signed passport failed verification.");
        error.code = "desktop-passport-invalid";
        throw error;
      }
      if (parsed.checksumSha256 !== signedPassport.checksumSha256) {
        const error = new Error(
          "A different device-signed passport already exists for this immutable review."
        );
        error.code = "desktop-passport-exists";
        throw error;
      }
      return canonicalPath;
    }
    const handle = await openFile(signedPassportPath, "wx", 0o600);
    try {
      await handle.writeFile(stableRunrailPassportJson(signedPassport), "utf8");
      await handle.sync();
    } finally {
      await handle.close();
    }
    if (process.platform !== "win32") await chmod(signedPassportPath, 0o600);
    const stored = verifyRunrailDeviceSignedReviewPassport(
      JSON.parse(await readFile(signedPassportPath, "utf8"))
    );
    if (stored.checksumSha256 !== signedPassport.checksumSha256) {
      const error = new Error("The stored device-signed passport did not verify.");
      error.code = "desktop-passport-write-invalid";
      throw error;
    }
    return signedPassportPath;
  }

  async function runTrackedOperation(operation, requestOperations = null) {
    if (!acceptingOperations) {
      const error = new Error("Runrail Desktop is shutting down.");
      error.code = "desktop-shutting-down";
      throw error;
    }
    if (!operation?.result || typeof operation.result.then !== "function") {
      try {
        if (typeof operation?.stop === "function") void operation.stop();
        else if (operation?.child?.exitCode === null) operation.child.kill();
      } catch {}
      const error = new Error("The local Runrail command did not create a trackable operation.");
      error.code = "desktop-operation-invalid";
      throw error;
    }
    activeOperations.add(operation);
    requestOperations?.add(operation);
    try {
      return await operation.result;
    } finally {
      activeOperations.delete(operation);
      requestOperations?.delete(operation);
    }
  }

  async function runCli(args, options = {}, requestOperations = null) {
    return runTrackedOperation(
      cliOperationFactory(args, options),
      requestOperations
    );
  }

  async function effectivePublicPreviewReviewRecord() {
    const record = await loadPublicPreviewReviewRecord(
      publicPreviewReviewHistoryRoot
    );
    if (record) return record;
    const sessions = await listAllRunrailReviewSessions({
      historyRoot: publicPreviewReviewHistoryRoot,
      limit: 2
    });
    if (sessions.length === 0) return null;
    if (sessions.length !== 1) {
      const error = new Error(
        "The isolated public-preview history contains an invalid review count."
      );
      error.code = "desktop-preview-review-record-invalid";
      throw error;
    }
    const [session] = sessions;
    return writePublicPreviewReviewRecord(publicPreviewReviewHistoryRoot, {
      reviewId: session.reviewId,
      auditChecksumSha256: session.evidence.auditChecksumSha256,
      createdAt: session.createdAt
    });
  }

  async function publicPreviewReviewStatus() {
    const record = await effectivePublicPreviewReviewRecord();
    return Object.freeze({
      available: record === null,
      used: record !== null,
      reviewId: record?.reviewId || null,
      candidateReviewLimit: 1,
      candidateReviewCount: record?.candidateReviewCount || 0,
      rerunAvailable: false,
      authority: "none"
    });
  }

  async function assertPublicPreviewReviewOwnership(reviewId) {
    const record = await effectivePublicPreviewReviewRecord();
    if (!record || record.reviewId !== String(reviewId || "")) {
      const error = new Error(
        "Public preview access is limited to the one review created by this installation."
      );
      error.code = "desktop-preview-review-not-owned";
      throw error;
    }
    return record;
  }

  async function assertPublicPreviewMutationAccess(route, body) {
    const access = await assertRunrailLocalDesktopAccess({
      opportunisticRenewal: false
    });
    reviewHistoryRoot = access.previewMode
      ? publicPreviewReviewHistoryRoot
      : subscriberReviewHistoryRoot;
    if (!access.previewMode) return false;
    if (access.publicPreviewCandidateReview !== true) {
      const error = new Error(
        "This Runrail preview does not include a bounded candidate review."
      );
      error.code = "runrail-feature-not-entitled";
      throw error;
    }
    if (route === "/api/review") {
      const status = await publicPreviewReviewStatus();
      if (!status.available) {
        const error = new Error(
          "This installation already used its one real public-preview review. Enroll Starter or Pro to review another candidate."
        );
        error.code = "desktop-preview-review-limit-reached";
        throw error;
      }
      return true;
    }
    if (route === "/api/review/handoff") {
      await assertPublicPreviewReviewOwnership(body.reviewId);
      return true;
    }
    if (route === "/api/coverage") {
      const auditPath = path.resolve(
        boundedText(body.auditPath, "Audit path")
      );
      const record = await effectivePublicPreviewReviewRecord();
      const ownedReview = coverageByAuditPath.get(auditPath);
      if (
        !record ||
        !allowedAuditPaths.has(auditPath) ||
        !ownedReview?.audit ||
        ownedReview.audit.checksumSha256 !== record.auditChecksumSha256
      ) {
        const error = new Error(
          "Public preview coverage requires the review created by this Desktop session."
        );
        error.code = "desktop-preview-review-not-owned";
        throw error;
      }
      return true;
    }
    const error = new Error(
      "This action requires an active Starter or Pro entitlement."
    );
    error.code = "runrail-feature-not-entitled";
    throw error;
  }

  async function assertReviewHistoryOrPublicPreviewAccess(reviewId, {
    deviceSigningRequested = false
  } = {}) {
    const access = await assertRunrailLocalDesktopAccess({
      opportunisticRenewal: false
    });
    if (!access.previewMode) {
      reviewHistoryRoot = subscriberReviewHistoryRoot;
      return assertRunrailLocalHistoryAccess({
        opportunisticRenewal: false
      });
    }
    reviewHistoryRoot = publicPreviewReviewHistoryRoot;
    if (deviceSigningRequested) {
      const error = new Error(
        "Device-signed passports require an enrolled Pro device."
      );
      error.code = "runrail-feature-not-entitled";
      throw error;
    }
    return assertPublicPreviewReviewOwnership(reviewId);
  }

  async function stopOperations(operations) {
    const uniqueOperations = [...new Set(operations)];
    await Promise.allSettled(uniqueOperations.map((operation) => {
      if (typeof operation?.stop === "function") return operation.stop();
      const child = operation?.child;
      if (!childStillRunning(child)) return Promise.resolve(false);
      try {
        child.kill();
      } catch {}
      return Promise.resolve(true);
    }));
    await Promise.allSettled(uniqueOperations.map((operation) => operation.result));
    return uniqueOperations.length;
  }

  function beginOperationShutdown() {
    if (operationShutdownPromise) return operationShutdownPromise;
    acceptingOperations = false;
    const operations = [...activeOperations];
    operationShutdownPromise = (async () => {
      await stopOperations(operations);
      while (clientCleanupPromises.size > 0) {
        await Promise.allSettled([...clientCleanupPromises]);
      }
      return operations.length;
    })();
    return operationShutdownPromise;
  }

  function closeServer() {
    if (serverClosePromise) return serverClosePromise;
    serverClosePromise = (async () => {
      const stoppedOperationCount = await beginOperationShutdown();
      if (server.listening) {
        await new Promise((resolve, reject) => {
          server.close((error) => {
            if (error) reject(error);
            else resolve();
          });
        });
      }
      return stoppedOperationCount;
    })();
    return serverClosePromise;
  }

  function trackClientCleanup(cleanup) {
    clientCleanupPromises.add(cleanup);
    cleanup.then(
      () => clientCleanupPromises.delete(cleanup),
      () => clientCleanupPromises.delete(cleanup)
    );
    return cleanup;
  }

  async function handleRequest(request, response) {
    const requestStartedAt = Date.now();
    const requestOperations = new Set();
    let requestCleanupPromise = null;
    let ownsCommandLock = false;
    const releaseCommandLock = () => {
      if (!ownsCommandLock) return;
      debugCommandLock("release", activeCommandRoute);
      busy = false;
      activeCommandRoute = "";
      ownsCommandLock = false;
    };
    const sendCommandJson = (statusCode, payload) => {
      releaseCommandLock();
      return sendJson(response, statusCode, payload);
    };
    const stopRequestOperations = () => {
      if (!requestCleanupPromise) {
        requestCleanupPromise = trackClientCleanup(stopOperations([...requestOperations]));
      }
      return requestCleanupPromise;
    };
    const stopForDisconnectedClient = () => {
      void stopRequestOperations();
    };
    request.once("aborted", stopForDisconnectedClient);
    request.once("error", stopForDisconnectedClient);
    response.once("error", stopForDisconnectedClient);
    response.once("close", () => {
      if (!response.writableFinished) stopForDisconnectedClient();
    });

    try {
      applySecurityHeaders(response, origin);
      if (request.headers.host !== origin.slice("http://".length)) {
        sendJson(response, 421, { ok: false, code: "desktop-host-rejected" });
        return;
      }
      const requestUrl = new URL(request.url || "/", origin);

      if (request.method === "GET" && staticFiles.has(requestUrl.pathname)) {
        const asset = staticFiles.get(requestUrl.pathname);
        try {
          const body = await readFile(path.join(desktopRoot, asset.file));
          sendBody(response, 200, asset.type, body);
        } catch {
          sendJson(response, 404, { ok: false, code: "desktop-asset-missing" });
        }
        return;
      }

      if (!requestUrl.pathname.startsWith("/api/")) {
        sendJson(response, 404, { ok: false, code: "desktop-route-not-found" });
        return;
      }
      if (request.method !== "POST") {
        sendJson(response, 405, { ok: false, code: "desktop-method-not-allowed" });
        return;
      }
      if (request.headers.origin !== origin) {
        sendJson(response, 403, { ok: false, code: "desktop-origin-rejected" });
        return;
      }
      if (request.headers["x-runrail-session"] !== sessionToken) {
        sendJson(response, 401, { ok: false, code: "desktop-session-rejected" });
        return;
      }
      if (requestUrl.pathname !== "/api/quit") {
        if (busy) {
          debugCommandLock("reject", `${requestUrl.pathname} owner=${activeCommandRoute}`);
          sendJson(response, 409, { ok: false, code: "desktop-command-in-progress" });
          return;
        }
        busy = true;
        activeCommandRoute = requestUrl.pathname;
        ownsCommandLock = true;
        debugCommandLock("acquire", activeCommandRoute);
      }

      reviewHistoryRoot = subscriberReviewHistoryRoot;
      const body = await readJsonBody(
        request,
        requestUrl.pathname === "/api/review/evidence/import"
          ? maxExternalEvidenceBodyBytes
          : maxBodyBytes
      );
      if (entitlementMutationRoutes.has(requestUrl.pathname)) {
        const previewAuthorized = await assertPublicPreviewMutationAccess(
          requestUrl.pathname,
          body
        );
        if (!previewAuthorized) {
          await assertRunrailLocalFeatureAccess("candidate-branch-review", {
            opportunisticRenewal: false
          });
        }
      }
      if (requestUrl.pathname === "/api/license/enroll-handoff") {
        if (
          !body ||
          typeof body !== "object" ||
          Array.isArray(body) ||
          JSON.stringify(Object.keys(body).sort()) !== JSON.stringify(["code"])
        ) {
          sendCommandJson(400, {
            ok: false,
            code: "desktop-enrollment-handoff-invalid",
            authority: "none"
          });
          return;
        }
        const result = await enrollRunrailDeviceFromHandoff({ code: body.code });
        sendCommandJson(200, result);
        return;
      }
      if (requestUrl.pathname === "/api/license/enroll-request") {
        if (!body || typeof body !== "object" || Array.isArray(body) || Object.keys(body).length !== 0) {
          sendCommandJson(400, {
            ok: false,
            code: "desktop-enrollment-request-invalid",
            authority: "none"
          });
          return;
        }
        const result = await createRunrailNativeEnrollmentHandoff();
        sendCommandJson(201, result);
        return;
      }
      if (requestUrl.pathname === "/api/status") {
        const [doctor, entitlement] = await Promise.all([
          runCli(["doctor"], {}, requestOperations),
          runCli(["license"], {}, requestOperations)
        ]);
        const desktopEntitlement = entitlement?.mode === "public-preview"
          ? {
              ...entitlement,
              previewReview: await publicPreviewReviewStatus()
            }
          : entitlement;
        reviewHistoryRoot = desktopEntitlement?.mode === "public-preview"
          ? publicPreviewReviewHistoryRoot
          : subscriberReviewHistoryRoot;
        currentMetricPlan = String(desktopEntitlement?.planCode || "preview")
          .toLowerCase()
          .replace(/[^a-z0-9._-]+/g, "-")
          .slice(0, 32) || "preview";
        if (!activationMetricRecorded) {
          await recordLocalProductMetric({
            eventType: "activation-stage",
            stage: metricEntitlementStage(desktopEntitlement),
            operationBinding: desktopMetricBinding,
            durationMilliseconds: Date.now() - requestStartedAt
          });
          activationMetricRecorded = true;
        }
        sendCommandJson(200, {
          ok: true,
          mode: "loopback-local",
          offlineDefault: true,
          repositoryUpload: false,
          sourceApplyAvailable: false,
          projectTestsExecuted: false,
          initialRepo: initialRepo ? path.resolve(initialRepo) : "",
          deepseekConfigured: Boolean(
            process.env.RUNRAIL_DEEPSEEK_ADVISORY_ENABLED === "true" &&
            process.env.RUNRAIL_DEEPSEEK_ADVISORY_API_KEY
          ),
          doctor,
          entitlement: desktopEntitlement,
          nativeMigration
        });
        return;
      }

      if (requestUrl.pathname === "/api/metrics/summary") {
        assertExactRequestKeys(body, [], "Product metrics summary");
        const summary = await loadRunrailProductMetricsSummary({
          historyRoot: reviewHistoryRoot,
          asOf: new Date().toISOString()
        });
        sendCommandJson(200, {
          ok: true,
          summary,
          integrity: {
            localWriteFailureCount: metricWriteFailures.length,
            healthy: metricWriteFailures.length === 0
          },
          boundaries: {
            localOnly: true,
            rawEventsReturned: false,
            repositoryFingerprintReturned: false,
            operationBindingReturned: false,
            dailyAggregateOnlyIfUploadAddedLater: true,
            uploadAvailable: false,
            uploadEnabled: false,
            explicitConsentRequired: true,
            networkUsed: false,
            authority: "none"
          }
        });
        return;
      }

      if (requestUrl.pathname === "/api/repository/inspect") {
        assertExactRequestKeys(body, ["repo", "base"], "Repository inspection");
        const desktopAccess = await assertRunrailLocalDesktopAccess({
          opportunisticRenewal: false
        });
        reviewHistoryRoot = desktopAccess.previewMode
          ? publicPreviewReviewHistoryRoot
          : subscriberReviewHistoryRoot;
        const repo = absoluteRepoPath(body.repo);
        const initialInspection = await inspectRunrailReviewRepository({ repo });
        const requestedBase = String(body.base || "").trim();
        const selectedBase = requestedBase ||
          initialInspection.defaultBaseCandidates.at(0)?.ref ||
          null;
        const inspection = selectedBase
          ? await inspectRunrailReviewRepository({ repo, base: selectedBase })
          : initialInspection;
        if (desktopAccess.sampleOnlyMode) {
          sendCommandJson(200, {
            ok: true,
            repoId: "",
            inspection: inspectionForDesktop(inspection, "", []),
            history: [],
            boundaries: {
              localOnly: true,
              previewReadinessOnly: true,
              repositoryIdentityPersisted: false,
              historyLoaded: false,
              sourceContentReturned: false,
              diffContentReturned: false,
              repositoryUpload: false,
              sourceMutation: false,
              projectTestsExecuted: false,
              networkUsed: false,
              authority: "none"
            }
          });
          return;
        }
        const repoId = await createRunrailRepoFingerprint({
          historyRoot: reviewHistoryRoot,
          repo,
          inspection
        });
        const history = await listHistory(repoId);
        sendCommandJson(200, {
          ok: true,
          repoId,
          inspection: inspectionForDesktop(inspection, repoId, history),
          history,
          boundaries: {
            localOnly: true,
            previewReadinessOnly: false,
            repositoryIdentityPersisted: true,
            historyLoaded: true,
            sourceContentReturned: false,
            diffContentReturned: false,
            authority: "none",
            repositoryUpload: false,
            sourceMutation: false,
            projectTestsExecuted: false,
            networkUsed: false
          }
        });
        return;
      }

      if (requestUrl.pathname === "/api/history/list") {
        await assertRunrailLocalHistoryAccess({
          opportunisticRenewal: false
        });
        const repoId = body.repoId
          ? boundedText(body.repoId, "Repository ID", 80)
          : null;
        const history = await listHistory(repoId);
        sendCommandJson(200, {
          ok: true,
          repoId,
          history,
          count: history.length,
          boundaries: {
            localOnly: true,
            authority: "none",
            sourceContentIncluded: false,
            diffContentIncluded: false,
            rawCommandOutputIncluded: false
          }
        });
        return;
      }

      if (requestUrl.pathname === "/api/review/open") {
        assertExactRequestKeys(body, ["reviewId"], "Review open");
        await assertReviewHistoryOrPublicPreviewAccess(body.reviewId);
        const session = await loadSessionByReviewId(body.reviewId);
        sendCommandJson(200, await hydrateReviewSession(session));
        return;
      }

      if (requestUrl.pathname === "/api/review/diff") {
        assertExactRequestKeys(body, ["reviewId"], "Review diff");
        await assertReviewHistoryOrPublicPreviewAccess(body.reviewId);
        const session = await loadSessionByReviewId(body.reviewId);
        const audit = await readSessionAudit(session);
        const coverage = await readSessionCoverage(session);
        const patch = await readSessionPatch(session, { audit, coverage });
        sendCommandJson(200, {
          ok: true,
          reviewId: session.reviewId,
          repoId: session.repoFingerprint,
          source: {
            auditChecksumSha256: audit.checksumSha256,
            coverageChecksumSha256: coverage.checksumSha256,
            diffSha256: patch.patchChecksum
          },
          diff: buildRunrailDiffInspection(patch.patchText, coverage),
          boundaries: {
            localOnly: true,
            serverOwnedReviewId: true,
            checksumVerified: true,
            boundedInMemoryDelivery: true,
            pathFree: false,
            sourceContentIncluded: true,
            diffContentIncluded: true,
            browserStorage: false,
            portableExport: false,
            sourceMutation: false,
            projectTestsExecuted: false,
            networkUsed: false,
            authority: "none"
          }
        });
        return;
      }

      if (requestUrl.pathname === "/api/review/evidence/import") {
        await assertRunrailLocalFeatureAccess("candidate-branch-review", {
          opportunisticRenewal: false
        });
        assertExactRequestKeys(
          body,
          ["reviewId", "format", "contentBase64", "sourceSha256"],
          "External evidence import"
        );
        const session = await loadSessionByReviewId(body.reviewId);
        const audit = await readSessionAudit(session);
        const dispositions = await listRunrailReviewDispositions({
          historyRoot: reviewHistoryRoot,
          repoFingerprint: session.repoFingerprint,
          reviewId: session.reviewId
        });
        const verdictBefore = evaluateRunrailReviewSession(
          session,
          dispositions
        );
        const receipt = createRunrailExternalEvidenceReceipt({
          reviewId: session.reviewId,
          format: body.format,
          contentBase64: body.contentBase64,
          sourceSha256: body.sourceSha256,
          candidateCommit: audit.source.candidateCommit,
          reviewAuditChecksumSha256: audit.checksumSha256
        });
        const written = await writeRunrailExternalEvidenceReceipt({
          artifactRoot: session.local.artifactRootPath,
          receipt
        });
        const verdictAfter = evaluateRunrailReviewSession(
          session,
          dispositions
        );
        if (JSON.stringify(verdictAfter) !== JSON.stringify(verdictBefore)) {
          const error = new Error(
            "External evidence import attempted to alter the deterministic verdict."
          );
          error.code = "external-evidence-authority-invalid";
          throw error;
        }
        sendCommandJson(200, {
          ok: true,
          reviewId: session.reviewId,
          receipt: written.receipt,
          created: written.created,
          externalEvidence: await listRunrailExternalEvidenceReceipts({
            artifactRoot: session.local.artifactRootPath
          }),
          verdict: verdictAfter,
          boundaries: {
            localOnly: true,
            checksumBound: true,
            aggregateOnly: true,
            pathFreePortableReceipt: true,
            rawEvidencePersisted: false,
            commandExecuted: false,
            projectCodeExecuted: false,
            projectTestsExecutedByRunrail: false,
            verdictChanged: false,
            assuranceChanged: false,
            sourceMutation: false,
            networkUsed: false,
            authority: "none"
          }
        });
        return;
      }

      if (requestUrl.pathname === "/api/review/assure") {
        await assertRunrailLocalFeatureAccess("candidate-branch-review", {
          opportunisticRenewal: false
        });
        assertExactRequestKeys(
          body,
          ["beforeReviewId", "currentReviewId"],
          "Agent Assurance"
        );
        const beforeSession = await loadSessionByReviewId(body.beforeReviewId);
        const currentSession = await loadSessionByReviewId(
          body.currentReviewId
        );
        const assurance = await writeAssuranceForSessions(
          beforeSession,
          currentSession
        );
        await recordLocalProductMetric({
          eventType: "assurance-completed",
          stage: assurance.result.status,
          repoFingerprint: currentSession.repoFingerprint,
          operationBinding:
            `${beforeSession.reviewId}\0${currentSession.reviewId}`,
          recordedAt: currentSession.createdAt,
          durationMilliseconds: Date.now() - requestStartedAt
        });
        assuranceBaselineByReviewId.set(
          currentSession.reviewId,
          beforeSession.reviewId
        );
        sendCommandJson(200, {
          ok: true,
          beforeReviewId: beforeSession.reviewId,
          currentReviewId: currentSession.reviewId,
          assurance
        });
        return;
      }

      if (requestUrl.pathname === "/api/outcomes/list") {
        await assertRunrailLocalFeatureAccess("advanced-evidence-exports", {
          opportunisticRenewal: false
        });
        assertExactRequestKeys(body, ["repoId"], "Agent outcome list");
        const repoId = boundedText(body.repoId, "Repository ID", 80);
        const outcomes = await listRunrailAgentOutcomes({
          historyRoot: reviewHistoryRoot,
          repoFingerprint: repoId
        });
        sendCommandJson(200, {
          ok: true,
          repoId,
          outcomes,
          summary: buildRunrailAgentOutcomeSummary({
            repoFingerprint: repoId,
            outcomes
          }),
          boundaries: {
            localOnly: true,
            repositoryLocal: true,
            explicitAgentLabelsOnly: true,
            verifiedRerunsOnly: true,
            globalModelScore: false,
            crossRepositoryRanking: false,
            agentQualityClaim: false,
            sourceMutation: false,
            networkUsed: false,
            authority: "none"
          }
        });
        return;
      }

      if (requestUrl.pathname === "/api/outcomes/record") {
        await assertRunrailLocalFeatureAccess("advanced-evidence-exports", {
          opportunisticRenewal: false
        });
        assertExactRequestKeys(
          body,
          ["beforeReviewId", "currentReviewId", "agentId"],
          "Agent outcome record"
        );
        const beforeSession = await loadSessionByReviewId(
          body.beforeReviewId
        );
        const currentSession = await loadSessionByReviewId(
          body.currentReviewId
        );
        const assurance = await buildAssuranceForSessions(
          beforeSession,
          currentSession
        );
        const outcome = createRunrailAgentOutcome({
          repoFingerprint: currentSession.repoFingerprint,
          beforeReviewId: beforeSession.reviewId,
          currentReviewId: currentSession.reviewId,
          agentId: body.agentId,
          recordedAt: currentSession.createdAt,
          assuranceResult: assurance.result
        });
        const written = await writeRunrailAgentOutcome({
          historyRoot: reviewHistoryRoot,
          outcome
        });
        const outcomes = await listRunrailAgentOutcomes({
          historyRoot: reviewHistoryRoot,
          repoFingerprint: currentSession.repoFingerprint
        });
        sendCommandJson(200, {
          ok: true,
          created: written.created,
          outcome: written.outcome,
          outcomes,
          summary: buildRunrailAgentOutcomeSummary({
            repoFingerprint: currentSession.repoFingerprint,
            outcomes
          }),
          boundaries: {
            localOnly: true,
            repositoryLocal: true,
            sourceFree: true,
            explicitAgentLabel: true,
            verifiedRerun: true,
            globalModelScore: false,
            crossRepositoryRanking: false,
            agentQualityClaim: false,
            sourceMutation: false,
            networkUsed: false,
            authority: "none"
          }
        });
        return;
      }

      if (requestUrl.pathname === "/api/trust/profile") {
        await assertRunrailLocalFeatureAccess("reusable-policy-profiles", {
          opportunisticRenewal: false
        });
        const repoId = boundedText(body.repoId, "Repository ID", 80);
        const trustProfile = await loadRunrailRepositoryTrustProfile({
          historyRoot: reviewHistoryRoot,
          repoFingerprint: repoId
        });
        sendCommandJson(200, {
          ok: true,
          trustProfile,
          boundaries: {
            localOnly: true,
            authority: "none",
            sourceMutation: false,
            policyMutation: false,
            networkUsed: false,
            telemetryEnabled: false
          }
        });
        return;
      }

      if (requestUrl.pathname === "/api/report/weekly") {
        await assertRunrailLocalFeatureAccess("reusable-policy-profiles", {
          opportunisticRenewal: false
        });
        const repoId = boundedText(body.repoId, "Repository ID", 80);
        const weeklyReport = await loadRunrailWeeklyEngineeringReport({
          historyRoot: reviewHistoryRoot,
          repoFingerprint: repoId
        });
        sendCommandJson(200, {
          ok: true,
          weeklyReport,
          boundaries: {
            localOnly: true,
            pathFree: true,
            authority: "none",
            sourceMutation: false,
            policyMutation: false,
            networkUsed: false,
            telemetryEnabled: false
          }
        });
        return;
      }

      if (requestUrl.pathname === "/api/tournament") {
        await assertRunrailLocalFeatureAccess("revision-comparison", {
          opportunisticRenewal: false
        });
        assertExactRequestKeys(
          body,
          ["repo", "base", "candidates"],
          "Candidate Tournament"
        );
        const repo = absoluteRepoPath(body.repo);
        const base = boundedText(body.base, "Base reference", 256);
        if (
          !Array.isArray(body.candidates) ||
          body.candidates.length < 2 ||
          body.candidates.length > 5
        ) {
          const error = new Error(
            "Candidate Tournament requires two to five local candidate branches."
          );
          error.code = "desktop-tournament-count";
          throw error;
        }
        const requestedCandidates = body.candidates.map((candidate) =>
          boundedText(candidate, "Candidate reference", 256)
        );
        if (new Set(requestedCandidates).size !== requestedCandidates.length) {
          const error = new Error(
            "Candidate Tournament does not accept duplicate candidate branches."
          );
          error.code = "desktop-tournament-duplicate";
          throw error;
        }
        const inspection = await inspectRunrailReviewRepository({ repo, base });
        if (!inspection.clean) {
          const error = new Error(
            "Candidate Tournament requires a clean reviewed repository."
          );
          error.code = "desktop-tournament-dirty-repository";
          throw error;
        }
        if (inspection.candidateLocalBranchesTruncated) {
          const error = new Error(
            "Candidate Tournament refuses a truncated local candidate inventory."
          );
          error.code = "desktop-tournament-inventory-truncated";
          throw error;
        }
        const selectedCandidates = requestedCandidates.map((candidate) => {
          const matches = inspection.candidateLocalBranches.filter(
            (entry) => entry.ref === candidate
          );
          if (matches.length !== 1) {
            const error = new Error(
              "Every tournament entry must be one discovered local branch ahead of the confirmed base."
            );
            error.code = "desktop-tournament-candidate-invalid";
            throw error;
          }
          return matches[0];
        });
        if (
          new Set(selectedCandidates.map((candidate) => candidate.commit)).size !==
          selectedCandidates.length
        ) {
          const error = new Error(
            "Candidate Tournament does not accept branch aliases for the same commit."
          );
          error.code = "desktop-tournament-duplicate-commit";
          throw error;
        }
        await createRunrailRepoFingerprint({
          historyRoot: reviewHistoryRoot,
          repo,
          inspection
        });
        const reviewResults = [];
        for (const candidate of selectedCandidates) {
          const result = await runCli([
            "review",
            "--repo",
            repo,
            "--base",
            inspection.confirmedBase.commit,
            "--candidate",
            candidate.commit,
            "--verifier",
            "safe-static"
          ], { allowNonZeroResult: true }, requestOperations);
          if (
            !result?.report ||
            !result?.coverage ||
            result.report.source.baseCommit !== inspection.confirmedBase.commit ||
            result.report.source.candidateCommit !== candidate.commit
          ) {
            const error = new Error(
              "A tournament candidate did not produce complete commit-bound review evidence."
            );
            error.code = "desktop-tournament-review-invalid";
            throw error;
          }
          reviewResults.push({ candidate, result });
        }
        const inspectionAfter = await inspectRunrailReviewRepository({
          repo,
          base: inspection.confirmedBase.commit
        });
        if (
          inspectionAfter.sourceStateChecksumSha256 !==
          inspection.sourceStateChecksumSha256
        ) {
          const error = new Error(
            "The reviewed repository changed during Candidate Tournament."
          );
          error.code = "desktop-tournament-source-changed";
          throw error;
        }
        const tournament = buildRunrailCandidateTournament({
          entries: reviewResults.map(({ result }) => ({
            audit: result.report,
            coverage: result.coverage
          }))
        });
        const written = await writeRunrailCandidateTournament({
          tournament,
          historyRoot: reviewHistoryRoot
        });
        const displayByAudit = new Map(
          reviewResults.map(({ candidate, result }) => [
            result.report.checksumSha256,
            candidate.ref
          ])
        );
        sendCommandJson(200, {
          ok: true,
          tournament: written.tournament,
          tournamentPath: written.tournamentPath,
          comparisonBasis: written.tournament.comparisonBasis,
          reviewOrderReceipt: written.tournament.reviewOrderReceipt,
          candidates: written.tournament.candidates.map((candidate) => ({
            rank: candidate.rank,
            candidateId: candidate.candidateId,
            displayRef: displayByAudit.get(candidate.auditChecksumSha256),
            metrics: candidate.metrics,
            priorityReasons: candidate.priorityReasons,
            humanDecisionRequired: true,
            bestCodeClaimed: false
          })),
          boundaries: {
            localOnly: true,
            pathFreeArtifact: true,
            sourceMutation: false,
            projectTestsExecuted: false,
            equalContractBudget: true,
            equalVerifierBudget: true,
            automaticSelection: false,
            bestCodeClaimed: false,
            networkUsed: false,
            authority: "none"
          }
        });
        return;
      }

      if (requestUrl.pathname === "/api/review") {
        const repo = absoluteRepoPath(body.repo);
        const base = boundedText(body.base, "Base reference", 256);
        const candidate = boundedText(body.candidate, "Candidate reference", 256);
        const reviewAccess = await assertRunrailLocalDesktopAccess({
          opportunisticRenewal: false
        });
        const cliResult = await runCli([
          "review",
          "--repo",
          repo,
          "--base",
          base,
          "--candidate",
          candidate,
          "--verifier",
          "safe-static"
        ], {
          allowNonZeroResult: true,
          internalPreviewReview: reviewAccess.previewMode === true
        }, requestOperations);
        const result = await persistReviewSession(cliResult, {
          repo,
          base,
          candidate,
          guidedSample: false
        });
        let previewReview = null;
        if (reviewAccess.previewMode) {
          previewReview = await writePublicPreviewReviewRecord(
            reviewHistoryRoot,
            {
              reviewId: result.reviewId,
              auditChecksumSha256: result.report?.checksumSha256,
              createdAt: result.session?.createdAt || new Date().toISOString()
            }
          );
        }
        if (result.reviewId && result.repoId) {
          await recordLocalProductMetric({
            eventType: "review-completed",
            stage: "completed",
            repoFingerprint: result.repoId,
            operationBinding: result.reviewId,
            recordedAt: result.session?.createdAt,
            durationMilliseconds: Date.now() - requestStartedAt
          });
        }
        sendCommandJson(200, {
          ...result,
          publicPreview: previewReview
            ? {
                candidateReviewCount: 1,
                candidateReviewLimit: 1,
                remainingCandidateReviews: 0,
                rerunAvailable: false,
                reviewId: previewReview.reviewId,
                authority: "none"
              }
            : null
        });
        return;
      }

      if (requestUrl.pathname === "/api/review/proofgraph") {
        await assertRunrailLocalFeatureAccess("advanced-evidence-exports", {
          opportunisticRenewal: false
        });
        assertExactRequestKeys(body, ["reviewId"], "ProofGraph");
        const reviewId = boundedText(body.reviewId, "Review ID", 64);
        const written = await loadRunrailProofGraph({
          historyRoot: reviewHistoryRoot,
          reviewId,
          asOf: new Date().toISOString()
        });
        sendCommandJson(200, {
          ok: true,
          reviewId,
          graph: written.graph,
          boundaries: {
            localOnly: true,
            pathFreeArtifact: true,
            pathFreeResponse: true,
            storedInLocalHistory: true,
            findingsHidden: false,
            policyMutation: false,
            sourceMutation: false,
            projectTestsExecuted: false,
            networkUsed: false,
            authority: "none"
          }
        });
        return;
      }

      if (requestUrl.pathname === "/api/agents/list") {
        assertExactRequestKeys(body, [], "Agent adapter list");
        const registry = await agentRegistryForSession();
        sendCommandJson(200, {
          ok: true,
          adapters: registry.list(),
          boundaries: {
            localOnly: true,
            fixedAdaptersOnly: true,
            executablePathsIncluded: false,
            callerCommandsAccepted: false,
            callerArgumentsAccepted: false,
            callerEnvironmentAccepted: false,
            shellUsed: false,
            unattendedExecution: false,
            genericCopyAvailable: true,
            authority: "none"
          }
        });
        return;
      }

      if (requestUrl.pathname === "/api/agents/launch") {
        await assertRunrailLocalFeatureAccess("candidate-branch-review", {
          opportunisticRenewal: false
        });
        assertExactRequestKeys(
          body,
          ["reviewId", "adapterId", "confirmed"],
          "Agent launch"
        );
        if (body.confirmed !== true) {
          const error = new Error(
            "Opening an external coding agent requires explicit confirmation."
          );
          error.code = "agent-bridge-confirmation-required";
          throw error;
        }
        const session = await loadSessionByReviewId(body.reviewId);
        const packetWritten = await writeAssurancePacketForSession(session);
        const registry = await agentRegistryForSession(session);
        const operation = agentOperationFactory({
          registry,
          adapterId: body.adapterId,
          cwd: await agentWorkingRoot(session),
          terminateProcess: terminateCliProcessTree
        });
        const launchResult = await runTrackedOperation(
          operation,
          requestOperations
        );
        const receipt = await persistAgentLaunchReceipt(
          packetWritten,
          launchResult
        );
        sendCommandJson(200, {
          ok: true,
          reviewId: session.reviewId,
          receipt,
          agentExitedSuccessfully:
            launchResult.outcome === "exited" &&
            launchResult.exitCode === 0,
          rerunRequired: true,
          externalAgentResultTrusted: false,
          boundaries: {
            localOnly: true,
            fixedAdapter: true,
            zeroArguments: true,
            shellUsed: false,
            callerPathAccepted: false,
            callerCommandAccepted: false,
            callerArgumentsAccepted: false,
            callerEnvironmentAccepted: false,
            executablePathIncluded: false,
            stdoutIncluded: false,
            stderrIncluded: false,
            receiptMetadataOnly: true,
            runrailSourceMutation: false,
            externalAgentMayModifyReviewedRepository: true,
            automaticApply: false,
            projectTestsExecutedByRunrail: false,
            agentCompletionTrusted: false,
            humanRerunRequired: true,
            authority: "none"
          }
        });
        return;
      }

      if (requestUrl.pathname === "/api/review/handoff") {
        assertExactRequestKeys(body, ["reviewId"], "Agent Assurance handoff");
        const handoffAccess = await assertRunrailLocalDesktopAccess({
          opportunisticRenewal: false
        });
        if (handoffAccess.previewMode) {
          await assertPublicPreviewReviewOwnership(body.reviewId);
        } else {
          await assertRunrailLocalFeatureAccess("candidate-branch-review", {
            opportunisticRenewal: false
          });
        }
        const session = await loadSessionByReviewId(body.reviewId);
        const written = await writeAssurancePacketForSession(session);
        sendCommandJson(200, {
          ok: true,
          reviewId: session.reviewId,
          packet: written.packet,
          packetPath: written.packetPath,
          briefPath: written.briefPath,
          boundaries: {
            localOnly: true,
            pathFreePacket: true,
            repositoryIdentityIncluded: false,
            sourceContentIncluded: false,
            diffContentIncluded: false,
            refOrCommitIncluded: false,
            rawVerifierOutputIncluded: false,
            projectTestsExecuted: false,
            patchApplied: false,
            networkUsed: false,
            providerUsed: false,
            authority: "none"
          }
        });
        return;
      }

      if (requestUrl.pathname === "/api/sample") {
        const cliResult = await runCli(
          ["sample"],
          { allowNonZeroResult: true },
          requestOperations
        );
        const result = await persistReviewSession(cliResult, {
          repo: cliResult.sampleRoot,
          base: cliResult.base,
          candidate: cliResult.candidate,
          guidedSample: true
        });
        if (result.reviewId) {
          await recordLocalProductMetric({
            eventType: "activation-stage",
            stage: "guided-sample-completed",
            operationBinding: result.reviewId,
            recordedAt: result.session?.createdAt,
            durationMilliseconds: Date.now() - requestStartedAt
          });
        }
        sendCommandJson(200, result);
        return;
      }

      if (requestUrl.pathname === "/api/coverage") {
        const auditPath = path.resolve(boundedText(body.auditPath, "Audit path"));
        const record = coverageByAuditPath.get(auditPath);
        if (!allowedAuditPaths.has(auditPath) || !record) {
          const error = new Error(
            "Review Coverage requires an audit created by this desktop session."
          );
          error.code = "desktop-audit-not-owned";
          throw error;
        }
        if (!Array.isArray(body.states) || body.states.length > 2_000) {
          const error = new Error(
            "Review Coverage states must be a bounded array."
          );
          error.code = "desktop-input-invalid";
          throw error;
        }
        const patchEntry = await lstat(record.patchPath);
        if (!patchEntry.isFile() || patchEntry.isSymbolicLink()) {
          const error = new Error(
            "The desktop review patch is no longer an ordinary Runrail-owned file."
          );
          error.code = "desktop-review-artifact-invalid";
          throw error;
        }
        const attention = buildRunrailHunkAttentionManifest(
          record.coverage,
          body.states
        );
        const result = await writeRunrailHunkContinuityArtifacts({
          audit: record.audit,
          patchText: await readFile(record.patchPath, "utf8"),
          reviewRoot: record.reviewRoot,
          attention
        });
        record.coverage = result.coverage;
        const context = reviewContextByAuditPath.get(auditPath);
        if (!context) {
          const error = new Error(
            "Review Coverage lost its server-owned review context."
          );
          error.code = "desktop-review-context-missing";
          throw error;
        }
        const coverageAccess = await assertRunrailLocalDesktopAccess({
          opportunisticRenewal: false
        });
        if (coverageAccess.previewMode) {
          const previewRecord = await loadPublicPreviewReviewRecord(
            reviewHistoryRoot
          );
          const previewSession = await loadSessionByReviewId(
            previewRecord.reviewId
          );
          sendCommandJson(200, {
            ...result,
            reviewId: previewSession.reviewId,
            repoId: previewSession.repoFingerprint,
            session: previewSession,
            verdict: previewSession.verdict,
            history: [],
            assurance: null,
            publicPreview: {
              candidateReviewCount: 1,
              candidateReviewLimit: 1,
              remainingCandidateReviews: 0,
              rerunAvailable: false,
              continuityPersisted: false,
              authority: "none"
            }
          });
          return;
        }
        const persisted = await persistReviewSession({
          ...result,
          reportPath: auditPath,
          coveragePath: result.coveragePath,
          passportPath: context.passportPath,
          patchPath: record.patchPath,
          outputRoot: record.reviewRoot,
          report: record.audit
        }, context);
        const currentSession = await loadSessionByReviewId(persisted.reviewId);
        const mappedBaselineId = assuranceBaselineByReviewId.get(
          currentSession.parentReviewId
        );
        const assuranceBaseline = mappedBaselineId
          ? await loadSessionByReviewId(mappedBaselineId)
          : await findAssuranceBaselineSession(currentSession);
        const assurance = assuranceBaseline
          ? await writeAssuranceForSessions(
              assuranceBaseline,
              currentSession
            )
          : null;
        if (assurance && assuranceBaseline) {
          await recordLocalProductMetric({
            eventType: "assurance-completed",
            stage: assurance.result.status,
            repoFingerprint: currentSession.repoFingerprint,
            operationBinding:
              `${assuranceBaseline.reviewId}\0${currentSession.reviewId}`,
            recordedAt: currentSession.createdAt,
            durationMilliseconds: Date.now() - requestStartedAt
          });
        }
        if (assuranceBaseline) {
          assuranceBaselineByReviewId.set(
            currentSession.reviewId,
            assuranceBaseline.reviewId
          );
        }
        sendCommandJson(200, {
          ...result,
          reviewId: persisted.reviewId,
          repoId: persisted.repoId,
          session: persisted.session,
          verdict: persisted.verdict,
          history: persisted.history,
          assurance: assurance
            ? {
                beforeReviewId: assuranceBaseline.reviewId,
                ...assurance
              }
            : null
        });
        return;
      }

      if (requestUrl.pathname === "/api/review/rerun") {
        assertExactRequestKeys(body, ["reviewId"], "Review rerun");
        const priorSession = await loadSessionByReviewId(body.reviewId);
        const comparisonAvailable = await revisionComparisonAvailable();
        let cliResult = await runCli([
          "review",
          "--repo",
          priorSession.local.repositoryPath,
          "--base",
          priorSession.local.baseRef,
          "--candidate",
          priorSession.local.candidateRef,
          "--verifier",
          "safe-static"
        ], { allowNonZeroResult: true }, requestOperations);
        const sameCandidateCommit =
          cliResult.report?.source?.candidateCommit ===
          priorSession.local.candidateCommit;
        let sameCandidateContinuity = null;
        if (sameCandidateCommit && comparisonAvailable) {
          sameCandidateContinuity = await runCli([
            "coverage",
            "--audit",
            cliResult.reportPath,
            "--previous",
            priorSession.local.coveragePath
          ], {}, requestOperations);
          cliResult = {
            ...cliResult,
            coverage: sameCandidateContinuity.coverage,
            coveragePath: sameCandidateContinuity.coveragePath,
            coverageReviewPath: sameCandidateContinuity.reviewPath,
            coverageHtmlPath: sameCandidateContinuity.htmlReportPath
          };
        }
        const result = await persistReviewSession(cliResult, {
          repo: priorSession.local.repositoryPath,
          base: priorSession.local.baseRef,
          candidate: priorSession.local.candidateRef,
          guidedSample: false
        });
        let revision = null;
        if (sameCandidateContinuity) {
          const summary = sameCandidateContinuity.coverage?.summary || {};
          const attention = Number(summary.unreviewedCount || 0) +
            Number(summary.needsRevisionCount || 0);
          revision = {
            ok: true,
            mode: "deterministic-review-continuity",
            relationship: "same-candidate-rerun",
            comparablePolicyBasis: true,
            policyComparable: true,
            carriedForwardCount: Number(summary.carriedForwardCount || 0),
            currentAttentionRequiredCount: attention,
            addedFindingCount: 0,
            resolvedFindingCount: 0,
            coverage: sameCandidateContinuity.coverage,
            outputRoot: path.dirname(sameCandidateContinuity.coveragePath),
            deltaPath: sameCandidateContinuity.coveragePath,
            nextActions: [
              {
                rank: 1,
                id: "REVIEW_CURRENT_ATTENTION",
                label: "Review current hunk attention",
                reason: "Exact attention was carried; unresolved current hunks still require a human decision."
              },
              {
                rank: 2,
                id: "RUN_APPROVED_PROJECT_CHECKS",
                label: "Run approved project checks",
                reason: "Runrail did not execute repository project tests."
              },
              {
                rank: 3,
                id: "HUMAN_MERGE_DECISION",
                label: "Make the human merge decision",
                reason: "Continuity evidence is not approval or proof of code correctness."
              }
            ],
            boundaries: {
              pathFree: true,
              authority: "none",
              projectTestsExecuted: false,
              sourceMutation: false
            }
          };
        } else if (comparisonAvailable && result.session?.parentReviewId) {
          const parentSession = await loadSessionByReviewId(
            result.session.parentReviewId
          );
          revision = await runCli([
            "recheck",
            "--before",
            parentSession.local.auditPath,
            "--after",
            result.reportPath,
            "--previous",
            parentSession.local.coveragePath
          ], {}, requestOperations);
          const currentRecord = coverageByAuditPath.get(
            path.resolve(result.reportPath)
          );
          if (currentRecord && revision.coverage) {
            currentRecord.coverage = revision.coverage;
          }
        }
        const currentSession = await loadSessionByReviewId(result.reviewId);
        const assuranceResult = await writeAssuranceForSessions(
          priorSession,
          currentSession
        );
        await recordLocalProductMetric({
          eventType: "rerun-completed",
          stage: "completed",
          repoFingerprint: currentSession.repoFingerprint,
          operationBinding: currentSession.reviewId,
          recordedAt: currentSession.createdAt,
          durationMilliseconds: Date.now() - requestStartedAt
        });
        await recordLocalProductMetric({
          eventType: "assurance-completed",
          stage: assuranceResult.result.status,
          repoFingerprint: currentSession.repoFingerprint,
          operationBinding:
            `${priorSession.reviewId}\0${currentSession.reviewId}`,
          recordedAt: currentSession.createdAt,
          durationMilliseconds: Date.now() - requestStartedAt
        });
        assuranceBaselineByReviewId.set(
          currentSession.reviewId,
          priorSession.reviewId
        );
        sendCommandJson(200, {
          ...result,
          revision,
          assurance: {
            beforeReviewId: priorSession.reviewId,
            ...assuranceResult
          },
          revisionComparisonAvailable: comparisonAvailable,
          comparisonConfirmed: true,
          comparisonSelection: revision
            ? "latest-related-ancestry-session"
            : comparisonAvailable
              ? "no-related-prior-session"
              : "starter-assurance-only"
        });
        return;
      }

      if (requestUrl.pathname === "/api/review/disposition") {
        const session = await loadSessionByReviewId(body.reviewId);
        const kind = boundedText(body.status || body.kind, "Disposition", 40);
        const expiresAt = String(body.expiresAt || "").trim();
        const result = await appendRunrailReviewDisposition({
          historyRoot: reviewHistoryRoot,
          repoFingerprint: session.repoFingerprint,
          reviewId: session.reviewId,
          findingId: boundedText(body.findingId, "Finding ID", 80),
          kind,
          reason: String(body.reason || "").trim() || null,
          owner: String(body.owner || "").trim() || null,
          expiresAt: kind === "accepted-exception"
            ? (
                /^\d{4}-\d{2}-\d{2}$/.test(expiresAt)
                  ? `${expiresAt}T23:59:59.000Z`
                  : expiresAt
              )
            : null
        });
        const dispositions = await listRunrailReviewDispositions({
          historyRoot: reviewHistoryRoot,
          repoFingerprint: session.repoFingerprint,
          reviewId: session.reviewId
        });
        const verdict = evaluateRunrailReviewSession(session, dispositions);
        sendCommandJson(200, {
          ok: true,
          ...result,
          verdict,
          history: await listHistory(session.repoFingerprint),
          boundaries: {
            appendOnly: true,
            localOnly: true,
            authority: "none",
            policyRewritten: false,
            sourceMutation: false
          }
        });
        return;
      }

      if (requestUrl.pathname === "/api/review/passport") {
        const passportRequestKeys = Object.keys(body).sort();
        if (
          passportRequestKeys.some(
            (key) => !["reviewId", "signWithDevice"].includes(key)
          ) ||
          (
            Object.hasOwn(body, "signWithDevice") &&
            typeof body.signWithDevice !== "boolean"
          )
        ) {
          const error = new Error(
            "Passport export accepts only a review ID and a boolean device-signing choice."
          );
          error.code = "desktop-passport-request-invalid";
          throw error;
        }
        await assertReviewHistoryOrPublicPreviewAccess(body.reviewId, {
          deviceSigningRequested: body.signWithDevice === true
        });
        const session = await loadSessionByReviewId(body.reviewId);
        const { passport, passportPath } = await readSessionPassport(session);
        if (body.signWithDevice === true) {
          const signedPassport = await signRunrailDeviceReviewPassport(passport);
          const signedPassportPath = await persistDeviceSignedPassport(
            session,
            signedPassport
          );
          await recordLocalProductMetric({
            eventType: "passport-exported",
            stage: "device-signed",
            repoFingerprint: session.repoFingerprint,
            operationBinding: session.reviewId,
            recordedAt: new Date().toISOString(),
            durationMilliseconds: Date.now() - requestStartedAt
          });
          sendCommandJson(200, {
            ok: true,
            reviewId: session.reviewId,
            passportPath: signedPassportPath,
            passport: signedPassport,
            signature: {
              mode: "device-key-possession",
              deviceSigned: true,
              devicePublicKeySha256:
                signedPassport.signature.devicePublicKeySha256,
              organizationalIdentityProven: false,
              complianceCertificationProven: false,
              codeCorrectnessProven: false,
              mergeApprovalGranted: false
            }
          });
          return;
        }
        await recordLocalProductMetric({
          eventType: "passport-exported",
          stage: "checksum-only",
          repoFingerprint: session.repoFingerprint,
          operationBinding: session.reviewId,
          recordedAt: new Date().toISOString(),
          durationMilliseconds: Date.now() - requestStartedAt
        });
        sendCommandJson(200, {
          ok: true,
          reviewId: session.reviewId,
          passportPath,
          passport,
          signature: {
            mode: "checksum-only",
            deviceSigned: false,
            organizationalIdentityProven: false,
            codeCorrectnessProven: false
          }
        });
        return;
      }

      if (requestUrl.pathname === "/api/revision") {
        await assertRunrailLocalFeatureAccess("revision-comparison", {
          opportunisticRenewal: false
        });
        const currentAuditPath = absoluteArtifactPath(
          body.currentAuditPath,
          "Current audit path"
        );
        if (!allowedAuditPaths.has(currentAuditPath)) {
          const error = new Error(
            "Revision Workspace requires a current audit created by this desktop session."
          );
          error.code = "desktop-audit-not-owned";
          throw error;
        }
        const previousAuditPath = absoluteArtifactPath(
          body.previousAuditPath,
          "Prior audit path"
        );
        const previousCoveragePath = absoluteArtifactPath(
          body.previousCoveragePath,
          "Prior coverage path"
        );
        const result = await runCli([
          "recheck",
          "--before",
          previousAuditPath,
          "--after",
          currentAuditPath,
          "--previous",
          previousCoveragePath
        ], {}, requestOperations);
        const record = coverageByAuditPath.get(currentAuditPath);
        if (record && result.coverage) record.coverage = result.coverage;
        sendCommandJson(200, result);
        return;
      }

      if (requestUrl.pathname === "/api/recommend") {
        const auditPath = path.resolve(boundedText(body.auditPath, "Audit path"));
        if (!allowedAuditPaths.has(auditPath)) {
          const error = new Error("Recommendation requires an audit created by this desktop session.");
          error.code = "desktop-audit-not-owned";
          throw error;
        }
        const provider = body.provider === "deepseek" ? "deepseek" : "deterministic";
        if (provider === "deepseek" && body.networkConsent !== true) {
          const error = new Error("DeepSeek requires explicit network consent for this request.");
          error.code = "desktop-network-consent-required";
          throw error;
        }
        const result = await runCli([
          "recommend",
          "--audit",
          auditPath,
          "--provider",
          provider,
          ...(provider === "deepseek" ? ["--allow-network"] : [])
        ], {
          env: runrailDesktopChildEnvironment({
            allowDeepSeek: provider === "deepseek" && body.networkConsent === true
          })
        }, requestOperations);
        sendCommandJson(200, result);
        return;
      }

      if (requestUrl.pathname === "/api/quit") {
        const stoppedOperationCount = await beginOperationShutdown();
        sendCommandJson(200, {
          ok: true,
          stopped: true,
          activeCommandStopped: stoppedOperationCount > 0,
          stoppedOperationCount
        });
        void closeServer().catch(() => {});
        return;
      }

      sendCommandJson(404, { ok: false, code: "desktop-api-not-found" });
    } catch (error) {
      await stopRequestOperations();
      sendCommandJson(400, publicError(error));
    } finally {
      await stopRequestOperations();
      releaseCommandLock();
    }
  }

  const server = createServer((request, response) => {
    void handleRequest(request, response).catch((error) => {
      sendJson(response, 400, publicError(error));
    });
  });

  server.on("close", () => {
    void beginOperationShutdown().then(resolveClosed, resolveClosed);
  });
  server.on("clientError", (_error, socket) => socket.destroy());
  await new Promise((resolve, reject) => {
    const onError = (error) => reject(error);
    server.once("error", onError);
    server.listen(port, "127.0.0.1", () => {
      server.off("error", onError);
      resolve();
    });
  });
  server.on("error", () => {
    void closeServer().catch(() => {});
  });
  const address = server.address();
  origin = `http://127.0.0.1:${address.port}`;
  const url = `${origin}/#session=${sessionToken}`;
  let opener = { attempted: false, opened: false, mode: "disabled", code: null };
  if (open) {
    try {
      opener = await openLocalApp(url, { spawnProcess: openerSpawn });
    } catch (error) {
      opener = openerFailure(error, "unknown");
    }
    if (!opener.opened) {
      const warning = [
        `Runrail Desktop could not open the browser (${opener.code}): ${opener.message}`,
        `If the browser did not open, copy this private loopback URL into a browser on this machine: ${url}`
      ].join("\n");
      try {
        onOpenerWarning(warning);
      } catch {}
    }
  }

  return {
    ok: true,
    product: "Runrail Desktop",
    mode: "loopback-local",
    origin,
    url,
    host: "127.0.0.1",
    port: address.port,
    offlineDefault: true,
    repositoryUpload: false,
    sourceApplyAvailable: false,
    projectTestsExecuted: false,
    opener,
    close: closeServer,
    closed
  };
}
