#!/usr/bin/env node
import { createHash } from "node:crypto";
import { lstat, mkdir, readFile, realpath, rm, writeFile } from "node:fs/promises";
import path from "node:path";
import {
  LOCAL_AUDIT_RUNNER,
  localAuditDoctor,
  LocalAuditRunnerError,
  prepareReviewedRepo,
  runLocalAudit
} from "./veyact-local-audit-runner-core.mjs";
import { reviewCandidateBranch } from "./runrail-branch-review-core.mjs";
import { verifyRunrailCandidateAudit } from "./runrail-deepseek-advisory-core.mjs";
import {
  compareRunrailReviewAudits,
  renderRunrailReviewComparisonHtml,
  renderRunrailReviewComparisonMarkdown,
  stableRunrailComparisonJson
} from "./runrail-review-comparison-core.mjs";
import {
  buildRunrailEvidenceContinuity,
  renderRunrailEvidenceContinuityHtml,
  renderRunrailEvidenceContinuityMarkdown,
  stableRunrailEvidenceContinuityJson
} from "./runrail-evidence-continuity-core.mjs";
import { writeRunrailReviewFocusArtifacts } from "./runrail-review-focus-core.mjs";
import {
  verifyRunrailHunkAttentionManifest,
  verifyRunrailHunkContinuity,
  writeRunrailHunkContinuityArtifacts
} from "./runrail-hunk-continuity-core.mjs";
import {
  writeRunrailReviewDeltaBundle
} from "./runrail-review-delta-core.mjs";
import {
  loadRunrailAgentAssurancePacket,
  writeRunrailAgentAssurancePacket,
  writeRunrailAgentAssuranceResult
} from "./runrail-agent-assurance-core.mjs";

function usage() {
  return `Runrail Local Audit Runner v1

Usage:
  runrail desktop [--repo <local-git-checkout>] [--port 0] [--no-open] [--json]
  runrail doctor --json
  runrail sample --json
  runrail prepare --repo <clean-git-checkout> --json
  runrail audit --request <packet.json> --repo <reviewed-copy> --task <bounded-task> --json
  runrail review --repo <clean-git-checkout> --base <base-ref> --candidate <candidate-ref> [--verifier safe-static|python-compile] --json
  runrail focus --audit <absolute-runrail-audit.json> --json
  runrail coverage --audit <absolute-runrail-audit.json> [--attention <absolute-attention.json>] [--previous <absolute-coverage.json>] --json
  runrail recheck --before <absolute-prior-audit.json> --after <absolute-current-audit.json> --previous <absolute-prior-coverage.json> --json
  runrail compare --before <absolute-baseline-audit.json> --after <absolute-revised-audit.json> --json
  runrail lineage --audit <absolute-audit.json> --audit <absolute-audit.json> [--audit <absolute-audit.json> ...] --json
  runrail handoff --audit <absolute-runrail-audit.json> --json
  runrail assure --packet <absolute-packet.json> --before <absolute-prior-audit.json> --after <absolute-current-audit.json> [--coverage <absolute-current-coverage.json>] --json
  runrail recommend --audit <absolute-runrail-audit.json> [--provider deterministic|deepseek] [--allow-network] --json
  runrail advise --audit <absolute-runrail-audit.json> --allow-network --json

Desktop opens the local loopback-only review workbench. Pass --repo . to begin with the current checkout. It adds no repository upload or source-apply authority.
Sample creates a safe local Git fixture, reviews its candidate branch, and returns the real local evidence path.
Prepare creates an isolated local copy under the Runrail workspace.
Audit produces a local engine proposal patch plus a separate sanitized evidence export.
Review applies the base-commit-owned review contract and defaults to bounded non-executing Python, JavaScript, and JSON syntax checks without checking out the candidate in the source repository.
Focus verifies one Runrail-owned audit and returns a path-free, ordered review plan that also works when the preflight is blocked.
Coverage records path-free human attention per exact diff hunk. Only a unique byte-and-context-identical hunk may carry reviewed or needs-revision state into a related revision; changed or ambiguous hunks reset to unreviewed.
Recheck binds a related prior audit and its exact Review Coverage to the current audit, carries only exact unique hunk attention, and exports a deterministic path-free re-review map.
Compare verifies two related local review audits and exports deterministic revision evidence without opening either repository.
Lineage verifies 2 to 20 related Runrail-owned review audits and exports a path-free, checksum-linked declared evidence sequence with finding lifecycle and policy-basis continuity.
Handoff turns one verified audit into a source-free correction packet that can be given to any coding agent. It contains fixed product-authored objectives, no repository identity, and no execution authority.
Assure binds that packet to a related revised audit and classifies resolved, remaining, new, and reintroduced findings without executing or applying the revision. Ready for human decision additionally requires verified current Review Coverage.
Recommend defaults to the offline deterministic Runrail policy. DeepSeek is an optional BYOK provider over minimized counts and booleans and requires explicit network consent.
Advise remains the compatibility alias for the DeepSeek provider.
Ordinary commands stay local and never upload evidence. Focus, Coverage, Recheck, Handoff, Assure, and both advisory paths exclude source, diff, path, commit, task, repository identity, and raw verifier output from their portable evidence, and none grants execution authority.
Runrail does not run project tests or determine semantic correctness. It never applies a patch to the reviewed source copy.
`;
}

function parseArgs(argv) {
  const values = [...argv];
  const command = ["desktop", "doctor", "sample", "prepare", "audit", "review", "focus", "coverage", "recheck", "compare", "lineage", "handoff", "assure", "recommend", "advise"].includes(values[0]) ? values.shift() : "audit";
  const parsed = {
    command,
    request: "",
    repo: "",
    task: "",
    base: "",
    candidate: "",
    auditFile: "",
    auditFiles: [],
    beforeAuditFile: "",
    afterAuditFile: "",
    attentionFile: "",
    previousCoverageFile: "",
    coverageFile: "",
    packetFile: "",
    verifier: "safe-static",
    provider: command === "advise" ? "deepseek" : "deterministic",
    allowNetwork: false,
    port: 0,
    open: true,
    json: false,
    help: false
  };
  for (let index = 0; index < values.length; index += 1) {
    const arg = values[index];
    if (arg === "--help" || arg === "-h") parsed.help = true;
    else if (arg === "--json") parsed.json = true;
    else if (arg === "--request") parsed.request = values[++index] || "";
    else if (arg === "--repo") parsed.repo = values[++index] || "";
    else if (arg === "--task") parsed.task = values[++index] || "";
    else if (arg === "--base") parsed.base = values[++index] || "";
    else if (arg === "--candidate") parsed.candidate = values[++index] || "";
    else if (arg === "--audit") {
      const value = values[++index] || "";
      parsed.auditFile = value;
      parsed.auditFiles.push(value);
    }
    else if (arg === "--before") parsed.beforeAuditFile = values[++index] || "";
    else if (arg === "--after") parsed.afterAuditFile = values[++index] || "";
    else if (arg === "--attention") parsed.attentionFile = values[++index] || "";
    else if (arg === "--previous") parsed.previousCoverageFile = values[++index] || "";
    else if (arg === "--coverage") parsed.coverageFile = values[++index] || "";
    else if (arg === "--packet") parsed.packetFile = values[++index] || "";
    else if (arg === "--verifier") parsed.verifier = values[++index] || "";
    else if (arg === "--provider") parsed.provider = values[++index] || "";
    else if (arg === "--allow-network") parsed.allowNetwork = true;
    else if (arg === "--port") {
      const value = Number(values[++index]);
      if (!Number.isInteger(value) || value < 0 || value > 65_535) {
        throw new LocalAuditRunnerError("desktop-port-invalid", "Desktop port must be an integer between 0 and 65535.");
      }
      parsed.port = value;
    }
    else if (arg === "--no-open") parsed.open = false;
    else throw new LocalAuditRunnerError("unknown-argument", `Unknown argument: ${arg}`);
  }
  return parsed;
}

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

async function loadOwnedCandidateAudit(auditInput, purpose = "advisory") {
  const pathCode = {
    advisory: "advisory-audit-path",
    focus: "focus-audit-path",
    coverage: "hunk-continuity-audit-path",
    delta: "review-delta-audit-path",
    comparison: "comparison-audit-path",
    lineage: "lineage-audit-path",
    assurance: "agent-assurance-audit-path"
  }[purpose];
  const invalidCode = {
    advisory: "advisory-audit-invalid",
    focus: "focus-audit-invalid",
    coverage: "hunk-continuity-audit-invalid",
    delta: "review-delta-audit-invalid",
    comparison: "comparison-audit-invalid",
    lineage: "lineage-audit-invalid",
    assurance: "agent-assurance-audit-invalid"
  }[purpose];
  const action = {
    advisory: "Advise",
    focus: "Focus",
    coverage: "Coverage",
    delta: "Recheck",
    comparison: "Compare",
    lineage: "Lineage",
    assurance: "Agent Assurance"
  }[purpose];
  if (!auditInput || !path.isAbsolute(auditInput)) {
    throw new LocalAuditRunnerError(pathCode, `${action} requires absolute Runrail-owned audit paths.`);
  }
  const requested = path.resolve(auditInput);
  let info;
  let auditPath;
  let runsRoot;
  try {
    info = await lstat(requested);
    auditPath = await realpath(requested);
    runsRoot = await realpath(LOCAL_AUDIT_RUNNER.runsRoot);
  } catch {
    throw new LocalAuditRunnerError(pathCode, "The Runrail review audit path does not exist or is not accessible.");
  }
  if (!info.isFile() || info.isSymbolicLink() || !isInside(auditPath, runsRoot)) {
    throw new LocalAuditRunnerError(pathCode, "The audit must be a regular Runrail-owned review artifact.");
  }
  const relative = path.relative(runsRoot, auditPath);
  const parts = relative.split(path.sep);
  if (parts.length !== 3 || !/^RRV-[A-F0-9]{16}-[a-f0-9]{8}$/.test(parts[0]) || parts[1] !== "review" || parts[2] !== "audit.json") {
    throw new LocalAuditRunnerError(pathCode, "The audit must be the audit.json file from a Runrail candidate review.");
  }
  let audit;
  try {
    audit = JSON.parse(await readFile(auditPath, "utf8"));
  } catch {
    throw new LocalAuditRunnerError(invalidCode, "The Runrail review audit must contain valid JSON.");
  }
  return { audit, auditPath };
}

async function loadOwnedCoverage(coverageInput) {
  if (!coverageInput || !path.isAbsolute(coverageInput)) {
    throw new LocalAuditRunnerError(
      "hunk-continuity-previous-path",
      "Coverage requires an absolute prior Runrail-owned coverage path."
    );
  }
  const requested = path.resolve(coverageInput);
  let info;
  let coveragePath;
  let runsRoot;
  try {
    info = await lstat(requested);
    coveragePath = await realpath(requested);
    runsRoot = await realpath(LOCAL_AUDIT_RUNNER.runsRoot);
  } catch {
    throw new LocalAuditRunnerError(
      "hunk-continuity-previous-path",
      "The prior Review Coverage path does not exist or is not accessible."
    );
  }
  const parts = path.relative(runsRoot, coveragePath).split(path.sep);
  if (
    !info.isFile() ||
    info.isSymbolicLink() ||
    !isInside(coveragePath, runsRoot) ||
    parts.length !== 5 ||
    !/^RRV-[A-F0-9]{16}-[a-f0-9]{8}$/.test(parts[0]) ||
    parts[1] !== "review" ||
    parts[2] !== "coverage" ||
    !/^COV-[A-F0-9]{24}$/.test(parts[3]) ||
    parts[4] !== "coverage.json"
  ) {
    throw new LocalAuditRunnerError(
      "hunk-continuity-previous-path",
      "The prior artifact must be a regular Runrail-owned coverage.json file."
    );
  }
  try {
    const coverage = JSON.parse(await readFile(coveragePath, "utf8"));
    verifyRunrailHunkContinuity(coverage);
    return coverage;
  } catch (error) {
    if (error instanceof LocalAuditRunnerError) throw error;
    throw new LocalAuditRunnerError(
      "hunk-continuity-previous-invalid",
      "The prior Review Coverage artifact is invalid."
    );
  }
}

async function loadHunkAttention(attentionInput) {
  if (!attentionInput) return null;
  if (!path.isAbsolute(attentionInput)) {
    throw new LocalAuditRunnerError(
      "hunk-attention-path",
      "Coverage attention requires an absolute local JSON path."
    );
  }
  const requested = path.resolve(attentionInput);
  let entry;
  try {
    entry = await lstat(requested);
  } catch {
    throw new LocalAuditRunnerError(
      "hunk-attention-path",
      "The Review Coverage attention file does not exist."
    );
  }
  if (!entry.isFile() || entry.isSymbolicLink() || entry.size > 256 * 1024) {
    throw new LocalAuditRunnerError(
      "hunk-attention-path",
      "Review Coverage attention must be a bounded ordinary local file."
    );
  }
  try {
    const attention = JSON.parse(await readFile(requested, "utf8"));
    verifyRunrailHunkAttentionManifest(attention);
    return attention;
  } catch (error) {
    if (error instanceof LocalAuditRunnerError) throw error;
    throw new LocalAuditRunnerError(
      "hunk-attention-invalid",
      "The Review Coverage attention file must contain valid JSON."
    );
  }
}

async function readOwnedCandidatePatch(auditPath) {
  const patchPath = path.join(path.dirname(auditPath), "candidate.patch");
  let entry;
  try {
    entry = await lstat(patchPath);
  } catch {
    throw new LocalAuditRunnerError(
      "hunk-continuity-patch-path",
      "Coverage requires candidate.patch beside its Runrail audit."
    );
  }
  if (!entry.isFile() || entry.isSymbolicLink() || entry.size > 12 * 1024 * 1024) {
    throw new LocalAuditRunnerError(
      "hunk-continuity-patch-path",
      "Coverage requires the bounded ordinary candidate.patch beside its audit."
    );
  }
  return readFile(patchPath, "utf8");
}

async function assertAdvisoryArtifactAvailable(advisoryPath, advisoryFile) {
  try {
    await lstat(advisoryPath);
  } catch (error) {
    if (error?.code === "ENOENT") return;
    throw error;
  }
  throw new LocalAuditRunnerError(
    "advisory-artifact-exists",
    `Remove the existing local ${advisoryFile} before requesting the same advisory again.`
  );
}

async function writeComparisonArtifacts(beforeRecord, afterRecord) {
  verifyRunrailCandidateAudit(beforeRecord.audit);
  verifyRunrailCandidateAudit(afterRecord.audit);
  const comparisonBody = compareRunrailReviewAudits(beforeRecord.audit, afterRecord.audit);
  const checksumSha256 = createHash("sha256").update(stableRunrailComparisonJson(comparisonBody)).digest("hex");
  const comparison = { ...comparisonBody, checksumSha256 };
  const afterReviewRoot = path.dirname(afterRecord.auditPath);
  const comparisonsRoot = path.join(afterReviewRoot, "comparisons");
  try {
    const existing = await lstat(comparisonsRoot);
    if (!existing.isDirectory() || existing.isSymbolicLink()) {
      throw new LocalAuditRunnerError("comparison-artifact-boundary", "The local comparison directory must be an ordinary Runrail-owned directory.");
    }
    const resolvedComparisonsRoot = await realpath(comparisonsRoot);
    if (!isInside(resolvedComparisonsRoot, afterReviewRoot)) {
      throw new LocalAuditRunnerError("comparison-artifact-boundary", "The local comparison directory escaped the revised review directory.");
    }
  } catch (error) {
    if (error instanceof LocalAuditRunnerError) throw error;
    if (error?.code !== "ENOENT") throw error;
    await mkdir(comparisonsRoot, { mode: 0o700 });
  }

  const outputRoot = path.join(comparisonsRoot, comparison.comparisonId);
  try {
    await mkdir(outputRoot, { mode: 0o700 });
  } catch (error) {
    if (error?.code === "EEXIST") {
      throw new LocalAuditRunnerError(
        "comparison-artifact-exists",
        "This local revision comparison already exists. Its artifacts were not overwritten."
      );
    }
    throw error;
  }
  const comparisonPath = path.join(outputRoot, "comparison.json");
  const reviewPath = path.join(outputRoot, "REVIEW_COMPARISON.md");
  const htmlReportPath = path.join(outputRoot, "comparison.html");
  try {
    await writeFile(comparisonPath, stableRunrailComparisonJson(comparison), { encoding: "utf8", mode: 0o600, flag: "wx" });
    await writeFile(reviewPath, renderRunrailReviewComparisonMarkdown(comparison), { encoding: "utf8", mode: 0o600, flag: "wx" });
    await writeFile(htmlReportPath, renderRunrailReviewComparisonHtml(comparison), { encoding: "utf8", mode: 0o600, flag: "wx" });
  } catch (error) {
    await rm(outputRoot, { recursive: true, force: true }).catch(() => {});
    throw error;
  }
  return {
    ok: true,
    mode: "revision-review-comparison",
    comparisonId: comparison.comparisonId,
    outputRoot,
    comparisonPath,
    reviewPath,
    htmlReportPath,
    relationship: comparison.relationship.type,
    reviewPriority: comparison.reviewPriority,
    resolvedFindingCount: comparison.findings.resolved.length,
    addedFindingCount: comparison.findings.added.length,
    humanApprovalRequired: true,
    projectTestsExecuted: false,
    mergeReady: false,
    networkRequired: false,
    sourceApplyPerformed: false,
    comparison
  };
}

async function writeEvidenceContinuityArtifacts(records) {
  const lineage = buildRunrailEvidenceContinuity(records.map((record) => record.audit));
  const latestReviewRoot = path.dirname(records.at(-1).auditPath);
  const lineagesRoot = path.join(latestReviewRoot, "lineages");
  try {
    const existing = await lstat(lineagesRoot);
    if (!existing.isDirectory() || existing.isSymbolicLink()) {
      throw new LocalAuditRunnerError(
        "lineage-artifact-boundary",
        "The local evidence-continuity directory must be an ordinary Runrail-owned directory."
      );
    }
    const resolvedLineagesRoot = await realpath(lineagesRoot);
    if (!isInside(resolvedLineagesRoot, latestReviewRoot)) {
      throw new LocalAuditRunnerError(
        "lineage-artifact-boundary",
        "The local evidence-continuity directory escaped the latest review directory."
      );
    }
  } catch (error) {
    if (error instanceof LocalAuditRunnerError) throw error;
    if (error?.code !== "ENOENT") throw error;
    await mkdir(lineagesRoot, { mode: 0o700 });
  }

  const outputRoot = path.join(lineagesRoot, lineage.lineageId);
  try {
    await mkdir(outputRoot, { mode: 0o700 });
  } catch (error) {
    if (error?.code === "EEXIST") {
      throw new LocalAuditRunnerError(
        "lineage-artifact-exists",
        "This local evidence-continuity artifact already exists. Its files were not overwritten."
      );
    }
    throw error;
  }
  const lineagePath = path.join(outputRoot, "lineage.json");
  const reviewPath = path.join(outputRoot, "REVIEW_LINEAGE.md");
  const htmlReportPath = path.join(outputRoot, "lineage.html");
  try {
    await writeFile(lineagePath, stableRunrailEvidenceContinuityJson(lineage), {
      encoding: "utf8",
      mode: 0o600,
      flag: "wx"
    });
    await writeFile(reviewPath, renderRunrailEvidenceContinuityMarkdown(lineage), {
      encoding: "utf8",
      mode: 0o600,
      flag: "wx"
    });
    await writeFile(htmlReportPath, renderRunrailEvidenceContinuityHtml(lineage), {
      encoding: "utf8",
      mode: 0o600,
      flag: "wx"
    });
  } catch (error) {
    await rm(outputRoot, { recursive: true, force: true }).catch(() => {});
    throw error;
  }
  return {
    ok: true,
    mode: "evidence-continuity",
    lineageId: lineage.lineageId,
    outputRoot,
    lineagePath,
    reviewPath,
    htmlReportPath,
    entryCount: lineage.sequence.entryCount,
    reviewPriorityDirection: lineage.sequence.reviewPriorityDirection,
    policyBasisContinuous: lineage.sequence.policyBasisContinuous,
    activeFindingCount: lineage.findingLifecycle.summary.activeInLatestCount,
    absentFindingCount: lineage.findingLifecycle.summary.absentFromLatestCount,
    recurringFindingCount: lineage.findingLifecycle.summary.recurringFindingCount,
    humanApprovalRequired: true,
    projectTestsExecuted: false,
    mergeReady: false,
    networkRequired: false,
    sourceApplyPerformed: false,
    originAuthenticated: false,
    orderAuthenticated: false,
    lineage
  };
}

const jsonRequested = process.argv.includes("--json");

try {
  const args = parseArgs(process.argv.slice(2));
  if (args.help) {
    console.log(usage());
  } else if (args.command === "desktop") {
    const { startRunrailDesktop } = await import("./runrail-desktop-app.mjs");
    const desktop = await startRunrailDesktop({
      port: args.port,
      open: args.open,
      initialRepo: args.repo ? path.resolve(args.repo) : ""
    });
    const result = {
      ok: desktop.ok,
      product: desktop.product,
      mode: desktop.mode,
      origin: desktop.origin,
      url: desktop.url,
      host: desktop.host,
      port: desktop.port,
      offlineDefault: desktop.offlineDefault,
      repositoryUpload: desktop.repositoryUpload,
      sourceApplyAvailable: desktop.sourceApplyAvailable,
      projectTestsExecuted: desktop.projectTestsExecuted
    };
    if (args.json) console.log(JSON.stringify(result));
    else {
      console.log(`Runrail Desktop session URL: ${desktop.url}`);
      console.log("If the browser did not open, copy that private loopback URL into a browser on this machine.");
      console.log("Repository upload: disabled. Source apply: unavailable. Press Ctrl+C to stop.");
    }
    let shutdownStarted = false;
    const shutdownDesktop = () => {
      if (shutdownStarted) return;
      shutdownStarted = true;
      void desktop.close().catch(() => {});
    };
    process.once("SIGINT", shutdownDesktop);
    process.once("SIGTERM", shutdownDesktop);
    try {
      await desktop.closed;
    } finally {
      process.off("SIGINT", shutdownDesktop);
      process.off("SIGTERM", shutdownDesktop);
    }
  } else if (args.command === "doctor") {
    const result = await localAuditDoctor();
    if (args.json) console.log(JSON.stringify(result, null, 2));
    else {
      console.log(`Runrail doctor passed: ${result.engine.tag} (${result.engine.mode})`);
      console.log(`Reviewed-copy workspace: ${result.workspace.reviewedReposRoot}`);
    }
  } else if (args.command === "sample") {
    const { createRunrailGuidedSample } = await import("./runrail-guided-sample-core.mjs");
    const result = await createRunrailGuidedSample();
    if (args.json) console.log(JSON.stringify(result, null, 2));
    else {
      console.log(`Runrail guided sample ${result.ok ? "passed" : "needs attention"}: ${result.runId}`);
      console.log(`Sample repository: ${result.sampleRoot}`);
      console.log(`Audit report: ${result.reportPath}`);
      console.log("This sample stayed local and did not apply a patch or run project tests.");
    }
    if (!result.ok) process.exitCode = 1;
  } else if (args.command === "prepare") {
    const result = await prepareReviewedRepo(args.repo);
    if (args.json) console.log(JSON.stringify(result, null, 2));
    else console.log(`Reviewed copy prepared: ${result.reviewedRepo}`);
  } else if (args.command === "review") {
    const result = await reviewCandidateBranch({
      repo: args.repo,
      base: args.base,
      candidate: args.candidate,
      verifierProfile: args.verifier
    });
    if (args.json) console.log(JSON.stringify(result, null, 2));
    else {
      console.log(`Runrail candidate preflight ${result.ok ? "passed" : "failed"}: ${result.runId}`);
      console.log(`Candidate patch: ${result.patchPath}`);
      console.log(`Audit report: ${result.reportPath}`);
    }
    if (!result.ok) process.exitCode = 1;
  } else if (args.command === "focus") {
    const { audit, auditPath } = await loadOwnedCandidateAudit(args.auditFile, "focus");
    const result = await writeRunrailReviewFocusArtifacts({
      audit,
      reviewRoot: path.dirname(auditPath)
    });
    if (args.json) console.log(JSON.stringify(result, null, 2));
    else {
      console.log(`Runrail Review Focus ready: ${result.focusId}`);
      console.log(`Review priority: ${result.priority}`);
      console.log(`Ordered review plan: ${result.htmlReportPath}`);
      console.log("Authority: none. Human approval and project checks are still required.");
    }
  } else if (args.command === "coverage") {
    const { audit, auditPath } = await loadOwnedCandidateAudit(args.auditFile, "coverage");
    const patchText = await readOwnedCandidatePatch(auditPath);
    const attention = await loadHunkAttention(args.attentionFile);
    const previousCoverage = args.previousCoverageFile
      ? await loadOwnedCoverage(args.previousCoverageFile)
      : null;
    const result = await writeRunrailHunkContinuityArtifacts({
      audit,
      patchText,
      reviewRoot: path.dirname(auditPath),
      attention,
      previousCoverage
    });
    if (args.json) console.log(JSON.stringify(result, null, 2));
    else {
      console.log(`Runrail Review Coverage ready: ${result.coverageId}`);
      console.log(`Reviewed: ${result.reviewedCount}`);
      console.log(`Needs revision: ${result.needsRevisionCount}`);
      console.log(`Unreviewed: ${result.unreviewedCount}`);
      console.log(`Coverage report: ${result.htmlReportPath}`);
      console.log("Attention is not approval. Human approval and project tests are still required.");
    }
  } else if (args.command === "recheck") {
    const beforeRecord = await loadOwnedCandidateAudit(
      args.beforeAuditFile,
      "delta"
    );
    const afterRecord = await loadOwnedCandidateAudit(
      args.afterAuditFile,
      "delta"
    );
    const previousCoverage = await loadOwnedCoverage(
      args.previousCoverageFile
    );
    const result = await writeRunrailReviewDeltaBundle({
      beforeAudit: beforeRecord.audit,
      afterAudit: afterRecord.audit,
      currentPatchText: await readOwnedCandidatePatch(afterRecord.auditPath),
      previousCoverage,
      reviewRoot: path.dirname(afterRecord.auditPath)
    });
    if (args.json) console.log(JSON.stringify(result, null, 2));
    else {
      console.log(`Runrail Re-review Map ready: ${result.deltaId}`);
      console.log(
        `Exact hunk attention carried: ${result.carriedForwardCount}`
      );
      console.log(
        `Current hunks requiring attention: ${result.currentAttentionRequiredCount}`
      );
      console.log(`Re-review report: ${result.htmlReportPath}`);
      console.log(
        "Continuity is not approval. Human approval and project tests are still required."
      );
    }
  } else if (args.command === "compare") {
    const beforeRecord = await loadOwnedCandidateAudit(args.beforeAuditFile, "comparison");
    const afterRecord = await loadOwnedCandidateAudit(args.afterAuditFile, "comparison");
    const result = await writeComparisonArtifacts(beforeRecord, afterRecord);
    if (args.json) console.log(JSON.stringify(result, null, 2));
    else {
      console.log(`Runrail revision comparison saved: ${result.comparisonId}`);
      console.log(`Review priority: ${result.reviewPriority.before} -> ${result.reviewPriority.after} (${result.reviewPriority.direction})`);
      console.log(`Comparison report: ${result.htmlReportPath}`);
      console.log("Human approval and project tests are still required.");
    }
  } else if (args.command === "lineage") {
    const records = [];
    for (const auditFile of args.auditFiles) {
      records.push(await loadOwnedCandidateAudit(auditFile, "lineage"));
    }
    const result = await writeEvidenceContinuityArtifacts(records);
    if (args.json) console.log(JSON.stringify(result, null, 2));
    else {
      console.log(`Runrail Evidence Continuity saved: ${result.lineageId}`);
      console.log(`Declared reviews: ${result.entryCount}`);
      console.log(`Review priority: ${result.reviewPriorityDirection}`);
      console.log(`Evidence report: ${result.htmlReportPath}`);
      console.log("Origin, time, and order are not authenticated. Human approval and project checks remain required.");
    }
  } else if (args.command === "handoff") {
    const { audit, auditPath } = await loadOwnedCandidateAudit(
      args.auditFile,
      "assurance"
    );
    const result = await writeRunrailAgentAssurancePacket({
      audit,
      reviewRoot: path.dirname(auditPath)
    });
    if (args.json) console.log(JSON.stringify(result, null, 2));
    else {
      console.log(`Runrail Agent Assurance packet ready: ${result.packet.packetId}`);
      console.log(`Correction brief: ${result.briefPath}`);
      console.log("Give the source-free brief to any coding agent, then rerun Runrail against the revised candidate.");
      console.log("Authority: none. Runrail did not execute tests, apply code, or approve a merge.");
    }
  } else if (args.command === "assure") {
    const beforeRecord = await loadOwnedCandidateAudit(
      args.beforeAuditFile,
      "assurance"
    );
    const afterRecord = await loadOwnedCandidateAudit(
      args.afterAuditFile,
      "assurance"
    );
    const packet = await loadRunrailAgentAssurancePacket(args.packetFile);
    const afterCoverage = args.coverageFile
      ? await loadOwnedCoverage(args.coverageFile)
      : null;
    const result = await writeRunrailAgentAssuranceResult({
      packet,
      beforeAudit: beforeRecord.audit,
      afterAudit: afterRecord.audit,
      afterCoverage,
      reviewRoot: path.dirname(afterRecord.auditPath)
    });
    if (args.json) console.log(JSON.stringify(result, null, 2));
    else {
      console.log(`Runrail Agent Assurance result: ${result.result.status}`);
      console.log(`Resolved: ${result.result.summary.resolvedCount}`);
      console.log(`Remaining: ${result.result.summary.remainingCount}`);
      console.log(`New: ${result.result.summary.newCount}`);
      console.log(`Reintroduced: ${result.result.summary.reintroducedCount}`);
      console.log(`Assurance report: ${result.reviewPath}`);
      console.log("Human approval and project tests are still required.");
    }
  } else if (args.command === "recommend" || args.command === "advise") {
    const { audit, auditPath } = await loadOwnedCandidateAudit(args.auditFile);
    const advisoryFile = args.provider === "deepseek"
      ? "candidate-advisory-deepseek.json"
      : "candidate-advisory.json";
    const advisoryPath = path.join(path.dirname(auditPath), advisoryFile);
    await assertAdvisoryArtifactAvailable(advisoryPath, advisoryFile);
    const { runRunrailCandidateAdvisory } = await import("./runrail-candidate-advisory-core.mjs");
    const artifact = await runRunrailCandidateAdvisory({
      audit,
      provider: args.provider,
      allowNetwork: args.allowNetwork
    });
    try {
      await writeFile(advisoryPath, `${JSON.stringify(artifact, null, 2)}\n`, {
        encoding: "utf8",
        mode: 0o600,
        flag: "wx"
      });
    } catch (error) {
      if (error?.code === "EEXIST") {
        throw new LocalAuditRunnerError(
          "advisory-artifact-exists",
          `Remove the existing local ${advisoryFile} before requesting the same advisory again.`
        );
      }
      throw error;
    }
    const result = {
      ok: true,
      mode: `${args.provider}-candidate-advisory`,
      advisoryPath,
      advisoryOnly: true,
      authority: "none",
      provider: artifact.provider,
      model: artifact.model,
      candidateIds: artifact.candidateIds,
      candidates: artifact.candidates,
      abstained: artifact.abstained,
      confidence: artifact.confidence,
      sourceChecksumSha256: artifact.sourceChecksumSha256,
      transmittedFields: artifact.transmittedFields,
      redactions: artifact.redactions
    };
    if (args.json) console.log(JSON.stringify(result, null, 2));
    else {
      console.log(`Runrail candidate advisory saved: ${advisoryPath}`);
      console.log(`Candidate IDs: ${artifact.candidateIds.join(", ")}`);
      console.log("Authority: none. A human must decide the next action.");
    }
  } else {
    let requestPacket = null;
    if (args.request) {
      try {
        requestPacket = JSON.parse(await readFile(args.request, "utf8"));
      } catch {
        throw new LocalAuditRunnerError("request-file-invalid", "The local audit request file must contain valid JSON.");
      }
    }
    const result = await runLocalAudit({ repo: args.repo, task: args.task, requestPacket });
    if (args.json) console.log(JSON.stringify(result, null, 2));
    else {
      console.log(`Runrail local audit passed: ${result.runId}`);
      console.log(`Local proposal: ${result.localProposal.proposalPath}`);
      console.log(`Sanitized export: ${result.exportDir}`);
    }
  }
} catch (error) {
  const code = error instanceof LocalAuditRunnerError || typeof error?.code === "string" ? error.code : "local-audit-failed";
  if (jsonRequested) {
    process.stderr.write(`${JSON.stringify({
      ok: false,
      code,
      message: String(error?.message || "Runrail failed."),
      authority: "none"
    })}\n`);
  } else {
    console.error(`Runrail failed [${code}]: ${error.message}`);
  }
  process.exitCode = 1;
}
