import { createHash } from "node:crypto";
import {
  lstat,
  mkdir,
  readFile,
  readdir,
  realpath,
  rm,
  writeFile
} from "node:fs/promises";
import path from "node:path";
import { verifyRunrailCandidateAudit } from "./runrail-deepseek-advisory-core.mjs";
import {
  compareRunrailReviewAudits
} from "./runrail-review-comparison-core.mjs";
import {
  buildRunrailHunkContinuity,
  verifyRunrailHunkContinuity,
  writeRunrailHunkContinuityArtifacts
} from "./runrail-hunk-continuity-core.mjs";
import { LocalAuditRunnerError } from "./veyact-local-audit-runner-core.mjs";

export const RUNRAIL_REVIEW_DELTA = Object.freeze({
  schemaVersion: 1,
  artifactType: "runrail-review-delta",
  profile: "runrail-review-delta-v1",
  product: "Runrail Local v1"
});

const SHA256_PATTERN = /^[a-f0-9]{64}$/;
const DELTA_ID_PATTERN = /^RRD-[A-F0-9]{24}$/;
const allowedRelationshipTypes = new Set(["same-base", "linear-successor"]);
const allowedDirections = new Set([
  "decreased",
  "increased",
  "changed",
  "unchanged",
  "policy-basis-changed"
]);
const allowedRiskLevels = new Set(["low", "medium", "high"]);
const allowedActionIds = new Set([
  "RECONFIRM_POLICY_BASIS",
  "RESOLVE_PREFLIGHT_BLOCKERS",
  "INSPECT_CURRENT_ATTENTION",
  "REVISIT_NEEDS_REVISION",
  "REVIEW_FINDING_DELTAS",
  "COLLECT_REQUIRED_EVIDENCE",
  "RUN_PROJECT_TESTS",
  "HUMAN_MERGE_DECISION"
]);

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

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 exactObject(value, keys, label) {
  if (!value || typeof value !== "object" || Array.isArray(value)) {
    fail("review-delta-schema-invalid", `${label} must be an object.`);
  }
  const actual = Object.keys(value).sort();
  const expected = [...keys].sort();
  if (
    actual.length !== expected.length ||
    actual.some((key, index) => key !== expected[index])
  ) {
    fail(
      "review-delta-schema-invalid",
      `${label} contains missing or unsupported fields.`
    );
  }
}

function nonNegativeInteger(value) {
  return Number.isSafeInteger(value) && value >= 0;
}

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

function assertReviewDeltaAudit(audit, label) {
  verifyRunrailCandidateAudit(audit);
  if (
    audit.schemaVersion !== 4 ||
    !audit.reviewContract ||
    typeof audit.reviewContract.contractSha256 !== "string" ||
    !Array.isArray(audit.reviewContract.requiredReviewLanes) ||
    !Array.isArray(audit.reviewContract.requiredEvidence)
  ) {
    fail(
      "review-delta-audit-invalid",
      `${label} must be a verified Runrail schema-v4 review with a baseline-owned review contract.`
    );
  }
}

function action(id, label, reason) {
  return { id, label, reason };
}

function buildNextActions({
  comparablePolicyBasis,
  preflightPassed,
  currentAttentionRequiredCount,
  needsRevisionCount,
  findingDeltaCount
}) {
  const actions = [];
  if (!comparablePolicyBasis) {
    actions.push(
      action(
        "RECONFIRM_POLICY_BASIS",
        "Reconfirm the review policy basis",
        "The baseline review contract changed, so the earlier and current priority levels are not directly comparable."
      )
    );
  }
  if (!preflightPassed) {
    actions.push(
      action(
        "RESOLVE_PREFLIGHT_BLOCKERS",
        "Resolve deterministic preflight blockers",
        "The current candidate did not pass the bounded Runrail preflight."
      )
    );
  }
  if (currentAttentionRequiredCount > 0) {
    actions.push(
      action(
        "INSPECT_CURRENT_ATTENTION",
        "Inspect hunks requiring current attention",
        `${currentAttentionRequiredCount} current hunk${currentAttentionRequiredCount === 1 ? "" : "s"} could not inherit an exact prior attention state.`
      )
    );
  }
  if (needsRevisionCount > 0) {
    actions.push(
      action(
        "REVISIT_NEEDS_REVISION",
        "Revisit carried needs-revision hunks",
        `${needsRevisionCount} current hunk${needsRevisionCount === 1 ? "" : "s"} remain marked needs revision.`
      )
    );
  }
  if (findingDeltaCount > 0) {
    actions.push(
      action(
        "REVIEW_FINDING_DELTAS",
        "Review changed deterministic findings",
        `${findingDeltaCount} deterministic finding change${findingDeltaCount === 1 ? "" : "s"} require review.`
      )
    );
  }
  actions.push(
    action(
      "COLLECT_REQUIRED_EVIDENCE",
      "Collect required review evidence",
      "The current baseline-owned review contract still defines evidence that a human must inspect."
    ),
    action(
      "RUN_PROJECT_TESTS",
      "Run approved project checks",
      "Runrail did not execute project tests or determine semantic correctness."
    ),
    action(
      "HUMAN_MERGE_DECISION",
      "Make the human merge decision",
      "Attention continuity and deterministic findings are evidence, not approval."
    )
  );
  return actions.map((entry, index) => ({ rank: index + 1, ...entry }));
}

export function buildRunrailReviewDelta({
  beforeAudit,
  afterAudit,
  previousCoverage,
  currentCoverage
}) {
  assertReviewDeltaAudit(beforeAudit, "The prior audit");
  assertReviewDeltaAudit(afterAudit, "The current audit");
  verifyRunrailHunkContinuity(previousCoverage);
  verifyRunrailHunkContinuity(currentCoverage);
  if (previousCoverage.source.auditChecksumSha256 !== beforeAudit.checksumSha256) {
    fail(
      "review-delta-previous-coverage-mismatch",
      "The prior Review Coverage artifact must belong to the prior audit."
    );
  }
  if (currentCoverage.source.auditChecksumSha256 !== afterAudit.checksumSha256) {
    fail(
      "review-delta-current-coverage-mismatch",
      "The current Review Coverage artifact must belong to the current audit."
    );
  }
  if (
    currentCoverage.provenance.previousCoverageChecksumSha256 !==
      previousCoverage.checksumSha256
  ) {
    fail(
      "review-delta-continuity-mismatch",
      "The current Review Coverage must be rebuilt directly from the supplied prior coverage."
    );
  }

  const comparison = compareRunrailReviewAudits(beforeAudit, afterAudit);
  const currentAttentionRequiredCount =
    currentCoverage.summary.hunkCount -
    currentCoverage.summary.carriedForwardCount;
  const findingDeltaCount =
    comparison.findings.added.length +
    comparison.findings.resolved.length +
    comparison.findings.changed.length;
  const comparablePolicyBasis =
    comparison.reviewContractDelta.comparablePolicyBasis;
  const identity = {
    source: {
      beforeAuditChecksumSha256: beforeAudit.checksumSha256,
      afterAuditChecksumSha256: afterAudit.checksumSha256,
      previousCoverageChecksumSha256: previousCoverage.checksumSha256,
      currentCoverageChecksumSha256: currentCoverage.checksumSha256,
      comparisonId: comparison.comparisonId
    },
    relationship: {
      type: comparison.relationship.type,
      originAuthenticated: false
    },
    policyBasis: {
      comparable: comparablePolicyBasis,
      beforeSha256: comparison.reviewContractDelta.beforeSha256,
      afterSha256: comparison.reviewContractDelta.afterSha256,
      reviewPriorityBefore: comparison.reviewPriority.before,
      reviewPriorityAfter: comparison.reviewPriority.after,
      direction: comparison.reviewPriority.direction
    },
    findings: {
      addedCount: comparison.findings.added.length,
      resolvedCount: comparison.findings.resolved.length,
      changedCount: comparison.findings.changed.length,
      unchangedCount: comparison.findings.unchanged.length
    },
    attention: {
      hunkCount: currentCoverage.summary.hunkCount,
      carriedForwardCount: currentCoverage.summary.carriedForwardCount,
      currentAttentionRequiredCount,
      reviewedCount: currentCoverage.summary.reviewedCount,
      needsRevisionCount: currentCoverage.summary.needsRevisionCount,
      unreviewedCount: currentCoverage.summary.unreviewedCount,
      attentionComplete: currentCoverage.summary.attentionComplete
    },
    obligations: {
      preflightPassed: afterAudit.preflightPassed === true,
      requiredReviewLaneCount:
        afterAudit.reviewContract.requiredReviewLanes.length,
      requiredEvidenceCount: afterAudit.reviewContract.requiredEvidence.length,
      projectTestsRequired: true,
      humanApprovalRequired: true,
      mergeReady: false
    }
  };
  const nextActions = buildNextActions({
    comparablePolicyBasis,
    preflightPassed: identity.obligations.preflightPassed,
    currentAttentionRequiredCount,
    needsRevisionCount: identity.attention.needsRevisionCount,
    findingDeltaCount
  });
  const deltaIdentitySha256 = sha256(
    stableJson({ ...identity, nextActions })
  );
  const body = {
    ...RUNRAIL_REVIEW_DELTA,
    deltaId: `RRD-${deltaIdentitySha256.slice(0, 24).toUpperCase()}`,
    ...identity,
    nextActions,
    boundaries: {
      pathFree: true,
      authority: "none",
      humanAttentionNotApproval: true,
      projectTestsExecuted: false,
      networkUsed: false,
      repositoryOpened: false,
      sourceMutation: false,
      automaticSourceApplyEnabled: false,
      originAuthenticated: false,
      learnedRuntimeAuthorityAdded: false
    }
  };
  return Object.freeze({
    ...body,
    checksumSha256: sha256(stableJson(body))
  });
}

export function verifyRunrailReviewDelta(
  delta,
  {
    beforeAudit = null,
    afterAudit = null,
    previousCoverage = null,
    currentCoverage = null
  } = {}
) {
  exactObject(
    delta,
    [
      "schemaVersion",
      "artifactType",
      "profile",
      "product",
      "deltaId",
      "source",
      "relationship",
      "policyBasis",
      "findings",
      "attention",
      "obligations",
      "nextActions",
      "boundaries",
      "checksumSha256"
    ],
    "Review Delta artifact"
  );
  if (
    delta.schemaVersion !== RUNRAIL_REVIEW_DELTA.schemaVersion ||
    delta.artifactType !== RUNRAIL_REVIEW_DELTA.artifactType ||
    delta.profile !== RUNRAIL_REVIEW_DELTA.profile ||
    delta.product !== RUNRAIL_REVIEW_DELTA.product ||
    !DELTA_ID_PATTERN.test(String(delta.deltaId || ""))
  ) {
    fail("review-delta-invalid", "The Review Delta identity is invalid.");
  }
  exactObject(
    delta.source,
    [
      "beforeAuditChecksumSha256",
      "afterAuditChecksumSha256",
      "previousCoverageChecksumSha256",
      "currentCoverageChecksumSha256",
      "comparisonId"
    ],
    "Review Delta source"
  );
  exactObject(
    delta.relationship,
    ["type", "originAuthenticated"],
    "Review Delta relationship"
  );
  exactObject(
    delta.policyBasis,
    [
      "comparable",
      "beforeSha256",
      "afterSha256",
      "reviewPriorityBefore",
      "reviewPriorityAfter",
      "direction"
    ],
    "Review Delta policy basis"
  );
  exactObject(
    delta.findings,
    ["addedCount", "resolvedCount", "changedCount", "unchangedCount"],
    "Review Delta findings"
  );
  exactObject(
    delta.attention,
    [
      "hunkCount",
      "carriedForwardCount",
      "currentAttentionRequiredCount",
      "reviewedCount",
      "needsRevisionCount",
      "unreviewedCount",
      "attentionComplete"
    ],
    "Review Delta attention"
  );
  exactObject(
    delta.obligations,
    [
      "preflightPassed",
      "requiredReviewLaneCount",
      "requiredEvidenceCount",
      "projectTestsRequired",
      "humanApprovalRequired",
      "mergeReady"
    ],
    "Review Delta obligations"
  );
  exactObject(
    delta.boundaries,
    [
      "pathFree",
      "authority",
      "humanAttentionNotApproval",
      "projectTestsExecuted",
      "networkUsed",
      "repositoryOpened",
      "sourceMutation",
      "automaticSourceApplyEnabled",
      "originAuthenticated",
      "learnedRuntimeAuthorityAdded"
    ],
    "Review Delta boundaries"
  );

  if (
    ![
      delta.source.beforeAuditChecksumSha256,
      delta.source.afterAuditChecksumSha256,
      delta.source.previousCoverageChecksumSha256,
      delta.source.currentCoverageChecksumSha256,
      delta.policyBasis.beforeSha256,
      delta.policyBasis.afterSha256
    ].every((value) => SHA256_PATTERN.test(String(value || ""))) ||
    !/^RRC-[A-F0-9]{12}-[A-F0-9]{12}$/.test(
      String(delta.source.comparisonId || "")
    ) ||
    !allowedRelationshipTypes.has(delta.relationship.type) ||
    delta.relationship.originAuthenticated !== false ||
    typeof delta.policyBasis.comparable !== "boolean" ||
    !allowedRiskLevels.has(delta.policyBasis.reviewPriorityBefore) ||
    !allowedRiskLevels.has(delta.policyBasis.reviewPriorityAfter) ||
    !allowedDirections.has(delta.policyBasis.direction) ||
    (
      delta.policyBasis.comparable &&
      delta.policyBasis.direction === "policy-basis-changed"
    ) ||
    (
      !delta.policyBasis.comparable &&
      delta.policyBasis.direction !== "policy-basis-changed"
    )
  ) {
    fail(
      "review-delta-invalid",
      "The Review Delta source, relationship, or policy basis is invalid."
    );
  }
  if (
    !Object.values(delta.findings).every(nonNegativeInteger) ||
    ![
      "hunkCount",
      "carriedForwardCount",
      "currentAttentionRequiredCount",
      "reviewedCount",
      "needsRevisionCount",
      "unreviewedCount"
    ].every((key) => nonNegativeInteger(delta.attention[key])) ||
    ![
      "requiredReviewLaneCount",
      "requiredEvidenceCount"
    ].every((key) => nonNegativeInteger(delta.obligations[key])) ||
    typeof delta.attention.attentionComplete !== "boolean" ||
    typeof delta.obligations.preflightPassed !== "boolean" ||
    delta.attention.hunkCount !==
      delta.attention.carriedForwardCount +
        delta.attention.currentAttentionRequiredCount ||
    delta.attention.hunkCount !==
      delta.attention.reviewedCount +
        delta.attention.needsRevisionCount +
        delta.attention.unreviewedCount ||
    delta.attention.attentionComplete !==
      (
        delta.attention.hunkCount > 0 &&
        delta.attention.unreviewedCount === 0
      ) ||
    delta.obligations.projectTestsRequired !== true ||
    delta.obligations.humanApprovalRequired !== true ||
    delta.obligations.mergeReady !== false
  ) {
    fail(
      "review-delta-invalid",
      "The Review Delta counts or obligations are inconsistent."
    );
  }

  if (
    !Array.isArray(delta.nextActions) ||
    delta.nextActions.length < 3 ||
    delta.nextActions.length > allowedActionIds.size
  ) {
    fail(
      "review-delta-action-invalid",
      "Review Delta actions must contain a bounded deterministic review sequence."
    );
  }
  const actionIds = new Set();
  for (const [index, entry] of delta.nextActions.entries()) {
    exactObject(
      entry,
      ["rank", "id", "label", "reason"],
      "Review Delta action"
    );
    if (
      entry.rank !== index + 1 ||
      !allowedActionIds.has(entry.id) ||
      actionIds.has(entry.id) ||
      typeof entry.label !== "string" ||
      entry.label.length < 3 ||
      entry.label.length > 120 ||
      typeof entry.reason !== "string" ||
      entry.reason.length < 3 ||
      entry.reason.length > 320
    ) {
      fail(
        "review-delta-action-invalid",
        "A Review Delta action is invalid or out of order."
      );
    }
    actionIds.add(entry.id);
  }
  if (delta.nextActions.at(-1).id !== "HUMAN_MERGE_DECISION") {
    fail(
      "review-delta-action-invalid",
      "The human merge decision must remain the final Review Delta action."
    );
  }
  const expectedActions = buildNextActions({
    comparablePolicyBasis: delta.policyBasis.comparable,
    preflightPassed: delta.obligations.preflightPassed,
    currentAttentionRequiredCount:
      delta.attention.currentAttentionRequiredCount,
    needsRevisionCount: delta.attention.needsRevisionCount,
    findingDeltaCount:
      delta.findings.addedCount +
      delta.findings.resolvedCount +
      delta.findings.changedCount
  });
  if (stableJson(expectedActions) !== stableJson(delta.nextActions)) {
    fail(
      "review-delta-action-invalid",
      "Review Delta actions do not match the deterministic evidence."
    );
  }
  if (
    delta.boundaries.pathFree !== true ||
    delta.boundaries.authority !== "none" ||
    delta.boundaries.humanAttentionNotApproval !== true ||
    delta.boundaries.projectTestsExecuted !== false ||
    delta.boundaries.networkUsed !== false ||
    delta.boundaries.repositoryOpened !== false ||
    delta.boundaries.sourceMutation !== false ||
    delta.boundaries.automaticSourceApplyEnabled !== false ||
    delta.boundaries.originAuthenticated !== false ||
    delta.boundaries.learnedRuntimeAuthorityAdded !== false
  ) {
    fail(
      "review-delta-authority",
      "Review Delta expanded its local evidence boundary."
    );
  }
  const { checksumSha256, ...body } = delta;
  if (
    !SHA256_PATTERN.test(String(checksumSha256 || "")) ||
    sha256(stableJson(body)) !== checksumSha256
  ) {
    fail(
      "review-delta-checksum",
      "The Review Delta checksum is invalid."
    );
  }
  const linkedInputs = [
    beforeAudit,
    afterAudit,
    previousCoverage,
    currentCoverage
  ];
  if (linkedInputs.some(Boolean) && !linkedInputs.every(Boolean)) {
    fail(
      "review-delta-source-incomplete",
      "Review Delta source verification requires both audits and both coverage artifacts."
    );
  }
  if (linkedInputs.every(Boolean)) {
    const rebuilt = buildRunrailReviewDelta({
      beforeAudit,
      afterAudit,
      previousCoverage,
      currentCoverage
    });
    if (stableJson(rebuilt) !== stableJson(delta)) {
      fail(
        "review-delta-source-mismatch",
        "The Review Delta does not match its verified source artifacts."
      );
    }
  }
  return delta;
}

export function stableRunrailReviewDeltaJson(delta) {
  verifyRunrailReviewDelta(delta);
  return stableJson(delta);
}

export function renderRunrailReviewDeltaMarkdown(delta) {
  verifyRunrailReviewDelta(delta);
  const actions = delta.nextActions
    .map(
      (entry) =>
        `${entry.rank}. **${entry.label}:** ${entry.reason}`
    )
    .join("\n");
  return `# Runrail Re-review Map

Delta ID: \`${delta.deltaId}\`

Relationship: ${delta.relationship.type}

Comparable review-contract basis: ${delta.policyBasis.comparable ? "yes" : "no"}

Review priority: ${delta.policyBasis.reviewPriorityBefore} to ${delta.policyBasis.reviewPriorityAfter} (${delta.policyBasis.direction})

## Finding delta

- Added: ${delta.findings.addedCount}
- Resolved: ${delta.findings.resolvedCount}
- Changed: ${delta.findings.changedCount}
- Unchanged: ${delta.findings.unchangedCount}

## Attention continuity

- Current hunks: ${delta.attention.hunkCount}
- Carried exactly: ${delta.attention.carriedForwardCount}
- Current attention required: ${delta.attention.currentAttentionRequiredCount}
- Reviewed: ${delta.attention.reviewedCount}
- Needs revision: ${delta.attention.needsRevisionCount}
- Unreviewed: ${delta.attention.unreviewedCount}

## Ordered re-review map

${actions}

## Decision boundary

This path-free artifact binds two verified local reviews to exact-hunk attention continuity. It does not authenticate origin, open a repository, execute project tests, determine semantic correctness, perform a security review, call a provider, mutate source, apply a patch, or approve a merge. Human approval and approved project checks remain required.

Checksum: \`${delta.checksumSha256}\`
`;
}

function escapeHtml(value) {
  return String(value)
    .replaceAll("&", "&amp;")
    .replaceAll("<", "&lt;")
    .replaceAll(">", "&gt;")
    .replaceAll('"', "&quot;")
    .replaceAll("'", "&#39;");
}

export function renderRunrailReviewDeltaHtml(delta) {
  verifyRunrailReviewDelta(delta);
  const actions = delta.nextActions
    .map(
      (entry) =>
        `<li><span>${entry.rank}</span><div><strong>${escapeHtml(entry.label)}</strong><p>${escapeHtml(entry.reason)}</p></div></li>`
    )
    .join("");
  return `<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width,initial-scale=1">
  <meta http-equiv="Content-Security-Policy" content="default-src 'none'; style-src 'unsafe-inline'; img-src 'none'; object-src 'none'; base-uri 'none'; form-action 'none'; frame-ancestors 'none'">
  <title>Runrail Re-review Map</title>
  <style>
    :root{color-scheme:light;--ink:#15201c;--muted:#64706a;--line:#d8ded8;--paper:#fff;--wash:#f3f5f1;--green:#17664f;--amber:#8a5b1e}*{box-sizing:border-box}body{margin:0;background:var(--wash);color:var(--ink);font:15px/1.55 ui-sans-serif,system-ui,-apple-system,BlinkMacSystemFont,"Segoe UI",sans-serif}main{width:min(1040px,calc(100% - 32px));margin:0 auto;padding:42px 0 68px}.eyebrow{margin:0;color:var(--green);font-size:11px;font-weight:900;text-transform:uppercase}h1{margin:6px 0 8px;font-size:clamp(34px,5vw,56px);line-height:1.02}p{margin:0;color:var(--muted)}.metrics{display:grid;grid-template-columns:repeat(4,minmax(0,1fr));margin:30px 0;border:1px solid var(--line);background:var(--paper)}.metrics div{padding:18px;border-right:1px solid var(--line)}.metrics div:last-child{border:0}.metrics span{display:block;color:var(--muted);font-size:11px}.metrics strong{display:block;margin-top:5px;font-size:23px}.plan{display:grid;grid-template-columns:minmax(0,1fr) minmax(250px,.55fr);gap:32px}.plan ol{margin:0;padding:0;list-style:none;border-top:1px solid var(--line)}.plan li{display:grid;grid-template-columns:32px minmax(0,1fr);gap:13px;padding:15px 0;border-bottom:1px solid var(--line)}.plan li>span{display:grid;width:27px;height:27px;place-items:center;border:1px solid var(--line);color:var(--green);font-weight:800}.plan strong{display:block}.plan p{margin-top:3px;font-size:12px}.boundary{align-self:start;padding:22px;border:1px solid var(--line);background:var(--paper)}.boundary h2{margin:5px 0 8px;font-size:19px}.boundary dl{margin:18px 0 0}.boundary dl div{display:flex;justify-content:space-between;gap:14px;padding:8px 0;border-top:1px solid var(--line)}.checksum{margin-top:28px;font:10px/1.5 ui-monospace,SFMono-Regular,Consolas,monospace;overflow-wrap:anywhere}@media(max-width:720px){.metrics{grid-template-columns:1fr 1fr}.metrics div:nth-child(2){border-right:0}.metrics div:nth-child(-n+2){border-bottom:1px solid var(--line)}.plan{grid-template-columns:1fr}}
  </style>
</head>
<body>
<main>
  <p class="eyebrow">Runrail deterministic revision workspace</p>
  <h1>Review only what changed.</h1>
  <p>${escapeHtml(delta.deltaId)} · ${escapeHtml(delta.relationship.type)} · authority none</p>
  <section class="metrics"><div><span>Carried exactly</span><strong>${delta.attention.carriedForwardCount}</strong></div><div><span>Current attention</span><strong>${delta.attention.currentAttentionRequiredCount}</strong></div><div><span>Added findings</span><strong>${delta.findings.addedCount}</strong></div><div><span>Resolved findings</span><strong>${delta.findings.resolvedCount}</strong></div></section>
  <div class="plan">
    <section><p class="eyebrow">Ordered re-review map</p><ol>${actions}</ol></section>
    <section class="boundary"><p class="eyebrow">Decision boundary</p><h2>Continuity is not approval.</h2><p>${delta.policyBasis.comparable ? "The baseline review-contract basis remains comparable." : "The review-contract basis changed and must be reconfirmed."} Runrail did not open a repository, execute project tests, call a provider, mutate source, authenticate origin, or approve a merge.</p><dl><div><dt>Project tests</dt><dd>Not run</dd></div><div><dt>Source apply</dt><dd>Disabled</dd></div><div><dt>Merge ready</dt><dd>No</dd></div><div><dt>Human approval</dt><dd>Required</dd></div></dl></section>
  </div>
  <p class="checksum">Review Delta checksum: ${escapeHtml(delta.checksumSha256)}</p>
</main>
</body>
</html>
`;
}

async function resolveOrdinaryReviewRoot(reviewRoot) {
  let before;
  let canonicalReviewRoot;
  let after;
  try {
    before = await lstat(reviewRoot);
    if (!before.isDirectory() || before.isSymbolicLink()) {
      fail(
        "review-delta-artifact-boundary",
        "The Review Delta parent must be an ordinary Runrail-owned review directory."
      );
    }
    canonicalReviewRoot = await realpath(reviewRoot);
    after = await lstat(reviewRoot);
  } catch (error) {
    if (error instanceof LocalAuditRunnerError) throw error;
    fail(
      "review-delta-artifact-boundary",
      "The Review Delta parent is missing or no longer accessible."
    );
  }
  if (
    !after.isDirectory() ||
    after.isSymbolicLink() ||
    String(before.dev) !== String(after.dev) ||
    String(before.ino) !== String(after.ino)
  ) {
    fail(
      "review-delta-artifact-boundary",
      "The Review Delta parent changed while its artifact boundary was being verified."
    );
  }
  return canonicalReviewRoot;
}

async function ensureDeltaRoot(canonicalReviewRoot) {
  const deltasRoot = path.join(canonicalReviewRoot, "deltas");
  try {
    const existing = await lstat(deltasRoot);
    if (!existing.isDirectory() || existing.isSymbolicLink()) {
      fail(
        "review-delta-artifact-boundary",
        "The Review Delta root must be an ordinary Runrail-owned directory."
      );
    }
    if (!isInside(await realpath(deltasRoot), canonicalReviewRoot)) {
      fail(
        "review-delta-artifact-boundary",
        "The Review Delta root escaped its Runrail review directory."
      );
    }
  } catch (error) {
    if (error instanceof LocalAuditRunnerError) throw error;
    if (error?.code !== "ENOENT") throw error;
    await mkdir(deltasRoot, { mode: 0o700 });
  }
  return deltasRoot;
}

async function verifyStoredDelta({
  delta,
  outputRoot,
  beforeAudit,
  afterAudit,
  previousCoverage,
  currentCoverage
}) {
  const entries = (await readdir(outputRoot)).sort();
  if (entries.join(",") !== "REVIEW_DELTA.md,delta.html,delta.json") {
    fail(
      "review-delta-artifact-mismatch",
      "The Review Delta output contains an invalid file set."
    );
  }
  const deltaPath = path.join(outputRoot, "delta.json");
  const reviewPath = path.join(outputRoot, "REVIEW_DELTA.md");
  const htmlReportPath = path.join(outputRoot, "delta.html");
  for (const artifactPath of [deltaPath, reviewPath, htmlReportPath]) {
    const entry = await lstat(artifactPath);
    if (!entry.isFile() || entry.isSymbolicLink()) {
      fail(
        "review-delta-artifact-boundary",
        "Review Delta artifacts must be ordinary Runrail-owned files."
      );
    }
  }
  const stored = JSON.parse(await readFile(deltaPath, "utf8"));
  verifyRunrailReviewDelta(stored, {
    beforeAudit,
    afterAudit,
    previousCoverage,
    currentCoverage
  });
  if (
    stableRunrailReviewDeltaJson(stored) !==
      stableRunrailReviewDeltaJson(delta) ||
    (await readFile(reviewPath, "utf8")) !==
      renderRunrailReviewDeltaMarkdown(delta) ||
    (await readFile(htmlReportPath, "utf8")) !==
      renderRunrailReviewDeltaHtml(delta)
  ) {
    fail(
      "review-delta-artifact-mismatch",
      "Stored Review Delta artifacts do not match their deterministic rebuild."
    );
  }
  return { deltaPath, reviewPath, htmlReportPath };
}

export async function writeRunrailReviewDeltaBundle({
  beforeAudit,
  afterAudit,
  currentPatchText,
  previousCoverage,
  reviewRoot
}) {
  assertReviewDeltaAudit(beforeAudit, "The prior audit");
  assertReviewDeltaAudit(afterAudit, "The current audit");
  verifyRunrailHunkContinuity(previousCoverage);
  if (previousCoverage.source.auditChecksumSha256 !== beforeAudit.checksumSha256) {
    fail(
      "review-delta-previous-coverage-mismatch",
      "The prior Review Coverage artifact must belong to the prior audit."
    );
  }
  const currentCoverage = buildRunrailHunkContinuity({
    audit: afterAudit,
    patchText: currentPatchText,
    previousCoverage
  });
  const delta = buildRunrailReviewDelta({
    beforeAudit,
    afterAudit,
    previousCoverage,
    currentCoverage
  });
  const canonicalReviewRoot = await resolveOrdinaryReviewRoot(reviewRoot);
  const deltasRoot = await ensureDeltaRoot(canonicalReviewRoot);
  const outputRoot = path.join(deltasRoot, delta.deltaId);
  const expectedCoverageRoot = path.join(
    canonicalReviewRoot,
    "coverage",
    currentCoverage.coverageId
  );
  let coverageExistedBefore = false;
  try {
    await lstat(expectedCoverageRoot);
    coverageExistedBefore = true;
  } catch (error) {
    if (error?.code !== "ENOENT") throw error;
  }

  const coverageResult = await writeRunrailHunkContinuityArtifacts({
    audit: afterAudit,
    patchText: currentPatchText,
    reviewRoot: canonicalReviewRoot,
    previousCoverage
  });
  let created = false;
  try {
    try {
      await mkdir(outputRoot, { mode: 0o700 });
      created = true;
    } catch (error) {
      if (error?.code !== "EEXIST") throw error;
      const entry = await lstat(outputRoot);
      if (!entry.isDirectory() || entry.isSymbolicLink()) {
        fail(
          "review-delta-artifact-boundary",
          "The Review Delta output must be an ordinary Runrail-owned directory."
        );
      }
    }
    const canonicalOutputRoot = await realpath(outputRoot);
    if (!isInside(canonicalOutputRoot, canonicalReviewRoot)) {
      fail(
        "review-delta-artifact-boundary",
        "The Review Delta output escaped its Runrail review directory."
      );
    }
    const deltaPath = path.join(outputRoot, "delta.json");
    const reviewPath = path.join(outputRoot, "REVIEW_DELTA.md");
    const htmlReportPath = path.join(outputRoot, "delta.html");
    if (created) {
      await writeFile(deltaPath, stableRunrailReviewDeltaJson(delta), {
        encoding: "utf8",
        mode: 0o600,
        flag: "wx"
      });
      await writeFile(reviewPath, renderRunrailReviewDeltaMarkdown(delta), {
        encoding: "utf8",
        mode: 0o600,
        flag: "wx"
      });
      await writeFile(htmlReportPath, renderRunrailReviewDeltaHtml(delta), {
        encoding: "utf8",
        mode: 0o600,
        flag: "wx"
      });
    }
    const verifiedPaths = await verifyStoredDelta({
      delta,
      outputRoot,
      beforeAudit,
      afterAudit,
      previousCoverage,
      currentCoverage: coverageResult.coverage
    });
    return {
      ok: true,
      mode: "deterministic-review-delta",
      deltaId: delta.deltaId,
      outputRoot,
      ...verifiedPaths,
      coverageId: coverageResult.coverageId,
      coveragePath: coverageResult.coveragePath,
      coverageReviewPath: coverageResult.reviewPath,
      coverageHtmlReportPath: coverageResult.htmlReportPath,
      relationship: delta.relationship.type,
      comparablePolicyBasis: delta.policyBasis.comparable,
      reviewPriority: {
        before: delta.policyBasis.reviewPriorityBefore,
        after: delta.policyBasis.reviewPriorityAfter,
        direction: delta.policyBasis.direction
      },
      addedFindingCount: delta.findings.addedCount,
      resolvedFindingCount: delta.findings.resolvedCount,
      changedFindingCount: delta.findings.changedCount,
      carriedForwardCount: delta.attention.carriedForwardCount,
      currentAttentionRequiredCount:
        delta.attention.currentAttentionRequiredCount,
      humanApprovalRequired: true,
      projectTestsExecuted: false,
      authority: "none",
      networkUsed: false,
      sourceMutation: false,
      reusedExistingArtifacts: !created,
      coverage: coverageResult.coverage,
      delta
    };
  } catch (error) {
    if (created) {
      await rm(outputRoot, { recursive: true, force: true }).catch(() => {});
    }
    if (!coverageExistedBefore) {
      await rm(coverageResult.outputRoot, {
        recursive: true,
        force: true
      }).catch(() => {});
    }
    throw error;
  }
}
