import { execFile } from "node:child_process";
import { createHash, randomUUID } from "node:crypto";
import { copyFile, lstat, mkdir, readFile, realpath, rm, writeFile } from "node:fs/promises";
import path from "node:path";
import { promisify } from "node:util";
import { fileURLToPath } from "node:url";
import { validateSubscriberLocalAuditRequest } from "../apps/pilot/src/subscriber-local-audit-request.mjs";
import { verifyRunrailPythonRuntime } from "./runrail-python-runtime-core.mjs";
import { verifyRunrailDistribution } from "./verify-runrail-distribution.mjs";

const execFileAsync = promisify(execFile);
const projectRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");

function configuredRoot(name, fallback) {
  const configured = String(process.env[name] || "").trim();
  return configured ? path.resolve(configured) : fallback;
}

const operatorRoot = configuredRoot("RUNRAIL_OPERATOR_ROOT", path.join(projectRoot, ".veyact", "operator-workspace"));
const engineRoot = configuredRoot("RUNRAIL_ENGINE_ROOT", path.resolve(projectRoot, "..", "SasV"));

export const LOCAL_AUDIT_RUNNER = Object.freeze({
  version: 1,
  artifactType: "veyact-local-audit-evidence",
  engineName: "Ra v1",
  engineTag: "ra-v1.0",
  engineCommit: "3076e7fd0508feecb42d8821e98fa8e3d9db5404",
  operatorRoot,
  reviewedReposRoot: path.join(operatorRoot, "reviewed-repos"),
  runsRoot: path.join(operatorRoot, "runs"),
  exportsRoot: path.join(operatorRoot, "exports"),
  engineRoot
});

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

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`;
}

async function fileSha256(filePath) {
  return sha256(await readFile(filePath));
}

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

async function assertBundledEngineRelease(engineRoot, expectedTag, expectedCommit) {
  const manifestPath = path.join(engineRoot, "RUNRAIL_ENGINE_DISTRIBUTION.json");
  let distribution;
  try {
    distribution = JSON.parse(await readFile(manifestPath, "utf8"));
  } catch {
    throw new LocalAuditRunnerError(
      "engine-distribution-missing",
      "The bundled Ra v1 distribution manifest is missing or invalid."
    );
  }
  const { checksumSha256, ...body } = distribution;
  if (
    distribution?.schemaVersion !== 1 ||
    distribution?.artifactType !== "runrail-engine-distribution" ||
    distribution?.releaseTag !== expectedTag ||
    distribution?.releaseCommit !== expectedCommit ||
    !Array.isArray(distribution?.files) ||
    distribution.files.length < 2 ||
    checksumSha256 !== sha256(stableJson(body))
  ) {
    throw new LocalAuditRunnerError("engine-distribution-mismatch", "The bundled Ra v1 distribution identity is invalid.");
  }
  let releaseManifestIncluded = false;
  let packageSourceIncluded = false;
  for (const entry of distribution.files) {
    if (!safeBundlePath(entry?.path) || !/^[a-f0-9]{64}$/.test(String(entry?.sha256 || ""))) {
      throw new LocalAuditRunnerError("engine-distribution-path", "The bundled engine manifest contains an unsafe file record.");
    }
    const resolved = path.resolve(engineRoot, entry.path);
    if (!isInside(resolved, engineRoot)) {
      throw new LocalAuditRunnerError("engine-distribution-path", "A bundled engine file escaped the engine root.");
    }
    let actual;
    try {
      actual = await fileSha256(resolved);
    } catch {
      throw new LocalAuditRunnerError("engine-distribution-file-missing", "A required bundled engine file is missing.");
    }
    if (actual !== entry.sha256) {
      throw new LocalAuditRunnerError("engine-distribution-tampered", "A bundled engine file failed its SHA-256 check.");
    }
    if (entry.path === "RELEASE_MANIFEST.json") releaseManifestIncluded = true;
    if (entry.path.startsWith("src/ra_cpu/") && entry.path.endsWith(".py")) packageSourceIncluded = true;
  }
  if (!releaseManifestIncluded || !packageSourceIncluded) {
    throw new LocalAuditRunnerError("engine-distribution-incomplete", "The bundled engine manifest is incomplete.");
  }
  return { commit: expectedCommit, tag: expectedTag, mode: "bundled-release", distribution };
}

function isInside(child, parent) {
  const relative = path.relative(parent, child);
  return Boolean(relative) && !relative.startsWith("..") && !path.isAbsolute(relative);
}

function safeTaskText(value) {
  const task = String(value || "").trim();
  if (!task) throw new LocalAuditRunnerError("task-required", "A bounded reviewed task is required.");
  if (task.length > 240) throw new LocalAuditRunnerError("task-too-long", "The reviewed task must be 240 characters or fewer.");
  if (/\p{Cc}/u.test(task)) throw new LocalAuditRunnerError("task-control-character", "The reviewed task contains a control character.");
  return task;
}

async function assertReviewedRepo(repoInput) {
  const requested = path.resolve(String(repoInput || ""));
  await mkdir(LOCAL_AUDIT_RUNNER.reviewedReposRoot, { recursive: true });
  let reviewedRoot;
  let repo;
  try {
    reviewedRoot = await realpath(LOCAL_AUDIT_RUNNER.reviewedReposRoot);
    repo = await realpath(requested);
  } catch {
    throw new LocalAuditRunnerError("reviewed-copy-not-found", "The reviewed repository copy does not exist.");
  }
  if (!isInside(repo, reviewedRoot)) {
    throw new LocalAuditRunnerError(
      "reviewed-copy-boundary",
      "The repository must be a copied Git checkout inside .veyact/operator-workspace/reviewed-repos."
    );
  }
  const info = await lstat(repo);
  if (!info.isDirectory() || info.isSymbolicLink()) {
    throw new LocalAuditRunnerError("reviewed-copy-type", "The reviewed repository copy must be a real directory, not a symlink.");
  }
  const { stdout: insideWorkTree } = await execFileAsync("git", ["-C", repo, "rev-parse", "--is-inside-work-tree"], {
    timeout: 10_000,
    windowsHide: true
  }).catch(() => ({ stdout: "" }));
  if (String(insideWorkTree).trim() !== "true") {
    throw new LocalAuditRunnerError("reviewed-copy-not-git", "The reviewed repository copy must be a Git checkout.");
  }
  const { stdout: status } = await execFileAsync("git", ["-C", repo, "status", "--porcelain=v1", "--untracked-files=all"], {
    timeout: 10_000,
    windowsHide: true
  });
  if (String(status).trim()) {
    throw new LocalAuditRunnerError("reviewed-copy-dirty", "The reviewed repository copy must be clean before a local audit run.");
  }
  return repo;
}

function assertEngineReport(report) {
  const requiredTrue = [
    ["success", report?.success],
    ["planned", report?.planned],
    ["worktree_isolated", report?.worktree_isolated],
    ["patch_proposed", report?.patch_proposed],
    ["verifier_passed", report?.verifier_passed],
    ["trace_recorded", report?.trace_recorded],
    ["human_approval_required_for_apply", report?.human_approval_required_for_apply],
    ["no_external_api_dependency", report?.no_external_api_dependency],
    ["no_background_daemon_enabled", report?.no_background_daemon_enabled],
    ["no_answer_authority_added", report?.no_answer_authority_added],
    ["no_runtime_authority_added", report?.no_runtime_authority_added]
  ];
  const failed = requiredTrue.filter(([, value]) => value !== true).map(([name]) => name);
  if (failed.length) {
    const verifierCodes = (report?.verifier?.records || [])
      .map((record) => Number(record?.returncode ?? -1))
      .join(",");
    const diagnostic = [
      report?.refusal_reason ? `refusal=${String(report.refusal_reason)}` : "",
      verifierCodes ? `verifier_exit_codes=${verifierCodes}` : ""
    ]
      .filter(Boolean)
      .join("; ");
    throw new LocalAuditRunnerError(
      "engine-boundary-failed",
      `Ra v1 report failed required boundaries: ${failed.join(", ")}.${diagnostic ? ` ${diagnostic}.` : ""}`
    );
  }
  if (Number(report?.main_checkout_mutation_count || 0) !== 0) {
    throw new LocalAuditRunnerError("source-checkout-mutated", "Ra v1 reported a source-checkout mutation.");
  }
  if (Number(report?.main_checkout_mutation_without_approval_count || 0) !== 0) {
    throw new LocalAuditRunnerError("unapproved-mutation", "Ra v1 reported an unapproved source-checkout mutation.");
  }
  if (report?.apply_request?.applied === true || report?.apply_request?.approved === true) {
    throw new LocalAuditRunnerError("apply-not-allowed", "The Veyact local audit runner never applies a patch to the reviewed source copy.");
  }
  if (report?.risk?.safe_patch_paths !== true) {
    throw new LocalAuditRunnerError("unsafe-patch-path", "Ra v1 did not confirm safe patch paths.");
  }
}

function taskCategory(report) {
  const strategy = String(report?.plan?.patch_strategy || "");
  if (strategy === "reviewed_service_status_fix") return "reviewed-service-repair";
  if (strategy === "missing_service_import_fix") return "reviewed-import-repair";
  return "reviewed-local-code-task";
}

function safeVerifierResults(report) {
  const records = Array.isArray(report?.verifier?.records) ? report.verifier.records : [];
  return records.map((record, index) => ({
    check: index + 1,
    allowed: record?.allowed === true,
    passed: record?.success === true,
    returnCode: Number(record?.returncode ?? -1),
    result: record?.success === true ? "passed" : "failed"
  }));
}

function collectForbiddenValues(report, context) {
  const values = [context.repoPath, context.taskText, report?.task_text, report?.inspection?.repo_root, report?.patch_report?.diff_text];
  for (const value of report?.patch_report?.changed_files || []) values.push(value);
  for (const value of report?.plan?.target_paths || []) values.push(value);
  for (const command of report?.plan?.approved_verifier_commands || []) values.push(Array.isArray(command) ? command.join(" ") : command);
  for (const record of report?.verifier?.records || []) {
    values.push(Array.isArray(record?.command) ? record.command.join(" ") : record?.command, record?.stdout_tail, record?.stderr_tail);
  }
  for (const value of Object.values(report?.paths || {})) values.push(value);
  return values.map((value) => String(value || "").trim()).filter((value) => value.length >= 4);
}

function assertSanitized(evidence, report, context) {
  const serialized = JSON.stringify(evidence);
  const forbiddenKeys = new Set([
    "repo_root",
    "task_text",
    "paths",
    "target_paths",
    "changed_files",
    "diff_text",
    "command",
    "stdout_tail",
    "stderr_tail",
    "confirmation_token_received",
    "rollback_artifact_path"
  ]);
  const walk = (value) => {
    if (Array.isArray(value)) return value.forEach(walk);
    if (!value || typeof value !== "object") return;
    for (const [key, child] of Object.entries(value)) {
      if (forbiddenKeys.has(key)) {
        throw new LocalAuditRunnerError("unsafe-export-key", `Sanitized evidence contains forbidden field ${key}.`);
      }
      walk(child);
    }
  };
  walk(evidence);
  for (const rawValue of collectForbiddenValues(report, context)) {
    if (serialized.includes(rawValue)) {
      throw new LocalAuditRunnerError("unsafe-export-value", "Sanitized evidence retained a raw engine or repository value.");
    }
  }
  if (/(?:[A-Za-z]:\\|\/(?:home|tmp|Users|mnt|var|etc)\/)/.test(serialized)) {
    throw new LocalAuditRunnerError("absolute-path-export", "Sanitized evidence contains an absolute host path.");
  }
  if (/\b(?:sk|rk|ghp|github_pat|xox[baprs]|AKIA)[-_A-Za-z0-9]{12,}\b/.test(serialized)) {
    throw new LocalAuditRunnerError("secret-like-export", "Sanitized evidence contains a secret-like token.");
  }
}

export function buildSanitizedAuditEvidence(report, context = {}) {
  assertEngineReport(report);
  const generatedAt = context.generatedAt || new Date().toISOString();
  const runId = `VYR-${sha256(String(report.session_id || "missing-session")).slice(0, 16).toUpperCase()}`;
  const verifierResults = safeVerifierResults(report);
  const body = {
    schemaVersion: LOCAL_AUDIT_RUNNER.version,
    artifactType: LOCAL_AUDIT_RUNNER.artifactType,
    product: "Runrail by Veyact",
    evidenceMode: "operator-led-local-audit",
    generatedAt,
    run: {
      runId,
      outcome: "passed",
      taskCategory: taskCategory(report),
      sourceRepoIdentityReturned: false,
      sourceRepoNameReturned: false,
      rawTaskTextReturned: false
    },
    engine: {
      name: LOCAL_AUDIT_RUNNER.engineName,
      releaseTag: LOCAL_AUDIT_RUNNER.engineTag,
      releaseCommit: LOCAL_AUDIT_RUNNER.engineCommit,
      sourceProvenance: "SasV/Ra internal research repo"
    },
    plan: {
      selectedCandidateClass: String(report?.plan?.selected_candidate_id || "ABSTAIN"),
      patchProposed: report.patch_proposed === true,
      changedFileCount: Number(report?.patch_report?.changed_file_count || 0),
      diffLineCount: Number(report?.patch_report?.diff_line_count || 0),
      diffSha256: String(report?.patch_report?.diff_hash || ""),
      changedPathsReturned: false,
      diffContentReturned: false
    },
    approval: {
      requiredBeforeSourceApply: true,
      sourceApplyRequested: false,
      sourceApplyPerformed: false,
      browserApprovalSupported: false,
      disposition: "proposal-only-source-untouched"
    },
    verifier: {
      passed: report.verifier_passed === true,
      checkCount: Number(report?.verifier?.command_count || verifierResults.length),
      results: verifierResults,
      commandDetailsReturned: false,
      rawLogsReturned: false
    },
    trace: {
      recorded: report.trace_recorded === true,
      eventCount: Number(context.traceEventCount ?? report?.trace_event_count ?? 0),
      rawTraceReturned: false
    },
    rollback: {
      sourceCheckoutUntouched: true,
      isolatedWorktreeDisposable: true,
      sourceRollbackRequired: false,
      rawRollbackCommandReturned: false
    },
    safety: {
      reviewedCopyBoundaryEnforced: true,
      worktreeIsolated: report.worktree_isolated === true,
      safePatchPaths: report?.risk?.safe_patch_paths === true,
      sourceCheckoutMutationCount: Number(report.main_checkout_mutation_count || 0),
      unapprovedMutationCount: Number(report.main_checkout_mutation_without_approval_count || 0),
      externalApiDependency: false,
      backgroundDaemonEnabled: false,
      learnedAnswerAuthorityAdded: false,
      learnedRuntimeAuthorityAdded: false,
      networkBridgeEnabled: false,
      customerRepoUploadEnabled: false
    },
    redaction: {
      rawSourceIncluded: false,
      repositoryPathIncluded: false,
      repositoryNameIncluded: false,
      rawTaskIncluded: false,
      commandTextIncluded: false,
      diffContentIncluded: false,
      rawLogsIncluded: false,
      secretsIncluded: false,
      personalDataIncluded: false
    },
    limitations: [
      "operator-led local Alpha evidence only",
      "not autonomous arbitrary-repository repair",
      "not a browser execution endpoint",
      "not production-readiness or launch approval",
      "no source apply was performed"
    ]
  };
  if (context.requestPacket) {
    body.request = {
      requestId: context.requestPacket.requestId,
      taskClass: context.requestPacket.taskClass.id,
      expectedEvidenceCategory: context.requestPacket.taskClass.expectedEvidenceCategory,
      packetChecksumSha256: context.requestPacket.checksumSha256,
      authorityGranted: false,
      serverReceivedRepoPath: false,
      serverReceivedTaskText: false
    };
  }
  const evidence = { ...body, checksumSha256: sha256(stableJson(body)) };
  assertSanitized(evidence, report, context);
  return evidence;
}

function runnerEnvironment(engineRoot) {
  return {
    PATH: String(process.env.PATH || ""),
    HOME: String(process.env.HOME || ""),
    LANG: String(process.env.LANG || "C.UTF-8"),
    LC_ALL: String(process.env.LC_ALL || "C.UTF-8"),
    PYTHONDONTWRITEBYTECODE: "1",
    PYTHONHASHSEED: "0",
    PYTHONNOUSERSITE: "1",
    RUNRAIL_ENGINE_ROOT: engineRoot
  };
}

export async function assertFrozenEngineRelease({
  engineRoot = LOCAL_AUDIT_RUNNER.engineRoot,
  expectedTag = LOCAL_AUDIT_RUNNER.engineTag,
  expectedCommit = LOCAL_AUDIT_RUNNER.engineCommit
} = {}) {
  const manifest = JSON.parse(await readFile(path.join(engineRoot, "RELEASE_MANIFEST.json"), "utf8"));
  if (manifest?.git_tag !== expectedTag || manifest?.ra_v1_passed !== true || manifest?.all_gates_passed !== true) {
    throw new LocalAuditRunnerError("engine-release-mismatch", "The local engine is not the frozen passing Ra v1 release.");
  }
  try {
    await lstat(path.join(engineRoot, ".git"));
  } catch {
    const bundled = await assertBundledEngineRelease(engineRoot, expectedTag, expectedCommit);
    return { manifest, ...bundled };
  }
  let head;
  let taggedCommit;
  let status;
  try {
    ({ stdout: head } = await execFileAsync("git", ["-C", engineRoot, "rev-parse", "HEAD"], {
      timeout: 10_000,
      windowsHide: true
    }));
    ({ stdout: taggedCommit } = await execFileAsync("git", ["-C", engineRoot, "rev-parse", `${expectedTag}^{commit}`], {
      timeout: 10_000,
      windowsHide: true
    }));
    ({ stdout: status } = await execFileAsync("git", ["-C", engineRoot, "status", "--porcelain=v1", "--untracked-files=all"], {
      timeout: 10_000,
      windowsHide: true
    }));
  } catch {
    throw new LocalAuditRunnerError("engine-release-mismatch", "The local engine Git release identity could not be verified.");
  }
  const actualHead = String(head).trim();
  const actualTaggedCommit = String(taggedCommit).trim();
  if (actualHead !== expectedCommit || actualTaggedCommit !== expectedCommit || actualHead !== actualTaggedCommit) {
    throw new LocalAuditRunnerError("engine-release-mismatch", "The local engine HEAD, release tag, and pinned commit do not match.");
  }
  if (String(status).trim()) {
    throw new LocalAuditRunnerError("engine-checkout-dirty", "The local engine checkout must be clean before a product audit run.");
  }
  return { manifest, commit: actualHead, tag: expectedTag, mode: "git-release" };
}

async function resolveEnginePython(engineRoot) {
  const configuredPython = String(process.env.RUNRAIL_PYTHON || "").trim();
  if (configuredPython) {
    try {
      const info = await lstat(configuredPython);
      if (!info.isFile() && !info.isSymbolicLink()) throw new Error("not executable");
      const { stdout, stderr } = await execFileAsync(configuredPython, ["-I", "-S", "-B", "--version"], {
        timeout: 10_000,
        windowsHide: true
      });
      const versionText = `${stdout || ""}${stderr || ""}`.trim();
      const match = versionText.match(/Python\s+(\d+)\.(\d+)/);
      if (!match || Number(match[1]) < 3 || (Number(match[1]) === 3 && Number(match[2]) < 11)) {
        throw new Error("unsupported Python version");
      }
      return { command: configuredPython, bundled: false, version: versionText, mode: "distribution-venv" };
    } catch {
      throw new LocalAuditRunnerError("engine-python-invalid", "The installed Runrail Python environment is missing or invalid.");
    }
  }
  const venvPython = path.join(engineRoot, ".venv", "bin", "python");
  try {
    await lstat(venvPython);
    return { command: venvPython, bundled: false };
  } catch {}
  try {
    const { stdout, stderr } = await execFileAsync("python3", ["-I", "-S", "-B", "--version"], {
      timeout: 10_000,
      windowsHide: true
    });
    const versionText = `${stdout || ""}${stderr || ""}`.trim();
    const match = versionText.match(/Python\s+(\d+)\.(\d+)/);
    if (!match || Number(match[1]) < 3 || (Number(match[1]) === 3 && Number(match[2]) < 11)) {
      throw new Error("unsupported Python version");
    }
    return { command: "python3", bundled: true, version: versionText };
  } catch {
    throw new LocalAuditRunnerError(
      "engine-python-missing",
      "Runrail requires Python 3.11 or newer, or the development engine virtual environment."
    );
  }
}

export async function localAuditDoctor() {
  let distribution;
  try {
    distribution = await verifyRunrailDistribution(projectRoot, { allowMissing: true });
  } catch (error) {
    throw new LocalAuditRunnerError(String(error?.message || "distribution-verification-failed"), "The Runrail distribution failed its SHA-256 integrity check.");
  }
  await mkdir(LOCAL_AUDIT_RUNNER.reviewedReposRoot, { recursive: true });
  await mkdir(LOCAL_AUDIT_RUNNER.runsRoot, { recursive: true });
  await mkdir(LOCAL_AUDIT_RUNNER.exportsRoot, { recursive: true });
  const pythonRuntime = distribution.mode === "verified-distribution"
    ? await verifyRunrailPythonRuntime(projectRoot)
    : { mode: "development-external-runtime" };
  const engine = await assertFrozenEngineRelease();
  const python = await resolveEnginePython(LOCAL_AUDIT_RUNNER.engineRoot);
  const bootstrapPath = path.join(projectRoot, "scripts", "runrail-engine-bootstrap.py");
  let bootstrap;
  try {
    const { stdout } = await execFileAsync(
      python.command,
      ["-I", "-S", "-B", bootstrapPath, "--bootstrap-probe"],
      {
        env: runnerEnvironment(LOCAL_AUDIT_RUNNER.engineRoot),
        timeout: 10_000,
        maxBuffer: 1024 * 1024,
        windowsHide: true
      }
    );
    bootstrap = JSON.parse(stdout);
  } catch {
    throw new LocalAuditRunnerError(
      "engine-python-bootstrap-invalid",
      "The installed Python runtime could not load the verified engine in isolated no-site mode."
    );
  }
  if (
    bootstrap?.ok !== true ||
    bootstrap?.mode !== "isolated-no-site" ||
    bootstrap?.siteImported !== false ||
    !isInside(path.resolve(String(bootstrap?.modulePath || "")), LOCAL_AUDIT_RUNNER.engineRoot)
  ) {
    throw new LocalAuditRunnerError(
      "engine-python-bootstrap-invalid",
      "The installed Python bootstrap escaped the verified engine or enabled site initialization."
    );
  }
  let gitVersion = "";
  try {
    ({ stdout: gitVersion } = await execFileAsync("git", ["--version"], { timeout: 10_000, windowsHide: true }));
  } catch {
    throw new LocalAuditRunnerError("git-missing", "Runrail requires Git.");
  }
  const nodeMajor = Number(String(process.versions.node || "0").split(".")[0]);
  if (nodeMajor < 20) throw new LocalAuditRunnerError("node-version", "Runrail requires Node.js 20 or newer.");
  return {
    ok: true,
    product: "Runrail Local Audit Runner",
    runtime: {
      platform: `${process.platform}-${process.arch}`,
      node: process.versions.node,
      python: python.version || "development-venv",
      pythonMode: python.mode || (python.bundled ? "system-python" : "development-venv"),
      pythonIsolation: bootstrap.mode,
      pythonSiteInitialization: false,
      pythonBootstrapVerified: true,
      pythonRuntimeIntegrity: pythonRuntime.mode,
      git: String(gitVersion).trim()
    },
    engine: {
      name: LOCAL_AUDIT_RUNNER.engineName,
      tag: engine.tag,
      commit: engine.commit,
      mode: engine.mode
    },
    distribution,
    workspace: {
      reviewedReposRoot: LOCAL_AUDIT_RUNNER.reviewedReposRoot,
      runsRoot: LOCAL_AUDIT_RUNNER.runsRoot,
      exportsRoot: LOCAL_AUDIT_RUNNER.exportsRoot
    },
    boundaries: {
      networkRequiredForRuns: false,
      sourceApplyAvailable: false,
      browserExecutionAvailable: false,
      arbitraryCommandAvailable: false
    }
  };
}

function safePreparedName(sourceRepo, head) {
  const basename = path.basename(sourceRepo).replace(/[^A-Za-z0-9._-]+/g, "-").replace(/^-+|-+$/g, "") || "reviewed-repo";
  return `${basename.slice(0, 48)}-${String(head).slice(0, 12)}-${randomUUID().slice(0, 8)}`;
}

export async function prepareReviewedRepo(sourceInput) {
  let sourceRepo;
  try {
    sourceRepo = await realpath(path.resolve(String(sourceInput || "")));
  } catch {
    throw new LocalAuditRunnerError("source-repo-not-found", "The source repository does not exist.");
  }
  const info = await lstat(sourceRepo);
  if (!info.isDirectory() || info.isSymbolicLink()) {
    throw new LocalAuditRunnerError("source-repo-type", "The source repository must be a real directory, not a symlink.");
  }
  let head;
  let status;
  try {
    ({ stdout: head } = await execFileAsync("git", ["-C", sourceRepo, "rev-parse", "HEAD"], {
      timeout: 10_000,
      windowsHide: true
    }));
    ({ stdout: status } = await execFileAsync("git", ["-C", sourceRepo, "status", "--porcelain=v1", "--untracked-files=all"], {
      timeout: 10_000,
      windowsHide: true
    }));
  } catch {
    throw new LocalAuditRunnerError("source-repo-not-git", "The source repository must be a Git checkout.");
  }
  if (String(status).trim()) {
    throw new LocalAuditRunnerError("source-repo-dirty", "The source repository must be clean before preparing a reviewed copy.");
  }
  await mkdir(LOCAL_AUDIT_RUNNER.reviewedReposRoot, { recursive: true });
  const destination = path.join(LOCAL_AUDIT_RUNNER.reviewedReposRoot, safePreparedName(sourceRepo, String(head).trim()));
  try {
    await execFileAsync("git", ["clone", "--quiet", "--local", "--no-hardlinks", "--no-recurse-submodules", sourceRepo, destination], {
      timeout: 120_000,
      maxBuffer: 4 * 1024 * 1024,
      windowsHide: true
    });
    await assertReviewedRepo(destination);
  } catch (error) {
    await rm(destination, { recursive: true, force: true });
    if (error instanceof LocalAuditRunnerError) throw error;
    throw new LocalAuditRunnerError("reviewed-copy-failed", "Runrail could not create the isolated reviewed repository copy.");
  }
  return {
    ok: true,
    reviewedRepo: destination,
    sourceCommit: String(head).trim(),
    sourceCheckoutMutated: false,
    networkUsed: false
  };
}

export async function runLocalAudit({ repo, task, requestPacket = null }) {
  let validatedRequest = null;
  if (requestPacket) {
    try {
      validatedRequest = validateSubscriberLocalAuditRequest(requestPacket);
    } catch (error) {
      throw new LocalAuditRunnerError("request-invalid", error.message);
    }
  }
  const taskText = safeTaskText(task);
  const repoPath = await assertReviewedRepo(repo);
  await assertFrozenEngineRelease();
  const python = await resolveEnginePython(LOCAL_AUDIT_RUNNER.engineRoot);
  const bootstrapPath = path.join(projectRoot, "scripts", "runrail-engine-bootstrap.py");

  const requestId = sha256(`${repoPath}\0${taskText}\0${Date.now()}`).slice(0, 20);
  const stateDir = path.join(LOCAL_AUDIT_RUNNER.runsRoot, requestId, "engine-state");
  await mkdir(stateDir, { recursive: true });
  const args = [
    "-I",
    "-S",
    "-B",
    bootstrapPath,
    "repo-task",
    "--repo",
    repoPath,
    "--task",
    taskText,
    "--state-dir",
    stateDir,
    "--json"
  ];
  let stdout;
  try {
    ({ stdout } = await execFileAsync(python.command, args, {
      cwd: LOCAL_AUDIT_RUNNER.engineRoot,
      env: runnerEnvironment(LOCAL_AUDIT_RUNNER.engineRoot),
      timeout: 120_000,
      maxBuffer: 8 * 1024 * 1024,
      windowsHide: true
    }));
  } catch (error) {
    throw new LocalAuditRunnerError("engine-run-failed", `Ra v1 local audit failed with exit code ${error.code || "unknown"}.`);
  }

  let report;
  try {
    report = JSON.parse(stdout);
  } catch {
    throw new LocalAuditRunnerError("engine-json-invalid", "Ra v1 did not return a valid JSON session report.");
  }
  const tracePath = path.resolve(String(report?.paths?.trace_path || ""));
  const stateRoot = path.resolve(stateDir);
  if (!isInside(tracePath, stateRoot)) {
    throw new LocalAuditRunnerError("engine-trace-boundary", "Ra v1 trace path escaped the runner-owned state directory.");
  }
  const traceText = await readFile(tracePath, "utf8");
  const traceEventCount = traceText.split(/\r?\n/).filter(Boolean).length;
  if (traceEventCount < 1) {
    throw new LocalAuditRunnerError("engine-trace-empty", "Ra v1 reported a trace but produced no trace events.");
  }
  const enginePatchPath = path.resolve(String(report?.paths?.patch_path || ""));
  if (!isInside(enginePatchPath, stateRoot)) {
    throw new LocalAuditRunnerError("engine-patch-boundary", "Ra v1 patch path escaped the runner-owned state directory.");
  }
  const actualTaskCategory = taskCategory(report);
  if (validatedRequest && actualTaskCategory !== validatedRequest.taskClass.expectedEvidenceCategory) {
    throw new LocalAuditRunnerError(
      "request-task-class-mismatch",
      "The engine proposal does not match the requested allowlisted task class."
    );
  }
  const evidence = buildSanitizedAuditEvidence(report, {
    repoPath,
    taskText,
    traceEventCount,
    requestPacket: validatedRequest
  });
  const exportDir = path.join(LOCAL_AUDIT_RUNNER.exportsRoot, evidence.run.runId);
  const proposalDir = path.join(LOCAL_AUDIT_RUNNER.runsRoot, requestId, "proposal");
  await mkdir(exportDir, { recursive: true });
  await mkdir(proposalDir, { recursive: true });
  const files = {
    evidence: "evidence.json",
    manifest: "manifest.json",
    receipt: "receipt.md"
  };
  const manifestBody = {
    schemaVersion: 1,
    artifactType: "veyact-local-audit-export-manifest",
    runId: evidence.run.runId,
    evidenceChecksumSha256: evidence.checksumSha256,
    files,
    rawEngineArtifactsIncluded: false,
    sourceRepositoryMaterialIncluded: false,
    uploadPerformed: false
  };
  const manifest = { ...manifestBody, checksumSha256: sha256(stableJson(manifestBody)) };
  const receipt = `# Veyact Local Audit Receipt\n\n- Run: ${evidence.run.runId}\n- Outcome: ${evidence.run.outcome}\n- Engine: ${evidence.engine.name} (${evidence.engine.releaseTag})\n- Verifiers: ${evidence.verifier.checkCount} passed\n- Source checkout mutation count: 0\n- Export mode: sanitized local files only\n\nNo repository path, task text, command text, diff content, raw logs, secret, or personal data is included.\n`;
  const proposalPath = path.join(proposalDir, "proposal.patch");
  const reviewPath = path.join(proposalDir, "REVIEW.md");
  const rollbackPath = path.join(proposalDir, "ROLLBACK.md");
  await copyFile(enginePatchPath, proposalPath);
  await writeFile(
    reviewPath,
    `# Runrail Local Proposal\n\nThis patch was produced and verified in an isolated worktree. The reviewed source checkout was not changed.\n\n1. Inspect \`proposal.patch\` locally.\n2. Run your own project checks.\n3. Approve and apply it manually only if the diff is acceptable.\n\nRunrail does not apply this patch automatically and does not upload it.\n`,
    "utf8"
  );
  await writeFile(
    rollbackPath,
    "# Rollback note\n\nNo rollback is required because Runrail did not modify the reviewed source checkout. If you manually apply the proposal later, create a Git commit first and use your normal Git revert workflow.\n",
    "utf8"
  );
  await writeFile(path.join(exportDir, files.evidence), stableJson(evidence), "utf8");
  await writeFile(path.join(exportDir, files.manifest), stableJson(manifest), "utf8");
  await writeFile(path.join(exportDir, files.receipt), receipt, "utf8");
  return {
    ok: true,
    mode: "operator-led-local-audit",
    runId: evidence.run.runId,
    outcome: evidence.run.outcome,
    exportDir,
    files,
    localProposal: {
      proposalPath,
      reviewPath,
      rollbackPath,
      containsRepositoryContent: true,
      uploaded: false,
      sourceApplyPerformed: false
    },
    evidence,
    boundaries: {
      sourceCheckoutApplied: false,
      browserExecutionEnabled: false,
      networkBridgeEnabled: false,
      uploadPerformed: false
    }
  };
}
