import { createHash } from "node:crypto";
import { lstat, readFile, readdir } from "node:fs/promises";
import path from "node:path";
import { fileURLToPath } from "node:url";

const runtimeGeneratedSubtrees = new Set(["python-env"]);
const allowedOsMetadataFiles = new Set([".DS_Store", "Thumbs.db", "desktop.ini"]);
const currentDistributionVersion = "2.4.14";
const compatiblePriorCoreFiles = Object.freeze([
  "RUNRAIL_DISTRIBUTION.json",
  "bin/runrail.mjs",
  "engine/RUNRAIL_ENGINE_DISTRIBUTION.json",
  "install.mjs",
  "scripts/verify-runrail-distribution.mjs",
  "scripts/veyact-local-audit-runner-core.mjs",
  "scripts/veyact-local-audit-runner.mjs",
  "uninstall.mjs"
]);

export const RUNRAIL_REQUIRED_DISTRIBUTION_FILE_MAP = Object.freeze([
  {
    path: "COMMERCIAL_LICENSE_NOTICE.md",
    sourceRelative: "packages/runrail-local/COMMERCIAL_LICENSE_NOTICE.md"
  },
  {
    path: "README.md",
    sourceRelative: "packages/runrail-local/README.md"
  },
  {
    path: "START-HERE.txt",
    sourceRelative: "packages/runrail-local/START-HERE.txt"
  },
  {
    path: "START-RUNRAIL-PREVIEW.cmd",
    sourceRelative: "packages/runrail-local/START-RUNRAIL-PREVIEW.cmd"
  },
  {
    path: "Start Runrail Preview.command",
    sourceRelative: "packages/runrail-local/Start Runrail Preview.command"
  },
  {
    path: "apps/pilot/src/runrail-entitlement-lease.mjs",
    sourceRelative: "apps/pilot/src/runrail-entitlement-lease.mjs"
  },
  {
    path: "apps/pilot/src/subscriber-local-audit-request.mjs",
    sourceRelative: "apps/pilot/src/subscriber-local-audit-request.mjs"
  },
  {
    path: "apps/shared/runrail-plan-catalog.mjs",
    sourceRelative: "apps/shared/runrail-plan-catalog.mjs"
  },
  {
    path: "bin/runrail",
    sourceRelative: "packages/runrail-local/bin/runrail"
  },
  {
    path: "bin/runrail.mjs",
    sourceRelative: "packages/runrail-local/bin/runrail.mjs"
  },
  {
    path: "desktop/app.css",
    sourceRelative: "packages/runrail-local/desktop/app.css"
  },
  {
    path: "desktop/app.js",
    sourceRelative: "packages/runrail-local/desktop/app.js"
  },
  {
    path: "desktop/favicon.ico",
    sourceRelative: "apps/web/public/favicon.ico"
  },
  {
    path: "desktop/icon-192.png",
    sourceRelative: "apps/web/public/icon-192.png"
  },
  {
    path: "desktop/icon-512.png",
    sourceRelative: "apps/web/public/icon-512.png"
  },
  {
    path: "desktop/index.html",
    sourceRelative: "packages/runrail-local/desktop/index.html"
  },
  {
    path: "engine/RUNRAIL_ENGINE_DISTRIBUTION.json",
    nestedManifestChecksumSha256: "7b3d30567acb98511ff424e713d1e69a60c32403e4575d5c09636843ab25fae6"
  },
  {
    path: "install.mjs",
    sourceRelative: "packages/runrail-local/install.mjs"
  },
  {
    path: "install.ps1",
    sourceRelative: "packages/runrail-local/install.ps1"
  },
  {
    path: "install.sh",
    sourceRelative: "packages/runrail-local/install.sh"
  },
  {
    path: "package.json"
  },
  {
    path: "runtime-bin/python",
    sourceRelative: "packages/runrail-local/runtime-bin/python"
  },
  {
    path: "scripts/runrail-agent-assurance-core.mjs",
    sourceRelative: "scripts/runrail-agent-assurance-core.mjs"
  },
  {
    path: "scripts/runrail-agent-bridge-core.mjs",
    sourceRelative: "scripts/runrail-agent-bridge-core.mjs"
  },
  {
    path: "scripts/runrail-agent-outcome-ledger-core.mjs",
    sourceRelative: "scripts/runrail-agent-outcome-ledger-core.mjs"
  },
  {
    path: "scripts/runrail-branch-review-core.mjs",
    sourceRelative: "scripts/runrail-branch-review-core.mjs"
  },
  {
    path: "scripts/runrail-candidate-advisory-core.mjs",
    sourceRelative: "scripts/runrail-candidate-advisory-core.mjs"
  },
  {
    path: "scripts/runrail-candidate-tournament-core.mjs",
    sourceRelative: "scripts/runrail-candidate-tournament-core.mjs"
  },
  {
    path: "scripts/runrail-deepseek-advisory-core.mjs",
    sourceRelative: "scripts/runrail-deepseek-advisory-core.mjs"
  },
  {
    path: "scripts/runrail-desktop-app.mjs",
    sourceRelative: "scripts/runrail-desktop-app.mjs"
  },
  {
    path: "scripts/runrail-engine-bootstrap.py",
    sourceRelative: "scripts/runrail-engine-bootstrap.py"
  },
  {
    path: "scripts/runrail-evidence-continuity-core.mjs",
    sourceRelative: "scripts/runrail-evidence-continuity-core.mjs"
  },
  {
    path: "scripts/runrail-external-evidence-core.mjs",
    sourceRelative: "scripts/runrail-external-evidence-core.mjs"
  },
  {
    path: "scripts/runrail-guided-sample-core.mjs",
    sourceRelative: "scripts/runrail-guided-sample-core.mjs"
  },
  {
    path: "scripts/runrail-hunk-continuity-core.mjs",
    sourceRelative: "scripts/runrail-hunk-continuity-core.mjs"
  },
  {
    path: "scripts/runrail-local-entitlement-core.mjs",
    sourceRelative: "scripts/runrail-local-entitlement-core.mjs"
  },
  {
    path: "scripts/runrail-native-state-migration.mjs",
    sourceRelative: "scripts/runrail-native-state-migration.mjs"
  },
  {
    path: "scripts/runrail-product-metrics-core.mjs",
    sourceRelative: "scripts/runrail-product-metrics-core.mjs"
  },
  {
    path: "scripts/runrail-proof-graph-core.mjs",
    sourceRelative: "scripts/runrail-proof-graph-core.mjs"
  },
  {
    path: "scripts/runrail-python-runtime-core.mjs",
    sourceRelative: "scripts/runrail-python-runtime-core.mjs"
  },
  {
    path: "scripts/runrail-review-comparison-core.mjs",
    sourceRelative: "scripts/runrail-review-comparison-core.mjs"
  },
  {
    path: "scripts/runrail-review-contract-core.mjs",
    sourceRelative: "scripts/runrail-review-contract-core.mjs"
  },
  {
    path: "scripts/runrail-review-delta-core.mjs",
    sourceRelative: "scripts/runrail-review-delta-core.mjs"
  },
  {
    path: "scripts/runrail-review-focus-core.mjs",
    sourceRelative: "scripts/runrail-review-focus-core.mjs"
  },
  {
    path: "scripts/runrail-review-passport-core.mjs",
    sourceRelative: "scripts/runrail-review-passport-core.mjs"
  },
  {
    path: "scripts/runrail-review-policy-core.mjs",
    sourceRelative: "scripts/runrail-review-policy-core.mjs"
  },
  {
    path: "scripts/runrail-review-session-core.mjs",
    sourceRelative: "scripts/runrail-review-session-core.mjs"
  },
  {
    path: "scripts/runrail-safe-static-verifier-core.mjs",
    sourceRelative: "scripts/runrail-safe-static-verifier-core.mjs"
  },
  {
    path: "scripts/runrail-trust-profile-core.mjs",
    sourceRelative: "scripts/runrail-trust-profile-core.mjs"
  },
  {
    path: "scripts/runrail-typescript-parser-core.mjs",
    sourceRelative: "scripts/runrail-typescript-parser-core.mjs"
  },
  {
    path: "scripts/verify-runrail-distribution.mjs",
    sourceRelative: "scripts/verify-runrail-distribution.mjs"
  },
  {
    path: "scripts/veyact-local-audit-runner-core.mjs",
    sourceRelative: "scripts/veyact-local-audit-runner-core.mjs"
  },
  {
    path: "scripts/veyact-local-audit-runner.mjs",
    sourceRelative: "scripts/veyact-local-audit-runner.mjs"
  },
  {
    path: "start-preview.mjs",
    sourceRelative: "packages/runrail-local/start-preview.mjs"
  },
  {
    path: "start-runrail-preview.sh",
    sourceRelative: "packages/runrail-local/start-runrail-preview.sh"
  },
  {
    path: "uninstall.mjs",
    sourceRelative: "packages/runrail-local/uninstall.mjs"
  },
  {
    path: "uninstall.ps1",
    sourceRelative: "packages/runrail-local/uninstall.ps1"
  },
  {
    path: "uninstall.sh",
    sourceRelative: "packages/runrail-local/uninstall.sh"
  },
  {
    path: "vendor/typescript/5.9.3/LICENSE.txt",
    sourceRelative: "vendor/typescript/5.9.3/LICENSE.txt"
  },
  {
    path: "vendor/typescript/5.9.3/RUNRAIL_TYPESCRIPT_VENDOR.json",
    sourceRelative: "vendor/typescript/5.9.3/RUNRAIL_TYPESCRIPT_VENDOR.json"
  },
  {
    path: "vendor/typescript/5.9.3/typescript.cjs",
    sourceRelative: "vendor/typescript/5.9.3/typescript.cjs"
  }
].map((entry) => Object.freeze(entry)));

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

function stableValue(value) {
  if (Array.isArray(value)) return value.map(stableValue);
  if (value && typeof value === "object") {
    return Object.fromEntries(Object.keys(value).sort().map((key) => [key, stableValue(value[key])]));
  }
  return value;
}

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

function safeRelativePath(value) {
  const relative = String(value || "").replaceAll("\\", "/");
  return (
    relative.length > 0 &&
    relative.length <= 240 &&
    !path.posix.isAbsolute(relative) &&
    !relative.split("/").includes("") &&
    !relative.split("/").includes("..")
  );
}

function parseVersion(value) {
  const match = String(value || "").match(/^(\d+)\.(\d+)\.(\d+)$/);
  if (!match) return null;
  return match.slice(1).map(Number);
}

function compareVersions(left, right) {
  for (let index = 0; index < 3; index += 1) {
    if (left[index] !== right[index]) return left[index] - right[index];
  }
  return 0;
}

function isRuntimeGeneratedPath(relative) {
  return runtimeGeneratedSubtrees.has(relative.split("/")[0]);
}

async function loadDistributionManifest(root) {
  const manifestPath = path.join(root, "RUNRAIL_DISTRIBUTION.json");
  let info;
  let manifest;
  try {
    info = await lstat(manifestPath);
    manifest = JSON.parse(await readFile(manifestPath, "utf8"));
  } catch {
    throw new Error("distribution-manifest-invalid");
  }
  if (!info.isFile() || info.isSymbolicLink()) throw new Error("distribution-manifest-invalid");
  return manifest;
}

async function verifySelfContainedManifestFiles(root, manifest) {
  const seen = new Set();
  for (const entry of manifest.files) {
    const relative = String(entry?.path || "");
    if (
      !safeRelativePath(relative) ||
      relative === "RUNRAIL_DISTRIBUTION.json" ||
      seen.has(relative) ||
      !/^[a-f0-9]{64}$/.test(String(entry?.sha256 || ""))
    ) {
      throw new Error("distribution-file-record-invalid");
    }
    seen.add(relative);
    const resolved = path.resolve(root, ...relative.split("/"));
    const contained = path.relative(root, resolved);
    if (!contained || contained.startsWith("..") || path.isAbsolute(contained)) {
      throw new Error("distribution-file-path-escape");
    }
    let info;
    let content;
    try {
      info = await lstat(resolved);
      content = await readFile(resolved);
    } catch {
      throw new Error("distribution-file-missing");
    }
    if (!info.isFile() || info.isSymbolicLink()) throw new Error("distribution-file-type-invalid");
    if (sha256(content) !== entry.sha256) throw new Error("distribution-file-tampered");
  }
  for (const relative of compatiblePriorCoreFiles) {
    if (relative !== "RUNRAIL_DISTRIBUTION.json" && !seen.has(relative)) {
      throw new Error("distribution-manifest-incomplete");
    }
  }
  await assertNoUnexpectedEntries(root, seen);
  return seen.size;
}

export async function verifyCompatiblePriorRunrailDistribution(distributionRoot) {
  const root = path.resolve(distributionRoot);
  const manifest = await loadDistributionManifest(root);
  const currentVersion = parseVersion(currentDistributionVersion);
  const candidateVersion = parseVersion(manifest.version);
  const minimumCompatibleMajor = Math.max(1, currentVersion[0] - 1);
  const { checksumSha256, ...body } = manifest;
  if (
    manifest.schemaVersion !== 1 ||
    manifest.artifactType !== "runrail-local-distribution" ||
    manifest.product !== "Runrail Local Audit Runner" ||
    !candidateVersion ||
    candidateVersion[0] < minimumCompatibleMajor ||
    candidateVersion[0] > currentVersion[0] ||
    compareVersions(candidateVersion, currentVersion) > 0 ||
    JSON.stringify(manifest.supportedPlatforms) !== JSON.stringify(["linux", "wsl2", "windows", "darwin"]) ||
    manifest.engineTag !== "ra-v1.0" ||
    manifest.engineCommit !== "3076e7fd0508feecb42d8821e98fa8e3d9db5404" ||
    manifest.networkRequiredForRuns !== false ||
    manifest.optionalCandidateAdvisoryAuthority !== "none" ||
    manifest.desktopAppRepositoryUpload !== false ||
    manifest.desktopAppSourceApplyAvailable !== false ||
    manifest.sourceApplyAvailable !== false ||
    !Array.isArray(manifest.files) ||
    checksumSha256 !== sha256(stableJson(body))
  ) {
    throw new Error("distribution-compatible-prior-invalid");
  }
  const verifiedFileCount = await verifySelfContainedManifestFiles(root, manifest);
  const filePaths = new Set(manifest.files.map((entry) => String(entry?.path || "")));
  return {
    mode: "verified-compatible-prior-distribution",
    version: manifest.version,
    verifiedFileCount,
    runtimeIntegrityAvailable:
      filePaths.has("scripts/runrail-engine-bootstrap.py") &&
      filePaths.has("scripts/runrail-python-runtime-core.mjs"),
    checksumSha256
  };
}

function compareUtf8Names(left, right) {
  return Buffer.compare(Buffer.from(left, "utf8"), Buffer.from(right, "utf8"));
}

const requiredMapPaths = RUNRAIL_REQUIRED_DISTRIBUTION_FILE_MAP.map((entry) => entry.path);
if (
  new Set(requiredMapPaths).size !== requiredMapPaths.length ||
  JSON.stringify(requiredMapPaths) !== JSON.stringify([...requiredMapPaths].sort(compareUtf8Names))
) {
  throw new Error("runrail-required-distribution-file-map-invalid");
}

async function loadRequiredDistributionFiles(root) {
  const required = new Map(
    RUNRAIL_REQUIRED_DISTRIBUTION_FILE_MAP.map((entry) => [entry.path, { ...entry }])
  );
  const engineManifestRecord = RUNRAIL_REQUIRED_DISTRIBUTION_FILE_MAP.find(
    (entry) => entry.nestedManifestChecksumSha256
  );
  if (!engineManifestRecord) throw new Error("runrail-required-distribution-file-map-invalid");

  const engineManifestPath = path.join(root, ...engineManifestRecord.path.split("/"));
  let engineManifestInfo;
  let engineManifest;
  try {
    engineManifestInfo = await lstat(engineManifestPath);
    engineManifest = JSON.parse(await readFile(engineManifestPath, "utf8"));
  } catch {
    throw new Error("distribution-engine-manifest-invalid");
  }
  if (!engineManifestInfo.isFile() || engineManifestInfo.isSymbolicLink()) {
    throw new Error("distribution-engine-manifest-invalid");
  }

  const { checksumSha256, ...body } = engineManifest;
  if (
    engineManifest.schemaVersion !== 1 ||
    engineManifest.artifactType !== "runrail-engine-distribution" ||
    engineManifest.releaseTag !== "ra-v1.0" ||
    engineManifest.releaseCommit !== "3076e7fd0508feecb42d8821e98fa8e3d9db5404" ||
    !Array.isArray(engineManifest.files) ||
    checksumSha256 !== engineManifestRecord.nestedManifestChecksumSha256 ||
    checksumSha256 !== sha256(stableJson(body))
  ) {
    throw new Error("distribution-engine-manifest-invalid");
  }

  const seenEngineFiles = new Set();
  for (const entry of engineManifest.files) {
    const relative = String(entry?.path || "");
    if (
      !safeRelativePath(relative) ||
      seenEngineFiles.has(relative) ||
      !/^[a-f0-9]{64}$/.test(String(entry?.sha256 || ""))
    ) {
      throw new Error("distribution-engine-file-record-invalid");
    }
    seenEngineFiles.add(relative);
    const distributionRelative = `engine/${relative}`;
    if (required.has(distributionRelative)) {
      throw new Error("distribution-engine-file-record-invalid");
    }
    required.set(distributionRelative, {
      path: distributionRelative,
      expectedSha256: entry.sha256
    });
  }
  return required;
}

async function assertNoUnexpectedEntries(root, listedFiles, directory = root) {
  const entries = await readdir(directory, { withFileTypes: true });
  for (const entry of entries) {
    const absolute = path.join(directory, entry.name);
    const relative = path.relative(root, absolute).split(path.sep).join("/");
    if (entry.isSymbolicLink()) throw new Error("distribution-file-type-invalid");
    if (entry.isDirectory()) {
      // The installer creates this platform-specific virtual environment after
      // package verification. Its contents are runtime state, not shipped files.
      if (isRuntimeGeneratedPath(relative)) continue;
      await assertNoUnexpectedEntries(root, listedFiles, absolute);
      continue;
    }
    if (!entry.isFile()) throw new Error("distribution-file-type-invalid");
    if (
      relative === "RUNRAIL_DISTRIBUTION.json" ||
      listedFiles.has(relative) ||
      allowedOsMetadataFiles.has(entry.name)
    ) {
      continue;
    }
    throw new Error(`distribution-file-unexpected:${relative}`);
  }
}

export async function verifyRunrailDistribution(
  distributionRoot,
  { allowMissing = false, allowDevelopmentTree = false } = {}
) {
  const root = path.resolve(distributionRoot);
  const manifestPath = path.join(root, "RUNRAIL_DISTRIBUTION.json");
  const developmentTreeRequested = allowDevelopmentTree || allowMissing;
  const installedDistributionConfigured = Boolean(String(process.env.RUNRAIL_DISTRIBUTION_ROOT || "").trim());
  let manifestInfo;
  let manifest;
  try {
    manifestInfo = await lstat(manifestPath);
  } catch (error) {
    if (error?.code === "ENOENT" && developmentTreeRequested && !installedDistributionConfigured) {
      return { mode: "development-tree", verifiedFileCount: 0 };
    }
    if (error?.code === "ENOENT") throw new Error("distribution-manifest-missing");
    throw new Error("distribution-manifest-invalid");
  }
  if (!manifestInfo.isFile() || manifestInfo.isSymbolicLink()) {
    throw new Error("distribution-manifest-invalid");
  }
  try {
    manifest = JSON.parse(await readFile(manifestPath, "utf8"));
  } catch {
    throw new Error("distribution-manifest-invalid");
  }

  const { checksumSha256, ...body } = manifest;
  if (
    manifest.schemaVersion !== 1 ||
    manifest.artifactType !== "runrail-local-distribution" ||
    manifest.product !== "Runrail Local Audit Runner" ||
    manifest.version !== currentDistributionVersion ||
    JSON.stringify(manifest.supportedPlatforms) !== JSON.stringify(["linux", "wsl2", "windows", "darwin"]) ||
    manifest.networkRequiredForRuns !== false ||
    manifest.optionalCandidateAdvisoryAvailable !== true ||
    manifest.defaultCandidateAdvisoryProvider !== "deterministic" ||
    manifest.defaultCandidateAdvisoryNetworkRequired !== false ||
    JSON.stringify(manifest.candidateAdvisoryProviders) !== JSON.stringify(["deterministic", "deepseek"]) ||
    manifest.optionalCandidateAdvisoryNetworkRequired !== true ||
    manifest.optionalCandidateAdvisoryAuthority !== "none" ||
    manifest.optionalCandidateAdvisoryModel !== "deepseek-v4-pro" ||
    manifest.deterministicReviewPolicyProfile !== "runrail-review-policy-v1" ||
    manifest.reviewContractAvailable !== true ||
    manifest.reviewContractProfile !== "runrail-review-contract-v1" ||
    manifest.reviewContractSourceAuthority !== "base-commit-only" ||
    manifest.candidateCanWeakenReviewContract !== false ||
    manifest.candidateReviewAuditSchemaVersion !== 4 ||
    manifest.reviewFocusAvailable !== true ||
    manifest.reviewFocusProfile !== "runrail-review-focus-v1" ||
    manifest.reviewFocusPathFree !== true ||
    manifest.reviewFocusBlockedPreflightSupported !== true ||
    manifest.reviewFocusNetworkRequired !== false ||
    manifest.reviewFocusAuthority !== "none" ||
    manifest.reviewCoverageAvailable !== true ||
    manifest.reviewCoverageProfile !== "runrail-hunk-continuity-v1" ||
    manifest.reviewCoveragePathFree !== true ||
    manifest.reviewCoverageExactUniqueCarryOnly !== true ||
    manifest.reviewCoverageHumanAttentionNotApproval !== true ||
    manifest.reviewCoverageNetworkRequired !== false ||
    manifest.reviewCoverageAuthority !== "none" ||
    manifest.reviewSessionAvailable !== true ||
    manifest.reviewSessionProfile !== "runrail-review-session-v1" ||
    manifest.repositoryInspectionAvailable !== true ||
    manifest.repositoryReadinessReceiptProfile !==
      "runrail-repository-readiness-v1" ||
    manifest.repositoryReadinessHandoffAvailable !== true ||
    manifest.repositoryReadinessHandoffProfile !==
      "runrail-repository-readiness-handoff-v1" ||
    manifest.repositoryReadinessCliAvailable !== true ||
    manifest.repositoryReadinessPathFreeHandoff !== true ||
    manifest.repositoryReadinessNetworkRequired !== false ||
    manifest.repositoryReadinessAuthority !== "none" ||
    manifest.reviewPassportAvailable !== true ||
    manifest.reviewPassportSchemaVersion !== 1 ||
    manifest.reviewPassportPathFree !== true ||
    manifest.reviewPassportOriginAuthenticated !== false ||
    manifest.deviceSignedReviewPassportAvailable !== true ||
    manifest.deviceSignedReviewPassportProfile !==
      "runrail-device-signed-review-passport-v1" ||
    manifest.deviceSignedReviewPassportClaim !== "device-key-possession" ||
    manifest.deviceSignedReviewPassportOrganizationalIdentityProven !== false ||
    manifest.repositoryTrustProfileAvailable !== true ||
    manifest.repositoryTrustProfileProfile !==
      "runrail-repository-trust-profile-v1" ||
    manifest.repositoryTrustProfileLocalOnly !== true ||
    manifest.repositoryTrustProfilePolicyAuthority !== "base-commit-only" ||
    manifest.repositoryTrustProfileAutomaticPolicyWrites !== false ||
    manifest.reviewHistoryOsImmutable !== false ||
    manifest.weeklyEngineeringReportAvailable !== true ||
    manifest.weeklyEngineeringReportProfile !==
      "runrail-weekly-engineering-report-v1" ||
    manifest.weeklyEngineeringReportPathFree !== true ||
    manifest.weeklyEngineeringReportTelemetryEnabled !== false ||
    manifest.candidateTournamentAvailable !== true ||
    manifest.candidateTournamentProfile !==
      "runrail-candidate-tournament-v2" ||
    manifest.candidateTournamentLegacyProfileReadable !==
      "runrail-candidate-tournament-v1" ||
    manifest.candidateTournamentMinimumCandidates !== 2 ||
    manifest.candidateTournamentMaximumCandidates !== 5 ||
    manifest.candidateTournamentEqualContractBudget !== true ||
    manifest.candidateTournamentEqualVerifierBudget !== true ||
    manifest.candidateTournamentReviewOrderReceiptProfile !==
      "runrail-tournament-review-order-receipt-v1" ||
    manifest.candidateTournamentReviewOrderOnly !== true ||
    manifest.candidateTournamentBestCodeClaimed !== false ||
    manifest.candidateTournamentNetworkRequired !== false ||
    manifest.candidateTournamentAuthority !== "none" ||
    manifest.proofGraphAvailable !== true ||
    manifest.proofGraphProfile !== "runrail-proof-graph-v1" ||
    manifest.proofGraphPathFree !== true ||
    manifest.proofGraphAllFindingsVisible !== true ||
    manifest.proofGraphNoiseControlMode !==
      "explicit-dispositions-and-base-contract-only" ||
    manifest.proofGraphAutomaticPolicyLearning !== false ||
    manifest.proofGraphNetworkRequired !== false ||
    manifest.proofGraphAuthority !== "none" ||
    manifest.agentAssuranceAvailable !== true ||
    manifest.agentAssurancePacketProfile !==
      "runrail-agent-assurance-packet-v1" ||
    manifest.agentAssuranceResultProfile !==
      "runrail-agent-assurance-result-v1" ||
    manifest.agentAssurancePathFree !== true ||
    manifest.agentAssuranceProjectTestsExecuted !== false ||
    manifest.agentAssuranceNetworkRequired !== false ||
    manifest.agentAssuranceAuthority !== "none" ||
    manifest.agentBridgeAvailable !== true ||
    manifest.agentBridgeProfile !== "runrail-fixed-agent-bridge-v1" ||
    JSON.stringify(manifest.agentBridgeAdapters) !==
      JSON.stringify(["codex", "claude", "gemini", "grok", "generic-copy"]) ||
    manifest.agentBridgeFixedExecutablesOnly !== true ||
    manifest.agentBridgeCallerArgumentsAccepted !== false ||
    manifest.agentBridgeCallerEnvironmentAccepted !== false ||
    manifest.agentBridgeShellEnabled !== false ||
    manifest.agentBridgeRequiresExplicitConfirmation !== true ||
    manifest.agentBridgeAppliesAgentResults !== false ||
    manifest.agentBridgeTrustsAgentCompletionClaims !== false ||
    manifest.agentBridgeNetworkAuthority !== "none" ||
    manifest.agentBridgeRuntimeAuthority !== "none" ||
    manifest.agentOutcomeLedgerAvailable !== true ||
    manifest.agentOutcomeLedgerProfile !==
      "runrail-agent-outcome-ledger-v1" ||
    manifest.agentOutcomeLedgerRepositoryLocal !== true ||
    manifest.agentOutcomeLedgerExplicitLabelsOnly !== true ||
    manifest.agentOutcomeLedgerVerifiedRerunsOnly !== true ||
    manifest.agentOutcomeLedgerGlobalModelScore !== false ||
    manifest.agentOutcomeLedgerCrossRepositoryRanking !== false ||
    manifest.agentOutcomeLedgerAgentQualityClaim !== false ||
    manifest.agentOutcomeLedgerNetworkRequired !== false ||
    manifest.agentOutcomeLedgerAuthority !== "none" ||
    manifest.productMetricsAvailable !== true ||
    manifest.productMetricsProfile !== "runrail-product-metrics-v1" ||
    manifest.productMetricsNorthStar !==
      "completed-assurance-loops-per-active-repository-per-week" ||
    manifest.productMetricsLocalEventLedger !== true ||
    manifest.productMetricsTelemetryDefaultOff !== true ||
    manifest.productMetricsUploadImplemented !== false ||
    manifest.productMetricsAggregateRepositoryIdentityFree !== true ||
    manifest.productMetricsNetworkRequired !== false ||
    manifest.productMetricsAuthority !== "none" ||
    manifest.externalEvidenceAvailable !== true ||
    manifest.externalEvidenceProfile !== "runrail-external-evidence-v1" ||
    JSON.stringify(manifest.externalEvidenceFormats) !==
      JSON.stringify(["sarif", "junit", "lcov"]) ||
    manifest.externalEvidenceMaximumDecodedBytes !== 2 * 1024 * 1024 ||
    manifest.externalEvidenceRawInputPersisted !== false ||
    manifest.externalEvidenceCanChangeVerdict !== false ||
    manifest.externalEvidenceCanChangeAssurance !== false ||
    manifest.externalEvidenceCommandExecution !== false ||
    manifest.externalEvidencePathFreeReceipt !== true ||
    manifest.externalEvidenceAuthority !== "none" ||
    manifest.defaultVerifierProfile !== "safe-static" ||
    JSON.stringify(manifest.staticVerifierLanguages) !==
      JSON.stringify(["python", "javascript", "json", "typescript"]) ||
    manifest.typeScriptParserProfile !== "runrail-parse-only-typescript-v1" ||
    manifest.typeScriptParserPackage !== "typescript" ||
    manifest.typeScriptParserVersion !== "5.9.3" ||
    JSON.stringify(manifest.typeScriptParserExtensions) !==
      JSON.stringify([".jsx", ".ts", ".tsx"]) ||
    manifest.typeScriptParserMaximumFileBytes !== 1024 * 1024 ||
    manifest.typeScriptParserMaximumTotalBytes !== 8 * 1024 * 1024 ||
    manifest.typeScriptParserTsconfigLoaded !== false ||
    manifest.typeScriptParserModuleResolutionUsed !== false ||
    manifest.typeScriptParserPluginLoadingUsed !== false ||
    manifest.typeScriptParserDependencyLoadingUsed !== false ||
    manifest.typeScriptParserEmitUsed !== false ||
    manifest.typeScriptParserProjectCodeExecuted !== false ||
    manifest.typeScriptParserAuthority !== "none" ||
    manifest.staticVerifierProjectCodeExecuted !== false ||
    manifest.staticVerifierProjectTestsExecuted !== false ||
    manifest.revisionComparisonAvailable !== true ||
    manifest.evidenceContinuityAvailable !== true ||
    manifest.evidenceContinuityProfile !== "runrail-evidence-continuity-v1" ||
    manifest.evidenceContinuityMaximumEntries !== 20 ||
    manifest.evidenceContinuityPathFree !== true ||
    manifest.evidenceContinuityOriginAuthenticated !== false ||
    manifest.evidenceContinuityOrderAuthenticated !== false ||
    manifest.evidenceContinuityNetworkRequired !== false ||
    manifest.signedPlanEntitlementAvailable !== true ||
    manifest.signedPlanEntitlementEnforcementDefault !== true ||
    manifest.signedPlanEntitlementAuthority !== "subscription-entitlement-only" ||
    manifest.deviceEnrollmentRequired !== true ||
    manifest.deviceEnrollmentNetworkRequired !== true ||
    manifest.deviceRenewalNetworkRequired !== true ||
    manifest.deviceEntitlementBackgroundDaemonEnabled !== false ||
    manifest.deviceEntitlementRepositoryDataTransmitted !== false ||
    manifest.revisionComparisonProfile !== "runrail-review-comparison-v1" ||
    manifest.revisionComparisonNetworkRequired !== false ||
    manifest.localHtmlReviewAvailable !== true ||
    manifest.browserAuditViewerCompatible !== true ||
    manifest.desktopAppAvailable !== true ||
    manifest.desktopAppMode !== "loopback-local" ||
    manifest.desktopAppNetworkRequired !== false ||
    manifest.desktopAppRepositoryUpload !== false ||
    manifest.desktopAppSourceApplyAvailable !== false ||
    manifest.desktopAppModelKeyStoredInBrowser !== false ||
    manifest.guidedSampleAvailable !== true ||
    manifest.guidedSampleRepositoryUpload !== false ||
    manifest.guidedSampleSourceApplyAvailable !== false ||
    manifest.guidedSampleProjectTestsExecuted !== false ||
    manifest.previewQuickstartAvailable !== true ||
    manifest.previewQuickstartProfile !== "runrail-preview-quickstart-v1" ||
    manifest.previewQuickstartAcceptsCallerInputs !== false ||
    manifest.previewQuickstartProviderRequired !== false ||
    manifest.previewQuickstartAuthority !== "none" ||
    JSON.stringify(manifest.nativeAppLaunchers) !== JSON.stringify([
      "windows-start-menu",
      "macos-application",
      "linux-desktop-entry"
    ]) ||
    manifest.sourceApplyAvailable !== false ||
    !Array.isArray(manifest.files) ||
    checksumSha256 !== sha256(stableJson(body))
  ) {
    throw new Error("distribution-manifest-invalid");
  }

  const required = await loadRequiredDistributionFiles(root);
  const seen = new Set();
  for (const entry of manifest.files) {
    const relative = String(entry?.path || "");
    if (!safeRelativePath(relative) || seen.has(relative) || !/^[a-f0-9]{64}$/.test(String(entry?.sha256 || ""))) {
      throw new Error("distribution-file-record-invalid");
    }
    const requiredRecord = required.get(relative);
    if (!requiredRecord) throw new Error("distribution-manifest-file-unexpected");
    if (requiredRecord.expectedSha256 && requiredRecord.expectedSha256 !== entry.sha256) {
      throw new Error("distribution-engine-file-record-mismatch");
    }
    seen.add(relative);
    required.delete(relative);
    const resolved = path.resolve(root, ...relative.split("/"));
    const contained = path.relative(root, resolved);
    if (!contained || contained.startsWith("..") || path.isAbsolute(contained)) {
      throw new Error("distribution-file-path-escape");
    }
    let info;
    let content;
    try {
      info = await lstat(resolved);
      content = await readFile(resolved);
    } catch {
      throw new Error("distribution-file-missing");
    }
    if (!info.isFile() || info.isSymbolicLink()) throw new Error("distribution-file-type-invalid");
    if (sha256(content) !== entry.sha256) throw new Error("distribution-file-tampered");
  }
  if (required.size > 0) throw new Error("distribution-manifest-incomplete");
  await assertNoUnexpectedEntries(root, seen);
  return {
    mode: "verified-distribution",
    version: manifest.version,
    verifiedFileCount: manifest.files.length,
    checksumSha256
  };
}

const invokedPath = process.argv[1] ? path.resolve(process.argv[1]) : "";
if (invokedPath === fileURLToPath(import.meta.url)) {
  const distributionRoot = path.resolve(process.argv[2] || ".");
  try {
    const result = await verifyRunrailDistribution(distributionRoot);
    process.stdout.write(`${JSON.stringify({ ok: true, ...result })}\n`);
  } catch (error) {
    process.stderr.write(`${String(error?.message || error)}\n`);
    process.exitCode = 1;
  }
}
