const directFileLaunch = location.protocol === "file:";
const sessionMatch = location.hash.match(/(?:^#|&)session=([^&]+)/);
const sessionToken = sessionMatch ? decodeURIComponent(sessionMatch[1]) : "";
if (!directFileLaunch) {
  history.replaceState(null, "", `${location.pathname}${location.search}`);
}

const state = {
  assurance: null,
  assuranceAgentBrief: "",
  agentAdapters: [],
  agentLaunchReceipt: null,
  outcomeLedger: null,
  outcomeLedgerAvailable: false,
  productMetrics: null,
  externalEvidence: [],
  auditPath: "",
  deepseekConfigured: false,
  history: [],
  inspection: null,
  readiness: null,
  readinessHandoff: null,
  readinessHandoffText: "",
  readinessBriefCopied: false,
  lastReviewInput: null,
  passportPath: "",
  proofGraph: null,
  proofGraphAvailable: false,
  repoId: "",
  repositoryInspectionInProgress: false,
  review: null,
  reviewId: "",
  revision: null,
  revisionWorkspaceAvailable: false,
  trustProfile: null,
  trustProfilesAvailable: false,
  tournament: null,
  tournamentAvailable: false,
  deviceSignedPassportsAvailable: false,
  coverage: null,
  coverageDraft: new Map(),
  coverageDraftKey: "",
  candidateReviewAvailable: false,
  diff: null,
  guidedSample: false,
  status: null,
  previewReadinessOnly: false,
  nativeAvailable: false,
  activeSurface: "activate",
  assuranceBriefCopied: false,
  todayAction: "select-repository"
};

const runtimeStatus = document.querySelector(".topbar-status");
const runtimeStatusText = document.querySelector("#runtime-status");
const reviewForm = document.querySelector("#review-form");
const reviewButton = document.querySelector("#review-button");
const reviewProgress = document.querySelector("#review-progress");
const sampleButton = document.querySelector("#sample-button");
const sampleProgress = document.querySelector("#sample-progress");
const inspectRepoButton = document.querySelector("#inspect-repo-button");
const copyReadinessButton = document.querySelector("#copy-readiness-button");
const downloadReadinessButton = document.querySelector("#download-readiness-button");
const readinessReinspectButton = document.querySelector("#readiness-reinspect-button");
const recommendButton = document.querySelector("#recommend-button");
const recommendProgress = document.querySelector("#recommend-progress");
const consentRow = document.querySelector("#consent-row");
const networkConsent = document.querySelector("#network-consent");
const saveCoverageButton = document.querySelector("#save-coverage");
const inspectDiffButton = document.querySelector("#inspect-diff-button");
const coverageProgress = document.querySelector("#coverage-progress");
const coverageReviewMeter = document.querySelector("#coverage-review-meter");
const coverageReviewProgress = document.querySelector("#coverage-review-progress");
const coverageReviewBar = document.querySelector("#coverage-review-bar");
const revisionButton = document.querySelector("#revision-button");
const revisionProgress = document.querySelector("#revision-progress");
const rerunButton = document.querySelector("#rerun-button");
const openEvidenceButton = document.querySelector("#open-evidence-button");
const exportPassportButton = document.querySelector("#export-passport-button");
const copyAgentBriefButton = document.querySelector("#copy-agent-brief-button");
const assuranceSectionButton = document.querySelector("#assurance-section-button");
const assuranceProgress = document.querySelector("#assurance-progress");
const deviceSignPassport = document.querySelector("#device-sign-passport");
const passportSignOption = document.querySelector("#passport-sign-option");
const passportProgress = document.querySelector("#passport-progress");
const historyRefreshButton = document.querySelector("#history-refresh");
const historyFilter = document.querySelector("#history-filter");
const trustRefreshButton = document.querySelector("#trust-refresh-button");
const weeklyReportButton = document.querySelector("#weekly-report-button");
const trustProgress = document.querySelector("#trust-progress");
const tournamentButton = document.querySelector("#tournament-button");
const tournamentProgress = document.querySelector("#tournament-progress");
const proofGraphButton = document.querySelector("#proofgraph-button");
const proofGraphProgress = document.querySelector("#proofgraph-progress");
const agentAdapterSelect = document.querySelector("#agent-adapter-select");
const agentLaunchConfirmed = document.querySelector("#agent-launch-confirmed");
const agentLaunchButton = document.querySelector("#agent-launch-button");
const agentLaunchProgress = document.querySelector("#agent-launch-progress");
const externalEvidenceFormat = document.querySelector("#external-evidence-format");
const externalEvidenceFile = document.querySelector("#external-evidence-file");
const externalEvidenceImport = document.querySelector("#external-evidence-import");
const externalEvidenceProgress = document.querySelector("#external-evidence-progress");
const outcomeAgentSelect = document.querySelector("#outcome-agent-select");
const outcomeRecordButton = document.querySelector("#outcome-record-button");
const outcomeLedgerProgress = document.querySelector("#outcome-ledger-progress");
const productMetricsRefresh = document.querySelector("#product-metrics-refresh");
const productMetricsProgress = document.querySelector("#product-metrics-progress");
const activationPrimaryAction = document.querySelector("#activation-primary-action");
const nativeRepoPicker = document.querySelector("#native-repo-picker");
const todayPrimaryAction = document.querySelector("#today-primary-action");
const toast = document.querySelector("#toast");

class LocalApiError extends Error {
  constructor(message, { code = "", status = 0 } = {}) {
    super(message);
    this.name = "LocalApiError";
    this.code = code;
    this.status = status;
  }
}

function text(node, value) {
  if (node) node.textContent = String(value ?? "");
}

function firstText(...values) {
  for (const value of values) {
    if (typeof value === "string" && value.trim()) return value.trim();
  }
  return "";
}

function firstArray(...values) {
  for (const value of values) {
    if (Array.isArray(value)) return value;
  }
  return [];
}

function titleCase(value) {
  return String(value || "")
    .replaceAll("_", " ")
    .replaceAll("-", " ")
    .replace(/\b\w/g, (letter) => letter.toUpperCase());
}

function pathName(value) {
  const normalized = String(value || "").replaceAll("\\", "/").replace(/\/+$/, "");
  return normalized.split("/").filter(Boolean).at(-1) || normalized || "Local repository";
}

function formatDateTime(value) {
  if (!value) return "";
  const date = new Date(value);
  if (Number.isNaN(date.getTime())) return String(value);
  return new Intl.DateTimeFormat(undefined, {
    dateStyle: "medium",
    timeStyle: "short"
  }).format(date);
}

function formatTime(value) {
  if (!value) return "";
  const date = new Date(value);
  if (Number.isNaN(date.getTime())) return "";
  return new Intl.DateTimeFormat(undefined, {
    hour: "2-digit",
    minute: "2-digit"
  }).format(date);
}

function showToast(message) {
  text(toast, message);
  toast.hidden = false;
  window.clearTimeout(showToast.timeoutId);
  showToast.timeoutId = window.setTimeout(() => {
    toast.hidden = true;
  }, 8000);
}

async function api(
  path,
  body = {},
  { acceptReviewResult = false, commandLockRetryCount = 0 } = {}
) {
  if (!sessionToken) {
    throw new LocalApiError(
      "The local desktop session token is missing. Restart Runrail Desktop.",
      { code: "desktop-session-missing" }
    );
  }
  const response = await fetch(path, {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
      "X-Runrail-Session": sessionToken
    },
    body: JSON.stringify(body)
  });
  let payload;
  try {
    payload = await response.json();
  } catch {
    payload = { ok: false, code: "desktop-response-invalid" };
  }
  if (
    response.status === 409 &&
    payload.code === "desktop-command-in-progress" &&
    commandLockRetryCount < 1
  ) {
    await new Promise((resolve) => window.setTimeout(resolve, 50));
    return api(path, body, {
      acceptReviewResult,
      commandLockRetryCount: commandLockRetryCount + 1
    });
  }
  const acceptedBlockedReview = (
    acceptReviewResult &&
    response.ok &&
    payload.ok === false &&
    Boolean(
      payload.reportPath ||
      payload.auditPath ||
      payload.report ||
      payload.session ||
      payload.verdict
    )
  );
  if (!response.ok || (payload.ok === false && !acceptedBlockedReview)) {
    throw new LocalApiError(
      payload.message || payload.code || "The local Runrail request failed.",
      { code: payload.code || "", status: response.status }
    );
  }
  return payload;
}

async function optionalApi(path, body = {}, options = {}) {
  try {
    return await api(path, body, options);
  } catch (error) {
    if (
      error instanceof LocalApiError &&
      (
        error.status === 404 ||
        error.code === "desktop-api-not-found" ||
        error.code === "desktop-route-not-found"
      )
    ) {
      return null;
    }
    throw error;
  }
}

function normalizeVerdict(source) {
  const verdict = source?.verdict;
  const raw = firstText(
    typeof verdict === "string" ? verdict : "",
    verdict?.status,
    verdict?.state,
    verdict?.outcome,
    source?.status,
    source?.outcome
  ).toLowerCase();
  if (raw.includes("block") || raw.includes("fail") || raw.includes("stop")) {
    return "blocked";
  }
  if (
    raw.includes("attention") ||
    raw.includes("revision") ||
    raw.includes("review-required") ||
    raw.includes("review required")
  ) {
    return "needs-attention";
  }
  if (
    raw.includes("ready") ||
    raw.includes("pass") ||
    raw.includes("human-decision") ||
    raw.includes("human decision")
  ) {
    return "ready-for-human-decision";
  }

  const report = source?.report || source?.audit || source?.session?.report || {};
  if (source?.ok === false || report.preflightPassed === false) return "blocked";
  if (source?.ok === true || report.preflightPassed === true) {
    return "ready-for-human-decision";
  }
  return "needs-attention";
}

function verdictCopy(verdict) {
  if (verdict === "blocked") {
    return {
      label: "Blocked",
      title: "Blocked at a deterministic review boundary.",
      summary: "Inspect the evidence and revise the candidate before deciding what to do next."
    };
  }
  if (verdict === "needs-attention") {
    return {
      label: "Needs attention",
      title: "Needs attention before a human decision.",
      summary: "The bounded checks completed, but one or more items still need explicit review."
    };
  }
  return {
    label: "Ready for human decision",
    title: "Ready for human decision.",
    summary: "Bounded local checks completed. Project tests and human review are still required."
  };
}

function setMetric(selector, value, tone = "") {
  const node = document.querySelector(selector);
  text(node, value);
  node?.classList.remove("is-pass", "is-attention", "is-blocked");
  if (tone) node?.classList.add(`is-${tone}`);
}

function makeIcon(symbol) {
  const svg = document.createElementNS("http://www.w3.org/2000/svg", "svg");
  const use = document.createElementNS("http://www.w3.org/2000/svg", "use");
  svg.classList.add("icon");
  svg.setAttribute("aria-hidden", "true");
  use.setAttribute("href", `#icon-${symbol}`);
  svg.append(use);
  return svg;
}

function activateSurface(name, { scroll = true } = {}) {
  const target = document.querySelector(`#surface-${name}`);
  const validSurface = target || ["review", "advanced"].includes(name);
  if (!validSurface) return;
  state.activeSurface = name;
  document.body.dataset.activeSurface = name;
  for (const surface of document.querySelectorAll(".product-surface")) {
    surface.classList.toggle("is-active", surface === target);
  }
  for (const item of document.querySelectorAll(".nav-item")) {
    item.classList.toggle("is-active", item.dataset.surface === name);
    item.disabled = false;
  }
  if (!scroll) return;
  const scrollTarget = target || (
    name === "advanced"
      ? document.querySelector(".advanced-section")
      : document.querySelector("#view-review")
  );
  scrollTarget?.scrollIntoView({ block: "start", behavior: "smooth" });
}

function activateView(name, { scroll = true } = {}) {
  const target = document.querySelector(`#view-${name}`);
  if (!target) return;
  if (name === "revision" && !state.revisionWorkspaceAvailable) {
    showToast("The Desktop Revision Workspace requires a Pro or higher entitlement.");
    return;
  }
  activateSurface(
    name === "revision" || name === "recommend" ? "advanced" : "review",
    { scroll: false }
  );
  for (const view of document.querySelectorAll(".view")) {
    view.classList.toggle("is-active", view === target);
  }
  if (target instanceof HTMLDetailsElement) target.open = true;
  if (scroll) {
    target.scrollIntoView({
      block: name === "evidence" ? "start" : "center",
      behavior: "smooth"
    });
  }
}

function unlockWorkflow() {
  const hasReview = Boolean(state.review || state.reviewId);
  for (const item of document.querySelectorAll(".nav-item")) {
    item.disabled = false;
  }
  rerunButton.disabled = !hasReview || state.previewReadinessOnly;
  reviewButton.disabled = !state.candidateReviewAvailable;
  reviewButton.title = state.candidateReviewAvailable
    ? state.previewReadinessOnly
      ? "Run the one bounded public-preview review"
      : "Run bounded local review"
    : state.previewReadinessOnly
      ? "The one public-preview review has been used."
      : "Candidate review requires a Starter or Pro entitlement.";
  revisionButton.disabled = !hasReview || !state.revisionWorkspaceAvailable;
  openEvidenceButton.disabled = !state.review;
  exportPassportButton.disabled = !state.reviewId && !state.passportPath;
  copyAgentBriefButton.disabled = !state.reviewId;
  assuranceSectionButton.disabled = !state.reviewId;
  deviceSignPassport.disabled = !hasReview || !state.deviceSignedPassportsAvailable;
  trustRefreshButton.disabled = !state.repoId || !state.trustProfilesAvailable;
  weeklyReportButton.disabled = !state.repoId || !state.trustProfilesAvailable;
  updateTournamentControlState();
  proofGraphButton.disabled =
    !state.proofGraphAvailable ||
    !state.reviewId;
  inspectDiffButton.disabled = !state.reviewId || !state.coverage?.hunks?.length;
  externalEvidenceFile.disabled = !state.reviewId;
  externalEvidenceImport.disabled =
    !state.reviewId ||
    !(externalEvidenceFile.files?.length > 0);
  const outcomeBaselineId = firstText(state.assurance?.beforeReviewId);
  const canRecordOutcome = Boolean(
    state.outcomeLedgerAvailable &&
    state.reviewId &&
    outcomeBaselineId &&
    outcomeBaselineId !== state.reviewId &&
    state.assurance?.result
  );
  outcomeAgentSelect.disabled =
    !state.outcomeLedgerAvailable || !state.reviewId;
  outcomeRecordButton.disabled = !canRecordOutcome;
  recommendButton.disabled = !state.auditPath;
  updateAgentBridgeState();
}

function selectedAgentAdapter() {
  return state.agentAdapters.find(
    (adapter) => adapter?.adapterId === agentAdapterSelect.value
  ) || null;
}

function updateAgentBridgeState() {
  const adapter = selectedAgentAdapter();
  const canPrepareLaunch = Boolean(
    state.reviewId &&
    state.assuranceBriefCopied &&
    adapter?.launchable === true
  );
  agentAdapterSelect.disabled = state.agentAdapters.length === 0;
  agentLaunchConfirmed.disabled = !canPrepareLaunch;
  if (!canPrepareLaunch) agentLaunchConfirmed.checked = false;
  agentLaunchButton.disabled = !canPrepareLaunch || !agentLaunchConfirmed.checked;
}

function renderAgentAdapters(payload) {
  state.agentAdapters = firstArray(payload?.adapters).filter(
    (adapter) =>
      typeof adapter?.adapterId === "string" &&
      typeof adapter?.label === "string" &&
      adapter?.authority === "none"
  );
  agentAdapterSelect.replaceChildren();
  for (const adapter of state.agentAdapters) {
    const option = document.createElement("option");
    option.value = adapter.adapterId;
    option.disabled = adapter.mode !== "copy" && adapter.launchable !== true;
    text(
      option,
      [
        adapter.label,
        adapter.mode === "copy"
          ? "copy only"
          : adapter.launchable
            ? "ready"
            : adapter.detected
              ? "terminal unavailable"
              : "not detected"
      ].join(" / ")
    );
    agentAdapterSelect.append(option);
  }
  const firstLaunchable = state.agentAdapters.find(
    (adapter) => adapter.launchable === true
  );
  const generic = state.agentAdapters.find(
    (adapter) => adapter.adapterId === "generic-copy"
  );
  agentAdapterSelect.value = firstLaunchable?.adapterId || generic?.adapterId || "";
  text(
    agentLaunchProgress,
    firstLaunchable
      ? `${firstLaunchable.label} is detected. Copy the brief, confirm the fixed interactive launch, then rerun Runrail after the agent exits.`
      : "No fixed interactive adapter is currently launchable. Generic source-free copy remains available."
  );
  updateAgentBridgeState();
}

function coverageSnapshot() {
  const hunks = firstArray(state.coverage?.hunks, state.coverage?.items);
  return {
    hunkCount: hunks.length,
    reviewedCount: hunks.filter((item) => item?.status === "reviewed").length,
    needsRevisionCount: hunks.filter(
      (item) => item?.status === "needs-revision"
    ).length,
    unreviewedCount: hunks.filter(
      (item) => !item?.status || item.status === "unreviewed"
    ).length
  };
}

function coverageDraftSnapshot() {
  const states = [...document.querySelectorAll("#coverage-list select")].map(
    (select) => ({
      hunkId: select.dataset.hunkId,
      status: select.value
    })
  );
  return {
    states,
    hunkCount: states.length,
    reviewedCount: states.filter((item) => item.status === "reviewed").length,
    needsRevisionCount: states.filter(
      (item) => item.status === "needs-revision"
    ).length,
    unreviewedCount: states.filter(
      (item) => item.status === "unreviewed"
    ).length
  };
}

function coverageDraftIsDirty(snapshot = coverageDraftSnapshot()) {
  const persistedById = new Map(
    firstArray(state.coverage?.hunks, state.coverage?.items).map((hunk, index) => [
      firstText(hunk?.hunkId, hunk?.id, String(index + 1)),
      firstText(hunk?.status) || "unreviewed"
    ])
  );
  return snapshot.states.some(
    (item) => persistedById.get(item.hunkId) !== item.status
  );
}

function setCurrentCoverageHunk(item, { focus = true, scroll = true } = {}) {
  for (const candidate of document.querySelectorAll("#coverage-list li")) {
    candidate.classList.toggle("is-current-hunk", candidate === item);
  }
  if (!item) return false;
  const details = item.querySelector(".coverage-diff");
  if (details) details.open = true;
  if (scroll) {
    item.scrollIntoView({ block: "center", behavior: "smooth" });
  }
  if (focus) item.querySelector("select")?.focus({ preventScroll: true });
  return true;
}

function focusNextUnreviewedHunk({ afterHunkId = "", focus = true, scroll = true } = {}) {
  const items = [...document.querySelectorAll("#coverage-list li[data-hunk-id]")];
  if (items.length === 0) return setCurrentCoverageHunk(null);
  const startIndex = Math.max(
    0,
    items.findIndex((item) => item.dataset.hunkId === afterHunkId) + 1
  );
  const ordered = [...items.slice(startIndex), ...items.slice(0, startIndex)];
  const next = ordered.find(
    (item) => item.querySelector("select")?.value === "unreviewed"
  );
  if (next) return setCurrentCoverageHunk(next, { focus, scroll });
  setCurrentCoverageHunk(null);
  if (focus) {
    saveCoverageButton.scrollIntoView({ block: "center", behavior: "smooth" });
    saveCoverageButton.focus({ preventScroll: true });
  }
  return false;
}

function refreshCoverageDraftUi({ advanceFrom = "", focus = false, scroll = false } = {}) {
  const snapshot = coverageDraftSnapshot();
  const classifiedCount =
    snapshot.reviewedCount + snapshot.needsRevisionCount;
  const dirty = coverageDraftIsDirty(snapshot);
  coverageReviewMeter.hidden = snapshot.hunkCount === 0;
  coverageReviewBar.max = Math.max(snapshot.hunkCount, 1);
  coverageReviewBar.value = classifiedCount;
  text(
    coverageReviewProgress,
    `${classifiedCount} of ${snapshot.hunkCount} classified`
  );
  text(
    document.querySelector("#coverage-summary"),
    snapshot.hunkCount > 0
      ? `${snapshot.reviewedCount} reviewed, ${snapshot.needsRevisionCount} needs revision, ${snapshot.unreviewedCount} unreviewed${dirty ? " · draft not saved" : ""}.`
      : "No hunk coverage yet."
  );
  saveCoverageButton.disabled = snapshot.hunkCount === 0 || !dirty;
  saveCoverageButton.classList.toggle(
    "is-ready-action",
    dirty && snapshot.unreviewedCount === 0
  );
  if (snapshot.hunkCount === 0) {
    text(coverageProgress, "No hunk attention snapshot is needed.");
    return snapshot;
  }
  if (dirty && snapshot.unreviewedCount === 0) {
    text(
      coverageProgress,
      `All ${snapshot.hunkCount} hunks are classified. Save the attention snapshot to update Agent Assurance; nothing is approved automatically.`
    );
  } else if (dirty) {
    text(
      coverageProgress,
      `${snapshot.unreviewedCount} hunk${snapshot.unreviewedCount === 1 ? "" : "s"} remaining. Draft attention stays in memory until you save it.`
    );
  } else if (snapshot.unreviewedCount === 0) {
    text(
      coverageProgress,
      `All ${snapshot.hunkCount} hunks are classified in the saved snapshot. Attention remains separate from approval.`
    );
  } else {
    text(
      coverageProgress,
      state.diff
        ? "Diff content is held in memory only. Classify the current hunk to continue."
        : "Inspect the local diff, then classify each hunk. Nothing is saved automatically."
    );
  }
  if (advanceFrom) {
    const changed = [...document.querySelectorAll("#coverage-list li[data-hunk-id]")]
      .find((item) => item.dataset.hunkId === advanceFrom);
    if (changed?.querySelector("select")?.value === "unreviewed") {
      setCurrentCoverageHunk(changed, { focus, scroll });
    } else {
      focusNextUnreviewedHunk({ afterHunkId: advanceFrom, focus, scroll });
    }
  }
  return snapshot;
}

function assurancePhase() {
  const resultStatus = firstText(state.assurance?.result?.status);
  if (resultStatus) return titleCase(resultStatus);
  if (state.assurance?.packet || state.assuranceAgentBrief) {
    return state.assuranceBriefCopied ? "Awaiting verified rerun" : "Brief ready";
  }
  return state.reviewId ? "Ready for handoff" : "Not started";
}

function todayActionModel() {
  const coverage = coverageSnapshot();
  const assuranceStatus = firstText(state.assurance?.result?.status);
  if (!state.reviewId) {
    if (state.inspection && state.previewReadinessOnly) {
      if (state.candidateReviewAvailable) {
        return {
          id: "run-first-review",
          label: "Run preview review",
          icon: "play",
          summary: "Review one real local candidate, inspect exact hunks, and export source-free evidence without an account."
        };
      }
      if (state.readinessHandoffText && !state.readinessBriefCopied) {
        return {
          id: "copy-readiness-brief",
          label: "Copy Review-Ready Brief",
          icon: "copy",
          summary: "Repository readiness is confirmed. Copy one path-free brief into any coding agent; candidate review remains enrollment-gated."
        };
      }
      if (state.readinessHandoffText && state.readinessBriefCopied) {
        return {
          id: "reinspect-repository",
          label: "Inspect revised repository",
          icon: "refresh",
          summary: "Brief copied. Complete its objective in any coding agent, then inspect this repository again."
        };
      }
      return {
        id: "inspect-another-repository",
        label: "Inspect another repository",
        icon: "folder",
        summary: "Repository readiness is confirmed. Candidate review remains enrollment-gated."
      };
    }
    if (latestHistoryItem()) {
      return {
        id: "resume-latest-review",
        label: "Resume latest review",
        icon: "history",
        summary: "Reopen the most recent checksum-verified local evidence and continue from its exact state."
      };
    }
    return {
      id: state.inspection ? "run-first-review" : "select-repository",
      label: state.inspection ? "Run first review" : "Select a repository",
      icon: state.inspection ? "play" : "folder",
      summary: state.inspection
        ? "Repository metadata is ready. Confirm the references and run the first review."
        : "Select a local Git repository or use the safe sample from Activate."
    };
  }
  if (coverage.unreviewedCount > 0) {
    return {
      id: "inspect-next-hunk",
      label: "Inspect next hunk",
      icon: "inspect",
      summary: `${coverage.unreviewedCount} changed hunk${coverage.unreviewedCount === 1 ? "" : "s"} still need an explicit attention state.`
    };
  }
  if (
    coverage.needsRevisionCount > 0 &&
    !state.assuranceBriefCopied
  ) {
    return {
      id: "copy-correction-brief",
      label: "Copy correction brief",
      icon: "copy",
      summary: `${coverage.needsRevisionCount} reviewed hunk${coverage.needsRevisionCount === 1 ? "" : "s"} require a candidate revision.`
    };
  }
  if (
    coverage.needsRevisionCount > 0 ||
    state.assuranceBriefCopied
  ) {
    return {
      id: "verify-revised-candidate",
      label: "Verify revised candidate",
      icon: "refresh",
      summary: "Rerun the same confirmed review references after the coding agent exits."
    };
  }
  if (
    assuranceStatus === "ready-for-human-decision" ||
    (
      normalizeVerdict(state.review) === "ready-for-human-decision" &&
      coverage.unreviewedCount === 0 &&
      coverage.needsRevisionCount === 0
    )
  ) {
    return {
      id: "review-human-decision",
      label: "Review human decision",
      icon: "shield",
      summary: "The bounded evidence loop is complete. Correctness, project tests, and merge approval remain human."
    };
  }
  return {
    id: "complete-attention",
    label: "Complete attention",
    icon: "check",
    summary: "Finish the explicit attention states before treating this review as ready."
  };
}

function activationActionModel() {
  if (state.previewReadinessOnly && state.readinessHandoffText) {
    if (state.candidateReviewAvailable) {
      return {
        id: "open-review",
        label: "Run preview review",
        icon: "play"
      };
    }
    return state.readinessBriefCopied
      ? {
          id: "reinspect-repository",
          label: "Inspect revised repository",
          icon: "refresh"
        }
      : {
          id: "copy-readiness-brief",
          label: "Copy Review-Ready Brief",
          icon: "copy"
        };
  }
  if (state.inspection && !state.guidedSample) {
    return {
      id: "open-review",
      label: state.candidateReviewAvailable
        ? "Review candidate"
        : "Inspect a repository",
      icon: state.candidateReviewAvailable ? "play" : "folder"
    };
  }
  if (state.status?.doctor?.ok !== true) {
    return {
      id: "wait-for-doctor",
      label: "Checking this device",
      icon: "refresh",
      disabled: true
    };
  }
  if (!state.reviewId && latestHistoryItem()) {
    return {
      id: "resume-latest-review",
      label: "Resume latest review",
      icon: "history"
    };
  }
  if (!(state.guidedSample === true && Boolean(state.review))) {
    return {
      id: "run-safe-sample",
      label: "Run safe sample",
      icon: "play"
    };
  }
  if (state.nativeAvailable && state.previewReadinessOnly && !state.candidateReviewAvailable) {
    return {
      id: "enroll-device",
      label: "Enroll this device",
      icon: "shield"
    };
  }
  return {
    id: "open-review",
    label: state.candidateReviewAvailable
      ? "Select a repository"
      : "Inspect a repository",
    icon: "folder"
  };
}

function assuranceLoopProgressModel() {
  const coverage = coverageSnapshot();
  const verdict = state.review ? normalizeVerdict(state.review) : "";
  const assuranceStatus = firstText(state.assurance?.result?.status);
  const reviewComplete = Boolean(state.reviewId);
  const inspectComplete =
    reviewComplete &&
    (coverage.hunkCount === 0 || coverage.unreviewedCount === 0);
  const readyForHumanDecision =
    assuranceStatus === "ready-for-human-decision" ||
    (
      verdict === "ready-for-human-decision" &&
      coverage.unreviewedCount === 0 &&
      coverage.needsRevisionCount === 0
    );
  const resolveComplete =
    inspectComplete &&
    (
      coverage.needsRevisionCount === 0 ||
      readyForHumanDecision
    );
  const completion = [
    reviewComplete,
    inspectComplete,
    resolveComplete,
    readyForHumanDecision
  ];
  const currentIndex = completion.findIndex((complete) => !complete);
  const labels = ["review", "inspect", "resolve", "decide"];
  const steps = labels.map((id, index) => ({
    id,
    state: completion[index]
      ? "complete"
      : index === currentIndex
        ? "current"
        : "pending"
  }));
  const completedCount = completion.filter(Boolean).length;
  const action = todayActionModel();
  return {
    completedCount,
    steps,
    title: readyForHumanDecision
      ? "Evidence loop complete. The decision stays human."
      : `${action.label}.`,
    summary: readyForHumanDecision
      ? "4 of 4 stages complete. Project tests, correctness, and merge approval remain outside Runrail."
      : `${completedCount} of 4 stages complete. ${action.summary}`
  };
}

function renderReviewInbox() {
  const inbox = document.querySelector("#review-inbox-list");
  const rows = state.history
    .filter((item) => normalizeVerdict(item) !== "ready-for-human-decision")
    .slice(0, 6);
  inbox.replaceChildren();
  text(
    document.querySelector("#review-inbox-count"),
    `${rows.length} open`
  );
  if (rows.length === 0) {
    const empty = document.createElement("p");
    empty.className = "empty-copy";
    text(
      empty,
      state.history.length > 0
        ? "No unfinished local reviews."
        : "No local review history yet."
    );
    inbox.append(empty);
    return;
  }
  for (const item of rows) {
    const button = document.createElement("button");
    const copy = document.createElement("span");
    const title = document.createElement("strong");
    const detail = document.createElement("small");
    const verdict = normalizeVerdict(item);
    button.className = "review-inbox-item";
    button.type = "button";
    text(title, historyCandidate(item));
    text(
      detail,
      `${verdictCopy(verdict).label}${historyTimestamp(item) ? ` · ${formatDateTime(historyTimestamp(item))}` : ""}`
    );
    copy.append(title, detail);
    button.append(makeIcon(verdict === "blocked" ? "x" : "alert"), copy);
    button.addEventListener("click", () => {
      activateSurface("review");
      void selectHistoryItem(item);
    });
    inbox.append(button);
  }
}

function renderActivationJourney() {
  const resumableHistory = latestHistoryItem();
  const doctorComplete = state.status?.doctor?.ok === true;
  const sampleComplete =
    (state.guidedSample === true && Boolean(state.review)) ||
    Boolean(resumableHistory);
  const repositoryComplete = Boolean(firstText(
    state.inspection?.repo,
    state.inspection?.path,
    state.inspection?.repositoryPath
  )) || Boolean(resumableHistory);
  const steps = [
    {
      id: "doctor",
      complete: doctorComplete,
      next: "Confirm this device"
    },
    {
      id: "sample",
      complete: sampleComplete,
      next: "Run the safe sample"
    },
    {
      id: "repository",
      complete: repositoryComplete,
      next: "Select a repository"
    }
  ];
  const firstIncomplete = steps.find((step) => !step.complete)?.id || "";
  const completedCount = steps.filter((step) => step.complete).length;
  for (const step of steps) {
    const item = document.querySelector(`[data-activation-step="${step.id}"]`);
    if (!item) continue;
    const stepState = step.complete
      ? "complete"
      : step.id === firstIncomplete
        ? "current"
        : "pending";
    item.dataset.stepState = stepState;
    if (stepState === "current") item.setAttribute("aria-current", "step");
    else item.removeAttribute("aria-current");
    text(
      item.querySelector("em"),
      stepState === "complete"
        ? "Complete"
        : stepState === "current"
          ? "Current"
          : "Pending"
    );
  }
  const nextStep = steps.find((step) => step.id === firstIncomplete);
  const action = activationActionModel();
  activationPrimaryAction.dataset.action = action.id;
  activationPrimaryAction.disabled =
    action.disabled === true || state.repositoryInspectionInProgress;
  text(activationPrimaryAction.querySelector("span"), action.label);
  activationPrimaryAction
    .querySelector("use")
    ?.setAttribute("href", `#icon-${action.icon}`);
  sampleButton.hidden = !sampleComplete;
  text(sampleButton.querySelector("span"), "Run sample again");
  text(
    document.querySelector("#activation-progress"),
    state.previewReadinessOnly && state.readinessBriefCopied
      ? "Brief copied. Complete the objective in any coding agent, then inspect this repository again."
      : resumableHistory && !state.reviewId && !state.inspection
        ? "Local history found. Resume the latest verified review, or select a new repository from Review."
      : completedCount === steps.length
      ? state.previewReadinessOnly
        ? state.candidateReviewAvailable
          ? "Preview setup complete. Select one real candidate and run the bounded local review."
          : "Preview review used. Existing evidence remains inspectable; another review requires enrollment."
        : "Setup complete. Start or reopen a review from Today."
      : `${completedCount} of ${steps.length} complete. Next: ${nextStep?.next || "Continue setup"}.`
  );
}

function renderToday() {
  const coverage = coverageSnapshot();
  const action = todayActionModel();
  const loop = assuranceLoopProgressModel();
  const verdict = state.review
    ? normalizeVerdict(state.review)
    : "";
  const expiringExceptions = Number(
    state.trustProfile?.dispositions?.expiringExceptionCount ??
    state.trustProfile?.dispositions?.expiredExceptionCount ??
    0
  );
  state.todayAction = action.id;
  text(document.querySelector("#today-summary"), action.summary);
  text(
    document.querySelector("#today-repository"),
    state.guidedSample
      ? "Guided sample"
      : state.inspection
      ? pathName(firstText(
        state.inspection.repo,
        state.inspection.path,
        state.inspection.repositoryPath,
        state.lastReviewInput?.repo
      ))
      : latestHistoryItem()
        ? "Verified local history"
      : "None selected"
  );
  text(
    document.querySelector("#today-verdict"),
    verdict ? verdictCopy(verdict).label : "No review"
  );
  text(
    document.querySelector("#today-attention"),
    coverage.unreviewedCount + coverage.needsRevisionCount
  );
  text(document.querySelector("#today-assurance"), assurancePhase());
  text(document.querySelector("#today-exceptions"), expiringExceptions);
  text(document.querySelector("#assurance-loop-title"), loop.title);
  text(document.querySelector("#today-loop-progress"), loop.summary);
  for (const step of loop.steps) {
    const item = document.querySelector(`[data-loop-step="${step.id}"]`);
    if (!item) continue;
    item.dataset.loopState = step.state;
    if (step.state === "current") item.setAttribute("aria-current", "step");
    else item.removeAttribute("aria-current");
    text(
      item.querySelector("em"),
      step.state === "complete"
        ? "Complete"
        : step.state === "current"
          ? "Current"
          : "Pending"
    );
  }
  const metricSummary = state.productMetrics?.northStar;
  const weeklyLoops = Number(metricSummary?.completedAssuranceLoopCount || 0);
  const weeklyRepositories = Number(metricSummary?.activeRepositoryCount || 0);
  text(document.querySelector("#today-weekly-loops"), weeklyLoops);
  text(
    document.querySelector("#today-weekly-repositories"),
    `${weeklyRepositories} active repositor${weeklyRepositories === 1 ? "y" : "ies"}`
  );
  const label = todayPrimaryAction.querySelector("span");
  const iconUse = todayPrimaryAction.querySelector("use");
  todayPrimaryAction.disabled = state.repositoryInspectionInProgress;
  text(label, action.label);
  iconUse?.setAttribute("href", `#icon-${action.icon}`);
  renderReviewInbox();
  renderActivationJourney();
}

function renderActivation(status) {
  state.status = status || null;
  const doctorPassed = status?.doctor?.ok === true;
  const planCode = firstText(status?.entitlement?.planCode);
  const entitlementStatus = firstText(
    status?.entitlement?.status,
    status?.entitlement?.state
  );
  const entitlementExpiry = firstText(
    status?.entitlement?.expiresAt,
    status?.entitlement?.validUntil,
    status?.entitlement?.leaseExpiresAt
  );
  text(
    document.querySelector("#activation-runtime"),
    doctorPassed ? "Ready" : "Attention required"
  );
  text(
    document.querySelector("#activation-doctor"),
    doctorPassed
      ? "Integrated doctor passed for this local package."
      : "Integrated doctor did not confirm this package."
  );
  text(
    document.querySelector("#activation-plan"),
    planCode ? `${titleCase(planCode)} access` : "Local preview"
  );
  text(
    document.querySelector("#activation-renewal"),
    [
      entitlementStatus ? titleCase(entitlementStatus) : "Local entitlement loaded",
      entitlementExpiry ? `until ${formatDateTime(entitlementExpiry)}` : ""
    ].filter(Boolean).join(" ")
  );
  renderActivationJourney();
}

function renderCoverage(coverage, { preserveDraft = false } = {}) {
  state.coverage = coverage || null;
  const hunks = firstArray(coverage?.hunks, coverage?.items);
  const draftKey = [
    state.reviewId,
    firstText(coverage?.checksumSha256, coverage?.checksum),
    hunks.map((hunk, index) => [
      firstText(hunk?.hunkId, hunk?.id, String(index + 1)),
      firstText(hunk?.status) || "unreviewed"
    ].join("=")).join(":")
  ].join("|");
  if (!preserveDraft || state.coverageDraftKey !== draftKey) {
    state.coverageDraft = new Map(
      hunks.map((hunk, index) => [
        firstText(hunk?.hunkId, hunk?.id, String(index + 1)),
        firstText(hunk?.status) || "unreviewed"
      ])
    );
    state.coverageDraftKey = draftKey;
  }
  const diffByHunkId = new Map();
  for (const file of firstArray(state.diff?.files)) {
    for (const hunk of firstArray(file?.hunks)) {
      if (hunk?.hunkId) diffByHunkId.set(hunk.hunkId, { file, hunk });
    }
  }

  text(document.querySelector("#coverage-count"), hunks.length);
  const list = document.querySelector("#coverage-list");
  list.replaceChildren();
  for (const [index, hunk] of hunks.entries()) {
    const item = document.createElement("li");
    const detail = document.createElement("div");
    const title = document.createElement("strong");
    const counts = document.createElement("small");
    const select = document.createElement("select");
    select.dataset.hunkId = firstText(hunk?.hunkId, hunk?.id, String(index + 1));
    item.dataset.hunkId = select.dataset.hunkId;
    select.setAttribute("aria-label", `Attention state for hunk ${index + 1}`);
    for (const [value, label] of [
      ["unreviewed", "Unreviewed"],
      ["reviewed", "Reviewed"],
      ["needs-revision", "Needs revision"]
    ]) {
      const option = document.createElement("option");
      option.value = value;
      option.selected = state.coverageDraft.get(select.dataset.hunkId) === value;
      text(option, label);
      select.append(option);
    }
    text(title, firstText(hunk?.label, `Hunk ${index + 1}`));
    text(
      counts,
      [
        `${Number(hunk?.addedLineCount || 0)} added`,
        `${Number(hunk?.removedLineCount || 0)} removed`,
        `${Number(hunk?.contextLineCount || 0)} context`,
        hunk?.carriedFromPrevious ? "carried exactly" : ""
      ].filter(Boolean).join(", ")
    );
    detail.append(title, counts);
    item.append(detail, select);
    const diffEntry = diffByHunkId.get(select.dataset.hunkId);
    if (diffEntry) {
      const details = document.createElement("details");
      const summaryNode = document.createElement("summary");
      const pre = document.createElement("pre");
      const code = document.createElement("code");
      details.className = "coverage-diff";
      text(
        summaryNode,
        `${firstText(diffEntry.file.path) || "Changed file"} · ${firstText(diffEntry.hunk.header) || "Diff hunk"}`
      );
      for (const line of firstArray(diffEntry.hunk.lines)) {
        const row = document.createElement("span");
        row.className = `diff-line is-${firstText(line?.kind) || "context"}`;
        row.dataset.prefix = firstText(line?.prefix);
        text(row, typeof line?.text === "string" ? line.text : "");
        code.append(row);
      }
      pre.append(code);
      details.append(summaryNode, pre);
      item.append(details);
    }
    select.addEventListener("change", () => {
      state.coverageDraft.set(select.dataset.hunkId, select.value);
      refreshCoverageDraftUi({
        advanceFrom: select.dataset.hunkId,
        focus: true,
        scroll: true
      });
    });
    list.append(item);
  }

  if (hunks.length === 0) {
    const item = document.createElement("li");
    const detail = document.createElement("div");
    const title = document.createElement("strong");
    const counts = document.createElement("small");
    text(title, "No textual diff hunks");
    text(counts, "No attention state is required for this candidate patch.");
    detail.append(title, counts);
    item.append(detail);
    list.append(item);
  }

  inspectDiffButton.disabled = hunks.length === 0 || !state.reviewId;
  refreshCoverageDraftUi();
  renderToday();
}

function resetRevision() {
  state.revision = null;
  text(document.querySelector("#revision-result .eyebrow"), "No map yet");
  text(
    document.querySelector("#revision-current-audit"),
    state.auditPath || "Run a current review first."
  );
  text(document.querySelector("#revision-relationship"), "-");
  text(document.querySelector("#revision-policy"), "-");
  text(document.querySelector("#revision-carried"), 0);
  text(document.querySelector("#revision-attention"), 0);
  text(document.querySelector("#revision-added"), 0);
  text(document.querySelector("#revision-resolved"), 0);
  text(document.querySelector("#revision-section-count"), "Not mapped");
  text(document.querySelector("#revision-artifact-path"), "No Re-review Map path yet.");
  document.querySelector("#revision-actions").replaceChildren();
  text(
    document.querySelector("#revision-result h2"),
    "Carry exact attention, reset everything else."
  );
  text(
    document.querySelector("#revision-result > div > p:last-child"),
    "The result will show relationship, policy continuity, finding changes, and current attention required."
  );
}

function resetAssurance() {
  state.assurance = null;
  state.assuranceAgentBrief = "";
  state.agentLaunchReceipt = null;
  agentLaunchConfirmed.checked = false;
  text(document.querySelector("#assurance-status"), "No result yet");
  text(
    document.querySelector("#assurance-title"),
    "Close the loop with evidence, not agent promises."
  );
  text(
    document.querySelector("#assurance-summary"),
    "After a rerun, Runrail will classify resolved, remaining, new, and reintroduced findings. Ready for human decision also requires complete Review Coverage."
  );
  text(document.querySelector("#assurance-resolved"), 0);
  text(document.querySelector("#assurance-remaining"), 0);
  text(document.querySelector("#assurance-new"), 0);
  text(document.querySelector("#assurance-reintroduced"), 0);
  text(document.querySelector("#assurance-section-count"), "Not generated");
  text(
    document.querySelector("#assurance-packet-path"),
    "No Agent Assurance packet yet."
  );
  text(
    document.querySelector("#assurance-result-path"),
    "Rerun after a revision to create the result."
  );
  document.querySelector("#assurance-actions").replaceChildren();
  text(
    assuranceProgress,
    "Agent Assurance is ready after the first review."
  );
  updateAgentBridgeState();
  renderToday();
}

function externalEvidenceSummary(receipt) {
  const summary = receipt?.summary || {};
  if (receipt?.format === "sarif") {
    return `${Number(summary.resultCount || 0)} results / ${Number(summary.errorCount || 0)} errors / ${Number(summary.warningCount || 0)} warnings`;
  }
  if (receipt?.format === "junit") {
    return `${Number(summary.testCount || 0)} tests / ${Number(summary.failureCount || 0)} failures / ${Number(summary.errorCount || 0)} errors`;
  }
  if (receipt?.format === "lcov") {
    return `${Number(summary.lineHitCount || 0)} of ${Number(summary.lineFoundCount || 0)} lines covered`;
  }
  return "Aggregate receipt";
}

function renderExternalEvidence(receipts = []) {
  state.externalEvidence = firstArray(receipts).filter(
    (receipt) =>
      receipt?.profile === "runrail-external-evidence-v1" &&
      receipt?.boundaries?.authority === "none" &&
      receipt?.boundaries?.verdictChanged === false
  );
  text(
    document.querySelector("#external-evidence-count"),
    state.externalEvidence.length
  );
  const list = document.querySelector("#external-evidence-receipts");
  list.replaceChildren();
  if (state.externalEvidence.length === 0) {
    const empty = document.createElement("p");
    empty.className = "empty-copy";
    text(
      empty,
      "No external evidence receipts are attached to this review."
    );
    list.append(empty);
  } else {
    for (const receipt of state.externalEvidence) {
      const row = document.createElement("article");
      const copy = document.createElement("div");
      const title = document.createElement("strong");
      const detail = document.createElement("small");
      const checksum = document.createElement("code");
      row.className = "external-evidence-receipt";
      text(title, `${String(receipt.format || "").toUpperCase()} / external`);
      text(
        detail,
        `${externalEvidenceSummary(receipt)}. Aggregate only; verdict unchanged.`
      );
      text(
        checksum,
        String(receipt.checksumSha256 || "").slice(0, 12)
      );
      copy.append(title, detail);
      row.append(copy, checksum);
      list.append(row);
    }
  }
  text(
    externalEvidenceProgress,
    state.reviewId
      ? state.externalEvidence.length > 0
        ? `${state.externalEvidence.length} checksum-bound external receipt(s). Imported evidence remains non-authoritative.`
        : "Choose bounded evidence created for this exact candidate revision."
      : "Run a review before importing external evidence."
  );
  unlockWorkflow();
}

function resetOutcomeLedger({ locked = false } = {}) {
  state.outcomeLedger = null;
  text(
    document.querySelector("#outcome-ledger-count"),
    locked ? "Locked" : "0"
  );
  text(document.querySelector("#outcome-sample-size"), 0);
  text(document.querySelector("#outcome-agent-count"), 0);
  text(document.querySelector("#outcome-ready-count"), 0);
  text(document.querySelector("#outcome-evidence-rate"), "-");
  const list = document.querySelector("#outcome-agent-list");
  list.replaceChildren();
  const empty = document.createElement("p");
  empty.className = "empty-copy";
  text(
    empty,
    locked
      ? "Agent Outcome Ledger requires Pro or higher."
      : "No verified agent outcomes are recorded for this repository."
  );
  list.append(empty);
  text(
    outcomeLedgerProgress,
    locked
      ? "Agent Outcome Ledger requires Pro and a verified rerun."
      : state.repoId
        ? "Complete a verified rerun to record a repository-local outcome."
        : "Select a reviewed repository to load its local outcomes."
  );
}

function renderOutcomeLedger(payload) {
  const summary = payload?.summary || payload;
  if (
    summary?.artifactType !== "runrail-agent-outcome-summary" ||
    summary?.profile !== "runrail-agent-outcome-ledger-v1" ||
    summary?.boundaries?.repositoryLocal !== true ||
    summary?.boundaries?.verifiedRerunsOnly !== true ||
    summary?.boundaries?.globalModelScore !== false ||
    summary?.boundaries?.agentQualityClaim !== false ||
    summary?.boundaries?.authority !== "none"
  ) {
    throw new LocalApiError("The Agent Outcome Ledger response is invalid.", {
      code: "desktop-outcome-ledger-invalid"
    });
  }
  state.outcomeLedger = summary;
  const agents = firstArray(summary.agents);
  const sampleSize = Number(summary.sampleSize || 0);
  const readyCount = agents.reduce(
    (total, row) => total + Number(row?.readyOutcomeCount || 0),
    0
  );
  const evidenceCount = agents.reduce(
    (total, row) =>
      total +
      Number(row?.sampleSize || 0) *
        Number(row?.evidenceCompletionRate || 0),
    0
  );
  const evidenceRate = sampleSize > 0 ? evidenceCount / sampleSize : null;
  text(document.querySelector("#outcome-ledger-count"), `${sampleSize} local`);
  text(document.querySelector("#outcome-sample-size"), sampleSize);
  text(document.querySelector("#outcome-agent-count"), agents.length);
  text(document.querySelector("#outcome-ready-count"), readyCount);
  text(
    document.querySelector("#outcome-evidence-rate"),
    evidenceRate === null ? "-" : `${Math.round(evidenceRate * 100)}%`
  );

  const list = document.querySelector("#outcome-agent-list");
  list.replaceChildren();
  if (agents.length === 0) {
    const empty = document.createElement("p");
    empty.className = "empty-copy";
    text(
      empty,
      "No verified agent outcomes are recorded for this repository."
    );
    list.append(empty);
  } else {
    for (const row of agents) {
      const item = document.createElement("article");
      const copy = document.createElement("div");
      const title = document.createElement("strong");
      const detail = document.createElement("small");
      const readiness = document.createElement("code");
      const revisions = document.createElement("code");
      item.className = "outcome-agent-row";
      text(title, titleCase(row.agentId));
      text(
        detail,
        `${Number(row.sampleSize || 0)} repository-local sample${Number(row.sampleSize || 0) === 1 ? "" : "s"} / ${titleCase(row.uncertainty || "insufficient-sample")}`
      );
      text(
        readiness,
        row.readyOutcomeRate === null
          ? "Ready -"
          : `Ready ${Math.round(Number(row.readyOutcomeRate) * 100)}%`
      );
      text(
        revisions,
        row.averageRevisionsToReady === null
          ? "Revisions -"
          : `${Number(row.averageRevisionsToReady).toFixed(2)} revisions`
      );
      copy.append(title, detail);
      item.append(copy, readiness, revisions);
      list.append(item);
    }
  }
  text(
    outcomeLedgerProgress,
    sampleSize > 0
      ? `${sampleSize} verified rerun outcome${sampleSize === 1 ? "" : "s"} recorded locally. These observations are not a global model score or an agent-quality claim.`
      : "Complete a verified rerun to record a repository-local outcome."
  );
  unlockWorkflow();
}

async function refreshOutcomeLedger({ announce = true } = {}) {
  if (!state.outcomeLedgerAvailable) {
    resetOutcomeLedger({ locked: true });
    unlockWorkflow();
    return false;
  }
  if (!state.repoId) {
    resetOutcomeLedger();
    unlockWorkflow();
    return false;
  }
  text(outcomeLedgerProgress, "Loading verified repository-local outcomes...");
  try {
    const payload = await optionalApi("/api/outcomes/list", {
      repoId: state.repoId
    });
    if (!payload) {
      resetOutcomeLedger();
      return false;
    }
    renderOutcomeLedger(payload);
    return true;
  } catch (error) {
    resetOutcomeLedger();
    text(
      outcomeLedgerProgress,
      "Agent Outcome Ledger was not loaded. No review evidence changed."
    );
    if (announce) showToast(error.message);
    return false;
  } finally {
    unlockWorkflow();
  }
}

function resetProductMetrics() {
  state.productMetrics = null;
  text(document.querySelector("#product-metrics-count"), "Local");
  text(document.querySelector("#metrics-loop-count"), 0);
  text(document.querySelector("#metrics-repo-count"), 0);
  text(document.querySelector("#metrics-loop-rate"), 0);
  text(document.querySelector("#metrics-upload-state"), "Off");
  text(
    productMetricsProgress,
    "No local metrics summary is available. Review evidence is unaffected."
  );
  renderToday();
}

function renderProductMetrics(payload) {
  const summary = payload?.summary;
  if (
    summary?.artifactType !== "runrail-product-metrics-summary" ||
    summary?.profile !== "runrail-product-metrics-v1" ||
    summary?.northStar?.metric !==
      "completed-assurance-loops-per-active-repository-per-week" ||
    summary?.upload?.available !== false ||
    summary?.upload?.enabled !== false ||
    summary?.upload?.consentRequired !== true ||
    summary?.upload?.repositoryFingerprintIncluded !== false ||
    summary?.upload?.operationBindingIncluded !== false ||
    summary?.boundaries?.localEventLedger !== true ||
    summary?.boundaries?.aggregateRepositoryIdentityFree !== true ||
    summary?.boundaries?.telemetryDefaultOff !== true ||
    summary?.boundaries?.uploadImplemented !== false ||
    summary?.boundaries?.authority !== "none" ||
    payload?.boundaries?.rawEventsReturned !== false ||
    payload?.boundaries?.repositoryFingerprintReturned !== false ||
    payload?.boundaries?.uploadAvailable !== false ||
    payload?.boundaries?.networkUsed !== false
  ) {
    throw new LocalApiError("The local product metrics response is invalid.", {
      code: "desktop-product-metrics-invalid"
    });
  }
  state.productMetrics = summary;
  const loops = Number(summary.northStar.completedAssuranceLoopCount || 0);
  const repositories = Number(summary.northStar.activeRepositoryCount || 0);
  const rate = Number(summary.northStar.loopsPerActiveRepository || 0);
  const eventCount = Object.values(summary.weeklyEventCounts || {}).reduce(
    (total, value) => total + Number(value || 0),
    0
  );
  text(document.querySelector("#product-metrics-count"), `${eventCount} local`);
  text(document.querySelector("#metrics-loop-count"), loops);
  text(document.querySelector("#metrics-repo-count"), repositories);
  text(
    document.querySelector("#metrics-loop-rate"),
    Number.isInteger(rate) ? rate : rate.toFixed(2)
  );
  text(document.querySelector("#metrics-upload-state"), "Off");
  text(
    productMetricsProgress,
    payload?.integrity?.healthy === true
      ? `This week: ${loops} completed assurance loop${loops === 1 ? "" : "s"} across ${repositories} active local repositor${repositories === 1 ? "y" : "ies"}.`
      : "The local summary loaded, but one or more metric writes failed. Review evidence remains authoritative."
  );
  renderToday();
}

async function refreshProductMetrics({ announce = true } = {}) {
  text(productMetricsProgress, "Refreshing local assurance activity...");
  try {
    const payload = await optionalApi("/api/metrics/summary", {});
    if (!payload) {
      resetProductMetrics();
      return false;
    }
    renderProductMetrics(payload);
    return true;
  } catch (error) {
    resetProductMetrics();
    if (announce) showToast(error.message);
    return false;
  } finally {
    unlockWorkflow();
  }
}

function renderAssurance(payload) {
  const assurance = payload?.assurance || payload || {};
  const packet = assurance.packet || {};
  const result = assurance.result || null;
  state.assurance = assurance;
  if (result) state.assuranceBriefCopied = false;
  state.assuranceAgentBrief = firstText(packet.agentBrief);
  document.querySelector("#assurance-section").open = true;
  text(
    document.querySelector("#assurance-packet-path"),
    firstText(assurance.briefPath, assurance.packetPath) ||
      "Source-free packet stored locally."
  );
  text(
    document.querySelector("#assurance-result-path"),
    firstText(assurance.reviewPath, assurance.resultPath) ||
      "Rerun after a revision to create the result."
  );

  const summary = result?.summary || {};
  text(document.querySelector("#assurance-resolved"), Number(summary.resolvedCount || 0));
  text(document.querySelector("#assurance-remaining"), Number(summary.remainingCount || 0));
  text(document.querySelector("#assurance-new"), Number(summary.newCount || 0));
  text(
    document.querySelector("#assurance-reintroduced"),
    Number(summary.reintroducedCount || 0)
  );
  const objectiveCount = firstArray(packet.objectives).length;
  const status = firstText(result?.status);
  if (status) {
    text(
      document.querySelector("#assurance-status"),
      `${titleCase(status)} / authority none`
    );
    text(
      document.querySelector("#assurance-section-count"),
      status === "ready-for-human-decision"
        ? "Ready for decision"
        : status === "blocked"
          ? "Blocked"
          : "Needs correction"
    );
    text(
      document.querySelector("#assurance-title"),
      status === "ready-for-human-decision"
        ? "The revision closed the deterministic correction loop."
        : status === "blocked"
          ? "The revision cannot be assessed on the same verified basis."
          : "The next correction pass is precisely scoped."
    );
    const coverage = result.currentEvidence || {};
    text(
      document.querySelector("#assurance-summary"),
      status === "ready-for-human-decision"
        ? "Required findings are resolved and current Review Coverage is complete. Project tests, correctness, and merge approval remain external."
        : coverage.coverageVerified
          ? "Runrail verified current coverage and classified every high- or medium-severity finding without executing or applying the revision."
          : "A verified current Review Coverage artifact is still required before Runrail can report ready for human decision."
    );
  } else {
    text(document.querySelector("#assurance-status"), "Packet ready / authority none");
    text(
      document.querySelector("#assurance-section-count"),
      `${objectiveCount} objective${objectiveCount === 1 ? "" : "s"}`
    );
    text(
      document.querySelector("#assurance-title"),
      objectiveCount > 0
        ? "The correction brief is ready for any coding agent."
        : "No high- or medium-severity correction objective remains."
    );
    text(
      document.querySelector("#assurance-summary"),
      "The packet contains fixed product-authored objectives and checksums, not repository identity, source, paths, refs, commits, or execution authority."
    );
  }

  const actions = document.querySelector("#assurance-actions");
  actions.replaceChildren();
  const rows = result?.topActions || firstArray(packet.objectives).map(
    (objective) => ({
      label: objective.findingId,
      detail: objective.summary
    })
  );
  for (const [index, action] of firstArray(rows).entries()) {
    const row = document.createElement("li");
    const rank = document.createElement("span");
    const content = document.createElement("div");
    const heading = document.createElement("strong");
    const detail = document.createElement("p");
    text(rank, index + 1);
    text(heading, firstText(action?.label, action?.findingId) || "Assurance step");
    text(detail, firstText(action?.detail, action?.summary) || "Inspect this bounded assurance step.");
    content.append(heading, detail);
    row.append(rank, content);
    actions.append(row);
  }
  renderToday();
}

function renderRevision(result) {
  state.revision = result;
  document.querySelector("#view-revision").open = true;
  const revision = result?.revision || result || {};
  const delta = revision.delta || revision;
  if (revision.coverage || delta.coverage) {
    renderCoverage(revision.coverage || delta.coverage);
  }
  const relationship = firstText(
    delta.relationship?.type,
    delta.relationship,
    revision.relationship
  ) || "Unreported";
  const comparable = delta.policyBasis?.comparable === true ||
    delta.policyComparable === true;
  const carried = Number(
    delta.attention?.carriedForwardCount ??
    revision.carriedForwardCount ??
    delta.carriedForwardCount ??
    0
  );
  const attention = Number(
    delta.attention?.currentAttentionRequiredCount ??
    revision.currentAttentionRequiredCount ??
    delta.currentAttentionRequiredCount ??
    0
  );
  const added = Number(
    delta.findings?.addedCount ??
    revision.addedFindingCount ??
    delta.addedFindingCount ??
    0
  );
  const resolved = Number(
    delta.findings?.resolvedCount ??
    revision.resolvedFindingCount ??
    delta.resolvedFindingCount ??
    0
  );

  text(document.querySelector("#revision-result .eyebrow"), "Re-review Map ready / authority none");
  text(document.querySelector("#revision-relationship"), relationship);
  text(document.querySelector("#revision-policy"), comparable ? "Comparable" : "Reconfirm");
  text(document.querySelector("#revision-carried"), carried);
  text(document.querySelector("#revision-attention"), attention);
  text(document.querySelector("#revision-added"), added);
  text(document.querySelector("#revision-resolved"), resolved);
  text(
    document.querySelector("#revision-artifact-path"),
    firstText(revision.outputRoot, revision.deltaPath, delta.outputRoot, delta.deltaPath) ||
      "Local artifact path unavailable."
  );
  text(
    document.querySelector("#revision-section-count"),
    `${attention} require attention`
  );
  text(document.querySelector("#revision-result h2"), "Your deterministic re-review map is ready.");
  text(
    document.querySelector("#revision-result > div > p:last-child"),
    comparable
      ? "The baseline review-contract basis is comparable. Exact unique hunk attention was carried; every other current hunk remains in the review plan."
      : "The baseline review-contract basis changed. Reconfirm policy before interpreting priority or attention continuity."
  );

  const actions = document.querySelector("#revision-actions");
  actions.replaceChildren();
  for (const [index, action] of firstArray(delta.nextActions, revision.nextActions).entries()) {
    const row = document.createElement("li");
    const rank = document.createElement("span");
    const content = document.createElement("div");
    const title = document.createElement("strong");
    const reason = document.createElement("p");
    text(rank, action?.rank ?? index + 1);
    text(title, firstText(action?.label, action?.title) || "Review step");
    text(reason, firstText(action?.reason, action?.detail) || "Inspect this bounded review step.");
    content.append(title, reason);
    row.append(rank, content);
    actions.append(row);
  }
}

function actionTarget(action) {
  const combined = [
    action?.candidateId,
    action?.id,
    action?.label,
    action?.title,
    action?.reason
  ].filter(Boolean).join(" ").toLowerCase();
  if (combined.includes("hunk") || combined.includes("attention")) return "#hunk-section";
  if (combined.includes("file") || combined.includes("patch")) return "#files-section";
  if (
    combined.includes("finding") ||
    combined.includes("security") ||
    combined.includes("contract") ||
    combined.includes("preflight")
  ) {
    return "#findings-section";
  }
  if (combined.includes("revision") || combined.includes("recheck")) return "#view-revision";
  return "#focus-section";
}

function fallbackActions(verdict) {
  if (verdict === "blocked") {
    return [
      { label: "Inspect deterministic findings", reason: "Start with the boundary that stopped the preflight." },
      { label: "Revise the candidate branch", reason: "Make source changes outside Runrail." },
      { label: "Rerun the local review", reason: "Create fresh evidence for the updated candidate." }
    ];
  }
  if (verdict === "needs-attention") {
    return [
      { label: "Resolve flagged review items", reason: "Record attention without treating it as approval." },
      { label: "Run approved project tests", reason: "Run project checks outside Runrail." },
      { label: "Make the human decision", reason: "Evidence informs but never replaces the decision." }
    ];
  }
  return [
    { label: "Inspect the changed files", reason: "Confirm the candidate matches the intended scope." },
    { label: "Run approved project tests", reason: "Project tests are not executed by Runrail." },
    { label: "Make the human decision", reason: "Merge readiness remains a human responsibility." }
  ];
}

function renderTopActions(result, verdict, focusItems) {
  const actions = firstArray(
    result?.topActions,
    result?.verdict?.topActions,
    result?.session?.topActions,
    focusItems
  ).slice(0, 3);
  const visibleActions = actions.length > 0 ? actions : fallbackActions(verdict);
  const list = document.querySelector("#top-action-list");
  list.replaceChildren();

  for (const [index, actionValue] of visibleActions.slice(0, 3).entries()) {
    const action = typeof actionValue === "string"
      ? { label: actionValue }
      : actionValue || {};
    const row = document.createElement("li");
    const rank = document.createElement("span");
    const content = document.createElement("div");
    const heading = document.createElement("strong");
    const detail = document.createElement("p");
    const open = document.createElement("button");
    const targetSelector = actionTarget(action);
    const target = document.querySelector(targetSelector);

    text(rank, action.rank ?? index + 1);
    text(heading, firstText(action.label, action.title, action.action) || "Review step");
    text(detail, firstText(action.reason, action.detail, action.summary) || "Inspect this bounded review step.");
    content.append(heading, detail);

    open.className = "text-button action-open";
    open.type = "button";
    open.title = "Open review section";
    open.setAttribute("aria-label", "Open related review section");
    open.append(makeIcon("chevron"));
    open.addEventListener("click", () => {
      if (target instanceof HTMLDetailsElement) target.open = true;
      target?.scrollIntoView({ block: "center", behavior: "smooth" });
    });
    row.append(rank, content, open);
    list.append(row);
  }
}

function renderFocus(focusItems) {
  const list = document.querySelector("#focus-list");
  list.replaceChildren();
  for (const [index, focusItem] of focusItems.entries()) {
    const item = document.createElement("li");
    const rank = document.createElement("em");
    const content = document.createElement("div");
    const heading = document.createElement("strong");
    const detail = document.createElement("p");
    text(rank, focusItem?.rank ?? index + 1);
    text(heading, firstText(focusItem?.label, focusItem?.title) || "Review step");
    text(detail, firstText(focusItem?.reason, focusItem?.detail) || "Inspect the local audit before deciding.");
    content.append(heading, detail);
    item.append(rank, content);
    list.append(item);
  }
  if (focusItems.length === 0) {
    const item = document.createElement("li");
    const content = document.createElement("div");
    const heading = document.createElement("strong");
    const detail = document.createElement("p");
    text(heading, "Review Focus unavailable");
    text(detail, "Inspect the deterministic findings and run your approved project checks.");
    content.append(heading, detail);
    item.append(content);
    list.append(item);
  }
}

function dispositionOptions(currentStatus) {
  const options = [
    ["", "Choose disposition"],
    ["useful", "Useful"],
    ["not-relevant", "Not relevant"],
    ["accepted-exception", "Accepted exception"]
  ];
  if (currentStatus && !options.some(([value]) => value === currentStatus)) {
    options.unshift([currentStatus, titleCase(currentStatus)]);
  }
  return options;
}

async function saveDisposition(form, findingId) {
  if (!state.reviewId) {
    showToast("This finding does not have a Desktop 2.0 review session ID.");
    return;
  }
  const button = form.querySelector("button");
  const progress = form.querySelector(".disposition-status");
  const status = form.querySelector('[name="status"]').value;
  const reason = form.querySelector('[name="reason"]').value.trim();
  const owner = form.querySelector('[name="owner"]').value.trim();
  const expiresAt = form.querySelector('[name="expiresAt"]').value;
  if (!status) {
    showToast("Choose useful, not relevant, or accepted exception.");
    return;
  }
  if (
    status === "accepted-exception" &&
    (!reason || !owner || !expiresAt)
  ) {
    showToast("Accepted exceptions require a reason, owner, and expiry.");
    return;
  }
  button.disabled = true;
  text(progress, "Saving local disposition...");
  try {
    const result = await optionalApi("/api/review/disposition", {
      reviewId: state.reviewId,
      findingId,
      status,
      reason,
      owner,
      expiresAt
    });
    if (!result) {
      text(progress, "Disposition storage is unavailable in this Desktop package.");
      return;
    }
    text(progress, "Disposition saved locally. It does not approve or apply source.");
    const returned = result.disposition || result.finding?.disposition;
    const returnedKind = firstText(returned?.kind, returned?.status);
    if (returnedKind) form.querySelector('[name="status"]').value = returnedKind;
    const embeddedHistory = extractHistory(result);
    if (embeddedHistory.length > 0) setHistory(embeddedHistory);
    if (result.verdict) {
      const verdict = normalizeVerdict(result);
      const copy = verdictCopy(verdict);
      const panel = document.querySelector("#verdict-panel");
      panel.dataset.verdict = verdict;
      text(document.querySelector("#verdict-label"), copy.label);
      text(document.querySelector("#evidence-title"), copy.title);
      text(document.querySelector("#evidence-summary"), copy.summary);
      renderTopActions(result, verdict, []);
      state.review = { ...state.review, verdict: result.verdict };
    }
    if (state.proofGraph) {
      resetProofGraph();
      text(
        proofGraphProgress,
        "Disposition changed. Build ProofGraph again to verify the updated append-only history."
      );
    }
    await refreshTrustProfile({ announce: false });
    await refreshOutcomeLedger({ announce: false });
  } catch (error) {
    text(progress, "Disposition was not saved. No source change occurred.");
    showToast(error.message);
  } finally {
    button.disabled = false;
  }
}

function renderFindings(findings) {
  const list = document.querySelector("#finding-list");
  list.replaceChildren();
  for (const [index, finding] of findings.entries()) {
    const item = document.createElement("li");
    const severity = document.createElement("em");
    const content = document.createElement("div");
    const heading = document.createElement("strong");
    const detail = document.createElement("p");
    const severityValue = firstText(finding?.severity, "info").toLowerCase();
    const findingId = firstText(finding?.findingId, finding?.id, `finding-${index + 1}`);
    severity.classList.add(`is-${severityValue}`);
    content.className = "finding-content";
    text(severity, severityValue);
    text(heading, firstText(finding?.title, finding?.label) || "Review finding");
    text(detail, firstText(finding?.detail, finding?.reason) || "Inspect the local audit for details.");
    content.append(heading, detail);

    const disposition = finding?.disposition || {};
    const form = document.createElement("form");
    form.className = "disposition-form";
    form.setAttribute("aria-label", `Disposition for finding ${index + 1}`);

    const statusLabel = document.createElement("label");
    const statusCaption = document.createElement("span");
    const statusSelect = document.createElement("select");
    statusSelect.name = "status";
    text(statusCaption, "Status");
    const dispositionKind = firstText(disposition.kind, disposition.status);
    for (const [value, label] of dispositionOptions(dispositionKind)) {
      const option = document.createElement("option");
      option.value = value;
      option.selected = value === dispositionKind;
      text(option, label);
      statusSelect.append(option);
    }
    statusLabel.append(statusCaption, statusSelect);

    const reasonLabel = document.createElement("label");
    const reasonCaption = document.createElement("span");
    const reasonInput = document.createElement("input");
    reasonInput.name = "reason";
    reasonInput.type = "text";
    reasonInput.maxLength = 500;
    reasonInput.placeholder = "Reason";
    reasonInput.value = firstText(disposition.reason);
    text(reasonCaption, "Reason");
    reasonLabel.append(reasonCaption, reasonInput);

    const ownerLabel = document.createElement("label");
    const ownerCaption = document.createElement("span");
    const ownerInput = document.createElement("input");
    ownerInput.name = "owner";
    ownerInput.type = "text";
    ownerInput.maxLength = 120;
    ownerInput.placeholder = "Reviewer";
    ownerInput.value = firstText(disposition.owner);
    text(ownerCaption, "Owner");
    ownerLabel.append(ownerCaption, ownerInput);

    const expiresLabel = document.createElement("label");
    const expiresCaption = document.createElement("span");
    const expiresInput = document.createElement("input");
    expiresInput.name = "expiresAt";
    expiresInput.type = "date";
    expiresInput.value = firstText(disposition.expiresAt).slice(0, 10);
    text(expiresCaption, "Expires");
    expiresLabel.append(expiresCaption, expiresInput);

    const save = document.createElement("button");
    save.className = "secondary-button";
    save.type = "submit";
    save.disabled = !state.reviewId;
    text(save, "Save");

    const progress = document.createElement("p");
    progress.className = "disposition-status";
    text(
      progress,
      state.reviewId
        ? "Disposition is local review context, not approval."
        : "Requires a Desktop 2.0 review session."
    );
    form.append(statusLabel, reasonLabel, ownerLabel, expiresLabel, save, progress);
    form.addEventListener("submit", (event) => {
      event.preventDefault();
      void saveDisposition(form, findingId);
    });

    content.append(form);
    item.append(severity, content);
    list.append(item);
  }

  if (findings.length === 0) {
    const item = document.createElement("li");
    const content = document.createElement("div");
    const heading = document.createElement("strong");
    const detail = document.createElement("p");
    text(heading, "No deterministic finding recorded");
    text(detail, "Project tests and human review are still required.");
    content.append(heading, detail);
    item.append(content);
    list.append(item);
  }
}

function renderFiles(files) {
  const list = document.querySelector("#file-list");
  list.replaceChildren();
  for (const file of files) {
    const item = document.createElement("li");
    const path = typeof file === "string"
      ? file
      : firstText(file?.path, file?.file, file?.name);
    const status = typeof file === "object" && file !== null
      ? firstText(file.status, file.changeType)
      : "";
    text(item, [status, path].filter(Boolean).join("  ") || "Changed file path unavailable");
    list.append(item);
  }
  if (files.length === 0) {
    const item = document.createElement("li");
    text(item, "No changed file path was reported.");
    list.append(item);
  }
}

function renderEvidenceLists(requiredEvidence, verifierChecks, report) {
  const requiredList = document.querySelector("#required-evidence-list");
  requiredList.replaceChildren();
  for (const evidence of requiredEvidence) {
    const item = document.createElement("li");
    const value = typeof evidence === "string"
      ? evidence
      : firstText(evidence?.label, evidence?.id, evidence?.name);
    text(item, String(value || "Evidence item").replaceAll("-", " "));
    requiredList.append(item);
  }
  if (requiredEvidence.length === 0) {
    const item = document.createElement("li");
    text(item, "No contract evidence label was reported.");
    requiredList.append(item);
  }

  const verifierList = document.querySelector("#verifier-check-list");
  verifierList.replaceChildren();
  const unsupportedSourceCount = Number(
    report?.verifier?.unsupportedChangedSourceFileCount || 0
  );
  if (unsupportedSourceCount > 0) {
    const item = document.createElement("li");
    text(item, `unsupported source  blocked  ${unsupportedSourceCount} file(s) not parsed by this verifier`);
    verifierList.append(item);
  }
  for (const check of verifierChecks) {
    const item = document.createElement("li");
    text(
      item,
      `${check?.language || "unknown"}  ${check?.status || "unreported"}  ${Number(check?.fileCount || 0)} file(s)`
    );
    verifierList.append(item);
  }
  if (verifierChecks.length === 0 && unsupportedSourceCount === 0) {
    const item = document.createElement("li");
    text(
      item,
      `${report?.verifier?.profile || "verifier"}  ${report?.verifier?.passed ? "passed" : "not run"}`
    );
    verifierList.append(item);
  }
}

function extractHistory(payload) {
  if (Array.isArray(payload)) return payload;
  return firstArray(
    payload?.history,
    payload?.items,
    payload?.reviews,
    payload?.history?.items,
    payload?.history?.reviews,
    payload?.session?.history
  );
}

function historyIdentity(item) {
  return firstText(
    item?.reviewId,
    item?.id,
    item?.session?.reviewId,
    item?.session?.id,
    item?.auditPath,
    item?.reportPath
  );
}

function historyCandidate(item) {
  return firstText(
    item?.candidate,
    item?.candidateRef,
    item?.refs?.candidate,
    item?.session?.candidate,
    item?.report?.source?.candidateRef,
    "Candidate review"
  );
}

function historyBase(item) {
  return firstText(
    item?.base,
    item?.baseRef,
    item?.refs?.base,
    item?.session?.base,
    item?.report?.source?.baseRef
  );
}

function historyTimestamp(item) {
  return firstText(
    item?.createdAt,
    item?.updatedAt,
    item?.timestamp,
    item?.session?.createdAt,
    item?.report?.createdAt
  );
}

function latestHistoryItem() {
  let latest = null;
  let latestTimestamp = Number.NEGATIVE_INFINITY;
  for (const item of state.history) {
    const timestamp = Date.parse(historyTimestamp(item));
    const comparable = Number.isFinite(timestamp)
      ? timestamp
      : Number.NEGATIVE_INFINITY;
    if (!latest || comparable > latestTimestamp) {
      latest = item;
      latestTimestamp = comparable;
    }
  }
  return latest;
}

function historyTone(verdict) {
  if (verdict === "blocked") return "blocked";
  if (verdict === "needs-attention") return "attention";
  return "ready";
}

async function selectHistoryItem(item) {
  const reviewId = historyIdentity(item);
  const candidate = historyCandidate(item);
  const base = historyBase(item);
  if (candidate && candidate !== "Candidate review") {
    document.querySelector("#candidate-input").value = candidate;
  }
  if (base) document.querySelector("#base-input").value = base;
  state.reviewId = reviewId;
  state.auditPath = firstText(item?.auditPath, item?.reportPath);
  state.passportPath = firstText(item?.passportPath);
  state.lastReviewInput = {
    repo: firstText(item?.repo, item?.repositoryPath, document.querySelector("#repo-input").value),
    base: base || document.querySelector("#base-input").value,
    candidate: candidate === "Candidate review"
      ? document.querySelector("#candidate-input").value
      : candidate
  };
  unlockWorkflow();
  renderHistory();
  if (!reviewId) {
    const embedded = item?.result || item?.review;
    if (embedded && typeof embedded === "object") {
      renderReview(embedded);
      return;
    }
    text(passportProgress, "This history item cannot be reopened.");
    return;
  }
  text(passportProgress, "Opening checksum-verified local review evidence...");
  try {
    const opened = await api(
      "/api/review/open",
      { reviewId },
      { acceptReviewResult: true }
    );
    const local = opened?.session?.local || {};
    if (local.repositoryPath) {
      document.querySelector("#repo-input").value = local.repositoryPath;
    }
    if (local.baseRef) document.querySelector("#base-input").value = local.baseRef;
    if (local.candidateRef) {
      document.querySelector("#candidate-input").value = local.candidateRef;
    }
    state.lastReviewInput = {
      repo: firstText(local.repositoryPath, state.lastReviewInput?.repo),
      base: firstText(local.baseRef, base, state.lastReviewInput?.base),
      candidate: firstText(
        local.candidateRef,
        candidate === "Candidate review" ? "" : candidate,
        state.lastReviewInput?.candidate
      )
    };
    renderReview(opened);
    await refreshOutcomeLedger({ announce: false });
    text(
      passportProgress,
      "Exact audit, coverage, assurance, and passport evidence reopened locally."
    );
  } catch (error) {
    text(
      passportProgress,
      "Stored evidence could not be verified. No stale review was displayed."
    );
    showToast(error.message);
  }
}

function renderHistory() {
  const query = historyFilter.value.trim().toLowerCase();
  const visible = state.history.filter((item) => {
    if (!query) return true;
    return [
      historyCandidate(item),
      historyBase(item),
      firstText(item?.repo, item?.repositoryPath),
      normalizeVerdict(item)
    ].join(" ").toLowerCase().includes(query);
  });
  text(document.querySelector("#history-count"), state.history.length);

  const rail = document.querySelector("#history-list");
  const detail = document.querySelector("#history-detail-list");
  rail.replaceChildren();
  detail.replaceChildren();

  if (visible.length === 0) {
    const railEmpty = document.createElement("p");
    const detailEmpty = document.createElement("p");
    railEmpty.className = "empty-copy";
    detailEmpty.className = "empty-copy";
    text(railEmpty, query ? "No review matches this filter." : "No local reviews yet.");
    text(detailEmpty, query ? "No review matches this filter." : "No local review history is available.");
    rail.append(railEmpty);
    detail.append(detailEmpty);
    renderToday();
    return;
  }

  for (const item of visible) {
    const verdict = normalizeVerdict(item);
    const tone = historyTone(verdict);
    const candidate = historyCandidate(item);
    const base = historyBase(item);
    const timestamp = historyTimestamp(item);
    const id = historyIdentity(item);

    const button = document.createElement("button");
    const dot = document.createElement("span");
    const copy = document.createElement("span");
    const candidateNode = document.createElement("strong");
    const statusNode = document.createElement("small");
    const timeNode = document.createElement("span");
    button.className = "history-item";
    if (id && id === state.reviewId) button.classList.add("is-selected");
    button.type = "button";
    dot.className = `history-status is-${tone}`;
    timeNode.className = "history-time";
    text(candidateNode, candidate);
    text(statusNode, verdictCopy(verdict).label);
    text(timeNode, formatTime(timestamp));
    copy.append(candidateNode, statusNode);
    button.append(dot, copy, timeNode);
    button.addEventListener("click", () => {
      void selectHistoryItem(item);
    });
    rail.append(button);

    const row = document.createElement("div");
    const rowCandidate = document.createElement("strong");
    const rowBase = document.createElement("span");
    const rowTime = document.createElement("span");
    const rowVerdict = document.createElement("span");
    row.className = "history-detail-row";
    rowVerdict.className = `history-verdict is-${tone}`;
    text(rowCandidate, candidate);
    text(rowBase, base ? `Base ${base}` : "Base not reported");
    text(rowTime, formatDateTime(timestamp) || "Time not reported");
    text(rowVerdict, verdictCopy(verdict).label);
    row.append(rowCandidate, rowBase, rowTime, rowVerdict);
    detail.append(row);
  }
  renderToday();
}

function setHistory(items) {
  state.history = Array.isArray(items) ? items.slice(0, 200) : [];
  renderHistory();
}

function upsertReviewHistory(result) {
  const session = result?.session || {};
  const synthetic = {
    reviewId: state.reviewId,
    auditPath: state.auditPath,
    passportPath: state.passportPath,
    candidate: firstText(
      session.candidate,
      result?.report?.source?.candidateRef,
      state.lastReviewInput?.candidate,
      result?.guidedSample ? "Guided sample" : ""
    ),
    base: firstText(
      session.base,
      result?.report?.source?.baseRef,
      state.lastReviewInput?.base
    ),
    repo: firstText(session.repo, state.lastReviewInput?.repo),
    createdAt: firstText(session.createdAt, result?.createdAt) || new Date().toISOString(),
    verdict: result?.verdict || normalizeVerdict(result),
    result
  };
  const id = historyIdentity(synthetic);
  state.history = [
    synthetic,
    ...state.history.filter((item) => !id || historyIdentity(item) !== id)
  ].slice(0, 200);
  renderHistory();
}

function repositoryReadinessHandoffText(receipt, handoff) {
  return [
    "Runrail Review-Ready Brief",
    `Status: ${receipt.status}`,
    `Objective: ${handoff.objective}`,
    `Done when: ${handoff.doneWhen}`,
    `Return: ${handoff.returnStep}`,
    "Guardrails:",
    ...handoff.guardrails.map((entry) => `- ${entry}`),
    `Readiness receipt: ${handoff.sourceReceiptChecksumSha256}`,
    `Brief checksum: ${handoff.checksumSha256}`,
    "Boundary: path-free local guidance only; no source, diff, network, project test, source mutation, or execution authority."
  ].join("\n");
}

async function copyReadinessBrief() {
  const brief = state.readinessHandoffText;
  if (!brief || typeof navigator.clipboard?.writeText !== "function") {
    showToast("The path-free Review-Ready Brief is not available to copy in this browser.");
    return false;
  }
  try {
    await navigator.clipboard.writeText(brief);
    state.readinessBriefCopied = true;
    renderToday();
    showToast("Path-free Review-Ready Brief copied. Complete it in any coding agent, then inspect again.");
    return true;
  } catch {
    showToast("The browser refused clipboard access. No repository data was sent or stored.");
    return false;
  }
}

function renderRepositoryReadiness(receipt, handoff) {
  const container = document.querySelector("#readiness-receipt");
  const validStatuses = new Set([
    "blocked",
    "setup-needed",
    "selection-required",
    "ready-to-review"
  ]);
  const valid =
    receipt?.artifactType === "runrail-repository-readiness-receipt" &&
    receipt?.profile === "runrail-repository-readiness-v1" &&
    validStatuses.has(receipt?.status) &&
    typeof receipt?.label === "string" &&
    Array.isArray(receipt?.checks) &&
    receipt.checks.length === 5 &&
    typeof receipt?.nextAction?.label === "string" &&
    /^[a-f0-9]{64}$/u.test(String(receipt?.checksumSha256 || "")) &&
    receipt?.boundaries?.localOnly === true &&
    receipt?.boundaries?.stored === false &&
    receipt?.boundaries?.pathIncluded === false &&
    receipt?.boundaries?.branchIncluded === false &&
    receipt?.boundaries?.commitIncluded === false &&
    receipt?.boundaries?.sourceIncluded === false &&
    receipt?.boundaries?.diffIncluded === false &&
    receipt?.boundaries?.networkUsed === false &&
    receipt?.boundaries?.projectTestsExecuted === false &&
    receipt?.boundaries?.sourceMutation === false &&
    receipt?.boundaries?.authority === "none" &&
    handoff?.artifactType === "runrail-repository-readiness-handoff" &&
    handoff?.profile === "runrail-repository-readiness-handoff-v1" &&
    handoff?.status === receipt?.status &&
    handoff?.actionId === receipt?.nextAction?.id &&
    typeof handoff?.title === "string" &&
    typeof handoff?.objective === "string" &&
    typeof handoff?.doneWhen === "string" &&
    handoff?.returnStep === "Inspect the repository again in Runrail." &&
    Array.isArray(handoff?.guardrails) &&
    handoff.guardrails.length === 3 &&
    handoff?.sourceReceiptChecksumSha256 === receipt?.checksumSha256 &&
    /^[a-f0-9]{64}$/u.test(String(handoff?.checksumSha256 || "")) &&
    handoff?.boundaries?.localOnly === true &&
    handoff?.boundaries?.stored === false &&
    handoff?.boundaries?.pathIncluded === false &&
    handoff?.boundaries?.branchIncluded === false &&
    handoff?.boundaries?.commitIncluded === false &&
    handoff?.boundaries?.sourceIncluded === false &&
    handoff?.boundaries?.diffIncluded === false &&
    handoff?.boundaries?.networkUsed === false &&
    handoff?.boundaries?.projectTestsExecuted === false &&
    handoff?.boundaries?.sourceMutation === false &&
    handoff?.boundaries?.authority === "none";
  if (!valid) {
    state.readiness = null;
    state.readinessHandoff = null;
    state.readinessHandoffText = "";
    state.readinessBriefCopied = false;
    copyReadinessButton.disabled = true;
    downloadReadinessButton.disabled = true;
    container.hidden = true;
    return;
  }

  state.readiness = receipt;
  state.readinessHandoff = handoff;
  state.readinessHandoffText = repositoryReadinessHandoffText(receipt, handoff);
  state.readinessBriefCopied = false;
  container.hidden = false;
  container.className = `readiness-receipt is-${receipt.status}`;
  text(document.querySelector("#readiness-title"), receipt.label);
  const candidateCount = Number(receipt.summary?.candidateCount || 0);
  const summary = receipt.status === "ready-to-review"
    ? "All setup checks passed. One local candidate is ready for a bounded review."
    : receipt.status === "selection-required"
      ? `${candidateCount} local candidates are available. Choose one to continue.`
      : receipt.status === "blocked"
        ? "Runrail found a local condition that must be resolved before review."
        : "Repository setup needs one more step before review.";
  text(document.querySelector("#readiness-summary"), summary);
  text(document.querySelector("#readiness-next-action"), receipt.nextAction.label);
  text(document.querySelector("#readiness-guidance-title"), handoff.title);
  text(document.querySelector("#readiness-guidance-objective"), handoff.objective);
  text(document.querySelector("#readiness-guidance-done"), `Done when: ${handoff.doneWhen}`);
  const checkList = document.querySelector("#readiness-checks");
  checkList.replaceChildren();
  for (const check of receipt.checks) {
    const item = document.createElement("li");
    item.className = `readiness-check is-${check.status}`;
    const label = document.createElement("span");
    label.className = "readiness-check-label";
    text(label, check.label);
    const detail = document.createElement("p");
    text(detail, check.detail);
    item.append(label, detail);
    checkList.append(item);
  }
  copyReadinessButton.disabled = false;
  downloadReadinessButton.disabled = false;
}

function renderInspection(payload) {
  const inspection = payload?.inspection || payload?.repository || payload || {};
  const previewReadinessOnly =
    payload?.boundaries?.previewReadinessOnly === true ||
    state.previewReadinessOnly;
  state.inspection = inspection;
  renderRepositoryReadiness(inspection.readiness, inspection.readinessHandoff);
  const nextRepoId = firstText(
    inspection.repoId,
    inspection.id,
    payload?.repoId,
    payload?.session?.repoId
  );
  const repositoryChanged = Boolean(
    state.repoId &&
    nextRepoId &&
    state.repoId !== nextRepoId
  );
  if (repositoryChanged) {
    state.trustProfile = null;
    state.tournament = null;
    state.proofGraph = null;
    text(document.querySelector("#trust-cadence"), "Not loaded");
    text(document.querySelector("#trust-policy"), "Not loaded");
    text(document.querySelector("#trust-verdict-changes"), "0");
    text(document.querySelector("#trust-attention-closed"), "0");
    text(document.querySelector("#trust-expired-exceptions"), "0");
    text(document.querySelector("#trust-passport-continuity"), "0 / 0");
    document.querySelector("#weekly-report-summary").hidden = true;
    resetTournamentResult();
    resetProofGraph();
  }
  state.repoId = nextRepoId;
  const repoPath = firstText(
    inspection.repo,
    inspection.path,
    inspection.repositoryPath,
    document.querySelector("#repo-input").value
  );
  const stackValue = inspection.stack;
  const stack = Array.isArray(stackValue)
    ? stackValue.map((item) => typeof item === "string" ? item : firstText(item?.name, item?.id)).filter(Boolean).join(", ")
    : typeof stackValue === "object" && stackValue !== null
      ? firstText(stackValue.label, stackValue.name, stackValue.primary)
      : firstText(stackValue);
  const contract = inspection.contract || {};
  const contractText = firstText(
    typeof contract === "string" ? contract : "",
    contract.label,
    contract.status,
    contract.source,
    inspection.contractStatus
  );

  text(document.querySelector("#repository-name"), pathName(repoPath));
  text(document.querySelector("#repository-stack"), stack || "Local Git repository");
  text(
    document.querySelector("#repository-contract"),
    contractText
      ? `Base-owned contract: ${titleCase(contractText)}.`
      : "No base-owned contract metadata reported."
  );

  const baseCandidates = firstArray(
    inspection.baseCandidates,
    inspection.bases,
    payload?.baseCandidates
  );
  const candidateBranches = firstArray(
    inspection.candidateBranches,
    inspection.candidates,
    payload?.candidateBranches
  );
  populateOptions("#base-options", baseCandidates);
  populateOptions("#candidate-options", candidateBranches);
  renderTournamentCandidates(candidateBranches);

  const defaultBase = firstText(inspection.defaultBase, payload?.defaultBase);
  const baseInput = document.querySelector("#base-input");
  if (defaultBase && (!baseInput.value || baseInput.value === "main")) {
    baseInput.value = defaultBase;
  }
  const candidateInput = document.querySelector("#candidate-input");
  if (!candidateInput.value && candidateBranches.length === 1) {
    candidateInput.value = referenceValue(candidateBranches[0]);
  }

  text(
    document.querySelector("#inspection-summary"),
    [
      defaultBase ? `Default base ${defaultBase}.` : "Base remains editable.",
      `${candidateBranches.length} candidate branch${candidateBranches.length === 1 ? "" : "es"} reported.`,
      previewReadinessOnly
        ? state.candidateReviewAvailable
          ? "Preview readiness confirmed. One real local candidate review is available."
          : "Read-only readiness confirmed. The one preview review has been used."
        : "Metadata only."
    ].join(" ")
  );

  const embeddedHistory = extractHistory(payload);
  if (embeddedHistory.length > 0) setHistory(embeddedHistory);
  renderToday();
}

function referenceValue(item) {
  return typeof item === "string"
    ? item
    : firstText(item?.ref, item?.name, item?.branch, item?.id);
}

function populateOptions(selector, values) {
  const datalist = document.querySelector(selector);
  datalist.replaceChildren();
  const seen = new Set();
  for (const value of values) {
    const ref = referenceValue(value);
    if (!ref || seen.has(ref)) continue;
    seen.add(ref);
    const option = document.createElement("option");
    option.value = ref;
    datalist.append(option);
  }
}

function selectedTournamentCandidates() {
  return [...document.querySelectorAll(
    '#tournament-candidate-list input[type="checkbox"]:checked'
  )].map((input) => input.value);
}

function updateTournamentControlState() {
  const selectedCount = selectedTournamentCandidates().length;
  tournamentButton.disabled =
    state.repositoryInspectionInProgress ||
    !state.tournamentAvailable ||
    selectedCount < 2 ||
    selectedCount > 5;
  text(
    document.querySelector("#tournament-section-count"),
    state.tournamentAvailable
      ? selectedCount > 0
        ? `${selectedCount} selected`
        : "Pro"
      : "Locked"
  );
}

function renderTournamentCandidates(values) {
  const fieldset = document.querySelector("#tournament-candidate-list");
  const legend = document.createElement("legend");
  text(legend, "Local candidate branches");
  fieldset.replaceChildren(legend);
  const candidates = [];
  const seen = new Set();
  for (const value of values) {
    const ref = referenceValue(value);
    if (!ref || seen.has(ref)) continue;
    seen.add(ref);
    candidates.push({
      ref,
      aheadBy: Number(value?.aheadBy || 0)
    });
  }
  if (candidates.length < 2) {
    const empty = document.createElement("p");
    empty.className = "empty-copy";
    text(
      empty,
      candidates.length === 1
        ? "Only one local branch is ahead of the confirmed base."
        : "Inspect a clean repository to discover tournament candidates."
    );
    fieldset.append(empty);
    updateTournamentControlState();
    return;
  }
  candidates.forEach((candidate, index) => {
    const label = document.createElement("label");
    const input = document.createElement("input");
    const copy = document.createElement("span");
    const name = document.createElement("strong");
    const detail = document.createElement("small");
    label.className = "tournament-option";
    input.type = "checkbox";
    input.value = candidate.ref;
    input.checked = index < 2;
    text(name, candidate.ref);
    text(
      detail,
      candidate.aheadBy > 0
        ? `${candidate.aheadBy} commit${candidate.aheadBy === 1 ? "" : "s"} ahead of base`
        : "Discovered ahead of the confirmed base"
    );
    copy.append(name, detail);
    label.append(input, copy);
    input.addEventListener("change", () => {
      if (selectedTournamentCandidates().length > 5) {
        input.checked = false;
        showToast("Candidate Tournament accepts at most five branches.");
      }
      updateTournamentControlState();
    });
    fieldset.append(label);
  });
  updateTournamentControlState();
}

function resetTournamentResult() {
  state.tournament = null;
  const result = document.querySelector("#tournament-result");
  result.replaceChildren();
  const intro = document.createElement("div");
  const eyebrow = document.createElement("p");
  const heading = document.createElement("h2");
  const detail = document.createElement("p");
  const ranking = document.createElement("ol");
  const receipt = document.createElement("div");
  const receiptTitle = document.createElement("strong");
  const receiptDetail = document.createElement("span");
  const artifact = document.createElement("div");
  const artifactLabel = document.createElement("span");
  const artifactPath = document.createElement("code");
  eyebrow.className = "eyebrow";
  ranking.className = "tournament-ranking";
  ranking.id = "tournament-ranking";
  receipt.className = "tournament-receipt";
  receipt.id = "tournament-receipt";
  artifact.className = "artifact-path tournament-artifact";
  artifactPath.id = "tournament-artifact-path";
  text(eyebrow, "No tournament yet");
  text(heading, "Compare review attention, not code quality.");
  text(
    detail,
    "Every candidate uses the same base-owned contract and safe-static verifier. The final choice remains human."
  );
  text(artifactLabel, "Path-free tournament artifact");
  text(artifactPath, "No Candidate Tournament path yet.");
  text(receiptTitle, "Why review this candidate first");
  text(
    receiptDetail,
    "Run a Tournament to create an equal-basis review-order receipt."
  );
  receipt.append(receiptTitle, receiptDetail);
  intro.append(eyebrow, heading, detail);
  artifact.append(artifactLabel, artifactPath);
  result.append(intro, receipt, ranking, artifact);
}

function renderTournament(payload) {
  const tournament = payload?.tournament;
  const candidates = firstArray(payload?.candidates);
  const receiptData = tournament?.reviewOrderReceipt;
  const comparisonBasis = tournament?.comparisonBasis;
  if (
    !tournament ||
    tournament.artifactType !== "runrail-candidate-tournament" ||
    candidates.length < 2 ||
    candidates.length > 5 ||
    (
      tournament.schemaVersion >= 2 &&
      (
        receiptData?.reviewOrderOnly !== true ||
        receiptData?.codeQualityClaim !== false ||
        receiptData?.mergeRecommendation !== false ||
        comparisonBasis?.equalContractBudget !== true ||
        comparisonBasis?.equalVerifierBudget !== true
      )
    )
  ) {
    throw new LocalApiError("The local Candidate Tournament response is invalid.", {
      code: "desktop-tournament-invalid"
    });
  }
  state.tournament = tournament;
  const result = document.querySelector("#tournament-result");
  result.replaceChildren();
  const intro = document.createElement("div");
  const eyebrow = document.createElement("p");
  const heading = document.createElement("h2");
  const detail = document.createElement("p");
  eyebrow.className = "eyebrow";
  text(eyebrow, `${candidates.length} candidates / human review order`);
  text(heading, "Review the highest-attention candidate first.");
  text(
    detail,
    "This ranking compares deterministic evidence only. It does not identify the best implementation or approve a merge."
  );
  intro.append(eyebrow, heading, detail);
  const receipt = document.createElement("div");
  const receiptTitle = document.createElement("strong");
  const receiptDetail = document.createElement("span");
  const firstCandidate = candidates.find(
    (candidate) => candidate.candidateId === receiptData?.candidateId
  ) || candidates[0];
  receipt.className = "tournament-receipt";
  receipt.id = "tournament-receipt";
  text(
    receiptTitle,
    firstText(receiptData?.title) || "Why review this candidate first"
  );
  text(
    receiptDetail,
    receiptData
      ? `${firstCandidate?.displayRef || firstCandidate?.candidateId} is first because ${firstArray(receiptData.reasonIds).map(titleCase).join(", ")}. Every candidate used the same confirmed base, contract budget, and safe-static verifier budget.`
      : "This legacy Tournament ranks review order on its verified deterministic basis."
  );
  receipt.append(receiptTitle, receiptDetail);
  const ranking = document.createElement("ol");
  ranking.className = "tournament-ranking";
  ranking.id = "tournament-ranking";
  for (const candidate of candidates) {
    const row = document.createElement("li");
    const rank = document.createElement("span");
    const copy = document.createElement("div");
    const name = document.createElement("strong");
    const metrics = document.createElement("small");
    const select = document.createElement("button");
    rank.className = "tournament-rank";
    select.className = "text-button";
    select.type = "button";
    text(rank, candidate.rank);
    text(name, candidate.displayRef || candidate.candidateId);
    text(
      metrics,
      [
        `${titleCase(candidate.metrics?.riskLevel || "unreported")} risk`,
        `${Number(candidate.metrics?.hunkAttentionRequiredCount || 0)} hunk attention`,
        firstArray(candidate.priorityReasons).map(titleCase).join(", ")
      ].filter(Boolean).join(" / ")
    );
    text(select, "Review");
    select.addEventListener("click", () => {
      document.querySelector("#candidate-input").value =
        candidate.displayRef || "";
      activateView("review");
      showToast("Candidate selected for the regular human-controlled review loop.");
    });
    copy.append(name, metrics);
    row.append(rank, copy, select);
    ranking.append(row);
  }
  const artifact = document.createElement("div");
  const artifactLabel = document.createElement("span");
  const artifactPath = document.createElement("code");
  artifact.className = "artifact-path tournament-artifact";
  artifactPath.id = "tournament-artifact-path";
  text(artifactLabel, "Path-free tournament artifact");
  text(artifactPath, payload?.tournamentPath || "Local path unavailable.");
  artifact.append(artifactLabel, artifactPath);
  result.append(intro, receipt, ranking, artifact);
  text(
    document.querySelector("#tournament-section-count"),
    `${candidates.length} ranked`
  );
  text(
    tournamentProgress,
    "Review order rebuilt deterministically. No source changed and no candidate was selected automatically."
  );
}

function resetProofGraph() {
  state.proofGraph = null;
  for (const [selector, value] of [
    ["#proofgraph-revisions", "0"],
    ["#proofgraph-findings", "0"],
    ["#proofgraph-hunks", "0"],
    ["#proofgraph-rules", "0"],
    ["#proofgraph-dispositions", "0"],
    ["#proofgraph-hidden", "0"]
  ]) {
    text(document.querySelector(selector), value);
  }
  const list = document.querySelector("#proofgraph-edge-list");
  list.replaceChildren();
  const row = document.createElement("li");
  const title = document.createElement("strong");
  const detail = document.createElement("span");
  text(title, "No graph loaded");
  text(detail, "Run a review first.");
  row.append(title, detail);
  list.append(row);
  text(
    document.querySelector("#proofgraph-artifact-path"),
    "No ProofGraph built yet."
  );
}

function renderProofGraph(payload) {
  const graph = payload?.graph;
  if (!graph || graph.artifactType !== "runrail-proof-graph") {
    throw new LocalApiError("The local ProofGraph response is invalid.", {
      code: "desktop-proofgraph-invalid"
    });
  }
  state.proofGraph = graph;
  const summary = graph.summary || {};
  text(document.querySelector("#proofgraph-revisions"), Number(summary.revisionCount || 0));
  text(document.querySelector("#proofgraph-findings"), Number(summary.findingCount || 0));
  text(document.querySelector("#proofgraph-hunks"), Number(summary.hunkCount || 0));
  text(document.querySelector("#proofgraph-rules"), Number(summary.ruleCount || 0));
  text(
    document.querySelector("#proofgraph-dispositions"),
    Number(summary.dispositionCount || 0)
  );
  text(
    document.querySelector("#proofgraph-hidden"),
    Number(graph.noiseControls?.hiddenFindingCount || 0)
  );
  text(
    document.querySelector("#proofgraph-section-count"),
    `${Number(summary.nodeCount || 0)} nodes`
  );
  const edgeCounts = new Map();
  for (const edge of firstArray(graph.edges)) {
    edgeCounts.set(edge.type, (edgeCounts.get(edge.type) || 0) + 1);
  }
  const list = document.querySelector("#proofgraph-edge-list");
  list.replaceChildren();
  for (const [type, count] of [...edgeCounts.entries()].sort((left, right) =>
    left[0].localeCompare(right[0])
  )) {
    const row = document.createElement("li");
    const title = document.createElement("strong");
    const detail = document.createElement("span");
    text(title, titleCase(type));
    text(detail, `${count} verified relationship${count === 1 ? "" : "s"}`);
    row.append(title, detail);
    list.append(row);
  }
  text(
    document.querySelector("#proofgraph-artifact-path"),
    "Stored in local Runrail history; no local path is returned."
  );
  text(
    proofGraphProgress,
    `${Number(summary.findingCount || 0)} finding occurrence${Number(summary.findingCount || 0) === 1 ? "" : "s"} remain visible. No opaque suppression or policy rewrite occurred.`
  );
}

async function refreshHistory({ announceUnsupported = false } = {}) {
  historyRefreshButton.disabled = true;
  try {
    const payload = await optionalApi(
      "/api/history/list",
      state.repoId ? { repoId: state.repoId } : {}
    );
    if (!payload) {
      if (announceUnsupported) {
        showToast("Local history is unavailable in this Desktop package.");
      }
      return false;
    }
    setHistory(extractHistory(payload));
    return true;
  } catch (error) {
    showToast(error.message);
    return false;
  } finally {
    historyRefreshButton.disabled = false;
  }
}

function renderTrustProfile(payload) {
  const profile = payload?.trustProfile || payload?.profile || payload;
  if (!profile || profile.artifactType !== "runrail-repository-trust-profile") {
    throw new LocalApiError("The local Trust Profile response is invalid.", {
      code: "desktop-trust-profile-invalid"
    });
  }
  state.trustProfile = profile;
  const cadence = profile.reviewCadence || {};
  const continuity = profile.continuity || {};
  const policyFingerprint = firstText(profile.policy?.currentFingerprint);
  text(
    document.querySelector("#trust-cadence"),
    `${titleCase(cadence.label || "new")} / ${Number(cadence.reviewCount || 0)} review${Number(cadence.reviewCount || 0) === 1 ? "" : "s"}`
  );
  text(
    document.querySelector("#trust-policy"),
    policyFingerprint
      ? `${policyFingerprint.slice(0, 12)} / base-owned`
      : "Evidence gap / base-owned"
  );
  text(
    document.querySelector("#trust-verdict-changes"),
    Number(profile.trends?.verdictChangeCount || 0)
  );
  text(
    document.querySelector("#trust-attention-closed"),
    Number(profile.trends?.attentionItemClosedCount || 0)
  );
  text(
    document.querySelector("#trust-expired-exceptions"),
    Number(profile.dispositions?.expiredExceptionCount || 0)
  );
  text(
    document.querySelector("#trust-passport-continuity"),
    `${Number(continuity.passportChecksumCount || 0)} / ${Number(continuity.reviewCount || 0)}`
  );
  text(
    document.querySelector("#trust-section-count"),
    `${Number(cadence.reviewCount || 0)} local`
  );
  text(
    document.querySelector("#trust-summary"),
    [
      `Preferred local base: ${firstText(profile.preferredBase) || "not reported"}.`,
      `${Number(profile.policy?.contractChangeCount || 0)} contract fingerprint change${Number(profile.policy?.contractChangeCount || 0) === 1 ? "" : "s"}.`,
      "Recommendations are advisory and never rewrite policy."
    ].join(" ")
  );
  text(
    trustProgress,
    `Trust Profile verified locally at ${formatDateTime(profile.generatedAt)}. Telemetry remains off.`
  );
  renderToday();
}

function renderWeeklyReport(payload) {
  const report = payload?.weeklyReport || payload?.report || payload;
  if (!report || report.artifactType !== "runrail-weekly-engineering-report") {
    throw new LocalApiError("The local weekly report response is invalid.", {
      code: "desktop-weekly-report-invalid"
    });
  }
  const summary = report.summary || {};
  const panel = document.querySelector("#weekly-report-summary");
  panel.hidden = false;
  text(
    document.querySelector("#weekly-report-title"),
    `${Number(summary.reviewedCandidateCount || 0)} reviewed candidate${Number(summary.reviewedCandidateCount || 0) === 1 ? "" : "s"} / ${Number(summary.unresolvedAttentionItemCount || 0)} unresolved attention`
  );
  text(
    document.querySelector("#weekly-report-detail"),
    [
      `${Number(summary.attentionItemClosedCount || 0)} attention item${Number(summary.attentionItemClosedCount || 0) === 1 ? "" : "s"} closed.`,
      `${Number(summary.expiredExceptionCount || 0)} expired exception${Number(summary.expiredExceptionCount || 0) === 1 ? "" : "s"}.`,
      `${Number(summary.evidenceContinuityGapCount || 0)} evidence continuity gap${Number(summary.evidenceContinuityGapCount || 0) === 1 ? "" : "s"}.`
    ].join(" ")
  );
  text(
    trustProgress,
    `Weekly report verified locally. Checksum ${String(report.checksumSha256 || "").slice(0, 12)}.`
  );
}

async function refreshTrustProfile({ weekly = false, announce = true } = {}) {
  if (!state.trustProfilesAvailable || !state.repoId) return false;
  trustRefreshButton.disabled = true;
  weeklyReportButton.disabled = true;
  text(
    trustProgress,
    weekly
      ? "Building a source-free local weekly report..."
      : "Rebuilding the local Repository Trust Profile..."
  );
  try {
    const payload = await api(
      weekly ? "/api/report/weekly" : "/api/trust/profile",
      { repoId: state.repoId }
    );
    if (weekly) renderWeeklyReport(payload);
    else renderTrustProfile(payload);
    return true;
  } catch (error) {
    text(
      trustProgress,
      "Trust evidence was not loaded. No policy or source file changed."
    );
    if (announce) showToast(error.message);
    return false;
  } finally {
    unlockWorkflow();
  }
}

async function inspectRepository({ announceUnsupported = true } = {}) {
  if (state.repositoryInspectionInProgress) return false;
  const repo = document.querySelector("#repo-input").value.trim();
  if (!repo) {
    showToast("Enter an absolute local repository path first.");
    return false;
  }
  state.repositoryInspectionInProgress = true;
  inspectRepoButton.disabled = true;
  updateTournamentControlState();
  renderRepositoryReadiness(null);
  renderToday();
  text(document.querySelector("#inspection-summary"), "Inspecting local repository metadata...");
  try {
    const payload = await optionalApi("/api/repository/inspect", { repo });
    if (!payload) {
      text(
        document.querySelector("#inspection-summary"),
        "Repository inspection is unavailable in this package. References remain editable."
      );
      if (announceUnsupported) {
        showToast("Repository inspection is unavailable; you can still enter base and candidate references.");
      }
      return false;
    }
    renderInspection(payload);
    if (payload?.boundaries?.previewReadinessOnly === true) {
      setHistory([]);
      return true;
    }
    if (extractHistory(payload).length === 0) await refreshHistory();
    await refreshTrustProfile({ announce: false });
    await refreshOutcomeLedger({ announce: false });
    return true;
  } catch (error) {
    text(document.querySelector("#inspection-summary"), "Repository inspection stopped.");
    showToast(error.message);
    return false;
  } finally {
    state.repositoryInspectionInProgress = false;
    inspectRepoButton.disabled = false;
    updateTournamentControlState();
    renderToday();
  }
}

function renderReview(result) {
  const previousReviewId = state.reviewId;
  const previousRepoId = state.repoId;
  state.review = result;
  const session = result?.session || {};
  const report = result?.report || result?.audit || session.report || {};
  const focus = result?.focus || session.focus || {};
  const verdict = normalizeVerdict(result);
  const verdictDetails = typeof result?.verdict === "object" && result.verdict !== null
    ? result.verdict
    : {};
  const copy = verdictCopy(verdict);
  const focusItems = firstArray(
    focus.items,
    result?.focusItems,
    session.focus?.items
  );
  const findings = firstArray(
    report.decision?.findings,
    result?.findings,
    verdictDetails.findings,
    session.findings
  );
  const files = firstArray(
    report.policy?.changedFiles,
    result?.files,
    result?.changedFiles,
    session.changedFiles
  );
  const requiredEvidence = firstArray(
    report.reviewContract?.requiredEvidence,
    result?.requiredEvidence,
    session.requiredEvidence
  );
  const verifierChecks = firstArray(
    report.verifier?.checks,
    result?.checks,
    session.checks
  );
  const coverage = result?.coverage || session.coverage || null;

  state.auditPath = firstText(
    result?.reportPath,
    result?.auditPath,
    session.reportPath,
    session.auditPath,
    report.path
  );
  state.reviewId = firstText(
    result?.reviewId,
    session.reviewId,
    session.id,
    result?.id
  );
  state.repoId = firstText(
    result?.repoId,
    session.repoId,
    session.repoFingerprint,
    state.repoId
  );
  if (
    previousRepoId &&
    state.repoId &&
    previousRepoId !== state.repoId
  ) {
    resetOutcomeLedger({
      locked: !state.outcomeLedgerAvailable
    });
  }
  state.passportPath = firstText(
    result?.passportPath,
    result?.passport?.path,
    session.passportPath
  );
  state.guidedSample = result?.guidedSample === true || session.guidedSample === true;
  if (previousReviewId && state.reviewId !== previousReviewId) {
    state.diff = null;
    resetProofGraph();
    resetAssurance();
  }
  if (session.local?.repositoryPath) {
    document.querySelector("#repo-input").value = session.local.repositoryPath;
    document.querySelector("#base-input").value = firstText(
      session.local.baseRef,
      document.querySelector("#base-input").value
    );
    document.querySelector("#candidate-input").value = firstText(
      session.local.candidateRef,
      document.querySelector("#candidate-input").value
    );
  }

  resetRevision();
  renderCoverage(coverage);
  renderFocus(focusItems);
  renderFindings(findings);
  renderFiles(files);
  renderEvidenceLists(requiredEvidence, verifierChecks, report);
  renderTopActions(result, verdict, focusItems);

  const panel = document.querySelector("#verdict-panel");
  panel.classList.remove("is-empty");
  panel.dataset.verdict = verdict;
  text(document.querySelector("#verdict-label"), firstText(verdictDetails.label) || copy.label);
  text(document.querySelector("#evidence-title"), firstText(verdictDetails.title) || copy.title);
  text(
    document.querySelector("#evidence-summary"),
    firstText(verdictDetails.summary, verdictDetails.detail, result?.summary) || copy.summary
  );

  const preflightPassed = report.preflightPassed === true || (
    report.preflightPassed !== false &&
    result?.ok === true
  );
  setMetric(
    "#metric-preflight",
    preflightPassed ? "Passed" : "Blocked",
    preflightPassed ? "pass" : "blocked"
  );
  setMetric(
    "#metric-priority",
    titleCase(report.decision?.riskLevel || verdictDetails.priority || "Unreported"),
    verdict === "blocked" ? "blocked" : verdict === "needs-attention" ? "attention" : ""
  );
  const contractPassed = report.reviewContract?.passed === true;
  const contractValue = contractPassed
    ? (report.reviewContract?.source === "baseline-file" ? "Repository / passed" : "Built-in / passed")
    : report.reviewContract?.passed === false
      ? "Blocked"
      : "Unreported";
  setMetric(
    "#metric-contract",
    contractValue,
    contractPassed ? "pass" : report.reviewContract?.passed === false ? "blocked" : ""
  );
  const sourceUnchanged = report.source?.sourceCheckoutUnchanged === true;
  setMetric(
    "#metric-source",
    sourceUnchanged ? "Unchanged" : "Check required",
    sourceUnchanged ? "pass" : "attention"
  );
  text(document.querySelector("#finding-count"), findings.length);
  text(document.querySelector("#finding-section-count"), findings.length);
  text(document.querySelector("#file-count"), files.length);
  text(document.querySelector("#file-section-count"), files.length);
  text(document.querySelector("#evidence-count"), requiredEvidence.length);
  text(document.querySelector("#check-count"), verifierChecks.length);
  text(document.querySelector("#focus-count"), focusItems.length);
  text(
    document.querySelector("#artifact-path"),
    firstText(result?.outputRoot, session.outputRoot, state.auditPath) ||
      "Local artifact path unavailable."
  );
  text(
    passportProgress,
    state.passportPath
      ? `Passport ready: ${state.passportPath}`
      : "Review evidence is stored locally."
  );

  const evidenceContext = document.querySelector("#evidence-context");
  const baseFingerprint = String(
    report.source?.baseCommit || session.baseCommit || ""
  ).slice(0, 12);
  const contractFingerprint = String(
    report.reviewContract?.contractSha256 || session.contractSha256 || ""
  ).slice(0, 12);
  evidenceContext.hidden = !baseFingerprint && !state.guidedSample;
  text(
    evidenceContext,
    [
      state.guidedSample ? "Guided sample." : "Local repository.",
      baseFingerprint ? `Baseline ${baseFingerprint}.` : "",
      contractFingerprint ? `Contract ${contractFingerprint}.` : "",
      "Checksums identify content but do not authenticate origin."
    ].filter(Boolean).join(" ")
  );

  if (result?.inspection) renderInspection(result);
  const embeddedHistory = extractHistory(result);
  if (embeddedHistory.length > 0) setHistory(embeddedHistory);
  upsertReviewHistory(result);
  if (result?.revision || session.revision) renderRevision(result.revision || session.revision);
  if (result?.assurance || session.assurance) {
    renderAssurance(result.assurance || session.assurance);
  }
  renderExternalEvidence(
    firstArray(result?.externalEvidence, session.externalEvidence)
  );
  if (result?.advisory || session.advisory) renderAdvisory(result.advisory || session.advisory);

  unlockWorkflow();
  renderToday();
  activateView("evidence", { scroll: true });
}

function renderAdvisory(result) {
  const panel = document.querySelector("#advisory-result");
  panel.replaceChildren();
  const eyebrow = document.createElement("p");
  const heading = document.createElement("h2");
  const explanation = document.createElement("p");
  eyebrow.className = "eyebrow";
  text(
    eyebrow,
    result?.provider === "deepseek"
      ? "DeepSeek advisory / authority none"
      : "Runrail offline advisory / authority none"
  );
  text(
    heading,
    result?.abstained
      ? "The advisory abstained."
      : "Review these fixed next-step candidates."
  );
  text(
    explanation,
    result?.abstained
      ? "No fixed candidate met the advisory threshold. No action was executed."
      : "These are review suggestions only. A human still chooses and performs every next action."
  );
  panel.append(eyebrow, heading, explanation);

  const candidates = firstArray(result?.candidates, result?.items);
  if (candidates.length > 0) {
    const list = document.createElement("div");
    list.className = "candidate-list";
    for (const candidate of candidates) {
      const card = document.createElement("article");
      const id = document.createElement("strong");
      const detail = document.createElement("p");
      card.className = "candidate-card";
      text(id, firstText(candidate?.candidateId, candidate?.id) || "FIXED_CANDIDATE");
      text(
        detail,
        firstText(candidate?.reason, candidate?.rationale, candidate?.label) ||
          "Inspect this bounded review step."
      );
      card.append(id, detail);
      list.append(card);
    }
    panel.append(list);
  }
}

function reviewInput() {
  return {
    repo: document.querySelector("#repo-input").value,
    base: document.querySelector("#base-input").value,
    candidate: document.querySelector("#candidate-input").value
  };
}

async function runReview({ rerun = false } = {}) {
  if (!state.candidateReviewAvailable) {
    text(
      reviewProgress,
      state.previewReadinessOnly
        ? "The one public-preview review has been used. Enroll Starter or Pro for another review."
        : "Repository readiness is available. Candidate review requires Starter or Pro enrollment."
    );
    showToast(
      state.previewReadinessOnly
        ? "The one public-preview review has been used."
        : "Candidate review requires a Starter or Pro entitlement."
    );
    return;
  }
  reviewButton.disabled = true;
  sampleButton.disabled = true;
  rerunButton.disabled = true;
  text(reviewProgress, rerun ? "Rerunning bounded local review..." : "Running bounded local review...");
  try {
    let result = null;
    if (rerun && state.reviewId) {
      result = await optionalApi(
        "/api/review/rerun",
        { reviewId: state.reviewId },
        { acceptReviewResult: true }
      );
    }
    if (!result && rerun && state.guidedSample) {
      result = await api("/api/sample", {}, { acceptReviewResult: true });
    }
    if (!result) {
      state.lastReviewInput = rerun && state.lastReviewInput
        ? state.lastReviewInput
        : reviewInput();
      result = await api(
        "/api/review",
        state.lastReviewInput,
        { acceptReviewResult: true }
      );
    }
    if (result?.publicPreview?.remainingCandidateReviews === 0) {
      state.candidateReviewAvailable = false;
    }
    renderReview(result);
    await refreshTrustProfile({ announce: false });
    await refreshOutcomeLedger({ announce: false });
    await refreshProductMetrics({ announce: false });
    text(
      reviewProgress,
      result.ok === false
        ? "Review blocked with evidence. Source checkout unchanged."
        : "Review complete. Source checkout unchanged."
    );
  } catch (error) {
    text(reviewProgress, "Review stopped. No source apply was performed.");
    showToast(error.message);
  } finally {
    reviewButton.disabled = !state.candidateReviewAvailable;
    sampleButton.disabled = false;
    unlockWorkflow();
  }
}

reviewForm.addEventListener("submit", (event) => {
  event.preventDefault();
  state.lastReviewInput = reviewInput();
  state.guidedSample = false;
  state.assuranceBriefCopied = false;
  void runReview();
});

sampleButton.addEventListener("click", async () => {
  sampleButton.disabled = true;
  activationPrimaryAction.disabled = true;
  reviewButton.disabled = true;
  text(sampleProgress, "Creating and reviewing a disposable local fixture...");
  try {
    const result = await api("/api/sample", {}, { acceptReviewResult: true });
    state.lastReviewInput = null;
    renderReview(result);
    await refreshTrustProfile({ announce: false });
    await refreshOutcomeLedger({ announce: false });
    await refreshProductMetrics({ announce: false });
    text(
      sampleProgress,
      result.ok === false
        ? "Sample complete. Continue from Today to inspect the blocked evidence."
        : "Sample complete. Continue from Today to inspect the local evidence."
    );
    activateSurface("today");
  } catch (error) {
    text(sampleProgress, "Sample stopped. No source apply was performed.");
    showToast(error.message);
  } finally {
    sampleButton.disabled = false;
    reviewButton.disabled = !state.candidateReviewAvailable;
    unlockWorkflow();
  }
});

inspectRepoButton.addEventListener("click", () => {
  void inspectRepository();
});

copyReadinessButton.addEventListener("click", () => {
  void copyReadinessBrief();
});

downloadReadinessButton.addEventListener("click", () => {
  if (!state.readinessHandoffText || !state.readinessHandoff) {
    showToast("The path-free Review-Ready Brief is not available to download.");
    return;
  }
  const blob = new Blob([`${state.readinessHandoffText}\n`], {
    type: "text/plain;charset=utf-8"
  });
  const url = URL.createObjectURL(blob);
  const link = document.createElement("a");
  link.href = url;
  link.download = `RUNRAIL_REVIEW_READY_BRIEF_${state.readinessHandoff.checksumSha256.slice(0, 12)}.txt`;
  link.rel = "noopener";
  document.body.append(link);
  link.click();
  link.remove();
  setTimeout(() => URL.revokeObjectURL(url), 0);
  showToast("Path-free Review-Ready Brief downloaded. Complete the objective, then inspect again.");
});

readinessReinspectButton.addEventListener("click", () => {
  void inspectRepository();
});

document.querySelector("#repo-input").addEventListener("change", () => {
  if (document.querySelector("#repo-input").value.trim()) {
    void inspectRepository({ announceUnsupported: false });
  }
});

const nativeInvoke = window.__TAURI__?.core?.invoke;
const nativeListen = window.__TAURI__?.event?.listen;
state.nativeAvailable = typeof nativeInvoke === "function";
let nativeEnrollmentInFlight = false;

async function completeNativeEnrollmentHandoff(code) {
  if (nativeEnrollmentInFlight) return;
  if (!/^[A-Za-z0-9_-]{43}$/.test(String(code || ""))) {
    showToast("Runrail refused an invalid device enrollment handoff.");
    return;
  }
  nativeEnrollmentInFlight = true;
  try {
    showToast("Completing the approved device enrollment...");
    const result = await api("/api/license/enroll-handoff", { code });
    if (result?.enrollmentCompleted !== true || result?.handoffCodeConsumed !== true) {
      throw new LocalApiError("Runrail could not verify the device enrollment response.", {
        code: "desktop-enrollment-handoff-invalid"
      });
    }
    showToast("Device enrollment completed. Reloading verified access...");
    window.setTimeout(() => window.location.reload(), 250);
  } catch (error) {
    showToast(error instanceof Error ? error.message : "Runrail device enrollment was refused.");
  } finally {
    nativeEnrollmentInFlight = false;
  }
}

if (typeof nativeInvoke === "function") {
  const consumeQueuedHandoff = async () => {
    try {
      const code = await nativeInvoke("take_enrollment_handoff");
      if (typeof code === "string" && code) await completeNativeEnrollmentHandoff(code);
    } catch {
      showToast("Runrail could not read the native enrollment handoff.");
    }
  };
  if (typeof nativeListen === "function") {
    void nativeListen("runrail-enrollment-handoff", (event) => {
      void completeNativeEnrollmentHandoff(event?.payload);
    }).then(consumeQueuedHandoff, consumeQueuedHandoff);
  } else {
    void consumeQueuedHandoff();
  }
}

if (nativeRepoPicker && typeof nativeInvoke === "function") {
  nativeRepoPicker.hidden = false;
  nativeRepoPicker.addEventListener("click", async () => {
    nativeRepoPicker.disabled = true;
    try {
      const selected = await nativeInvoke("select_repository");
      if (typeof selected === "string" && selected) {
        const repoInput = document.querySelector("#repo-input");
        repoInput.value = selected;
        repoInput.dispatchEvent(new Event("change"));
      }
    } catch (error) {
      showToast(error instanceof Error ? error.message : "Runrail could not open that repository.");
    } finally {
      nativeRepoPicker.disabled = false;
    }
  });
}

historyRefreshButton.addEventListener("click", () => {
  void refreshHistory({ announceUnsupported: true });
});

productMetricsRefresh.addEventListener("click", () => {
  void refreshProductMetrics();
});

historyFilter.addEventListener("input", renderHistory);

trustRefreshButton.addEventListener("click", () => {
  void refreshTrustProfile();
});

weeklyReportButton.addEventListener("click", () => {
  void refreshTrustProfile({ weekly: true });
});

tournamentButton.addEventListener("click", async () => {
  if (!state.tournamentAvailable) {
    showToast("Candidate Tournament requires a Pro or higher entitlement.");
    return;
  }
  const candidates = selectedTournamentCandidates();
  if (candidates.length < 2 || candidates.length > 5) {
    showToast("Select two to five discovered local candidate branches.");
    return;
  }
  tournamentButton.disabled = true;
  text(
    tournamentProgress,
    `Reviewing ${candidates.length} frozen local candidate revisions with the same bounded verifier...`
  );
  try {
    const payload = await api("/api/tournament", {
      repo: document.querySelector("#repo-input").value,
      base: document.querySelector("#base-input").value,
      candidates
    });
    renderTournament(payload);
  } catch (error) {
    text(
      tournamentProgress,
      "Candidate Tournament stopped. No source change or automatic selection occurred."
    );
    showToast(error.message);
  } finally {
    updateTournamentControlState();
  }
});

proofGraphButton.addEventListener("click", async () => {
  if (!state.proofGraphAvailable) {
    showToast("ProofGraph requires a Pro or higher entitlement.");
    return;
  }
  if (!state.reviewId) {
    showToast("Run a local review before building its ProofGraph.");
    return;
  }
  proofGraphButton.disabled = true;
  text(
    proofGraphProgress,
    "Verifying local review lineage and building a path-free ProofGraph..."
  );
  try {
    const payload = await api("/api/review/proofgraph", {
      reviewId: state.reviewId
    });
    renderProofGraph(payload);
  } catch (error) {
    text(
      proofGraphProgress,
      "ProofGraph stopped. No finding was hidden and no policy changed."
    );
    showToast(error.message);
  } finally {
    unlockWorkflow();
  }
});

rerunButton.addEventListener("click", () => {
  void runReview({ rerun: true });
});

openEvidenceButton.addEventListener("click", () => {
  const evidence = document.querySelector(".evidence-details");
  const focus = document.querySelector("#focus-section");
  evidence.open = true;
  focus.open = true;
  document.querySelector("#evidence-sections").scrollIntoView({
    block: "start",
    behavior: "smooth"
  });
  text(passportProgress, "Evidence sections opened. All artifacts remain local.");
});

async function copyAgentAssuranceBrief() {
  if (!state.reviewId) {
    showToast("Run a candidate review before creating an Agent Assurance packet.");
    return;
  }
  copyAgentBriefButton.disabled = true;
  assuranceSectionButton.disabled = true;
  text(
    assuranceProgress,
    "Building a source-free correction packet from verified local evidence..."
  );
  try {
    const result = await api("/api/review/handoff", {
      reviewId: state.reviewId
    });
    renderAssurance(result);
    let copied = false;
    if (state.assuranceAgentBrief && navigator.clipboard?.writeText) {
      try {
        await navigator.clipboard.writeText(state.assuranceAgentBrief);
        copied = true;
      } catch {}
    }
    if (!copied && state.assuranceAgentBrief) {
      const field = document.createElement("textarea");
      field.value = state.assuranceAgentBrief;
      field.setAttribute("readonly", "");
      field.style.position = "fixed";
      field.style.opacity = "0";
      document.body.append(field);
      field.select();
      copied = document.execCommand("copy");
      field.remove();
    }
    text(
      assuranceProgress,
      copied
        ? "Source-free brief copied. Give it to any coding agent, revise the candidate, then rerun."
        : `Brief saved locally: ${firstText(result.briefPath, result.packetPath)}`
    );
    state.assuranceBriefCopied = true;
    renderToday();
  } catch (error) {
    text(
      assuranceProgress,
      "Agent Assurance stopped. No network, model, test, or source apply was used."
    );
    showToast(error.message);
  } finally {
    unlockWorkflow();
  }
}

copyAgentBriefButton.addEventListener("click", () => {
  void copyAgentAssuranceBrief();
});

assuranceSectionButton.addEventListener("click", () => {
  void copyAgentAssuranceBrief();
});

agentAdapterSelect.addEventListener("change", () => {
  agentLaunchConfirmed.checked = false;
  const adapter = selectedAgentAdapter();
  text(
    agentLaunchProgress,
    adapter?.mode === "copy"
      ? "Use Copy source-free brief, then paste it into any coding agent."
      : adapter?.launchable
        ? `${adapter.label} is ready for an explicit fixed interactive launch.`
        : `${adapter?.label || "This adapter"} is not safely launchable in the current terminal.`
  );
  updateAgentBridgeState();
});

agentLaunchConfirmed.addEventListener("change", updateAgentBridgeState);

externalEvidenceFile.addEventListener("change", unlockWorkflow);

outcomeRecordButton.addEventListener("click", async () => {
  const beforeReviewId = firstText(state.assurance?.beforeReviewId);
  if (
    !state.outcomeLedgerAvailable ||
    !beforeReviewId ||
    !state.reviewId ||
    !state.assurance?.result
  ) {
    showToast("Complete a verified Pro rerun before recording an agent outcome.");
    return;
  }
  outcomeRecordButton.disabled = true;
  text(
    outcomeLedgerProgress,
    "Verifying the rerun evidence and recording a source-free local outcome..."
  );
  try {
    const payload = await api("/api/outcomes/record", {
      beforeReviewId,
      currentReviewId: state.reviewId,
      agentId: outcomeAgentSelect.value
    });
    renderOutcomeLedger(payload);
    text(
      outcomeLedgerProgress,
      payload.created
        ? "Verified outcome recorded locally. It does not create a global model score or code-quality claim."
        : "This exact verified outcome was already recorded; no duplicate was created."
    );
  } catch (error) {
    text(
      outcomeLedgerProgress,
      "Outcome was not recorded. Existing review evidence remains unchanged."
    );
    showToast(error.message);
  } finally {
    unlockWorkflow();
  }
});

function arrayBufferToBase64(buffer) {
  const bytes = new Uint8Array(buffer);
  let binary = "";
  for (let offset = 0; offset < bytes.length; offset += 32 * 1024) {
    binary += String.fromCharCode(...bytes.subarray(offset, offset + 32 * 1024));
  }
  return btoa(binary);
}

async function sha256Hex(buffer) {
  const digest = await crypto.subtle.digest("SHA-256", buffer);
  return [...new Uint8Array(digest)]
    .map((byte) => byte.toString(16).padStart(2, "0"))
    .join("");
}

externalEvidenceImport.addEventListener("click", async () => {
  const file = externalEvidenceFile.files?.[0];
  if (!state.reviewId || !file) {
    showToast("Run a review and choose one bounded external evidence file first.");
    return;
  }
  if (file.size < 1 || file.size > 2 * 1024 * 1024) {
    showToast("External evidence must be between 1 byte and 2 MiB.");
    return;
  }
  externalEvidenceImport.disabled = true;
  externalEvidenceFile.disabled = true;
  text(
    externalEvidenceProgress,
    "Verifying checksum, candidate revision, parser limits, and path boundary..."
  );
  try {
    const content = await file.arrayBuffer();
    const payload = await api("/api/review/evidence/import", {
      reviewId: state.reviewId,
      format: externalEvidenceFormat.value,
      contentBase64: arrayBufferToBase64(content),
      sourceSha256: await sha256Hex(content)
    });
    renderExternalEvidence(payload.externalEvidence);
    text(
      externalEvidenceProgress,
      payload.created
        ? "External aggregate receipt attached. The deterministic verdict and Assurance result were unchanged."
        : "This exact external evidence receipt was already attached."
    );
    externalEvidenceFile.value = "";
  } catch (error) {
    text(
      externalEvidenceProgress,
      "External evidence was refused. No raw content was persisted and no verdict changed."
    );
    showToast(error.message);
  } finally {
    externalEvidenceFile.disabled = !state.reviewId;
    unlockWorkflow();
  }
});

agentLaunchButton.addEventListener("click", async () => {
  const adapter = selectedAgentAdapter();
  if (!adapter?.launchable || !state.reviewId || !state.assuranceBriefCopied) {
    showToast("Copy the verified brief and select a launchable fixed adapter first.");
    return;
  }
  if (!agentLaunchConfirmed.checked) {
    showToast("Confirm the fixed interactive agent launch first.");
    return;
  }
  agentLaunchButton.disabled = true;
  agentAdapterSelect.disabled = true;
  text(
    agentLaunchProgress,
    `${adapter.label} is running in the attached terminal. Runrail is not trusting or applying its result.`
  );
  try {
    const payload = await api("/api/agents/launch", {
      reviewId: state.reviewId,
      adapterId: adapter.adapterId,
      confirmed: true
    });
    state.agentLaunchReceipt = payload.receipt || null;
    text(
      agentLaunchProgress,
      payload.agentExitedSuccessfully
        ? `${adapter.label} exited. Verify the revised candidate with a fresh Runrail rerun.`
        : `${adapter.label} stopped or exited unsuccessfully. Inspect the repository and rerun only when ready.`
    );
    state.assuranceBriefCopied = true;
    renderToday();
  } catch (error) {
    text(
      agentLaunchProgress,
      "Agent launch stopped. No shell fallback, automatic apply, or trusted completion was used."
    );
    showToast(error.message);
  } finally {
    agentLaunchConfirmed.checked = false;
    agentAdapterSelect.disabled = false;
    updateAgentBridgeState();
  }
});

exportPassportButton.addEventListener("click", async () => {
  exportPassportButton.disabled = true;
  const signWithDevice =
    state.deviceSignedPassportsAvailable &&
    deviceSignPassport.checked;
  text(
    passportProgress,
    signWithDevice
      ? "Signing the path-free passport with this enrolled device key..."
      : "Exporting a checksum-only local review passport..."
  );
  try {
    let result = null;
    if (state.reviewId) {
      result = await optionalApi("/api/review/passport", {
        reviewId: state.reviewId,
        signWithDevice
      });
    }
    const path = firstText(
      result?.passportPath,
      result?.path,
      result?.artifactPath,
      result?.passport?.path,
      state.passportPath
    );
    if (!result && !path) {
      text(passportProgress, "Passport export is unavailable in this Desktop package.");
      return;
    }
    state.passportPath = path;
    text(
      passportProgress,
      path
        ? (
            signWithDevice
              ? `Device-signed passport exported locally: ${path}. This proves device-key possession only.`
              : `Checksum-only passport exported locally: ${path}`
          )
        : "Passport exported locally without a returned path."
    );
    await refreshTrustProfile({ announce: false });
    await refreshProductMetrics({ announce: false });
  } catch (error) {
    text(passportProgress, "Passport was not exported. No source change occurred.");
    showToast(error.message);
  } finally {
    unlockWorkflow();
  }
});

inspectDiffButton.addEventListener("click", async () => {
  if (!state.reviewId || !state.coverage) {
    showToast("Open a verified local review before inspecting its diff.");
    return;
  }
  inspectDiffButton.disabled = true;
  text(
    coverageProgress,
    "Loading the checksum-bound local diff into memory..."
  );
  try {
    const result = await api("/api/review/diff", {
      reviewId: state.reviewId
    });
    state.diff = result.diff || null;
    renderCoverage(state.coverage, { preserveDraft: true });
    focusNextUnreviewedHunk({ focus: true, scroll: true });
    text(
      coverageProgress,
      `${Number(result.diff?.summary?.hunkCount || 0)} hunk${Number(result.diff?.summary?.hunkCount || 0) === 1 ? "" : "s"} loaded in memory only. Classify the focused hunk to continue; nothing is saved automatically.`
    );
  } catch (error) {
    state.diff = null;
    text(
      coverageProgress,
      "Diff inspection stopped because the local evidence could not be verified."
    );
    showToast(error.message);
  } finally {
    unlockWorkflow();
  }
});

saveCoverageButton.addEventListener("click", async () => {
  if (!state.auditPath || !state.coverage) {
    showToast("Run a candidate review before saving Review Coverage.");
    return;
  }
  saveCoverageButton.disabled = true;
  text(coverageProgress, "Saving an immutable path-free attention snapshot...");
  try {
    const states = [...document.querySelectorAll("#coverage-list select")].map(
      (select) => ({
        hunkId: select.dataset.hunkId,
        status: select.value
      })
    );
    const result = await api("/api/coverage", {
      auditPath: state.auditPath,
      states
    });
    if (result.reviewId && state.review) {
      renderReview({
        ...state.review,
        ...result,
        coverage: result.coverage
      });
    } else {
      renderCoverage(result.coverage);
    }
    text(
      coverageProgress,
      `Snapshot saved: ${result.reviewedCount} reviewed, ${result.needsRevisionCount} needs revision, ${result.unreviewedCount} unreviewed. Attention is not approval.`
    );
    await refreshTrustProfile({ announce: false });
    await refreshProductMetrics({ announce: false });
  } catch (error) {
    text(coverageProgress, "Coverage was not saved. No source change occurred.");
    showToast(error.message);
  } finally {
    refreshCoverageDraftUi();
  }
});

revisionButton.addEventListener("click", async () => {
  if (!state.revisionWorkspaceAvailable) {
    showToast("The Desktop Revision Workspace requires a Pro or higher entitlement.");
    return;
  }
  if (!state.auditPath) {
    showToast("Run the current candidate review before building a re-review map.");
    return;
  }
  revisionButton.disabled = true;
  text(revisionProgress, "Rerunning this candidate and selecting the latest related local review...");
  try {
    const result = await api(
      "/api/review/rerun",
      { reviewId: state.reviewId },
      { acceptReviewResult: true }
    );
    renderReview(result);
    await refreshTrustProfile({ announce: false });
    await refreshProductMetrics({ announce: false });
    const revision = result.revision || {};
    const delta = revision.delta || revision;
    const carried = Number(
      delta.attention?.carriedForwardCount ??
      revision.carriedForwardCount ??
      0
    );
    const attention = Number(
      delta.attention?.currentAttentionRequiredCount ??
      revision.currentAttentionRequiredCount ??
      0
    );
    text(
      revisionProgress,
      result.revision
        ? `${carried} exact hunk attention state${carried === 1 ? "" : "s"} carried; ${attention} current hunk${attention === 1 ? "" : "s"} require attention.`
        : "Review rerun completed. No related prior local session was available for comparison."
    );
  } catch (error) {
    text(revisionProgress, "Rerun stopped. No source apply was performed.");
    showToast(error.message);
  } finally {
    unlockWorkflow();
  }
});

recommendButton.addEventListener("click", async () => {
  const provider = document.querySelector('input[name="provider"]:checked').value;
  if (!state.auditPath) {
    showToast("Run a candidate review before requesting an advisory.");
    return;
  }
  if (provider === "deepseek" && !state.deepseekConfigured) {
    showToast("DeepSeek BYOK is not configured in the local Runrail environment.");
    return;
  }
  recommendButton.disabled = true;
  text(
    recommendProgress,
    provider === "deepseek"
      ? "Requesting metadata-only advisory..."
      : "Running offline policy..."
  );
  try {
    const result = await api("/api/recommend", {
      auditPath: state.auditPath,
      provider,
      networkConsent: provider === "deepseek" && networkConsent.checked
    });
    renderAdvisory(result);
    text(recommendProgress, "Advisory saved locally. Authority remains none.");
  } catch (error) {
    text(recommendProgress, "Advisory stopped. No action was executed.");
    showToast(error.message);
  } finally {
    recommendButton.disabled = false;
  }
});

for (const option of document.querySelectorAll('input[name="provider"]')) {
  option.addEventListener("change", () => {
    const selected = document.querySelector('input[name="provider"]:checked');
    const deepseek = selected?.value === "deepseek";
    consentRow.hidden = !deepseek;
    for (const label of document.querySelectorAll(".provider-option")) {
      label.classList.toggle(
        "is-selected",
        label.querySelector("input") === selected
      );
    }
  });
}

for (const button of document.querySelectorAll("[data-back-to-review]")) {
  button.addEventListener("click", () => activateView("review"));
}

for (const button of document.querySelectorAll("[data-view-target]")) {
  button.addEventListener("click", () => activateView(button.dataset.viewTarget));
}

for (const button of document.querySelectorAll("[data-surface-target]")) {
  button.addEventListener("click", () => activateSurface(button.dataset.surfaceTarget));
}

activationPrimaryAction.addEventListener("click", () => {
  const action = activationPrimaryAction.dataset.action;
  if (action === "wait-for-doctor") return;
  if (action === "run-safe-sample") {
    sampleButton.click();
    return;
  }
  if (action === "copy-readiness-brief") {
    void copyReadinessBrief();
    return;
  }
  if (action === "reinspect-repository") {
    activateSurface("review");
    void inspectRepository();
    return;
  }
  if (action === "resume-latest-review") {
    const latest = latestHistoryItem();
    if (!latest) {
      showToast("No verified local review is available to resume.");
      return;
    }
    activateSurface("review");
    void selectHistoryItem(latest);
    return;
  }
  if (action === "enroll-device") {
    activationPrimaryAction.disabled = true;
    void api("/api/license/enroll-request")
      .then(async (result) => {
        if (
          result?.ok !== true ||
          typeof result.browserUrl !== "string" ||
          typeof nativeInvoke !== "function"
        ) {
          throw new LocalApiError("Runrail could not create a native enrollment request.", {
            code: "desktop-enrollment-request-invalid"
          });
        }
        await nativeInvoke("open_enrollment_approval", { value: result.browserUrl });
        showToast("Approve this device in the subscriber browser window.");
      })
      .catch((error) => {
        showToast(error instanceof Error ? error.message : "Runrail device enrollment could not start.");
      })
      .finally(() => {
        activationPrimaryAction.disabled = false;
      });
    return;
  }
  activateSurface("review");
  document.querySelector("#repo-input").focus();
});

for (const item of document.querySelectorAll(".nav-item")) {
  item.addEventListener("click", () => {
    if (!item.disabled) activateSurface(item.dataset.surface);
  });
}

todayPrimaryAction.addEventListener("click", () => {
  if (state.todayAction === "copy-readiness-brief") {
    void copyReadinessBrief();
    return;
  }
  if (state.todayAction === "reinspect-repository") {
    activateSurface("review");
    void inspectRepository();
    return;
  }
  if (state.todayAction === "run-first-review") {
    activateSurface("review");
    reviewForm.requestSubmit();
    return;
  }
  if (state.todayAction === "resume-latest-review") {
    const latest = latestHistoryItem();
    if (!latest) {
      showToast("No verified local review is available to resume.");
      return;
    }
    activateSurface("review");
    void selectHistoryItem(latest);
    return;
  }
  if (state.todayAction === "inspect-next-hunk") {
    activateSurface("review");
    const section = document.querySelector("#hunk-section");
    section.open = true;
    section.scrollIntoView({ block: "start", behavior: "smooth" });
    if (!state.diff && !inspectDiffButton.disabled) {
      inspectDiffButton.click();
    } else {
      focusNextUnreviewedHunk({ focus: true, scroll: true });
    }
    return;
  }
  if (state.todayAction === "copy-correction-brief") {
    activateSurface("review");
    document.querySelector("#assurance-section").open = true;
    void copyAgentAssuranceBrief();
    return;
  }
  if (state.todayAction === "verify-revised-candidate") {
    activateSurface("review");
    void runReview({ rerun: true });
    return;
  }
  if (state.todayAction === "complete-attention") {
    activateSurface("review");
    const section = document.querySelector("#hunk-section");
    section.open = true;
    section.scrollIntoView({ block: "start", behavior: "smooth" });
    return;
  }
  if (state.todayAction === "review-human-decision") {
    activateView("evidence");
    document.querySelector("#verdict-panel").scrollIntoView({
      block: "start",
      behavior: "smooth"
    });
    return;
  }
  activateSurface("review");
  document.querySelector("#repo-input").focus();
});

document.querySelector("#quit-button").addEventListener("click", async () => {
  try {
    await api("/api/quit");
    const message = document.createElement("main");
    const status = document.createElement("p");
    const heading = document.createElement("h1");
    const detail = document.createElement("p");
    message.className = "stopped-message";
    text(status, "Runrail Desktop stopped");
    text(heading, "This local session is closed.");
    text(
      detail,
      "You can close this window. Start Runrail Desktop again when you need another review."
    );
    message.append(status, heading, detail);
    document.body.className = "stopped-screen";
    document.body.replaceChildren(message);
  } catch (error) {
    showToast(error.message);
  }
});

async function initialize() {
  text(document.querySelector("#session-origin"), location.origin);
  activateSurface("activate", { scroll: false });
  renderHistory();
  unlockWorkflow();
  if (!sessionToken) {
    runtimeStatus.classList.add("is-error");
    text(runtimeStatusText, "Session token missing");
    showToast("This page is not attached to a valid Runrail Desktop session.");
    return;
  }

  try {
    const status = await api("/api/status");
    const entitlementFeatures = Array.isArray(status.entitlement?.features)
      ? status.entitlement.features
      : [];
    state.candidateReviewAvailable =
      entitlementFeatures.includes("candidate-branch-review") ||
      (
        entitlementFeatures.includes("public-preview-candidate-review") &&
        status.entitlement?.previewReview?.available === true
      );
    state.previewReadinessOnly =
      status.entitlement?.mode === "public-preview";
    renderActivation(status);
    const agentList = await optionalApi("/api/agents/list");
    renderAgentAdapters(agentList || {
      adapters: [{
        adapterId: "generic-copy",
        label: "Generic copy",
        detected: true,
        launchable: false,
        mode: "copy",
        reason: "copy-brief-only",
        authority: "none"
      }]
    });
    state.deepseekConfigured = status.deepseekConfigured === true;
    state.revisionWorkspaceAvailable =
      entitlementFeatures.includes("revision-comparison");
    state.tournamentAvailable = state.revisionWorkspaceAvailable;
    state.trustProfilesAvailable =
      entitlementFeatures.includes("reusable-policy-profiles");
    state.deviceSignedPassportsAvailable =
      entitlementFeatures.includes("advanced-evidence-exports");
    state.outcomeLedgerAvailable =
      entitlementFeatures.includes("advanced-evidence-exports");
    state.proofGraphAvailable = state.deviceSignedPassportsAvailable;
    passportSignOption.hidden = !state.deviceSignedPassportsAvailable;
    deviceSignPassport.checked = false;
    text(
      document.querySelector("#trust-section-count"),
      state.trustProfilesAvailable ? "Pro" : "Locked"
    );
    text(
      trustProgress,
      state.trustProfilesAvailable
        ? "Select a reviewed repository to load local continuity."
        : "Repository Trust Profiles and weekly reports require Pro or higher."
    );
    text(
      document.querySelector("#tournament-section-count"),
      state.tournamentAvailable ? "Pro" : "Locked"
    );
    text(
      tournamentProgress,
      state.tournamentAvailable
        ? "Inspect a clean repository and select two to five local candidate branches."
        : "Candidate Tournament requires Pro or higher."
    );
    text(
      document.querySelector("#proofgraph-section-count"),
      state.proofGraphAvailable ? "Pro" : "Locked"
    );
    resetOutcomeLedger({
      locked: !state.outcomeLedgerAvailable
    });
    text(
      proofGraphProgress,
      state.proofGraphAvailable
        ? "Run a local review to build its path-free ProofGraph."
        : "ProofGraph requires Pro or higher."
    );
    text(
      document.querySelector("#deepseek-state"),
      state.deepseekConfigured ? "Configured" : "Not configured"
    );

    text(
      document.querySelector("#review-title"),
      state.candidateReviewAvailable
        ? state.previewReadinessOnly
          ? "Review one real candidate"
          : "Review a candidate change"
        : "Check repository readiness"
    );
    text(
      document.querySelector("#review-intro"),
      state.candidateReviewAvailable
        ? state.previewReadinessOnly
          ? "Use the public preview for one real local candidate review, exact-hunk inspection, and source-free evidence. Reruns require enrollment."
          : "Compare two local Git references, inspect deterministic evidence, and leave the final decision to a human."
        : state.previewReadinessOnly
          ? "Inspect local Git metadata and the evidence from the one completed preview review. New reviews require enrollment."
          : "Inspect local Git metadata and supported project types without starting a review."
    );
    text(
      document.querySelector("#review-button-label"),
      state.candidateReviewAvailable
        ? state.previewReadinessOnly
          ? "Run preview review"
          : "Run review"
        : state.previewReadinessOnly
          ? "Preview review used"
          : "Review requires enrollment"
    );
    text(
      document.querySelector(".activate-review-button span"),
      state.candidateReviewAvailable
        ? "Select a repository"
        : "Inspect a repository"
    );
    text(
      reviewProgress,
      state.candidateReviewAvailable
        ? state.previewReadinessOnly
          ? "One preview review is available. Source apply and project tests are unavailable."
          : "Ready. Source apply is unavailable."
        : state.previewReadinessOnly
          ? "The one preview review has been used. Existing evidence remains inspectable; rerun requires enrollment."
          : "Read-only repository readiness is available. Candidate review remains locked until enrollment."
    );
    renderActivationJourney();

    const revisionAccessLabel = state.revisionWorkspaceAvailable
      ? "Pro Revision Workspace available"
      : "Requires a Pro or higher entitlement";
    revisionButton.title = revisionAccessLabel;
    unlockWorkflow();

    const initialRepo = firstText(
      status.initialRepo,
      status.inspection?.repo,
      status.repository?.path
    );
    if (initialRepo) {
      document.querySelector("#repo-input").value = initialRepo;
      if (status.inspection || status.repository) {
        renderInspection(status);
      } else {
        await inspectRepository({ announceUnsupported: false });
      }
    }
    const embeddedHistory = extractHistory(status);
    if (state.previewReadinessOnly) {
      setHistory([]);
    } else if (embeddedHistory.length > 0) {
      setHistory(embeddedHistory);
    } else {
      await refreshHistory();
    }
    if (!state.previewReadinessOnly) {
      await refreshTrustProfile({ announce: false });
      await refreshOutcomeLedger({ announce: false });
    }
    await refreshProductMetrics({ announce: false });

    runtimeStatus.classList.add("is-ready");
    const plan = status.entitlement?.planCode && status.entitlement.planCode !== "legacy"
      ? `${status.entitlement.planCode} plan`
      : "subscriber package";
    text(runtimeStatusText, `Verified local runtime / ${plan} / offline`);
    renderToday();
  } catch (error) {
    runtimeStatus.classList.add("is-error");
    text(runtimeStatusText, "Local runtime unavailable");
    showToast(error.message);
  }
}

function showDirectFileLaunch() {
  document.title = "Start Runrail Desktop";
  const launchScreen = document.querySelector("#direct-file-launch");
  const appShell = document.querySelector(".app-shell");
  if (launchScreen) launchScreen.hidden = false;
  if (appShell) appShell.hidden = true;
}

if (directFileLaunch) showDirectFileLaunch();
else void initialize();
